feat: start of cross platform page system (#4731)

* feat: abstract api-client DI into ui package

* feat: cross platform page system

* feat: tanstack as cross platform useAsyncData

* feat: archon servers routes + labrinth billing routes

* fix: dont use partial

* feat: migrate server list page to tanstack + api-client + re-enabled broken features!

* feat: migrate servers manage page to api-client before page system

* feat: migrate manage page to page system

* fix: type issues

* fix: upgrade wrapper bugs

* refactor: move state types into api-client

* feat: disable financial stuff on app frontend

* feat: finalize cross platform page system for now

* fix: lint

* fix: build issues

* feat: remove papaparse

* fix: lint

* fix: interface error

---------

Co-authored-by: Prospector <6166773+Prospector@users.noreply.github.com>
This commit is contained in:
Calum H.
2025-11-14 17:15:09 +00:00
committed by GitHub
parent 26feaf753a
commit 7ccc32675b
79 changed files with 2631 additions and 1259 deletions

View File

@@ -120,7 +120,7 @@ import {
UpdatedIcon,
XIcon,
} from '@modrinth/assets'
import { ButtonStyled, Checkbox, NewModal } from '@modrinth/ui'
import { ButtonStyled, Checkbox, NewModal, ServerInfoLabels } from '@modrinth/ui'
import type { PowerAction as ServerPowerAction, ServerState } from '@modrinth/utils'
import { useStorage } from '@vueuse/core'
import { computed, ref } from 'vue'
@@ -130,7 +130,6 @@ import type { BackupInProgressReason } from '~/pages/servers/manage/[id].vue'
import LoadingIcon from './icons/LoadingIcon.vue'
import PanelSpinner from './PanelSpinner.vue'
import ServerInfoLabels from './ServerInfoLabels.vue'
import TeleportOverflowMenu from './TeleportOverflowMenu.vue'
const flags = useFeatureFlags()

View File

@@ -1,39 +0,0 @@
<template>
<div
v-if="game"
v-tooltip="'Change server version'"
class="min-w-0 flex-none flex-row items-center gap-2 first:!flex"
>
<GameIcon aria-hidden="true" class="size-5 shrink-0" />
<NuxtLink
v-if="isLink"
:to="serverId ? `/servers/manage/${serverId}/options/loader` : ''"
class="flex min-w-0 items-center truncate text-sm font-semibold"
:class="serverId ? 'hover:underline' : ''"
>
<div class="flex flex-row items-center gap-1">
{{ game[0].toUpperCase() + game.slice(1) }}
<span v-if="mcVersion">{{ mcVersion }}</span>
<span v-else class="inline-block h-3 w-12 animate-pulse rounded bg-button-border"></span>
</div>
</NuxtLink>
<div v-else class="flex min-w-0 flex-row items-center gap-1 truncate text-sm font-semibold">
{{ game[0].toUpperCase() + game.slice(1) }}
<span v-if="mcVersion">{{ mcVersion }}</span>
<span v-else class="inline-block h-3 w-16 animate-pulse rounded bg-button-border"></span>
</div>
</div>
</template>
<script setup lang="ts">
import { GameIcon } from '@modrinth/assets'
defineProps<{
game: string
mcVersion: string
isLink?: boolean
}>()
const route = useNativeRoute()
const serverId = route.params.id as string
</script>

View File

@@ -1,26 +0,0 @@
<template>
<div
class="experimental-styles-within flex size-16 shrink-0 overflow-hidden rounded-xl border-[1px] border-solid border-button-border bg-button-bg shadow-sm"
>
<client-only>
<img
v-if="image"
class="h-full w-full select-none object-fill"
alt="Server Icon"
:src="image"
/>
<img
v-else
class="h-full w-full select-none object-fill"
alt="Server Icon"
src="~/assets/images/servers/minecraft_server_icon.png"
/>
</client-only>
</div>
</template>
<script setup lang="ts">
defineProps<{
image: string | undefined
}>()
</script>

View File

@@ -1,45 +0,0 @@
<template>
<div>
<ServerGameLabel
v-if="showGameLabel"
:game="serverData.game"
:mc-version="serverData.mc_version ?? ''"
:is-link="linked"
/>
<ServerLoaderLabel
:loader="serverData.loader"
:loader-version="serverData.loader_version ?? ''"
:no-separator="column"
:is-link="linked"
/>
<ServerSubdomainLabel
v-if="serverData.net?.domain"
:subdomain="serverData.net.domain"
:no-separator="column"
:is-link="linked"
/>
<ServerUptimeLabel
v-if="uptimeSeconds"
:uptime-seconds="uptimeSeconds"
:no-separator="column"
/>
</div>
</template>
<script setup lang="ts">
import ServerGameLabel from './ServerGameLabel.vue'
import ServerLoaderLabel from './ServerLoaderLabel.vue'
import ServerSubdomainLabel from './ServerSubdomainLabel.vue'
import ServerUptimeLabel from './ServerUptimeLabel.vue'
interface ServerInfoLabelsProps {
serverData: Record<string, any>
showGameLabel: boolean
showLoaderLabel: boolean
uptimeSeconds?: number
column?: boolean
linked?: boolean
}
defineProps<ServerInfoLabelsProps>()
</script>

View File

@@ -1,174 +0,0 @@
<template>
<div>
<NuxtLink :to="status === 'suspended' ? '' : `/servers/manage/${props.server_id}`">
<div
class="flex flex-row items-center overflow-x-hidden rounded-2xl border-[1px] border-solid border-button-bg bg-bg-raised p-4 transition-transform duration-100"
:class="{
'!rounded-b-none border-b-0': status === 'suspended' || !!pendingChange,
'opacity-75': status === 'suspended',
'active:scale-95': status !== 'suspended' && !pendingChange,
}"
data-pyro-server-listing
:data-pyro-server-listing-id="server_id"
>
<ServerIcon v-if="status !== 'suspended'" :image="image" />
<div
v-else
class="bg-bg-secondary flex size-16 items-center justify-center rounded-xl border-[1px] border-solid border-button-border bg-button-bg shadow-sm"
>
<LockIcon class="size-12 text-secondary" />
</div>
<div class="ml-4 flex flex-col gap-2.5">
<div class="flex flex-row items-center gap-2">
<h2 class="m-0 text-xl font-bold text-contrast">{{ name }}</h2>
<ChevronRightIcon />
</div>
<div
v-if="projectData?.title"
class="m-0 flex flex-row items-center gap-2 text-sm font-medium text-secondary"
>
<Avatar
:src="iconUrl"
no-shadow
style="min-height: 20px; min-width: 20px; height: 20px; width: 20px"
alt="Server Icon"
/>
Using {{ projectData?.title || 'Unknown' }}
</div>
<div
v-if="isConfiguring"
class="flex min-w-0 items-center gap-2 truncate text-sm font-semibold text-brand"
>
<SparklesIcon class="size-5 shrink-0" /> New server
</div>
<ServerInfoLabels
v-else
:server-data="{ game, mc_version, loader, loader_version, net }"
:show-game-label="showGameLabel"
:show-loader-label="showLoaderLabel"
:linked="false"
class="pointer-events-none flex w-full flex-row flex-wrap items-center gap-4 text-secondary *:hidden sm:flex-row sm:*:flex"
/>
</div>
</div>
</NuxtLink>
<div
v-if="status === 'suspended' && suspension_reason === 'upgrading'"
class="relative flex w-full flex-row items-center gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-blue bg-bg-blue p-4 text-sm font-bold text-contrast"
>
<PanelSpinner />
Your server's hardware is currently being upgraded and will be back online shortly.
</div>
<div
v-else-if="status === 'suspended' && suspension_reason === 'cancelled'"
class="relative flex w-full flex-col gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-red bg-bg-red p-4 text-sm font-bold text-contrast"
>
<div class="flex flex-row gap-2">
<PanelErrorIcon class="!size-5" /> Your server has been cancelled. Please update your
billing information or contact Modrinth Support for more information.
</div>
<CopyCode :text="`${props.server_id}`" class="ml-auto" />
</div>
<div
v-else-if="status === 'suspended' && suspension_reason"
class="relative flex w-full flex-col gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-red bg-bg-red p-4 text-sm font-bold text-contrast"
>
<div class="flex flex-row gap-2">
<PanelErrorIcon class="!size-5" /> Your server has been suspended: {{ suspension_reason }}.
Please update your billing information or contact Modrinth Support for more information.
</div>
<CopyCode :text="`${props.server_id}`" class="ml-auto" />
</div>
<div
v-else-if="status === 'suspended'"
class="relative flex w-full flex-col gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-red bg-bg-red p-4 text-sm font-bold text-contrast"
>
<div class="flex flex-row gap-2">
<PanelErrorIcon class="!size-5" /> Your server has been suspended. Please update your
billing information or contact Modrinth Support for more information.
</div>
<CopyCode :text="`${props.server_id}`" class="ml-auto" />
</div>
<div
v-if="pendingChange && status !== 'suspended'"
class="relative flex w-full flex-col gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-orange bg-bg-orange p-4 text-sm font-bold text-contrast"
>
<div>
Your server will {{ pendingChange.verb.toLowerCase() }} to the "{{
pendingChange.planSize
}}" plan on {{ formatDate(pendingChange.date) }}.
</div>
<ServersSpecs
class="!font-normal !text-contrast"
:ram="Math.round((pendingChange.ramGb ?? 0) * 1024)"
:storage="Math.round((pendingChange.storageGb ?? 0) * 1024)"
:cpus="pendingChange.cpuBurst"
bursting-link="https://docs.modrinth.com/servers/bursting"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { ChevronRightIcon, LockIcon, SparklesIcon } from '@modrinth/assets'
import { Avatar, CopyCode, ServersSpecs } from '@modrinth/ui'
import type { Project, Server } from '@modrinth/utils'
import dayjs from 'dayjs'
import { useModrinthServers } from '~/composables/servers/modrinth-servers.ts'
import PanelErrorIcon from './icons/PanelErrorIcon.vue'
import PanelSpinner from './PanelSpinner.vue'
import ServerIcon from './ServerIcon.vue'
import ServerInfoLabels from './ServerInfoLabels.vue'
type PendingChange = {
planSize: string
cpu: number
cpuBurst: number
ramGb: number
swapGb?: number
storageGb?: number
date: string | number | Date
intervalChange?: string | null
verb: string
}
const props = defineProps<Partial<Server> & { pendingChange?: PendingChange }>()
if (props.server_id && props.status === 'available') {
// Necessary only to get server icon
await useModrinthServers(props.server_id, ['general'])
}
const showGameLabel = computed(() => !!props.game)
const showLoaderLabel = computed(() => !!props.loader)
let projectData: Ref<Project | null>
if (props.upstream) {
const { data } = await useAsyncData<Project>(
`server-project-${props.server_id}`,
async (): Promise<Project> => {
const result = await useBaseFetch(`project/${props.upstream?.project_id}`)
return result as Project
},
)
projectData = data
} else {
projectData = ref(null)
}
const image = useState<string | undefined>(`server-icon-${props.server_id}`, () => undefined)
const iconUrl = computed(() => projectData.value?.icon_url || undefined)
const isConfiguring = computed(() => props.flows?.intro)
const formatDate = (d: unknown) => {
try {
return dayjs(d as any).format('MMMM D, YYYY')
} catch {
return ''
}
}
</script>

