From dc54a8618af94eda1fb2a7d71daf162c5a3bf72d Mon Sep 17 00:00:00 2001 From: gall-levi-tech Date: Wed, 12 Aug 2026 08:15:47 -0500 Subject: [PATCH 1/2] Revamp gallery presentation and protected media viewing --- docs/schemas/gallery-api.schema.json | 76 +- services/frame-gallery/README.md | 17 +- services/frame-gallery/public/admin.css | 271 +++-- services/frame-gallery/public/admin.html | 168 +-- services/frame-gallery/public/admin.js | 1067 ++++++++++++----- services/frame-gallery/public/gallery.js | 699 ++++++++++- services/frame-gallery/public/index.html | 66 +- .../frame-gallery/public/justified-rows.js | 62 + services/frame-gallery/public/socials.js | 128 ++ services/frame-gallery/public/styles.css | 185 ++- services/frame-gallery/src/app.ts | 248 +++- services/frame-gallery/src/store.ts | 436 ++++++- services/frame-gallery/src/theme.ts | 122 ++ services/frame-gallery/tests/gallery.test.mjs | 695 ++++++++++- .../tests/justified-rows.test.mjs | 23 + services/frame-gallery/tests/socials.test.mjs | 26 + .../frame-pipeline-photos/src/pipeline.ts | 5 +- .../tests/pipeline.test.mjs | 11 + services/frame-today/package-lock.json | 6 +- services/frame-today/public/today.css | 12 +- services/frame-today/public/viewer.html | 10 +- services/frame-today/public/viewer.js | 304 ++++- services/frame-today/src/app.ts | 14 - services/frame-today/src/store.ts | 20 +- services/frame-today/tests/today.test.mjs | 120 +- 25 files changed, 4058 insertions(+), 733 deletions(-) create mode 100644 services/frame-gallery/public/justified-rows.js create mode 100644 services/frame-gallery/public/socials.js create mode 100644 services/frame-gallery/tests/justified-rows.test.mjs create mode 100644 services/frame-gallery/tests/socials.test.mjs diff --git a/docs/schemas/gallery-api.schema.json b/docs/schemas/gallery-api.schema.json index 3dc1ac2..6ec6573 100644 --- a/docs/schemas/gallery-api.schema.json +++ b/docs/schemas/gallery-api.schema.json @@ -5,13 +5,16 @@ "date": { "type": "object", "additionalProperties": false, - "required": ["date_folder", "count", "first_at", "latest_at", "duration_ms", "cover_thumbnail_url", "has_explore"], + "required": ["date_folder", "count", "first_at", "latest_at", "duration_ms", "cover_base", "cover_fallback_active", "cover_is_custom", "cover_thumbnail_url", "has_explore"], "properties": { "date_folder": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }, "count": { "type": "integer", "minimum": 1 }, "first_at": { "type": ["string", "null"], "format": "date-time" }, "latest_at": { "type": ["string", "null"], "format": "date-time" }, "duration_ms": { "type": "integer", "minimum": 0 }, + "cover_base": { "type": ["string", "null"], "pattern": "^[A-Za-z0-9_-]+$" }, + "cover_fallback_active": { "type": "boolean" }, + "cover_is_custom": { "type": "boolean" }, "cover_thumbnail_url": { "type": ["string", "null"], "pattern": "^/gallery/thumb/" }, "has_explore": { "type": "boolean" } } @@ -22,7 +25,6 @@ "required": [ "base", "date_folder", - "image_url", "thumbnail_url", "width", "height", @@ -34,7 +36,6 @@ "properties": { "base": { "type": "string", "pattern": "^[A-Za-z0-9_-]+$" }, "date_folder": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }, - "image_url": { "type": "string", "pattern": "^/gallery/image/" }, "thumbnail_url": { "type": "string", "pattern": "^/gallery/thumb/" }, "width": { "type": ["integer", "null"], "minimum": 1 }, "height": { "type": ["integer", "null"], "minimum": 1 }, @@ -105,20 +106,48 @@ "required": ["url", "width", "height", "updated_at"], "properties": { "url": { "type": "string", "pattern": "^/gallery/branding/logo\\.webp\\?v=" }, - "width": { "type": "integer", "minimum": 1, "maximum": 360 }, - "height": { "type": "integer", "minimum": 1, "maximum": 120 }, + "width": { "type": "integer", "minimum": 1, "maximum": 720 }, + "height": { "type": "integer", "minimum": 1, "maximum": 240 }, "updated_at": { "type": "string", "format": "date-time" } } }, + "socialGraphic": { + "type": "object", + "additionalProperties": false, + "required": ["url", "width", "height", "updated_at"], + "properties": { + "url": { "type": "string", "pattern": "^/gallery/branding/socials/[A-Za-z0-9_-]{1,64}/graphic\\.webp\\?v=" }, + "width": { "type": "integer", "minimum": 1 }, + "height": { "type": "integer", "minimum": 1 }, + "updated_at": { "type": "string", "format": "date-time" } + } + }, + "social": { + "type": "object", + "additionalProperties": false, + "required": ["id", "platform", "url"], + "properties": { + "id": { "type": "string", "pattern": "^[A-Za-z0-9_-]{1,64}$" }, + "platform": { + "type": "string", + "enum": ["website", "instagram", "tiktok", "youtube", "twitch", "facebook", "x", "threads", "bluesky", "discord", "linkedin", "reddit", "snapchat", "flickr"] + }, + "label": { "type": "string", "minLength": 1, "maxLength": 60 }, + "url": { "type": "string", "maxLength": 2048, "pattern": "^https?://" }, + "graphic": { "$ref": "#/$defs/socialGraphic" } + } + }, "branding": { "type": "object", "additionalProperties": false, "required": [ "brand_name", "gallery_title", + "show_download_button", "mode", "profile_id", "custom_profiles", + "socials", "logo", "updated_at", "active_profile", @@ -127,14 +156,43 @@ "properties": { "brand_name": { "type": "string", "minLength": 1, "maxLength": 60 }, "gallery_title": { "type": "string", "minLength": 1, "maxLength": 80 }, + "show_download_button": { "type": "boolean", "default": false }, "mode": { "type": "string", "enum": ["system", "day", "night"] }, "profile_id": { "type": "string", "pattern": "^[a-z0-9-]+$" }, "custom_profiles": { "type": "array", "items": { "$ref": "#/$defs/profile" } }, + "socials": { "type": "array", "maxItems": 32, "items": { "$ref": "#/$defs/social" } }, "logo": { "$ref": "#/$defs/logo" }, "updated_at": { "type": "string", "format": "date-time" }, "active_profile": { "$ref": "#/$defs/profile" }, "presets": { "type": "array", "minItems": 5, "items": { "$ref": "#/$defs/profile" } } } + }, + "tile": { + "type": "object", + "additionalProperties": false, + "required": ["x", "y", "width", "height", "url"], + "properties": { + "x": { "type": "integer", "minimum": 0 }, + "y": { "type": "integer", "minimum": 0 }, + "width": { "type": "integer", "minimum": 1, "maximum": 512 }, + "height": { "type": "integer", "minimum": 1, "maximum": 512 }, + "url": { "type": "string", "pattern": "^/gallery/tile/[A-Za-z0-9_-]{43}/(?:0|[1-9][0-9]*)/(?:0|[1-9][0-9]*)\\.webp$" } + } + }, + "tileView": { + "type": "object", + "additionalProperties": false, + "required": ["handle", "width", "height", "tile_size", "overlap", "columns", "rows", "tiles"], + "properties": { + "handle": { "type": "string", "pattern": "^[A-Za-z0-9_-]{43}$" }, + "width": { "type": "integer", "minimum": 1 }, + "height": { "type": "integer", "minimum": 1 }, + "tile_size": { "type": "integer", "const": 512 }, + "overlap": { "type": "integer", "const": 1 }, + "columns": { "type": "integer", "minimum": 1 }, + "rows": { "type": "integer", "minimum": 1 }, + "tiles": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/tile" } } + } } }, "oneOf": [ @@ -163,6 +221,14 @@ "branding": { "$ref": "#/$defs/branding" } } }, + { + "type": "object", + "additionalProperties": false, + "required": ["view"], + "properties": { + "view": { "$ref": "#/$defs/tileView" } + } + }, { "type": "object", "additionalProperties": false, diff --git a/services/frame-gallery/README.md b/services/frame-gallery/README.md index 0252c47..fa51c87 100644 --- a/services/frame-gallery/README.md +++ b/services/frame-gallery/README.md @@ -18,7 +18,8 @@ Use it if you want to: - Explore a day's route and jump between mapped photos. - Hide or restore photos from the gallery. - Permanently delete published gallery copies when needed. -- Customize gallery branding, colors, and logo. +- Choose each album's gallery cover. +- Customize gallery branding, logo, and visitor download controls. ## What You Use It For @@ -31,6 +32,7 @@ Common uses: - Remove unwanted photos from public view. - Restore photos that were hidden by mistake. - Match the gallery branding to your stream, event, or production. +- Control whether visitors can view and download the full gallery JPEG. - Correct camera-to-GPX clock differences and manually place unmatched photos. Photo Gallery does not receive uploads directly. Photos come from Photo Upload or Photo FTP, then @@ -76,7 +78,7 @@ On the public gallery, viewers can: - Browse available photo days. - Open one day's album. -- View photos in the selected style. +- View photos through page-bound tiles when downloads are disabled, or the full gallery JPEG when downloads are enabled. - Switch between Photos and Explore when a day has attached route data. - Select a mapped photo from its thumbnail, lightbox, map marker, or Explore photo strip. - Switch day/night mode when enabled. @@ -89,8 +91,9 @@ On the admin page, operators can: - Empty the gallery trash. - Add or remove multiple GPX sessions for one day. - Adjust camera-to-GPX timing and manually place photos that do not match a route. -- Change the gallery title, brand name, logo, and colors. -- Save custom gallery styles. +- Choose or clear a custom cover for each album. +- Change the gallery title, brand name, and logo. +- Enable or disable full gallery JPEG downloads for every public gallery. Trash is reversible. Permanent delete is not. @@ -128,6 +131,12 @@ The admin page should stay login-protected. Photo Gallery asks Photo Pipeline to hide, restore, or delete photos. It does not edit the published photo files directly. +When downloads are disabled, public lightbox photos are delivered as short-lived, page-bound tiles and +FRAME does not expose a public full-image route. When downloads are enabled, the lightbox and Download +action use the full normalized gallery JPEG; the archived camera file remains private. Tiles can still +be captured or reassembled by a determined visitor, and anything visible in a browser can be +screenshotted; this is download deterrence and archive-file protection, not image DRM. + Explore uses the camera capture clock retained in the photo sidecar, not the time FRAME processed the photo. If the camera clock and GPX clock differ, Gallery Admin can infer the coarse timezone shift and apply a fine seconds adjustment. Manual photo placements survive trash and restore; permanent photo diff --git a/services/frame-gallery/public/admin.css b/services/frame-gallery/public/admin.css index 0e9c373..f85a5d2 100644 --- a/services/frame-gallery/public/admin.css +++ b/services/frame-gallery/public/admin.css @@ -37,9 +37,11 @@ } * { box-sizing: border-box; } [hidden] { display: none !important; } +.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } body { min-height: 100vh; margin: 0; background: var(--background); } button, input, select { font: inherit; } button, a { -webkit-tap-highlight-color: transparent; } +button, a, input { transition: border-color 140ms ease, background-color 140ms ease, color 140ms ease, box-shadow 140ms ease, transform 140ms ease; } .topbar { position: sticky; z-index: 5; top: 0; min-height: 72px; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 9px clamp(12px, 3vw, 36px); @@ -77,6 +79,7 @@ button, a { -webkit-tap-highlight-color: transparent; } } :root[data-theme="day"] .theme-toggle, :root[data-theme-mode="day"] .theme-toggle, .theme-toggle[aria-pressed="true"] { border-color: var(--accent); background: var(--toggle-day-bg, #fff6d5); color: var(--toggle-day-text, #8a5e00); } main { width: min(1500px, 100%); margin: 0 auto; padding: 16px clamp(10px, 3vw, 30px) 48px; } +body.settings-dirty main { padding-bottom: calc(132px + env(safe-area-inset-bottom)); } .page-heading, .section-heading { display: flex; justify-content: space-between; align-items: end; gap: 12px; } .page-heading { margin-bottom: 14px; } .page-heading p, .section-heading p { margin: 0; color: var(--accent); font-size: 12px; font-weight: 800; text-transform: uppercase; } @@ -89,13 +92,17 @@ h1, h2 { margin: 2px 0; } .subtabs { display: grid; gap: 7px; margin-bottom: 14px; } .subtabs { grid-template-columns: repeat(2, minmax(0, 1fr)); } .section-tabs button { - min-height: 44px; padding: 0 16px; border: 0; border-bottom: 3px solid transparent; border-radius: 0; + position: relative; min-height: 44px; padding: 0 16px; border: 0; border-bottom: 3px solid transparent; border-radius: 0; background: transparent; color: var(--muted); font-weight: 800; cursor: pointer; } .section-tabs button[aria-selected="true"] { border-bottom-color: var(--accent); color: var(--text); background: color-mix(in srgb, var(--accent) 8%, transparent); } .section-tabs button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.section-tabs button[data-dirty="true"]::after { + content: ""; position: absolute; top: 8px; right: 7px; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); + box-shadow: 0 0 8px color-mix(in srgb, var(--accent) 70%, transparent); +} .subtabs button { min-height: 46px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--control-text); cursor: pointer; } @@ -110,24 +117,50 @@ h1, h2 { margin: 2px 0; } .album-card.selected { border-color: var(--accent); } .album-open { display: grid; width: 100%; padding: 0; border: 0; background: transparent; color: inherit; text-align: left; cursor: pointer; } .album-open img, .photo-card > img, .trash-photo > img { width: 100%; aspect-ratio: 4 / 3; display: block; object-fit: cover; background: var(--surface-strong); } -.album-open span, .photo-card > span, .trash-photo > span { min-width: 0; display: grid; gap: 2px; padding: 9px 10px; } +.album-open span, .trash-photo > span { min-width: 0; display: grid; gap: 2px; padding: 9px 10px; } +.photo-details > span { min-width: 0; display: grid; gap: 2px; } .album-open strong, .photo-card strong, .trash-photo strong { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.album-actions { display: grid; grid-template-columns: minmax(0, 1fr) 44px; gap: 8px; padding: 8px; border-top: 1px solid var(--border); } +.album-actions > * { min-width: 0; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; text-align: center; text-decoration: none; } .album-detail, #trash-view { margin-top: 20px; scroll-margin-top: 86px; } +.cover-management-panel { + display: flex; align-items: center; justify-content: space-between; gap: 18px; margin-bottom: 16px; padding: 14px 16px; border: 1px solid var(--border); + border-radius: 8px; background: var(--surface); +} +.cover-management-panel > div { min-width: 0; display: grid; gap: 4px; } +.cover-management-panel p { margin: 0; color: var(--muted); font-size: 12px; font-weight: 700; line-height: 1.45; } +.cover-management-panel p[data-kind="fallback"] { color: var(--accent); } +.cover-management-panel p[data-kind="error"] { color: var(--danger); } +.cover-management-panel:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +.cover-management-panel > button { flex: none; } .section-heading { margin-bottom: 12px; } .section-actions { display: flex; justify-content: end; gap: 8px; } .section-actions a { display: inline-flex; align-items: center; text-decoration: none; } -.danger-button, .restore-button, .icon-action { +.danger-button, .restore-button, .icon-action, .icon-danger-button { min-height: 39px; padding: 7px 10px; border-radius: 5px; color: var(--control-text); font-weight: 800; cursor: pointer; } .secondary-button { min-height: 39px; padding: 7px 10px; border: 1px solid var(--border); border-radius: 5px; background: var(--surface); color: var(--control-text); font-weight: 800; cursor: pointer; } -.danger-button, .icon-action { border: 1px solid var(--danger); background: color-mix(in srgb, var(--danger) 44%, var(--surface)); } +.danger-button, .icon-action, .icon-danger-button { border: 1px solid var(--danger); background: color-mix(in srgb, var(--danger) 44%, var(--surface)); } .restore-button { border: 1px solid var(--good); background: color-mix(in srgb, var(--good) 36%, var(--surface)); } +.secondary-button:hover, .secondary-button:focus-visible, .gallery-button:hover, .icon-button:hover, .icon-button:focus-visible { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, var(--surface)); } +.restore-button:hover, .restore-button:focus-visible { border-color: var(--good); background: color-mix(in srgb, var(--good) 52%, var(--surface)); } +.danger-button:hover, .danger-button:focus-visible, .icon-action:hover, .icon-action:focus-visible, .icon-danger-button:hover, .icon-danger-button:focus-visible { background: color-mix(in srgb, var(--danger) 58%, var(--surface)); } +.icon-danger-button { width: 42px; height: 42px; min-height: 42px; display: grid; place-items: center; padding: 0; } +.icon-danger-button:active, .secondary-button:active, .restore-button:active { transform: translateY(1px); } .compact-button { min-height: 34px; padding: 5px 9px; } .icon-action { width: 100%; border-width: 1px 0 0; border-radius: 0; } -.photo-card > button { width: calc(100% - 16px); margin: 0 8px 8px; } +.photo-card { position: relative; } +.photo-details { min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr) 42px; align-items: center; gap: 8px; padding: 8px 8px 8px 10px; } +.photo-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +.cover-star { + position: absolute; z-index: 2; top: 8px; right: 8px; width: 34px; height: 34px; display: grid; place-items: center; + padding: 0; border: 1px solid var(--accent); border-radius: 50%; background: color-mix(in srgb, var(--topbar) 88%, transparent); + color: var(--accent); font-size: 19px; line-height: 1; box-shadow: 0 5px 18px rgb(0 0 0 / 32%); +} +.cover-star svg { width: 18px; height: 18px; display: block; fill: currentColor; } .trash-list { display: grid; gap: 12px; } .trash-album { padding: 10px; } .trash-album-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; } @@ -138,24 +171,107 @@ h1, h2 { margin: 2px 0; } .trash-photo > div button { flex: 1; } .empty { min-height: 260px; display: grid; place-content: center; gap: 5px; text-align: center; color: var(--muted); } .empty strong { color: var(--text); font-size: 19px; } -.branding-form { display: grid; gap: 12px; } +.branding-form { display: grid; gap: 16px; } .field-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; } .field-grid label { min-width: 0; display: grid; gap: 5px; color: var(--muted); font-size: 12px; font-weight: 800; text-transform: uppercase; } .field-grid input, .field-grid select { min-width: 0; min-height: 42px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--control-text); padding: 8px 10px; text-transform: none; font-weight: 600; } -.branding-fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.branding-fields { grid-template-columns: 1fr; align-content: center; } .field-grid input[type="color"] { padding: 3px; cursor: pointer; } .branding-panel { - min-width: 0; display: grid; gap: 10px; padding: 12px; border: 1px solid var(--border); + min-width: 0; display: grid; gap: 16px; padding: 18px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); } +.settings-section .mini-heading > div { display: grid; gap: 3px; } +.settings-section .mini-heading small { text-align: left; line-height: 1.45; } +.visitor-control-row { display: flex; align-items: center; justify-content: space-between; gap: 18px; padding-top: 14px; border-top: 1px solid var(--border); } +.visitor-control-row > div:first-child { min-width: 0; display: grid; gap: 4px; } +.visitor-control-row small { max-width: 720px; color: var(--muted); line-height: 1.45; } +.segmented-control { flex: none; display: grid; grid-template-columns: repeat(2, minmax(96px, 1fr)); padding: 3px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-strong); } +.segmented-control button { min-height: 38px; padding: 6px 12px; border: 1px solid transparent; border-radius: 5px; background: transparent; color: var(--muted); font-weight: 800; cursor: pointer; } +.segmented-control button[aria-pressed="true"] { border-color: var(--accent); background: var(--surface); color: var(--text); box-shadow: 0 2px 8px rgb(0 0 0 / 18%); } +.segmented-control button:hover, .segmented-control button:focus-visible { color: var(--text); border-color: var(--accent); } +.branding-layout { display: grid; grid-template-columns: minmax(280px, 360px) minmax(0, 1fr); gap: 20px; align-items: stretch; padding-top: 14px; border-top: 1px solid var(--border); } +.logo-editor { position: relative; min-width: 0; display: grid; align-content: start; gap: 8px; } +.logo-preview-button { + position: relative; overflow: hidden; min-height: 210px; display: grid; place-items: center; padding: 14px; + border: 1px solid var(--border); border-radius: 9px; background: var(--surface-strong); color: var(--text); cursor: pointer; +} +.logo-preview-button img { width: min(100%, 320px); height: 200px; display: block; object-fit: contain; } +.logo-preview-button span { + position: absolute; inset: auto 10px 10px; padding: 8px 10px; border: 1px solid var(--accent); border-radius: 6px; + background: color-mix(in srgb, var(--topbar) 90%, transparent); color: var(--text); font-size: 12px; font-weight: 800; + opacity: 0; transform: translateY(4px); +} +.logo-preview-button:hover, .logo-preview-button:focus-visible { border-color: var(--accent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 28%, transparent); } +.logo-preview-button:hover span, .logo-preview-button:focus-visible span { opacity: 1; transform: translateY(0); } +.logo-remove-button { + position: absolute; z-index: 2; top: 10px; right: 10px; width: 42px; height: 42px; display: grid; place-items: center; + padding: 0; border: 1px solid var(--danger); border-radius: 7px; background: color-mix(in srgb, var(--topbar) 88%, transparent); color: var(--danger); cursor: pointer; +} +.logo-remove-button:hover, .logo-remove-button:focus-visible { background: color-mix(in srgb, var(--danger) 26%, var(--topbar)); box-shadow: 0 0 0 2px color-mix(in srgb, var(--danger) 24%, transparent); } +.logo-editor > small { color: var(--muted); line-height: 1.45; } +.settings-action-bar { + position: fixed; z-index: 10; left: 50%; bottom: max(12px, env(safe-area-inset-bottom)); transform: translateX(-50%); + display: flex; align-items: center; justify-content: space-between; gap: 16px; + width: min(720px, calc(100vw - 24px - env(safe-area-inset-left) - env(safe-area-inset-right))); margin: 0; padding: 10px 12px; border: 1px solid var(--accent); + border-radius: 9px; background: color-mix(in srgb, var(--topbar) 94%, transparent); box-shadow: 0 10px 34px rgb(0 0 0 / 34%); backdrop-filter: blur(10px); +} +.settings-action-bar > span { color: var(--text); font-weight: 750; } +.settings-action-bar > span[data-kind="error"] { color: var(--danger); } +.settings-action-bar > div { flex: none; display: flex; gap: 8px; } +.socials-form, .social-admin-list { display: grid; gap: 12px; } +.social-add-fields { grid-template-columns: minmax(240px, 2fr) minmax(150px, 1fr) minmax(180px, 1fr) auto; align-items: end; } +.social-add-fields > button { min-height: 42px; } +.social-form-error { margin: 0; color: var(--danger); font-weight: 750; } +.social-admin-item { + min-width: 0; display: grid; grid-template-columns: 32px 56px minmax(0, 1fr) 42px; align-items: center; gap: 10px; + padding: 0 0 12px; border-bottom: 1px solid var(--border); +} +.social-admin-item:last-child { padding-bottom: 0; border-bottom: 0; } +.social-admin-item.is-dragging { opacity: .45; } +.social-admin-item.is-drag-target { box-shadow: inset 3px 0 var(--accent); } +.social-order-controls { + overflow: hidden; display: grid; align-self: stretch; min-height: 88px; border: 1px solid var(--border); + border-radius: 7px; background: var(--surface-strong); +} +.social-order-button { + min-width: 0; min-height: 28px; display: grid; place-items: center; padding: 0; border: 0; + border-bottom: 1px solid var(--border); background: transparent; color: var(--muted); cursor: pointer; +} +.social-order-button:last-child { border-bottom: 0; } +.social-order-button:hover, .social-order-button:focus-visible { background: var(--surface); color: var(--accent); } +.social-order-button:disabled { opacity: .25; cursor: default; } +.social-order-button svg { width: 17px; height: 17px; fill: currentColor; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.social-drag-handle { cursor: grab; } +.social-drag-handle:active { cursor: grabbing; } +.social-admin-graphic { position: relative; width: 56px; height: 56px; } +.social-admin-icon { + position: relative; overflow: hidden; width: 56px; height: 56px; display: grid; place-items: center; padding: 0; + border: 1px solid var(--border); border-radius: 7px; background: var(--surface-strong); color: var(--accent); cursor: pointer; +} +.social-admin-icon:hover, .social-admin-icon:focus-visible { border-color: var(--accent); } +.social-admin-icon > img { width: 100%; height: 100%; display: block; object-fit: cover; } +.social-admin-platform-icon { display: grid; place-items: center; } +.social-admin-platform-icon > svg { width: 26px; height: 26px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.8; } +.social-graphic-badge { + position: absolute; right: 3px; bottom: 3px; width: 21px; height: 21px; display: grid; place-items: center; + border: 1px solid var(--accent); border-radius: 50%; background: color-mix(in srgb, var(--surface) 90%, transparent); color: var(--accent); +} +.social-graphic-badge svg, .social-graphic-reset svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.social-graphic-reset { + position: absolute; z-index: 2; top: -7px; right: -7px; width: 24px; height: 24px; display: grid; place-items: center; + padding: 0; border: 1px solid var(--border); border-radius: 50%; background: var(--surface); color: var(--muted); cursor: pointer; +} +.social-graphic-reset:hover, .social-graphic-reset:focus-visible { border-color: var(--accent); color: var(--accent); } +.social-row-fields { grid-template-columns: minmax(220px, 2fr) minmax(150px, 1fr) minmax(170px, 1fr); } +.social-row-actions { display: grid; } +.social-remove { width: 42px; height: 42px; display: grid; place-items: center; padding: 0; } .mini-heading { display: flex; justify-content: space-between; align-items: end; gap: 10px; } .mini-heading strong { font-size: 15px; } .mini-heading small { max-width: 620px; text-align: right; } -.style-fields { display: grid; max-width: 560px; gap: 12px; align-items: start; } -.style-fields label, .preset-field { min-width: 0; display: grid; gap: 5px; color: var(--muted); font-size: 12px; font-weight: 800; text-transform: uppercase; } .select-shell { position: relative; display: block; min-width: 0; } .select-shell::after { content: ""; position: absolute; right: 14px; top: calc(50% - 6px); width: 9px; height: 9px; @@ -166,55 +282,7 @@ h1, h2 { margin: 2px 0; } background: var(--surface-strong); color: var(--control-text); padding: 9px 40px 9px 11px; text-transform: none; font-weight: 650; } .field-label { color: var(--muted); } -.preset-select { position: relative; min-width: 0; width: 100%; max-width: 560px; } -.preset-trigger, .preset-option { - min-width: 0; width: 100%; display: grid; align-items: center; gap: 10px; - border: 1px solid var(--border); border-radius: 8px; background: var(--surface-strong); color: var(--control-text); cursor: pointer; - text-align: left; -} -.preset-trigger { min-height: 58px; grid-template-columns: 92px minmax(0, 1fr) 16px; padding: 10px; } -.preset-trigger::after { - content: ""; width: 9px; height: 9px; justify-self: end; border-right: 2px solid var(--muted); border-bottom: 2px solid var(--muted); - transform: translateY(-2px) rotate(45deg); -} -.preset-menu { - position: absolute; z-index: 8; top: calc(100% + 6px); left: 0; width: min(560px, 100%); - max-height: min(360px, calc(100vh - 240px)); overflow: auto; display: grid; gap: 6px; - padding: 8px; border: 1px solid var(--border); border-radius: 8px; background: var(--topbar); - box-shadow: 0 16px 40px rgb(0 0 0 / 28%); -} -.preset-option-row { display: grid; grid-template-columns: minmax(0, 1fr); align-items: stretch; gap: 6px; } -.preset-option-row[data-custom-profile="true"] { grid-template-columns: minmax(0, 1fr) 42px; } -.preset-option { min-height: 54px; grid-template-columns: 92px minmax(0, 1fr); padding: 9px; } -.preset-option-main[aria-selected="true"] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--secondary); } -.preset-trigger strong, .preset-option strong { overflow: hidden; display: block; white-space: nowrap; text-overflow: ellipsis; } -.preset-trigger[data-default-profile="true"] strong::after, .preset-option[data-default-profile="true"] strong::after { - content: "\2605"; display: inline-block; margin-left: 6px; color: var(--accent); -} -.preset-trigger small, .preset-option small { display: block; color: var(--muted); } -.swatches { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px; } -.swatches i { height: 28px; border: 1px solid var(--border); border-radius: 5px; } -.preset-delete { - min-width: 42px; min-height: 54px; display: grid; place-items: center; border: 1px solid var(--danger); - border-radius: 8px; background: color-mix(in srgb, var(--danger) 24%, var(--surface)); color: var(--control-text); cursor: pointer; -} -.preset-delete:hover { background: color-mix(in srgb, var(--danger) 36%, var(--surface)); } -.trash-icon { - position: relative; width: 15px; height: 15px; display: block; border: 2px solid currentColor; border-top: 0; border-radius: 0 0 3px 3px; -} -.trash-icon::before { - content: ""; position: absolute; left: -4px; top: -6px; width: 19px; height: 2px; border-radius: 999px; background: currentColor; -} -.trash-icon::after { - content: ""; position: absolute; left: 3px; top: -10px; width: 7px; height: 4px; border: 2px solid currentColor; border-bottom: 0; border-radius: 3px 3px 0 0; -} -.logo-controls { display: flex; align-items: center; gap: 12px; } -.logo-controls img { - width: auto; max-width: min(360px, 46vw); height: auto; max-height: 120px; object-fit: contain; - padding: 8px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-strong); -} -.logo-controls > div { display: grid; gap: 8px; } -.logo-controls input { max-width: 100%; color: var(--muted); } +.trash-icon { width: 18px; height: 18px; display: block; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 2; } .logo-crop-dialog { width: min(980px, calc(100vw - 24px)); } .logo-crop-layout { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 14px; align-items: start; } .logo-crop-stage { @@ -262,6 +330,7 @@ h1, h2 { margin: 2px 0; } .logo-ratio-inputs span { color: var(--muted); font-weight: 900; } .logo-crop-dialog:not([data-crop-mode="custom"]) .logo-ratio-inputs, .logo-crop-dialog[data-crop-mode="full"] .logo-zoom-field { display: none; } +.logo-crop-dialog[data-crop-target="social"] #logo-shape-controls { display: none; } .logo-crop-handle { position: absolute; display: none; width: 18px; height: 18px; border: 2px solid var(--accent); border-radius: 4px; background: var(--surface); box-shadow: 0 1px 8px rgb(0 0 0 / 35%); @@ -287,25 +356,54 @@ h1, h2 { margin: 2px 0; } } .preset-dialog::backdrop { background: rgb(0 0 0 / 62%); } .confirm-dialog { width: min(520px, calc(100vw - 24px)); } +.confirm-dialog.has-media { width: fit-content; max-width: calc(100vw - 24px); overflow: hidden; } +.confirm-dialog.has-media .dialog-panel { width: fit-content; max-width: calc(100vw - 24px); } +.confirm-media { + width: fit-content; max-width: 100%; justify-self: center; overflow: hidden; + border: 1px solid var(--border); border-radius: 8px; background: var(--surface-strong); +} +.confirm-media:not([hidden]) { display: grid; } +.confirm-media img { + width: auto; max-width: min(920px, calc(100vw - 58px)); height: auto; max-height: max(80px, calc(100dvh - 220px)); + display: block; object-fit: contain; +} .dialog-panel { display: grid; gap: 14px; padding: 16px; } .dialog-heading p { margin: 0; color: var(--accent); font-size: 12px; font-weight: 800; text-transform: uppercase; } .dialog-heading h2 { margin: 2px 0 0; } .dialog-copy { margin: 0; color: var(--muted); line-height: 1.45; } -.choice-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } -.choice-grid button { - min-height: 86px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); color: var(--control-text); - font-weight: 800; cursor: pointer; -} -.choice-grid button:hover { border-color: var(--accent); } .dialog-actions { display: flex; justify-content: end; gap: 8px; } -.palette-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; } -.palette-group { min-width: 0; display: grid; gap: 8px; padding: 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); } -.palette-group h3 { margin: 0; font-size: 15px; } -.color-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } -.color-grid label { min-width: 0; display: grid; gap: 4px; color: var(--muted); font-size: 11px; font-weight: 800; text-transform: uppercase; } -.color-grid input { width: 100%; min-height: 34px; padding: 2px; border: 1px solid var(--border); border-radius: 5px; background: var(--surface-strong); cursor: pointer; } button:disabled { opacity: .45; cursor: wait; } +body.cover-picker-open { overflow: hidden; } +.cover-picker { + position: fixed; z-index: 20; inset: 0; width: 100vw; max-width: none; height: 100dvh; max-height: none; margin: 0; overflow: auto; + padding: calc(112px + env(safe-area-inset-top)) calc(5px + env(safe-area-inset-right)) calc(5px + env(safe-area-inset-bottom)) calc(5px + env(safe-area-inset-left)); + border: 0; border-radius: 0; background: var(--background); color: var(--text); +} +.cover-picker::backdrop { background: var(--background); } +.cover-picker-toolbar { + position: fixed; z-index: 22; top: max(16px, env(safe-area-inset-top)); left: 50%; width: min(520px, calc(100vw - 24px)); + display: grid; justify-items: center; gap: 8px; transform: translateX(-50%); pointer-events: none; +} +.cover-picker-cancel { min-width: 160px; box-shadow: 0 8px 28px rgb(0 0 0 / 40%); backdrop-filter: blur(10px); pointer-events: auto; } +.cover-picker-status { + max-width: 100%; margin: 0; padding: 7px 10px; border: 1px solid var(--accent); border-radius: 999px; + background: color-mix(in srgb, var(--topbar) 94%, transparent); color: var(--text); font-size: 12px; font-weight: 800; + box-shadow: 0 8px 28px rgb(0 0 0 / 34%); backdrop-filter: blur(10px); text-align: center; +} +.cover-picker-status[data-kind="error"] { border-color: var(--danger); color: var(--danger); } +.cover-picker-grid { display: grid; align-content: start; gap: 5px; } +.cover-picker-row { min-width: 0; display: flex; flex-wrap: nowrap; align-items: start; gap: 5px; } +.cover-picker-photo { + position: relative; min-width: 0; overflow: hidden; display: block; padding: 0; border: 0; border-radius: 2px; + background: var(--surface-strong); cursor: pointer; +} +.cover-picker-photo img { width: 100%; height: 100%; display: block; object-fit: contain; background: var(--surface-strong); transition: filter 150ms ease, transform 150ms ease; } +.cover-picker-photo::after { content: ""; position: absolute; inset: 0; border: 2px solid transparent; pointer-events: none; transition: border-color 150ms ease, background-color 150ms ease; } +.cover-picker-photo:hover::after, .cover-picker-photo:focus-visible::after { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 9%, transparent); } +.cover-picker-photo:hover img, .cover-picker-photo:focus-visible img { filter: brightness(1.08); transform: scale(1.01); } +.cover-picker-photo:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } + .explore-admin-page main { width: min(1700px, 100%); } .privacy-warning { position: relative; display: grid; gap: 4px; margin: 0; padding: 12px 42px 12px 14px; border: 1px solid var(--warning, #f0b429); @@ -406,6 +504,8 @@ button:disabled { opacity: .45; cursor: wait; } .explore-admin-page .page-heading { display: none; } } @media (max-width: 900px) { + .branding-layout { grid-template-columns: 1fr; } + .logo-editor { width: min(100%, 420px); justify-self: center; } .explore-admin-layout { grid-template-columns: 1fr; } .explore-admin-map { min-height: 420px; height: 58vh; } } @@ -416,24 +516,33 @@ button:disabled { opacity: .45; cursor: wait; } .page-heading, .section-heading, .trash-album-heading { align-items: stretch; display: grid; } .page-heading .status { justify-self: start; } .section-heading > button { width: 100%; } - .section-actions { display: grid; } + .section-actions { display: grid; grid-template-columns: minmax(0, 1fr) 42px; } + .cover-management-panel, .visitor-control-row { align-items: stretch; display: grid; } + .cover-management-panel > button { width: 100%; } + .segmented-control { width: 100%; grid-template-columns: repeat(2, minmax(0, 1fr)); } .photo-grid, .trash-photo-grid { grid-template-columns: repeat(2, calc((100% - 7px) / 2)); gap: 7px; } - .photo-card > span, .trash-photo > span { padding: 7px; font-size: 12px; } + .photo-details { gap: 6px; padding: 6px; } + .photo-details > span, .trash-photo > span { font-size: 12px; } .trash-photo > div { display: grid; padding: 0 6px; } .trash-album-heading > div:last-child { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } .section-tabs { overflow-x: auto; } - .subtabs, .field-grid, .branding-fields, .style-fields { grid-template-columns: 1fr; max-width: none; } + .subtabs, .field-grid, .branding-fields, .social-add-fields, .social-row-fields { grid-template-columns: 1fr; max-width: none; } + .social-admin-item { grid-template-columns: 32px 56px minmax(0, 1fr) 42px; align-items: start; } + .social-order-controls { grid-column: 1; grid-row: 1 / span 2; } + .social-admin-graphic { grid-column: 2; grid-row: 1; } + .social-row-fields { grid-column: 2 / -1; grid-row: 2; } + .social-row-actions { grid-column: 4; grid-row: 1; } .mini-heading { display: grid; } .mini-heading small { text-align: left; } - .logo-controls { align-items: stretch; display: grid; } - .logo-controls img { max-width: 100%; } + .branding-panel { padding: 14px; } + .logo-preview-button { min-height: 180px; padding: 12px; } + .logo-preview-button img { width: min(100%, 280px); height: 150px; } + .settings-action-bar { align-items: stretch; display: grid; width: calc(100vw - 20px - env(safe-area-inset-left) - env(safe-area-inset-right)); bottom: max(8px, env(safe-area-inset-bottom)); } + .settings-action-bar > div { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } .logo-crop-layout { grid-template-columns: 1fr; } .logo-crop-stage { min-height: min(48vh, 360px); } - .preset-trigger { grid-template-columns: 78px minmax(0, 1fr) 16px; } - .preset-option { grid-template-columns: 78px minmax(0, 1fr); } - .preset-option-row[data-custom-profile="true"] { grid-template-columns: minmax(0, 1fr) 42px; } - .palette-fields, .choice-grid, .color-grid { grid-template-columns: 1fr; } - .dialog-actions { display: grid; } + .dialog-actions > button { min-width: 0; flex: 1; } + .confirm-media img { max-width: calc(100vw - 58px); max-height: max(56px, calc(100dvh - 270px)); } .explore-admin-page .header-actions { display: grid; gap: 5px; } .explore-admin-page .header-actions .gallery-button { min-height: 34px; padding: 5px 8px; font-size: 12px; } .explore-time-fields { grid-template-columns: 1fr; } diff --git a/services/frame-gallery/public/admin.html b/services/frame-gallery/public/admin.html index 1c8c4af..8733f30 100644 --- a/services/frame-gallery/public/admin.html +++ b/services/frame-gallery/public/admin.html @@ -29,7 +29,7 @@ })(); - +
@@ -53,12 +53,13 @@

Gallery Admin

Loading photo library... - Connecting + Connecting
@@ -74,9 +75,16 @@

Gallery Admin

Published album

Manage Explore - +
+
+
+ Cover image +

Automatic cover uses the earliest published photo.

+
+ +
@@ -97,91 +105,83 @@

Gallery Admin

- + - + - - + + + +
+ + +
+ +
+
+ + + - + diff --git a/services/frame-gallery/public/justified-rows.js b/services/frame-gallery/public/justified-rows.js new file mode 100644 index 0000000..3225b58 --- /dev/null +++ b/services/frame-gallery/public/justified-rows.js @@ -0,0 +1,62 @@ +const FALLBACK_RATIO = 4 / 3; + +export function planJustifiedRows(ratios, width, targetHeight, gap = 5) { + if (!ratios.length || width < 1 || targetHeight < 1) return []; + const normalized = ratios.map((ratio) => Number.isFinite(Number(ratio)) && Number(ratio) > 0 ? Number(ratio) : FALLBACK_RATIO); + const rows = []; + let row = []; + let ratioTotal = 0; + + const finishRow = (last) => { + const available = width - gap * Math.max(0, row.length - 1); + const fillHeight = available / ratioTotal; + const partial = last && fillHeight > targetHeight * 1.5; + rows.push({ items: row, height: partial ? targetHeight : fillHeight, partial }); + row = []; + ratioTotal = 0; + }; + + normalized.forEach((ratio, index) => { + const currentWidth = ratioTotal * targetHeight + gap * Math.max(0, row.length - 1); + const projectedWidth = currentWidth + (row.length ? gap : 0) + ratio * targetHeight; + if (row.length && projectedWidth > width && index < normalized.length - 1) { + const nextIsPenultimate = index === normalized.length - 2; + const includeNext = !nextIsPenultimate && width - currentWidth > projectedWidth - width; + if (includeNext) { + row.push({ index, ratio }); + ratioTotal += ratio; + finishRow(false); + return; + } + finishRow(false); + } + row.push({ index, ratio }); + ratioTotal += ratio; + if (index === normalized.length - 1) finishRow(true); + }); + + return rows; +} + +export function layoutJustifiedRows(container, items, { rowClass, targetHeight, gap = 5 }) { + const rows = planJustifiedRows(items.map((item) => item.dataset.ratio), container.clientWidth, targetHeight, gap); + if (!rows.length) return; + const activeElement = items.some((item) => item.contains(container.ownerDocument.activeElement)) + ? container.ownerDocument.activeElement + : null; + const rowElements = rows.map((row) => { + const element = container.ownerDocument.createElement("div"); + element.className = `${rowClass}${row.partial ? " is-partial" : ""}`; + for (const entry of row.items) { + const item = items[entry.index]; + item.style.aspectRatio = String(entry.ratio); + item.style.flex = row.partial ? "none" : `${entry.ratio * 100} 1 0px`; + item.style.width = row.partial ? `${Math.max(1, entry.ratio * row.height)}px` : ""; + item.style.height = row.partial ? `${Math.max(1, row.height)}px` : ""; + element.append(item); + } + return element; + }); + container.replaceChildren(...rowElements); + if (activeElement?.isConnected) activeElement.focus({ preventScroll: true }); +} diff --git a/services/frame-gallery/public/socials.js b/services/frame-gallery/public/socials.js new file mode 100644 index 0000000..1585d92 --- /dev/null +++ b/services/frame-gallery/public/socials.js @@ -0,0 +1,128 @@ +export const SOCIAL_PLATFORMS = Object.freeze([ + ["website", "Website"], + ["instagram", "Instagram"], + ["tiktok", "TikTok"], + ["youtube", "YouTube"], + ["twitch", "Twitch"], + ["facebook", "Facebook"], + ["x", "X"], + ["threads", "Threads"], + ["bluesky", "Bluesky"], + ["discord", "Discord invite"], + ["linkedin", "LinkedIn"], + ["reddit", "Reddit"], + ["snapchat", "Snapchat"], + ["flickr", "Flickr"], +].map(([id, label]) => Object.freeze({ id, label }))); + +const PLATFORM_HOSTS = { + instagram: ["instagram.com"], + tiktok: ["tiktok.com"], + youtube: ["youtube.com", "youtu.be"], + twitch: ["twitch.tv"], + facebook: ["facebook.com", "fb.com"], + x: ["x.com", "twitter.com"], + threads: ["threads.com", "threads.net"], + bluesky: ["bsky.app"], + discord: ["discord.gg", "discord.com", "discordapp.com"], + linkedin: ["linkedin.com"], + reddit: ["reddit.com"], + snapchat: ["snapchat.com"], + flickr: ["flickr.com", "flic.kr"], +}; + +const ICONS = { + website: ``, + instagram: ``, + tiktok: ``, + youtube: ``, + twitch: ``, + facebook: ``, + x: ``, + threads: ``, + bluesky: ``, + discord: ``, + linkedin: ``, + reddit: ``, + snapchat: ``, + flickr: ``, +}; + +export function detectSocialPlatform(value) { + const input = String(value || "").trim(); + if (!input) return null; + if (input.startsWith("@")) return null; + if (!/[/:]/.test(input) && /\.bsky\.social$/i.test(input)) return "bluesky"; + const url = parseWebUrl(input); + if (!url) return null; + const host = url.hostname.toLowerCase().replace(/^www\./, ""); + for (const [platform, hosts] of Object.entries(PLATFORM_HOSTS)) { + if (hosts.some((candidate) => host === candidate || host.endsWith(`.${candidate}`))) return platform; + } + return "website"; +} + +export function buildSocialUrl(value, platform) { + const input = String(value || "").trim(); + if (!input) throw new Error("Enter a URL or handle."); + const forcedHandle = input.startsWith("@"); + const detected = forcedHandle ? null : detectSocialPlatform(input); + const bareBlueskyHandle = platform === "bluesky" && !/^(?:https?:\/\/|www\.)/i.test(input) && !input.includes("/"); + const explicitUrl = !bareBlueskyHandle && (/^(?:https?:\/\/|www\.)/i.test(input) || input.includes("/") || (detected && detected !== "website")); + if (platform === "website" || (!forcedHandle && explicitUrl)) { + const url = parseWebUrl(input); + if (!url) throw new Error("Enter a valid public website URL."); + return url.toString(); + } + + const handle = input.replace(/^@/, "").trim(); + if (!handle || /\s/.test(handle)) throw new Error("Enter a valid handle."); + const encoded = encodeURIComponent(handle); + const urls = { + instagram: `https://www.instagram.com/${encoded}/`, + tiktok: `https://www.tiktok.com/@${encoded}`, + youtube: `https://www.youtube.com/@${encoded}`, + twitch: `https://www.twitch.tv/${encoded}`, + facebook: `https://www.facebook.com/${encoded}`, + x: `https://x.com/${encoded}`, + threads: `https://www.threads.com/@${encoded}`, + bluesky: `https://bsky.app/profile/${encoded}`, + discord: `https://discord.gg/${encoded}`, + linkedin: `https://www.linkedin.com/in/${encoded}`, + reddit: `https://www.reddit.com/user/${encoded}/`, + snapchat: `https://www.snapchat.com/add/${encoded}`, + flickr: `https://www.flickr.com/photos/${encoded}/`, + }; + if (!urls[platform]) throw new Error("Select a platform for this handle."); + return urls[platform]; +} + +export function resolveSocialPlatform(value, selected) { + const detected = detectSocialPlatform(value); + if (!detected) return selected; + if (detected !== "website" || looksLikeExplicitUrl(value) || !selected) return detected; + return selected; +} + +export function socialIcon(platform) { + return ICONS[platform] || ICONS.website; +} + +export function createSocialId() { + return globalThis.crypto?.randomUUID?.() || `social-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +} + +function parseWebUrl(value) { + try { + const url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(value) ? value : `https://${value}`); + const publicHost = url.hostname.includes(".") || url.hostname.includes(":"); + return publicHost && (url.protocol === "http:" || url.protocol === "https:") ? url : null; + } catch { + return null; + } +} + +function looksLikeExplicitUrl(value) { + const input = String(value || "").trim(); + return /^(?:https?:\/\/|www\.)/i.test(input) || input.includes("/"); +} diff --git a/services/frame-gallery/public/styles.css b/services/frame-gallery/public/styles.css index b31eaef..e5e28cc 100644 --- a/services/frame-gallery/public/styles.css +++ b/services/frame-gallery/public/styles.css @@ -45,7 +45,8 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s justify-content: space-between; gap: 18px; padding: 10px clamp(14px, 4vw, 42px); border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--topbar) 94%, transparent); backdrop-filter: blur(16px); } -.brand { min-width: 0; display: flex; align-items: center; gap: 12px; color: inherit; text-decoration: none; } +.brand-cluster { min-width: 0; flex: 1 1 auto; display: flex; align-items: center; gap: 12px; } +.brand { min-width: 0; flex: 0 1 auto; display: flex; align-items: center; gap: 12px; color: inherit; text-decoration: none; } .brand img { width: auto; max-width: min(220px, 38vw); height: 54px; max-height: 54px; object-fit: contain; flex: none; } .brand span { display: grid; min-width: 0; } .brand small { color: var(--accent); font-weight: 800; } @@ -56,6 +57,8 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s .summary span, .date-summary { color: var(--muted); font-size: 13px; } main { width: min(1500px, 100%); margin: 0 auto; padding: 18px clamp(12px, 3vw, 32px) 48px; } +.is-photo-grid main { width: 100%; padding-inline: 5px; } +.is-photo-grid .gallery-heading { margin-inline: clamp(7px, 2vw, 27px); } .gallery-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; margin: 12px 0 18px; } .gallery-heading > div { min-width: 0; } .gallery-heading p { margin: 0; color: var(--accent); font-weight: 800; } @@ -76,6 +79,16 @@ main { width: min(1500px, 100%); margin: 0 auto; padding: 18px clamp(12px, 3vw, width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 2; } .theme-toggle { width: 38px; min-width: 38px; min-height: 34px; padding: 7px; border-color: var(--accent); background: var(--toggle-night-bg, #dff4ff); color: var(--toggle-night-text, #087fc0); } +.socials-button { + flex: none; min-height: 38px; border-color: color-mix(in srgb, var(--accent) 78%, white); background: var(--accent); + color: var(--accent-contrast, var(--action-text, #03121b)); font-weight: 800; box-shadow: 0 5px 14px color-mix(in srgb, var(--accent) 18%, transparent); + animation: socials-glow 2.8s ease-in-out infinite; +} +.socials-button:hover { border-color: var(--accent); filter: brightness(1.06); } +@keyframes socials-glow { + 0%, 100% { box-shadow: 0 0 0 0 transparent, 0 5px 14px color-mix(in srgb, var(--accent) 18%, transparent); } + 50% { box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 16%, transparent), 0 5px 18px color-mix(in srgb, var(--accent) 30%, transparent); } +} :root[data-theme="day"] .theme-toggle, :root[data-theme-mode="day"] .theme-toggle, .theme-toggle[aria-pressed="true"] { border-color: var(--accent); background: var(--toggle-day-bg, #fff6d5); color: var(--toggle-day-text, #8a5e00); } .secondary-button:hover, .icon-button:hover, .icon-toggle:hover, .lightbox-control:hover { border-color: var(--accent); } .view-switch { display: inline-flex; overflow: hidden; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); } @@ -83,20 +96,50 @@ main { width: min(1500px, 100%); margin: 0 auto; padding: 18px clamp(12px, 3vw, .view-switch button + button { border-left: 1px solid var(--border); } .view-switch button[aria-pressed="true"] { background: var(--accent); color: var(--background); font-weight: 800; } -.date-grid, .gallery-grid { width: 100%; min-width: 0; display: grid; gap: 12px; } -.date-grid { grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr)); } -.gallery-grid { grid-template-columns: repeat(auto-fill, minmax(min(230px, 100%), 1fr)); } -.date-card, .photo-card { +.date-grid, .gallery-grid { width: 100%; min-width: 0; } +.date-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr)); gap: 12px; } +.gallery-grid { display: grid; align-content: start; gap: 5px; } +.gallery-photo-row { min-width: 0; display: flex; flex-wrap: nowrap; align-items: start; gap: 5px; } +.date-card { position: relative; min-width: 0; overflow: hidden; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); transition: border-color 120ms ease, transform 120ms ease; } -.date-card:hover, .photo-card:hover { border-color: var(--accent); box-shadow: 0 0 0 1px var(--secondary); transform: translateY(-1px); } -.date-open, .photo-open { min-width: 0; display: grid; width: 100%; padding: 0; border: 0; background: transparent; color: inherit; text-align: left; text-decoration: none; cursor: pointer; } -.date-card img, .photo-open img { width: 100%; aspect-ratio: 4 / 3; display: block; object-fit: cover; background: var(--surface-strong); } -.date-card-meta, .photo-meta { min-width: 0; display: grid; gap: 3px; padding: 10px 58px 12px 12px; } -.date-card.has-map-action .date-card-meta, .photo-card.has-map-action .photo-meta { padding-right: 102px; } -.date-card-meta strong, .photo-meta strong { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } -.date-card-stats, .photo-meta small { color: var(--muted); font-size: 12px; } +.date-card:hover { border-color: var(--accent); box-shadow: 0 0 0 1px var(--secondary); transform: translateY(-1px); } +.date-open { min-width: 0; display: grid; width: 100%; padding: 0; border: 0; background: transparent; color: inherit; text-align: left; text-decoration: none; cursor: pointer; } +.date-card img { width: 100%; aspect-ratio: 4 / 3; display: block; object-fit: cover; background: var(--surface-strong); } +.date-card-meta { min-width: 0; display: grid; gap: 3px; padding: 10px 58px 12px 12px; } +.date-card.has-map-action .date-card-meta { padding-right: 102px; } +.date-card-meta strong { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.date-card-stats { color: var(--muted); font-size: 12px; } +.photo-card { position: relative; min-width: 0; overflow: hidden; border-radius: 2px; background: var(--surface-strong); } +.photo-card::after { + content: ""; position: absolute; z-index: 4; inset: 0; opacity: 0; pointer-events: none; + box-shadow: inset 0 0 0 3px var(--accent); transition: opacity 120ms ease; +} +.photo-card:focus-within::after { opacity: 1; } +.photo-open { position: absolute; inset: 0; width: 100%; height: 100%; padding: 0; border: 0; background: transparent; color: inherit; cursor: pointer; } +.photo-open img { width: 100%; height: 100%; display: block; object-fit: contain; background: var(--surface-strong); transition: filter 150ms ease; } +.photo-open:focus-visible { outline: 0; } +.photo-overlay { + position: absolute; z-index: 2; inset: 0; opacity: 0; transform: translateY(4px); pointer-events: none; + background: linear-gradient(180deg, transparent 48%, rgb(0 0 0 / 18%) 62%, rgb(0 0 0 / 82%) 100%); + transition: opacity 150ms ease, transform 150ms ease; +} +.photo-meta { + position: absolute; z-index: 1; right: 58px; bottom: 10px; left: 12px; min-width: 0; display: grid; gap: 2px; + color: #fff; text-shadow: 0 1px 3px rgb(0 0 0 / 78%); +} +.photo-card.has-map-action .photo-meta { right: 102px; } +.photo-meta strong { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.photo-meta time { color: rgb(255 255 255 / 82%); font-size: 12px; } +.photo-card:focus-within .photo-overlay { opacity: 1; transform: none; } +.photo-card:focus-within .photo-overlay .card-action { pointer-events: auto; } +.photo-card:focus-within .photo-open img { filter: brightness(1.04); } +@media (hover: hover) and (pointer: fine) { + .photo-card:hover .photo-overlay { opacity: 1; transform: none; } + .photo-card:hover .photo-overlay .card-action { pointer-events: auto; } + .photo-card:hover .photo-open img { filter: brightness(1.04); } +} .card-actions { position: absolute; z-index: 2; right: 8px; bottom: 8px; display: flex; gap: 6px; } .card-action { position: absolute; z-index: 2; right: 8px; bottom: 8px; width: 38px; height: 38px; display: inline-flex; align-items: center; justify-content: center; @@ -105,6 +148,8 @@ main { width: min(1500px, 100%); margin: 0 auto; padding: 18px clamp(12px, 3vw, } .card-actions .card-action { position: static; } .card-action:hover { background: var(--accent); color: var(--background); } +.photo-overlay .card-action { pointer-events: none; } +.photo-overlay .card-action:focus-visible { outline: 0; box-shadow: 0 0 0 3px var(--accent); } .card-action svg, .lightbox-photo-button svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.8; } @@ -195,6 +240,35 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } .share-status { min-height: 1.25em; margin: 0; color: var(--text); font-size: 13px; } .share-status[data-error="true"] { font-weight: 700; } +.socials-dialog { + width: min(900px, calc(100vw - 24px)); max-width: none; height: min(760px, calc(100dvh - 24px)); max-height: none; + overflow: hidden; padding: 0; border: 1px solid var(--border); border-radius: 8px; background: var(--background); color: var(--text); +} +.socials-dialog::backdrop { background: rgb(0 0 0 / 62%); } +.socials-dialog-panel { height: 100%; display: grid; grid-template-rows: auto auto minmax(0, 1fr) auto; gap: 14px; margin: 0; padding: 18px; } +.socials-list { min-height: 0; overflow-y: auto; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); } +.social-link { min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 14px; padding: 14px 2px; } +.social-link + .social-link { border-top: 1px solid var(--border); } +.social-link-identity { min-width: 0; display: grid; grid-template-columns: 42px minmax(0, 1fr); align-items: center; gap: 11px; border-radius: 7px; color: inherit; text-decoration: none; } +.social-link-identity:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; } +.social-link-identity:hover .social-platform-icon, .social-link-identity:focus-visible .social-platform-icon { border-color: var(--accent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 22%, transparent); } +.social-link-identity:hover .social-link-copy strong, .social-link-identity:focus-visible .social-link-copy strong { color: var(--accent); text-decoration: underline; text-underline-offset: 3px; } +.social-platform-icon { width: 42px; height: 42px; display: grid; place-items: center; border: 1px solid var(--border); border-radius: 50%; color: var(--accent); background: var(--surface); } +.social-platform-icon svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; } +.social-platform-icon.has-custom-graphic { overflow: hidden; border-radius: 8px; } +.social-platform-icon img { width: 100%; height: 100%; display: block; object-fit: cover; } +.social-link-copy { min-width: 0; display: grid; gap: 3px; } +.social-link-copy strong, .social-link-copy small { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.social-link-copy small { color: var(--muted); } +.social-link-actions { display: flex; gap: 7px; } +.social-link-actions .icon-button { display: inline-grid; place-items: center; } +.social-link-actions svg { width: 19px; height: 19px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.social-qr-dialog { width: min(430px, calc(100vw - 24px)); } +.social-qr-panel { justify-items: stretch; } +.social-destination-qr { justify-self: center; } +.social-destination-qr figcaption { max-width: 340px; } +.social-destination-qr figcaption span { overflow-wrap: anywhere; } + .lightbox { position: fixed; width: 100vw; max-width: none; height: 100vh; max-height: none; margin: 0; padding: 0; border: 0; background: var(--lightbox-background); color: var(--lightbox-text); @@ -202,14 +276,50 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } .lightbox::backdrop { background: var(--lightbox-background); } .lightbox[open] { display: block; overflow: hidden; } .lightbox-viewport { - position: absolute; inset: 0; overflow: auto; display: grid; place-items: start center; padding: 54px 0 0; + position: absolute; inset: 0; overflow: auto; display: grid; place-items: center; padding: 54px 0 0; scrollbar-color: var(--accent) var(--topbar); overscroll-behavior: contain; touch-action: none; user-select: none; } -.lightbox-viewport img { display: block; max-width: none; max-height: none; cursor: zoom-in; } -.lightbox-viewport img.fit { width: 100%; height: calc(100vh - 54px); object-fit: contain; } +.lightbox-image { position: relative; flex: none; overflow: hidden; background: color-mix(in srgb, var(--lightbox-background) 88%, white); cursor: zoom-in; } +.lightbox-preview { position: absolute; inset: 0; width: 100%; height: 100%; display: block; object-fit: fill; opacity: 0; filter: blur(2px); transition: opacity 160ms ease, filter 160ms ease; pointer-events: none; } +.lightbox-preview.is-ready { opacity: 1; filter: none; } +.lightbox-preview.is-complete { opacity: 0; } +.lightbox-full { position: absolute; inset: 0; width: 100%; height: 100%; display: block; object-fit: fill; opacity: 0; transition: opacity 140ms ease; pointer-events: none; } +.lightbox-full.is-ready { opacity: 1; } +.lightbox-tiles { position: absolute; top: 0; left: 0; display: grid; gap: 0; transform-origin: 0 0; opacity: 0; transition: opacity 140ms ease; pointer-events: none; } +.lightbox-tiles.is-ready { opacity: 1; } +.lightbox-tile-clip { position: relative; min-width: 0; min-height: 0; overflow: hidden; } +.lightbox-tile-image { position: absolute; display: block; max-width: none; max-height: none; pointer-events: none; } +.lightbox-loading { + position: fixed; z-index: 2; top: 50%; left: 50%; display: inline-flex; align-items: center; gap: 9px; transform: translate(-50%, -50%); + padding: 9px 12px; border: 1px solid var(--border); border-radius: 6px; background: color-mix(in srgb, var(--topbar) 90%, transparent); + color: var(--lightbox-text); font: 700 12px/1.2 Inter, ui-sans-serif, system-ui, sans-serif; pointer-events: none; +} +.lightbox-loading[hidden] { display: none; } +.lightbox-loading::before { content: ""; width: 16px; height: 16px; border: 2px solid color-mix(in srgb, var(--accent) 30%, transparent); border-top-color: var(--accent); border-radius: 50%; animation: lightbox-loading-spin 700ms linear infinite; } +.lightbox-loading.is-upgrading, .lightbox-loading.is-complete { top: 64px; right: 8px; left: auto; padding: 7px 9px; transform: none; } +.lightbox-loading.is-upgrading::before { width: 12px; height: 12px; } +.lightbox-loading.is-complete { border-color: color-mix(in srgb, var(--accent) 72%, white); animation: lightbox-quality-ready 900ms ease-out both; } +.lightbox-loading.is-complete::before { + width: 14px; height: 14px; border: 0; border-radius: 0; background: var(--accent); + clip-path: polygon(50% 0, 61% 39%, 100% 50%, 61% 61%, 50% 100%, 39% 61%, 0 50%, 39% 39%); + animation: lightbox-quality-sparkle 650ms ease-out both; +} +.lightbox-loading.is-error::before { display: none; } +@keyframes lightbox-loading-spin { to { transform: rotate(360deg); } } +@keyframes lightbox-quality-ready { + 0% { opacity: 0; transform: translateY(-4px) scale(.96); } + 18%, 72% { opacity: 1; transform: translateY(0) scale(1); } + 100% { opacity: 0; transform: translateY(-2px) scale(.98); } +} +@keyframes lightbox-quality-sparkle { + 0% { opacity: 0; transform: rotate(-24deg) scale(.2); } + 48% { opacity: 1; transform: rotate(12deg) scale(1.35); } + 100% { opacity: 1; transform: rotate(0) scale(1); } +} .lightbox-viewport.is-zoomed { cursor: grab; } -.lightbox-viewport.is-zoomed img { margin: 22px auto 28px; cursor: grab; } -.lightbox-viewport.is-panning, .lightbox-viewport.is-panning img { cursor: grabbing; } +.lightbox-viewport.is-zoomed { align-items: start; justify-items: safe center; } +.lightbox-viewport.is-zoomed .lightbox-image { margin: 22px auto 28px; cursor: grab; } +.lightbox-viewport.is-panning, .lightbox-viewport.is-panning .lightbox-image { cursor: grabbing; } .lightbox-toolbar { position: absolute; z-index: 4; top: 0; right: 0; left: 0; min-height: 54px; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 7px 9px; border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--lightbox-background) 92%, transparent); @@ -255,16 +365,22 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } } .lightbox-photo-button:hover { background: var(--accent); color: var(--background); } .lightbox-photo-button svg { width: 18px; height: 18px; } -.lightbox-nav { position: absolute; z-index: 4; top: 50%; min-width: 42px; min-height: 54px; transform: translateY(-50%); background: color-mix(in srgb, var(--topbar) 82%, transparent); } +.lightbox-download-button { width: 34px; min-width: 34px; height: 34px; justify-content: center; padding: 7px; border-radius: 6px; text-decoration: none; } +.lightbox-nav { position: absolute; z-index: 4; top: 72%; width: 48px; min-width: 48px; min-height: 68px; padding: 10px 7px; transform: translateY(-50%); background: color-mix(in srgb, var(--topbar) 82%, transparent); opacity: .3; transition: opacity 180ms ease; } +.lightbox-nav svg { width: 30px; height: 46px; fill: none; stroke: currentColor; stroke-width: 2.3; stroke-linecap: round; stroke-linejoin: round; } .lightbox-nav.previous { left: 7px; } .lightbox-nav.next { right: 7px; } .lightbox-control:disabled { opacity: .25; cursor: default; } +.lightbox-nav.is-active { opacity: 1; transition: none; } +.lightbox-nav:not(:disabled):hover, .lightbox-nav:not(:disabled):focus-visible, .lightbox-nav:not(:disabled):active { opacity: 1; } +.lightbox-control.lightbox-nav:disabled { opacity: .15; } @media (max-width: 620px) { .share-dialog-body { grid-template-columns: minmax(0, 1fr); } .topbar { height: 52px; min-height: 52px; flex-wrap: nowrap; gap: 6px; padding: 4px 8px; } .is-exploring .topbar { height: 52px; min-height: 52px; } - .brand { flex: 1 1 auto; gap: 8px; } + .brand-cluster { gap: 6px; } + .brand { gap: 8px; } .brand img { height: 40px; max-height: 40px; max-width: 120px; } .brand span { overflow: hidden; } .brand small, .summary span { display: none; } @@ -273,6 +389,11 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } .summary strong { font-size: 12px; } .topbar-actions { width: auto; justify-content: flex-end; gap: 6px; } .theme-toggle { min-height: 34px; } + .socials-button { min-height: 34px; padding: 6px 8px; font-size: 12px; } + .socials-dialog { width: calc(100vw - 12px); height: calc(100dvh - 12px); } + .socials-dialog-panel { padding: 13px; } + .social-link { grid-template-columns: minmax(0, 1fr); gap: 9px; } + .social-link-actions { justify-content: flex-end; } main { padding: 6px 8px 36px; } .gallery-heading { display: flex; align-items: center; gap: 6px; margin: 0 0 8px; } .gallery-heading > div:first-child { flex: 1; } @@ -284,18 +405,23 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } .view-switch button { flex: none; min-height: 32px; padding: 5px 8px; font-size: 12px; } .heading-actions > .secondary-button { padding: 6px 8px; font-size: 12px; } #all-galleries { display: none !important; } - .date-card img { aspect-ratio: 16 / 9; } - .gallery-grid { grid-template-columns: repeat(2, calc((100% - 7px) / 2)); gap: 7px; } - .date-card-meta, .photo-meta { padding: 8px 54px 8px 8px; } - .date-card.has-map-action .date-card-meta, .photo-card.has-map-action .photo-meta { padding-right: 96px; } - .date-card-meta strong, .photo-meta strong { font-size: 13px; } - .date-card-stats, .photo-meta small { overflow: hidden; font-size: 11px; white-space: nowrap; text-overflow: ellipsis; } + .is-photo-grid main { padding-inline: 4px; } + .is-photo-grid .gallery-heading { margin-inline: 4px; } + .date-card-meta { padding: 8px 54px 8px 8px; } + .date-card.has-map-action .date-card-meta { padding-right: 96px; } + .date-card-meta strong { font-size: 13px; } + .date-card-stats { overflow: hidden; font-size: 11px; white-space: nowrap; text-overflow: ellipsis; } .lightbox-toolbar { align-items: start; } .lightbox-identity { display: none; } .zoom-controls { width: 100%; justify-content: flex-end; } .zoom-controls label { display: none; } .zoom-slider-shell { flex: 1 1 auto; min-width: 0; grid-template-columns: minmax(80px, 1fr) 44px; } .lightbox-control { min-height: 34px; padding: 6px 8px; } + .lightbox-download-button { width: 44px; min-width: 44px; height: 44px; } + .lightbox-control.lightbox-nav { width: 52px; min-width: 52px; min-height: 84px; padding: 12px 8px; touch-action: manipulation; } + .lightbox-nav svg { width: 34px; height: 54px; } + .lightbox-nav.previous { left: 4px; } + .lightbox-nav.next { right: 4px; } #explore-map { height: max(360px, 56vh); } .explore-filmstrip > div { flex-basis: 150px; } .is-exploring main { height: calc(100dvh - 52px); padding: 6px 8px; } @@ -306,4 +432,11 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } .is-exploring .explore-filmstrip img { height: 60px; } } -@media (hover: none) { .explore-strip-nav:not(:disabled) { opacity: .55; } } +@media (prefers-reduced-motion: reduce) { + .socials-button, .lightbox-loading::before, .lightbox-loading.is-complete { animation: none; } + .lightbox-nav, .lightbox-preview, .lightbox-full, .lightbox-tiles, .photo-card::after, .photo-overlay, .photo-open img { transition: none; } +} +@media (hover: none), (pointer: coarse) { + .explore-strip-nav:not(:disabled) { opacity: .55; } + .photo-card:focus-within .photo-overlay .card-action { pointer-events: none; } +} diff --git a/services/frame-gallery/src/app.ts b/services/frame-gallery/src/app.ts index 145b5d5..093b610 100644 --- a/services/frame-gallery/src/app.ts +++ b/services/frame-gallery/src/app.ts @@ -1,7 +1,19 @@ import express, { type Express } from "express"; +import { createHmac, randomBytes } from "node:crypto"; import path from "node:path"; import { type BasicAuthConfig, requireBasicAuth } from "./auth.js"; -import { GalleryRequestError, GalleryStore } from "./store.js"; +import { GalleryRequestError, GalleryStore, type GalleryTileView } from "./store.js"; + +const VIEW_COOKIE = "frame_gallery_view"; +const VIEW_SESSION_TTL_MS = 5 * 60 * 1000; +const MAX_VIEW_SESSIONS = 4096; +const MAX_SESSION_PHOTOS = 32; + +interface TileSession { + id: string; + expires_at: number; + photos: Map; +} export interface GalleryManagementConfig { pipelineUrl: string; @@ -12,6 +24,8 @@ export interface GalleryManagementConfig { export async function createApp(store: GalleryStore, publicDir: string, management?: GalleryManagementConfig): Promise { await store.init(); const app = express(); + const tileSessions = new Map(); + const tileSecret = randomBytes(32); app.disable("x-powered-by"); app.use(express.json({ limit: "5mb" })); @@ -46,6 +60,14 @@ export async function createApp(store: GalleryStore, publicDir: string, manageme next(error); } }); + app.get("/gallery/branding/socials/:id/graphic.webp", async (request, response, next) => { + try { + response.setHeader("Cache-Control", "public, max-age=3600"); + response.type("image/webp").sendFile(await store.requireSocialGraphic(request.params.id)); + } catch (error) { + next(error); + } + }); if (management) { const protect = requireBasicAuth(management.auth); app.get(["/gallery/admin", "/gallery/admin/", "/today/gallery/admin", "/today/gallery/admin/"], protect, (_request, response) => { @@ -65,7 +87,13 @@ export async function createApp(store: GalleryStore, publicDir: string, manageme app.post(["/gallery/admin/api/manage", "/today/gallery/admin/api/manage"], protect, async (request, response, next) => { try { response.setHeader("Cache-Control", "no-store"); - response.json(await pipelineRequest(management, "/api/internal/photo-pipeline/manage", "POST", request.body)); + const result = await pipelineRequest(management, "/api/internal/photo-pipeline/manage", "POST", request.body); + try { + await store.pruneGallerySettings(); + } catch (error) { + console.error(`[gallery] settings cleanup failed after photo management: ${errorMessage(error)}`); + } + response.json(result); } catch (error) { next(error); } @@ -138,6 +166,39 @@ export async function createApp(store: GalleryStore, publicDir: string, manageme next(error); } }); + app.post([ + "/gallery/admin/api/branding/socials/:id/graphic", + "/today/gallery/admin/api/branding/socials/:id/graphic", + ], protect, async (request, response, next) => { + try { + response.setHeader("Cache-Control", "no-store"); + response.json({ branding: await store.saveSocialGraphic(request.params.id, request.body) }); + } catch (error) { + next(error); + } + }); + app.delete([ + "/gallery/admin/api/branding/socials/:id/graphic", + "/today/gallery/admin/api/branding/socials/:id/graphic", + ], protect, async (request, response, next) => { + try { + response.setHeader("Cache-Control", "no-store"); + response.json({ branding: await store.deleteSocialGraphic(request.params.id) }); + } catch (error) { + next(error); + } + }); + app.put([ + "/gallery/admin/api/galleries/:date/settings", + "/today/gallery/admin/api/galleries/:date/settings", + ], protect, async (request, response, next) => { + try { + response.setHeader("Cache-Control", "no-store"); + response.json({ settings: await store.updateGallerySettings(request.params.date, request.body) }); + } catch (error) { + next(error); + } + }); app.get(["/gallery/admin/image/:date/:file", "/today/gallery/admin/image/:date/:file"], protect, async (request, response, next) => { try { const base = stripExtension(request.params.file, ".jpg"); @@ -185,23 +246,101 @@ export async function createApp(store: GalleryStore, publicDir: string, manageme next(error); } }); - app.get("/gallery/api/explore", async (request, response, next) => { + app.post("/gallery/api/view-session", async (request, response, next) => { + response.setHeader("Cache-Control", "private, no-store"); try { - const date = typeof request.query.date === "string" ? request.query.date : ""; - response.setHeader("Cache-Control", "private, no-cache"); + requireSameOriginBrowserRequest(request, "empty"); + if (!isRecord(request.body) || typeof request.body.date_folder !== "string" || typeof request.body.base !== "string") { + throw new GalleryRequestError("A gallery date and photo are required.", 400); + } + const view = await store.createTileView(request.body.date_folder, request.body.base); + const session = requireOrCreateTileSession(request, tileSessions); + const handle = createHmac("sha256", tileSecret) + .update(`${session.id}\0${view.date_folder}\0${view.base}\0${view.source_version}`) + .digest("base64url"); + session.photos.delete(handle); + session.photos.set(handle, view); + while (session.photos.size > MAX_SESSION_PHOTOS) session.photos.delete(session.photos.keys().next().value!); + response.cookie(VIEW_COOKIE, session.id, { + httpOnly: true, + sameSite: "strict", + secure: requestIsSecure(request), + path: "/gallery", + maxAge: VIEW_SESSION_TTL_MS, + }); response.json({ - date_folder: date, - explore: await store.getPublicExplore(date), + view: { + handle, + width: view.width, + height: view.height, + tile_size: view.tile_size, + overlap: view.overlap, + columns: view.columns, + rows: view.rows, + tiles: tileEntries(handle, view), + }, }); } catch (error) { next(error); } }); + app.get("/gallery/tile/:handle/:x/:file", async (request, response, next) => { + response.setHeader("Cache-Control", "private, no-store"); + response.setHeader("Cross-Origin-Resource-Policy", "same-origin"); + response.setHeader("X-Content-Type-Options", "nosniff"); + try { + requireSameOriginBrowserRequest(request, "image"); + const session = findTileSession(request, tileSessions); + const view = session?.photos.get(request.params.handle); + if (!view) throw new GalleryRequestError("Tile was not found.", 404); + const x = tileCoordinate(request.params.x); + const y = tileCoordinate(stripExtension(request.params.file, ".webp")); + const tile = await store.requireTile(view, x, y); + response.type("image/webp").sendFile(tile); + } catch (error) { + next(error); + } + }); app.get("/gallery/image/:date/:file", async (request, response, next) => { + response.setHeader("Cache-Control", "private, no-cache"); + response.setHeader("Cross-Origin-Resource-Policy", "same-origin"); + response.setHeader("X-Content-Type-Options", "nosniff"); try { + requireSameOriginBrowserRequest(request, "image"); + if (!(await store.getBranding()).show_download_button) { + throw new GalleryRequestError("Gallery image was not found.", 404); + } const base = stripExtension(request.params.file, ".jpg"); - response.setHeader("Cache-Control", "public, max-age=31536000, immutable"); - response.sendFile(await store.requireImage(request.params.date, base)); + const image = await store.requireImage(request.params.date, base); + response.setHeader("Content-Disposition", `inline; filename="${base}.jpg"`); + response.type("image/jpeg").sendFile(image); + } catch (error) { + next(error); + } + }); + app.get("/gallery/download/:date/:file", async (request, response, next) => { + response.setHeader("Cache-Control", "private, no-store"); + response.setHeader("Cross-Origin-Resource-Policy", "same-origin"); + response.setHeader("X-Content-Type-Options", "nosniff"); + try { + const base = stripExtension(request.params.file, ".jpg"); + if (!(await store.getBranding()).show_download_button) { + throw new GalleryRequestError("Photo download was not found.", 404); + } + const image = await store.requireImage(request.params.date, base); + response.attachment(`${base}.jpg`).sendFile(image); + } catch (error) { + next(error); + } + }); + app.get("/gallery/api/explore", async (request, response, next) => { + try { + const date = typeof request.query.date === "string" ? request.query.date : ""; + response.setHeader("Cache-Control", "private, no-cache"); + response.json({ + date_folder: date, + explore: await store.getPublicExplore(date), + }); } catch (error) { next(error); } @@ -253,6 +392,97 @@ function stripExtension(value: string, extension: string): string { return value.slice(0, -extension.length); } +function requireOrCreateTileSession(request: express.Request, sessions: Map): TileSession { + const now = Date.now(); + pruneTileSessions(sessions, now); + const existingId = readCookie(request, VIEW_COOKIE); + const existing = existingId ? sessions.get(existingId) : undefined; + if (existing) { + existing.expires_at = now + VIEW_SESSION_TTL_MS; + sessions.delete(existing.id); + sessions.set(existing.id, existing); + return existing; + } + while (sessions.size >= MAX_VIEW_SESSIONS) sessions.delete(sessions.keys().next().value!); + const session: TileSession = { + id: randomBytes(32).toString("base64url"), + expires_at: now + VIEW_SESSION_TTL_MS, + photos: new Map(), + }; + sessions.set(session.id, session); + return session; +} + +function findTileSession(request: express.Request, sessions: Map): TileSession | null { + pruneTileSessions(sessions, Date.now()); + const id = readCookie(request, VIEW_COOKIE); + return id ? sessions.get(id) ?? null : null; +} + +function pruneTileSessions(sessions: Map, now: number): void { + for (const [id, session] of sessions) { + if (session.expires_at <= now) sessions.delete(id); + } +} + +function readCookie(request: express.Request, name: string): string | null { + for (const part of (request.get("cookie") || "").split(";")) { + const separator = part.indexOf("="); + if (separator > 0 && part.slice(0, separator).trim() === name) return part.slice(separator + 1).trim(); + } + return null; +} + +function requireSameOriginBrowserRequest(request: express.Request, destination: "empty" | "image"): void { + if (request.get("sec-fetch-site") !== "same-origin" || request.get("sec-fetch-dest") !== destination) { + throw new GalleryRequestError("Gallery media was not found.", 404); + } +} + +function requestIsSecure(request: express.Request): boolean { + if (request.secure || (request.get("x-forwarded-proto") || "").split(",", 1)[0].trim().toLowerCase() === "https") { + return true; + } + try { + return JSON.parse(request.get("cf-visitor") || "null")?.scheme === "https"; + } catch { + return false; + } +} + +function tileCoordinate(value: string): number { + if (!/^(?:0|[1-9]\d*)$/.test(value)) throw new GalleryRequestError("Tile was not found.", 404); + const parsed = Number(value); + if (!Number.isSafeInteger(parsed)) throw new GalleryRequestError("Tile was not found.", 404); + return parsed; +} + +function tileEntries(handle: string, view: GalleryTileView): Array<{ + x: number; + y: number; + width: number; + height: number; + url: string; +}> { + const tiles = []; + for (let y = 0; y < view.rows; y += 1) { + for (let x = 0; x < view.columns; x += 1) { + tiles.push({ + x, + y, + width: Math.min(view.tile_size, view.width - x * view.tile_size), + height: Math.min(view.tile_size, view.height - y * view.tile_size), + url: `/gallery/tile/${handle}/${x}/${y}.webp`, + }); + } + } + return tiles; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/services/frame-gallery/src/store.ts b/services/frame-gallery/src/store.ts index a689555..e2ace40 100644 --- a/services/frame-gallery/src/store.ts +++ b/services/frame-gallery/src/store.ts @@ -1,4 +1,5 @@ import { access, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import { randomBytes } from "node:crypto"; import path from "node:path"; import sharp from "sharp"; import { @@ -19,11 +20,18 @@ const MAX_LOGO_SOURCE_PIXELS = 16_777_216; const MAX_LOGO_ASPECT_RATIO = 8; const MIN_LOGO_EDGE_PX = 24; const LOGO_BOX = { width: 720, height: 240 }; +const SOCIAL_GRAPHIC_SIZE = 320; +const TILE_SIZE = 512; +const TILE_OVERLAP = 1; +const TILE_QUALITY = 90; +const TILE_CACHE_VERSION = `v2-overlap-${TILE_OVERLAP}`; +const MAX_TILE_GENERATORS = 2; +const MAX_QUEUED_TILE_SETS = 32; +const TILE_COMPLETE_FILE = ".complete"; export interface GalleryPhoto { base: string; date_folder: string; - image_url: string; thumbnail_url: string; width: number | null; height: number | null; @@ -39,10 +47,33 @@ export interface GalleryDate { first_at: string | null; latest_at: string | null; duration_ms: number; + cover_base: string | null; + cover_fallback_active: boolean; + cover_is_custom: boolean; cover_thumbnail_url: string | null; has_explore: boolean; } +export interface GallerySettings { + schema_version: 1; + cover_base: string | null; + updated_at: string; +} + +export interface GalleryTileView { + date_folder: string; + base: string; + width: number; + height: number; + tile_size: number; + overlap: number; + columns: number; + rows: number; + source_mtime_ms: number; + source_size_bytes: number; + source_version: string; +} + export interface GalleryExplore { schema_version: 1; updated_at: string; @@ -71,7 +102,14 @@ export class GalleryStore { readonly brandingRoot: string; readonly brandingConfigFile: string; readonly logoFile: string; + readonly socialGraphicsRoot: string; + readonly gallerySettingsRoot: string; private thumbnails = new Map>(); + private tiles = new Map>(); + private tileGenerators = 0; + private tileWaiters: Array<() => void> = []; + private brandingMutation: Promise = Promise.resolve(); + private gallerySettingsMutation: Promise = Promise.resolve(); constructor(readonly dataRoot: string, readonly thumbWidth: number, readonly thumbQuality: number) { this.galleriesRoot = path.join(dataRoot, "galleries"); @@ -79,6 +117,8 @@ export class GalleryStore { this.brandingRoot = path.join(dataRoot, "gallery-branding"); this.brandingConfigFile = path.join(this.brandingRoot, "config.json"); this.logoFile = path.join(this.brandingRoot, "logo.webp"); + this.socialGraphicsRoot = path.join(this.brandingRoot, "socials"); + this.gallerySettingsRoot = path.join(this.brandingRoot, "galleries"); } async init(): Promise { @@ -86,6 +126,8 @@ export class GalleryStore { mkdir(this.galleriesRoot, { recursive: true }), mkdir(this.cacheRoot, { recursive: true }), mkdir(this.brandingRoot, { recursive: true }), + mkdir(this.socialGraphicsRoot, { recursive: true }), + mkdir(this.gallerySettingsRoot, { recursive: true }), ]); } @@ -94,14 +136,20 @@ export class GalleryStore { } async updateBranding(input: unknown): Promise { - const current = await this.readBrandingConfig(); - const next = applyBrandingUpdate(current, input, new Date().toISOString()); - await this.writeBrandingConfig(next); - return toBrandingResponse(next); + return this.mutateBranding(async () => { + const current = await this.readBrandingConfig(); + const next = applyBrandingUpdate(current, input, new Date().toISOString()); + await this.writeBrandingConfig(next); + const nextIds = new Set(next.socials.map((social) => social.id)); + await Promise.all(current.socials + .filter((social) => !nextIds.has(social.id)) + .map((social) => rm(this.socialGraphicFile(social.id), { force: true }))); + return toBrandingResponse(next); + }); } async saveLogo(input: unknown): Promise { - const upload = parseLogoUpload(input); + const upload = parseImageUpload(input, "Logo"); const image = sharp(upload.buffer, { limitInputPixels: MAX_LOGO_SOURCE_PIXELS, density: upload.mediaType === "image/svg+xml" ? 192 : undefined, @@ -127,29 +175,33 @@ export class GalleryStore { const logoHeight = integerOrNull(outputMetadata.height); if (!logoWidth || !logoHeight) throw new GalleryRequestError("Logo image could not be processed.", 400); - await mkdir(this.brandingRoot, { recursive: true }); - const temporary = `${this.logoFile}.tmp`; - await writeFile(temporary, output); - await rename(temporary, this.logoFile); - - const updatedAt = new Date().toISOString(); - const logo: GalleryLogo = { - url: `/gallery/branding/logo.webp?v=${encodeURIComponent(updatedAt)}`, - width: logoWidth, - height: logoHeight, - updated_at: updatedAt, - }; - const next = withLogo(await this.readBrandingConfig(), logo, updatedAt); - await this.writeBrandingConfig(next); - return toBrandingResponse(next); + return this.mutateBranding(async () => { + await mkdir(this.brandingRoot, { recursive: true }); + const temporary = `${this.logoFile}.tmp`; + await writeFile(temporary, output); + await rename(temporary, this.logoFile); + + const updatedAt = new Date().toISOString(); + const logo: GalleryLogo = { + url: `/gallery/branding/logo.webp?v=${encodeURIComponent(updatedAt)}`, + width: logoWidth, + height: logoHeight, + updated_at: updatedAt, + }; + const next = withLogo(await this.readBrandingConfig(), logo, updatedAt); + await this.writeBrandingConfig(next); + return toBrandingResponse(next); + }); } async deleteLogo(): Promise { - await rm(this.logoFile, { force: true }); - const updatedAt = new Date().toISOString(); - const next = withLogo(await this.readBrandingConfig(), null, updatedAt); - await this.writeBrandingConfig(next); - return toBrandingResponse(next); + return this.mutateBranding(async () => { + await rm(this.logoFile, { force: true }); + const updatedAt = new Date().toISOString(); + const next = withLogo(await this.readBrandingConfig(), null, updatedAt); + await this.writeBrandingConfig(next); + return toBrandingResponse(next); + }); } async requireLogo(): Promise { @@ -157,6 +209,82 @@ export class GalleryStore { return this.logoFile; } + async saveSocialGraphic(id: string, input: unknown): Promise { + const upload = parseImageUpload(input, "Social graphic"); + const image = sharp(upload.buffer, { + limitInputPixels: MAX_LOGO_SOURCE_PIXELS, + density: upload.mediaType === "image/svg+xml" ? 192 : undefined, + }); + const metadata = await image.metadata(); + const width = integerOrNull(metadata.width); + const height = integerOrNull(metadata.height); + if (!width || !height) throw new GalleryRequestError("Social graphic dimensions could not be read.", 400); + if (width * height > MAX_LOGO_SOURCE_PIXELS) throw new GalleryRequestError("Social graphic is too large.", 413); + if (Math.min(width, height) < MIN_LOGO_EDGE_PX) { + throw new GalleryRequestError("Social graphic is too small for web display.", 400); + } + + const output = await image + .rotate() + .resize({ width: SOCIAL_GRAPHIC_SIZE, height: SOCIAL_GRAPHIC_SIZE, fit: "cover" }) + .webp({ quality: 88 }) + .toBuffer(); + const outputMetadata = await sharp(output).metadata(); + const graphicWidth = integerOrNull(outputMetadata.width); + const graphicHeight = integerOrNull(outputMetadata.height); + if (graphicWidth !== SOCIAL_GRAPHIC_SIZE || graphicHeight !== SOCIAL_GRAPHIC_SIZE) { + throw new GalleryRequestError("Social graphic could not be processed.", 400); + } + + return this.mutateBranding(async () => { + const current = await this.readBrandingConfig(); + if (!current.socials.some((social) => social.id === id)) { + throw new GalleryRequestError("Social link was not found.", 404); + } + await mkdir(this.socialGraphicsRoot, { recursive: true }); + const graphicFile = this.socialGraphicFile(id); + const temporary = `${graphicFile}.tmp`; + await writeFile(temporary, output); + await rename(temporary, graphicFile); + + const updatedAt = new Date().toISOString(); + const graphic: GalleryLogo = { + url: `/gallery/branding/socials/${encodeURIComponent(id)}/graphic.webp?v=${encodeURIComponent(updatedAt)}`, + width: graphicWidth, + height: graphicHeight, + updated_at: updatedAt, + }; + const next = setSocialGraphic(current, id, graphic, updatedAt); + await this.writeBrandingConfig(next); + return toBrandingResponse(next); + }); + } + + async deleteSocialGraphic(id: string): Promise { + return this.mutateBranding(async () => { + const current = await this.readBrandingConfig(); + const social = current.socials.find((item) => item.id === id); + if (!social) throw new GalleryRequestError("Social link was not found.", 404); + if (!social.graphic) { + await rm(this.socialGraphicFile(id), { force: true }); + return toBrandingResponse(current); + } + const updatedAt = new Date().toISOString(); + const next = setSocialGraphic(current, id, null, updatedAt); + await this.writeBrandingConfig(next); + await rm(this.socialGraphicFile(id), { force: true }); + return toBrandingResponse(next); + }); + } + + async requireSocialGraphic(id: string): Promise { + const social = (await this.readBrandingConfig()).socials.find((item) => item.id === id); + if (!social?.graphic) throw new GalleryRequestError("Social graphic was not found.", 404); + const file = this.socialGraphicFile(social.id); + await access(file); + return file; + } + async listDates(): Promise { const dates: GalleryDate[] = []; for (const entry of await readdir(this.galleriesRoot, { withFileTypes: true })) { @@ -164,6 +292,17 @@ export class GalleryStore { const photos = await this.listPhotos(entry.name); const latest = photos[0] ?? null; const first = photos[photos.length - 1] ?? null; + const settings = await this.readGallerySettings(entry.name); + const customCover = settings.cover_base + ? photos.find((photo) => photo.base === settings.cover_base) ?? null + : null; + const customCoverIsRecoverable = settings.cover_base + ? Boolean( + await statOrNull(path.join(this.galleriesRoot, entry.name, `${settings.cover_base}.ready`)) + && await statOrNull(path.join(this.galleriesRoot, entry.name, `${settings.cover_base}.jpg`)), + ) + : false; + const cover = customCover || first; dates.push({ date_folder: entry.name, count: photos.length, @@ -172,7 +311,10 @@ export class GalleryStore { duration_ms: first && latest ? Math.max(0, new Date(latest.processed_at).getTime() - new Date(first.processed_at).getTime()) : 0, - cover_thumbnail_url: first?.thumbnail_url ?? null, + cover_base: cover?.base ?? null, + cover_fallback_active: customCoverIsRecoverable && !customCover, + cover_is_custom: customCoverIsRecoverable, + cover_thumbnail_url: cover?.thumbnail_url ?? null, has_explore: Boolean(await statOrNull(path.join(this.galleriesRoot, entry.name, "_explore.json"))), }); } @@ -194,6 +336,58 @@ export class GalleryStore { return photos.sort((left, right) => right.processed_at.localeCompare(left.processed_at)); } + async updateGallerySettings(dateFolder: string, input: unknown): Promise { + assertDate(dateFolder); + if (!isRecord(input)) throw new GalleryRequestError("Gallery settings must be an object.", 400); + const updatesCover = Object.hasOwn(input, "cover_base"); + if (!updatesCover) throw new GalleryRequestError("No gallery settings were supplied.", 400); + + return this.mutateGallerySettings(async () => { + if (!(await this.listPhotos(dateFolder)).length) throw new GalleryRequestError("Gallery was not found.", 404); + const current = await this.readGallerySettings(dateFolder); + let coverBase = current.cover_base; + const value = input.cover_base; + if (value !== null && typeof value !== "string") { + throw new GalleryRequestError("Gallery cover must identify a photo or use automatic selection.", 400); + } + if (typeof value === "string") await this.requireImage(dateFolder, value); + coverBase = value; + const next: GallerySettings = { + schema_version: 1, + cover_base: coverBase, + updated_at: new Date().toISOString(), + }; + await this.writeGallerySettings(dateFolder, next); + return next; + }); + } + + async pruneGallerySettings(): Promise { + await this.mutateGallerySettings(async () => { + for (const entry of await readdir(this.gallerySettingsRoot, { withFileTypes: true })) { + const match = entry.isFile() ? entry.name.match(/^(\d{4}-\d{2}-\d{2})\.json$/) : null; + if (!match) continue; + const dateFolder = match[1]; + const galleryEntries = await readEntriesOrEmpty(path.join(this.galleriesRoot, dateFolder)); + const published = new Set(galleryEntries + .filter((name) => name.endsWith(".ready")) + .map((name) => name.slice(0, -6)) + .filter((base) => BASE_PATTERN.test(base))); + if (!published.size) { + await rm(this.gallerySettingsFile(dateFolder), { force: true }); + continue; + } + const current = await this.readGallerySettings(dateFolder); + if (!current.cover_base || published.has(current.cover_base)) continue; + await this.writeGallerySettings(dateFolder, { + ...current, + cover_base: null, + updated_at: new Date().toISOString(), + }); + } + }); + } + async getExplore(dateFolder: string): Promise { assertDate(dateFolder); const explore = await readJsonOrNull(path.join(this.galleriesRoot, dateFolder, "_explore.json")); @@ -221,6 +415,62 @@ export class GalleryStore { return image; } + async createTileView(dateFolder: string, base: string): Promise { + const image = await this.requireImage(dateFolder, base); + const [metadata, source] = await Promise.all([sharp(image).metadata(), stat(image)]); + const width = integerOrNull(metadata.width); + const height = integerOrNull(metadata.height); + if (!width || !height) throw new GalleryRequestError("Photo dimensions could not be read.", 500); + return { + date_folder: dateFolder, + base, + width, + height, + tile_size: TILE_SIZE, + overlap: TILE_OVERLAP, + columns: Math.ceil(width / TILE_SIZE), + rows: Math.ceil(height / TILE_SIZE), + source_mtime_ms: source.mtimeMs, + source_size_bytes: source.size, + source_version: `${Math.round(source.mtimeMs * 1000)}-${source.size}`, + }; + } + + async requireTile(view: GalleryTileView, x: number, y: number): Promise { + if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0 || x >= view.columns || y >= view.rows) { + throw new GalleryRequestError("Tile was not found.", 404); + } + const image = await this.requireImage(view.date_folder, view.base); + const source = await stat(image); + if (source.mtimeMs !== view.source_mtime_ms || source.size !== view.source_size_bytes) { + throw new GalleryRequestError("Viewing session expired.", 404); + } + const tileSet = path.join( + this.cacheRoot, + "tiles", + view.date_folder, + view.base, + TILE_CACHE_VERSION, + view.source_version, + ); + const tile = path.join(tileSet, "photo_files", "0", `${x}_${y}.webp`); + const key = tileSet; + const pending = this.tiles.get(key) ?? this.generateTileSet(image, tileSet, tile); + this.tiles.set(key, pending); + try { + await pending; + await this.assertPublished(view.date_folder, view.base); + const current = await stat(image); + if (current.mtimeMs !== view.source_mtime_ms || current.size !== view.source_size_bytes) { + throw new GalleryRequestError("Viewing session expired.", 404); + } + await access(tile); + return tile; + } finally { + if (this.tiles.get(key) === pending) this.tiles.delete(key); + } + } + async requireThumbnail(dateFolder: string, base: string): Promise { const key = `${dateFolder}/${base}`; const pending = this.thumbnails.get(key) ?? this.generateThumbnail(dateFolder, base); @@ -272,6 +522,46 @@ export class GalleryStore { return thumbnail; } + private async generateTileSet(image: string, tileSet: string, requestedTile: string): Promise { + const completeMarker = path.join(tileSet, TILE_COMPLETE_FILE); + if (await statOrNull(completeMarker) && await statOrNull(requestedTile)) return; + return this.withTileGenerator(async () => { + if (await statOrNull(completeMarker) && await statOrNull(requestedTile)) return; + const temporary = `${tileSet}.tmp-${process.pid}-${randomBytes(8).toString("hex")}`; + await mkdir(path.dirname(tileSet), { recursive: true }); + try { + await mkdir(temporary, { recursive: true }); + await sharp(image, { failOn: "error" }) + .webp({ quality: TILE_QUALITY }) + .tile({ size: TILE_SIZE, overlap: TILE_OVERLAP, depth: "one", layout: "dz", container: "fs" }) + .toFile(path.join(temporary, "photo.dz")); + await access(path.join(temporary, path.relative(tileSet, requestedTile))); + await writeFile(path.join(temporary, TILE_COMPLETE_FILE), "complete\n"); + await rm(tileSet, { recursive: true, force: true }); + await rename(temporary, tileSet); + } finally { + await rm(temporary, { recursive: true, force: true }); + } + }); + } + + private async withTileGenerator(operation: () => Promise): Promise { + if (this.tileGenerators < MAX_TILE_GENERATORS) this.tileGenerators += 1; + else { + if (this.tileWaiters.length >= MAX_QUEUED_TILE_SETS) { + throw new GalleryRequestError("Photo detail is busy. Try again shortly.", 503); + } + await new Promise((resolve) => this.tileWaiters.push(resolve)); + } + try { + return await operation(); + } finally { + const next = this.tileWaiters.shift(); + if (next) next(); + else this.tileGenerators -= 1; + } + } + private async readPhoto(dateFolder: string, base: string): Promise { assertBase(base); const directory = path.join(this.galleriesRoot, dateFolder); @@ -281,7 +571,6 @@ export class GalleryStore { return { base, date_folder: dateFolder, - image_url: `/gallery/image/${dateFolder}/${base}.jpg`, thumbnail_url: `/gallery/thumb/${dateFolder}/${base}.webp`, width: integerOrNull(sidecar?.width), height: integerOrNull(sidecar?.height), @@ -311,12 +600,51 @@ export class GalleryStore { return normalizeStoredBranding(await readJsonOrNull(this.brandingConfigFile)); } + private async readGallerySettings(dateFolder: string): Promise { + const value = await readJsonOrNull(this.gallerySettingsFile(dateFolder)); + if (!isRecord(value) || value.schema_version !== 1) return defaultGallerySettings(); + return { + schema_version: 1, + cover_base: typeof value.cover_base === "string" && BASE_PATTERN.test(value.cover_base) ? value.cover_base : null, + updated_at: typeof value.updated_at === "string" && value.updated_at ? value.updated_at : defaultGallerySettings().updated_at, + }; + } + + private async writeGallerySettings(dateFolder: string, settings: GallerySettings): Promise { + await mkdir(this.gallerySettingsRoot, { recursive: true }); + const file = this.gallerySettingsFile(dateFolder); + const temporary = `${file}.tmp`; + await writeFile(temporary, `${JSON.stringify(settings, null, 2)}\n`); + await rename(temporary, file); + } + private async writeBrandingConfig(config: GalleryBranding): Promise { await mkdir(path.dirname(this.brandingConfigFile), { recursive: true }); const temporary = `${this.brandingConfigFile}.tmp`; await writeFile(temporary, `${JSON.stringify(config, null, 2)}\n`); await rename(temporary, this.brandingConfigFile); } + + private socialGraphicFile(id: string): string { + return path.join(this.socialGraphicsRoot, `${id}.webp`); + } + + private gallerySettingsFile(dateFolder: string): string { + assertDate(dateFolder); + return path.join(this.gallerySettingsRoot, `${dateFolder}.json`); + } + + private mutateBranding(operation: () => Promise): Promise { + const result = this.brandingMutation.then(operation, operation); + this.brandingMutation = result.then(() => undefined, () => undefined); + return result; + } + + private mutateGallerySettings(operation: () => Promise): Promise { + const result = this.gallerySettingsMutation.then(operation, operation); + this.gallerySettingsMutation = result.then(() => undefined, () => undefined); + return result; + } } function assertDate(value: string): void { @@ -362,6 +690,27 @@ function integerOrNull(value: unknown): number | null { return Number.isInteger(value) && Number(value) > 0 ? Number(value) : null; } +async function readEntriesOrEmpty(directory: string): Promise { + try { + return await readdir(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } +} + +function defaultGallerySettings(): GallerySettings { + return { + schema_version: 1, + cover_base: null, + updated_at: "1970-01-01T00:00:00.000Z", + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + function visibleBases(entries: string[]): string[] { const names = new Set(entries); return entries @@ -370,16 +719,35 @@ function visibleBases(entries: string[]): string[] { .filter((base) => !names.has(`${base}.trashed.json`)); } -function parseLogoUpload(input: unknown): { buffer: Buffer; mediaType: string } { +function parseImageUpload(input: unknown, subject: string): { buffer: Buffer; mediaType: string } { if (typeof input !== "object" || input === null || Array.isArray(input)) { - throw new GalleryRequestError("Logo upload must include an image data URL.", 400); + throw new GalleryRequestError(`${subject} upload must include an image data URL.`, 400); } const dataUrl = (input as { data_url?: unknown }).data_url; - if (typeof dataUrl !== "string") throw new GalleryRequestError("Logo upload must include an image data URL.", 400); + if (typeof dataUrl !== "string") throw new GalleryRequestError(`${subject} upload must include an image data URL.`, 400); const match = dataUrl.match(LOGO_DATA_URL_PATTERN); - if (!match) throw new GalleryRequestError("Logo must be a PNG, JPEG, WebP, or SVG image.", 400); + if (!match) throw new GalleryRequestError(`${subject} must be a PNG, JPEG, WebP, or SVG image.`, 400); const buffer = Buffer.from(match[2].replace(/\s/g, ""), "base64"); - if (!buffer.length) throw new GalleryRequestError("Logo upload was empty.", 400); - if (buffer.length > MAX_LOGO_UPLOAD_BYTES) throw new GalleryRequestError("Processed logo image is too large.", 413); + if (!buffer.length) throw new GalleryRequestError(`${subject} upload was empty.`, 400); + if (buffer.length > MAX_LOGO_UPLOAD_BYTES) throw new GalleryRequestError(`Processed ${subject.toLowerCase()} image is too large.`, 413); return { buffer, mediaType: match[1].toLowerCase() }; } + +function setSocialGraphic( + config: GalleryBranding, + id: string, + graphic: GalleryLogo | null, + updatedAt: string, +): GalleryBranding { + return { + ...config, + socials: config.socials.map((social) => { + if (social.id !== id) return social; + const next = { ...social }; + if (graphic) next.graphic = graphic; + else delete next.graphic; + return next; + }), + updated_at: updatedAt, + }; +} diff --git a/services/frame-gallery/src/theme.ts b/services/frame-gallery/src/theme.ts index fcc1743..e1dab25 100644 --- a/services/frame-gallery/src/theme.ts +++ b/services/frame-gallery/src/theme.ts @@ -34,12 +34,41 @@ export interface GalleryLogo { updated_at: string; } +export const GALLERY_SOCIAL_PLATFORMS = [ + "website", + "instagram", + "tiktok", + "youtube", + "twitch", + "facebook", + "x", + "threads", + "bluesky", + "discord", + "linkedin", + "reddit", + "snapchat", + "flickr", +] as const; + +export type GallerySocialPlatform = typeof GALLERY_SOCIAL_PLATFORMS[number]; + +export interface GallerySocialLink { + id: string; + platform: GallerySocialPlatform; + label?: string; + url: string; + graphic?: GalleryLogo; +} + export interface GalleryBranding { brand_name: string; gallery_title: string; + show_download_button: boolean; mode: GalleryThemeMode; profile_id: string; custom_profiles: GalleryThemeProfile[]; + socials: GallerySocialLink[]; logo: GalleryLogo | null; updated_at: string; } @@ -55,6 +84,10 @@ export const DEFAULT_GALLERY_TITLE = "Photo Gallery"; const DEFAULT_UPDATED_AT = "1970-01-01T00:00:00.000Z"; const HEX_COLOR = /^#[0-9a-fA-F]{6}$/; const CUSTOM_ID_PATTERN = /^custom-[a-z0-9-]{1,50}$/; +const SOCIAL_ID_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/; +const MAX_SOCIAL_LINKS = 32; +const MAX_SOCIAL_LABEL_LENGTH = 60; +const MAX_SOCIAL_URL_LENGTH = 2048; const PALETTE_KEYS = [ "background", "topbar", @@ -84,9 +117,11 @@ export function createDefaultBranding(): GalleryBranding { return { brand_name: DEFAULT_BRAND_NAME, gallery_title: DEFAULT_GALLERY_TITLE, + show_download_button: false, mode: "system", profile_id: PRESET_PROFILES[0].id, custom_profiles: [], + socials: [], logo: null, updated_at: DEFAULT_UPDATED_AT, }; @@ -100,9 +135,11 @@ export function normalizeStoredBranding(value: unknown): GalleryBranding { return { brand_name: cleanText(record.brand_name, fallback.brand_name, 60), gallery_title: cleanText(record.gallery_title, fallback.gallery_title, 80), + show_download_button: typeof record.show_download_button === "boolean" ? record.show_download_button : false, mode: normalizeMode(record.mode, fallback.mode), profile_id: profileId, custom_profiles: customProfiles, + socials: normalizeStoredSocials(record.socials), logo: normalizeLogo(record.logo), updated_at: typeof record.updated_at === "string" && record.updated_at ? record.updated_at : fallback.updated_at, }; @@ -115,13 +152,18 @@ export function applyBrandingUpdate(previous: GalleryBranding, value: unknown, u previous.custom_profiles, ); const profileId = normalizeProfileId(record.profile_id, previous.profile_id, customProfiles); + if (record.show_download_button !== undefined && typeof record.show_download_button !== "boolean") { + throw badRequest("Show download button must be true or false."); + } return { ...previous, brand_name: cleanText(record.brand_name, previous.brand_name, 60), gallery_title: cleanText(record.gallery_title, previous.gallery_title, 80), + show_download_button: record.show_download_button ?? previous.show_download_button, mode: normalizeMode(record.mode, previous.mode), profile_id: profileId, custom_profiles: customProfiles, + socials: record.socials === undefined ? previous.socials : validateSocials(record.socials, previous.socials), updated_at: updatedAt, }; } @@ -203,6 +245,86 @@ function normalizeLogo(value: unknown): GalleryLogo | null { }; } +function normalizeStoredSocials(value: unknown): GallerySocialLink[] { + if (!Array.isArray(value)) return []; + const seen = new Set(); + const socials: GallerySocialLink[] = []; + for (const item of value.slice(0, MAX_SOCIAL_LINKS)) { + const social = normalizeStoredSocial(item); + if (!social || seen.has(social.id)) continue; + seen.add(social.id); + socials.push(social); + } + return socials; +} + +function normalizeStoredSocial(value: unknown): GallerySocialLink | null { + if (!isRecord(value) || typeof value.id !== "string" || !SOCIAL_ID_PATTERN.test(value.id)) return null; + if (!isSocialPlatform(value.platform)) return null; + const url = canonicalHttpUrl(value.url); + if (!url) return null; + const label = cleanOptionalText(value.label, MAX_SOCIAL_LABEL_LENGTH); + const graphic = normalizeLogo(value.graphic); + return { + id: value.id, + platform: value.platform, + ...(label ? { label } : {}), + url, + ...(graphic && graphic.width === graphic.height ? { graphic } : {}), + }; +} + +function validateSocials(value: unknown, previous: GallerySocialLink[]): GallerySocialLink[] { + if (!Array.isArray(value)) throw badRequest("Social links must be an array."); + if (value.length > MAX_SOCIAL_LINKS) throw badRequest(`Social links are limited to ${MAX_SOCIAL_LINKS}.`); + const seen = new Set(); + const previousById = new Map(previous.map((social) => [social.id, social])); + return value.map((item, index) => { + if (!isRecord(item)) throw badRequest(`Social link ${index + 1} is invalid.`); + if (typeof item.id !== "string" || !SOCIAL_ID_PATTERN.test(item.id)) { + throw badRequest(`Social link ${index + 1} must have a valid id.`); + } + if (seen.has(item.id)) throw badRequest(`Social link id "${item.id}" is duplicated.`); + seen.add(item.id); + if (!isSocialPlatform(item.platform)) throw badRequest(`Social link ${index + 1} has an unsupported platform.`); + if (item.label !== undefined && typeof item.label !== "string") { + throw badRequest(`Social link ${index + 1} has an invalid label.`); + } + if (typeof item.label === "string" && item.label.length > MAX_SOCIAL_LABEL_LENGTH) { + throw badRequest(`Social link labels are limited to ${MAX_SOCIAL_LABEL_LENGTH} characters.`); + } + const url = canonicalHttpUrl(item.url); + if (!url) throw badRequest(`Social link ${index + 1} must use a valid http or https URL.`); + const label = cleanOptionalText(item.label, MAX_SOCIAL_LABEL_LENGTH); + const graphic = previousById.get(item.id)?.graphic; + return { id: item.id, platform: item.platform, ...(label ? { label } : {}), url, ...(graphic ? { graphic } : {}) }; + }); +} + +function isSocialPlatform(value: unknown): value is GallerySocialPlatform { + return typeof value === "string" && (GALLERY_SOCIAL_PLATFORMS as readonly string[]).includes(value); +} + +function canonicalHttpUrl(value: unknown): string | null { + if (typeof value !== "string" || !value.trim() || value.length > MAX_SOCIAL_URL_LENGTH) return null; + try { + const url = new URL(value.trim()); + if ((url.protocol !== "http:" && url.protocol !== "https:") || !url.hostname || url.username || url.password) return null; + return url.href; + } catch { + return null; + } +} + +function cleanOptionalText(value: unknown, maxLength: number): string | undefined { + if (typeof value !== "string") return undefined; + return value.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, maxLength) || undefined; +} + +function badRequest(message: string): Error & { status: number } { + return Object.assign(new Error(message), { status: 400 }); +} + function normalizeHexColor(value: unknown, fallback: string): string { if (typeof value === "string" && HEX_COLOR.test(value.trim())) return value.trim().toLowerCase(); return fallback; diff --git a/services/frame-gallery/tests/gallery.test.mjs b/services/frame-gallery/tests/gallery.test.mjs index 2f570c7..f8dc900 100644 --- a/services/frame-gallery/tests/gallery.test.mjs +++ b/services/frame-gallery/tests/gallery.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { once } from "node:events"; import { createServer } from "node:http"; import os from "node:os"; @@ -24,21 +24,204 @@ test("lists and serves only ready publications", async () => { const dates = await store.listDates(); assert.deepEqual(dates.map((item) => item.date_folder), [date]); + assert.equal(dates[0].cover_base, "visible"); + assert.equal(dates[0].cover_fallback_active, false); + assert.equal(dates[0].cover_is_custom, false); assert.equal(dates[0].cover_thumbnail_url, `/gallery/thumb/${date}/visible.webp`); assert.equal(dates[0].duration_ms, 0); assert.equal(dates[0].has_explore, true); const photos = await store.listPhotos(date); assert.deepEqual(photos.map((photo) => photo.base), ["visible"]); assert.equal(photos[0].capture_clock, "2026-06-13T17:00:00.000Z"); + assert.equal(Object.hasOwn(photos[0], "image_url"), false); assert.equal((await store.getExplore(date)).routes.length, 1); const thumbnail = await store.requireThumbnail(date, "visible"); assert.equal((await sharp(thumbnail).metadata()).format, "webp"); + const view = await store.createTileView(date, "visible"); + assert.deepEqual( + { width: view.width, height: view.height, columns: view.columns, rows: view.rows, tile_size: view.tile_size, overlap: view.overlap }, + { width: 120, height: 80, columns: 1, rows: 1, tile_size: 512, overlap: 1 }, + ); + const [tile, duplicateTile] = await Promise.all([ + store.requireTile(view, 0, 0), + store.requireTile(view, 0, 0), + ]); + assert.equal(duplicateTile, tile); + assert.deepEqual( + await sharp(tile).metadata().then(({ format, width, height, exif }) => ({ format, width, height, exif })), + { format: "webp", width: 120, height: 80, exif: undefined }, + ); + await assert.rejects(store.requireTile(view, 1, 0), (error) => error.status === 404); await assert.rejects(store.requireImage(date, "partial")); await assert.rejects(store.requireImage(date, "trashed")); assert.match(await store.requireAdminImage(date, "trashed"), /trashed\.jpg$/); assert.equal((await sharp(await store.requireAdminThumbnail(date, "trashed")).metadata()).format, "webp"); }); +test("rebuilds incomplete tile caches before serving them", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "frame-gallery-")); + const date = "2026-06-13"; + const gallery = path.join(root, "galleries", date); + await mkdir(gallery, { recursive: true }); + await publish(gallery, "visible", true, "2026-06-13T12:00:00.000Z", 1025, 513); + const sourcePixels = Buffer.alloc(1025 * 513 * 3); + for (let y = 0; y < 513; y += 1) { + for (let x = 0; x < 1025; x += 1) { + const offset = (y * 1025 + x) * 3; + sourcePixels[offset] = x % 256; + sourcePixels[offset + 1] = y % 256; + sourcePixels[offset + 2] = (x + y) % 256; + } + } + await sharp(sourcePixels, { raw: { width: 1025, height: 513, channels: 3 } }) + .jpeg({ quality: 100, chromaSubsampling: "4:4:4" }) + .toFile(path.join(gallery, "visible.jpg")); + const store = new GalleryStore(root, 320, 80); + await store.init(); + const view = await store.createTileView(date, "visible"); + const legacyTileSet = path.join(store.cacheRoot, "tiles", date, "visible", view.source_version); + await mkdir(legacyTileSet, { recursive: true }); + await writeFile(path.join(legacyTileSet, ".complete"), "complete\n"); + const tileSet = path.join(store.cacheRoot, "tiles", date, "visible", "v2-overlap-1", view.source_version); + const requestedTile = path.join(tileSet, "photo_files", "0", "0_0.webp"); + await mkdir(path.dirname(requestedTile), { recursive: true }); + await writeFile(requestedTile, "partial"); + + const tile = await store.requireTile(view, 0, 0); + + assert.equal(tile, requestedTile); + const reconstructed = Buffer.alloc(view.width * view.height * 3); + const encodedSizes = []; + for (let y = 0; y < view.rows; y += 1) { + for (let x = 0; x < view.columns; x += 1) { + const encoded = await sharp(await store.requireTile(view, x, y)) + .removeAlpha() + .raw() + .toBuffer({ resolveWithObject: true }); + encodedSizes.push({ width: encoded.info.width, height: encoded.info.height }); + const left = x > 0 ? view.overlap : 0; + const top = y > 0 ? view.overlap : 0; + const coreWidth = Math.min(view.tile_size, view.width - x * view.tile_size); + const coreHeight = Math.min(view.tile_size, view.height - y * view.tile_size); + for (let row = 0; row < coreHeight; row += 1) { + const sourceStart = ((top + row) * encoded.info.width + left) * 3; + const targetStart = ((y * view.tile_size + row) * view.width + x * view.tile_size) * 3; + encoded.data.copy(reconstructed, targetStart, sourceStart, sourceStart + coreWidth * 3); + } + } + } + assert.deepEqual(encodedSizes, [ + { width: 513, height: 513 }, + { width: 514, height: 513 }, + { width: 2, height: 513 }, + { width: 513, height: 2 }, + { width: 514, height: 2 }, + { width: 2, height: 2 }, + ]); + const source = await sharp(path.join(gallery, "visible.jpg")).removeAlpha().raw().toBuffer(); + const reconstructionError = reconstructed.reduce((sum, value, index) => sum + Math.abs(value - source[index]), 0); + assert.ok(reconstructionError / reconstructed.length < 3); + assert.match(await readFile(path.join(tileSet, "photo.dzi"), "utf8"), /Overlap="1"/); + assert.equal(await readFile(path.join(tileSet, ".complete"), "utf8"), "complete\n"); + assert.equal(await readFile(path.join(legacyTileSet, ".complete"), "utf8"), "complete\n"); + assert.equal((await readdir(path.dirname(tileSet))).some((entry) => entry.startsWith(`${view.source_version}.tmp-`)), false); +}); + +test("rejects excess queued tile-set work with a retryable response", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "frame-gallery-")); + const date = "2026-06-13"; + const gallery = path.join(root, "galleries", date); + await mkdir(gallery, { recursive: true }); + await publish(gallery, "visible", true); + const store = new GalleryStore(root, 320, 80); + await store.init(); + const view = await store.createTileView(date, "visible"); + store.tileGenerators = 2; + store.tileWaiters = Array.from({ length: 32 }, () => () => {}); + + await assert.rejects( + store.requireTile(view, 0, 0), + (error) => error.status === 503 && error.message === "Photo detail is busy. Try again shortly.", + ); +}); + +test("persists per-gallery covers with a safe fallback and ignores retired download fields", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "frame-gallery-")); + const date = "2026-06-13"; + const otherDate = "2026-06-14"; + const gallery = path.join(root, "galleries", date); + const otherGallery = path.join(root, "galleries", otherDate); + await Promise.all([mkdir(gallery, { recursive: true }), mkdir(otherGallery, { recursive: true })]); + await publish(gallery, "oldest", true, "2026-06-13T12:00:00.000Z"); + await publish(gallery, "newest", true, "2026-06-13T13:00:00.000Z"); + await publish(gallery, "partial", false, "2026-06-13T14:00:00.000Z"); + await publish(otherGallery, "other", true, "2026-06-14T12:00:00.000Z"); + const store = new GalleryStore(root, 320, 80); + await store.init(); + + let dates = await store.listDates(); + let selected = dates.find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "oldest"); + assert.equal(selected.cover_fallback_active, false); + assert.equal(selected.cover_is_custom, false); + + await store.updateGallerySettings(date, { cover_base: "newest", show_download_button: true }); + dates = await new GalleryStore(root, 320, 80).listDates(); + selected = dates.find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "newest"); + assert.equal(selected.cover_fallback_active, false); + assert.equal(selected.cover_is_custom, true); + assert.equal(selected.cover_thumbnail_url, `/gallery/thumb/${date}/newest.webp`); + assert.equal(Object.hasOwn(selected, "show_download_button"), false); + + await writeFile(path.join(gallery, "newest.trashed.json"), JSON.stringify({ trashed_at: new Date().toISOString() })); + selected = (await store.listDates()).find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "oldest"); + assert.equal(selected.cover_fallback_active, true); + assert.equal(selected.cover_is_custom, true); + await rm(path.join(gallery, "newest.trashed.json")); + selected = (await store.listDates()).find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "newest"); + assert.equal(selected.cover_fallback_active, false); + await Promise.all([ + rm(path.join(gallery, "newest.ready")), + rm(path.join(gallery, "newest.jpg")), + ]); + selected = (await store.listDates()).find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "oldest"); + assert.equal(selected.cover_fallback_active, false); + assert.equal(selected.cover_is_custom, false); + + await store.pruneGallerySettings(); + await publish(gallery, "newest", true, "2026-06-13T13:00:00.000Z"); + selected = (await store.listDates()).find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "oldest"); + assert.equal(selected.cover_is_custom, false); + await store.updateGallerySettings(date, { cover_base: "newest" }); + await store.updateGallerySettings(date, { cover_base: null }); + selected = (await store.listDates()).find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "oldest"); + assert.equal(selected.cover_is_custom, false); + await assert.rejects(store.updateGallerySettings(date, { cover_base: "partial" }), /ENOENT/); + await assert.rejects(store.updateGallerySettings(date, { show_download_button: false }), (error) => error.status === 400); + await assert.rejects(store.updateGallerySettings(date, {}), (error) => error.status === 400); + await assert.rejects( + store.updateGallerySettings("2026-06-15", { cover_base: null }), + (error) => error.status === 404, + ); + await Promise.all([ + rm(path.join(gallery, "oldest.ready")), + rm(path.join(gallery, "oldest.jpg")), + rm(path.join(gallery, "newest.ready")), + rm(path.join(gallery, "newest.jpg")), + ]); + await store.pruneGallerySettings(); + await publish(gallery, "reborn", true, "2026-06-13T15:00:00.000Z"); + selected = (await store.listDates()).find((item) => item.date_folder === date); + assert.equal(selected.cover_base, "reborn"); + assert.equal(selected.cover_is_custom, false); +}); + test("persists branding settings and constrains uploaded logos", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "frame-gallery-")); const store = new GalleryStore(root, 320, 80); @@ -47,6 +230,8 @@ test("persists branding settings and constrains uploaded logos", async () => { const defaults = await store.getBranding(); assert.equal(defaults.presets.length, 5); assert.deepEqual(defaults.custom_profiles, []); + assert.deepEqual(defaults.socials, []); + assert.equal(defaults.show_download_button, false); assert.equal(defaults.mode, "system"); assert.equal(defaults.logo, null); const fullPalette = { @@ -57,14 +242,20 @@ test("persists branding settings and constrains uploaded logos", async () => { const updated = await store.updateBranding({ brand_name: "North Studio", gallery_title: "Launch Photos", + show_download_button: true, mode: "night", profile_id: "custom-midnight-field", custom_profiles: [ { id: "custom-launch-orange", name: "Launch Orange", theme_color: "#ff6600" }, { id: "custom-midnight-field", name: "Midnight Field", theme_color: "#123456", palettes: fullPalette }, ], + socials: [ + { id: "instagram-main", platform: "instagram", label: " North Studio ", url: "HTTPS://Instagram.COM/northstudio" }, + { id: "portfolio", platform: "website", url: "https://photos.example.com" }, + ], }); assert.equal(updated.brand_name, "North Studio"); + assert.equal(updated.show_download_button, true); assert.equal(updated.presets.length, 7); assert.equal(updated.custom_profiles.length, 2); assert.equal(updated.active_profile.id, "custom-midnight-field"); @@ -72,6 +263,42 @@ test("persists branding settings and constrains uploaded logos", async () => { assert.equal(updated.active_profile.palettes.day.accent, "#123456"); assert.equal(updated.active_profile.palettes.night.accent, "#abcdef"); assert.notEqual(updated.active_profile.palettes.day.background, updated.active_profile.palettes.night.background); + assert.deepEqual(updated.socials, [ + { id: "instagram-main", platform: "instagram", label: "North Studio", url: "https://instagram.com/northstudio" }, + { id: "portfolio", platform: "website", url: "https://photos.example.com/" }, + ]); + assert.deepEqual((await new GalleryStore(root, 320, 80).getBranding()).socials, updated.socials); + await assert.rejects( + store.updateBranding({ socials: [{ id: "bad", platform: "website", url: "javascript:alert(1)" }] }), + (error) => error.status === 400 && /http or https/.test(error.message), + ); + await assert.rejects( + store.updateBranding({ show_download_button: "yes" }), + (error) => error.status === 400 && /true or false/.test(error.message), + ); + + const socialSource = await pngBuffer(640, 360, "#123456"); + const withGraphic = await store.saveSocialGraphic("instagram-main", { + data_url: `data:image/png;base64,${socialSource.toString("base64")}`, + }); + assert.equal(withGraphic.socials[0].graphic.width, 320); + assert.equal(withGraphic.socials[0].graphic.height, 320); + const socialGraphicFile = await store.requireSocialGraphic("instagram-main"); + assert.deepEqual( + await sharp(await readFile(socialGraphicFile)).metadata().then(({ format, width, height }) => ({ format, width, height })), + { format: "webp", width: 320, height: 320 }, + ); + const reordered = await store.updateBranding({ + socials: [ + { id: "portfolio", platform: "website", url: "https://photos.example.com", graphic: { url: "https://example.com/spoof.webp", width: 320, height: 320, updated_at: "now" } }, + { id: "instagram-main", platform: "instagram", label: "North Studio", url: "https://instagram.com/northstudio" }, + ], + }); + assert.equal(reordered.socials[0].graphic, undefined); + assert.equal(reordered.socials[1].graphic.url, withGraphic.socials[0].graphic.url); + await store.updateBranding({ socials: [reordered.socials[0]] }); + await assert.rejects(store.requireSocialGraphic("instagram-main"), (error) => error.status === 404); + await assert.rejects(readFile(socialGraphicFile), (error) => error.code === "ENOENT"); const logo = await pngBuffer(900, 260, "#ff6600"); const branded = await store.saveLogo({ data_url: `data:image/png;base64,${logo.toString("base64")}` }); @@ -99,39 +326,207 @@ test("persists branding settings and constrains uploaded logos", async () => { await assert.rejects(store.requireLogo()); }); -test("gallery HTTP API blocks unpublished media", async () => { +test("gallery HTTP API switches between protected tiles and the globally enabled inline image", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "frame-gallery-")); const date = "2026-06-13"; const gallery = path.join(root, "galleries", date); await mkdir(gallery, { recursive: true }); - await publish(gallery, "visible", true); + await publish(gallery, "visible", true, "2026-06-13T12:00:00.000Z", 1025, 513); await publish(gallery, "partial", false); await publish(gallery, "hidden", true); await writeFile(path.join(gallery, "hidden.trashed.json"), JSON.stringify({ trashed_at: new Date().toISOString() })); const storedExplore = exploreDocument("visible"); storedExplore.placements.hidden = { lat: 40.5, lon: -86.5, updated_at: "2026-06-13T18:00:00.000Z" }; await writeFile(path.join(gallery, "_explore.json"), JSON.stringify(storedExplore)); - const app = await createApp(new GalleryStore(root, 320, 80), path.resolve("public")); + const store = new GalleryStore(root, 320, 80); + const app = await createApp(store, path.resolve("public")); const server = app.listen(0); await once(server, "listening"); - const port = server.address().port; - - const photos = await fetch(`http://127.0.0.1:${port}/gallery/api/photos?date=${date}`).then((response) => response.json()); - assert.deepEqual(photos.photos.map((photo) => photo.base), ["visible"]); - assert.equal(photos.photos[0].capture_clock, "2026-06-13T17:00:00.000Z"); - const exploreResponse = await fetch(`http://127.0.0.1:${port}/gallery/api/explore?date=${date}`); - assert.match(exploreResponse.headers.get("cache-control"), /private, no-cache/); - assert.ok(exploreResponse.headers.get("etag")); - const publicExplore = (await exploreResponse.json()).explore; - assert.equal(publicExplore.routes.length, 1); - assert.ok(publicExplore.placements.visible); - assert.equal(publicExplore.placements.hidden, undefined); - assert.equal((await fetch(`http://127.0.0.1:${port}/gallery/image/${date}/visible.jpg`)).status, 200); - assert.equal((await fetch(`http://127.0.0.1:${port}/gallery/image/${date}/partial.jpg`)).status, 404); - assert.equal((await fetch(`http://127.0.0.1:${port}/gallery/image/not-a-date/visible.jpg`)).status, 400); - assert.equal((await fetch(`http://127.0.0.1:${port}/gallery/thumb/${date}/visible.webp`)).headers.get("content-type"), "image/webp"); - assert.equal((await fetch(`http://127.0.0.1:${port}/today/gallery/${date}/`)).status, 200); - server.close(); + const origin = `http://127.0.0.1:${server.address().port}`; + const sessionHeaders = { + "content-type": "application/json", + "sec-fetch-site": "same-origin", + "sec-fetch-dest": "empty", + "cf-visitor": JSON.stringify({ scheme: "https" }), + }; + const sessionBody = JSON.stringify({ date_folder: date, base: "visible" }); + const imageUrl = `${origin}/gallery/image/${date}/visible.jpg`; + const imageHeaders = { "sec-fetch-site": "same-origin", "sec-fetch-dest": "image" }; + try { + const photos = await fetch(`${origin}/gallery/api/photos?date=${date}`).then((response) => response.json()); + assert.deepEqual(photos.photos.map((photo) => photo.base), ["visible"]); + assert.equal(photos.photos[0].capture_clock, "2026-06-13T17:00:00.000Z"); + assert.equal(photos.photos[0].thumbnail_url, `/gallery/thumb/${date}/visible.webp`); + assert.equal(Object.hasOwn(photos.photos[0], "image_url"), false); + const disabledImage = await fetch(imageUrl, { headers: imageHeaders }); + assert.equal(disabledImage.status, 404); + assert.equal(disabledImage.headers.get("cache-control"), "private, no-cache"); + assert.equal(disabledImage.headers.get("cross-origin-resource-policy"), "same-origin"); + assert.equal(disabledImage.headers.get("x-content-type-options"), "nosniff"); + + const rejectedSession = await fetch(`${origin}/gallery/api/view-session`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: sessionBody, + }); + assert.equal(rejectedSession.status, 404); + assert.equal(rejectedSession.headers.get("cache-control"), "private, no-store"); + assert.equal((await fetch(`${origin}/gallery/api/view-session`, { + method: "POST", + headers: { ...sessionHeaders, "sec-fetch-site": "cross-site" }, + body: sessionBody, + })).status, 404); + assert.equal((await fetch(`${origin}/gallery/api/view-session`, { + method: "POST", + headers: sessionHeaders, + body: JSON.stringify({ date_folder: date, base: "partial" }), + })).status, 404); + assert.equal((await fetch(`${origin}/gallery/api/view-session`, { + method: "POST", + headers: sessionHeaders, + body: JSON.stringify({ date_folder: date, base: "hidden" }), + })).status, 404); + + const manifestResponse = await fetch(`${origin}/gallery/api/view-session`, { + method: "POST", + headers: sessionHeaders, + body: sessionBody, + }); + assert.equal(manifestResponse.status, 200); + assert.equal(manifestResponse.headers.get("cache-control"), "private, no-store"); + const setCookie = manifestResponse.headers.get("set-cookie"); + assert.match(setCookie, /^frame_gallery_view=[A-Za-z0-9_-]+;/); + assert.match(setCookie, /Max-Age=300/); + assert.match(setCookie, /Path=\/gallery/); + assert.match(setCookie, /HttpOnly/); + assert.match(setCookie, /Secure/); + assert.match(setCookie, /SameSite=Strict/); + const cookie = setCookie.split(";", 1)[0]; + const { view } = await manifestResponse.json(); + assert.deepEqual( + { width: view.width, height: view.height, tile_size: view.tile_size, overlap: view.overlap, columns: view.columns, rows: view.rows }, + { width: 1025, height: 513, tile_size: 512, overlap: 1, columns: 3, rows: 2 }, + ); + assert.equal(view.tiles.length, 6); + assert.deepEqual( + view.tiles.map(({ x, y, width, height }) => ({ x, y, width, height })), + [ + { x: 0, y: 0, width: 512, height: 512 }, + { x: 1, y: 0, width: 512, height: 512 }, + { x: 2, y: 0, width: 1, height: 512 }, + { x: 0, y: 1, width: 512, height: 1 }, + { x: 1, y: 1, width: 512, height: 1 }, + { x: 2, y: 1, width: 1, height: 1 }, + ], + ); + assert.doesNotMatch(view.tiles[0].url, /visible|2026-06-13/); + + const isolatedManifestResponse = await fetch(`${origin}/gallery/api/view-session`, { + method: "POST", + headers: sessionHeaders, + body: sessionBody, + }); + assert.equal(isolatedManifestResponse.status, 200); + const isolatedCookie = isolatedManifestResponse.headers.get("set-cookie").split(";", 1)[0]; + const isolatedView = (await isolatedManifestResponse.json()).view; + assert.notEqual(isolatedView.handle, view.handle); + + const tileHeaders = { cookie, "sec-fetch-site": "same-origin", "sec-fetch-dest": "image" }; + assert.equal((await fetch(`${origin}${view.tiles[0].url}`, { + headers: { ...tileHeaders, cookie: isolatedCookie }, + })).status, 404); + const rejectedTile = await fetch(`${origin}${view.tiles[0].url}`, { headers: { cookie } }); + assert.equal(rejectedTile.status, 404); + assert.equal(rejectedTile.headers.get("cache-control"), "private, no-store"); + assert.equal(rejectedTile.headers.get("cross-origin-resource-policy"), "same-origin"); + assert.equal(rejectedTile.headers.get("x-content-type-options"), "nosniff"); + assert.equal((await fetch(`${origin}${view.tiles[0].url}`, { + headers: { ...tileHeaders, "sec-fetch-site": "cross-site" }, + })).status, 404); + assert.equal((await fetch(`${origin}/gallery/tile/${view.handle}/3/0.webp`, { headers: tileHeaders })).status, 404); + const tileResponse = await fetch(`${origin}${view.tiles[0].url}`, { headers: tileHeaders }); + assert.equal(tileResponse.status, 200); + assert.equal(tileResponse.headers.get("content-type"), "image/webp"); + assert.equal(tileResponse.headers.get("cache-control"), "private, no-store"); + assert.equal(tileResponse.headers.get("cross-origin-resource-policy"), "same-origin"); + assert.equal(tileResponse.headers.get("x-content-type-options"), "nosniff"); + assert.deepEqual( + await sharp(Buffer.from(await tileResponse.arrayBuffer())).metadata() + .then(({ format, width, height, exif }) => ({ format, width, height, exif })), + { format: "webp", width: 513, height: 513, exif: undefined }, + ); + + const rejectedDownload = await fetch(`${origin}/gallery/download/${date}/visible.jpg`); + assert.equal(rejectedDownload.status, 404); + assert.equal(rejectedDownload.headers.get("cache-control"), "private, no-store"); + assert.equal(rejectedDownload.headers.get("x-content-type-options"), "nosniff"); + await store.updateBranding({ show_download_button: true }); + + assert.equal((await fetch(imageUrl)).status, 404); + assert.equal((await fetch(imageUrl, { + headers: { ...imageHeaders, "sec-fetch-site": "cross-site" }, + })).status, 404); + assert.equal((await fetch(imageUrl, { + headers: { ...imageHeaders, "sec-fetch-dest": "document" }, + })).status, 404); + + const imageResponse = await fetch(imageUrl, { headers: imageHeaders }); + assert.equal(imageResponse.status, 200); + assert.match(imageResponse.headers.get("content-type"), /^image\/jpeg/); + assert.match(imageResponse.headers.get("content-disposition"), /^inline;/); + assert.equal(imageResponse.headers.get("cache-control"), "private, no-cache"); + assert.equal(imageResponse.headers.get("cross-origin-resource-policy"), "same-origin"); + assert.equal(imageResponse.headers.get("x-content-type-options"), "nosniff"); + assert.equal(imageResponse.headers.get("accept-ranges"), "bytes"); + const imageEtag = imageResponse.headers.get("etag"); + assert.ok(imageEtag); + const sourceImage = await readFile(path.join(gallery, "visible.jpg")); + const inlineImage = Buffer.from(await imageResponse.arrayBuffer()); + assert.deepEqual(inlineImage, sourceImage); + assert.deepEqual( + await sharp(inlineImage).metadata().then(({ format, width, height }) => ({ format, width, height })), + { format: "jpeg", width: 1025, height: 513 }, + ); + + const rangedImage = await fetch(imageUrl, { + headers: { ...imageHeaders, range: "bytes=0-31" }, + }); + assert.equal(rangedImage.status, 206); + assert.equal(rangedImage.headers.get("content-range"), `bytes 0-31/${sourceImage.length}`); + assert.equal(rangedImage.headers.get("content-length"), "32"); + assert.deepEqual(Buffer.from(await rangedImage.arrayBuffer()), sourceImage.subarray(0, 32)); + + const download = await fetch(`${origin}/gallery/download/${date}/visible.jpg`); + assert.equal(download.status, 200); + assert.match(download.headers.get("content-type"), /^image\/jpeg/); + assert.match(download.headers.get("content-disposition"), /^attachment;/); + assert.equal(download.headers.get("cache-control"), "private, no-store"); + + await store.updateBranding({ show_download_button: false }); + assert.equal((await fetch(imageUrl, { + headers: { ...imageHeaders, "if-none-match": imageEtag }, + })).status, 404); + await store.updateBranding({ show_download_button: true }); + + const exploreResponse = await fetch(`${origin}/gallery/api/explore?date=${date}`); + assert.match(exploreResponse.headers.get("cache-control"), /private, no-cache/); + assert.ok(exploreResponse.headers.get("etag")); + const publicExplore = (await exploreResponse.json()).explore; + assert.equal(publicExplore.routes.length, 1); + assert.ok(publicExplore.placements.visible); + assert.equal(publicExplore.placements.hidden, undefined); + const thumbnailResponse = await fetch(`${origin}/gallery/thumb/${date}/visible.webp`); + assert.equal(thumbnailResponse.headers.get("content-type"), "image/webp"); + assert.equal(thumbnailResponse.headers.get("cache-control"), "public, max-age=31536000, immutable"); + + await writeFile(path.join(gallery, "visible.trashed.json"), JSON.stringify({ trashed_at: new Date().toISOString() })); + assert.equal((await fetch(`${origin}${view.tiles[0].url}`, { headers: tileHeaders })).status, 404); + assert.equal((await fetch(imageUrl, { headers: imageHeaders })).status, 404); + assert.equal((await fetch(`${origin}/gallery/download/${date}/visible.jpg`)).status, 404); + assert.equal((await fetch(`${origin}/today/gallery/${date}/`)).status, 200); + } finally { + await closeServer(server); + } }); test("gallery admin is protected and proxies management through the internal service token", async () => { @@ -162,39 +557,87 @@ test("gallery admin is protected and proxies management through the internal ser } response.end(JSON.stringify({ ok: true, action: "empty-trash", affected: 0 })); }); - pipeline.listen(0); - await once(pipeline, "listening"); - const pipelinePort = pipeline.address().port; - const app = await createApp(new GalleryStore(root, 320, 80), path.resolve("public"), { - pipelineUrl: `http://127.0.0.1:${pipelinePort}`, - serviceToken: "service-secret", - auth: { username: "frame", password: "secret", realm: "FRAME Test" }, - }); - const server = app.listen(0); - await once(server, "listening"); - const base = `http://127.0.0.1:${server.address().port}`; - const authorization = `Basic ${Buffer.from("frame:secret").toString("base64")}`; + let server = null; try { + pipeline.listen(0); + await once(pipeline, "listening"); + const pipelinePort = pipeline.address().port; + const app = await createApp(new GalleryStore(root, 320, 80), path.resolve("public"), { + pipelineUrl: `http://127.0.0.1:${pipelinePort}`, + serviceToken: "service-secret", + auth: { username: "frame", password: "secret", realm: "FRAME Test" }, + }); + server = app.listen(0); + await once(server, "listening"); + const base = `http://127.0.0.1:${server.address().port}`; + const authorization = `Basic ${Buffer.from("frame:secret").toString("base64")}`; assert.equal((await fetch(`${base}/today/gallery/admin`)).status, 401); assert.equal((await fetch(`${base}/today/gallery/admin`, { headers: { authorization } })).status, 200); assert.deepEqual(await fetch(`${base}/gallery/admin/api/trash`, { headers: { authorization } }).then((response) => response.json()), { trash: [] }); assert.equal((await fetch(`${base}/gallery/admin/api/branding`, { method: "PUT" })).status, 401); - assert.equal((await fetch(`${base}/gallery/api/branding`).then((response) => response.json())).branding.presets.length, 5); + const defaultBranding = (await fetch(`${base}/gallery/api/branding`).then((response) => response.json())).branding; + assert.equal(defaultBranding.presets.length, 5); + assert.equal(defaultBranding.show_download_button, false); const branding = await fetch(`${base}/gallery/admin/api/branding`, { method: "PUT", headers: { authorization, "content-type": "application/json" }, body: JSON.stringify({ brand_name: "North Studio", gallery_title: "Launch Photos", + show_download_button: true, mode: "day", profile_id: "custom-launch-orange", custom_profiles: [{ id: "custom-launch-orange", name: "Launch Orange", theme_color: "#ff6600" }], + socials: [{ id: "flickr-main", platform: "flickr", label: "Event photos", url: "https://www.flickr.com/photos/frame" }], }), }).then((response) => response.json()); assert.equal(branding.branding.brand_name, "North Studio"); + assert.equal(branding.branding.show_download_button, true); assert.equal(branding.branding.active_profile.id, "custom-launch-orange"); assert.equal(branding.branding.presets.length, 6); - assert.equal((await fetch(`${base}/gallery/api/branding`).then((response) => response.json())).branding.gallery_title, "Launch Photos"); + const publicBranding = (await fetch(`${base}/gallery/api/branding`).then((response) => response.json())).branding; + assert.equal(publicBranding.gallery_title, "Launch Photos"); + assert.equal(publicBranding.show_download_button, true); + assert.equal(publicBranding.socials[0].platform, "flickr"); + const graphicDataUrl = `data:image/png;base64,${(await pngBuffer(500, 240, "#ff6600")).toString("base64")}`; + assert.equal((await fetch(`${base}/gallery/admin/api/branding/socials/flickr-main/graphic`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ data_url: graphicDataUrl }), + })).status, 401); + const graphicBranding = await fetch(`${base}/gallery/admin/api/branding/socials/flickr-main/graphic`, { + method: "POST", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ data_url: graphicDataUrl }), + }).then((response) => response.json()); + assert.equal(graphicBranding.branding.socials[0].graphic.width, 320); + const publicGraphic = await fetch(`${base}/gallery/branding/socials/flickr-main/graphic.webp`); + assert.equal(publicGraphic.status, 200); + assert.match(publicGraphic.headers.get("content-type"), /^image\/webp/); + const preserved = await fetch(`${base}/gallery/admin/api/branding`, { + method: "PUT", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ + socials: [{ + id: "flickr-main", + platform: "flickr", + url: "https://www.flickr.com/photos/frame", + graphic: { url: "https://example.com/spoof.webp", width: 320, height: 320, updated_at: "now" }, + }], + }), + }).then((response) => response.json()); + assert.equal(preserved.branding.socials[0].graphic.url, graphicBranding.branding.socials[0].graphic.url); + const deletedGraphic = await fetch(`${base}/gallery/admin/api/branding/socials/flickr-main/graphic`, { + method: "DELETE", + headers: { authorization }, + }).then((response) => response.json()); + assert.equal(deletedGraphic.branding.socials[0].graphic, undefined); + assert.equal((await fetch(`${base}/gallery/branding/socials/flickr-main/graphic.webp`)).status, 404); + assert.equal((await fetch(`${base}/gallery/admin/api/branding`, { + method: "PUT", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ socials: [{ id: "unsafe", platform: "website", url: "file:///etc/passwd" }] }), + })).status, 400); assert.equal((await fetch(`${base}/gallery/api/explore?date=${date}`).then((response) => response.json())).explore, null); assert.equal((await fetch(`${base}/gallery/admin/api/explore?date=${date}`)).status, 401); const storedExplore = await fetch(`${base}/gallery/admin/api/explore?date=${date}`, { headers: { authorization } }) @@ -210,6 +653,43 @@ test("gallery admin is protected and proxies management through the internal ser method: "DELETE", headers: { authorization }, }).then((response) => response.json())).explore, null); + await publish(gallery, "hero", true, "2026-06-13T19:00:00.000Z"); + const settingsUrl = `${base}/gallery/admin/api/galleries/${date}/settings`; + assert.equal((await fetch(settingsUrl, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ cover_base: "hero" }), + })).status, 401); + const settings = await fetch(settingsUrl, { + method: "PUT", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ cover_base: "hero", show_download_button: false }), + }).then((response) => response.json()); + assert.equal(settings.settings.cover_base, "hero"); + assert.equal(Object.hasOwn(settings.settings, "show_download_button"), false); + const dateSettings = (await fetch(`${base}/gallery/api/dates`).then((response) => response.json())).dates + .find((item) => item.date_folder === date); + assert.equal(dateSettings.cover_base, "hero"); + assert.equal(dateSettings.cover_fallback_active, false); + assert.equal(dateSettings.cover_is_custom, true); + assert.equal(Object.hasOwn(dateSettings, "show_download_button"), false); + assert.equal((await fetch(`${base}/gallery/admin/image/${date}/hero.jpg`)).status, 401); + const adminImage = await fetch(`${base}/gallery/admin/image/${date}/hero.jpg`, { headers: { authorization } }); + assert.equal(adminImage.status, 200); + assert.equal(adminImage.headers.get("cache-control"), "private, no-store"); + assert.equal((await fetch(`${base}/gallery/download/${date}/hero.jpg`)).status, 200); + const downloadsDisabled = await fetch(`${base}/gallery/admin/api/branding`, { + method: "PUT", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ show_download_button: false }), + }).then((response) => response.json()); + assert.equal(downloadsDisabled.branding.show_download_button, false); + assert.equal((await fetch(`${base}/gallery/download/${date}/hero.jpg`)).status, 404); + assert.equal((await fetch(settingsUrl, { + method: "PUT", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ cover_base: "missing" }), + })).status, 404); const result = await fetch(`${base}/gallery/admin/api/manage`, { method: "POST", headers: { authorization, "content-type": "application/json" }, @@ -218,21 +698,150 @@ test("gallery admin is protected and proxies management through the internal ser assert.equal(result.action, "empty-trash"); } finally { await Promise.all([ - new Promise((resolve) => server.close(resolve)), - new Promise((resolve) => pipeline.close(resolve)), + closeServer(server), + closeServer(pipeline), ]); } }); -async function publish(directory, base, ready) { - await sharp({ create: { width: 120, height: 80, channels: 3, background: "#2cb4fb" } }) +test("wires cover selection, global downloads, flowing photos, and viewer modes into the owner and visitor interfaces", async () => { + const [adminHtml, adminScript, adminStyles, galleryHtml, galleryScript, galleryStyles, justifiedScript] = await Promise.all([ + readFile(path.resolve("public/admin.html"), "utf8"), + readFile(path.resolve("public/admin.js"), "utf8"), + readFile(path.resolve("public/admin.css"), "utf8"), + readFile(path.resolve("public/index.html"), "utf8"), + readFile(path.resolve("public/gallery.js"), "utf8"), + readFile(path.resolve("public/styles.css"), "utf8"), + readFile(path.resolve("public/justified-rows.js"), "utf8"), + ]); + assert.match(adminHtml, /id="cover-action"/); + assert.match(adminHtml, /id="cover-picker"[^>]+role="dialog"[^>]+aria-modal="true"/); + assert.match(adminHtml, /id="cancel-cover-picker"/); + assert.doesNotMatch(adminHtml, /id="confirm-filename"/); + assert.match(adminHtml, /id="downloads-disabled"[^>]+aria-pressed="true"/); + assert.match(adminHtml, /id="downloads-enabled"[^>]+aria-pressed="false"/); + assert.match(adminHtml, /id="settings-action-bar"[^>]+hidden/); + assert.equal((adminHtml.match(/d="M3 6h18M8 6V4h8v2M6 6l1 15h10l1-15M10 11v6M14 11v6"/g) || []).length, 4); + assert.doesNotMatch(adminHtml, /\s*<\/strong><\/small><\/span>\s* +
diff --git a/services/frame-gallery/public/styles.css b/services/frame-gallery/public/styles.css index e5e28cc..7a17559 100644 --- a/services/frame-gallery/public/styles.css +++ b/services/frame-gallery/public/styles.css @@ -34,14 +34,14 @@ * { box-sizing: border-box; } [hidden] { display: none !important; } -html, body { max-width: 100%; overflow-x: hidden; } +html, body { max-width: 100%; overflow-x: clip; } body { margin: 0; min-height: 100vh; background: var(--background); } button, input { font: inherit; } button, a { -webkit-tap-highlight-color: transparent; } button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; } .topbar { - position: sticky; z-index: 5; top: 0; min-height: 76px; display: flex; align-items: center; + position: sticky; z-index: 1100; top: 0; min-height: 76px; display: flex; align-items: center; justify-content: space-between; gap: 18px; padding: 10px clamp(14px, 4vw, 42px); border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--topbar) 94%, transparent); backdrop-filter: blur(16px); } @@ -80,14 +80,37 @@ main { width: min(1500px, 100%); margin: 0 auto; padding: 18px clamp(12px, 3vw, } .theme-toggle { width: 38px; min-width: 38px; min-height: 34px; padding: 7px; border-color: var(--accent); background: var(--toggle-night-bg, #dff4ff); color: var(--toggle-night-text, #087fc0); } .socials-button { - flex: none; min-height: 38px; border-color: color-mix(in srgb, var(--accent) 78%, white); background: var(--accent); + --socials-travel: 82px; + position: relative; flex: none; width: 82px; height: 38px; min-height: 38px; padding: 8px 12px; + border-color: color-mix(in srgb, var(--accent) 78%, white); background: var(--accent); color: var(--accent-contrast, var(--action-text, #03121b)); font-weight: 800; box-shadow: 0 5px 14px color-mix(in srgb, var(--accent) 18%, transparent); - animation: socials-glow 2.8s ease-in-out infinite; + animation: socials-bounce 8s ease-in-out infinite; } .socials-button:hover { border-color: var(--accent); filter: brightness(1.06); } -@keyframes socials-glow { - 0%, 100% { box-shadow: 0 0 0 0 transparent, 0 5px 14px color-mix(in srgb, var(--accent) 18%, transparent); } - 50% { box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 16%, transparent), 0 5px 18px color-mix(in srgb, var(--accent) 30%, transparent); } +.socials-button:hover, .socials-button:focus-visible { animation: none; transform: none; } +.socials-button:hover .socials-label-default, .socials-button:focus-visible .socials-label-default { animation: none; transform: none; } +.socials-button:hover .socials-label-invite, .socials-button:focus-visible .socials-label-invite { display: none; } +.socials-reel { position: relative; display: block; width: 100%; height: 20px; overflow: hidden; } +.socials-label { position: absolute; top: 0; height: 100%; display: flex; align-items: center; white-space: nowrap; } +.socials-label-default { inset-inline: 0; justify-content: center; } +.socials-label-invite { left: 100%; width: max-content; } +.socials-label-default { animation: socials-default-label 8s ease-in-out infinite; } +.socials-label-invite { animation: socials-invite-label 8s linear infinite; } +@keyframes socials-bounce { + 0%, 42%, 50%, 100% { transform: translateY(0) scale(1); } + 44% { transform: translateY(0) scaleX(1.05) scaleY(.94); } + 46% { transform: translateY(-5px) scaleX(.97) scaleY(1.06); } + 48% { transform: translateY(0) scaleX(1.04) scaleY(.96); } +} +@keyframes socials-default-label { + 0%, 48% { transform: translateX(0); } + 52%, 72% { transform: translateX(-125%); } + 72.01% { transform: translateX(125%); } + 78%, 100% { transform: translateX(0); } +} +@keyframes socials-invite-label { + 0%, 52% { transform: translateX(0); } + 72%, 100% { transform: translateX(calc(-100% - var(--socials-travel))); } } :root[data-theme="day"] .theme-toggle, :root[data-theme-mode="day"] .theme-toggle, .theme-toggle[aria-pressed="true"] { border-color: var(--accent); background: var(--toggle-day-bg, #fff6d5); color: var(--toggle-day-text, #8a5e00); } .secondary-button:hover, .icon-button:hover, .icon-toggle:hover, .lightbox-control:hover { border-color: var(--accent); } @@ -389,7 +412,7 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } .summary strong { font-size: 12px; } .topbar-actions { width: auto; justify-content: flex-end; gap: 6px; } .theme-toggle { min-height: 34px; } - .socials-button { min-height: 34px; padding: 6px 8px; font-size: 12px; } + .socials-button { --socials-travel: 64px; width: 64px; height: 34px; min-height: 34px; padding: 6px 8px; font-size: 12px; } .socials-dialog { width: calc(100vw - 12px); height: calc(100dvh - 12px); } .socials-dialog-panel { padding: 13px; } .social-link { grid-template-columns: minmax(0, 1fr); gap: 9px; } @@ -433,7 +456,8 @@ body.is-exploring { height: 100dvh; min-height: 0; overflow: hidden; } } @media (prefers-reduced-motion: reduce) { - .socials-button, .lightbox-loading::before, .lightbox-loading.is-complete { animation: none; } + .socials-button, .socials-label, .lightbox-loading::before, .lightbox-loading.is-complete { animation: none; } + .socials-label-invite { display: none; } .lightbox-nav, .lightbox-preview, .lightbox-full, .lightbox-tiles, .photo-card::after, .photo-overlay, .photo-open img { transition: none; } } @media (hover: none), (pointer: coarse) { diff --git a/services/frame-gallery/tests/gallery.test.mjs b/services/frame-gallery/tests/gallery.test.mjs index f8dc900..70f52a7 100644 --- a/services/frame-gallery/tests/gallery.test.mjs +++ b/services/frame-gallery/tests/gallery.test.mjs @@ -811,7 +811,19 @@ test("wires cover selection, global downloads, flowing photos, and viewer modes assert.match(galleryHtml, /Select a platform or link name to open it, or use the buttons to copy or scan it\./); assert.match(galleryStyles, /\.social-link-identity\s*\{[^}]*color:\s*inherit[^}]*text-decoration:\s*none/); assert.match(galleryStyles, /\.social-link-identity:focus-visible\s*\{[^}]*outline:\s*2px solid var\(--accent\)/); - assert.match(galleryHtml, /styles\.css\?v=gallery-viewer-modes-1/); + assert.match(galleryHtml, /id="socials-button"[^>]*aria-label="Socials — Connect with me"[^>]*aria-haspopup="dialog"[^>]*aria-controls="socials-dialog"/); + assert.match(galleryHtml, /class="socials-reel" aria-hidden="true"[^>]*>[\s\S]*Socials[\s\S]*Connect with me!/); + assert.match(galleryStyles, /\.socials-button\s*\{[^}]*width:\s*82px[^}]*height:\s*38px[^}]*animation:\s*socials-bounce 8s/); + assert.match(galleryStyles, /\.socials-reel\s*\{[^}]*overflow:\s*hidden/); + assert.match(galleryStyles, /\.socials-label-invite\s*\{[^}]*left:\s*100%[^}]*width:\s*max-content/); + assert.match(galleryStyles, /@keyframes socials-default-label/); + assert.match(galleryStyles, /@keyframes socials-invite-label/); + assert.doesNotMatch(galleryStyles, /socials-glow/); + assert.match(galleryStyles, /\.socials-button:hover, \.socials-button:focus-visible\s*\{\s*animation:\s*none/); + assert.match(galleryStyles, /@media \(prefers-reduced-motion:\s*reduce\)[\s\S]*\.socials-label-invite\s*\{\s*display:\s*none/); + assert.match(galleryStyles, /html, body\s*\{[^}]*overflow-x:\s*clip/); + assert.match(galleryStyles, /\.topbar\s*\{[^}]*position:\s*sticky[^}]*z-index:\s*1100[^}]*top:\s*0/); + assert.match(galleryHtml, /styles\.css\?v=gallery-sticky-header-2/); assert.match(galleryHtml, /gallery\.js\?v=gallery-viewer-modes-1/); assert.doesNotMatch(galleryScript, /photo\.image_url/); assert.match(galleryScript, /openPhotoBase/);