fix: content tab fixes (#5543)

* fix: search again

* fix: navigation bug

* fix: switch to stable key for toggle disable

* feat: inline backup slow warning icon

* fix: qa

* feat: fix installation state
This commit is contained in:
Calum H.
2026-03-12 22:52:55 +00:00
committed by GitHub
parent 52d46b8aaa
commit ba06c89a0e
15 changed files with 387 additions and 196 deletions

View File

@@ -1,6 +1,6 @@
<template> <template>
<ProjectCard <ProjectCard
:title="project.title" :title="project.name"
:link=" :link="
() => { () => {
emit('open') emit('open')
@@ -12,7 +12,7 @@
" "
:author="{ name: project.author, link: `https://modrinth.com/user/${project.author}` }" :author="{ name: project.author, link: `https://modrinth.com/user/${project.author}` }"
:icon-url="project.icon_url" :icon-url="project.icon_url"
:summary="project.description" :summary="project.summary"
:tags="project.display_categories" :tags="project.display_categories"
:all-tags="project.categories" :all-tags="project.categories"
:downloads="project.downloads" :downloads="project.downloads"
@@ -20,16 +20,6 @@
:date-updated="project.date_modified" :date-updated="project.date_modified"
:banner="project.featured_gallery ?? undefined" :banner="project.featured_gallery ?? undefined"
:color="project.color ?? undefined" :color="project.color ?? undefined"
:environment="
projectType
? ['mod', 'modpack'].includes(projectType)
? {
clientSide: project.client_side,
serverSide: project.server_side,
}
: undefined
: undefined
"
layout="list" layout="list"
> >
<template #actions> <template #actions>
@@ -140,5 +130,5 @@ async function install() {
).catch(handleError) ).catch(handleError)
} }
const modpack = computed(() => props.project.project_type === 'modpack') const modpack = computed(() => props.project.project_types?.includes('modpack'))
</script> </script>

View File