View File

@@ -1,24 +0,0 @@
<template>
<div class="flex flex-row items-center gap-8 overflow-x-hidden rounded-3xl bg-bg-raised p-4">
<div class="relative grid place-content-center">
<img
no-shadow
size="lg"
alt="Server Icon"
class="size-[96px] rounded-xl bg-bg-raised opacity-50"
src="~/assets/images/servers/minecraft_server_icon.png"
/>
<div class="absolute inset-0 grid place-content-center">
<LoadingIcon class="size-8 animate-spin text-contrast" />
</div>
</div>
<div class="flex flex-col gap-4">
<h2 class="m-0 text-contrast">Your new server is being prepared.</h2>
<p class="m-0">It'll appear here once it's ready.</p>
</div>
</div>
</template>
<script lang="ts" setup>
import LoadingIcon from './icons/LoadingIcon.vue'
</script>

View File

@@ -1,47 +0,0 @@
<template>
<div v-tooltip="'Change server loader'" class="flex min-w-0 flex-row items-center gap-4 truncate">
<div v-if="!noSeparator" class="experimental-styles-within h-6 w-0.5 bg-button-border"></div>
<div class="flex flex-row items-center gap-2">
<LoaderIcon v-if="loader" :loader="loader" class="flex shrink-0 [&&]:size-5" />
<div v-else class="size-5 shrink-0 animate-pulse rounded-full bg-button-border"></div>
<NuxtLink
v-if="isLink"
:to="serverId ? `/servers/manage/${serverId}/options/loader` : ''"
class="flex min-w-0 items-center text-sm font-semibold"
:class="serverId ? 'hover:underline' : ''"
>
<span v-if="loader">
{{ loader }}
<span v-if="loaderVersion">{{ loaderVersion }}</span>
</span>
<span v-else class="flex gap-2">
<span class="inline-block h-4 w-12 animate-pulse rounded bg-button-border"></span>
<span class="inline-block h-4 w-12 animate-pulse rounded bg-button-border"></span>
</span>
</NuxtLink>
<div v-else class="min-w-0 text-sm font-semibold">
<span v-if="loader">
{{ loader }}
<span v-if="loaderVersion">{{ loaderVersion }}</span>
</span>
<span v-else class="flex gap-2">
<span class="inline-block h-4 w-12 animate-pulse rounded bg-button-border"></span>
<span class="inline-block h-4 w-12 animate-pulse rounded bg-button-border"></span>
</span>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import LoaderIcon from './icons/LoaderIcon.vue'
defineProps<{
noSeparator?: boolean
loader?: 'Fabric' | 'Quilt' | 'Forge' | 'NeoForge' | 'Paper' | 'Spigot' | 'Bukkit' | 'Vanilla'
loaderVersion?: string
isLink?: boolean
}>()
const route = useNativeRoute()
const serverId = route.params.id as string
</script>

