Compare commits

...
Author SHA1 Message Date
Calum H. (IMB11) 8b4f913605 feat: qa 2026-05-23 21:35:37 +01:00
Calum H. (IMB11) 8e61f042b7 feat: qa + app routing bugs 2026-05-23 21:09:18 +01:00
Calum H. (IMB11) 8301620b76 feat: migrate all headers to use PageHeader shared component. 2026-05-23 19:12:46 +01:00
Calum H. (IMB11) 3a69e8818a fix: ssr for instances subpages with middleware 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 8944437f1b fix: ssr 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 65e250f7f2 fix: header power state 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 5e34efea22 feat: header migration pt 2 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) e36f8a42f5 feat: PageHeader migration start 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) c5f1fa1154 fix: header issues 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 443e17f9d5 fix: lint 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 7622abe59b qa: pass 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 76036602a3 chore: rename worlds -> instances 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) e2ac1274ac fix: modpack linked text alignment 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) ceef2811f4 fix: worlds layout 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 739a1baef5 feat: fix btn sizing 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) 1e1a75ab90 fix: lint 2026-05-23 19:09:14 +01:00
Calum H. (IMB11) b6f25e9ed4 chore: clean up wrapped layout folder structure 2026-05-23 19:07:40 +01:00
Calum H. (IMB11) ef4c2e3161 feat: reshuffle layout for worlds 2026-05-23 19:05:31 +01:00
Calum H. (IMB11) 7911ce8e4a feat: world card alignment 2026-05-23 19:02:50 +01:00
Calum H. (IMB11) fcaaf534a8 fix: lint + i18n 2026-05-23 19:02:50 +01:00
Calum H. (IMB11) 3cd18b7205 feat: world switching page implementation 2026-05-23 19:02:50 +01:00
f9d47e8edc feat: Add new "Enabled" sorting button next to "Disabled" (#6000)
* feat: Added new "Enabled" sorting button next to "Disabled"

* Updated when filter buttons show

- When all mods are disabled, only "Disabled" shows
- When all mods are enabled, only "Enabled" shows
- When there disabled and enabled mods, then only both buttons show.

* Updated when filter buttons show

---------

Co-authored-by: Prospector <6166773+Prospector@users.noreply.github.com>
2026-05-23 16:12:14 +00:00
a58bc3dc21 feat: java installation ui improvements (#5731)
* Clean impl of java installation ui improvements

* Migrate composable to ts

* Migrate to ButtonStyled, fix coloring

* Fix lint

* Fix clearing java path not refreshing state

* fix: use Table component + install btn disabled state tooltip

---------

Signed-off-by: Arthur <creeperkatze.dev@gmail.com>
Signed-off-by: Arthur <contact@creeperkatze.dev>
Co-authored-by: Creeperkatze <178587183+Creeperkatze@users.noreply.github.com>
Co-authored-by: Calum H. <calum@modrinth.com>
Co-authored-by: Calum H. (IMB11) <contact@cal.engineer>
2026-05-23 14:46:12 +00:00
ProspectorandGitHub 1e46444fb0 fix: checklist forcing redirects (#6173) 2026-05-22 15:53:22 -07:00
ProspectorandGitHub 1511e55597 fix: skip reviewed projects in queue (#6171) 2026-05-22 14:54:50 -07:00
aecsocketandGitHub 5727e156ed Fetch project analytics events on analytics get (#6143)
* Fetch project analytics events

* fix

* post-query ua bucketing

* fmt
2026-05-22 18:32:33 +00:00
Calum H.andGitHub 657186398d fix: remove broken roadmap reference (#6165)
Signed-off-by: Calum H. <calum@modrinth.com>
2026-05-22 18:10:01 +00:00
94 changed files with 6702 additions and 2368 deletions
@@ -9,8 +9,6 @@ body:
options:
- label: I checked the [existing issues](https://github.com/modrinth/code/issues?q=is%3Aissue) for duplicate feature requests
required: true
- label: I have checked that this feature request is not on our [roadmap](https://roadmap.modrinth.com)
required: true
- type: dropdown
id: projects
attributes:
+76 -4
View File
@@ -134,6 +134,7 @@ const route = useRoute()
const APP_LEFT_NAV_WIDTH = '4rem'
const APP_SIDEBAR_WIDTH = 300
const INTERCOM_BUBBLE_DEFAULT_PADDING = 20
const ROUTE_SUSPENSE_TIMEOUT_MS = 60_000
const credentials = ref()
const sidebarToggled = ref(true)
const unsubscribeSidebarToggle = themeStore.$subscribe(() => {
@@ -143,6 +144,22 @@ const forceSidebar = computed(
() => route.path.startsWith('/browse') || route.path.startsWith('/project'),
)
const sidebarVisible = computed(() => sidebarToggled.value || forceSidebar.value)
const keepAliveRouteComponents = computed(() => [
...new Set(
router
.getRoutes()
.map((route) => route.meta.keepAliveComponent)
.filter((name) => typeof name === 'string'),
),
])
function getRouteViewKey(viewRoute) {
const keepAliveKey = viewRoute.meta.keepAliveKey
if (typeof keepAliveKey === 'function') return keepAliveKey(viewRoute)
if (typeof keepAliveKey === 'string') return keepAliveKey
return undefined
}
const hostingRouteActive = computed(() => route.path.startsWith('/hosting'))
const hostingIntercomIdentityKey = computed(() => {
const rawServerId = route.params.id
@@ -482,6 +499,11 @@ const sidebarOverlayScrollbarsOptions = Object.freeze({
},
})
router.beforeEach(async (to) => {
const redirect = await resolveLegacyServerInstanceTabRedirect(to)
if (redirect) return redirect
})
router.beforeEach(() => {
suspensePending = false
if (routerToken) loading.end(routerToken)
@@ -513,6 +535,50 @@ function onSuspensePending() {
suspenseToken = loading.begin()
}
async function resolveLegacyServerInstanceTabRedirect(to) {
if (!['ServerManageContent', 'ServerManageFiles', 'ServerManageBackups'].includes(to.name)) {
return null
}
const serverId = getRouteParam(to.params.id)
if (!serverId) return null
const tabPath =
to.name === 'ServerManageFiles' ? '/files' : to.name === 'ServerManageBackups' ? '/backups' : ''
const instancesPath = `/hosting/manage/${encodeURIComponent(serverId)}/instances`
try {
const serverFull = await tauriApiClient.archon.servers_v1.get(serverId)
const world = serverFull.worlds.find((item) => item.is_active) ?? serverFull.worlds[0]
if (world) {
return {
path: `${instancesPath}/${encodeURIComponent(world.id)}${tabPath}`,
query: to.query,
hash: to.hash,
replace: true,
}
}
} catch {
return {
path: instancesPath,
query: to.query,
hash: to.hash,
replace: true,
}
}
return {
path: instancesPath,
query: to.query,
hash: to.hash,
replace: true,
}
}
function getRouteParam(param) {
return Array.isArray(param) ? param[0] : param
}
function onSuspenseResolve() {
if (suspenseToken) {
loading.end(suspenseToken)
@@ -1446,11 +1512,17 @@ provideAppUpdateDownloadProgress(appUpdateDownload)
>
{{ formatMessage(messages.authUnreachableBody) }}
</Admonition>
<RouterView v-slot="{ Component }">
<RouterView v-slot="{ Component, route: viewRoute }">
<template v-if="Component">
<Suspense @pending="onSuspensePending" @resolve="onSuspenseResolve">
<component :is="Component"></component>
</Suspense>
<KeepAlive :include="keepAliveRouteComponents" :max="3">
<Suspense
:timeout="ROUTE_SUSPENSE_TIMEOUT_MS"
@pending="onSuspensePending"
@resolve="onSuspenseResolve"
>
<component :is="Component" :key="getRouteViewKey(viewRoute)"></component>
</Suspense>
</KeepAlive>
</template>
</RouterView>
</div>
@@ -1,35 +1,33 @@
<template>
<ModalWrapper ref="detectJavaModal" header="Select java version" :show-ad-on-close="false">
<div class="auto-detect-modal">
<div class="table">
<div class="table-row table-head">
<div class="table-cell table-text">Version</div>
<div class="table-cell table-text">Path</div>
<div class="table-cell table-text">Actions</div>
</div>
<div v-for="javaInstall in chosenInstallOptions" :key="javaInstall.path" class="table-row">
<div class="table-cell table-text">
<span>{{ javaInstall.version }}</span>
</div>
<div v-tooltip="javaInstall.path" class="table-cell table-text">
<span>{{ javaInstall.path }}</span>
</div>
<div class="table-cell table-text manage">
<ButtonStyled v-if="currentSelected.path === javaInstall.path">
<button disabled><CheckIcon /> Selected</button>
<div class="flex flex-col gap-4">
<Table :columns="javaInstallColumns" :data="chosenInstallOptions" row-key="path">
<template #cell-version="{ value }">
<span class="font-semibold text-primary">{{ value }}</span>
</template>
<template #cell-path="{ value }">
<span v-tooltip="value" class="block truncate font-mono text-xs">{{ value }}</span>
</template>
<template #cell-actions="{ row }">
<div class="flex items-center justify-end">
<ButtonStyled v-if="currentSelected.path === row.path">
<button class="!shadow-none" disabled><CheckIcon /> Selected</button>
</ButtonStyled>
<ButtonStyled v-else>
<button @click="setJavaInstall(javaInstall)"><PlusIcon /> Select</button>
<button class="!shadow-none" @click="setJavaInstall(row)"><PlusIcon /> Select</button>
</ButtonStyled>
</div>
</div>
<div v-if="chosenInstallOptions.length === 0" class="table-row entire-row">
<div class="table-cell table-text">No java installations found!</div>
</div>
</div>
<div class="input-group push-right">
</template>
<template #empty-state>
<div class="p-4 text-secondary">No java installations found!</div>
</template>
</Table>
<div class="flex justify-end">
<ButtonStyled type="outlined">
<button @click="$refs.detectJavaModal.hide()">
<button
class="!shadow-none !border-surface-4 !border"
@click="$refs.detectJavaModal.hide()"
>
<XIcon />
Cancel
</button>
@@ -40,7 +38,7 @@
</template>
<script setup>
import { CheckIcon, PlusIcon, XIcon } from '@modrinth/assets'
import { ButtonStyled, injectNotificationManager } from '@modrinth/ui'
import { ButtonStyled, injectNotificationManager, Table } from '@modrinth/ui'
import { ref } from 'vue'
import ModalWrapper from '@/components/ui/modal/ModalWrapper.vue'
@@ -52,6 +50,11 @@ const { handleError } = injectNotificationManager()
const chosenInstallOptions = ref([])
const detectJavaModal = ref(null)
const currentSelected = ref({})
const javaInstallColumns = [
{ key: 'version', label: 'Version', width: '9rem' },
{ key: 'path', label: 'Path' },
{ key: 'actions', label: 'Actions', align: 'right', width: '10rem' },
]
defineExpose({
show: async (version, currentSelectedJava) => {
@@ -77,25 +80,3 @@ function setJavaInstall(javaInstall) {
})
}
</script>
<style lang="scss" scoped>
.auto-detect-modal {
.table {
.table-row {
grid-template-columns: 1fr 4fr min-content;
}
span {
display: inherit;
align-items: center;
justify-content: center;
}
padding: 0.5rem;
}
}
.manage {
display: flex;
gap: 0.5rem;
}
</style>
@@ -1,85 +1,104 @@
<template>
<JavaDetectionModal ref="detectJavaModal" @submit="(val) => emit('update:modelValue', val)" />
<div class="toggle-setting" :class="{ compact }">
<StyledInput
autocomplete="off"
:disabled="props.disabled"
:model-value="props.modelValue ? props.modelValue.path : ''"
:placeholder="placeholder ?? '/path/to/java'"
wrapper-class="installation-input"
@update:model-value="
(val) => {
emit('update:modelValue', {
...props.modelValue,
path: val,
})
}
"
/>
<div :id="props.id" class="toggle-setting" :class="{ compact }">
<div class="input-with-status">
<StyledInput
autocomplete="off"
:disabled="props.disabled"
:model-value="props.modelValue ? props.modelValue.path : ''"
:placeholder="placeholder ?? '/path/to/java'"
wrapper-class="installation-input"
@update:model-value="
(val) => {
emit('update:modelValue', {
...props.modelValue,
path: val,
})
}
"
/>
<ButtonStyled
:color="
!hoveringTest && !testingJava
? testingJavaSuccess === true
? 'green'
: 'red'
: 'standard'
"
color-fill="text"
>
<button
class="!shadow-none"
:disabled="testingJava || props.disabled"
@click="runTest(props.modelValue?.path)"
@mouseenter="!props.disabled && (hoveringTest = true)"
@mouseleave="hoveringTest = false"
>
<SpinnerIcon v-if="testingJava" class="animate-spin h-4 w-4" />
<CheckCircleIcon
v-else-if="testingJavaSuccess === true && !hoveringTest"
class="h-4 w-4"
/>
<XCircleIcon v-else-if="testingJavaSuccess !== true && !hoveringTest" class="h-4 w-4" />
<RefreshCwIcon v-else-if="!props.disabled" class="h-4 w-4" />
</button>
</ButtonStyled>
</div>
<span class="installation-buttons">
<ButtonStyled v-if="props.version">
<button :disabled="props.disabled || installingJava" @click="reinstallJava">
<button
v-tooltip="testingJavaSuccess === true ? 'Already installed' : undefined"
class="!shadow-none"
:disabled="props.disabled || installingJava || testingJavaSuccess === true"
@click="reinstallJava"
>
<DownloadIcon />
{{ installingJava ? 'Installing...' : 'Install recommended' }}
</button>
</ButtonStyled>
<ButtonStyled>
<button :disabled="props.disabled" @click="autoDetect">
<button class="!shadow-none" :disabled="props.disabled" @click="autoDetect">
<SearchIcon />
Detect
</button>
</ButtonStyled>
<ButtonStyled>
<button :disabled="props.disabled" @click="handleJavaFileInput()">
<button class="!shadow-none" :disabled="props.disabled" @click="handleJavaFileInput()">
<FolderSearchIcon />
Browse
</button>
</ButtonStyled>
<ButtonStyled v-if="testingJava">
<button disabled>Testing...</button>
</ButtonStyled>
<ButtonStyled v-else-if="testingJavaSuccess === true">
<button disabled>
<CheckIcon />
Success
</button>
</ButtonStyled>
<ButtonStyled v-else-if="testingJavaSuccess === false">
<button disabled>
<XIcon />
Failed
</button>
</ButtonStyled>
<ButtonStyled v-else>
<button :disabled="props.disabled" @click="testJava">
<PlayIcon />
Test
</button>
</ButtonStyled>
</span>
</div>
</template>
<script setup>
import {
CheckIcon,
CheckCircleIcon,
DownloadIcon,
FolderSearchIcon,
PlayIcon,
RefreshCwIcon,
SearchIcon,
XIcon,
SpinnerIcon,
XCircleIcon,
} from '@modrinth/assets'
import { ButtonStyled, injectNotificationManager, StyledInput } from '@modrinth/ui'
import { open } from '@tauri-apps/plugin-dialog'
import { ref } from 'vue'
import { ref, watch } from 'vue'
import JavaDetectionModal from '@/components/ui/JavaDetectionModal.vue'
import useJavaTest from '@/composables/useJavaTest'
import { trackEvent } from '@/helpers/analytics'
import { auto_install_java, find_filtered_jres, get_jre, test_jre } from '@/helpers/jre.js'
import { auto_install_java, find_filtered_jres, get_jre } from '@/helpers/jre.js'
const { handleError } = injectNotificationManager()
const props = defineProps({
id: {
type: String,
required: false,
default: null,
},
version: {
type: Number,
required: false,
@@ -110,29 +129,36 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue'])
const testingJava = ref(false)
const testingJavaSuccess = ref(null)
const {
testingJava,
javaTestResult: testingJavaSuccess,
testJavaInstallationDebounced,
testJavaInstallation,
} = useJavaTest()
const installingJava = ref(false)
const hoveringTest = ref(false)
let hasInitialized = false
async function testJava() {
testingJava.value = true
testingJavaSuccess.value = await test_jre(
props.modelValue ? props.modelValue.path : '',
props.version,
)
testingJava.value = false
trackEvent('JavaTest', {
path: props.modelValue ? props.modelValue.path : '',
success: testingJavaSuccess.value,
})
setTimeout(() => {
testingJavaSuccess.value = null
}, 2000)
async function runTest(path) {
await testJavaInstallation(path, props.version, true)
}
watch(
() => props.modelValue?.path,
(newPath) => {
if (newPath) {
if (!hasInitialized) {
testJavaInstallation(newPath, props.version, false)
hasInitialized = true
} else {
testJavaInstallationDebounced(newPath, props.version)
}
}
},
{ immediate: true },
)
async function handleJavaFileInput() {
const filePath = await open()
@@ -142,6 +168,7 @@ async function handleJavaFileInput() {
result = {
path: filePath.path ?? filePath,
version: props.version.toString(),
parsed_version: props.version,
architecture: 'x86',
}
}
@@ -175,6 +202,7 @@ async function reinstallJava() {
result = {
path: path,
version: props.version.toString(),
parsed_version: props.version,
architecture: 'x86',
}
}
@@ -186,13 +214,23 @@ async function reinstallJava() {
emit('update:modelValue', result)
installingJava.value = false
runTest(result.path)
}
</script>
<style lang="scss" scoped>
.input-with-status {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.installation-input {
width: 100% !important;
flex-grow: 1;
flex: 1 1 0;
min-width: 0;
}
.toggle-setting {
@@ -215,12 +253,4 @@ async function reinstallJava() {
gap: 0.5rem;
margin: 0;
}
.test-success {
color: var(--color-green);
}
.test-fail {
color: var(--color-red);
}
</style>
@@ -1,6 +1,15 @@
<script setup lang="ts">
import { CheckCircleIcon, XCircleIcon } from '@modrinth/assets'
import {
CheckCircleIcon,
CoffeeIcon,
FolderSearchIcon,
RefreshCwIcon,
SearchIcon,
SpinnerIcon,
XCircleIcon,
} from '@modrinth/assets'
import {
ButtonStyled,
Checkbox,
defineMessages,
injectNotificationManager,
@@ -8,9 +17,11 @@ import {
StyledInput,
useVIntl,
} from '@modrinth/ui'
import { open } from '@tauri-apps/plugin-dialog'
import { computed, readonly, ref, watch } from 'vue'
import JavaSelector from '@/components/ui/JavaSelector.vue'
import JavaDetectionModal from '@/components/ui/JavaDetectionModal.vue'
import useJavaTest from '@/composables/useJavaTest'
import useMemorySlider from '@/composables/useMemorySlider'
import { edit, get_optimal_jre_key } from '@/helpers/profile'
import { get } from '@/helpers/settings.ts'
@@ -25,9 +36,54 @@ const { instance } = injectInstanceSettings()
const globalSettings = (await get().catch(handleError)) as unknown as AppSettings
const overrideJavaInstall = ref(!!instance.value.java_path)
const optimalJava = readonly(await get_optimal_jre_key(instance.value.path).catch(handleError))
const javaInstall = ref({ path: optimalJava.path ?? instance.value.java_path })
const overrideJavaInstall = ref(!!instance.value.java_path)
const javaPath = ref(instance.value.java_path ?? optimalJava?.path ?? '')
const activePath = computed(() =>
overrideJavaInstall.value ? javaPath.value : (optimalJava?.path ?? ''),
)
watch(overrideJavaInstall, (enabled) => {
if (enabled && !javaPath.value) {
javaPath.value = optimalJava?.path ?? ''
}
})
const { testingJava, javaTestResult, testJavaInstallationDebounced, testJavaInstallation } =
useJavaTest()
const hoveringTest = ref(false)
let hasInitialized = false
watch(
activePath,
(newPath) => {
if (newPath && optimalJava?.parsed_version) {
if (!hasInitialized) {
testJavaInstallation(newPath, optimalJava?.parsed_version, false)
hasInitialized = true
} else {
testJavaInstallationDebounced(newPath, optimalJava?.parsed_version)
}
}
},
{ immediate: true },
)
const javaDetectionModal = ref<{ show: (version: number, current: object) => void } | null>(null)
async function handleBrowseJava() {
const result = await open({ multiple: false })
if (result) {
javaPath.value = result
}
}
function handleDetectJava() {
javaDetectionModal.value?.show(optimalJava?.parsed_version, { path: javaPath.value })
}
const overrideJavaArgs = ref((instance.value.extra_launch_args?.length ?? 0) > 0)
const javaArgs = ref(
@@ -51,8 +107,8 @@ const { maxMemory, snapPoints } = (await useMemorySlider().catch(handleError)) a
const editProfileObject = computed(() => {
return {
java_path:
overrideJavaInstall.value && javaInstall.value.path !== ''
? javaInstall.value.path.replace('java.exe', 'javaw.exe')
overrideJavaInstall.value && javaPath.value
? javaPath.value.replace('java.exe', 'javaw.exe')
: null,
extra_launch_args: overrideJavaArgs.value
? javaArgs.value.trim().split(/\s+/).filter(Boolean)
@@ -71,7 +127,7 @@ const editProfileObject = computed(() => {
watch(
[
overrideJavaInstall,
javaInstall,
javaPath,
overrideJavaArgs,
javaArgs,
overrideEnvVars,
@@ -90,17 +146,45 @@ const messages = defineMessages({
id: 'instance.settings.tabs.java.java-installation',
defaultMessage: 'Java installation',
},
customJavaInstallation: {
id: 'instance.settings.tabs.java.custom-java-installation',
defaultMessage: 'Custom Java installation',
},
javaPathPlaceholder: {
id: 'instance.settings.tabs.java.java-path-placeholder',
defaultMessage: '/path/to/java',
},
javaMemory: {
id: 'instance.settings.tabs.java.java-memory',
defaultMessage: 'Memory allocated',
},
customMemoryAllocation: {
id: 'instance.settings.tabs.java.custom-memory-allocation',
defaultMessage: 'Custom memory allocation',
},
javaArguments: {
id: 'instance.settings.tabs.java.java-arguments',
defaultMessage: 'Java arguments',
},
customJavaArguments: {
id: 'instance.settings.tabs.java.custom-java-arguments',
defaultMessage: 'Custom Java arguments',
},
enterJavaArguments: {
id: 'instance.settings.tabs.java.enter-java-arguments',
defaultMessage: 'Enter Java arguments...',
},
javaEnvironmentVariables: {
id: 'instance.settings.tabs.java.environment-variables',
defaultMessage: 'Environment variables',
},
javaMemory: {
id: 'instance.settings.tabs.java.java-memory',
defaultMessage: 'Memory allocated',
customEnvironmentVariables: {
id: 'instance.settings.tabs.java.custom-environment-variables',
defaultMessage: 'Custom environment variables',
},
enterEnvironmentVariables: {
id: 'instance.settings.tabs.java.enter-environment-variables',
defaultMessage: 'Enter environmental variables...',
},
hooks: {
id: 'instance.settings.tabs.java.hooks',
@@ -111,43 +195,86 @@ const messages = defineMessages({
<template>
<div>
<h2 id="project-name" class="m-0 mb-2.5 text-lg font-semibold text-contrast block">
<JavaDetectionModal ref="javaDetectionModal" @submit="(val) => (javaPath = val.path)" />
<h2 class="m-0 mb-2 text-lg font-extrabold text-contrast block">
{{ formatMessage(messages.javaInstallation) }}
</h2>
<Checkbox v-model="overrideJavaInstall" label="Custom Java installation" class="mb-2.5" />
<template v-if="!overrideJavaInstall">
<div class="flex my-2 items-center gap-2 font-semibold">
<template v-if="javaInstall">
<CheckCircleIcon class="text-brand-green h-4 w-4" />
<span>Using default Java {{ optimalJava.major_version }} installation:</span>
</template>
<template v-else-if="optimalJava">
<XCircleIcon class="text-brand-red h-5 w-5" />
<span
>Could not find a default Java {{ optimalJava.major_version }} installation. Please set
one below:</span
<Checkbox
v-model="overrideJavaInstall"
:label="formatMessage(messages.customJavaInstallation)"
class="mb-2"
/>
<div class="flex gap-4 p-4 bg-bg rounded-2xl">
<div class="flex gap-3 items-start flex-1 min-w-0">
<div
class="w-10 h-10 flex items-center justify-center rounded-full bg-button-bg border-solid border-[1px] border-button-border p-2 mt-1 shrink-0 [&_svg]:h-full [&_svg]:w-full"
>
<CoffeeIcon />
</div>
<div class="flex flex-col gap-2 flex-1 min-w-0">
<span class="font-semibold leading-none mt-2"
>Java {{ optimalJava?.parsed_version }}</span
>
</template>
<template v-else>
<XCircleIcon class="text-brand-red h-5 w-5" />
<span
>Could not automatically determine a Java installation to use. Please set one
below:</span
>
</template>
<div class="flex gap-2 items-center">
<StyledInput
:model-value="activePath"
:disabled="!overrideJavaInstall"
autocomplete="off"
:placeholder="formatMessage(messages.javaPathPlaceholder)"
wrapper-class="flex-1 min-w-0"
@update:model-value="(val) => (javaPath = String(val))"
/>
<ButtonStyled
:color="
!hoveringTest && !testingJava
? javaTestResult === true
? 'green'
: 'red'
: 'standard'
"
color-fill="text"
>
<button
:disabled="!overrideJavaInstall || testingJava"
@click="testJavaInstallation(activePath, optimalJava?.parsed_version, true)"
@mouseenter="overrideJavaInstall && (hoveringTest = true)"
@mouseleave="hoveringTest = false"
>
<SpinnerIcon v-if="testingJava" class="animate-spin h-4 w-4" />
<CheckCircleIcon
v-else-if="javaTestResult === true && !hoveringTest"
class="h-4 w-4"
/>
<XCircleIcon v-else-if="javaTestResult !== true && !hoveringTest" class="h-4 w-4" />
<RefreshCwIcon v-else-if="overrideJavaInstall" class="h-4 w-4" />
</button>
</ButtonStyled>
</div>
<div v-if="overrideJavaInstall" class="flex gap-2">
<ButtonStyled>
<button @click="handleDetectJava">
<SearchIcon />
Detect
</button>
</ButtonStyled>
<ButtonStyled>
<button @click="handleBrowseJava">
<FolderSearchIcon />
Browse
</button>
</ButtonStyled>
</div>
</div>
</div>
<div
v-if="javaInstall && !overrideJavaInstall"
class="p-4 bg-bg rounded-xl text-xs text-secondary leading-none font-mono"
>
{{ javaInstall.path }}
</div>
</template>
<JavaSelector v-if="overrideJavaInstall || !javaInstall" v-model="javaInstall" />
<h2 id="project-name" class="mt-6 mb-2.5 text-lg font-semibold text-contrast block">
</div>
<h2 class="mt-4 mb-1 text-lg font-extrabold text-contrast block">
{{ formatMessage(messages.javaMemory) }}
</h2>
<Checkbox v-model="overrideMemorySettings" label="Custom memory allocation" class="mb-2.5" />
<Checkbox
v-model="overrideMemorySettings"
:label="formatMessage(messages.customMemoryAllocation)"
class="mb-2"
/>
<Slider
id="max-memory"
v-model="memory.maximum"
@@ -159,28 +286,36 @@ const messages = defineMessages({
:snap-range="512"
unit="MB"
/>
<h2 id="project-name" class="mt-6 mb-2.5 text-lg font-semibold text-contrast block">
<h2 class="mt-4 mb-1 text-lg font-extrabold text-contrast block">
{{ formatMessage(messages.javaArguments) }}
</h2>
<Checkbox v-model="overrideJavaArgs" label="Custom java arguments" class="my-2" />
<Checkbox
v-model="overrideJavaArgs"
:label="formatMessage(messages.customJavaArguments)"
class="my-2"
/>
<StyledInput
id="java-args"
v-model="javaArgs"
autocomplete="off"
:disabled="!overrideJavaArgs"
placeholder="Enter java arguments..."
:placeholder="formatMessage(messages.enterJavaArguments)"
wrapper-class="w-full"
/>
<h2 id="project-name" class="mt-6 mb-2.5 text-lg font-semibold text-contrast block">
<h2 class="mt-4 mb-1 text-lg font-extrabold text-contrast block">
{{ formatMessage(messages.javaEnvironmentVariables) }}
</h2>
<Checkbox v-model="overrideEnvVars" label="Custom environment variables" class="mb-2.5" />
<Checkbox
v-model="overrideEnvVars"
:label="formatMessage(messages.customEnvironmentVariables)"
class="mb-2"
/>
<StyledInput
id="env-vars"
v-model="envVars"
autocomplete="off"
:disabled="!overrideEnvVars"
placeholder="Enter environmental variables..."
:placeholder="formatMessage(messages.enterEnvironmentVariables)"
wrapper-class="w-full"
/>
</div>
@@ -2,16 +2,21 @@ import type { Labrinth } from '@modrinth/api-client'
import { CheckIcon, PlayIcon, PlusIcon, StopCircleIcon } from '@modrinth/assets'
import type { CardAction } from '@modrinth/ui'
import { commonMessages, defineMessages, useDebugLogger, useVIntl } from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
import { openUrl } from '@tauri-apps/plugin-opener'
import type { ComputedRef, Ref } from 'vue'
import { onUnmounted, ref, shallowRef } from 'vue'
import type { Router } from 'vue-router'
import {
fetchCachedServerStatus,
getFreshCachedServerStatus,
} from '@/composables/instances/use-server-status-query'
import { process_listener } from '@/helpers/events'
import { get_by_profile_path } from '@/helpers/process'
import { kill, list as listInstances } from '@/helpers/profile.js'
import type { GameInstance } from '@/helpers/types'
import { add_server_to_profile, getServerLatency } from '@/helpers/worlds'
import { add_server_to_profile } from '@/helpers/worlds'
import { getServerAddress } from '@/store/install.js'
interface BrowseServerInstance {
@@ -65,14 +70,13 @@ const messages = defineMessages({
export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
const { formatMessage } = useVIntl()
const queryClient = useQueryClient()
const debugLog = useDebugLogger('BrowseServer')
const serverPings = shallowRef<Record<string, number | undefined>>({})
const serverPingCache = new Map<string, number | undefined>()
const pendingServerPings = new Map<string, Promise<number | undefined>>()
const runningServerProjects = ref<Record<string, string>>({})
const lastServerHits = shallowRef<Labrinth.Search.v3.ResultSearchProject[]>([])
const contextMenuRef = ref<ContextMenuHandle | null>(null)
let serverPingCacheActive = true
let serverPingsActive = true
let unlistenProcesses: (() => void) | null = null
async function checkServerRunningStates(hits: Labrinth.Search.v3.ResultSearchProject[]) {
@@ -145,37 +149,26 @@ export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
})
const nextPings = { ...serverPings.value }
for (const { hit, address } of pingsToFetch) {
if (serverPingCache.has(address)) {
nextPings[hit.project_id] = serverPingCache.get(address)
const cachedStatus = getFreshCachedServerStatus(queryClient, address)
if (cachedStatus) {
nextPings[hit.project_id] = cachedStatus.ping
}
}
serverPings.value = nextPings
await Promise.all(
pingsToFetch.map(async ({ hit, address }) => {
if (serverPingCache.has(address)) return
if (getFreshCachedServerStatus(queryClient, address)) return
let pending = pendingServerPings.get(address)
if (!pending) {
pending = getServerLatency(address)
.then((latency) => {
if (serverPingCacheActive) serverPingCache.set(address, latency)
return latency
})
.catch((error) => {
console.error(`Failed to ping server ${address}:`, error)
if (serverPingCacheActive) serverPingCache.set(address, undefined)
return undefined
})
.finally(() => {
pendingServerPings.delete(address)
})
pendingServerPings.set(address, pending)
try {
const status = await fetchCachedServerStatus(queryClient, address)
if (!serverPingsActive) return
serverPings.value = { ...serverPings.value, [hit.project_id]: status.ping }
} catch (error) {
console.error(`Failed to ping server ${address}:`, error)
if (!serverPingsActive) return
serverPings.value = { ...serverPings.value, [hit.project_id]: undefined }
}
const latency = await pending
if (!serverPingCacheActive) return
serverPings.value = { ...serverPings.value, [hit.project_id]: latency }
}),
)
}
@@ -307,10 +300,8 @@ export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
.catch(options.handleError)
onUnmounted(() => {
serverPingCacheActive = false
serverPingsActive = false
unlistenProcesses?.()
serverPingCache.clear()
pendingServerPings.clear()
})
return {
@@ -0,0 +1,50 @@
import type { QueryClient } from '@tanstack/vue-query'
import {
get_server_status,
normalizeServerAddress,
type ProtocolVersion,
type ServerStatus,
} from '@/helpers/worlds'
export const SERVER_STATUS_CACHE_MS = 10 * 60 * 1000
function getProtocolVersionKey(protocolVersion: ProtocolVersion | null) {
if (!protocolVersion) return 'default'
return `${protocolVersion.version}:${protocolVersion.legacy ? 'legacy' : 'modern'}`
}
export function getServerStatusQueryKey(
address: string,
protocolVersion: ProtocolVersion | null = null,
) {
return [
'minecraft-server-status',
normalizeServerAddress(address) || address.trim().toLowerCase(),
getProtocolVersionKey(protocolVersion),
] as const
}
export function getFreshCachedServerStatus(
queryClient: QueryClient,
address: string,
protocolVersion: ProtocolVersion | null = null,
) {
const queryKey = getServerStatusQueryKey(address, protocolVersion)
const updatedAt = queryClient.getQueryState(queryKey)?.dataUpdatedAt ?? 0
if (!updatedAt || Date.now() - updatedAt >= SERVER_STATUS_CACHE_MS) return undefined
return queryClient.getQueryData<ServerStatus>(queryKey)
}
export async function fetchCachedServerStatus(
queryClient: QueryClient,
address: string,
protocolVersion: ProtocolVersion | null = null,
) {
return await queryClient.fetchQuery({
queryKey: getServerStatusQueryKey(address, protocolVersion),
queryFn: () => get_server_status(address, protocolVersion),
staleTime: SERVER_STATUS_CACHE_MS,
gcTime: SERVER_STATUS_CACHE_MS,
})
}
@@ -0,0 +1,52 @@
import { ref } from 'vue'
import { trackEvent } from '@/helpers/analytics'
import { test_jre } from '@/helpers/jre.js'
export default function useJavaTest() {
const testingJava = ref(false)
const javaTestResult = ref<boolean | null>(null)
let testDebounceTimer: ReturnType<typeof setTimeout> | null = null
async function runJavaTest(path: string, version: number, track = true) {
if (testDebounceTimer) {
clearTimeout(testDebounceTimer)
testDebounceTimer = null
}
if (!path) {
javaTestResult.value = null
return
}
testingJava.value = true
try {
javaTestResult.value = await test_jre(path, version)
} catch {
javaTestResult.value = false
}
testingJava.value = false
if (track) {
trackEvent('JavaTest', { path, success: javaTestResult.value })
}
}
function testJavaInstallationDebounced(path: string, version: number, delay = 600) {
if (testDebounceTimer) clearTimeout(testDebounceTimer)
if (!path) {
javaTestResult.value = null
return
}
testDebounceTimer = setTimeout(() => runJavaTest(path, version, false), delay)
}
async function testJavaInstallation(path: string, version: number, track = false) {
await runJavaTest(path, version, track)
}
return {
testingJava,
javaTestResult,
testJavaInstallationDebounced,
testJavaInstallation,
}
}
+8 -1
View File
@@ -147,9 +147,16 @@ export async function get_mod_full_path(path: string, projectPath: string): Prom
return await invoke('plugin:profile|profile_get_mod_full_path', { path, projectPath })
}
export interface JavaVersion {
parsed_version: number
version: string
architecture: string
path: string
}
// Get optimal java version from profile
// Returns a java version
export async function get_optimal_jre_key(path: string): Promise<string | null> {
export async function get_optimal_jre_key(path: string): Promise<JavaVersion | null> {
return await invoke('plugin:profile|profile_get_optimal_jre_key', { path })
}
@@ -143,6 +143,9 @@
"app.browse.server.installing": {
"message": "Installing"
},
"app.browse.server.world-fallback-name": {
"message": "Instance"
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
@@ -611,6 +614,24 @@
"instance.settings.tabs.java": {
"message": "Java and memory"
},
"instance.settings.tabs.java.custom-environment-variables": {
"message": "Custom environment variables"
},
"instance.settings.tabs.java.custom-java-arguments": {
"message": "Custom Java arguments"
},
"instance.settings.tabs.java.custom-java-installation": {
"message": "Custom Java installation"
},
"instance.settings.tabs.java.custom-memory-allocation": {
"message": "Custom memory allocation"
},
"instance.settings.tabs.java.enter-environment-variables": {
"message": "Enter environmental variables..."
},
"instance.settings.tabs.java.enter-java-arguments": {
"message": "Enter Java arguments..."
},
"instance.settings.tabs.java.environment-variables": {
"message": "Environment variables"
},
@@ -626,6 +647,9 @@
"instance.settings.tabs.java.java-memory": {
"message": "Memory allocated"
},
"instance.settings.tabs.java.java-path-placeholder": {
"message": "/path/to/java"
},
"instance.settings.tabs.window": {
"message": "Window"
},
+53 -36
View File
@@ -10,6 +10,7 @@ import {
} from '@modrinth/assets'
import type { BrowseInstallContentType, CardAction, ProjectType, Tags } from '@modrinth/ui'
import {
BrowseInstallHeader,
BrowsePageLayout,
BrowseSidebar,
commonMessages,
@@ -22,8 +23,9 @@ import {
preferencesDiffer,
provideBrowseManager,
requestInstall,
SelectedProjectsFloatingBar,
useBrowseSearch,
useDebugLogger,
useStickyObserver,
useVIntl,
} from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
@@ -56,18 +58,25 @@ import {
} from '@/providers/setup/server-install-content'
import { useBreadcrumbs } from '@/store/breadcrumbs'
defineOptions({
name: 'Browse',
})
const { handleError } = injectNotificationManager()
const { formatMessage } = useVIntl()
const { installingServerProjects, playServerProject, showAddServerToInstanceModal } =
injectServerInstall()
const { install: installVersion } = injectContentInstall()
const queryClient = useQueryClient()
const debugLog = useDebugLogger('Browse')
const router = useRouter()
const route = useRoute()
const browseRouteActive = computed(() => route.path.startsWith('/browse/'))
const serverSetupModalRef = ref<InstanceType<typeof CreationFlowModal> | null>(null)
const serverInstallContent = createServerInstallContent({ serverSetupModalRef })
const serverInstallContent = createServerInstallContent({
serverSetupModalRef,
isRouteInContext: (targetRoute) => targetRoute.path.startsWith('/browse/'),
})
provideServerInstallContent(serverInstallContent)
const {
serverIdQuery,
@@ -77,6 +86,7 @@ const {
isSetupServerContext,
effectiveServerWorldId,
serverContextServerData,
serverContextWorldName,
serverContentProjectIds,
queuedServerInstallProjectIds,
queuedServerInstallCount,
@@ -103,8 +113,6 @@ const {
handleServerModpackFlowCreate,
markServerProjectInstalled,
} = serverInstallContent
debugLog('fetching tags (categories, loaders, gameVersions)')
const [categories, loaders, availableGameVersions] = await Promise.all([
get_categories()
.catch(handleError)
@@ -182,22 +190,10 @@ watchServerContextChanges()
await initInstanceContext()
async function initInstanceContext() {
debugLog('initInstanceContext', {
queryI: route.query.i,
queryAi: route.query.ai,
querySid: route.query.sid,
queryWid: route.query.wid,
queryFrom: route.query.from,
})
await initServerContext()
if (route.query.i) {
instance.value = (await getInstance(route.query.i as string).catch(handleError)) ?? null
debugLog('instance loaded', {
name: instance.value?.name,
loader: instance.value?.loader,
gameVersion: instance.value?.game_version,
})
if (route.query.from === 'worlds') {
get_profile_worlds(route.query.i as string)
@@ -205,34 +201,29 @@ async function initInstanceContext() {
const serverProjectIds = worlds
.filter((w) => w.type === 'server' && 'project_id' in w && w.project_id)
.map((w) => (w as { project_id: string }).project_id)
debugLog('installedServerProjectIds loaded', { count: serverProjectIds.length })
installedProjectIds.value = serverProjectIds
})
.catch(handleError)
} else {
getInstalledProjectIds(route.query.i as string)
.then((ids) => {
debugLog('installedProjectIds loaded', { count: ids?.length })
installedProjectIds.value = ids
})
.catch(handleError)
}
if (instance.value?.linked_data?.project_id) {
debugLog('checking linked project for server status', instance.value.linked_data.project_id)
const projectV3 = await get_project_v3(
instance.value.linked_data.project_id,
'must_revalidate',
).catch(handleError)
if (projectV3?.minecraft_server != null) {
debugLog('instance is a server instance')
isServerInstance.value = true
}
}
}
if (route.query.ai && !(route.params.projectType === 'modpack')) {
debugLog('setting instanceHideInstalled from query', route.query.ai)
instanceHideInstalled.value = route.query.ai === 'true'
}
}
@@ -283,7 +274,7 @@ function syncHiddenServerContentProjectIds() {
watch(
serverContentProjectIds,
() => {
if (!hiddenServerContentProjectIdsInitialized.value) {
if (!hiddenServerContentProjectIdsInitialized.value || serverHideInstalled.value) {
syncHiddenServerContentProjectIds()
}
},
@@ -356,11 +347,9 @@ const {
const offline = ref(!navigator.onLine)
window.addEventListener('offline', () => {
debugLog('went offline')
offline.value = true
})
window.addEventListener('online', () => {
debugLog('went online')
offline.value = false
})
@@ -405,6 +394,10 @@ const messages = defineMessages({
id: 'app.browse.back-to-instance',
defaultMessage: 'Back to instance',
},
worldFallbackName: {
id: 'app.browse.server.world-fallback-name',
defaultMessage: 'Instance',
},
serverInstanceContentWarning: {
id: 'app.browse.server-instance-content-warning',
defaultMessage:
@@ -464,6 +457,9 @@ const projectType = ref<ProjectType>(route.params.projectType as ProjectType)
watch(
() => route.params.projectType as ProjectType,
async (newType) => {
if (!browseRouteActive.value) {
return
}
if (isSetupServerContext.value) {
enforceSetupModpackRoute(newType)
if (newType !== 'modpack') return
@@ -471,11 +467,9 @@ watch(
if (!newType || newType === projectType.value) return
debugLog('projectType route param changed', { from: projectType.value, to: newType })
projectType.value = newType
if (!route.query.i && instance.value) {
debugLog('instance context removed, resetting')
instance.value = null
installedProjectIds.value = null
instanceHideInstalled.value = false
@@ -545,8 +539,9 @@ const selectableProjectTypes = computed(() => {
const installContext = computed(() => {
if (isServerContext.value && serverContextServerData.value) {
return {
name: serverContextServerData.value.name,
name: serverContextWorldName.value ?? formatMessage(messages.worldFallbackName),
loader: serverContextServerData.value.loader ?? '',
loaderVersion: serverContextServerData.value.loader_version ?? '',
gameVersion: serverContextServerData.value.mc_version ?? '',
serverId: serverIdQuery.value,
upstream: serverContextServerData.value.upstream,
@@ -586,6 +581,12 @@ const installContext = computed(() => {
return null
})
const stickyInstallHeaderRef = ref<HTMLElement | null>(null)
const { isStuck: isInstallHeaderStuck } = useStickyObserver(
stickyInstallHeaderRef,
'BrowseInstallHeader',
)
const installingProjectIds = ref<Set<string>>(new Set())
function setProjectInstalling(projectId: string, installing: boolean) {
@@ -682,11 +683,10 @@ function getCardActions(
installed?: boolean
installing?: boolean
}
const isInstalled =
projectResult.installed ||
allInstalledIds.value.has(projectResult.project_id || '') ||
serverContentProjectIds.value.has(projectResult.project_id || '') ||
serverContextServerData.value?.upstream?.project_id === projectResult.project_id
const isInstalled = isServerContext.value
? serverContentProjectIds.value.has(projectResult.project_id || '') ||
serverContextServerData.value?.upstream?.project_id === projectResult.project_id
: projectResult.installed || allInstalledIds.value.has(projectResult.project_id || '')
const isInstalling = installingProjectIds.value.has(projectResult.project_id)
if (
@@ -838,7 +838,6 @@ function onSearchResultInstalled(id: string) {
}
async function search(requestParams: string) {
debugLog('searching v3', requestParams)
const isServer = projectType.value === 'server'
const rawResults = await queryClient.fetchQuery({
@@ -920,6 +919,7 @@ const lockedFilterMessages = computed(() => ({
const searchState = useBrowseSearch({
projectType,
tags,
active: browseRouteActive,
providedFilters: combinedProvidedFilters,
search,
persistentQueryParams: ['i', 'ai', 'shi', 'sid', 'wid', 'from'],
@@ -967,7 +967,12 @@ if (instance.value?.game_version) {
await searchState.refreshSearch()
function getProjectBrowseQuery() {
if (!installContext.value) return undefined
if (!browseRouteActive.value) {
return undefined
}
if (!installContext.value) {
return undefined
}
return {
...route.query,
b: route.fullPath,
@@ -1031,6 +1036,17 @@ provideBrowseManager({
<template>
<div class="flex flex-col gap-3 p-6">
<div
v-if="installContext"
ref="stickyInstallHeaderRef"
class="sticky top-0 z-20 -mx-6 -mt-6 rounded-tl-[--radius-xl] border-0 border-b border-solid border-divider bg-surface-1 px-6 pt-6"
:class="[isInstallHeaderStuck ? 'border-t' : '']"
>
<BrowseInstallHeader bottom-padding />
</div>
<SelectedProjectsFloatingBar v-if="installContext" />
<BrowsePageLayout>
<template #after>
<ContextMenu ref="contextMenuRef" @option-clicked="handleOptionsClick">
@@ -1057,7 +1073,8 @@ provideBrowseManager({
@browse-modpacks="() => {}"
@create="handleServerModpackFlowCreate"
/>
<Teleport to="#sidebar-teleport-target">
<Teleport v-if="browseRouteActive" to="#sidebar-teleport-target">
<BrowseSidebar />
</Teleport>
</div>
@@ -13,7 +13,7 @@ const queryClient = useQueryClient()
if (worldId.value) {
try {
await queryClient.ensureQueryData({
queryKey: ['backups', 'list', serverId],
queryKey: ['backups', 'list', serverId, worldId.value],
queryFn: () => client.archon.backups_v1.list(serverId, worldId.value!),
staleTime: 30_000,
})
@@ -13,7 +13,7 @@ const queryClient = useQueryClient()
if (worldId.value) {
try {
await queryClient.ensureQueryData({
queryKey: ['content', 'list', 'v1', serverId],
queryKey: ['content', 'list', 'v1', serverId, worldId.value],
queryFn: () =>
client.archon.content_v1.getAddons(serverId, worldId.value!, { from_modpack: false }),
staleTime: 30_000,
@@ -4,7 +4,6 @@
:server-id="serverId"
:reload-page="() => router.go(0)"
:resolve-viewer="resolveViewer"
:show-copy-id-action="themeStore.devMode"
:auth-user="authUser"
:navigate-to-billing="() => openUrl('https://modrinth.com/settings/billing')"
:navigate-to-servers="() => router.push('/hosting/manage')"
@@ -26,7 +25,7 @@
"
>
<template #default="{ onReinstall, onReinstallFailed }">
<RouterView v-slot="{ Component }">
<RouterView v-slot="{ Component }" :route="managedRoute">
<template v-if="Component">
<Suspense>
<component
@@ -47,26 +46,37 @@ import type { Archon, Labrinth } from '@modrinth/api-client'
import { injectAuth, injectModrinthClient, ServersManageRootLayout } from '@modrinth/ui'
import { useQuery, useQueryClient } from '@tanstack/vue-query'
import { openUrl } from '@tauri-apps/plugin-opener'
import { computed, watch } from 'vue'
import { computed, ref, shallowRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { get_user } from '@/helpers/cache'
import { get as getCreds } from '@/helpers/mr_auth'
import { useBreadcrumbs } from '@/store/breadcrumbs'
import { useTheming } from '@/store/theme'
const route = useRoute()
const router = useRouter()
const auth = injectAuth()
const client = injectModrinthClient()
const queryClient = useQueryClient()
const themeStore = useTheming()
const breadcrumbs = useBreadcrumbs()
const serverId = computed(() => {
const rawId = route.params.id
return Array.isArray(rawId) ? rawId[0] : (rawId ?? '')
})
const managedRoute = shallowRef(router.currentRoute.value)
const serverId = ref(getRouteParam(managedRoute.value.params.id) ?? '')
watch(
router.currentRoute,
(nextRoute) => {
if (!nextRoute.path.startsWith('/hosting/manage/')) return
managedRoute.value = nextRoute
serverId.value = getRouteParam(nextRoute.params.id) ?? ''
},
{ immediate: true },
)
function getRouteParam(param: string | string[] | undefined): string | null {
if (Array.isArray(param)) return param[0] ?? null
return param ?? null
}
if (serverId.value) {
try {
@@ -93,7 +103,7 @@ watch(
breadcrumbs.setName('Server', server.name)
breadcrumbs.setContext({
name: server.name,
link: `/hosting/manage/${serverId.value}/content`,
link: `/hosting/manage/${serverId.value}/instances`,
})
}
},
@@ -0,0 +1,16 @@
<template>
<ServersManageInstanceRootLayout>
<RouterView v-slot="{ Component }">
<template v-if="Component">
<Suspense>
<component :is="Component" />
</Suspense>
</template>
</RouterView>
</ServersManageInstanceRootLayout>
</template>
<script setup lang="ts">
import { ServersManageInstanceRootLayout } from '@modrinth/ui'
import { RouterView } from 'vue-router'
</script>
@@ -0,0 +1,7 @@
<script setup lang="ts">
import { ServersManageInstancesPage } from '@modrinth/ui'
</script>
<template>
<ServersManageInstancesPage />
</template>
@@ -2,6 +2,8 @@ import Backups from './Backups.vue'
import Content from './Content.vue'
import Files from './Files.vue'
import Index from './Index.vue'
import Instance from './Instance.vue'
import Instances from './Instances.vue'
import Overview from './Overview.vue'
export { Backups, Content, Files, Index, Overview }
export { Backups, Content, Files, Index, Instance, Instances, Overview }
+375 -241
View File
@@ -13,200 +13,57 @@
@unlinked="fetchInstance"
/>
<UpdateToPlayModal ref="updateToPlayModal" :instance="instance" />
<ContentPageHeader>
<template #icon>
<Avatar
:src="icon ? icon : undefined"
:alt="instance.name"
size="64px"
:tint-by="instance.path"
/>
</template>
<template #title>
{{ instance.name }}
</template>
<template #stats>
<PageHeader
:header="instance.name"
:leading="instanceHeaderLeading"
:metadata="instanceHeaderMetadata"
:actions="instanceHeaderActions"
>
<template #metadata-server-details>
<div class="flex items-center flex-wrap gap-2">
<template v-if="!isServerInstance">
<div class="flex items-center gap-2 capitalize font-medium">
{{ instance.loader }} {{ instance.game_version }}
</div>
<div class="w-1.5 h-1.5 rounded-full bg-surface-5"></div>
<div class="flex items-center gap-2 font-medium">
<template v-if="timePlayed > 0">
{{ timePlayedHumanized }}
</template>
<template v-else> Never played </template>
</div>
</template>
<template v-else>
<template v-if="loadingServerPing">
<ServerOnlinePlayers
v-if="playersOnline !== undefined"
:online="playersOnline"
:status-online="statusOnline"
hide-label
/>
<ServerRecentPlays :recent-plays="recentPlays ?? 0" hide-label />
<div
v-if="
(playersOnline !== undefined || recentPlays !== undefined) &&
(minecraftServer?.region || ping)
"
class="w-1.5 h-1.5 rounded-full bg-surface-5"
></div>
<ServerPing v-if="ping" :ping="ping" />
</template>
<ServerRegion v-if="minecraftServer?.region" :region="minecraftServer?.region" />
<template v-if="loadingServerPing">
<ServerOnlinePlayers
v-if="playersOnline !== undefined"
:online="playersOnline"
:status-online="statusOnline"
hide-label
/>
<ServerRecentPlays :recent-plays="recentPlays ?? 0" hide-label />
<div
v-if="minecraftServer?.region || ping"
v-if="
(playersOnline !== undefined || recentPlays !== undefined) &&
(minecraftServer?.region || ping)
"
class="w-1.5 h-1.5 rounded-full bg-surface-5"
></div>
<div
v-if="linkedProjectV3"
class="flex gap-1.5 items-center font-medium text-primary"
>
Linked to
<Avatar
:src="linkedProjectV3.icon_url"
:alt="linkedProjectV3.name"
:tint-by="instance.path"
size="24px"
/>
<router-link
:to="`/project/${linkedProjectV3.slug ?? linkedProjectV3.id}`"
class="hover:underline text-primary truncate"
>
{{ linkedProjectV3.name }}
</router-link>
</div>
<ServerPing v-if="ping" :ping="ping" />
</template>
</div>
</template>
<template #actions>
<div class="flex gap-2">
<ButtonStyled
v-if="
[
'installing',
'pack_installing',
'pack_installed',
'not_installed',
'minecraft_installing',
].includes(instance.install_stage)
"
color="brand"
size="large"
>
<button disabled>Installing...</button>
</ButtonStyled>
<ButtonStyled
v-else-if="instance.install_stage !== 'installed'"
color="brand"
size="large"
>
<button @click="repairInstance()">
<DownloadIcon />
Repair
</button>
</ButtonStyled>
<ButtonStyled v-else-if="playing === true" color="red" size="large">
<button :disabled="stopping" @click="stopInstance('InstancePage')">
<StopCircleIcon />
{{ stopping ? 'Stopping...' : 'Stop' }}
</button>
</ButtonStyled>
<ButtonStyled
v-else-if="playing === false && loading === false && !isServerInstance"
color="brand"
size="large"
>
<button @click="startInstance('InstancePage')">
<PlayIcon />
Play
</button>
</ButtonStyled>
<div
v-else-if="playing === false && loading === false && isServerInstance"
class="joined-buttons"
>
<ButtonStyled color="brand" size="large">
<button @click="handlePlayServer()">
<PlayIcon />
Play
</button>
</ButtonStyled>
<ButtonStyled color="brand" size="large">
<OverflowMenu
:options="[
{
id: 'join_server',
action: () => handlePlayServer(),
},
{
id: 'launch_instance',
action: () => startInstance('InstancePage'),
},
]"
>
<div class="w-0 text-xl relative top-0.5 right-2.5">
<DropdownIcon />
</div>
<template #join_server>
<PlayIcon />
Join server
</template>
<template #launch_instance>
<PlayIcon />
Launch instance
</template>
</OverflowMenu>
</ButtonStyled>
</div>
<ButtonStyled
v-else-if="loading === true && playing === false"
color="brand"
size="large"
>
<button disabled>Starting...</button>
</ButtonStyled>
<ButtonStyled circular size="large">
<button v-tooltip="'Instance settings'" @click="settingsModal?.show()">
<SettingsIcon />
</button>
</ButtonStyled>
<ButtonStyled type="transparent" circular size="large">
<OverflowMenu
:options="[
{
id: 'open-folder',
action: () => {
if (instance) showProfileInFolder(instance.path)
},
},
{
id: 'export-mrpack',
action: () => exportModal?.show(),
},
]"
<ServerRegion v-if="minecraftServer?.region" :region="minecraftServer?.region" />
<div
v-if="minecraftServer?.region || ping"
class="w-1.5 h-1.5 rounded-full bg-surface-5"
></div>
<div v-if="linkedProjectV3" class="flex gap-1.5 items-center font-medium text-primary">
Linked to
<Avatar
:src="linkedProjectV3.icon_url"
:alt="linkedProjectV3.name"
:tint-by="instance.path"
size="24px"
/>
<router-link
:to="`/project/${linkedProjectV3.slug ?? linkedProjectV3.id}`"
class="hover:underline text-primary truncate"
>
<MoreVerticalIcon />
<template #share-instance> <UserPlusIcon /> Share instance </template>
<template #host-a-server> <ServerIcon /> Create a server </template>
<template #open-folder> <FolderOpenIcon /> Open folder </template>
<template #export-mrpack> <PackageIcon /> Export modpack </template>
</OverflowMenu>
</ButtonStyled>
{{ linkedProjectV3.name }}
</router-link>
</div>
</div>
</template>
</ContentPageHeader>
</PageHeader>
</div>
<div :class="['px-6', { 'shrink-0': isFixedRender }]">
<NavTabs :links="tabs" />
@@ -270,50 +127,54 @@ import {
CheckCircleIcon,
ClipboardCopyIcon,
DownloadIcon,
DropdownIcon,
EditIcon,
ExternalIcon,
EyeIcon,
FolderOpenIcon,
TagCategoryGamepad2Icon as Gamepad2Icon,
GlobeIcon,
HashIcon,
MoreVerticalIcon,
PackageIcon,
PlayIcon,
PlusIcon,
ServerIcon,
SettingsIcon,
StopCircleIcon,
TerminalSquareIcon,
TimerIcon,
UpdatedIcon,
UserPlusIcon,
XIcon,
} from '@modrinth/assets'
import {
Avatar,
ButtonStyled,
ContentPageHeader,
formatLoaderLabel,
injectNotificationManager,
NavTabs,
OverflowMenu,
PageHeader,
LoaderIcon as ServerLoaderIcon,
ServerOnlinePlayers,
ServerPing,
ServerRecentPlays,
ServerRegion,
useLoadingBarToken,
} from '@modrinth/ui'
import type { Loaders } from '@modrinth/utils'
import { useQueryClient } from '@tanstack/vue-query'
import { convertFileSrc } from '@tauri-apps/api/core'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import relativeTime from 'dayjs/plugin/relativeTime'
import { computed, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { computed, onUnmounted, ref } from 'vue'
import { onBeforeRouteUpdate, useRoute, useRouter, type LocationQuery } from 'vue-router'
import ContextMenu from '@/components/ui/ContextMenu.vue'
import ExportModal from '@/components/ui/ExportModal.vue'
import InstanceSettingsModal from '@/components/ui/modal/InstanceSettingsModal.vue'
import UpdateToPlayModal from '@/components/ui/modal/UpdateToPlayModal.vue'
import {
fetchCachedServerStatus,
getFreshCachedServerStatus,
} from '@/composables/instances/use-server-status-query'
import { useInstanceConsole } from '@/composables/useInstanceConsole'
import { trackEvent } from '@/helpers/analytics'
import { get_project_v3 } from '@/helpers/cache.js'
@@ -323,7 +184,7 @@ import { get_by_profile_path } from '@/helpers/process'
import { finish_install, get, get_full_path, kill, run } from '@/helpers/profile'
import type { GameInstance } from '@/helpers/types'
import { showProfileInFolder } from '@/helpers/utils.js'
import { get_server_status, refreshWorlds } from '@/helpers/worlds'
import { refreshWorlds, type ServerStatus } from '@/helpers/worlds'
import { injectServerInstall } from '@/providers/server-install'
import { handleSevereError } from '@/store/error.js'
import { useBreadcrumbs } from '@/store/state'
@@ -365,32 +226,79 @@ const selected = ref<unknown[]>([])
const minecraftServer = computed(() => linkedProjectV3.value?.minecraft_server)
const javaServerPingData = computed(() => linkedProjectV3.value?.minecraft_java_server?.ping?.data)
const statusOnline = computed(() => !!javaServerPingData.value)
const liveServerStatusOnline = ref(false)
const statusOnline = computed(() => liveServerStatusOnline.value || !!javaServerPingData.value)
const recentPlays = computed(
() => linkedProjectV3.value?.minecraft_java_server?.verified_plays_2w ?? undefined,
)
const playersOnline = ref<number | undefined>(undefined)
const ping = ref<number | undefined>(undefined)
const loadingServerPing = ref(false)
const activeProfilePath = ref<string>()
let fetchInstanceRequestId = 0
function isContentSubpageRoute(routeName = route.name) {
type InstanceRouteContext = {
name: unknown
path: string
query: LocationQuery
}
type InstancePageData = {
profilePath: string
instance?: GameInstance
linkedProjectV3?: Labrinth.Projects.v3.Project
isServerInstance: boolean
preloadedContent: InstanceContentData | null
}
function applyServerStatus(status: ServerStatus) {
playersOnline.value = status.players?.online
ping.value = status.ping
liveServerStatusOnline.value = true
loadingServerPing.value = true
}
function isContentSubpageRoute(routeName: unknown = route.name) {
return typeof routeName === 'string' && contentSubpageRouteNames.has(routeName)
}
async function fetchInstance() {
isServerInstance.value = false
linkedProjectV3.value = undefined
preloadedContent.value = null
function resetServerStatus() {
ping.value = undefined
playersOnline.value = undefined
liveServerStatusOnline.value = false
loadingServerPing.value = false
}
const nextInstance = await get(route.params.id as string).catch(handleError)
function isCurrentInstanceRequest(requestId: number, profilePath: string) {
return (
requestId === fetchInstanceRequestId &&
route.path.startsWith('/instance') &&
route.params.id === profilePath
)
}
function setInstanceBreadcrumbs(nextInstance: GameInstance, routeContext: InstanceRouteContext) {
breadcrumbs.setName(
'Instance',
nextInstance.name.length > 40 ? nextInstance.name.substring(0, 40) + '...' : nextInstance.name,
)
breadcrumbs.setContext({
name: nextInstance.name,
link: routeContext.path,
query: routeContext.query,
})
}
async function loadInstancePageData(
profilePath: string,
routeName: unknown = route.name,
): Promise<InstancePageData> {
const nextInstance = await get(profilePath).catch(handleError)
let nextLinkedProjectV3: Labrinth.Projects.v3.Project | undefined
let nextIsServerInstance = false
const contentPreloadPromise =
nextInstance && isContentSubpageRoute()
nextInstance && isContentSubpageRoute(routeName)
? loadInstanceContentData(nextInstance.path, undefined, handleError)
: Promise.resolve(null)
@@ -411,59 +319,112 @@ async function fetchInstance() {
const nextPreloadedContent = await contentPreloadPromise
instance.value = nextInstance ?? undefined
linkedProjectV3.value = nextLinkedProjectV3
isServerInstance.value = nextIsServerInstance
preloadedContent.value = nextPreloadedContent
return {
profilePath,
instance: nextInstance ?? undefined,
linkedProjectV3: nextLinkedProjectV3,
isServerInstance: nextIsServerInstance,
preloadedContent: nextPreloadedContent,
}
}
fetchDeferredData()
function applyInstancePageData(data: InstancePageData, routeContext: InstanceRouteContext) {
activeProfilePath.value = data.profilePath
resetServerStatus()
playing.value = false
if (nextInstance) {
instance.value = data.instance
linkedProjectV3.value = data.linkedProjectV3
isServerInstance.value = data.isServerInstance
preloadedContent.value = data.preloadedContent
if (data.instance) {
setInstanceBreadcrumbs(data.instance, routeContext)
}
fetchDeferredData(data.profilePath)
if (data.instance) {
queryClient.prefetchQuery({
queryKey: ['worlds', nextInstance.path],
queryFn: () => refreshWorlds(nextInstance.path),
queryKey: ['worlds', data.instance.path],
queryFn: () => refreshWorlds(data.instance!.path),
staleTime: 30_000,
})
}
}
function fetchDeferredData() {
async function fetchInstance(profilePath = route.params.id as string) {
const requestId = ++fetchInstanceRequestId
const data = await loadInstancePageData(profilePath)
if (!isCurrentInstanceRequest(requestId, profilePath)) return
applyInstancePageData(data, {
name: route.name,
path: route.path,
query: route.query,
})
}
function fetchDeferredData(profilePath: string) {
const serverAddress = linkedProjectV3.value?.minecraft_java_server?.address
if (isServerInstance.value && serverAddress) {
get_server_status(serverAddress)
const cachedStatus = getFreshCachedServerStatus(queryClient, serverAddress)
if (cachedStatus) {
applyServerStatus(cachedStatus)
} else {
playersOnline.value = undefined
ping.value = undefined
loadingServerPing.value = false
}
fetchCachedServerStatus(queryClient, serverAddress)
.then((status) => {
playersOnline.value = status.players?.online
ping.value = status.ping
if (
activeProfilePath.value !== profilePath ||
linkedProjectV3.value?.minecraft_java_server?.address !== serverAddress
)
return
applyServerStatus(status)
})
.catch((error) => {
console.error(`Failed to fetch server status for ${serverAddress}:`, error)
})
.finally(() => {
if (activeProfilePath.value !== profilePath) return
loadingServerPing.value = true
})
} else {
loadingServerPing.value = true
}
updatePlayState()
updatePlayState(profilePath)
}
async function updatePlayState() {
if (!route.params.id) return
const runningProcesses = await get_by_profile_path(route.params.id as string).catch(handleError)
async function updatePlayState(profilePath = route.params.id as string) {
if (!profilePath) return
const runningProcesses = await get_by_profile_path(profilePath).catch(handleError)
if (activeProfilePath.value !== profilePath) return
playing.value = Array.isArray(runningProcesses) && runningProcesses.length > 0
}
await fetchInstance()
watch(
() => route.params.id,
async () => {
if (route.params.id && route.path.startsWith('/instance')) {
await fetchInstance()
}
},
)
await fetchInstance(route.params.id as string)
onBeforeRouteUpdate(async (to) => {
if (!to.path.startsWith('/instance')) return
const profilePath = Array.isArray(to.params.id) ? to.params.id[0] : to.params.id
if (typeof profilePath !== 'string') return false
const requestId = ++fetchInstanceRequestId
const data = await loadInstancePageData(profilePath, to.name)
if (requestId !== fetchInstanceRequestId) return false
applyInstancePageData(data, {
name: to.name,
path: to.path,
query: to.query,
})
})
const basePath = computed(() => `/instance/${encodeURIComponent(route.params.id as string)}`)
@@ -506,20 +467,6 @@ const tabs = computed(() => [
},
])
if (instance.value) {
breadcrumbs.setName(
'Instance',
instance.value.name.length > 40
? instance.value.name.substring(0, 40) + '...'
: instance.value.name,
)
breadcrumbs.setContext({
name: instance.value.name,
link: route.path,
query: route.query,
})
}
const options = ref<InstanceType<typeof ContextMenu> | null>(null)
const startInstance = async (context: string) => {
@@ -679,6 +626,16 @@ const timePlayed = computed(() => {
: 0
})
const loaderDisplayName = computed(() =>
instance.value ? (formatLoaderLabel(instance.value.loader) as Loaders) : null,
)
const loaderLabel = computed(() =>
instance.value && loaderDisplayName.value
? [loaderDisplayName.value, instance.value.loader_version].filter(Boolean).join(' ')
: '',
)
const timePlayedHumanized = computed(() => {
const duration = dayjs.duration(timePlayed.value, 'seconds')
const hours = Math.floor(duration.asHours())
@@ -695,6 +652,183 @@ const timePlayedHumanized = computed(() => {
return seconds + ' second' + (seconds > 1 ? 's' : '')
})
const playtimeLabel = computed(() =>
timePlayed.value > 0 ? timePlayedHumanized.value : 'Never played',
)
const instanceHeaderLeading = computed(() => ({
type: 'avatar' as const,
src: icon.value ? icon.value : undefined,
alt: instance.value?.name,
avatarSize: '64px',
tintBy: instance.value?.path,
}))
const instanceHeaderMetadata = computed(() => {
if (!instance.value) return []
if (isServerInstance.value) {
return [
{
id: 'server-details',
type: 'custom' as const,
class: 'contents',
},
]
}
return [
{
id: 'game-version',
label: instance.value.game_version,
icon: Gamepad2Icon,
},
{
id: 'loader',
label: loaderLabel.value,
icon: ServerLoaderIcon,
iconProps: {
loader: loaderDisplayName.value,
},
},
{
id: 'playtime',
label: playtimeLabel.value,
icon: TimerIcon,
},
]
})
const installingStages = [
'installing',
'pack_installing',
'pack_installed',
'not_installed',
'minecraft_installing',
]
const primaryInstanceAction = computed(() => {
if (!instance.value) return null
if (installingStages.includes(instance.value.install_stage)) {
return {
id: 'installing',
label: 'Installing...',
color: 'brand' as const,
disabled: true,
}
}
if (instance.value.install_stage !== 'installed') {
return {
id: 'repair',
label: 'Repair',
icon: DownloadIcon,
color: 'brand' as const,
onClick: () => {
void repairInstance()
},
}
}
if (playing.value === true) {
return {
id: 'stop',
label: stopping.value ? 'Stopping...' : 'Stop',
icon: StopCircleIcon,
color: 'red' as const,
disabled: stopping.value,
onClick: () => {
void stopInstance('InstancePage')
},
}
}
if (playing.value === false && loading.value === false && !isServerInstance.value) {
return {
id: 'play',
label: 'Play',
icon: PlayIcon,
color: 'brand' as const,
onClick: () => {
void startInstance('InstancePage')
},
}
}
if (playing.value === false && loading.value === false && isServerInstance.value) {
return {
id: 'play',
label: 'Play',
color: 'brand' as const,
joinedActions: [
{
id: 'join_server',
label: 'Play',
icon: PlayIcon,
action: () => {
void handlePlayServer()
},
},
{
id: 'launch_instance',
label: 'Launch instance',
icon: PlayIcon,
action: () => {
void startInstance('InstancePage')
},
},
],
}
}
if (loading.value === true && playing.value === false) {
return {
id: 'starting',
label: 'Starting...',
color: 'brand' as const,
disabled: true,
}
}
return null
})
const instanceHeaderActions = computed(() => [
...(primaryInstanceAction.value ? [primaryInstanceAction.value] : []),
{
id: 'settings',
label: 'Instance settings',
icon: SettingsIcon,
labelHidden: true,
tooltip: 'Instance settings',
onClick: () => settingsModal.value?.show(),
},
{
id: 'more',
label: 'More actions',
icon: MoreVerticalIcon,
labelHidden: true,
type: 'transparent' as const,
tooltip: 'More actions',
menuActions: [
{
id: 'open-folder',
label: 'Open folder',
icon: FolderOpenIcon,
action: () => {
if (instance.value) void showProfileInFolder(instance.value.path)
},
},
{
id: 'export-mrpack',
label: 'Export modpack',
icon: PackageIcon,
action: () => exportModal.value?.show(),
},
],
},
])
onUnmounted(() => {
unlistenProcesses()
unlistenProfiles()
+159 -125
View File
@@ -47,9 +47,9 @@
<div class="flex flex-col gap-4 p-6">
<div
v-if="projectInstallContext"
class="sticky top-0 z-20 -mx-6 -mt-6 rounded-tl-[--radius-xl] border-0 border-b border-solid bg-surface-1 p-3 border-surface-5"
class="sticky top-0 z-20 -mx-6 -mt-6 rounded-tl-[--radius-xl] border-0 border-b border-solid border-divider bg-surface-1 px-6 pt-6"
>
<BrowseInstallHeader :install-context="projectInstallContext" />
<BrowseInstallHeader :install-context="projectInstallContext" bottom-padding />
</div>
<InstanceIndicator v-if="instance && !projectInstallContext" :instance="instance" />
<template v-if="data">
@@ -64,121 +64,9 @@
:project="data"
:project-v3="projectV3"
:ping="serverPing"
:actions="projectHeaderActions"
@contextmenu.prevent.stop="handleRightClick"
>
<template v-if="isServerProject" #actions>
<ButtonStyled v-if="serverPlaying" size="large" color="red">
<button @click="handleStopServer">
<StopCircleIcon />
{{ formatMessage(commonMessages.stopButton) }}
</button>
</ButtonStyled>
<ButtonStyled v-else size="large" color="brand">
<button
:disabled="data && installingServerProjects.includes(data.id)"
@click="handleClickPlay"
>
<PlayIcon />
{{
data && installingServerProjects.includes(data.id)
? formatMessage(commonMessages.installingLabel)
: formatMessage(commonMessages.playButton)
}}
</button>
</ButtonStyled>
<ButtonStyled size="large" circular>
<button
v-tooltip="formatMessage(commonMessages.addServerToInstanceButton)"
@click="handleAddServerToInstance"
>
<PlusIcon />
</button>
</ButtonStyled>
<ButtonStyled size="large" circular type="transparent">
<OverflowMenu
:tooltip="`More options`"
:options="[
{
id: 'open-in-browser',
link: `https://modrinth.com/project/${data.slug}`,
external: true,
},
{
divider: true,
},
{
id: 'report',
color: 'red',
hoverFilled: true,
link: `https://modrinth.com/report?item=project&itemID=${data.id}`,
},
]"
aria-label="More options"
>
<MoreVerticalIcon aria-hidden="true" />
<template #open-in-browser> <ExternalIcon /> Open in browser </template>
<template #report> <ReportIcon /> Report </template>
</OverflowMenu>
</ButtonStyled>
</template>
<template v-else #actions>
<ButtonStyled size="large" color="brand">
<button
v-tooltip="installButtonTooltip"
:disabled="installButtonDisabled"
@click="install(null)"
>
<SpinnerIcon
v-if="installButtonLoading && !installButtonInstalled"
class="animate-spin"
/>
<DownloadIcon v-else-if="!installButtonInstalled && !serverProjectSelected" />
<CheckIcon v-else />
{{ installButtonLabel }}
</button>
</ButtonStyled>
<ButtonStyled size="large" circular type="transparent">
<OverflowMenu
:tooltip="`More options`"
:options="[
{
id: 'follow',
disabled: true,
tooltip: 'Coming soon',
action: () => {},
},
{
id: 'save',
disabled: true,
tooltip: 'Coming soon',
action: () => {},
},
{
id: 'open-in-browser',
link: `https://modrinth.com/${data.project_type}/${data.slug}`,
external: true,
},
{
divider: true,
},
{
id: 'report',
color: 'red',
hoverFilled: true,
link: `https://modrinth.com/report?item=project&itemID=${data.id}`,
},
]"
aria-label="More options"
>
<MoreVerticalIcon aria-hidden="true" />
<template #open-in-browser> <ExternalIcon /> Open in browser </template>
<template #follow> <HeartIcon /> Follow </template>
<template #save> <BookmarkIcon /> Save </template>
<template #report> <ReportIcon /> Report </template>
</OverflowMenu>
</ButtonStyled>
</template>
</ProjectHeader>
/>
<NavTabs
:links="[
{
@@ -266,14 +154,12 @@ import {
} from '@modrinth/assets'
import {
BrowseInstallHeader,
ButtonStyled,
commonMessages,
CreationFlowModal,
defineMessages,
getTargetInstallPreferences,
injectNotificationManager,
NavTabs,
OverflowMenu,
ProjectBackgroundGradient,
ProjectHeader,
ProjectSidebarCompatibility,
@@ -286,6 +172,7 @@ import {
SelectedProjectsFloatingBar,
useVIntl,
} from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
import { convertFileSrc } from '@tauri-apps/api/core'
import { openUrl } from '@tauri-apps/plugin-opener'
import dayjs from 'dayjs'
@@ -295,6 +182,10 @@ import { useRoute, useRouter } from 'vue-router'
import ContextMenu from '@/components/ui/ContextMenu.vue'
import InstanceIndicator from '@/components/ui/InstanceIndicator.vue'
import {
fetchCachedServerStatus,
getFreshCachedServerStatus,
} from '@/composables/instances/use-server-status-query'
import {
get_organization,
get_project,
@@ -313,7 +204,6 @@ import {
list as listInstances,
} from '@/helpers/profile'
import { get_categories, get_game_versions, get_loaders } from '@/helpers/tags'
import { getServerLatency } from '@/helpers/worlds'
import { injectContentInstall } from '@/providers/content-install'
import { injectServerInstall } from '@/providers/server-install'
import { createServerInstallContent } from '@/providers/setup/server-install-content'
@@ -327,6 +217,7 @@ const { handleError } = injectNotificationManager()
const { install: installVersion } = injectContentInstall()
const route = useRoute()
const router = useRouter()
const queryClient = useQueryClient()
const breadcrumbs = useBreadcrumbs()
const themeStore = useTheming()
const { formatMessage } = useVIntl()
@@ -340,6 +231,10 @@ const messages = defineMessages({
id: 'app.project.install-context.install-content-to-instance',
defaultMessage: 'Install content to instance',
},
worldFallbackName: {
id: 'app.project.install-context.world-fallback-name',
defaultMessage: 'Instance',
},
alreadyInstalled: {
id: 'app.project.install-button.already-installed',
defaultMessage: 'This project is already installed',
@@ -370,7 +265,10 @@ const serverStatusOnline = ref(false)
const serverInstancePath = ref(null)
const serverPlaying = ref(false)
const serverSetupModalRef = ref(null)
const serverInstallContent = createServerInstallContent({ serverSetupModalRef })
const serverInstallContent = createServerInstallContent({
serverSetupModalRef,
isRouteInContext: (targetRoute) => targetRoute.path.startsWith('/project/'),
})
serverInstallContent.watchServerContextChanges()
await serverInstallContent.initServerContext()
@@ -423,7 +321,9 @@ const projectInstallContext = computed(() => {
const serverData = serverInstallContent.serverContextServerData.value
if (serverData) {
return {
name: serverData.name,
name:
serverInstallContent.serverContextWorldName.value ??
formatMessage(messages.worldFallbackName),
loader: serverData.loader ?? '',
gameVersion: serverData.mc_version ?? '',
serverId: serverInstallContent.serverIdQuery.value,
@@ -501,6 +401,131 @@ const installButtonTooltip = computed(() => {
return null
})
const projectHeaderActions = computed(() => {
if (!data.value) return []
if (isServerProject.value) {
return [
serverPlaying.value
? {
id: 'stop',
label: formatMessage(commonMessages.stopButton),
icon: StopCircleIcon,
color: 'red',
onClick: handleStopServer,
}
: {
id: 'play',
label:
data.value && installingServerProjects.value.includes(data.value.id)
? formatMessage(commonMessages.installingLabel)
: formatMessage(commonMessages.playButton),
icon: PlayIcon,
color: 'brand',
disabled: data.value && installingServerProjects.value.includes(data.value.id),
onClick: handleClickPlay,
},
{
id: 'add-server-to-instance',
label: formatMessage(commonMessages.addServerToInstanceButton),
icon: PlusIcon,
labelHidden: true,
tooltip: formatMessage(commonMessages.addServerToInstanceButton),
onClick: handleAddServerToInstance,
},
{
id: 'more',
label: 'More options',
icon: MoreVerticalIcon,
labelHidden: true,
type: 'transparent',
tooltip: 'More options',
menuActions: [
{
id: 'open-in-browser',
label: 'Open in browser',
icon: ExternalIcon,
action: () => openUrl(`https://modrinth.com/project/${data.value.slug}`),
},
{
divider: true,
},
{
id: 'report',
label: 'Report',
icon: ReportIcon,
color: 'red',
action: () =>
openUrl(`https://modrinth.com/report?item=project&itemID=${data.value.id}`),
},
],
},
]
}
return [
{
id: 'install',
label: installButtonLabel.value,
icon:
installButtonLoading.value && !installButtonInstalled.value
? SpinnerIcon
: !installButtonInstalled.value && !serverProjectSelected.value
? DownloadIcon
: CheckIcon,
iconClass:
installButtonLoading.value && !installButtonInstalled.value ? 'animate-spin' : undefined,
color: 'brand',
tooltip: installButtonTooltip.value,
disabled: installButtonDisabled.value,
onClick: () => install(null),
},
{
id: 'more',
label: 'More options',
icon: MoreVerticalIcon,
labelHidden: true,
type: 'transparent',
tooltip: 'More options',
menuActions: [
{
id: 'follow',
label: 'Follow',
icon: HeartIcon,
disabled: true,
tooltip: 'Coming soon',
action: () => {},
},
{
id: 'save',
label: 'Save',
icon: BookmarkIcon,
disabled: true,
tooltip: 'Coming soon',
action: () => {},
},
{
id: 'open-in-browser',
label: 'Open in browser',
icon: ExternalIcon,
action: () =>
openUrl(`https://modrinth.com/${data.value.project_type}/${data.value.slug}`),
},
{
divider: true,
},
{
id: 'report',
label: 'Report',
icon: ReportIcon,
color: 'red',
action: () => openUrl(`https://modrinth.com/report?item=project&itemID=${data.value.id}`),
},
],
},
]
})
const [allLoaders, allGameVersions] = await Promise.all([
get_loaders().catch(handleError).then(ref),
get_game_versions().catch(handleError).then(ref),
@@ -587,10 +612,19 @@ async function fetchProjectData() {
function fetchDeferredServerData(project) {
const serverAddress = projectV3.value?.minecraft_java_server?.address
if (serverAddress) {
serverPing.value = undefined
getServerLatency(serverAddress)
.then((latency) => {
serverPing.value = latency
const cachedStatus = getFreshCachedServerStatus(queryClient, serverAddress)
if (cachedStatus) {
serverPing.value = cachedStatus.ping
serverStatusOnline.value = true
} else {
serverPing.value = undefined
}
fetchCachedServerStatus(queryClient, serverAddress)
.then((status) => {
if (projectV3.value?.minecraft_java_server?.address !== serverAddress) return
serverPing.value = status.ping
serverStatusOnline.value = true
})
.catch((error) => {
console.error(`Failed to ping server ${serverAddress}:`, error)
@@ -18,7 +18,18 @@ import {
writeStoredServerInstallQueue,
} from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
import { computed, type ComputedRef, nextTick, type Ref, ref, watch } from 'vue'
import {
computed,
type ComputedRef,
nextTick,
onActivated,
onDeactivated,
type Ref,
ref,
shallowRef,
watch,
} from 'vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { useRoute, useRouter } from 'vue-router'
type ServerFlowFrom = 'onboarding' | 'reset-server'
@@ -53,6 +64,7 @@ export interface ServerInstallContentContext {
isSetupServerContext: ComputedRef<boolean>
effectiveServerWorldId: ComputedRef<string | null>
serverContextServerData: Ref<Archon.Servers.v0.Server | null>
serverContextWorldName: ComputedRef<string | null>
serverContentProjectIds: Ref<Set<string>>
queuedServerInstallProjectIds: ComputedRef<Set<string>>
queuedServerInstallCount: ComputedRef<number>
@@ -203,6 +215,7 @@ async function getQueuedInstallPlaceholders(
export function createServerInstallContent(opts: {
serverSetupModalRef: Ref<ServerSetupModalHandle | null>
isRouteInContext?: (route: RouteLocationNormalizedLoaded) => boolean
}) {
const { serverSetupModalRef } = opts
const route = useRoute()
@@ -211,9 +224,22 @@ export function createServerInstallContent(opts: {
const { handleError } = injectNotificationManager()
const queryClient = useQueryClient()
const serverIdQuery = computed(() => readQueryString(route.query.sid))
const worldIdQuery = computed(() => readQueryString(route.query.wid))
const browseFrom = computed(() => readQueryString(route.query.from))
const routeInContext = computed(() => opts.isRouteInContext?.(route) ?? true)
const contextQuery = shallowRef(route.query)
watch(
[() => route.fullPath, routeInContext],
() => {
if (routeInContext.value) {
contextQuery.value = route.query
}
},
{ immediate: true },
)
const serverIdQuery = computed(() => readQueryString(contextQuery.value.sid))
const worldIdQuery = computed(() => readQueryString(contextQuery.value.wid))
const browseFrom = computed(() => readQueryString(contextQuery.value.from))
const serverFlowFrom = computed<ServerFlowFrom | null>(() =>
browseFrom.value === 'onboarding' || browseFrom.value === 'reset-server'
? browseFrom.value
@@ -226,11 +252,13 @@ export function createServerInstallContent(opts: {
const serverContextWorldId = ref<string | null>(worldIdQuery.value)
const serverContextServerData = ref<Archon.Servers.v0.Server | null>(null)
const serverContextServerFull = ref<Archon.Servers.v1.ServerFull | null>(null)
const serverContentProjectIds = ref<Set<string>>(new Set())
const serverContentInstallKeys = ref<Set<string>>(new Set())
const queuedServerInstalls = ref<Map<string, BrowseInstallPlan<InstallableSearchResult>>>(
new Map(),
)
const componentActive = ref(true)
const queuedServerInstallProjectIds = computed(() => new Set(queuedServerInstalls.value.keys()))
const queuedServerInstallCount = computed(() => queuedServerInstalls.value.size)
const selectedServerInstallProjects = computed<BrowseSelectedProject[]>(() =>
@@ -243,6 +271,18 @@ export function createServerInstallContent(opts: {
const isInstallingQueuedServerInstalls = ref(false)
const queuedInstallProgress = ref({ completed: 0, total: 0 })
const effectiveServerWorldId = computed(() => worldIdQuery.value ?? serverContextWorldId.value)
const serverContextWorld = computed(() => {
const serverFull = serverContextServerFull.value
if (!serverFull) return null
const worldId = effectiveServerWorldId.value
if (worldId) {
return serverFull.worlds.find((world) => world.id === worldId) ?? null
}
return serverFull.worlds.find((world) => world.is_active) ?? serverFull.worlds[0] ?? null
})
const serverContextWorldName = computed(() => serverContextWorld.value?.name ?? null)
const serverBackUrl = computed(() => {
const sid = serverIdQuery.value
if (!sid) return '/hosting/manage'
@@ -252,7 +292,7 @@ export function createServerInstallContent(opts: {
if (serverFlowFrom.value === 'reset-server') {
return `/hosting/manage/${sid}?openSettings=installation`
}
return `/hosting/manage/${sid}/content`
return getServerInstanceContentPath(sid, effectiveServerWorldId.value)
})
const serverBackLabel = computed(() => {
if (serverFlowFrom.value === 'onboarding') return 'Back to setup'
@@ -266,9 +306,27 @@ export function createServerInstallContent(opts: {
return 'Installing content'
})
onActivated(() => {
componentActive.value = true
})
onDeactivated(() => {
componentActive.value = false
})
async function getServerContextServerFull(serverId: string) {
if (serverContextServerFull.value?.id === serverId) {
return serverContextServerFull.value
}
const server = await client.archon.servers_v1.get(serverId)
serverContextServerFull.value = server
return server
}
async function resolveServerContextWorldId(serverId: string) {
try {
const server = await client.archon.servers_v1.get(serverId)
const server = await getServerContextServerFull(serverId)
const activeWorld = server.worlds.find((world) => world.is_active)
return activeWorld?.id ?? server.worlds[0]?.id ?? null
} catch (err) {
@@ -304,6 +362,11 @@ export function createServerInstallContent(opts: {
} catch (err) {
handleError(err as Error)
}
try {
await getServerContextServerFull(sid)
} catch (err) {
handleError(err as Error)
}
let resolvedWorldId = effectiveServerWorldId.value
if (!resolvedWorldId) {
@@ -320,41 +383,79 @@ export function createServerInstallContent(opts: {
}
function watchServerContextChanges() {
watch([serverIdQuery, effectiveServerWorldId], async ([sid, wid], [prevSid, prevWid]) => {
if (!sid) {
serverContextServerData.value = null
serverContentProjectIds.value = new Set()
serverContentInstallKeys.value = new Set()
setQueuedServerInstallPlans(new Map())
return
}
watch(
[componentActive, routeInContext, serverIdQuery, effectiveServerWorldId],
async ([active, inContext, sid, wid], [prevActive, prevInContext, prevSid, prevWid]) => {
if (!active || !inContext) return
if (sid !== prevSid) {
serverContentProjectIds.value = new Set()
serverContentInstallKeys.value = new Set()
queuedServerInstalls.value = readStoredServerInstallQueue(sid, wid)
try {
serverContextServerData.value = await client.archon.servers_v0.get(sid)
} catch (err) {
handleError(err as Error)
if (!sid) {
serverContextServerData.value = null
serverContextServerFull.value = null
serverContentProjectIds.value = new Set()
serverContentInstallKeys.value = new Set()
setQueuedServerInstallPlans(new Map())
return
}
}
if (wid !== prevWid) {
queuedServerInstalls.value = readStoredServerInstallQueue(sid, wid)
}
const hasServerDataForRoute = serverContextServerData.value?.server_id === sid
const hasServerFullForRoute = serverContextServerFull.value?.id === sid
const didEnterContext = !prevActive || !prevInContext
const shouldReloadRouteContext =
didEnterContext ||
sid !== prevSid ||
wid !== prevWid ||
!hasServerDataForRoute ||
!hasServerFullForRoute
if (wid && (sid !== prevSid || wid !== prevWid)) {
await refreshServerInstalledContent(sid, wid)
}
})
if (!hasServerDataForRoute || !hasServerFullForRoute) {
serverContextWorldId.value = worldIdQuery.value
if (!hasServerDataForRoute) {
serverContextServerData.value = null
}
if (!hasServerFullForRoute) {
serverContextServerFull.value = null
}
serverContentProjectIds.value = new Set()
serverContentInstallKeys.value = new Set()
}
if (!hasServerDataForRoute) {
try {
serverContextServerData.value = await client.archon.servers_v0.get(sid)
} catch (err) {
handleError(err as Error)
}
}
if (!hasServerFullForRoute) {
try {
const serverFull = await getServerContextServerFull(sid)
if (!worldIdQuery.value) {
const activeWorld = serverFull.worlds.find((world) => world.is_active)
serverContextWorldId.value = activeWorld?.id ?? serverFull.worlds[0]?.id ?? null
}
} catch (err) {
handleError(err as Error)
}
}
if (shouldReloadRouteContext) {
queuedServerInstalls.value = readStoredServerInstallQueue(sid, wid)
}
if (wid && shouldReloadRouteContext) {
await refreshServerInstalledContent(sid, wid)
}
},
)
}
function enforceSetupModpackRoute(currentProjectType: string | undefined) {
if (!isSetupServerContext.value || currentProjectType === 'modpack') return
if (!routeInContext.value || !isSetupServerContext.value || currentProjectType === 'modpack')
return
router.replace({
path: '/browse/modpack',
query: route.query,
query: contextQuery.value,
})
}
@@ -424,7 +525,7 @@ export function createServerInstallContent(opts: {
if (isInstallingQueuedServerInstalls.value) return false
if (!serverId || !worldId) {
handleError(new Error('No server world is available for install.'))
handleError(new Error('No server instance is available for install.'))
return false
}
@@ -556,7 +657,7 @@ export function createServerInstallContent(opts: {
if (serverFlowFrom.value === 'onboarding') {
await client.archon.servers_v1.endIntro(sid)
await router.push(`/hosting/manage/${sid}/content`)
await router.push(getServerInstanceContentPath(sid, wid))
return
}
@@ -571,6 +672,11 @@ export function createServerInstallContent(opts: {
serverContentProjectIds.value = new Set([...serverContentProjectIds.value, id])
}
function getServerInstanceContentPath(serverId: string, worldId: string | null) {
const base = `/hosting/manage/${encodeURIComponent(serverId)}/instances`
return worldId ? `${base}/${encodeURIComponent(worldId)}` : base
}
return {
serverIdQuery,
worldIdQuery,
@@ -581,6 +687,7 @@ export function createServerInstallContent(opts: {
isSetupServerContext,
effectiveServerWorldId,
serverContextServerData,
serverContextWorldName,
serverContentProjectIds,
queuedServerInstallProjectIds,
queuedServerInstallCount,
+58
View File
@@ -6,6 +6,11 @@ import * as Instance from '@/pages/instance'
import * as Library from '@/pages/library'
import * as Project from '@/pages/project'
function getQueryParam(value) {
if (Array.isArray(value)) return value[0] ?? ''
return value ?? ''
}
/**
* Configures application routing. Add page to pages/index and then add to route table here.
*/
@@ -57,6 +62,48 @@ export default new createRouter({
breadcrumb: [{ name: '?Server' }],
},
},
{
path: 'instances',
name: 'ServerManageInstances',
component: Hosting.Instances,
meta: {
breadcrumb: [{ name: '?Server' }],
},
},
{
path: 'instances/:instance_id',
name: 'ServerManageInstance',
component: Hosting.Instance,
meta: {
breadcrumb: [{ name: '?Server' }],
},
children: [
{
path: '',
name: 'ServerManageInstanceContent',
component: Hosting.Content,
meta: {
breadcrumb: [{ name: '?Server' }],
},
},
{
path: 'files',
name: 'ServerManageInstanceFiles',
component: Hosting.Files,
meta: {
breadcrumb: [{ name: '?Server' }],
},
},
{
path: 'backups',
name: 'ServerManageInstanceBackups',
component: Hosting.Backups,
meta: {
breadcrumb: [{ name: '?Server' }],
},
},
],
},
{
path: 'files',
name: 'ServerManageFiles',
@@ -81,6 +128,17 @@ export default new createRouter({
component: Pages.Browse,
meta: {
useContext: true,
keepAliveComponent: 'Browse',
keepAliveKey: (route) => {
return [
'browse',
getQueryParam(route.params.projectType),
getQueryParam(route.query.i),
getQueryParam(route.query.sid),
getQueryParam(route.query.wid),
getQueryParam(route.query.from),
].join(':')
},
breadcrumb: [{ name: '?BrowseTitle' }],
},
},
@@ -0,0 +1,127 @@
<template>
<ButtonStyled size="large" circular>
<PopoutMenu
v-if="authUser"
:tooltip="
saved ? formatMessage(commonMessages.savedLabel) : formatMessage(commonMessages.saveButton)
"
from="top-right"
:aria-label="formatMessage(commonMessages.saveButton)"
:dropdown-id="`${baseId}-save`"
>
<BookmarkIcon aria-hidden="true" :fill="saved ? 'currentColor' : 'none'" />
<template #menu>
<StyledInput
v-model="displayCollectionsSearch"
:placeholder="formatMessage(commonMessages.searchPlaceholder)"
wrapper-class="menu-search"
/>
<div v-if="filteredCollections.length > 0" class="collections-list text-primary">
<Checkbox
v-for="option in filteredCollections"
:key="option.id"
:model-value="option.projects.includes(projectId)"
class="popout-checkbox"
@update:model-value="() => collectProject(option, projectId)"
>
{{ option.name }}
</Checkbox>
</div>
<div v-else class="menu-text">
<p class="popout-text">{{ noCollectionsLabel }}</p>
</div>
<ButtonStyled>
<button class="mx-3 mb-3" @click="createCollection">
<PlusIcon aria-hidden="true" />
{{ createNewCollectionLabel }}
</button>
</ButtonStyled>
</template>
</PopoutMenu>
<nuxt-link
v-else
v-tooltip="formatMessage(commonMessages.saveButton)"
:to="signInRoute"
:aria-label="formatMessage(commonMessages.saveButton)"
>
<BookmarkIcon aria-hidden="true" />
</nuxt-link>
</ButtonStyled>
</template>
<script setup lang="ts">
import { BookmarkIcon, PlusIcon } from '@modrinth/assets'
import {
ButtonStyled,
Checkbox,
commonMessages,
PopoutMenu,
StyledInput,
useVIntl,
} from '@modrinth/ui'
import { computed, ref } from 'vue'
import type { RouteLocationRaw } from 'vue-router'
type CollectionOption = {
id: string
name: string
projects: string[]
}
const props = defineProps<{
authUser?: unknown
signInRoute: RouteLocationRaw
projectId: string
collections: CollectionOption[]
saved: boolean
baseId: string
noCollectionsLabel: string
createNewCollectionLabel: string
collectProject: (option: CollectionOption, projectId: string) => void | Promise<void>
createCollection: (event: MouseEvent) => void
}>()
const { formatMessage } = useVIntl()
const displayCollectionsSearch = ref('')
const filteredCollections = computed(() =>
props.collections
.filter((collection) =>
collection.name.toLowerCase().includes(displayCollectionsSearch.value.toLowerCase()),
)
.slice()
.sort((a, b) => a.name.localeCompare(b.name)),
)
</script>
<style scoped lang="scss">
.popout-checkbox {
padding: var(--gap-sm) var(--gap-md);
white-space: nowrap;
&:hover {
filter: brightness(0.95);
}
}
.menu-text {
padding: 0 var(--gap-md);
font-size: var(--font-size-nm);
color: var(--color-secondary);
}
.menu-search {
margin: var(--gap-sm) var(--gap-md);
width: calc(100% - var(--gap-md) * 2);
}
.collections-list {
max-height: 40rem;
overflow-y: auto;
background-color: var(--color-bg);
border-radius: var(--radius-md);
margin: var(--gap-sm) var(--gap-md);
padding: var(--gap-sm);
}
</style>
@@ -701,11 +701,11 @@ async function navigateToNextUnlockedProject(): Promise<boolean> {
// Quick re-check if close to expiry (last 5 seconds of TTL)
if (now - next.validatedAt > PREFETCH_STALE_MS - 5000) {
const recheck = await moderationQueue.checkLock(next.projectId)
if (recheck.locked && !recheck.expired) {
// Project got locked, remove from queue and try next
const recheckResults = await batchCheckQueueCandidates([next.projectId])
const recheck = recheckResults.get(next.projectId)
if (!isEligibleQueueCandidate(recheck)) {
prefetchQueue.value.shift()
return navigateToNextUnlockedProject() // Recurse to try next
return navigateToNextUnlockedProject()
}
}
@@ -717,33 +717,14 @@ async function navigateToNextUnlockedProject(): Promise<boolean> {
next.skippedIds.map((id) => moderationQueue.completeCurrentProject(id, 'skipped')),
)
if (next.skippedIds.length > 0) {
addNotification({
title: 'Skipped locked projects',
text: `Skipped ${next.skippedIds.length} project(s) being moderated by others.`,
type: 'info',
})
}
notifySkippedQueueProjects(next.skippedIds.length)
// Trigger prefetch replenishment in background (don't await)
maintainPrefetchQueue()
// Navigate to canonical URL if we have metadata (avoids middleware redirect)
if (next.slug && next.projectType) {
const urlType = getProjectTypeForUrlShorthand(next.projectType, [], tags.value)
navigateTo({
path: `/${urlType}/${next.slug}`,
state: { showChecklist: true },
})
} else {
// Fallback: use project ID (will trigger middleware redirect)
navigateTo({
name: 'type-project',
params: { type: 'project', project: next.projectId },
state: { showChecklist: true },
})
}
navigateToQueueProject(
{ slug: next.slug, projectType: next.projectType, locked: false, isProcessing: true },
next.projectId,
)
return true
}
@@ -869,53 +850,107 @@ function reviewAnyway() {
maintainPrefetchQueue()
}
// Batch check locks and fetch project metadata in parallel
interface LockCheckResult {
// Batch check locks, processing status, and fetch project metadata in parallel
interface QueueCandidateCheck {
locked: boolean
expired?: boolean
isOwnLock?: boolean
slug?: string
projectType?: string
status?: string
isProcessing: boolean
}
async function batchCheckLocksWithMetadata(
function isEligibleQueueCandidate(result: QueueCandidateCheck | undefined): boolean {
if (!result?.isProcessing) return false
return !result.locked || !!result.expired || !!result.isOwnLock
}
function notifySkippedQueueProjects(count: number) {
if (count <= 0) return
addNotification({
title: 'Skipped projects',
text: `Skipped ${count} project(s) already moderated or locked by others.`,
type: 'info',
})
}
function navigateToQueueProject(result: QueueCandidateCheck, projectId: string) {
if (result.slug && result.projectType) {
const urlType = getProjectTypeForUrlShorthand(result.projectType, [], tags.value)
navigateTo({
path: `/${urlType}/${result.slug}`,
state: { showChecklist: true },
})
} else {
navigateTo({
name: 'type-project',
params: { type: 'project', project: projectId },
state: { showChecklist: true },
})
}
}
async function batchCheckQueueCandidates(
projectIds: string[],
): Promise<Map<string, LockCheckResult>> {
const results = new Map<string, LockCheckResult>()
): Promise<Map<string, QueueCandidateCheck>> {
const results = new Map<string, QueueCandidateCheck>()
// Check locks and fetch minimal project data in parallel
const checks = await Promise.allSettled(
projectIds.map(async (id) => {
// Parallel: check lock AND fetch project metadata
const [lockResponse, projectData] = await Promise.all([
moderationQueue.checkLock(id),
useBaseFetch(`project/${id}`, { method: 'GET' }).catch(() => null),
])
const status = (projectData as { status?: string } | null)?.status
return {
id,
locked: lockResponse.locked,
expired: lockResponse.expired,
isOwnLock: lockResponse.is_own_lock,
slug: (projectData as { slug?: string })?.slug,
projectType: (projectData as { project_type?: string })?.project_type,
slug: (projectData as { slug?: string } | null)?.slug,
projectType: (projectData as { project_type?: string } | null)?.project_type,
status,
isProcessing: projectData === null ? true : status === 'processing',
}
}),
)
// Use forEach with index to avoid indexOf bug on PromiseSettledResult
checks.forEach((result, index) => {
if (result.status === 'fulfilled') {
results.set(result.value.id, result.value)
} else {
// On error, mark as needing fallback (no metadata)
results.set(projectIds[index], { locked: false })
results.set(projectIds[index], { locked: false, isProcessing: true })
}
})
return results
}
async function findNextEligibleQueueProject(candidateIds: string[]) {
const skippedIds: string[] = []
let checkedCount = 0
while (checkedCount < candidateIds.length) {
const batch = candidateIds.slice(checkedCount, checkedCount + PREFETCH_BATCH_SIZE)
checkedCount += batch.length
const results = await batchCheckQueueCandidates(batch)
for (const id of batch) {
const result = results.get(id)
if (isEligibleQueueCandidate(result)) {
return { projectId: id, result: result!, skippedIds: [...skippedIds] }
}
skippedIds.push(id)
}
}
return null
}
// Maintain a queue of prefetched unlocked projects for instant navigation
async function maintainPrefetchQueue() {
if (isPrefetching.value) return
@@ -947,13 +982,10 @@ async function maintainPrefetchQueue() {
const remainingItems =
currentIndex >= 0 ? queueItems.slice(currentIndex + 1) : queueItems.slice(1)
const candidateIds = remainingItems
.filter((id) => !prefetchedIds.has(id))
.slice(0, PREFETCH_BATCH_SIZE * 2) // Check up to 10 candidates
const candidateIds = remainingItems.filter((id) => !prefetchedIds.has(id))
if (candidateIds.length === 0) return
// 5. Batch check locks AND fetch metadata in parallel
const skippedIds: string[] = []
let checkedCount = 0
@@ -964,31 +996,18 @@ async function maintainPrefetchQueue() {
const batch = candidateIds.slice(checkedCount, checkedCount + PREFETCH_BATCH_SIZE)
checkedCount += batch.length
const results = await batchCheckLocksWithMetadata(batch)
const results = await batchCheckQueueCandidates(batch)
for (const id of batch) {
const result = results.get(id)
// Treat as unlocked if: not locked, OR expired, OR it's our own lock
if (!result?.locked || result?.expired || result?.isOwnLock) {
// Found unlocked project with metadata
if (result?.slug && result?.projectType) {
prefetchQueue.value.push({
projectId: id,
slug: result.slug,
projectType: result.projectType,
validatedAt: Date.now(),
skippedIds: [...skippedIds],
})
} else {
// No metadata - still add but will need fallback navigation
prefetchQueue.value.push({
projectId: id,
slug: '', // Empty = use fallback
projectType: '',
validatedAt: Date.now(),
skippedIds: [...skippedIds],
})
}
if (isEligibleQueueCandidate(result)) {
prefetchQueue.value.push({
projectId: id,
slug: result?.slug ?? '',
projectType: result?.projectType ?? '',
validatedAt: Date.now(),
skippedIds: [...skippedIds],
})
if (prefetchQueue.value.length >= PREFETCH_TARGET_COUNT) break
} else {
@@ -1004,8 +1023,6 @@ async function maintainPrefetchQueue() {
// Debounced prefetch to prevent spam from rapid stage changes
const debouncedPrefetch = useDebounceFn(maintainPrefetchQueue, 300)
const MAX_SKIP_ATTEMPTS = 10
async function skipToNextProject() {
// Skip the current project
const currentProjectId = projectV2.value?.id
@@ -1029,60 +1046,28 @@ async function skipToNextProject() {
debug('[skipToNextProject] No prefetch, entering fallback with batch checking')
// Fallback: batch check remaining projects with metadata (excluding current)
const remainingIds: string[] = []
const queueItems = moderationQueue.currentQueue.items
// Build list of remaining projects, excluding current
for (const id of queueItems) {
if (id === currentProjectId) continue
if (remainingIds.length >= MAX_SKIP_ATTEMPTS) break
remainingIds.push(id)
}
const remainingIds = moderationQueue.currentQueue.items.filter((id) => id !== currentProjectId)
if (remainingIds.length > 0) {
const results = await batchCheckLocksWithMetadata(remainingIds)
const next = await findNextEligibleQueueProject(remainingIds)
let skippedCount = 0
for (const id of remainingIds) {
const result = results.get(id)
// Treat as unlocked if: not locked, OR expired, OR it's our own lock
if (!result?.locked || result?.expired || result?.isOwnLock) {
// Found unlocked - skip the locked ones before it
if (skippedCount > 0) {
addNotification({
title: 'Skipped locked projects',
text: `Skipped ${skippedCount} project(s) being moderated by others.`,
type: 'info',
})
}
// Navigate to canonical URL if we have metadata
if (result?.slug && result?.projectType) {
const urlType = getProjectTypeForUrlShorthand(result.projectType, [], tags.value)
navigateTo({
path: `/${urlType}/${result.slug}`,
state: { showChecklist: true },
})
} else {
// Fallback: use project ID
navigateTo({
name: 'type-project',
params: { type: 'project', project: id },
state: { showChecklist: true },
})
}
return
}
await moderationQueue.completeCurrentProject(id, 'skipped')
skippedCount++
if (next) {
await Promise.all(
next.skippedIds.map((id) => moderationQueue.completeCurrentProject(id, 'skipped')),
)
notifySkippedQueueProjects(next.skippedIds.length)
navigateToQueueProject(next.result, next.projectId)
return
}
// All checked were locked
debug('[skipToNextProject] All projects were locked, skippedCount:', skippedCount)
await Promise.all(
remainingIds.map((id) => moderationQueue.completeCurrentProject(id, 'skipped')),
)
debug('[skipToNextProject] No eligible projects in queue')
addNotification({
title: 'All projects locked',
text: 'All remaining projects are currently being moderated by others.',
title: 'No projects available',
text: 'All remaining projects are already moderated or locked by others.',
type: 'warning',
})
}
@@ -1298,32 +1283,16 @@ onMounted(async () => {
document.addEventListener('visibilitychange', handleVisibilityChange)
notifications.setNotificationLocation('left')
// Check if project has already been reviewed (not in processing status)
if (projectV2.value.status !== 'processing') {
alreadyReviewed.value = true
return
}
// Try to acquire lock
const result = await moderationQueue.acquireLock(projectV2.value.id)
if (result.success) {
handleLockAcquired()
} else if (result.locked_by) {
// Actually locked by another moderator
// In queue mode with more projects - auto-skip to next project
if (moderationQueue.isQueueMode && moderationQueue.queueLength > 1) {
addNotification({
title: 'Project locked',
text: `Skipped project locked by @${result.locked_by.username}.`,
type: 'info',
})
// skipToNextProject already calls completeCurrentProject
await skipToNextProject()
return
}
// Single project mode or last in queue - show locked UI
lockStatus.value = {
locked: true,
lockedBy: result.locked_by,
@@ -2085,72 +2054,36 @@ async function endChecklist(status?: string) {
})
}
} else {
// Use prefetched data if available for instant navigation
if (!(await navigateToNextUnlockedProject())) {
// Fallback: batch check remaining projects with metadata
const remainingIds: string[] = []
const currentProjectId = projectV2.value?.id
const queueItems = moderationQueue.currentQueue.items
const remainingIds = moderationQueue.currentQueue.items.filter(
(id) => id !== currentProjectId,
)
// Build list of remaining projects, excluding current
for (const id of queueItems) {
if (id === currentProjectId) continue
if (remainingIds.length >= MAX_SKIP_ATTEMPTS) break
remainingIds.push(id)
}
let foundUnlocked = false
let foundEligible = false
if (remainingIds.length > 0) {
const results = await batchCheckLocksWithMetadata(remainingIds)
const next = await findNextEligibleQueueProject(remainingIds)
let skippedCount = 0
for (const id of remainingIds) {
const result = results.get(id)
// Treat as unlocked if: not locked, OR expired, OR it's our own lock
if (!result?.locked || result?.expired || result?.isOwnLock) {
// Found unlocked - skip the locked ones before it
if (skippedCount > 0) {
addNotification({
title: 'Skipped locked projects',
text: `Skipped ${skippedCount} project(s) being moderated by others.`,
type: 'info',
})
}
// Navigate to canonical URL if we have metadata
if (result?.slug && result?.projectType) {
const urlType = getProjectTypeForUrlShorthand(result.projectType, [], tags.value)
navigateTo({
path: `/${urlType}/${result.slug}`,
state: { showChecklist: true },
})
} else {
// Fallback: use project ID
navigateTo({
name: 'type-project',
params: { type: 'project', project: id },
state: { showChecklist: true },
})
}
foundUnlocked = true
break
}
await moderationQueue.completeCurrentProject(id, 'skipped')
skippedCount++
}
// If no unlocked projects found, show notification
if (!foundUnlocked && skippedCount > 0) {
if (next) {
await Promise.all(
next.skippedIds.map((id) => moderationQueue.completeCurrentProject(id, 'skipped')),
)
notifySkippedQueueProjects(next.skippedIds.length)
navigateToQueueProject(next.result, next.projectId)
foundEligible = true
} else {
await Promise.all(
remainingIds.map((id) => moderationQueue.completeCurrentProject(id, 'skipped')),
)
addNotification({
title: 'All projects locked',
text: 'All remaining projects are currently being moderated by others.',
title: 'No projects available',
text: 'All remaining projects are already moderated or locked by others.',
type: 'warning',
})
}
}
// If no unlocked projects found, go back to moderation queue
if (!foundUnlocked) {
if (!foundEligible) {
await navigateTo({
name: 'moderation',
})
@@ -65,7 +65,7 @@ const messages = defineMessages({
},
noServerWorld: {
id: 'discover.install.error.no-server-world',
defaultMessage: 'No server world is available for install.',
defaultMessage: 'No server instance is available for install.',
},
backToSetup: {
id: 'discover.install.back-to-setup',
@@ -83,6 +83,10 @@ const messages = defineMessages({
id: 'discover.install.heading.reset-modpack',
defaultMessage: 'Selecting modpack to install after reset',
},
worldFallbackName: {
id: 'discover.install.world-fallback-name',
defaultMessage: 'Instance',
},
})
function getQueuedInstallOwnerFallback(project: ServerInstallSearchResult) {
@@ -145,6 +149,11 @@ export function useServerInstallContent({
return enabled
}),
})
const { data: serverFullData } = useQuery({
queryKey: computed(() => ['servers', 'v1', 'detail', currentServerId.value ?? ''] as const),
queryFn: () => client.archon.servers_v1.get(currentServerId.value!),
enabled: computed(() => !!currentServerId.value),
})
watch(serverData, (val) =>
debug('serverData changed:', val?.server_id, val?.name, val?.loader, val?.mc_version),
@@ -187,7 +196,10 @@ export function useServerInstallContent({
},
}
const contentQueryKey = computed(() => ['content', 'list', currentServerId.value ?? ''] as const)
const contentQueryKey = computed(
() =>
['content', 'list', 'v1', currentServerId.value ?? '', currentWorldId.value ?? null] as const,
)
const { data: serverContentData, error: serverContentError } = useQuery({
queryKey: contentQueryKey,
queryFn: () =>
@@ -625,7 +637,9 @@ export function useServerInstallContent({
if (fromContext.value === 'onboarding') {
await client.archon.servers_v1.endIntro(currentServerId.value)
queryClient.invalidateQueries({ queryKey: ['servers', 'detail', currentServerId.value] })
navigateTo(`/hosting/manage/${currentServerId.value}/content`)
navigateTo(
getServerInstanceContentPath(currentServerId.value, currentWorldId.value ?? null),
)
} else {
navigateTo(`/hosting/manage/${currentServerId.value}?openSettings=installation`)
}
@@ -641,9 +655,14 @@ export function useServerInstallContent({
if (fromContext.value === 'onboarding') return `/hosting/manage/${id}?resumeModal=setup-type`
if (fromContext.value === 'reset-server')
return `/hosting/manage/${id}?openSettings=installation`
return `/hosting/manage/${id}/content`
return getServerInstanceContentPath(id, currentWorldId.value)
})
function getServerInstanceContentPath(serverId: string, worldId: string | null) {
const base = `/hosting/manage/${encodeURIComponent(serverId)}/instances`
return worldId ? `${base}/${encodeURIComponent(worldId)}` : base
}
const serverBackLabel = computed(() => {
if (fromContext.value === 'onboarding') return formatMessage(messages.backToSetup)
if (fromContext.value === 'reset-server') return formatMessage(messages.cancelReset)
@@ -655,13 +674,26 @@ export function useServerInstallContent({
? formatMessage(messages.resetModpackHeading)
: formatMessage(commonMessages.installingContentLabel),
)
const currentWorld = computed(() => {
const full = serverFullData.value
if (!full) return null
const worldId = currentWorldId.value
if (worldId) {
return full.worlds.find((world) => world.id === worldId) ?? null
}
return full.worlds.find((world) => world.is_active) ?? full.worlds[0] ?? null
})
const installContext = computed(() => {
if (!serverData.value) return null
return {
name: serverData.value.name,
loader: serverData.value.loader ?? '',
gameVersion: serverData.value.mc_version ?? '',
name: currentWorld.value?.name ?? formatMessage(messages.worldFallbackName),
loader: currentWorld.value?.content?.modloader ?? serverData.value.loader ?? '',
loaderVersion:
currentWorld.value?.content?.modloader_version ?? serverData.value.loader_version ?? '',
gameVersion: currentWorld.value?.content?.game_version ?? serverData.value.mc_version ?? '',
serverId: currentServerId.value,
upstream: serverData.value.upstream,
iconSrc: serverIcon.value,
+10 -1
View File
@@ -1353,7 +1353,7 @@
"message": "Cancel reset"
},
"discover.install.error.no-server-world": {
"message": "No server world is available for install."
"message": "No server instance is available for install."
},
"discover.install.error.unsupported-content-type": {
"message": "This content type cannot be installed to a server from browse."
@@ -1361,6 +1361,9 @@
"discover.install.heading.reset-modpack": {
"message": "Selecting modpack to install after reset"
},
"discover.install.world-fallback-name": {
"message": "Instance"
},
"discover.seo.description": {
"message": "Search and browse thousands of Minecraft {projectType, select, mod {mods} modpack {modpacks} resourcepack {resource packs} shader {shaders} plugin {plugins} datapack {datapacks} other {projects}} on Modrinth with instant, accurate search results. Our filters help you quickly find the best Minecraft {projectType, select, mod {mods} modpack {modpacks} resourcepack {resource packs} shader {shaders} plugin {plugins} datapack {datapacks} other {projects}}."
},
@@ -3290,6 +3293,12 @@
"servers.manage.content.title": {
"message": "Content - {serverName} - Modrinth"
},
"servers.manage.instances.meta.title": {
"message": "Instances - {server} - Modrinth"
},
"servers.manage.instances.slot-name": {
"message": "Instance #{index}"
},
"servers.notice.actions": {
"message": "Actions"
},
@@ -0,0 +1,84 @@
import { useAppQueryClient } from '~/composables/query-client'
import { createModrinthClient } from '~/helpers/api.ts'
export default defineNuxtRouteMiddleware(async (to) => {
const serverId = getRouteParam(to.params.id)
const worldId = getRouteParam(to.params.instance_id)
if (!serverId || !worldId) return
if (import.meta.client) startLoading()
try {
const auth = await useAuth()
if (!auth.value.token) return
const config = useRuntimeConfig()
const queryClient = useAppQueryClient()
const client = createModrinthClient(auth, {
apiBaseUrl: config.public.apiBaseUrl.replace('/v2/', '/'),
archonBaseUrl: config.public.pyroBaseUrl.replace('/v2/', '/'),
rateLimitKey: config.rateLimitKey,
})
await queryClient.ensureQueryData({
queryKey: ['servers', 'v1', 'detail', serverId],
queryFn: () => client.archon.servers_v1.get(serverId),
staleTime: 30_000,
})
const tab = getInstanceTab(to.path)
if (tab === 'backups') {
await queryClient.ensureQueryData({
queryKey: ['backups', 'list', serverId, worldId],
queryFn: () => client.archon.backups_v1.list(serverId, worldId),
staleTime: 30_000,
})
return
}
if (tab === 'files') {
const path = typeof to.query.path === 'string' ? to.query.path : '/'
await queryClient.ensureQueryData({
queryKey: ['files', serverId, path],
queryFn: () => client.kyros.files_v0.listDirectory(path, 1, 2000),
staleTime: 30_000,
})
return
}
const content = await queryClient.ensureQueryData({
queryKey: ['content', 'list', 'v1', serverId, worldId],
queryFn: () => client.archon.content_v1.getAddons(serverId, worldId, { from_modpack: false }),
staleTime: 30_000,
})
const modpackProjectId =
content.modpack?.spec.platform === 'modrinth' ? content.modpack.spec.project_id : null
if (modpackProjectId) {
await queryClient.ensureQueryData({
queryKey: ['labrinth', 'project', modpackProjectId],
queryFn: () => client.labrinth.projects_v2.get(modpackProjectId),
staleTime: 30_000,
})
}
} catch {
// Let mounted layouts' useQuery surface errors; do not fail route setup.
} finally {
if (import.meta.client) stopLoading()
}
})
function getRouteParam(param: string | string[] | undefined): string | null {
if (Array.isArray(param)) return param[0] ?? null
return param ?? null
}
function getInstanceTab(path: string): 'content' | 'files' | 'backups' {
const segments = path.split('/').filter(Boolean)
const lastSegment = segments[segments.length - 1]
if (lastSegment === 'files') return 'files'
return lastSegment === 'backups' ? 'backups' : 'content'
}
@@ -0,0 +1,40 @@
import { createModrinthClient } from '~/helpers/api.ts'
export default defineNuxtRouteMiddleware(async (to) => {
const match = to.path.match(/^\/hosting\/manage\/([^/]+)\/(content|files|backups)\/?$/)
if (!match) return
const serverId = decodeURIComponent(match[1])
const tab = match[2]
const instancesPath = `/hosting/manage/${encodeURIComponent(serverId)}/instances`
const tabPath = tab === 'content' ? '' : `/${tab}`
const auth = await useAuth()
if (auth.value.token) {
try {
const config = useRuntimeConfig()
const client = createModrinthClient(auth, {
apiBaseUrl: config.public.apiBaseUrl.replace('/v2/', '/'),
archonBaseUrl: config.public.pyroBaseUrl.replace('/v2/', '/'),
rateLimitKey: config.rateLimitKey,
})
const serverFull = await client.archon.servers_v1.get(serverId)
const world = serverFull.worlds.find((item) => item.is_active) ?? serverFull.worlds[0]
if (world) {
return navigateTo(
{
path: `${instancesPath}/${encodeURIComponent(world.id)}${tabPath}`,
query: to.query,
hash: to.hash,
},
{ replace: true },
)
}
} catch {
return navigateTo({ path: instancesPath, query: to.query, hash: to.hash }, { replace: true })
}
}
return navigateTo({ path: instancesPath, query: to.query, hash: to.hash }, { replace: true })
})
+183 -366
View File
@@ -459,358 +459,8 @@
:project="project"
:project-v3="projectV3"
:member="!!currentMember"
>
<template #actions>
<ButtonStyled v-if="auth.user && currentMember" size="large" color="brand" circular>
<nuxt-link
v-tooltip="'Edit project'"
:to="`/${project.project_type}/${project.slug ? project.slug : project.id}/settings`"
class="!font-bold lg:!hidden"
>
<SettingsIcon aria-hidden="true" />
</nuxt-link>
</ButtonStyled>
<ButtonStyled v-if="auth.user && currentMember" size="large" color="brand">
<nuxt-link
:to="`/${project.project_type}/${project.slug ? project.slug : project.id}/settings`"
class="!font-bold max-lg:!hidden"
>
<SettingsIcon aria-hidden="true" />
Edit project
</nuxt-link>
</ButtonStyled>
<div class="hidden sm:contents">
<ButtonStyled
v-if="!isServerProject"
size="large"
:color="
(auth.user && currentMember) || route.name === 'type-project-version-version'
? `standard`
: `brand`
"
:circular="!!auth.user && !!currentMember"
>
<button
v-tooltip="
auth.user && currentMember ? formatMessage(commonMessages.downloadButton) : ''
"
@click="(event) => downloadModal.show(event)"
>
<DownloadIcon aria-hidden="true" />
{{
auth.user && currentMember ? '' : formatMessage(commonMessages.downloadButton)
}}
</button>
</ButtonStyled>
<ButtonStyled
v-else
size="large"
:color="
(auth.user && currentMember) || route.name === 'type-project-version-version'
? `standard`
: `brand`
"
:circular="!!auth.user && !!currentMember"
>
<button
v-tooltip="auth.user && currentMember && !openInAppModal?.open ? 'Play' : ''"
@click="handlePlayServerProject"
>
<PlayIcon aria-hidden="true" />
{{ auth.user && currentMember ? '' : 'Play' }}
</button>
</ButtonStyled>
</div>
<div class="contents sm:hidden">
<ButtonStyled
v-if="!isServerProject"
size="large"
circular
:color="
route.name === 'type-project-version-version' || (auth.user && currentMember)
? `standard`
: `brand`
"
>
<button
:aria-label="formatMessage(commonMessages.downloadButton)"
class="flex sm:hidden"
@click="(event) => downloadModal.show(event)"
>
<DownloadIcon aria-hidden="true" />
</button>
</ButtonStyled>
<ButtonStyled
v-else
size="large"
circular
:color="
route.name === 'type-project-version-version' || (auth.user && currentMember)
? `standard`
: `brand`
"
>
<button aria-label="Play" class="flex sm:hidden" @click="handlePlayServerProject">
<PlayIcon aria-hidden="true" />
</button>
</ButtonStyled>
</div>
<Tooltip
v-if="canCreateServerFrom && flags.showProjectPageQuickServerButton"
theme="dismissable-prompt"
:triggers="[]"
:shown="flags.showProjectPageCreateServersTooltip"
:auto-hide="false"
placement="bottom-start"
>
<ButtonStyled size="large" circular>
<nuxt-link
v-tooltip="formatMessage(messages.createServerTooltip)"
:to="`/hosting?project=${project.id}#plan`"
@click="
() => {
flags.showProjectPageCreateServersTooltip = false
saveFeatureFlags()
}
"
>
<ServerPlusIcon aria-hidden="true" />
</nuxt-link>
</ButtonStyled>
<template #popper>
<div class="grid grid-cols-[min-content] gap-1">
<div class="flex min-w-60 items-center justify-between gap-4">
<h3
class="m-0 flex items-center gap-2 whitespace-nowrap text-base font-bold text-contrast"
>
{{ formatMessage(messages.serversPromoTitle) }}
<TagItem
:style="{
'--_color': 'var(--color-brand)',
'--_bg-color': 'var(--color-brand-highlight)',
}"
>{{ formatMessage(commonMessages.newBadge) }}</TagItem
>
</h3>
<ButtonStyled size="small" circular>
<button
v-tooltip="formatMessage(messages.dontShowAgain)"
@click="
() => {
flags.showProjectPageCreateServersTooltip = false
saveFeatureFlags()
}
"
>
<XIcon aria-hidden="true" />
</button>
</ButtonStyled>
</div>
<p class="m-0 text-wrap text-sm font-medium leading-tight text-secondary">
{{ formatMessage(messages.serversPromoDescription) }}
</p>
<p class="m-0 text-wrap text-sm font-bold text-primary">
<IntlFormatted
:message-id="messages.serversPromoPricing"
:values="{
price: formatPrice(500, 'USD', true),
}"
>
<template #small="{ children }">
<span class="text-xs">
<component :is="() => children" />
</span>
</template>
</IntlFormatted>
</p>
</div>
</template>
</Tooltip>
<ButtonStyled size="large" circular>
<ClientOnly>
<button
v-if="auth.user"
v-tooltip="
following
? formatMessage(commonMessages.unfollowButton)
: formatMessage(commonMessages.followButton)
"
:aria-label="
following
? formatMessage(commonMessages.unfollowButton)
: formatMessage(commonMessages.followButton)
"
@click="userFollowProject(project)"
>
<HeartIcon :fill="following ? 'currentColor' : 'none'" aria-hidden="true" />
</button>
<nuxt-link
v-else
v-tooltip="formatMessage(commonMessages.followButton)"
:to="signInRouteObj"
:aria-label="formatMessage(commonMessages.followButton)"
>
<HeartIcon aria-hidden="true" />
</nuxt-link>
<template #fallback>
<nuxt-link
v-tooltip="formatMessage(commonMessages.followButton)"
:to="signInRouteObj"
:aria-label="formatMessage(commonMessages.followButton)"
>
<HeartIcon aria-hidden="true" />
</nuxt-link>
</template>
</ClientOnly>
</ButtonStyled>
<ButtonStyled size="large" circular>
<PopoutMenu
v-if="auth.user"
:tooltip="
collections.some((x) => x.projects.includes(project.id))
? formatMessage(commonMessages.savedLabel)
: formatMessage(commonMessages.saveButton)
"
from="top-right"
:aria-label="formatMessage(commonMessages.saveButton)"
:dropdown-id="`${baseId}-save`"
>
<BookmarkIcon
aria-hidden="true"
:fill="
collections.some((x) => x.projects.includes(project.id))
? 'currentColor'
: 'none'
"
/>
<template #menu>
<StyledInput
v-model="displayCollectionsSearch"
:placeholder="formatMessage(commonMessages.searchPlaceholder)"
wrapper-class="menu-search"
/>
<div v-if="collections.length > 0" class="collections-list text-primary">
<Checkbox
v-for="option in collections
.slice()
.sort((a, b) => a.name.localeCompare(b.name))"
:key="option.id"
:model-value="option.projects.includes(project.id)"
class="popout-checkbox"
@update:model-value="() => onUserCollectProject(option, project.id)"
>
{{ option.name }}
</Checkbox>
</div>
<div v-else class="menu-text">
<p class="popout-text">{{ formatMessage(messages.noCollectionsFound) }}</p>
</div>
<ButtonStyled>
<button
class="mx-3 mb-3"
@click="(event) => $refs.modal_collection.show(event)"
>
<PlusIcon aria-hidden="true" />
{{ formatMessage(messages.createNewCollection) }}
</button>
</ButtonStyled>
</template>
</PopoutMenu>
<nuxt-link v-else v-tooltip="'Save'" :to="signInRouteObj" aria-label="Save">
<BookmarkIcon aria-hidden="true" />
</nuxt-link>
</ButtonStyled>
<ButtonStyled size="large" circular type="transparent">
<OverflowMenu
:tooltip="formatMessage(commonMessages.moreOptionsButton)"
:options="[
{
id: 'analytics',
link: `/${project.project_type}/${project.slug ? project.slug : project.id}/settings/analytics`,
hoverOnly: true,
shown: auth.user && !!currentMember,
},
{
divider: true,
shown: auth.user && !!currentMember,
},
{
id: 'moderation-checklist',
action: openModerationChecklistFromMenu,
color: 'orange',
hoverOnly: true,
shown:
auth.user &&
tags.staffRoles.includes(auth.user.role) &&
!showModerationChecklist,
},
{
divider: true,
shown:
auth.user &&
tags.staffRoles.includes(auth.user.role) &&
!showModerationChecklist,
},
{
id: 'tech-review',
link: `/moderation/technical-review/${project.id}`,
color: 'orange',
hoverOnly: true,
shown: auth.user && tags.staffRoles.includes(auth.user.role),
},
{
divider: true,
shown: auth.user && tags.staffRoles.includes(auth.user.role),
},
{
id: 'report',
action: () =>
auth.user
? reportProject(project.id)
: navigateTo(
getSignInRouteObj(route, getReportPath('project', project.id)),
),
color: 'red',
hoverOnly: true,
shown: !isMember,
},
{ id: 'copy-id', action: () => copyId() },
{ id: 'copy-permalink', action: () => copyPermalink() },
]"
:aria-label="formatMessage(commonMessages.moreOptionsButton)"
:dropdown-id="`${baseId}-more-options`"
>
<MoreVerticalIcon aria-hidden="true" />
<template #analytics>
<ChartIcon aria-hidden="true" />
{{ formatMessage(commonMessages.analyticsButton) }}
</template>
<template #moderation-checklist>
<ScaleIcon aria-hidden="true" /> {{ formatMessage(messages.reviewProject) }}
</template>
<template #tech-review> <ScanEyeIcon aria-hidden="true" /> Tech review </template>
<template #report>
<ReportIcon aria-hidden="true" />
{{ formatMessage(commonMessages.reportButton) }}
</template>
<template #copy-id>
<ClipboardCopyIcon aria-hidden="true" />
{{ formatMessage(commonMessages.copyIdButton) }}
</template>
<template #copy-permalink>
<ClipboardCopyIcon aria-hidden="true" />
{{ formatMessage(commonMessages.copyPermalinkButton) }}
</template>
</OverflowMenu>
</ButtonStyled>
</template>
</ProjectHeader>
:actions="projectHeaderActions"
/>
<ProjectMemberHeader
v-if="currentMember"
:project="project"
@@ -1042,7 +692,6 @@
<script setup>
import {
BookmarkIcon,
BookTextIcon,
CalendarIcon,
ChartIcon,
@@ -1058,7 +707,6 @@ import {
ModrinthIcon,
MoreVerticalIcon,
PlayIcon,
PlusIcon,
ReportIcon,
ScaleIcon,
ScanEyeIcon,
@@ -1067,7 +715,6 @@ import {
SettingsIcon,
VersionIcon,
WrenchIcon,
XIcon,
} from '@modrinth/assets'
import {
Admonition,
@@ -1079,12 +726,9 @@ import {
getTagMessage,
injectModrinthClient,
injectNotificationManager,
IntlFormatted,
NavTabs,
NewModal,
OpenInAppModal,
OverflowMenu,
PopoutMenu,
PROJECT_DEP_MARKER_QUERY,
ProjectBackgroundGradient,
ProjectEnvironmentModal,
@@ -1099,7 +743,6 @@ import {
ScrollablePanel,
ServersPromo,
StyledInput,
TagItem,
useDebugLogger,
useFormatDateTime,
useFormatPrice,
@@ -1111,7 +754,6 @@ import { capitalizeString, formatProjectType, renderString } from '@modrinth/uti
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import { useLocalStorage } from '@vueuse/core'
import dayjs from 'dayjs'
import { Tooltip } from 'floating-vue'
import { nextTick, readonly, ref, useTemplateRef, watch } from 'vue'
import { navigateTo } from '#app'
@@ -1122,6 +764,7 @@ import CollectionCreateModal from '~/components/ui/create/CollectionCreateModal.
import MessageBanner from '~/components/ui/MessageBanner.vue'
import ModerationChecklist from '~/components/ui/moderation/checklist/ModerationChecklist.vue'
import ModerationProjectNags from '~/components/ui/moderation/ModerationProjectNags.vue'
import ProjectCollectionSaveButton from '~/components/ui/ProjectCollectionSaveButton.vue'
import ProjectMemberHeader from '~/components/ui/ProjectMemberHeader.vue'
import { getSignInRouteObj } from '~/composables/auth.js'
import { saveFeatureFlags } from '~/composables/featureFlags.ts'
@@ -1200,6 +843,7 @@ const projectV3Loaded = computed(() => !projectV3Pending.value || projectV3.valu
const isServerProject = computed(() => projectV3.value?.minecraft_server != null)
const projectEnvironmentModal = useTemplateRef('projectEnvironmentModal')
const modalCollection = useTemplateRef('modal_collection')
const baseId = useId()
@@ -1630,13 +1274,8 @@ const filteredAlpha = computed(() => {
)
})
const displayCollectionsSearch = ref('')
const collections = computed(() =>
user.value && user.value.collections
? user.value.collections.filter((x) =>
x.name.toLowerCase().includes(displayCollectionsSearch.value.toLowerCase()),
)
: [],
user.value && user.value.collections ? user.value.collections : [],
)
if (
@@ -2353,6 +1992,184 @@ const canCreateServerFrom = computed(() => {
return project.value.project_type === 'modpack' && project.value.server_side !== 'unsupported'
})
const projectHeaderActions = computed(() => {
if (!project.value) return []
const projectPath = `/${project.value.project_type}/${project.value.slug ? project.value.slug : project.value.id}`
const hasMember = !!currentMember.value
const userSignedIn = !!auth.value.user
const mutedPrimaryAction = hasMember || route.name === 'type-project-version-version'
const primaryLabel = isServerProject.value ? 'Play' : formatMessage(commonMessages.downloadButton)
return [
...(userSignedIn && hasMember
? [
{
id: 'edit-project',
label: 'Edit project',
icon: SettingsIcon,
color: 'brand',
to: `${projectPath}/settings`,
},
]
: []),
{
id: isServerProject.value ? 'play' : 'download',
label: primaryLabel,
icon: isServerProject.value ? PlayIcon : DownloadIcon,
color: mutedPrimaryAction ? 'standard' : 'brand',
labelHidden: userSignedIn && hasMember,
tooltip: userSignedIn && hasMember ? primaryLabel : undefined,
onClick: (event) => {
if (isServerProject.value) {
handlePlayServerProject()
} else {
downloadModal.value?.show(event)
}
},
},
...(canCreateServerFrom.value && flags.value.showProjectPageQuickServerButton
? [
{
id: 'create-server',
label: formatMessage(messages.serversPromoTitle),
icon: ServerPlusIcon,
labelHidden: true,
tooltip: formatMessage(messages.createServerTooltip),
to: `/hosting?project=${project.value.id}#plan`,
onClick: () => {
flags.value.showProjectPageCreateServersTooltip = false
saveFeatureFlags()
},
prompt: {
title: formatMessage(messages.serversPromoTitle),
description: formatMessage(messages.serversPromoDescription),
badge: formatMessage(commonMessages.newBadge),
footer: formatMessage(messages.serversPromoPricing, {
price: formatPrice(500, 'USD', true),
small: (children) => (Array.isArray(children) ? children.join('') : children),
}),
dismissLabel: formatMessage(messages.dontShowAgain),
shown: flags.value.showProjectPageCreateServersTooltip,
placement: 'bottom-start',
onDismiss: () => {
flags.value.showProjectPageCreateServersTooltip = false
saveFeatureFlags()
},
},
},
]
: []),
{
id: 'follow',
label: following.value
? formatMessage(commonMessages.unfollowButton)
: formatMessage(commonMessages.followButton),
icon: HeartIcon,
iconProps: {
fill: following.value ? 'currentColor' : 'none',
},
labelHidden: true,
tooltip: following.value
? formatMessage(commonMessages.unfollowButton)
: formatMessage(commonMessages.followButton),
to: userSignedIn ? undefined : signInRouteObj.value,
onClick: userSignedIn ? () => userFollowProject(project.value) : undefined,
},
{
id: 'save',
label: formatMessage(commonMessages.saveButton),
component: ProjectCollectionSaveButton,
componentProps: {
authUser: auth.value.user,
signInRoute: signInRouteObj.value,
projectId: project.value.id,
collections: collections.value,
saved: collections.value.some((x) => x.projects.includes(project.value.id)),
baseId,
noCollectionsLabel: formatMessage(messages.noCollectionsFound),
createNewCollectionLabel: formatMessage(messages.createNewCollection),
collectProject: onUserCollectProject,
createCollection: (event) => modalCollection.value?.show(event),
},
},
{
id: 'more',
label: formatMessage(commonMessages.moreOptionsButton),
icon: MoreVerticalIcon,
labelHidden: true,
type: 'transparent',
tooltip: formatMessage(commonMessages.moreOptionsButton),
menuActions: [
{
id: 'analytics',
label: formatMessage(commonMessages.analyticsButton),
icon: ChartIcon,
link: `${projectPath}/settings/analytics`,
shown: userSignedIn && hasMember,
},
{
divider: true,
shown: userSignedIn && hasMember,
},
{
id: 'moderation-checklist',
label: formatMessage(messages.reviewProject),
icon: ScaleIcon,
action: openModerationChecklistFromMenu,
color: 'orange',
shown:
userSignedIn &&
tags.value.staffRoles.includes(auth.value.user.role) &&
!showModerationChecklist.value,
},
{
divider: true,
shown:
userSignedIn &&
tags.value.staffRoles.includes(auth.value.user.role) &&
!showModerationChecklist.value,
},
{
id: 'tech-review',
label: 'Tech review',
icon: ScanEyeIcon,
link: `/moderation/technical-review/${project.value.id}`,
color: 'orange',
shown: userSignedIn && tags.value.staffRoles.includes(auth.value.user.role),
},
{
divider: true,
shown: userSignedIn && tags.value.staffRoles.includes(auth.value.user.role),
},
{
id: 'report',
label: formatMessage(commonMessages.reportButton),
icon: ReportIcon,
action: () =>
auth.value.user
? reportProject(project.value.id)
: navigateTo(getSignInRouteObj(route, getReportPath('project', project.value.id))),
color: 'red',
shown: !isMember.value,
},
{
id: 'copy-id',
label: formatMessage(commonMessages.copyIdButton),
icon: ClipboardCopyIcon,
action: () => copyId(),
},
{
id: 'copy-permalink',
label: formatMessage(commonMessages.copyPermalinkButton),
icon: ClipboardCopyIcon,
action: () => copyPermalink(),
},
],
},
]
})
const createCanonicalUrl = () =>
project.value ? `https://modrinth.com/project/${project.value.id}` : undefined
+7 -10
View File
@@ -4,7 +4,6 @@ import { commonProjectTypeCategoryMessages, NavTabs, useVIntl } from '@modrinth/
const { formatMessage } = useVIntl()
const flags = useFeatureFlags()
const cosmetics = useCosmetics()
const route = useRoute()
const allowTabChanging = computed(() => !route.query.sid)
@@ -48,15 +47,13 @@ const selectableProjectTypes = [
]
</script>
<template>
<div class="new-page sidebar" :class="{ 'alt-layout': !cosmetics.rightSearchLayout }">
<section class="normal-page__header mb-4 flex flex-col gap-4">
<NavTabs
v-if="!flags.projectTypesPrimaryNav && allowTabChanging"
:links="selectableProjectTypes"
replace
class="hidden md:flex"
/>
</section>
<div class="mx-auto box-border flex w-full max-w-[1280px] flex-col gap-4 px-6 pb-6">
<NavTabs
v-if="!flags.projectTypesPrimaryNav && allowTabChanging"
:links="selectableProjectTypes"
replace
class="hidden md:flex"
/>
<NuxtPage />
</div>
</template>
+88 -103
View File
@@ -54,9 +54,6 @@ const client = injectModrinthClient()
const queryClient = useQueryClient()
const filtersMenuOpen = ref(false)
const stickyInstallHeaderRef = ref<HTMLElement | null>(null)
useStickyObserver(stickyInstallHeaderRef, 'DiscoverInstallHeader')
const route = useRoute()
@@ -175,6 +172,11 @@ const {
onboardingModalRef,
debug,
})
const stickyInstallHeaderRef = ref<HTMLElement | null>(null)
const { isStuck: isInstallHeaderStuck } = useStickyObserver(
stickyInstallHeaderRef,
'DiscoverInstallHeader',
)
function getServerModpackContent(project: Labrinth.Search.v3.ResultSearchProject) {
const content = project.minecraft_java_server?.content
@@ -198,49 +200,66 @@ function getServerModpackContent(project: Labrinth.Search.v3.ResultSearchProject
return undefined
}
async function search(requestParams: string) {
type DiscoverProjectSearchHit = Labrinth.Search.v2.ResultSearchProject & {
version_id?: string | null
}
function mapV3ProjectHit(hit: Labrinth.Search.v3.ResultSearchProject): DiscoverProjectSearchHit {
return {
...hit,
project_type: hit.project_types[0] ?? projectTypeId.value,
title: hit.name,
description: hit.summary,
versions: hit.version_id ? [hit.version_id] : [],
latest_version: hit.version_id,
icon_url: hit.icon_url ?? '',
client_side: 'unknown',
server_side: 'unknown',
}
}
async function fetchSearch(requestParams: string) {
debug('search() called', {
requestParams: requestParams.substring(0, 100),
isServer: isServerType.value,
projectTypeId: projectTypeId.value,
})
const config = useRuntimeConfig()
let base = import.meta.server ? config.apiBaseUrl : config.public.apiBaseUrl
if (isServerType.value) {
base = base.replace(/\/v\d\//, '/v3/').replace(/\/v\d$/, '/v3')
}
const url = `${base}search${requestParams}`
debug('search() fetching:', url.substring(0, 120))
const raw = await $fetch<Labrinth.Search.v2.SearchResults | Labrinth.Search.v3.SearchResults>(
url,
{
headers: withLabrinthCanaryHeader(),
},
)
const raw = await client.request<Labrinth.Search.v3.SearchResults>('/search', {
api: 'labrinth',
version: 3,
method: 'GET',
params: Object.fromEntries(new URLSearchParams(requestParams.replace(/^\?/, ''))),
headers: withLabrinthCanaryHeader(),
})
debug('search() response', { total_hits: raw.total_hits, hitCount: raw.hits?.length })
if ('hits_per_page' in raw) {
// v3 response (servers)
if (isServerType.value) {
return {
projectHits: [],
serverHits: raw.hits as Labrinth.Search.v3.ResultSearchProject[],
serverHits: raw.hits,
total_hits: raw.total_hits,
per_page: raw.hits_per_page,
}
}
return {
projectHits: raw.hits as Labrinth.Search.v2.ResultSearchProject[],
projectHits: raw.hits.map(mapV3ProjectHit),
serverHits: [],
total_hits: raw.total_hits,
per_page: raw.limit,
per_page: raw.hits_per_page,
}
}
async function search(requestParams: string) {
return await queryClient.ensureQueryData({
queryKey: ['discover', 'search', 'v3', requestParams],
queryFn: () => fetchSearch(requestParams),
staleTime: 30_000,
})
}
function getCardActions(
result: Labrinth.Search.v2.ResultSearchProject | Labrinth.Search.v3.ResultSearchProject,
currentProjectType: string,
@@ -412,7 +431,7 @@ watch(
)
debug('calling initial refreshSearch')
searchState.refreshSearch()
await searchState.refreshSearch()
const ogTitle = computed(() =>
searchState.query.value
@@ -480,20 +499,30 @@ provideBrowseManager({
<Teleport v-if="flags.searchBackground" to="#absolute-background-teleport">
<div class="search-background"></div>
</Teleport>
<div
v-if="installContext"
ref="stickyInstallHeaderRef"
class="normal-page__header browse-install-header-bleed sticky top-0 z-20 mb-4 flex flex-col gap-2 border-0 bg-surface-1 py-3"
class="sticky top-0 z-20 -mx-6 border-0 border-solid border-divider bg-surface-1 px-6 pt-4"
:class="[isInstallHeaderStuck ? 'border-t' : '']"
>
<BrowseInstallHeader />
<BrowseInstallHeader divider bottom-padding />
</div>
<SelectedProjectsFloatingBar v-if="installContext" :install-context="installContext" />
<aside class="normal-page__sidebar" :aria-label="formatMessage(commonMessages.filtersLabel)">
<AdPlaceholder v-if="!auth.user && !serverData" />
<BrowseSidebar />
</aside>
<section class="normal-page__content">
<div class="flex flex-col gap-3">
<div
class="grid min-w-0 gap-3"
:class="
cosmetics.rightSearchLayout
? 'lg:grid-cols-[minmax(0,1fr)_18.75rem]'
: 'lg:grid-cols-[18.75rem_minmax(0,1fr)]'
"
>
<section
class="flex min-w-0 flex-col gap-3"
:class="cosmetics.rightSearchLayout ? 'lg:order-1' : 'lg:order-2'"
>
<BrowsePageLayout>
<template #display-mode-icon>
<GridIcon v-if="resultsDisplayMode === 'grid'" />
@@ -501,78 +530,34 @@ provideBrowseManager({
<ListIcon v-else />
</template>
</BrowsePageLayout>
<CreationFlowModal
v-if="currentServerId && projectType?.id === 'modpack'"
ref="onboardingModalRef"
:type="fromContext === 'reset-server' ? 'reset-server' : 'server-onboarding'"
:available-loaders="['vanilla', 'fabric', 'neoforge', 'forge', 'quilt', 'paper', 'purpur']"
:show-snapshot-toggle="true"
:on-back="onOnboardingBack"
@hide="onOnboardingHide"
@browse-modpacks="() => {}"
@create="onModpackFlowCreate"
/>
</div>
</section>
</section>
<aside
class="min-w-0"
:class="cosmetics.rightSearchLayout ? 'lg:order-2' : 'lg:order-1'"
:aria-label="formatMessage(commonMessages.filtersLabel)"
>
<BrowseSidebar>
<template #prepend>
<AdPlaceholder v-if="!auth.user && !serverData" />
</template>
</BrowseSidebar>
</aside>
</div>
<CreationFlowModal
v-if="currentServerId && projectType?.id === 'modpack'"
ref="onboardingModalRef"
:type="fromContext === 'reset-server' ? 'reset-server' : 'server-onboarding'"
:available-loaders="['vanilla', 'fabric', 'neoforge', 'forge', 'quilt', 'paper', 'purpur']"
:show-snapshot-toggle="true"
:on-back="onOnboardingBack"
@hide="onOnboardingHide"
@browse-modpacks="() => {}"
@create="onModpackFlowCreate"
/>
</template>
<style lang="scss" scoped>
.browse-install-header-bleed {
grid-column: 1 / -1;
margin-inline: -1.5rem;
padding-inline: 0.75rem !important;
&::after {
content: '';
position: absolute;
right: 50%;
bottom: 0;
width: 100vw;
border-bottom: 1px solid var(--surface-5);
transform: translateX(50%);
}
}
.normal-page__content {
display: contents;
@media screen and (min-width: 1024px) {
display: block;
}
}
.normal-page__sidebar {
grid-row: 3;
@media screen and (min-width: 1024px) {
display: block;
}
}
.filters-card {
padding: var(--spacing-card-md);
@media screen and (min-width: 1024px) {
padding: var(--spacing-card-lg);
}
}
.content-wrapper {
grid-row: 1;
}
.pagination-after {
grid-row: 6;
}
.no-results {
text-align: center;
display: flow-root;
}
.loading-logo {
margin: 2rem;
}
.search-background {
width: 100%;
height: 20rem;
@@ -3,7 +3,6 @@
:server-id="serverId"
:reload-page="() => reloadNuxtApp({ path: route.path })"
:resolve-viewer="resolveViewer"
:show-copy-id-action="flags.developerMode"
:show-advanced-debug-info="flags.advancedDebugInfo"
:stripe-publishable-key="config.public.stripePublishableKey as string"
:site-url="config.public.siteUrl as string"
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { injectModrinthClient } from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
const route = useNativeRoute()
const serverId = route.params.id as string
const client = injectModrinthClient()
const queryClient = useQueryClient()
if (serverId) {
try {
await queryClient.ensureQueryData({
queryKey: ['servers', 'v1', 'detail', serverId],
queryFn: () => client.archon.servers_v1.get(serverId),
staleTime: 30_000,
})
} catch {
// Let mounted layouts' useQuery surface errors; do not fail route setup.
}
}
</script>
<template>
<NuxtPage :route="route" />
</template>
@@ -0,0 +1,31 @@
<script setup lang="ts">
import { injectModrinthClient, ServersManageInstanceRootLayout } from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
const route = useNativeRoute()
const serverId = route.params.id as string
const client = injectModrinthClient()
const queryClient = useQueryClient()
definePageMeta({
middleware: 'server-instance-ready',
})
if (serverId) {
try {
await queryClient.ensureQueryData({
queryKey: ['servers', 'v1', 'detail', serverId],
queryFn: () => client.archon.servers_v1.get(serverId),
staleTime: 30_000,
})
} catch {
// Let mounted layouts' useQuery surface errors; do not fail route setup.
}
}
</script>
<template>
<ServersManageInstanceRootLayout>
<NuxtPage :route="route" />
</ServersManageInstanceRootLayout>
</template>
@@ -14,7 +14,7 @@ const flags = useFeatureFlags()
if (worldId.value) {
try {
await queryClient.ensureQueryData({
queryKey: ['backups', 'list', serverId],
queryKey: ['backups', 'list', serverId, worldId.value],
queryFn: () => client.archon.backups_v1.list(serverId, worldId.value!),
staleTime: 30_000,
})
@@ -10,11 +10,13 @@ const client = injectModrinthClient()
const { server, serverId } = injectModrinthServerContext()
const queryClient = useQueryClient()
const flags = useFeatureFlags()
const route = useNativeRoute()
const initialPath = typeof route.query.path === 'string' ? route.query.path : '/'
try {
await queryClient.ensureQueryData({
queryKey: ['files', serverId, '/'],
queryFn: () => client.kyros.files_v0.listDirectory('/', 1, 2000),
queryKey: ['files', serverId, initialPath],
queryFn: () => client.kyros.files_v0.listDirectory(initialPath, 1, 2000),
staleTime: 30_000,
})
} catch {
@@ -38,7 +38,7 @@ const contentWorldId = await getContentWorldId()
if (contentWorldId) {
try {
const content = await queryClient.ensureQueryData({
queryKey: ['content', 'list', 'v1', serverId],
queryKey: ['content', 'list', 'v1', serverId, contentWorldId],
queryFn: () =>
client.archon.content_v1.getAddons(serverId, contentWorldId, { from_modpack: false }),
staleTime: 30_000,
@@ -0,0 +1,216 @@
<script setup lang="ts">
import type { Archon } from '@modrinth/api-client'
import {
commonMessages,
defineMessages,
formatLoaderLabel,
injectModrinthClient,
injectModrinthServerContext,
ServersManageInstancesPage,
useVIntl,
} from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
const client = injectModrinthClient()
const { server, serverId, isServerRunning } = injectModrinthServerContext()
const queryClient = useQueryClient()
const { formatMessage } = useVIntl()
const messages = defineMessages({
title: {
id: 'servers.manage.instances.meta.title',
defaultMessage: 'Instances - {server} - Modrinth',
},
instanceSlotName: {
id: 'servers.manage.instances.slot-name',
defaultMessage: 'Instance #{index}',
},
})
type LinkedModpack = {
name: string
iconUrl: string | null
link: string | null
}
type WorldSlot =
| {
type: 'world'
id: string
name: string
active: boolean
gameVersion: string | null
loaderLabel: string | null
linkedModpack: LinkedModpack | null
installedContentCount: number | null
lastActiveAt: string | null
createdAt: string | null
}
| {
type: 'empty'
id: string
name: string
}
type ContentSummary = {
gameVersion: string | null
loader: string | null
loaderVersion: string | null
linkedModpack: LinkedModpack | null
installedContentCount: number | null
}
const WORLD_SLOT_COUNT = 3
try {
await queryClient.ensureQueryData({
queryKey: ['servers', 'worlds', 'summary', 'v1', serverId],
queryFn: loadWorldSlots,
staleTime: 30_000,
})
} catch {
// Let mounted layouts' useQuery surface errors; do not fail route setup.
}
useHead({
title: () =>
formatMessage(messages.title, {
server: server.value?.name ?? formatMessage(commonMessages.serverLabel),
}),
})
async function loadWorldSlots(): Promise<WorldSlot[]> {
const serverFull = await client.archon.servers_v1.get(serverId)
const slots = await Promise.all(
serverFull.worlds.map(async (world, index) => {
const content = await loadContentSummary(world, index)
return toWorldSlot(world, content)
}),
)
return padWorldSlots(slots)
}
async function loadContentSummary(
world: Archon.Servers.v1.WorldFull,
index: number,
): Promise<ContentSummary> {
try {
const content = await client.archon.content_v1.getAddons(serverId, world.id, {
addons: true,
updates: false,
})
return {
gameVersion: content.game_version ?? world.content?.game_version ?? null,
loader: content.modloader ?? world.content?.modloader ?? null,
loaderVersion: content.modloader_version ?? world.content?.modloader_version ?? null,
linkedModpack: getLinkedModpack(content.modpack),
installedContentCount: content.addons?.length ?? 0,
}
} catch {
return createDummyContentSummary(world, index)
}
}
function toWorldSlot(world: Archon.Servers.v1.WorldFull, content: ContentSummary): WorldSlot {
return {
type: 'world',
id: world.id,
name: world.name,
active: world.is_active,
gameVersion: content.gameVersion,
loaderLabel: getLoaderLabel(content.loader, content.loaderVersion),
linkedModpack: content.linkedModpack,
installedContentCount: content.installedContentCount,
lastActiveAt: getLatestKnownActivity(world),
createdAt: world.created_at,
}
}
function padWorldSlots(slots: WorldSlot[]): WorldSlot[] {
const padded = [...slots]
for (let i = padded.length; i < WORLD_SLOT_COUNT; i++) {
padded.push({
type: 'empty',
id: `empty-world-slot-${i + 1}`,
name: formatMessage(messages.instanceSlotName, { index: i + 1 }),
})
}
return padded
}
function getLinkedModpack(modpack: Archon.Content.v1.ModpackFields | null): LinkedModpack | null {
if (!modpack) return null
const name =
modpack.title ??
(modpack.spec.platform === 'local_file' ? modpack.spec.name : modpack.spec.project_id)
return {
name,
iconUrl: modpack.icon_url ?? null,
link: modpack.spec.platform === 'modrinth' ? `/project/${modpack.spec.project_id}` : null,
}
}
function getLoaderLabel(loader: string | null, loaderVersion: string | null): string | null {
if (!loader) return null
const normalizedLoader = loader.toLowerCase()
return [formatLoaderLabel(normalizedLoader), loaderVersion].filter(Boolean).join(' ')
}
function getLatestKnownActivity(world: Archon.Servers.v1.WorldFull): string | null {
const latestBackup = latestDate(world.backups.map((backup) => backup.created_at))
if (latestBackup) return latestBackup
if (world.is_active && isServerRunning.value) return new Date().toISOString()
return world.created_at ?? null
}
function latestDate(dates: string[]): string | null {
let latest = 0
let latestIso: string | null = null
for (const date of dates) {
const timestamp = new Date(date).getTime()
if (!Number.isFinite(timestamp) || timestamp <= latest) continue
latest = timestamp
latestIso = date
}
return latestIso
}
function createDummyContentSummary(
world: Archon.Servers.v1.WorldFull,
index: number,
): ContentSummary {
const gameVersion = world.content?.game_version ?? server.value?.mc_version ?? '1.20.4'
const loader = world.content?.modloader ?? server.value?.loader?.toLowerCase() ?? 'fabric'
const loaderVersion = world.content?.modloader_version ?? server.value?.loader_version ?? '0.16.6'
if (index === 0) {
return {
gameVersion,
loader,
loaderVersion,
linkedModpack: {
name: 'Cobblemon Official',
iconUrl: null,
link: null,
},
installedContentCount: 47,
}
}
return {
gameVersion,
loader,
loaderVersion,
linkedModpack: null,
installedContentCount: 13,
}
}
</script>
<template>
<ServersManageInstancesPage />
</template>
+39 -14
View File
@@ -452,9 +452,21 @@ const filteredProjects = computed(() => {
const filtered = [...typeFiltered.value]
if (currentSortType.value === 'Most external deps') {
filtered.sort((a, b) => b.external_dependencies_count - a.external_dependencies_count)
filtered.sort((a, b) => {
const depsDiff = b.external_dependencies_count - a.external_dependencies_count
if (depsDiff !== 0) return depsDiff
const dateA = new Date(a.project.queued || a.project.published || 0).getTime()
const dateB = new Date(b.project.queued || b.project.published || 0).getTime()
return dateA - dateB
})
} else if (currentSortType.value === 'Least external deps') {
filtered.sort((a, b) => a.external_dependencies_count - b.external_dependencies_count)
filtered.sort((a, b) => {
const depsDiff = a.external_dependencies_count - b.external_dependencies_count
if (depsDiff !== 0) return depsDiff
const dateA = new Date(a.project.queued || a.project.published || 0).getTime()
const dateB = new Date(b.project.queued || b.project.published || 0).getTime()
return dateA - dateB
})
} else if (currentSortType.value === 'Oldest') {
filtered.sort((a, b) => {
const dateA = new Date(a.project.queued || a.project.published || 0).getTime()
@@ -503,7 +515,7 @@ function goToPage(page: number) {
currentPage.value = page
}
async function findFirstUnlockedProject(): Promise<ModerationProject | null> {
async function findFirstEligibleProject(): Promise<ModerationProject | null> {
let skippedCount = 0
while (moderationQueue.hasItems) {
@@ -513,24 +525,30 @@ async function findFirstUnlockedProject(): Promise<ModerationProject | null> {
const project = filteredProjects.value.find((p) => p.project.id === currentId)
if (!project) {
await moderationQueue.completeCurrentProject(currentId, 'skipped')
skippedCount++
continue
}
if (project.project.status !== 'processing') {
await moderationQueue.completeCurrentProject(currentId, 'skipped')
skippedCount++
continue
}
try {
const lockStatus = await moderationQueue.checkLock(currentId)
if (!lockStatus.locked || lockStatus.expired) {
if (!lockStatus.locked || lockStatus.expired || lockStatus.is_own_lock) {
if (skippedCount > 0) {
addNotification({
title: 'Skipped locked projects',
text: `Skipped ${skippedCount} project(s) being moderated by others.`,
title: 'Skipped projects',
text: `Skipped ${skippedCount} project(s) already moderated or locked by others.`,
type: 'info',
})
}
return project
}
// Project is locked, skip it
await moderationQueue.completeCurrentProject(currentId, 'skipped')
skippedCount++
} catch {
@@ -538,6 +556,14 @@ async function findFirstUnlockedProject(): Promise<ModerationProject | null> {
}
}
if (skippedCount > 0) {
addNotification({
title: 'Skipped projects',
text: `Skipped ${skippedCount} project(s) already moderated or locked by others.`,
type: 'info',
})
}
return null
}
@@ -549,12 +575,12 @@ async function moderateAllInFilter() {
await moderationQueue.setQueue(projectIds)
// Find first unlocked project
const targetProject = await findFirstUnlockedProject()
const targetProject = await findFirstEligibleProject()
if (!targetProject) {
addNotification({
title: 'All projects locked',
text: 'All projects in queue are currently being moderated by others.',
title: 'No projects available',
text: 'All projects in queue are already moderated or locked by others.',
type: 'warning',
})
return
@@ -585,13 +611,12 @@ async function startFromProject(projectId: string) {
await moderationQueue.setQueue(projectIds)
}
// Find first unlocked project
const targetProject = await findFirstUnlockedProject()
const targetProject = await findFirstEligibleProject()
if (!targetProject) {
addNotification({
title: 'All projects locked',
text: 'All projects in queue are currently being moderated by others.',
title: 'No projects available',
text: 'All projects in queue are already moderated or locked by others.',
type: 'warning',
})
return
@@ -62,86 +62,14 @@
</template>
<template v-else>
<div class="normal-page__header py-4">
<ContentPageHeader>
<template #icon>
<Avatar :src="organization.icon_url" :alt="organization.name" size="96px" />
</template>
<template #title>
{{ organization.name }}
</template>
<template #title-suffix>
<div class="ml-1 flex items-center gap-2 font-semibold">
<OrganizationIcon />
Organization
</div>
</template>
<template #summary>
{{ organization.description }}
</template>
<template #stats>
<div
class="flex items-center gap-2 border-0 border-r border-solid border-divider pr-4 font-semibold"
>
<UsersIcon class="h-6 w-6 text-secondary" />
{{ formatCompactNumber(acceptedMembers?.length || 0) }}
members
</div>
<div
class="flex items-center gap-2 border-0 border-r border-solid border-divider pr-4 font-semibold"
>
<BoxIcon class="h-6 w-6 text-secondary" />
{{ formatCompactNumber(projects?.length || 0) }}
projects
</div>
<div
v-tooltip="formatNumber(sumDownloads)"
class="flex items-center gap-2 font-semibold"
>
<DownloadIcon class="h-6 w-6 text-secondary" />
{{ formatCompactNumber(sumDownloads) }}
downloads
</div>
</template>
<template #actions>
<ButtonStyled v-if="auth.user && currentMember" size="large">
<NuxtLink :to="`/organization/${organization.slug}/settings`">
<SettingsIcon aria-hidden="true" />
Manage
</NuxtLink>
</ButtonStyled>
<ButtonStyled size="large" circular type="transparent">
<OverflowMenu
:options="[
{
id: 'manage-projects',
action: () =>
router.push('/organization/' + organization?.slug + '/settings/projects'),
hoverFilledOnly: true,
shown: !!(auth.user && currentMember),
},
{ divider: true, shown: !!(auth?.user && currentMember) },
{ id: 'copy-id', action: () => copyId() },
{ id: 'copy-permalink', action: () => copyPermalink() },
]"
aria-label="More options"
>
<MoreVerticalIcon aria-hidden="true" />
<template #manage-projects>
<BoxIcon aria-hidden="true" />
Manage projects
</template>
<template #copy-id>
<ClipboardCopyIcon aria-hidden="true" />
{{ formatMessage(commonMessages.copyIdButton) }}
</template>
<template #copy-permalink>
<ClipboardCopyIcon aria-hidden="true" />
{{ formatMessage(commonMessages.copyPermalinkButton) }}
</template>
</OverflowMenu>
</ButtonStyled>
</template>
</ContentPageHeader>
<PageHeader
:header="organization.name"
:summary="organization.description"
:leading="organizationHeaderLeading"
:badges="organizationHeaderBadges"
:metadata="organizationHeaderMetadata"
:actions="organizationHeaderActions"
/>
</div>
<div class="normal-page__sidebar">
<AdPlaceholder v-if="!auth.user" />
@@ -303,10 +231,9 @@ import {
Avatar,
ButtonStyled,
commonMessages,
ContentPageHeader,
injectModrinthClient,
NavTabs,
OverflowMenu,
PageHeader,
PROJECT_DEP_MARKER_QUERY,
ProjectCard,
ProjectCardList,
@@ -535,6 +462,93 @@ provideOrganizationContext(organizationContext)
const canAccessSettings = computed(() => !!currentMember.value?.accepted)
const organizationHeaderLeading = computed(() => ({
type: 'avatar' as const,
src: organization.value?.icon_url,
alt: organization.value?.name,
avatarSize: '96px',
}))
const organizationHeaderBadges = computed(() => [
{
id: 'organization',
label: 'Organization',
icon: OrganizationIcon,
class: 'px-0 text-primary',
},
])
const organizationHeaderMetadata = computed(() => [
{
id: 'members',
label: `${formatCompactNumber(acceptedMembers.value?.length || 0)} members`,
icon: UsersIcon,
},
{
id: 'projects',
label: `${formatCompactNumber(projects.value?.length || 0)} projects`,
icon: BoxIcon,
},
{
id: 'downloads',
label: `${formatCompactNumber(sumDownloads.value)} downloads`,
icon: DownloadIcon,
tooltip: formatNumber(sumDownloads.value),
},
])
const organizationHeaderActions = computed(() => [
...(auth.value.user && currentMember.value
? [
{
id: 'manage',
label: 'Manage',
icon: SettingsIcon,
to: `/organization/${organization.value?.slug}/settings`,
},
]
: []),
{
id: 'more',
label: 'More options',
icon: MoreVerticalIcon,
labelHidden: true,
type: 'transparent' as const,
tooltip: 'More options',
menuActions: [
{
id: 'manage-projects',
label: 'Manage projects',
icon: BoxIcon,
action: () => {
void router.push(`/organization/${organization.value?.slug}/settings/projects`)
},
shown: !!(auth.value.user && currentMember.value),
},
{
divider: true,
shown: !!(auth.value.user && currentMember.value),
},
{
id: 'copy-id',
label: formatMessage(commonMessages.copyIdButton),
icon: ClipboardCopyIcon,
action: () => {
void copyId()
},
},
{
id: 'copy-permalink',
label: formatMessage(commonMessages.copyPermalinkButton),
icon: ClipboardCopyIcon,
action: () => {
void copyPermalink()
},
},
],
},
])
watch(
[routeHasSettings, acceptedMembers, currentMember],
() => {
+162 -163
View File
@@ -120,164 +120,14 @@
</NewModal>
<div class="new-page sidebar" :class="{ 'alt-layout': cosmetics.leftContentLayout }">
<div class="normal-page__header py-4">
<ContentPageHeader>
<template #icon>
<Avatar :src="user.avatar_url" :alt="user.username" size="96px" circle />
</template>
<template #title>
<span class="flex items-center gap-2">
{{ user.username }}
<TagItem
v-if="isAdminViewing && isAffiliate"
:style="{
'--_color': 'var(--color-brand)',
'--_bg-color': 'var(--color-brand-highlight)',
}"
>
<AffiliateIcon /> Affiliate
</TagItem>
</span>
</template>
<template #summary>
{{
user.bio
? user.bio
: projects.length === 0
? formatMessage(messages.bioFallbackUser)
: formatMessage(messages.bioFallbackCreator)
}}
</template>
<template #stats>
<div
class="flex items-center gap-2 border-0 border-r border-solid border-divider pr-4 font-semibold"
>
<BoxIcon class="h-6 w-6 text-secondary" />
{{
formatMessage(messages.profileProjectsLabel, {
count: formatCompactNumber(projects?.length || 0),
countPlural: formatCompactNumberPlural(projects?.length || 0),
})
}}
</div>
<div
v-tooltip="formatNumber(sumDownloads)"
class="flex items-center gap-2 border-0 border-r border-solid border-divider pr-4 font-semibold"
>
<DownloadIcon class="h-6 w-6 text-secondary" />
{{
formatMessage(messages.profileDownloadsLabel, {
count: formatCompactNumber(sumDownloads),
countPlural: formatCompactNumberPlural(sumDownloads),
})
}}
</div>
<div
v-tooltip="formatDateTime(user.created)"
class="flex items-center gap-2 font-semibold"
>
<CalendarIcon class="h-6 w-6 text-secondary" />
{{ formatMessage(messages.profileJoinedLabel) }}
{{ formatRelativeTime(user.created) }}
</div>
</template>
<template #actions>
<ButtonStyled size="large">
<NuxtLink v-if="auth.user && auth.user.id === user.id" to="/settings/profile">
<EditIcon aria-hidden="true" />
{{ formatMessage(commonMessages.editButton) }}
</NuxtLink>
</ButtonStyled>
<ButtonStyled size="large" circular type="transparent">
<OverflowMenu
:options="[
{
id: 'manage-projects',
action: () => navigateTo('/dashboard/projects'),
hoverOnly: true,
shown: auth.user && auth.user.id === user.id,
},
{ divider: true, shown: auth.user && auth.user.id === user.id },
{
id: 'report',
action: () =>
auth.user ? reportUser(user.id) : navigateTo(getSignInRouteObj(route)),
color: 'red',
hoverOnly: true,
shown: auth.user?.id !== user.id,
},
{ id: 'copy-id', action: () => copyId() },
{ id: 'copy-permalink', action: () => copyPermalink() },
{
divider: true,
shown: auth.user && isAdmin(auth.user),
},
{
id: 'open-billing',
action: () => navigateTo(`/admin/billing/${user.id}`),
shown: auth.user && isStaff(auth.user),
},
{
id: 'toggle-affiliate',
action: () => toggleAffiliate(user.id),
shown: isAdminViewing,
remainOnClick: true,
color: isAffiliate ? 'red' : 'orange',
},
{
id: 'open-info',
action: () => $refs.userDetailsModal.show(),
shown: auth.user && isStaff(auth.user),
},
{
id: 'edit-role',
action: () => openRoleEditModal(),
shown: auth.user && isAdmin(auth.user),
},
]"
aria-label="More options"
:dropdown-id="`${baseId}-more-options`"
>
<MoreVerticalIcon aria-hidden="true" />
<template #manage-projects>
<BoxIcon aria-hidden="true" />
{{ formatMessage(messages.profileManageProjectsButton) }}
</template>
<template #report>
<ReportIcon aria-hidden="true" />
{{ formatMessage(commonMessages.reportButton) }}
</template>
<template #copy-id>
<ClipboardCopyIcon aria-hidden="true" />
{{ formatMessage(commonMessages.copyIdButton) }}
</template>
<template #copy-permalink>
<ClipboardCopyIcon aria-hidden="true" />
{{ formatMessage(commonMessages.copyPermalinkButton) }}
</template>
<template #open-billing>
<CurrencyIcon aria-hidden="true" />
{{ formatMessage(messages.billingButton) }}
</template>
<template #open-info>
<InfoIcon aria-hidden="true" />
{{ formatMessage(messages.infoButton) }}
</template>
<template #toggle-affiliate>
<AffiliateIcon aria-hidden="true" />
{{
formatMessage(
isAffiliate ? messages.removeAffiliateButton : messages.setAffiliateButton,
)
}}
</template>
<template #edit-role>
<EditIcon aria-hidden="true" />
{{ formatMessage(messages.editRoleButton) }}
</template>
</OverflowMenu>
</ButtonStyled>
</template>
</ContentPageHeader>
<PageHeader
:header="user.username"
:summary="profileHeaderSummary"
:leading="profileHeaderLeading"
:badges="profileHeaderBadges"
:metadata="profileHeaderMetadata"
:actions="profileHeaderActions"
/>
</div>
<div class="normal-page__content">
<div v-if="navLinks.length > 2" class="mb-4 max-w-full overflow-x-auto">
@@ -489,17 +339,15 @@ import {
ButtonStyled,
Combobox,
commonMessages,
ContentPageHeader,
defineMessages,
injectModrinthClient,
injectNotificationManager,
IntlFormatted,
NavTabs,
NewModal,
OverflowMenu,
PageHeader,
ProjectCard,
ProjectCardList,
TagItem,
useCompactNumber,
useFormatDateTime,
useFormatNumber,
@@ -543,8 +391,6 @@ const formatDateTime = useFormatDateTime({
const { addNotification } = injectNotificationManager()
const baseId = useId()
const messages = defineMessages({
profileProjectsLabel: {
id: 'profile.label.projects',
@@ -864,12 +710,165 @@ async function copyPermalink() {
const isAffiliate = computed(() => user.value?.badges & UserBadge.AFFILIATE)
const isAdminViewing = computed(() => isAdmin(auth.value.user))
const userDetailsModal = useTemplateRef('userDetailsModal')
async function toggleAffiliate(id) {
await client.labrinth.users_v2.patch(id, { badges: user.value.badges ^ (1 << 7) })
queryClient.invalidateQueries({ queryKey: ['user', userId] })
}
const profileHeaderSummary = computed(() =>
user.value?.bio
? user.value.bio
: (projects.value?.length ?? 0) === 0
? formatMessage(messages.bioFallbackUser)
: formatMessage(messages.bioFallbackCreator),
)
const profileHeaderLeading = computed(() => ({
type: 'avatar',
src: user.value?.avatar_url,
alt: user.value?.username,
avatarSize: '96px',
circle: true,
}))
const profileHeaderBadges = computed(() =>
isAdminViewing.value && isAffiliate.value
? [
{
id: 'affiliate',
label: 'Affiliate',
icon: AffiliateIcon,
class: 'border-brand-highlight bg-brand-highlight text-brand',
},
]
: [],
)
const profileHeaderMetadata = computed(() => [
{
id: 'projects',
label: formatMessage(messages.profileProjectsLabel, {
count: formatCompactNumber(projects.value?.length || 0),
countPlural: formatCompactNumberPlural(projects.value?.length || 0),
}),
icon: BoxIcon,
},
{
id: 'downloads',
label: formatMessage(messages.profileDownloadsLabel, {
count: formatCompactNumber(sumDownloads.value),
countPlural: formatCompactNumberPlural(sumDownloads.value),
}),
icon: DownloadIcon,
tooltip: formatNumber(sumDownloads.value),
},
{
id: 'joined',
label: `${formatMessage(messages.profileJoinedLabel)} ${formatRelativeTime(user.value.created)}`,
icon: CalendarIcon,
tooltip: formatDateTime(user.value.created),
},
])
const profileHeaderActions = computed(() => {
if (!user.value) return []
const viewer = auth.value.user
const isSelf = viewer?.id === user.value.id
return [
...(isSelf
? [
{
id: 'edit-profile',
label: formatMessage(commonMessages.editButton),
icon: EditIcon,
to: '/settings/profile',
},
]
: []),
{
id: 'more',
label: 'More options',
icon: MoreVerticalIcon,
labelHidden: true,
type: 'transparent',
tooltip: 'More options',
menuActions: [
{
id: 'manage-projects',
label: formatMessage(messages.profileManageProjectsButton),
icon: BoxIcon,
action: () => navigateTo('/dashboard/projects'),
shown: isSelf,
},
{
divider: true,
shown: isSelf,
},
{
id: 'report',
label: formatMessage(commonMessages.reportButton),
icon: ReportIcon,
action: () => (viewer ? reportUser(user.value.id) : navigateTo(getSignInRouteObj(route))),
color: 'red',
shown: viewer?.id !== user.value.id,
},
{
id: 'copy-id',
label: formatMessage(commonMessages.copyIdButton),
icon: ClipboardCopyIcon,
action: () => copyId(),
},
{
id: 'copy-permalink',
label: formatMessage(commonMessages.copyPermalinkButton),
icon: ClipboardCopyIcon,
action: () => copyPermalink(),
},
{
divider: true,
shown: viewer && isAdmin(viewer),
},
{
id: 'open-billing',
label: formatMessage(messages.billingButton),
icon: CurrencyIcon,
action: () => navigateTo(`/admin/billing/${user.value.id}`),
shown: viewer && isStaff(viewer),
},
{
id: 'toggle-affiliate',
label: formatMessage(
isAffiliate.value ? messages.removeAffiliateButton : messages.setAffiliateButton,
),
icon: AffiliateIcon,
action: () => toggleAffiliate(user.value.id),
shown: isAdminViewing.value,
remainOnClick: true,
color: isAffiliate.value ? 'red' : 'orange',
},
{
id: 'open-info',
label: formatMessage(messages.infoButton),
icon: InfoIcon,
action: () => userDetailsModal.value?.show(),
shown: viewer && isStaff(viewer),
},
{
id: 'edit-role',
label: formatMessage(messages.editRoleButton),
icon: EditIcon,
action: () => openRoleEditModal(),
shown: viewer && isAdmin(viewer),
},
],
},
]
})
const navLinks = computed(() => [
{
label: formatMessage(commonMessages.allProjectType),
@@ -0,0 +1,36 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n t.mod_id AS \"project_id!\",\n tm.created,\n tm.body AS \"body: sqlx::types::Json<MessageBody>\"\n FROM threads_messages tm\n INNER JOIN threads t ON t.id = tm.thread_id\n WHERE\n t.mod_id = ANY($1)\n AND tm.body->>'type' = 'status_change'\n AND tm.created BETWEEN $2 AND $3\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "project_id!",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "created",
"type_info": "Timestamptz"
},
{
"ordinal": 2,
"name": "body: sqlx::types::Json<MessageBody>",
"type_info": "Jsonb"
}
],
"parameters": {
"Left": [
"Int8Array",
"Timestamptz",
"Timestamptz"
]
},
"nullable": [
true,
false,
false
]
},
"hash": "a5141c0435441f062231c842cb5db5e0c78f8f3896c1e9f2b2b56cce41fa1591"
}
+238 -43
View File
@@ -9,7 +9,7 @@
mod old;
use std::{num::NonZeroU64, sync::LazyLock};
use std::{collections::HashMap, num::NonZeroU64, sync::LazyLock};
use crate::database::PgPool;
use actix_web::{HttpRequest, post, web};
@@ -21,19 +21,24 @@ use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
use crate::{
auth::{AuthenticationError, get_user_from_headers},
auth::{
AuthenticationError, checks::filter_visible_version_ids,
get_user_from_headers,
},
database::{
self, DBProject,
models::{
DBAffiliateCode, DBAffiliateCodeId, DBProjectId, DBUser, DBUserId,
DBVersionId,
DBVersion, DBVersionId,
},
redis::RedisPool,
},
models::{
ids::{AffiliateCodeId, ProjectId, VersionId},
pats::Scopes,
projects::ProjectStatus,
teams::ProjectPermissions,
threads::MessageBody,
v3::analytics::DownloadReason,
},
queue::session::AuthQueue,
@@ -255,17 +260,46 @@ pub const MAX_TIME_SLICES: usize = 1024;
/// Response for a [`GetRequest`].
#[derive(Debug, Default, Serialize, Deserialize, utoipa::ToSchema)]
pub struct FetchResponse {
pub struct GetResponse {
/// List of N [`TimeSlice`]s, where each slice represents an equal
/// time interval of metrics collection. The number of slices is determined
/// by [`GetRequest::time_range`].
pub metrics: Vec<TimeSlice>,
/// List of events associated with projects that were requested.
pub project_events: Vec<ProjectAnalyticsEvent>,
}
/// Single time interval of metrics collection.
#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)]
pub struct TimeSlice(pub Vec<AnalyticsData>);
/// Notable update to a project which may reflect in analytics metrics.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct ProjectAnalyticsEvent {
/// ID of the event's project.
pub project_id: ProjectId,
/// When the event occurred.
pub timestamp: DateTime<Utc>,
#[serde(flatten)]
pub kind: ProjectAnalyticsEventKind,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ProjectAnalyticsEventKind {
/// New version of this project was uploaded.
VersionUploaded {
version_id: VersionId,
version_name: String,
version_number: String,
},
/// Project changed status.
StatusChanged {
status_from: ProjectStatus,
status_to: ProjectStatus,
},
}
/// Metrics collected in a single [`TimeSlice`].
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(untagged)] // the presence of `source_project`, `source_affiliate_code` determines the kind
@@ -351,7 +385,7 @@ pub struct ProjectDownloads {
downloads: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, utoipa::ToSchema)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, utoipa::ToSchema)]
pub enum DownloadSource {
Website,
ModrinthApp,
@@ -665,7 +699,7 @@ mod query {
/// Fetches analytics data for the authorized user's projects.
#[utoipa::path(
responses((status = OK, body = inline(FetchResponse))),
responses((status = OK, body = inline(GetResponse))),
)]
#[post("")]
pub async fn fetch_analytics(
@@ -675,7 +709,7 @@ pub async fn fetch_analytics(
redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>,
clickhouse: web::Data<clickhouse::Client>,
) -> Result<web::Json<FetchResponse>, ApiError> {
) -> Result<web::Json<GetResponse>, ApiError> {
let (scopes, user) = get_user_from_headers(
&http_req,
&**pool,
@@ -768,6 +802,44 @@ pub async fn fetch_analytics(
.iter()
.map(|version| DBProjectId(version.mod_id))
.collect::<Vec<_>>();
let parent_version_data =
DBVersion::get_many(&parent_version_ids, &**pool, &redis).await?;
let visible_version_ids = filter_visible_version_ids(
parent_version_data
.iter()
.map(|version| &version.inner)
.collect(),
&Some(user.clone()),
&pool,
&redis,
)
.await?;
let mut project_events = parent_version_data
.iter()
.filter(|version| {
visible_version_ids.contains(&version.inner.id)
&& version.inner.date_published >= req.time_range.start
&& version.inner.date_published <= req.time_range.end
})
.map(|version| ProjectAnalyticsEvent {
project_id: version.inner.project_id.into(),
timestamp: version.inner.date_published,
kind: ProjectAnalyticsEventKind::VersionUploaded {
version_id: version.inner.id.into(),
version_name: version.inner.name.clone(),
version_number: version.inner.version_number.clone(),
},
})
.collect::<Vec<_>>();
project_events.extend(
fetch_project_status_change_events(
&project_ids,
&req.time_range,
&pool,
)
.await?,
);
project_events.sort_by_key(|event| event.timestamp);
let affiliate_code_ids =
DBAffiliateCode::get_by_affiliate(user.id.into(), &**pool)
@@ -830,9 +902,8 @@ pub async fn fetch_analytics(
use ProjectDownloadsField as F;
let uses = |field| metrics.bucket_by.contains(&field);
query_clickhouse::<query::DownloadRow>(
query_clickhouse_downloads(
&mut query_clickhouse_cx,
query::DOWNLOADS,
&[
("use_project_id", uses(F::ProjectId)),
("use_domain", uses(F::Domain)),
@@ -844,37 +915,6 @@ pub async fn fetch_analytics(
("use_game_version", uses(F::GameVersion)),
("use_loader", uses(F::Loader)),
],
|row| row.bucket,
|row| {
let country = if uses(F::Country) {
Some(condense_country(row.country, row.downloads))
} else {
None
};
AnalyticsData::Project(ProjectAnalytics {
source_project: row.project_id.into(),
metrics: ProjectMetrics::Downloads(ProjectDownloads {
domain: none_if_empty(row.domain),
user_agent: if uses(F::UserAgent) {
normalize_download_source(&row.user_agent)
} else {
None
},
version_id: none_if_zero_version_id(row.version_id),
monetized: match row.monetized {
0 => Some(false),
1 => Some(true),
_ => None,
},
country,
reason: none_if_empty(row.reason)
.and_then(|s| s.parse().ok()),
game_version: none_if_empty(row.game_version),
loader: none_if_empty(row.loader),
downloads: row.downloads,
}),
})
},
)
.await?;
}
@@ -1103,8 +1143,9 @@ pub async fn fetch_analytics(
}
}
Ok(web::Json(FetchResponse {
Ok(web::Json(GetResponse {
metrics: time_slices,
project_events,
}))
}
@@ -1195,6 +1236,57 @@ fn condense_country(country: String, count: u64) -> String {
}
}
async fn fetch_project_status_change_events(
project_ids: &[DBProjectId],
time_range: &TimeRange,
pool: &PgPool,
) -> Result<Vec<ProjectAnalyticsEvent>, ApiError> {
let project_id_values =
project_ids.iter().map(|id| id.0).collect::<Vec<_>>();
let rows = sqlx::query!(
r#"
SELECT
t.mod_id AS "project_id!",
tm.created,
tm.body AS "body: sqlx::types::Json<MessageBody>"
FROM threads_messages tm
INNER JOIN threads t ON t.id = tm.thread_id
WHERE
t.mod_id = ANY($1)
AND tm.body->>'type' = 'status_change'
AND tm.created BETWEEN $2 AND $3
"#,
&project_id_values,
time_range.start,
time_range.end,
)
.fetch_all(&**pool)
.await?;
Ok(rows
.into_iter()
.filter_map(|row| {
let MessageBody::StatusChange {
old_status,
new_status,
} = row.body.0
else {
return None;
};
Some(ProjectAnalyticsEvent {
project_id: DBProjectId(row.project_id).into(),
timestamp: row.created,
kind: ProjectAnalyticsEventKind::StatusChanged {
status_from: old_status,
status_to: new_status,
},
})
})
.collect())
}
struct QueryClickhouseContext<'a> {
clickhouse: &'a clickhouse::Client,
req: &'a GetRequest,
@@ -1205,6 +1297,107 @@ struct QueryClickhouseContext<'a> {
affiliate_code_ids: &'a [DBAffiliateCodeId],
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct DownloadBucket {
bucket: u64,
project_id: DBProjectId,
domain: Option<String>,
user_agent: Option<DownloadSource>,
version_id: Option<DBVersionId>,
monetized: Option<bool>,
country: Option<String>,
reason: Option<DownloadReason>,
game_version: Option<String>,
loader: Option<String>,
}
async fn query_clickhouse_downloads(
cx: &mut QueryClickhouseContext<'_>,
use_columns: &[(&str, bool)],
) -> Result<(), ApiError> {
let mut query = cx
.clickhouse
.query(query::DOWNLOADS)
.param("time_range_start", cx.req.time_range.start.timestamp())
.param("time_range_end", cx.req.time_range.end.timestamp())
.param("time_slices", cx.time_slices.len())
.param("project_ids", cx.project_ids)
.param("parent_version_ids", cx.parent_version_ids)
.param("parent_version_project_ids", cx.parent_version_project_ids)
.param("affiliate_code_ids", cx.affiliate_code_ids);
for (param_name, used) in use_columns {
query = query.param(param_name, used)
}
let uses = |name| {
use_columns
.iter()
.any(|(column_name, used)| *column_name == name && *used)
};
let mut cursor = query.fetch::<query::DownloadRow>()?;
let mut buckets = HashMap::<DownloadBucket, u64>::new();
while let Some(row) = cursor.next().await? {
let key = DownloadBucket {
bucket: row.bucket,
project_id: row.project_id,
domain: uses("use_domain").then(|| row.domain.clone()),
user_agent: uses("use_user_agent")
.then(|| normalize_download_source(&row.user_agent))
.flatten(),
version_id: uses("use_version_id").then_some(row.version_id),
monetized: if uses("use_monetized") {
match row.monetized {
0 => Some(false),
1 => Some(true),
_ => None,
}
} else {
None
},
country: uses("use_country").then(|| row.country.clone()),
reason: if uses("use_reason") {
none_if_empty(row.reason.clone()).and_then(|s| s.parse().ok())
} else {
None
},
game_version: uses("use_game_version")
.then(|| row.game_version.clone()),
loader: uses("use_loader").then(|| row.loader.clone()),
};
*buckets.entry(key).or_default() += row.downloads;
}
for (key, downloads) in buckets {
let bucket = key.bucket as usize;
add_to_time_slice(
cx.time_slices,
bucket,
AnalyticsData::Project(ProjectAnalytics {
source_project: key.project_id.into(),
metrics: ProjectMetrics::Downloads(ProjectDownloads {
domain: key.domain.and_then(none_if_empty),
user_agent: key.user_agent,
version_id: key
.version_id
.and_then(none_if_zero_version_id),
monetized: key.monetized,
country: key
.country
.map(|country| condense_country(country, downloads)),
reason: key.reason,
game_version: key.game_version.and_then(none_if_empty),
loader: key.loader.and_then(none_if_empty),
downloads,
}),
}),
)?;
}
Ok(())
}
async fn query_clickhouse<Row>(
cx: &mut QueryClickhouseContext<'_>,
query: &str,
@@ -1395,7 +1588,7 @@ mod tests {
let test_project_2 = ProjectId(456);
let test_project_3 = ProjectId(789);
let src = FetchResponse {
let src = GetResponse {
metrics: vec![
TimeSlice(vec![
AnalyticsData::Project(ProjectAnalytics {
@@ -1422,6 +1615,7 @@ mod tests {
}),
})]),
],
project_events: vec![],
};
let target = json!({
"metrics": [
@@ -1446,7 +1640,8 @@ mod tests {
"revenue": "200.00",
}
]
]
],
"project_events": []
});
assert_eq!(serde_json::to_value(src).unwrap(), target);
@@ -103,7 +103,7 @@ export class ArchonServersV0Module extends AbstractModule {
*/
public async power(
serverId: string,
action: 'Start' | 'Stop' | 'Restart' | 'Kill',
action: Archon.Servers.v0.PowerAction,
): Promise<void> {
await this.client.request(`/servers/${serverId}/power`, {
api: 'archon',
@@ -336,6 +336,8 @@ export namespace Archon {
token: string // JWT token for filesystem access
}
export type PowerAction = 'Start' | 'Stop' | 'Restart' | 'Kill'
export type ReinstallLoaderRequest = {
loader: string
loader_version?: string
@@ -1,45 +0,0 @@
<template>
<div class="flex flex-col gap-2 border-0 border-b border-solid border-divider pb-4">
<div class="flex flex-wrap items-start gap-4 max-md:flex-col">
<div class="flex min-w-0 flex-1 gap-4">
<slot name="icon" />
<div class="flex min-w-0 flex-col gap-2 justify-center">
<div class="flex flex-col gap-1.5 justify-center">
<div class="flex flex-wrap items-center gap-2">
<h1 class="m-0 text-2xl font-semibold leading-none text-contrast">
<slot name="title" />
</h1>
<slot name="title-suffix" />
</div>
<p
v-if="$slots.summary"
class="m-0 max-w-[44rem] empty:hidden"
:class="[disableLineClamp ? '' : 'line-clamp-2']"
>
<slot name="summary" />
</p>
</div>
<div v-if="$slots.stats" class="flex flex-wrap gap-3 empty:hidden max-md:hidden">
<slot name="stats" />
</div>
</div>
</div>
<div class="flex flex-wrap gap-2 items-center">
<slot name="actions" />
</div>
</div>
<div v-if="$slots.stats" class="flex justify-between md:hidden">
<div class="flex flex-wrap gap-3 empty:hidden">
<slot name="stats" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
interface Props {
disableLineClamp?: boolean
}
const { disableLineClamp } = defineProps<Props>()
</script>
@@ -31,7 +31,8 @@ import { DropdownIcon } from '@modrinth/assets'
import type { Component } from 'vue'
import { computed } from 'vue'
import { ButtonStyled, OverflowMenu } from '../index'
import ButtonStyled from './ButtonStyled.vue'
import OverflowMenu from './OverflowMenu.vue'
// TODO: This should be moved to a shared types file.
type Colors = 'standard' | 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple'
+154 -31
View File
@@ -6,40 +6,138 @@
:class="{ 'drop-shadow-xl': mode === 'navigation' }"
>
<template v-if="mode === 'navigation'">
<RouterLink
v-for="(link, index) in filteredLinks"
v-show="link.shown ?? true"
:key="link.href"
ref="tabLinkElements"
:replace="replace"
:to="query ? (link.href ? `?${query}=${link.href}` : '?') : link.href"
class="button-animation z-[1] flex flex-row items-center gap-2 px-4 py-2 focus:rounded-full"
:class="getSSRFallbackClasses(index)"
@mouseenter="link.onHover?.()"
@focus="link.onHover?.()"
>
<component :is="link.icon" v-if="link.icon" class="size-5" :class="getIconClasses(index)" />
<span class="text-nowrap" :class="getLabelClasses(index)">
{{ link.label }}
</span>
</RouterLink>
<template v-for="(link, index) in filteredLinks" :key="link.href">
<Tooltip
v-if="link.prompt"
theme="dismissable-prompt"
:triggers="[]"
:shown="link.prompt.shown"
:auto-hide="false"
:placement="link.prompt.placement ?? 'bottom'"
>
<RouterLink
ref="tabLinkElements"
:replace="replace"
:to="query ? (link.href ? `?${query}=${link.href}` : '?') : link.href"
class="button-animation z-[1] flex flex-row items-center gap-2 px-4 py-2 focus:rounded-full"
:class="getSSRFallbackClasses(index)"
@mouseenter="link.onHover?.()"
@focus="link.onHover?.()"
@click="dismissPrompt(link)"
>
<component
:is="link.icon"
v-if="link.icon"
class="size-5"
:class="getIconClasses(index)"
/>
<span class="text-nowrap" :class="getLabelClasses(index)">
{{ link.label }}
</span>
</RouterLink>
<template #popper>
<div class="grid grid-cols-[min-content] gap-1">
<div class="flex min-w-48 items-center justify-between gap-8">
<h3 class="m-0 whitespace-nowrap text-base font-bold text-contrast">
{{ link.prompt.title }}
</h3>
<ButtonStyled size="small" circular>
<button v-tooltip="link.prompt.dismissLabel" @click="link.prompt.onDismiss?.()">
<XIcon aria-hidden="true" />
</button>
</ButtonStyled>
</div>
<p class="m-0 text-wrap text-sm font-medium leading-tight text-secondary">
{{ link.prompt.description }}
</p>
</div>
</template>
</Tooltip>
<RouterLink
v-else
ref="tabLinkElements"
:replace="replace"
:to="query ? (link.href ? `?${query}=${link.href}` : '?') : link.href"
class="button-animation z-[1] flex flex-row items-center gap-2 px-4 py-2 focus:rounded-full"
:class="getSSRFallbackClasses(index)"
@mouseenter="link.onHover?.()"
@focus="link.onHover?.()"
>
<component
:is="link.icon"
v-if="link.icon"
class="size-5"
:class="getIconClasses(index)"
/>
<span class="text-nowrap" :class="getLabelClasses(index)">
{{ link.label }}
</span>
</RouterLink>
</template>
</template>
<template v-else>
<div
v-for="(link, index) in filteredLinks"
v-show="link.shown ?? true"
:key="link.href"
ref="tabLinkElements"
class="button-animation z-[1] flex flex-row items-center gap-2 px-4 py-2 hover:cursor-pointer focus:rounded-full"
:class="getSSRFallbackClasses(index)"
@click="emit('tabClick', index, link)"
>
<component :is="link.icon" v-if="link.icon" class="size-5" :class="getIconClasses(index)" />
<span class="text-nowrap" :class="getLabelClasses(index)">
{{ link.label }}
</span>
</div>
<template v-for="(link, index) in filteredLinks" :key="link.href">
<Tooltip
v-if="link.prompt"
theme="dismissable-prompt"
:triggers="[]"
:shown="link.prompt.shown"
:auto-hide="false"
:placement="link.prompt.placement ?? 'bottom'"
>
<div
ref="tabLinkElements"
class="button-animation z-[1] flex flex-row items-center gap-2 px-4 py-2 hover:cursor-pointer focus:rounded-full"
:class="getSSRFallbackClasses(index)"
@click="handleLocalTabClick(index, link)"
>
<component
:is="link.icon"
v-if="link.icon"
class="size-5"
:class="getIconClasses(index)"
/>
<span class="text-nowrap" :class="getLabelClasses(index)">
{{ link.label }}
</span>
</div>
<template #popper>
<div class="grid grid-cols-[min-content] gap-1">
<div class="flex min-w-48 items-center justify-between gap-8">
<h3 class="m-0 whitespace-nowrap text-base font-bold text-contrast">
{{ link.prompt.title }}
</h3>
<ButtonStyled size="small" circular>
<button v-tooltip="link.prompt.dismissLabel" @click="link.prompt.onDismiss?.()">
<XIcon aria-hidden="true" />
</button>
</ButtonStyled>
</div>
<p class="m-0 text-wrap text-sm font-medium leading-tight text-secondary">
{{ link.prompt.description }}
</p>
</div>
</template>
</Tooltip>
<div
v-else
ref="tabLinkElements"
class="button-animation z-[1] flex flex-row items-center gap-2 px-4 py-2 hover:cursor-pointer focus:rounded-full"
:class="getSSRFallbackClasses(index)"
@click="handleLocalTabClick(index, link)"
>
<component
:is="link.icon"
v-if="link.icon"
class="size-5"
:class="getIconClasses(index)"
/>
<span class="text-nowrap" :class="getLabelClasses(index)">
{{ link.label }}
</span>
</div>
</template>
</template>
<!-- Animated slider background -->
@@ -57,12 +155,25 @@
</template>
<script setup lang="ts">
import { XIcon } from '@modrinth/assets'
import { Tooltip } from 'floating-vue'
import type { Component } from 'vue'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import ButtonStyled from './ButtonStyled.vue'
const route = useRoute()
interface TabPrompt {
title: string
description: string
dismissLabel?: string
shown?: boolean
placement?: string
onDismiss?: () => void
}
interface Tab {
label: string
href: string
@@ -70,6 +181,7 @@ interface Tab {
icon?: Component
subpages?: string[]
onHover?: () => void
prompt?: TabPrompt
}
const props = withDefaults(
@@ -131,6 +243,17 @@ const isActiveAndNotSubpage = computed(
() => (index: number) => currentActiveIndex.value === index && !subpageSelected.value,
)
function dismissPrompt(link: Tab) {
if (link.prompt?.shown) {
link.prompt.onDismiss?.()
}
}
function handleLocalTabClick(index: number, link: Tab) {
dismissPrompt(link)
emit('tabClick', index, link)
}
function getSSRFallbackClasses(index: number) {
if (sliderReady.value) return {}
if (currentActiveIndex.value !== index) return {}
+675 -7
View File
@@ -1,11 +1,679 @@
<template>
<div class="grid grid-cols-[min-content_1fr_auto] gap-4">
<slot name="icon" />
<div class="flex flex-col gap-1.5">
<slot name="title" />
<slot name="summary" />
<slot name="stats" />
<div
class="flex flex-col gap-2"
:class="[
props.divider ? 'border-0 border-b border-solid border-divider' : '',
props.bottomPadding ? 'pb-4' : '',
props.headerClass,
]"
>
<div class="flex flex-wrap items-start gap-4 max-md:flex-col" :class="props.rowClass">
<div class="flex min-w-0 flex-1 gap-4" :class="props.mainClass">
<div v-if="leadingItems.length" class="contents">
<template v-for="(leadingItem, index) in leadingItems" :key="leadingItem.id ?? index">
<div
v-if="leadingItem.type === 'button'"
:class="
leadingWrapperClass(
leadingItem,
'flex size-16 shrink-0 items-center justify-center',
)
"
>
<ButtonStyled
circular
:color="leadingItem.color ?? 'standard'"
:size="leadingItem.size ?? 'large'"
:type="leadingItem.buttonType ?? 'standard'"
>
<AutoLink
v-if="leadingItem.to"
v-tooltip="leadingItem.tooltip"
:to="leadingItem.to"
:aria-label="leadingLabel(leadingItem)"
>
<component
:is="leadingItem.icon"
v-if="leadingItem.icon"
aria-hidden="true"
v-bind="leadingItem.iconProps"
/>
</AutoLink>
<button
v-else
v-tooltip="leadingItem.tooltip"
type="button"
:aria-label="leadingLabel(leadingItem)"
@click="leadingItem.onClick"
>
<component
:is="leadingItem.icon"
v-if="leadingItem.icon"
aria-hidden="true"
v-bind="leadingItem.iconProps"
/>
</button>
</ButtonStyled>
</div>
<Avatar
v-else-if="leadingItem.type === 'avatar'"
:src="leadingItem.src"
:alt="leadingItem.alt ?? ''"
:size="leadingItem.avatarSize ?? '64px'"
:tint-by="leadingItem.tintBy ?? null"
:circle="leadingItem.circle ?? false"
:no-shadow="leadingItem.noShadow ?? false"
:raised="leadingItem.raised ?? false"
:loading="leadingItem.loading ?? 'eager'"
:class="leadingItem.class"
/>
<component
:is="leadingItem.component"
v-else-if="leadingItem.component"
:class="leadingItem.class"
v-bind="leadingItem.componentProps"
/>
</template>
</div>
<div class="flex min-w-0 flex-col gap-2 justify-center">
<div class="flex flex-col gap-1.5 justify-center">
<div class="flex flex-wrap items-center gap-2">
<h1
class="m-0 min-w-0 max-w-full text-2xl font-semibold leading-none text-contrast"
:class="[props.truncateTitle ? 'truncate' : '', props.titleClass]"
>
{{ props.header }}
</h1>
<template v-for="badge in props.badges" :key="badge.id">
<component
:is="badge.component"
v-if="badge.component"
:class="badge.class"
v-bind="badge.componentProps"
/>
<AutoLink
v-else-if="badge.to"
v-tooltip="badge.tooltip"
:to="badge.to"
:aria-label="badge.ariaLabel ?? badge.label"
:class="badgeClass(badge, true)"
:style="badge.style"
>
<component
:is="badge.icon"
v-if="badge.icon"
aria-hidden="true"
v-bind="badge.iconProps"
/>
<span>{{ badge.label }}</span>
</AutoLink>
<button
v-else-if="badge.onClick"
v-tooltip="badge.tooltip"
type="button"
:aria-label="badge.ariaLabel ?? badge.label"
:class="badgeClass(badge, true)"
:style="badge.style"
@click="badge.onClick"
>
<component
:is="badge.icon"
v-if="badge.icon"
aria-hidden="true"
v-bind="badge.iconProps"
/>
<span>{{ badge.label }}</span>
</button>
<div
v-else
v-tooltip="badge.tooltip"
:aria-label="badge.ariaLabel"
:class="badgeClass(badge)"
:style="badge.style"
>
<component
:is="badge.icon"
v-if="badge.icon"
aria-hidden="true"
v-bind="badge.iconProps"
/>
<span>{{ badge.label }}</span>
</div>
</template>
</div>
<p
v-if="props.summary"
class="m-0 max-w-[44rem] empty:hidden"
:class="[props.disableLineClamp ? '' : 'line-clamp-2']"
>
{{ props.summary }}
</p>
</div>
<div v-if="props.metadata.length" class="flex flex-wrap gap-3 empty:hidden max-md:hidden">
<div class="flex min-w-0 flex-wrap items-center gap-2">
<template v-for="(item, index) in props.metadata" :key="item.id">
<BulletDivider v-if="index > 0" class="shrink-0" />
<div v-if="item.type === 'custom'" :class="item.class">
<slot :name="metadataSlotName(item)" :item="item" />
</div>
<AutoLink
v-else-if="item.to"
v-tooltip="item.tooltip"
:to="item.to"
:aria-label="item.ariaLabel ?? item.label ?? ''"
:class="metadataClass(item, true)"
>
<component
:is="item.icon"
v-if="item.icon"
class="flex size-5 shrink-0"
aria-hidden="true"
v-bind="item.iconProps"
/>
<span class="truncate">{{ item.label }}</span>
</AutoLink>
<button
v-else-if="item.onClick"
v-tooltip="item.tooltip"
type="button"
:aria-label="item.ariaLabel ?? item.label ?? ''"
:class="metadataClass(item, true)"
@click="item.onClick"
>
<component
:is="item.icon"
v-if="item.icon"
class="flex size-5 shrink-0"
aria-hidden="true"
v-bind="item.iconProps"
/>
<span class="truncate">{{ item.label }}</span>
</button>
<div
v-else
v-tooltip="item.tooltip"
:aria-label="item.ariaLabel"
:class="metadataClass(item)"
>
<component
:is="item.icon"
v-if="item.icon"
class="flex size-5 shrink-0"
aria-hidden="true"
v-bind="item.iconProps"
/>
<span class="truncate">{{ item.label }}</span>
</div>
</template>
</div>
</div>
</div>
</div>
<div v-if="props.actions.length" class="flex flex-wrap gap-2 items-center">
<template v-for="action in props.actions" :key="action.id">
<component
:is="action.component"
v-if="action.component"
:class="action.class"
v-bind="action.componentProps"
/>
<Tooltip
v-else-if="action.prompt"
theme="dismissable-prompt"
:triggers="[]"
:shown="action.prompt.shown"
:auto-hide="false"
:placement="action.prompt.placement ?? 'bottom'"
>
<JoinedButtons
v-if="action.joinedActions?.length"
:actions="action.joinedActions"
:color="joinedActionColor(action.color)"
:size="action.size ?? 'large'"
:disabled="action.disabled"
:primary-disabled="action.primaryDisabled"
:dropdown-disabled="action.dropdownDisabled"
:primary-muted="action.primaryMuted"
/>
<ButtonStyled
v-else
:color="action.color ?? 'standard'"
:size="action.size ?? 'large'"
:type="action.type ?? 'standard'"
:circular="action.circular ?? action.labelHidden ?? false"
>
<TeleportOverflowMenu
v-if="action.menuActions?.length"
:options="action.menuActions"
:tooltip="action.tooltip"
:aria-label="actionLabel(action)"
:disabled="action.disabled"
@open="dismissActionPrompt(action)"
>
<component
:is="action.icon"
v-if="action.icon"
:class="action.iconClass"
aria-hidden="true"
v-bind="action.iconProps"
/>
<span v-if="!action.labelHidden && !action.circular">{{ action.label }}</span>
</TeleportOverflowMenu>
<AutoLink
v-else-if="action.to"
v-tooltip="action.tooltip"
:to="action.to"
:aria-label="actionLabel(action)"
@click="(event) => handleActionClick(action, event)"
>
<component
:is="action.icon"
v-if="action.icon"
:class="action.iconClass"
aria-hidden="true"
v-bind="action.iconProps"
/>
<span v-if="!action.labelHidden && !action.circular">{{ action.label }}</span>
</AutoLink>
<button
v-else
v-tooltip="action.tooltip"
type="button"
:disabled="action.disabled"
:aria-label="actionLabel(action)"
@click="(event) => handleActionClick(action, event)"
>
<component
:is="action.icon"
v-if="action.icon"
:class="action.iconClass"
aria-hidden="true"
v-bind="action.iconProps"
/>
<span v-if="!action.labelHidden && !action.circular">{{ action.label }}</span>
</button>
</ButtonStyled>
<template #popper>
<div class="grid grid-cols-[min-content] gap-1">
<div class="flex min-w-48 items-center justify-between gap-8">
<h3
class="m-0 flex items-center gap-2 whitespace-nowrap text-base font-bold text-contrast"
>
{{ action.prompt.title }}
<span
v-if="action.prompt.badge"
class="inline-flex items-center rounded-full border border-solid border-brand-highlight bg-brand-highlight px-2 py-1 text-sm font-semibold leading-none text-brand"
>
{{ action.prompt.badge }}
</span>
</h3>
<ButtonStyled size="small" circular>
<button
v-tooltip="action.prompt.dismissLabel"
@click="action.prompt.onDismiss?.()"
>
<XIcon aria-hidden="true" />
</button>
</ButtonStyled>
</div>
<p class="m-0 text-wrap text-sm font-medium leading-tight text-secondary">
{{ action.prompt.description }}
</p>
<p v-if="action.prompt.footer" class="m-0 text-wrap text-sm font-bold text-primary">
{{ action.prompt.footer }}
</p>
</div>
</template>
</Tooltip>
<template v-else>
<JoinedButtons
v-if="action.joinedActions?.length"
:actions="action.joinedActions"
:color="joinedActionColor(action.color)"
:size="action.size ?? 'large'"
:disabled="action.disabled"
:primary-disabled="action.primaryDisabled"
:dropdown-disabled="action.dropdownDisabled"
:primary-muted="action.primaryMuted"
/>
<ButtonStyled
v-else
:color="action.color ?? 'standard'"
:size="action.size ?? 'large'"
:type="action.type ?? 'standard'"
:circular="action.circular ?? action.labelHidden ?? false"
>
<TeleportOverflowMenu
v-if="action.menuActions?.length"
:options="action.menuActions"
:tooltip="action.tooltip"
:aria-label="actionLabel(action)"
:disabled="action.disabled"
>
<component
:is="action.icon"
v-if="action.icon"
:class="action.iconClass"
aria-hidden="true"
v-bind="action.iconProps"
/>
<span v-if="!action.labelHidden && !action.circular">{{ action.label }}</span>
</TeleportOverflowMenu>
<AutoLink
v-else-if="action.to"
v-tooltip="action.tooltip"
:to="action.to"
:aria-label="actionLabel(action)"
@click="(event) => handleActionClick(action, event)"
>
<component
:is="action.icon"
v-if="action.icon"
:class="action.iconClass"
aria-hidden="true"
v-bind="action.iconProps"
/>
<span v-if="!action.labelHidden && !action.circular">{{ action.label }}</span>
</AutoLink>
<button
v-else
v-tooltip="action.tooltip"
type="button"
:disabled="action.disabled"
:aria-label="actionLabel(action)"
@click="(event) => handleActionClick(action, event)"
>
<component
:is="action.icon"
v-if="action.icon"
:class="action.iconClass"
aria-hidden="true"
v-bind="action.iconProps"
/>
<span v-if="!action.labelHidden && !action.circular">{{ action.label }}</span>
</button>
</ButtonStyled>
</template>
</template>
</div>
</div>
<div v-if="props.metadata.length" class="flex justify-between md:hidden">
<div class="flex flex-wrap gap-3 empty:hidden">
<div class="flex min-w-0 flex-wrap items-center gap-2">
<template v-for="(item, index) in props.metadata" :key="item.id">
<BulletDivider v-if="index > 0" class="shrink-0" />
<div v-if="item.type === 'custom'" :class="item.class">
<slot :name="metadataSlotName(item)" :item="item" />
</div>
<AutoLink
v-else-if="item.to"
v-tooltip="item.tooltip"
:to="item.to"
:aria-label="item.ariaLabel ?? item.label ?? ''"
:class="metadataClass(item, true)"
>
<component
:is="item.icon"
v-if="item.icon"
class="flex size-5 shrink-0"
aria-hidden="true"
v-bind="item.iconProps"
/>
<span class="truncate">{{ item.label }}</span>
</AutoLink>
<button
v-else-if="item.onClick"
v-tooltip="item.tooltip"
type="button"
:aria-label="item.ariaLabel ?? item.label ?? ''"
:class="metadataClass(item, true)"
@click="item.onClick"
>
<component
:is="item.icon"
v-if="item.icon"
class="flex size-5 shrink-0"
aria-hidden="true"
v-bind="item.iconProps"
/>
<span class="truncate">{{ item.label }}</span>
</button>
<div
v-else
v-tooltip="item.tooltip"
:aria-label="item.ariaLabel"
:class="metadataClass(item)"
>
<component
:is="item.icon"
v-if="item.icon"
class="flex size-5 shrink-0"
aria-hidden="true"
v-bind="item.iconProps"
/>
<span class="truncate">{{ item.label }}</span>
</div>
</template>
</div>
</div>
</div>
<slot name="actions" />
</div>
</template>
<script setup lang="ts">
import { XIcon } from '@modrinth/assets'
import { Tooltip } from 'floating-vue'
import type { Component } from 'vue'
import { computed } from 'vue'
import type { RouteLocationRaw } from 'vue-router'
import AutoLink from './AutoLink.vue'
import Avatar from './Avatar.vue'
import BulletDivider from './BulletDivider.vue'
import ButtonStyled from './ButtonStyled.vue'
import JoinedButtons, { type JoinedButtonAction } from './JoinedButtons.vue'
import TeleportOverflowMenu, {
type Item as TeleportOverflowMenuItem,
} from './TeleportOverflowMenu.vue'
type PageHeaderTarget = string | RouteLocationRaw
type ButtonColor =
| 'standard'
| 'brand'
| 'red'
| 'orange'
| 'green'
| 'blue'
| 'purple'
| 'medal-promo'
type ButtonSize = 'standard' | 'large' | 'small'
type ButtonType =
| 'standard'
| 'outlined'
| 'transparent'
| 'highlight'
| 'highlight-colored-text'
| 'chip'
type PageHeaderLeading = {
id?: string
type: 'avatar' | 'button' | 'component'
icon?: Component
iconProps?: Record<string, unknown>
component?: Component
componentProps?: Record<string, unknown>
src?: string | null
alt?: string
tintBy?: string | null
avatarSize?: string
circle?: boolean
noShadow?: boolean
raised?: boolean
loading?: 'eager' | 'lazy'
class?: string
wrapperClass?: string
to?: PageHeaderTarget
onClick?: (event?: MouseEvent) => void | Promise<void>
tooltip?: string
ariaLabel?: string
color?: ButtonColor
size?: ButtonSize
buttonType?: ButtonType
}
type PageHeaderBadge = {
id: string
label?: string
icon?: Component
iconProps?: Record<string, unknown>
component?: Component
componentProps?: Record<string, unknown>
tooltip?: string
ariaLabel?: string
to?: PageHeaderTarget
onClick?: () => void | Promise<void>
class?: string
style?: Record<string, string>
}
type PageHeaderMetadataItem = {
id: string
type?: 'text' | 'custom'
label?: string
icon?: Component
iconProps?: Record<string, unknown>
tooltip?: string
ariaLabel?: string
to?: PageHeaderTarget
onClick?: () => void | Promise<void>
class?: string
}
type PageHeaderActionPrompt = {
title: string
description: string
badge?: string
footer?: string
dismissLabel?: string
shown?: boolean
placement?: string
onDismiss?: () => void
}
type PageHeaderAction = {
id: string
label: string
component?: Component
componentProps?: Record<string, unknown>
class?: string
icon?: Component
iconProps?: Record<string, unknown>
iconClass?: string
tooltip?: string
ariaLabel?: string
to?: PageHeaderTarget
onClick?: () => void | Promise<void>
disabled?: boolean
labelHidden?: boolean
circular?: boolean
color?: ButtonColor
size?: ButtonSize
type?: ButtonType
joinedActions?: JoinedButtonAction[]
menuActions?: TeleportOverflowMenuItem[]
primaryDisabled?: boolean
dropdownDisabled?: boolean
primaryMuted?: boolean
prompt?: PageHeaderActionPrompt
}
const props = withDefaults(
defineProps<{
header: string
summary?: string | null
leading?: PageHeaderLeading | PageHeaderLeading[] | null
badges?: PageHeaderBadge[]
metadata?: PageHeaderMetadataItem[]
actions?: PageHeaderAction[]
headerClass?: string
rowClass?: string
mainClass?: string
titleClass?: string
truncateTitle?: boolean
divider?: boolean
bottomPadding?: boolean
disableLineClamp?: boolean
}>(),
{
summary: null,
leading: null,
badges: () => [],
metadata: () => [],
actions: () => [],
headerClass: '',
rowClass: '',
mainClass: '',
titleClass: '',
truncateTitle: false,
divider: true,
bottomPadding: true,
disableLineClamp: false,
},
)
const leadingItems = computed(() => {
if (!props.leading) return []
return Array.isArray(props.leading) ? props.leading : [props.leading]
})
function leadingLabel(item: PageHeaderLeading) {
return item.ariaLabel ?? item.tooltip ?? 'Header action'
}
function leadingWrapperClass(item: PageHeaderLeading, defaultClass: string) {
return [item.wrapperClass ?? defaultClass]
}
function metadataClass(item: PageHeaderMetadataItem, interactive = false) {
return [
'flex min-w-0 items-center gap-2 font-medium text-secondary text-nowrap',
interactive ? 'm-0 cursor-pointer border-0 bg-transparent p-0 hover:underline' : '',
item.class,
]
}
function metadataSlotName(item: PageHeaderMetadataItem) {
return `metadata-${item.id}`
}
function badgeClass(badge: PageHeaderBadge, interactive = false) {
return [
'inline-flex items-center gap-1 rounded-full border border-solid border-surface-5 bg-button-bg px-2 py-1 text-sm font-semibold leading-none text-secondary text-nowrap [&>svg]:size-4 [&>svg]:shrink-0',
interactive ? 'm-0 cursor-pointer hover:underline' : '',
badge.class,
]
}
function actionLabel(action: PageHeaderAction) {
return action.ariaLabel ?? action.tooltip ?? action.label
}
function dismissActionPrompt(action: PageHeaderAction) {
if (action.prompt?.shown) {
action.prompt.onDismiss?.()
}
}
function handleActionClick(action: PageHeaderAction, event?: MouseEvent) {
dismissActionPrompt(action)
void action.onClick?.(event)
}
function joinedActionColor(color?: ButtonColor) {
return color === 'medal-promo' ? 'standard' : color
}
</script>
@@ -2,10 +2,13 @@
<div data-pyro-telepopover-wrapper class="relative">
<button
ref="triggerRef"
v-tooltip="tooltip"
class="teleport-overflow-menu-trigger"
:class="btnClass"
:aria-expanded="isOpen"
:aria-haspopup="true"
:aria-label="ariaLabel"
:disabled="disabled"
@mousedown="handleMouseDown"
@mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave"
@@ -38,9 +41,14 @@
:key="isDivider(option) ? `divider-${index}` : option.id"
>
<div v-if="isDivider(option)" class="h-px w-full bg-surface-5"></div>
<ButtonStyled v-else type="transparent" role="menuitem" :color="option.color">
<ButtonStyled
v-else
type="transparent"
role="menuitem"
:color="optionButtonColor(option)"
>
<button
v-if="typeof option.action === 'function'"
v-if="typeof option.action === 'function' || option.disabled"
:ref="
(el) => {
if (el) menuItemsRef[index] = el as HTMLElement
@@ -51,39 +59,41 @@
class="w-full !justify-start !whitespace-nowrap focus-visible:!outline-none"
:aria-selected="index === selectedIndex"
:style="index === selectedIndex ? { background: 'var(--color-button-bg)' } : {}"
@click="handleItemClick(option, index)"
@click="(event) => handleItemClick(option, index, event)"
@focus="selectedIndex = index"
@mouseover="handleMouseOver(index)"
>
<slot :name="option.id">
<component :is="option.icon" v-if="option.icon" class="size-5" />
{{ option.id }}
{{ option.label ?? option.id }}
</slot>
</button>
<AutoLink
v-else-if="typeof option.action === 'string'"
v-else-if="optionLink(option)"
:ref="
(el) => {
if (el) menuItemsRef[index] = el as HTMLElement
}
"
:to="option.action"
:to="optionLink(option)"
:target="option.external ? '_blank' : undefined"
:rel="option.external ? 'noopener noreferrer' : undefined"
class="w-full !justify-start !whitespace-nowrap focus-visible:!outline-none"
:aria-selected="index === selectedIndex"
:style="index === selectedIndex ? { background: 'var(--color-button-bg)' } : {}"
@click="handleItemClick(option, index)"
@click="(event) => handleItemClick(option, index, event)"
@focus="selectedIndex = index"
@mouseover="handleMouseOver(index)"
>
<slot :name="option.id">
<component :is="option.icon" v-if="option.icon" class="size-5" />
{{ option.id }}
{{ option.label ?? option.id }}
</slot>
</AutoLink>
<span v-else>
<slot :name="option.id">
<component :is="option.icon" v-if="option.icon" class="size-5" />
{{ option.id }}
{{ option.label ?? option.id }}
</slot>
</span>
</ButtonStyled>
@@ -95,29 +105,48 @@
</template>
<script setup lang="ts">
import { AutoLink, ButtonStyled } from '@modrinth/ui'
import { onClickOutside, useElementHover } from '@vueuse/core'
import { type Component, computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
interface Option {
import AutoLink from './AutoLink.vue'
import ButtonStyled from './ButtonStyled.vue'
type OptionColor =
| 'standard'
| 'brand'
| 'primary'
| 'danger'
| 'secondary'
| 'highlight'
| 'red'
| 'orange'
| 'green'
| 'blue'
| 'purple'
export interface Option {
id: string
label?: string
icon?: Component
action?: (() => void) | string
action?: ((event?: MouseEvent) => void) | string
link?: string
external?: boolean
shown?: boolean
color?: 'standard' | 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple'
color?: OptionColor
disabled?: boolean
tooltip?: string
remainOnClick?: boolean
}
type Divider = {
export type Divider = {
divider?: boolean
shown?: boolean
}
type Item = Option | Divider
export type Item = Option | Divider
function isDivider(item: Item): item is Divider {
return (item as Divider).divider
return !!(item as Divider).divider
}
const props = withDefaults(
@@ -125,10 +154,16 @@ const props = withDefaults(
options: Item[]
hoverable?: boolean
btnClass?: string | string[] | Record<string, boolean>
disabled?: boolean
tooltip?: string
ariaLabel?: string
}>(),
{
hoverable: false,
btnClass: undefined,
disabled: false,
tooltip: undefined,
ariaLabel: undefined,
},
)
@@ -191,6 +226,7 @@ const calculateMenuPosition = () => {
const toggleMenu = (event: MouseEvent) => {
event.stopPropagation()
if (props.disabled) return
if (!props.hoverable) {
if (isOpen.value) {
closeMenu()
@@ -201,6 +237,7 @@ const toggleMenu = (event: MouseEvent) => {
}
const openMenu = () => {
if (props.disabled) return
isOpen.value = true
emit('open')
disableBodyScroll()
@@ -218,15 +255,18 @@ const closeMenu = () => {
document.removeEventListener('mousemove', handleMouseMove)
}
const selectOption = (option: Option) => {
const selectOption = (option: Option, event?: MouseEvent) => {
emit('select', option)
if (typeof option.action === 'function') {
option.action()
option.action(event)
}
if (!option.remainOnClick) {
closeMenu()
}
closeMenu()
}
const handleMouseDown = (event: MouseEvent) => {
if (props.disabled) return
event.preventDefault()
isMouseDown.value = true
}
@@ -270,10 +310,10 @@ const handleMouseMove = (event: MouseEvent) => {
}
}
const handleItemClick = (option: Option, index: number) => {
const handleItemClick = (option: Option, index: number, event?: MouseEvent) => {
if (option.disabled) return
selectedIndex.value = index
selectOption(option)
selectOption(option, event)
}
const handleMouseOver = (index: number) => {
@@ -432,4 +472,23 @@ onClickOutside(menuRef, (event) => {
closeMenu()
}
})
function optionLink(option: Option) {
if (typeof option.action === 'string') return option.action
return option.link
}
function optionButtonColor(option: Option) {
switch (option.color) {
case 'primary':
return 'brand'
case 'danger':
return 'red'
case 'secondary':
case 'highlight':
return 'standard'
default:
return option.color ?? 'standard'
}
}
</script>
+6 -1
View File
@@ -19,7 +19,6 @@ export { default as CollapsibleAdmonition } from './CollapsibleAdmonition.vue'
export { default as CollapsibleRegion } from './CollapsibleRegion.vue'
export type { ComboboxOption } from './Combobox.vue'
export { default as Combobox } from './Combobox.vue'
export { default as ContentPageHeader } from './ContentPageHeader.vue'
export { default as CopyCode } from './CopyCode.vue'
export { default as DatePicker } from './DatePicker.vue'
export { default as DoubleIcon } from './DoubleIcon.vue'
@@ -59,6 +58,7 @@ export { default as OptionGroup } from './OptionGroup.vue'
export type { Option as OverflowMenuOption } from './OverflowMenu.vue'
export { default as OverflowMenu } from './OverflowMenu.vue'
export { default as Page } from './Page.vue'
export { default as PageHeader } from './PageHeader.vue'
export { default as Pagination } from './Pagination.vue'
export { default as PopoutMenu } from './PopoutMenu.vue'
export { default as PreviewSelectButton } from './PreviewSelectButton.vue'
@@ -83,6 +83,11 @@ export type { TabsTab, TabsValue } from './Tabs.vue'
export { default as Tabs } from './Tabs.vue'
export { default as TagItem } from './TagItem.vue'
export { default as TagTagItem } from './TagTagItem.vue'
export type {
Item as TeleportOverflowMenuItem,
Option as TeleportOverflowMenuOption,
} from './TeleportOverflowMenu.vue'
export { default as TeleportOverflowMenu } from './TeleportOverflowMenu.vue'
export { default as Timeline } from './Timeline.vue'
export { default as Toggle } from './Toggle.vue'
export { default as UnsavedChangesPopup } from './UnsavedChangesPopup.vue'
@@ -1,18 +1,14 @@
<template>
<ContentPageHeader>
<template #icon>
<Avatar :src="project.icon_url" :alt="project.title" size="96px" />
</template>
<template #title>
{{ project.title }}
</template>
<template #title-suffix>
<ProjectStatusBadge v-if="member || project.status !== 'approved'" :status="project.status" />
</template>
<template #summary>
{{ project.description }}
</template>
<template #stats>
<PageHeader
:header="project.title"
:summary="project.description"
:leading="leadingItem"
:badges="headerBadges"
:metadata="headerMetadata"
:actions="actions"
:disable-line-clamp="disableLineClamp"
>
<template #metadata-project-stats>
<div class="flex items-center gap-3 flex-wrap gap-y-0">
<template v-if="isServerProject">
<ServerDetails
@@ -66,24 +62,24 @@
</div>
</div>
</template>
<template #actions>
<slot name="actions" />
</template>
</ContentPageHeader>
</PageHeader>
</template>
<script setup lang="ts">
import type { Labrinth } from '@modrinth/api-client'
import { DownloadIcon, HeartIcon } from '@modrinth/assets'
import { capitalizeString, type Project } from '@modrinth/utils'
import type { Component } from 'vue'
import { computed } from 'vue'
import type { RouteLocationRaw } from 'vue-router'
import { useRouter } from 'vue-router'
import { useCompactNumber, useVIntl } from '../../composables'
import { commonMessages } from '../../utils'
import Avatar from '../base/Avatar.vue'
import ContentPageHeader from '../base/ContentPageHeader.vue'
import FormattedTag from '../base/FormattedTag.vue'
import type { JoinedButtonAction } from '../base/JoinedButtons.vue'
import PageHeader from '../base/PageHeader.vue'
import TagItem from '../base/TagItem.vue'
import type { Item as TeleportOverflowMenuItem } from '../base/TeleportOverflowMenu.vue'
import ProjectStatusBadge from './ProjectStatusBadge.vue'
import ServerDetails from './server/ServerDetails.vue'
@@ -91,18 +87,77 @@ const router = useRouter()
const { formatMessage } = useVIntl()
const { formatCompactNumber } = useCompactNumber()
type HeaderAction = {
id: string
label: string
component?: Component
componentProps?: Record<string, unknown>
class?: string
icon?: Component
iconProps?: Record<string, unknown>
iconClass?: string
tooltip?: string
ariaLabel?: string
to?: string | RouteLocationRaw
onClick?: (event?: MouseEvent) => void | Promise<void>
disabled?: boolean
labelHidden?: boolean
circular?: boolean
color?: 'standard' | 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple' | 'medal-promo'
size?: 'standard' | 'large' | 'small'
type?: 'standard' | 'outlined' | 'transparent' | 'highlight' | 'highlight-colored-text' | 'chip'
joinedActions?: JoinedButtonAction[]
menuActions?: TeleportOverflowMenuItem[]
primaryDisabled?: boolean
dropdownDisabled?: boolean
primaryMuted?: boolean
}
const props = withDefaults(
defineProps<{
project: Project
member?: boolean
projectV3?: Labrinth.Projects.v3.Project | null
ping?: number
actions?: HeaderAction[]
disableLineClamp?: boolean
}>(),
{
member: false,
actions: () => [],
disableLineClamp: false,
},
)
const leadingItem = computed(() => ({
type: 'avatar' as const,
src: props.project.icon_url,
alt: props.project.title,
avatarSize: '96px',
}))
const headerBadges = computed(() =>
props.member || props.project.status !== 'approved'
? [
{
id: 'status',
component: ProjectStatusBadge,
componentProps: {
status: props.project.status,
},
},
]
: [],
)
const headerMetadata = [
{
id: 'project-stats',
type: 'custom' as const,
class: 'contents',
},
]
const searchUrl = computed(
() => `/discover/${isServerProject.value ? 'servers' : `${props.project.project_type}s`}`,
)
@@ -77,7 +77,7 @@ onMounted(() => {
isClient.value = true
})
const { serverId } = injectModrinthServerContext()
const { serverId, worldId } = injectModrinthServerContext()
const { featureFlags } = injectPageContext()
const props = withDefaults(
@@ -190,7 +190,9 @@ const metrics = computed(() => {
showGraph: false,
chartOptions: null as ReturnType<typeof buildChartOptions> | null,
series: null as { name: string; data: number[] }[] | null,
link: `/hosting/manage/${encodeURIComponent(serverId)}/files`,
link: worldId.value
? `/hosting/manage/${encodeURIComponent(serverId)}/instances/${encodeURIComponent(worldId.value)}/files`
: `/hosting/manage/${encodeURIComponent(serverId)}/instances`,
}
if (props.loading) {
@@ -186,7 +186,7 @@ async function show({ serverId, tabIndex, tabId }: ShowOptions) {
queryFn: () => client.archon.properties_v1.getProperties(targetServerId, worldId.value!),
})
queryClient.prefetchQuery({
queryKey: ['content', 'list', 'v1', targetServerId],
queryKey: ['content', 'list', 'v1', targetServerId, worldId.value],
queryFn: () =>
client.archon.content_v1.getAddons(targetServerId, worldId.value!, {
from_modpack: false,
@@ -11,7 +11,7 @@ import InstallingBanner, {
type SyncProgress,
} from '#ui/components/servers/InstallingBanner.vue'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import { useServerBackupsQueue } from '#ui/composables/server-backups-queue'
import { useServerBackupsQueue } from '#ui/composables/servers/server-backups-queue.ts'
import type { FileOperation } from '#ui/layouts/shared/files-tab/types'
import { injectModrinthClient, injectModrinthServerContext } from '#ui/providers'
@@ -53,8 +53,12 @@ const messages = defineMessages({
},
})
const isOnContentTab = computed(() => route.path.includes('/content'))
const isOnFilesTab = computed(() => route.path.includes('/files'))
const isOnContentTab = computed(
() =>
route.path.includes('/content') ||
(!!route.params.instance_id && !isOnFilesTab.value && !route.path.includes('/backups')),
)
const bannerCoversInstalling = computed(
() =>
@@ -87,12 +87,12 @@ const props = defineProps<{
backups?: Archon.BackupsQueue.v1.BackupQueueBackup[]
}>()
const backupsQueryKey = ['backups', 'queue', ctx.serverId]
const backupsQueryKey = computed(() => ['backups', 'queue', ctx.serverId, ctx.worldId.value])
const createMutation = useMutation({
mutationFn: (name: string) =>
client.archon.backups_queue_v1.create(ctx.serverId, ctx.worldId.value!, { name }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: backupsQueryKey }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: backupsQueryKey.value }),
})
const modal = ref<InstanceType<typeof NewModal>>()
@@ -69,12 +69,12 @@ const props = defineProps<{
backups?: Archon.BackupsQueue.v1.BackupQueueBackup[]
}>()
const backupsQueryKey = ['backups', 'queue', ctx.serverId]
const backupsQueryKey = computed(() => ['backups', 'queue', ctx.serverId, ctx.worldId.value])
const renameMutation = useMutation({
mutationFn: ({ backupId, name }: { backupId: string; name: string }) =>
client.archon.backups_v1.rename(ctx.serverId, ctx.worldId.value!, backupId, { name }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: backupsQueryKey }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: backupsQueryKey.value }),
})
const modal = ref<InstanceType<typeof NewModal>>()
@@ -39,7 +39,7 @@
import type { Archon } from '@modrinth/api-client'
import { RotateCounterClockwiseIcon, SpinnerIcon, XIcon } from '@modrinth/assets'
import { useMutation, useQueryClient } from '@tanstack/vue-query'
import { ref } from 'vue'
import { computed, ref } from 'vue'
import {
injectModrinthClient,
@@ -56,7 +56,7 @@ const client = injectModrinthClient()
const queryClient = useQueryClient()
const ctx = injectModrinthServerContext()
const backupsQueryKey = ['backups', 'queue', ctx.serverId]
const backupsQueryKey = computed(() => ['backups', 'queue', ctx.serverId, ctx.worldId.value])
function safetyBackupName(backupName: string) {
const base = `Before restoring "${backupName}"`
@@ -66,7 +66,7 @@ function safetyBackupName(backupName: string) {
const restoreMutation = useMutation({
mutationFn: ({ backupId, name }: { backupId: string; name: string }) =>
client.archon.backups_queue_v1.restore(ctx.serverId, ctx.worldId.value!, backupId, { name }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: backupsQueryKey }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: backupsQueryKey.value }),
})
const modal = ref<InstanceType<typeof NewModal>>()
@@ -0,0 +1,312 @@
<template>
<article
class="flex min-h-[19.75rem] w-full flex-col overflow-hidden rounded-2xl border border-solid border-surface-5 bg-bg-raised shadow-xl"
:class="(world as any)?.active ? '!border-brand' : ''"
>
<template v-if="world.type === 'empty'">
<div class="flex flex-1 flex-col items-center pt-[3.125rem] text-center">
<svg
class="size-[5.6645rem]"
viewBox="0 0 91 91"
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<rect
x="22.4356"
y="0.629395"
width="71"
height="71"
rx="19.5"
transform="rotate(17.8856 22.4356 0.629395)"
stroke="#42444A"
/>
<rect
x="4.36354"
y="16.5661"
width="71"
height="71"
rx="19.5"
transform="rotate(-8.79487 4.36354 16.5661)"
fill="#34363C"
/>
<rect
x="4.36354"
y="16.5661"
width="71"
height="71"
rx="19.5"
transform="rotate(-8.79487 4.36354 16.5661)"
stroke="#42444A"
/>
<g :clip-path="`url(#${emptyCardClipId})`">
<path
d="M47.4227 62.6919C56.5193 61.2846 62.7525 52.7695 61.3452 43.673C59.9378 34.5764 51.4227 28.3432 42.3262 29.7505C33.2297 31.1579 26.9964 39.673 28.4038 48.7695C29.8111 57.866 38.3262 64.0993 47.4227 62.6919Z"
stroke="#B0BAC5"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M42.3246 29.7502C38.7824 34.8453 37.3358 41.1078 38.2846 47.2402C39.2334 53.3727 42.5048 58.9052 47.4212 62.6916C50.9634 57.5965 52.41 51.3341 51.4612 45.2016C50.5124 39.0691 47.241 33.5366 42.3246 29.7502Z"
stroke="#B0BAC5"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
<path
d="M28.4023 48.7695L61.3437 43.673"
stroke="#B0BAC5"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</g>
<defs>
<clipPath :id="emptyCardClipId">
<rect
width="40"
height="40"
fill="white"
transform="translate(22.0508 29.5137) rotate(-8.79487)"
/>
</clipPath>
</defs>
</svg>
<div class="mt-6 flex flex-col gap-1">
<h2 class="m-0 text-2xl font-semibold leading-8 text-contrast">{{ world.name }}</h2>
<p class="m-0 text-base leading-6 text-secondary">
{{ formatMessage(messages.newInstance) }}
</p>
</div>
</div>
<div class="px-5 pb-4">
<ButtonStyled color="brand">
<button class="w-full !h-10" @click="emit('create', world.id)">
<PlusIcon aria-hidden="true" />
{{ formatMessage(messages.createInstance) }}
</button>
</ButtonStyled>
</div>
</template>
<template v-else>
<header class="flex min-h-[5.75rem] flex-col justify-center gap-1 px-5 py-4">
<div class="flex min-w-0 items-center justify-between gap-3">
<span
ref="worldNameRef"
v-tooltip="truncatedTooltip(worldNameRef, world.name)"
class="m-0 truncate text-xl font-semibold text-contrast"
>{{ world.name }}</span
>
<span
v-if="world.active"
class="shrink-0 rounded-full bg-brand-highlight border border-brand border-solid px-2.5 py-1 text-green"
>
{{ formatMessage(messages.active) }}
</span>
</div>
<div class="flex min-w-0 text-md items-center gap-2 text-secondary">
{{ world.gameVersion }} <BulletDivider /> {{ world.loaderLabel }}
</div>
</header>
<div
class="flex flex-1 flex-col gap-3 border-0 border-y bg-surface-2 border-solid border-surface-5 my-auto px-5 py-4"
>
<div
class="grid min-h-6 grid-cols-[minmax(0,1fr)_minmax(0,70%)] items-center gap-4 text-base text-secondary [&>*:last-child]:max-w-full [&>*:last-child]:justify-self-end"
>
<span>{{ formatMessage(commonMessages.modpackLabel) }}</span>
<div
v-if="world.linkedModpack"
class="flex min-w-0 items-center gap-2 text-right font-semibold leading-5 text-contrast"
>
<AutoLink :to="world.linkedModpack.link" class="flex shrink-0 items-center">
<Avatar
:src="world.linkedModpack.iconUrl"
:alt="world.linkedModpack.name"
:tint-by="world.linkedModpack.name"
size="1.25rem"
no-shadow
/>
</AutoLink>
<AutoLink
:to="world.linkedModpack.link"
class="flex min-w-0 items-center font-semibold leading-5 text-contrast"
:class="world.linkedModpack.link ? 'hover:underline' : ''"
>
<span
ref="modpackNameRef"
v-tooltip="truncatedTooltip(modpackNameRef, world.linkedModpack.name)"
class="block truncate leading-5"
>
{{ world.linkedModpack.name }}
</span>
</AutoLink>
</div>
<span v-else class="font-semibold text-contrast">{{ formatMessage(messages.noModpack) }}</span>
</div>
<div
class="grid min-h-6 grid-cols-[minmax(0,1fr)_minmax(0,25%)] items-center gap-4 text-base text-secondary [&>*:last-child]:max-w-full [&>*:last-child]:justify-self-end"
>
<span>{{ formatMessage(messages.installedContent) }}</span>
<span class="font-semibold text-contrast">{{ installedContentLabel }}</span>
</div>
<div
class="grid min-h-6 grid-cols-[minmax(0,1fr)_minmax(0,45%)] items-center gap-4 text-base text-secondary [&>*:last-child]:max-w-full [&>*:last-child]:justify-self-end"
>
<span>{{ formatMessage(messages.lastActive) }}</span>
<span class="font-semibold text-contrast">{{ lastActiveLabel }}</span>
</div>
<div
class="grid min-h-6 grid-cols-[minmax(0,1fr)_minmax(0,45%)] items-center gap-4 text-base text-secondary [&>*:last-child]:max-w-full [&>*:last-child]:justify-self-end"
>
<span>{{ formatMessage(messages.created) }}</span>
<span class="font-semibold text-contrast">{{ createdLabel }}</span>
</div>
</div>
<footer class="flex items-center justify-between gap-3 px-5 py-4">
<ButtonStyled>
<button class="!shadow-none" @click="emit('edit', world.id)">
<PencilIcon aria-hidden="true" />
{{ formatMessage(messages.editInstance) }}
</button>
</ButtonStyled>
<ButtonStyled circular>
<button
v-tooltip="formatMessage(messages.instanceSettings)"
class="!shadow-none"
@click="emit('settings', world.id)"
>
<Settings2Icon aria-hidden="true" />
</button>
</ButtonStyled>
</footer>
</template>
</article>
</template>
<script setup lang="ts">
import { PencilIcon, PlusIcon, Settings2Icon } from '@modrinth/assets'
import { capitalizeString } from '@modrinth/utils'
import { computed, useId, useTemplateRef } from 'vue'
import AutoLink from '#ui/components/base/AutoLink.vue'
import Avatar from '#ui/components/base/Avatar.vue'
import BulletDivider from '#ui/components/base/BulletDivider.vue'
import ButtonStyled from '#ui/components/base/ButtonStyled.vue'
import { useFormatDateTime, useRelativeTime } from '#ui/composables'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import { truncatedTooltip } from '#ui/utils'
import { commonMessages } from '#ui/utils/common-messages'
const messages = defineMessages({
newInstance: {
id: 'servers.manage.instances.card.empty-description',
defaultMessage: 'New instance',
},
createInstance: {
id: 'servers.manage.instances.card.create',
defaultMessage: 'Create instance',
},
active: {
id: 'servers.manage.instances.card.active',
defaultMessage: 'Active',
},
noModpack: {
id: 'servers.manage.instances.card.no-modpack',
defaultMessage: '—',
},
installedContent: {
id: 'servers.manage.instances.card.installed-content',
defaultMessage: 'Installed content',
},
lastActive: {
id: 'servers.manage.instances.card.last-active',
defaultMessage: 'Last active',
},
created: {
id: 'servers.manage.instances.card.created',
defaultMessage: 'Created',
},
editInstance: {
id: 'servers.manage.instances.card.edit',
defaultMessage: 'Edit instance',
},
instanceSettings: {
id: 'servers.manage.instances.card.settings',
defaultMessage: 'Instance settings',
},
notTrackedYet: {
id: 'servers.manage.instances.card.not-tracked-yet',
defaultMessage: 'Not tracked yet',
},
})
type LinkedModpack = {
name: string
iconUrl: string | null
link: string | null
}
type UsedWorld = {
type: 'world'
id: string
name: string
active: boolean
gameVersion: string | null
loaderLabel: string | null
linkedModpack: LinkedModpack | null
installedContentCount: number | null
lastActiveAt: string | null
createdAt: string | null
}
type EmptyWorld = {
type: 'empty'
id: string
name: string
}
const props = defineProps<{
world: UsedWorld | EmptyWorld
}>()
const emit = defineEmits<{
create: [slotId: string]
edit: [worldId: string]
settings: [worldId: string]
}>()
const formatRelativeTime = useRelativeTime()
const formatDate = useFormatDateTime({ dateStyle: 'medium' })
const { formatMessage } = useVIntl()
const emptyCardClipId = useId()
const modpackNameRef = useTemplateRef<HTMLElement>('modpackNameRef')
const worldNameRef = useTemplateRef<HTMLElement>('worldNameRef')
const installedContentLabel = computed(() => {
if (props.world.type === 'empty') return ''
return props.world.installedContentCount === null
? formatMessage(commonMessages.unknownLabel)
: String(props.world.installedContentCount)
})
const lastActiveLabel = computed(() => {
if (props.world.type === 'empty') return ''
return props.world.lastActiveAt
? capitalizeString(formatRelativeTime(props.world.lastActiveAt))
: formatMessage(messages.notTrackedYet)
})
const createdLabel = computed(() => {
if (props.world.type === 'empty') return ''
return props.world.createdAt
? formatDate(props.world.createdAt)
: formatMessage(commonMessages.unknownLabel)
})
</script>
@@ -1,14 +1,14 @@
<template>
<div class="contents">
<div class="flex flex-row items-center gap-2 rounded-lg">
<ButtonStyled v-if="isInstalling" type="standard" color="brand" size="large">
<ButtonStyled v-if="isInstalling" type="standard" color="brand" :size="size">
<button disabled class="flex-shrink-0">
<LoaderCircleIcon class="size-5 animate-spin" /> Installing...
</button>
</ButtonStyled>
<template v-else-if="showRestartButton">
<ButtonStyled type="standard" color="orange" size="large">
<ButtonStyled type="standard" color="orange" :size="size">
<button v-tooltip="busyTooltip" :disabled="!canTakeAction" @click="handlePrimaryAction">
<UpdatedIcon />
<span>{{ primaryActionText }}</span>
@@ -17,7 +17,7 @@
<JoinedButtons
color="red"
size="large"
:size="size"
:actions="stopSplitActions"
:primary-disabled="!canTakeAction"
:dropdown-disabled="!canKill"
@@ -32,7 +32,7 @@
<template v-else-if="isStopping">
<JoinedButtons
color="red"
size="large"
:size="size"
:actions="stopSplitActions"
:primary-disabled="true"
:dropdown-disabled="!canKill"
@@ -46,10 +46,10 @@
</template>
<template v-else>
<ButtonStyled type="standard" color="brand" size="large">
<ButtonStyled type="standard" color="brand" :size="size">
<button v-tooltip="busyTooltip" :disabled="!canTakeAction" @click="handlePrimaryAction">
<PlayIcon />
<span>{{ primaryActionText }}</span>
<span>{{ startActionText }}</span>
</button>
</ButtonStyled>
</template>
@@ -74,9 +74,13 @@ import { useServerPowerAction } from './use-server-power-action'
const props = withDefaults(
defineProps<{
disabled?: boolean
size?: 'standard' | 'large' | 'small'
startLabel?: string
}>(),
{
disabled: false,
size: 'large',
startLabel: 'Start',
},
)
@@ -94,6 +98,11 @@ const {
disabled: computed(() => props.disabled),
})
const size = computed(() => props.size)
const startActionText = computed(() =>
primaryActionText.value === 'Start' ? props.startLabel : primaryActionText.value,
)
const stopSplitActions = computed<JoinedButtonAction[]>(() => [
{
id: 'stop',
@@ -1,65 +0,0 @@
<template>
<div class="contents">
<ButtonStyled circular type="transparent" size="large">
<TeleportOverflowMenu :options="menuOptions">
<MoreVerticalIcon aria-hidden="true" />
<template #allServers>
<ServerIcon class="h-5 w-5" />
<span>All servers</span>
</template>
<template #copy-id>
<ClipboardCopyIcon class="h-5 w-5" aria-hidden="true" />
<span>Copy ID</span>
</template>
</TeleportOverflowMenu>
</ButtonStyled>
</div>
</template>
<script setup lang="ts">
import { ClipboardCopyIcon, MoreVerticalIcon, ServerIcon } from '@modrinth/assets'
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ButtonStyled } from '#ui/components'
import TeleportOverflowMenu from '#ui/components/base/TeleportOverflowMenu.vue'
import { injectModrinthServerContext } from '#ui/providers'
const props = withDefaults(
defineProps<{
disabled?: boolean
showCopyIdAction?: boolean
showDebugInfo?: boolean
uptimeSeconds?: number
}>(),
{
disabled: false,
showCopyIdAction: false,
showDebugInfo: false,
uptimeSeconds: 0,
},
)
const router = useRouter()
const { serverId } = injectModrinthServerContext()
const menuOptions = computed(() => [
{
id: 'allServers',
label: 'All servers',
icon: ServerIcon,
action: () => router.push('/hosting/manage'),
},
{
id: 'copy-id',
label: 'Copy ID',
icon: ClipboardCopyIcon,
action: () => copyId(),
shown: props.showCopyIdAction,
},
])
async function copyId() {
await navigator.clipboard.writeText(serverId)
}
</script>
@@ -1,96 +1,38 @@
<template>
<div class="w-full flex flex-col gap-4" :class="{ 'mt-4': isNuxt }">
<ContentPageHeader :class="props.headerClass">
<template #icon>
<ServerIcon
:image="headerImage"
:class="isNuxt ? 'size-20 !rounded-2xl' : 'size-16 !rounded-xl'"
/>
</template>
<template #title>
{{ props.server?.name || 'Server' }}
</template>
<template #stats>
<div
v-if="props.server?.flows?.intro"
class="flex items-center gap-2 font-semibold text-secondary"
>
<SettingsIcon />
Configuring server...
</div>
<div v-else class="flex flex-wrap items-center gap-2">
<div v-if="props.server?.loader" class="flex items-center gap-2 font-medium capitalize">
<LoaderIcon :loader="props.server.loader" class="flex shrink-0 [&&]:size-5" />
{{ props.server.loader }} {{ props.server.mc_version }}
</div>
<div
v-if="
props.server?.loader &&
props.server?.net?.domain &&
!userPreferences.hideSubdomainLabel
"
class="h-1.5 w-1.5 rounded-full bg-surface-5"
/>
<div
v-if="props.server?.net?.domain && !userPreferences.hideSubdomainLabel"
v-tooltip="'Copy server address'"
class="flex cursor-pointer items-center gap-2 font-medium hover:underline text-nowrap"
@click="copyServerAddress"
>
<LinkIcon class="flex size-5 shrink-0" />
{{ props.server.net.domain }}.modrinth.gg
</div>
<div v-if="showUptime" class="h-1.5 w-1.5 rounded-full bg-surface-5" />
<div v-if="showUptime" class="flex items-center gap-2 font-medium">
<TimerIcon class="flex size-5 shrink-0" />
{{ formattedUptime }}
</div>
<div
v-if="showProject && (props.server?.loader || props.server?.net?.domain || showUptime)"
class="h-1.5 w-1.5 rounded-full bg-surface-5"
/>
<div
v-if="showProject"
class="flex items-center gap-1.5 font-medium text-primary text-nowrap"
>
Linked to
<Avatar
:src="props.serverProject?.icon_url ?? undefined"
:alt="props.serverProject?.title ?? ''"
size="24px"
/>
<AutoLink :to="serverProjectLink" class="truncate text-primary hover:underline">
{{ props.serverProject?.title }}
</AutoLink>
</div>
</div>
</template>
<template #actions>
<slot name="actions" />
</template>
</ContentPageHeader>
<PageHeader
:header="props.server?.name || 'Server'"
:leading="leadingItems"
:metadata="metadataItems"
:actions="headerActions"
:header-class="props.headerClass"
/>
</div>
</template>
<script setup lang="ts">
import type { Archon } from '@modrinth/api-client'
import { NuxtModrinthClient } from '@modrinth/api-client'
import { LinkIcon, LoaderIcon, SettingsIcon, TimerIcon } from '@modrinth/assets'
import { useStorage } from '@vueuse/core'
import { computed } from 'vue'
import { AutoLink, Avatar, ContentPageHeader, ServerIcon } from '#ui/components'
import {
injectModrinthClient,
injectModrinthServerContext,
injectNotificationManager,
} from '#ui/providers'
GlobeIcon,
LinkIcon,
LoaderCircleIcon,
PlayIcon,
SettingsIcon,
SlashIcon,
StopCircleIcon,
UpdatedIcon,
} from '@modrinth/assets'
import type { Component } from 'vue'
import { computed } from 'vue'
import type { RouteLocationRaw } from 'vue-router'
import type { JoinedButtonAction } from '#ui/components/base/JoinedButtons.vue'
import PageHeader from '#ui/components/base/PageHeader.vue'
import ServerIcon from '#ui/components/servers/icons/ServerIcon.vue'
import { injectModrinthClient, injectNotificationManager } from '#ui/providers'
import { useServerPowerAction } from './use-server-power-action'
type ServerProjectSummary = {
id: string
@@ -99,37 +41,115 @@ type ServerProjectSummary = {
icon_url?: string | null
}
type HeaderWorld = {
id: string
name: string
}
type HeaderMetadataItem = {
id: string
label: string
icon: Component
iconProps?: Record<string, unknown>
tooltip?: string
ariaLabel?: string
to?: string | RouteLocationRaw
onClick?: () => void | Promise<void>
class?: string
}
type HeaderAction = {
id: string
label: string
icon?: Component
iconProps?: Record<string, unknown>
iconClass?: string
tooltip?: string
ariaLabel?: string
to?: string | RouteLocationRaw
onClick?: () => void | Promise<void>
disabled?: boolean
labelHidden?: boolean
circular?: boolean
color?: 'standard' | 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple'
size?: 'standard' | 'large' | 'small'
type?: 'standard' | 'outlined' | 'transparent' | 'highlight' | 'highlight-colored-text' | 'chip'
joinedActions?: JoinedButtonAction[]
primaryDisabled?: boolean
dropdownDisabled?: boolean
primaryMuted?: boolean
prompt?: {
title: string
description: string
dismissLabel?: string
shown?: boolean
placement?: string
onDismiss?: () => void
}
}
const props = withDefaults(
defineProps<{
server: Archon.Servers.v0.Server | null | undefined
serverImage?: string | null
serverProject?: ServerProjectSummary | null
serverProjectLink?: string
activeWorldName?: string | null
uptimeSeconds?: number
showUptime?: boolean
backHref?: string
breadcrumbClass?: string
headerClass?: string
worlds?: HeaderWorld[]
powerDisabled?: boolean
settingsLabel?: string
showSettingsHint?: boolean
settingsHintTitle?: string
settingsHintDescription?: string
settingsHintDismissLabel?: string
actions?: HeaderAction[]
}>(),
{
serverImage: null,
serverProject: null,
serverProjectLink: '',
activeWorldName: null,
uptimeSeconds: 0,
showUptime: true,
backHref: '/hosting/manage',
breadcrumbClass: 'breadcrumb goto-link flex w-fit items-center',
headerClass: '',
worlds: () => [],
powerDisabled: false,
settingsLabel: 'Server settings',
showSettingsHint: false,
settingsHintTitle: '',
settingsHintDescription: '',
settingsHintDismissLabel: "Don't show again",
actions: () => [],
},
)
const emit = defineEmits<{
openSettings: []
dismissSettingsHint: []
}>()
const client = injectModrinthClient()
const { addNotification } = injectNotificationManager()
const { serverId } = injectModrinthServerContext()
const isNuxt = computed(() => client instanceof NuxtModrinthClient)
const userPreferences = useStorage(`pyro-server-${serverId}-preferences`, {
hideSubdomainLabel: false,
const {
isInstalling,
isStopping,
showRestartButton,
busyTooltip,
canTakeAction,
canKill,
primaryActionText,
initiateAction,
handlePrimaryAction,
} = useServerPowerAction({
disabled: computed(() => props.powerDisabled),
})
const headerImage = computed(() => {
@@ -139,37 +159,206 @@ const headerImage = computed(() => {
return props.serverImage ?? undefined
})
const showUptime = computed(() => props.showUptime && (props.uptimeSeconds ?? 0) > 0)
const leadingItems = computed(() => [
{
id: 'server-icon',
type: 'component' as const,
component: ServerIcon,
componentProps: {
image: headerImage.value,
},
class: isNuxt.value ? 'size-15 !rounded-2xl' : 'size-15 !rounded-xl',
},
])
const formattedUptime = computed(() => {
const uptime = props.uptimeSeconds ?? 0
const days = Math.floor(uptime / (24 * 3600))
const hours = Math.floor((uptime % (24 * 3600)) / 3600)
const minutes = Math.floor((uptime % 3600) / 60)
const seconds = uptime % 60
const serverAddress = computed(() => {
const domain = props.server?.net?.domain
if (domain) return `${domain}.modrinth.gg`
let formatted = ''
if (days > 0) formatted += `${days}d `
if (hours > 0 || days > 0) formatted += `${hours}h `
formatted += `${minutes}m ${seconds}s`
return formatted.trim()
const ip = props.server?.net?.ip
if (!ip) return null
const port = props.server?.net?.port
return port ? `${ip}:${port}` : ip
})
const showProject = computed(() => !!props.serverProject)
const metadataItems = computed<HeaderMetadataItem[]>(() => {
if (props.server?.flows?.intro) {
return [
{
id: 'configuring',
label: 'Configuring server...',
icon: SettingsIcon,
},
]
}
const serverProjectLink = computed(() => {
if (props.serverProjectLink) {
return props.serverProjectLink
const items: HeaderMetadataItem[] = []
const worldName = props.activeWorldName
if (worldName) {
items.push({
id: 'world',
label: worldName,
icon: GlobeIcon,
})
}
if (!props.serverProject) {
return ''
if (serverAddress.value) {
items.push({
id: 'address',
label: serverAddress.value,
icon: LinkIcon,
tooltip: 'Copy server address',
onClick: copyServerAddress,
})
}
return `/project/${props.serverProject.slug ?? props.serverProject.id}`
return items
})
const startActionText = computed(() =>
primaryActionText.value === 'Start' ? 'Start server' : primaryActionText.value,
)
const startableWorlds = computed(() => {
if (props.worlds.length > 0) return props.worlds
return [
{
id: 'current-world',
name: props.activeWorldName ?? 'current instance',
},
]
})
const startSplitActions = computed<JoinedButtonAction[]>(() => [
{
id: 'start',
label: startActionText.value,
icon: PlayIcon,
action: handlePrimaryAction,
},
...startableWorlds.value.map((world) => ({
id: `start-${world.id}`,
label: `Start with ${world.name}`,
icon: GlobeIcon,
action: handlePrimaryAction,
})),
])
const restartSplitActions = computed<JoinedButtonAction[]>(() => [
{
id: 'restart',
label: primaryActionText.value,
icon: UpdatedIcon,
action: () => initiateAction('Restart'),
},
// TODO: Implement world scoping when Archon/Kyros support target worlds in power requests.
...startableWorlds.value.map((world) => ({
id: `restart-${world.id}`,
label: `Restart with ${world.name}`,
icon: GlobeIcon,
action: () => initiateAction('Restart'),
})),
])
const stopSplitActions = computed<JoinedButtonAction[]>(() => [
{
id: 'stop',
label: isStopping.value ? 'Stopping' : 'Stop',
icon: StopCircleIcon,
action: () => initiateAction('Stop'),
},
{
id: 'kill_server',
label: 'Kill server',
icon: SlashIcon,
action: () => initiateAction('Kill'),
},
])
const powerActions = computed<HeaderAction[]>(() => {
if (isInstalling.value) {
return [
{
id: 'installing',
label: 'Installing...',
icon: LoaderCircleIcon,
iconClass: 'animate-spin',
color: 'brand',
disabled: true,
},
]
}
if (showRestartButton.value) {
return [
{
id: 'restart',
label: primaryActionText.value,
color: 'orange',
joinedActions: restartSplitActions.value,
primaryDisabled: !canTakeAction.value,
dropdownDisabled: !canTakeAction.value,
},
{
id: 'stop',
label: 'Stop server',
color: 'red',
joinedActions: stopSplitActions.value,
primaryDisabled: !canTakeAction.value,
dropdownDisabled: !canKill.value,
},
]
}
if (isStopping.value) {
return [
{
id: 'stop',
label: 'Stop server',
color: 'red',
joinedActions: stopSplitActions.value,
primaryDisabled: true,
dropdownDisabled: !canKill.value,
primaryMuted: true,
},
]
}
return [
{
id: 'start',
label: startActionText.value,
color: 'brand',
tooltip: busyTooltip.value,
joinedActions: startSplitActions.value,
primaryDisabled: !canTakeAction.value,
dropdownDisabled: !canTakeAction.value,
},
]
})
const settingsAction = computed<HeaderAction>(() => ({
id: 'settings',
label: props.settingsLabel,
icon: SettingsIcon,
labelHidden: true,
tooltip: props.showSettingsHint ? undefined : props.settingsLabel,
onClick: () => emit('openSettings'),
prompt: {
title: props.settingsHintTitle,
description: props.settingsHintDescription,
dismissLabel: props.settingsHintDismissLabel,
shown: props.showSettingsHint,
placement: 'bottom-end',
onDismiss: () => emit('dismissSettingsHint'),
},
}))
const headerActions = computed<HeaderAction[]>(() => [
...powerActions.value,
settingsAction.value,
...props.actions,
])
function copyServerAddress() {
if (!props.server?.net?.domain) return
navigator.clipboard.writeText(`${props.server.net.domain}.modrinth.gg`)
if (!serverAddress.value) return
navigator.clipboard.writeText(serverAddress.value)
addNotification({
title: 'Server address copied',
text: "Your server's address has been copied to your clipboard.",
@@ -0,0 +1,134 @@
<template>
<div class="w-full flex flex-col gap-4" :class="{ 'mt-4': isNuxt }">
<PageHeader
:header="props.name || props.fallbackName"
:leading="leadingItems"
:metadata="headerMetadata"
:actions="props.actions"
:header-class="props.headerClass"
/>
</div>
</template>
<script setup lang="ts">
import { NuxtModrinthClient } from '@modrinth/api-client'
import { LeftArrowIcon, TagCategoryGamepad2Icon as Gamepad2Icon, TimerIcon } from '@modrinth/assets'
import { type Component, computed } from 'vue'
import { useRouter } from 'vue-router'
import PageHeader from '#ui/components/base/PageHeader.vue'
import LoaderIcon from '#ui/components/servers/icons/LoaderIcon.vue'
import { injectModrinthClient } from '#ui/providers'
import { formatLoaderLabel } from '#ui/utils/loaders'
type MetadataItem = {
id: string
label: string
icon: Component
iconProps?: Record<string, unknown>
}
type HeaderAction = {
id: string
label: string
icon?: Component
iconProps?: Record<string, unknown>
iconClass?: string
tooltip?: string
ariaLabel?: string
onClick?: () => void | Promise<void>
disabled?: boolean
labelHidden?: boolean
circular?: boolean
color?: 'standard' | 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple'
size?: 'standard' | 'large' | 'small'
type?: 'standard' | 'outlined' | 'transparent' | 'highlight' | 'highlight-colored-text' | 'chip'
joinedActions?: {
id: string
label: string
icon?: Component
action: () => void
color?: 'standard' | 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple'
hoverFilled?: boolean
}[]
primaryDisabled?: boolean
dropdownDisabled?: boolean
primaryMuted?: boolean
}
const props = withDefaults(
defineProps<{
name?: string | null
metadataItems?: MetadataItem[]
gameVersion?: string | null
loader?: string | null
loaderVersion?: string | null
lastActive?: string | null
backHref: string
backLabel: string
fallbackName?: string
headerClass?: string
actions?: HeaderAction[]
}>(),
{
name: null,
metadataItems: () => [],
gameVersion: null,
loader: null,
loaderVersion: null,
lastActive: null,
fallbackName: 'World',
headerClass: '',
actions: () => [],
},
)
const client = injectModrinthClient()
const router = useRouter()
const isNuxt = computed(() => client instanceof NuxtModrinthClient)
const leadingItems = computed(() => [
{
id: 'back',
type: 'button' as const,
icon: LeftArrowIcon,
ariaLabel: props.backLabel,
tooltip: props.backLabel,
onClick: () => router.push(props.backHref),
},
])
const loaderLabel = computed(() => {
if (!props.loader) return null
const label = formatLoaderLabel(props.loader.toLowerCase())
return [label, props.loaderVersion].filter(Boolean).join(' ')
})
const headerMetadata = computed<MetadataItem[]>(() => {
if (props.metadataItems.length) return props.metadataItems
const items: MetadataItem[] = []
if (props.gameVersion) {
items.push({
id: 'game-version',
label: props.gameVersion,
icon: Gamepad2Icon,
})
}
if (props.loader && loaderLabel.value) {
items.push({
id: 'loader',
label: loaderLabel.value,
icon: LoaderIcon,
iconProps: {
loader: formatLoaderLabel(props.loader.toLowerCase()),
},
})
}
if (props.lastActive) {
items.push({
id: 'last-active',
label: props.lastActive,
icon: TimerIcon,
})
}
return items
})
</script>
@@ -1,3 +1,3 @@
export { default as PanelServerActionButton } from './PanelServerActionButton.vue'
export { default as PanelServerOverflowMenu } from './PanelServerOverflowMenu.vue'
export { default as ServerManageHeader } from './ServerManageHeader.vue'
export { default as WorldManageHeader } from './WorldManageHeader.vue'
@@ -1,3 +1,4 @@
import type { Archon } from '@modrinth/api-client'
import { computed, type Ref } from 'vue'
import { useVIntl } from '#ui/composables/i18n'
@@ -7,7 +8,7 @@ import {
injectNotificationManager,
} from '#ui/providers'
export type PowerAction = 'Start' | 'Stop' | 'Restart' | 'Kill'
export type PowerAction = Archon.Servers.v0.PowerAction
export function useServerPowerAction(options?: { disabled?: Ref<boolean> }) {
const { formatMessage } = useVIntl()
+5 -5
View File
@@ -10,15 +10,15 @@ export * from './i18n'
export * from './i18n-debug'
export * from './page-leave-safety'
export * from './scroll-indicator'
export * from './server-backup'
export * from './server-backups-queue'
export * from './server-console'
export * from './server-manage-core-runtime'
export * from './servers/server-backup'
export * from './servers/server-backups-queue'
export * from './servers/server-console'
export * from './servers/server-manage-core-runtime'
export * from './servers/use-server-image'
export * from './sticky-observer'
export * from './terminal'
export * from './use-loading-bar-token'
export * from './use-loading-state-core'
export * from './use-ready-state'
export * from './use-server-image'
export * from './use-server-project'
export * from './virtual-scroll'
@@ -1,7 +1,7 @@
import type { Archon } from '@modrinth/api-client'
import { injectModrinthClient } from '../providers/api-client'
import { injectNotificationManager } from '../providers/web-notifications'
import { injectModrinthClient } from '../../providers/api-client'
import { injectNotificationManager } from '../../providers/web-notifications'
export function useServerBackupDownload() {
const client = injectModrinthClient()
@@ -4,7 +4,7 @@ import { computed, reactive, type Ref } from 'vue'
import { type BusyReason, injectModrinthClient } from '#ui/providers'
import { defineMessage } from './i18n'
import { defineMessage } from '../i18n'
type ProgressKey = `${string}:${'create' | 'restore'}`
@@ -12,7 +12,7 @@ export function useServerBackupsQueue(serverId: Ref<string>, worldId: Ref<string
const client = injectModrinthClient()
const queryClient = useQueryClient()
const queryKey = computed(() => ['backups', 'queue', serverId.value] as const)
const queryKey = computed(() => ['backups', 'queue', serverId.value, worldId.value] as const)
const progressOverlay = reactive(new Map<ProgressKey, number>())
const lastSeenState = new Map<ProgressKey, Archon.Websocket.v0.BackupState>()
@@ -1,8 +1,8 @@
import { createGlobalState } from '@vueuse/core'
import { type Ref, ref, shallowRef, triggerRef } from 'vue'
import { detectLogLevel } from '../layouts/shared/console/composables/log-level'
import type { Log4jEvent, LogLevel, LogLine } from '../layouts/shared/console/types'
import { detectLogLevel } from '../../layouts/shared/console/composables/log-level'
import type { Log4jEvent, LogLevel, LogLine } from '../../layouts/shared/console/types'
// Flip to true during development to enable console perf logging.
// Uses a plain constant to avoid turbo env-var declarations.
@@ -8,10 +8,10 @@ import type { Stats } from '@modrinth/utils'
import type { ComputedRef, Ref } from 'vue'
import { computed, ref } from 'vue'
import type { FileOperation } from '../layouts/shared/files-tab/types'
import { injectModrinthClient, provideModrinthServerContext } from '../providers'
import type { BusyReason, CancelUploadHandler } from '../providers/server-context'
import { defineMessage } from './i18n'
import type { FileOperation } from '../../layouts/shared/files-tab/types'
import { injectModrinthClient, provideModrinthServerContext } from '../../providers'
import type { BusyReason, CancelUploadHandler } from '../../providers/server-context'
import { defineMessage } from '../i18n'
import { useModrinthServersConsole } from './server-console'
type ReadableRef<T> = Ref<T> | ComputedRef<T>
@@ -5,6 +5,7 @@ import { computed, type ComputedRef, ref } from 'vue'
import { injectModrinthClient } from '#ui/providers'
type UpstreamRef = ComputedRef<Archon.Servers.v0.Server['upstream'] | null | undefined>
type ServerIdSource = string | { readonly value: string }
type UseServerImageOptions = {
enabled?: ComputedRef<boolean> | boolean
@@ -39,7 +40,7 @@ function isNotFound(error: unknown): boolean {
}
export function useServerImage(
serverId: string,
serverId: ServerIdSource,
upstream: UpstreamRef,
options: UseServerImageOptions = {},
) {
@@ -47,24 +48,33 @@ export function useServerImage(
const localImage = ref<string | null | undefined>(undefined)
const iconSize = options.size ?? 512
const includeProjectFallback = options.includeProjectFallback ?? false
const resolvedServerId = computed(() => resolveServerId(serverId))
const queryKey = computed(
() => ['servers', 'detail', serverId, 'icon', upstream.value?.project_id ?? null] as const,
() =>
[
'servers',
'detail',
resolvedServerId.value,
'icon',
upstream.value?.project_id ?? null,
] as const,
)
const isEnabled = computed(() => {
const explicitEnabled =
typeof options.enabled === 'boolean' ? options.enabled : options.enabled?.value
return !!serverId && (explicitEnabled ?? true)
return !!resolvedServerId.value && (explicitEnabled ?? true)
})
const { data: remoteImage, refetch } = useQuery({
queryKey,
queryFn: async (): Promise<string | null> => {
if (!serverId) return null
const id = resolvedServerId.value
if (!id) return null
try {
const fsAuth = await client.archon.servers_v0.getFilesystemAuth(serverId)
const fsAuth = await client.archon.servers_v0.getFilesystemAuth(id)
try {
const blob = await client.kyros.files_v0.downloadFileWithAuth(fsAuth, '/server-icon.png')
@@ -132,3 +142,7 @@ export function useServerImage(
resetLocalOverride,
}
}
function resolveServerId(serverId: ServerIdSource): string {
return typeof serverId === 'string' ? serverId : serverId.value
}
@@ -3,7 +3,6 @@ import type { ComputedRef, Ref, ShallowRef } from 'vue'
import { computed, nextTick, ref, shallowRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDebugLogger } from '#ui/composables/debug-logger'
import type { FilterType, FilterValue, ProjectType, SortType } from '#ui/utils/search'
import { LOADER_FILTER_TYPES, useSearch } from '#ui/utils/search'
import { useServerSearch } from '#ui/utils/server-search'
@@ -18,6 +17,7 @@ export interface UseBrowseSearchOptions {
categories: Labrinth.Tags.v2.Category[]
}>
providedFilters?: ComputedRef<FilterValue[]>
active?: ComputedRef<boolean>
search: (params: string) => Promise<BrowseSearchResponse>
persistentQueryParams: string[]
getExtraQueryParams?: () => Record<string, string | undefined>
@@ -61,12 +61,10 @@ export interface BrowseSearchState {
}
export function useBrowseSearch(options: UseBrowseSearchOptions): BrowseSearchState {
const debug = useDebugLogger('BrowseSearch')
const route = useRoute()
const router = useRouter()
debug('init, projectType:', options.projectType.value)
const active = computed(() => options.active?.value ?? true)
const projectTypes = computed(() => [options.projectType.value] as ProjectType[])
const isServerType = computed(() => options.projectType.value === 'server')
@@ -172,6 +170,13 @@ export function useBrowseSearch(options: UseBrowseSearchOptions): BrowseSearchSt
let searchVersion = 0
let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null
function clearSearchDebounce() {
if (searchDebounceTimer) {
clearTimeout(searchDebounceTimer)
searchDebounceTimer = null
}
}
const providedFiltersOrEmpty = computed(() => options.providedFilters?.value ?? [])
watch(
@@ -192,24 +197,29 @@ export function useBrowseSearch(options: UseBrowseSearchOptions): BrowseSearchSt
{ deep: true },
)
watch(effectiveRequestParams, (newVal, oldVal) => {
debug('effectiveRequestParams changed', {
from: oldVal?.substring(0, 80),
to: newVal?.substring(0, 80),
})
if (searchDebounceTimer) clearTimeout(searchDebounceTimer)
watch(effectiveRequestParams, () => {
clearSearchDebounce()
if (!active.value) {
return
}
searchDebounceTimer = setTimeout(() => {
refreshSearch()
}, 200)
})
watch(active, (isActive, wasActive) => {
clearSearchDebounce()
if (isActive && wasActive === false) {
void refreshSearch()
}
})
async function refreshSearch() {
if (!active.value) {
return
}
const version = ++searchVersion
debug('refreshSearch start', {
version,
projectType: options.projectType.value,
params: effectiveRequestParams.value.substring(0, 100),
})
const currentHitsEmpty = isServerType.value
? serverHits.value.length === 0
@@ -221,8 +231,11 @@ export function useBrowseSearch(options: UseBrowseSearchOptions): BrowseSearchSt
try {
const response = await options.search(effectiveRequestParams.value)
if (!active.value) {
return
}
if (version !== searchVersion) {
debug('refreshSearch stale, discarding', { version, current: searchVersion })
return
}
@@ -232,17 +245,10 @@ export function useBrowseSearch(options: UseBrowseSearchOptions): BrowseSearchSt
projectHits.value = response.projectHits
}
totalHits.value = response.total_hits
debug('refreshSearch complete', {
version,
hits: response.total_hits,
projectHits: response.projectHits.length,
serverHits: response.serverHits.length,
})
updateUrlParams()
loading.value = false
} catch (err) {
debug('refreshSearch error', err)
console.error('Browse search error:', err)
if (version === searchVersion) {
loading.value = false
@@ -251,7 +257,9 @@ export function useBrowseSearch(options: UseBrowseSearchOptions): BrowseSearchSt
}
function updateUrlParams() {
debug('updateUrlParams', { path: route.path })
if (!active.value) {
return
}
const persistentParams: Record<string, string | (string | null)[] | null | undefined> = {}
for (const [key, value] of Object.entries(route.query)) {
@@ -292,8 +300,7 @@ export function useBrowseSearch(options: UseBrowseSearchOptions): BrowseSearchSt
watch(
() => options.projectType.value,
(newType, oldType) => {
debug('projectType changed', { from: oldType, to: newType })
() => {
effectiveCurrentSortType.value =
effectiveSortTypes.value.find((sortType) => sortType.name === 'relevance') ??
effectiveSortTypes.value[0]
@@ -1,12 +1,12 @@
<script setup lang="ts">
import { LeftArrowIcon } from '@modrinth/assets'
import { LeftArrowIcon, TagCategoryGamepad2Icon as Gamepad2Icon } from '@modrinth/assets'
import type { Component } from 'vue'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import Admonition from '#ui/components/base/Admonition.vue'
import Avatar from '#ui/components/base/Avatar.vue'
import ButtonStyled from '#ui/components/base/ButtonStyled.vue'
import { useServerImage } from '#ui/composables/use-server-image'
import PageHeader from '#ui/components/base/PageHeader.vue'
import LoaderIcon from '#ui/components/servers/icons/LoaderIcon.vue'
import { useServerImage } from '#ui/composables/servers/use-server-image.ts'
import { formatLoaderLabel } from '#ui/utils/loaders'
import SelectedProjectsLeaveModal from './components/SelectedProjectsLeaveModal.vue'
@@ -18,8 +18,17 @@ const MEDAL_ICON_URL = 'https://cdn-raw.modrinth.com/medal_icon.webp'
const router = useRouter()
const props = defineProps<{
installContext?: BrowseInstallContext | null
divider?: boolean
bottomPadding?: boolean
}>()
type SelectedProjectsLeaveResult = 'cancel' | 'discard' | 'install'
type BrowseHeaderMetadataItem = {
id: string
label: string
icon?: Component
iconProps?: Record<string, unknown>
class?: string
}
const ctx = injectBrowseManager(null)
const installContext = computed(() => props.installContext ?? ctx?.installContext?.value ?? null)
@@ -37,14 +46,66 @@ const iconSrc = computed(() => {
return fetchedIcon.value ?? installContext.value?.iconSrc ?? null
})
const leadingItems = computed(() => {
const context = installContext.value
if (!context) return []
return [
{
id: 'back',
type: 'button' as const,
icon: LeftArrowIcon,
ariaLabel: context.backLabel,
tooltip: context.backLabel,
onClick: handleBack,
},
...(iconSrc.value
? [
{
id: 'icon',
type: 'avatar' as const,
src: iconSrc.value,
alt: context.name,
avatarSize: '48px',
class: 'shrink-0',
},
]
: []),
]
})
const metadataItems = computed(() => {
const context = installContext.value
if (!context) return []
return [
context.heading,
context.gameVersion ? `MC ${context.gameVersion}` : '',
context.loader ? formatLoaderLabel(context.loader) : '',
].filter(Boolean)
const items: BrowseHeaderMetadataItem[] = []
if (context.heading) {
items.push({
id: 'heading',
label: context.heading,
class: '!text-primary',
})
}
if (context.gameVersion) {
items.push({
id: 'game-version',
label: context.gameVersion,
icon: Gamepad2Icon,
class: '!text-primary',
})
}
if (context.loader) {
const loaderName = formatLoaderLabel(context.loader)
const loaderLabel = [loaderName, context.loaderVersion].filter(Boolean).join(' ')
items.push({
id: 'loader',
label: loaderLabel,
icon: LoaderIcon,
iconProps: { loader: loaderName },
class: '!text-primary',
})
}
return items
})
const selectedCount = computed(() => installContext.value?.selectedProjects?.length ?? 0)
@@ -94,39 +155,15 @@ async function handleSelectedProjectsLeaveResult(
:count="selectedCount"
:installing="isInstallingSelected"
/>
<div class="flex flex-col gap-2">
<div class="flex flex-wrap items-center justify-between gap-4">
<div class="flex min-w-0 items-center gap-4">
<ButtonStyled circular size="large">
<button :aria-label="installContext.backLabel" @click="handleBack">
<LeftArrowIcon />
</button>
</ButtonStyled>
<Avatar v-if="iconSrc" :src="iconSrc" size="48px" class="shrink-0" />
<div class="flex min-w-0 flex-col justify-center gap-1">
<h1 class="m-0 truncate text-2xl font-semibold leading-8 text-contrast">
{{ installContext.name }}
</h1>
<div
v-if="metadataItems.length"
class="flex flex-wrap items-center gap-2 text-base font-medium leading-6 text-primary"
>
<template v-for="(item, index) in metadataItems" :key="item">
<span
v-if="index > 0"
class="h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-60"
/>
<span>{{ item }}</span>
</template>
</div>
</div>
</div>
</div>
</div>
<Admonition v-if="installContext.warning" type="warning" class="mb-1">
{{ installContext.warning }}
</Admonition>
<PageHeader
:header="installContext.name"
:leading="leadingItems"
:metadata="metadataItems"
:divider="props.divider ?? false"
:bottom-padding="props.bottomPadding ?? false"
main-class="items-center"
title-class="leading-8"
truncate-title
/>
</template>
</template>
@@ -1,8 +1,9 @@
<script setup lang="ts">
import type { Labrinth } from '@modrinth/api-client'
import { SearchIcon } from '@modrinth/assets'
import { computed, ref, toValue } from 'vue'
import { computed, toValue } from 'vue'
import Admonition from '#ui/components/base/Admonition.vue'
import ButtonStyled from '#ui/components/base/ButtonStyled.vue'
import Combobox, { type ComboboxOption } from '#ui/components/base/Combobox.vue'
import LoadingIndicator from '#ui/components/base/LoadingIndicator.vue'
@@ -13,22 +14,15 @@ import ProjectCard from '#ui/components/project/card/ProjectCard.vue'
import ProjectCardList from '#ui/components/project/ProjectCardList.vue'
import SearchFilterControl from '#ui/components/search/SearchFilterControl.vue'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import { useStickyObserver } from '#ui/composables/sticky-observer'
import { commonMessages } from '#ui/utils/common-messages'
import type { SortType } from '#ui/utils/search'
import SelectedProjectsFloatingBar from './components/SelectedProjectsFloatingBar.vue'
import BrowseInstallHeader from './header.vue'
import { injectBrowseManager } from './providers/browse-manager'
const ctx = injectBrowseManager()
const { formatMessage } = useVIntl()
const lockedMessages = computed(() => toValue(ctx.lockedFilterMessages))
const stickyInstallHeaderRef = ref<HTMLElement | null>(null)
const { isStuck: isInstallHeaderStuck } = useStickyObserver(
stickyInstallHeaderRef,
'BrowseInstallHeader',
)
const installWarning = computed(() => ctx.installContext?.value?.warning)
const sortOptions = computed<ComboboxOption<SortType>[]>(() =>
ctx.effectiveSortTypes.value.map((st) => ({
@@ -70,16 +64,9 @@ const messages = defineMessages({
</script>
<template>
<template v-if="ctx.installContext?.value && ctx.variant !== 'web'">
<div
ref="stickyInstallHeaderRef"
class="sticky top-0 z-20 -mx-6 -mt-6 rounded-tl-[--radius-xl] border-0 border-b border-solid bg-surface-1 p-3 border-surface-5"
:class="[isInstallHeaderStuck ? 'border-t' : '']"
>
<BrowseInstallHeader />
</div>
</template>
<SelectedProjectsFloatingBar v-if="ctx.installContext?.value && ctx.variant !== 'web'" />
<Admonition v-if="installWarning" type="warning">
{{ installWarning }}
</Admonition>
<NavTabs v-if="ctx.showProjectTypeTabs.value" :links="ctx.selectableProjectTypes.value" />
@@ -21,6 +21,7 @@ export interface BrowseSelectedProject {
export interface BrowseInstallContext {
name: string
loader: string
loaderVersion?: string | null
gameVersion: string
serverId?: string | null
upstream?: { project_id?: string | null } | null
@@ -2,7 +2,7 @@ import { useSessionStorage } from '@vueuse/core'
import type { Ref } from 'vue'
import { computed, ref, watch } from 'vue'
import { useVIntl } from '#ui/composables/i18n'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import { commonProjectTypeCategoryMessages, normalizeProjectType } from '#ui/utils/common-messages'
import type { ClientWarningType, ContentItem } from '../types'
@@ -33,6 +33,25 @@ export interface ContentFilterConfig {
persistKey?: string
}
const messages = defineMessages({
updates: {
id: 'content.filter.updates',
defaultMessage: 'Updates',
},
warnings: {
id: 'content.filter.warnings',
defaultMessage: 'Warnings',
},
enabled: {
id: 'content.filter.enabled',
defaultMessage: 'Enabled',
},
disabled: {
id: 'content.filter.disabled',
defaultMessage: 'Disabled',
},
})
export function useContentFilters(items: Ref<ContentItem[]>, config?: ContentFilterConfig) {
const { formatMessage } = useVIntl()
@@ -40,6 +59,13 @@ export function useContentFilters(items: Ref<ContentItem[]>, config?: ContentFil
? useSessionStorage<string[]>(`content-filters:${config.persistKey}`, [])
: ref<string[]>([])
const availableStatusFilters = computed<Array<'enabled' | 'disabled'>>(() => {
const hasEnabledContent = items.value.some((m) => m.enabled)
const hasDisabledContent = items.value.some((m) => !m.enabled)
return hasEnabledContent && hasDisabledContent ? ['enabled', 'disabled'] : []
})
const filterOptions = computed<ContentFilterOption[]>(() => {
const options: ContentFilterOption[] = []
@@ -59,27 +85,48 @@ export function useContentFilters(items: Ref<ContentItem[]>, config?: ContentFil
}
if (config?.showUpdateFilter && items.value.some((m) => m.has_update)) {
options.push({ id: 'updates', label: 'Updates' })
options.push({ id: 'updates', label: formatMessage(messages.updates) })
}
if (config?.showWarningsFilter && items.value.some((m) => getClientWarningType(m) !== null)) {
options.push({ id: 'warnings', label: 'Warnings' })
options.push({ id: 'warnings', label: formatMessage(messages.warnings) })
}
if (items.value.some((m) => !m.enabled)) {
options.push({ id: 'disabled', label: 'Disabled' })
for (const status of availableStatusFilters.value) {
options.push({
id: status,
label: formatMessage(status === 'enabled' ? messages.enabled : messages.disabled),
})
}
return options
})
watch(filterOptions, () => {
selectedFilters.value = selectedFilters.value.filter((f) =>
filterOptions.value.some((opt) => opt.id === f),
)
})
watch(
filterOptions,
() => {
selectedFilters.value = selectedFilters.value.filter((f) =>
filterOptions.value.some((opt) => opt.id === f),
)
},
{ immediate: true },
)
function toggleFilter(filterId: string) {
if (filterId === 'enabled' || filterId === 'disabled') {
const index = selectedFilters.value.indexOf(filterId)
const otherStatusFilter = filterId === 'enabled' ? 'disabled' : 'enabled'
if (index === -1) {
selectedFilters.value = [
...selectedFilters.value.filter((filter) => filter !== otherStatusFilter),
filterId,
]
} else {
selectedFilters.value.splice(index, 1)
}
return
}
const index = selectedFilters.value.indexOf(filterId)
if (index === -1) {
selectedFilters.value.push(filterId)
@@ -91,7 +138,7 @@ export function useContentFilters(items: Ref<ContentItem[]>, config?: ContentFil
function applyFilters(source: ContentItem[]): ContentItem[] {
if (selectedFilters.value.length === 0) return source
const attributeFilters = new Set(['updates', 'disabled', 'warnings'])
const attributeFilters = new Set(['updates', 'enabled', 'disabled', 'warnings'])
const typeFilters = selectedFilters.value.filter((f) => !attributeFilters.has(f))
const activeAttributes = selectedFilters.value.filter((f) => attributeFilters.has(f))
@@ -105,6 +152,7 @@ export function useContentFilters(items: Ref<ContentItem[]>, config?: ContentFil
for (const filter of activeAttributes) {
if (filter === 'updates' && !item.has_update) return false
if (filter === 'enabled' && !item.enabled) return false
if (filter === 'disabled' && item.enabled) return false
if (filter === 'warnings' && getClientWarningType(item) === null) return false
}
@@ -1,7 +1,7 @@
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { useServerBackupsQueue } from '#ui/composables/server-backups-queue'
import { useServerBackupsQueue } from '#ui/composables/servers/server-backups-queue.ts'
import {
injectAppBackup,
injectModrinthClient,
@@ -206,18 +206,19 @@ const isInstalling = computed(() => {
})
const installationSettingsLayout = ref<InstanceType<typeof InstallationSettingsLayout>>()
const setupModal = ref<InstanceType<typeof ServerSetupModal>>()
const contentListQueryKey = computed(() => ['content', 'list', 'v1', serverId, worldId.value])
async function invalidateServerState() {
debug('invalidateServerState: starting')
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['servers', 'detail', serverId] }),
queryClient.invalidateQueries({ queryKey: ['content', 'list', 'v1', serverId] }),
queryClient.invalidateQueries({ queryKey: contentListQueryKey.value }),
])
debug('invalidateServerState: complete')
}
const addonsQuery = useQuery({
queryKey: computed(() => ['content', 'list', 'v1', serverId]),
queryKey: contentListQueryKey,
queryFn: () =>
client.archon.content_v1.getAddons(serverId, worldId.value!, { from_modpack: false }),
enabled: computed(() => worldId.value !== null),
@@ -628,7 +629,7 @@ provideInstallationSettings({
const previousData = addonsQuery.data.value
if (previousData) {
debug('unlinkModpack: optimistically removing modpack from cache')
queryClient.setQueryData(['content', 'list', 'v1', serverId], {
queryClient.setQueryData(contentListQueryKey.value, {
...previousData,
modpack: null,
})
@@ -640,7 +641,7 @@ provideInstallationSettings({
} catch (err) {
debug('unlinkModpack: failed, reverting cache', err)
if (previousData) {
queryClient.setQueryData(['content', 'list', 'v1', serverId], previousData)
queryClient.setQueryData(contentListQueryKey.value, previousData)
}
addNotification({
type: 'error',
@@ -653,7 +654,7 @@ provideInstallationSettings({
queryKey: ['servers', 'detail', serverId],
}),
queryClient.invalidateQueries({
queryKey: ['content', 'list', 'v1', serverId],
queryKey: contentListQueryKey.value,
}),
])
debug('unlinkModpack: invalidation complete')
@@ -284,8 +284,10 @@ const { addNotification } = injectNotificationManager()
const client = injectModrinthClient()
const { serverId, worldId, powerState, busyReasons } = injectModrinthServerContext()
const queryClient = useQueryClient()
const filesTabLink = computed(
() => `/hosting/manage/${encodeURIComponent(serverId)}/files?path=/&editing=server.properties`,
const filesTabLink = computed(() =>
worldId.value
? `/hosting/manage/${encodeURIComponent(serverId)}/instances/${encodeURIComponent(worldId.value)}/files?path=/&editing=server.properties`
: `/hosting/manage/${encodeURIComponent(serverId)}/instances`,
)
const serverSettings = injectServerSettings(null)
@@ -22,8 +22,8 @@
class="flex min-h-[calc(100vh-4rem)] items-center justify-center text-contrast"
>
<ErrorInformationCard
title="We're getting your server ready"
description="Your server's hardware is being prepared and will be available shortly!"
:title="formatMessage(messages.serverPreparingTitle)"
:description="formatMessage(messages.serverPreparingDescription)"
:icon="TransferIcon"
icon-color="blue"
:action="generalErrorAction"
@@ -34,8 +34,8 @@
class="flex min-h-[calc(100vh-4rem)] items-center justify-center text-contrast"
>
<ErrorInformationCard
title="Server upgrading"
description="Your server's hardware is currently being upgraded and will be back online shortly!"
:title="formatMessage(messages.serverUpgradingTitle)"
:description="formatMessage(messages.serverUpgradingDescription)"
:icon="TransferIcon"
icon-color="blue"
:action="generalErrorAction"
@@ -46,7 +46,7 @@
class="flex min-h-[calc(100vh-4rem)] items-center justify-center text-contrast"
>
<ErrorInformationCard
title="Server suspended"
:title="formatMessage(messages.serverSuspendedTitle)"
:description="suspendedDescription"
:icon="LockIcon"
icon-color="orange"
@@ -58,8 +58,8 @@
class="flex min-h-[calc(100vh-4rem)] items-center justify-center text-contrast"
>
<ErrorInformationCard
title="An error occured."
description="Please contact Modrinth Support."
:title="formatMessage(messages.generalErrorTitle)"
:description="formatMessage(messages.contactSupportDescription)"
:icon="TransferIcon"
icon-color="orange"
:error-details="generalErrorDetails"
@@ -71,7 +71,7 @@
class="flex min-h-[calc(100vh-4rem)] items-center justify-center text-contrast"
>
<ErrorInformationCard
title="Server Node Unavailable"
:title="formatMessage(messages.nodeUnavailableTitle)"
:icon="TriangleAlertIcon"
icon-color="red"
:action="nodeUnavailableAction"
@@ -80,22 +80,29 @@
<template #description>
<div class="text-md space-y-4">
<p class="leading-[170%] text-secondary">
Your server's node, where your Modrinth Server is physically hosted, is not accessible
at the moment. We are working to resolve the issue as quickly as possible.
{{ formatMessage(messages.nodeUnavailableDescription) }}
</p>
<p class="leading-[170%] text-secondary">
Your data is safe and will not be lost, and your server will be back online as soon as
the issue is resolved.
{{ formatMessage(messages.nodeUnavailableDataDescription) }}
</p>
<p class="leading-[170%] text-secondary">
If reloading does not work initially, please contact Modrinth Support via the chat
bubble in the bottom right corner and we'll be happy to help.
{{ formatMessage(messages.nodeUnavailableSupportDescription) }}
</p>
</div>
</template>
</ErrorInformationCard>
</div>
<!-- SERVER START -->
<div
v-else-if="serverData && isInstanceDetailRoute"
data-pyro-instance-manager-root
class="experimental-styles-within relative mx-auto box-border flex w-full min-w-0 flex-col px-6 transition-all duration-300"
:class="[
'server-panel-' + revealState,
isNuxt ? 'min-h-[100svh] max-w-[1280px] pb-16' : 'min-h-[calc(100svh-100px)] pb-6',
]"
>
<slot :on-reinstall="onReinstall" :on-reinstall-failed="onReinstallFailed" />
</div>
<div
v-else-if="serverData"
data-pyro-server-manager-root
@@ -118,61 +125,18 @@
:server="serverData"
:server-image="serverImage"
:server-project="serverProject"
:active-world-name="activeWorldName"
:uptime-seconds="showUptime ? uptimeSeconds : undefined"
>
<template #actions>
<div class="flex gap-2">
<PanelServerActionButton :disabled="!!installError" />
<Tooltip
theme="dismissable-prompt"
:triggers="[]"
:shown="showSettingsHint"
:auto-hide="false"
placement="bottom-end"
>
<ButtonStyled circular size="large">
<button
v-tooltip="showSettingsHint ? undefined : 'Server settings'"
@click="
() => {
openServerSettingsModal()
dismissSettingsHint()
}
"
>
<SettingsIcon />
</button>
</ButtonStyled>
<template #popper>
<div class="grid grid-cols-[min-content] gap-1">
<div class="flex min-w-48 items-center justify-between gap-8">
<h3 class="m-0 whitespace-nowrap text-base font-bold text-contrast">
{{ formatMessage(settingsHintMessages.title) }}
</h3>
<ButtonStyled size="small" circular>
<button
v-tooltip="formatMessage(settingsHintMessages.dismiss)"
@click="dismissSettingsHint"
>
<XIcon aria-hidden="true" />
</button>
</ButtonStyled>
</div>
<p class="m-0 text-wrap text-sm font-medium leading-tight text-secondary">
{{ formatMessage(settingsHintMessages.description) }}
</p>
</div>
</template>
</Tooltip>
<PanelServerOverflowMenu
:disabled="!!installError"
:uptime-seconds="uptimeSeconds"
:show-copy-id-action="showCopyIdAction"
:show-debug-info="showAdvancedDebugInfo"
/>
</div>
</template>
</ServerManageHeader>
:worlds="serverFull?.worlds ?? []"
:power-disabled="!!installError"
:settings-label="formatMessage(messages.serverSettings)"
:show-settings-hint="showSettingsHint"
:settings-hint-title="formatMessage(settingsHintMessages.title)"
:settings-hint-description="formatMessage(settingsHintMessages.description)"
:settings-hint-dismiss-label="formatMessage(settingsHintMessages.dismiss)"
@open-settings="openServerSettingsModal()"
@dismiss-settings-hint="dismissSettingsHint"
/>
<ServerOnboardingPanelPage v-if="isOnboarding" :browse-modpacks="handleBrowseModpacks" />
@@ -199,70 +163,59 @@
<div class="flex flex-col gap-2 leading-[150%]">
<div class="flex items-center gap-3">
<IssuesIcon class="flex h-8 w-8 shrink-0 text-red sm:hidden" />
<div class="flex gap-2 text-2xl font-bold">{{ errorTitle }}</div>
<div class="flex gap-2 text-2xl font-bold">{{ errorTitleLabel }}</div>
</div>
<div
v-if="errorTitle.toLocaleLowerCase() === 'installation error'"
class="font-normal"
>
<div v-if="errorTitle === 'installation'" class="font-normal">
<div
v-if="
errorMessage.toLocaleLowerCase() === 'the specified version may be incorrect'
"
>
An invalid loader or Minecraft version was specified and could not be installed.
{{ formatMessage(messages.installInvalidVersionDescription) }}
<ul class="m-0 mt-4 p-0 pl-4">
<li>
If this version of Minecraft was released recently, please check if Modrinth
Hosting supports it.
{{ formatMessage(messages.installRecentMinecraftVersionNotice) }}
</li>
<li>
If you've installed a modpack, it may have been packaged incorrectly or may
not be compatible with the loader.
{{ formatMessage(messages.installModpackCompatibilityNotice) }}
</li>
<li>
Your server may need to be reinstalled with a valid mod loader and version.
You can change the loader by clicking the "Change Loader" button.
{{ formatMessage(messages.installChangeLoaderNotice) }}
</li>
<li>
If you're stuck, please contact Modrinth Support with the information below:
{{ formatMessage(messages.installSupportNotice) }}
</li>
</ul>
<ButtonStyled>
<button class="mt-2" @click="copyServerDebugInfo">
<CopyIcon v-if="!copied" />
<CheckIcon v-else />
Copy Debug Info
{{ formatMessage(messages.copyDebugInfo) }}
</button>
</ButtonStyled>
</div>
<div v-if="errorMessage.toLocaleLowerCase() === 'internal error'">
An internal error occurred while installing your server. Don't fret try
reinstalling your server, and if the problem persists, please contact Modrinth
support with your server's debug information.
{{ formatMessage(messages.installInternalErrorDescription) }}
</div>
<div
v-if="errorMessage.toLocaleLowerCase() === 'this version is not yet supported'"
>
An error occurred while installing your server because Modrinth Hosting does not
support the version of Minecraft or the loader you specified. Try reinstalling
your server with a different version or loader, and if the problem persists,
please contact Modrinth Support with your server's debug information.
{{ formatMessage(messages.installUnsupportedVersionDescription) }}
</div>
<div
v-if="errorTitle === 'Installation error'"
class="mt-2 flex flex-col gap-4 sm:flex-row"
>
<div class="mt-2 flex flex-col gap-4 sm:flex-row">
<ButtonStyled v-if="errorLog">
<button @click="openInstallLog"><FileIcon />Open Installation Log</button>
<button @click="openInstallLog">
<FileIcon />
{{ formatMessage(messages.openInstallationLog) }}
</button>
</ButtonStyled>
<ButtonStyled>
<button @click="copyServerDebugInfo">
<CopyIcon v-if="!copied" />
<CheckIcon v-else />
Copy Debug Info
{{ formatMessage(messages.copyDebugInfo) }}
</button>
</ButtonStyled>
<ButtonStyled color="red" type="standard">
@@ -271,7 +224,7 @@
@click="openServerSettingsModal('installation')"
>
<RightArrowIcon />
Change Loader
{{ formatMessage(messages.changeLoader) }}
</button>
</ButtonStyled>
</div>
@@ -295,7 +248,7 @@
class="mb-4 flex w-full flex-row items-center gap-4 rounded-2xl bg-bg-red p-4 text-contrast"
>
<IssuesIcon class="size-5 text-red" />
Something went wrong...
{{ formatMessage(messages.websocketError) }}
</div>
<div
@@ -304,7 +257,7 @@
class="mb-4 flex w-full flex-row items-center gap-4 rounded-2xl bg-bg-orange p-4 text-sm text-contrast"
>
<LoaderCircleIcon class="h-5 w-5 animate-spin" />
Hang on, we're reconnecting to your server.
{{ formatMessage(messages.websocketReconnecting) }}
</div>
<ServerPanelAdmonitions
@@ -319,10 +272,12 @@
</template>
</div>
<div
v-if="showAdvancedDebugInfo"
class="relative mx-auto mt-6 box-border w-full min-w-0 max-w-[1280px] px-6"
v-if="showAdvancedDebugInfo && !isInstanceDetailRoute"
class="experimental-styles-within relative mx-auto mt-6 box-border w-full min-w-0 max-w-[1280px] px-6"
>
<h2 class="m-0 text-lg font-extrabold text-contrast">Server data</h2>
<h2 class="m-0 text-lg font-extrabold text-contrast">
{{ formatMessage(messages.serverDataTitle) }}
</h2>
<pre class="markdown-body w-full overflow-auto rounded-2xl bg-bg-raised p-4 text-sm">{{
safeStringify(serverData)
}}</pre>
@@ -346,27 +301,22 @@
import type { Archon, Labrinth } from '@modrinth/api-client'
import { ModrinthApiError, NuxtModrinthClient } from '@modrinth/api-client'
import {
BoxesIcon,
CheckIcon,
CopyIcon,
DatabaseBackupIcon,
FileIcon,
FolderOpenIcon,
GlobeIcon,
IssuesIcon,
LayoutTemplateIcon,
LoaderCircleIcon,
LockIcon,
RightArrowIcon,
SettingsIcon,
TransferIcon,
TriangleAlertIcon,
XIcon,
} from '@modrinth/assets'
import type { Stats } from '@modrinth/utils'
import { useQuery, useQueryClient } from '@tanstack/vue-query'
import { useStorage, useTimeoutFn } from '@vueuse/core'
import DOMPurify from 'dompurify'
import { Tooltip } from 'floating-vue'
import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, ref, watch } from 'vue'
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
@@ -377,11 +327,7 @@ import ServerNotice from '#ui/components/base/ServerNotice.vue'
import ConfirmLeaveModal from '#ui/components/modal/ConfirmLeaveModal.vue'
import ServerPanelAdmonitions from '#ui/components/servers/admonitions/ServerPanelAdmonitions.vue'
import MedalServerCountdown from '#ui/components/servers/marketing/MedalServerCountdown.vue'
import {
PanelServerActionButton,
PanelServerOverflowMenu,
ServerManageHeader,
} from '#ui/components/servers/server-header'
import { ServerManageHeader } from '#ui/components/servers/server-header'
import ServerSettingsModal from '#ui/components/servers/ServerSettingsModal.vue'
import {
useDebugLogger,
@@ -392,8 +338,8 @@ import {
useServerProject,
} from '#ui/composables'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import { useServerBackupsQueue } from '#ui/composables/server-backups-queue'
import { useServerManageCoreRuntime } from '#ui/composables/server-manage-core-runtime'
import { useServerBackupsQueue } from '#ui/composables/servers/server-backups-queue.ts'
import { useServerManageCoreRuntime } from '#ui/composables/servers/server-manage-core-runtime.ts'
import type { LogLine } from '#ui/layouts/shared/console'
import type { ServerSettingsTabId } from '#ui/layouts/shared/server-settings'
import {
@@ -408,13 +354,21 @@ import {
writePendingServerContentInstalls,
} from '#ui/utils/server-content-installing'
import ServerOnboardingPanelPage from './[id]/onboarding.vue'
import ServerOnboardingPanelPage from './onboarding.vue'
interface Tab {
label: string
href: string
icon?: object
subpages?: string[]
prompt?: {
title: string
description: string
dismissLabel?: string
shown?: boolean
placement?: string
onDismiss?: () => void
}
}
const props = withDefaults(
@@ -422,7 +376,6 @@ const props = withDefaults(
serverId: string
reloadPage: () => void
resolveViewer: () => Promise<{ userId: string | null; userRole: string | null }>
showCopyIdAction?: boolean
showAdvancedDebugInfo?: boolean
showUptime?: boolean
additionalTabs?: Tab[]
@@ -444,7 +397,6 @@ const props = withDefaults(
}) => void | Promise<void>
}>(),
{
showCopyIdAction: false,
showAdvancedDebugInfo: false,
showUptime: true,
additionalTabs: () => [],
@@ -487,6 +439,230 @@ const settingsHintMessages = defineMessages({
},
})
const instancesHintMessages = defineMessages({
title: {
id: 'servers.manage.instances-hint.title',
defaultMessage: 'New: Server Instances!',
},
description: {
id: 'servers.manage.instances-hint.description',
defaultMessage: 'Your server state has been converted into an instance.',
},
dismiss: {
id: 'servers.manage.instances-hint.dismiss',
defaultMessage: "Don't show again",
},
})
const messages = defineMessages({
serverPreparingTitle: {
id: 'servers.manage.status.preparing.title',
defaultMessage: "We're getting your server ready",
},
serverPreparingDescription: {
id: 'servers.manage.status.preparing.description',
defaultMessage: "Your server's hardware is being prepared and will be available shortly!",
},
serverUpgradingTitle: {
id: 'servers.manage.status.upgrading.title',
defaultMessage: 'Server upgrading',
},
serverUpgradingDescription: {
id: 'servers.manage.status.upgrading.description',
defaultMessage:
"Your server's hardware is currently being upgraded and will be back online shortly!",
},
serverSuspendedTitle: {
id: 'servers.manage.status.suspended.title',
defaultMessage: 'Server suspended',
},
suspendedCancelledDescription: {
id: 'servers.manage.status.suspended.cancelled-description',
defaultMessage:
'Your subscription has been cancelled.\nContact Modrinth Support if you believe this is an error.',
},
suspendedReasonDescription: {
id: 'servers.manage.status.suspended.reason-description',
defaultMessage:
'Your server has been suspended: {reason}\nContact Modrinth Support if you believe this is an error.',
},
suspendedDescription: {
id: 'servers.manage.status.suspended.description',
defaultMessage:
'Your server has been suspended.\nContact Modrinth Support if you believe this is an error.',
},
generalErrorTitle: {
id: 'servers.manage.error.general.title',
defaultMessage: 'An error occurred.',
},
genericErrorMessage: {
id: 'servers.manage.error.general.message',
defaultMessage: 'An unexpected error occurred.',
},
contactSupportDescription: {
id: 'servers.manage.error.contact-support',
defaultMessage: 'Please contact Modrinth Support.',
},
nodeUnavailableTitle: {
id: 'servers.manage.error.node-unavailable.title',
defaultMessage: 'Server Node Unavailable',
},
nodeUnavailableDescription: {
id: 'servers.manage.error.node-unavailable.description',
defaultMessage:
"Your server's node, where your Modrinth Server is physically hosted, is not accessible at the moment. We are working to resolve the issue as quickly as possible.",
},
nodeUnavailableDataDescription: {
id: 'servers.manage.error.node-unavailable.data-description',
defaultMessage:
'Your data is safe and will not be lost, and your server will be back online as soon as the issue is resolved.',
},
nodeUnavailableSupportDescription: {
id: 'servers.manage.error.node-unavailable.support-description',
defaultMessage:
"If reloading does not work initially, please contact Modrinth Support via the chat bubble in the bottom right corner and we'll be happy to help.",
},
installInvalidVersionDescription: {
id: 'servers.manage.error.install.invalid-version.description',
defaultMessage:
'An invalid loader or Minecraft version was specified and could not be installed.',
},
installRecentMinecraftVersionNotice: {
id: 'servers.manage.error.install.invalid-version.recent-minecraft',
defaultMessage:
'If this version of Minecraft was released recently, please check if Modrinth Hosting supports it.',
},
installModpackCompatibilityNotice: {
id: 'servers.manage.error.install.invalid-version.modpack-compatibility',
defaultMessage:
"If you've installed a modpack, it may have been packaged incorrectly or may not be compatible with the loader.",
},
installChangeLoaderNotice: {
id: 'servers.manage.error.install.invalid-version.change-loader',
defaultMessage:
'Your server may need to be reinstalled with a valid mod loader and version. You can change the loader by clicking the "Change Loader" button.',
},
installSupportNotice: {
id: 'servers.manage.error.install.invalid-version.support',
defaultMessage: "If you're stuck, please contact Modrinth Support with the information below:",
},
installInternalErrorDescription: {
id: 'servers.manage.error.install.internal.description',
defaultMessage:
"An internal error occurred while installing your server. Don't fret - try reinstalling your server, and if the problem persists, please contact Modrinth support with your server's debug information.",
},
installUnsupportedVersionDescription: {
id: 'servers.manage.error.install.unsupported-version.description',
defaultMessage:
"An error occurred while installing your server because Modrinth Hosting does not support the version of Minecraft or the loader you specified. Try reinstalling your server with a different version or loader, and if the problem persists, please contact Modrinth Support with your server's debug information.",
},
installationErrorTitle: {
id: 'servers.manage.error.install.title',
defaultMessage: 'Installation error',
},
unknownError: {
id: 'servers.manage.error.unknown',
defaultMessage: 'Unknown error',
},
copyDebugInfo: {
id: 'servers.manage.error.copy-debug-info',
defaultMessage: 'Copy Debug Info',
},
openInstallationLog: {
id: 'servers.manage.error.open-installation-log',
defaultMessage: 'Open Installation Log',
},
changeLoader: {
id: 'servers.manage.error.change-loader',
defaultMessage: 'Change Loader',
},
websocketError: {
id: 'servers.manage.websocket.error',
defaultMessage: 'Something went wrong...',
},
websocketReconnecting: {
id: 'servers.manage.websocket.reconnecting',
defaultMessage: "Hang on, we're reconnecting to your server.",
},
serverDataTitle: {
id: 'servers.manage.debug.server-data',
defaultMessage: 'Server data',
},
serverSettings: {
id: 'servers.manage.server-settings',
defaultMessage: 'Server settings',
},
overviewNav: {
id: 'servers.manage.nav.overview',
defaultMessage: 'Overview',
},
instancesNav: {
id: 'servers.manage.nav.instances',
defaultMessage: 'Instances',
},
errorDismissingNotice: {
id: 'servers.manage.notice.dismiss-error',
defaultMessage: 'Error dismissing notice',
},
failedToRetryInstallation: {
id: 'servers.manage.install.retry-error',
defaultMessage: 'Failed to retry installation',
},
serverIdLabel: {
id: 'servers.manage.error-details.server-id',
defaultMessage: 'Server ID',
},
nodeLabel: {
id: 'servers.manage.error-details.node',
defaultMessage: 'Node',
},
errorMessageLabel: {
id: 'servers.manage.error-details.error-message',
defaultMessage: 'Error message',
},
timestampLabel: {
id: 'servers.manage.error-details.timestamp',
defaultMessage: 'Timestamp',
},
errorNameLabel: {
id: 'servers.manage.error-details.error-name',
defaultMessage: 'Error Name',
},
originalErrorLabel: {
id: 'servers.manage.error-details.original-error',
defaultMessage: 'Original Error',
},
stackTraceLabel: {
id: 'servers.manage.error-details.stack-trace',
defaultMessage: 'Stack Trace',
},
unknownLabel: {
id: 'servers.manage.error-details.unknown',
defaultMessage: 'Unknown',
},
nodePingFailed: {
id: 'servers.manage.error.node-ping-failed',
defaultMessage: 'Unable to reach node. Ping test failed.',
},
goToBillingSettings: {
id: 'servers.manage.action.go-to-billing-settings',
defaultMessage: 'Go to billing settings',
},
goBackToAllServers: {
id: 'servers.manage.action.go-back-to-all-servers',
defaultMessage: 'Go back to all servers',
},
reload: {
id: 'servers.manage.action.reload',
defaultMessage: 'Reload',
},
debugInfo: {
id: 'servers.manage.error.debug-info',
defaultMessage:
'Server ID: {serverId}\nError: {error}\nKind: {kind}\nProject ID: {projectId}\nVersion ID: {versionId}\nLog: {log}',
},
})
// disabled, keeping the animation logic cos it's really nice and we might want to re-enable in future
const DISABLE_LOADING_ANIM = true
@@ -503,8 +679,14 @@ const isLoading = ref(true)
const isMounted = ref(true)
const copied = ref(false)
const installError = ref<Error | null>(null)
const errorTitle = ref('Error')
const errorMessage = ref('An unexpected error occurred.')
type InstallErrorTitle = 'generic' | 'installation'
const errorTitle = ref<InstallErrorTitle>('generic')
const errorTitleLabel = computed(() =>
errorTitle.value === 'installation'
? formatMessage(messages.installationErrorTitle)
: formatMessage(messages.generalErrorTitle),
)
const errorMessage = ref(formatMessage(messages.genericErrorMessage))
const errorLog = ref('')
const errorLogFile = ref('')
const isOnboarding = computed(() => serverData.value?.flows?.intro)
@@ -517,6 +699,14 @@ function dismissSettingsHint() {
settingsHintDismissed.value = true
}
const INSTANCES_HINT_KEY = 'server-panel-instances-hint-dismissed'
const instancesHintDismissed = useStorage(INSTANCES_HINT_KEY, false)
const showInstancesHint = ref(!instancesHintDismissed.value)
function dismissInstancesHint() {
showInstancesHint.value = false
instancesHintDismissed.value = true
}
const serverSettingsModal = ref<InstanceType<typeof ServerSettingsModal> | null>(null)
const confirmLeaveModal = ref<InstanceType<typeof ConfirmLeaveModal>>()
@@ -550,12 +740,47 @@ const { data: serverFull } = useQuery({
queryFn: () => client.archon.servers_v1.get(props.serverId),
})
const routeInstanceId = ref<string | null>(getRouteParam(route.params.instance_id))
watch(
() => [route.path, route.params.id, route.params.instance_id, props.serverId] as const,
() => {
if (!isRouteForManagedServer()) return
routeInstanceId.value = getRouteParam(route.params.instance_id)
},
{ immediate: true },
)
const worldId = computed(() => {
if (routeInstanceId.value) return routeInstanceId.value
if (!serverFull.value) return null
const activeWorld = serverFull.value.worlds.find((w) => w.is_active)
return activeWorld?.id ?? serverFull.value.worlds[0]?.id ?? null
})
const isInstanceDetailRoute = computed(() => !!routeInstanceId.value)
const activeWorldName = computed(() => {
if (!serverFull.value) return null
const activeWorld = serverFull.value.worlds.find((world) => world.is_active)
return activeWorld?.name ?? serverFull.value.worlds[0]?.name ?? null
})
function isRouteForManagedServer() {
const routeServerId = getRouteParam(route.params.id)
if (!routeServerId || routeServerId !== props.serverId) return false
const basePath = `/hosting/manage/${encodeURIComponent(routeServerId)}`
return route.path === basePath || route.path.startsWith(`${basePath}/`)
}
function getRouteParam(param: string | string[] | undefined): string | null {
if (Array.isArray(param)) return param[0] ?? null
return param ?? null
}
function getWorldPath(targetWorldId: string) {
return `/hosting/manage/${encodeURIComponent(props.serverId)}/instances/${encodeURIComponent(targetWorldId)}`
}
const { handleWsBackupProgress, busyReasons: backupsBusy } = useServerBackupsQueue(
computed(() => props.serverId),
worldId,
@@ -799,28 +1024,24 @@ watch(serverData, (data) => {
const navLinks = computed<Tab[]>(() => [
{
label: 'Overview',
href: `/hosting/manage/${props.serverId}`,
label: formatMessage(messages.overviewNav),
href: `/hosting/manage/${encodeURIComponent(props.serverId)}`,
icon: LayoutTemplateIcon,
subpages: [],
},
{
label: 'Content',
href: `/hosting/manage/${props.serverId}/content`,
icon: BoxesIcon,
subpages: ['mods', 'datapacks'],
},
{
label: 'Files',
href: `/hosting/manage/${props.serverId}/files`,
icon: FolderOpenIcon,
subpages: [],
},
{
label: 'Backups',
href: `/hosting/manage/${props.serverId}/backups`,
icon: DatabaseBackupIcon,
label: formatMessage(messages.instancesNav),
href: `/hosting/manage/${encodeURIComponent(props.serverId)}/instances`,
icon: GlobeIcon,
subpages: [],
prompt: {
title: formatMessage(instancesHintMessages.title),
description: formatMessage(instancesHintMessages.description),
dismissLabel: formatMessage(instancesHintMessages.dismiss),
shown: showInstancesHint.value,
placement: 'bottom',
onDismiss: dismissInstancesHint,
},
},
...props.additionalTabs,
])
@@ -833,7 +1054,7 @@ const surveyNotice = computed(() => serverData.value?.notices?.find((n) => n.lev
async function dismissNotice(noticeId: number) {
await client.archon.servers_v0.dismissNotice(props.serverId, noticeId).catch((err) => {
addNotification({
title: 'Error dismissing notice',
title: formatMessage(messages.errorDismissingNotice),
text: err,
type: 'error',
})
@@ -937,7 +1158,7 @@ async function handleContentRetry() {
} catch (err) {
addNotification({
type: 'error',
text: err instanceof Error ? err.message : 'Failed to retry installation',
text: err instanceof Error ? err.message : formatMessage(messages.failedToRetryInstallation),
})
}
}
@@ -968,7 +1189,7 @@ const handleFilesystemOps = (data: Archon.Websocket.v0.WSFilesystemOpsEvent) =>
}
const handleNewMod = () => {
queryClient.invalidateQueries({ queryKey: ['content', 'list'] })
queryClient.invalidateQueries({ queryKey: ['content', 'list', 'v1', props.serverId] })
}
const handleInstallationResult = async (data: Archon.Websocket.v0.WSInstallationResultEvent) => {
@@ -987,9 +1208,9 @@ const handleInstallationResult = async (data: Archon.Websocket.v0.WSInstallation
case 'err': {
console.log('failed to install')
console.log(data)
errorTitle.value = 'Installation error'
errorMessage.value = data.reason ?? 'Unknown error'
installError.value = new Error(data.reason ?? 'Unknown error')
errorTitle.value = 'installation'
errorMessage.value = data.reason ?? formatMessage(messages.unknownError)
installError.value = new Error(errorMessage.value)
try {
let files = await client.kyros.files_v0.listDirectory('/', 1, 100)
@@ -1047,14 +1268,14 @@ const onReinstall = async (
}
installError.value = null
errorTitle.value = 'Error'
errorMessage.value = 'An unexpected error occurred.'
errorTitle.value = 'generic'
errorMessage.value = formatMessage(messages.genericErrorMessage)
modrinthServersConsole.clear()
debug('[root.vue] onReinstall: triggering immediate invalidation')
queryClient.invalidateQueries({ queryKey: ['servers', 'detail', props.serverId] })
queryClient.invalidateQueries({ queryKey: ['content', 'list'] })
queryClient.invalidateQueries({ queryKey: ['content', 'list', 'v1', props.serverId] })
}
const onReinstallFailed = () => {
@@ -1103,7 +1324,7 @@ async function invalidateAfterInstall() {
queryClient.invalidateQueries({
queryKey: ['servers', 'startup', 'v1', props.serverId],
}),
queryClient.invalidateQueries({ queryKey: ['content', 'list'] }),
queryClient.invalidateQueries({ queryKey: ['content', 'list', 'v1', props.serverId] }),
])
} catch (err: unknown) {
console.error('Error refreshing data after installation:', err)
@@ -1117,62 +1338,64 @@ const nodeAccessible = ref(true)
const nodeUnavailableDetails = computed(() => [
{
label: 'Server ID',
label: formatMessage(messages.serverIdLabel),
value: props.serverId,
type: 'inline' as const,
},
{
label: 'Node',
label: formatMessage(messages.nodeLabel),
value:
(serverError.value?.responseData as { hostname?: string } | undefined)?.hostname ??
serverData.value?.datacenter ??
'Unknown',
formatMessage(messages.unknownLabel),
type: 'inline' as const,
},
{
label: 'Error message',
label: formatMessage(messages.errorMessageLabel),
value: nodeAccessible.value
? (serverError.value?.message ?? 'Unknown')
: 'Unable to reach node. Ping test failed.',
? (serverError.value?.message ?? formatMessage(messages.unknownLabel))
: formatMessage(messages.nodePingFailed),
type: 'block' as const,
},
])
const suspendedDescription = computed(() => {
if (serverData.value?.suspension_reason === 'cancelled') {
return 'Your subscription has been cancelled.\nContact Modrinth Support if you believe this is an error.'
return formatMessage(messages.suspendedCancelledDescription)
}
if (serverData.value?.suspension_reason) {
return `Your server has been suspended: ${serverData.value.suspension_reason}\nContact Modrinth Support if you believe this is an error.`
return formatMessage(messages.suspendedReasonDescription, {
reason: serverData.value.suspension_reason,
})
}
return 'Your server has been suspended.\nContact Modrinth Support if you believe this is an error.'
return formatMessage(messages.suspendedDescription)
})
const generalErrorDetails = computed(() => [
{
label: 'Server ID',
label: formatMessage(messages.serverIdLabel),
value: props.serverId,
type: 'inline' as const,
},
{
label: 'Timestamp',
label: formatMessage(messages.timestampLabel),
value: String(new Date().toISOString()),
type: 'inline' as const,
},
{
label: 'Error Name',
label: formatMessage(messages.errorNameLabel),
value: serverError.value?.name,
type: 'inline' as const,
},
{
label: 'Error Message',
label: formatMessage(messages.errorMessageLabel),
value: serverError.value?.message,
type: 'block' as const,
},
...(serverError.value?.originalError
? [
{
label: 'Original Error',
label: formatMessage(messages.originalErrorLabel),
value: String(serverError.value.originalError),
type: 'hidden' as const,
},
@@ -1181,7 +1404,7 @@ const generalErrorDetails = computed(() => [
...(serverError.value?.stack
? [
{
label: 'Stack Trace',
label: formatMessage(messages.stackTraceLabel),
value: serverError.value.stack,
type: 'hidden' as const,
},
@@ -1190,26 +1413,33 @@ const generalErrorDetails = computed(() => [
])
const suspendedAction = computed(() => ({
label: 'Go to billing settings',
label: formatMessage(messages.goToBillingSettings),
onClick: () => props.navigateToBilling?.(),
color: 'brand' as const,
}))
const generalErrorAction = computed(() => ({
label: 'Go back to all servers',
label: formatMessage(messages.goBackToAllServers),
onClick: () => props.navigateToServers?.(),
color: 'brand' as const,
}))
const nodeUnavailableAction = computed(() => ({
label: 'Reload',
label: formatMessage(messages.reload),
onClick: () => props.reloadPage(),
color: 'brand' as const,
disabled: false,
}))
const copyServerDebugInfo = () => {
const debugInfo = `Server ID: ${serverData.value?.server_id}\nError: ${errorMessage.value}\nKind: ${serverData.value?.upstream?.kind}\nProject ID: ${serverData.value?.upstream?.project_id}\nVersion ID: ${serverData.value?.upstream?.version_id}\nLog: ${errorLog.value}`
const debugInfo = formatMessage(messages.debugInfo, {
serverId: serverData.value?.server_id ?? '',
error: errorMessage.value,
kind: serverData.value?.upstream?.kind ?? '',
projectId: serverData.value?.upstream?.project_id ?? '',
versionId: serverData.value?.upstream?.version_id ?? '',
log: errorLog.value,
})
navigator.clipboard.writeText(debugInfo)
copied.value = true
setTimeout(() => {
@@ -1218,7 +1448,10 @@ const copyServerDebugInfo = () => {
}
const openInstallLog = () => {
const url = `/hosting/manage/${props.serverId}/files?editing=${encodeURIComponent(errorLogFile.value)}`
const filesPath = worldId.value
? `${getWorldPath(worldId.value)}/files`
: `/hosting/manage/${encodeURIComponent(props.serverId)}/instances`
const url = `${filesPath}?editing=${encodeURIComponent(errorLogFile.value)}`
window.history.pushState({}, '', url)
window.dispatchEvent(new PopStateEvent('popstate'))
}
@@ -245,7 +245,6 @@ import { useMutation, useQueryClient } from '@tanstack/vue-query'
import dayjs from 'dayjs'
import type { Component } from 'vue'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import ButtonStyled from '#ui/components/base/ButtonStyled.vue'
import Checkbox from '#ui/components/base/Checkbox.vue'
@@ -258,9 +257,9 @@ import BackupDeleteModal from '#ui/components/servers/backups/BackupDeleteModal.
import BackupItem from '#ui/components/servers/backups/BackupItem.vue'
import BackupRenameModal from '#ui/components/servers/backups/BackupRenameModal.vue'
import BackupRestoreModal from '#ui/components/servers/backups/BackupRestoreModal.vue'
import { useBackupsSelection } from '#ui/composables/hosting/backups-selection'
import { useBackupsSelection } from '#ui/composables/servers/backups-selection'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import { useServerBackupsQueue } from '#ui/composables/server-backups-queue'
import { useServerBackupsQueue } from '#ui/composables/servers/server-backups-queue.ts'
import { useBulkOperation } from '#ui/layouts/shared/content-tab/composables/bulk-operations'
import {
injectModrinthClient,
@@ -334,7 +333,7 @@ const filterPillOptions = computed<FilterPillOption[]>(() => [
])
const client = injectModrinthClient()
const queryClient = useQueryClient()
const { server, worldId, busyReasons } = injectModrinthServerContext()
const { server, serverId, worldId, busyReasons } = injectModrinthServerContext()
const props = defineProps<{
isServerRunning: boolean
@@ -342,9 +341,6 @@ const props = defineProps<{
showDebugInfo?: boolean
}>()
const route = useRoute()
const serverId = route.params.id as string
defineEmits(['onDownload'])
const { backups, invalidate, hasActiveCreate, hasActiveRestore, query } = useServerBackupsQueue(
@@ -358,7 +354,7 @@ const error = computed(() => {
})
const refetch = () => query.refetch()
/** Until world exists we cannot fetch; `isLoading` is false while the query is disabled, which would flash empty state. */
/** Until the instance exists we cannot fetch; `isLoading` is false while the query is disabled, which would flash empty state. */
const backupsReadyPending = computed(
() => !worldId.value || (query.data.value === undefined && !query.error.value),
)
@@ -4,11 +4,28 @@ import { ClipboardCopyIcon } from '@modrinth/assets'
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import { useIntervalFn } from '@vueuse/core'
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useRouter } from 'vue-router'
import ReadyTransition from '#ui/components/base/ReadyTransition.vue'
import { useUploadSessionUpload } from '#ui/composables/hosting/kyros-session-upload'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import {
flushStoredServerAddonInstallQueue,
getStoredServerAddonInstallQueue,
} from '#ui/layouts/shared/browse-tab/composables/install-logic'
import ConfirmModpackUpdateModal from '#ui/layouts/shared/content-tab/components/modals/ConfirmModpackUpdateModal.vue'
import ConfirmUnlinkModal from '#ui/layouts/shared/content-tab/components/modals/ConfirmUnlinkModal.vue'
import ContentUpdaterModal from '#ui/layouts/shared/content-tab/components/modals/ContentUpdaterModal.vue'
import ModpackContentModal from '#ui/layouts/shared/content-tab/components/modals/ModpackContentModal.vue'
import ContentPageLayout from '#ui/layouts/shared/content-tab/layout.vue'
import type { ContentModpackData } from '#ui/layouts/shared/content-tab/providers/content-manager'
import { provideContentManager } from '#ui/layouts/shared/content-tab/providers/content-manager'
import type {
ContentItem,
ContentModpackCardCategory,
ContentModpackCardProject,
ContentModpackCardVersion,
} from '#ui/layouts/shared/content-tab/types'
import {
injectModrinthClient,
injectModrinthServerContext,
@@ -25,24 +42,6 @@ import {
} from '#ui/utils/server-content-installing'
import { versionChangesGameVersion } from '#ui/utils/version-compatibility'
import {
flushStoredServerAddonInstallQueue,
getStoredServerAddonInstallQueue,
} from '../../../shared/browse-tab/composables/install-logic'
import ConfirmModpackUpdateModal from '../../../shared/content-tab/components/modals/ConfirmModpackUpdateModal.vue'
import ConfirmUnlinkModal from '../../../shared/content-tab/components/modals/ConfirmUnlinkModal.vue'
import ContentUpdaterModal from '../../../shared/content-tab/components/modals/ContentUpdaterModal.vue'
import ModpackContentModal from '../../../shared/content-tab/components/modals/ModpackContentModal.vue'
import ContentPageLayout from '../../../shared/content-tab/layout.vue'
import type { ContentModpackData } from '../../../shared/content-tab/providers/content-manager'
import { provideContentManager } from '../../../shared/content-tab/providers/content-manager'
import type {
ContentItem,
ContentModpackCardCategory,
ContentModpackCardProject,
ContentModpackCardVersion,
} from '../../../shared/content-tab/types'
type AddonWithUiState = Archon.Content.v1.Addon & { installing?: boolean }
type ContentOwnerAvatarSource = {
id: string
@@ -112,7 +111,7 @@ const messages = defineMessages({
})
const client = injectModrinthClient()
const { server, worldId, busyReasons, isSyncingContent, uploadState, cancelUpload } =
const { server, serverId, worldId, busyReasons, isSyncingContent, uploadState, cancelUpload } =
injectModrinthServerContext()
const contentUploadSession = useUploadSessionUpload({
client,
@@ -123,10 +122,8 @@ const contentUploadSession = useUploadSessionUpload({
})
const { addNotification } = injectNotificationManager()
const { openServerSettings, browseServerContent } = injectServerSettingsModal()
const route = useRoute()
const router = useRouter()
const queryClient = useQueryClient()
const serverId = route.params.id as string
const type = computed(() => {
const loader = server.value?.loader?.toLowerCase()
@@ -135,7 +132,7 @@ const type = computed(() => {
return 'mod'
})
const queryKey = computed(() => ['content', 'list', 'v1', serverId])
const queryKey = computed(() => ['content', 'list', 'v1', serverId, worldId.value])
function getContentOwnerAvatarUrl(owner: ContentOwnerAvatarSource) {
const ownerId = owner.type === 'user' ? owner.name || owner.id : owner.id
@@ -8,6 +8,8 @@ import ReadyTransition from '#ui/components/base/ReadyTransition.vue'
import { useReadyState } from '#ui/composables'
import { useUploadSessionUpload } from '#ui/composables/hosting/kyros-session-upload'
import { useVIntl } from '#ui/composables/i18n'
import type { EditingFile, FileItem } from '#ui/layouts/shared/files-tab/index.ts'
import { FilePageLayout, provideFileManager } from '#ui/layouts/shared/files-tab/index.ts'
import {
injectModrinthClient,
injectModrinthServerContext,
@@ -15,10 +17,6 @@ import {
} from '#ui/providers'
import { commonMessages } from '#ui/utils/common-messages'
import FilePageLayout from '../../../shared/files-tab/layout.vue'
import { provideFileManager } from '../../../shared/files-tab/providers/file-manager'
import type { EditingFile, FileItem } from '../../../shared/files-tab/types'
const props = defineProps<{
showDebugInfo?: boolean
showRefreshButton?: boolean
@@ -0,0 +1,302 @@
<template>
<div class="flex min-h-[36rem] flex-col gap-4 text-primary">
<WorldManageHeader
:name="worldName"
:game-version="gameVersion"
:loader="loader"
:loader-version="loaderVersion"
:last-active="lastActiveLabel"
:back-href="instancesPath"
:back-label="formatMessage(messages.allInstances)"
:fallback-name="formatMessage(messages.worldFallbackName)"
:actions="headerActions"
/>
<NavTabs :links="worldTabLinks" replace />
<slot />
</div>
</template>
<script setup lang="ts">
import type { Archon } from '@modrinth/api-client'
import {
BoxesIcon,
DatabaseBackupIcon,
FolderOpenIcon,
GlobeIcon,
LoaderCircleIcon,
PlayIcon,
Settings2Icon,
SlashIcon,
StopCircleIcon,
UpdatedIcon,
} from '@modrinth/assets'
import { useQuery } from '@tanstack/vue-query'
import { computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import type { JoinedButtonAction } from '#ui/components/base/JoinedButtons.vue'
import NavTabs from '#ui/components/base/NavTabs.vue'
import { WorldManageHeader } from '#ui/components/servers/server-header'
import { useServerPowerAction } from '#ui/components/servers/server-header/use-server-power-action'
import { useRelativeTime } from '#ui/composables'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import {
injectModrinthClient,
injectModrinthServerContext,
injectServerSettingsModal,
} from '#ui/providers'
interface Tab {
label: string
href: string
icon?: object
subpages?: string[]
}
const messages = defineMessages({
allInstances: {
id: 'servers.manage.instance.all-instances',
defaultMessage: 'All instances',
},
contentNav: {
id: 'servers.manage.nav.content',
defaultMessage: 'Content',
},
filesNav: {
id: 'servers.manage.nav.files',
defaultMessage: 'Files',
},
backupsNav: {
id: 'servers.manage.nav.backups',
defaultMessage: 'Backups',
},
worldFallbackName: {
id: 'servers.manage.instance.fallback-name',
defaultMessage: 'Instance',
},
lastActive: {
id: 'servers.manage.instance.last-active',
defaultMessage: 'Last active {time}',
},
instanceSettings: {
id: 'servers.manage.instance.settings',
defaultMessage: 'Instance settings',
},
})
const client = injectModrinthClient()
const { serverId, server, worldId, isServerRunning } = injectModrinthServerContext()
const { openServerSettings } = injectServerSettingsModal()
const { formatMessage } = useVIntl()
const formatRelativeTime = useRelativeTime()
const router = useRouter()
const {
isInstalling,
isStopping,
showRestartButton,
busyTooltip,
canTakeAction,
canKill,
primaryActionText,
initiateAction,
handlePrimaryAction,
} = useServerPowerAction()
const { data: serverFull } = useQuery({
queryKey: computed(() => ['servers', 'v1', 'detail', serverId]),
queryFn: () => client.archon.servers_v1.get(serverId),
staleTime: 30_000,
})
const instancesPath = computed(() => `/hosting/manage/${encodeURIComponent(serverId)}/instances`)
const worldPath = computed(() =>
worldId.value
? `${instancesPath.value}/${encodeURIComponent(worldId.value)}`
: instancesPath.value,
)
const currentWorld = computed(() => {
const id = worldId.value
if (!id) return null
return serverFull.value?.worlds.find((world) => world.id === id) ?? null
})
const worldName = computed(
() => currentWorld.value?.name ?? formatMessage(messages.worldFallbackName),
)
const gameVersion = computed(() => {
const version = currentWorld.value?.content?.game_version ?? server.value?.mc_version
return version ?? null
})
const loader = computed(
() => currentWorld.value?.content?.modloader ?? server.value?.loader ?? null,
)
const loaderVersion = computed(
() => currentWorld.value?.content?.modloader_version ?? server.value?.loader_version ?? null,
)
const lastActiveLabel = computed(() => {
const latestBackup = currentWorld.value ? latestDate(currentWorld.value.backups) : null
const lastActiveAt =
latestBackup ??
(currentWorld.value?.is_active && isServerRunning.value
? new Date().toISOString()
: currentWorld.value?.created_at)
return lastActiveAt
? formatMessage(messages.lastActive, { time: formatRelativeTime(lastActiveAt) })
: null
})
const startActionText = computed(() =>
primaryActionText.value === 'Start' ? 'Start instance' : primaryActionText.value,
)
const stopSplitActions = computed(() => [
{
id: 'stop',
label: isStopping.value ? 'Stopping' : 'Stop',
icon: StopCircleIcon,
action: () => initiateAction('Stop'),
},
{
id: 'kill_server',
label: 'Kill server',
icon: SlashIcon,
action: () => initiateAction('Kill'),
},
])
const restartableWorlds = computed(() =>
(serverFull.value?.worlds ?? []).filter((world) => world.id !== worldId.value),
)
const restartSplitActions = computed<JoinedButtonAction[]>(() => [
{
id: 'restart',
label: primaryActionText.value,
icon: UpdatedIcon,
action: () => initiateAction('Restart'),
},
// TODO: Implement world scoping when Archon/Kyros support target worlds in power requests.
...restartableWorlds.value.map((world) => ({
id: `restart-${world.id}`,
label: `Restart with ${world.name}`,
icon: GlobeIcon,
action: () => initiateAction('Restart'),
})),
])
const powerActions = computed(() => {
if (isInstalling.value) {
return [
{
id: 'installing',
label: 'Installing...',
icon: LoaderCircleIcon,
iconClass: 'animate-spin',
color: 'brand' as const,
disabled: true,
},
]
}
if (showRestartButton.value) {
return [
{
id: 'restart',
label: primaryActionText.value,
color: 'orange' as const,
joinedActions: restartSplitActions.value,
primaryDisabled: !canTakeAction.value,
dropdownDisabled: !canTakeAction.value,
},
{
id: 'stop',
label: 'Stop instance',
color: 'red' as const,
joinedActions: stopSplitActions.value,
primaryDisabled: !canTakeAction.value,
dropdownDisabled: !canKill.value,
},
]
}
if (isStopping.value) {
return [
{
id: 'stop',
label: 'Stop instance',
color: 'red' as const,
joinedActions: stopSplitActions.value,
primaryDisabled: true,
dropdownDisabled: !canKill.value,
primaryMuted: true,
},
]
}
return [
{
id: 'start',
label: startActionText.value,
icon: PlayIcon,
color: 'brand' as const,
tooltip: busyTooltip.value,
disabled: !canTakeAction.value,
onClick: handlePrimaryAction,
},
]
})
const headerActions = computed(() => [
...powerActions.value,
{
id: 'settings',
label: formatMessage(messages.instanceSettings),
icon: Settings2Icon,
labelHidden: true,
tooltip: formatMessage(messages.instanceSettings),
onClick: () => openServerSettings({ tabId: 'installation' }),
},
])
const worldTabLinks = computed<Tab[]>(() => [
{
label: formatMessage(messages.contentNav),
href: worldPath.value,
icon: BoxesIcon,
subpages: [],
},
{
label: formatMessage(messages.filesNav),
href: `${worldPath.value}/files`,
icon: FolderOpenIcon,
subpages: [],
},
{
label: formatMessage(messages.backupsNav),
href: `${worldPath.value}/backups`,
icon: DatabaseBackupIcon,
subpages: [],
},
])
watch(
() => [serverFull.value, currentWorld.value, worldId.value] as const,
([full, world, id]) => {
if (full && id && !world) {
router.replace(instancesPath.value)
}
},
{ immediate: true },
)
function latestDate(backups: Archon.Servers.v1.WorldFull['backups']): string | null {
let latest = 0
let latestIso: string | null = null
for (const backup of backups) {
const timestamp = new Date(backup.created_at).getTime()
if (!Number.isFinite(timestamp) || timestamp <= latest) continue
latest = timestamp
latestIso = backup.created_at
}
return latestIso
}
</script>
@@ -0,0 +1,336 @@
<template>
<div class="flex flex-col gap-4">
<div
v-if="!instanceInfoAdmonitionDismissed"
class="grid grid-cols-[1.5rem_minmax(0,1fr)_auto] items-start gap-x-3 rounded-2xl border border-solid border-brand-blue bg-bg-blue p-5 pr-4 text-contrast"
>
<InfoIcon class="mt-0.5 size-6 text-brand-blue" aria-hidden="true" />
<div class="flex min-w-0 flex-col gap-1">
<h2 class="m-0 text-xl font-bold leading-7">
{{ formatMessage(messages.instanceInfoHeader) }}
</h2>
<p class="m-0 text-lg leading-7 text-contrast/85">
{{ formatMessage(messages.instanceInfoBody) }}
</p>
</div>
<ButtonStyled circular type="transparent" color="blue" hover-color-fill="background">
<button
type="button"
class="mt-0.5"
:aria-label="formatMessage(messages.instanceInfoDismiss)"
@click="dismissInstanceInfoAdmonition"
>
<XIcon aria-hidden="true" />
</button>
</ButtonStyled>
</div>
<div
v-if="worldsPending"
class="grid grid-cols-[repeat(auto-fit,minmax(min(100%,20.25rem),1fr))] gap-6"
>
<div
v-for="slot in WORLD_SLOT_COUNT"
:key="`instance-card-skeleton-${slot}`"
class="min-h-[19.75rem] animate-pulse rounded-2xl border border-solid border-surface-5 bg-bg-raised shadow-xl"
/>
</div>
<div v-else class="grid grid-cols-[repeat(auto-fit,minmax(min(100%,20.25rem),1fr))] gap-6">
<InstanceCard
v-for="world in worldSlots"
:key="world.id"
:world="world"
@create="handleCreateWorld"
@edit="handleEditWorld"
@settings="handleWorldSettings"
/>
</div>
</div>
</template>
<script setup lang="ts">
import type { Archon } from '@modrinth/api-client'
import { InfoIcon, XIcon } from '@modrinth/assets'
import { useQuery } from '@tanstack/vue-query'
import { useStorage } from '@vueuse/core'
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import ButtonStyled from '#ui/components/base/ButtonStyled.vue'
import InstanceCard from '#ui/components/servers/instances/InstanceCard.vue'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import {
injectModrinthClient,
injectModrinthServerContext,
injectServerSettingsModal,
} from '#ui/providers'
import { formatLoaderLabel } from '#ui/utils/loaders'
const messages = defineMessages({
instanceSlotName: {
id: 'servers.manage.instances.slot-name',
defaultMessage: 'Instance #{index}',
},
instanceInfoHeader: {
id: 'servers.manage.instances.info.header',
defaultMessage: 'What is a server instance?',
},
instanceInfoBody: {
id: 'servers.manage.instances.info.body',
defaultMessage:
'An instance is a separate setup of your server with its own content, files, worlds, and settings. You can switch which instance your server runs at any time.',
},
instanceInfoDismiss: {
id: 'servers.manage.instances.info.dismiss',
defaultMessage: "Don't show this again",
},
})
type LinkedModpack = {
name: string
iconUrl: string | null
link: string | null
}
type WorldSlot =
| {
type: 'world'
id: string
name: string
active: boolean
gameVersion: string | null
loaderLabel: string | null
linkedModpack: LinkedModpack | null
installedContentCount: number | null
lastActiveAt: string | null
createdAt: string | null
}
| {
type: 'empty'
id: string
name: string
}
type ContentSummary = {
gameVersion: string | null
loader: string | null
loaderVersion: string | null
linkedModpack: LinkedModpack | null
installedContentCount: number | null
}
const WORLD_SLOT_COUNT = 3
const INSTANCE_INFO_ADMONITION_KEY = 'server-instances-info-admonition-dismissed'
const client = injectModrinthClient()
const { serverId, server, isServerRunning } = injectModrinthServerContext()
const { openServerSettings } = injectServerSettingsModal()
const { formatMessage } = useVIntl()
const router = useRouter()
const instanceInfoAdmonitionDismissed = useStorage(INSTANCE_INFO_ADMONITION_KEY, false)
const worldsQuery = useQuery({
queryKey: computed(() => ['servers', 'worlds', 'summary', 'v1', serverId]),
queryFn: loadWorldSlots,
staleTime: 30_000,
})
const worldsPending = computed(() => worldsQuery.isLoading.value && !worldsQuery.data.value)
const worldSlots = computed(() => worldsQuery.data.value ?? [])
async function loadWorldSlots(): Promise<WorldSlot[]> {
try {
const serverFull = await client.archon.servers_v1.get(serverId)
const slots = await Promise.all(
serverFull.worlds.map(async (world, index) => {
const content = await loadContentSummary(world, index)
return toWorldSlot(world, content)
}),
)
return padWorldSlots(slots)
} catch {
return createDummyWorldSlots()
}
}
async function loadContentSummary(
world: Archon.Servers.v1.WorldFull,
index: number,
): Promise<ContentSummary> {
try {
const content = await client.archon.content_v1.getAddons(serverId, world.id, {
addons: true,
updates: false,
})
return {
gameVersion: content.game_version ?? world.content?.game_version ?? null,
loader: content.modloader ?? world.content?.modloader ?? null,
loaderVersion: content.modloader_version ?? world.content?.modloader_version ?? null,
linkedModpack: getLinkedModpack(content.modpack),
installedContentCount: content.addons?.length ?? 0,
}
} catch {
return createDummyContentSummary(world, index)
}
}
function toWorldSlot(world: Archon.Servers.v1.WorldFull, content: ContentSummary): WorldSlot {
return {
type: 'world',
id: world.id,
name: world.name,
active: world.is_active,
gameVersion: content.gameVersion,
loaderLabel: getLoaderLabel(content.loader, content.loaderVersion),
linkedModpack: content.linkedModpack,
installedContentCount: content.installedContentCount,
lastActiveAt: getLatestKnownActivity(world),
createdAt: world.created_at,
}
}
function padWorldSlots(slots: WorldSlot[]): WorldSlot[] {
const padded = [...slots]
for (let i = padded.length; i < WORLD_SLOT_COUNT; i++) {
padded.push({
type: 'empty',
id: `empty-world-slot-${i + 1}`,
name: formatMessage(messages.instanceSlotName, { index: i + 1 }),
})
}
return padded
}
function getLinkedModpack(modpack: Archon.Content.v1.ModpackFields | null): LinkedModpack | null {
if (!modpack) return null
const name =
modpack.title ??
(modpack.spec.platform === 'local_file' ? modpack.spec.name : modpack.spec.project_id)
return {
name,
iconUrl: modpack.icon_url ?? null,
link: modpack.spec.platform === 'modrinth' ? `/project/${modpack.spec.project_id}` : null,
}
}
function getLoaderLabel(loader: string | null, loaderVersion: string | null): string | null {
if (!loader) return null
const normalizedLoader = loader.toLowerCase()
return [formatLoaderLabel(normalizedLoader), loaderVersion].filter(Boolean).join(' ')
}
function getLatestKnownActivity(world: Archon.Servers.v1.WorldFull): string | null {
const latestBackup = latestDate(world.backups.map((backup) => backup.created_at))
if (latestBackup) return latestBackup
if (world.is_active && isServerRunning.value) return new Date().toISOString()
return world.created_at ?? null
}
function latestDate(dates: string[]): string | null {
let latest = 0
let latestIso: string | null = null
for (const date of dates) {
const timestamp = new Date(date).getTime()
if (!Number.isFinite(timestamp) || timestamp <= latest) continue
latest = timestamp
latestIso = date
}
return latestIso
}
function createDummyContentSummary(
world: Archon.Servers.v1.WorldFull,
index: number,
): ContentSummary {
const gameVersion = world.content?.game_version ?? server.value?.mc_version ?? '1.20.4'
const loader = world.content?.modloader ?? server.value?.loader?.toLowerCase() ?? 'fabric'
const loaderVersion = world.content?.modloader_version ?? server.value?.loader_version ?? '0.16.6'
if (index === 0) {
return {
gameVersion,
loader,
loaderVersion,
linkedModpack: {
name: 'Cobblemon Official',
iconUrl: null,
link: null,
},
installedContentCount: 47,
}
}
return {
gameVersion,
loader,
loaderVersion,
linkedModpack: null,
installedContentCount: 13,
}
}
function createDummyWorldSlots(): WorldSlot[] {
const now = Date.now()
const twoHoursAgo = new Date(now - 2 * 60 * 60 * 1000).toISOString()
const sixteenDaysAgo = new Date(now - 16 * 24 * 60 * 60 * 1000).toISOString()
const createdAt = new Date(now - 197 * 24 * 60 * 60 * 1000).toISOString()
return [
{
type: 'world',
id: 'dummy-world-1',
name: 'Cobbletown',
active: true,
gameVersion: '1.20.4',
loaderLabel: 'Fabric 0.16.6',
linkedModpack: {
name: 'Cobblemon Official',
iconUrl: null,
link: null,
},
installedContentCount: 47,
lastActiveAt: twoHoursAgo,
createdAt,
},
{
type: 'world',
id: 'dummy-world-2',
name: 'SMP Season 4',
active: false,
gameVersion: '1.20.4',
loaderLabel: 'Fabric 0.16.6',
linkedModpack: null,
installedContentCount: 13,
lastActiveAt: sixteenDaysAgo,
createdAt,
},
{
type: 'empty',
id: 'empty-world-slot-3',
name: formatMessage(messages.instanceSlotName, { index: 3 }),
},
]
}
function handleEditWorld(worldId: string) {
router.push(
`/hosting/manage/${encodeURIComponent(serverId)}/instances/${encodeURIComponent(worldId)}`,
)
}
function handleWorldSettings() {
openServerSettings({ tabId: 'installation' })
}
function handleCreateWorld() {
openServerSettings({ tabId: 'installation' })
}
function dismissInstanceInfoAdmonition() {
instanceInfoAdmonitionDismissed.value = true
}
</script>
@@ -137,14 +137,14 @@ const messages = defineMessages({
defaultMessage:
'Pick your favorite modpack from Modrinth, or choose a loader and add the mods you want.',
},
configureWorldTitle: {
id: 'servers.setup.onboarding.step.configure-world.title',
defaultMessage: 'Configure your world',
configureInstanceTitle: {
id: 'servers.setup.onboarding.step.configure-instance.title',
defaultMessage: 'Configure your instance',
},
configureWorldDescription: {
id: 'servers.setup.onboarding.step.configure-world.description',
configureInstanceDescription: {
id: 'servers.setup.onboarding.step.configure-instance.description',
defaultMessage:
'Set up your world just like singleplayer. Choose your gamemode and world seed.',
'Set up your instance just like singleplayer. Choose your gamemode and world seed.',
},
inviteFriendsTitle: {
id: 'servers.setup.onboarding.step.invite-friends.title',
@@ -253,7 +253,11 @@ async function finalizeSetup() {
client.archon.servers_v1.endIntro(serverId).then(() => {
queryClient.invalidateQueries({ queryKey: ['servers', 'detail', serverId] })
})
await router.push(`/hosting/manage/${serverId}/`)
await router.push(
worldId.value
? `/hosting/manage/${encodeURIComponent(serverId)}/instances/${encodeURIComponent(worldId.value)}`
: `/hosting/manage/${encodeURIComponent(serverId)}/instances`,
)
}
/** Map UI loader names to API Modloader values */
@@ -347,8 +351,8 @@ const steps = computed(() => [
},
{
icon: GlobeIcon,
title: formatMessage(messages.configureWorldTitle),
description: formatMessage(messages.configureWorldDescription),
title: formatMessage(messages.configureInstanceTitle),
description: formatMessage(messages.configureInstanceDescription),
},
{
icon: UsersIcon,
+7 -5
View File
@@ -1,7 +1,9 @@
export { default as ServersManageRootLayout } from './hosting/manage/[id]/index.vue'
export { default as ServersManageBackupsPage } from './hosting/manage/[id]/instances/[instance-id]/backups.vue'
export { default as ServersManageContentPage } from './hosting/manage/[id]/instances/[instance-id]/content.vue'
export { default as ServersManageFilesPage } from './hosting/manage/[id]/instances/[instance-id]/files.vue'
export { default as ServersManageInstanceRootLayout } from './hosting/manage/[id]/instances/[instance-id]/index.vue'
export { default as ServersManageInstancesPage } from './hosting/manage/[id]/instances/index.vue'
export { default as ServerOnboardingPanelPage } from './hosting/manage/[id]/onboarding.vue'
export { default as ServersManageBackupsPage } from './hosting/manage/backups.vue'
export { default as ServersManageContentPage } from './hosting/manage/content.vue'
export { default as ServersManageFilesPage } from './hosting/manage/files.vue'
export { default as ServersManageOverviewPage } from './hosting/manage/[id]/overview.vue'
export { default as ServersManagePageIndex } from './hosting/manage/index.vue'
export { default as ServersManageOverviewPage } from './hosting/manage/overview.vue'
export { default as ServersManageRootLayout } from './hosting/manage/root.vue'
+235 -4
View File
@@ -398,6 +398,18 @@
"content.diff-modal.updated-count": {
"defaultMessage": "{count} updated"
},
"content.filter.disabled": {
"defaultMessage": "Disabled"
},
"content.filter.enabled": {
"defaultMessage": "Enabled"
},
"content.filter.updates": {
"defaultMessage": "Updates"
},
"content.filter.warnings": {
"defaultMessage": "Warnings"
},
"content.inline-backup.backing-up": {
"defaultMessage": "Creating backup..."
},
@@ -3503,6 +3515,15 @@
"servers.listing.using-project-label": {
"defaultMessage": "Using {projectTitle}"
},
"servers.manage.action.go-back-to-all-servers": {
"defaultMessage": "Go back to all servers"
},
"servers.manage.action.go-to-billing-settings": {
"defaultMessage": "Go to billing settings"
},
"servers.manage.action.reload": {
"defaultMessage": "Reload"
},
"servers.manage.checking-for-new-servers": {
"defaultMessage": "Checking for new servers..."
},
@@ -3515,15 +3536,102 @@
"servers.manage.contact-support-button": {
"defaultMessage": "Contact Modrinth Support"
},
"servers.manage.debug.server-data": {
"defaultMessage": "Server data"
},
"servers.manage.error-details.error-message": {
"defaultMessage": "Error message"
},
"servers.manage.error-details.error-name": {
"defaultMessage": "Error Name"
},
"servers.manage.error-details.node": {
"defaultMessage": "Node"
},
"servers.manage.error-details.original-error": {
"defaultMessage": "Original Error"
},
"servers.manage.error-details.server-id": {
"defaultMessage": "Server ID"
},
"servers.manage.error-details.stack-trace": {
"defaultMessage": "Stack Trace"
},
"servers.manage.error-details.timestamp": {
"defaultMessage": "Timestamp"
},
"servers.manage.error-details.unknown": {
"defaultMessage": "Unknown"
},
"servers.manage.error.alert-notice": {
"defaultMessage": "Our systems automatically alert our team when there's an issue. We are already working on getting them back online."
},
"servers.manage.error.change-loader": {
"defaultMessage": "Change Loader"
},
"servers.manage.error.contact-support": {
"defaultMessage": "Please contact Modrinth Support."
},
"servers.manage.error.copy-debug-info": {
"defaultMessage": "Copy Debug Info"
},
"servers.manage.error.debug-info": {
"defaultMessage": "Server ID: {serverId}\nError: {error}\nKind: {kind}\nProject ID: {projectId}\nVersion ID: {versionId}\nLog: {log}"
},
"servers.manage.error.description": {
"defaultMessage": "We may have temporary issues with our servers."
},
"servers.manage.error.details": {
"defaultMessage": "Error details:"
},
"servers.manage.error.general.message": {
"defaultMessage": "An unexpected error occurred."
},
"servers.manage.error.general.title": {
"defaultMessage": "An error occurred."
},
"servers.manage.error.install.internal.description": {
"defaultMessage": "An internal error occurred while installing your server. Don't fret - try reinstalling your server, and if the problem persists, please contact Modrinth support with your server's debug information."
},
"servers.manage.error.install.invalid-version.change-loader": {
"defaultMessage": "Your server may need to be reinstalled with a valid mod loader and version. You can change the loader by clicking the \"Change Loader\" button."
},
"servers.manage.error.install.invalid-version.description": {
"defaultMessage": "An invalid loader or Minecraft version was specified and could not be installed."
},
"servers.manage.error.install.invalid-version.modpack-compatibility": {
"defaultMessage": "If you've installed a modpack, it may have been packaged incorrectly or may not be compatible with the loader."
},
"servers.manage.error.install.invalid-version.recent-minecraft": {
"defaultMessage": "If this version of Minecraft was released recently, please check if Modrinth Hosting supports it."
},
"servers.manage.error.install.invalid-version.support": {
"defaultMessage": "If you're stuck, please contact Modrinth Support with the information below:"
},
"servers.manage.error.install.title": {
"defaultMessage": "Installation error"
},
"servers.manage.error.install.unsupported-version.description": {
"defaultMessage": "An error occurred while installing your server because Modrinth Hosting does not support the version of Minecraft or the loader you specified. Try reinstalling your server with a different version or loader, and if the problem persists, please contact Modrinth Support with your server's debug information."
},
"servers.manage.error.node-ping-failed": {
"defaultMessage": "Unable to reach node. Ping test failed."
},
"servers.manage.error.node-unavailable.data-description": {
"defaultMessage": "Your data is safe and will not be lost, and your server will be back online as soon as the issue is resolved."
},
"servers.manage.error.node-unavailable.description": {
"defaultMessage": "Your server's node, where your Modrinth Server is physically hosted, is not accessible at the moment. We are working to resolve the issue as quickly as possible."
},
"servers.manage.error.node-unavailable.support-description": {
"defaultMessage": "If reloading does not work initially, please contact Modrinth Support via the chat bubble in the bottom right corner and we'll be happy to help."
},
"servers.manage.error.node-unavailable.title": {
"defaultMessage": "Server Node Unavailable"
},
"servers.manage.error.open-installation-log": {
"defaultMessage": "Open Installation Log"
},
"servers.manage.error.queue-notice": {
"defaultMessage": "If you recently purchased your Modrinth Hosting server, it is currently in a queue and will appear here as soon as it's ready. <warning>Do not attempt to purchase a new server.</warning>"
},
@@ -3533,15 +3641,105 @@
"servers.manage.error.title": {
"defaultMessage": "Servers could not be loaded"
},
"servers.manage.error.unknown": {
"defaultMessage": "Unknown error"
},
"servers.manage.handle-error.title": {
"defaultMessage": "An error occurred"
},
"servers.manage.install.retry-error": {
"defaultMessage": "Failed to retry installation"
},
"servers.manage.instance.all-instances": {
"defaultMessage": "All instances"
},
"servers.manage.instance.fallback-name": {
"defaultMessage": "Instance"
},
"servers.manage.instance.last-active": {
"defaultMessage": "Last active {time}"
},
"servers.manage.instance.settings": {
"defaultMessage": "Instance settings"
},
"servers.manage.instances-hint.description": {
"defaultMessage": "Your server state has been converted into an instance."
},
"servers.manage.instances-hint.dismiss": {
"defaultMessage": "Don't show again"
},
"servers.manage.instances-hint.title": {
"defaultMessage": "New: Server Instances!"
},
"servers.manage.instances.card.active": {
"defaultMessage": "Active"
},
"servers.manage.instances.card.create": {
"defaultMessage": "Create instance"
},
"servers.manage.instances.card.created": {
"defaultMessage": "Created"
},
"servers.manage.instances.card.edit": {
"defaultMessage": "Edit instance"
},
"servers.manage.instances.card.empty-description": {
"defaultMessage": "New instance"
},
"servers.manage.instances.card.installed-content": {
"defaultMessage": "Installed content"
},
"servers.manage.instances.card.last-active": {
"defaultMessage": "Last active"
},
"servers.manage.instances.card.none": {
"defaultMessage": "None"
},
"servers.manage.instances.card.not-tracked-yet": {
"defaultMessage": "Not tracked yet"
},
"servers.manage.instances.card.settings": {
"defaultMessage": "Instance settings"
},
"servers.manage.instances.info.definition": {
"defaultMessage": "An instance is a separate server setup."
},
"servers.manage.instances.info.files": {
"defaultMessage": "Each instance has its own server files, worlds, installed content, and settings."
},
"servers.manage.instances.info.header": {
"defaultMessage": "What is an instance?"
},
"servers.manage.instances.info.switching": {
"defaultMessage": "You can switch which instance your server runs."
},
"servers.manage.instances.slot-name": {
"defaultMessage": "Instance #{index}"
},
"servers.manage.nav.backups": {
"defaultMessage": "Backups"
},
"servers.manage.nav.content": {
"defaultMessage": "Content"
},
"servers.manage.nav.files": {
"defaultMessage": "Files"
},
"servers.manage.nav.instances": {
"defaultMessage": "Instances"
},
"servers.manage.nav.overview": {
"defaultMessage": "Overview"
},
"servers.manage.new-server-button": {
"defaultMessage": "New server"
},
"servers.manage.no-servers-found": {
"defaultMessage": "No servers found."
},
"servers.manage.notice.dismiss-error": {
"defaultMessage": "Error dismissing notice"
},
"servers.manage.purchase-unavailable.text": {
"defaultMessage": "Payment information is still loading. Opening checkout as soon as it is ready."
},
@@ -3572,6 +3770,9 @@
"servers.manage.search-placeholder": {
"defaultMessage": "Search {count} {count, plural, one {server} other {servers}}..."
},
"servers.manage.server-settings": {
"defaultMessage": "Server settings"
},
"servers.manage.servers-title": {
"defaultMessage": "Modrinth Hosting"
},
@@ -3584,6 +3785,36 @@
"servers.manage.settings-hint.title": {
"defaultMessage": "Your server settings have moved"
},
"servers.manage.status.preparing.description": {
"defaultMessage": "Your server's hardware is being prepared and will be available shortly!"
},
"servers.manage.status.preparing.title": {
"defaultMessage": "We're getting your server ready"
},
"servers.manage.status.suspended.cancelled-description": {
"defaultMessage": "Your subscription has been cancelled.\nContact Modrinth Support if you believe this is an error."
},
"servers.manage.status.suspended.description": {
"defaultMessage": "Your server has been suspended.\nContact Modrinth Support if you believe this is an error."
},
"servers.manage.status.suspended.reason-description": {
"defaultMessage": "Your server has been suspended: {reason}\nContact Modrinth Support if you believe this is an error."
},
"servers.manage.status.suspended.title": {
"defaultMessage": "Server suspended"
},
"servers.manage.status.upgrading.description": {
"defaultMessage": "Your server's hardware is currently being upgraded and will be back online shortly!"
},
"servers.manage.status.upgrading.title": {
"defaultMessage": "Server upgrading"
},
"servers.manage.websocket.error": {
"defaultMessage": "Something went wrong..."
},
"servers.manage.websocket.reconnecting": {
"defaultMessage": "Hang on, we're reconnecting to your server."
},
"servers.medal-listing.countdown.remaining": {
"defaultMessage": "<days-count>{days}</days-count> {days, plural, one {day} other {days}} <hours-count>{hours}</hours-count> {hours, plural, one {hour} other {hours}} <minutes-count>{minutes}</minutes-count> {minutes, plural, one {minute} other {minutes}} <seconds-count>{seconds}</seconds-count> {seconds, plural, one {second} other {seconds}} remaining..."
},
@@ -3752,11 +3983,11 @@
"servers.setup.onboarding.step.choose.title": {
"defaultMessage": "Choose what to play"
},
"servers.setup.onboarding.step.configure-world.description": {
"defaultMessage": "Set up your world just like singleplayer. Choose your gamemode and world seed."
"servers.setup.onboarding.step.configure-instance.description": {
"defaultMessage": "Set up your instance just like singleplayer. Choose your gamemode and world seed."
},
"servers.setup.onboarding.step.configure-world.title": {
"defaultMessage": "Configure your world"
"servers.setup.onboarding.step.configure-instance.title": {
"defaultMessage": "Configure your instance"
},
"servers.setup.onboarding.step.invite-friends.description": {
"defaultMessage": "Share your server with friends by copying the address and letting them know which mods they'll need to join."
@@ -1,63 +0,0 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import Avatar from '../../components/base/Avatar.vue'
import ButtonStyled from '../../components/base/ButtonStyled.vue'
import ContentPageHeader from '../../components/base/ContentPageHeader.vue'
const meta = {
title: 'Base/ContentPageHeader',
component: ContentPageHeader,
} satisfies Meta<typeof ContentPageHeader>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
render: () => ({
components: { ContentPageHeader, Avatar, ButtonStyled },
template: `
<ContentPageHeader>
<template #icon>
<Avatar size="64px" />
</template>
<template #title>Project Name</template>
<template #summary>A brief description of the project goes here.</template>
<template #stats>
<span>1.2M downloads</span>
<span>50K followers</span>
</template>
<template #actions>
<ButtonStyled color="brand">
<button>Follow</button>
</ButtonStyled>
</template>
</ContentPageHeader>
`,
}),
}
export const WithTitleSuffix: Story = {
render: () => ({
components: { ContentPageHeader, Avatar, ButtonStyled },
template: `
<ContentPageHeader>
<template #icon>
<Avatar size="64px" />
</template>
<template #title>Featured Project</template>
<template #title-suffix>
<span class="px-2 py-1 bg-brand-highlight text-brand rounded-full text-sm">Featured</span>
</template>
<template #summary>This project has been featured by the Modrinth team.</template>
<template #actions>
<ButtonStyled color="brand">
<button>Download</button>
</ButtonStyled>
<ButtonStyled type="transparent">
<button>Share</button>
</ButtonStyled>
</template>
</ContentPageHeader>
`,
}),
}
@@ -0,0 +1,353 @@
import {
AffiliateIcon,
ClipboardCopyIcon,
DownloadIcon,
GlobeIcon,
HeartIcon,
LeftArrowIcon,
LinkIcon,
MoreVerticalIcon,
PlayIcon,
SettingsIcon,
SlashIcon,
StopCircleIcon,
TagCategoryGamepad2Icon as Gamepad2Icon,
TimerIcon,
} from '@modrinth/assets'
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import PageHeader from '../../components/base/PageHeader.vue'
import LoaderIcon from '../../components/servers/icons/LoaderIcon.vue'
import ServerIcon from '../../components/servers/icons/ServerIcon.vue'
const noop = () => undefined
const meta = {
title: 'Base/PageHeader',
component: PageHeader,
parameters: {
layout: 'padded',
},
decorators: [
(story) => ({
components: { story },
template: '<div class="w-full"><story /></div>',
}),
],
} satisfies Meta<typeof PageHeader>
export default meta
type Story = StoryObj<typeof meta>
export const AppInstanceHeader: Story = {
args: {
header: 'Create: Astral',
leading: {
type: 'avatar',
src: null,
alt: 'Create: Astral',
tintBy: '/Users/calum/Library/Application Support/com.modrinth.theseus/profiles/astral',
},
metadata: [
{
id: 'game-version',
label: '1.20.1',
icon: Gamepad2Icon,
tooltip: 'Minecraft version',
},
{
id: 'loader',
label: 'Fabric 0.16.14',
icon: LoaderIcon,
iconProps: { loader: 'Fabric' },
tooltip: 'Mod loader',
},
{
id: 'playtime',
label: '12 hours',
icon: TimerIcon,
tooltip: 'Total playtime',
},
],
actions: [
{
id: 'play',
label: 'Play',
icon: PlayIcon,
color: 'brand',
onClick: noop,
},
{
id: 'settings',
label: 'Instance settings',
icon: SettingsIcon,
labelHidden: true,
tooltip: 'Instance settings',
onClick: noop,
},
{
id: 'more',
label: 'More actions',
icon: MoreVerticalIcon,
labelHidden: true,
type: 'transparent',
tooltip: 'More actions',
menuActions: [
{
id: 'open-folder',
label: 'Open folder',
icon: GlobeIcon,
action: noop,
},
{
id: 'copy-id',
label: 'Copy ID',
icon: ClipboardCopyIcon,
action: noop,
},
],
},
],
},
}
export const CreatorHeader: Story = {
args: {
header: 'Prospector',
summary: 'A Modrinth creator with a handful of popular projects.',
leading: {
type: 'avatar',
src: null,
alt: 'Prospector',
avatarSize: '96px',
circle: true,
},
badges: [
{
id: 'affiliate',
label: 'Affiliate',
icon: AffiliateIcon,
class: 'border-brand-highlight bg-brand-highlight text-brand',
},
],
metadata: [
{
id: 'projects',
label: '12 projects',
icon: Gamepad2Icon,
},
{
id: 'downloads',
label: '4.2M downloads',
icon: DownloadIcon,
},
{
id: 'followers',
label: '82K followers',
icon: HeartIcon,
},
],
actions: [
{
id: 'follow',
label: 'Follow',
icon: HeartIcon,
color: 'brand',
onClick: noop,
},
],
},
}
export const BrowseHeader: Story = {
args: {
header: 'Survival SMP',
leading: [
{
id: 'back',
type: 'button',
icon: LeftArrowIcon,
to: '/instance/my-world',
ariaLabel: 'Back to instance',
tooltip: 'Back to instance',
wrapperClass: 'flex size-12 shrink-0 items-center justify-center',
},
{
id: 'target',
type: 'avatar',
src: null,
alt: 'Survival SMP',
avatarSize: '48px',
tintBy: 'survival-smp',
},
],
metadata: [
{
id: 'heading',
label: 'Installing content',
class: '!text-primary',
},
{
id: 'game-version',
label: '1.20.1',
icon: Gamepad2Icon,
tooltip: 'Minecraft version',
class: '!text-primary',
},
{
id: 'loader',
label: 'Fabric',
icon: LoaderIcon,
iconProps: { loader: 'Fabric' },
tooltip: 'Mod loader',
class: '!text-primary',
},
],
divider: false,
bottomPadding: false,
mainClass: 'items-center',
titleClass: 'leading-8',
truncateTitle: true,
},
}
export const ServerPanelRootHeader: Story = {
args: {
header: 'Survival SMP',
leading: {
type: 'component',
component: ServerIcon,
componentProps: { image: undefined },
class: 'size-15 !rounded-xl',
},
metadata: [
{
id: 'active-world',
label: 'My World',
icon: GlobeIcon,
tooltip: 'Active instance',
},
{
id: 'address',
label: 'play.modrinth.gg',
icon: LinkIcon,
tooltip: 'Copy server address',
onClick: noop,
},
],
actions: [
{
id: 'start',
label: 'Start server',
icon: PlayIcon,
color: 'brand',
onClick: noop,
},
{
id: 'settings',
label: 'Server settings',
icon: SettingsIcon,
labelHidden: true,
tooltip: 'Server settings',
onClick: noop,
},
],
},
}
export const ServerPanelInstanceHeader: Story = {
args: {
header: 'My World',
leading: {
type: 'button',
icon: LeftArrowIcon,
to: '/hosting/manage/demo-server/instances',
ariaLabel: 'All instances',
tooltip: 'All instances',
},
metadata: [
{
id: 'game-version',
label: '1.20.1',
icon: Gamepad2Icon,
tooltip: 'Minecraft version',
},
{
id: 'loader',
label: 'Fabric 0.19.2',
icon: LoaderIcon,
iconProps: { loader: 'Fabric' },
tooltip: 'Mod loader',
},
{
id: 'last-active',
label: 'Last active 2 weeks ago',
icon: TimerIcon,
tooltip: 'Last activity',
},
],
actions: [
{
id: 'start',
label: 'Start instance',
icon: PlayIcon,
color: 'brand',
onClick: noop,
},
{
id: 'stop',
label: 'Stop instance',
color: 'red',
joinedActions: [
{
id: 'stop',
label: 'Stop',
icon: StopCircleIcon,
action: noop,
},
{
id: 'kill_server',
label: 'Kill server',
icon: SlashIcon,
action: noop,
},
],
},
{
id: 'settings',
label: 'Instance settings',
icon: SettingsIcon,
labelHidden: true,
tooltip: 'Instance settings',
onClick: noop,
},
],
},
}
export const CustomMetadata: Story = {
render: () => ({
components: { PageHeader, DownloadIcon, HeartIcon },
template: `
<PageHeader
header="Custom Metadata Project"
summary="Custom metadata is reserved for rich stat rows that cannot be represented by icon and label data."
:leading="{ type: 'avatar', src: null, alt: 'Custom Metadata Project', avatarSize: '96px' }"
:metadata="[{ id: 'project-stats', type: 'custom', class: 'contents' }]"
>
<template #metadata-project-stats>
<div class="flex flex-wrap items-center gap-3">
<div class="flex items-center gap-2 font-semibold">
<DownloadIcon class="h-6 w-6 text-secondary" />
1.2M downloads
</div>
<div class="flex items-center gap-2 font-semibold">
<HeartIcon class="h-6 w-6 text-secondary" />
50K followers
</div>
</div>
</template>
</PageHeader>
`,
}),
}
@@ -0,0 +1,53 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import InstanceCard from '../../components/servers/instances/InstanceCard.vue'
const meta = {
title: 'Servers/InstanceCard',
component: InstanceCard,
parameters: {
layout: 'padded',
},
render: (args) => ({
components: { InstanceCard },
setup() {
return { args }
},
template: '<div style="max-width: 360px"><InstanceCard v-bind="args" /></div>',
}),
} satisfies Meta<typeof InstanceCard>
export default meta
type Story = StoryObj<typeof meta>
export const Active: Story = {
args: {
world: {
type: 'world',
id: 'demo-world',
name: 'Cobbletown',
active: true,
gameVersion: '1.20.4',
loaderLabel: 'Fabric 0.16.6',
linkedModpack: {
name: 'Cobblemon Official',
iconUrl: null,
link: null,
},
installedContentCount: 47,
lastActiveAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
createdAt: new Date(Date.now() - 197 * 24 * 60 * 60 * 1000).toISOString(),
},
},
}
export const Empty: Story = {
args: {
world: {
type: 'empty',
id: 'empty-instance-slot',
name: 'Instance #2',
},
},
}
@@ -22,7 +22,7 @@ const meta = {
setup() {
const router = useRouter()
onMounted(() => {
router.replace('/hosting/manage/demo-server/content')
router.replace('/hosting/manage/demo-server/instances/demo-world')
})
const server = ref({
@@ -0,0 +1,50 @@
import { PlayIcon, SettingsIcon } from '@modrinth/assets'
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import WorldManageHeader from '../../components/servers/server-header/WorldManageHeader.vue'
const meta = {
title: 'Servers/WorldManageHeader',
component: WorldManageHeader,
parameters: {
layout: 'padded',
},
decorators: [
(story) => ({
components: { story },
template: '<div style="max-width: 920px;"><story /></div>',
}),
],
} satisfies Meta<typeof WorldManageHeader>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
args: {
name: 'My World',
gameVersion: '1.20.1',
loader: 'fabric',
loaderVersion: '0.19.2',
lastActive: 'Last active 2 weeks ago',
backHref: '/hosting/manage/demo-server/instances',
backLabel: 'All instances',
actions: [
{
id: 'start',
label: 'Start instance',
icon: PlayIcon,
color: 'brand',
onClick: () => undefined,
},
{
id: 'settings',
label: 'Instance settings',
icon: SettingsIcon,
labelHidden: true,
tooltip: 'Instance settings',
onClick: () => undefined,
},
],
},
}