feat(SPA): screen to manage API keys (PART 2/3)

This commit is contained in:
fsylvain committed 2026-10-05 00:05:12 +02:00
1 parent 844842fdae
commit 514a082c96
30 files changed
+3844 -83

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
<script setup lang="ts">
import { t } from '@/i18n'
import ApiKeyStatusBadge from '@/components/ApiKeyStatusBadge.vue'
import { API_KEY_SKELETON_ROWS, type ApiKey } from '@/composables/useApiKeys'
import {
creatorLabel,
displayPrefix,
expiresLabel,
formatKeyDate,
lastUsedLabel,
} from '@/lib/apiKeys'
defineProps<{
keys: ApiKey[]
loading: boolean
showCreatedBy: boolean
}>()
const emit = defineEmits<{ revoke: [key: ApiKey] }>()
function createdText(key: ApiKey, showCreatedBy: boolean) {
const date = formatKeyDate(key.created_at, '')
return showCreatedBy
? t('Created {0} by {1}', [date, creatorLabel(key)])
: t('Created {0}', [date])
}
function detailsText(key: ApiKey, showCreatedBy: boolean) {
return [
createdText(key, showCreatedBy),
t('Last used {0}', [lastUsedLabel(key)]),
t('Expires {0}', [expiresLabel(key)]),
].join(' · ')
}
</script>
<template>
<ul class="-mx-4 border-y border-default bg-default" :aria-busy="loading ? 'true' : undefined">
<template v-if="loading">
<li
v-for="n in API_KEY_SKELETON_ROWS"
:key="n"
class="flex flex-col gap-1.5 border-b border-default px-4 py-3"
>
<USkeleton class="h-3.5 w-[55%] rounded-none bg-accented" />
<USkeleton class="h-3 w-[40%] rounded-none bg-accented" />
</li>
</template>
<template v-else>
<li
v-for="key in keys"
:key="key.id"
data-testid="api-key-card"
class="flex flex-col gap-1.5 border-b border-default px-4 py-3"
:class="key.status === 'revoked' ? 'bg-muted' : 'bg-default'"
>
<div class="flex items-center gap-2">
<span
class="min-w-0 flex-1 truncate text-[0.9375rem]/5 font-medium"
:class="key.status === 'revoked' ? 'text-muted' : 'text-highlighted'"
>{{ key.name }}</span
>
<ApiKeyStatusBadge :status="key.status" />
</div>
<span
class="font-mono text-xs leading-[normal]"
:class="key.status === 'revoked' ? 'text-muted' : 'text-toned'"
>{{ displayPrefix(key.prefix) }}</span
>
<span :class="key.status === 'revoked' ? 'text-muted' : 'text-toned'">{{
detailsText(key, showCreatedBy)
}}</span>
<UButton
v-if="key.status !== 'revoked'"
color="neutral"
variant="outline"
class="h-11 self-start border border-accented bg-default px-3.5 text-sm font-medium text-highlighted ring-0"
@click="emit('revoke', key)"
>
{{ t('Revoke') }}
</UButton>
</li>
</template>
</ul>
</template>
+117
View File
@@ -0,0 +1,117 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, nextTick, ref, watch } from 'vue'
import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
const props = defineProps<{
name: string
apiKey: string
}>()
const open = defineModel<boolean>('open', { default: false })
const emit = defineEmits<{ done: [] }>()
const { copied, copy } = useCopyToClipboard()
const copyButton = ref<{ $el: HTMLElement } | null>(null)
const description = computed(() =>
t('"{0}" is ready. Copy the key and store it somewhere safe.', [props.name]),
)
const copyLabel = computed(() => (copied.value ? t('Copied') : t('Copy')))
const copyIcon = computed(() => (copied.value ? 'i-lucide-check' : 'i-lucide-copy'))
watch(
open,
async (isOpen) => {
if (!isOpen) {
return
}
await nextTick()
await nextTick()
copyButton.value?.$el?.focus()
},
{ immediate: true },
)
function onOpenChange(isOpen: boolean) {
if (!isOpen) {
emit('done')
}
}
function keepOpenOnOutsideInteraction(event: Event) {
event.preventDefault()
}
</script>
<template>
<UModal
:open="open"
:title="t('Your new API key')"
:description="description"
:close="false"
:content="{
onPointerDownOutside: keepOpenOnOutsideInteraction,
onInteractOutside: keepOpenOnOutsideInteraction,
}"
:ui="{
content:
'divide-y-0 border border-default shadow-(--shadow-modal) ring-0 sm:top-30 sm:max-w-120 sm:translate-y-0 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!left-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0',
header: 'min-h-0 px-5 pt-5 pb-0 sm:px-5',
title: 'text-[1.125rem]/6.5 font-semibold',
description: 'mt-1 text-base/5.5 text-toned text-pretty',
body: 'px-5 pt-3.5 pb-0 sm:px-5 sm:pt-3.5 sm:pb-0',
footer: 'px-5 pt-3.5 pb-5 sm:px-5',
}"
@update:open="onOpenChange"
>
<template #body>
<div class="flex flex-col gap-3.5">
<UAlert
role="alert"
color="warning"
variant="soft"
:close="false"
icon="i-lucide-triangle-alert"
:title="t('You won\'t be able to see this key again.')"
:ui="{ root: 'gap-2.5 px-3 py-2.5', title: 'text-sm font-medium' }"
/>
<div class="flex flex-col border border-accented bg-elevated md:flex-row">
<span
class="min-w-0 flex-1 px-3 py-2.5 font-mono text-code/5 break-all text-highlighted"
>{{ apiKey }}</span
>
<UButton
ref="copyButton"
:icon="copyIcon"
color="neutral"
variant="ghost"
aria-live="polite"
class="h-11 justify-center gap-1.5 rounded-none border-t border-accented px-3.5 font-medium md:border-t-0 md:border-l"
:class="copied ? 'text-success' : 'text-highlighted'"
:ui="{ leadingIcon: 'size-3.5' }"
@click="copy(apiKey)"
>
{{ copyLabel }}
</UButton>
</div>
<span class="text-muted">{{
t('Closing this window discards the key from the screen. Copy it first.')
}}</span>
</div>
</template>
<template #footer>
<div class="flex w-full flex-col sm:flex-row sm:justify-end">
<UButton
block
class="h-11 justify-center sm:w-auto sm:px-3.5"
@click="emit('done')"
>
{{ t('Done') }}
</UButton>
</div>
</template>
</UModal>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import type { ApiKeyStatus } from '@/composables/useApiKeys'
const props = defineProps<{ status: ApiKeyStatus }>()
const badges = {
active: {
get label() {
return t('active')
},
color: 'success',
class: 'bg-(--rc-success-soft) text-success',
},
expired: {
get label() {
return t('expired')
},
color: 'warning',
class: 'bg-(--rc-warning-soft) text-warning',
},
revoked: {
get label() {
return t('revoked')
},
color: 'neutral',
class: 'bg-elevated text-muted',
},
} as const
const badge = computed(() => badges[props.status])
</script>
<template>
<UBadge
:color="badge.color"
variant="soft"
:class="badge.class"
:ui="{ base: 'h-5 px-1.5 py-0 text-xs' }"
>
{{ badge.label }}
</UBadge>
</template>
+190
View File
@@ -0,0 +1,190 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import ApiKeyStatusBadge from '@/components/ApiKeyStatusBadge.vue'
import { API_KEY_SKELETON_ROWS, type ApiKey } from '@/composables/useApiKeys'
import {
creatorLabel,
displayPrefix,
expiresLabel,
formatKeyDate,
lastUsedLabel,
} from '@/lib/apiKeys'
const props = defineProps<{
keys: ApiKey[]
loading: boolean
showCreatedBy: boolean
}>()
const emit = defineEmits<{ revoke: [key: ApiKey] }>()
type Row = ApiKey | { skeleton: true; id: number }
const skeletonRows: Row[] = Array.from({ length: API_KEY_SKELETON_ROWS }, (_, index) => ({
skeleton: true,
id: index,
}))
const data = computed<Row[]>(() => (props.loading ? skeletonRows : props.keys))
function fixed(width: string) {
return { meta: { class: { th: width, td: width } } }
}
const columns = computed(() => [
{
id: 'name',
get header() {
return t('Name')
},
},
{
id: 'prefix',
get header() {
return t('Key')
},
...fixed('w-30.5'),
},
{
id: 'status',
get header() {
return t('Status')
},
...fixed('w-22'),
},
...(props.showCreatedBy
? [
{
id: 'created_by',
get header() {
return t('Created by')
},
...fixed('w-54.75'),
},
]
: []),
{
id: 'created_at',
get header() {
return t('Created')
},
...fixed('w-28'),
},
{
id: 'last_used_at',
get header() {
return t('Last used')
},
...fixed('w-28'),
},
{
id: 'expires_at',
get header() {
return t('Expires')
},
...fixed('w-28'),
},
{ id: 'actions', header: '', ...fixed('w-24.5') },
])
const meta = {
class: {
tr: (row: { original: Row }) => {
const original = row.original
return 'skeleton' in original || original.status !== 'revoked' ? '' : 'bg-muted'
},
},
}
function key(row: { original: Row }) {
return row.original as ApiKey
}
function isSkeleton(row: { original: Row }) {
return 'skeleton' in row.original
}
function isRevoked(row: { original: Row }) {
return !isSkeleton(row) && key(row).status === 'revoked'
}
function mutedClass(row: { original: Row }) {
return isRevoked(row) ? 'text-muted' : 'text-toned'
}
</script>
<template>
<div class="border border-default bg-default" :aria-busy="loading ? 'true' : undefined">
<span v-if="loading" role="status" class="sr-only">{{ t('Loading API keys') }}</span>
<UTable
:data="data"
:columns="columns"
:meta="meta"
:ui="{
base: 'table-fixed',
thead: 'bg-elevated [&>tr]:border-t-0',
separator: 'hidden',
th: 'h-9 px-1.5 py-0 first:pl-3 last:pr-3',
td: 'h-12 px-1.5 py-0 first:pl-3 last:pr-3',
tbody: 'divide-y-0',
tr: 'border-t border-default',
}"
>
<template #name-cell="{ row }">
<USkeleton v-if="isSkeleton(row)" class="h-3 w-[60%] rounded-none bg-accented" />
<span
v-else
class="block truncate font-medium"
:class="isRevoked(row) ? 'text-muted' : 'text-highlighted'"
>{{ key(row).name }}</span
>
</template>
<template #prefix-cell="{ row }">
<USkeleton v-if="isSkeleton(row)" class="h-3 w-[70%] rounded-none bg-accented" />
<span v-else class="font-mono text-xs" :class="mutedClass(row)">{{
displayPrefix(key(row).prefix)
}}</span>
</template>
<template #status-cell="{ row }">
<USkeleton v-if="isSkeleton(row)" class="h-5 w-14 rounded-none bg-accented" />
<ApiKeyStatusBadge v-else :status="key(row).status" />
</template>
<template #created_by-cell="{ row }">
<USkeleton v-if="isSkeleton(row)" class="h-3 w-[60%] rounded-none bg-accented" />
<span v-else class="block truncate" :class="mutedClass(row)">{{
creatorLabel(key(row))
}}</span>
</template>
<template #created_at-cell="{ row }">
<span v-if="!isSkeleton(row)" :class="mutedClass(row)">{{
formatKeyDate(key(row).created_at, '')
}}</span>
</template>
<template #last_used_at-cell="{ row }">
<span v-if="!isSkeleton(row)" :class="mutedClass(row)">{{
lastUsedLabel(key(row))
}}</span>
</template>
<template #expires_at-cell="{ row }">
<span v-if="!isSkeleton(row)" :class="mutedClass(row)">{{
expiresLabel(key(row))
}}</span>
</template>
<template #actions-cell="{ row }">
<span v-if="!isSkeleton(row) && !isRevoked(row)" class="flex justify-end">
<UButton
color="neutral"
variant="outline"
size="xs"
class="h-7 border border-accented bg-default px-2.5 text-xs font-medium text-highlighted ring-0"
@click="emit('revoke', key(row))"
>
{{ t('Revoke') }}
</UButton>
</span>
</template>
</UTable>
</div>
</template>
+9 -1
View File
@@ -80,6 +80,13 @@ async function onConfirm() {
}
}
function onOpenChange(value: boolean) {
if (!value && pending.value) {
return
}
open.value = value
}
function onCancel() {
if (pending.value) {
return
@@ -90,10 +97,11 @@ function onCancel() {
<template>
<UModal
v-model:open="open"
:open="open"
:title="title"
:description="description"
:dismissible="!pending"
@update:open="onOpenChange"
:close="false"
:content="{
role: 'alertdialog',
+272
View File
@@ -0,0 +1,272 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, nextTick, ref, watch } from 'vue'
import CharacterCounter from '@/components/CharacterCounter.vue'
import { ApiError, NetworkError } from '@/composables/useApi'
import { useApiKeys, type CreateApiKeyInput, type CreatedApiKey } from '@/composables/useApiKeys'
import { expiryInstant, isFutureExpiry } from '@/lib/apiKeys'
const NAME_MAX_LENGTH = 60
const fieldUi = { help: 'mt-1.5 text-sm/5 text-muted', error: 'mt-1.5 text-sm/5' }
const OPTIONAL_SUFFIX = /\s*\([^)]*\)$/
const open = defineModel<boolean>('open', { default: false })
const emit = defineEmits<{ created: [created: CreatedApiKey] }>()
const { createApiKey } = useApiKeys()
const name = ref('')
const expiry = ref('')
const submitted = ref(false)
const focused = ref(false)
const submitting = ref(false)
const formAlert = ref<'' | 'invalid' | 'rateLimited' | 'failed' | 'network'>('')
const nameLength = computed(() => [...name.value].length)
const trimmedName = computed(() => name.value.trim())
const nameError = computed(() => {
if (nameLength.value > NAME_MAX_LENGTH) {
return t('Use 60 characters or fewer.')
}
if (submitted.value && !trimmedName.value) {
return t('Enter a name.')
}
return ''
})
const expiryError = computed(() =>
submitted.value && expiry.value && !isFutureExpiry(expiry.value)
? t('Choose a date in the future.')
: '',
)
const expiryLabel = computed(() => t('Expiry date (optional)').replace(OPTIONAL_SUFFIX, ''))
const expiryOptional = computed(
() => OPTIONAL_SUFFIX.exec(t('Expiry date (optional)'))?.[0].trim() ?? '',
)
const alertMessage = computed(() => {
switch (formAlert.value) {
case 'invalid':
return t("Something in the form isn't valid. Check the highlighted fields.")
case 'rateLimited':
return t('Too many requests. Wait a moment, then try again.')
case 'network':
return t("Couldn't reach RenewCMS. Check your connection and try again.")
case 'failed':
return t("Couldn't create the key. Try again in a moment.")
default:
return ''
}
})
function resetForm() {
name.value = ''
expiry.value = ''
submitted.value = false
focused.value = false
submitting.value = false
formAlert.value = ''
}
async function focusNameField() {
await nextTick()
await nextTick()
document.querySelector<HTMLInputElement>('input[name="name"]')?.focus()
focused.value = true
}
watch(
open,
(isOpen) => {
if (!isOpen) {
return
}
resetForm()
focusNameField()
},
{ immediate: true },
)
function showFailure(error: unknown) {
if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
return
}
if (error instanceof ApiError && error.status === 400) {
formAlert.value = 'invalid'
} else if (error instanceof ApiError && error.status === 429) {
formAlert.value = 'rateLimited'
} else if (error instanceof NetworkError) {
formAlert.value = 'network'
} else {
formAlert.value = 'failed'
}
}
async function onSubmit() {
if (submitting.value) {
return
}
submitted.value = true
focused.value = false
if (!trimmedName.value || nameLength.value > NAME_MAX_LENGTH || expiryError.value) {
return
}
const input: CreateApiKeyInput = { name: trimmedName.value }
if (expiry.value) {
input.expires_at = expiryInstant(expiry.value)
}
formAlert.value = ''
submitting.value = true
try {
const created = await createApiKey(input)
emit('created', created)
open.value = false
resetForm()
} catch (error) {
showFailure(error)
} finally {
submitting.value = false
}
}
function onCancel() {
if (submitting.value) {
return
}
open.value = false
}
function onOpenChange(isOpen: boolean) {
if (!isOpen && submitting.value) {
return
}
open.value = isOpen
}
function keepOpenOnOutsideInteraction(event: Event) {
event.preventDefault()
}
</script>
<template>
<UModal
:open="open"
:title="t('Create API key')"
:description="t('The key acts as you, with your role. It is shown in full once.')"
:dismissible="!submitting"
:close="false"
:content="{
onPointerDownOutside: keepOpenOnOutsideInteraction,
onInteractOutside: keepOpenOnOutsideInteraction,
}"
:ui="{
content:
'divide-y-0 border border-default shadow-(--shadow-modal) ring-0 sm:top-30 sm:max-w-120 sm:translate-y-0 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!left-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0',
header: 'min-h-0 px-5 pt-5 pb-0 sm:px-5',
title: 'text-[1.125rem]/6.5 font-semibold',
description: 'mt-1 text-base/5.5 text-toned text-pretty',
body: 'px-5 pt-3.5 pb-0 sm:px-5 sm:pt-3.5 sm:pb-0',
footer: 'px-5 pt-3.5 pb-5 sm:px-5',
}"
@update:open="onOpenChange"
>
<template #body>
<div class="flex flex-col gap-3.5">
<UAlert
v-if="alertMessage"
role="alert"
color="error"
variant="soft"
:close="false"
icon="i-lucide-circle-x"
:ui="{ root: 'gap-2 px-3 py-2.5' }"
:description="alertMessage"
/>
<UForm :state="{ name, expiry }" class="flex flex-col gap-3.5" @submit="onSubmit">
<UFormField
:label="t('Name')"
name="name"
:error="nameError || undefined"
:help="t('Required. Up to 60 characters.')"
:ui="fieldUi"
>
<template #hint>
<CharacterCounter
:value="nameLength"
:max="NAME_MAX_LENGTH"
variant="field"
/>
</template>
<UInput
v-model="name"
name="name"
autocomplete="off"
:disabled="submitting"
color="primary"
:highlight="focused || !!nameError"
:ui="{ base: 'h-10' }"
class="w-full"
@focus="focused = true"
@blur="focused = false"
/>
</UFormField>
<UFormField
name="expires_at"
:ui="fieldUi"
:error="expiryError || undefined"
:help="
t(
'Optional. Must be in the future. Leave it empty for a key that does not expire.',
)
"
>
<template #label>
{{ expiryLabel }}
<span v-if="expiryOptional" class="font-normal text-muted">{{
expiryOptional
}}</span>
</template>
<UInput
v-model="expiry"
type="date"
name="expires_at"
:disabled="submitting"
color="primary"
:highlight="!!expiryError"
:ui="{ base: 'h-10' }"
class="w-full"
/>
</UFormField>
</UForm>
</div>
</template>
<template #footer>
<div class="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<UButton
color="neutral"
variant="outline"
block
class="h-11 justify-center border border-accented bg-default text-highlighted ring-0 sm:w-auto sm:px-3.5"
:disabled="submitting"
@click="onCancel"
>
{{ t('Cancel') }}
</UButton>
<UButton
block
class="h-11 justify-center sm:w-auto sm:px-3.5"
:loading="submitting"
:disabled="submitting"
@click="onSubmit"
>
{{ submitting ? t('Creating…') : t('Create key') }}
</UButton>
</div>
</template>
</UModal>
</template>
+21 -1
View File
@@ -18,6 +18,9 @@ import UserMenu from '@/components/UserMenu.vue'
const props = withDefaults(
defineProps<{
mobileTitle?: string
backTo?: string
backLabel?: string
stickyFooter?: boolean
fullBleed?: boolean
compactPadding?: boolean
renderWhileChecking?: boolean
@@ -26,6 +29,9 @@ const props = withDefaults(
}>(),
{
mobileTitle: undefined,
backTo: undefined,
backLabel: undefined,
stickyFooter: false,
offlineMessage: undefined,
offlineIcon: undefined,
fullBleed: false,
@@ -36,11 +42,15 @@ const props = withDefaults(
const COMPACT_BODY = 'gap-0 px-4 pt-4 pb-22 sm:gap-0 sm:px-4 sm:pt-4 sm:pb-22 lg:p-6'
const DEFAULT_BODY = 'gap-0 px-4 pt-5 pb-22 sm:gap-0 sm:px-4 sm:pt-5 sm:pb-22 lg:p-8'
const STICKY_FOOTER_BODY = 'gap-0 px-4 pt-5 pb-0 sm:gap-0 sm:px-4 sm:pt-5 sm:pb-0 lg:p-8'
const bodyUi = computed(() => {
if (props.fullBleed) {
return 'gap-0 p-0 sm:gap-0 sm:p-0 lg:p-0'
}
if (props.stickyFooter) {
return STICKY_FOOTER_BODY
}
return props.compactPadding ? COMPACT_BODY : DEFAULT_BODY
})
@@ -229,7 +239,17 @@ async function onLogout() {
}"
>
<template #toggle>
<span class="relative lg:hidden">
<UButton
v-if="backTo"
:to="backTo"
icon="i-lucide-arrow-left"
color="neutral"
variant="ghost"
class="size-11 justify-center lg:hidden"
:ui="{ leadingIcon: 'size-5' }"
:aria-label="backLabel"
/>
<span v-else class="relative lg:hidden">
<UDashboardSidebarToggle
data-slot="toggle"
color="neutral"