View File

@@ -1,19 +0,0 @@
<template>
<div class="flex h-full flex-col items-center justify-center gap-8">
<img
src="https://cdn.modrinth.com/servers/excitement.webp"
alt=""
class="max-w-[360px]"
style="mask-image: radial-gradient(97% 77% at 50% 25%, #d9d9d9 0, hsla(0, 0%, 45%, 0) 100%)"
/>
<h1 class="m-0 text-contrast">You don't have any servers yet!</h1>
<p class="m-0">Modrinth Servers is a new way to play modded Minecraft with your friends.</p>
<ButtonStyled size="large" type="standard" color="brand">
<NuxtLink to="/servers#plan">Create a Server</NuxtLink>
</ButtonStyled>
</div>
</template>
<script setup lang="ts">
import { ButtonStyled } from '@modrinth/ui'
</script>

View File

@@ -1,50 +0,0 @@
<template>
<div
v-if="subdomain && !isHidden"
v-tooltip="'Copy custom URL'"
class="flex min-w-0 flex-row items-center gap-4 truncate hover:cursor-pointer"
>
<div v-if="!noSeparator" class="experimental-styles-within h-6 w-0.5 bg-button-border"></div>
<div class="flex flex-row items-center gap-2">
<LinkIcon class="flex size-5 shrink-0" />
<div
class="flex min-w-0 text-sm font-semibold"
:class="serverId ? 'hover:underline' : ''"
@click="copySubdomain"
>
{{ subdomain }}.modrinth.gg
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { LinkIcon } from '@modrinth/assets'
import { injectNotificationManager } from '@modrinth/ui'
import { useStorage } from '@vueuse/core'
const { addNotification } = injectNotificationManager()
const props = defineProps<{
subdomain: string
noSeparator?: boolean
}>()
const copySubdomain = () => {
navigator.clipboard.writeText(props.subdomain + '.modrinth.gg')
addNotification({
title: 'Custom URL copied',
text: "Your server's URL has been copied to your clipboard.",
type: 'success',
})
}
const route = useNativeRoute()
const serverId = computed(() => route.params.id as string)
const userPreferences = useStorage(`pyro-server-${serverId.value}-preferences`, {
hideSubdomainLabel: false,
})
const isHidden = computed(() => userPreferences.value.hideSubdomainLabel)
</script>