@@ -40,7 +40,7 @@ import type Instance from '@/components/ui/Instance.vue'
import InstanceIndicator from '@/components/ui/InstanceIndicator.vue' import InstanceIndicator from '@/components/ui/InstanceIndicator.vue'
import NavTabs from '@/components/ui/NavTabs.vue' import NavTabs from '@/components/ui/NavTabs.vue'
import SearchCard from '@/components/ui/SearchCard.vue' import SearchCard from '@/components/ui/SearchCard.vue'
import { get_project_v3, get_search_results, get_search_results_v3 } from '@/helpers/cache.js' import { get_project_v3, get_search_results_v3 } from '@/helpers/cache.js'
import { process_listener } from '@/helpers/events' import { process_listener } from '@/helpers/events'
import { get_by_profile_path } from '@/helpers/process' import { get_by_profile_path } from '@/helpers/process'
import { import {
@@ -186,6 +186,21 @@ const instanceFilters = computed(() => {
option: 'client', option: 'client',
}) })
} }
if (
instanceHideInstalled.value &&
(installedProjectIds.value || newlyInstalled.value.length > 0)
) {
const allInstalled = [...(installedProjectIds.value ?? []), ...newlyInstalled.value]
allInstalled
.map((x) => ({
type: 'project_id',
option: `project_id:${x}`,
negative: true,
}))
.forEach((x) => filters.push(x))
}
} }
debugLog('instanceFilters result', filters) debugLog('instanceFilters result', filters)
@@ -338,13 +353,13 @@ watch(projectType, () => {
loading.value = true loading.value = true
}) })
interface SearchResults extends Labrinth.Search.v2.SearchResults { interface SearchResults extends Labrinth.Search.v3.SearchResults {
hits: (Labrinth.Search.v2.ResultSearchProject & { installed?: boolean })[] hits: (Labrinth.Search.v3.ResultSearchProject & { installed?: boolean })[]
} }
const results: Ref<SearchResults | null> = shallowRef(null) const results: Ref<SearchResults | null> = shallowRef(null)
const pageCount = computed(() => const pageCount = computed(() =>
results.value ? Math.ceil(results.value.total_hits / results.value.limit) : 1, results.value ? Math.ceil(results.value.total_hits / results.value.hits_per_page) : 1,
) )
const effectiveRequestParams = computed(() => { const effectiveRequestParams = computed(() => {
@@ -364,10 +379,6 @@ watch(effectiveRequestParams, () => {
}, 200) }, 200)
}) })
watch(instanceHideInstalled, () => {
debugLog('instanceHideInstalled changed', instanceHideInstalled.value)
refreshSearch()
})
async function refreshSearch() { async function refreshSearch() {
const version = ++searchVersion const version = ++searchVersion
@@ -375,23 +386,34 @@ async function refreshSearch() {
try { try {
const isServer = projectType.value === 'server' const isServer = projectType.value === 'server'
const searchParams = isServer ? serverRequestParams.value : requestParams.value
debugLog('searching v3', searchParams)
let rawResults = (await get_search_results_v3(searchParams)) as {
result: SearchResults
} | null
if (version !== searchVersion) {
debugLog('search version stale, discarding', { version, current: searchVersion })
return
}
if (!rawResults) {
rawResults = {
result: {
hits: [],
total_hits: 0,
hits_per_page: maxResults.value,
page: 1,
},
}
}
if (isServer) { if (isServer) {
debugLog('searching v3 (server)', serverRequestParams.value) const hits = rawResults.result.hits ?? []
const rawResults = (await get_search_results_v3(serverRequestParams.value)) as {
result: Labrinth.Search.v3.SearchResults
} | null
if (version !== searchVersion) {
debugLog('search version stale, discarding', { version, current: searchVersion })
return
}
const searchResults = rawResults?.result ?? { hits: [], total_hits: 0 }
const hits = searchResults.hits ?? []
debugLog('server search results', { debugLog('server search results', {
hitCount: hits.length, hitCount: hits.length,
totalHits: searchResults.total_hits, totalHits: rawResults.result.total_hits,
}) })
serverHits.value = hits serverHits.value = hits
serverPings.value = {} serverPings.value = {}
@@ -399,31 +421,11 @@ async function refreshSearch() {
checkServerRunningStates(hits) checkServerRunningStates(hits)
results.value = { results.value = {
hits: [], hits: [],
total_hits: searchResults.total_hits ?? 0, total_hits: rawResults.result.total_hits ?? 0,
limit: maxResults.value, hits_per_page: maxResults.value,
offset: 0, page: 1,
} }
} else { } else {
debugLog('searching v2', requestParams.value)
let rawResults = (await get_search_results(requestParams.value)) as {
result: SearchResults
} | null
if (version !== searchVersion) {
debugLog('search version stale, discarding', { version, current: searchVersion })
return
}
if (!rawResults) {
rawResults = {
result: {
hits: [],
total_hits: 0,
limit: 1,
offset: 0,
},
}
}
if (instance.value) { if (instance.value) {
const allInstalledIds = new Set([ const allInstalledIds = new Set([
...newlyInstalled.value, ...newlyInstalled.value,
@@ -434,12 +436,8 @@ async function refreshSearch() {
...val, ...val,
installed: allInstalledIds.has(val.project_id), installed: allInstalledIds.has(val.project_id),
})) }))
if (instanceHideInstalled.value) {
rawResults.result.hits = rawResults.result.hits.filter((val) => !val.installed)
}
} }
debugLog('v2 search results', { debugLog('v3 search results', {
hitCount: rawResults.result.hits.length, hitCount: rawResults.result.hits.length,
totalHits: rawResults.result.total_hits, totalHits: rawResults.result.total_hits,
}) })
@@ -671,11 +669,11 @@ const handleRightClick = (event, result) => {
const handleOptionsClick = (args) => { const handleOptionsClick = (args) => {
switch (args.option) { switch (args.option) {
case 'open_link': case 'open_link':
openUrl(`https://modrinth.com/${args.item.project_type}/${args.item.slug}`) openUrl(`https://modrinth.com/${args.item.project_types?.[0] ?? 'project'}/${args.item.slug}`)
break break
case 'copy_link': case 'copy_link':
navigator.clipboard.writeText( navigator.clipboard.writeText(
`https://modrinth.com/${args.item.project_type}/${args.item.slug}`, `https://modrinth.com/${args.item.project_types?.[0] ?? 'project'}/${args.item.slug}`,
) )
break break
} }
@@ -887,7 +885,7 @@ previousFilterState.value = JSON.stringify({
exclude-loaders exclude-loaders
@contextmenu.prevent.stop=" @contextmenu.prevent.stop="
(event: any) => (event: any) =>
handleRightClick(event, { project_type: 'server', slug: project.slug }) handleRightClick(event, { project_types: ['server'], slug: project.slug })
" "
> >
<template #actions> <template #actions>

View File

@@ -76,6 +76,7 @@ import {
useVIntl, useVIntl,
} from '@modrinth/ui' } from '@modrinth/ui'
import { ContentCardLayout as ContentPageLayout } from '@modrinth/ui' import { ContentCardLayout as ContentPageLayout } from '@modrinth/ui'
import { useDebounceFn } from '@vueuse/core'
import { getCurrentWebview } from '@tauri-apps/api/webview' import { getCurrentWebview } from '@tauri-apps/api/webview'
import { open } from '@tauri-apps/plugin-dialog' import { open } from '@tauri-apps/plugin-dialog'
import { openUrl } from '@tauri-apps/plugin-opener' import { openUrl } from '@tauri-apps/plugin-opener'
@@ -174,12 +175,34 @@ const props = defineProps<{
const loading = ref(true) const loading = ref(true)
const projects = ref<ContentItem[]>([]) const projects = ref<ContentItem[]>([])
const installingBuffer = ref<ContentItem[]>([])
watch(
() => installingItems.value.get(props.instance.path),
(items) => {
if (items && items.length > 0) {
installingBuffer.value = [...items]
}
},
{ immediate: true, deep: true },
)
watch(projects, (newProjects) => {
if (installingBuffer.value.length === 0) return
const realProjectIds = new Set(newProjects.map((p) => p.project?.id).filter(Boolean))
if (installingBuffer.value.every((item) => realProjectIds.has(item.project?.id))) {
installingBuffer.value = []
}
})
const mergedProjects = computed<ContentItem[]>(() => { const mergedProjects = computed<ContentItem[]>(() => {
const pending = installingItems.value.get(props.instance.path) ?? [] const active = installingItems.value.get(props.instance.path)
const pending = active ?? installingBuffer.value
if (pending.length === 0) return projects.value if (pending.length === 0) return projects.value
const realProjectIds = new Set(projects.value.map((p) => p.project?.id).filter(Boolean)) const realProjectIds = new Set(projects.value.map((p) => p.project?.id).filter(Boolean))
const placeholders = pending.filter((item) => !realProjectIds.has(item.project?.id)) const placeholders = pending.filter((item) => !realProjectIds.has(item.project?.id))
return [...projects.value, ...placeholders] return placeholders.length > 0 ? [...projects.value, ...placeholders] : projects.value
}) })
const linkedModpackProject = ref<ContentModpackCardProject | null>(null) const linkedModpackProject = ref<ContentModpackCardProject | null>(null)
@@ -252,7 +275,7 @@ async function handleUploadFiles() {
} }
} }
async function toggleDisableMod(mod: ContentItem) { async function _toggleDisableMod(mod: ContentItem) {
try { try {
mod.file_path = await toggle_disable_project(props.instance.path, mod.file_path!) mod.file_path = await toggle_disable_project(props.instance.path, mod.file_path!)
mod.enabled = !mod.enabled mod.enabled = !mod.enabled
@@ -270,6 +293,8 @@ async function toggleDisableMod(mod: ContentItem) {
} }
} }
const toggleDisableMod = useDebounceFn(_toggleDisableMod, 20)
async function removeMod(mod: ContentItem) { async function removeMod(mod: ContentItem) {
await remove_project(props.instance.path, mod.file_path!).catch(handleError) await remove_project(props.instance.path, mod.file_path!).catch(handleError)
projects.value = projects.value.filter((x) => mod.file_path !== x.file_path) projects.value = projects.value.filter((x) => mod.file_path !== x.file_path)
@@ -354,9 +379,7 @@ async function handleModpackContentToggle(item: ContentItem) {
} }
async function handleModpackContentBulkToggle(items: ContentItem[]) { async function handleModpackContentBulkToggle(items: ContentItem[]) {
for (const item of items) { await Promise.all(items.map((item) => toggleDisableMod(item)))
await toggleDisableMod(item)
}
} }
async function handleModpackContent() { async function handleModpackContent() {
@@ -676,7 +699,10 @@ provideContentManager({
getItemId: (item) => item.file_name, getItemId: (item) => item.file_name,
contentTypeLabel: ref(formatMessage(messages.contentTypeProject)), contentTypeLabel: ref(formatMessage(messages.contentTypeProject)),
toggleEnabled: toggleDisableMod, toggleEnabled: toggleDisableMod,
bulkEnableItems: (items) => Promise.all(items.map((item) => toggleDisableMod(item))).then(() => {}),
bulkDisableItems: (items) => Promise.all(items.map((item) => toggleDisableMod(item))).then(() => {}),
deleteItem: removeMod, deleteItem: removeMod,
bulkDeleteItems: (items) => Promise.all(items.map((item) => removeMod(item))).then(() => {}),
refresh: () => initProjects('must_revalidate'), refresh: () => initProjects('must_revalidate'),
browse: handleBrowseContent, browse: handleBrowseContent,
uploadFiles: handleUploadFiles, uploadFiles: handleUploadFiles,
@@ -699,27 +725,17 @@ provideContentManager({
title: item.file_name.replace('.disabled', ''), title: item.file_name.replace('.disabled', ''),
icon_url: null, icon_url: null,
}, },
projectLink: item.installing projectLink: item.project?.id
? undefined ? `/project/${item.project.id}`
: item.project?.id : undefined,
? `/project/${item.project.id}` version: item.version ?? {
: undefined, id: item.file_name,
version: item.installing version_number: formatMessage(messages.unknownVersion),
? { file_name: item.file_name,
id: item.file_name, },
version_number: formatMessage(messages.installing), versionLink: item.project?.id && item.version?.id
file_name: '', ? `/project/${item.project.id}/version/${item.version.id}`
} : undefined,
: (item.version ?? {
id: item.file_name,
version_number: formatMessage(messages.unknownVersion),
file_name: item.file_name,
}),
versionLink: item.installing
? undefined
: item.project?.id && item.version?.id
? `/project/${item.project.id}/version/${item.version.id}`
: undefined,
owner: item.owner owner: item.owner
? { ? {
...item.owner, ...item.owner,

View File

@@ -127,7 +127,9 @@ export function createContentInstall(opts: {
icon_url?: string | null icon_url?: string | null
project_type?: string project_type?: string
}, },
version?: Labrinth.Versions.v2.Version,
) { ) {
const primaryFile = version?.files?.find((f) => f.primary) ?? version?.files?.[0]
const placeholder: ContentItem = { const placeholder: ContentItem = {
file_name: `__installing_${project.id}`, file_name: `__installing_${project.id}`,
project: { project: {
@@ -136,6 +138,13 @@ export function createContentInstall(opts: {
title: project.title, title: project.title,
icon_url: project.icon_url ?? null, icon_url: project.icon_url ?? null,
}, },
version: version
? {
id: version.id,
version_number: version.version_number,
file_name: primaryFile?.filename ?? '',
}
: undefined,
project_type: project.project_type ?? 'mod', project_type: project.project_type ?? 'mod',
has_update: false, has_update: false,
update_version_id: null, update_version_id: null,
@@ -288,7 +297,7 @@ export function createContentInstall(opts: {
const installedProjectIds: string[] = [] const installedProjectIds: string[] = []
if (currentProject) { if (currentProject) {
addInstallingItem(instance.id, currentProject) addInstallingItem(instance.id, currentProject, version)
installedProjectIds.push(currentProject.id) installedProjectIds.push(currentProject.id)
} }
@@ -297,8 +306,8 @@ export function createContentInstall(opts: {
await installVersionDependencies( await installVersionDependencies(
profile, profile,
version, version,
(depProject: Labrinth.Projects.v2.Project) => { (depProject: Labrinth.Projects.v2.Project, depVersion?: Labrinth.Versions.v2.Version) => {
addInstallingItem(instance.id, depProject) addInstallingItem(instance.id, depProject, depVersion)
installedProjectIds.push(depProject.id) installedProjectIds.push(depProject.id)
}, },
) )
@@ -450,14 +459,14 @@ export function createContentInstall(opts: {
} }
const installedProjectIds: string[] = [project.id] const installedProjectIds: string[] = [project.id]
addInstallingItem(instancePath, project) addInstallingItem(instancePath, project, version)
try { try {
await add_project_from_version(instance.path, version.id) await add_project_from_version(instance.path, version.id)
await installVersionDependencies( await installVersionDependencies(
instance, instance,
version, version,
(depProject: Labrinth.Projects.v2.Project) => { (depProject: Labrinth.Projects.v2.Project, depVersion?: Labrinth.Versions.v2.Version) => {
addInstallingItem(instancePath, depProject) addInstallingItem(instancePath, depProject, depVersion)
installedProjectIds.push(depProject.id) installedProjectIds.push(depProject.id)
}, },
) )

View File

@@ -173,7 +173,7 @@
data-pyro-navigation data-pyro-navigation
class="isolate flex w-full select-none flex-col justify-between gap-4 overflow-auto md:flex-row md:items-center" class="isolate flex w-full select-none flex-col justify-between gap-4 overflow-auto md:flex-row md:items-center"
> >
<NavTabs :links="navLinks" /> <NavTabs :links="navLinks" replace />
</div> </div>
<div data-pyro-mount class="h-full w-full flex-1"> <div data-pyro-mount class="h-full w-full flex-1">

View File

@@ -586,10 +586,6 @@ impl Typesense {
/// `filters`/`version` fields, translating each from Meilisearch filter /// `filters`/`version` fields, translating each from Meilisearch filter
/// syntax to Typesense filter syntax. /// syntax to Typesense filter syntax.
fn build_filter(info: &SearchRequest) -> Result<Option<String>, ApiError> { fn build_filter(info: &SearchRequest) -> Result<Option<String>, ApiError> {
if let Some(new_filters) = info.new_filters.as_deref() {
return Ok(Some(meili_to_typesense(new_filters)));
}
let facet_part = if let Some(facets_json) = info.facets.as_deref() { let facet_part = if let Some(facets_json) = info.facets.as_deref() {
Some( Some(
facets_to_typesense(facets_json) facets_to_typesense(facets_json)
@@ -599,10 +595,18 @@ impl Typesense {
None None
}; };
let legacy_part = let new_filters_part =
combined_search_filters(info).map(|f| meili_to_typesense(&f)); info.new_filters.as_deref().map(|f| meili_to_typesense(f));
Ok(match (facet_part, legacy_part) { let legacy_part = if info.new_filters.is_none() {
combined_search_filters(info).map(|f| meili_to_typesense(&f))
} else {
None
};
let filter_part = new_filters_part.or(legacy_part);
Ok(match (facet_part, filter_part) {
(Some(f), Some(l)) if !f.is_empty() && !l.is_empty() => { (Some(f), Some(l)) if !f.is_empty() && !l.is_empty() => {
Some(format!("({f}) && ({l})")) Some(format!("({f}) && ({l})"))
} }

View File

@@ -1223,20 +1223,41 @@ impl Profile {
} }
/// Toggle a project's disabled state. /// Toggle a project's disabled state.
///
/// Accepts either a bare file name (e.g. `mymod.jar`) or a relative
/// path (`mods/mymod.jar`). The function resolves the current on-disk
/// path (enabled or disabled) before renaming, so callers don't need
/// to track the `.disabled` suffix.
#[tracing::instrument] #[tracing::instrument]
pub async fn toggle_disable_project( pub async fn toggle_disable_project(
profile_path: &str, profile_path: &str,
project_path: &str, project_path: &str,
) -> crate::Result<String> { ) -> crate::Result<String> {
let path = crate::api::profile::get_full_path(profile_path).await?; let base = crate::api::profile::get_full_path(profile_path).await?;
let new_path = if project_path.ends_with(".disabled") { let trimmed = project_path.trim_end_matches(".disabled");
project_path.trim_end_matches(".disabled").to_string()
// Resolve the actual current path on disk
let current_path = if base.join(project_path).exists() {
project_path.to_string()
} else if base.join(format!("{trimmed}.disabled")).exists() {
format!("{trimmed}.disabled")
} else if base.join(trimmed).exists() {
trimmed.to_string()
} else { } else {
format!("{project_path}.disabled") return Err(crate::ErrorKind::FSError(format!(
"Could not find project file for '{project_path}' in profile"
))
.into());
}; };
io::rename_or_move(&path.join(project_path), &path.join(&new_path)) let new_path = if current_path.ends_with(".disabled") {
current_path.trim_end_matches(".disabled").to_string()
} else {
format!("{current_path}.disabled")
};
io::rename_or_move(&base.join(&current_path), &base.join(&new_path))
.await?; .await?;
Ok(new_path) Ok(new_path)

View File

@@ -3,6 +3,7 @@ import {
DownloadIcon, DownloadIcon,
MoreVerticalIcon, MoreVerticalIcon,
OrganizationIcon, OrganizationIcon,
SpinnerIcon,
TrashIcon, TrashIcon,
TriangleAlertIcon, TriangleAlertIcon,
} from '@modrinth/assets' } from '@modrinth/assets'
@@ -33,6 +34,7 @@ interface Props {
versionLink?: string | RouteLocationRaw versionLink?: string | RouteLocationRaw
owner?: ContentOwner owner?: ContentOwner
enabled?: boolean enabled?: boolean
installing?: boolean
hasUpdate?: boolean hasUpdate?: boolean
isClientOnly?: boolean isClientOnly?: boolean
overflowOptions?: OverflowMenuOption[] overflowOptions?: OverflowMenuOption[]
@@ -48,6 +50,7 @@ const props = withDefaults(defineProps<Props>(), {
versionLink: undefined, versionLink: undefined,
owner: undefined, owner: undefined,
enabled: undefined, enabled: undefined,
installing: false,
hasUpdate: false, hasUpdate: false,
isClientOnly: false, isClientOnly: false,
overflowOptions: undefined, overflowOptions: undefined,
@@ -95,13 +98,21 @@ const fileNameRef = ref<HTMLElement | null>(null)
/> />
<div class="flex min-w-0 items-center gap-3"> <div class="flex min-w-0 items-center gap-3">
<Avatar <div v-tooltip="installing ? formatMessage(commonMessages.installingLabel) : undefined" class="relative shrink-0">
:src="project.icon_url" <Avatar
:alt="project.title" :src="project.icon_url"
size="3rem" :alt="project.title"
no-shadow size="3rem"
class="shrink-0 rounded-2xl border border-surface-5" no-shadow
/> class="rounded-2xl border border-surface-5"
/>
<div
v-if="installing"
class="absolute inset-0 flex items-center justify-center rounded-2xl bg-black/20"
>
<SpinnerIcon class="size-5 animate-spin text-white" />
</div>
</div>
<div class="flex min-w-0 flex-col gap-0.5"> <div class="flex min-w-0 flex-col gap-0.5">
<div class="flex min-w-0 items-center gap-1"> <div class="flex min-w-0 items-center gap-1">
<AutoLink <AutoLink

View File

@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { ChevronDownIcon, ChevronUpIcon } from '@modrinth/assets' import { ChevronDownIcon, ChevronUpIcon } from '@modrinth/assets'
import { computed, getCurrentInstance, ref, toRef } from 'vue' import { computed, getCurrentInstance, onMounted, onUnmounted, ref, toRef } from 'vue'
import Checkbox from '#ui/components/base/Checkbox.vue' import Checkbox from '#ui/components/base/Checkbox.vue'
import { useVIntl } from '#ui/composables/i18n' import { useVIntl } from '#ui/composables/i18n'
@@ -112,14 +112,43 @@ function toggleSelectAll() {
} }
} }
function toggleItemSelection(itemId: string, selected: boolean) { const lastSelectedIndex = ref<number | null>(null)
if (selected) { const shiftHeld = ref(false)
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Shift') shiftHeld.value = true
}
function onKeyUp(e: KeyboardEvent) {
if (e.key === 'Shift') shiftHeld.value = false
}
onMounted(() => {
window.addEventListener('keydown', onKeyDown)
window.addEventListener('keyup', onKeyUp)
})
onUnmounted(() => {
window.removeEventListener('keydown', onKeyDown)
window.removeEventListener('keyup', onKeyUp)
})
function toggleItemSelection(itemId: string, selected: boolean, index?: number) {
if (selected && shiftHeld.value && lastSelectedIndex.value !== null && index !== undefined) {
const start = Math.min(lastSelectedIndex.value, index)
const end = Math.max(lastSelectedIndex.value, index)
const rangeIds = props.items.slice(start, end + 1).map((item) => item.id)
const merged = new Set([...selectedIds.value, ...rangeIds])
selectedIds.value = [...merged]
} else if (selected) {
if (!selectedIds.value.includes(itemId)) { if (!selectedIds.value.includes(itemId)) {
selectedIds.value = [...selectedIds.value, itemId] selectedIds.value = [...selectedIds.value, itemId]
} }
} else { } else {
selectedIds.value = selectedIds.value.filter((id) => id !== itemId) selectedIds.value = selectedIds.value.filter((id) => id !== itemId)
} }
if (index !== undefined) {
lastSelectedIndex.value = index
}
} }
function isItemSelected(itemId: string): boolean { function isItemSelected(itemId: string): boolean {
@@ -241,6 +270,7 @@ function handleSort(column: ContentCardTableSortColumn) {
:version-link="item.versionLink" :version-link="item.versionLink"
:owner="item.owner" :owner="item.owner"
:enabled="item.enabled" :enabled="item.enabled"
:installing="item.installing"
:has-update="item.hasUpdate" :has-update="item.hasUpdate"
:is-client-only="item.isClientOnly" :is-client-only="item.isClientOnly"
:overflow-options="item.overflowOptions" :overflow-options="item.overflowOptions"
@@ -254,7 +284,7 @@ function handleSort(column: ContentCardTableSortColumn) {
'border-0 border-t border-solid border-surface-4', 'border-0 border-t border-solid border-surface-4',
visibleRange.start + idx === items.length - 1 && !flat ? 'rounded-b-[20px]' : '', visibleRange.start + idx === items.length - 1 && !flat ? 'rounded-b-[20px]' : '',
]" ]"
@update:selected="(val) => toggleItemSelection(item.id, val ?? false)" @update:selected="(val) => toggleItemSelection(item.id, val ?? false, visibleRange.start + idx)"
@update:enabled="(val) => emit('update:enabled', item.id, val)" @update:enabled="(val) => emit('update:enabled', item.id, val)"
@delete="emit('delete', item.id)" @delete="emit('delete', item.id)"
@update="emit('update', item.id)" @update="emit('update', item.id)"
@@ -285,6 +315,7 @@ function handleSort(column: ContentCardTableSortColumn) {
:version-link="item.versionLink" :version-link="item.versionLink"
:owner="item.owner" :owner="item.owner"
:enabled="item.enabled" :enabled="item.enabled"
:installing="item.installing"
:has-update="item.hasUpdate" :has-update="item.hasUpdate"
:overflow-options="item.overflowOptions" :overflow-options="item.overflowOptions"
:disabled="item.disabled" :disabled="item.disabled"
@@ -297,7 +328,7 @@ function handleSort(column: ContentCardTableSortColumn) {
'border-0 border-t border-solid border-surface-4', 'border-0 border-t border-solid border-surface-4',
index === items.length - 1 && !flat ? 'rounded-b-[20px]' : '', index === items.length - 1 && !flat ? 'rounded-b-[20px]' : '',
]" ]"
@update:selected="(val) => toggleItemSelection(item.id, val ?? false)" @update:selected="(val) => toggleItemSelection(item.id, val ?? false, index)"
@update:enabled="(val) => emit('update:enabled', item.id, val)" @update:enabled="(val) => emit('update:enabled', item.id, val)"
@delete="emit('delete', item.id)" @delete="emit('delete', item.id)"
@update="emit('update', item.id)" @update="emit('update', item.id)"

View File

@@ -3,11 +3,8 @@
<span class="text-primary"> <span class="text-primary">
{{ formatMessage(messages.warningBody, { type: backup.isServer ? 'server' : 'instance' }) }} {{ formatMessage(messages.warningBody, { type: backup.isServer ? 'server' : 'instance' }) }}
</span> </span>
<span v-if="backup.isServer" class="text-brand-orange font-semibold">
{{ formatMessage(messages.backupTakesAWhile) }}
</span>
<div v-if="backup.available"> <div v-if="backup.available" class="flex items-center gap-2">
<!-- Button / Loading state --> <!-- Button / Loading state -->
<ButtonStyled v-if="!backup.backupComplete.value && !backup.backupFailed.value"> <ButtonStyled v-if="!backup.backupComplete.value && !backup.backupFailed.value">
<button <button
@@ -39,12 +36,18 @@
<div v-else-if="backup.backupFailed.value" class="text-sm text-red"> <div v-else-if="backup.backupFailed.value" class="text-sm text-red">
{{ formatMessage(messages.backupFailed) }} {{ formatMessage(messages.backupFailed) }}
</div> </div>
<TriangleAlertIcon
v-if="backup.isServer"
v-tooltip="formatMessage(messages.backupTakesAWhile)"
class="size-5 shrink-0 text-brand-orange hover:brightness-110"
/>
</div> </div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { CheckCircleIcon, PlusIcon, SpinnerIcon } from '@modrinth/assets' import { CheckCircleIcon, PlusIcon, SpinnerIcon, TriangleAlertIcon } from '@modrinth/assets'
import { watch } from 'vue' import { watch } from 'vue'
import ButtonStyled from '#ui/components/base/ButtonStyled.vue' import ButtonStyled from '#ui/components/base/ButtonStyled.vue'

View File

@@ -230,6 +230,7 @@ const tableItems = computed<ContentCardTableItem[]>(() =>
return { return {
...base, ...base,
disabled: isChanging(base.id) || ctx.isBusy.value || item.installing === true, disabled: isChanging(base.id) || ctx.isBusy.value || item.installing === true,
installing: item.installing === true,
hasUpdate: !ctx.isPackLocked.value && item.has_update, hasUpdate: !ctx.isPackLocked.value && item.has_update,
isClientOnly: isClientOnlyEnvironment(item.environment), isClientOnly: isClientOnlyEnvironment(item.environment),
overflowOptions: ctx.getOverflowOptions?.(item), overflowOptions: ctx.getOverflowOptions?.(item),
@@ -542,7 +543,7 @@ const confirmUnlinkModal = ref<InstanceType<typeof ConfirmUnlinkModal>>()
</div> </div>
</div> </div>
<div class="flex flex-wrap items-center justify-between gap-2"> <div class="@container flex flex-wrap items-center justify-between gap-2">
<div class="flex flex-wrap items-center gap-1.5"> <div class="flex flex-wrap items-center gap-1.5">
<FilterIcon class="size-5 text-secondary" /> <FilterIcon class="size-5 text-secondary" />
<button <button
@@ -571,22 +572,36 @@ const confirmUnlinkModal = ref<InstanceType<typeof ConfirmUnlinkModal>>()
> >
{{ option.label }} {{ option.label }}
</button> </button>
<div class="ml-4 mx-0.5 h-5 w-px bg-surface-5" /> <div class="hidden @[900px]:block">
<ButtonStyled type="transparent" hover-color-fill="none">
<ButtonStyled type="transparent" hover-color-fill="none"> <button
<button :aria-label="
:aria-label=" formatMessage(messages.sortByLabel, { mode: sortLabels[sortMode]() })
formatMessage(messages.sortByLabel, { mode: sortLabels[sortMode]() }) "
" @click="cycleSortMode"
@click="cycleSortMode" >
> <ArrowUpDownIcon />
<ArrowUpDownIcon /> {{ sortLabels[sortMode]() }}
{{ sortLabels[sortMode]() }} </button>
</button> </ButtonStyled>
</ButtonStyled> </div>
</div> </div>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<div class="@[900px]:hidden">
<ButtonStyled type="transparent" hover-color-fill="none">
<button
:aria-label="
formatMessage(messages.sortByLabel, { mode: sortLabels[sortMode]() })
"
@click="cycleSortMode"
>
<ArrowUpDownIcon />
{{ sortLabels[sortMode]() }}
</button>
</ButtonStyled>
</div>
<ButtonStyled <ButtonStyled
v-if="hasBulkUpdateSupport && !ctx.isPackLocked.value && hasOutdatedProjects" v-if="hasBulkUpdateSupport && !ctx.isPackLocked.value && hasOutdatedProjects"
color="green" color="green"

View File

@@ -30,6 +30,7 @@ export interface ContentCardTableItem {
owner?: ContentOwner owner?: ContentOwner
enabled?: boolean enabled?: boolean
disabled?: boolean disabled?: boolean
installing?: boolean
hasUpdate?: boolean hasUpdate?: boolean
isClientOnly?: boolean isClientOnly?: boolean
overflowOptions?: OverflowMenuOption[] overflowOptions?: OverflowMenuOption[]

View File

@@ -61,6 +61,22 @@ const messages = defineMessages({
id: 'hosting.content.failed-to-update', id: 'hosting.content.failed-to-update',
defaultMessage: 'Failed to update', defaultMessage: 'Failed to update',
}, },
failedToBulkDelete: {
id: 'hosting.content.failed-to-bulk-delete',
defaultMessage: 'Failed to delete content',
},
failedToBulkEnable: {
id: 'hosting.content.failed-to-bulk-enable',
defaultMessage: 'Failed to enable content',
},
failedToBulkDisable: {
id: 'hosting.content.failed-to-bulk-disable',
defaultMessage: 'Failed to disable content',
},
failedToBulkUpdate: {
id: 'hosting.content.failed-to-bulk-update',
defaultMessage: 'Failed to update content',
},
}) })
const props = withDefaults( const props = withDefaults(
@@ -208,7 +224,8 @@ const deleteMutation = useMutation({
} }
addNotification({ addNotification({
type: 'error', type: 'error',
text: err instanceof Error ? err.message : formatMessage(messages.failedToRemoveContent), title: formatMessage(messages.failedToRemoveContent),
text: err instanceof Error ? err.message : undefined,
}) })
}, },
}) })
@@ -241,7 +258,7 @@ const toggleMutation = useMutation({
onError: (_err, { addon }) => { onError: (_err, { addon }) => {
addNotification({ addNotification({
type: 'error', type: 'error',
text: formatMessage(messages.failedToToggle, { name: friendlyAddonName(addon) }), title: formatMessage(messages.failedToToggle, { name: friendlyAddonName(addon) }),
}) })
}, },
}) })
@@ -269,22 +286,46 @@ function itemsToAddonRequests(items: ContentItem[]): Archon.Content.v1.RemoveAdd
async function handleBulkDelete(items: ContentItem[]) { async function handleBulkDelete(items: ContentItem[]) {
const requests = itemsToAddonRequests(items) const requests = itemsToAddonRequests(items)
if (requests.length === 0) return if (requests.length === 0) return
await client.archon.content_v1.deleteAddons(serverId, worldId.value!, requests) try {
await queryClient.invalidateQueries({ queryKey: queryKey.value }) await client.archon.content_v1.deleteAddons(serverId, worldId.value!, requests)
await queryClient.invalidateQueries({ queryKey: queryKey.value })
} catch (err) {
addNotification({
type: 'error',
title: formatMessage(messages.failedToBulkDelete),
text: err instanceof Error ? err.message : undefined,
})
}
} }
async function handleBulkEnable(items: ContentItem[]) { async function handleBulkEnable(items: ContentItem[]) {
const requests = itemsToAddonRequests(items) const requests = itemsToAddonRequests(items)
if (requests.length === 0) return if (requests.length === 0) return
await client.archon.content_v1.enableAddons(serverId, worldId.value!, requests) try {
await queryClient.invalidateQueries({ queryKey: queryKey.value }) await client.archon.content_v1.enableAddons(serverId, worldId.value!, requests)
await queryClient.invalidateQueries({ queryKey: queryKey.value })
} catch (err) {
addNotification({
type: 'error',
title: formatMessage(messages.failedToBulkEnable),
text: err instanceof Error ? err.message : undefined,
})
}
} }
async function handleBulkDisable(items: ContentItem[]) { async function handleBulkDisable(items: ContentItem[]) {
const requests = itemsToAddonRequests(items) const requests = itemsToAddonRequests(items)
if (requests.length === 0) return if (requests.length === 0) return
await client.archon.content_v1.disableAddons(serverId, worldId.value!, requests) try {
await queryClient.invalidateQueries({ queryKey: queryKey.value }) await client.archon.content_v1.disableAddons(serverId, worldId.value!, requests)
await queryClient.invalidateQueries({ queryKey: queryKey.value })
} catch (err) {
addNotification({
type: 'error',
title: formatMessage(messages.failedToBulkDisable),
text: err instanceof Error ? err.message : undefined,
})
}
} }
const uploadState = ref<UploadState>({ const uploadState = ref<UploadState>({
@@ -396,7 +437,8 @@ function handleUploadFiles() {
if (err instanceof Error && err.message === 'Upload cancelled') return if (err instanceof Error && err.message === 'Upload cancelled') return
addNotification({ addNotification({
type: 'error', type: 'error',
text: err instanceof Error ? err.message : formatMessage(messages.failedToUpload), title: formatMessage(messages.failedToUpload),
text: err instanceof Error ? err.message : undefined,
}) })
} finally { } finally {
activeUploadCancel = null activeUploadCancel = null
@@ -458,7 +500,8 @@ async function handleViewModpackContent() {
modpackContentModal.value?.hide() modpackContentModal.value?.hide()
addNotification({ addNotification({
type: 'error', type: 'error',
text: err instanceof Error ? err.message : formatMessage(messages.failedToLoadModpackContent), title: formatMessage(messages.failedToLoadModpackContent),
text: err instanceof Error ? err.message : undefined,
}) })
} }
} }
@@ -500,14 +543,18 @@ async function handleModpackBulkToggle(items: ContentItem[], enable: boolean) {
await client.archon.content_v1.disableAddons(serverId, worldId.value!, requests) await client.archon.content_v1.disableAddons(serverId, worldId.value!, requests)
} }
await queryClient.invalidateQueries({ queryKey: queryKey.value }) await queryClient.invalidateQueries({ queryKey: queryKey.value })
} catch { } catch (err) {
// Revert
for (const item of items) { for (const item of items) {
modpackAddons.value = modpackAddons.value.map((a) => modpackAddons.value = modpackAddons.value.map((a) =>
a.filename === item.file_name ? { ...a, disabled: enable } : a, a.filename === item.file_name ? { ...a, disabled: enable } : a,
) )
modpackContentModal.value?.updateItem(item.file_name, { enabled: !enable }) modpackContentModal.value?.updateItem(item.file_name, { enabled: !enable })
} }
addNotification({
type: 'error',
title: formatMessage(enable ? messages.failedToBulkEnable : messages.failedToBulkDisable),
text: err instanceof Error ? err.message : undefined,
})
} }
} }
@@ -522,7 +569,8 @@ async function handleModpackUnlinkConfirm() {
} catch (err) { } catch (err) {
addNotification({ addNotification({
type: 'error', type: 'error',
text: err instanceof Error ? err.message : formatMessage(messages.failedToUnlink), title: formatMessage(messages.failedToUnlink),
text: err instanceof Error ? err.message : undefined,
}) })
} }
} }
@@ -535,8 +583,16 @@ async function handleBulkUpdate(items: ContentItem[]) {
version_id: item.update_version_id ?? undefined, version_id: item.update_version_id ?? undefined,
})) }))
if (addons.length === 0) return if (addons.length === 0) return
await client.archon.content_v1.updateAddons(serverId, worldId.value!, addons) try {
await queryClient.invalidateQueries({ queryKey: queryKey.value }) await client.archon.content_v1.updateAddons(serverId, worldId.value!, addons)
await queryClient.invalidateQueries({ queryKey: queryKey.value })
} catch (err) {
addNotification({
type: 'error',
title: formatMessage(messages.failedToBulkUpdate),
text: err instanceof Error ? err.message : undefined,
})
}
} }
async function handleUpdateItem(fileNameKey: string) { async function handleUpdateItem(fileNameKey: string) {
@@ -564,7 +620,8 @@ async function handleUpdateItem(fileNameKey: string) {
} catch (err) { } catch (err) {
addNotification({ addNotification({
type: 'error', type: 'error',
text: err instanceof Error ? err.message : formatMessage(messages.failedToLoadVersions), title: formatMessage(messages.failedToLoadVersions),
text: err instanceof Error ? err.message : undefined,
}) })
} finally { } finally {
loadingVersions.value = false loadingVersions.value = false
@@ -593,7 +650,7 @@ async function handleModpackUpdate() {
await nextTick() await nextTick()
contentUpdaterModal.value?.show(mp.spec.version_id ?? undefined) contentUpdaterModal.value?.show(mp.has_update ?? undefined)
if (!cached) { if (!cached) {
try { try {
@@ -607,7 +664,8 @@ async function handleModpackUpdate() {
} catch (err) { } catch (err) {
addNotification({ addNotification({
type: 'error', type: 'error',
text: err instanceof Error ? err.message : formatMessage(messages.failedToLoadVersions), title: formatMessage(messages.failedToLoadVersions),
text: err instanceof Error ? err.message : undefined,
}) })
} finally { } finally {
loadingVersions.value = false loadingVersions.value = false
@@ -698,7 +756,8 @@ async function performUpdate(selectedVersion: Labrinth.Versions.v2.Version) {
} catch (err) { } catch (err) {
addNotification({ addNotification({
type: 'error', type: 'error',
text: err instanceof Error ? err.message : formatMessage(messages.failedToUpdate), title: formatMessage(messages.failedToUpdate),
text: err instanceof Error ? err.message : undefined,
}) })
} finally { } finally {
resetUpdateState() resetUpdateState()

View File

@@ -414,6 +414,10 @@ export const commonMessages = defineMessages({
id: 'label.update-available', id: 'label.update-available',
defaultMessage: 'Update available', defaultMessage: 'Update available',
}, },
installingLabel: {
id: 'label.installing',
defaultMessage: 'Installing...',
},
changelogLabel: { changelogLabel: {
id: 'label.changelog', id: 'label.changelog',
defaultMessage: 'Changelog', defaultMessage: 'Changelog',

View File

@@ -227,7 +227,7 @@ export function useSearch(
options: tags.value.gameVersions.map((gameVersion) => ({ options: tags.value.gameVersions.map((gameVersion) => ({
id: gameVersion.version, id: gameVersion.version,
toggle_group: gameVersion.version_type !== 'release' ? 'all_versions' : undefined, toggle_group: gameVersion.version_type !== 'release' ? 'all_versions' : undefined,
value: `versions:${gameVersion.version}`, value: `game_versions:${gameVersion.version}`,
query_value: gameVersion.version, query_value: gameVersion.version,
method: 'or', method: 'or',
})), })),
@@ -425,7 +425,7 @@ export function useSearch(
.sort((a, b) => (b.ordering ?? 0) - (a.ordering ?? 0)) .sort((a, b) => (b.ordering ?? 0) - (a.ordering ?? 0))
}) })
const facets = computed(() => { const newFilters = computed(() => {
const validProvidedFilters = providedFilters.value.filter( const validProvidedFilters = providedFilters.value.filter(
(providedFilter) => !overriddenProvidedFilterTypes.value.includes(providedFilter.type), (providedFilter) => !overriddenProvidedFilterTypes.value.includes(providedFilter.type),
) )
@@ -435,8 +435,10 @@ export function useSearch(
) )
const filterValues = [...filteredFilters, ...validProvidedFilters] const filterValues = [...filteredFilters, ...validProvidedFilters]
const andFacets: string[][] = [] const parts: string[] = []
const orFacets: Record<string, string[]> = {} const orGroups: Record<string, string[]> = {}
const negativeByType: Record<string, string[]> = {}
for (const filterValue of filterValues) { for (const filterValue of filterValues) {
const type = filters.value.find((type) => type.id === filterValue.type) const type = filters.value.find((type) => type.id === filterValue.type)
if (!type) { if (!type) {
@@ -458,43 +460,68 @@ export function useSearch(
} }
if (option.method === 'or' || option.method === 'and') { if (option.method === 'or' || option.method === 'and') {
const [field, val] = option.value.split(':')
if (!field || !val) continue
if (filterValue.negative) { if (filterValue.negative) {
andFacets.push([option.value.replace(':', '!=')]) if (!negativeByType[field]) {
} else { negativeByType[field] = []
if (option.method === 'or') {
if (!orFacets[type.id]) {
orFacets[type.id] = []
}
orFacets[type.id].push(option.value)
} else if (option.method === 'and') {
andFacets.push([option.value])
} }
negativeByType[field].push(val)
} else if (option.method === 'or') {
if (!orGroups[field]) {
orGroups[field] = []
}
orGroups[field].push(val)
} else {
parts.push(`${field} = "${val}"`)
} }
} }
} }
Object.values(orFacets).forEach((facets) => andFacets.push(facets)) for (const [field, values] of Object.entries(orGroups)) {
if (values.length === 1) {
parts.push(`${field} = "${values[0]}"`)
} else {
const quoted = values.map((v) => `"${v}"`).join(', ')
parts.push(`${field} IN [${quoted}]`)
}
}
/* for (const [field, values] of Object.entries(negativeByType)) {
Add environment facets, separate from the rest because it oddly depends on the combination const quoted = values.map((v) => `"${v}"`).join(', ')
of filters selected to determine which facets to add. parts.push(`${field} NOT IN [${quoted}]`)
Uses filterValues (merged user + provided filters) so server-provided environment }
filters are respected.
*/ // Environment facets
const client = filterValues.some( const client = filterValues.some(
(filter) => filter.type === 'environment' && filter.option === 'client', (filter) => filter.type === 'environment' && filter.option === 'client',
) )
const server = filterValues.some( const server = filterValues.some(
(filter) => filter.type === 'environment' && filter.option === 'server', (filter) => filter.type === 'environment' && filter.option === 'server',
) )
andFacets.push(...createEnvironmentFacets(client, server)) for (const envGroup of getEnvironmentFilterGroups(client, server)) {
if (envGroup.length === 1) {
const projectType = projectTypes.value.map((projectType) => `project_type:${projectType}`) const [field, val] = envGroup[0].split(':')
if (andFacets.length > 0) { parts.push(`${field} = "${val}"`)
return [projectType, ...andFacets] } else if (envGroup.length > 1) {
} else { const conditions = envGroup.map((f) => {
return [projectType] const [field, val] = f.split(':')
return `${field} = "${val}"`
})
parts.push(`(${conditions.join(' OR ')})`)
}
} }
// Project types
if (projectTypes.value.length === 1) {
parts.push(`project_types = "${projectTypes.value[0]}"`)
} else if (projectTypes.value.length > 1) {
const quoted = projectTypes.value.map((v) => `"${v}"`).join(', ')
parts.push(`project_types IN [${quoted}]`)
}
return parts.join(' AND ')
}) })
const requestParams: Ref<string> = computed(() => { const requestParams: Ref<string> = computed(() => {
@@ -504,7 +531,9 @@ export function useSearch(
params.push(`query=${encodeURIComponent(query.value)}`) params.push(`query=${encodeURIComponent(query.value)}`)
} }
params.push(`facets=${encodeURIComponent(JSON.stringify(facets.value))}`) if (newFilters.value) {
params.push(`new_filters=${encodeURIComponent(newFilters.value)}`)
}
const offset = (currentPage.value - 1) * maxResults.value const offset = (currentPage.value - 1) * maxResults.value
if (currentPage.value !== 1) { if (currentPage.value !== 1) {
@@ -716,7 +745,7 @@ export function useSearch(
filters, filters,
// Computed // Computed
facets, newFilters,
requestParams, requestParams,
// Functions // Functions
@@ -725,22 +754,22 @@ export function useSearch(
} }
} }
export function createEnvironmentFacets(client: boolean, server: boolean): string[][] { function getEnvironmentFilterGroups(client: boolean, server: boolean): string[][] {
const facets: string[][] = [] const groups: string[][] = []
if (client && server) { if (client && server) {
facets.push(['client_side:required'], ['server_side:required']) groups.push(['client_side:required'], ['server_side:required'])
} else if (client) { } else if (client) {
facets.push( groups.push(
['client_side:optional', 'client_side:required'], ['client_side:optional', 'client_side:required'],
['server_side:optional', 'server_side:unsupported'], ['server_side:optional', 'server_side:unsupported'],
) )
} else if (server) { } else if (server) {
facets.push( groups.push(
['client_side:optional', 'client_side:unsupported'], ['client_side:optional', 'client_side:unsupported'],
['server_side:optional', 'server_side:required'], ['server_side:optional', 'server_side:required'],
) )
} }
return facets return groups
} }
function getOptionValue(option: FilterOption, negative?: boolean): string { function getOptionValue(option: FilterOption, negative?: boolean): string {