Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

refactor: unify Cloud management and shared Site gallery experience

Timothy Yin83b2633f6d1f
diff --git a/apps/cloud/app/app.vue b/apps/cloud/app/app.vue
index a3be40ca..1fc5b4d9 100644
--- a/apps/cloud/app/app.vue
+++ b/apps/cloud/app/app.vue
@@ -1,5 +1,8 @@
+<script setup lang="ts">
+useHead({ bodyAttrs: { class: 'cf-cloud-body' } })
+</script>
<template>
- <div class="cf-root">
+ <UApp class="cf-root">
<a
href="#main-content"
class="cf-skip-link"
@@ -7,5 +10,5 @@
><NuxtLoadingIndicator color="var(--cf-primary)" /><NuxtLayout
><NuxtPage
/></NuxtLayout>
- </div>
+ </UApp>
</template>
diff --git a/apps/cloud/app/assets/cloud.css b/apps/cloud/app/assets/cloud.css
index 594bce79..b8670736 100644
--- a/apps/cloud/app/assets/cloud.css
+++ b/apps/cloud/app/assets/cloud.css
@@ -1,4 +1,5 @@
/* ChronoFrame Cloud tokens. Scoped to this entry: shared editions retain their theme. */
+.cf-cloud-body,
.cf-root,
.cf-error {
--background: #f7f7f2;
@@ -27,6 +28,7 @@
line-height: 1.6;
-webkit-font-smoothing: antialiased;
}
+.dark .cf-cloud-body,
.dark .cf-root,
.dark .cf-error {
--background: #171d18;
@@ -1747,3 +1749,655 @@
margin-left: 0;
}
}
+
+/* One persistent shell: workspace and site navigation share a wider sidebar. */
+.cf-portal-grid {
+ grid-template-columns: 260px minmax(0, 1fr);
+}
+.cf-sidebar {
+ padding: 18px 12px 12px;
+ overflow: hidden;
+}
+.cf-sidebar-viewport {
+ position: relative;
+ flex: 1;
+ min-height: 200px;
+ overflow: hidden;
+}
+.cf-sidebar-panel {
+ width: 100%;
+}
+.cf-sidebar-panel nav {
+ display: grid;
+ gap: 4px;
+}
+.cf-sidebar-panel nav a,
+.cf-sidebar-back {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 9px 12px;
+ min-height: 38px;
+ border-radius: 7px;
+ font-size: 13px;
+ color: var(--muted-foreground);
+}
+.cf-sidebar-panel nav a:hover,
+.cf-sidebar-back:hover {
+ background: var(--secondary);
+ color: var(--foreground);
+}
+.cf-sidebar-panel nav a.active {
+ background: var(--secondary);
+ color: var(--primary);
+ box-shadow: inset 0 0 0 1px var(--border);
+}
+.cf-sidebar-back {
+ margin-bottom: 14px;
+ font-size: 12px;
+}
+.cf-sidebar-site {
+ display: flex;
+ gap: 10px;
+ padding: 0 10px 22px;
+ align-items: center;
+ min-width: 0;
+}
+.cf-sidebar-site > div {
+ min-width: 0;
+}
+.cf-sidebar-site strong,
+.cf-sidebar-site span:not(.cf-site-icon) {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.cf-sidebar-site strong {
+ font-size: 13px;
+ font-weight: 600;
+}
+.cf-sidebar-site > div > span {
+ font-size: 11px;
+ color: var(--muted-foreground);
+ margin-top: 2px;
+}
+.cf-sidebar-bottom {
+ display: block;
+ padding: 12px 0 0;
+ margin-top: auto;
+ border-top: 1px solid var(--border);
+}
+.cf-user-trigger {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ min-width: 0;
+ gap: 9px;
+ padding: 10px 8px;
+ text-align: left;
+ border-radius: 8px;
+ cursor: pointer;
+}
+.cf-user-trigger:hover,
+.cf-user-trigger[data-state='open'] {
+ background: var(--secondary);
+}
+.cf-user-trigger > svg {
+ flex-shrink: 0;
+ color: var(--muted-foreground);
+}
+.cf-user-avatar {
+ flex: 0 0 32px;
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--secondary);
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--primary);
+}
+.cf-user-identity {
+ flex: 1;
+ min-width: 0;
+ display: grid;
+ gap: 2px;
+}
+.cf-user-identity strong {
+ font-size: 12px;
+ color: var(--foreground);
+ font-weight: 550;
+}
+.cf-user-identity span {
+ font-size: 10px;
+ color: var(--muted-foreground);
+}
+.cf-user-identity > * {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.cf-account-menu {
+ z-index: 120;
+ width: 248px;
+ max-width: calc(100vw - 24px);
+ padding: 5px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ background: var(--card);
+ box-shadow: 0 12px 32px #111c1620;
+ font-size: 12px;
+}
+.cf-account-menu-label {
+ display: grid;
+ gap: 3px;
+ padding: 9px;
+}
+.cf-account-menu-label > * {
+ overflow-wrap: anywhere;
+}
+.cf-account-menu-label span {
+ color: var(--muted-foreground);
+ font-size: 11px;
+}
+.cf-account-menu [role='menuitem'] {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 9px;
+ border-radius: 5px;
+ cursor: pointer;
+ outline: none;
+}
+.cf-account-menu [role='menuitem'][data-highlighted] {
+ background: var(--secondary);
+}
+.cf-menu-separator {
+ height: 1px;
+ margin: 4px 0;
+ background: var(--border);
+}
+.cf-sidebar-toggle {
+ display: none;
+}
+.cf-sidebar-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 60;
+ background: #10191066;
+ backdrop-filter: blur(3px);
+}
+.cf-sidebar-drawer {
+ position: fixed;
+ inset: 0 auto 0 0;
+ z-index: 70;
+ width: min(290px, calc(100vw - 36px));
+ display: flex;
+ flex-direction: column;
+ padding: 14px 12px;
+ background: var(--background);
+ color: var(--foreground);
+ border-right: 1px solid var(--border);
+}
+.cf-drawer-heading {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ font-weight: 600;
+ margin-bottom: 16px;
+}
+.cf-portal-content {
+ max-width: 1320px;
+}
+.cf-portal-main {
+ padding: 26px 30px 40px;
+}
+.cf-account-page {
+ max-width: 980px;
+ margin-inline: auto;
+}
+.cf-account-page #security {
+ margin-top: 38px;
+ scroll-margin-top: 84px;
+}
+.cf-section-title {
+ font-size: 15px;
+ font-weight: 600;
+ margin-bottom: 14px;
+}
+.cf-nav-forward-enter-active,
+.cf-nav-forward-leave-active,
+.cf-nav-back-enter-active,
+.cf-nav-back-leave-active {
+ transition:
+ transform 220ms cubic-bezier(0.22, 0.68, 0.3, 1),
+ opacity 180ms ease;
+}
+.cf-nav-forward-leave-active,
+.cf-nav-back-leave-active {
+ position: absolute;
+ inset: 0;
+}
+.cf-nav-forward-enter-from,
+.cf-nav-back-leave-to {
+ transform: translateX(100%);
+ opacity: 0;
+}
+.cf-nav-forward-leave-to,
+.cf-nav-back-enter-from {
+ transform: translateX(-100%);
+ opacity: 0;
+}
+@media (max-width: 899px) {
+ .cf-portal-grid {
+ display: block;
+ }
+ .cf-sidebar {
+ display: none;
+ }
+ .cf-sidebar-toggle {
+ display: inline-flex;
+ }
+ .cf-portal-header {
+ height: 56px;
+ padding: 0 14px;
+ gap: 8px;
+ }
+ .cf-portal-brand {
+ gap: 7px;
+ }
+ .cf-portal-main {
+ padding: 22px 16px 32px;
+ }
+ .cf-sidebar-drawer .cf-sidebar-bottom {
+ display: block;
+ }
+ .cf-sidebar-drawer .cf-sidebar-panel nav {
+ display: grid;
+ }
+ .cf-preview-badge {
+ display: none;
+ }
+ .cf-portal .cf-brand {
+ font-size: 15px;
+ gap: 6px;
+ }
+ .cf-portal .cf-brand-edition {
+ font-size: 11px;
+ margin-inline-start: 3px;
+ }
+ .cf-portal-header .cf-button-icon {
+ width: 32px;
+ height: 36px;
+ min-height: 36px;
+ padding: 0;
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .cf-sidebar-viewport *,
+ .cf-sidebar-viewport {
+ transition: none !important;
+ animation: none !important;
+ }
+}
+
+/* Management surfaces use the same table, metadata forms and viewer primitives as the console. */
+.cf-site-page-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 14px;
+ padding-bottom: 22px;
+ margin-bottom: 24px;
+ border-bottom: 1px solid var(--border);
+}
+.cf-site-heading {
+ min-width: 0;
+}
+.cf-site-heading h1 {
+ font-size: 22px;
+ line-height: 1.3;
+ font-weight: 600;
+ overflow-wrap: anywhere;
+}
+.cf-site-publication {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 8px;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.cf-site-page-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+}
+.cf-draft-hint {
+ width: 100%;
+ font-size: 12px;
+ color: var(--muted-foreground);
+}
+.cf-site-settings-stack {
+ display: grid;
+ gap: 22px;
+ max-width: 980px;
+}
+.cf-library {
+ min-width: 0;
+}
+.cf-library-heading {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ margin-bottom: 20px;
+}
+.cf-library-heading h2 {
+ font-size: 17px;
+ font-weight: 600;
+}
+.cf-library-heading p {
+ color: var(--muted-foreground);
+ font-size: 12px;
+ margin-top: 4px;
+}
+.cf-library-toolbar {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 12px;
+}
+.cf-library-search {
+ width: 260px;
+ max-width: 100%;
+}
+.cf-library-table {
+ overflow-x: auto;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ background: var(--card);
+}
+.cf-library-table table {
+ font-size: 12px;
+}
+.cf-library-thumb {
+ display: flex;
+ width: 52px;
+ height: 44px;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ border-radius: 5px;
+ background: var(--secondary);
+}
+.cf-library-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.cf-photo-title {
+ text-align: left;
+ max-width: 240px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-weight: 500;
+ cursor: pointer;
+}
+.cf-photo-dimensions,
+.cf-table-description {
+ font-size: 11px;
+ color: var(--muted-foreground);
+ max-width: 240px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.cf-tag-list {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+}
+.cf-live-label {
+ display: block;
+ font-size: 10px;
+ color: var(--muted-foreground);
+}
+.cf-library-empty {
+ padding: 42px 18px;
+ display: grid;
+ justify-items: center;
+ gap: 10px;
+ text-align: center;
+ color: var(--muted-foreground);
+}
+.cf-library-empty h3 {
+ color: var(--foreground);
+ font-size: 14px;
+ font-weight: 500;
+}
+.cf-selection-bar {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+ padding: 10px 12px;
+ margin-bottom: 10px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--secondary);
+ font-size: 12px;
+}
+.cf-processing-panel {
+ margin-top: 20px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 14px;
+}
+.cf-processing-row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 0;
+ font-size: 12px;
+}
+.cf-photo-preview {
+ width: 100%;
+ max-height: 70vh;
+ object-fit: contain;
+}
+.cf-preview-details {
+ display: flex;
+ gap: 12px;
+ font-size: 12px;
+ color: var(--muted-foreground);
+}
+.cf-selected-photo {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-top: 8px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 6px;
+}
+.cf-selected-photo > img {
+ width: 38px;
+ height: 38px;
+ object-fit: cover;
+ border-radius: 4px;
+}
+.cf-selected-photo > span {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+}
+.cf-photo-picker {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 12px;
+}
+.cf-picker-photo {
+ position: relative;
+ padding: 4px;
+ border: 2px solid transparent;
+ border-radius: 8px;
+ text-align: left;
+}
+.cf-picker-photo.selected {
+ border-color: var(--ui-primary);
+ background: var(--ui-bg-elevated);
+}
+.cf-picker-photo img {
+ width: 100%;
+ height: 110px;
+ object-fit: cover;
+ border-radius: 4px;
+}
+.cf-picker-photo > span {
+ display: block;
+ font-size: 12px;
+ margin: 6px 2px 2px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.cf-picker-check {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ background: var(--ui-bg);
+ color: var(--ui-primary);
+ border-radius: 50%;
+}
+@media (max-width: 600px) {
+ .cf-site-page-header {
+ align-items: flex-start;
+ gap: 12px;
+ }
+ .cf-site-heading h1 {
+ font-size: 20px;
+ }
+ .cf-site-page-actions {
+ width: 100%;
+ }
+ .cf-library-heading {
+ align-items: flex-start;
+ }
+ .cf-library-search {
+ flex: 1;
+ min-width: 150px;
+ }
+ .cf-selected-photo {
+ gap: 2px;
+ }
+ .cf-selected-photo > img {
+ width: 30px;
+ height: 30px;
+ }
+}
+
+.cf-cloud-body {
+ --ui-primary: var(--primary);
+ --ui-bg: var(--background);
+ --ui-bg-elevated: var(--secondary);
+ --ui-bg-muted: var(--muted);
+ --ui-text: var(--foreground);
+ --ui-text-muted: var(--muted-foreground);
+ --ui-border: var(--border);
+}
+.cf-upload-dropzone {
+ width: 100%;
+ display: grid;
+ justify-items: center;
+ gap: 10px;
+ padding: 36px 16px;
+ border: 1px dashed var(--ui-border);
+ border-radius: 10px;
+ text-align: center;
+ background: var(--ui-bg-muted);
+ cursor: pointer;
+}
+.cf-upload-dropzone span {
+ font-size: 12px;
+ color: var(--ui-text-muted);
+}
+.cf-upload-dropzone:disabled {
+ opacity: 0.5;
+ cursor: default;
+}
+.cf-library-thumb {
+ position: relative;
+}
+.cf-library-thumb > div {
+ width: 100%;
+ height: 100%;
+}
+.cf-library-thumb .cf-live-label {
+ position: absolute;
+ bottom: 2px;
+ left: 3px;
+ padding: 0 2px;
+ border-radius: 2px;
+ color: #fff;
+ background: #0009;
+ font-size: 8px;
+}
+.cf-photo-dimensions {
+ display: block;
+ margin-top: 3px;
+}
+.cf-library-heading > button {
+ white-space: nowrap;
+ font-size: 12px;
+}
+.cf-selected-photo > div {
+ width: 38px;
+ height: 38px;
+ flex-shrink: 0;
+ border-radius: 4px;
+}
+.cf-picker-photo > div {
+ width: 100%;
+ height: 110px;
+ border-radius: 4px;
+}
+@media (max-width: 600px) {
+ .cf-library-toolbar .cf-library-search {
+ flex-basis: 100%;
+ width: 100%;
+ }
+}
+
+.cf-inline-picker {
+ margin-top: 18px;
+ padding: 14px;
+ border: 1px solid var(--ui-border);
+ border-radius: 8px;
+}
+.cf-inline-picker .cf-photo-picker {
+ grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
+ max-height: 320px;
+ overflow-y: auto;
+}
+
+.cf-photo-preview > .webgl-image-viewer {
+ height: min(65svh, 650px);
+}
+.cf-preview-details {
+ padding: 12px 16px;
+ flex-wrap: wrap;
+}
diff --git a/apps/cloud/app/components/CloudAlbumsManager.vue b/apps/cloud/app/components/CloudAlbumsManager.vue
new file mode 100644
index 00000000..29d79def
--- /dev/null
+++ b/apps/cloud/app/components/CloudAlbumsManager.vue
@@ -0,0 +1,597 @@
+<script setup lang="ts">
+import type { Album, Photo } from '@chronoframe/contracts/resources'
+import type { TableColumn } from '@nuxt/ui'
+const {
+ albums,
+ message,
+ failed,
+ photos,
+ admin,
+ busy,
+ loading,
+ api,
+ base,
+ action,
+ refreshMedia,
+} = useCloudSiteMedia()
+const toast = useToast()
+const search = ref(''),
+ editor = ref(false),
+ removeOpen = ref(false),
+ picker = ref(false),
+ saving = ref(false),
+ loaded = ref(false),
+ selected = ref<number | null>(null),
+ revision = ref(0),
+ hadPassword = ref(false),
+ generation = ref(0)
+const draft = reactive({
+ title: '',
+ description: '',
+ isHidden: false,
+ passwordEnabled: false,
+ password: '',
+ photoIds: [] as string[],
+ coverPhotoId: '',
+})
+const photoSearch = ref(''),
+ pickerPanel = ref<HTMLElement>()
+watch(picker, async (open) => {
+ if (open) {
+ await nextTick()
+ pickerPanel.value?.querySelector('input')?.focus()
+ } else document.getElementById('album-select-photographs')?.focus()
+})
+const rows = computed(() =>
+ albums.value.filter(
+ (a) =>
+ !search.value ||
+ [a.title, a.description]
+ .join(' ')
+ .toLowerCase()
+ .includes(search.value.toLowerCase()),
+ ),
+)
+const choices = computed(() =>
+ photos.value.filter(
+ (p) =>
+ !photoSearch.value ||
+ [p.title, ...(p.tags ?? [])]
+ .join(' ')
+ .toLowerCase()
+ .includes(photoSearch.value.toLowerCase()),
+ ),
+)
+const chosen = computed(() =>
+ draft.photoIds
+ .map((id) => photos.value.find((p) => p.id === id))
+ .filter((p): p is Photo => !!p),
+)
+const columns: TableColumn<Album & { photoIds: string[] }>[] = [
+ { id: 'cover', header: 'Cover' },
+ { accessorKey: 'title', header: 'Title' },
+ { accessorKey: 'description', header: 'Description' },
+ { id: 'count', header: 'Photographs' },
+ { id: 'visibility', header: 'Visibility' },
+ { id: 'actions', header: '' },
+]
+function cover(album: Album & { photoIds: string[] }) {
+ return photos.value.find(
+ (p) => p.id === (album.coverPhotoId || album.photoIds?.[0]),
+ )
+}
+function create() {
+ generation.value++
+ selected.value = null
+ revision.value = 0
+ hadPassword.value = false
+ Object.assign(draft, {
+ title: '',
+ description: '',
+ isHidden: false,
+ passwordEnabled: false,
+ password: '',
+ photoIds: [],
+ coverPhotoId: '',
+ })
+ loaded.value = true
+ editor.value = true
+}
+async function edit(album: Album) {
+ const request = ++generation.value
+ selected.value = album.id
+ loaded.value = false
+ editor.value = true
+ draft.password = ''
+ try {
+ const data = await api<{
+ album: Album & { photos: Photo[] }
+ revision: number
+ }>(base.value + '/albums/' + album.id + '/settings')
+ if (
+ request !== generation.value ||
+ selected.value !== album.id ||
+ !editor.value
+ )
+ return
+ revision.value = data.revision
+ hadPassword.value = !!data.album.hasPassword
+ Object.assign(draft, {
+ title: data.album.title,
+ description: data.album.description || '',
+ isHidden: !!data.album.isHidden,
+ passwordEnabled: !!data.album.hasPassword,
+ password: '',
+ photoIds: data.album.photos.map((p) => p.id),
+ coverPhotoId: data.album.coverPhotoId || '',
+ })
+ loaded.value = true
+ } catch {
+ if (request === generation.value)
+ toast.add({
+ title: 'Album could not be loaded. Please try again.',
+ color: 'error',
+ })
+ }
+}
+watch(editor, (open) => {
+ if (!open) {
+ generation.value++
+ picker.value = false
+ loaded.value = false
+ draft.password = ''
+ }
+})
+function toggle(id: string, value: boolean) {
+ if (value && !draft.photoIds.includes(id)) draft.photoIds.push(id)
+ if (!value) {
+ draft.photoIds = draft.photoIds.filter((v) => v !== id)
+ if (draft.coverPhotoId === id) draft.coverPhotoId = ''
+ }
+}
+function movePhoto(index: number, step: number) {
+ const next = index + step
+ if (next < 0 || next >= draft.photoIds.length) return
+ const copy = [...draft.photoIds]
+ ;[copy[index], copy[next]] = [copy[next]!, copy[index]!]
+ draft.photoIds = copy
+}
+async function save() {
+ if (!loaded.value || saving.value || !draft.title.trim()) return
+ if (draft.passwordEnabled && !hadPassword.value && !draft.password) {
+ toast.add({ title: 'Enter an album password.', color: 'error' })
+ return
+ }
+ if (
+ hadPassword.value &&
+ !draft.passwordEnabled &&
+ !window.confirm(
+ 'Remove password protection? Published photographs may become public.',
+ )
+ )
+ return
+ saving.value = true
+ try {
+ const ok = await action(async () => {
+ if (selected.value === null) {
+ const id = crypto.getRandomValues(new Uint32Array(1))[0] || 1
+ await api(base.value + '/albums', {
+ method: 'POST',
+ body: { id, title: draft.title, isHidden: true },
+ })
+ selected.value = id
+ revision.value = 1
+ }
+ const result = await api<{ revision: number }>(
+ base.value + '/albums/' + selected.value + '/settings',
+ {
+ method: 'PATCH',
+ body: {
+ revision: revision.value,
+ title: draft.title,
+ description: draft.description || null,
+ isHidden: draft.isHidden,
+ photoIds: draft.photoIds,
+ coverPhotoId: draft.coverPhotoId || null,
+ ...(draft.passwordEnabled
+ ? draft.password
+ ? { password: draft.password }
+ : {}
+ : hadPassword.value
+ ? { password: null }
+ : {}),
+ },
+ },
+ )
+ revision.value = result.revision
+ }, 'Album saved.')
+ if (ok) editor.value = false
+ } finally {
+ saving.value = false
+ }
+}
+function askDelete(album: Album) {
+ selected.value = album.id
+ removeOpen.value = true
+}
+async function remove() {
+ if (selected.value === null) return
+ const ok = await action(
+ () =>
+ api(base.value + '/albums/' + selected.value + '/delete', {
+ method: 'POST',
+ body: {},
+ }),
+ 'Album deleted. Photographs remain in your library.',
+ )
+ if (ok) removeOpen.value = false
+}
+async function moveAlbum(album: Album, step: number) {
+ const next = [...albums.value],
+ index = next.findIndex((a) => a.id === album.id),
+ target = index + step
+ if (target < 0 || target >= next.length) return
+ ;[next[index], next[target]] = [next[target]!, next[index]!]
+ await action(
+ () =>
+ api(base.value + '/albums/reorder', {
+ method: 'POST',
+ body: { albumIds: next.map((a) => a.id) },
+ }),
+ 'Album order updated.',
+ )
+}
+function menu(album: Album) {
+ return [
+ [
+ {
+ label: 'Edit album',
+ icon: 'i-lucide-pencil',
+ disabled: !admin.value,
+ onSelect: () => edit(album),
+ },
+ ],
+ [
+ {
+ label: 'Delete album',
+ icon: 'i-lucide-trash-2',
+ color: 'error' as const,
+ disabled: !admin.value,
+ onSelect: () => askDelete(album),
+ },
+ ],
+ ]
+}
+</script>
+<template>
+ <section
+ class="cf-library"
+ aria-labelledby="albums-heading"
+ >
+ <div class="cf-library-heading">
+ <div>
+ <h2 id="albums-heading">Albums</h2>
+ <p>Organize your photographs and choose how they are shared.</p>
+ </div>
+ <UButton
+ v-if="admin"
+ icon="i-lucide-plus"
+ @click="create"
+ >Create album</UButton
+ >
+ </div>
+ <div class="cf-library-toolbar">
+ <UInput
+ v-model="search"
+ icon="i-lucide-search"
+ placeholder="Search albums…"
+ aria-label="Search albums"
+ class="cf-library-search"
+ /><UButton
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-refresh-cw"
+ aria-label="Refresh albums"
+ :loading="loading"
+ @click="refreshMedia"
+ />
+ </div>
+ <div class="cf-library-table">
+ <ConsoleMediaTable
+ :data="rows"
+ :columns="columns"
+ :loading="loading && !albums.length"
+ ><template #cover-cell="{ row }"
+ ><button
+ class="cf-library-thumb"
+ :aria-label="`Edit ${row.original.title}`"
+ :disabled="!admin"
+ @click="edit(row.original)"
+ >
+ <ThumbImage
+ v-if="cover(row.original)"
+ :src="cover(row.original)?.thumbnailUrl || ''"
+ :alt="row.original.title"
+ /><UIcon
+ v-else
+ name="i-lucide-images"
+ class="size-5"
+ /></button></template
+ ><template #title-cell="{ row }"
+ ><button
+ class="cf-photo-title"
+ :disabled="!admin"
+ @click="edit(row.original)"
+ >
+ {{ row.original.title }}
+ </button></template
+ ><template #description-cell="{ row }"
+ ><p class="cf-table-description">
+ {{ row.original.description || '—' }}
+ </p></template
+ ><template #count-cell="{ row }"
+ ><UBadge
+ color="neutral"
+ variant="soft"
+ >{{ row.original.photoIds.length }}</UBadge
+ ></template
+ ><template #visibility-cell="{ row }"
+ ><UBadge
+ color="neutral"
+ variant="soft"
+ :icon="
+ row.original.isHidden
+ ? 'i-lucide-eye-off'
+ : row.original.hasPassword
+ ? 'i-lucide-lock'
+ : 'i-lucide-globe'
+ "
+ >{{
+ row.original.isHidden
+ ? 'Hidden'
+ : row.original.hasPassword
+ ? 'Password'
+ : 'Public'
+ }}</UBadge
+ ></template
+ ><template #actions-cell="{ row }"
+ ><div class="flex items-center gap-1">
+ <UButton
+ v-if="admin"
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-arrow-up"
+ size="xs"
+ :disabled="busy || albums[0]?.id === row.original.id"
+ :aria-label="`Move ${row.original.title} up`"
+ @click="moveAlbum(row.original, -1)"
+ /><UButton
+ v-if="admin"
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-arrow-down"
+ size="xs"
+ :disabled="busy || albums.at(-1)?.id === row.original.id"
+ :aria-label="`Move ${row.original.title} down`"
+ @click="moveAlbum(row.original, 1)"
+ /><UDropdownMenu :items="menu(row.original)"
+ ><UButton
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-ellipsis"
+ :aria-label="`Actions for ${row.original.title}`"
+ /></UDropdownMenu></div></template
+ ><template #empty
+ ><div class="cf-library-empty">
+ <UIcon
+ name="i-lucide-library-big"
+ class="size-8"
+ />
+ <h3>
+ {{ search ? 'No matching albums' : 'Make room for a collection' }}
+ </h3>
+ <p>Create an album to bring related photographs together.</p>
+ <UButton
+ v-if="admin && !albums.length"
+ variant="soft"
+ @click="create"
+ >Create album</UButton
+ >
+ </div></template
+ ></ConsoleMediaTable
+ >
+ </div>
+ <USlideover
+ v-model:open="editor"
+ :title="selected === null ? 'Create album' : 'Edit album'"
+ description="Choose the photographs, cover and access for this album."
+ :ui="{ footer: 'justify-end' }"
+ ><template #body
+ ><p
+ v-if="failed && message"
+ role="alert"
+ class="cf-notice cf-notice-error"
+ >
+ {{ message }}
+ </p>
+ <p
+ v-if="!loaded"
+ role="status"
+ >
+ Loading album…
+ </p>
+ <UForm
+ v-else
+ id="cloud-album-form"
+ :state="draft"
+ class="space-y-5"
+ @submit="save"
+ ><ConsoleAlbumDetailsFields
+ v-model:title="draft.title"
+ v-model:description="draft.description"
+ /><UCheckbox
+ v-model="draft.isHidden"
+ label="Hide album"
+ description="Hide this album and its photographs from public browsing."
+ /><UCheckbox
+ v-model="draft.passwordEnabled"
+ label="Password protection"
+ description="Visitors must unlock this album to view its photographs."
+ /><UFormField
+ v-if="draft.passwordEnabled"
+ label="Album password"
+ :hint="
+ hadPassword
+ ? 'Leave blank to keep the current password.'
+ : 'Use 8–256 characters.'
+ "
+ ><UInput
+ v-model="draft.password"
+ type="password"
+ autocomplete="new-password"
+ minlength="8"
+ maxlength="256"
+ class="w-full"
+ /></UFormField>
+ <div class="cf-album-photo-section">
+ <div class="flex items-center justify-between gap-3">
+ <h3>Photographs · {{ draft.photoIds.length }}</h3>
+ <UButton
+ color="neutral"
+ variant="outline"
+ icon="i-lucide-image-plus"
+ size="sm"
+ id="album-select-photographs"
+ @click="picker = !picker"
+ >Select photographs</UButton
+ >
+ </div>
+ <div
+ v-for="(photo, index) in chosen"
+ :key="photo.id"
+ class="cf-selected-photo"
+ >
+ <ThumbImage
+ :src="photo.thumbnailUrl || ''"
+ :alt="photo.title || 'Photograph'"
+ /><span>{{ photo.title }}</span
+ ><UButton
+ :color="draft.coverPhotoId === photo.id ? 'primary' : 'neutral'"
+ variant="ghost"
+ icon="i-lucide-star"
+ size="xs"
+ :aria-label="`Set ${photo.title} as cover`"
+ @click="draft.coverPhotoId = photo.id"
+ /><UButton
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-arrow-up"
+ size="xs"
+ :disabled="index === 0"
+ :aria-label="`Move ${photo.title} up`"
+ @click="movePhoto(index, -1)"
+ /><UButton
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-arrow-down"
+ size="xs"
+ :disabled="index === chosen.length - 1"
+ :aria-label="`Move ${photo.title} down`"
+ @click="movePhoto(index, 1)"
+ /><UButton
+ color="error"
+ variant="ghost"
+ icon="i-lucide-x"
+ size="xs"
+ :aria-label="`Remove ${photo.title} from album`"
+ @click="toggle(photo.id, false)"
+ />
+ </div>
+ <p
+ v-if="!draft.photoIds.length"
+ class="text-sm text-muted"
+ >
+ Choose photographs from your library.
+ </p>
+ </div></UForm
+ >
+ <div
+ v-if="picker"
+ ref="pickerPanel"
+ role="region"
+ aria-label="Select photographs"
+ class="cf-inline-picker"
+ @keydown.esc.stop.prevent="picker = false"
+ >
+ <h3 class="font-medium mb-3">Select photographs</h3>
+ <UInput
+ v-model="photoSearch"
+ icon="i-lucide-search"
+ placeholder="Search photographs…"
+ aria-label="Search photographs for album"
+ class="w-full mb-4"
+ />
+ <div class="cf-photo-picker">
+ <button
+ v-for="photo in choices"
+ :key="photo.id"
+ class="cf-picker-photo"
+ :aria-label="photo.title || 'Photograph'"
+ :class="{ selected: draft.photoIds.includes(photo.id) }"
+ :aria-pressed="draft.photoIds.includes(photo.id)"
+ @click="toggle(photo.id, !draft.photoIds.includes(photo.id))"
+ >
+ <ThumbImage
+ :src="photo.thumbnailUrl || ''"
+ :alt="photo.title || 'Photograph'"
+ /><span>{{ photo.title }}</span
+ ><UIcon
+ v-if="draft.photoIds.includes(photo.id)"
+ name="i-lucide-circle-check"
+ class="cf-picker-check"
+ />
+ </button>
+ </div>
+ <div class="flex items-center justify-between gap-3 mt-4">
+ <span class="text-sm text-muted"
+ >{{ draft.photoIds.length }} selected</span
+ ><UButton @click="picker = false">Done</UButton>
+ </div>
+ </div></template
+ ><template #footer
+ ><UButton
+ color="neutral"
+ variant="outline"
+ :disabled="saving"
+ @click="editor = false"
+ >Cancel</UButton
+ ><UButton
+ type="submit"
+ form="cloud-album-form"
+ :loading="saving"
+ :disabled="!loaded || !draft.title.trim()"
+ >Save album</UButton
+ ></template
+ ></USlideover
+ >
+
+ <UModal
+ v-model:open="removeOpen"
+ title="Delete album?"
+ description="Photographs remain in your library. They may become public if no other protected album contains them."
+ ><template #footer
+ ><UButton
+ color="neutral"
+ variant="outline"
+ @click="removeOpen = false"
+ >Cancel</UButton
+ ><UButton
+ color="error"
+ :loading="busy"
+ @click="remove"
+ >Delete album</UButton
+ ></template
+ ></UModal
+ >
+ </section>
+</template>
diff --git a/apps/cloud/app/components/CloudMediaWorkbench.vue b/apps/cloud/app/components/CloudMediaWorkbench.vue
deleted file mode 100644
index 5ff19b1e..00000000
--- a/apps/cloud/app/components/CloudMediaWorkbench.vue
+++ /dev/null
@@ -1,991 +0,0 @@
-<script setup lang="ts">
-import { STORAGE_CONNECTION_MESSAGES } from '@chronoframe/contracts/storage-diagnostics'
-import type { Photo } from '@chronoframe/contracts/resources'
-const api = $fetch as <T = unknown>(
- path: string,
- options?: { method?: 'GET' | 'POST' | 'DELETE' | 'PATCH'; body?: unknown },
-) => Promise<T>
-const props = defineProps<{ siteId: number; role?: string }>()
-const context = useEntryContext(),
- base = computed(() => `/api/sites/${props.siteId}/media`)
-const connections = ref<
- {
- id: string
- current_revision: number
- healthy: number
- config: { bucket: string }
- }[]
- >([]),
- photos = ref<Photo[]>([]),
- jobs = ref<
- {
- id: string
- photo_id: string
- state: string
- attempts: number
- error_code: string | null
- }[]
- >([]),
- albums = ref<
- { id: number; title: string; isHidden: boolean; hasPassword: boolean }[]
- >([])
-const usage = ref<{ photos: number; pending: number; bytes: number } | null>(
- null,
-)
-const rotation = reactive({ accessKeyId: '', secretAccessKey: '' })
-const editPhoto = reactive({ id: '', title: '', description: '', revision: 0 })
-const renameAlbum = reactive({ title: '', revision: 0 })
-const connectionId = ref(''),
- message = ref(''),
- failed = ref(false),
- busy = ref(false),
- uploading = ref(false),
- progress = ref(0),
- currentFile = ref('')
-const storage = reactive({
- endpoint: '',
- region: 'auto',
- bucket: '',
- accessKeyId: '',
- secretAccessKey: '',
-})
-const albumTitle = ref(''),
- albumId = ref<number | ''>(''),
- albumPassword = ref(''),
- albumHidden = ref(false),
- photoId = ref('')
-const admin = computed(() => props.role === 'admin')
-let timer: ReturnType<typeof setInterval> | undefined,
- controller: AbortController | undefined,
- activeUpload: string | undefined,
- activeResumeKey: string | undefined
-const canPoll = ref(true)
-async function reload() {
- try {
- const [s, p, a, u] = await Promise.all([
- api<{ connections: typeof connections.value }>(base.value + '/storage'),
- api<{ photos: Photo[]; jobs: typeof jobs.value }>(base.value + '/photos'),
- api<{ albums: typeof albums.value }>(base.value + '/albums'),
- api<{ usage: NonNullable<typeof usage.value> }>(base.value + '/usage'),
- ])
- usage.value = u.usage
- connections.value = s.connections
- photos.value = p.photos
- jobs.value = p.jobs
- albums.value = a.albums
- if (!connectionId.value) connectionId.value = s.connections[0]?.id ?? ''
- } catch (error) {
- failed.value = true
- message.value =
- (error as { statusCode?: number }).statusCode === 503
- ? 'Media services need deployment configuration. Your existing site settings are available.'
- : 'Could not refresh media. Check your access and retry.'
- canPoll.value = false
- }
-}
-function refreshMedia() {
- canPoll.value = true
- void reload()
-}
-async function action(run: () => Promise<unknown>, success: string) {
- if (busy.value) return
- busy.value = true
- message.value = ''
- failed.value = false
- try {
- await run()
- message.value = success
- canPoll.value = true
- await reload()
- } catch (error) {
- failed.value = true
- const code = (error as { statusCode?: number }).statusCode
- const diagnostic = (error as { data?: { data?: { code?: string } } }).data
- ?.data?.code
- message.value =
- diagnostic && Object.hasOwn(STORAGE_CONNECTION_MESSAGES, diagnostic)
- ? STORAGE_CONNECTION_MESSAGES[
- diagnostic as keyof typeof STORAGE_CONNECTION_MESSAGES
- ]
- : code === 503
- ? 'Media services need deployment configuration. Check the selected environment settings.'
- : code === 409
- ? 'This item changed. Refresh and try again.'
- : code === 429
- ? 'The preview resource limit has been reached.'
- : code === 403
- ? 'Administrator access is required.'
- : 'The operation failed. Check storage permissions and CORS, then retry.'
- } finally {
- busy.value = false
- }
-}
-async function saveStorage() {
- await action(async () => {
- await api(base.value + '/storage', { method: 'POST', body: storage })
- storage.accessKeyId = ''
- storage.secretAccessKey = ''
- }, 'Storage connected and verified.')
-}
-async function rotateStorage() {
- const selected = connections.value.find((c) => c.id === connectionId.value)
- if (!selected) return
- await action(async () => {
- await api(base.value + '/storage/' + selected.id + '/rotate', {
- method: 'POST',
- body: { revision: selected.current_revision, ...rotation },
- })
- rotation.accessKeyId = ''
- rotation.secretAccessKey = ''
- }, 'Credentials rotated. Existing media references remain available.')
-}
-const photoLoaded = ref(''),
- albumLoaded = ref<number | ''>('')
-let photoLoadGeneration = 0,
- albumLoadGeneration = 0
-const albumReady = computed(
- () => !!albumId.value && albumLoaded.value === albumId.value,
-)
-async function loadPhoto() {
- const id = editPhoto.id,
- generation = ++photoLoadGeneration
- photoLoaded.value = ''
- editPhoto.title = ''
- editPhoto.description = ''
- if (!id) return
- try {
- const data = await api<{ photo: Photo; revision: number }>(
- base.value + '/photos/' + id,
- )
- if (editPhoto.id !== id || generation !== photoLoadGeneration) return
- editPhoto.title = data.photo.title ?? 'Untitled photograph'
- editPhoto.description = data.photo.description ?? ''
- editPhoto.revision = data.revision
- photoLoaded.value = id
- } catch {
- if (editPhoto.id !== id || generation !== photoLoadGeneration) return
- failed.value = true
- message.value =
- 'Could not load photograph settings. Select it again to retry.'
- }
-}
-async function savePhoto() {
- if (!editPhoto.id || photoLoaded.value !== editPhoto.id) return
- await action(
- () =>
- api(base.value + '/photos/' + editPhoto.id, {
- method: 'PATCH',
- body: {
- title: editPhoto.title,
- description: editPhoto.description || null,
- revision: editPhoto.revision,
- },
- }),
- 'Photograph updated.',
- )
- await loadPhoto()
-}
-async function loadAlbum() {
- const id = albumId.value,
- generation = ++albumLoadGeneration
- albumLoaded.value = ''
- albumPassword.value = ''
- renameAlbum.title = ''
- if (!id) return
- try {
- const data = await api<{
- album: { title: string; isHidden: boolean }
- revision: number
- }>(base.value + '/albums/' + id + '/settings')
- if (albumId.value !== id || generation !== albumLoadGeneration) return
- renameAlbum.title = data.album.title
- albumHidden.value = data.album.isHidden
- renameAlbum.revision = data.revision
- albumLoaded.value = id
- } catch {
- if (albumId.value !== id || generation !== albumLoadGeneration) return
- failed.value = true
- message.value = 'Could not load album settings. Select it again to retry.'
- }
-}
-async function saveAlbumAccess(removePassword = false) {
- if (!albumReady.value) return
- if (
- removePassword &&
- !window.confirm(
- 'Remove password protection? Published photographs may become public.',
- )
- )
- return
- const id = albumId.value
- await action(
- async () => {
- await api(base.value + '/albums/' + id + '/access', {
- method: 'POST',
- body: {
- hidden: albumHidden.value,
- ...(removePassword
- ? { password: null }
- : albumPassword.value
- ? { password: albumPassword.value }
- : {}),
- },
- })
- if (albumId.value === id) albumPassword.value = ''
- },
- removePassword ? 'Album password removed.' : 'Album access updated.',
- )
-}
-async function saveAlbum() {
- if (!albumReady.value) return
- await action(
- () =>
- api(base.value + '/albums/' + albumId.value + '/settings', {
- method: 'PATCH',
- body: renameAlbum,
- }),
- 'Album renamed.',
- )
- await loadAlbum()
-}
-function resumeKey(file: File) {
- return [
- 'chronoframe-upload',
- context.value?.scope,
- props.siteId,
- file.name,
- file.size,
- file.lastModified,
- connectionId.value,
- ].join(':')
-}
-async function sendFile(file: File, liveVideo?: File) {
- const cache = resumeKey(file),
- id = localStorage.getItem(cache) || crypto.randomUUID()
- await api(base.value + '/uploads', {
- method: 'POST',
- body: {
- requestId: id,
- connectionId: connectionId.value,
- fileName: file.name,
- bytes: file.size,
- ...(liveVideo
- ? { liveVideo: { fileName: liveVideo.name, bytes: liveVideo.size } }
- : {}),
- },
- })
- localStorage.setItem(cache, id)
- activeResumeKey = cache
- if (controller?.signal.aborted) {
- await api(base.value + '/uploads/' + id + '/cancel', {
- method: 'POST',
- body: {},
- }).catch(() => {})
- localStorage.removeItem(cache)
- throw new Error('cancelled')
- }
- activeUpload = id
- const plan = await api<{
- state: string
- mode?: string
- url?: string
- contentType?: string
- videoUrl?: string | null
- partBytes?: number
- parts?: { partNumber: number; bytes: number }[]
- urls?: string[]
- }>(base.value + '/uploads/' + id + '/plan', { method: 'POST', body: {} })
- if (plan.state === 'completed') {
- localStorage.removeItem(cache)
- return
- }
- if (plan.state !== 'pending' || !plan.mode) {
- localStorage.removeItem(cache)
- activeResumeKey = undefined
- activeUpload = undefined
- throw new Error('Upload unavailable')
- }
- async function put(url: string, body: Blob, type?: string) {
- for (let attempt = 0; attempt < 3; attempt++) {
- controller?.signal.throwIfAborted()
- const response = await fetch(url, {
- method: 'PUT',
- body,
- headers: type ? { 'Content-Type': type } : {},
- signal: controller?.signal,
- redirect: 'error',
- })
- if (response.ok) return
- if (attempt === 2) throw new Error('Upload failed')
- await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt))
- }
- }
- if (plan.mode === 'single') await put(plan.url!, file, plan.contentType)
- else {
- const partBytes = plan.partBytes!,
- count = plan.urls!.length
- for (let i = 0; i < count; i++) {
- const start = i * partBytes,
- end = Math.min(file.size, start + partBytes)
- if (
- !plan.parts?.some(
- (p) => p.partNumber === i + 1 && p.bytes === end - start,
- )
- )
- await put(plan.urls![i]!, file.slice(start, end))
- progress.value = Math.round((end / file.size) * 100)
- }
- }
- if (liveVideo && plan.videoUrl)
- await put(plan.videoUrl, liveVideo, 'video/quicktime')
- progress.value = 100
- await api(base.value + '/uploads/' + id + '/complete', {
- method: 'POST',
- body: {},
- })
- localStorage.removeItem(cache)
- activeUpload = undefined
-}
-async function upload(event: Event) {
- const input = event.target as HTMLInputElement,
- files = Array.from(input.files ?? [])
- if (!files.length || uploading.value || !connectionId.value) return
- if (
- files.some((f) => f.size > 100 * 1024 * 1024) ||
- files.every((f) => f.name.toLowerCase().endsWith('.mov'))
- ) {
- failed.value = true
- message.value =
- 'Choose photographs under 100 MB. A Live Photo MOV must accompany a photograph with the same filename.'
- input.value = ''
- return
- }
- uploading.value = true
- failed.value = false
- message.value = ''
- controller = new AbortController()
- try {
- for (const file of files.filter(
- (f) => !f.name.toLowerCase().endsWith('.mov'),
- )) {
- const companion = files.find(
- (f) =>
- f.name.toLowerCase().endsWith('.mov') &&
- f.name.replace(/\.[^.]+$/, '').toLowerCase() ===
- file.name.replace(/\.[^.]+$/, '').toLowerCase(),
- )
- currentFile.value = file.name
- progress.value = 0
- await sendFile(file, companion)
- }
- message.value = 'Upload verified. Processing continues in the background.'
- } catch (error) {
- failed.value = true
- message.value = controller.signal.aborted
- ? 'Upload cancelled.'
- : 'Upload interrupted. Select the same file to resume its uploaded parts.'
- } finally {
- uploading.value = false
- input.value = ''
- currentFile.value = ''
- await reload()
- }
-}
-async function cancel() {
- controller?.abort()
- if (activeResumeKey) localStorage.removeItem(activeResumeKey)
- activeResumeKey = undefined
- if (activeUpload)
- await api(base.value + '/uploads/' + activeUpload + '/cancel', {
- method: 'POST',
- body: {},
- }).catch(() => {})
- activeUpload = undefined
-}
-async function removePhoto(id: string) {
- if (
- !window.confirm(
- 'Delete this photograph and its managed original, thumbnail and Live Photo files from storage?',
- )
- )
- return
- await action(
- () =>
- api(base.value + '/photos/' + id + '/delete', {
- method: 'POST',
- body: {},
- }),
- 'Photograph deleted. Managed storage files are queued for cleanup.',
- )
-}
-function createAlbum() {
- return action(
- () =>
- api(base.value + '/albums', {
- method: 'POST',
- body: {
- id: crypto.getRandomValues(new Uint32Array(1))[0] || 1,
- title: albumTitle.value,
- },
- }),
- 'Album created.',
- )
-}
-async function removeAlbum() {
- if (
- !window.confirm(
- 'Delete this album? Photographs remain in your library and may become public if no other protected album contains them.',
- )
- )
- return
- await action(
- () =>
- api(base.value + '/albums/' + albumId.value + '/delete', {
- method: 'POST',
- body: {},
- }),
- 'Album deleted. Photographs remain in your library.',
- )
- albumId.value = ''
-}
-async function removeFromAlbum() {
- if (
- !window.confirm(
- 'Remove this photograph from the album? It may become public if no other protected album contains it.',
- )
- )
- return
- await action(
- () =>
- api(base.value + '/albums/' + albumId.value + '/remove-photo', {
- method: 'POST',
- body: { photoId: photoId.value },
- }),
- 'Photograph removed from album.',
- )
-}
-async function publish(value: boolean) {
- await action(
- async () => {
- const settings = await api<{ site: { revision: number } }>(
- `/api/sites/${props.siteId}/settings`,
- )
- const result = await api<{ published: boolean }>(
- base.value + '/publish',
- {
- method: 'POST',
- body: { revision: settings.site.revision, published: value },
- },
- )
- if (context.value?.siteId === props.siteId)
- context.value.published = result.published
- },
- value ? 'Gallery published.' : 'Gallery unpublished.',
- )
-}
-onMounted(() => {
- void reload()
- timer = setInterval(() => {
- if (canPoll.value && !busy.value && !uploading.value) void reload()
- }, 5000)
-})
-onBeforeUnmount(() => {
- if (timer) clearInterval(timer)
- controller?.abort()
-})
-</script>
-<template>
- <section
- class="cf-media-workbench"
- aria-label="Gallery media"
- >
- <p
- v-if="message"
- :role="failed ? 'alert' : 'status'"
- class="cf-notice"
- >
- {{ message }}
- </p>
- <CloudCard>
- <div class="cf-panel-heading">
- <h2>Storage &amp; uploads</h2>
- <p>Your files stay in your private S3-compatible bucket.</p>
- </div>
- <div class="cf-panel-body cf-media-controls">
- <label class="cf-field-label"
- >Storage connection<select
- v-model="connectionId"
- class="cf-input"
- :disabled="!admin"
- >
- <option value="">Choose a connection</option>
- <option
- v-for="c in connections"
- :key="c.id"
- :value="c.id"
- >
- {{ c.config.bucket }} · revision {{ c.current_revision }}
- </option>
- </select></label
- >
- <label
- v-if="admin"
- class="cf-upload-control cf-button cf-button-primary"
- :aria-disabled="!connectionId || uploading"
- >Upload photographs<input
- type="file"
- multiple
- accept=".jpg,.jpeg,.png,.webp,.heic,.heif,.avif,.gif,.mov"
- :disabled="!connectionId || uploading"
- @change="upload"
- /></label>
- <CloudButton
- v-if="uploading"
- variant="secondary"
- @click="cancel"
- >Cancel upload</CloudButton
- >
- <div
- v-if="uploading"
- role="status"
- class="cf-upload-progress"
- >
- <span>{{ currentFile }}</span
- ><progress
- :value="progress"
- max="100"
- aria-label="Upload progress"
- />
- </div>
- <p
- v-if="usage"
- class="cf-muted"
- >
- {{ usage.photos }} / 1,000 photographs · {{ usage.pending }} pending ·
- {{ (usage.bytes / 1024 ** 3).toFixed(2) }} / 5 GiB uploaded in 30 days
- </p>
- <details
- v-if="admin && connectionId"
- class="cf-storage-details"
- >
- <summary>Rotate storage credentials</summary>
- <form
- class="cf-storage-grid"
- @submit.prevent="rotateStorage"
- >
- <label
- >New access key ID<input
- v-model="rotation.accessKeyId"
- class="cf-input"
- autocomplete="off"
- required
- /></label>
- <label
- >New secret access key<input
- v-model="rotation.secretAccessKey"
- class="cf-input"
- type="password"
- autocomplete="new-password"
- required
- /></label>
- <CloudButton
- type="submit"
- variant="secondary"
- :disabled="busy"
- >Test &amp; rotate</CloudButton
- >
- </form>
- </details>
- <details
- v-if="admin"
- class="cf-storage-details"
- >
- <summary>Connect storage</summary>
- <form
- class="cf-storage-grid"
- @submit.prevent="saveStorage"
- >
- <label
- >Endpoint<input
- v-model="storage.endpoint"
- class="cf-input"
- type="url"
- placeholder="https://s3.us-east-1.amazonaws.com"
- required
- /></label>
- <label
- >Region<input
- v-model="storage.region"
- class="cf-input"
- required
- /></label>
- <label
- >Bucket<input
- v-model="storage.bucket"
- class="cf-input"
- required
- /></label>
- <label
- >Access key ID<input
- v-model="storage.accessKeyId"
- class="cf-input"
- autocomplete="off"
- required
- /></label>
- <label
- >Secret access key<input
- v-model="storage.secretAccessKey"
- class="cf-input"
- type="password"
- autocomplete="new-password"
- required
- /></label>
- <p>
- Use a dedicated bucket with private access. Allow this portal
- origin in CORS for GET, PUT and HEAD; allow Content-Type and
- expose ETag. Other endpoint hosts require operator approval.
- </p>
- <CloudButton
- type="submit"
- :disabled="busy"
- >Test &amp; connect</CloudButton
- >
- </form>
- </details>
- </div>
- </CloudCard>
- <CloudCard>
- <div class="cf-panel-heading cf-media-heading">
- <div>
- <h2>Photographs</h2>
- <p>
- {{ photos.length }} ready ·
- {{
- jobs.filter((j) =>
- ['queued', 'running', 'retry_wait'].includes(j.state),
- ).length
- }}
- processing
- </p>
- </div>
- <CloudButton
- variant="secondary"
- @click="refreshMedia"
- >Refresh</CloudButton
- >
- </div>
- <div class="cf-panel-body">
- <GalleryGrid
- v-if="photos.length"
- :photos="photos"
- />
- <p
- v-else
- class="cf-empty-note"
- >
- Upload your first photograph to begin.
- </p>
- <ul
- v-if="jobs.some((j) => j.state !== 'succeeded')"
- class="cf-job-list"
- >
- <li
- v-for="job in jobs.filter((j) => j.state !== 'succeeded')"
- :key="job.id"
- >
- <code>{{ job.id.slice(0, 8) }}</code
- ><span>{{ job.state.replace('_', ' ') }}</span
- ><small
- >Attempt {{ job.attempts
- }}<template v-if="job.error_code">
- · {{ job.error_code.replaceAll('_', ' ') }}</template
- ></small
- >
- <CloudButton
- v-if="admin && job.state === 'failed'"
- size="sm"
- variant="secondary"
- :disabled="busy"
- @click="
- action(
- () =>
- api(base + '/jobs/' + job.id + '/retry', {
- method: 'POST',
- body: {},
- }),
- 'Job queued again.',
- )
- "
- >Retry</CloudButton
- >
- <CloudButton
- v-if="admin && job.state !== 'cancelled'"
- size="sm"
- variant="ghost"
- :disabled="busy"
- @click="removePhoto(job.photo_id)"
- >Remove</CloudButton
- >
- </li>
- </ul>
- <details v-if="admin && photos.length">
- <summary>Edit a photograph</summary>
- <form
- class="cf-storage-grid"
- @submit.prevent="savePhoto"
- >
- <label
- >Photograph<select
- v-model="editPhoto.id"
- :disabled="busy"
- class="cf-input"
- required
- @change="loadPhoto"
- >
- <option value="">Choose a photograph</option>
- <option
- v-for="p in photos"
- :key="p.id"
- :value="p.id"
- >
- {{ p.title }}
- </option>
- </select></label
- >
- <label
- >Title<input
- v-model="editPhoto.title"
- :disabled="busy || photoLoaded !== editPhoto.id"
- class="cf-input"
- maxlength="255"
- required
- /></label>
- <label
- >Description<textarea
- v-model="editPhoto.description"
- :disabled="busy || photoLoaded !== editPhoto.id"
- class="cf-input"
- maxlength="2048"
- />
- </label>
- <CloudButton
- type="submit"
- variant="secondary"
- :disabled="busy || !editPhoto.id || photoLoaded !== editPhoto.id"
- >Save photograph</CloudButton
- >
- </form>
- </details>
- <details v-if="admin && photos.length">
- <summary>Remove a photograph</summary>
- <form
- class="cf-inline-controls"
- @submit.prevent="removePhoto(photoId)"
- >
- <label
- class="sr-only"
- for="cf-delete-photo"
- >Photograph</label
- ><select
- id="cf-delete-photo"
- v-model="photoId"
- class="cf-input"
- required
- >
- <option value="">Choose a photograph</option>
- <option
- v-for="p in photos"
- :key="p.id"
- :value="p.id"
- >
- {{ p.title }}
- </option></select
- ><CloudButton
- type="submit"
- variant="secondary"
- :disabled="busy"
- >Remove</CloudButton
- >
- </form>
- </details>
- </div>
- </CloudCard>
- <CloudCard>
- <div class="cf-panel-heading">
- <h2>Albums &amp; publication</h2>
- <p>
- Hidden and password-protected albums also protect every media variant.
- </p>
- </div>
- <div class="cf-panel-body cf-media-controls">
- <form
- v-if="admin"
- class="cf-inline-controls"
- @submit.prevent="createAlbum()"
- >
- <label
- class="sr-only"
- for="cf-album-name"
- >Album name</label
- ><input
- id="cf-album-name"
- v-model="albumTitle"
- class="cf-input"
- placeholder="Album name"
- maxlength="80"
- required
- /><CloudButton
- type="submit"
- variant="secondary"
- :disabled="busy"
- >Create album</CloudButton
- >
- </form>
- <label class="cf-field-label"
- >Album<select
- v-model="albumId"
- :disabled="busy"
- @change="loadAlbum"
- class="cf-input"
- >
- <option value="">Choose an album</option>
- <option
- v-for="a in albums"
- :key="a.id"
- :value="a.id"
- >
- {{ a.title }}{{ a.isHidden ? ' · hidden' : ''
- }}{{ a.hasPassword ? ' · protected' : '' }}
- </option>
- </select></label
- >
- <form
- v-if="admin && albumId"
- class="cf-inline-controls"
- @submit.prevent="saveAlbum"
- >
- <label
- >Album name<input
- v-model="renameAlbum.title"
- :disabled="busy || !albumReady"
- class="cf-input"
- maxlength="80"
- required /></label
- ><CloudButton
- type="submit"
- variant="secondary"
- :disabled="busy || !albumReady"
- >Rename album</CloudButton
- >
- </form>
- <form
- v-if="admin && albumId"
- class="cf-inline-controls"
- @submit.prevent="
- action(
- () =>
- api(base + '/albums/' + albumId + '/photos', {
- method: 'POST',
- body: { photoId },
- }),
- 'Photograph added.',
- )
- "
- >
- <label
- class="sr-only"
- for="cf-add-photo"
- >Photograph</label
- ><select
- id="cf-add-photo"
- v-model="photoId"
- class="cf-input"
- required
- >
- <option value="">Choose a photograph</option>
- <option
- v-for="p in photos"
- :key="p.id"
- :value="p.id"
- >
- {{ p.title }}
- </option></select
- ><CloudButton
- type="submit"
- variant="secondary"
- :disabled="busy"
- >Add to album</CloudButton
- >
- </form>
- <form
- v-if="admin && albumId"
- class="cf-inline-controls"
- @submit.prevent="saveAlbumAccess()"
- >
- <label
- ><input
- v-model="albumHidden"
- :disabled="busy || !albumReady"
- type="checkbox"
- />
- Hidden</label
- ><label
- >Album password<input
- v-model="albumPassword"
- :disabled="busy || !albumReady"
- type="password"
- class="cf-input"
- minlength="8"
- autocomplete="new-password"
- placeholder="Leave blank to keep current password" /></label
- ><CloudButton
- type="submit"
- variant="secondary"
- :disabled="busy || !albumReady"
- >Save access</CloudButton
- >
- <CloudButton
- v-if="albums.find((a) => a.id === albumId)?.hasPassword"
- type="button"
- variant="ghost"
- :disabled="busy || !albumReady"
- @click="saveAlbumAccess(true)"
- >Remove password protection</CloudButton
- >
- </form>
- <div
- v-if="admin && albumId"
- class="cf-inline-controls"
- >
- <CloudButton
- variant="secondary"
- :disabled="busy || !photoId"
- @click="removeFromAlbum"
- >Remove selected photograph from album</CloudButton
- >
- <CloudButton
- variant="ghost"
- :disabled="busy"
- @click="removeAlbum"
- >Delete album</CloudButton
- >
- </div>
- <div
- v-if="admin"
- class="cf-inline-controls"
- >
- <CloudButton
- :disabled="busy || (!photos.length && !context?.published)"
- @click="publish(!context?.published)"
- >{{
- context?.published ? 'Unpublish gallery' : 'Publish gallery'
- }}</CloudButton
- ><span class="cf-muted"
- >Publishing makes unprotected photographs public at your reserved
- .site.chronoframe.art address.</span
- >
- </div>
- </div>
- </CloudCard>
- </section>
-</template>
diff --git a/apps/cloud/app/components/CloudPhotoLibrary.vue b/apps/cloud/app/components/CloudPhotoLibrary.vue
new file mode 100644
index 00000000..789dd854
--- /dev/null
+++ b/apps/cloud/app/components/CloudPhotoLibrary.vue
@@ -0,0 +1,506 @@
+<script setup lang="ts">
+import type { Photo } from '@chronoframe/contracts/resources'
+import type { TableColumn } from '@nuxt/ui'
+const {
+ photos,
+ message,
+ failed,
+ albums,
+ jobs,
+ loading,
+ admin,
+ busy,
+ uploadOpen,
+ editPhoto,
+ photoLoaded,
+ loadPhoto,
+ savePhoto,
+ removePhoto,
+ refreshMedia,
+ action,
+ api,
+ base,
+} = useCloudSiteMedia()
+const search = ref(''),
+ selection = ref<Record<string, boolean>>({}),
+ editor = ref(false),
+ preview = ref<Photo | null>(null),
+ deleteOpen = ref(false),
+ albumOpen = ref(false),
+ targetAlbum = ref<number>(),
+ saving = ref(false)
+const { sortedPhotos } = usePhotoSort(),
+ { filteredPhotos, hasActiveFilters } = usePhotoFilters()
+const rows = computed(() => {
+ const matches = new Set(filteredPhotos.value.map((p) => p.id))
+ return sortedPhotos.value.filter(
+ (p) =>
+ (!hasActiveFilters.value || matches.has(p.id)) &&
+ (!search.value ||
+ [p.title, p.description, ...(p.tags ?? [])]
+ .join(' ')
+ .toLowerCase()
+ .includes(search.value.toLowerCase())),
+ )
+})
+const chosen = computed(() => rows.value.filter((p) => selection.value[p.id]))
+const columns: TableColumn<Photo>[] = [
+ { id: 'select', header: '', size: 32 },
+ { accessorKey: 'thumbnailUrl', header: 'Photograph' },
+ { accessorKey: 'title', header: 'Title' },
+ { accessorKey: 'tags', header: 'Tags' },
+ { accessorKey: 'dateTaken', header: 'Date taken' },
+ { accessorKey: 'fileSize', header: 'Size' },
+ { id: 'actions', header: '' },
+]
+const pendingJobs = computed(() =>
+ jobs.value.filter((j) => j.state !== 'succeeded'),
+)
+async function edit(photo: Photo) {
+ editPhoto.id = photo.id
+ editor.value = true
+ await loadPhoto()
+}
+async function save() {
+ if (await savePhoto()) editor.value = false
+}
+function deleteOne(photo: Photo) {
+ selection.value = { [photo.id]: true }
+ deleteOpen.value = true
+}
+async function deleteChosen() {
+ saving.value = true
+ try {
+ const ok = await action(
+ () =>
+ api(base.value + '/photos/delete-batch', {
+ method: 'POST',
+ body: { photoIds: chosen.value.map((p) => p.id) },
+ }),
+ 'Photographs deleted. Managed files are queued for cleanup.',
+ )
+ if (ok) {
+ selection.value = {}
+ deleteOpen.value = false
+ }
+ } finally {
+ saving.value = false
+ }
+}
+async function addToAlbum() {
+ if (!targetAlbum.value) return
+ const ok = await action(
+ () =>
+ api(base.value + '/albums/' + targetAlbum.value + '/photos', {
+ method: 'POST',
+ body: { photoIds: chosen.value.map((p) => p.id) },
+ }),
+ 'Photographs added to album.',
+ )
+ if (ok) {
+ albumOpen.value = false
+ selection.value = {}
+ }
+}
+function actions(photo: Photo) {
+ return [
+ [
+ {
+ label: 'Preview',
+ icon: 'i-lucide-eye',
+ onSelect: () => {
+ preview.value = photo
+ },
+ },
+ {
+ label: 'Edit details',
+ icon: 'i-lucide-pencil',
+ disabled: !admin.value,
+ onSelect: () => edit(photo),
+ },
+ ],
+ [
+ {
+ label: 'Delete photograph',
+ icon: 'i-lucide-trash-2',
+ color: 'error' as const,
+ disabled: !admin.value,
+ onSelect: () => deleteOne(photo),
+ },
+ ],
+ ]
+}
+watch(
+ () => photos.value.map((p) => p.id).join(','),
+ () => {
+ const ids = new Set(photos.value.map((p) => p.id))
+ selection.value = Object.fromEntries(
+ Object.entries(selection.value).filter(([id]) => ids.has(id)),
+ )
+ },
+)
+</script>
+<template>
+ <section
+ aria-labelledby="library-heading"
+ class="cf-library"
+ >
+ <div class="cf-library-heading">
+ <div>
+ <h2 id="library-heading">Photo library</h2>
+ <p>
+ {{ photos.length }} photographs · {{ pendingJobs.length }} processing
+ </p>
+ </div>
+ <UButton
+ v-if="admin"
+ icon="i-lucide-upload"
+ @click="uploadOpen = true"
+ >Upload</UButton
+ >
+ </div>
+ <div class="cf-library-toolbar">
+ <UInput
+ v-model="search"
+ icon="i-lucide-search"
+ placeholder="Search photographs…"
+ aria-label="Search photographs"
+ class="cf-library-search"
+ /><UPopover
+ ><UButton
+ color="neutral"
+ :variant="hasActiveFilters ? 'soft' : 'outline'"
+ icon="i-lucide-filter"
+ >Filters</UButton
+ ><template #content><OverlayFilterPanel /></template></UPopover
+ ><UPopover
+ ><UButton
+ color="neutral"
+ variant="outline"
+ icon="i-lucide-arrow-up-down"
+ >Sort</UButton
+ ><template #content><OverlaySortPanel /></template></UPopover
+ ><UButton
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-refresh-cw"
+ aria-label="Refresh photographs"
+ :loading="loading"
+ @click="refreshMedia"
+ />
+ </div>
+ <div
+ v-if="chosen.length"
+ class="cf-selection-bar"
+ >
+ <span>{{ chosen.length }} selected</span
+ ><UButton
+ v-if="admin"
+ size="sm"
+ variant="soft"
+ icon="i-lucide-folder-plus"
+ @click="albumOpen = true"
+ >Add to album</UButton
+ ><UButton
+ v-if="admin"
+ size="sm"
+ color="error"
+ variant="soft"
+ icon="i-lucide-trash-2"
+ @click="deleteOpen = true"
+ >Delete</UButton
+ ><UButton
+ color="neutral"
+ size="sm"
+ variant="ghost"
+ @click="selection = {}"
+ >Clear</UButton
+ >
+ </div>
+ <div class="cf-library-table">
+ <ConsoleMediaTable
+ :data="rows"
+ :columns="columns"
+ :loading="loading && !photos.length"
+ :get-row-id="(row: Photo) => row.id"
+ ><template #select-header
+ ><UCheckbox
+ :model-value="rows.length > 0 && rows.every((p) => selection[p.id])"
+ aria-label="Select all photographs"
+ @update:model-value="
+ (v) => {
+ selection = v
+ ? Object.fromEntries(rows.map((p) => [p.id, true]))
+ : {}
+ }
+ " /></template
+ ><template #select-cell="{ row }"
+ ><UCheckbox
+ :model-value="!!selection[row.original.id]"
+ :aria-label="`Select ${row.original.title}`"
+ @update:model-value="
+ (v) => (selection[row.original.id] = !!v)
+ " /></template
+ ><template #thumbnailUrl-cell="{ row }"
+ ><button
+ class="cf-library-thumb"
+ :aria-label="`Preview ${row.original.title}`"
+ @click="preview = row.original"
+ >
+ <ThumbImage
+ :src="row.original.thumbnailUrl || ''"
+ :alt="row.original.title"
+ /><span
+ v-if="row.original.isLivePhoto"
+ class="cf-live-label"
+ >LIVE</span
+ >
+ </button></template
+ ><template #title-cell="{ row }"
+ ><button
+ class="cf-photo-title"
+ @click="preview = row.original"
+ >
+ {{ row.original.title }}</button
+ ><span class="cf-photo-dimensions"
+ >{{ row.original.width }} × {{ row.original.height }}</span
+ ></template
+ ><template #tags-cell="{ row }"
+ ><div class="cf-tag-list">
+ <UBadge
+ v-for="tag in (row.original.tags ?? []).slice(0, 3)"
+ :key="tag"
+ color="neutral"
+ variant="soft"
+ size="sm"
+ >{{ tag }}</UBadge
+ ><span
+ v-if="!row.original.tags?.length"
+ class="text-muted"
+ >—</span
+ >
+ </div></template
+ ><template #dateTaken-cell="{ row }"
+ ><span class="text-xs text-muted">{{
+ row.original.dateTaken
+ ? new Date(row.original.dateTaken).toLocaleDateString()
+ : '—'
+ }}</span></template
+ ><template #fileSize-cell="{ row }"
+ ><span class="text-xs text-muted">{{
+ row.original.fileSize ? formatBytes(row.original.fileSize) : '—'
+ }}</span></template
+ ><template #actions-cell="{ row }"
+ ><UDropdownMenu :items="actions(row.original)"
+ ><UButton
+ color="neutral"
+ variant="ghost"
+ icon="i-lucide-ellipsis"
+ :aria-label="`Actions for ${row.original.title}`" /></UDropdownMenu></template
+ ><template #empty
+ ><div class="cf-library-empty">
+ <UIcon
+ name="i-lucide-images"
+ class="size-8"
+ />
+ <h3>
+ {{
+ search ? 'No matching photographs' : 'Your library starts here'
+ }}
+ </h3>
+ <p>
+ {{
+ search
+ ? 'Try another search or clear your filters.'
+ : 'Upload photographs to start telling your story.'
+ }}
+ </p>
+ <UButton
+ v-if="admin && !photos.length"
+ variant="soft"
+ @click="uploadOpen = true"
+ >Upload</UButton
+ >
+ </div></template
+ ></ConsoleMediaTable
+ >
+ </div>
+ <section
+ v-if="pendingJobs.length"
+ class="cf-processing-panel"
+ aria-label="Processing queue"
+ >
+ <h3>Processing queue</h3>
+ <div
+ v-for="job in pendingJobs"
+ :key="job.id"
+ class="cf-processing-row"
+ >
+ <UIcon
+ :name="
+ job.state === 'failed'
+ ? 'i-lucide-circle-alert'
+ : 'i-lucide-loader-circle'
+ "
+ :class="{ 'animate-spin': job.state === 'running' }"
+ />
+ <div>
+ <strong>{{ job.state.replaceAll('_', ' ') }}</strong
+ ><span
+ >Attempt {{ job.attempts
+ }}<template v-if="job.error_code">
+ · {{ job.error_code.replaceAll('_', ' ') }}</template
+ ></span
+ >
+ </div>
+ <UButton
+ v-if="admin && job.state === 'failed'"
+ color="neutral"
+ variant="outline"
+ size="sm"
+ :disabled="busy"
+ @click="
+ action(
+ () =>
+ api(base + '/jobs/' + job.id + '/retry', {
+ method: 'POST',
+ body: {},
+ }),
+ 'Job queued again.',
+ )
+ "
+ >Retry</UButton
+ ><UButton
+ v-if="admin && job.state !== 'cancelled'"
+ color="error"
+ variant="ghost"
+ size="sm"
+ @click="removePhoto(job.photo_id)"
+ >Remove</UButton
+ >
+ </div>
+ </section>
+ <USlideover
+ v-model:open="editor"
+ title="Edit photograph"
+ description="Update the details shown in your gallery."
+ :ui="{ footer: 'justify-end' }"
+ ><template #body
+ ><p
+ v-if="failed && message"
+ role="alert"
+ class="cf-notice cf-notice-error"
+ >
+ {{ message }}
+ </p>
+ <p
+ v-if="photoLoaded !== editPhoto.id"
+ role="status"
+ >
+ Loading photograph…
+ </p>
+ <UForm
+ v-else
+ id="cloud-edit-photo"
+ :state="editPhoto"
+ class="space-y-5"
+ @submit="save"
+ ><ConsolePhotoDetailsFields
+ v-model:title="editPhoto.title"
+ v-model:description="editPhoto.description"
+ v-model:tags="editPhoto.tags"
+ v-model:rating="editPhoto.rating" /></UForm></template
+ ><template #footer
+ ><UButton
+ color="neutral"
+ variant="outline"
+ @click="editor = false"
+ >Cancel</UButton
+ ><UButton
+ type="submit"
+ form="cloud-edit-photo"
+ :loading="busy"
+ :disabled="photoLoaded !== editPhoto.id || !editPhoto.title.trim()"
+ >Save changes</UButton
+ ></template
+ ></USlideover
+ >
+ <UModal
+ :open="!!preview"
+ :title="preview?.title || 'Photograph'"
+ description="Preview photograph"
+ :ui="{ content: 'max-w-5xl', body: 'p-0' }"
+ @update:open="
+ (v) => {
+ if (!v) preview = null
+ }
+ "
+ ><template #body
+ ><div
+ v-if="preview"
+ class="cf-photo-preview"
+ >
+ <WebGLImageViewer
+ :src="preview.originalUrl || preview.thumbnailUrl || ''"
+ :alt="preview.title"
+ />
+ <div class="cf-preview-details">
+ <strong>{{ preview.title }}</strong>
+ <p>{{ preview.description }}</p>
+ </div>
+ </div></template
+ ></UModal
+ >
+ <UModal
+ v-model:open="deleteOpen"
+ title="Delete photographs?"
+ description="This deletes the selected photographs and queues their managed original, thumbnail and Live Photo files for cleanup."
+ ><template #footer
+ ><UButton
+ color="neutral"
+ variant="outline"
+ @click="deleteOpen = false"
+ >Cancel</UButton
+ ><UButton
+ color="error"
+ :loading="saving"
+ @click="deleteChosen"
+ >Delete {{ chosen.length }} photograph{{
+ chosen.length === 1 ? '' : 's'
+ }}</UButton
+ ></template
+ ></UModal
+ >
+ <UModal
+ v-model:open="albumOpen"
+ title="Add to album"
+ description="Choose an album for the selected photographs."
+ ><template #body
+ ><USelect
+ v-model="targetAlbum"
+ :items="albums.map((a) => ({ label: a.title, value: a.id }))"
+ placeholder="Choose an album"
+ class="w-full"
+ />
+ <p
+ v-if="!albums.length"
+ class="text-sm text-muted"
+ >
+ Create an album first from the Albums page.
+ </p></template
+ ><template #footer
+ ><UButton
+ color="neutral"
+ variant="outline"
+ @click="albumOpen = false"
+ >Cancel</UButton
+ ><UButton
+ :disabled="!targetAlbum"
+ :loading="busy"
+ @click="addToAlbum"
+ >Add photographs</UButton
+ ></template
+ ></UModal
+ >
+ </section>
+</template>
diff --git a/apps/cloud/app/components/CloudPortalShell.vue b/apps/cloud/app/components/CloudPortalShell.vue
index f76bf21a..663fe65d 100644
--- a/apps/cloud/app/components/CloudPortalShell.vue
+++ b/apps/cloud/app/components/CloudPortalShell.vue
@@ -1,66 +1,63 @@
<script setup lang="ts">
+import { Menu, X } from 'lucide-vue-next'
import {
- Images,
- UserRound,
- ArrowUpRight,
- BookOpen,
- ShieldCheck,
- LogOut,
- Menu,
-} from 'lucide-vue-next'
-import { PopoverRoot, PopoverTrigger, PopoverContent } from 'reka-ui'
-const mobileMenuOpen = ref(false)
-const route = useRoute()
-const { busy, error, signOut } = useCloudSignOut()
+ DialogRoot,
+ DialogTrigger,
+ DialogPortal,
+ DialogOverlay,
+ DialogContent,
+ DialogTitle,
+ DialogDescription,
+ DialogClose,
+} from 'reka-ui'
+const menuOpen = ref(false),
+ route = useRoute()
+watch(
+ () => route.fullPath,
+ () => {
+ menuOpen.value = false
+ },
+)
+useCloudSiteSubscription()
</script>
<template>
<div class="cf-portal">
<header class="cf-portal-header">
<div class="cf-portal-brand">
- <CloudBrand cloud /><span
- class="cf-header-divider"
- aria-hidden="true"
- /><span class="cf-header-location">{{
- route.path.startsWith('/sites') ? 'Workspace' : 'Account settings'
- }}</span>
- </div>
- <div class="cf-header-actions cf-portal-desktop-actions">
- <CloudBadge>Cloud preview</CloudBadge
- ><CloudButton
- variant="ghost"
- size="sm"
- :loading="busy"
- @click="signOut"
- ><LogOut :size="15" />Sign out</CloudButton
- ><CloudThemeToggle />
- </div>
- <div class="cf-portal-mobile-actions">
- <PopoverRoot v-model:open="mobileMenuOpen">
- <PopoverTrigger as-child
+ <DialogRoot v-model:open="menuOpen"
+ ><DialogTrigger as-child
><CloudButton
+ class="cf-sidebar-toggle"
variant="ghost"
size="icon"
- aria-label="Open account menu"
- ><Menu :size="20" /></CloudButton
- ></PopoverTrigger>
- <PopoverContent
- class="cf-mobile-menu"
- align="end"
- :side-offset="12"
- :collision-padding="16"
- aria-label="Account menu"
- >
- <div class="cf-mobile-menu-theme">
- <span>Appearance</span><CloudThemeToggle />
- </div>
- <CloudButton
- variant="ghost"
- :loading="busy"
- @click="signOut"
- ><LogOut :size="16" />Sign out</CloudButton
- >
- </PopoverContent>
- </PopoverRoot>
+ aria-label="Open navigation"
+ ><Menu :size="19" /></CloudButton></DialogTrigger
+ ><DialogPortal
+ ><DialogOverlay class="cf-sidebar-overlay" /><DialogContent
+ class="cf-sidebar-drawer"
+ ><DialogTitle class="sr-only">Navigation</DialogTitle
+ ><DialogDescription class="sr-only"
+ >Your workspace and site navigation.</DialogDescription
+ >
+ <div class="cf-drawer-heading">
+ <span>ChronoFrame Cloud</span
+ ><DialogClose as-child
+ ><CloudButton
+ variant="ghost"
+ size="icon"
+ aria-label="Close navigation"
+ ><X :size="19" /></CloudButton
+ ></DialogClose>
+ </div>
+ <CloudSidebarNavigation />
+ <div class="cf-sidebar-bottom">
+ <CloudUserMenu /></div></DialogContent></DialogPortal
+ ></DialogRoot>
+ <CloudBrand cloud />
+ </div>
+ <div class="cf-header-actions">
+ <CloudBadge class="cf-preview-badge">Cloud preview</CloudBadge
+ ><CloudThemeToggle />
</div>
</header>
<div class="cf-portal-grid">
@@ -68,52 +65,17 @@ const { busy, error, signOut } = useCloudSignOut()
class="cf-sidebar"
aria-label="Workspace"
>
- <p class="cf-nav-label">YOUR SPACE</p>
- <nav aria-label="Portal navigation">
- <NuxtLink
- to="/sites"
- :class="{ active: route.path.startsWith('/sites') }"
- :aria-current="route.path.startsWith('/sites') ? 'page' : undefined"
- ><Images :size="18" />Sites</NuxtLink
- ><NuxtLink
- to="/account"
- :class="{ active: route.path === '/account' }"
- :aria-current="route.path === '/account' ? 'page' : undefined"
- ><UserRound :size="18" />Account</NuxtLink
- >
- <NuxtLink
- to="/account/security"
- :class="{ active: route.path === '/account/security' }"
- :aria-current="
- route.path === '/account/security' ? 'page' : undefined
- "
- ><ShieldCheck :size="18" />Security</NuxtLink
- >
- </nav>
- <p
- v-if="error"
- role="alert"
- class="cf-error-message"
- >
- {{ error }}
- </p>
- <div class="cf-sidebar-bottom">
- <p>ChronoFrame Cloud</p>
- <a
- href="https://docs.chronoframe.art/"
- target="_blank"
- rel="noopener noreferrer"
- ><BookOpen :size="16" />Read the documentation<ArrowUpRight
- :size="14"
- /></a>
- </div>
+ <CloudSidebarNavigation />
+ <div class="cf-sidebar-bottom"><CloudUserMenu /></div>
</aside>
<main
id="main-content"
class="cf-portal-main"
tabindex="-1"
>
- <div class="cf-portal-content"><slot /></div>
+ <div class="cf-portal-content">
+ <slot />
+ </div>
</main>
</div>
</div>
diff --git a/apps/cloud/app/components/CloudSecuritySettings.vue b/apps/cloud/app/components/CloudSecuritySettings.vue
new file mode 100644
index 00000000..874ce800
--- /dev/null
+++ b/apps/cloud/app/components/CloudSecuritySettings.vue
@@ -0,0 +1,371 @@
+<script setup lang="ts">
+import { accountError } from '../utils/account-error'
+
+const { data: security, refresh } = await useFetch<{
+ email: string
+ hasPassword: boolean
+ twoFactorEnabled: boolean
+ hasAuthenticator: boolean
+ passkeys: { id: number; name: string | null; createdAt: string }[]
+}>('/api/auth/security')
+const password = ref(''),
+ newPassword = ref(''),
+ code = ref(''),
+ passkeyName = ref('')
+const busy = ref(false),
+ error = ref(''),
+ notice = ref(''),
+ qr = ref(''),
+ totpURI = ref(''),
+ backupCodes = ref<string[]>([])
+async function run(action: () => Promise<void>) {
+ if (busy.value) return
+ busy.value = true
+ error.value = ''
+ notice.value = ''
+ try {
+ await action()
+ await refresh()
+ } catch (cause) {
+ error.value = accountError(cause)
+ } finally {
+ busy.value = false
+ }
+}
+async function changePassword() {
+ await run(async () => {
+ await $fetch('/api/auth/change-password', {
+ method: 'POST',
+ body: {
+ currentPassword: password.value,
+ newPassword: newPassword.value,
+ revokeOtherSessions: true,
+ },
+ })
+ newPassword.value = ''
+ password.value = ''
+ notice.value = 'Password updated. Other sessions have been signed out.'
+ })
+}
+async function enable(method: 'otp' | 'totp') {
+ await run(async () => {
+ const result = await $fetch<{ totpURI?: string; backupCodes?: string[] }>(
+ '/api/auth/two-factor/enable',
+ { method: 'POST', body: { password: password.value, method } },
+ )
+ password.value = ''
+ if (result.totpURI) {
+ totpURI.value = result.totpURI
+ backupCodes.value = result.backupCodes ?? []
+ const QRCode = await import('qrcode')
+ qr.value = await QRCode.toDataURL(result.totpURI, {
+ width: 240,
+ margin: 2,
+ })
+ notice.value =
+ 'Scan the QR code, save your recovery codes, and enter a code to finish setup.'
+ } else notice.value = 'Email second-step verification is enabled.'
+ })
+}
+async function confirmAuthenticator() {
+ await run(async () => {
+ await $fetch('/api/auth/two-factor/verify-totp', {
+ method: 'POST',
+ body: { code: code.value },
+ })
+ code.value = ''
+ qr.value = ''
+ totpURI.value = ''
+ notice.value =
+ 'Authenticator verified and enabled. Keep your recovery codes somewhere safe.'
+ })
+}
+async function disable() {
+ await run(async () => {
+ await $fetch('/api/auth/two-factor/disable', {
+ method: 'POST',
+ body: { password: password.value },
+ })
+ password.value = ''
+ backupCodes.value = []
+ qr.value = ''
+ totpURI.value = ''
+ notice.value = 'Two-step verification has been disabled.'
+ })
+}
+async function regenerate() {
+ await run(async () => {
+ const result = await $fetch<{ backupCodes: string[] }>(
+ '/api/auth/two-factor/generate-backup-codes',
+ { method: 'POST', body: { password: password.value } },
+ )
+ backupCodes.value = result.backupCodes
+ password.value = ''
+ notice.value =
+ 'New recovery codes generated. Your previous codes no longer work.'
+ })
+}
+async function addPasskey() {
+ await run(async () => {
+ const result = await useCloudAccount().passkey.addPasskey({
+ name: passkeyName.value.trim() || 'My passkey',
+ })
+ if (result.error) throw result.error
+ passkeyName.value = ''
+ notice.value =
+ 'Passkey created. Its private key stays on your device or password manager.'
+ })
+}
+async function deletePasskey(id: number) {
+ await run(async () => {
+ await $fetch('/api/auth/passkey/delete-passkey', {
+ method: 'POST',
+ body: { id: String(id) },
+ })
+ notice.value = 'Passkey removed.'
+ })
+}
+</script>
+<template>
+ <section
+ id="security"
+ aria-labelledby="security-heading"
+ >
+ <div class="cf-page-heading">
+ <div>
+ <h2
+ id="security-heading"
+ class="cf-page-title"
+ >
+ Security
+ </h2>
+ <p class="cf-page-description">
+ Manage sign-in methods for {{ security?.email }}.
+ </p>
+ </div>
+ </div>
+ <p
+ v-if="error"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ <p
+ v-if="notice"
+ class="cf-notice"
+ role="status"
+ >
+ {{ notice }}
+ </p>
+ <CloudCard class="cf-security-card"
+ ><div class="cf-settings-intro">
+ <h2>Password</h2>
+ <p>Use a unique password with at least 12 characters.</p>
+ </div>
+ <div class="cf-settings-body">
+ <form
+ v-if="security?.hasPassword"
+ @submit.prevent="changePassword"
+ >
+ <label for="current-password">Current password</label
+ ><CloudInput
+ id="current-password"
+ v-model="password"
+ type="password"
+ autocomplete="current-password"
+ :disabled="busy"
+ required
+ /><label for="new-password">New password</label
+ ><CloudInput
+ id="new-password"
+ v-model="newPassword"
+ type="password"
+ autocomplete="new-password"
+ minlength="12"
+ maxlength="128"
+ :disabled="busy"
+ required
+ /><CloudButton
+ type="submit"
+ :loading="busy"
+ >Update password</CloudButton
+ >
+ </form>
+ <p v-else>
+ You signed in with an email code.
+ <NuxtLink
+ class="cf-text-link"
+ to="/forgot-password"
+ >Email yourself a link to set a password</NuxtLink
+ >
+ before enabling two-step verification.
+ </p>
+ </div></CloudCard
+ >
+ <CloudCard class="cf-security-card"
+ ><div class="cf-settings-intro">
+ <div>
+ <h2>Two-step verification</h2>
+ <p>
+ Add a code after password sign-in. Connected authenticators also
+ protect email-code sign-in. Passkeys use device verification.
+ </p>
+ </div>
+ <CloudBadge
+ :tone="security?.twoFactorEnabled ? 'success' : 'neutral'"
+ >{{ security?.twoFactorEnabled ? 'Enabled' : 'Off' }}</CloudBadge
+ >
+ </div>
+ <div class="cf-settings-body">
+ <template v-if="security?.hasPassword"
+ ><label for="security-password"
+ >Confirm your password to change security settings</label
+ ><CloudInput
+ id="security-password"
+ v-model="password"
+ type="password"
+ autocomplete="current-password"
+ :disabled="busy"
+ />
+ <div class="cf-security-actions">
+ <CloudButton
+ v-if="!security.twoFactorEnabled"
+ :disabled="busy || !password"
+ @click="enable('otp')"
+ >Enable email verification</CloudButton
+ ><CloudButton
+ v-if="!security.hasAuthenticator"
+ variant="secondary"
+ :disabled="busy || !password"
+ @click="enable('totp')"
+ >Set up authenticator</CloudButton
+ ><CloudButton
+ v-if="security.twoFactorEnabled"
+ variant="destructive"
+ :disabled="busy || !password"
+ @click="disable"
+ >Disable two-step verification</CloudButton
+ >
+ </div>
+ <div
+ v-if="totpURI"
+ class="cf-totp-setup"
+ >
+ <img
+ v-if="qr"
+ :src="qr"
+ width="240"
+ height="240"
+ alt="Scan this private QR code with your authenticator app"
+ />
+ <details>
+ <summary>Cannot scan the QR code?</summary>
+ <p class="cf-secret-value">{{ totpURI }}</p>
+ </details>
+ <form @submit.prevent="confirmAuthenticator">
+ <label for="totp-code">Authenticator code</label
+ ><CloudInput
+ id="totp-code"
+ v-model="code"
+ inputmode="numeric"
+ autocomplete="one-time-code"
+ pattern="[0-9]{6}"
+ maxlength="6"
+ required
+ :disabled="busy"
+ /><CloudButton
+ type="submit"
+ :loading="busy"
+ >Verify and enable</CloudButton
+ >
+ </form>
+ </div>
+ <div v-if="security.hasAuthenticator">
+ <p>
+ Authenticator connected. Recovery codes are single use. Generating
+ new codes replaces the old ones.
+ </p>
+ <CloudButton
+ variant="secondary"
+ :disabled="busy || !password"
+ @click="regenerate"
+ >Replace recovery codes</CloudButton
+ >
+ </div>
+ <div
+ v-if="backupCodes.length"
+ class="cf-notice"
+ >
+ <strong>Save these recovery codes privately.</strong>
+ <p>These are only shown here. Keep them outside this browser.</p>
+ <ul class="cf-recovery-codes">
+ <li
+ v-for="item in backupCodes"
+ :key="item"
+ >
+ <code>{{ item }}</code>
+ </li>
+ </ul>
+ <CloudButton
+ variant="secondary"
+ @click="backupCodes = []"
+ >I have saved my codes</CloudButton
+ >
+ </div></template
+ >
+ </div></CloudCard
+ >
+ <CloudCard class="cf-security-card"
+ ><div class="cf-settings-intro">
+ <h2>Passkeys</h2>
+ <p>
+ Use your device lock, fingerprint or security key. Your device creates
+ the keys automatically.
+ </p>
+ </div>
+ <div class="cf-settings-body">
+ <form @submit.prevent="addPasskey">
+ <label for="passkey-name">Passkey name</label
+ ><CloudInput
+ id="passkey-name"
+ v-model="passkeyName"
+ maxlength="80"
+ autocomplete="off"
+ placeholder="For example, my laptop"
+ :disabled="busy"
+ /><CloudButton
+ type="submit"
+ :loading="busy"
+ >Create passkey</CloudButton
+ >
+ </form>
+ <ul
+ v-if="security?.passkeys.length"
+ class="cf-passkey-list"
+ >
+ <li
+ v-for="key in security.passkeys"
+ :key="key.id"
+ >
+ <span>{{ key.name || 'Passkey' }}</span
+ ><CloudButton
+ variant="destructive"
+ size="sm"
+ :disabled="busy"
+ :aria-label="`Remove ${key.name || 'passkey'}`"
+ @click="deletePasskey(key.id)"
+ >Remove</CloudButton
+ >
+ </li>
+ </ul>
+ <p
+ v-else
+ class="cf-auth-hint"
+ >
+ No passkeys yet.
+ </p>
+ </div></CloudCard
+ >
+ </section>
+</template>
diff --git a/apps/cloud/app/components/CloudSidebarNavigation.vue b/apps/cloud/app/components/CloudSidebarNavigation.vue
new file mode 100644
index 00000000..cd427608
--- /dev/null
+++ b/apps/cloud/app/components/CloudSidebarNavigation.vue
@@ -0,0 +1,75 @@
+<script setup lang="ts">
+import { ArrowLeft, Images, LibraryBig, PanelsTopLeft } from 'lucide-vue-next'
+const route = useRoute(),
+ context = useEntryContext()
+const site = computed(() =>
+ route.path.startsWith('/sites/') && context.value?.audience === 'portal'
+ ? context.value
+ : null,
+)
+const mode = computed(() => (site.value ? 'site' : 'workspace'))
+const direction = ref('cf-nav-forward')
+watch(mode, (next) => {
+ direction.value = next === 'site' ? 'cf-nav-forward' : 'cf-nav-back'
+})
+</script>
+<template>
+ <div class="cf-sidebar-viewport">
+ <Transition :name="direction"
+ ><div
+ :key="mode"
+ class="cf-sidebar-panel"
+ >
+ <template v-if="site"
+ ><NuxtLink
+ to="/sites"
+ class="cf-sidebar-back"
+ ><ArrowLeft :size="15" />All sites</NuxtLink
+ >
+ <div class="cf-sidebar-site">
+ <span class="cf-site-icon"><Images :size="18" /></span>
+ <div>
+ <strong>{{ site.name }}</strong
+ ><span>{{
+ site.published ? 'Published gallery' : 'Private draft'
+ }}</span>
+ </div>
+ </div>
+ <p class="cf-nav-label">MANAGE SITE</p>
+ <nav aria-label="Site navigation">
+ <NuxtLink
+ :to="`/sites/${site.siteId}/photos`"
+ :class="{
+ active:
+ /\/(?:photos)?$/.test(route.path) ||
+ route.path === `/sites/${site.siteId}`,
+ }"
+ :aria-current="
+ route.path.endsWith('/photos') ? 'page' : undefined
+ "
+ ><Images :size="17" />Photo library</NuxtLink
+ ><NuxtLink
+ :to="`/sites/${site.siteId}/albums`"
+ :class="{ active: route.path.endsWith('/albums') }"
+ :aria-current="
+ route.path.endsWith('/albums') ? 'page' : undefined
+ "
+ ><LibraryBig :size="17" />Albums</NuxtLink
+ >
+ </nav>
+ </template>
+ <template v-else
+ ><p class="cf-nav-label">WORKSPACE</p>
+ <nav aria-label="Portal navigation">
+ <NuxtLink
+ to="/sites"
+ :class="{ active: route.path === '/sites' }"
+ :aria-current="route.path === '/sites' ? 'page' : undefined"
+ ><PanelsTopLeft :size="17" />Sites</NuxtLink
+ >
+ </nav></template
+ >
+ </div></Transition
+ >
+ </div>
+</template>
diff --git a/apps/cloud/app/components/CloudSiteHeader.vue b/apps/cloud/app/components/CloudSiteHeader.vue
new file mode 100644
index 00000000..a51a886a
--- /dev/null
+++ b/apps/cloud/app/components/CloudSiteHeader.vue
@@ -0,0 +1,60 @@
+<script setup lang="ts">
+import { ArrowUpRight, Settings, Globe } from 'lucide-vue-next'
+const context = useEntryContext(),
+ { admin, busy, photos, publish } = useCloudSiteMedia()
+const { data } = useFetch<{ site: { slug: string | null } }>(
+ `/api/sites/${context.value?.siteId}/settings`,
+)
+const host = computed(() =>
+ data.value?.site.slug ? `${data.value.site.slug}.site.chronoframe.art` : '',
+)
+</script>
+<template>
+ <div class="cf-site-page-header">
+ <div class="cf-site-heading">
+ <h1>{{ context?.name }}</h1>
+ <div class="cf-site-publication">
+ <CloudBadge :tone="context?.published ? 'success' : 'neutral'">{{
+ context?.published ? 'Published' : 'Private draft'
+ }}</CloudBadge
+ ><span>{{ host }}</span>
+ </div>
+ </div>
+ <div class="cf-site-page-actions">
+ <CloudButton
+ v-if="host && context?.published"
+ as-child
+ variant="ghost"
+ size="sm"
+ ><a
+ :href="`https://${host}`"
+ target="_blank"
+ rel="noopener noreferrer"
+ >View site<ArrowUpRight :size="14" /></a></CloudButton
+ ><CloudButton
+ v-if="admin"
+ variant="secondary"
+ size="sm"
+ :disabled="busy || (!photos.length && !context?.published)"
+ @click="publish(!context?.published)"
+ ><Globe :size="14" />{{
+ context?.published ? 'Unpublish' : 'Publish gallery'
+ }}</CloudButton
+ ><CloudButton
+ as-child
+ variant="ghost"
+ size="icon"
+ ><NuxtLink
+ :to="`/sites/${context?.siteId}/settings`"
+ aria-label="Site settings"
+ ><Settings :size="17" /></NuxtLink
+ ></CloudButton>
+ </div>
+ <p
+ v-if="!context?.published"
+ class="cf-draft-hint"
+ >
+ Your gallery is private. Publish it when you are ready to share.
+ </p>
+ </div>
+</template>
diff --git a/apps/cloud/app/components/CloudSiteWorkspace.vue b/apps/cloud/app/components/CloudSiteWorkspace.vue
new file mode 100644
index 00000000..45085901
--- /dev/null
+++ b/apps/cloud/app/components/CloudSiteWorkspace.vue
@@ -0,0 +1,32 @@
+<script setup lang="ts">
+import { PUBLIC_GALLERY_DEFAULTS } from '@chronoframe/contracts/gallery-settings'
+import type { SettingValue } from '@chronoframe/contracts/settings'
+const props = defineProps<{ siteId: number; role?: string }>()
+const settings = useSettingsStore()
+settings.data = structuredClone(PUBLIC_GALLERY_DEFAULTS) as Record<
+ string,
+ Record<string, SettingValue>
+>
+settings.data.app!.title = useEntryContext().value?.name ?? 'ChronoFrame'
+settings.isInitialized = true
+const media = provideCloudSiteMedia(props)
+const { photos, loading, message, failed, reload } = media
+const status = computed(() => (loading.value ? 'pending' : 'success'))
+</script>
+<template>
+ <PhotosProvider
+ :photos="photos"
+ :refresh="reload"
+ :status="status"
+ ><CloudSiteHeader />
+ <p
+ v-if="message"
+ :role="failed ? 'alert' : 'status'"
+ class="cf-notice"
+ :class="{ 'cf-notice-error': failed }"
+ >
+ {{ message }}
+ </p>
+ <slot /><CloudUploadDrawer
+ /></PhotosProvider>
+</template>
diff --git a/apps/cloud/app/components/CloudStorageSettings.vue b/apps/cloud/app/components/CloudStorageSettings.vue
new file mode 100644
index 00000000..43d3218e
--- /dev/null
+++ b/apps/cloud/app/components/CloudStorageSettings.vue
@@ -0,0 +1,127 @@
+<script setup lang="ts">
+const {
+ connections,
+ connectionId,
+ storage,
+ rotation,
+ saveStorage,
+ rotateStorage,
+ busy,
+ admin,
+} = useCloudSiteMedia()
+</script>
+<template>
+ <CloudCard
+ ><div class="cf-panel-heading">
+ <h2>Storage</h2>
+ <p>Connect a private S3-compatible bucket for your photographs.</p>
+ </div>
+ <div class="cf-panel-body cf-media-controls">
+ <label class="cf-field-label"
+ >Storage connection<select
+ v-model="connectionId"
+ class="cf-input"
+ :disabled="!admin"
+ >
+ <option value="">Choose a connection</option>
+ <option
+ v-for="connection in connections"
+ :key="connection.id"
+ :value="connection.id"
+ >
+ {{ connection.config.bucket }} · revision
+ {{ connection.current_revision }}
+ </option>
+ </select></label
+ >
+ <details
+ v-if="admin && connectionId"
+ class="cf-storage-details"
+ >
+ <summary>Rotate storage credentials</summary>
+ <form
+ class="cf-storage-grid"
+ @submit.prevent="rotateStorage"
+ >
+ <label
+ >New access key ID<input
+ v-model="rotation.accessKeyId"
+ class="cf-input"
+ autocomplete="off"
+ required
+ /></label>
+ <label
+ >New secret access key<input
+ v-model="rotation.secretAccessKey"
+ class="cf-input"
+ type="password"
+ autocomplete="new-password"
+ required
+ /></label>
+ <CloudButton
+ type="submit"
+ variant="secondary"
+ :disabled="busy"
+ >Test &amp; rotate</CloudButton
+ >
+ </form>
+ </details>
+ <details
+ v-if="admin"
+ class="cf-storage-details"
+ >
+ <summary>Connect storage</summary>
+ <form
+ class="cf-storage-grid"
+ @submit.prevent="saveStorage"
+ >
+ <label
+ >Endpoint<input
+ v-model="storage.endpoint"
+ class="cf-input"
+ type="url"
+ placeholder="https://s3.us-east-1.amazonaws.com"
+ required
+ /></label>
+ <label
+ >Region<input
+ v-model="storage.region"
+ class="cf-input"
+ required
+ /></label>
+ <label
+ >Bucket<input
+ v-model="storage.bucket"
+ class="cf-input"
+ required
+ /></label>
+ <label
+ >Access key ID<input
+ v-model="storage.accessKeyId"
+ class="cf-input"
+ autocomplete="off"
+ required
+ /></label>
+ <label
+ >Secret access key<input
+ v-model="storage.secretAccessKey"
+ class="cf-input"
+ type="password"
+ autocomplete="new-password"
+ required
+ /></label>
+ <p>
+ Use a dedicated bucket with private access. Allow this portal origin
+ in CORS for GET, PUT and HEAD; allow Content-Type and expose ETag.
+ Other endpoint hosts require operator approval.
+ </p>
+ <CloudButton
+ type="submit"
+ :disabled="busy"
+ >Test &amp; connect</CloudButton
+ >
+ </form>
+ </details>
+ </div></CloudCard
+ >
+</template>
diff --git a/apps/cloud/app/components/CloudUploadDrawer.vue b/apps/cloud/app/components/CloudUploadDrawer.vue
new file mode 100644
index 00000000..76540bae
--- /dev/null
+++ b/apps/cloud/app/components/CloudUploadDrawer.vue
@@ -0,0 +1,130 @@
+<script setup lang="ts">
+const {
+ uploadOpen,
+ message,
+ failed,
+ connections,
+ connectionId,
+ upload,
+ uploading,
+ progress,
+ currentFile,
+ cancel,
+ usage,
+ admin,
+} = useCloudSiteMedia()
+const context = useEntryContext(),
+ input = ref<HTMLInputElement>()
+async function dropFiles(event: DragEvent) {
+ if (
+ !input.value ||
+ uploading.value ||
+ !connectionId.value ||
+ !admin.value ||
+ !event.dataTransfer?.files.length
+ )
+ return
+ input.value.files = event.dataTransfer.files
+ await upload({ target: input.value } as unknown as Event)
+}
+</script>
+<template>
+ <USlideover
+ v-model:open="uploadOpen"
+ title="Upload photographs"
+ description="Add photographs to your library. JPEG, PNG, HEIC and paired Live Photos are supported."
+ :ui="{ footer: 'justify-end' }"
+ ><template #body
+ ><div class="space-y-5">
+ <p
+ v-if="message"
+ :role="failed ? 'alert' : 'status'"
+ class="cf-notice"
+ :class="{ 'cf-notice-error': failed }"
+ >
+ {{ message }}
+ </p>
+ <UFormField label="Storage connection"
+ ><USelect
+ v-model="connectionId"
+ :items="
+ connections.map((c) => ({ label: c.config.bucket, value: c.id }))
+ "
+ class="w-full"
+ :disabled="uploading"
+ /></UFormField>
+ <p
+ v-if="!connections.length"
+ class="text-sm text-muted"
+ >
+ Connect your private storage in
+ <NuxtLink
+ :to="`/sites/${context?.siteId}/settings`"
+ class="underline"
+ @click="uploadOpen = false"
+ >site settings</NuxtLink
+ >
+ before uploading.
+ </p>
+ <input
+ ref="input"
+ class="sr-only"
+ type="file"
+ multiple
+ accept="image/*,.heic,.heif,.mov"
+ aria-label="Choose photographs"
+ :disabled="uploading || !connectionId || !admin"
+ @change="upload"
+ /><button
+ class="cf-upload-dropzone"
+ @dragover.prevent
+ @drop.prevent="dropFiles"
+ :disabled="uploading || !connectionId || !admin"
+ @click="input?.click()"
+ >
+ <UIcon
+ name="tabler:cloud-upload"
+ class="size-9"
+ /><strong>Select photographs</strong
+ ><span
+ >Drop images here, or choose images and matching .MOV files
+ together.</span
+ ><span>Up to 100 MB per photograph and paired video.</span>
+ </button>
+ <div
+ v-if="uploading"
+ role="status"
+ class="space-y-3"
+ >
+ <p class="text-sm break-all">{{ currentFile }}</p>
+ <UProgress :model-value="progress" />
+ <p class="text-xs text-muted">
+ {{ progress }}% · Uploading to your private bucket
+ </p>
+ </div>
+ <p
+ v-if="usage"
+ class="text-xs text-muted"
+ >
+ {{ usage.photos }} / 1,000 photographs ·
+ {{ (usage.bytes / 1073741824).toFixed(2) }} / 5 GiB uploaded in 30
+ days
+ </p>
+ </div></template
+ ><template #footer
+ ><UButton
+ v-if="uploading"
+ color="error"
+ variant="soft"
+ @click="cancel"
+ >Cancel upload</UButton
+ ><UButton
+ v-else
+ color="neutral"
+ variant="outline"
+ @click="uploadOpen = false"
+ >Done</UButton
+ ></template
+ ></USlideover
+ >
+</template>
diff --git a/apps/cloud/app/components/CloudUserMenu.vue b/apps/cloud/app/components/CloudUserMenu.vue
new file mode 100644
index 00000000..a2d4144e
--- /dev/null
+++ b/apps/cloud/app/components/CloudUserMenu.vue
@@ -0,0 +1,77 @@
+<script setup lang="ts">
+import { ChevronsUpDown, UserRound, LogOut } from 'lucide-vue-next'
+import {
+ DropdownMenuRoot,
+ DropdownMenuTrigger,
+ DropdownMenuPortal,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from 'reka-ui'
+const user = usePortalIdentity(),
+ { busy, error, signOut } = useCloudSignOut()
+const label = computed(
+ () => user.value?.name || user.value?.email || 'Your account',
+)
+const initials = computed(() =>
+ label.value
+ .split(/[\s@]+/)
+ .slice(0, 2)
+ .map((v) => v[0])
+ .join('')
+ .toUpperCase(),
+)
+</script>
+<template>
+ <div class="cf-user-menu">
+ <p
+ v-if="error"
+ class="cf-error-message"
+ role="alert"
+ >
+ {{ error }}
+ </p>
+ <DropdownMenuRoot
+ ><DropdownMenuTrigger as-child
+ ><button
+ class="cf-user-trigger"
+ aria-label="Open user menu"
+ >
+ <span class="cf-user-avatar">{{ initials }}</span
+ ><span class="cf-user-identity"
+ ><strong>{{ label }}</strong
+ ><span>{{ user?.email || 'Account settings' }}</span></span
+ ><ChevronsUpDown :size="15" /></button
+ ></DropdownMenuTrigger>
+ <DropdownMenuPortal
+ ><DropdownMenuContent
+ class="cf-account-menu"
+ side="top"
+ align="start"
+ :side-offset="8"
+ :collision-padding="12"
+ aria-label="User menu"
+ >
+ <div class="cf-account-menu-label">
+ <strong>{{ label }}</strong
+ ><span>{{ user?.email }}</span>
+ </div>
+ <DropdownMenuSeparator class="cf-menu-separator" />
+ <DropdownMenuItem as-child
+ ><NuxtLink to="/account"
+ ><UserRound :size="16" />Account &amp; security</NuxtLink
+ ></DropdownMenuItem
+ >
+ <DropdownMenuSeparator class="cf-menu-separator" />
+ <DropdownMenuItem
+ :disabled="busy"
+ @select="signOut"
+ ><LogOut :size="16" />{{
+ busy ? 'Signing out…' : 'Sign out'
+ }}</DropdownMenuItem
+ >
+ </DropdownMenuContent></DropdownMenuPortal
+ >
+ </DropdownMenuRoot>
+ </div>
+</template>
diff --git a/apps/cloud/app/composables/useCloudSignOut.ts b/apps/cloud/app/composables/useCloudSignOut.ts
index 38828a7b..c87a918a 100644
--- a/apps/cloud/app/composables/useCloudSignOut.ts
+++ b/apps/cloud/app/composables/useCloudSignOut.ts
@@ -1,5 +1,11 @@
/** One logout behavior for account settings and the portal account menu. */
export function useCloudSignOut() {
+ const nuxtApp = useNuxtApp(),
+ context = useEntryContext(),
+ catalog = useState('platform-site-catalog'),
+ userId = useState('platform-user-id'),
+ identity = usePortalIdentity(),
+ settings = useSettingsStore()
const busy = ref(false),
error = ref('')
async function signOut() {
@@ -8,13 +14,18 @@ export function useCloudSignOut() {
error.value = ''
try {
await $fetch('/api/auth/sign-out', { method: 'POST' })
- clearNuxtData()
- useEntryContext().value = null
- useState('platform-site-catalog').value = null
- useState('platform-user-id').value = null
- useSettingsStore().$reset()
- // Reset the document at the authentication boundary so no previous user's data survives.
- await navigateTo('/signin', { external: true })
+ nuxtApp.runWithContext(() => {
+ clearNuxtData()
+ context.value = null
+ catalog.value = null
+ userId.value = null
+ identity.value = null
+ settings.$reset()
+ })
+ // Reset the document at the authentication boundary.
+ await nuxtApp.runWithContext(() =>
+ navigateTo('/signin', { external: true }),
+ )
} catch {
error.value = 'We could not sign you out. Please try again.'
} finally {
diff --git a/apps/cloud/app/composables/useCloudSiteMedia.ts b/apps/cloud/app/composables/useCloudSiteMedia.ts
new file mode 100644
index 00000000..ded98171
--- /dev/null
+++ b/apps/cloud/app/composables/useCloudSiteMedia.ts
@@ -0,0 +1,476 @@
+import { STORAGE_CONNECTION_MESSAGES } from '@chronoframe/contracts/storage-diagnostics'
+import type { Album, Photo } from '@chronoframe/contracts/resources'
+export function useCloudMediaWorkspace(props: {
+ siteId: number
+ role?: string
+}) {
+ const entryContext = useEntryContext(),
+ snapshot = entryContext.value?.scope
+ const api = async <T = unknown>(
+ path: string,
+ options?: { method?: 'GET' | 'POST' | 'DELETE' | 'PATCH'; body?: unknown },
+ ): Promise<T> => {
+ if (entryContext.value?.scope !== snapshot)
+ throw new Error('Site context changed')
+ const result = await (
+ $fetch as (
+ path: string,
+ options?: Record<string, unknown>,
+ ) => Promise<unknown>
+ )(path, options)
+ if (entryContext.value?.scope !== snapshot)
+ throw new Error('Site context changed')
+ return result as T
+ }
+ const context = useEntryContext(),
+ base = computed(() => `/api/sites/${props.siteId}/media`)
+ const connections = ref<
+ {
+ id: string
+ current_revision: number
+ healthy: number
+ config: { bucket: string }
+ }[]
+ >([]),
+ photos = ref<Photo[]>([]),
+ jobs = ref<
+ {
+ id: string
+ photo_id: string
+ state: string
+ attempts: number
+ error_code: string | null
+ }[]
+ >([]),
+ albums = ref<(Album & { photoIds: string[] })[]>([])
+ const usage = ref<{ photos: number; pending: number; bytes: number } | null>(
+ null,
+ )
+ const rotation = reactive({ accessKeyId: '', secretAccessKey: '' })
+ const editPhoto = reactive({
+ id: '',
+ title: '',
+ description: '',
+ tags: [] as string[],
+ rating: null as number | null,
+ revision: 0,
+ })
+ const connectionId = ref(''),
+ message = ref(''),
+ failed = ref(false),
+ busy = ref(false),
+ uploading = ref(false),
+ progress = ref(0),
+ currentFile = ref('')
+ const storage = reactive({
+ endpoint: '',
+ region: 'auto',
+ bucket: '',
+ accessKeyId: '',
+ secretAccessKey: '',
+ })
+ const admin = computed(() => props.role === 'admin')
+ let timer: ReturnType<typeof setInterval> | undefined,
+ controller: AbortController | undefined,
+ activeUpload: string | undefined,
+ activeResumeKey: string | undefined
+ const canPoll = ref(true)
+ const loading = ref(false),
+ uploadOpen = ref(false)
+ let reloadGeneration = 0
+ async function reload() {
+ const generation = ++reloadGeneration
+ loading.value = true
+ try {
+ const [s, p, a, u] = await Promise.all([
+ api<{ connections: typeof connections.value }>(base.value + '/storage'),
+ api<{ photos: Photo[]; jobs: typeof jobs.value }>(
+ base.value + '/photos',
+ ),
+ api<{ albums: typeof albums.value }>(base.value + '/albums'),
+ api<{ usage: NonNullable<typeof usage.value> }>(base.value + '/usage'),
+ ])
+ if (
+ generation !== reloadGeneration ||
+ entryContext.value?.scope !== snapshot
+ )
+ return
+ usage.value = u.usage
+ connections.value = s.connections
+ photos.value = p.photos
+ jobs.value = p.jobs
+ albums.value = a.albums
+ if (!connectionId.value) connectionId.value = s.connections[0]?.id ?? ''
+ } catch (error) {
+ if (
+ generation !== reloadGeneration ||
+ entryContext.value?.scope !== snapshot
+ )
+ return
+ failed.value = true
+ message.value =
+ (error as { statusCode?: number }).statusCode === 503
+ ? 'Media services need deployment configuration. Your existing site settings are available.'
+ : 'Could not refresh media. Check your access and retry.'
+ canPoll.value = false
+ } finally {
+ if (generation === reloadGeneration) loading.value = false
+ }
+ }
+ function refreshMedia() {
+ canPoll.value = true
+ void reload()
+ }
+ async function action(run: () => Promise<unknown>, success: string) {
+ if (busy.value) return
+ busy.value = true
+ message.value = ''
+ failed.value = false
+ try {
+ await run()
+ message.value = success
+ canPoll.value = true
+ await reload()
+ return !failed.value
+ } catch (error) {
+ failed.value = true
+ const code = (error as { statusCode?: number }).statusCode
+ const diagnostic = (error as { data?: { data?: { code?: string } } }).data
+ ?.data?.code
+ message.value =
+ diagnostic && Object.hasOwn(STORAGE_CONNECTION_MESSAGES, diagnostic)
+ ? STORAGE_CONNECTION_MESSAGES[
+ diagnostic as keyof typeof STORAGE_CONNECTION_MESSAGES
+ ]
+ : code === 503
+ ? 'Media services need deployment configuration. Check the selected environment settings.'
+ : code === 409
+ ? 'This item changed. Refresh and try again.'
+ : code === 429
+ ? 'The preview resource limit has been reached.'
+ : code === 403
+ ? 'Administrator access is required.'
+ : 'The operation failed. Check the entered values and your connection, then retry.'
+ return false
+ } finally {
+ busy.value = false
+ }
+ }
+ async function saveStorage() {
+ await action(async () => {
+ await api(base.value + '/storage', { method: 'POST', body: storage })
+ storage.accessKeyId = ''
+ storage.secretAccessKey = ''
+ }, 'Storage connected and verified.')
+ }
+ async function rotateStorage() {
+ const selected = connections.value.find((c) => c.id === connectionId.value)
+ if (!selected) return
+ await action(async () => {
+ await api(base.value + '/storage/' + selected.id + '/rotate', {
+ method: 'POST',
+ body: { revision: selected.current_revision, ...rotation },
+ })
+ rotation.accessKeyId = ''
+ rotation.secretAccessKey = ''
+ }, 'Credentials rotated. Existing media references remain available.')
+ }
+ const photoLoaded = ref('')
+ let photoLoadGeneration = 0
+ async function loadPhoto() {
+ const id = editPhoto.id,
+ generation = ++photoLoadGeneration
+ photoLoaded.value = ''
+ editPhoto.title = ''
+ editPhoto.description = ''
+ if (!id) return
+ try {
+ const data = await api<{ photo: Photo; revision: number }>(
+ base.value + '/photos/' + id,
+ )
+ if (editPhoto.id !== id || generation !== photoLoadGeneration) return
+ editPhoto.title = data.photo.title ?? 'Untitled photograph'
+ editPhoto.description = data.photo.description ?? ''
+ editPhoto.tags = data.photo.tags ?? []
+ editPhoto.rating =
+ typeof data.photo.exif?.Rating === 'number'
+ ? data.photo.exif.Rating
+ : null
+ editPhoto.revision = data.revision
+ photoLoaded.value = id
+ } catch {
+ if (editPhoto.id !== id || generation !== photoLoadGeneration) return
+ failed.value = true
+ message.value =
+ 'Could not load photograph settings. Select it again to retry.'
+ }
+ }
+ async function savePhoto() {
+ if (!editPhoto.id || photoLoaded.value !== editPhoto.id) return
+ const saved = await action(
+ () =>
+ api(base.value + '/photos/' + editPhoto.id, {
+ method: 'PATCH',
+ body: {
+ title: editPhoto.title,
+ description: editPhoto.description || null,
+ revision: editPhoto.revision,
+ tags: editPhoto.tags,
+ rating: editPhoto.rating,
+ },
+ }),
+ 'Photograph updated.',
+ )
+ if (saved) await loadPhoto()
+ return saved
+ }
+ function resumeKey(file: File) {
+ return [
+ 'chronoframe-upload',
+ context.value?.scope,
+ props.siteId,
+ file.name,
+ file.size,
+ file.lastModified,
+ connectionId.value,
+ ].join(':')
+ }
+ async function sendFile(file: File, liveVideo?: File) {
+ const cache = resumeKey(file),
+ id = localStorage.getItem(cache) || crypto.randomUUID()
+ await api(base.value + '/uploads', {
+ method: 'POST',
+ body: {
+ requestId: id,
+ connectionId: connectionId.value,
+ fileName: file.name,
+ bytes: file.size,
+ ...(liveVideo
+ ? { liveVideo: { fileName: liveVideo.name, bytes: liveVideo.size } }
+ : {}),
+ },
+ })
+ localStorage.setItem(cache, id)
+ activeResumeKey = cache
+ if (controller?.signal.aborted) {
+ await api(base.value + '/uploads/' + id + '/cancel', {
+ method: 'POST',
+ body: {},
+ }).catch(() => {})
+ localStorage.removeItem(cache)
+ throw new Error('cancelled')
+ }
+ activeUpload = id
+ const plan = await api<{
+ state: string
+ mode?: string
+ url?: string
+ contentType?: string
+ videoUrl?: string | null
+ partBytes?: number
+ parts?: { partNumber: number; bytes: number }[]
+ urls?: string[]
+ }>(base.value + '/uploads/' + id + '/plan', { method: 'POST', body: {} })
+ if (plan.state === 'completed') {
+ localStorage.removeItem(cache)
+ return
+ }
+ if (plan.state !== 'pending' || !plan.mode) {
+ localStorage.removeItem(cache)
+ activeResumeKey = undefined
+ activeUpload = undefined
+ throw new Error('Upload unavailable')
+ }
+ async function put(url: string, body: Blob, type?: string) {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ controller?.signal.throwIfAborted()
+ const response = await fetch(url, {
+ method: 'PUT',
+ body,
+ headers: type ? { 'Content-Type': type } : {},
+ signal: controller?.signal,
+ redirect: 'error',
+ })
+ if (response.ok) return
+ if (attempt === 2) throw new Error('Upload failed')
+ await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt))
+ }
+ }
+ if (plan.mode === 'single') await put(plan.url!, file, plan.contentType)
+ else {
+ const partBytes = plan.partBytes!,
+ count = plan.urls!.length
+ for (let i = 0; i < count; i++) {
+ const start = i * partBytes,
+ end = Math.min(file.size, start + partBytes)
+ if (
+ !plan.parts?.some(
+ (p) => p.partNumber === i + 1 && p.bytes === end - start,
+ )
+ )
+ await put(plan.urls![i]!, file.slice(start, end))
+ progress.value = Math.round((end / file.size) * 100)
+ }
+ }
+ if (liveVideo && plan.videoUrl)
+ await put(plan.videoUrl, liveVideo, 'video/quicktime')
+ progress.value = 100
+ await api(base.value + '/uploads/' + id + '/complete', {
+ method: 'POST',
+ body: {},
+ })
+ localStorage.removeItem(cache)
+ activeUpload = undefined
+ }
+ async function upload(event: Event) {
+ const input = event.target as HTMLInputElement,
+ files = Array.from(input.files ?? [])
+ if (!files.length || uploading.value || !connectionId.value) return
+ if (
+ files.some((f) => f.size > 100 * 1024 * 1024) ||
+ files.every((f) => f.name.toLowerCase().endsWith('.mov'))
+ ) {
+ failed.value = true
+ message.value =
+ 'Choose photographs under 100 MB. A Live Photo MOV must accompany a photograph with the same filename.'
+ input.value = ''
+ return
+ }
+ uploading.value = true
+ failed.value = false
+ message.value = ''
+ controller = new AbortController()
+ try {
+ for (const file of files.filter(
+ (f) => !f.name.toLowerCase().endsWith('.mov'),
+ )) {
+ const companion = files.find(
+ (f) =>
+ f.name.toLowerCase().endsWith('.mov') &&
+ f.name.replace(/\.[^.]+$/, '').toLowerCase() ===
+ file.name.replace(/\.[^.]+$/, '').toLowerCase(),
+ )
+ currentFile.value = file.name
+ progress.value = 0
+ await sendFile(file, companion)
+ }
+ message.value = 'Upload verified. Processing continues in the background.'
+ } catch {
+ failed.value = true
+ message.value = controller.signal.aborted
+ ? 'Upload cancelled.'
+ : 'Upload interrupted. Select the same file to resume its uploaded parts.'
+ } finally {
+ uploading.value = false
+ input.value = ''
+ currentFile.value = ''
+ await reload()
+ }
+ }
+ async function cancel() {
+ controller?.abort()
+ if (activeResumeKey) localStorage.removeItem(activeResumeKey)
+ activeResumeKey = undefined
+ if (activeUpload)
+ await api(base.value + '/uploads/' + activeUpload + '/cancel', {
+ method: 'POST',
+ body: {},
+ }).catch(() => {})
+ activeUpload = undefined
+ }
+ async function removePhoto(id: string) {
+ if (
+ !window.confirm(
+ 'Delete this photograph and its managed original, thumbnail and Live Photo files from storage?',
+ )
+ )
+ return
+ await action(
+ () =>
+ api(base.value + '/photos/' + id + '/delete', {
+ method: 'POST',
+ body: {},
+ }),
+ 'Photograph deleted. Managed storage files are queued for cleanup.',
+ )
+ }
+ async function publish(value: boolean) {
+ await action(
+ async () => {
+ const settings = await api<{ site: { revision: number } }>(
+ `/api/sites/${props.siteId}/settings`,
+ )
+ const result = await api<{ published: boolean }>(
+ base.value + '/publish',
+ {
+ method: 'POST',
+ body: { revision: settings.site.revision, published: value },
+ },
+ )
+ if (context.value?.siteId === props.siteId)
+ context.value.published = result.published
+ },
+ value ? 'Gallery published.' : 'Gallery unpublished.',
+ )
+ }
+ onMounted(() => {
+ void reload()
+ timer = setInterval(() => {
+ if (canPoll.value && !busy.value && !uploading.value) void reload()
+ }, 5000)
+ })
+ onBeforeUnmount(() => {
+ reloadGeneration++
+ if (timer) clearInterval(timer)
+ controller?.abort()
+ })
+
+ return {
+ photos,
+ albums,
+ jobs,
+ connections,
+ usage,
+ rotation,
+ editPhoto,
+ connectionId,
+ message,
+ failed,
+ busy,
+ uploading,
+ progress,
+ currentFile,
+ storage,
+ admin,
+ photoLoaded,
+ action,
+ reload,
+ refreshMedia,
+ saveStorage,
+ rotateStorage,
+ loadPhoto,
+ savePhoto,
+ upload,
+ cancel,
+ removePhoto,
+ publish,
+ base,
+ api,
+ loading,
+ uploadOpen,
+ }
+}
+const cloudMediaKey = Symbol('cloud-media-workspace')
+export function provideCloudSiteMedia(props: {
+ siteId: number
+ role?: string
+}) {
+ const media = useCloudMediaWorkspace(props)
+ provide(cloudMediaKey, media)
+ return media
+}
+export function useCloudSiteMedia() {
+ const media = inject<ReturnType<typeof useCloudMediaWorkspace>>(cloudMediaKey)
+ if (!media) throw new Error('Site media workspace missing')
+ return media
+}
diff --git a/apps/cloud/app/composables/useCloudSiteSubscription.ts b/apps/cloud/app/composables/useCloudSiteSubscription.ts
new file mode 100644
index 00000000..76df7d2f
--- /dev/null
+++ b/apps/cloud/app/composables/useCloudSiteSubscription.ts
@@ -0,0 +1,62 @@
+import type { EntrySiteContext } from '@chronoframe/contracts/entry'
+/** Persist one membership-checked stream across sibling site pages. */
+export function useCloudSiteSubscription() {
+ const context = useEntryContext(),
+ fetcher = useRequestFetch()
+ let stream: EventSource | undefined,
+ mounted = false
+ function connect() {
+ stream?.close()
+ const snapshot = context.value
+ if (
+ !mounted ||
+ !snapshot?.capabilities.subscriptions ||
+ snapshot.audience !== 'portal'
+ )
+ return
+ const current = new EventSource(`/api/sites/${snapshot.siteId}/events`)
+ stream = current
+ const invalidate = () => {
+ current.close()
+ if (
+ mounted &&
+ stream === current &&
+ context.value?.scope === snapshot.scope
+ ) {
+ context.value = null
+ void navigateTo('/sites')
+ }
+ }
+ const update = (next: EntrySiteContext) => {
+ if (
+ !mounted ||
+ stream !== current ||
+ context.value?.scope !== snapshot.scope
+ )
+ return
+ if (next.scope !== snapshot.scope) return invalidate()
+ context.value = next
+ }
+ stream.addEventListener('context', (event) => {
+ try {
+ update(JSON.parse((event as MessageEvent).data))
+ } catch {
+ invalidate()
+ }
+ })
+ stream.onerror = () => {
+ void fetcher<EntrySiteContext>(`/api/sites/${snapshot.siteId}/context`)
+ .then(update)
+ .catch(invalidate)
+ }
+ }
+ watch(() => context.value?.scope, connect, { flush: 'sync' })
+ onMounted(() => {
+ mounted = true
+ connect()
+ })
+ onBeforeUnmount(() => {
+ mounted = false
+ stream?.close()
+ })
+}
diff --git a/apps/cloud/app/composables/usePortalIdentity.ts b/apps/cloud/app/composables/usePortalIdentity.ts
new file mode 100644
index 00000000..30aadaee
--- /dev/null
+++ b/apps/cloud/app/composables/usePortalIdentity.ts
@@ -0,0 +1,8 @@
+export interface PortalIdentity {
+ id: number
+ name?: string | null
+ email?: string
+}
+export function usePortalIdentity() {
+ return useState<PortalIdentity | null>('platform-current-user', () => null)
+}
diff --git a/apps/cloud/app/layouts/portal.vue b/apps/cloud/app/layouts/portal.vue
new file mode 100644
index 00000000..c14c53a6
--- /dev/null
+++ b/apps/cloud/app/layouts/portal.vue
@@ -0,0 +1,3 @@
+<template>
+ <CloudPortalShell><slot /></CloudPortalShell>
+</template>
diff --git a/apps/cloud/app/middleware/platform.global.ts b/apps/cloud/app/middleware/platform.global.ts
index c4f29fb8..8304df25 100644
--- a/apps/cloud/app/middleware/platform.global.ts
+++ b/apps/cloud/app/middleware/platform.global.ts
@@ -5,7 +5,8 @@ import type {
export default defineNuxtRouteMiddleware(async (to) => {
const path = to.path.toLowerCase()
const context = useEntryContext()
- const detail = /^\/sites\/([1-9][0-9]*)$/.exec(path)
+ const detail =
+ /^\/sites\/([1-9][0-9]*)(?:\/(?:photos|albums|settings))?$/.exec(path)
if (
!detail ||
context.value?.siteId !== Number(detail[1]) ||
@@ -37,13 +38,14 @@ export default defineNuxtRouteMiddleware(async (to) => {
const fetcher = useRequestFetch()
const session = await fetcher<{
authenticated: boolean
- user: { id: number } | null
+ user: { id: number; name?: string | null; email?: string } | null
}>('/api/auth/session').catch((error) => {
if ([401, 403].includes(error.statusCode ?? error.status))
return { authenticated: false, user: null }
context.value = null
throw error
})
+ usePortalIdentity().value = session.user
useState<number | null>('platform-user-id', () => null).value =
session.user?.id ?? null
if (!session.authenticated || !session.user) {
@@ -55,13 +57,20 @@ export default defineNuxtRouteMiddleware(async (to) => {
catalog.value = { userId: session.user.id, sites: result.sites }
}
if (path.startsWith('/sites/')) {
- const match = /^\/sites\/([1-9][0-9]*)$/.exec(path)
+ const match =
+ /^\/sites\/([1-9][0-9]*)(?:\/(?:photos|albums|settings))?$/.exec(path)
if (!match)
return abortNavigation(
createError({ statusCode: 404, statusMessage: 'Page not found' }),
)
try {
context.value = await fetcher(`/api/sites/${match[1]}/context`)
+ // Resolve legacy URLs before mounting a nested page/Suspense boundary.
+ if (path === `/sites/${match[1]}`)
+ return navigateTo(`/sites/${match[1]}/photos`, {
+ replace: true,
+ redirectCode: 302,
+ })
} catch (error) {
context.value = null
return abortNavigation(error as Error)
diff --git a/apps/cloud/app/pages/account/index.vue b/apps/cloud/app/pages/account/index.vue
index 9ca49e87..84beff29 100644
--- a/apps/cloud/app/pages/account/index.vue
+++ b/apps/cloud/app/pages/account/index.vue
@@ -1,84 +1,47 @@
<script setup lang="ts">
-import { motion } from 'motion-v'
-import { ShieldCheck, ArrowRight, LogOut } from 'lucide-vue-next'
-const entrance = useCloudMotion()
-const { busy, error, signOut } = useCloudSignOut()
-useSeoMeta({ title: 'Your account — ChronoFrame Cloud', robots: 'noindex' })
-const { data: security } = await useFetch('/api/auth/security')
+import { ShieldCheck } from 'lucide-vue-next'
+definePageMeta({ layout: 'portal' })
+useSeoMeta({
+ title: 'Account & security — ChronoFrame Cloud',
+ robots: 'noindex',
+})
+const user = usePortalIdentity()
</script>
<template>
- <CloudPortalShell
- ><motion.div v-bind="entrance"
- ><div class="cf-page-heading">
- <div>
- <h1 class="cf-page-title">Your account</h1>
- <p class="cf-page-description">
- Your profile, preferences and session.
- </p>
- </div>
- <CloudBadge tone="success"
- ><ShieldCheck :size="12" />Email verified</CloudBadge
- >
+ <div class="cf-account-page">
+ <div class="cf-page-heading">
+ <div>
+ <h1 class="cf-page-title">Account &amp; security</h1>
+ <p class="cf-page-description">
+ Your profile, preferences and sign-in methods.
+ </p>
</div>
+ </div>
+ <section aria-labelledby="profile-heading">
+ <h2
+ id="profile-heading"
+ class="cf-section-title"
+ >
+ Profile
+ </h2>
<CloudCard class="cf-settings-card"
><div class="cf-setting-row">
<div>
- <h2>Email address</h2>
- <p>{{ security?.email }}</p>
+ <h3>Email address</h3>
+ <p>{{ user?.email }}</p>
</div>
- <CloudButton
- as-child
- variant="secondary"
- size="sm"
- ><NuxtLink to="/account/security"
- >Security settings <ArrowRight :size="14" /></NuxtLink
- ></CloudButton>
- </div>
- <div class="cf-setting-row">
- <div>
- <h2>Your sites</h2>
- <p>Find the galleries you have access to.</p>
- </div>
- <CloudButton
- as-child
- variant="secondary"
- size="sm"
- ><NuxtLink to="/sites"
- >View sites <ArrowRight :size="14" /></NuxtLink
- ></CloudButton>
+ <CloudBadge tone="success"
+ ><ShieldCheck :size="12" />Verified</CloudBadge
+ >
</div>
<div class="cf-setting-row">
<div>
- <h2>Appearance</h2>
+ <h3>Appearance</h3>
<p>Choose the light that suits you.</p>
</div>
<CloudThemeToggle /></div
></CloudCard>
- <CloudCard class="cf-settings-card"
- ><div class="cf-setting-row">
- <div>
- <h2>Sign out</h2>
- <p>End your current session on this browser.</p>
- </div>
- <CloudButton
- variant="destructive"
- :loading="busy"
- @click="signOut"
- ><LogOut
- v-if="!busy"
- :size="15"
- />Sign out</CloudButton
- >
- </div></CloudCard
- >
- <p
- v-if="error"
- class="cf-error-message"
- role="alert"
- style="margin-top: 16px"
- >
- {{ error }}
- </p>
- </motion.div></CloudPortalShell
- >
+ </section>
+ <CloudSecuritySettings />
+ </div>
</template>
diff --git a/apps/cloud/app/pages/account/security.vue b/apps/cloud/app/pages/account/security.vue
index 0e619e1f..4fb12346 100644
--- a/apps/cloud/app/pages/account/security.vue
+++ b/apps/cloud/app/pages/account/security.vue
@@ -1,363 +1,5 @@
<script setup lang="ts">
-import { accountError } from '../../utils/account-error'
-useSeoMeta({ title: 'Account security — ChronoFrame Cloud', robots: 'noindex' })
-const { data: security, refresh } = await useFetch<{
- email: string
- hasPassword: boolean
- twoFactorEnabled: boolean
- hasAuthenticator: boolean
- passkeys: { id: number; name: string | null; createdAt: string }[]
-}>('/api/auth/security')
-const password = ref(''),
- newPassword = ref(''),
- code = ref(''),
- passkeyName = ref('')
-const busy = ref(false),
- error = ref(''),
- notice = ref(''),
- qr = ref(''),
- totpURI = ref(''),
- backupCodes = ref<string[]>([])
-async function run(action: () => Promise<void>) {
- if (busy.value) return
- busy.value = true
- error.value = ''
- notice.value = ''
- try {
- await action()
- await refresh()
- } catch (cause) {
- error.value = accountError(cause)
- } finally {
- busy.value = false
- }
-}
-async function changePassword() {
- await run(async () => {
- await $fetch('/api/auth/change-password', {
- method: 'POST',
- body: {
- currentPassword: password.value,
- newPassword: newPassword.value,
- revokeOtherSessions: true,
- },
- })
- newPassword.value = ''
- password.value = ''
- notice.value = 'Password updated. Other sessions have been signed out.'
- })
-}
-async function enable(method: 'otp' | 'totp') {
- await run(async () => {
- const result = await $fetch<{ totpURI?: string; backupCodes?: string[] }>(
- '/api/auth/two-factor/enable',
- { method: 'POST', body: { password: password.value, method } },
- )
- password.value = ''
- if (result.totpURI) {
- totpURI.value = result.totpURI
- backupCodes.value = result.backupCodes ?? []
- const QRCode = await import('qrcode')
- qr.value = await QRCode.toDataURL(result.totpURI, {
- width: 240,
- margin: 2,
- })
- notice.value =
- 'Scan the QR code, save your recovery codes, and enter a code to finish setup.'
- } else notice.value = 'Email second-step verification is enabled.'
- })
-}
-async function confirmAuthenticator() {
- await run(async () => {
- await $fetch('/api/auth/two-factor/verify-totp', {
- method: 'POST',
- body: { code: code.value },
- })
- code.value = ''
- qr.value = ''
- totpURI.value = ''
- notice.value =
- 'Authenticator verified and enabled. Keep your recovery codes somewhere safe.'
- })
-}
-async function disable() {
- await run(async () => {
- await $fetch('/api/auth/two-factor/disable', {
- method: 'POST',
- body: { password: password.value },
- })
- password.value = ''
- backupCodes.value = []
- qr.value = ''
- totpURI.value = ''
- notice.value = 'Two-step verification has been disabled.'
- })
-}
-async function regenerate() {
- await run(async () => {
- const result = await $fetch<{ backupCodes: string[] }>(
- '/api/auth/two-factor/generate-backup-codes',
- { method: 'POST', body: { password: password.value } },
- )
- backupCodes.value = result.backupCodes
- password.value = ''
- notice.value =
- 'New recovery codes generated. Your previous codes no longer work.'
- })
-}
-async function addPasskey() {
- await run(async () => {
- const result = await useCloudAccount().passkey.addPasskey({
- name: passkeyName.value.trim() || 'My passkey',
- })
- if (result.error) throw result.error
- passkeyName.value = ''
- notice.value =
- 'Passkey created. Its private key stays on your device or password manager.'
- })
-}
-async function deletePasskey(id: number) {
- await run(async () => {
- await $fetch('/api/auth/passkey/delete-passkey', {
- method: 'POST',
- body: { id: String(id) },
- })
- notice.value = 'Passkey removed.'
- })
-}
+definePageMeta({ layout: 'portal' })
+await navigateTo('/account#security', { redirectCode: 302 })
</script>
-<template>
- <CloudPortalShell
- ><div class="cf-page-heading">
- <div>
- <h1 class="cf-page-title">Security</h1>
- <p class="cf-page-description">
- Manage sign-in methods for {{ security?.email }}.
- </p>
- </div>
- </div>
- <p
- v-if="error"
- class="cf-error-message"
- role="alert"
- >
- {{ error }}
- </p>
- <p
- v-if="notice"
- class="cf-notice"
- role="status"
- >
- {{ notice }}
- </p>
- <CloudCard class="cf-security-card"
- ><div class="cf-settings-intro">
- <h2>Password</h2>
- <p>Use a unique password with at least 12 characters.</p>
- </div>
- <div class="cf-settings-body">
- <form
- v-if="security?.hasPassword"
- @submit.prevent="changePassword"
- >
- <label for="current-password">Current password</label
- ><CloudInput
- id="current-password"
- v-model="password"
- type="password"
- autocomplete="current-password"
- :disabled="busy"
- required
- /><label for="new-password">New password</label
- ><CloudInput
- id="new-password"
- v-model="newPassword"
- type="password"
- autocomplete="new-password"
- minlength="12"
- maxlength="128"
- :disabled="busy"
- required
- /><CloudButton
- type="submit"
- :loading="busy"
- >Update password</CloudButton
- >
- </form>
- <p v-else>
- You signed in with an email code.
- <NuxtLink
- class="cf-text-link"
- to="/forgot-password"
- >Email yourself a link to set a password</NuxtLink
- >
- before enabling two-step verification.
- </p>
- </div></CloudCard
- >
- <CloudCard class="cf-security-card"
- ><div class="cf-settings-intro">
- <div>
- <h2>Two-step verification</h2>
- <p>
- Add a code after password sign-in. Connected authenticators also
- protect email-code sign-in. Passkeys use device verification.
- </p>
- </div>
- <CloudBadge
- :tone="security?.twoFactorEnabled ? 'success' : 'neutral'"
- >{{ security?.twoFactorEnabled ? 'Enabled' : 'Off' }}</CloudBadge
- >
- </div>
- <div class="cf-settings-body">
- <template v-if="security?.hasPassword"
- ><label for="security-password"
- >Confirm your password to change security settings</label
- ><CloudInput
- id="security-password"
- v-model="password"
- type="password"
- autocomplete="current-password"
- :disabled="busy"
- />
- <div class="cf-security-actions">
- <CloudButton
- v-if="!security.twoFactorEnabled"
- :disabled="busy || !password"
- @click="enable('otp')"
- >Enable email verification</CloudButton
- ><CloudButton
- v-if="!security.hasAuthenticator"
- variant="secondary"
- :disabled="busy || !password"
- @click="enable('totp')"
- >Set up authenticator</CloudButton
- ><CloudButton
- v-if="security.twoFactorEnabled"
- variant="destructive"
- :disabled="busy || !password"
- @click="disable"
- >Disable two-step verification</CloudButton
- >
- </div>
- <div
- v-if="totpURI"
- class="cf-totp-setup"
- >
- <img
- v-if="qr"
- :src="qr"
- width="240"
- height="240"
- alt="Scan this private QR code with your authenticator app"
- />
- <details>
- <summary>Cannot scan the QR code?</summary>
- <p class="cf-secret-value">{{ totpURI }}</p>
- </details>
- <form @submit.prevent="confirmAuthenticator">
- <label for="totp-code">Authenticator code</label
- ><CloudInput
- id="totp-code"
- v-model="code"
- inputmode="numeric"
- autocomplete="one-time-code"
- pattern="[0-9]{6}"
- maxlength="6"
- required
- :disabled="busy"
- /><CloudButton
- type="submit"
- :loading="busy"
- >Verify and enable</CloudButton
- >
- </form>
- </div>
- <div v-if="security.hasAuthenticator">
- <p>
- Authenticator connected. Recovery codes are single use. Generating
- new codes replaces the old ones.
- </p>
- <CloudButton
- variant="secondary"
- :disabled="busy || !password"
- @click="regenerate"
- >Replace recovery codes</CloudButton
- >
- </div>
- <div
- v-if="backupCodes.length"
- class="cf-notice"
- >
- <strong>Save these recovery codes privately.</strong>
- <p>These are only shown here. Keep them outside this browser.</p>
- <ul class="cf-recovery-codes">
- <li
- v-for="item in backupCodes"
- :key="item"
- >
- <code>{{ item }}</code>
- </li>
- </ul>
- <CloudButton
- variant="secondary"
- @click="backupCodes = []"
- >I have saved my codes</CloudButton
- >
- </div></template
- >
- </div></CloudCard
- >
- <CloudCard class="cf-security-card"
- ><div class="cf-settings-intro">
- <h2>Passkeys</h2>
- <p>
- Use your device lock, fingerprint or security key. Your device creates
- the keys automatically.
- </p>
- </div>
- <div class="cf-settings-body">
- <form @submit.prevent="addPasskey">
- <label for="passkey-name">Passkey name</label
- ><CloudInput
- id="passkey-name"
- v-model="passkeyName"
- maxlength="80"
- autocomplete="off"
- placeholder="For example, my laptop"
- :disabled="busy"
- /><CloudButton
- type="submit"
- :loading="busy"
- >Create passkey</CloudButton
- >
- </form>
- <ul
- v-if="security?.passkeys.length"
- class="cf-passkey-list"
- >
- <li
- v-for="key in security.passkeys"
- :key="key.id"
- >
- <span>{{ key.name || 'Passkey' }}</span
- ><CloudButton
- variant="destructive"
- size="sm"
- :disabled="busy"
- :aria-label="`Remove ${key.name || 'passkey'}`"
- @click="deletePasskey(key.id)"
- >Remove</CloudButton
- >
- </li>
- </ul>
- <p
- v-else
- class="cf-auth-hint"
- >
- No passkeys yet.
- </p>
- </div></CloudCard
- ></CloudPortalShell
- >
-</template>
+<template><div /></template>
diff --git a/apps/cloud/app/pages/sites/[siteId].vue b/apps/cloud/app/pages/sites/[siteId].vue
new file mode 100644
index 00000000..7fafa73c
--- /dev/null
+++ b/apps/cloud/app/pages/sites/[siteId].vue
@@ -0,0 +1,14 @@
+<script setup lang="ts">
+definePageMeta({ layout: 'portal' })
+const context = useEntryContext()
+const site = context.value
+if (!site || site.audience !== 'portal') throw createError({ statusCode: 404 })
+</script>
+<template>
+ <CloudSiteWorkspace
+ :key="site.scope"
+ :site-id="site.siteId"
+ :role="site.role"
+ ><NuxtPage
+ /></CloudSiteWorkspace>
+</template>
diff --git a/apps/cloud/app/pages/sites/[siteId]/albums.vue b/apps/cloud/app/pages/sites/[siteId]/albums.vue
new file mode 100644
index 00000000..a63116e6
--- /dev/null
+++ b/apps/cloud/app/pages/sites/[siteId]/albums.vue
@@ -0,0 +1,5 @@
+<script setup lang="ts">
+definePageMeta({ layout: 'portal' })
+useSeoMeta({ title: 'Albums — ChronoFrame Cloud', robots: 'noindex' })
+</script>
+<template><CloudAlbumsManager /></template>
diff --git a/apps/cloud/app/pages/sites/[siteId]/index.vue b/apps/cloud/app/pages/sites/[siteId]/index.vue
index 8deb28a3..dc92c83e 100644
--- a/apps/cloud/app/pages/sites/[siteId]/index.vue
+++ b/apps/cloud/app/pages/sites/[siteId]/index.vue
@@ -1,114 +1,4 @@
<script setup lang="ts">
-import { motion } from 'motion-v'
-import {
- ArrowLeft,
- ArrowUpRight,
- Images,
- ImagePlus,
- ShieldCheck,
-} from 'lucide-vue-next'
-const entrance = useCloudMotion()
-
-import type { EntrySiteContext } from '@chronoframe/contracts/entry'
-definePageMeta({ key: (route) => route.fullPath })
-useSeoMeta({ title: 'Manage site — ChronoFrame Cloud', robots: 'noindex' })
-const context = useEntryContext()
-const fetcher = useRequestFetch()
-let stream: EventSource | undefined
-watch(
- () => context.value?.scope,
- () => stream?.close(),
- { flush: 'sync' },
-)
-onMounted(() => {
- const snapshot = context.value
- if (!snapshot?.capabilities.subscriptions) return
- const invalidate = () => {
- stream?.close()
- if (context.value?.scope !== snapshot.scope) return
- context.value = null
- void navigateTo('/sites')
- }
- const updateContext = (update: EntrySiteContext) => {
- if (context.value?.scope !== snapshot.scope) return
- if (update.scope !== snapshot.scope) return invalidate()
- context.value = update
- }
- stream = new EventSource(`/api/sites/${snapshot.siteId}/events`)
- stream.addEventListener('context', (event) => {
- try {
- updateContext(JSON.parse((event as MessageEvent).data))
- } catch {
- invalidate()
- }
- })
- // A short stream reconnects every 15 seconds and rechecks live membership.
- stream.onerror = () => {
- void fetcher<EntrySiteContext>(`/api/sites/${snapshot.siteId}/context`)
- .then(updateContext)
- .catch(invalidate)
- }
-})
-onBeforeUnmount(() => stream?.close())
+definePageMeta({ layout: 'portal' })
</script>
-<template>
- <CloudPortalShell
- ><motion.div
- v-if="context"
- v-bind="entrance"
- >
- <NuxtLink
- to="/sites"
- class="cf-back-link"
- ><ArrowLeft :size="14" />All sites</NuxtLink
- >
- <div class="cf-page-heading">
- <div class="cf-detail-header">
- <span class="cf-site-icon"><Images :size="20" /></span>
- <div>
- <h1 class="cf-page-title">{{ context.name }}</h1>
- <p class="cf-page-description">Gallery settings and access.</p>
- </div>
- </div>
- <CloudBadge :tone="context.published ? 'success' : 'neutral'">{{
- context.published ? 'Published' : 'Draft'
- }}</CloudBadge>
- </div>
- <dl class="cf-site-facts">
- <div>
- <dt>Your role</dt>
- <dd class="cf-capitalize">{{ context.role }}</dd>
- </div>
- <div>
- <dt>Publication</dt>
- <dd>{{ context.published ? 'Published' : 'Private draft' }}</dd>
- </div>
- <div>
- <dt>Access</dt>
- <dd><ShieldCheck :size="13" />Membership verified</dd>
- </div>
- </dl>
- <div class="cf-site-workbench">
- <CloudSiteSettings :site-id="context.siteId" />
- <aside
- v-if="!context.capabilities.mediaManagement"
- class="cf-workbench-note"
- aria-label="Photo management information"
- >
- <span class="cf-note-icon"><ImagePlus :size="18" /></span>
- <h2>Photo management</h2>
- <p>
- Storage, uploads and new publishing options are coming in the next
- stage.
- </p>
- <a href="https://docs.chronoframe.art/"
- >Read the documentation<ArrowUpRight :size="13"
- /></a>
- </aside>
- </div>
- <CloudMediaWorkbench
- :site-id="context.siteId"
- :role="context.role"
- /> </motion.div
- ></CloudPortalShell>
-</template>
+<template><div /></template>
diff --git a/apps/cloud/app/pages/sites/[siteId]/photos.vue b/apps/cloud/app/pages/sites/[siteId]/photos.vue
new file mode 100644
index 00000000..f77d74bb
--- /dev/null
+++ b/apps/cloud/app/pages/sites/[siteId]/photos.vue
@@ -0,0 +1,5 @@
+<script setup lang="ts">
+definePageMeta({ layout: 'portal' })
+useSeoMeta({ title: 'Photos — ChronoFrame Cloud', robots: 'noindex' })
+</script>
+<template><CloudPhotoLibrary /></template>
diff --git a/apps/cloud/app/pages/sites/[siteId]/settings.vue b/apps/cloud/app/pages/sites/[siteId]/settings.vue
new file mode 100644
index 00000000..72c9c953
--- /dev/null
+++ b/apps/cloud/app/pages/sites/[siteId]/settings.vue
@@ -0,0 +1,13 @@
+<script setup lang="ts">
+definePageMeta({ layout: 'portal' })
+useSeoMeta({ title: 'Site settings — ChronoFrame Cloud', robots: 'noindex' })
+const context = useEntryContext()
+</script>
+<template>
+ <div class="cf-site-settings-stack">
+ <CloudSiteSettings
+ v-if="context"
+ :site-id="context.siteId"
+ /><CloudStorageSettings />
+ </div>
+</template>
diff --git a/apps/cloud/app/pages/sites/index.vue b/apps/cloud/app/pages/sites/index.vue
index 398cec26..39d1784c 100644
--- a/apps/cloud/app/pages/sites/index.vue
+++ b/apps/cloud/app/pages/sites/index.vue
@@ -2,6 +2,7 @@
import { motion } from 'motion-v'
import { ArrowUpRight, Images, ShieldCheck } from 'lucide-vue-next'
const entrance = useCloudMotion()
+definePageMeta({ layout: 'portal' })
const workspace = ref<{ name: string } | null>(null)
const workspaceError = ref(false)
async function prepareWorkspace() {
@@ -30,97 +31,96 @@ const sites = computed(() =>
)
</script>
<template>
- <CloudPortalShell
- ><motion.div v-bind="entrance">
- <div class="cf-page-heading">
- <div>
- <h1 class="cf-page-title">Your sites</h1>
- <p class="cf-page-description">
- Manage your galleries, settings and access.
- </p>
- </div>
- <CloudBadge
- >{{ sites.length }}
- {{ sites.length === 1 ? 'site' : 'sites' }}</CloudBadge
- >
+ <motion.div v-bind="entrance">
+ <div class="cf-page-heading">
+ <div>
+ <h1 class="cf-page-title">Your sites</h1>
+ <p class="cf-page-description">
+ Manage your galleries, settings and access.
+ </p>
</div>
- <div
- v-if="workspaceError"
- class="cf-notice"
- role="alert"
+ <CloudBadge
+ >{{ sites.length }}
+ {{ sites.length === 1 ? 'site' : 'sites' }}</CloudBadge
>
- Your workspace could not be opened.
- <CloudButton
- variant="ghost"
- @click="prepareWorkspace"
- >Try again</CloudButton
- >
- </div>
- <CloudSiteCreate
- v-if="workspace"
- :workspace-name="workspace.name"
- />
+ </div>
+ <div
+ v-if="workspaceError"
+ class="cf-notice"
+ role="alert"
+ >
+ Your workspace could not be opened.
+ <CloudButton
+ variant="ghost"
+ @click="prepareWorkspace"
+ >Try again</CloudButton
+ >
+ </div>
+ <CloudSiteCreate
+ v-if="workspace"
+ :workspace-name="workspace.name"
+ />
+ <div
+ v-if="sites.length"
+ class="cf-sites-table"
+ >
<div
- v-if="sites.length"
- class="cf-sites-table"
+ class="cf-site-columns"
+ aria-hidden="true"
>
- <div
- class="cf-site-columns"
- aria-hidden="true"
+ <span>Site</span><span>Status</span><span>Role</span><span />
+ </div>
+ <ul class="cf-sites-list">
+ <li
+ v-for="site in sites"
+ :key="site.siteId"
>
- <span>Site</span><span>Status</span><span>Role</span><span />
- </div>
- <ul class="cf-sites-list">
- <li
- v-for="site in sites"
- :key="site.siteId"
+ <NuxtLink
+ :to="`/sites/${site.siteId}/photos`"
+ :aria-label="site.name"
+ :aria-describedby="`site-status-${site.siteId} site-role-${site.siteId}`"
+ class="cf-site-row"
>
- <NuxtLink
- :to="`/sites/${site.siteId}`"
- :aria-label="site.name"
- :aria-describedby="`site-status-${site.siteId} site-role-${site.siteId}`"
- class="cf-site-row"
+ <span class="cf-site-identity"
+ ><span class="cf-site-icon"><Images :size="17" /></span
+ ><span
+ class="cf-site-name"
+ :title="site.name"
+ >{{ site.name }}</span
+ ></span
>
- <span class="cf-site-identity"
- ><span class="cf-site-icon"><Images :size="17" /></span
- ><span
- class="cf-site-name"
- :title="site.name"
- >{{ site.name }}</span
- ></span
- >
- <span :id="`site-status-${site.siteId}`"
- ><CloudBadge :tone="site.published ? 'success' : 'neutral'">{{
- site.published ? 'Published' : 'Draft'
- }}</CloudBadge></span
- >
- <span
- :id="`site-role-${site.siteId}`"
- class="cf-site-role cf-capitalize"
- >{{ site.role }}</span
- ><ArrowUpRight
- :size="15"
- class="cf-row-arrow"
- aria-hidden="true"
- />
- </NuxtLink>
- </li>
- </ul>
- </div>
- <CloudCard
- v-else
- class="cf-portal-empty"
- ><span class="cf-site-icon"><Images :size="20" /></span>
- <div>
- <h2>No sites yet</h2>
- <p>Create a draft above to reserve your gallery’s address.</p>
- </div></CloudCard
- >
- <p class="cf-catalog-note">
- <ShieldCheck :size="14" />Only sites you belong to appear here.<a
- href="https://docs.chronoframe.art/"
- >View documentation<ArrowUpRight :size="12"
- /></a>
- </p> </motion.div
- ></CloudPortalShell>
+ <span :id="`site-status-${site.siteId}`"
+ ><CloudBadge :tone="site.published ? 'success' : 'neutral'">{{
+ site.published ? 'Published' : 'Draft'
+ }}</CloudBadge></span
+ >
+ <span
+ :id="`site-role-${site.siteId}`"
+ class="cf-site-role cf-capitalize"
+ >{{ site.role }}</span
+ ><ArrowUpRight
+ :size="15"
+ class="cf-row-arrow"
+ aria-hidden="true"
+ />
+ </NuxtLink>
+ </li>
+ </ul>
+ </div>
+ <CloudCard
+ v-else
+ class="cf-portal-empty"
+ ><span class="cf-site-icon"><Images :size="20" /></span>
+ <div>
+ <h2>No sites yet</h2>
+ <p>Create a draft above to reserve your gallery’s address.</p>
+ </div></CloudCard
+ >
+ <p class="cf-catalog-note">
+ <ShieldCheck :size="14" />Only sites you belong to appear here.<a
+ href="https://docs.chronoframe.art/"
+ >View documentation<ArrowUpRight :size="12"
+ /></a>
+ </p>
+ </motion.div>
</template>
diff --git a/apps/cloud/package.json b/apps/cloud/package.json
index c6ffe643..9487c8d7 100644
--- a/apps/cloud/package.json
+++ b/apps/cloud/package.json
@@ -46,6 +46,7 @@
"tailwind-merge": "^3.7.0",
"vue": "^3.5.43",
"@chronoframe/database": "workspace:*",
- "@chronoframe/storage": "workspace:*"
+ "@chronoframe/storage": "workspace:*",
+ "nuxt-gtag": "4.1.0"
}
}
diff --git a/apps/cloud/server/api/auth/session.get.ts b/apps/cloud/server/api/auth/session.get.ts
index c59d59bb..39be8a02 100644
--- a/apps/cloud/server/api/auth/session.get.ts
+++ b/apps/cloud/server/api/auth/session.get.ts
@@ -1,13 +1,19 @@
import { definePlatformHandler } from '../../../../shared/platform/runtime'
import {
platformPortalOrigin,
+ platformDatabase,
platformSession,
} from '../../../../shared/platform/runtime'
export default definePlatformHandler(async (event) => {
const config = useRuntimeConfig(event).platform
platformPortalOrigin(event, config.portalOrigin)
const session = await platformSession(event, config.secret)
- return session
- ? { authenticated: true, user: { id: session.userId } }
+ if (!session) return { authenticated: false, user: null }
+ const profile = await platformDatabase(event)
+ .prepare('SELECT name,email FROM platform_users WHERE id=?')
+ .bind(session.userId)
+ .first<{ name: string | null; email: string }>()
+ return profile
+ ? { authenticated: true, user: { id: session.userId, ...profile } }
: { authenticated: false, user: null }
})
diff --git a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
index 221b22b6..06c50b98 100644
--- a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
+++ b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts
@@ -1,3 +1,5 @@
+import { deleteCloudPhotos } from '../../../../utils/cloud-photo-delete'
+import { updateCloudAlbum } from '../../../../utils/cloud-album-editor'
import { getRouterParam, createError } from 'h3'
import { definePlatformHandler } from '../../../../../../shared/platform/runtime'
import { cloudMedia, checkStorage } from '../../../../utils/cloud-media'
@@ -40,7 +42,7 @@ export default definePlatformHandler(async (event) => {
const { siteId, userId, site, db, raw, sql, repository, vault } = ctx
const operation = getRouterParam(event, 'operation') ?? ''
const [kind, id, action] = operation.split('/')
- const body = mutation ? await siteManagementBody(event) : {}
+ const body = mutation ? await siteManagementBody(event, 131072) : {}
const now = Date.now()
if (kind === 'storage' && !id) {
if (event.method === 'GET') return { connections: await vault.list() }
@@ -377,14 +379,49 @@ export default definePlatformHandler(async (event) => {
}
if (kind === 'photos' && id && event.method === 'PATCH') {
const title = text(body.title, 255),
- description =
- body.description === null ? null : text(body.description, 2048),
revision = number(body.revision)
+ const row = await raw
+ .prepare(
+ 'SELECT metadata_json FROM cloud_photos WHERE site_id=? AND id=? AND revision=? AND deleted=0 AND metadata_json IS NOT NULL',
+ )
+ .bind(siteId, ID(id), revision)
+ .first<{ metadata_json: string }>()
+ if (!row) throw createError({ statusCode: 409 })
+ const metadata = JSON.parse(row.metadata_json)
+ if (body.description !== undefined) {
+ if (
+ body.description !== null &&
+ (typeof body.description !== 'string' || body.description.length > 2048)
+ )
+ throw createError({ statusCode: 400 })
+ metadata.description = body.description || null
+ }
+ if (body.tags !== undefined) {
+ if (
+ !Array.isArray(body.tags) ||
+ body.tags.length > 32 ||
+ body.tags.some((t) => typeof t !== 'string' || t.length > 64)
+ )
+ throw createError({ statusCode: 400 })
+ metadata.tags = body.tags
+ }
+ if (body.rating !== undefined) {
+ if (
+ body.rating !== null &&
+ (!Number.isInteger(body.rating) ||
+ Number(body.rating) < 1 ||
+ Number(body.rating) > 5)
+ )
+ throw createError({ statusCode: 400 })
+ metadata.exif = { ...metadata.exif }
+ if (body.rating === null) delete metadata.exif.Rating
+ else metadata.exif.Rating = body.rating
+ }
const changed = await raw
.prepare(
- `UPDATE cloud_photos SET title=?,metadata_json=json_set(metadata_json,'$.description',?),revision=revision+1 WHERE site_id=? AND id=? AND revision=? AND deleted=0 AND metadata_json IS NOT NULL RETURNING id`,
+ 'UPDATE cloud_photos SET title=?,metadata_json=?,revision=revision+1 WHERE site_id=? AND id=? AND revision=? AND deleted=0 RETURNING id',
)
- .bind(title, description, siteId, ID(id), revision)
+ .bind(title, JSON.stringify(metadata), siteId, ID(id), revision)
.first()
if (!changed) throw createError({ statusCode: 409 })
return { revision: revision + 1 }
@@ -395,38 +432,10 @@ export default definePlatformHandler(async (event) => {
event.method === 'POST' &&
action === 'delete'
) {
- const found = await raw
- .prepare('SELECT id FROM cloud_photos WHERE site_id=? AND id=?')
- .bind(siteId, ID(id))
- .first()
- if (!found) throw createError({ statusCode: 404 })
- await db.batch([
- db
- .prepare('UPDATE cloud_photos SET deleted=1 WHERE site_id=? AND id=?')
- .bind(siteId, id),
- db
- .prepare(
- "UPDATE cloud_processing_jobs SET state='cancelled' WHERE site_id=? AND photo_id=? AND state IN ('queued','running','retry_wait')",
- )
- .bind(siteId, id),
- db
- .prepare(
- `INSERT INTO cloud_cleanup_requests(site_id,id,connection_id,connection_revision,object_key,provider_upload_id,available_at) SELECT site_id,'original-'||id,connection_id,connection_revision,object_key,NULL,? FROM cloud_uploads WHERE site_id=? AND photo_id=? ON CONFLICT DO NOTHING`,
- )
- .bind(now + 360000, siteId, id),
- db
- .prepare(
- `INSERT INTO cloud_cleanup_requests(site_id,id,connection_id,connection_revision,object_key,provider_upload_id,available_at) SELECT site_id,'video-'||id,connection_id,connection_revision,video_key,NULL,? FROM cloud_uploads WHERE site_id=? AND photo_id=? AND video_key IS NOT NULL ON CONFLICT DO NOTHING`,
- )
- .bind(now + 360000, siteId, id),
- db
- .prepare(
- `INSERT INTO cloud_cleanup_requests(site_id,id,connection_id,connection_revision,object_key,provider_upload_id,available_at) SELECT site_id,'asset-'||photo_id||'-'||role,connection_id,connection_revision,object_key,NULL,? FROM cloud_media_assets WHERE site_id=? AND photo_id=? ON CONFLICT DO NOTHING`,
- )
- .bind(now + 360000, siteId, id),
- ])
- return { ok: true }
+ return deleteCloudPhotos(raw, siteId, [ID(id)], now)
}
+ if (kind === 'photos' && id === 'delete-batch' && event.method === 'POST')
+ return deleteCloudPhotos(raw, siteId, body.photoIds, now)
if (kind === 'jobs' && id && action === 'retry' && event.method === 'POST') {
const changed = await raw
.prepare(
@@ -446,7 +455,16 @@ export default definePlatformHandler(async (event) => {
}
if (event.method === 'POST') {
const albumId = String(number(body.id))
- await repository.createAlbum(albumId, text(body.title, 80))
+ const title = text(body.title, 80)
+ if (body.isHidden === true) {
+ const created = await raw
+ .prepare(
+ 'INSERT INTO cloud_albums(site_id,id,title,hidden,created_at,updated_at) SELECT ?,?,?,1,?,? WHERE (SELECT COUNT(*) FROM cloud_albums WHERE site_id=?)<100 ON CONFLICT DO NOTHING RETURNING id',
+ )
+ .bind(siteId, albumId, title, now, now, siteId)
+ .first()
+ if (!created) throw createError({ statusCode: 409 })
+ } else await repository.createAlbum(albumId, title)
return { id: Number(albumId) }
}
}
@@ -460,12 +478,18 @@ export default definePlatformHandler(async (event) => {
if (!(await repository.album(albumId)))
throw createError({ statusCode: 404 })
if (action === 'remove-photo') {
- await raw
- .prepare(
- 'DELETE FROM cloud_album_photos WHERE site_id=? AND album_id=? AND photo_id=?',
- )
- .bind(siteId, albumId, ID(body.photoId))
- .run()
+ await raw.batch([
+ raw
+ .prepare(
+ 'DELETE FROM cloud_album_photos WHERE site_id=? AND album_id=? AND photo_id=?',
+ )
+ .bind(siteId, albumId, ID(body.photoId)),
+ raw
+ .prepare(
+ 'UPDATE cloud_albums SET revision=revision+1,updated_at=? WHERE site_id=? AND id=?',
+ )
+ .bind(now, siteId, albumId),
+ ])
} else if (action === 'delete') {
await raw.batch([
raw
@@ -497,7 +521,13 @@ export default definePlatformHandler(async (event) => {
.bind(siteId, id)
.first<{ revision: number }>()
if (!album || !revision) throw createError({ statusCode: 404 })
- return { album: album.resource, revision: revision.revision }
+ return {
+ album: {
+ ...album.resource,
+ photos: await ctx.resources.listAlbumPhotos(number(Number(id))),
+ },
+ revision: revision.revision,
+ }
}
if (
kind === 'albums' &&
@@ -505,23 +535,75 @@ export default definePlatformHandler(async (event) => {
action === 'settings' &&
event.method === 'PATCH'
) {
- const revision = number(body.revision),
- title = text(body.title, 80)
- const changed = await raw
- .prepare(
- 'UPDATE cloud_albums SET title=?,revision=revision+1,updated_at=? WHERE site_id=? AND id=? AND revision=? RETURNING id',
- )
- .bind(title, now, siteId, String(number(Number(id))), revision)
- .first()
- if (!changed) throw createError({ statusCode: 409 })
- return { revision: revision + 1 }
+ return updateCloudAlbum(raw, siteId, number(Number(id)), body)
+ }
+ if (kind === 'albums' && id === 'reorder' && event.method === 'POST') {
+ if (
+ !Array.isArray(body.albumIds) ||
+ body.albumIds.length > 100 ||
+ body.albumIds.some((v) => !Number.isSafeInteger(v) || Number(v) < 1) ||
+ new Set(body.albumIds).size !== body.albumIds.length
+ )
+ throw createError({ statusCode: 400 })
+ const rows = await sql<{ id: string }>(
+ 'SELECT id FROM cloud_albums WHERE site_id=?',
+ siteId,
+ )
+ if (
+ rows.length !== body.albumIds.length ||
+ rows.some((row) => !(body.albumIds as number[]).includes(Number(row.id)))
+ )
+ throw createError({ statusCode: 409 })
+ await raw.batch(
+ body.albumIds.map((album, index) =>
+ raw
+ .prepare(
+ 'UPDATE cloud_albums SET position=? WHERE site_id=? AND id=?',
+ )
+ .bind(index, siteId, String(album)),
+ ),
+ )
+ return { ok: true }
}
if (kind === 'albums' && id && event.method === 'POST') {
const albumId = String(number(Number(id))),
album = await repository.album(albumId)
if (!album) throw createError({ statusCode: 404 })
if (action === 'photos') {
- await repository.addToAlbum(albumId, ID(body.photoId))
+ {
+ const ids = Array.isArray(body.photoIds)
+ ? body.photoIds
+ : [ID(body.photoId)]
+ if (
+ !ids.length ||
+ ids.length > 1000 ||
+ ids.some(
+ (v) => typeof v !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(v),
+ )
+ )
+ throw createError({ statusCode: 400 })
+ const values = JSON.stringify([...new Set(ids)])
+ const ready = await raw
+ .prepare(
+ `SELECT COUNT(*) AS total FROM cloud_photos p WHERE p.site_id=? AND p.id IN (SELECT value FROM json_each(?)) AND p.deleted=0 AND p.metadata_json IS NOT NULL AND EXISTS(SELECT 1 FROM cloud_processing_jobs j WHERE j.site_id=p.site_id AND j.photo_id=p.id AND j.source_version=p.source_version AND j.state='succeeded')`,
+ )
+ .bind(siteId, values)
+ .first<{ total: number }>()
+ if (ready?.total !== new Set(ids).size)
+ throw createError({ statusCode: 400 })
+ await raw.batch([
+ raw
+ .prepare(
+ `INSERT INTO cloud_album_photos(site_id,album_id,photo_id,position) SELECT ?,?,value,CAST(key AS INTEGER)+COALESCE((SELECT MAX(position)+1 FROM cloud_album_photos WHERE site_id=? AND album_id=?),0) FROM json_each(?) WHERE true ON CONFLICT DO NOTHING`,
+ )
+ .bind(siteId, albumId, siteId, albumId, values),
+ raw
+ .prepare(
+ 'UPDATE cloud_albums SET revision=revision+1,updated_at=? WHERE site_id=? AND id=?',
+ )
+ .bind(now, siteId, albumId),
+ ])
+ }
return { ok: true }
}
if (action === 'access') {
@@ -540,7 +622,7 @@ export default definePlatformHandler(async (event) => {
const statements = [
db
.prepare(
- 'UPDATE cloud_albums SET hidden=?,updated_at=? WHERE site_id=? AND id=?',
+ 'UPDATE cloud_albums SET hidden=?,updated_at=?,revision=revision+1 WHERE site_id=? AND id=?',
)
.bind(hidden ? 1 : 0, now, siteId, albumId),
]
diff --git a/apps/cloud/server/utils/cloud-album-editor.ts b/apps/cloud/server/utils/cloud-album-editor.ts
new file mode 100644
index 00000000..b6bcf61f
--- /dev/null
+++ b/apps/cloud/server/utils/cloud-album-editor.ts
@@ -0,0 +1,145 @@
+import { createError } from 'h3'
+import type { platformDatabase } from '../../../shared/platform/runtime'
+type CloudDatabase = ReturnType<typeof platformDatabase>
+import { visitorPasswordHash } from '../../../shared/platform/crypto.ts'
+/** Conditional child writes precede the revision bump in one D1 batch. A stale
+ * editor therefore cannot replace membership or password state before a 409. */
+export async function updateCloudAlbum(
+ db: CloudDatabase,
+ siteId: number,
+ id: number,
+ body: Record<string, unknown>,
+) {
+ const revision = body.revision,
+ title = body.title
+ if (
+ !Number.isSafeInteger(revision) ||
+ Number(revision) < 1 ||
+ typeof title !== 'string' ||
+ !title.trim() ||
+ title.length > 80
+ )
+ throw createError({ statusCode: 400 })
+ const description = body.description
+ if (
+ description !== undefined &&
+ description !== null &&
+ (typeof description !== 'string' || description.length > 2048)
+ )
+ throw createError({ statusCode: 400 })
+ const ids = body.photoIds
+ if (
+ ids !== undefined &&
+ (!Array.isArray(ids) ||
+ ids.length > 1000 ||
+ ids.some(
+ (v) => typeof v !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(v),
+ ) ||
+ new Set(ids).size !== ids.length)
+ )
+ throw createError({ statusCode: 400 })
+ const photoIds = ids as string[] | undefined
+ if (photoIds?.length) {
+ const result = await db
+ .prepare(
+ `SELECT COUNT(*) AS total FROM cloud_photos p WHERE site_id=? AND id IN (SELECT value FROM json_each(?)) AND deleted=0 AND metadata_json IS NOT NULL AND EXISTS(SELECT 1 FROM cloud_processing_jobs j WHERE j.site_id=p.site_id AND j.photo_id=p.id AND j.source_version=p.source_version AND j.state='succeeded')`,
+ )
+ .bind(siteId, JSON.stringify(photoIds))
+ .first<{ total: number }>()
+ if (result?.total !== photoIds.length)
+ throw createError({ statusCode: 400 })
+ }
+ const cover = body.coverPhotoId
+ if (
+ cover !== undefined &&
+ cover !== null &&
+ (typeof cover !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(cover))
+ )
+ throw createError({ statusCode: 400 })
+ if (typeof cover === 'string') {
+ if (photoIds && !photoIds.includes(cover))
+ throw createError({ statusCode: 400 })
+ if (
+ !photoIds &&
+ !(await db
+ .prepare(
+ 'SELECT 1 FROM cloud_album_photos WHERE site_id=? AND album_id=? AND photo_id=?',
+ )
+ .bind(siteId, String(id), cover)
+ .first())
+ )
+ throw createError({ statusCode: 400 })
+ }
+ if (body.isHidden !== undefined && typeof body.isHidden !== 'boolean')
+ throw createError({ statusCode: 400 })
+ const password = body.password
+ if (
+ password !== undefined &&
+ password !== null &&
+ (typeof password !== 'string' ||
+ password.length < 8 ||
+ password.length > 256)
+ )
+ throw createError({ statusCode: 400 })
+ const guard =
+ 'EXISTS(SELECT 1 FROM cloud_albums WHERE site_id=? AND id=? AND revision=?)'
+ const args = [siteId, String(id), Number(revision)]
+ const statements = []
+ if (photoIds) {
+ statements.push(
+ db
+ .prepare(
+ `DELETE FROM cloud_album_photos WHERE site_id=? AND album_id=? AND ${guard}`,
+ )
+ .bind(siteId, String(id), ...args),
+ )
+ statements.push(
+ db
+ .prepare(
+ `INSERT INTO cloud_album_photos(site_id,album_id,photo_id,position) SELECT ?,?,value,CAST(key AS INTEGER) FROM json_each(?) WHERE ${guard}`,
+ )
+ .bind(siteId, String(id), JSON.stringify(photoIds), ...args),
+ )
+ }
+ if (password !== undefined) {
+ if (password === null)
+ statements.push(
+ db
+ .prepare(
+ `DELETE FROM platform_album_access WHERE site_id=? AND album_id=? AND ${guard}`,
+ )
+ .bind(siteId, id, ...args),
+ )
+ else {
+ const salt = crypto.randomUUID(),
+ hash = await visitorPasswordHash(password as string, salt)
+ statements.push(
+ db
+ .prepare(
+ `INSERT INTO platform_album_access(site_id,album_id,revision,salt,password_hash) SELECT ?,?,?,?,? WHERE ${guard} ON CONFLICT(site_id,album_id) DO UPDATE SET revision=excluded.revision,salt=excluded.salt,password_hash=excluded.password_hash`,
+ )
+ .bind(siteId, id, crypto.randomUUID(), salt, hash, ...args),
+ )
+ }
+ }
+ statements.push(
+ db
+ .prepare(
+ `UPDATE cloud_albums SET title=?,description=CASE WHEN ? THEN ? ELSE description END,cover_photo_id=CASE WHEN ? THEN ? ELSE cover_photo_id END,hidden=CASE WHEN ? THEN ? ELSE hidden END,updated_at=?,revision=revision+1 WHERE site_id=? AND id=? AND revision=?`,
+ )
+ .bind(
+ title.trim(),
+ description !== undefined ? 1 : 0,
+ description ?? null,
+ cover !== undefined ? 1 : 0,
+ cover ?? null,
+ body.isHidden !== undefined ? 1 : 0,
+ body.isHidden ? 1 : 0,
+ Date.now(),
+ ...args,
+ ),
+ )
+ const results = await db.batch(statements)
+ if (results.at(-1)?.meta.changes !== 1) throw createError({ statusCode: 409 })
+ return { revision: Number(revision) + 1 }
+}
diff --git a/apps/cloud/server/utils/cloud-photo-delete.ts b/apps/cloud/server/utils/cloud-photo-delete.ts
new file mode 100644
index 00000000..9d488c99
--- /dev/null
+++ b/apps/cloud/server/utils/cloud-photo-delete.ts
@@ -0,0 +1,57 @@
+import { createError } from 'h3'
+import type { PlatformD1 } from '../../../../packages/platform/src/index'
+/** Tombstone and enqueue only exact managed object references in one transaction. */
+export async function deleteCloudPhotos(
+ db: PlatformD1,
+ siteId: number,
+ input: unknown,
+ now: number,
+) {
+ if (
+ !Array.isArray(input) ||
+ !input.length ||
+ input.length > 1000 ||
+ input.some(
+ (id) => typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(id),
+ )
+ )
+ throw createError({ statusCode: 400 })
+ const ids = JSON.stringify([...new Set(input)])
+ const found = await db
+ .prepare(
+ 'SELECT COUNT(*) AS total FROM cloud_photos WHERE site_id=? AND id IN (SELECT value FROM json_each(?))',
+ )
+ .bind(siteId, ids)
+ .first<{ total: number }>()
+ if (found?.total !== new Set(input).size)
+ throw createError({ statusCode: 404 })
+ const selection = 'IN (SELECT value FROM json_each(?))'
+ await db.batch([
+ db
+ .prepare(
+ `UPDATE cloud_photos SET deleted=1 WHERE site_id=? AND id ${selection}`,
+ )
+ .bind(siteId, ids),
+ db
+ .prepare(
+ `UPDATE cloud_processing_jobs SET state='cancelled' WHERE site_id=? AND photo_id ${selection} AND state IN ('queued','running','retry_wait')`,
+ )
+ .bind(siteId, ids),
+ db
+ .prepare(
+ `INSERT INTO cloud_cleanup_requests(site_id,id,connection_id,connection_revision,object_key,provider_upload_id,available_at) SELECT site_id,'original-'||id,connection_id,connection_revision,object_key,NULL,? FROM cloud_uploads WHERE site_id=? AND photo_id ${selection} ON CONFLICT DO NOTHING`,
+ )
+ .bind(now + 360000, siteId, ids),
+ db
+ .prepare(
+ `INSERT INTO cloud_cleanup_requests(site_id,id,connection_id,connection_revision,object_key,provider_upload_id,available_at) SELECT site_id,'video-'||id,connection_id,connection_revision,video_key,NULL,? FROM cloud_uploads WHERE site_id=? AND photo_id ${selection} AND video_key IS NOT NULL ON CONFLICT DO NOTHING`,
+ )
+ .bind(now + 360000, siteId, ids),
+ db
+ .prepare(
+ `INSERT INTO cloud_cleanup_requests(site_id,id,connection_id,connection_revision,object_key,provider_upload_id,available_at) SELECT site_id,'asset-'||photo_id||'-'||role,connection_id,connection_revision,object_key,NULL,? FROM cloud_media_assets WHERE site_id=? AND photo_id ${selection} ON CONFLICT DO NOTHING`,
+ )
+ .bind(now + 360000, siteId, ids),
+ ])
+ return { ok: true }
+}
diff --git a/apps/cloud/server/utils/site-management.ts b/apps/cloud/server/utils/site-management.ts
index 1c283595..18043c1d 100644
--- a/apps/cloud/server/utils/site-management.ts
+++ b/apps/cloud/server/utils/site-management.ts
@@ -17,12 +17,15 @@ export async function siteManagement(event: H3Event, mutation = false) {
store: createD1Provisioning(platformDatabase(event)),
}
}
-export async function siteManagementBody(event: H3Event) {
+export async function siteManagementBody(event: H3Event, limit = 4096) {
if (
+ !Number.isSafeInteger(limit) ||
+ limit < 1 ||
+ limit > 131072 ||
!getHeader(event, 'content-type')?.startsWith('application/json') ||
- Number(getHeader(event, 'content-length')) > 4096
+ Number(getHeader(event, 'content-length')) > limit
)
throw createError({ statusCode: 400 })
// Nitro may already hold the original Cloudflare Request; read H3's active stream.
- return readSiteBody(getRequestWebStream(event))
+ return readSiteBody(getRequestWebStream(event), limit)
}
diff --git a/apps/nuxt.shared.ts b/apps/nuxt.shared.ts
index d5efdbcd..0f33f8f8 100644
--- a/apps/nuxt.shared.ts
+++ b/apps/nuxt.shared.ts
@@ -1,5 +1,6 @@
import type { NuxtConfig } from 'nuxt/schema'
import { createRequire } from 'node:module'
+import { fileURLToPath } from 'node:url'
import { dayjsLocales } from '../packages/gallery/i18n/i18n.options'
const require = createRequire(import.meta.url)
@@ -46,10 +47,28 @@ export const sharedUi = {
'nuxt-mapbox',
'nuxt-maplibre',
'nuxt-og-image',
+ 'nuxt-gtag',
],
// Enable dynamic OG only after selecting a Worker-compatible WASM/remote renderer.
ogImage: { enabled: false },
ui: { fonts: false },
+ icon: {
+ clientBundle: {
+ scan: {
+ globInclude: [
+ fileURLToPath(
+ new URL('../packages/gallery/app/**/*.{vue,ts}', import.meta.url),
+ ),
+ fileURLToPath(
+ new URL('../packages/console/app/**/*.{vue,ts}', import.meta.url),
+ ),
+ fileURLToPath(new URL('./cloud/app/**/*.{vue,ts}', import.meta.url)),
+ ],
+ },
+ },
+ },
+ // Keep shared gallery event helpers available without injecting tracking scripts.
+ gtag: { enabled: false },
components: ['~/components'],
runtimeConfig: {
public: {
diff --git a/apps/self-hosted/app/app.vue b/apps/self-hosted/app/app.vue
index c392caeb..a94834a3 100644
--- a/apps/self-hosted/app/app.vue
+++ b/apps/self-hosted/app/app.vue
@@ -1,118 +1,15 @@
<script setup lang="ts">
-import dayjsLocale_zhCN from 'dayjs/locale/zh-cn'
-import dayjsLocale_zhTW from 'dayjs/locale/zh-tw'
-import dayjsLocale_zhHK from 'dayjs/locale/zh-hk'
-
const DebugPanel = import.meta.dev
? defineAsyncComponent(() => import('#gallery/components/debug/Panel.vue'))
: null
-
-const dayjs = useDayjs()
-const colorMode = useColorMode()
-const localeRef = ref('en')
-try {
- const { locale } = useI18n()
- watch(
- locale,
- (value) => {
- localeRef.value = value
- },
- { immediate: true },
- )
-} catch {
- // i18n context may be unavailable during early server-side error rendering
-}
-
-// 初始化设置系统 - 一次性加载所有设置
-const settingsStore = useSettingsStore()
-await settingsStore.initSettings()
-
-const appTitle = useSettingRef('app:title')
-
-colorMode.preference = useSettingRef('app:appearance.theme').value as string
-
-useHead({
- htmlAttrs: { lang: localeRef },
- titleTemplate: (title) =>
- `${title ? title + ' | ' : ''}${appTitle.value || 'ChronoFrame'}`,
-})
-
-// 根据用户登录状态和当前路由决定使用哪个 API
-// 登录用户或后台管理页面显示所有照片,未登录用户在前端页面只显示可见照片
-const route = useRoute()
-const { loggedIn } = useUserSession()
-const apiEndpoint = computed(() => {
- // 后台管理页面始终显示所有照片
- if (route.path.startsWith('/dashboard')) {
- return '/api/photos'
- }
- // 前端页面:登录用户显示所有照片,未登录用户只显示可见照片
- return loggedIn.value ? '/api/photos' : '/api/photos/visible'
-})
-const { data, refresh, status } = await useFetch(() => apiEndpoint.value, {
- watch: [apiEndpoint],
-})
-
-const photos = computed(() => (data.value as Photo[]) || [])
-await useInstanceOpenGraph(photos)
-
-const {
- viewerPhotos,
- currentPhotoIndex,
- isViewerOpen,
- handleClose,
- handleIndexChange,
-} = useGalleryViewer(photos)
-
-watchEffect(() => {
- dayjs.locale('zh-Hans', dayjsLocale_zhCN)
- dayjs.locale('zh-Hant-TW', dayjsLocale_zhTW)
- dayjs.locale('zh-Hant-HK', dayjsLocale_zhHK)
- dayjs.locale(localeRef.value)
-})
-
-// 在全局级别提供筛选功能的状态管理
-provide(
- 'photosFiltering',
- reactive({
- activeFilters: {
- tags: [],
- cameras: [],
- lenses: [],
- cities: [],
- ratings: [],
- },
- }),
-)
</script>
-
<template>
- <UApp>
- <NuxtLoadingIndicator />
- <PhotosProvider
- :photos="photos"
- :refresh="refresh"
- :status="status"
- >
- <NuxtLayout>
- <NuxtPage />
- </NuxtLayout>
- <ClientOnly>
- <AdminTours />
- <component
- :is="DebugPanel"
- v-if="DebugPanel"
- />
- <PhotoViewer
- :photos="viewerPhotos"
- :current-index="currentPhotoIndex"
- :is-open="isViewerOpen"
- @close="handleClose"
- @index-change="handleIndexChange"
- />
- </ClientOnly>
- </PhotosProvider>
- </UApp>
+ <GalleryApplication>
+ <NuxtLayout><NuxtPage /></NuxtLayout>
+ <template #overlays
+ ><AdminTours /><component
+ :is="DebugPanel"
+ v-if="DebugPanel"
+ /></template>
+ </GalleryApplication>
</template>
-
-<style></style>
diff --git a/apps/self-hosted/server/api/photos/[photoId]/reactions.ts b/apps/self-hosted/server/api/photos/[photoId]/reactions.ts
index e458636c..cb0da4b2 100644
--- a/apps/self-hosted/server/api/photos/[photoId]/reactions.ts
+++ b/apps/self-hosted/server/api/photos/[photoId]/reactions.ts
@@ -1,19 +1,10 @@
+import { REACTION_TYPES } from '@chronoframe/contracts/reactions'
import { and as siteAnd, eq as siteEq } from 'drizzle-orm'
import { DEFAULT_SITE } from '@chronoframe/core'
import type { H3Event } from 'h3'
import { eq, and, sql } from 'drizzle-orm'
import { assertPhotoIdAccess } from '../../../utils/album-access'
-const REACTION_TYPES = [
- 'like',
- 'love',
- 'amazing',
- 'funny',
- 'wow',
- 'sad',
- 'fire',
- 'sparkle',
-] as const
const RATE_LIMIT_WINDOW = 60 * 1000 // 1分钟
const MAX_REACTIONS_PER_WINDOW = 10 // 每分钟最多10次表态
diff --git a/apps/self-hosted/server/services/settings/contants.ts b/apps/self-hosted/server/services/settings/contants.ts
index 119855d7..40b12547 100644
--- a/apps/self-hosted/server/services/settings/contants.ts
+++ b/apps/self-hosted/server/services/settings/contants.ts
@@ -1,3 +1,4 @@
+import { PUBLIC_GALLERY_DEFAULTS } from '@chronoframe/contracts/gallery-settings'
import { tourIds } from '~~/shared/types/tours'
import type { SettingConfig } from '~~/shared/types/settings'
import i18nOptions from '@chronoframe/gallery/i18n/i18n.options'
@@ -40,7 +41,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'app',
key: 'title',
type: 'string',
- defaultValue: 'ChronoFrame',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['title'],
label: 'settings.app.title.label',
description: 'settings.app.title.description',
isPublic: true,
@@ -49,7 +50,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'app',
key: 'slogan',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['slogan'],
label: 'settings.app.slogan.label',
description: 'settings.app.slogan.description',
isPublic: true,
@@ -58,7 +59,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'app',
key: 'author',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['author'],
label: 'settings.app.author.label',
description: 'settings.app.author.description',
isPublic: true,
@@ -67,7 +68,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'app',
key: 'avatarUrl',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['avatarUrl'],
label: 'settings.app.avatarUrl.label',
description: 'settings.app.avatarUrl.description',
isPublic: true,
@@ -83,7 +84,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'app',
key: 'homeView',
type: 'string',
- defaultValue: 'photos',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['homeView'],
enum: ['photos', 'albums'],
label: 'settings.app.homeView.label',
description: 'settings.app.homeView.description',
@@ -93,14 +94,14 @@ export const DEFAULT_SETTINGS = [
namespace: 'app',
key: 'socialLinks',
type: 'json',
- defaultValue: { links: [] },
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['socialLinks'],
isPublic: true,
},
{
namespace: 'app',
key: 'appearance.theme',
type: 'string',
- defaultValue: 'system',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['appearance.theme'],
enum: ['light', 'dark', 'system'],
label: 'settings.app.appearance.theme.label',
description: 'settings.app.appearance.theme.description',
@@ -110,7 +111,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'app',
key: 'appearance.homeHeaderLayout',
type: 'string',
- defaultValue: 'embedded',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['app']['appearance.homeHeaderLayout'],
enum: ['embedded', 'fixed'],
label: 'settings.app.appearance.homeHeaderLayout.label',
description: 'settings.app.appearance.homeHeaderLayout.description',
@@ -120,7 +121,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'system',
key: 'upload.maxFileSize',
type: 'number',
- defaultValue: 256,
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['system']['upload.maxFileSize'],
label: 'settings.app.upload.maxFileSize.label',
description: 'settings.app.upload.maxFileSize.description',
isPublic: true,
@@ -129,7 +130,8 @@ export const DEFAULT_SETTINGS = [
namespace: 'system',
key: 'upload.duplicateCheck.enabled',
type: 'boolean',
- defaultValue: true,
+ defaultValue:
+ PUBLIC_GALLERY_DEFAULTS['system']['upload.duplicateCheck.enabled'],
label: 'settings.system.upload.duplicateCheck.enabled.label',
description: 'settings.system.upload.duplicateCheck.enabled.description',
isPublic: true,
@@ -138,7 +140,8 @@ export const DEFAULT_SETTINGS = [
namespace: 'system',
key: 'upload.duplicateCheck.mode',
type: 'string',
- defaultValue: 'skip',
+ defaultValue:
+ PUBLIC_GALLERY_DEFAULTS['system']['upload.duplicateCheck.mode'],
enum: ['warn', 'block', 'skip'],
label: 'settings.system.upload.duplicateCheck.mode.label',
description: 'settings.system.upload.duplicateCheck.mode.description',
@@ -148,7 +151,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'system',
key: 'webglImageViewerDebug',
type: 'boolean',
- defaultValue: false,
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['system']['webglImageViewerDebug'],
label: 'settings.system.webglImageViewerDebug.label',
description: 'settings.system.webglImageViewerDebug.description',
isPublic: true,
@@ -157,7 +160,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'system',
key: 'auth.github.enabled',
type: 'boolean',
- defaultValue: false,
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['system']['auth.github.enabled'],
label: 'settings.system.auth.github.enabled.label',
description: 'settings.system.auth.github.enabled.description',
isPublic: true,
@@ -184,7 +187,8 @@ export const DEFAULT_SETTINGS = [
namespace: 'privacy',
key: 'upload.autoEraseLocation',
type: 'boolean',
- defaultValue: false,
+ defaultValue:
+ PUBLIC_GALLERY_DEFAULTS['privacy']['upload.autoEraseLocation'],
label: 'settings.privacy.upload.autoEraseLocation.label',
description: 'settings.privacy.upload.autoEraseLocation.description',
isPublic: true,
@@ -194,7 +198,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'map',
key: 'provider',
type: 'string',
- defaultValue: 'maplibre',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['map']['provider'],
enum: ['mapbox', 'maplibre'],
label: 'settings.map.provider.label',
description: 'settings.map.provider.description',
@@ -204,7 +208,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'map',
key: 'mapbox.token',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['map']['mapbox.token'],
label: 'settings.map.mapbox.token.label',
description: 'settings.map.mapbox.token.description',
isPublic: true,
@@ -213,7 +217,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'map',
key: 'mapbox.style',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['map']['mapbox.style'],
label: 'settings.map.mapbox.style.label',
description: 'settings.map.mapbox.style.description',
isPublic: true,
@@ -222,7 +226,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'map',
key: 'maplibre.token',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['map']['maplibre.token'],
label: 'settings.map.maplibre.token.label',
description: 'settings.map.maplibre.token.description',
isPublic: true,
@@ -231,7 +235,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'map',
key: 'maplibre.style',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['map']['maplibre.style'],
label: 'settings.map.maplibre.style.label',
description: 'settings.map.maplibre.style.description',
isPublic: true,
@@ -241,7 +245,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'location',
key: 'preferredLevel',
type: 'string',
- defaultValue: 'city',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['location']['preferredLevel'],
enum: [
'country',
'region',
@@ -259,7 +263,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'location',
key: 'fallbackOrder',
type: 'string',
- defaultValue: 'city,subregion,region,country',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['location']['fallbackOrder'],
label: 'settings.location.fallbackOrder.label',
description: 'settings.location.fallbackOrder.description',
isPublic: true,
@@ -268,7 +272,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'location',
key: 'language',
type: 'string',
- defaultValue: 'en',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['location']['language'],
enum: i18nOptions.locales.map(({ language }) => language),
label: 'settings.location.language.label',
description: 'settings.location.language.description',
@@ -278,7 +282,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'location',
key: 'mapbox.token',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['location']['mapbox.token'],
label: 'settings.location.mapbox.token.label',
description: 'settings.location.mapbox.token.description',
isPublic: true,
@@ -287,7 +291,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'location',
key: 'nominatim.baseUrl',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['location']['nominatim.baseUrl'],
label: 'settings.location.nominatim.baseUrl.label',
description: 'settings.location.nominatim.baseUrl.description',
isPublic: true,
@@ -306,7 +310,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'analytics',
key: 'headScripts',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['analytics']['headScripts'],
label: 'settings.analytics.headScripts.label',
description: 'settings.analytics.headScripts.description',
isPublic: true,
@@ -315,7 +319,7 @@ export const DEFAULT_SETTINGS = [
namespace: 'analytics',
key: 'bodyScripts',
type: 'string',
- defaultValue: '',
+ defaultValue: PUBLIC_GALLERY_DEFAULTS['analytics']['bodyScripts'],
label: 'settings.analytics.bodyScripts.label',
description: 'settings.analytics.bodyScripts.description',
isPublic: true,
diff --git a/apps/site/app/app.vue b/apps/site/app/app.vue
index dcdf3aaa..6ee384a6 100644
--- a/apps/site/app/app.vue
+++ b/apps/site/app/app.vue
@@ -1,6 +1,9 @@
+<script setup lang="ts">
+// Resolve Host scope before the shared application loads settings or photographs.
+useEntryContext().value = await useRequestFetch()('/api/public/context')
+</script>
<template>
- <UApp>
- <NuxtLoadingIndicator />
- <NuxtLayout><NuxtPage /></NuxtLayout>
- </UApp>
+ <GalleryApplication
+ ><NuxtLayout><NuxtPage /></NuxtLayout
+ ></GalleryApplication>
</template>
diff --git a/apps/site/app/layouts/default.vue b/apps/site/app/layouts/default.vue
deleted file mode 100644
index e933f51a..00000000
--- a/apps/site/app/layouts/default.vue
+++ /dev/null
@@ -1,126 +0,0 @@
-<script setup lang="ts">
-const context = useEntryContext()
-</script>
-<template>
- <div class="site-frame">
- <header>
- <NuxtLink
- to="/"
- class="site-title"
- >{{ context?.name || 'ChronoFrame' }}</NuxtLink
- >
- <nav aria-label="Gallery navigation">
- <NuxtLink to="/">Photographs</NuxtLink
- ><NuxtLink to="/albums">Albums</NuxtLink>
- </nav>
- </header>
- <main><slot /></main>
- <footer>
- Made with <a href="https://chronoframe.art/">ChronoFrame</a>
- </footer>
- </div>
-</template>
-<style>
-.site-frame {
- max-width: 1280px;
- margin: auto;
- padding: 24px;
- color: #243128;
- font-family: system-ui, sans-serif;
-}
-.site-frame header {
- display: flex;
- gap: 20px;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 32px;
- border-bottom: 1px solid #d9dfd5;
- padding-bottom: 18px;
-}
-.site-title {
- font-size: 20px;
- font-weight: 650;
- min-width: 0;
- overflow-wrap: anywhere;
-}
-.site-frame nav {
- display: flex;
- gap: 16px;
- flex-shrink: 0;
- font-size: 14px;
-}
-.site-frame a {
- color: inherit;
-}
-.site-frame h1 {
- font-size: 28px;
- font-weight: 500;
- margin-bottom: 24px;
-}
-.site-frame footer {
- border-top: 1px solid #d9dfd5;
- margin-top: 40px;
- padding-top: 18px;
- font-size: 12px;
- opacity: 0.7;
-}
-.site-frame input {
- font-size: 16px;
- min-height: 42px;
- padding: 8px;
- border: 1px solid #c5cec0;
- border-radius: 5px;
- max-width: 100%;
-}
-.site-frame button {
- font: inherit;
-}
-.site-album-list {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
- gap: 12px;
-}
-.site-album-list a {
- display: block;
- padding: 18px;
- border: 1px solid #d9dfd5;
- border-radius: 6px;
- text-decoration: none;
-}
-.site-unlock {
- display: flex;
- gap: 10px;
- flex-wrap: wrap;
-}
-.site-unlock button {
- padding: 10px 16px;
- background: #344d38;
- color: #fff;
- border: 0;
- border-radius: 5px;
-}
-@media (max-width: 480px) {
- .site-frame {
- padding: 16px;
- }
- .site-frame header {
- gap: 12px;
- }
- .site-title {
- font-size: 17px;
- }
- .site-frame nav {
- gap: 10px;
- font-size: 12px;
- }
-}
-@media (prefers-color-scheme: dark) {
- .site-frame {
- color: #d9e1d6;
- }
- .site-frame input {
- background: #202b22;
- color: inherit;
- }
-}
-</style>
diff --git a/apps/site/app/middleware/site.global.ts b/apps/site/app/middleware/site.global.ts
index 3892e062..4e6dbcfc 100644
--- a/apps/site/app/middleware/site.global.ts
+++ b/apps/site/app/middleware/site.global.ts
@@ -15,7 +15,11 @@ export default defineNuxtRouteMiddleware(async (to) => {
context.value = null
return abortNavigation(error as Error)
}
+ if (to.path === '/signin')
+ return navigateTo('https://app.chronoframe.art/signin', { external: true })
if (
+ !['/photos', '/globe'].includes(to.path) &&
+ !/^\/[a-z0-9_-]{1,128}$/.test(to.path) &&
to.path !== '/' &&
to.path !== '/albums' &&
!/^\/albums\/[1-9][0-9]*$/.test(to.path)
diff --git a/apps/site/app/pages/albums/[albumId].vue b/apps/site/app/pages/albums/[albumId].vue
deleted file mode 100644
index 6b7146bf..00000000
--- a/apps/site/app/pages/albums/[albumId].vue
+++ /dev/null
@@ -1,75 +0,0 @@
-<script setup lang="ts">
-import type { Album, Photo } from '@chronoframe/contracts/resources'
-const route = useRoute(),
- context = useEntryContext(),
- id = Number(route.params.albumId)
-const password = ref(''),
- failed = ref(false),
- busy = ref(false)
-const { data, error, refresh } = await useFetch<{
- album: Album & { photos: Photo[] }
-}>(`/api/public/albums/${id}`, {
- key: `public-album-${context.value?.scope}-${id}`,
-})
-async function unlock() {
- busy.value = true
- failed.value = false
- try {
- await $fetch(`/api/public/albums/${id}/unlock`, {
- method: 'POST',
- body: { password: password.value },
- })
- password.value = ''
- await refresh()
- } catch {
- failed.value = true
- } finally {
- busy.value = false
- }
-}
-useSeoMeta({
- title: () => data.value?.album.title ?? 'Album',
- robots: 'noindex',
-})
-</script>
-<template>
- <section>
- <h1>{{ data?.album.title || 'Album' }}</h1>
- <template v-if="error"
- ><form
- v-if="error.statusCode === 403"
- class="site-unlock"
- @submit.prevent="unlock"
- >
- <label
- >Album password
- <input
- v-model="password"
- type="password"
- required
- autocomplete="current-password" /></label
- ><button
- type="submit"
- :disabled="busy"
- >
- Unlock album
- </button>
- </form>
- <p
- v-else
- role="alert"
- >
- This album is unavailable.
- </p>
- <p
- v-if="failed"
- role="alert"
- >
- The password was not accepted. Please try again.
- </p></template
- ><GalleryGrid
- v-else-if="data"
- :photos="data.album.photos"
- />
- </section>
-</template>
diff --git a/apps/site/app/pages/albums/index.vue b/apps/site/app/pages/albums/index.vue
deleted file mode 100644
index 3cbdf6e3..00000000
--- a/apps/site/app/pages/albums/index.vue
+++ /dev/null
@@ -1,35 +0,0 @@
-<script setup lang="ts">
-import type { Album } from '@chronoframe/contracts/resources'
-const context = useEntryContext()
-const { data, error } = await useFetch<{ albums: Album[] }>(
- '/api/public/albums',
- { key: `public-albums-${context.value?.scope}` },
-)
-useSeoMeta({
- title: () => `Albums — ${context.value?.name ?? 'ChronoFrame'}`,
- robots: 'noindex',
-})
-</script>
-<template>
- <section>
- <h1>Albums</h1>
- <p
- v-if="error"
- role="alert"
- >
- Albums could not be loaded.
- </p>
- <div
- v-else
- class="site-album-list"
- >
- <NuxtLink
- v-for="album in data?.albums"
- :key="album.id"
- :to="'/albums/' + album.id"
- ><h2>{{ album.title }}</h2>
- <p v-if="album.hasPassword">Password protected</p></NuxtLink
- >
- </div>
- </section>
-</template>
diff --git a/apps/site/app/pages/index.vue b/apps/site/app/pages/index.vue
deleted file mode 100644
index d674e526..00000000
--- a/apps/site/app/pages/index.vue
+++ /dev/null
@@ -1,28 +0,0 @@
-<script setup lang="ts">
-import type { Photo } from '@chronoframe/contracts/resources'
-const context = useEntryContext()
-useSeoMeta({
- title: () => context.value?.name ?? 'ChronoFrame',
- robots: 'noindex',
-})
-const { data, error } = await useFetch<{ photos: Photo[] }>(
- '/api/public/photos',
- { key: `public-photos-${context.value?.scope}` },
-)
-</script>
-<template>
- <section>
- <h1>Your photographs. Your perspective.</h1>
- <p
- v-if="error"
- role="alert"
- >
- Photographs could not be loaded.
- </p>
- <GalleryGrid
- v-else-if="data?.photos.length"
- :photos="data.photos"
- />
- <p v-else>No public photographs yet.</p>
- </section>
-</template>
diff --git a/apps/site/package.json b/apps/site/package.json
index b0db1c1a..0fa10c84 100644
--- a/apps/site/package.json
+++ b/apps/site/package.json
@@ -36,6 +36,7 @@
"h3": "1.15.11",
"@chronoframe/database": "workspace:*",
"@chronoframe/storage": "workspace:*",
- "@chronoframe/contracts": "workspace:*"
+ "@chronoframe/contracts": "workspace:*",
+ "nuxt-gtag": "4.1.0"
}
}
diff --git a/apps/site/server/api/public/photos/[photoId]/[operation].ts b/apps/site/server/api/public/photos/[photoId]/[operation].ts
new file mode 100644
index 00000000..14285253
--- /dev/null
+++ b/apps/site/server/api/public/photos/[photoId]/[operation].ts
@@ -0,0 +1,123 @@
+import { createError, getRouterParam, getHeader, getRequestWebStream } from 'h3'
+import { REACTION_TYPES } from '@chronoframe/contracts/reactions'
+import { createResourceReader } from '@chronoframe/core'
+import { createCloudResourceRepository } from '@chronoframe/database/cloud-resources'
+import type { MediaDatabase } from '@chronoframe/database/cloud-media'
+import {
+ definePlatformHandler,
+ platformDatabase,
+ platformRequestURL,
+} from '../../../../../../shared/platform/runtime'
+import { publicSiteContext } from '../../../../../../shared/platform/context'
+import { authorizePublicPhoto } from '../../../../../../shared/platform/media'
+import { createEmailCodeCrypto } from '../../../../../../shared/platform/crypto'
+import { readSiteBody } from '../../../../../../shared/platform/json'
+export default definePlatformHandler(async (event) => {
+ const context = await publicSiteContext(event),
+ id = getRouterParam(event, 'photoId') ?? '',
+ operation = getRouterParam(event, 'operation')
+ const db = platformDatabase(event)
+ const photo = await db
+ .prepare(
+ `SELECT p.id FROM cloud_photos p WHERE p.site_id=? AND p.id=? AND p.deleted=0 AND p.metadata_json IS NOT NULL AND EXISTS(SELECT 1 FROM cloud_processing_jobs j WHERE j.site_id=p.site_id AND j.photo_id=p.id AND j.source_version=p.source_version AND j.state='succeeded')`,
+ )
+ .bind(context.site.id, id)
+ .first()
+ if (!photo) throw createError({ statusCode: 404 })
+ await authorizePublicPhoto(event, context, id)
+ if (operation === 'albums' && event.method === 'GET') {
+ const repository = createCloudResourceRepository(
+ db as unknown as MediaDatabase,
+ context.site,
+ '/api/public/media',
+ )
+ const memberships = await repository.membershipsForPhoto!(id),
+ ids = new Set(memberships.map((m) => m.albumId))
+ return (
+ await createResourceReader(repository).listAlbums({ admin: false })
+ ).filter((a) => ids.has(a.id))
+ }
+ if (
+ operation !== 'reactions' ||
+ !['GET', 'POST', 'DELETE'].includes(event.method)
+ )
+ throw createError({ statusCode: 405 })
+ const mac = await createEmailCodeCrypto(
+ useRuntimeConfig(event).platform.secret,
+ ),
+ client = getHeader(event, 'cf-connecting-ip') ?? 'unknown'
+ const visitor = await mac.mac([
+ 'gallery-reaction',
+ String(context.site.id),
+ platformRequestURL(event).hostname,
+ client,
+ getHeader(event, 'user-agent') ?? 'unknown',
+ ])
+ if (event.method !== 'GET') {
+ if (
+ !event.context.cloudflare ||
+ client === 'unknown' ||
+ getHeader(event, 'origin') !== platformRequestURL(event).origin
+ )
+ throw createError({ statusCode: 403 })
+ const window = Math.floor(Date.now() / 60000)
+ const limit = await db
+ .prepare(
+ `INSERT INTO platform_auth_attempts(key,window_start,attempts) VALUES(?,?,1) ON CONFLICT(key) DO UPDATE SET attempts=CASE WHEN window_start=excluded.window_start THEN attempts+1 ELSE 1 END,window_start=excluded.window_start RETURNING attempts`,
+ )
+ .bind(
+ 'gallery-reaction:' +
+ (await mac.mac([String(context.site.id), client])),
+ window,
+ )
+ .first<{ attempts: number }>()
+ if (!limit || limit.attempts > 10) throw createError({ statusCode: 429 })
+ if (event.method === 'DELETE')
+ await db
+ .prepare(
+ 'DELETE FROM platform_photo_reactions WHERE site_id=? AND photo_id=? AND visitor_key=?',
+ )
+ .bind(context.site.id, id, visitor)
+ .run()
+ else {
+ const body = await readSiteBody(getRequestWebStream(event))
+ const reaction = body?.reactionType
+ if (
+ typeof reaction !== 'string' ||
+ !(REACTION_TYPES as readonly string[]).includes(reaction)
+ )
+ throw createError({ statusCode: 400 })
+ await db
+ .prepare(
+ 'INSERT INTO platform_photo_reactions(site_id,photo_id,visitor_key,reaction_type,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(site_id,photo_id,visitor_key) DO UPDATE SET reaction_type=excluded.reaction_type,updated_at=excluded.updated_at',
+ )
+ .bind(context.site.id, id, visitor, reaction, Date.now())
+ .run()
+ }
+ }
+ const countRow = await db
+ .prepare(
+ "SELECT COALESCE(json_group_array(json_object('reaction_type',reaction_type,'total',total)),'[]') AS items FROM (SELECT reaction_type,COUNT(*) AS total FROM platform_photo_reactions WHERE site_id=? AND photo_id=? GROUP BY reaction_type)",
+ )
+ .bind(context.site.id, id)
+ .first<{ items: string }>()
+ const counts = JSON.parse(countRow?.items ?? '[]') as {
+ reaction_type: string
+ total: number
+ }[]
+ const own = await db
+ .prepare(
+ 'SELECT reaction_type FROM platform_photo_reactions WHERE site_id=? AND photo_id=? AND visitor_key=?',
+ )
+ .bind(context.site.id, id, visitor)
+ .first<{ reaction_type: string }>()
+ return {
+ reactions: Object.fromEntries(
+ REACTION_TYPES.map((type) => [
+ type,
+ counts.find((c) => c.reaction_type === type)?.total ?? 0,
+ ]),
+ ),
+ userReaction: own?.reaction_type ?? null,
+ }
+})
diff --git a/apps/site/server/api/public/system/settings/all.get.ts b/apps/site/server/api/public/system/settings/all.get.ts
new file mode 100644
index 00000000..10653de6
--- /dev/null
+++ b/apps/site/server/api/public/system/settings/all.get.ts
@@ -0,0 +1,15 @@
+import { PUBLIC_GALLERY_DEFAULTS } from '@chronoframe/contracts/gallery-settings'
+import { definePlatformHandler } from '../../../../../../shared/platform/runtime'
+import {
+ publicSiteContext,
+ siteContextDTO,
+} from '../../../../../../shared/platform/context'
+export default definePlatformHandler(async (event) => {
+ const context = await siteContextDTO(event, await publicSiteContext(event))
+ const data = structuredClone(PUBLIC_GALLERY_DEFAULTS) as Record<
+ string,
+ Record<string, unknown>
+ >
+ data.app!.title = context.name
+ return { timestamp: Date.now(), data }
+})
diff --git a/apps/site/server/middleware/platform-boundary.ts b/apps/site/server/middleware/platform-boundary.ts
index 7760fb6a..115d9637 100644
--- a/apps/site/server/middleware/platform-boundary.ts
+++ b/apps/site/server/middleware/platform-boundary.ts
@@ -13,10 +13,12 @@ export default defineEventHandler((event) => {
if (
[
'/api/public/context',
+ '/api/public/system/settings/all',
'/api/public/photos',
'/api/public/albums',
].includes(path) ||
/^\/api\/public\/albums\/[1-9][0-9]*$/.test(path) ||
+ /^\/api\/public\/photos\/[a-z0-9_-]+\/(?:albums|reactions)$/.test(path) ||
/^\/api\/public\/media\/[a-z0-9_-]+\/(?:original|thumbnail|live-video|display)$/.test(
path,
) ||
diff --git a/packages/console/app/components/ConsoleAlbumDetailsFields.vue b/packages/console/app/components/ConsoleAlbumDetailsFields.vue
new file mode 100644
index 00000000..75e15408
--- /dev/null
+++ b/packages/console/app/components/ConsoleAlbumDetailsFields.vue
@@ -0,0 +1,31 @@
+<script setup lang="ts">
+const title = defineModel<string>('title', { required: true })
+const description = defineModel<string>('description', { required: true })
+</script>
+<template>
+ <div class="space-y-4">
+ <UFormField
+ :label="$t('dashboard.albums.form.title')"
+ name="title"
+ required
+ >
+ <UInput
+ v-model="title"
+ class="w-full"
+ :placeholder="$t('dashboard.albums.form.titlePlaceholder')"
+ />
+ </UFormField>
+
+ <UFormField
+ :label="$t('dashboard.albums.form.description')"
+ name="description"
+ >
+ <UTextarea
+ v-model="description"
+ class="w-full"
+ :placeholder="$t('dashboard.albums.form.descriptionPlaceholder')"
+ :rows="3"
+ />
+ </UFormField>
+ </div>
+</template>
diff --git a/packages/console/app/components/ConsoleMediaTable.vue b/packages/console/app/components/ConsoleMediaTable.vue
new file mode 100644
index 00000000..17f0f2da
--- /dev/null
+++ b/packages/console/app/components/ConsoleMediaTable.vue
@@ -0,0 +1,25 @@
+<script setup lang="ts" generic="T">
+import type { TableColumn } from '@nuxt/ui'
+defineOptions({ inheritAttrs: false })
+defineProps<{ data: T[]; columns?: TableColumn<T>[] }>()
+const table = ref()
+defineExpose({
+ get tableApi() {
+ return table.value?.tableApi
+ },
+})
+</script>
+<template>
+ <UTable
+ ref="table"
+ v-bind="$attrs"
+ :data="data"
+ :columns="columns"
+ ><template
+ v-for="(_, name) in $slots"
+ #[name]="slotData"
+ ><slot
+ :name="name"
+ v-bind="slotData" /></template
+ ></UTable>
+</template>
diff --git a/packages/console/app/components/ConsolePhotoDetailsFields.vue b/packages/console/app/components/ConsolePhotoDetailsFields.vue
new file mode 100644
index 00000000..bc084923
--- /dev/null
+++ b/packages/console/app/components/ConsolePhotoDetailsFields.vue
@@ -0,0 +1,71 @@
+<script setup lang="ts">
+const title = defineModel<string>('title', { required: true })
+const description = defineModel<string>('description', { required: true })
+const tags = defineModel<string[]>('tags', { required: true })
+const rating = defineModel<number | null>('rating', { required: true })
+</script>
+<template>
+ <div class="space-y-5">
+ <UFormField
+ :label="$t('dashboard.photos.editModal.fields.title')"
+ name="title"
+ >
+ <UInput
+ v-model="title"
+ class="w-full"
+ />
+ </UFormField>
+
+ <UFormField
+ :label="$t('dashboard.photos.editModal.fields.description')"
+ name="description"
+ >
+ <UTextarea
+ v-model="description"
+ :rows="3"
+ class="w-full"
+ />
+ </UFormField>
+
+ <div class="space-y-2">
+ <UFormField
+ :label="$t('dashboard.photos.editModal.fields.tags')"
+ name="tags"
+ >
+ <UInputTags
+ v-model="tags"
+ class="w-full"
+ />
+ </UFormField>
+ <p class="text-xs text-neutral-500 dark:text-neutral-400">
+ {{ $t('dashboard.photos.editModal.fields.tagsHint') }}
+ </p>
+ </div>
+
+ <div class="flex items-center justify-between space-y-2">
+ <label class="text-sm font-medium text-neutral-700 dark:text-neutral-200">
+ {{ $t('dashboard.photos.editModal.fields.rating') }}
+ </label>
+ <div class="flex items-center gap-3">
+ <span
+ v-if="rating"
+ class="text-sm text-neutral-600 dark:text-neutral-400"
+ >
+ {{ rating }} / 5
+ </span>
+ <span
+ v-else
+ class="text-sm text-neutral-500 dark:text-neutral-500"
+ >
+ {{ $t('dashboard.photos.editModal.fields.noRating') }}
+ </span>
+ <Rating
+ :model-value="rating || 0"
+ :allow-half="false"
+ size="lg"
+ @update:model-value="rating = $event || null"
+ />
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/packages/console/app/pages/dashboard/albums.vue b/packages/console/app/pages/dashboard/albums.vue
index 6d51bb2d..1657e497 100644
--- a/packages/console/app/pages/dashboard/albums.vue
+++ b/packages/console/app/pages/dashboard/albums.vue
@@ -570,7 +570,7 @@ const columns = computed<any[]>(() => [
v-if="albums.length > 0"
class="bg-white dark:bg-neutral-900 rounded-lg border border-gray-200 dark:border-neutral-800"
>
- <UTable
+ <ConsoleMediaTable
:data="albums"
:columns="columns"
>
@@ -719,7 +719,7 @@ const columns = computed<any[]>(() => [
/>
</div>
</template>
- </UTable>
+ </ConsoleMediaTable>
</div>
<div
@@ -806,31 +806,10 @@ const columns = computed<any[]>(() => [
class="space-y-4"
@submit="onFormSubmit"
>
- <UFormField
- :label="$t('dashboard.albums.form.title')"
- name="title"
- required
- >
- <UInput
- v-model="formData.title"
- class="w-full"
- :placeholder="$t('dashboard.albums.form.titlePlaceholder')"
- />
- </UFormField>
-
- <UFormField
- :label="$t('dashboard.albums.form.description')"
- name="description"
- >
- <UTextarea
- v-model="formData.description"
- class="w-full"
- :placeholder="
- $t('dashboard.albums.form.descriptionPlaceholder')
- "
- :rows="3"
- />
- </UFormField>
+ <ConsoleAlbumDetailsFields
+ v-model:title="formData.title"
+ v-model:description="formData.description"
+ />
<UFormField name="isHidden">
<UCheckbox
diff --git a/packages/console/app/pages/dashboard/photos.vue b/packages/console/app/pages/dashboard/photos.vue
index 5e07be38..8fc43d90 100644
--- a/packages/console/app/pages/dashboard/photos.vue
+++ b/packages/console/app/pages/dashboard/photos.vue
@@ -2765,7 +2765,7 @@ onUnmounted(() => {
<!-- 照片列表 -->
<div class="relative flex-1 min-h-0 flex flex-col">
- <UTable
+ <ConsoleMediaTable
ref="table"
v-model:row-selection="rowSelection"
v-model:column-visibility="columnVisibility"
@@ -2822,7 +2822,7 @@ onUnmounted(() => {
</UDropdownMenu>
</div>
</template>
- </UTable>
+ </ConsoleMediaTable>
<!-- 悬浮版批量操作菜单 -->
<transition
@@ -2977,71 +2977,12 @@ onUnmounted(() => {
class="space-y-5"
@submit="handleEditSubmit"
>
- <UFormField
- :label="$t('dashboard.photos.editModal.fields.title')"
- name="title"
- >
- <UInput
- v-model="editFormState.title"
- class="w-full"
- />
- </UFormField>
-
- <UFormField
- :label="$t('dashboard.photos.editModal.fields.description')"
- name="description"
- >
- <UTextarea
- v-model="editFormState.description"
- :rows="3"
- class="w-full"
- />
- </UFormField>
-
- <div class="space-y-2">
- <UFormField
- :label="$t('dashboard.photos.editModal.fields.tags')"
- name="tags"
- >
- <UInputTags
- v-model="tagsModel"
- class="w-full"
- />
- </UFormField>
- <p class="text-xs text-neutral-500 dark:text-neutral-400">
- {{ $t('dashboard.photos.editModal.fields.tagsHint') }}
- </p>
- </div>
-
- <div class="flex items-center justify-between space-y-2">
- <label
- class="text-sm font-medium text-neutral-700 dark:text-neutral-200"
- >
- {{ $t('dashboard.photos.editModal.fields.rating') }}
- </label>
- <div class="flex items-center gap-3">
- <span
- v-if="editFormState.rating"
- class="text-sm text-neutral-600 dark:text-neutral-400"
- >
- {{ editFormState.rating }} / 5
- </span>
- <span
- v-else
- class="text-sm text-neutral-500 dark:text-neutral-500"
- >
- {{ $t('dashboard.photos.editModal.fields.noRating') }}
- </span>
- <Rating
- :model-value="editFormState.rating || 0"
- :allow-half="false"
- size="lg"
- @update:model-value="
- editFormState.rating = $event || null
- "
- />
- </div>
- </div>
+ <ConsolePhotoDetailsFields
+ v-model:title="editFormState.title"
+ v-model:description="editFormState.description"
+ v-model:tags="tagsModel"
+ v-model:rating="editFormState.rating"
+ />
<div class="space-y-3">
<div class="flex items-center justify-between">
diff --git a/packages/contracts/package.json b/packages/contracts/package.json
index 365bc230..ced98509 100644
--- a/packages/contracts/package.json
+++ b/packages/contracts/package.json
@@ -14,7 +14,9 @@
"./social-links": "./src/social-links.ts",
"./queue": "./src/queue.ts",
"./entry": "./src/entry.ts",
- "./storage-diagnostics": "./src/storage-diagnostics.ts"
+ "./storage-diagnostics": "./src/storage-diagnostics.ts",
+ "./gallery-settings": "./src/gallery-settings.ts",
+ "./reactions": "./src/reactions.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
diff --git a/packages/contracts/src/gallery-settings.ts b/packages/contracts/src/gallery-settings.ts
new file mode 100644
index 00000000..34098304
--- /dev/null
+++ b/packages/contracts/src/gallery-settings.ts
@@ -0,0 +1,41 @@
+/** Shared public defaults for both gallery editions. Never includes credentials or private settings. */
+export const PUBLIC_GALLERY_DEFAULTS = {
+ app: {
+ title: 'ChronoFrame',
+ slogan: '',
+ author: '',
+ avatarUrl: '',
+ homeView: 'photos',
+ socialLinks: { links: [] },
+ 'appearance.theme': 'system',
+ 'appearance.homeHeaderLayout': 'embedded',
+ },
+ system: {
+ 'upload.maxFileSize': 256,
+ 'upload.duplicateCheck.enabled': true,
+ 'upload.duplicateCheck.mode': 'skip',
+ webglImageViewerDebug: false,
+ 'auth.github.enabled': false,
+ },
+ privacy: {
+ 'upload.autoEraseLocation': false,
+ },
+ map: {
+ provider: 'maplibre',
+ 'mapbox.token': '',
+ 'mapbox.style': '',
+ 'maplibre.token': '',
+ 'maplibre.style': '',
+ },
+ location: {
+ preferredLevel: 'city',
+ fallbackOrder: 'city,subregion,region,country',
+ language: 'en',
+ 'mapbox.token': '',
+ 'nominatim.baseUrl': '',
+ },
+ analytics: {
+ headScripts: '',
+ bodyScripts: '',
+ },
+} as const
diff --git a/packages/contracts/src/reactions.ts b/packages/contracts/src/reactions.ts
new file mode 100644
index 00000000..32bc0b62
--- /dev/null
+++ b/packages/contracts/src/reactions.ts
@@ -0,0 +1,10 @@
+export const REACTION_TYPES = [
+ 'like',
+ 'love',
+ 'amazing',
+ 'funny',
+ 'wow',
+ 'sad',
+ 'fire',
+ 'sparkle',
+] as const
diff --git a/packages/contracts/src/resources.ts b/packages/contracts/src/resources.ts
index 84b48fc1..e8e5c608 100644
--- a/packages/contracts/src/resources.ts
+++ b/packages/contracts/src/resources.ts
@@ -15,6 +15,8 @@ export interface Photo {
fileSize: number | null
lastModified: string | null
originalUrl: string | null
+ /** Unconverted source for download when the viewer uses a display derivative. */
+ downloadUrl?: string | null
thumbnailUrl: string | null
thumbnailHash: string | null
tags: string[] | null
diff --git a/packages/database/src/cloud-resources.ts b/packages/database/src/cloud-resources.ts
index 2e19635d..4e23ffa9 100644
--- a/packages/database/src/cloud-resources.ts
+++ b/packages/database/src/cloud-resources.ts
@@ -40,6 +40,7 @@ export function createCloudResourceRepository(
fileSize: typeof m.fileSize === 'number' ? m.fileSize : null,
lastModified: null,
originalUrl: base + '/display',
+ downloadUrl: base + '/original',
thumbnailUrl: base + '/thumbnail',
thumbnailHash:
typeof m.thumbnailHash === 'string' ? m.thumbnailHash : null,
diff --git a/packages/gallery/app/assets/css/tailwind.css b/packages/gallery/app/assets/css/tailwind.css
index 30219b97..71454236 100644
--- a/packages/gallery/app/assets/css/tailwind.css
+++ b/packages/gallery/app/assets/css/tailwind.css
@@ -66,3 +66,12 @@
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.2);
}
+
+/* Preserve pinch zoom while preventing iOS focus zoom in gallery forms. */
+@media (max-width: 767px) {
+ input,
+ textarea,
+ select {
+ font-size: max(16px, 1em);
+ }
+}
diff --git a/packages/gallery/app/components/GalleryApplication.vue b/packages/gallery/app/components/GalleryApplication.vue
new file mode 100644
index 00000000..7e27886f
--- /dev/null
+++ b/packages/gallery/app/components/GalleryApplication.vue
@@ -0,0 +1,111 @@
+<script setup lang="ts">
+import dayjsLocale_zhCN from 'dayjs/locale/zh-cn'
+import dayjsLocale_zhTW from 'dayjs/locale/zh-tw'
+import dayjsLocale_zhHK from 'dayjs/locale/zh-hk'
+
+const dayjs = useDayjs()
+const colorMode = useColorMode()
+const localeRef = ref('en')
+try {
+ const { locale } = useI18n()
+ watch(
+ locale,
+ (value) => {
+ localeRef.value = value
+ },
+ { immediate: true },
+ )
+} catch {
+ // i18n context may be unavailable during early server-side error rendering
+}
+
+// 初始化设置系统 - 一次性加载所有设置
+const settingsStore = useSettingsStore()
+await settingsStore.initSettings()
+
+const appTitle = useSettingRef('app:title')
+
+colorMode.preference = useSettingRef('app:appearance.theme').value as string
+
+useHead({
+ htmlAttrs: { lang: localeRef },
+ titleTemplate: (title) =>
+ `${title ? title + ' | ' : ''}${appTitle.value || 'ChronoFrame'}`,
+})
+
+// 根据用户登录状态和当前路由决定使用哪个 API
+// 登录用户或后台管理页面显示所有照片,未登录用户在前端页面只显示可见照片
+const route = useRoute()
+const { loggedIn } = useUserSession()
+const apiEndpoint = computed(() => {
+ // 后台管理页面始终显示所有照片
+ if (route.path.startsWith('/dashboard')) {
+ return '/api/photos'
+ }
+ // 前端页面:登录用户显示所有照片,未登录用户只显示可见照片
+ return loggedIn.value ? '/api/photos' : '/api/photos/visible'
+})
+const { data, refresh, status } = await useGalleryFetch(
+ () => apiEndpoint.value,
+ {
+ watch: [apiEndpoint],
+ },
+)
+
+const photos = computed(() => (data.value as Photo[]) || [])
+await useInstanceOpenGraph(photos)
+
+const {
+ viewerPhotos,
+ currentPhotoIndex,
+ isViewerOpen,
+ handleClose,
+ handleIndexChange,
+} = useGalleryViewer(photos)
+
+watchEffect(() => {
+ dayjs.locale('zh-Hans', dayjsLocale_zhCN)
+ dayjs.locale('zh-Hant-TW', dayjsLocale_zhTW)
+ dayjs.locale('zh-Hant-HK', dayjsLocale_zhHK)
+ dayjs.locale(localeRef.value)
+})
+
+// 在全局级别提供筛选功能的状态管理
+provide(
+ 'photosFiltering',
+ reactive({
+ activeFilters: {
+ tags: [],
+ cameras: [],
+ lenses: [],
+ cities: [],
+ ratings: [],
+ },
+ }),
+)
+</script>
+
+<template>
+ <UApp>
+ <NuxtLoadingIndicator />
+ <PhotosProvider
+ :photos="photos"
+ :refresh="refresh"
+ :status="status"
+ >
+ <slot />
+ <ClientOnly>
+ <slot name="overlays" />
+ <PhotoViewer
+ :photos="viewerPhotos"
+ :current-index="currentPhotoIndex"
+ :is-open="isViewerOpen"
+ @close="handleClose"
+ @index-change="handleIndexChange"
+ />
+ </ClientOnly>
+ </PhotosProvider>
+ </UApp>
+</template>
+
+<style></style>
diff --git a/packages/gallery/app/components/GalleryGrid.vue b/packages/gallery/app/components/GalleryGrid.vue
deleted file mode 100644
index fa2d6665..00000000
--- a/packages/gallery/app/components/GalleryGrid.vue
+++ /dev/null
@@ -1,165 +0,0 @@
-<script setup lang="ts">
-import type { Photo } from '@chronoframe/contracts/resources'
-defineProps<{ photos: Photo[] }>()
-const selected = ref<Photo | null>(null)
-const dialog = ref<HTMLDialogElement>()
-const trigger = ref<HTMLElement | null>(null)
-function open(photo: Photo, event: MouseEvent) {
- trigger.value = event.currentTarget as HTMLElement
- selected.value = photo
- nextTick(() => dialog.value?.showModal())
-}
-function close() {
- dialog.value?.close()
- selected.value = null
- trigger.value?.focus()
-}
-</script>
-<template>
- <div class="cf-gallery-grid">
- <button
- v-for="photo in photos"
- :key="photo.id"
- class="cf-gallery-tile"
- type="button"
- :aria-label="'View ' + (photo.title || 'photograph')"
- @click="open(photo, $event)"
- >
- <img
- :src="photo.thumbnailUrl || undefined"
- :alt="photo.title || 'Photograph'"
- loading="lazy"
- :width="photo.width || undefined"
- :height="photo.height || undefined"
- />
- <span>{{ photo.title || 'Untitled' }}</span>
- </button>
- </div>
- <dialog
- ref="dialog"
- class="cf-gallery-dialog"
- aria-label="Photograph viewer"
- @cancel.prevent="close"
- @click="$event.target === dialog && close()"
- >
- <template v-if="selected">
- <div class="cf-gallery-dialog-tools">
- <span>{{ selected.title }}</span
- ><a
- :href="selected.originalUrl?.replace(/\/display$/, '/original')"
- target="_blank"
- rel="noopener"
- >Original</a
- ><button
- type="button"
- @click="close"
- >
- Close
- </button>
- </div>
- <img
- :src="selected.originalUrl || undefined"
- :alt="selected.title || 'Photograph'"
- />
- <video
- v-if="selected.livePhotoVideoUrl"
- :src="selected.livePhotoVideoUrl"
- controls
- playsinline
- preload="none"
- aria-label="Live Photo video"
- />
- </template>
- </dialog>
-</template>
-<style scoped>
-.cf-gallery-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(min(180px, 100%), 1fr));
- gap: 12px;
-}
-.cf-gallery-tile {
- border: 0;
- background: transparent;
- padding: 0;
- cursor: pointer;
- text-align: left;
- color: inherit;
- min-width: 0;
-}
-.cf-gallery-tile img {
- width: 100%;
- height: 190px;
- object-fit: cover;
- border-radius: 6px;
- background: #eceee7;
-}
-.cf-gallery-tile span {
- display: block;
- font-size: 12px;
- padding: 6px 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.cf-gallery-dialog {
- border: 0;
- border-radius: 8px;
- padding: 12px;
- background: #171d18;
- color: white;
- max-width: 96vw;
- max-height: 96vh;
-}
-.cf-gallery-dialog::backdrop {
- background: #101710e8;
-}
-.cf-gallery-dialog img {
- display: block;
- object-fit: contain;
- max-width: 90vw;
- max-height: 78vh;
- width: auto;
- height: auto;
- margin: auto;
-}
-.cf-gallery-dialog video {
- max-width: 100%;
- max-height: 60vh;
- margin: auto;
- display: block;
-}
-.cf-gallery-dialog-tools {
- display: flex;
- align-items: center;
- gap: 16px;
- margin-bottom: 10px;
- font-size: 14px;
-}
-.cf-gallery-dialog-tools span {
- flex: 1;
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.cf-gallery-dialog-tools button,
-.cf-gallery-dialog-tools a {
- color: inherit;
- background: transparent;
- min-height: 40px;
- padding: 8px;
- border: 1px solid #ffffff55;
- border-radius: 5px;
- font: inherit;
- cursor: pointer;
-}
-@media (max-width: 480px) {
- .cf-gallery-grid {
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: 8px;
- }
- .cf-gallery-tile img {
- height: 160px;
- }
-}
-</style>
diff --git a/packages/gallery/app/components/masonry/item/HeaderIdentity.vue b/packages/gallery/app/components/masonry/item/HeaderIdentity.vue
index 8437bff7..79550197 100644
--- a/packages/gallery/app/components/masonry/item/HeaderIdentity.vue
+++ b/packages/gallery/app/components/masonry/item/HeaderIdentity.vue
@@ -4,7 +4,7 @@ const props = defineProps<{
loggedIn: boolean
}>()
-const router = useRouter()
+const visitorIdentity = useEntryCapabilities().identity === 'visitor'
const isFixed = computed(() => props.variant === 'fixed')
const title = computed(() => getSetting('app:title'))
const author = computed(() => getSetting('app:author'))
@@ -36,7 +36,12 @@ const avatarUrl = computed(
type="button"
:aria-label="$t('auth.form.signin.title')"
class="absolute inset-0 cursor-pointer rounded-full focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-primary-500"
- @click="router.push('/signin')"
+ @click="
+ navigateTo(
+ visitorIdentity ? 'https://app.chronoframe.art/signin' : '/signin',
+ { external: visitorIdentity },
+ )
+ "
/>
<span
v-if="loggedIn"
diff --git a/packages/gallery/app/components/masonry/item/Photo.vue b/packages/gallery/app/components/masonry/item/Photo.vue
index 92872b1e..b8c63056 100644
--- a/packages/gallery/app/components/masonry/item/Photo.vue
+++ b/packages/gallery/app/components/masonry/item/Photo.vue
@@ -481,6 +481,11 @@ onUnmounted(() => {
<template>
<div
ref="photoRef"
+ role="button"
+ tabindex="0"
+ :aria-label="photo.title || $t('ui.photo.altFallback')"
+ @keydown.enter.prevent="handleClick"
+ @keydown.space.prevent="handleClick"
class="w-full transition-all duration-300 cursor-pointer select-none"
:style="{
transform: 'translateZ(0)',
diff --git a/packages/gallery/app/components/photo/ShareModal.vue b/packages/gallery/app/components/photo/ShareModal.vue
index 29720560..9994aede 100644
--- a/packages/gallery/app/components/photo/ShareModal.vue
+++ b/packages/gallery/app/components/photo/ShareModal.vue
@@ -287,7 +287,8 @@ const downloadOriginalImage = async () => {
if (downloadingOriginal.value || !props.photo.originalUrl) return
downloadingOriginal.value = true
try {
- const response = await fetch(props.photo.originalUrl!)
+ const source = props.photo.downloadUrl || props.photo.originalUrl!
+ const response = await fetch(source)
if (!response.ok) throw new Error(`HTTP ${response.status}`)
const blob = await response.blob()
const url = window.URL.createObjectURL(blob)
diff --git a/packages/gallery/app/composables/useGalleryApi.ts b/packages/gallery/app/composables/useGalleryApi.ts
index 985bc0ae..677de544 100644
--- a/packages/gallery/app/composables/useGalleryApi.ts
+++ b/packages/gallery/app/composables/useGalleryApi.ts
@@ -1,15 +1,45 @@
import { useEntryApi, useEntryFetch } from './useEntryApi'
-/** Create a request-scoped gallery transport using this entry's API origin. */
+/** Public endpoints retain their API envelopes; the shared gallery consumes resource arrays. */
+function publicPath(path: string, isPublic: boolean) {
+ return isPublic && path === '/api/photos/visible' ? '/api/photos' : path
+}
+function galleryResponse(path: string, data: unknown, isPublic: boolean) {
+ if (!isPublic || !data || typeof data !== 'object') return data
+ const result = data as Record<string, unknown>
+ if (['/api/photos', '/api/photos/visible'].includes(path))
+ return result.photos
+ if (path === '/api/albums') return result.albums
+ if (/^\/api\/albums\/[1-9][0-9]*$/.test(path)) return result.album
+ return data
+}
export function useGalleryApi() {
- return useEntryApi(useRuntimeConfig().public.gallery.apiBase)
+ const isPublic = useEntryContext().value?.audience === 'public'
+ const fetcher = useEntryApi(useRuntimeConfig().public.gallery.apiBase)
+ return (async (request: string, options?: Record<string, unknown>) =>
+ galleryResponse(
+ request,
+ await fetcher(publicPath(request, isPublic), options),
+ isPublic,
+ )) as typeof $fetch
}
-/** Preserve useFetch response inference while applying gallery transport and scope keys. */
export const useGalleryFetch = ((
request: unknown,
options?: Record<string, unknown>,
-) =>
- useEntryFetch(
- request,
- options,
+) => {
+ const isPublic = useEntryContext().value?.audience === 'public'
+ const original = computed(() => String(toValue(request as string)))
+ const transform = options?.transform as
+ | ((data: unknown) => unknown)
+ | undefined
+ return useEntryFetch(
+ computed(() => publicPath(original.value, isPublic)),
+ {
+ ...options,
+ transform: (data: unknown) => {
+ const result = galleryResponse(original.value, data, isPublic)
+ return transform ? transform(result) : result
+ },
+ },
useRuntimeConfig().public.gallery.apiBase,
- )) as typeof useFetch
+ )
+}) as typeof useFetch
diff --git a/packages/gallery/app/composables/usePhotoFilters.ts b/packages/gallery/app/composables/usePhotoFilters.ts
index 4b1f9a26..dc6eb71d 100644
--- a/packages/gallery/app/composables/usePhotoFilters.ts
+++ b/packages/gallery/app/composables/usePhotoFilters.ts
@@ -16,21 +16,23 @@ interface FilterStats {
}
// 全局筛选状态管理
-const globalFilters = ref<FilterOptions>({
- tags: [],
- cameras: [],
- lenses: [],
- cities: [],
- ratings: 0,
- search: '',
-})
export function usePhotoFilters() {
const { photos } = usePhotos()
const { sortedPhotos } = usePhotoSort()
// 使用全局筛选状态
- const activeFilters = globalFilters
+ const activeFilters = useState<FilterOptions>(
+ `photo-filters:${useEntryContext().value?.scope ?? 'self-hosted'}`,
+ () => ({
+ tags: [],
+ cameras: [],
+ lenses: [],
+ cities: [],
+ ratings: 0,
+ search: '',
+ }),
+ )
// 计算可用的筛选选项及其数量
const filterStats = computed((): FilterStats => {
diff --git a/packages/gallery/app/composables/usePhotoSort.ts b/packages/gallery/app/composables/usePhotoSort.ts
index 8a73b153..eda3a14d 100644
--- a/packages/gallery/app/composables/usePhotoSort.ts
+++ b/packages/gallery/app/composables/usePhotoSort.ts
@@ -6,87 +6,82 @@ interface SortOption {
order: 'asc' | 'desc'
}
-interface SortState {
- currentSort: string
- availableSorts: SortOption[]
-}
-
// 全局排序状态
-const globalSortState = ref<SortState>({
- currentSort: 'dateTaken-desc', // 默认按拍摄时间倒序
- availableSorts: [
- {
- key: 'dateTaken-desc',
- labelI18n: 'ui.action.sort.options.dateTakenDesc',
- icon: 'tabler:sort-descending',
- value: (photo: Photo) =>
- photo.dateTaken ? new Date(photo.dateTaken).getTime() : 0,
- order: 'desc',
- },
- {
- key: 'dateTaken-asc',
- labelI18n: 'ui.action.sort.options.dateTakenAsc',
- icon: 'tabler:sort-ascending',
- value: (photo: Photo) =>
- photo.dateTaken ? new Date(photo.dateTaken).getTime() : 0,
- order: 'asc',
- },
- {
- key: 'lastModified-desc',
- labelI18n: 'ui.action.sort.options.lastModifiedDesc',
- icon: 'tabler:sort-descending',
- value: (photo: Photo) =>
- photo.lastModified ? new Date(photo.lastModified).getTime() : 0,
- order: 'desc',
- },
- {
- key: 'lastModified-asc',
- labelI18n: 'ui.action.sort.options.lastModifiedAsc',
- icon: 'tabler:sort-ascending',
- value: (photo: Photo) =>
- photo.lastModified ? new Date(photo.lastModified).getTime() : 0,
- order: 'asc',
- },
- {
- key: 'fileSize-asc',
- labelI18n: 'ui.action.sort.options.fileSizeAsc',
- icon: 'tabler:sort-ascending-small-big',
- value: (photo: Photo) => photo.fileSize || 0,
- order: 'asc',
- },
- {
- key: 'fileSize-desc',
- labelI18n: 'ui.action.sort.options.fileSizeDesc',
- icon: 'tabler:sort-descending-small-big',
- value: (photo: Photo) => photo.fileSize || 0,
- order: 'desc',
- },
- {
- key: 'title-asc',
- labelI18n: 'ui.action.sort.options.titleAsc',
- icon: 'tabler:sort-ascending-letters',
- value: (photo: Photo) => (photo.title || photo.id).toLowerCase(),
- order: 'asc',
- },
- {
- key: 'title-desc',
- labelI18n: 'ui.action.sort.options.titleDesc',
- icon: 'tabler:sort-descending-letters',
- value: (photo: Photo) => (photo.title || photo.id).toLowerCase(),
- order: 'desc',
- },
- ],
-})
+const sortOptions: SortOption[] = [
+ {
+ key: 'dateTaken-desc',
+ labelI18n: 'ui.action.sort.options.dateTakenDesc',
+ icon: 'tabler:sort-descending',
+ value: (photo: Photo) =>
+ photo.dateTaken ? new Date(photo.dateTaken).getTime() : 0,
+ order: 'desc',
+ },
+ {
+ key: 'dateTaken-asc',
+ labelI18n: 'ui.action.sort.options.dateTakenAsc',
+ icon: 'tabler:sort-ascending',
+ value: (photo: Photo) =>
+ photo.dateTaken ? new Date(photo.dateTaken).getTime() : 0,
+ order: 'asc',
+ },
+ {
+ key: 'lastModified-desc',
+ labelI18n: 'ui.action.sort.options.lastModifiedDesc',
+ icon: 'tabler:sort-descending',
+ value: (photo: Photo) =>
+ photo.lastModified ? new Date(photo.lastModified).getTime() : 0,
+ order: 'desc',
+ },
+ {
+ key: 'lastModified-asc',
+ labelI18n: 'ui.action.sort.options.lastModifiedAsc',
+ icon: 'tabler:sort-ascending',
+ value: (photo: Photo) =>
+ photo.lastModified ? new Date(photo.lastModified).getTime() : 0,
+ order: 'asc',
+ },
+ {
+ key: 'fileSize-asc',
+ labelI18n: 'ui.action.sort.options.fileSizeAsc',
+ icon: 'tabler:sort-ascending-small-big',
+ value: (photo: Photo) => photo.fileSize || 0,
+ order: 'asc',
+ },
+ {
+ key: 'fileSize-desc',
+ labelI18n: 'ui.action.sort.options.fileSizeDesc',
+ icon: 'tabler:sort-descending-small-big',
+ value: (photo: Photo) => photo.fileSize || 0,
+ order: 'desc',
+ },
+ {
+ key: 'title-asc',
+ labelI18n: 'ui.action.sort.options.titleAsc',
+ icon: 'tabler:sort-ascending-letters',
+ value: (photo: Photo) => (photo.title || photo.id).toLowerCase(),
+ order: 'asc',
+ },
+ {
+ key: 'title-desc',
+ labelI18n: 'ui.action.sort.options.titleDesc',
+ icon: 'tabler:sort-descending-letters',
+ value: (photo: Photo) => (photo.title || photo.id).toLowerCase(),
+ order: 'desc',
+ },
+]
export function usePhotoSort() {
const { photos } = usePhotos()
+ const currentSort = useState<string>(
+ `photo-sort:${useEntryContext().value?.scope ?? 'self-hosted'}`,
+ () => 'dateTaken-desc',
+ )
// 当前排序选项
const currentSortOption = computed(() => {
return (
- globalSortState.value.availableSorts.find(
- (sort) => sort.key === globalSortState.value.currentSort,
- ) || globalSortState.value.availableSorts[0]
+ sortOptions.find((sort) => sort.key === currentSort.value) ||
+ sortOptions[0]
)
})
@@ -127,16 +122,14 @@ export function usePhotoSort() {
// 设置排序方式
const setSortOption = (sortKey: string) => {
- if (
- globalSortState.value.availableSorts.some((sort) => sort.key === sortKey)
- ) {
- globalSortState.value.currentSort = sortKey
+ if (sortOptions.some((sort) => sort.key === sortKey)) {
+ currentSort.value = sortKey
}
}
// 切换时间排序(正序/倒序)
const toggleDateSortOrder = () => {
- const current = globalSortState.value.currentSort
+ const current = currentSort.value
if (current === 'dateTaken-desc') {
setSortOption('dateTaken-asc')
} else {
@@ -145,7 +138,7 @@ export function usePhotoSort() {
}
// 获取可用的排序选项
- const availableSorts = computed(() => globalSortState.value.availableSorts)
+ const availableSorts = computed(() => sortOptions)
// 获取当前排序的显示标签
const currentSortLabel = computed(
@@ -161,27 +154,25 @@ export function usePhotoSort() {
// 检查是否为时间排序
const isDateSort = computed(() => {
- return globalSortState.value.currentSort.startsWith('dateTaken')
+ return currentSort.value.startsWith('dateTaken')
})
// 检查时间排序是否为倒序
const isDateSortDesc = computed(() => {
- return globalSortState.value.currentSort === 'dateTaken-desc'
+ return currentSort.value === 'dateTaken-desc'
})
// 打乱照片顺序
const shufflePhotos = () => {
// 创建一个特殊的排序方式用于打乱
- globalSortState.value.currentSort = 'shuffle'
+ currentSort.value = 'shuffle'
// 更新可用排序中的 shuffle 选项
- const shuffleIndex = globalSortState.value.availableSorts.findIndex(
- (sort) => sort.key === 'shuffle',
- )
+ const shuffleIndex = sortOptions.findIndex((sort) => sort.key === 'shuffle')
if (shuffleIndex === -1) {
// 如果没有 shuffle 排序选项,则添加它
- globalSortState.value.availableSorts.push({
+ sortOptions.push({
key: 'shuffle',
labelI18n: 'ui.action.sort.options.shuffle',
icon: 'tabler:dice-3',
diff --git a/packages/gallery/app/pages/albums/[albumId].vue b/packages/gallery/app/pages/albums/[albumId].vue
index fc4ab5f2..33b45a6d 100644
--- a/packages/gallery/app/pages/albums/[albumId].vue
+++ b/packages/gallery/app/pages/albums/[albumId].vue
@@ -301,6 +301,7 @@ useHead({
type="password"
autocomplete="off"
:placeholder="$t('album.passwordPlaceholder')"
+ :aria-label="$t('album.passwordPlaceholder')"
autofocus
class="w-full"
/>
diff --git a/packages/platform/migrations/0010_gallery_reactions.sql b/packages/platform/migrations/0010_gallery_reactions.sql
new file mode 100644
index 00000000..320b344b
--- /dev/null
+++ b/packages/platform/migrations/0010_gallery_reactions.sql
@@ -0,0 +1,10 @@
+CREATE TABLE platform_photo_reactions (
+ site_id INTEGER NOT NULL,
+ photo_id TEXT NOT NULL,
+ visitor_key TEXT NOT NULL,
+ reaction_type TEXT NOT NULL CHECK(reaction_type IN ('like','love','amazing','funny','wow','sad','fire','sparkle')),
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY(site_id,photo_id,visitor_key),
+ FOREIGN KEY(site_id,photo_id) REFERENCES cloud_photos(site_id,id) ON DELETE CASCADE
+);
+CREATE INDEX platform_photo_reaction_counts ON platform_photo_reactions(site_id,photo_id,reaction_type);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cfc4eab8..e0575cb8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -824,6 +824,9 @@ importers:
'@nuxtjs/i18n':
specifier: 10.6.0
+ nuxt-gtag:
+ specifier: 4.1.0
nuxt-mapbox:
specifier: 1.6.4
@@ -905,6 +908,9 @@ importers:
'@nuxtjs/i18n':
specifier: 10.6.0
+ nuxt-gtag:
+ specifier: 4.1.0
nuxt-mapbox:
specifier: 1.6.4
diff --git a/tests/cloud-album-editor.test.ts b/tests/cloud-album-editor.test.ts
new file mode 100644
index 00000000..d9c392ed
--- /dev/null
+++ b/tests/cloud-album-editor.test.ts
@@ -0,0 +1,116 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import Database from 'better-sqlite3'
+import { readFileSync, readdirSync } from 'node:fs'
+import { updateCloudAlbum } from '../apps/cloud/server/utils/cloud-album-editor.ts'
+import type { PlatformD1 } from '../packages/platform/src/index.ts'
+test('album metadata and password changes share a revision fence and retain tenant isolation', async () => {
+ const sqlite = new Database(':memory:')
+ try {
+ for (const n of readdirSync('packages/platform/migrations')
+ .filter((n) => n.endsWith('.sql'))
+ .sort())
+ sqlite.exec(readFileSync('packages/platform/migrations/' + n, 'utf8'))
+ sqlite.exec(
+ "INSERT INTO platform_workspaces(id,name) VALUES(1,'One'),(2,'Two'); INSERT INTO platform_sites(id,workspace_id,name,published) VALUES(1,1,'One',0),(2,2,'Two',0); INSERT INTO cloud_albums(site_id,id,title,revision) VALUES(1,'1','Original',1),(2,'1','Foreign',1)",
+ )
+ const db = {
+ prepare(sql: string) {
+ let args: unknown[] = []
+ const statement = {
+ bind(...v: unknown[]) {
+ args = v
+ return statement
+ },
+ async first() {
+ return sqlite.prepare(sql).get(...args)
+ },
+ async run() {
+ const r = sqlite.prepare(sql).run(...args)
+ return { meta: { changes: r.changes } }
+ },
+ }
+ return statement
+ },
+ async batch(statements: { run(): Promise<unknown> }[]) {
+ sqlite.exec('BEGIN')
+ try {
+ const values = []
+ for (const s of statements) values.push(await s.run())
+ sqlite.exec('COMMIT')
+ return values
+ } catch (e) {
+ sqlite.exec('ROLLBACK')
+ throw e
+ }
+ },
+ } as unknown as PlatformD1
+ assert.deepEqual(
+ await updateCloudAlbum(db, 1, 1, {
+ title: 'Updated',
+ revision: 1,
+ photoIds: [],
+ coverPhotoId: null,
+ isHidden: true,
+ password: 'new-password',
+ }),
+ { revision: 2 },
+ )
+ const protectedBefore = sqlite
+ .prepare(
+ 'SELECT * FROM platform_album_access WHERE site_id=1 AND album_id=1',
+ )
+ .get()
+ assert.ok(protectedBefore)
+ await assert.rejects(
+ updateCloudAlbum(db, 1, 1, {
+ title: 'Stale',
+ revision: 1,
+ photoIds: [],
+ password: null,
+ }),
+ { statusCode: 409 },
+ )
+ assert.deepEqual(
+ sqlite
+ .prepare(
+ 'SELECT * FROM platform_album_access WHERE site_id=1 AND album_id=1',
+ )
+ .get(),
+ protectedBefore,
+ )
+ await updateCloudAlbum(db, 1, 1, { title: 'Keep password', revision: 2 })
+ assert.deepEqual(
+ sqlite
+ .prepare(
+ 'SELECT * FROM platform_album_access WHERE site_id=1 AND album_id=1',
+ )
+ .get(),
+ protectedBefore,
+ )
+ assert.equal(
+ sqlite.prepare('SELECT title FROM cloud_albums WHERE site_id=2').get()
+ .title,
+ 'Foreign',
+ )
+ await assert.rejects(
+ updateCloudAlbum(db, 1, 1, {
+ title: 'Invalid',
+ revision: 3,
+ password: 'short',
+ }),
+ { statusCode: 400 },
+ )
+ await updateCloudAlbum(db, 1, 1, {
+ title: 'Remove password',
+ revision: 3,
+ password: null,
+ })
+ assert.equal(
+ sqlite.prepare('SELECT COUNT(*) n FROM platform_album_access').get().n,
+ 0,
+ )
+ } finally {
+ sqlite.close()
+ }
+})
diff --git a/tests/cloud-photo-delete.test.ts b/tests/cloud-photo-delete.test.ts
new file mode 100644
index 00000000..ab14ac2c
--- /dev/null
+++ b/tests/cloud-photo-delete.test.ts
@@ -0,0 +1,75 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import Database from 'better-sqlite3'
+import { readFileSync, readdirSync } from 'node:fs'
+import { deleteCloudPhotos } from '../apps/cloud/server/utils/cloud-photo-delete.ts'
+import type { PlatformD1 } from '../packages/platform/src/index.ts'
+
+test('bulk deletion rejects foreign or invalid IDs before any site changes', async () => {
+ const sqlite = new Database(':memory:')
+ try {
+ for (const name of readdirSync('packages/platform/migrations')
+ .filter((n) => n.endsWith('.sql'))
+ .sort())
+ sqlite.exec(readFileSync('packages/platform/migrations/' + name, 'utf8'))
+ sqlite.exec(
+ "INSERT INTO platform_workspaces(id,name) VALUES(1,'One'),(2,'Two');INSERT INTO platform_sites(id,workspace_id,name,published) VALUES(1,1,'One',0),(2,2,'Two',0)",
+ )
+ sqlite
+ .prepare(
+ "INSERT INTO cloud_photos(site_id,id,source_version,title) VALUES(1,'own','1','Own'),(2,'foreign','1','Foreign')",
+ )
+ .run()
+ const db = {
+ prepare(sql: string) {
+ let args: unknown[] = []
+ const statement = {
+ bind(...values: unknown[]) {
+ args = values
+ return statement
+ },
+ async first() {
+ return sqlite.prepare(sql).get(...args)
+ },
+ async run() {
+ return sqlite.prepare(sql).run(...args)
+ },
+ }
+ return statement
+ },
+ async batch(statements: { run(): Promise<unknown> }[]) {
+ const results = []
+ sqlite.exec('BEGIN')
+ try {
+ for (const s of statements) results.push(await s.run())
+ sqlite.exec('COMMIT')
+ return results
+ } catch (e) {
+ sqlite.exec('ROLLBACK')
+ throw e
+ }
+ },
+ } as unknown as PlatformD1
+ await assert.rejects(deleteCloudPhotos(db, 1, ['own', 'foreign'], 1), {
+ statusCode: 404,
+ })
+ await assert.rejects(deleteCloudPhotos(db, 1, [], 1), { statusCode: 400 })
+ assert.equal(
+ sqlite.prepare('SELECT SUM(deleted) AS n FROM cloud_photos').get().n,
+ 0,
+ )
+ await deleteCloudPhotos(db, 1, ['own', 'own'], 1)
+ assert.equal(
+ sqlite.prepare('SELECT deleted FROM cloud_photos WHERE site_id=1').get()
+ .deleted,
+ 1,
+ )
+ assert.equal(
+ sqlite.prepare('SELECT deleted FROM cloud_photos WHERE site_id=2').get()
+ .deleted,
+ 0,
+ )
+ } finally {
+ sqlite.close()
+ }
+})
diff --git a/tests/ui-api.test.ts b/tests/ui-api.test.ts
index 83e015b9..1e714aba 100644
--- a/tests/ui-api.test.ts
+++ b/tests/ui-api.test.ts
@@ -34,6 +34,7 @@ for (const name of ['console', 'gallery'])
useRuntimeConfig: () => ({ public: { [name]: { apiBase: '' } } }),
useRequestFetch: () => scopedFetch,
useFetch: scopedFetch,
+ useEntryContext: () => context,
computed: (get: () => unknown) => ({
get value() {
return get()
@@ -99,3 +100,65 @@ for (const name of ['console', 'gallery'])
})
assert.equal(calls.at(-1)!.options.baseURL, '')
})
+
+test('public gallery unwraps resource envelopes without changing scoped SSR requests', async () => {
+ const calls: string[] = []
+ const context = { value: { audience: 'public', scope: 'site:1:public' } }
+ const responses: Record<string, unknown> = {
+ '/api/photos': { photos: [{ id: 'one' }] },
+ '/api/albums': { albums: [{ id: 1 }] },
+ '/api/albums/1': { album: { id: 1 } },
+ '/api/photos/one/reactions': { reactions: { heart: 1 } },
+ }
+ const exports: Record<string, any> = {}
+ const value = (v: any): any =>
+ typeof v === 'function'
+ ? v()
+ : v && typeof v === 'object' && 'value' in v
+ ? v.value
+ : v
+ const code = ts.transpileModule(
+ readFileSync('packages/gallery/app/composables/useGalleryApi.ts', 'utf8'),
+ { compilerOptions: { module: ts.ModuleKind.CommonJS } },
+ ).outputText
+ vm.runInNewContext(code, {
+ exports,
+ useEntryContext: () => context,
+ useRuntimeConfig: () => ({ public: { gallery: { apiBase: '' } } }),
+ computed: (get: () => unknown) => ({
+ get value() {
+ return get()
+ },
+ }),
+ toValue: value,
+ require: () => ({
+ useEntryApi: () => async (path: string) => {
+ calls.push(path)
+ return responses[path]
+ },
+ useEntryFetch: async (path: unknown, options: any) => {
+ const p = value(path)
+ calls.push(p)
+ return options.transform(responses[p])
+ },
+ }),
+ })
+ const api = exports.useGalleryApi()
+ assert.equal(
+ JSON.stringify(await api('/api/photos/visible')),
+ '[{"id":"one"}]',
+ )
+ assert.equal(calls.at(-1), '/api/photos')
+ assert.equal(JSON.stringify(await api('/api/albums')), '[{"id":1}]')
+ assert.equal(JSON.stringify(await api('/api/albums/1')), '{"id":1}')
+ assert.equal(
+ JSON.stringify(await api('/api/photos/one/reactions')),
+ '{"reactions":{"heart":1}}',
+ )
+ assert.equal(
+ await exports.useGalleryFetch(() => '/api/photos/visible', {
+ transform: (photos: unknown[]) => photos.length,
+ }),
+ 1,
+ )
+})