View File

@@ -1,67 +0,0 @@
<template>
<div
v-if="uptimeSeconds || uptimeSeconds !== 0"
v-tooltip="`Online for ${verboseUptime}`"
class="server-action-buttons-anim flex min-w-0 flex-row items-center gap-4"
data-pyro-uptime
>
<div v-if="!noSeparator" class="experimental-styles-within h-6 w-0.5 bg-button-border"></div>
<div class="flex gap-2">
<Timer class="flex size-5 shrink-0" />
<time class="truncate text-sm font-semibold" :aria-label="verboseUptime">
{{ formattedUptime }}
</time>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import Timer from './icons/Timer.vue'
const props = defineProps<{
uptimeSeconds: number
noSeparator?: boolean
}>()
const formattedUptime = computed(() => {
const days = Math.floor(props.uptimeSeconds / (24 * 3600))
const hours = Math.floor((props.uptimeSeconds % (24 * 3600)) / 3600)
const minutes = Math.floor((props.uptimeSeconds % 3600) / 60)
const seconds = props.uptimeSeconds % 60
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 verboseUptime = computed(() => {
const days = Math.floor(props.uptimeSeconds / (24 * 3600))
const hours = Math.floor((props.uptimeSeconds % (24 * 3600)) / 3600)
const minutes = Math.floor((props.uptimeSeconds % 3600) / 60)
const seconds = props.uptimeSeconds % 60
let verbose = ''
if (days > 0) {
verbose += `${days} day${days > 1 ? 's' : ''} `
}
if (hours > 0) {
verbose += `${hours} hour${hours > 1 ? 's' : ''} `
}
if (minutes > 0) {
verbose += `${minutes} minute${minutes > 1 ? 's' : ''} `
}
verbose += `${seconds} second${seconds > 1 ? 's' : ''}`
return verbose.trim()
})
</script>

View File

@@ -1,270 +1,24 @@
<template>
<ModrinthServersPurchaseModal
v-if="customer"
ref="purchaseModal"
:publishable-key="config.public.stripePublishableKey"
:initiate-payment="async (body) => await initiatePayment(body)"
:available-products="pyroProducts"
:on-error="handleError"
:customer="customer"
:payment-methods="paymentMethods"
:currency="selectedCurrency"
:return-url="`${config.public.siteUrl}/servers/manage`"
:pings="regionPings"
:regions="regions"
:refresh-payment-methods="fetchPaymentData"
:fetch-stock="fetchStock"
:plan-stage="true"
:existing-plan="currentPlanFromSubscription"
:existing-subscription="subscription || undefined"
:on-finalize-no-payment-change="finalizeDowngrade"
@hide="
() => {
subscription = null
}
"
<ServersUpgradeModalWrapperBase
ref="wrapperRef"
:stripe-publishable-key="config.public.stripePublishableKey"
:site-url="config.public.siteUrl"
:products="generatedState.products || []"
/>
</template>
<script setup lang="ts">
import { injectNotificationManager, ModrinthServersPurchaseModal } from '@modrinth/ui'
import type { ServerPlan } from '@modrinth/ui/src/utils/billing'
import type { UserSubscription } from '@modrinth/utils'
import { computed, onMounted, ref } from 'vue'
// TODO: Remove this wrapper when we figure out how to do cross platform state + stripe
import { ServersUpgradeModalWrapper as ServersUpgradeModalWrapperBase } from '@modrinth/ui'
import { useServersFetch } from '~/composables/servers/servers-fetch.ts'
import { products } from '~/generated/state.json'
const { addNotification } = injectNotificationManager()
import { useGeneratedState } from '~/composables/generated'
const config = useRuntimeConfig()
const purchaseModal = ref<InstanceType<typeof ModrinthServersPurchaseModal> | null>(null)
const customer = ref<any>(null)
const paymentMethods = ref<any[]>([])
const selectedCurrency = ref<string>('USD')
const regions = ref<any[]>([])
const regionPings = ref<any[]>([])
const generatedState = useGeneratedState()
const pyroProducts = (products as any[])
.filter((p) => p?.metadata?.type === 'pyro')
.sort((a, b) => (a?.metadata?.ram ?? 0) - (b?.metadata?.ram ?? 0))
function handleError(err: any) {
console.error('Purchase modal error:', err)
}
async function fetchPaymentData() {
try {
const [customerData, paymentMethodsData] = await Promise.all([
useBaseFetch('billing/customer', { internal: true }),
useBaseFetch('billing/payment_methods', { internal: true }),
])
customer.value = customerData as any
paymentMethods.value = paymentMethodsData as any[]
} catch (error) {
console.error('Error fetching payment data:', error)
}
}
function fetchStock(region: any, request: any) {
return useServersFetch(`stock?region=${region.shortcode}`, {
method: 'POST',
body: {
...request,
},
bypassAuth: true,
}).then((res: any) => res.available as number)
}
function pingRegions() {
useServersFetch('regions', {
method: 'GET',
version: 1,
bypassAuth: true,
}).then((res: any) => {
regions.value = res as any[]
;(regions.value as any[]).forEach((region: any) => {
runPingTest(region)
})
})
}
const PING_COUNT = 20
const PING_INTERVAL = 200
const MAX_PING_TIME = 1000
function runPingTest(region: any, index = 1) {
if (index > 10) {
regionPings.value.push({
region: region.shortcode,
ping: -1,
})
return
}
const wsUrl = `wss://${region.shortcode}${index}.${region.zone}/pingtest`
try {
const socket = new WebSocket(wsUrl)
const pings: number[] = []
socket.onopen = () => {
for (let i = 0; i < PING_COUNT; i++) {
setTimeout(() => {
socket.send(String(performance.now()))
}, i * PING_INTERVAL)
}
setTimeout(
() => {
socket.close()
const median = Math.round([...pings].sort((a, b) => a - b)[Math.floor(pings.length / 2)])
if (median) {
regionPings.value.push({
region: region.shortcode,
ping: median,
})
}
},
PING_COUNT * PING_INTERVAL + MAX_PING_TIME,
)
}
socket.onmessage = (event) => {
const start = Number(event.data)
pings.push(performance.now() - start)
}
socket.onerror = () => {
runPingTest(region, index + 1)
}
} catch {
// ignore
}
}
const subscription = ref<UserSubscription | null>(null)
// Dry run state
const dryRunResponse = ref<{
requires_payment: boolean
required_payment_is_proration: boolean
} | null>(null)
const pendingDowngradeBody = ref<any | null>(null)
const currentPlanFromSubscription = computed<ServerPlan | undefined>(() => {
return subscription.value
? (pyroProducts.find(
(p) =>
p.prices.filter((price: { id: string }) => price.id === subscription.value?.price_id)
.length > 0,
) ?? undefined)
: undefined
})
const currentInterval = computed(() => {
const interval = subscription.value?.interval
if (interval === 'monthly' || interval === 'quarterly') {
return interval
}
return 'monthly'
})
async function initiatePayment(body: any): Promise<any> {
if (subscription.value) {
const transformedBody = {
interval: body.charge?.interval,
payment_method: body.type === 'confirmation_token' ? body.token : body.id,
product: body.charge?.product_id,
region: body.metadata?.server_region,
}
try {
const dry = await useBaseFetch(`billing/subscription/${subscription.value.id}?dry=true`, {
internal: true,
method: 'PATCH',
body: transformedBody,
})
if (dry && typeof dry === 'object' && 'requires_payment' in dry) {
dryRunResponse.value = dry as any
pendingDowngradeBody.value = transformedBody
if (dry.requires_payment) {
return await finalizeImmediate(transformedBody)
} else {
return null
}
} else {
// Fallback if dry run not supported
return await finalizeImmediate(transformedBody)
}
} catch (e) {
console.error('Dry run failed, attempting immediate patch', e)
return await finalizeImmediate(transformedBody)
}
} else {
addNotification({
title: 'Unable to determine subscription ID.',
text: 'Please contact support.',
type: 'error',
})
return Promise.reject(new Error('Unable to determine subscription ID.'))
}
}
async function finalizeImmediate(body: any) {
const result = await useBaseFetch(`billing/subscription/${subscription.value?.id}`, {
internal: true,
method: 'PATCH',
body,
})
return result
}
async function finalizeDowngrade() {
if (!subscription.value || !pendingDowngradeBody.value) return
try {
await finalizeImmediate(pendingDowngradeBody.value)
addNotification({
title: 'Subscription updated',
text: 'Your plan has been downgraded and will take effect next billing cycle.',
type: 'success',
})
} catch (e) {
addNotification({
title: 'Failed to apply subscription changes',
text: 'Please try again or contact support.',
type: 'error',
})
throw e
} finally {
dryRunResponse.value = null
pendingDowngradeBody.value = null
}
}
async function open(id?: string) {
if (id) {
const subscriptions = (await useBaseFetch(`billing/subscriptions`, {
internal: true,
})) as any[]
for (const sub of subscriptions) {
if (sub?.metadata?.id === id) {
subscription.value = sub
break
}
}
} else {
subscription.value = null
}
purchaseModal.value?.show(currentInterval.value)
}
const wrapperRef = ref<InstanceType<typeof ServersUpgradeModalWrapperBase> | null>(null)
defineExpose({
open,
})
onMounted(() => {
fetchPaymentData()
pingRegions()
open: (id?: string) => wrapperRef.value?.open(id),
})
</script>

View File

@@ -1,59 +0,0 @@
<template>
<div class="overlay"></div>
<img
src="https://cdn-raw.modrinth.com/medal-banner-background.webp"
class="background-pattern dark-pattern shadow-xl"
alt=""
/>
<img
src="https://cdn-raw.modrinth.com/medal-banner-background-light.webp"
class="background-pattern light-pattern shadow-xl"
alt=""
/>
</template>
<script setup lang="ts"></script>
<style scoped lang="scss">
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: var(--medal-promotion-bg-gradient);
z-index: 1;
border-radius: inherit;
}
.light-mode,
.light {
.background-pattern.dark-pattern {
display: none;
}
.background-pattern.light-pattern {
display: block;
}
}
.background-pattern.dark-pattern {
display: block;
}
.background-pattern.light-pattern {
display: none;
}
.background-pattern {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
object-fit: cover;
object-position: bottom;
background-color: var(--medal-promotion-bg);
border-radius: inherit;
color: var(--medal-promotion-bg-orange);
}
</style>

View File

@@ -31,10 +31,9 @@
<script lang="ts" setup>
import { ExternalIcon } from '@modrinth/assets'
import { ButtonStyled } from '@modrinth/ui'
import { ButtonStyled, MedalBackgroundImage } from '@modrinth/ui'
import MedalIcon from '~/assets/images/illustrations/medal_icon.svg?component'
import MedalBackgroundImage from '~/components/ui/servers/marketing/MedalBackgroundImage.vue'
</script>
<style scoped lang="scss">

View File

@@ -39,14 +39,12 @@
<script setup lang="ts">
import { ClockIcon, RocketIcon } from '@modrinth/assets'
import { ButtonStyled } from '@modrinth/ui'
import { ButtonStyled, MedalBackgroundImage } from '@modrinth/ui'
import type { UserSubscription } from '@modrinth/utils'
import dayjs from 'dayjs'
import dayjsDuration from 'dayjs/plugin/duration'
import type { ComponentPublicInstance } from 'vue'
import MedalBackgroundImage from '~/components/ui/servers/marketing/MedalBackgroundImage.vue'
import ServersUpgradeModalWrapper from '../ServersUpgradeModalWrapper.vue'
dayjs.extend(dayjsDuration)

View File

@@ -1,226 +0,0 @@
<template>
<div class="rounded-2xl shadow-xl">
<div
class="medal-promotion flex flex-row items-center overflow-x-hidden rounded-t-2xl p-4 transition-transform duration-100"
:class="status === 'suspended' ? 'rounded-b-none border-b-0 opacity-75' : 'rounded-b-2xl'"
data-pyro-server-listing
:data-pyro-server-listing-id="server_id"
>
<MedalBackgroundImage />
<AutoLink
:to="status === 'suspended' ? '' : `/servers/manage/${props.server_id}`"
class="z-10 flex flex-grow flex-row items-center overflow-x-hidden"
:class="status !== 'suspended' && 'active:scale-95'"
>
<Avatar
v-if="status !== 'suspended'"
src="https://cdn-raw.modrinth.com/medal_icon.webp"
size="64px"
class="z-10"
/>
<div
v-else
class="bg-bg-secondary z-10 flex size-16 shrink-0 items-center justify-center rounded-xl border-[1px] border-solid border-button-border bg-button-bg shadow-sm"
>
<LockIcon class="size-12 text-secondary" />
</div>
<div class="z-10 ml-4 flex min-w-0 flex-col gap-2.5">
<div class="flex flex-row items-center gap-2">
<h2 class="m-0 truncate text-xl font-bold text-contrast">{{ name }}</h2>
<ChevronRightIcon />
<span class="truncate">
<span class="text-medal-orange">
{{ timeLeftCountdown.days }}
</span>
days
<span class="text-medal-orange">
{{ timeLeftCountdown.hours }}
</span>
hours
<span class="text-medal-orange">
{{ timeLeftCountdown.minutes }}
</span>
minutes
<span class="text-medal-orange">
{{ timeLeftCountdown.seconds }}
</span>
seconds remaining...
</span>
</div>
<div
v-if="projectData?.title"
class="m-0 flex flex-row items-center gap-2 text-sm font-medium text-secondary"
>
<Avatar
:src="iconUrl"
no-shadow
style="min-height: 20px; min-width: 20px; height: 20px; width: 20px"
alt="Server Icon"
/>
Using {{ projectData?.title || 'Unknown' }}
</div>
<div
v-if="isConfiguring"
class="text-medal-orange flex min-w-0 items-center gap-2 truncate text-sm font-semibold"
>
<SparklesIcon class="size-5 shrink-0" /> New server
</div>
<ServerInfoLabels
v-else
:server-data="{ game, mc_version, loader, loader_version, net }"
:show-game-label="showGameLabel"
:show-loader-label="showLoaderLabel"
:linked="false"
class="pointer-events-none flex w-full flex-row flex-wrap items-center gap-4 text-secondary *:hidden sm:flex-row sm:*:flex"
/>
</div>
</AutoLink>
<div class="z-10 ml-auto">
<ButtonStyled color="medal-promo" type="outlined" size="large">
<button class="my-auto" @click="handleUpgrade"><RocketIcon /> Upgrade</button>
</ButtonStyled>
</div>
</div>
<div
v-if="status === 'suspended' && suspension_reason === 'upgrading'"
class="relative flex w-full flex-row items-center gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-blue bg-bg-blue p-4 text-sm font-bold text-contrast"
>
<PanelSpinner />
Your server's hardware is currently being upgraded and will be back online shortly.
</div>
<div
v-else-if="status === 'suspended' && suspension_reason === 'cancelled'"
class="relative flex w-full flex-col gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-red bg-bg-red p-4 text-sm font-bold text-contrast"
>
<div class="flex flex-row gap-2">
<PanelErrorIcon class="!size-5" /> Your Medal server trial has ended and your server has
been suspended. Please upgrade to continue to use your server.
</div>
</div>
<div
v-else-if="status === 'suspended' && suspension_reason"
class="relative flex w-full flex-col gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-red bg-bg-red p-4 text-sm font-bold text-contrast"
>
<div class="flex flex-row gap-2">
<PanelErrorIcon class="!size-5" /> Your server has been suspended: {{ suspension_reason }}.
Please update your billing information or contact Modrinth Support for more information.
</div>
<CopyCode :text="`${props.server_id}`" class="ml-auto" />
</div>
<div
v-else-if="status === 'suspended'"
class="relative flex w-full flex-col gap-2 rounded-b-2xl border-[1px] border-t-0 border-solid border-bg-red bg-bg-red p-4 text-sm font-bold text-contrast"
>
<div class="flex flex-row gap-2">
<PanelErrorIcon class="!size-5" /> Your server has been suspended. Please update your
billing information or contact Modrinth Support for more information.
</div>
<CopyCode :text="`${props.server_id}`" class="ml-auto" />
</div>
</div>
</template>
<script setup lang="ts">
import { ChevronRightIcon, LockIcon, RocketIcon, SparklesIcon } from '@modrinth/assets'
import { AutoLink, Avatar, ButtonStyled, CopyCode } from '@modrinth/ui'
import type { Project, Server } from '@modrinth/utils'
import dayjs from 'dayjs'
import dayjsDuration from 'dayjs/plugin/duration'
import MedalBackgroundImage from '~/components/ui/servers/marketing/MedalBackgroundImage.vue'
import PanelErrorIcon from '../icons/PanelErrorIcon.vue'
import PanelSpinner from '../PanelSpinner.vue'
import ServerInfoLabels from '../ServerInfoLabels.vue'
dayjs.extend(dayjsDuration)
const props = defineProps<Partial<Server>>()
const emit = defineEmits<{ (e: 'upgrade'): void }>()
const showGameLabel = computed(() => !!props.game)
const showLoaderLabel = computed(() => !!props.loader)
let projectData: Ref<Project | null>
if (props.upstream) {
const { data } = await useAsyncData<Project>(
`server-project-${props.server_id}`,
async (): Promise<Project> => {
const result = await useBaseFetch(`project/${props.upstream?.project_id}`)
return result as Project
},
)
projectData = data
} else {
projectData = ref(null)
}
const iconUrl = computed(() => projectData.value?.icon_url || undefined)
const isConfiguring = computed(() => props.flows?.intro)
const timeLeftCountdown = ref({ days: 0, hours: 0, minutes: 0, seconds: 0 })
const expiryDate = computed(() => (props.medal_expires ? dayjs(props.medal_expires) : null))
function handleUpgrade(event: Event) {
event.stopPropagation()
emit('upgrade')
}
function updateCountdown() {
if (!expiryDate.value) {
timeLeftCountdown.value = { days: 0, hours: 0, minutes: 0, seconds: 0 }
return
}
const now = dayjs()
const diff = expiryDate.value.diff(now)
if (diff <= 0) {
timeLeftCountdown.value = { days: 0, hours: 0, minutes: 0, seconds: 0 }
return
}
const duration = dayjs.duration(diff)
timeLeftCountdown.value = {
days: duration.days(),
hours: duration.hours(),
minutes: duration.minutes(),
seconds: duration.seconds(),
}
}
watch(expiryDate, () => updateCountdown(), { immediate: true })
const intervalId = ref<NodeJS.Timeout | null>(null)
onMounted(() => {
intervalId.value = setInterval(updateCountdown, 1000)
})
onUnmounted(() => {
if (intervalId.value) clearInterval(intervalId.value)
})
</script>
<style scoped lang="scss">
.medal-promotion {
position: relative;
border: 1px solid var(--medal-promotion-bg-orange);
background: inherit; // allows overlay + pattern to take over
overflow: hidden;
}
.text-medal-orange {
color: var(--medal-promotion-text-orange);
font-weight: bold;
}
.border-medal-orange {
border-color: var(--medal-promotion-bg-orange);
}
</style>