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>