You've already forked AstralRinth
forked from didirus/AstralRinth
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:
@@ -1,16 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
import type { Labrinth } from '@modrinth/api-client'
|
||||
import { InfoIcon } from '@modrinth/assets'
|
||||
import { formatPrice } from '@modrinth/utils'
|
||||
import { type MessageDescriptor, useVIntl } from '@vintl/vintl'
|
||||
import { Menu } from 'floating-vue'
|
||||
import { computed, inject, type Ref } from 'vue'
|
||||
|
||||
import { monthsInInterval, type ServerBillingInterval, type ServerPlan } from '../../utils/billing'
|
||||
import { getPriceForInterval, monthsInInterval } from '../../utils/product-utils'
|
||||
import type { ServerBillingInterval } from './ModrinthServersPurchaseModal.vue'
|
||||
import ServersSpecs from './ServersSpecs.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
plan: ServerPlan
|
||||
plan: Labrinth.Billing.Internal.Product
|
||||
title: MessageDescriptor
|
||||
description: MessageDescriptor
|
||||
buttonColor?: 'standard' | 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple'
|
||||
@@ -25,7 +27,7 @@ const props = withDefaults(
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'select', plan: ServerPlan): void
|
||||
(e: 'select', plan: Labrinth.Billing.Internal.Product): void
|
||||
}>()
|
||||
|
||||
const { formatMessage, locale } = useVIntl()
|
||||
@@ -36,13 +38,23 @@ const currency = inject<string>('currency')
|
||||
|
||||
const perMonth = computed(() => {
|
||||
if (!props.plan || !currency || !selectedInterval?.value) return undefined
|
||||
const total = props.plan.prices?.find((x) => x.currency_code === currency)?.prices?.intervals?.[
|
||||
selectedInterval.value
|
||||
]
|
||||
const total = getPriceForInterval(props.plan, currency, selectedInterval.value)
|
||||
if (!total) return undefined
|
||||
return total / monthsInInterval[selectedInterval.value]
|
||||
})
|
||||
|
||||
const planSpecs = computed(() => {
|
||||
const metadata = props.plan.metadata
|
||||
if (metadata.type === 'pyro' || metadata.type === 'medal') {
|
||||
return {
|
||||
ram: metadata.ram,
|
||||
storage: metadata.storage,
|
||||
cpu: metadata.cpu,
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
const mostPopularStyle = computed(() => {
|
||||
if (!props.mostPopular) return undefined
|
||||
const style: Record<string, string> = {
|
||||
@@ -121,11 +133,11 @@ const mostPopularStyle = computed(() => {
|
||||
</template>
|
||||
|
||||
<template #popper>
|
||||
<div class="w-fit rounded-md border border-contrast/10 p-3 shadow-lg">
|
||||
<div v-if="planSpecs" class="w-fit rounded-md border border-contrast/10 p-3 shadow-lg">
|
||||
<ServersSpecs
|
||||
:ram="plan.metadata.ram!"
|
||||
:storage="plan.metadata.storage!"
|
||||
:cpus="plan.metadata.cpu!"
|
||||
:ram="planSpecs.ram"
|
||||
:storage="planSpecs.storage"
|
||||
:cpus="planSpecs.cpu"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { Archon, Labrinth } from '@modrinth/api-client'
|
||||
import {
|
||||
CheckCircleIcon,
|
||||
ChevronRightIcon,
|
||||
@@ -7,23 +8,12 @@ import {
|
||||
SpinnerIcon,
|
||||
XIcon,
|
||||
} from '@modrinth/assets'
|
||||
import type { UserSubscription } from '@modrinth/utils'
|
||||
import { defineMessage, type MessageDescriptor, useVIntl } from '@vintl/vintl'
|
||||
import type Stripe from 'stripe'
|
||||
import { computed, nextTick, ref, useTemplateRef, watch } from 'vue'
|
||||
|
||||
import { useStripe } from '../../composables/stripe'
|
||||
import { commonMessages } from '../../utils'
|
||||
import type {
|
||||
CreatePaymentIntentRequest,
|
||||
CreatePaymentIntentResponse,
|
||||
ServerBillingInterval,
|
||||
ServerPlan,
|
||||
ServerRegion,
|
||||
ServerStockRequest,
|
||||
UpdatePaymentIntentRequest,
|
||||
UpdatePaymentIntentResponse,
|
||||
} from '../../utils/billing'
|
||||
import { ButtonStyled } from '../index'
|
||||
import ModalLoadingIndicator from '../modal/ModalLoadingIndicator.vue'
|
||||
import NewModal from '../modal/NewModal.vue'
|
||||
@@ -39,6 +29,9 @@ export type RegionPing = {
|
||||
ping: number
|
||||
}
|
||||
|
||||
// Type alias for billing interval that matches both the local and api-client types
|
||||
export type ServerBillingInterval = 'monthly' | 'quarterly' | 'yearly'
|
||||
|
||||
const props = defineProps<{
|
||||
publishableKey: string
|
||||
returnUrl: string
|
||||
@@ -46,23 +39,30 @@ const props = defineProps<{
|
||||
customer: Stripe.Customer
|
||||
currency: string
|
||||
pings: RegionPing[]
|
||||
regions: ServerRegion[]
|
||||
availableProducts: ServerPlan[]
|
||||
regions: Archon.Servers.v1.Region[]
|
||||
availableProducts: Labrinth.Billing.Internal.Product[]
|
||||
planStage?: boolean
|
||||
existingPlan?: ServerPlan
|
||||
existingSubscription?: UserSubscription
|
||||
existingPlan?: Labrinth.Billing.Internal.Product
|
||||
existingSubscription?: Labrinth.Billing.Internal.UserSubscription
|
||||
refreshPaymentMethods: () => Promise<void>
|
||||
fetchStock: (region: ServerRegion, request: ServerStockRequest) => Promise<number>
|
||||
fetchStock: (
|
||||
region: Archon.Servers.v1.Region,
|
||||
request: Archon.Servers.v0.StockRequest,
|
||||
) => Promise<number>
|
||||
initiatePayment: (
|
||||
body: CreatePaymentIntentRequest | UpdatePaymentIntentRequest,
|
||||
) => Promise<UpdatePaymentIntentResponse | CreatePaymentIntentResponse | null>
|
||||
body: Labrinth.Billing.Internal.InitiatePaymentRequest,
|
||||
) => Promise<
|
||||
| Labrinth.Billing.Internal.InitiatePaymentResponse
|
||||
| Labrinth.Billing.Internal.EditSubscriptionResponse
|
||||
| null
|
||||
>
|
||||
onError: (err: Error) => void
|
||||
onFinalizeNoPaymentChange?: () => Promise<void>
|
||||
affiliateCode?: string | null
|
||||
}>()
|
||||
|
||||
const modal = useTemplateRef<InstanceType<typeof NewModal>>('modal')
|
||||
const selectedPlan = ref<ServerPlan>()
|
||||
const selectedPlan = ref<Labrinth.Billing.Internal.Product>()
|
||||
const selectedInterval = ref<ServerBillingInterval>('quarterly')
|
||||
const loading = ref(false)
|
||||
const selectedRegion = ref<string>()
|
||||
@@ -237,7 +237,7 @@ watch(selectedPlan, () => {
|
||||
}
|
||||
})
|
||||
|
||||
const defaultPlan = computed<ServerPlan | undefined>(() => {
|
||||
const defaultPlan = computed<Labrinth.Billing.Internal.Product | undefined>(() => {
|
||||
return (
|
||||
props.availableProducts.find((p) => p?.metadata?.type === 'pyro' && p.metadata.ram === 6144) ??
|
||||
props.availableProducts.find((p) => p?.metadata?.type === 'pyro') ??
|
||||
@@ -245,7 +245,11 @@ const defaultPlan = computed<ServerPlan | undefined>(() => {
|
||||
)
|
||||
})
|
||||
|
||||
function begin(interval: ServerBillingInterval, plan?: ServerPlan, project?: string) {
|
||||
function begin(
|
||||
interval: ServerBillingInterval,
|
||||
plan?: Labrinth.Billing.Internal.Product | null,
|
||||
project?: string,
|
||||
) {
|
||||
loading.value = false
|
||||
|
||||
if (plan === null) {
|
||||
|
||||
@@ -552,7 +552,7 @@ import Checkbox from '../base/Checkbox.vue'
|
||||
import Slider from '../base/Slider.vue'
|
||||
import AnimatedLogo from '../brand/AnimatedLogo.vue'
|
||||
import NewModal from '../modal/NewModal.vue'
|
||||
import LoaderIcon from '../servers/LoaderIcon.vue'
|
||||
import LoaderIcon from '../servers/icons/LoaderIcon.vue'
|
||||
|
||||
const { locale, formatMessage } = useVIntl()
|
||||
|
||||
|
||||
@@ -1,23 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import type { Labrinth } from '@modrinth/api-client'
|
||||
import { formatPrice } from '@modrinth/utils'
|
||||
import { defineMessages, useVIntl } from '@vintl/vintl'
|
||||
import { computed, provide } from 'vue'
|
||||
|
||||
import { monthsInInterval, type ServerBillingInterval, type ServerPlan } from '../../utils/billing'
|
||||
import { getPriceForInterval, monthsInInterval } from '../../utils/product-utils'
|
||||
import OptionGroup from '../base/OptionGroup.vue'
|
||||
import ModalBasedServerPlan from './ModalBasedServerPlan.vue'
|
||||
import type { ServerBillingInterval } from './ModrinthServersPurchaseModal.vue'
|
||||
|
||||
const { formatMessage, locale } = useVIntl()
|
||||
|
||||
const props = defineProps<{
|
||||
availableProducts: ServerPlan[]
|
||||
availableProducts: Labrinth.Billing.Internal.Product[]
|
||||
currency: string
|
||||
existingPlan?: ServerPlan
|
||||
existingPlan?: Labrinth.Billing.Internal.Product
|
||||
}>()
|
||||
|
||||
const availableBillingIntervals = ['monthly', 'quarterly']
|
||||
|
||||
const selectedPlan = defineModel<ServerPlan>('plan')
|
||||
const selectedPlan = defineModel<Labrinth.Billing.Internal.Product>('plan')
|
||||
const selectedInterval = defineModel<ServerBillingInterval>('interval')
|
||||
const emit = defineEmits<{
|
||||
(e: 'choose-custom'): void
|
||||
@@ -75,7 +77,10 @@ const isSameAsExistingPlan = computed(() => {
|
||||
})
|
||||
|
||||
const plansByRam = computed(() => {
|
||||
const byName: Record<'small' | 'medium' | 'large', ServerPlan | undefined> = {
|
||||
const byName: Record<
|
||||
'small' | 'medium' | 'large',
|
||||
Labrinth.Billing.Internal.Product | undefined
|
||||
> = {
|
||||
small: undefined,
|
||||
medium: undefined,
|
||||
large: undefined,
|
||||
@@ -93,13 +98,11 @@ function handleCustomPlan() {
|
||||
emit('choose-custom')
|
||||
}
|
||||
|
||||
function pricePerMonth(plan?: ServerPlan) {
|
||||
if (!plan) return undefined
|
||||
const total = plan.prices?.find((x) => x.currency_code === props.currency)?.prices?.intervals?.[
|
||||
selectedInterval.value!
|
||||
]
|
||||
function pricePerMonth(plan?: Labrinth.Billing.Internal.Product) {
|
||||
if (!plan || !selectedInterval.value) return undefined
|
||||
const total = getPriceForInterval(plan, props.currency, selectedInterval.value)
|
||||
if (!total) return undefined
|
||||
return total / monthsInInterval[selectedInterval.value!]
|
||||
return total / monthsInInterval[selectedInterval.value]
|
||||
}
|
||||
|
||||
const customPricePerGb = computed(() => {
|
||||
@@ -107,7 +110,9 @@ const customPricePerGb = computed(() => {
|
||||
let min: number | undefined
|
||||
for (const p of props.availableProducts) {
|
||||
const perMonth = pricePerMonth(p)
|
||||
const ramGb = (p?.metadata?.ram ?? 0) / 1024
|
||||
const metadata = p?.metadata
|
||||
if (!metadata || (metadata.type !== 'pyro' && metadata.type !== 'medal')) continue
|
||||
const ramGb = metadata.ram / 1024
|
||||
if (perMonth && ramGb > 0) {
|
||||
const perGb = perMonth / ramGb
|
||||
if (min === undefined || perGb < min) min = perGb
|
||||
|
||||
@@ -1,44 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import type { Archon, Labrinth } from '@modrinth/api-client'
|
||||
import { InfoIcon, SpinnerIcon, XIcon } from '@modrinth/assets'
|
||||
import { defineMessages, useVIntl } from '@vintl/vintl'
|
||||
import { IntlFormatted } from '@vintl/vintl/components'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
|
||||
import { formatPrice } from '../../../../utils'
|
||||
import {
|
||||
monthsInInterval,
|
||||
type ServerBillingInterval,
|
||||
type ServerPlan,
|
||||
type ServerRegion,
|
||||
type ServerStockRequest,
|
||||
} from '../../utils/billing'
|
||||
import { getPriceForInterval, monthsInInterval } from '../../utils/product-utils.ts'
|
||||
import { regionOverrides } from '../../utils/regions.ts'
|
||||
import Slider from '../base/Slider.vue'
|
||||
import ModalLoadingIndicator from '../modal/ModalLoadingIndicator.vue'
|
||||
import type { RegionPing } from './ModrinthServersPurchaseModal.vue'
|
||||
import type { RegionPing, ServerBillingInterval } from './ModrinthServersPurchaseModal.vue'
|
||||
import ServersRegionButton from './ServersRegionButton.vue'
|
||||
import ServersSpecs from './ServersSpecs.vue'
|
||||
|
||||
const { formatMessage, locale } = useVIntl()
|
||||
|
||||
const props = defineProps<{
|
||||
regions: ServerRegion[]
|
||||
regions: Archon.Servers.v1.Region[]
|
||||
pings: RegionPing[]
|
||||
fetchStock: (region: ServerRegion, request: ServerStockRequest) => Promise<number>
|
||||
fetchStock: (
|
||||
region: Archon.Servers.v1.Region,
|
||||
request: Archon.Servers.v0.StockRequest,
|
||||
) => Promise<number>
|
||||
custom: boolean
|
||||
currency: string
|
||||
interval: ServerBillingInterval
|
||||
availableProducts: ServerPlan[]
|
||||
availableProducts: Labrinth.Billing.Internal.Product[]
|
||||
}>()
|
||||
|
||||
const loading = ref(true)
|
||||
const checkingCustomStock = ref(false)
|
||||
const selectedPlan = defineModel<ServerPlan>('plan')
|
||||
const selectedPlan = defineModel<Labrinth.Billing.Internal.Product>('plan')
|
||||
const selectedRegion = defineModel<string>('region')
|
||||
|
||||
const selectedPrice = computed(() => {
|
||||
const amount = selectedPlan.value?.prices?.find((price) => price.currency_code === props.currency)
|
||||
?.prices?.intervals?.[props.interval]
|
||||
if (!selectedPlan.value) return undefined
|
||||
const amount = getPriceForInterval(selectedPlan.value, props.currency, props.interval)
|
||||
return amount ? amount / monthsInInterval[props.interval] : undefined
|
||||
})
|
||||
|
||||
@@ -67,7 +65,13 @@ const selectedRam = ref<number>(-1)
|
||||
|
||||
const ramOptions = computed(() => {
|
||||
return props.availableProducts
|
||||
.map((product) => (product.metadata.ram ?? 0) / 1024)
|
||||
.map((product) => {
|
||||
const metadata = product.metadata
|
||||
if (metadata.type === 'pyro' || metadata.type === 'medal') {
|
||||
return metadata.ram / 1024
|
||||
}
|
||||
return 0
|
||||
})
|
||||
.filter((x) => x > 0)
|
||||
})
|
||||
|
||||
@@ -80,38 +84,63 @@ const maxRam = computed(() => {
|
||||
|
||||
const lowestProduct = computed(() => {
|
||||
return (
|
||||
props.availableProducts.find(
|
||||
(product) => (product.metadata.ram ?? 0) / 1024 === minRam.value,
|
||||
) ?? props.availableProducts[0]
|
||||
props.availableProducts.find((product) => {
|
||||
const metadata = product.metadata
|
||||
return (
|
||||
(metadata.type === 'pyro' || metadata.type === 'medal') &&
|
||||
metadata.ram / 1024 === minRam.value
|
||||
)
|
||||
}) ?? props.availableProducts[0]
|
||||
)
|
||||
})
|
||||
|
||||
const selectedPlanSpecs = computed(() => {
|
||||
if (!selectedPlan.value) return null
|
||||
const metadata = selectedPlan.value.metadata
|
||||
if (metadata.type === 'pyro' || metadata.type === 'medal') {
|
||||
return {
|
||||
ram: metadata.ram,
|
||||
storage: metadata.storage,
|
||||
cpu: metadata.cpu,
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
function updateRamStock(regionToCheck: string, newRam: number) {
|
||||
if (newRam > 0) {
|
||||
checkingCustomStock.value = true
|
||||
const plan = props.availableProducts.find(
|
||||
(product) => (product.metadata.ram ?? 0) / 1024 === newRam,
|
||||
)
|
||||
const plan = props.availableProducts.find((product) => {
|
||||
const metadata = product.metadata
|
||||
return (
|
||||
(metadata.type === 'pyro' || metadata.type === 'medal') && metadata.ram / 1024 === newRam
|
||||
)
|
||||
})
|
||||
if (plan) {
|
||||
const region = sortedRegions.value.find((region) => region.shortcode === regionToCheck)
|
||||
if (region) {
|
||||
props
|
||||
.fetchStock(region, {
|
||||
cpu: plan.metadata.cpu ?? 0,
|
||||
memory_mb: plan.metadata.ram ?? 0,
|
||||
swap_mb: plan.metadata.swap ?? 0,
|
||||
storage_mb: plan.metadata.storage ?? 0,
|
||||
})
|
||||
.then((stock: number) => {
|
||||
if (stock > 0) {
|
||||
selectedPlan.value = plan
|
||||
} else {
|
||||
selectedPlan.value = undefined
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
checkingCustomStock.value = false
|
||||
})
|
||||
const metadata = plan.metadata
|
||||
if (metadata.type === 'pyro' || metadata.type === 'medal') {
|
||||
props
|
||||
.fetchStock(region, {
|
||||
cpu: metadata.cpu,
|
||||
memory_mb: metadata.ram,
|
||||
swap_mb: metadata.swap,
|
||||
storage_mb: metadata.storage,
|
||||
})
|
||||
.then((stock: number) => {
|
||||
if (stock > 0) {
|
||||
selectedPlan.value = plan
|
||||
} else {
|
||||
selectedPlan.value = undefined
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
checkingCustomStock.value = false
|
||||
})
|
||||
} else {
|
||||
checkingCustomStock.value = false
|
||||
}
|
||||
} else {
|
||||
checkingCustomStock.value = false
|
||||
}
|
||||
@@ -151,22 +180,28 @@ const messages = defineMessages({
|
||||
|
||||
async function updateStock() {
|
||||
currentStock.value = {}
|
||||
|
||||
const getStockRequest = (
|
||||
product: Labrinth.Billing.Internal.Product,
|
||||
): Archon.Servers.v0.StockRequest => {
|
||||
const metadata = product.metadata
|
||||
if (metadata.type === 'pyro' || metadata.type === 'medal') {
|
||||
return {
|
||||
cpu: metadata.cpu,
|
||||
memory_mb: metadata.ram,
|
||||
swap_mb: metadata.swap,
|
||||
storage_mb: metadata.storage,
|
||||
}
|
||||
}
|
||||
return { cpu: 0, memory_mb: 0, swap_mb: 0, storage_mb: 0 }
|
||||
}
|
||||
|
||||
const capacityChecks = sortedRegions.value.map((region) =>
|
||||
props.fetchStock(
|
||||
region,
|
||||
selectedPlan.value
|
||||
? {
|
||||
cpu: selectedPlan.value?.metadata.cpu ?? 0,
|
||||
memory_mb: selectedPlan.value?.metadata.ram ?? 0,
|
||||
swap_mb: selectedPlan.value?.metadata.swap ?? 0,
|
||||
storage_mb: selectedPlan.value?.metadata.storage ?? 0,
|
||||
}
|
||||
: {
|
||||
cpu: lowestProduct.value.metadata.cpu ?? 0,
|
||||
memory_mb: lowestProduct.value.metadata.ram ?? 0,
|
||||
swap_mb: lowestProduct.value.metadata.swap ?? 0,
|
||||
storage_mb: lowestProduct.value.metadata.storage ?? 0,
|
||||
},
|
||||
? getStockRequest(selectedPlan.value)
|
||||
: getStockRequest(lowestProduct.value),
|
||||
),
|
||||
)
|
||||
const results = await Promise.all(capacityChecks)
|
||||
@@ -255,12 +290,12 @@ onMounted(() => {
|
||||
<div v-if="checkingCustomStock" class="flex gap-2 items-center">
|
||||
<SpinnerIcon class="size-5 shrink-0 animate-spin" /> Checking availability...
|
||||
</div>
|
||||
<div v-else-if="selectedPlan">
|
||||
<div v-else-if="selectedPlanSpecs">
|
||||
<ServersSpecs
|
||||
class="!flex-row justify-between"
|
||||
:ram="selectedPlan.metadata.ram ?? 0"
|
||||
:storage="selectedPlan.metadata.storage ?? 0"
|
||||
:cpus="selectedPlan.metadata.cpu ?? 0"
|
||||
:ram="selectedPlanSpecs.ram"
|
||||
:storage="selectedPlanSpecs.storage"
|
||||
:cpus="selectedPlanSpecs.cpu"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="flex gap-2 items-center">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { Archon, Labrinth } from '@modrinth/api-client'
|
||||
import {
|
||||
EditIcon,
|
||||
ExternalIcon,
|
||||
@@ -9,18 +10,13 @@ import {
|
||||
SpinnerIcon,
|
||||
XIcon,
|
||||
} from '@modrinth/assets'
|
||||
import { formatPrice, getPingLevel, type UserSubscription } from '@modrinth/utils'
|
||||
import { formatPrice, getPingLevel } from '@modrinth/utils'
|
||||
import { useVIntl } from '@vintl/vintl'
|
||||
import dayjs from 'dayjs'
|
||||
import type Stripe from 'stripe'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import {
|
||||
monthsInInterval,
|
||||
type ServerBillingInterval,
|
||||
type ServerPlan,
|
||||
type ServerRegion,
|
||||
} from '../../utils/billing'
|
||||
import { getPriceForInterval, monthsInInterval } from '../../utils/product-utils'
|
||||
import { regionOverrides } from '../../utils/regions'
|
||||
import ButtonStyled from '../base/ButtonStyled.vue'
|
||||
import Checkbox from '../base/Checkbox.vue'
|
||||
@@ -28,6 +24,7 @@ import TagItem from '../base/TagItem.vue'
|
||||
import ModrinthServersIcon from '../servers/ModrinthServersIcon.vue'
|
||||
import ExpandableInvoiceTotal from './ExpandableInvoiceTotal.vue'
|
||||
import FormattedPaymentMethod from './FormattedPaymentMethod.vue'
|
||||
import type { ServerBillingInterval } from './ModrinthServersPurchaseModal.vue'
|
||||
import ServersSpecs from './ServersSpecs.vue'
|
||||
|
||||
const vintl = useVIntl()
|
||||
@@ -38,8 +35,8 @@ const emit = defineEmits<{
|
||||
}>()
|
||||
|
||||
const props = defineProps<{
|
||||
plan: ServerPlan
|
||||
region: ServerRegion
|
||||
plan: Labrinth.Billing.Internal.Product
|
||||
region: Archon.Servers.v1.Region
|
||||
tax?: number
|
||||
total?: number
|
||||
currency: string
|
||||
@@ -48,25 +45,28 @@ const props = defineProps<{
|
||||
selectedPaymentMethod: Stripe.PaymentMethod | undefined
|
||||
hasPaymentMethod?: boolean
|
||||
noPaymentRequired?: boolean
|
||||
existingPlan?: ServerPlan
|
||||
existingSubscription?: UserSubscription
|
||||
existingPlan?: Labrinth.Billing.Internal.Product
|
||||
existingSubscription?: Labrinth.Billing.Internal.UserSubscription
|
||||
}>()
|
||||
|
||||
const interval = defineModel<ServerBillingInterval>('interval', { required: true })
|
||||
const acceptedEula = defineModel<boolean>('acceptedEula', { required: true })
|
||||
|
||||
const prices = computed(() => {
|
||||
return props.plan.prices.find((x) => x.currency_code === props.currency)
|
||||
})
|
||||
|
||||
const selectedPlanPriceForInterval = computed<number | undefined>(() => {
|
||||
return prices.value?.prices?.intervals?.[interval.value as keyof typeof monthsInInterval]
|
||||
return getPriceForInterval(props.plan, props.currency, interval.value)
|
||||
})
|
||||
|
||||
const existingPlanPriceForInterval = computed<number | undefined>(() => {
|
||||
if (!props.existingPlan) return undefined
|
||||
const p = props.existingPlan.prices.find((x) => x.currency_code === props.currency)
|
||||
return p?.prices?.intervals?.[interval.value as keyof typeof monthsInInterval]
|
||||
return getPriceForInterval(props.existingPlan, props.currency, interval.value)
|
||||
})
|
||||
|
||||
const monthlyPrice = computed<number | undefined>(() => {
|
||||
return getPriceForInterval(props.plan, props.currency, 'monthly')
|
||||
})
|
||||
|
||||
const quarterlyPrice = computed<number | undefined>(() => {
|
||||
return getPriceForInterval(props.plan, props.currency, 'quarterly')
|
||||
})
|
||||
|
||||
const upgradeDeltaPrice = computed<number | undefined>(() => {
|
||||
@@ -137,6 +137,18 @@ const planName = computed(() => {
|
||||
return 'Custom'
|
||||
})
|
||||
|
||||
const planSpecs = computed(() => {
|
||||
const metadata = props.plan.metadata
|
||||
if (metadata.type === 'pyro' || metadata.type === 'medal') {
|
||||
return {
|
||||
ram: metadata.ram,
|
||||
storage: metadata.storage,
|
||||
cpu: metadata.cpu,
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
const flag = computed(
|
||||
() =>
|
||||
regionOverrides[props.region.shortcode]?.flag ??
|
||||
@@ -173,11 +185,11 @@ function setInterval(newInterval: ServerBillingInterval) {
|
||||
</div>
|
||||
<div>
|
||||
<ServersSpecs
|
||||
v-if="plan.metadata && plan.metadata.ram && plan.metadata.storage && plan.metadata.cpu"
|
||||
v-if="planSpecs"
|
||||
class="!grid sm:grid-cols-2"
|
||||
:ram="plan.metadata.ram"
|
||||
:storage="plan.metadata.storage"
|
||||
:cpus="plan.metadata.cpu"
|
||||
:ram="planSpecs.ram"
|
||||
:storage="planSpecs.storage"
|
||||
:cpus="planSpecs.cpu"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -234,8 +246,7 @@ function setInterval(newInterval: ServerBillingInterval) {
|
||||
>Pay monthly</span
|
||||
>
|
||||
<span class="text-sm text-secondary flex items-center gap-1"
|
||||
>{{ formatPrice(locale, prices?.prices.intervals['monthly'], currency, true) }} /
|
||||
month</span
|
||||
>{{ formatPrice(locale, monthlyPrice, currency, true) }} / month</span
|
||||
>
|
||||
</div>
|
||||
</button>
|
||||
@@ -261,7 +272,7 @@ function setInterval(newInterval: ServerBillingInterval) {
|
||||
>{{
|
||||
formatPrice(
|
||||
locale,
|
||||
(prices?.prices?.intervals?.['quarterly'] ?? 0) / monthsInInterval['quarterly'],
|
||||
(quarterlyPrice ?? 0) / monthsInInterval['quarterly'],
|
||||
currency,
|
||||
true,
|
||||
)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import type { Archon } from '@modrinth/api-client'
|
||||
import { SignalIcon, SpinnerIcon } from '@modrinth/assets'
|
||||
import { getPingLevel } from '@modrinth/utils'
|
||||
import { useVIntl } from '@vintl/vintl'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import type { ServerRegion } from '../../utils/billing'
|
||||
import { regionOverrides } from '../../utils/regions'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
@@ -12,7 +12,7 @@ const { formatMessage } = useVIntl()
|
||||
const currentRegion = defineModel<string | undefined>({ required: true })
|
||||
|
||||
const props = defineProps<{
|
||||
region: ServerRegion
|
||||
region: Archon.Servers.v1.Region
|
||||
ping?: number
|
||||
bestPing?: boolean
|
||||
outOfStock?: boolean
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
<template>
|
||||
<ModrinthServersPurchaseModal
|
||||
v-if="customer && regionsData"
|
||||
ref="purchaseModal"
|
||||
:publishable-key="props.stripePublishableKey"
|
||||
:initiate-payment="async (body) => await initiatePayment(body)"
|
||||
:available-products="pyroProducts"
|
||||
:on-error="handleError"
|
||||
:customer="customer"
|
||||
:payment-methods="paymentMethods"
|
||||
:currency="selectedCurrency"
|
||||
:return-url="`${props.siteUrl}/servers/manage`"
|
||||
:pings="regionPings"
|
||||
:regions="regionsData"
|
||||
:refresh-payment-methods="fetchPaymentData"
|
||||
:fetch-stock="fetchStock"
|
||||
:plan-stage="true"
|
||||
:existing-plan="currentPlanFromSubscription"
|
||||
:existing-subscription="subscription || undefined"
|
||||
:on-finalize-no-payment-change="finalizeDowngrade"
|
||||
@hide="
|
||||
() => {
|
||||
debug('modal hidden, resetting subscription')
|
||||
subscription = null
|
||||
}
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { Archon, Labrinth } from '@modrinth/api-client'
|
||||
import {
|
||||
injectModrinthClient,
|
||||
injectNotificationManager,
|
||||
ModrinthServersPurchaseModal,
|
||||
useDebugLogger,
|
||||
} from '@modrinth/ui'
|
||||
import { useMutation, useQuery } from '@tanstack/vue-query'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
stripePublishableKey: string
|
||||
siteUrl: string
|
||||
products: Labrinth.Billing.Internal.Product[]
|
||||
}>()
|
||||
|
||||
const { addNotification } = injectNotificationManager()
|
||||
const { labrinth, archon } = injectModrinthClient()
|
||||
const debug = useDebugLogger('ServersUpgradeModalWrapper')
|
||||
const purchaseModal = ref<InstanceType<typeof ModrinthServersPurchaseModal> | null>(null)
|
||||
|
||||
// stripe type
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const customer = ref<any>(null)
|
||||
|
||||
// stripe type
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const paymentMethods = ref<any[]>([])
|
||||
const selectedCurrency = ref<string>('USD')
|
||||
|
||||
const regionPings = ref<
|
||||
{
|
||||
region: string
|
||||
ping: number
|
||||
}[]
|
||||
>([])
|
||||
|
||||
const pyroProducts = (props.products as Labrinth.Billing.Internal.Product[])
|
||||
.filter((p) => p?.metadata?.type === 'pyro' || p?.metadata?.type === 'medal')
|
||||
.sort((a, b) => {
|
||||
const aRam = a?.metadata?.type === 'pyro' || a?.metadata?.type === 'medal' ? a.metadata.ram : 0
|
||||
const bRam = b?.metadata?.type === 'pyro' || b?.metadata?.type === 'medal' ? b.metadata.ram : 0
|
||||
return aRam - bRam
|
||||
})
|
||||
|
||||
function handleError(err: unknown) {
|
||||
debug('Purchase modal error:', err)
|
||||
}
|
||||
|
||||
const { data: customerData } = useQuery({
|
||||
queryKey: ['billing', 'customer'],
|
||||
queryFn: () => labrinth.billing_internal.getCustomer(),
|
||||
})
|
||||
|
||||
const { data: paymentMethodsData, refetch: refetchPaymentMethods } = useQuery({
|
||||
queryKey: ['billing', 'payment-methods'],
|
||||
queryFn: () => labrinth.billing_internal.getPaymentMethods(),
|
||||
})
|
||||
|
||||
const { data: regionsData } = useQuery({
|
||||
queryKey: ['servers', 'regions'],
|
||||
queryFn: () => archon.servers_v1.getRegions(),
|
||||
})
|
||||
|
||||
watch(customerData, (newCustomer) => {
|
||||
if (newCustomer) customer.value = newCustomer
|
||||
})
|
||||
|
||||
watch(paymentMethodsData, (newMethods) => {
|
||||
if (newMethods) paymentMethods.value = newMethods
|
||||
})
|
||||
|
||||
watch(regionsData, (newRegions) => {
|
||||
if (newRegions) {
|
||||
newRegions.forEach((region) => {
|
||||
runPingTest(region)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
async function fetchPaymentData() {
|
||||
await refetchPaymentMethods()
|
||||
}
|
||||
|
||||
async function fetchStock(
|
||||
region: Archon.Servers.v1.Region,
|
||||
request: Archon.Servers.v0.StockRequest,
|
||||
): Promise<number> {
|
||||
const result = await archon.servers_v0.checkStock(region.shortcode, request)
|
||||
return result.available
|
||||
}
|
||||
|
||||
const PING_COUNT = 20
|
||||
const PING_INTERVAL = 200
|
||||
const MAX_PING_TIME = 1000
|
||||
|
||||
function runPingTest(region: Archon.Servers.v1.Region, 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<Labrinth.Billing.Internal.UserSubscription | null>(null)
|
||||
// Dry run state
|
||||
const dryRunResponse = ref<{
|
||||
requires_payment: boolean
|
||||
required_payment_is_proration: boolean
|
||||
} | null>(null)
|
||||
const pendingDowngradeBody = ref<Labrinth.Billing.Internal.EditSubscriptionRequest | null>(null)
|
||||
const currentPlanFromSubscription = computed<Labrinth.Billing.Internal.Product | undefined>(() => {
|
||||
return subscription.value
|
||||
? pyroProducts.find((p) =>
|
||||
p.prices.some((price) => price.id === subscription.value?.price_id),
|
||||
) ?? undefined
|
||||
: undefined
|
||||
})
|
||||
|
||||
const currentInterval = computed<'monthly' | 'quarterly'>(() => {
|
||||
const interval = subscription.value?.interval
|
||||
|
||||
if (interval === 'monthly' || interval === 'quarterly') {
|
||||
return interval
|
||||
}
|
||||
|
||||
return 'monthly'
|
||||
})
|
||||
|
||||
const editSubscriptionMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
id,
|
||||
body,
|
||||
dry,
|
||||
}: {
|
||||
id: string
|
||||
body: Labrinth.Billing.Internal.EditSubscriptionRequest
|
||||
dry: boolean
|
||||
}) => {
|
||||
return await labrinth.billing_internal.editSubscription(id, body, dry)
|
||||
},
|
||||
})
|
||||
|
||||
async function initiatePayment(
|
||||
body: Labrinth.Billing.Internal.InitiatePaymentRequest,
|
||||
): Promise<Labrinth.Billing.Internal.EditSubscriptionResponse | null> {
|
||||
debug('initiatePayment called', {
|
||||
hasSubscription: !!subscription.value,
|
||||
subscriptionId: subscription.value?.id,
|
||||
body,
|
||||
})
|
||||
if (subscription.value) {
|
||||
const transformedBody: Labrinth.Billing.Internal.EditSubscriptionRequest = {
|
||||
interval: body.charge.type === 'new' ? body.charge.interval : undefined,
|
||||
payment_method: body.type === 'confirmation_token' ? body.token : body.id,
|
||||
product: body.charge.type === 'new' ? body.charge.product_id : undefined,
|
||||
region: body.metadata?.server_region,
|
||||
}
|
||||
|
||||
try {
|
||||
const dry = await editSubscriptionMutation.mutateAsync({
|
||||
id: subscription.value.id,
|
||||
body: transformedBody,
|
||||
dry: true,
|
||||
})
|
||||
|
||||
if (dry && typeof dry === 'object' && 'payment_intent_id' in dry) {
|
||||
dryRunResponse.value = {
|
||||
requires_payment: !!dry.payment_intent_id,
|
||||
required_payment_is_proration: true,
|
||||
}
|
||||
pendingDowngradeBody.value = transformedBody
|
||||
if (dry.payment_intent_id) {
|
||||
return await finalizeImmediate(transformedBody)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
} else {
|
||||
// Fallback if dry run not supported
|
||||
return await finalizeImmediate(transformedBody)
|
||||
}
|
||||
} catch (e) {
|
||||
debug('Dry run failed, attempting immediate patch', e)
|
||||
return await finalizeImmediate(transformedBody)
|
||||
}
|
||||
} else {
|
||||
debug('subscription.value is null/undefined', {
|
||||
subscriptionValue: subscription.value,
|
||||
})
|
||||
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: Labrinth.Billing.Internal.EditSubscriptionRequest) {
|
||||
if (!subscription.value) return null
|
||||
|
||||
const result = await editSubscriptionMutation.mutateAsync({
|
||||
id: subscription.value.id,
|
||||
body,
|
||||
dry: false,
|
||||
})
|
||||
|
||||
return result ?? null
|
||||
}
|
||||
|
||||
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) {
|
||||
debug('open called', { id })
|
||||
if (id) {
|
||||
const subscriptions = await labrinth.billing_internal.getSubscriptions()
|
||||
debug('fetched subscriptions', {
|
||||
count: subscriptions.length,
|
||||
subscriptions: subscriptions.map((s) => ({
|
||||
id: s.id,
|
||||
metadataType: s.metadata?.type,
|
||||
metadataId: s.metadata?.id,
|
||||
})),
|
||||
})
|
||||
for (const sub of subscriptions) {
|
||||
if (
|
||||
(sub?.metadata?.type === 'pyro' || sub?.metadata?.type === 'medal') &&
|
||||
sub.metadata.id === id
|
||||
) {
|
||||
subscription.value = sub
|
||||
debug('found matching subscription', {
|
||||
subscriptionId: sub.id,
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!subscription.value) {
|
||||
debug('no matching subscription found for id', id)
|
||||
}
|
||||
} else {
|
||||
debug('no id provided, resetting subscription')
|
||||
subscription.value = null
|
||||
}
|
||||
|
||||
purchaseModal.value?.show(currentInterval.value)
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
open,
|
||||
})
|
||||
</script>
|
||||
@@ -108,6 +108,7 @@ export { default as AffiliateLinkCreateModal } from './affiliate/AffiliateLinkCr
|
||||
export { default as AddPaymentMethodModal } from './billing/AddPaymentMethodModal.vue'
|
||||
export { default as ModrinthServersPurchaseModal } from './billing/ModrinthServersPurchaseModal.vue'
|
||||
export { default as PurchaseModal } from './billing/PurchaseModal.vue'
|
||||
export { default as ServersUpgradeModalWrapper } from './billing/ServersUpgradeModalWrapper.vue'
|
||||
|
||||
// Skins
|
||||
export { default as CapeButton } from './skin/CapeButton.vue'
|
||||
@@ -127,4 +128,11 @@ export { default as ThemeSelector } from './settings/ThemeSelector.vue'
|
||||
// Servers
|
||||
export { default as ServersSpecs } from './billing/ServersSpecs.vue'
|
||||
export { default as BackupWarning } from './servers/backups/BackupWarning.vue'
|
||||
export { default as LoaderIcon } from './servers/icons/LoaderIcon.vue'
|
||||
export { default as ServerIcon } from './servers/icons/ServerIcon.vue'
|
||||
export { default as ServerInfoLabels } from './servers/labels/ServerInfoLabels.vue'
|
||||
export { default as MedalBackgroundImage } from './servers/marketing/MedalBackgroundImage.vue'
|
||||
export { default as MedalServerListing } from './servers/marketing/MedalServerListing.vue'
|
||||
export type { PendingChange } from './servers/ServerListing.vue'
|
||||
export { default as ServerListing } from './servers/ServerListing.vue'
|
||||
export { default as ServersPromo } from './servers/ServersPromo.vue'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
import type { EnvironmentV3 } from '@modrinth/utils'
|
||||
import { defineMessage, type MessageDescriptor, useVIntl } from '@vintl/vintl'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
@@ -8,7 +7,7 @@ import LargeRadioButton from '../../../base/LargeRadioButton.vue'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
|
||||
const value = defineModel<EnvironmentV3 | undefined>({ required: true })
|
||||
const value = defineModel<string | undefined>({ required: true })
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
@@ -135,7 +134,7 @@ type SubOptionKey = ValidKeys<(typeof OUTER_OPTIONS)[keyof typeof OUTER_OPTIONS]
|
||||
const currentOuterOption = ref<OuterOptionKey>()
|
||||
const currentSubOption = ref<SubOptionKey>()
|
||||
|
||||
const computedOption = computed<EnvironmentV3>(() => {
|
||||
const computedOption = computed<string>(() => {
|
||||
switch (currentOuterOption.value) {
|
||||
case 'client':
|
||||
return 'client_only'
|
||||
|
||||
245
packages/ui/src/components/servers/ServerListing.vue
Normal file
245
packages/ui/src/components/servers/ServerListing.vue
Normal file
@@ -0,0 +1,245 @@
|
||||
<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"
|
||||
>
|
||||
<LoaderCircleIcon class="size-5 animate-spin" />
|
||||
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">
|
||||
<TriangleAlertIcon 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">
|
||||
<TriangleAlertIcon 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">
|
||||
<TriangleAlertIcon 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 type { Archon, ProjectV2 } from '@modrinth/api-client'
|
||||
import {
|
||||
ChevronRightIcon,
|
||||
LoaderCircleIcon,
|
||||
LockIcon,
|
||||
SparklesIcon,
|
||||
TriangleAlertIcon,
|
||||
} from '@modrinth/assets'
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import dayjs from 'dayjs'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { injectModrinthClient } from '../../providers/api-client'
|
||||
import Avatar from '../base/Avatar.vue'
|
||||
import CopyCode from '../base/CopyCode.vue'
|
||||
import ServersSpecs from '../billing/ServersSpecs.vue'
|
||||
import ServerIcon from './icons/ServerIcon.vue'
|
||||
import ServerInfoLabels from './labels/ServerInfoLabels.vue'
|
||||
|
||||
export 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<Archon.Servers.v0.Server> & { pendingChange?: PendingChange }>()
|
||||
|
||||
const { archon, kyros, labrinth } = injectModrinthClient()
|
||||
|
||||
const showGameLabel = computed(() => !!props.game)
|
||||
const showLoaderLabel = computed(() => !!props.loader)
|
||||
|
||||
const { data: projectData } = useQuery({
|
||||
queryKey: ['project', props.upstream?.project_id] as const,
|
||||
queryFn: async (): Promise<ProjectV2 | null> => {
|
||||
if (!props.upstream?.project_id) return null
|
||||
return await labrinth.projects_v2.get(props.upstream.project_id)
|
||||
},
|
||||
enabled: computed(() => !!props.upstream?.project_id),
|
||||
})
|
||||
|
||||
const iconUrl = computed(() => projectData.value?.icon_url)
|
||||
|
||||
async function processImageBlob(blob: Blob, size: number): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx = canvas.getContext('2d')!
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
canvas.width = size
|
||||
canvas.height = size
|
||||
ctx.drawImage(img, 0, 0, size, size)
|
||||
const dataURL = canvas.toDataURL('image/png')
|
||||
URL.revokeObjectURL(img.src)
|
||||
resolve(dataURL)
|
||||
}
|
||||
img.src = URL.createObjectURL(blob)
|
||||
})
|
||||
}
|
||||
|
||||
async function dataURLToBlob(dataURL: string): Promise<Blob> {
|
||||
const res = await fetch(dataURL)
|
||||
return res.blob()
|
||||
}
|
||||
|
||||
const { data: image } = useQuery({
|
||||
queryKey: ['server-icon', props.server_id] as const,
|
||||
queryFn: async (): Promise<string | undefined> => {
|
||||
if (!props.server_id || props.status !== 'available') return undefined
|
||||
|
||||
try {
|
||||
const auth = await archon.servers_v0.getFilesystemAuth(props.server_id)
|
||||
|
||||
try {
|
||||
const blob = await kyros.files_v0.downloadFile(
|
||||
auth.url,
|
||||
auth.token,
|
||||
'/server-icon-original.png',
|
||||
)
|
||||
|
||||
return await processImageBlob(blob, 512)
|
||||
} catch {
|
||||
const projectIcon = iconUrl.value
|
||||
if (projectIcon) {
|
||||
const response = await fetch(projectIcon)
|
||||
const blob = await response.blob()
|
||||
|
||||
const scaledDataUrl = await processImageBlob(blob, 64)
|
||||
const scaledBlob = await dataURLToBlob(scaledDataUrl)
|
||||
const scaledFile = new File([scaledBlob], 'server-icon.png', { type: 'image/png' })
|
||||
|
||||
await kyros.files_v0.uploadFile(auth.url, auth.token, '/server-icon.png', scaledFile)
|
||||
|
||||
const originalFile = new File([blob], 'server-icon-original.png', {
|
||||
type: 'image/png',
|
||||
})
|
||||
await kyros.files_v0.uploadFile(
|
||||
auth.url,
|
||||
auth.token,
|
||||
'/server-icon-original.png',
|
||||
originalFile,
|
||||
)
|
||||
|
||||
return scaledDataUrl
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.debug('Icon processing failed:', error)
|
||||
return undefined
|
||||
}
|
||||
},
|
||||
enabled: computed(() => !!props.server_id && props.status === 'available'),
|
||||
})
|
||||
|
||||
const isConfiguring = computed(() => props.flows?.intro)
|
||||
|
||||
const formatDate = (d: unknown) => {
|
||||
try {
|
||||
return dayjs(d as string).format('MMMM D, YYYY')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
28
packages/ui/src/components/servers/icons/ServerIcon.vue
Normal file
28
packages/ui/src/components/servers/icons/ServerIcon.vue
Normal file
@@ -0,0 +1,28 @@
|
||||
<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="MinecraftServerIcon"
|
||||
/>
|
||||
</client-only>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { MinecraftServerIcon } from '@modrinth/assets'
|
||||
|
||||
defineProps<{
|
||||
image: string | undefined
|
||||
}>()
|
||||
</script>
|
||||
@@ -0,0 +1,42 @@
|
||||
<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" />
|
||||
<AutoLink
|
||||
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>
|
||||
</AutoLink>
|
||||
<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'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
import AutoLink from '../../base/AutoLink.vue'
|
||||
|
||||
defineProps<{
|
||||
game: string
|
||||
mcVersion: string
|
||||
isLink?: boolean
|
||||
}>()
|
||||
|
||||
const route = useRoute()
|
||||
const serverId = route.params.id as string
|
||||
</script>
|
||||
@@ -0,0 +1,46 @@
|
||||
<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 {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
serverData: Record<string, any>
|
||||
showGameLabel: boolean
|
||||
showLoaderLabel: boolean
|
||||
uptimeSeconds?: number
|
||||
column?: boolean
|
||||
linked?: boolean
|
||||
}
|
||||
|
||||
defineProps<ServerInfoLabelsProps>()
|
||||
</script>
|
||||
@@ -0,0 +1,51 @@
|
||||
<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>
|
||||
<AutoLink
|
||||
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>
|
||||
</AutoLink>
|
||||
<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 { useRoute } from 'vue-router'
|
||||
|
||||
import AutoLink from '../../base/AutoLink.vue'
|
||||
import LoaderIcon from '../icons/LoaderIcon.vue'
|
||||
|
||||
defineProps<{
|
||||
noSeparator?: boolean
|
||||
loader?: 'Fabric' | 'Quilt' | 'Forge' | 'NeoForge' | 'Paper' | 'Spigot' | 'Bukkit' | 'Vanilla'
|
||||
loaderVersion?: string
|
||||
isLink?: boolean
|
||||
}>()
|
||||
|
||||
const route = useRoute()
|
||||
const serverId = route.params.id as string
|
||||
</script>
|
||||
@@ -0,0 +1,52 @@
|
||||
<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'
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
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 = useRoute()
|
||||
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>
|
||||
@@ -0,0 +1,66 @@
|
||||
<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">
|
||||
<TimerIcon 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 { TimerIcon } from '@modrinth/assets'
|
||||
import { computed } from '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>
|
||||
@@ -0,0 +1,58 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
@@ -0,0 +1,236 @@
|
||||
<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 v-if="isNuxt" 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"
|
||||
>
|
||||
<LoaderCircleIcon class="size-5 animate-spin" />
|
||||
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">
|
||||
<TriangleAlertIcon 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">
|
||||
<TriangleAlertIcon 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">
|
||||
<TriangleAlertIcon 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 { type Archon, NuxtModrinthClient } from '@modrinth/api-client'
|
||||
import {
|
||||
ChevronRightIcon,
|
||||
LoaderCircleIcon,
|
||||
LockIcon,
|
||||
RocketIcon,
|
||||
SparklesIcon,
|
||||
TriangleAlertIcon,
|
||||
} from '@modrinth/assets'
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import dayjs from 'dayjs'
|
||||
import dayjsDuration from 'dayjs/plugin/duration'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
|
||||
import { injectModrinthClient } from '../../../providers/api-client'
|
||||
import AutoLink from '../../base/AutoLink.vue'
|
||||
import Avatar from '../../base/Avatar.vue'
|
||||
import ButtonStyled from '../../base/ButtonStyled.vue'
|
||||
import CopyCode from '../../base/CopyCode.vue'
|
||||
import ServerInfoLabels from '../labels/ServerInfoLabels.vue'
|
||||
import MedalBackgroundImage from './MedalBackgroundImage.vue'
|
||||
|
||||
dayjs.extend(dayjsDuration)
|
||||
|
||||
const props = defineProps<Partial<Archon.Servers.v0.Server>>()
|
||||
const emit = defineEmits<{ (e: 'upgrade'): void }>()
|
||||
|
||||
const client = injectModrinthClient()
|
||||
|
||||
const isNuxt = computed(() => client instanceof NuxtModrinthClient)
|
||||
|
||||
const showGameLabel = computed(() => !!props.game)
|
||||
const showLoaderLabel = computed(() => !!props.loader)
|
||||
|
||||
const { data: projectData } = useQuery({
|
||||
queryKey: ['server-project', props.server_id, props.upstream?.project_id],
|
||||
queryFn: async () => {
|
||||
if (!props.upstream?.project_id) return null
|
||||
return await client.labrinth.projects_v2.get(props.upstream.project_id)
|
||||
},
|
||||
enabled: !!props.upstream?.project_id,
|
||||
})
|
||||
|
||||
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>
|
||||
@@ -1,19 +1,11 @@
|
||||
import type { Labrinth } from '@modrinth/api-client'
|
||||
import { loadStripe, type Stripe as StripeJs, type StripeElements } from '@stripe/stripe-js'
|
||||
import type { ContactOption } from '@stripe/stripe-js/dist/stripe-js/elements/address'
|
||||
import type Stripe from 'stripe'
|
||||
import { computed, type Ref, ref } from 'vue'
|
||||
|
||||
import type {
|
||||
BasePaymentIntentResponse,
|
||||
ChargeRequestType,
|
||||
CreatePaymentIntentRequest,
|
||||
CreatePaymentIntentResponse,
|
||||
PaymentRequestType,
|
||||
ServerBillingInterval,
|
||||
ServerPlan,
|
||||
UpdatePaymentIntentRequest,
|
||||
UpdatePaymentIntentResponse,
|
||||
} from '../utils/billing.ts'
|
||||
import type { ServerBillingInterval } from '../components/billing/ModrinthServersPurchaseModal.vue'
|
||||
import { getPriceForInterval } from '../utils/product-utils'
|
||||
|
||||
// export type CreateElements = (
|
||||
// paymentMethods: Stripe.PaymentMethod[],
|
||||
@@ -29,13 +21,17 @@ export const useStripe = (
|
||||
customer: Stripe.Customer,
|
||||
paymentMethods: Stripe.PaymentMethod[],
|
||||
currency: string,
|
||||
product: Ref<ServerPlan | undefined>,
|
||||
product: Ref<Labrinth.Billing.Internal.Product | undefined>,
|
||||
interval: Ref<ServerBillingInterval>,
|
||||
region: Ref<string | undefined>,
|
||||
project: Ref<string | undefined>,
|
||||
initiatePayment: (
|
||||
body: CreatePaymentIntentRequest | UpdatePaymentIntentRequest,
|
||||
) => Promise<CreatePaymentIntentResponse | UpdatePaymentIntentResponse | null>,
|
||||
body: Labrinth.Billing.Internal.InitiatePaymentRequest,
|
||||
) => Promise<
|
||||
| Labrinth.Billing.Internal.InitiatePaymentResponse
|
||||
| Labrinth.Billing.Internal.EditSubscriptionResponse
|
||||
| null
|
||||
>,
|
||||
onError: (err: Error) => void,
|
||||
affiliateCode?: Ref<string | null>,
|
||||
) => {
|
||||
@@ -62,18 +58,6 @@ export const useStripe = (
|
||||
stripe.value = await loadStripe(publishableKey)
|
||||
}
|
||||
|
||||
function createIntent(
|
||||
body: CreatePaymentIntentRequest,
|
||||
): Promise<CreatePaymentIntentResponse | null> {
|
||||
return initiatePayment(body) as Promise<CreatePaymentIntentResponse | null>
|
||||
}
|
||||
|
||||
function updateIntent(
|
||||
body: UpdatePaymentIntentRequest,
|
||||
): Promise<UpdatePaymentIntentResponse | null> {
|
||||
return initiatePayment(body) as Promise<UpdatePaymentIntentResponse | null>
|
||||
}
|
||||
|
||||
const planPrices = computed(() => {
|
||||
return product.value?.prices.find((x) => x.currency_code === currency)
|
||||
})
|
||||
@@ -180,9 +164,9 @@ export const useStripe = (
|
||||
} = createElements({
|
||||
mode: 'payment',
|
||||
currency: currency.toLowerCase(),
|
||||
amount: product.value?.prices.find((x) => x.currency_code === currency)?.prices.intervals[
|
||||
interval.value
|
||||
],
|
||||
amount: product.value
|
||||
? getPriceForInterval(product.value, currency, interval.value)
|
||||
: undefined,
|
||||
paymentMethodCreation: 'manual',
|
||||
setupFutureUsage: 'off_session',
|
||||
})
|
||||
@@ -208,82 +192,61 @@ export const useStripe = (
|
||||
selectedPaymentMethod.value = paymentMethods.find((x) => x.id === id)
|
||||
}
|
||||
|
||||
const requestType: PaymentRequestType = confirmation
|
||||
? {
|
||||
type: 'confirmation_token',
|
||||
token: id,
|
||||
}
|
||||
: {
|
||||
type: 'payment_method',
|
||||
id: id,
|
||||
}
|
||||
|
||||
if (!product.value) {
|
||||
return handlePaymentError('No product selected')
|
||||
}
|
||||
|
||||
const charge: ChargeRequestType = {
|
||||
type: 'new',
|
||||
product_id: product.value?.id,
|
||||
interval: interval.value,
|
||||
const request: Labrinth.Billing.Internal.InitiatePaymentRequest = {
|
||||
type: confirmation ? 'confirmation_token' : 'payment_method',
|
||||
...(confirmation ? { token: id } : { id }),
|
||||
charge: {
|
||||
type: 'new',
|
||||
product_id: product.value.id,
|
||||
interval: interval.value as Labrinth.Billing.Internal.PriceDuration,
|
||||
},
|
||||
...(paymentIntentId.value ? { existing_payment_intent: paymentIntentId.value } : {}),
|
||||
metadata: {
|
||||
type: 'pyro',
|
||||
server_region: region.value,
|
||||
source: project.value
|
||||
? {
|
||||
project_id: project.value,
|
||||
}
|
||||
: {},
|
||||
...(affiliateCode?.value ? { affiliate_code: affiliateCode.value } : {}),
|
||||
},
|
||||
}
|
||||
|
||||
let result: BasePaymentIntentResponse | null = null
|
||||
|
||||
const affiliateMetadata =
|
||||
affiliateCode && affiliateCode.value
|
||||
? {
|
||||
affiliate_code: affiliateCode.value,
|
||||
}
|
||||
: {}
|
||||
|
||||
const metadata: CreatePaymentIntentRequest['metadata'] = {
|
||||
type: 'pyro',
|
||||
server_region: region.value,
|
||||
source: project.value
|
||||
? {
|
||||
project_id: project.value,
|
||||
}
|
||||
: {},
|
||||
...affiliateMetadata,
|
||||
}
|
||||
|
||||
if (paymentIntentId.value) {
|
||||
result = await updateIntent({
|
||||
...requestType,
|
||||
charge,
|
||||
existing_payment_intent: paymentIntentId.value,
|
||||
metadata,
|
||||
})
|
||||
if (result) console.log(`Updated payment intent: ${interval.value} for ${result.total}`)
|
||||
} else {
|
||||
const created = await createIntent({
|
||||
...requestType,
|
||||
charge,
|
||||
metadata: metadata,
|
||||
})
|
||||
if (created) {
|
||||
paymentIntentId.value = created.payment_intent_id
|
||||
clientSecret.value = created.client_secret
|
||||
result = created
|
||||
console.log(`Created payment intent: ${interval.value} for ${created.total}`)
|
||||
}
|
||||
}
|
||||
const result = await initiatePayment(request)
|
||||
|
||||
if (!result) {
|
||||
tax.value = 0
|
||||
total.value = 0
|
||||
noPaymentRequired.value = true
|
||||
} else {
|
||||
if (result.payment_intent_id) {
|
||||
paymentIntentId.value = result.payment_intent_id
|
||||
}
|
||||
if (result.client_secret) {
|
||||
clientSecret.value = result.client_secret
|
||||
}
|
||||
tax.value = result.tax
|
||||
total.value = result.total
|
||||
noPaymentRequired.value = false
|
||||
|
||||
console.log(
|
||||
`${paymentIntentId.value ? 'Updated' : 'Created'} payment intent: ${interval.value} for ${result.total}`,
|
||||
)
|
||||
}
|
||||
|
||||
if (confirmation) {
|
||||
confirmationToken.value = id
|
||||
if (result && result.payment_method) {
|
||||
inputtedPaymentMethod.value = result.payment_method
|
||||
if (result && 'payment_method' in result && result.payment_method) {
|
||||
// payment_method is a string ID from the API, need to find the full object
|
||||
const method = paymentMethods.find((x) => x.id === result.payment_method)
|
||||
if (method) {
|
||||
inputtedPaymentMethod.value = method
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -384,11 +347,12 @@ export const useStripe = (
|
||||
}
|
||||
|
||||
submittingPayment.value = true
|
||||
const productPrice = product.value?.prices.find((x) => x.currency_code === currency)
|
||||
const { error } = await stripe.value.confirmPayment({
|
||||
clientSecret: secert,
|
||||
confirmParams: {
|
||||
confirmation_token: confirmationToken.value,
|
||||
return_url: `${returnUrl}?priceId=${product.value?.prices.find((x) => x.currency_code === currency)?.id}&plan=${interval.value}`,
|
||||
return_url: `${returnUrl}?priceId=${productPrice?.id}&plan=${interval.value}`,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
1
packages/ui/src/pages/index.ts
Normal file
1
packages/ui/src/pages/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as ServersManagePageIndex } from './servers/manage/index.vue'
|
||||
339
packages/ui/src/pages/servers/manage/index.vue
Normal file
339
packages/ui/src/pages/servers/manage/index.vue
Normal file
@@ -0,0 +1,339 @@
|
||||
<template>
|
||||
<div
|
||||
data-pyro-server-list-root
|
||||
class="experimental-styles-within relative mx-auto mb-6 flex min-h-screen w-full max-w-[1280px] flex-col px-6"
|
||||
>
|
||||
<ServersUpgradeModalWrapper
|
||||
v-if="isNuxt"
|
||||
ref="upgradeModal"
|
||||
:stripe-publishable-key
|
||||
:site-url
|
||||
:products
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="hasError || fetchError"
|
||||
class="mx-auto flex h-full min-h-[calc(100vh-4rem)] flex-col items-center justify-center gap-4 text-left"
|
||||
>
|
||||
<div class="flex max-w-lg flex-col items-center rounded-3xl bg-bg-raised p-6 shadow-xl">
|
||||
<div class="flex flex-col items-center text-center">
|
||||
<div class="flex flex-col items-center gap-4">
|
||||
<div class="grid place-content-center rounded-full bg-bg-blue p-4">
|
||||
<HammerIcon class="size-12 text-blue" />
|
||||
</div>
|
||||
<h1 class="m-0 w-fit text-3xl font-bold">Servers could not be loaded</h1>
|
||||
</div>
|
||||
<p class="text-lg text-secondary">We may have temporary issues with our servers.</p>
|
||||
<ul class="m-0 list-disc space-y-4 p-0 pl-4 text-left text-sm leading-[170%]">
|
||||
<li>
|
||||
Our systems automatically alert our team when there's an issue. We are already working
|
||||
on getting them back online.
|
||||
</li>
|
||||
<li>
|
||||
If you recently purchased your Modrinth Server, it is currently in a queue and will
|
||||
appear here as soon as it's ready. <br />
|
||||
<span class="font-medium text-contrast"
|
||||
>Do not attempt to purchase a new server.</span
|
||||
>
|
||||
</li>
|
||||
<li>
|
||||
If you require personalized support regarding the status of your server, please
|
||||
contact Modrinth Support.
|
||||
</li>
|
||||
|
||||
<li v-if="fetchError" class="text-red">
|
||||
<p>Error details:</p>
|
||||
<CopyCode
|
||||
:text="(fetchError as ModrinthServersFetchError).message || 'Unknown error'"
|
||||
:copyable="false"
|
||||
:selectable="false"
|
||||
:language="'json'"
|
||||
/>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<ButtonStyled size="large" type="standard" color="brand">
|
||||
<AutoLink class="mt-6 !w-full" to="https://support.modrinth.com"
|
||||
>Contact Modrinth Support</AutoLink
|
||||
>
|
||||
</ButtonStyled>
|
||||
<ButtonStyled size="large" @click="() => router.go(0)">
|
||||
<button class="mt-3 !w-full">Reload</button>
|
||||
</ButtonStyled>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Transition v-else name="fade" mode="out-in">
|
||||
<div v-if="isLoading && !serverResponse" key="loading" class="flex flex-col gap-4 py-8">
|
||||
<div class="mb-4 text-center">
|
||||
<LoaderCircleIcon class="mx-auto size-8 animate-spin text-contrast" />
|
||||
<p class="m-0 mt-2 text-secondary">Loading your servers...</p>
|
||||
</div>
|
||||
<div
|
||||
v-for="i in 3"
|
||||
:key="i"
|
||||
class="flex animate-pulse flex-row items-center gap-4 overflow-x-hidden rounded-2xl border-[1px] border-solid border-button-bg bg-bg-raised p-4"
|
||||
>
|
||||
<div class="size-16 rounded-xl bg-button-bg"></div>
|
||||
<div class="flex flex-1 flex-col gap-2">
|
||||
<div class="h-6 w-48 rounded bg-button-bg"></div>
|
||||
<div class="h-4 w-64 rounded bg-button-bg opacity-75"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="serverList.length === 0 && !isPollingForNewServers"
|
||||
key="empty"
|
||||
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">
|
||||
<AutoLink to="/servers#plan">Create a Server</AutoLink>
|
||||
</ButtonStyled>
|
||||
</div>
|
||||
|
||||
<div v-else key="list">
|
||||
<div class="relative flex h-fit w-full flex-col items-center justify-between md:flex-row">
|
||||
<h1 class="w-full text-4xl font-bold text-contrast">Servers</h1>
|
||||
<div class="mb-4 flex w-full flex-row items-center justify-end gap-2 md:mb-0 md:gap-4">
|
||||
<div class="iconified-input w-full md:w-72">
|
||||
<label class="sr-only" for="search">Search</label>
|
||||
<SearchIcon />
|
||||
<input
|
||||
id="search"
|
||||
v-model="searchInput"
|
||||
class="input-text-inherit"
|
||||
type="search"
|
||||
name="search"
|
||||
autocomplete="off"
|
||||
placeholder="Search servers..."
|
||||
/>
|
||||
</div>
|
||||
<ButtonStyled v-if="isNuxt" type="standard">
|
||||
<AutoLink :to="{ path: '/servers', hash: '#plan' }">
|
||||
<PlusIcon />
|
||||
New server
|
||||
</AutoLink>
|
||||
</ButtonStyled>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
enter-active-class="transition-all duration-300 ease-out"
|
||||
enter-from-class="opacity-0 max-h-0"
|
||||
enter-to-class="opacity-100 max-h-20"
|
||||
leave-active-class="transition-all duration-200 ease-in"
|
||||
leave-from-class="opacity-100 max-h-20"
|
||||
leave-to-class="opacity-0 max-h-0"
|
||||
>
|
||||
<div
|
||||
v-if="isPollingForNewServers"
|
||||
class="bg-brand/10 my-4 flex items-center justify-center gap-2 rounded-full px-4 py-2 text-sm text-brand"
|
||||
>
|
||||
<LoaderCircleIcon class="size-4 animate-spin" />
|
||||
<span>Checking for new servers...</span>
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
<TransitionGroup
|
||||
v-if="filteredData.length > 0 || isPollingForNewServers"
|
||||
name="list"
|
||||
tag="ul"
|
||||
class="m-0 flex flex-col gap-4 p-0"
|
||||
>
|
||||
<MedalServerListing
|
||||
v-for="server in filteredData.filter((s) => s.is_medal)"
|
||||
:key="server.server_id"
|
||||
v-bind="server"
|
||||
@upgrade="openUpgradeModal(server.server_id)"
|
||||
/>
|
||||
<ServerListing
|
||||
v-for="server in filteredData.filter((s) => !s.is_medal)"
|
||||
:key="server.server_id"
|
||||
v-bind="server"
|
||||
/>
|
||||
</TransitionGroup>
|
||||
<div v-else class="flex h-full items-center justify-center">
|
||||
<p class="text-contrast"><LoaderCircleIcon class="size-5 animate-spin" /></p>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { type Archon, type Labrinth, NuxtModrinthClient } from '@modrinth/api-client'
|
||||
import { HammerIcon, LoaderCircleIcon, PlusIcon, SearchIcon } from '@modrinth/assets'
|
||||
import { AutoLink, ButtonStyled, CopyCode, injectModrinthClient } from '@modrinth/ui'
|
||||
import type { ModrinthServersFetchError } from '@modrinth/utils'
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import dayjs from 'dayjs'
|
||||
import Fuse from 'fuse.js'
|
||||
import type { ComponentPublicInstance } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import ServersUpgradeModalWrapper from '../../../components/billing/ServersUpgradeModalWrapper.vue'
|
||||
import MedalServerListing from '../../../components/servers/marketing/MedalServerListing.vue'
|
||||
import ServerListing from '../../../components/servers/ServerListing.vue'
|
||||
|
||||
defineProps<{
|
||||
stripePublishableKey?: string
|
||||
siteUrl?: string
|
||||
products?: Labrinth.Billing.Internal.Product[]
|
||||
}>()
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const client = injectModrinthClient()
|
||||
|
||||
const isNuxt = computed(() => client instanceof NuxtModrinthClient)
|
||||
|
||||
const hasError = ref(false)
|
||||
const isPollingForNewServers = ref(false)
|
||||
const pollingState = ref({
|
||||
enabled: false,
|
||||
count: 0,
|
||||
initialServers: [] as Archon.Servers.v0.Server[],
|
||||
})
|
||||
|
||||
const {
|
||||
data: serverResponse,
|
||||
error: fetchError,
|
||||
isLoading,
|
||||
} = useQuery({
|
||||
queryKey: ['servers'],
|
||||
queryFn: async () => {
|
||||
const response = await client.archon.servers_v0.list()
|
||||
|
||||
// Fetch subscriptions for medal servers
|
||||
const hasMedalServers = response.servers.some((s) => s.is_medal)
|
||||
if (hasMedalServers) {
|
||||
const subscriptions = await client.labrinth.billing_internal.getSubscriptions()
|
||||
|
||||
// Inject medal_expires into servers
|
||||
for (const server of response.servers) {
|
||||
if (server.is_medal) {
|
||||
const sub = subscriptions.find((s) => s.metadata?.id === server.server_id)
|
||||
if (sub) {
|
||||
server.medal_expires = dayjs(sub.created).add(5, 'days').toISOString()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if new servers appeared (stop polling)
|
||||
if (pollingState.value.enabled) {
|
||||
pollingState.value.count++
|
||||
if (response.servers.length !== pollingState.value.initialServers.length) {
|
||||
pollingState.value.enabled = false
|
||||
router.replace({ query: {} })
|
||||
} else if (pollingState.value.count >= 5) {
|
||||
pollingState.value.enabled = false
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
},
|
||||
refetchInterval: () => (pollingState.value.enabled ? 5000 : false),
|
||||
})
|
||||
|
||||
watch([fetchError, serverResponse], ([error, response]) => {
|
||||
hasError.value = !!error || !response
|
||||
})
|
||||
|
||||
const serverList = computed<Archon.Servers.v0.Server[]>(() => {
|
||||
if (!serverResponse.value) return []
|
||||
return serverResponse.value.servers
|
||||
})
|
||||
|
||||
const searchInput = ref('')
|
||||
|
||||
const fuse = computed(() => {
|
||||
if (serverList.value.length === 0) return null
|
||||
return new Fuse(serverList.value, {
|
||||
keys: ['name', 'loader', 'mc_version', 'game', 'state'],
|
||||
includeScore: true,
|
||||
threshold: 0.4,
|
||||
})
|
||||
})
|
||||
|
||||
function introToTop(array: Archon.Servers.v0.Server[]): Archon.Servers.v0.Server[] {
|
||||
return array.slice().sort((a, b) => {
|
||||
return Number(b.flows?.intro) - Number(a.flows?.intro)
|
||||
})
|
||||
}
|
||||
|
||||
const filteredData = computed<Archon.Servers.v0.Server[]>(() => {
|
||||
if (!searchInput.value.trim()) {
|
||||
return introToTop(serverList.value)
|
||||
}
|
||||
return fuse.value
|
||||
? introToTop(fuse.value.search(searchInput.value).map((result) => result.item))
|
||||
: []
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
if (route.query.redirect_status === 'succeeded') {
|
||||
isPollingForNewServers.value = true
|
||||
pollingState.value = {
|
||||
enabled: true,
|
||||
count: 0,
|
||||
initialServers: [...(serverResponse.value?.servers ?? [])],
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
type ServersUpgradeModalWrapperRef = ComponentPublicInstance<{
|
||||
open: (id: string) => void | Promise<void>
|
||||
}>
|
||||
|
||||
const upgradeModal = ref<ServersUpgradeModalWrapperRef | null>(null)
|
||||
function openUpgradeModal(serverId: string) {
|
||||
upgradeModal.value?.open(serverId)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition:
|
||||
opacity 300ms ease-in-out,
|
||||
transform 300ms ease-in-out;
|
||||
}
|
||||
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.list-enter-active,
|
||||
.list-leave-active {
|
||||
transition: all 200ms ease-in-out;
|
||||
}
|
||||
|
||||
.list-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
|
||||
.list-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
.list-move {
|
||||
transition: transform 200ms ease-in-out;
|
||||
}
|
||||
</style>
|
||||
8
packages/ui/src/providers/api-client.ts
Normal file
8
packages/ui/src/providers/api-client.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import type { AbstractModrinthClient } from '@modrinth/api-client'
|
||||
|
||||
import { createContext } from './index'
|
||||
|
||||
export const [injectModrinthClient, provideModrinthClient] = createContext<AbstractModrinthClient>(
|
||||
'root',
|
||||
'modrinthClient',
|
||||
)
|
||||
@@ -78,5 +78,6 @@ export function createContext<ContextValue>(
|
||||
return [injectContext, provideContext] as const
|
||||
}
|
||||
|
||||
export * from './api-client'
|
||||
export * from './project-page'
|
||||
export * from './web-notifications'
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import type { Project, ProjectV3Partial, TeamMember } from '@modrinth/utils'
|
||||
import type { Labrinth } from '@modrinth/api-client/src/modules/types'
|
||||
// TODO: api client this shit
|
||||
import type { TeamMember } from '@modrinth/utils'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
import { createContext } from '.'
|
||||
|
||||
export interface ProjectPageContext {
|
||||
projectV2: Ref<Project>
|
||||
projectV3: Ref<ProjectV3Partial>
|
||||
projectV2: Ref<Labrinth.Projects.v2.Project>
|
||||
projectV3: Ref<Labrinth.Projects.v3.Project>
|
||||
refreshProject: () => Promise<void>
|
||||
currentMember: Ref<TeamMember>
|
||||
}
|
||||
|
||||
54
packages/ui/src/utils/product-utils.ts
Normal file
54
packages/ui/src/utils/product-utils.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { Labrinth } from '@modrinth/api-client'
|
||||
|
||||
export function getProductDisplayName(product: Labrinth.Billing.Internal.Product): string {
|
||||
const { metadata } = product
|
||||
|
||||
if (metadata.type === 'pyro') {
|
||||
const ramGB = metadata.ram / 1024
|
||||
return `${ramGB}GB Server`
|
||||
}
|
||||
|
||||
if (metadata.type === 'medal') {
|
||||
const ramGB = metadata.ram / 1024
|
||||
return `${ramGB}GB Medal Server (${metadata.region})`
|
||||
}
|
||||
|
||||
return 'Unknown Product'
|
||||
}
|
||||
|
||||
export function getProductDescription(product: Labrinth.Billing.Internal.Product): string {
|
||||
const { metadata } = product
|
||||
|
||||
if (metadata.type === 'pyro') {
|
||||
return `${metadata.cpu} vCPU, ${metadata.ram}MB RAM, ${metadata.storage}MB Storage`
|
||||
}
|
||||
|
||||
if (metadata.type === 'medal') {
|
||||
return `${metadata.cpu} vCPU, ${metadata.ram}MB RAM, ${metadata.storage}MB Storage`
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
export function getPriceForInterval(
|
||||
product: Labrinth.Billing.Internal.Product,
|
||||
currency: string,
|
||||
interval: Labrinth.Billing.Internal.PriceDuration,
|
||||
): number | undefined {
|
||||
const productPrice = product.prices.find((x) => x.currency_code === currency)
|
||||
if (!productPrice) return undefined
|
||||
|
||||
const { prices } = productPrice
|
||||
|
||||
if (prices.type === 'recurring') {
|
||||
return prices.intervals[interval]
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const monthsInInterval: Record<'monthly' | 'quarterly' | 'yearly', number> = {
|
||||
monthly: 1,
|
||||
quarterly: 3,
|
||||
yearly: 12,
|
||||
}
|
||||
Reference in New Issue
Block a user