feat: init

This commit is contained in:
ccbikai
2024-05-25 08:09:30 +08:00
commit bd47e755d5
298 changed files with 21915 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
<script setup>
import { NuxtLink } from '#components'
defineProps({
title: {
type: String,
required: true,
},
})
</script>
<template>
<Breadcrumb class="flex justify-between">
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink href="/">
Sink
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbLink
:as="NuxtLink"
to="/dashboard"
>
Dashboard
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>{{ title }}</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
<DashboardLogout />
</Breadcrumb>
</template>
+99
View File
@@ -0,0 +1,99 @@
<script setup>
import { Flame, MousePointerClick, Users } from 'lucide-vue-next'
const defaultData = Object.freeze({
visits: 0,
visitors: 0,
referers: 0,
})
const counters = ref(defaultData)
const id = inject('id')
const startAt = inject('startAt')
const endAt = inject('endAt')
async function getLinkCounters() {
counters.value = defaultData
const { data } = await useAPI('/api/stats/counters', {
query: {
id: id.value,
startAt: startAt.value,
endAt: endAt.value,
},
})
counters.value = data?.[0]
}
const stopWatchTime = watch([startAt, endAt], getLinkCounters)
onMounted(async () => {
getLinkCounters()
})
onBeforeUnmount(() => {
stopWatchTime()
})
</script>
<template>
<div class="grid gap-4 sm:gap-3 lg:gap-4 sm:grid-cols-3">
<Card>
<CardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<CardTitle class="text-sm font-medium">
Visits
</CardTitle>
<MousePointerClick class="w-4 h-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div
class="text-2xl font-bold"
:class="{ 'blur-lg': !counters.visits }"
>
{{ formatNumber(counters.visits) }}
</div>
<!-- <p class="text-xs text-muted-foreground">
+90
</p> -->
</CardContent>
</Card>
<Card>
<CardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<CardTitle class="text-sm font-medium">
Visitors
</CardTitle>
<Users class="w-4 h-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div
class="text-2xl font-bold"
:class="{ 'blur-lg': !counters.visitors }"
>
{{ formatNumber(counters.visitors) }}
</div>
<!-- <p class="text-xs text-muted-foreground">
+90
</p> -->
</CardContent>
</Card>
<Card>
<CardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<CardTitle class="text-sm font-medium">
Referers
</CardTitle>
<Flame class="w-4 h-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div
class="text-2xl font-bold"
:class="{ 'blur-lg': !counters.referers }"
>
{{ formatNumber(counters.referers) }}
</div>
<!-- <p class="text-xs text-muted-foreground">
-20
</p> -->
</CardContent>
</Card>
</div>
</template>
+152
View File
@@ -0,0 +1,152 @@
<script setup>
import { now, startOfMonth, startOfWeek } from '@internationalized/date'
const emit = defineEmits(['update:dateRange'])
const startAt = inject('startAt')
const endAt = inject('endAt')
const dateRange = ref('last-7d')
const openCustomDateRange = ref(false)
const customDate = ref()
const customDateRange = ref()
const locale = getLocale()
function updateCustomDate(customDateValue) {
emit('update:dateRange', [date2unix(customDateValue, 'start'), date2unix(customDateValue, 'end')])
openCustomDateRange.value = false
customDate.value = undefined
}
function updateCustomDateRange(customDateRangeValue) {
if (customDateRangeValue.start && customDateRangeValue.end) {
emit('update:dateRange', [date2unix(customDateRangeValue.start, 'start'), date2unix(customDateRangeValue.end, 'end')])
openCustomDateRange.value = false
customDateRange.value = undefined
}
}
function isDateDisabled(dateValue) {
return dateValue.toDate() > new Date()
}
watch(dateRange, (newValue) => {
switch (newValue) {
case 'today':
emit('update:dateRange', [date2unix(now(), 'start'), date2unix(now())])
break
case 'last-24h':
emit('update:dateRange', [date2unix(now().subtract({ hours: 24 })), date2unix(now())])
break
case 'this-week':
emit('update:dateRange', [date2unix(startOfWeek(now(), locale), 'start'), date2unix(now())])
break
case 'last-7d':
emit('update:dateRange', [date2unix(now().subtract({ days: 7 })), date2unix(now())])
break
case 'this-month':
emit('update:dateRange', [date2unix(startOfMonth(now()), 'start'), date2unix(now())])
break
case 'last-30d':
emit('update:dateRange', [date2unix(now().subtract({ days: 30 })), date2unix(now())])
break
case 'last-90d':
emit('update:dateRange', [date2unix(now().subtract({ days: 90 })), date2unix(now())])
break
case 'custom':
openCustomDateRange.value = true
dateRange.value = null
break
default:
break
}
})
</script>
<template>
<Select v-model="dateRange">
<SelectTrigger>
<SelectValue v-if="dateRange" />
<div v-else>
{{ shortDate(startAt) }} - {{ shortDate(endAt) }}
</div>
</SelectTrigger>
<SelectContent>
<SelectItem value="today">
Today
</SelectItem>
<SelectItem value="last-24h">
Last 24 hours
</SelectItem>
<SelectSeparator />
<SelectItem value="this-week">
This week
</SelectItem>
<SelectItem value="last-7d">
Last 7 days
</SelectItem>
<SelectSeparator />
<SelectItem value="this-month">
This month
</SelectItem>
<SelectItem value="last-30d">
Last 30 days
</SelectItem>
<SelectSeparator />
<SelectItem value="last-90d">
Last 90 days
</SelectItem>
<SelectSeparator />
<SelectItem value="custom">
Custom
</SelectItem>
</SelectContent>
</Select>
<Dialog v-model:open="openCustomDateRange">
<DialogContent class="w-auto max-w-[95svw] max-h-[95svh] md:max-w-screen-md grid-rows-[auto_minmax(0,1fr)_auto]">
<DialogHeader>
<DialogTitle>Custom Date</DialogTitle>
</DialogHeader>
<Tabs
default-value="range"
>
<div class="flex justify-center">
<TabsList>
<TabsTrigger value="date">
Date
</TabsTrigger>
<TabsTrigger value="range">
Date Range
</TabsTrigger>
</TabsList>
</div>
<TabsContent
value="date"
class="overflow-y-auto h-80"
>
<Calendar
:model-value="customDate"
weekday-format="short"
:is-date-disabled="isDateDisabled"
@update:model-value="updateCustomDate"
/>
</TabsContent>
<TabsContent
value="range"
class="overflow-y-auto h-80"
>
<RangeCalendar
:model-value="customDateRange"
initial-focus
weekday-format="short"
:number-of-months="2"
:is-date-disabled="isDateDisabled"
@update:model-value="updateCustomDateRange"
/>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
</template>
+41
View File
@@ -0,0 +1,41 @@
<script setup>
import { now } from '@internationalized/date'
defineProps({
link: {
type: Object,
default: () => null,
},
})
const startAt = ref(date2unix(now().subtract({ days: 7 })))
const endAt = ref(date2unix(now()))
provide('startAt', startAt)
provide('endAt', endAt)
function changeDate(time) {
// console.log('dashboard date', new Date(time[0] * 1000), new Date(time[1] * 1000))
startAt.value = time[0]
endAt.value = time[1]
}
</script>
<template>
<main class="space-y-6">
<DashboardNav>
<template
v-if="link"
#left
>
<h3 class="text-xl font-bold leading-10">
{{ link.slug }}'s Stats
</h3>
</template>
<DashboardDatePicker @update:date-range="changeDate" />
</DashboardNav>
<DashboardCounters />
<DashboardViews />
<DashboardMetrics />
</main>
</template>
+32
View File
@@ -0,0 +1,32 @@
<script setup>
import { LogOut } from 'lucide-vue-next'
function logOut() {
localStorage.removeItem('SinkSiteToken')
navigateTo('/dashboard/login')
}
</script>
<template>
<AlertDialog>
<AlertDialogTrigger as-child>
<LogOut
class="w-4 h-4 cursor-pointer"
/>
</AlertDialogTrigger>
<AlertDialogContent class="max-w-[95svw] max-h-[95svh] md:max-w-lg grid-rows-[auto_minmax(0,1fr)_auto]">
<AlertDialogHeader>
<AlertDialogTitle>LogOut ?</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to log out ?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="logOut">
LogOut
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</template>
+28
View File
@@ -0,0 +1,28 @@
<script setup>
const route = useRoute()
</script>
<template>
<nav class="flex justify-between">
<Tabs
v-if="route.path !== '/dashboard/link'"
:default-value="route.path"
@update:model-value="navigateTo"
>
<TabsList>
<TabsTrigger value="/dashboard">
Analysis
</TabsTrigger>
<TabsTrigger
value="/dashboard/links"
>
Links
</TabsTrigger>
</TabsList>
</Tabs>
<slot name="left" />
<div>
<slot />
</div>
</nav>
</template>
+73
View File
@@ -0,0 +1,73 @@
<script setup>
import { AreaChart } from '@/components/ui/chart-area'
import { BarChart } from '@/components/ui/chart-bar'
const views = ref([])
const chart = computed(() => views.value.length > 1 ? AreaChart : BarChart)
const id = inject('id')
const startAt = inject('startAt')
const endAt = inject('endAt')
const OneDay = 24 * 60 * 60 // 1 day in seconds
function getUnit(startAt, endAt) {
if (startAt && endAt && endAt - startAt <= OneDay)
return 'hour'
return 'day'
}
async function getLinkViews() {
views.value = []
const { data } = await useAPI('/api/stats/views', {
query: {
id: id.value,
unit: getUnit(startAt.value, endAt.value),
clientTimezone: getTimeZone(),
startAt: startAt.value,
endAt: endAt.value,
},
})
views.value = (data || []).map((item) => {
item.visitors = +item.visitors
item.visits = +item.visits
return item
})
}
const stopWatchTime = watch([startAt, endAt], getLinkViews)
onMounted(async () => {
getLinkViews()
})
onBeforeUnmount(() => {
stopWatchTime()
})
function formatTime(tick) {
if (Number.isInteger(tick) && views.value[tick]) {
if (getUnit(startAt.value, endAt.value) === 'hour')
return views.value[tick].time.split(' ')[1] || ''
return views.value[tick].time
}
return ''
}
</script>
<template>
<Card class="px-0 py-6 md:px-6">
<CardTitle class="px-6 md:px-0">
Views
</CardTitle>
<component
:is="chart"
:data="views"
index="time"
:categories="['visitors', 'visits']"
:x-formatter="formatTime"
:y-formatter="formatNumber"
/>
</Card>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup>
import { toast } from 'vue-sonner'
const props = defineProps({
link: {
type: Object,
required: true,
},
})
const emit = defineEmits(['update:link'])
async function deleteLink() {
await useAPI('/api/link/delete', {
method: 'POST',
body: {
slug: props.link.slug,
},
})
emit('update:link', props.link, 'delete')
toast('Delete successful!')
}
</script>
<template>
<AlertDialog>
<AlertDialogTrigger as-child>
<slot />
</AlertDialogTrigger>
<AlertDialogContent class="max-w-[95svw] max-h-[95svh] md:max-w-lg grid-rows-[auto_minmax(0,1fr)_auto]">
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will really delete your link from servers.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="deleteLink">
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</template>
+193
View File
@@ -0,0 +1,193 @@
<script setup>
import { z } from 'zod'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import { Shuffle, Sparkles } from 'lucide-vue-next'
import { toast } from 'vue-sonner'
import { DependencyType } from '@/components/ui/auto-form/interface'
import { LinkSchema, nanoid } from '@/schemas/link'
const props = defineProps({
link: {
type: Object,
default: () => ({}),
},
})
const emit = defineEmits(['update:link'])
const link = ref(props.link)
const dialogOpen = ref(false)
const isEdit = !!props.link.id
const EditLinkSchema = LinkSchema.pick({
url: true,
slug: true,
}).extend({
optional: LinkSchema.omit({
id: true,
url: true,
slug: true,
createdAt: true,
updatedAt: true,
title: true,
description: true,
image: true,
}).extend({
expiration: z.coerce.date().optional(),
}).optional(),
})
const fieldConfig = {
slug: {
disabled: isEdit,
},
optional: {
comment: {
component: 'textarea',
},
},
}
const dependencies = [
{
sourceField: 'slug',
type: DependencyType.DISABLES,
targetField: 'slug',
when: () => isEdit,
},
]
const form = useForm({
validationSchema: toTypedSchema(EditLinkSchema),
initialValues: {
slug: link.value.slug,
url: link.value.url,
optional: {
comment: link.value.comment,
},
},
validateOnMount: isEdit,
keepValuesOnUnmount: isEdit,
})
function randomSlug() {
form.setFieldValue('slug', nanoid()())
}
const aiSlugPending = ref(false)
async function aiSlug() {
if (!form.values.url)
return
aiSlugPending.value = true
try {
const { slug } = await useAPI('/api/link/ai', {
query: {
url: form.values.url,
},
})
form.setFieldValue('slug', slug)
}
catch (error) {
console.log(error)
}
aiSlugPending.value = false
}
onMounted(() => {
if (link.value.expiration) {
form.setFieldValue('optional.expiration', unix2date(link.value.expiration))
}
})
async function onSubmit(formData) {
const link = {
url: formData.url,
slug: formData.slug,
...(formData.optional || []),
expiration: formData.optional?.expiration ? date2unix(formData.optional?.expiration, 'end') : undefined,
}
const { link: newLink } = await useAPI(isEdit ? '/api/link/edit' : '/api/link/create', {
method: isEdit ? 'PUT' : 'POST',
body: link,
})
dialogOpen.value = false
emit('update:link', newLink, isEdit ? 'edit' : 'create')
isEdit ? toast('Link updated successfully') : toast('Link created successfully')
}
const { previewMode } = useRuntimeConfig().public
</script>
<template>
<Dialog v-model:open="dialogOpen">
<DialogTrigger as-child>
<slot>
<Button
class="ml-2"
variant="outline"
@click="randomSlug"
>
Create Link
</Button>
</slot>
</DialogTrigger>
<DialogContent class="max-w-[95svw] max-h-[95svh] md:max-w-lg grid-rows-[auto_minmax(0,1fr)_auto]">
<DialogHeader>
<DialogTitle>{{ link.id ? 'Edit Link' : 'Create Link' }}</DialogTitle>
</DialogHeader>
<p
v-if="previewMode"
class="text-sm text-muted-foreground"
>
The preview mode link is valid for up to 24 hours.
</p>
<AutoForm
class="px-2 space-y-2 overflow-y-auto"
:schema="EditLinkSchema"
:form="form"
:field-config="fieldConfig"
:dependencies="dependencies"
@submit="onSubmit"
>
<template #slug="slotProps">
<div
v-if="!isEdit"
class="relative"
>
<div class="absolute right-0 flex space-x-3 top-1">
<Shuffle
class="w-4 h-4 cursor-pointer"
@click="randomSlug"
/>
<Sparkles
class="w-4 h-4 cursor-pointer"
:class="{ 'animate-bounce': aiSlugPending }"
@click="aiSlug"
/>
</div>
<AutoFormField
v-bind="slotProps"
/>
</div>
</template>
<DialogFooter>
<DialogClose as-child>
<Button
type="button"
variant="secondary"
class="mt-2 sm:mt-0"
>
Close
</Button>
</DialogClose>
<Button type="submit">
Save
</Button>
</DialogFooter>
</AutoForm>
</DialogContent>
</Dialog>
</template>
+63
View File
@@ -0,0 +1,63 @@
<script setup>
import { Loader } from 'lucide-vue-next'
import { useInfiniteScroll } from '@vueuse/core'
const links = ref([])
const limit = 24
let cursor = ''
let listComplete = false
async function getLinks() {
const data = await useAPI('/api/link/list', {
query: {
limit,
cursor,
},
})
links.value = links.value.concat(data.links)
cursor = data.cursor
listComplete = data.list_complete
}
const { isLoading } = useInfiniteScroll(
document,
getLinks,
{ distance: 10, interval: 1000, canLoadMore: () => !listComplete },
)
function updateLinkList(link, type) {
if (type === 'edit') {
const index = links.value.findIndex(l => l.id === link.id)
links.value[index] = link
}
else if (type === 'delete') {
const index = links.value.findIndex(l => l.id === link.id)
links.value.splice(index, 1)
}
else {
links.value.unshift(link)
}
}
</script>
<template>
<main class="space-y-6">
<DashboardNav>
<DashboardLinksEditor @update:link="updateLinkList" />
</DashboardNav>
<section class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
<DashboardLinksLink
v-for="link in links"
:key="link.id"
:link="link"
@update:link="updateLinkList"
/>
</section>
<div
v-if="isLoading"
class="flex items-center justify-center"
>
<Loader class="animate-spin" />
</div>
</main>
</template>
+186
View File
@@ -0,0 +1,186 @@
<script setup>
import { CalendarPlus2, Copy, CopyCheck, Eraser, Hourglass, Link as LinkIcon, QrCode, SquareChevronDown, SquarePen } from 'lucide-vue-next'
import { useClipboard } from '@vueuse/core'
import { toast } from 'vue-sonner'
import { parseURL } from 'ufo'
import QRCode from './QRCode.vue'
const props = defineProps({
link: {
type: Object,
required: true,
},
})
const emit = defineEmits(['update:link'])
const editPopoverOpen = ref(false)
const { host, origin } = location
function getLinkHost(url) {
const { host } = parseURL(url)
return host
}
const shortLink = computed(() => `${origin}/${props.link.slug}`)
const linkIcon = computed(() => `https://unavatar.io/${getLinkHost(props.link.url)}?fallback=https://sink.cool/sink.png`)
const { copy, copied } = useClipboard({ source: shortLink.value, copiedDuring: 400 })
function updateLink(link, type) {
emit('update:link', link, type)
editPopoverOpen.value = false
}
</script>
<template>
<Card>
<NuxtLink
class="flex flex-col p-4 space-y-3"
:to="`/dashboard/link?slug=${link.slug}`"
>
<div class="flex items-center justify-center space-x-3">
<Avatar>
<AvatarImage
:src="linkIcon"
alt="@radix-vue"
/>
<AvatarFallback>
<img
src="/sink.png"
alt="Sink"
>
</AvatarFallback>
</Avatar>
<div class="flex-1 overflow-hidden">
<div class="flex items-center">
<div class="font-bold leading-5 truncate text-md">
{{ host }}/{{ link.slug }}
</div>
<CopyCheck
v-if="copied"
class="w-4 h-4 ml-1 shrink-0"
@click.prevent
/>
<Copy
v-else
class="w-4 h-4 ml-1 shrink-0"
@click.prevent="copy(shortLink);toast('Copy successful!')"
/>
</div>
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<p class="text-sm truncate">
{{ link.comment || link.title || link.description }}
</p>
</TooltipTrigger>
<TooltipContent>
<p class="max-w-[90svw] break-all">
{{ link.comment || link.title || link.description }}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<a
:href="link.url"
target="_blank"
rel="noopener noreferrer"
@click.stop
>
<LinkIcon class="w-5 h-5" />
</a>
<Popover>
<PopoverTrigger>
<QrCode
class="w-5 h-5"
@click.prevent
/>
</PopoverTrigger>
<PopoverContent>
<QRCode
:data="shortLink"
:image="linkIcon"
/>
</PopoverContent>
</Popover>
<Popover v-model:open="editPopoverOpen">
<PopoverTrigger>
<SquareChevronDown
class="w-5 h-5"
@click.prevent
/>
</PopoverTrigger>
<PopoverContent
class="w-auto p-0"
:hide-when-detached="false"
>
<DashboardLinksEditor
:link="link"
@update:link="updateLink"
>
<div
class="cursor-pointer flex select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground"
>
<SquarePen
class="w-5 h-5 mr-2"
/>
Edit
</div>
</DashboardLinksEditor>
<Separator />
<DashboardLinksDelete
:link="link"
@update:link="updateLink"
>
<div
class="cursor-pointer flex select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground"
>
<Eraser
class="w-5 h-5 mr-2"
/> Delete
</div>
</DashboardLinksDelete>
</PopoverContent>
</Popover>
</div>
<div class="flex w-full h-5 space-x-2 text-sm">
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<span class="inline-flex items-center leading-5"><CalendarPlus2 class="w-4 h-4 mr-1" /> {{ shortDate(link.createdAt) }}</span>
</TooltipTrigger>
<TooltipContent>
<p>Created At: {{ longDate(link.createdAt) }}</p>
<p>Updated At: {{ longDate(link.updatedAt) }}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<template v-if="link.expiration">
<Separator orientation="vertical" />
<TooltipProvider>
<Tooltip>
<TooltipTrigger as-child>
<span class="inline-flex items-center leading-5"><Hourglass class="w-4 h-4 mr-1" /> {{ shortDate(link.expiration) }}</span>
</TooltipTrigger>
<TooltipContent>
<p>Expires At: {{ longDate(link.expiration) }}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</template>
<Separator orientation="vertical" />
<span class="truncate">{{ link.url }}</span>
</div>
</NuxtLink>
</Card>
</template>
+81
View File
@@ -0,0 +1,81 @@
<script setup>
import QRCodeStyling from 'qr-code-styling'
const props = defineProps({
data: {
type: String,
required: true,
},
image: {
type: String,
default: '',
},
})
const options = {
width: 256,
height: 256,
data: props.data,
margin: 10,
qrOptions: { typeNumber: '0', mode: 'Byte', errorCorrectionLevel: 'Q' },
imageOptions: { hideBackgroundDots: true, imageSize: 0.4, margin: 2 },
dotsOptions: { type: 'dots', color: '#000000', gradient: null },
backgroundOptions: { color: '#ffffff', gradient: null },
image: props.image,
dotsOptionsHelper: {
colorType: { single: true, gradient: false },
gradient: {
linear: true,
radial: false,
color1: '#6a1a4c',
color2: '#6a1a4c',
rotation: '0',
},
},
cornersSquareOptions: { type: 'extra-rounded', color: '#000000' },
cornersSquareOptionsHelper: {
colorType: { single: true, gradient: false },
gradient: {
linear: true,
radial: false,
color1: '#000000',
color2: '#000000',
rotation: '0',
},
},
cornersDotOptions: { type: 'dot', color: '#000000' },
cornersDotOptionsHelper: {
colorType: { single: true, gradient: false },
gradient: {
linear: true,
radial: false,
color1: '#000000',
color2: '#000000',
rotation: '0',
},
},
backgroundOptionsHelper: {
colorType: { single: true, gradient: false },
gradient: {
linear: true,
radial: false,
color1: '#ffffff',
color2: '#ffffff',
rotation: '0',
},
},
}
const qrCode = new QRCodeStyling(options)
const qrCodeEl = ref(null)
onMounted(() => {
qrCode.append(qrCodeEl.value)
})
</script>
<template>
<div
ref="qrCodeEl"
:data-text="data"
/>
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup>
import pluralize from 'pluralize'
defineProps({
tabs: {
type: Array,
required: true,
},
})
function type2name(type) {
if (['os'].includes(type))
return type.toUpperCase()
return pluralize(type.replace(type[0], type[0].toUpperCase()))
}
</script>
<template>
<Tabs
:default-value="tabs[0]"
class="flex flex-col"
>
<TabsList class="w-fit">
<TabsTrigger
v-for="tab in tabs"
:key="tab"
:value="tab"
>
{{ type2name(tab) }}
</TabsTrigger>
</TabsList>
<TabsContent
v-for="tab in tabs"
:key="tab"
:value="tab"
class="flex-1"
>
<DashboardMetricsMetric
:type="tab"
:name="type2name(tab)"
class="h-full"
/>
</TabsContent>
</Tabs>
</template>
+25
View File
@@ -0,0 +1,25 @@
<template>
<main class="grid gap-8 lg:grid-cols-12">
<DashboardMetricsLocations class="col-span-1 lg:col-span-8" />
<DashboardMetricsGroup
class="lg:col-span-4"
:tabs="['country', 'region', 'city']"
/>
<DashboardMetricsGroup
class="lg:col-span-6"
:tabs="['referer', 'slug']"
/>
<DashboardMetricsGroup
class="lg:col-span-6"
:tabs="['language', 'timezone']"
/>
<DashboardMetricsGroup
class="lg:col-span-6"
:tabs="['device', 'deviceType']"
/>
<DashboardMetricsGroup
class="lg:col-span-6"
:tabs="['os', 'browser', 'browserType']"
/>
</main>
</template>
+75
View File
@@ -0,0 +1,75 @@
<script setup>
import { VList } from 'virtua/vue'
defineProps({
metrics: {
type: Array,
required: true,
},
type: {
type: String,
required: true,
},
})
</script>
<template>
<div class="w-full text-sm">
<div
class="flex justify-between transition-colors border-b hover:bg-muted/50 leading-[48px]"
>
<div
class="h-12 px-4 font-medium text-left align-middle text-muted-foreground "
>
Name
</div>
<div
class="h-12 px-4 font-medium text-right align-middle text-muted-foreground"
>
Count
</div>
</div>
<VList
v-slot="metric"
:data="metrics"
:style="{ height: '342px' }"
>
<div class="px-4 py-2 transition-colors border-b hover:bg-muted/50">
<div class="flex justify-between">
<div
class="flex-1 leading-5 truncate font-mediums"
>
<DashboardMetricsName
:name="metric.name"
:type="type"
/>
</div>
<div
class="text-right"
>
{{ formatNumber(metric.count) }}
<span class="text-xs text-gray-500">({{ metric.percent }}%)</span>
</div>
</div>
<div
class="flex-1"
>
<TooltipProvider>
<Tooltip>
<TooltipTrigger class="w-full">
<Progress
v-model="metric.percent"
class="h-2"
:color="metric.color"
/>
</TooltipTrigger>
<TooltipContent>
<p>{{ metric.percent }}%</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</div>
</VList>
</div>
</template>
@@ -0,0 +1,93 @@
<script setup>
import { VisSingleContainer, VisTopoJSONMap, VisTopoJSONMapSelectors } from '@unovis/vue'
import { WorldMapSimplestTopoJSON } from '@unovis/ts/maps'
import WorldMapTopoJSON from '@/assets/location/world-topo.json' // https://github.com/apache/echarts/blob/master/test/data/map/json/world.json
import { ChartTooltip } from '@/components/ui/chart'
WorldMapTopoJSON.objects.states.geometries.map((state) => {
const name = state.properties.name
const country = WorldMapSimplestTopoJSON.objects.countries.geometries.find(country => country.properties.name === name)
state.id = state.name || ''
if (country) {
state.id = country.id || ''
state.properties = country.properties
}
return state
})
const id = inject('id')
const startAt = inject('startAt')
const endAt = inject('endAt')
const areaData = ref([])
async function getMapData() {
areaData.value = []
const { data } = await useAPI('/api/stats/metrics', {
query: {
type: 'country',
id: id.value,
startAt: startAt.value,
endAt: endAt.value,
},
})
if (Array.isArray(data)) {
areaData.value = data.map((country) => {
country.id = country.name
return country
})
}
}
const stopWatchTime = watch([startAt, endAt], getMapData)
onMounted(() => {
getMapData()
})
onBeforeUnmount(() => {
stopWatchTime()
})
const valueFormatter = v => v
const Tooltip = {
props: ['title', 'data'],
setup(props) {
const title = props.data[1]?.value?.name
const data = [{
name: props.title,
value: props.data[3]?.value?.count,
color: 'black',
}]
return () => h(ChartTooltip, { title, data })
},
}
</script>
<template>
<Card class="flex flex-col md:h-[500px]">
<CardHeader>
<CardTitle>Locations</CardTitle>
</CardHeader>
<CardContent class="flex-1 flex [&_[data-radix-aspect-ratio-wrapper]]:flex-1">
<AspectRatio :ratio="65 / 30">
<VisSingleContainer
:data="{ areas: areaData }"
class="h-full"
>
<VisTopoJSONMap
:topojson="WorldMapTopoJSON"
map-feature-name="states"
/>
<ChartSingleTooltip
index="id"
:selector="VisTopoJSONMapSelectors.feature"
:items="areaData"
:value-formatter="valueFormatter"
:custom-tooltip="Tooltip"
/>
</VisSingleContainer>
</AspectRatio>
</CardContent>
</Card>
</template>
+113
View File
@@ -0,0 +1,113 @@
<script setup>
import { Maximize } from 'lucide-vue-next'
const props = defineProps({
type: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
})
const id = inject('id')
const startAt = inject('startAt')
const endAt = inject('endAt')
const total = ref(0)
const metrics = ref([])
const top6 = ref([])
async function getLinkMetrics() {
total.value = 0
metrics.value = []
top6.value = []
const { data } = await useAPI('/api/stats/metrics', {
query: {
type: props.type,
id: id.value,
startAt: startAt.value,
endAt: endAt.value,
},
})
if (Array.isArray(data)) {
const colors = colorGradation(data.length)
total.value = data.reduce((acc, cur) => acc + Number(cur.count), 0)
metrics.value = data.map((item, i) => {
item.color = colors[i]
item.percent = Math.floor(item.count / total.value * 100) || (item.count ? 1 : 0)
return item
})
top6.value = metrics.value.slice(0, 6)
}
}
const stopWatchTime = watch([startAt, endAt], getLinkMetrics)
onMounted(() => {
getLinkMetrics()
})
onBeforeUnmount(() => {
stopWatchTime()
})
</script>
<template>
<Card class="flex flex-col">
<template v-if="metrics.length">
<DashboardMetricsList
class="flex-1"
:metrics="top6"
:type="type"
/>
<CardFooter class="py-2">
<Dialog>
<DialogTrigger
as-child
class="w-full"
>
<Button
variant="link"
>
<Maximize
class="w-4 h-4 mr-2"
/> DETAILS
</Button>
</DialogTrigger>
<DialogContent class="max-w-[95svw] max-h-[95svh] md:max-w-screen-md grid-rows-[auto_minmax(0,1fr)_auto]">
<DialogHeader>
<DialogTitle>{{ name }}</DialogTitle>
</DialogHeader>
<DashboardMetricsList
class="overflow-y-auto"
:metrics="metrics"
:type="type"
/>
</DialogContent>
</Dialog>
</CardFooter>
</template>
<template v-else>
<div class="flex items-center justify-between h-12 px-4">
<Skeleton
class="w-32 h-4 rounded-full"
/>
<Skeleton
class="w-20 h-4 rounded-full"
/>
</div>
<div
v-for="i in 3"
:key="i"
class="px-4 py-4"
>
<Skeleton
class="w-full h-4 rounded-full"
/>
</div>
</template>
</Card>
</template>
+101
View File
@@ -0,0 +1,101 @@
<script setup>
// https://vue3-simple-icons.wyatt-herkamp.dev/
import {
AppleIcon,
AndroidIcon,
DebianIcon,
FacebookIcon,
FirefoxBrowserIcon,
GoogleChromeIcon,
GoogleIcon,
HuaweiIcon,
IOsIcon,
InternetExplorerIcon,
LinuxIcon,
MacOsIcon,
MicrosoftEdgeIcon,
OperaIcon,
SafariIcon,
SamsungIcon,
UbuntuIcon,
VivoIcon,
WeChatIcon,
WindowsIcon,
XiaomiIcon,
YandexCloudIcon,
} from 'vue3-simple-icons'
import {
Globe,
Laptop,
MonitorCheck,
Smartphone,
Tablet,
Terminal,
} from 'lucide-vue-next'
defineProps({
name: {
type: String,
required: true,
},
type: {
type: String,
default: 'browser',
},
})
const iconMaps = {
'android': AndroidIcon,
'browser': Globe,
'chrome': GoogleChromeIcon,
'chrome headless': GoogleChromeIcon,
'chrome webview': GoogleChromeIcon,
'chromium': GoogleChromeIcon,
'curl': Terminal,
'debian': DebianIcon,
'desktop': MonitorCheck,
'edge': MicrosoftEdgeIcon,
'facebook': FacebookIcon,
'facebookexternalhit': FacebookIcon,
'firefox': FirefoxBrowserIcon,
'googlebot': GoogleIcon,
'googlebot-image': GoogleIcon,
'harmonyos': HuaweiIcon,
'huawei browser': HuaweiIcon,
'ie': InternetExplorerIcon,
'ios': IOsIcon,
'ipad': AppleIcon,
'iphone': AppleIcon,
'ipod': AppleIcon,
'laptop': Laptop,
'linux': LinuxIcon,
'macintosh': AppleIcon,
'macos': MacOsIcon,
'miui browser': XiaomiIcon,
'mobile': Smartphone,
'mobile chrome': GoogleChromeIcon,
'mobile firefox': FirefoxBrowserIcon,
'mobile safari': SafariIcon,
'opera': OperaIcon,
'os': MonitorCheck,
'safari': SafariIcon,
'samsung internet': SamsungIcon,
'tablet': Tablet,
'ubuntu': UbuntuIcon,
'vivo browser': VivoIcon,
'wechat': WeChatIcon,
'windows': WindowsIcon,
'yandex': YandexCloudIcon,
}
</script>
<template>
<div class="w-full truncate">
<component
:is="iconMaps[name.toLowerCase()] || iconMaps[type]"
class="w-5 h-5 py-0.5 float-left"
/>
<span>{{ name }}</span>
</div>
</template>
@@ -0,0 +1,66 @@
<script setup>
defineProps({
name: {
type: String,
required: true,
},
type: {
type: String,
required: true,
},
})
function formatName(name, type) {
if (!name || typeof Intl === 'undefined')
return name
try {
if (type === 'country') {
const regionNames = new Intl.DisplayNames(['en'], { type: 'region' })
return `${getFlag(name)} ${regionNames.of(name)}`
}
if (type === 'language') {
const languageNames = new Intl.DisplayNames(['en'], { type: 'language' })
return languageNames.of(name)
}
return name
}
catch (e) {
console.error(e)
return name
}
}
</script>
<template>
<TooltipProvider>
<Tooltip>
<TooltipTrigger class="w-full text-left">
<DashboardMetricsNameReferer
v-if="name && type === 'referer'"
:name="name"
/>
<DashboardMetricsNameSlug
v-else-if="name && type === 'slug'"
:name="name"
/>
<DashboardMetricsNameIcon
v-else-if="name && ['os', 'browser', 'browserType', 'device', 'deviceType'].includes(type)"
:name="name"
:type="type"
/>
<div
v-else
class="w-full truncate"
>
{{ formatName(name, type) || '(None)' }}
</div>
</TooltipTrigger>
<TooltipContent v-if="name">
<p>
{{ formatName(name, type) }}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</template>
@@ -0,0 +1,30 @@
<script setup>
defineProps({
name: String,
})
</script>
<template>
<a
:href="`http://${name}`"
target="_blank"
rel="noopener noreferrer"
class="block w-full truncate"
>
<Avatar
class="w-5 h-5 p-0.5 float-left"
>
<AvatarImage
:src="`https://unavatar.io/${name}?fallback=false`"
alt="@radix-vue"
/>
<AvatarFallback>
<img
src="/sink.png"
alt="Sink"
>
</AvatarFallback>
</Avatar>
<span>{{ name }}</span>
</a>
</template>
@@ -0,0 +1,14 @@
<script setup>
defineProps({
name: String,
})
</script>
<template>
<NuxtLink
:to="`/dashboard/link?slug=${name}`"
class="inline-flex items-center justify-start w-full"
>
<span class="w-full truncate">{{ name }}</span>
</NuxtLink>
</template>
+20
View File
@@ -0,0 +1,20 @@
<template>
<div
class="flex flex-col items-center max-w-4xl p-8 mx-auto my-12 text-center bg-black rounded-lg md:px-20 md:py-20"
>
<h2 class="text-4xl tracking-tight text-white md:text-6xl">
Deployment immediately.
</h2>
<p class="mt-4 text-lg text-slate-400 md:text-xl">
With just a few simple clicks, you can start deploying without any expenses.
</p>
<div class="flex mt-5">
<HomeLink
href="https://github.com/ccbikai/sink?tab=readme-ov-file#%EF%B8%8F-deployment"
type="inverted"
>
Start Deploy
</HomeLink>
</div>
</div>
</template>
+78
View File
@@ -0,0 +1,78 @@
<script setup>
import { Link, AreaChart, ServerOff, Paintbrush, Sparkles, Hourglass } from 'lucide-vue-next'
const features = ref([
{
title: 'URL Shortening',
description:
'Compress your URLs to their minimal length.',
icon: Link,
},
{
title: 'Analytics',
description:
'Monitor link analytics and gather insightful statistics.',
icon: AreaChart,
},
{
title: 'Serverless',
description:
'Deploy without the need for traditional servers.',
icon: ServerOff,
},
{
title: 'Customizable Slug',
description:
'Support for personalized slugs.',
icon: Paintbrush,
},
{
title: 'AI Slug',
description:
'Leverage AI to generate slugs.',
icon: Sparkles,
},
{
title: 'Link Expiration',
description:
'Set expiration dates for your links.',
icon: Hourglass,
},
])
</script>
<template>
<main class="pt-16 md:py-12">
<div class="md:pb-12">
<h2 class="text-4xl font-bold lg:text-5xl lg:tracking-tight">
Features
</h2>
<p class="my-8 text-lg md:mb-0 text-slate-600">
Simple and sufficient functionality
</p>
</div>
<div class="grid gap-8 md:gap-16 sm:grid-cols-2 md:grid-cols-3">
<div
v-for="item in features"
:key="item.title"
class="flex items-start gap-4"
>
<div class="w-8 h-8 p-2 mt-1 bg-black rounded-full shrink-0">
<component
:is="item.icon"
class="w-4 h-4 text-white"
/>
</div>
<div>
<h3 class="text-lg font-semibold">
{{ item.title }}
</h3>
<p class="mt-2 leading-relaxed text-slate-500">
{{ item.description }}
</p>
</div>
</div>
</div>
</main>
</template>
+56
View File
@@ -0,0 +1,56 @@
<script setup>
import { AreaChart } from 'lucide-vue-next'
import { GitHubIcon } from 'vue3-simple-icons'
import heroImg from '@/assets/images/hero.svg?raw'
const { title, description } = useAppConfig()
</script>
<template>
<main
class="grid pt-8 pb-8 lg:grid-cols-2 place-items-center md:py-12"
>
<div class="hidden py-6 md:order-1 md:block">
<div
class="w-[512px]"
v-html="heroImg"
/>
</div>
<div>
<h1
class="text-5xl font-bold lg:text-6xl xl:text-7xl lg:tracking-tight xl:tracking-tighter"
>
{{ title }}
</h1>
<p class="max-w-xl mt-4 text-lg text-slate-600">
{{ description }}
</p>
<div class="flex flex-col gap-3 mt-6 sm:flex-row">
<HomeLink
href="/dashboard"
target="_blank"
class="flex items-center justify-center gap-1"
rel="noopener"
>
<AreaChart
class="w-5 h-5"
/>
Dashboard
</HomeLink>
<HomeLink
size="lg"
type="outline"
rel="noopener"
href="https://github.com/ccbikai/sink"
class="flex items-center justify-center gap-1"
target="_blank"
>
<GitHubIcon
class="w-5 h-5"
/>
GitHub Repo
</HomeLink>
</div>
</div>
</main>
</template>
+52
View File
@@ -0,0 +1,52 @@
<script setup>
defineProps({
href: {
type: String,
required: true,
},
block: {
type: Boolean,
default: false,
},
size: {
type: String,
default: 'md',
},
type: {
type: String,
default: 'primary',
},
className: {
type: String,
default: '',
},
})
const sizes = {
lg: 'px-5 py-2.5',
md: 'px-4 py-2',
}
const styles = {
outline: 'bg-white border-2 border-black hover:bg-gray-100 text-black',
primary: 'bg-black text-white hover:bg-gray-800 border-2 border-transparent',
inverted: 'bg-white text-black border-2 border-transparent',
muted: 'bg-gray-100 hover:bg-gray-200 border-2 border-transparent',
}
</script>
<template>
<a
:href="href"
class="rounded text-center transition focus-visible:ring-2 ring-offset-2 ring-gray-200"
:class="[
block && 'w-full',
sizes[size],
styles[type],
className,
]"
v-bind="$attrs"
>
<slot />
</a>
</template>
+19
View File
@@ -0,0 +1,19 @@
<template>
<div class="md:py-12">
<h2 class="text-center text-slate-500">
Built with awesome technologies
</h2>
<div class="flex flex-wrap items-center justify-center gap-8 mt-10 md:gap-20">
<img
class="w-64 aspect-[1256/632]"
alt="Cloudflare"
src="@/assets/images/cloudflare.png"
>
<img
class="w-64 aspect-[1256/632]"
alt="Nuxt.js"
src="@/assets/images/nuxtjs.png"
>
</div>
</div>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup>
import { XIcon } from 'vue3-simple-icons'
import { ArrowRight } from 'lucide-vue-next'
</script>
<template>
<a
href="https://x.com/ccbikai"
target="_blank"
class="inline-flex items-center px-3 py-1 mx-auto my-4 space-x-1 text-sm font-medium rounded-lg bg-muted"
>
<XIcon class="w-4 h-4" />
<Separator
orientation="vertical"
class="h-4"
/>
<span>Follow me on X(Twitter)</span>
<ArrowRight class="w-4 h-4" />
</a>
</template>
+99
View File
@@ -0,0 +1,99 @@
<script setup>
import { GmailIcon, TelegramIcon, BloggerIcon, XIcon, MastodonIcon, GitHubIcon } from 'vue3-simple-icons'
const email = ref(null)
onMounted(() => {
email.value.href = email.value.href.replace('$', '@')
})
</script>
<template>
<section class="text-gray-700 bg-white md:pt-6">
<div class="container flex flex-col items-center py-8 mx-auto sm:flex-row">
<a
href="/"
class="text-xl font-black leading-none text-gray-900 select-none logo"
>Sink</a>
<a
class="mt-4 text-sm text-gray-500 sm:ml-4 sm:pl-4 sm:border-l sm:border-gray-200 sm:mt-0"
href="https://html.zone"
target="_blank"
>
&copy; {{ new Date().getFullYear() }} Products of HTML.ZONE
</a>
<span
class="inline-flex justify-center mt-4 space-x-5 sm:ml-auto sm:mt-0 sm:justify-start"
>
<a
ref="email"
href="mailto:sink.cool$miantiao.me"
title="Email"
class="text-gray-400 hover:text-gray-500"
>
<span class="sr-only">Email</span>
<GmailIcon
class="w-6 h-6"
/>
</a>
<a
href="https://t.me/htmlzone"
target="_blank"
title="Telegram"
class="text-gray-400 hover:text-gray-500"
>
<span class="sr-only">Telegram</span>
<TelegramIcon
class="w-6 h-6"
/>
</a>
<a
href="https://mt.ci"
target="_blank"
title="Blog"
class="text-gray-400 hover:text-gray-500"
>
<span class="sr-only">Blog</span>
<BloggerIcon
class="w-6 h-6"
/>
</a>
<a
href="https://x.com/ccbikai"
target="_blank"
title="Twitter"
class="text-gray-400 hover:text-gray-500"
>
<span class="sr-only">Twitter</span>
<XIcon
class="w-6 h-6"
/>
</a>
<a
href="https://miantiao.me/@chi"
target="_blank"
title="Mastodon"
class="text-gray-400 hover:text-gray-500"
>
<span class="sr-only">Mastodon</span>
<MastodonIcon
class="w-6 h-6"
/>
</a>
<a
href="https://github.com/ccbikai"
target="_blank"
title="GitHub"
class="text-gray-400 hover:text-gray-500"
>
<span class="sr-only">GitHub</span>
<GitHubIcon
class="w-6 h-6"
/>
</a>
</span>
</div>
</section>
</template>
+93
View File
@@ -0,0 +1,93 @@
<script setup>
import { Ellipsis, X } from 'lucide-vue-next'
import { GitHubIcon } from 'vue3-simple-icons'
const showMenu = ref(false)
</script>
<template>
<section class="pb-6 bg-white">
<nav class="container relative z-50 h-24 select-none">
<div
class="container relative flex flex-wrap items-center justify-between h-24 px-0 mx-auto overflow-hidden font-medium border-b border-gray-200 md:overflow-visible lg:justify-center"
>
<div class="flex items-center justify-start w-1/4 h-full pr-4">
<a
href="/"
class="flex items-center py-4 space-x-2 text-xl font-extrabold text-gray-900 md:py-0"
>
<span
class="flex items-center justify-center w-8 h-8 text-white bg-gray-900 rounded-full"
>
<img
src="/sink.png"
alt="Sink"
class="w-full h-full rounded-full"
>
</span>
<span class="mx-2">Sink</span>
</a>
</div>
<div
class="top-0 left-0 items-start w-full h-full p-4 text-sm bg-gray-900 bg-opacity-50 md:items-center md:w-3/4 md:absolute lg:text-base md:bg-transparent md:p-0 md:relative md:flex"
:class="{ 'flex fixed': showMenu, 'hidden': !showMenu }"
@touchmove.prevent
>
<div
class="flex-col w-full h-auto overflow-hidden bg-white rounded-lg md:bg-transparent md:overflow-visible md:rounded-none md:relative md:flex md:flex-row"
>
<a
href="/"
target="_blank"
class="inline-flex items-center w-auto h-16 px-6 text-xl font-black leading-none text-gray-900 md:hidden"
>
<span
class="flex items-center justify-center w-8 h-8 text-white bg-gray-900 rounded-full"
>
<img
src="/sink.png"
alt="Sink"
class="w-full h-full rounded-full"
>
</span>
<span class="mx-2">Sink</span>
</a>
<div class="w-full mx-4" />
<div
class="flex flex-col items-start justify-end w-full pt-4 md:items-center md:w-1/3 md:flex-row md:py-0"
>
<a
class="w-full px-6 py-2 mr-0 text-gray-700 cursor-pointer md:px-3 md:mr-2 lg:mr-3 md:w-auto"
href="/dashboard"
>Dashboard</a>
<a
href="https://github.com/ccbikai/sink"
target="_blank"
class="inline-flex items-center w-full px-6 py-3 text-sm font-medium leading-4 text-white bg-gray-900 md:w-auto md:rounded-full hover:bg-gray-800 focus:outline-none md:focus:ring-2 focus:ring-0 focus:ring-offset-2 focus:ring-gray-800"
>
<GitHubIcon
class="w-5 h-5 mr-1"
/>
GitHub</a>
</div>
</div>
</div>
<div
class="absolute right-0 flex flex-col items-center justify-center w-10 h-10 bg-white rounded-full cursor-pointer md:hidden hover:bg-gray-100"
@click="showMenu = !showMenu"
>
<Ellipsis
v-show="!showMenu"
class="w-6 h-6"
/>
<X
v-show="showMenu"
class="w-6 h-6"
/>
</div>
</div>
</nav>
</section>
</template>
+65
View File
@@ -0,0 +1,65 @@
<script setup>
import { AlertCircle } from 'lucide-vue-next'
import { z } from 'zod'
import { toast } from 'vue-sonner'
const LoginSchema = z.object({
token: z.string().describe('SiteToken'),
})
const loginFieldConfig = {
token: {
inputProps: {
type: 'password',
placeholder: '********',
},
},
}
const { previewMode } = useRuntimeConfig().public
async function onSubmit(form) {
try {
localStorage.setItem('SinkSiteToken', form.token)
await useAPI('/api/verify')
navigateTo('/dashboard')
}
catch (e) {
console.error(e)
toast.error('Login failed, please try again.', {
description: e.message,
})
}
}
</script>
<template>
<Card class="w-full max-w-sm">
<CardHeader>
<CardTitle class="text-2xl">
Login
</CardTitle>
<CardDescription>
Enter your site token to login.
</CardDescription>
</CardHeader>
<CardContent class="grid gap-4">
<AutoForm
class="space-y-6"
:schema="LoginSchema"
:field-config="loginFieldConfig"
@submit="onSubmit"
>
<Alert v-if="previewMode">
<AlertCircle class="w-4 h-4" />
<AlertTitle>Tips</AlertTitle>
<AlertDescription>
The site token for preview mode is <code class="font-mono text-green-500">SinkCool</code> .
</AlertDescription>
</Alert>
<Button class="w-full">
Login
</Button>
</AutoForm>
</CardContent>
</Card>
</template>
+19
View File
@@ -0,0 +1,19 @@
<script setup lang="ts">
import {
AccordionRoot,
type AccordionRootEmits,
type AccordionRootProps,
useForwardPropsEmits,
} from 'radix-vue'
const props = defineProps<AccordionRootProps>()
const emits = defineEmits<AccordionRootEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<AccordionRoot v-bind="forwarded">
<slot />
</AccordionRoot>
</template>
@@ -0,0 +1,24 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import { AccordionContent, type AccordionContentProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<AccordionContentProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
</script>
<template>
<AccordionContent
v-bind="delegatedProps"
class="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
>
<div :class="cn('pb-4 pt-0', props.class)">
<slot />
</div>
</AccordionContent>
</template>
+24
View File
@@ -0,0 +1,24 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import { AccordionItem, type AccordionItemProps, useForwardProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<AccordionItemProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<AccordionItem
v-bind="forwardedProps"
:class="cn('border-b', props.class)"
>
<slot />
</AccordionItem>
</template>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import {
AccordionHeader,
AccordionTrigger,
type AccordionTriggerProps,
} from 'radix-vue'
import { ChevronDown } from 'lucide-vue-next'
import { cn } from '@/utils'
const props = defineProps<AccordionTriggerProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
</script>
<template>
<AccordionHeader class="flex">
<AccordionTrigger
v-bind="delegatedProps"
:class="
cn(
'flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180',
props.class,
)
"
>
<slot />
<slot name="icon">
<ChevronDown
class="h-4 w-4 shrink-0 transition-transform duration-200"
/>
</slot>
</AccordionTrigger>
</AccordionHeader>
</template>
+4
View File
@@ -0,0 +1,4 @@
export { default as Accordion } from './Accordion.vue'
export { default as AccordionContent } from './AccordionContent.vue'
export { default as AccordionItem } from './AccordionItem.vue'
export { default as AccordionTrigger } from './AccordionTrigger.vue'
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { type AlertDialogEmits, type AlertDialogProps, AlertDialogRoot, useForwardPropsEmits } from 'radix-vue'
const props = defineProps<AlertDialogProps>()
const emits = defineEmits<AlertDialogEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<AlertDialogRoot v-bind="forwarded">
<slot />
</AlertDialogRoot>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import { AlertDialogAction, type AlertDialogActionProps } from 'radix-vue'
import { cn } from '@/utils'
import { buttonVariants } from '@/components/ui/button'
const props = defineProps<AlertDialogActionProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
</script>
<template>
<AlertDialogAction v-bind="delegatedProps" :class="cn(buttonVariants(), props.class)">
<slot />
</AlertDialogAction>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import { AlertDialogCancel, type AlertDialogCancelProps } from 'radix-vue'
import { cn } from '@/utils'
import { buttonVariants } from '@/components/ui/button'
const props = defineProps<AlertDialogCancelProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
</script>
<template>
<AlertDialogCancel v-bind="delegatedProps" :class="cn(buttonVariants({ variant: 'outline' }), 'mt-2 sm:mt-0', props.class)">
<slot />
</AlertDialogCancel>
</template>
@@ -0,0 +1,42 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import {
AlertDialogContent,
type AlertDialogContentEmits,
type AlertDialogContentProps,
AlertDialogOverlay,
AlertDialogPortal,
useForwardPropsEmits,
} from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<AlertDialogContentProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<AlertDialogContentEmits>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<AlertDialogPortal>
<AlertDialogOverlay
class="fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
/>
<AlertDialogContent
v-bind="forwarded"
:class="
cn(
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
props.class,
)
"
>
<slot />
</AlertDialogContent>
</AlertDialogPortal>
</template>
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import {
AlertDialogDescription,
type AlertDialogDescriptionProps,
} from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<AlertDialogDescriptionProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
</script>
<template>
<AlertDialogDescription
v-bind="delegatedProps"
:class="cn('text-sm text-muted-foreground', props.class)"
>
<slot />
</AlertDialogDescription>
</template>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div
:class="
cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:gap-x-2',
props.class,
)
"
>
<slot />
</div>
</template>
@@ -0,0 +1,16 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div
:class="cn('flex flex-col gap-y-2 text-center sm:text-left', props.class)"
>
<slot />
</div>
</template>
@@ -0,0 +1,22 @@
<script setup lang="ts">
import { type HTMLAttributes, computed } from 'vue'
import { AlertDialogTitle, type AlertDialogTitleProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<AlertDialogTitleProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
</script>
<template>
<AlertDialogTitle
v-bind="delegatedProps"
:class="cn('text-lg font-semibold', props.class)"
>
<slot />
</AlertDialogTitle>
</template>
@@ -0,0 +1,11 @@
<script setup lang="ts">
import { AlertDialogTrigger, type AlertDialogTriggerProps } from 'radix-vue'
const props = defineProps<AlertDialogTriggerProps>()
</script>
<template>
<AlertDialogTrigger v-bind="props">
<slot />
</AlertDialogTrigger>
</template>
+9
View File
@@ -0,0 +1,9 @@
export { default as AlertDialog } from './AlertDialog.vue'
export { default as AlertDialogTrigger } from './AlertDialogTrigger.vue'
export { default as AlertDialogContent } from './AlertDialogContent.vue'
export { default as AlertDialogHeader } from './AlertDialogHeader.vue'
export { default as AlertDialogTitle } from './AlertDialogTitle.vue'
export { default as AlertDialogDescription } from './AlertDialogDescription.vue'
export { default as AlertDialogFooter } from './AlertDialogFooter.vue'
export { default as AlertDialogAction } from './AlertDialogAction.vue'
export { default as AlertDialogCancel } from './AlertDialogCancel.vue'
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { type AlertVariants, alertVariants } from '.'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
variant?: AlertVariants['variant']
}>()
</script>
<template>
<div :class="cn(alertVariants({ variant }), props.class)" role="alert">
<slot />
</div>
</template>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div :class="cn('text-sm [&_p]:leading-relaxed', props.class)">
<slot />
</div>
</template>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<h5 :class="cn('mb-1 font-medium leading-none tracking-tight', props.class)">
<slot />
</h5>
</template>
+23
View File
@@ -0,0 +1,23 @@
import { type VariantProps, cva } from 'class-variance-authority'
export { default as Alert } from './Alert.vue'
export { default as AlertTitle } from './AlertTitle.vue'
export { default as AlertDescription } from './AlertDescription.vue'
export const alertVariants = cva(
'relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground',
{
variants: {
variant: {
default: 'bg-background text-foreground',
destructive:
'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive',
},
},
defaultVariants: {
variant: 'default',
},
},
)
export type AlertVariants = VariantProps<typeof alertVariants>
@@ -0,0 +1,11 @@
<script setup lang="ts">
import { AspectRatio, type AspectRatioProps } from 'radix-vue'
const props = defineProps<AspectRatioProps>()
</script>
<template>
<AspectRatio v-bind="props">
<slot />
</AspectRatio>
</template>
+1
View File
@@ -0,0 +1 @@
export { default as AspectRatio } from './AspectRatio.vue'
+105
View File
@@ -0,0 +1,105 @@
<script setup lang="ts" generic="T extends ZodObjectOrWrapped">
import { computed, toRefs } from 'vue'
import type { ZodAny, z } from 'zod'
import { toTypedSchema } from '@vee-validate/zod'
import type { FormContext, GenericObject } from 'vee-validate'
import { type ZodObjectOrWrapped, getBaseSchema, getBaseType, getDefaultValueInZodStack, getObjectFormSchema } from './utils'
import type { Config, ConfigItem, Dependency, Shape } from './interface'
import AutoFormField from './AutoFormField.vue'
import { provideDependencies } from './dependencies'
import { Form } from '@/components/ui/form'
const props = defineProps<{
schema: T
form?: FormContext<GenericObject>
fieldConfig?: Config<z.infer<T>>
dependencies?: Dependency<z.infer<T>>[]
}>()
const emits = defineEmits<{
submit: [event: GenericObject]
}>()
const { dependencies } = toRefs(props)
provideDependencies(dependencies)
const shapes = computed(() => {
// @ts-expect-error ignore {} not assignable to object
const val: { [key in keyof T]: Shape } = {}
const baseSchema = getObjectFormSchema(props.schema)
const shape = baseSchema.shape
Object.keys(shape).forEach((name) => {
const item = shape[name] as ZodAny
const baseItem = getBaseSchema(item) as ZodAny
let options = (baseItem && 'values' in baseItem._def) ? baseItem._def.values as string[] : undefined
if (!Array.isArray(options) && typeof options === 'object')
options = Object.values(options)
val[name as keyof T] = {
type: getBaseType(item),
default: getDefaultValueInZodStack(item),
options,
required: !['ZodOptional', 'ZodNullable'].includes(item._def.typeName),
schema: baseItem,
}
})
return val
})
const fields = computed(() => {
// @ts-expect-error ignore {} not assignable to object
const val: { [key in keyof z.infer<T>]: { shape: Shape, fieldName: string, config: ConfigItem } } = {}
for (const key in shapes.value) {
const shape = shapes.value[key]
val[key as keyof z.infer<T>] = {
shape,
config: props.fieldConfig?.[key] as ConfigItem,
fieldName: key,
}
}
return val
})
const formComponent = computed(() => props.form ? 'form' : Form)
const formComponentProps = computed(() => {
if (props.form) {
return {
onSubmit: props.form.handleSubmit(val => emits('submit', val)),
}
}
else {
const formSchema = toTypedSchema(props.schema)
return {
keepValues: true,
validationSchema: formSchema,
onSubmit: (val: GenericObject) => emits('submit', val),
}
}
})
</script>
<template>
<component
:is="formComponent"
v-bind="formComponentProps"
>
<slot name="customAutoForm" :fields="fields">
<template v-for="(shape, key) of shapes" :key="key">
<slot
:shape="shape"
:name="key.toString() as keyof z.infer<T>"
:field-name="key.toString()"
:config="fieldConfig?.[key as keyof typeof fieldConfig] as ConfigItem"
>
<AutoFormField
:config="fieldConfig?.[key as keyof typeof fieldConfig] as ConfigItem"
:field-name="key.toString()"
:shape="shape"
/>
</slot>
</template>
</slot>
<slot :shapes="shapes" />
</component>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts" generic="U extends ZodAny">
import type { ZodAny } from 'zod'
import { computed } from 'vue'
import type { Config, ConfigItem, Shape } from './interface'
import { DEFAULT_ZOD_HANDLERS, INPUT_COMPONENTS } from './constant'
import useDependencies from './dependencies'
const props = defineProps<{
fieldName: string
shape: Shape
config?: ConfigItem | Config<U>
}>()
function isValidConfig(config: any): config is ConfigItem {
return !!config?.component
}
const delegatedProps = computed(() => {
if (['ZodObject', 'ZodArray'].includes(props.shape?.type))
return { schema: props.shape?.schema }
return undefined
})
const { isDisabled, isHidden, isRequired, overrideOptions } = useDependencies(props.fieldName)
</script>
<template>
<component
:is="isValidConfig(config)
? typeof config.component === 'string'
? INPUT_COMPONENTS[config.component!]
: config.component
: INPUT_COMPONENTS[DEFAULT_ZOD_HANDLERS[shape.type]] "
v-if="!isHidden"
:field-name="fieldName"
:label="shape.schema?.description"
:required="isRequired || shape.required"
:options="overrideOptions || shape.options"
:disabled="isDisabled"
:config="config"
v-bind="delegatedProps"
>
<slot />
</component>
</template>
@@ -0,0 +1,110 @@
<script setup lang="ts" generic="T extends z.ZodAny">
import * as z from 'zod'
import { computed, provide } from 'vue'
import { PlusIcon, TrashIcon } from 'lucide-vue-next'
import { FieldArray, FieldContextKey, useField } from 'vee-validate'
import type { Config, ConfigItem } from './interface'
import { beautifyObjectName, getBaseType } from './utils'
import AutoFormField from './AutoFormField.vue'
import AutoFormLabel from './AutoFormLabel.vue'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { FormItem, FormMessage } from '@/components/ui/form'
const props = defineProps<{
fieldName: string
required?: boolean
config?: Config<T>
schema?: z.ZodArray<T>
disabled?: boolean
}>()
function isZodArray(
item: z.ZodArray<any> | z.ZodDefault<any>,
): item is z.ZodArray<any> {
return item instanceof z.ZodArray
}
function isZodDefault(
item: z.ZodArray<any> | z.ZodDefault<any>,
): item is z.ZodDefault<any> {
return item instanceof z.ZodDefault
}
const itemShape = computed(() => {
if (!props.schema)
return
const schema: z.ZodAny = isZodArray(props.schema)
? props.schema._def.type
: isZodDefault(props.schema)
// @ts-expect-error missing schema
? props.schema._def.innerType._def.type
: null
return {
type: getBaseType(schema),
schema,
}
})
const fieldContext = useField(props.fieldName)
// @ts-expect-error ignore missing `id`
provide(FieldContextKey, fieldContext)
</script>
<template>
<FieldArray v-slot="{ fields, remove, push }" as="section" :name="fieldName">
<slot v-bind="props">
<Accordion type="multiple" class="w-full" collapsible :disabled="disabled" as-child>
<FormItem>
<AccordionItem :value="fieldName" class="border-none">
<AccordionTrigger>
<AutoFormLabel class="text-base" :required="required">
{{ schema?.description || beautifyObjectName(fieldName) }}
</AutoFormLabel>
</AccordionTrigger>
<AccordionContent>
<template v-for="(field, index) of fields" :key="field.key">
<div class="mb-4 p-1">
<AutoFormField
:field-name="`${fieldName}[${index}]`"
:label="fieldName"
:shape="itemShape!"
:config="config as ConfigItem"
/>
<div class="!my-4 flex justify-end">
<Button
type="button"
size="icon"
variant="secondary"
@click="remove(index)"
>
<TrashIcon :size="16" />
</Button>
</div>
<Separator v-if="!field.isLast" />
</div>
</template>
<Button
type="button"
variant="secondary"
class="mt-4 flex items-center"
@click="push(null)"
>
<PlusIcon class="mr-2" :size="16" />
Add
</Button>
</AccordionContent>
<FormMessage />
</AccordionItem>
</FormItem>
</Accordion>
</slot>
</FieldArray>
</template>
@@ -0,0 +1,41 @@
<script setup lang="ts">
import { computed } from 'vue'
import { beautifyObjectName } from './utils'
import type { FieldProps } from './interface'
import AutoFormLabel from './AutoFormLabel.vue'
import { FormControl, FormDescription, FormField, FormItem, FormMessage } from '@/components/ui/form'
import { Switch } from '@/components/ui/switch'
import { Checkbox } from '@/components/ui/checkbox'
const props = defineProps<FieldProps>()
const booleanComponent = computed(() => props.config?.component === 'switch' ? Switch : Checkbox)
</script>
<template>
<FormField v-slot="slotProps" :name="fieldName">
<FormItem>
<div class="space-y-0 mb-3 flex items-center gap-3">
<FormControl>
<slot v-bind="slotProps">
<component
:is="booleanComponent"
v-bind="{ ...slotProps.componentField }"
:disabled="disabled"
:checked="slotProps.componentField.modelValue"
@update:checked="slotProps.componentField['onUpdate:modelValue']"
/>
</slot>
</FormControl>
<AutoFormLabel v-if="!config?.hideLabel" :required="required">
{{ config?.label || beautifyObjectName(label ?? fieldName) }}
</AutoFormLabel>
</div>
<FormDescription v-if="config?.description">
{{ config.description }}
</FormDescription>
<FormMessage />
</FormItem>
</FormField>
</template>
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { DateFormatter, getLocalTimeZone } from '@internationalized/date'
import { CalendarIcon } from 'lucide-vue-next'
import { beautifyObjectName } from './utils'
import AutoFormLabel from './AutoFormLabel.vue'
import type { FieldProps } from './interface'
import { FormControl, FormDescription, FormField, FormItem, FormMessage } from '@/components/ui/form'
import { Calendar } from '@/components/ui/calendar'
import { Button } from '@/components/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/utils'
defineProps<FieldProps>()
const df = new DateFormatter('en-US', {
dateStyle: 'long',
})
</script>
<template>
<FormField v-slot="slotProps" :name="fieldName">
<FormItem>
<AutoFormLabel v-if="!config?.hideLabel" :required="required">
{{ config?.label || beautifyObjectName(label ?? fieldName) }}
</AutoFormLabel>
<FormControl>
<slot v-bind="slotProps">
<div>
<Popover>
<PopoverTrigger as-child :disabled="disabled">
<Button
variant="outline"
:class="cn(
'w-full justify-start text-left font-normal',
!slotProps.componentField.modelValue && 'text-muted-foreground',
)"
>
<CalendarIcon class="mr-2 h-4 w-4" :size="16" />
{{ slotProps.componentField.modelValue ? df.format(slotProps.componentField.modelValue.toDate(getLocalTimeZone())) : "Pick a date" }}
</Button>
</PopoverTrigger>
<PopoverContent class="w-auto p-0">
<Calendar initial-focus v-bind="slotProps.componentField" />
</PopoverContent>
</Popover>
</div>
</slot>
</FormControl>
<FormDescription v-if="config?.description">
{{ config.description }}
</FormDescription>
<FormMessage />
</FormItem>
</FormField>
</template>
@@ -0,0 +1,49 @@
<script setup lang="ts">
import AutoFormLabel from './AutoFormLabel.vue'
import { beautifyObjectName } from './utils'
import type { FieldProps } from './interface'
import { FormControl, FormDescription, FormField, FormItem, FormMessage } from '@/components/ui/form'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
defineProps<FieldProps & {
options?: string[]
}>()
</script>
<template>
<FormField v-slot="slotProps" :name="fieldName">
<FormItem>
<AutoFormLabel v-if="!config?.hideLabel" :required="required">
{{ config?.label || beautifyObjectName(label ?? fieldName) }}
</AutoFormLabel>
<FormControl>
<slot v-bind="slotProps">
<RadioGroup v-if="config?.component === 'radio'" :disabled="disabled" :orientation="'vertical'" v-bind="{ ...slotProps.componentField }">
<div v-for="(option, index) in options" :key="option" class="mb-2 flex items-center gap-3 space-y-0">
<RadioGroupItem :id="`${option}-${index}`" :value="option" />
<Label :for="`${option}-${index}`">{{ beautifyObjectName(option) }}</Label>
</div>
</RadioGroup>
<Select v-else :disabled="disabled" v-bind="{ ...slotProps.componentField }">
<SelectTrigger class="w-full">
<SelectValue :placeholder="config?.inputProps?.placeholder" />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="option in options" :key="option" :value="option">
{{ beautifyObjectName(option) }}
</SelectItem>
</SelectContent>
</Select>
</slot>
</FormControl>
<FormDescription v-if="config?.description">
{{ config.description }}
</FormDescription>
<FormMessage />
</FormItem>
</FormField>
</template>
@@ -0,0 +1,74 @@
<script setup lang="ts">
import { ref } from 'vue'
import { TrashIcon } from 'lucide-vue-next'
import AutoFormLabel from './AutoFormLabel.vue'
import { beautifyObjectName } from './utils'
import type { FieldProps } from './interface'
import { FormControl, FormDescription, FormField, FormItem, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
defineProps<FieldProps>()
const inputFile = ref<File>()
async function parseFileAsString(file: File | undefined): Promise<string> {
return new Promise((resolve, reject) => {
if (file) {
const reader = new FileReader()
reader.onloadend = () => {
resolve(reader.result as string)
}
reader.onerror = (err) => {
reject(err)
}
reader.readAsDataURL(file)
}
})
}
</script>
<template>
<FormField v-slot="slotProps" :name="fieldName">
<FormItem v-bind="$attrs">
<AutoFormLabel v-if="!config?.hideLabel" :required="required">
{{ config?.label || beautifyObjectName(label ?? fieldName) }}
</AutoFormLabel>
<FormControl>
<slot v-bind="slotProps">
<Input
v-if="!inputFile"
type="file"
v-bind="{ ...config?.inputProps }"
:disabled="disabled"
@change="async (ev: InputEvent) => {
const file = (ev.target as HTMLInputElement).files?.[0]
inputFile = file
const parsed = await parseFileAsString(file)
slotProps.componentField.onInput(parsed)
}"
/>
<div v-else class="flex h-10 w-full items-center justify-between rounded-md border border-input bg-transparent pl-3 pr-1 py-1 text-sm shadow-sm transition-colors">
<p>{{ inputFile?.name }}</p>
<Button
:size="'icon'"
:variant="'ghost'"
class="h-[26px] w-[26px]"
aria-label="Remove file"
type="button"
@click="() => {
inputFile = undefined
slotProps.componentField.onInput(undefined)
}"
>
<TrashIcon :size="16" />
</Button>
</div>
</slot>
</FormControl>
<FormDescription v-if="config?.description">
{{ config.description }}
</FormDescription>
<FormMessage />
</FormItem>
</FormField>
</template>
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { computed } from 'vue'
import AutoFormLabel from './AutoFormLabel.vue'
import { beautifyObjectName } from './utils'
import type { FieldProps } from './interface'
import { FormControl, FormDescription, FormField, FormItem, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
const props = defineProps<FieldProps>()
const inputComponent = computed(() => props.config?.component === 'textarea' ? Textarea : Input)
</script>
<template>
<FormField v-slot="slotProps" :name="fieldName">
<FormItem v-bind="$attrs">
<AutoFormLabel v-if="!config?.hideLabel" :required="required">
{{ config?.label || beautifyObjectName(label ?? fieldName) }}
</AutoFormLabel>
<FormControl>
<slot v-bind="slotProps">
<component
:is="inputComponent"
type="text"
v-bind="{ ...slotProps.componentField, ...config?.inputProps }"
:disabled="disabled"
/>
</slot>
</FormControl>
<FormDescription v-if="config?.description">
{{ config.description }}
</FormDescription>
<FormMessage />
</FormItem>
</FormField>
</template>
@@ -0,0 +1,32 @@
<script setup lang="ts">
import AutoFormLabel from './AutoFormLabel.vue'
import { beautifyObjectName } from './utils'
import type { FieldProps } from './interface'
import { FormControl, FormDescription, FormField, FormItem, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
defineOptions({
inheritAttrs: false,
})
defineProps<FieldProps>()
</script>
<template>
<FormField v-slot="slotProps" :name="fieldName">
<FormItem>
<AutoFormLabel v-if="!config?.hideLabel" :required="required">
{{ config?.label || beautifyObjectName(label ?? fieldName) }}
</AutoFormLabel>
<FormControl>
<slot v-bind="slotProps">
<Input type="number" v-bind="{ ...slotProps.componentField, ...config?.inputProps }" :disabled="disabled" />
</slot>
</FormControl>
<FormDescription v-if="config?.description">
{{ config.description }}
</FormDescription>
<FormMessage />
</FormItem>
</FormField>
</template>
@@ -0,0 +1,78 @@
<script setup lang="ts" generic="T extends ZodRawShape">
import type { ZodAny, ZodObject, ZodRawShape } from 'zod'
import { computed, provide } from 'vue'
import { FieldContextKey, useField } from 'vee-validate'
import AutoFormField from './AutoFormField.vue'
import type { Config, ConfigItem, Shape } from './interface'
import { beautifyObjectName, getBaseSchema, getBaseType, getDefaultValueInZodStack } from './utils'
import AutoFormLabel from './AutoFormLabel.vue'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
import { FormItem } from '@/components/ui/form'
const props = defineProps<{
fieldName: string
required?: boolean
config?: Config<T>
schema?: ZodObject<T>
disabled?: boolean
}>()
const shapes = computed(() => {
// @ts-expect-error ignore {} not assignable to object
const val: { [key in keyof T]: Shape } = {}
if (!props.schema)
return
const shape = getBaseSchema(props.schema)?.shape
if (!shape)
return
Object.keys(shape).forEach((name) => {
const item = shape[name] as ZodAny
const baseItem = getBaseSchema(item) as ZodAny
let options = (baseItem && 'values' in baseItem._def) ? baseItem._def.values as string[] : undefined
if (!Array.isArray(options) && typeof options === 'object')
options = Object.values(options)
val[name as keyof T] = {
type: getBaseType(item),
default: getDefaultValueInZodStack(item),
options,
required: !['ZodOptional', 'ZodNullable'].includes(item._def.typeName),
schema: item,
}
})
return val
})
const fieldContext = useField(props.fieldName)
// @ts-expect-error ignore missing `id`
provide(FieldContextKey, fieldContext)
</script>
<template>
<section>
<slot v-bind="props">
<Accordion type="single" as-child class="w-full" collapsible :disabled="disabled">
<FormItem>
<AccordionItem :value="fieldName" class="border-none">
<AccordionTrigger>
<AutoFormLabel class="text-base" :required="required">
{{ schema?.description || beautifyObjectName(fieldName) }}
</AutoFormLabel>
</AccordionTrigger>
<AccordionContent class="p-1 space-y-5">
<template v-for="(shape, key) in shapes" :key="key">
<AutoFormField
:config="config?.[key as keyof typeof config] as ConfigItem"
:field-name="`${fieldName}.${key.toString()}`"
:label="key.toString()"
:shape="shape"
/>
</template>
</AccordionContent>
</AccordionItem>
</FormItem>
</Accordion>
</slot>
</section>
</template>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { FormLabel } from '@/components/ui/form'
defineProps<{
required?: boolean
}>()
</script>
<template>
<FormLabel>
<slot />
<span v-if="required" class="text-destructive"> *</span>
</FormLabel>
</template>
+39
View File
@@ -0,0 +1,39 @@
import AutoFormFieldArray from './AutoFormFieldArray.vue'
import AutoFormFieldBoolean from './AutoFormFieldBoolean.vue'
import AutoFormFieldDate from './AutoFormFieldDate.vue'
import AutoFormFieldEnum from './AutoFormFieldEnum.vue'
import AutoFormFieldFile from './AutoFormFieldFile.vue'
import AutoFormFieldInput from './AutoFormFieldInput.vue'
import AutoFormFieldNumber from './AutoFormFieldNumber.vue'
import AutoFormFieldObject from './AutoFormFieldObject.vue'
export const INPUT_COMPONENTS = {
date: AutoFormFieldDate,
select: AutoFormFieldEnum,
radio: AutoFormFieldEnum,
checkbox: AutoFormFieldBoolean,
switch: AutoFormFieldBoolean,
textarea: AutoFormFieldInput,
number: AutoFormFieldNumber,
string: AutoFormFieldInput,
file: AutoFormFieldFile,
array: AutoFormFieldArray,
object: AutoFormFieldObject,
}
/**
* Define handlers for specific Zod types.
* You can expand this object to support more types.
*/
export const DEFAULT_ZOD_HANDLERS: {
[key: string]: keyof typeof INPUT_COMPONENTS
} = {
ZodString: 'string',
ZodBoolean: 'checkbox',
ZodDate: 'date',
ZodEnum: 'select',
ZodNativeEnum: 'select',
ZodNumber: 'number',
ZodArray: 'array',
ZodObject: 'object',
}
+92
View File
@@ -0,0 +1,92 @@
import type * as z from 'zod'
import type { Ref } from 'vue'
import { computed, ref, watch } from 'vue'
import { useFieldValue, useFormValues } from 'vee-validate'
import { createContext } from 'radix-vue'
import { type Dependency, DependencyType, type EnumValues } from './interface'
import { getFromPath, getIndexIfArray } from './utils'
export const [injectDependencies, provideDependencies] = createContext<Ref<Dependency<z.infer<z.ZodObject<any>>>[] | undefined>>('AutoFormDependencies')
export default function useDependencies(
fieldName: string,
) {
const form = useFormValues()
// parsed test[0].age => test.age
const currentFieldName = fieldName.replace(/\[\d+\]/g, '')
const currentFieldValue = useFieldValue<any>(fieldName)
if (!form)
throw new Error('useDependencies should be used within <AutoForm>')
const dependencies = injectDependencies()
const isDisabled = ref(false)
const isHidden = ref(false)
const isRequired = ref(false)
const overrideOptions = ref<EnumValues | undefined>()
const currentFieldDependencies = computed(() => dependencies.value?.filter(
dependency => dependency.targetField === currentFieldName,
))
function getSourceValue(dep: Dependency<any>) {
const source = dep.sourceField as string
const index = getIndexIfArray(fieldName) ?? -1
const [sourceLast, ...sourceInitial] = source.split('.').toReversed()
const [_targetLast, ...targetInitial] = (dep.targetField as string).split('.').toReversed()
if (index >= 0 && sourceInitial.join(',') === targetInitial.join(',')) {
const [_currentLast, ...currentInitial] = fieldName.split('.').toReversed()
return getFromPath(form.value, currentInitial.join('.') + sourceLast)
}
return getFromPath(form.value, source)
}
const sourceFieldValues = computed(() => currentFieldDependencies.value?.map(dep => getSourceValue(dep)))
const resetConditionState = () => {
isDisabled.value = false
isHidden.value = false
isRequired.value = false
overrideOptions.value = undefined
}
watch([sourceFieldValues, dependencies], () => {
resetConditionState()
currentFieldDependencies.value?.forEach((dep) => {
const sourceValue = getSourceValue(dep)
const conditionMet = dep.when(sourceValue, currentFieldValue.value)
switch (dep.type) {
case DependencyType.DISABLES:
if (conditionMet)
isDisabled.value = true
break
case DependencyType.REQUIRES:
if (conditionMet)
isRequired.value = true
break
case DependencyType.HIDES:
if (conditionMet)
isHidden.value = true
break
case DependencyType.SETS_OPTIONS:
if (conditionMet)
overrideOptions.value = dep.options
break
}
})
}, { immediate: true, deep: true })
return {
isDisabled,
isHidden,
isRequired,
overrideOptions,
}
}
+15
View File
@@ -0,0 +1,15 @@
export { getObjectFormSchema, getBaseSchema, getBaseType } from './utils'
export type { Config, ConfigItem, FieldProps } from './interface'
export { default as AutoForm } from './AutoForm.vue'
export { default as AutoFormField } from './AutoFormField.vue'
export { default as AutoFormLabel } from './AutoFormLabel.vue'
export { default as AutoFormFieldArray } from './AutoFormFieldArray.vue'
export { default as AutoFormFieldBoolean } from './AutoFormFieldBoolean.vue'
export { default as AutoFormFieldDate } from './AutoFormFieldDate.vue'
export { default as AutoFormFieldEnum } from './AutoFormFieldEnum.vue'
export { default as AutoFormFieldFile } from './AutoFormFieldFile.vue'
export { default as AutoFormFieldInput } from './AutoFormFieldInput.vue'
export { default as AutoFormFieldNumber } from './AutoFormFieldNumber.vue'
export { default as AutoFormFieldObject } from './AutoFormFieldObject.vue'
+81
View File
@@ -0,0 +1,81 @@
import type { Component, InputHTMLAttributes } from 'vue'
import type { ZodAny, z } from 'zod'
import type { INPUT_COMPONENTS } from './constant'
export interface FieldProps {
fieldName: string
label?: string
required?: boolean
config?: ConfigItem
disabled?: boolean
}
export interface Shape {
type: string
default?: any
required?: boolean
options?: string[]
schema?: ZodAny
}
export interface ConfigItem {
/** Value for the `FormLabel` */
label?: string
/** Value for the `FormDescription` */
description?: string
/** Pick which component to be rendered. */
component?: keyof typeof INPUT_COMPONENTS | Component
/** Hide `FormLabel`. */
hideLabel?: boolean
inputProps?: InputHTMLAttributes
}
// Define a type to unwrap an array
type UnwrapArray<T> = T extends (infer U)[] ? U : never
export type Config<SchemaType extends object> = {
// If SchemaType.key is an object, create a nested Config, otherwise ConfigItem
[Key in keyof SchemaType]?:
SchemaType[Key] extends any[]
? UnwrapArray<Config<SchemaType[Key]>>
: SchemaType[Key] extends object
? Config<SchemaType[Key]>
: ConfigItem;
}
export enum DependencyType {
DISABLES,
REQUIRES,
HIDES,
SETS_OPTIONS,
}
interface BaseDependency<SchemaType extends z.infer<z.ZodObject<any, any>>> {
sourceField: keyof SchemaType
type: DependencyType
targetField: keyof SchemaType
when: (sourceFieldValue: any, targetFieldValue: any) => boolean
}
export type ValueDependency<SchemaType extends z.infer<z.ZodObject<any, any>>> =
BaseDependency<SchemaType> & {
type:
| DependencyType.DISABLES
| DependencyType.REQUIRES
| DependencyType.HIDES
}
export type EnumValues = readonly [string, ...string[]]
export type OptionsDependency<
SchemaType extends z.infer<z.ZodObject<any, any>>,
> = BaseDependency<SchemaType> & {
type: DependencyType.SETS_OPTIONS
// Partial array of values from sourceField that will trigger the dependency
options: EnumValues
}
export type Dependency<SchemaType extends z.infer<z.ZodObject<any, any>>> =
| ValueDependency<SchemaType>
| OptionsDependency<SchemaType>
+171
View File
@@ -0,0 +1,171 @@
import type { z } from 'zod'
// TODO: This should support recursive ZodEffects but TypeScript doesn't allow circular type definitions.
export type ZodObjectOrWrapped =
| z.ZodObject<any, any>
| z.ZodEffects<z.ZodObject<any, any>>
/**
* Beautify a camelCase string.
* e.g. "myString" -> "My String"
*/
export function beautifyObjectName(string: string) {
// Remove bracketed indices
// if numbers only return the string
let output = string.replace(/\[\d+\]/g, '').replace(/([A-Z])/g, ' $1')
output = output.charAt(0).toUpperCase() + output.slice(1)
return output
}
/**
* Parse string and extract the index
* @param string
* @returns index or undefined
*/
export function getIndexIfArray(string: string) {
const indexRegex = /\[(\d+)\]/
// Match the index
const match = string.match(indexRegex)
// Extract the index (number)
const index = match ? Number.parseInt(match[1]) : undefined
return index
}
/**
* Get the lowest level Zod type.
* This will unpack optionals, refinements, etc.
*/
export function getBaseSchema<
ChildType extends z.ZodAny | z.AnyZodObject = z.ZodAny,
>(schema: ChildType | z.ZodEffects<ChildType>): ChildType | null {
if (!schema)
return null
if ('innerType' in schema._def)
return getBaseSchema(schema._def.innerType as ChildType)
if ('schema' in schema._def)
return getBaseSchema(schema._def.schema as ChildType)
return schema as ChildType
}
/**
* Get the type name of the lowest level Zod type.
* This will unpack optionals, refinements, etc.
*/
export function getBaseType(schema: z.ZodAny) {
const baseSchema = getBaseSchema(schema)
return baseSchema ? baseSchema._def.typeName : ''
}
/**
* Search for a "ZodDefault" in the Zod stack and return its value.
*/
export function getDefaultValueInZodStack(schema: z.ZodAny): any {
const typedSchema = schema as unknown as z.ZodDefault<
z.ZodNumber | z.ZodString
>
if (typedSchema._def.typeName === 'ZodDefault')
return typedSchema._def.defaultValue()
if ('innerType' in typedSchema._def) {
return getDefaultValueInZodStack(
typedSchema._def.innerType as unknown as z.ZodAny,
)
}
if ('schema' in typedSchema._def) {
return getDefaultValueInZodStack(
(typedSchema._def as any).schema as z.ZodAny,
)
}
return undefined
}
export function getObjectFormSchema(
schema: ZodObjectOrWrapped,
): z.ZodObject<any, any> {
if (schema?._def.typeName === 'ZodEffects') {
const typedSchema = schema as z.ZodEffects<z.ZodObject<any, any>>
return getObjectFormSchema(typedSchema._def.schema)
}
return schema as z.ZodObject<any, any>
}
function isIndex(value: unknown): value is number {
return Number(value) >= 0
}
/**
* Constructs a path with dot paths for arrays to use brackets to be compatible with vee-validate path syntax
*/
export function normalizeFormPath(path: string): string {
const pathArr = path.split('.')
if (!pathArr.length)
return ''
let fullPath = String(pathArr[0])
for (let i = 1; i < pathArr.length; i++) {
if (isIndex(pathArr[i])) {
fullPath += `[${pathArr[i]}]`
continue
}
fullPath += `.${pathArr[i]}`
}
return fullPath
}
type NestedRecord = Record<string, unknown> | { [k: string]: NestedRecord }
/**
* Checks if the path opted out of nested fields using `[fieldName]` syntax
*/
export function isNotNestedPath(path: string) {
return /^\[.+\]$/i.test(path)
}
function isObject(obj: unknown): obj is Record<string, unknown> {
return obj !== null && !!obj && typeof obj === 'object' && !Array.isArray(obj)
}
function isContainerValue(value: unknown): value is Record<string, unknown> {
return isObject(value) || Array.isArray(value)
}
function cleanupNonNestedPath(path: string) {
if (isNotNestedPath(path))
return path.replace(/\[|\]/gi, '')
return path
}
/**
* Gets a nested property value from an object
*/
export function getFromPath<TValue = unknown>(object: NestedRecord | undefined, path: string): TValue | undefined
export function getFromPath<TValue = unknown, TFallback = TValue>(
object: NestedRecord | undefined,
path: string,
fallback?: TFallback,
): TValue | TFallback
export function getFromPath<TValue = unknown, TFallback = TValue>(
object: NestedRecord | undefined,
path: string,
fallback?: TFallback,
): TValue | TFallback | undefined {
if (!object)
return fallback
if (isNotNestedPath(path))
return object[cleanupNonNestedPath(path)] as TValue | undefined
const resolvedValue = (path || '')
.split(/\.|\[(\d+)\]/)
.filter(Boolean)
.reduce((acc, propKey) => {
if (isContainerValue(acc) && propKey in acc)
return acc[propKey]
return fallback
}, object as unknown)
return resolvedValue as TValue | undefined
}
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { AvatarRoot } from 'radix-vue'
import { type AvatarVariants, avatarVariant } from '.'
import { cn } from '@/utils'
const props = withDefaults(defineProps<{
class?: HTMLAttributes['class']
size?: AvatarVariants['size']
shape?: AvatarVariants['shape']
}>(), {
size: 'sm',
shape: 'circle',
})
</script>
<template>
<AvatarRoot :class="cn(avatarVariant({ size, shape }), props.class)">
<slot />
</AvatarRoot>
</template>
+11
View File
@@ -0,0 +1,11 @@
<script setup lang="ts">
import { AvatarFallback, type AvatarFallbackProps } from 'radix-vue'
const props = defineProps<AvatarFallbackProps>()
</script>
<template>
<AvatarFallback v-bind="props">
<slot />
</AvatarFallback>
</template>
+9
View File
@@ -0,0 +1,9 @@
<script setup lang="ts">
import { AvatarImage, type AvatarImageProps } from 'radix-vue'
const props = defineProps<AvatarImageProps>()
</script>
<template>
<AvatarImage v-bind="props" class="h-full w-full object-cover" />
</template>
+24
View File
@@ -0,0 +1,24 @@
import { type VariantProps, cva } from 'class-variance-authority'
export { default as Avatar } from './Avatar.vue'
export { default as AvatarImage } from './AvatarImage.vue'
export { default as AvatarFallback } from './AvatarFallback.vue'
export const avatarVariant = cva(
'inline-flex items-center justify-center font-normal text-foreground select-none shrink-0 bg-secondary overflow-hidden',
{
variants: {
size: {
sm: 'h-10 w-10 text-xs',
base: 'h-16 w-16 text-2xl',
lg: 'h-32 w-32 text-5xl',
},
shape: {
circle: 'rounded-full',
square: 'rounded-md',
},
},
},
)
export type AvatarVariants = VariantProps<typeof avatarVariant>
+13
View File
@@ -0,0 +1,13 @@
<script lang="ts" setup>
import type { HTMLAttributes } from 'vue'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<nav aria-label="breadcrumb" :class="props.class">
<slot />
</nav>
</template>
@@ -0,0 +1,22 @@
<script lang="ts" setup>
import type { HTMLAttributes } from 'vue'
import { MoreHorizontal } from 'lucide-vue-next'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<span
role="presentation"
aria-hidden="true"
:class="cn('flex h-9 w-9 items-center justify-center', props.class)"
>
<slot>
<MoreHorizontal class="h-4 w-4" />
</slot>
<span class="sr-only">More</span>
</span>
</template>
@@ -0,0 +1,16 @@
<script lang="ts" setup>
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<li
:class="cn('inline-flex items-center gap-1.5', props.class)"
>
<slot />
</li>
</template>
@@ -0,0 +1,19 @@
<script lang="ts" setup>
import type { HTMLAttributes } from 'vue'
import { Primitive, type PrimitiveProps } from 'radix-vue'
import { cn } from '@/utils'
const props = withDefaults(defineProps<PrimitiveProps & { class?: HTMLAttributes['class'] }>(), {
as: 'a',
})
</script>
<template>
<Primitive
:as="as"
:as-child="asChild"
:class="cn('transition-colors hover:text-foreground', props.class)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,16 @@
<script lang="ts" setup>
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<ol
:class="cn('flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5', props.class)"
>
<slot />
</ol>
</template>
@@ -0,0 +1,19 @@
<script lang="ts" setup>
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<span
role="link"
aria-disabled="true"
aria-current="page"
:class="cn('font-normal text-foreground', props.class)"
>
<slot />
</span>
</template>
@@ -0,0 +1,21 @@
<script lang="ts" setup>
import type { HTMLAttributes } from 'vue'
import { ChevronRight } from 'lucide-vue-next'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<li
role="presentation"
aria-hidden="true"
:class="cn('[&>svg]:size-3.5', props.class)"
>
<slot>
<ChevronRight />
</slot>
</li>
</template>
+7
View File
@@ -0,0 +1,7 @@
export { default as Breadcrumb } from './Breadcrumb.vue'
export { default as BreadcrumbEllipsis } from './BreadcrumbEllipsis.vue'
export { default as BreadcrumbItem } from './BreadcrumbItem.vue'
export { default as BreadcrumbLink } from './BreadcrumbLink.vue'
export { default as BreadcrumbList } from './BreadcrumbList.vue'
export { default as BreadcrumbPage } from './BreadcrumbPage.vue'
export { default as BreadcrumbSeparator } from './BreadcrumbSeparator.vue'
+26
View File
@@ -0,0 +1,26 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { Primitive, type PrimitiveProps } from 'radix-vue'
import { type ButtonVariants, buttonVariants } from '.'
import { cn } from '@/utils'
interface Props extends PrimitiveProps {
variant?: ButtonVariants['variant']
size?: ButtonVariants['size']
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'button',
})
</script>
<template>
<Primitive
:as="as"
:as-child="asChild"
:class="cn(buttonVariants({ variant, size }), props.class)"
>
<slot />
</Primitive>
</template>
+35
View File
@@ -0,0 +1,35 @@
import { type VariantProps, cva } from 'class-variance-authority'
export { default as Button } from './Button.vue'
export const buttonVariants = cva(
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground hover:bg-destructive/90',
outline:
'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-10 px-4 py-2',
xs: 'h-7 rounded px-2',
sm: 'h-9 rounded-md px-3',
lg: 'h-11 rounded-md px-8',
icon: 'h-10 w-10',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
},
)
export type ButtonVariants = VariantProps<typeof buttonVariants>
+60
View File
@@ -0,0 +1,60 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarRoot, type CalendarRootEmits, type CalendarRootProps, useForwardPropsEmits } from 'radix-vue'
import { CalendarCell, CalendarCellTrigger, CalendarGrid, CalendarGridBody, CalendarGridHead, CalendarGridRow, CalendarHeadCell, CalendarHeader, CalendarHeading, CalendarNextButton, CalendarPrevButton } from '.'
import { cn } from '@/utils'
const props = defineProps<CalendarRootProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<CalendarRootEmits>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<CalendarRoot
v-slot="{ grid, weekDays }"
:class="cn('p-3', props.class)"
v-bind="forwarded"
>
<CalendarHeader>
<CalendarPrevButton />
<CalendarHeading />
<CalendarNextButton />
</CalendarHeader>
<div class="flex flex-col gap-y-4 mt-4 sm:flex-row sm:gap-x-4 sm:gap-y-0">
<CalendarGrid v-for="month in grid" :key="month.value.toString()">
<CalendarGridHead>
<CalendarGridRow>
<CalendarHeadCell
v-for="day in weekDays" :key="day"
>
{{ day }}
</CalendarHeadCell>
</CalendarGridRow>
</CalendarGridHead>
<CalendarGridBody>
<CalendarGridRow v-for="(weekDates, index) in month.rows" :key="`weekDate-${index}`" class="mt-2 w-full">
<CalendarCell
v-for="weekDate in weekDates"
:key="weekDate.toString()"
:date="weekDate"
>
<CalendarCellTrigger
:day="weekDate"
:month="month.value"
/>
</CalendarCell>
</CalendarGridRow>
</CalendarGridBody>
</CalendarGrid>
</div>
</CalendarRoot>
</template>
+24
View File
@@ -0,0 +1,24 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarCell, type CalendarCellProps, useForwardProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<CalendarCellProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarCell
:class="cn('relative h-9 w-9 p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([data-selected])]:rounded-md [&:has([data-selected])]:bg-accent [&:has([data-selected][data-outside-month])]:bg-accent/50', props.class)"
v-bind="forwardedProps"
>
<slot />
</CalendarCell>
</template>
@@ -0,0 +1,38 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarCellTrigger, type CalendarCellTriggerProps, useForwardProps } from 'radix-vue'
import { buttonVariants } from '@/components/ui/button'
import { cn } from '@/utils'
const props = defineProps<CalendarCellTriggerProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarCellTrigger
:class="cn(
buttonVariants({ variant: 'ghost' }),
'h-9 w-9 p-0 font-normal',
'[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground',
// Selected
'data-[selected]:bg-primary data-[selected]:text-primary-foreground data-[selected]:opacity-100 data-[selected]:hover:bg-primary data-[selected]:hover:text-primary-foreground data-[selected]:focus:bg-primary data-[selected]:focus:text-primary-foreground',
// Disabled
'data-[disabled]:text-muted-foreground data-[disabled]:opacity-50',
// Unavailable
'data-[unavailable]:text-destructive-foreground data-[unavailable]:line-through',
// Outside months
'data-[outside-month]:pointer-events-none data-[outside-month]:text-muted-foreground data-[outside-month]:opacity-50 [&[data-outside-month][data-selected]]:bg-accent/50 [&[data-outside-month][data-selected]]:text-muted-foreground [&[data-outside-month][data-selected]]:opacity-30',
props.class,
)"
v-bind="forwardedProps"
>
<slot />
</CalendarCellTrigger>
</template>
+24
View File
@@ -0,0 +1,24 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarGrid, type CalendarGridProps, useForwardProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<CalendarGridProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarGrid
:class="cn('w-full border-collapse space-y-1', props.class)"
v-bind="forwardedProps"
>
<slot />
</CalendarGrid>
</template>
@@ -0,0 +1,11 @@
<script lang="ts" setup>
import { CalendarGridBody, type CalendarGridBodyProps } from 'radix-vue'
const props = defineProps<CalendarGridBodyProps>()
</script>
<template>
<CalendarGridBody v-bind="props">
<slot />
</CalendarGridBody>
</template>
@@ -0,0 +1,11 @@
<script lang="ts" setup>
import { CalendarGridHead, type CalendarGridHeadProps } from 'radix-vue'
const props = defineProps<CalendarGridHeadProps>()
</script>
<template>
<CalendarGridHead v-bind="props">
<slot />
</CalendarGridHead>
</template>
@@ -0,0 +1,21 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarGridRow, type CalendarGridRowProps, useForwardProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<CalendarGridRowProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarGridRow :class="cn('flex', props.class)" v-bind="forwardedProps">
<slot />
</CalendarGridRow>
</template>
@@ -0,0 +1,21 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarHeadCell, type CalendarHeadCellProps, useForwardProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<CalendarHeadCellProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarHeadCell :class="cn('w-9 rounded-md text-[0.8rem] font-normal text-muted-foreground', props.class)" v-bind="forwardedProps">
<slot />
</CalendarHeadCell>
</template>
+21
View File
@@ -0,0 +1,21 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarHeader, type CalendarHeaderProps, useForwardProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<CalendarHeaderProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarHeader :class="cn('relative flex w-full items-center justify-between pt-1', props.class)" v-bind="forwardedProps">
<slot />
</CalendarHeader>
</template>
@@ -0,0 +1,27 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarHeading, type CalendarHeadingProps, useForwardProps } from 'radix-vue'
import { cn } from '@/utils'
const props = defineProps<CalendarHeadingProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarHeading
v-slot="{ headingValue }"
:class="cn('text-sm font-medium', props.class)"
v-bind="forwardedProps"
>
<slot :heading-value>
{{ headingValue }}
</slot>
</CalendarHeading>
</template>
@@ -0,0 +1,32 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarNext, type CalendarNextProps, useForwardProps } from 'radix-vue'
import { ChevronRight } from 'lucide-vue-next'
import { cn } from '@/utils'
import { buttonVariants } from '@/components/ui/button'
const props = defineProps<CalendarNextProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarNext
:class="cn(
buttonVariants({ variant: 'outline' }),
'h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100',
props.class,
)"
v-bind="forwardedProps"
>
<slot>
<ChevronRight class="h-4 w-4" />
</slot>
</CalendarNext>
</template>
@@ -0,0 +1,32 @@
<script lang="ts" setup>
import { type HTMLAttributes, computed } from 'vue'
import { CalendarPrev, type CalendarPrevProps, useForwardProps } from 'radix-vue'
import { ChevronLeft } from 'lucide-vue-next'
import { cn } from '@/utils'
import { buttonVariants } from '@/components/ui/button'
const props = defineProps<CalendarPrevProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = computed(() => {
const { class: _, ...delegated } = props
return delegated
})
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<CalendarPrev
:class="cn(
buttonVariants({ variant: 'outline' }),
'h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100',
props.class,
)"
v-bind="forwardedProps"
>
<slot>
<ChevronLeft class="h-4 w-4" />
</slot>
</CalendarPrev>
</template>
+12
View File
@@ -0,0 +1,12 @@
export { default as Calendar } from './Calendar.vue'
export { default as CalendarCell } from './CalendarCell.vue'
export { default as CalendarCellTrigger } from './CalendarCellTrigger.vue'
export { default as CalendarGrid } from './CalendarGrid.vue'
export { default as CalendarGridBody } from './CalendarGridBody.vue'
export { default as CalendarGridHead } from './CalendarGridHead.vue'
export { default as CalendarGridRow } from './CalendarGridRow.vue'
export { default as CalendarHeadCell } from './CalendarHeadCell.vue'
export { default as CalendarHeader } from './CalendarHeader.vue'
export { default as CalendarHeading } from './CalendarHeading.vue'
export { default as CalendarNextButton } from './CalendarNextButton.vue'
export { default as CalendarPrevButton } from './CalendarPrevButton.vue'
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div
:class="
cn(
'rounded-lg border bg-card text-card-foreground shadow-sm',
props.class,
)
"
>
<slot />
</div>
</template>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div :class="cn('p-6 pt-0', props.class)">
<slot />
</div>
</template>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<p :class="cn('text-sm text-muted-foreground', props.class)">
<slot />
</p>
</template>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div :class="cn('flex items-center p-6 pt-0', props.class)">
<slot />
</div>
</template>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div :class="cn('flex flex-col gap-y-1.5 p-6', props.class)">
<slot />
</div>
</template>
+18
View File
@@ -0,0 +1,18 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<h3
:class="
cn('text-2xl font-semibold leading-none tracking-tight', props.class)
"
>
<slot />
</h3>
</template>

Some files were not shown because too many files have changed in this diff Show More