release: v0.11.0 — journal fixes, admin URLs, design system cleanup (#432)
* fix(screenshots): sharp-Typen fuer 0.34 und 0.35 gleichzeitig (#410) sharp 0.35 ist von `export =` auf ESM umgestellt: der Modul-Namespace ist nicht mehr aufrufbar, die Factory sitzt unter .default. Der Type-Check brach damit in scripts/screenshots.ts weg, sobald der Next-Bump (#402) sharp von 0.34.5 auf 0.35.3 mitzieht -- sharp ist hier keine deklarierte Dependency, sondern kommt ueber Next mit. Die Form wird jetzt aus dem installierten Paket abgeleitet statt festgeschrieben, zur Laufzeit wie im Typ. Geprueft mit beiden Versionen: tsc laeuft mit 0.34.5 und mit 0.35.3 fehlerfrei durch. Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(deps): bump the nextjs group across 1 directory with 2 updates (#402) Bumps the nextjs group with 2 updates in the / directory: [next](https://github.com/vercel/next.js) and [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next). Updates `next` from 16.2.12 to 16.3.0 - [Release notes](https://github.com/vercel/next.js/releases) - [Commits](https://github.com/vercel/next.js/compare/v16.2.12...v16.3.0) Updates `eslint-config-next` from 16.2.12 to 16.3.0 - [Release notes](https://github.com/vercel/next.js/releases) - [Commits](https://github.com/vercel/next.js/commits/v16.3.0/packages/eslint-config-next) --- updated-dependencies: - dependency-name: eslint-config-next dependency-version: 16.3.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: nextjs - dependency-name: next dependency-version: 16.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: nextjs ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump prettier from 3.8.3 to 3.9.6 (#405) Bumps [prettier](https://github.com/prettier/prettier) from 3.8.3 to 3.9.6. - [Release notes](https://github.com/prettier/prettier/releases) - [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md) - [Commits](https://github.com/prettier/prettier/compare/3.8.3...3.9.6) --- updated-dependencies: - dependency-name: prettier dependency-version: 3.9.6 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * docs(changelog): Unreleased-Sektion fuer die Bumps nach v0.10.0 (#413) Die Dependency-PRs sind nach dem Release auf dev gelandet, teils auch auf main. Ohne Eintrag waeren sie beim naechsten Release unsichtbar -- inklusive Next 16.3.0, das CVE-2025-13465 mitbringt. Ausserdem im 0.10.0-Abschnitt nachgetragen, dass der Trivy-Scan bis #409 nie gelaufen ist. Der Fix steckt im Tag v0.10.0, fehlte aber in der Aufzaehlung -- und "Images werden bei jedem Publish gescannt" stand im Changelog, waehrend der Job im Action-Setup abbrach. Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(gallery): per-album sort order, independent of Immich (#408) (#414) Album order was dictated entirely by Immich: getAlbum() sorted by the album's own asc/desc flag, so a Folio album always mirrored the archive. A curated series has a narrative order that has nothing to do with capture time, and changing the Immich album's sort to fit the website changes it for the archive too. Adds an optional per-album `sort` in gallery.yaml, editable in /admin, defaulting to today's behaviour so every existing config is unchanged: immich (default) | newest | oldest | filename | manual `manual` is a pinned *prefix*: `assetOrder` lists only the photos placed by hand, everything else follows in the album's Immich order. A full permutation of a 2,000-photo album would be ~80 KB of UUIDs in a file that is rewritten and copied to content/.backups/ on every admin save. It also makes drift fall out for free — photos removed in Immich never match, new ones land in the tail rather than being hidden. Sorting is applied after the cache read, not before the cache write, so the LRU keeps one canonical Immich-ordered copy per album. That avoids putting the mode in the cache key, lets a config change take effect without depending on invalidation, and keeps the stale-serving path correct. cache.get() returns the stored object by reference, so withSort() returns a shallow clone with a new array — sorting in place would reorder the shared entry, and under request coalescing every concurrent caller would be sorting the same array. Also fixes a prerequisite bug: /api/admin/albums/[albumId]/assets read album.assets from GET /albums/:id, which Immich 3.x no longer populates (lib/immich.ts:507). The hero picker's "This Album" tab returned nothing and threw outright when the key was absent. It now goes through the client's paginated metadata search, with ?types=all to opt videos in for the reorder editor. Co-authored-by: ralksta <ralksta@users.noreply.github.com> * refactor(admin): drop decorative emoji from the sort select labels (#415) An <option> cannot contain markup, so the SVG set in Icons is not reachable there — but a decorative emoji is not a substitute for it. Plain text instead; the album card badge already uses a real icon. The remaining emoji in the admin panel (asset picker tabs, section headings, layout picker options) predate this branch and are left for a separate cleanup. Co-authored-by: ralksta <ralksta@users.noreply.github.com> * refactor(admin): replace emoji icons with the shared SVG icon set (#416) The admin panel mixed two icon conventions: inline SVGs from `Icons.tsx` in most components, and decorative emoji in the asset picker and a few PageBuilder labels. Emoji render inconsistently across platforms, ignore the accent colour, and cannot inherit the `.svg-icon` sizing rules. - Icons.tsx: add `IconStar` (filled — it marks a state, not an action) and `IconImage`. - AssetPicker: the three tab labels and the favourite tile badge now use IconFolder / IconStar / IconImage. - PageBuilder: the "Standalone Albums" and "Subpages" headings use the icon set instead of an emoji. - PageBuilder: the layout picker drops its emoji for plain text. An <option> cannot contain markup, so an SVG is impossible there and a decorative glyph is not a substitute. - admin.css: align icon and label in the picker tabs, and swap the favourite badge's text-shadow for drop-shadow, which is what applies to an inline SVG. Co-authored-by: ralksta <ralksta@users.noreply.github.com> * refactor(admin): fold PageBuilder's local icons into the shared Icons module (#418) * refactor(admin): fold PageBuilder's local icons into the shared module PageBuilder.tsx carried its own `Icons` object duplicating most of the glyphs already exported by Icons.tsx, with hardcoded sizes and slightly divergent paths. Migrate all 32 call sites to the shared module and delete the local object. Five glyphs had no counterpart and are added to Icons.tsx as 1:1 ports of the local paths: IconX, IconPlus, IconHome, IconCopy, IconImage. The local ExternalLink and Check are dropped rather than ported — both had zero call sites. Two glyphs change shape slightly, which is the point of consolidating: the shared IconCamera includes the viewfinder bump the local copy omitted, and drag handles now use IconGripVertical. IconGripVertical uses the module's square 24x24 viewBox, so `.svg-drag` goes from 12x18 to 18x18 — the old non-square box would letterbox the glyph down to 12x12 and shrink the handle. * fix(admin): resolve icon-module integration after #416 Merging dev brought in #416, which added a second IconImage to Icons.tsx and two <Icons.Camera>/<Icons.Folder> section headers that reference the local Icons object this PR removes. Git merged both cleanly but the result did not type-check. - drop the duplicate IconImage (both copies were byte-identical) - point the two section headers at the imported IconCamera/IconFolder - refresh the SORT_LABELS comment: the icon set is imported now, not declared below --------- Co-authored-by: ralksta <ralksta@users.noreply.github.com> * fix(config): allow an empty gallery, guard against a double /api suffix (#421) An empty gallery is now a valid, rendered state instead of a throw: deriveGallery() no longer requires at least one album or subpage, so a deployment with no albums yet renders a bare homepage the owner can fill in via /admin. getConfig() also stops appending /api to an Immich URL that already ends in it, which previously produced .../api/api and broke every upstream request. Includes a restore of the per-album sort test cases, which the branch had lost by being cut before #408/#414. * feat(admin): favicon upload, served from the content volume (#422) Adds a bundled default favicon, an upload widget in admin Settings > General, and a route that serves the icon from the writable content/ volume with a fallback to the bundled default. Raster uploads (PNG/ICO/JPEG) are wrapped in an SVG container; the response carries its own CSP so an uploaded SVG cannot execute script on the origin. The GET route revalidates with an ETag instead of caching immutably, so a newly uploaded icon shows up immediately. Uploads are written via temp file + rename, and a Reset button restores the bundled default. * ci: flag unformatted files in a PR, without blocking it (#424) Prettier is configured as an error rule in eslint.config.mjs but has never run in CI, so part of the tree predates it. A final CI step now diffs against the PR base, runs prettier --list-different over the changed files, and emits a warning annotation per offender plus a job summary. Advisory by design: it never fails the job. Blocking would turn a PR red for merely touching a file that was already unformatted, and normalising the tree in one commit would wreck git blame and conflict with the PRs in flight. Requires fetch-depth: 0, since diffing against the base needs its history. * feat(install): first-run wizard gated by a one-time setup token (#419) Adds /install, a four-step first-run wizard: connect to Immich, optionally pick albums, name the site, finish. It verifies the credentials against the Immich server before writing anything, then writes gallery.yaml, settings.yaml and a content/install.json carrying the Immich credentials and a generated site secret. install.json exists because a running process cannot pick up new env vars — the wizard has to write configuration that takes effect without a restart. getInstallCredentials() merges it under the real environment, so env vars always win and rotation stays a matter of setting one. Both the page and the API routes are gated by a one-time setup token printed to the server log, so a deployment that is reachable before gallery.yaml exists cannot be configured by whoever finds it first. The token is stored in content/.setup-token (0600) rather than a module variable: Next.js bundles the page and each route handler separately, so a module-level token left the page and the API disagreeing inside one process and the wizard stuck on step 1. It is removed once the install completes. The admin password is stored as an scrypt hash using the scheme lib/auth.ts already applies to album passwords; a plaintext ADMIN_PASSWORD env var keeps working. * docs: document the setup wizard, fix the read-only content mount (#425) Quick Start now leads with the /install wizard, with the hand-written YAML route kept alongside it, and a First-Run Setup section covers the setup token, the files the wizard writes, and env-var precedence. Two corrections: both Docker examples mounted content/ as :ro, which silently breaks the wizard, the admin panel and the backup rotation alike — docs/admin-panel.md already said so and the README contradicted it. And nothing documented that content/install.json holds the Immich API key, so a backup of content/ is a backup of credentials. Also adds a Contributors section crediting the people whose work is in the project. * feat(admin): floating save bar pinned to the bottom of the viewport (#426) The save bar was the first, static element inside .admin-main. Since the document itself scrolls, it left the viewport as soon as you scrolled down — editing a subpage section or a settings block far below gave no visible dirty hint and no reachable save button. Replace it with a bottom-pinned floating bar shared by both editors. It only mounts while there is something to act on (unsaved changes, an in-flight save, or a result message), so it never covers content while idle. The success message clears after 5s, which hides the bar again. - new SaveBar component, replacing the duplicated markup in PageBuilder and SettingsEditor - adopt the previously unused .floating-save-bar CSS: slide-in keyframes (carrying translateX(-50%)), dirty border, wrap/gap, mobile variant and a prefers-reduced-motion opt-out; z-index 900 keeps it below modals - .admin-main gains bottom padding so the bar never covers page content - drop the now-unreachable idle hints: the ⌘S hint becomes a button title, the Live Sync note becomes a static line above the settings layout - header "Site" link now bypasses the cache (/?fresh=1), so the preview stays reachable when the bar is hidden Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(admin): themed listbox for the album sort control (#427) The per-album "Photo order" control was a native <select>. Because an <option> cannot contain markup, its choices could not use the admin panel's currentColor SVG set — the reason #415 had to fall back to plain text after dropping the emoji labels. Adds a Listbox component implementing the ARIA combobox/listbox pattern, so options can render a glyph beside their label: - DOM focus stays on the trigger button; the active option is announced through aria-activedescendant, keeping focus management to one element - Keyboard: arrows (clamped at the ends, like a native select), Home/End, Enter/Space to commit, Escape to cancel, Tab commits and moves on, and prefix type-ahead with a repeat-key cycle - Outside dismissal on pointerdown, so a press starting outside closes the popup before the click retargets The sort options now carry an icon each: calendar, arrow-down, arrow-up, an A→Z marker, and the drag glyph for manual — matching the badge the album card already shows. SORT_LABELS stays plain text because the badge feeds it to a title attribute. Closes #417 Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(git): ignore generated design handoff folders * fix(admin): stop the album sort dropdown clipping, and simplify the panel (#428) * fix(admin): render listbox popup in a portal so it escapes modal clipping The sort control's popup was position:absolute inside three clipping ancestors (.album-drawer overflow:hidden > .album-drawer-body overflow-y:auto > .modal-right-column overflow-y:auto), so it was cut off at the bottom of the Edit Album Details modal. z-index could not help: clipping happens before stacking. It also always hung below the trigger, with no flip. Portal the popup to document.body and position it from the trigger's viewport rect, flipping above when there is more room there and capping max-height to the space available so it scrolls internally rather than overflowing. It is dismissed on scroll and resize, since the anchor is only measured on open. The outside-pointerdown handler now also treats the popup as inside; without that the portalled list counts as outside, and a click on an option would close it before the selection commits. * refactor(admin): single-column album details panel The left column spent 1.2fr on a cover thumbnail and three stat rows, two of which (Status, Custom Hero) only restated the form fields opposite them, while the form itself was squeezed into 1.8fr behind a second nested scroller. Stack the drawer in one column instead: cover as a banner, then the form at full width, with the UUID moved into the footer. The body is now the only scroll container, which also removes one of the ancestors that was clipping the sort popup. --------- Co-authored-by: ralksta <ralksta@users.noreply.github.com> * fix(admin): give the portalled listbox its theme back, lock the page behind modals (#429) Two defects in the album editor. The sort listbox popup painted transparent. Every --admin-* variable is scoped to .admin-layout, and since the popup moved into document.body it sits outside that subtree, so background/border/text all resolved to nothing. It now carries its own copy of the palette in both colour schemes, plus the font it no longer inherits. Scrolling inside a modal also moved the page behind it. No admin modal ever locked body scroll: the overlay covers the page but does not absorb wheel events, so a scroll starting on the backdrop — or continuing past the end of the modal's own scroller — reaches the document. overscroll-behavior cannot cover that case on its own, because it only applies to scroll containers and the backdrop is not one. useScrollLock freezes body while a modal is open and compensates for the width the scrollbar gives up, so nothing shifts underneath. Each lock restores the inline value it found, which makes nesting work without a counter — a picker opened from the drawer restores the drawer's hidden state instead of clearing it. Applied to both drawers and all four picker modals, which share the defect. overscroll-behavior: contain on the scrollers stops the chaining they can handle themselves. Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * fix(security): allow unsafe-eval in CSP script-src during dev mode * feat(journal): add Journal Studio with split-screen editor, live preview and dedicated routes * fix(build): separate client parser from server journal-service and fix build type errors * fix(journal): Fotos rendern, Layout und Lightbox-Steuerung korrigieren Fünf unabhängige Fehler in der öffentlichen Journal- und Essay-Ansicht: * Foto-Blöcke wurden nie angezeigt. EssayView löst ein Foto über PhotoItem.id auf, und das sind verschlüsselte Tokens — die Blöcke aus dem Markdown tragen aber rohe Asset-UUIDs. Jede Zuordnung lief ins Leere, und nicht auflösbare Blöcke werden still verworfen. Die IDs werden jetzt serverseitig übersetzt; damit verschwinden nebenbei die rohen UUIDs aus dem Client-Payload, die dort laut Projektregel nie auftauchen dürfen. Nicht auflösbare Referenzen werden geloggt. * Überschriften standen weiter links als der Fließtext. Jeder Block hatte einzeln `max-width: 68ch`, und `ch` ist relativ zur Schrift des Elements — die Serif-Überschrift ergab eine breitere Spalte. Ersetzt durch eine gemeinsame, font-unabhängige `--essay-measure`. * Fullbleed-Fotos bluteten nur nach links aus: `.essay-figure` ist `width: 100%`, wodurch die Box überbestimmt ist und der negative rechte Margin verworfen wird. * Foto-Paare stellten beide Bilder gleich breit dar, wodurch ein Hochformat neben einem Querformat doppelt so hoch wurde. Jetzt eine Justified-Reihe: Breite proportional zum Seitenverhältnis, dadurch exakt gleiche Höhen ohne Beschnitt. * Die Lightbox hatte im Journal keine Tastatursteuerung und keine Scroll-Sperre — beides lag in PhotoGrid, also nur im Album-Raster. Verlagert in die Lightbox selbst, der doppelte Handler in PhotoGrid entfernt (sonst wäre pro Pfeildruck zwei Bilder weitergesprungen). Zusätzlich sind Proofing-Herzen und das EXIF-Panel im redaktionellen Modus abschaltbar und im Journal aus: Client-Proofing ist ein Übergabe-Workflow für Alben, keine Funktion einer Reportage. Auf der Übersicht wurde der Untertitel doppelt gerendert, weil extractExcerpt() auf ihn zurückfällt. * feat(admin): eigene URLs für alle Bereiche und überarbeiteter Journal Studio Das Panel war eine einzige Client-Komponente, die ihre Tabs über useState umschaltet: keine Route pro Bereich, kein Deep-Link, kein Zurück-Button, und nach jedem Reload landete man wieder auf "Pages". Auch der Journal-Editor hatte keine eigene URL. Jetzt sieben echte Routen (/admin, /admin/pages, /admin/journal, /admin/journal/<slug>, /admin/settings, /admin/settings/<section>, /admin/analytics). Die Shell mit Auth-Prüfung und Kopfzeile sitzt im Layout und umschließt children — so bleibt die Session-Prüfung über Routenwechsel montiert, statt bei jedem Tab-Wechsel neu zu laufen und den Spinner aufblitzen zu lassen. Unbekannte Settings-Sections fallen auf General zurück. Im selben Zug der Journal Studio, der die Routing-Änderung ohnehin berührt: * Alle Eingabefelder nutzten die Klasse `admin-input`, die in keinem CSS definiert war — sie fielen auf Browser-Defaults zurück. Jetzt gestylt, gescoped, damit der generische Name nicht ins übrige Panel leckt. * Der Split View ist per Divider verschiebbar (Maus, Tastatur, Doppelklick zum Zurücksetzen), Breite in localStorage. * Das Studio bricht aus der 1120px-Spalte aus, die Preview hat Platz. * Die Preview zeigte für jedes Foto fest 3:2 und log damit über das Layout der veröffentlichten Seite; die echten Verhältnisse werden jetzt an den Thumbnails gemessen. * Blöcke mit alten positionsbasierten Foto-Referenzen werden markiert — die lassen sich auf einer eigenständigen Journal-Seite nicht auflösen und verschwanden bisher stillschweigend. * Blocktyp-Chips als gemeinsame Komponente, monochrom und per Icon unterschieden statt in einer eigenen Blau/Lila/Orange-Palette, die sonst nirgends im Panel vorkommt. * Emojis raus, SVG-Icons rein. * fix(admin): Designsystem-Lücken im Panel schließen Eine systematische Suche nach Klassen, die im TSX benutzt, aber in keinem CSS definiert sind, hat vier Stellen mit demselben Muster gefunden: * `admin-btn-secondary` und `admin-btn-danger` existierten nicht. Sämtliche Löschen-Buttons sahen aus wie normale Buttons — keine Warnwirkung. Als `.admin-btn.admin-btn-danger` geschrieben, weil die Varianten mit den Größenklassen kombiniert werden, die weiter unten ihren eigenen Hintergrund setzen. * `page-progress-fill` fehlte: die Balken im Analytics-Panel waren leere Rinnen, der Wert unsichtbar. Ebenso `analytics-empty` und `admin-loading-container`. * `subpage-drawer-section`, `subpage-drawer-title-group` und `input-with-icon` im PageBuilder waren wirkungslos und teils mit Inline-Styles notdürftig kompensiert. * `grid-card-preview` fehlte, wodurch alle Layout-Vorschauen auf Höhe null kollabierten. Nur "Showcase" war sichtbar — und das aus Versehen, weil sein Tile `hero-tile` hieß und damit die `aspect-ratio` einer fremden PageBuilder-Klasse erbte. Umbenannt. Dazu die Theme-Vorschauen, die praktisch identisch aussahen: alle sieben zeigten dieselben drei quadratischen Kacheln, einziger Unterschied war die Hintergrundfarbe. Sie spiegeln jetzt die echten Preset-Daten aus lib/config/theme.ts — Schriftcharakter, Eckradius, Rasterdichte, Passepartout bzw. Schatten. Die Kopfzeile richtet sich an einer gemeinsamen Steuerhöhe aus. Der "Site"-Link war höher als die Buttons daneben: `.admin-btn` hatte keine explizite line-height, und <button> bekommt box-sizing: border-box vom Browser, <a> nicht. Die Statusanzeige setzte weder Schriftfamilie noch -größe und fiel auf den Browser-Default zurück — sie war nie Teil des Designsystems. Jetzt gleiche Höhe und Typografie, Pillenform als Zustandsanzeige, Trenner zur Aktionsgruppe. Das dauerhafte Pulsieren des grünen Punkts entfällt; Animation bleibt den Zuständen vorbehalten, die Aufmerksamkeit brauchen. Restliche Emojis durch SVG-Icons ersetzt. * feat(admin): add scroll-to-top toggle and SVG arrow The back-to-top button was always on and drew its arrow with the ↑ text character. Add a `scrollToTop` setting (General section in the admin panel, defaults to on so existing sites are unaffected) and replace the glyph with a stroked SVG that inherits currentColor across all presets. Scroll handling is now rAF-throttled, and prefers-reduced-motion turns off both the hover lift and the smooth scroll. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * security(journal): escape author HTML instead of filtering it CodeQL flags 26 high-severity alerts on the release PR; the bulk of them point at sanitizeHtml(), a denylist of three regexes whose output goes into dangerouslySetInnerHTML. I reproduced the bypasses before changing anything — all four pass the old filter: <img src=x onerror=alert(1)> unquoted handler, regex wants quotes <img src=x onerror='alert(1)'> single quotes, same reason <svg onload=alert(1)> not a <script> tag javasjavascript:cript:alert(1) one-pass replace, the rest recombines Plus an attribute breakout in the link renderer, which interpolated the URL into href="${url}" unescaped: [x](" onmouseover=alert(1) x=") -> <a href="" onmouseover=alert(1" ...> Replaced with escaping. Every `&<>"'` in author text becomes an entity before any markdown rule runs, so the only tags in the output are the ones renderInlineMarkdown builds itself and a URL cannot leave its attribute. Link schemes are now an allowlist (http, https, mailto, tel, relative, anchor); anything else renders as plain text. The serializer needed decodeHtmlEntities to match: without it a save would write `<` into the Markdown file and the next parse would escape the `&` again, corrupting the text further on every round trip. A test covers parse -> serialize -> parse stability. Two existing tests asserted the old behaviour and were rewritten rather than deleted: one expected the script tag to be *removed* from the output, the other expected the substring "onerror" to be absent. Both now assert the property that matters — that no tag can form — because `onerror` surviving as inert text is fine. Exploitation required admin access either way: journal and essay text comes from the studio or from content/*.md. This removes the weakness, it does not close an open door. * fix(journal): contain file paths, fix frontmatter escaping, defuse two regexes Follow-up to the CodeQL findings on release PR #432. I went through all 23 alerts individually; this addresses the ones that are worth addressing and documents the ones that are not. Path containment (12 alerts, all false positives). Every path built from a slug goes through isValidSlug(), a strict `/^[a-zA-Z0-9_-]+$/` allowlist — verified against `../../etc/passwd`, `foo/../../bar`, `a/b`, `..` and friends, all rejected. CodeQL cannot see it because the check lives in another module. Added a containedPath() helper that resolves the path and refuses anything landing outside the content directory: a second lock on a door that was already locked, and a barrier the analysis can follow. Also removed the dead `slug.endsWith('.md')` branches — isValidSlug rejects dots, so they could never be taken. Frontmatter escaping (1 alert, a real bug). The serializer escaped `"` but not `\`, and the parser never unescaped anything. A title containing either character gained a backslash on every save/load cycle: Path C:\Users "quoted" -> Path C:\\Users \"quoted\" -> ... Escaping now covers the backslash first and the parser undoes both. A round trip test covers quotes, backslashes, colons and apostrophes. Two of three ReDoS regexes (2 alerts). The heading pattern had `\s+` next to `(.+)`, which overlap, so the engine tried every split of the whitespace run before failing; it is `[ \t]+` and `(\S.*)` now. The quote author pattern wrapped a lazy group around an optional group — the quadratic case — and is an index split on the first separator now. The third regex, the bold/italic pass, is deliberately left alone. Rewriting it with a negated class removes the backtracking but breaks nesting: `**bold *and italic* here**` renders as `*<em>bold </em>and italic<em> here</em>*`. The input is Markdown from an authenticated admin, never a visitor, so the worst case is an author slowing down their own page. The comment in the code says so. Not addressed: 5 js/insufficient-password-hash alerts. They ask for a slow KDF where the code uses SHA-256/HMAC — correct in general, but the admin password comes from an environment variable and is never stored, so a stronger KDF protects nothing that is not already in plaintext in the environment. 399 unit tests pass (18 new), build and tsc clean. * fix(journal): split the quote author by scanning, not by pattern Cleaning up after myself. #439 replaced the quote author regex `/^(.*?)(?:\s+--\s+(.+))?$/` — a lazy group around an optional one, the quadratic case — with `/\s+--\s+/`, and CodeQL promptly flagged the replacement for the same reason. One reported pattern traded for another. splitQuoteAuthor() scans for the first `--` that has whitespace on both sides. Linear, and it needs no reasoning about the regex engine at all. Behaviour is identical to the original regex, checked case by case against it: separator, no separator, several separators, tabs, wide gaps, `a--b` without spaces, leading and trailing separators, empty string. All nine are covered by tests, plus one asserting it stays fast on a 50k whitespace run. * security(admin): derive the session signing key with scrypt getSigningKey() ran the admin password through a single SHA-256 digest. It is key derivation rather than password storage, so it was never a stored-hash problem — but if the derived key ever leaked, one fast hash makes recovering the password by brute force cheap. CodeQL flags it as js/insufficient-password-hash and, for this particular alert, has a point. scrypt now. Two details that matter: The salt has to be stable. A random salt would produce a different key on every call and invalidate every session; it is derived from AUTH_SECRET, which is deployment-specific. Verified across separate processes: same inputs produce a verifying token, so a restart or redeploy does not log everyone out. The result is cached for the process lifetime. scrypt is deliberately slow and getSigningKey() runs on every admin request — deriving per call would add ~24ms to each one. The cache key is a digest of secret plus password, so a rotation misses the cache and derives again, and no extra plaintext copy of the password is kept around. Measured: first derivation 24ms, subsequent calls 0.12ms. Password change and secret change both invalidate an existing token, checked in separate processes. Note the one-time effect: existing admin sessions are invalidated by the change in derivation, so everyone logs in once more. * security(admin): key the signing-key cache on its inputs, not a digest #441 removed the SHA-256 digest of the admin password from the key derivation and introduced a new one three lines above it, as the cache key. Same rule, same file: CodeQL reported it immediately. The comment justifying it was wrong too. It claimed no second plaintext copy of the password was retained, while building the digest input allocates exactly that in order to hash it. The cache now holds the two input strings and compares them directly. They are the same objects the env and install caches already hold, so nothing extra is retained, and no fast hash of the password exists in memory for the life of the process. Re-verified after the change, in separate processes: a token from one process verifies in another with the same inputs, a changed password or secret rejects it, first derivation 24ms, cached calls 0.001ms. That leaves scrypt as the only place the password is hashed here. The two HMACs further down operate on the derived key and on token data, not on the password; the constant-time comparison in verifyAdminPassword is the previously dismissed one. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: lancetm714 <108419425+lancetm714@users.noreply.github.com>
This commit is contained in:
@@ -16,9 +16,22 @@ interface EssayViewProps {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
watermark?: LightboxWatermark;
|
||||
/**
|
||||
* Client proofing — favorite hearts, the selection bar and the send-off modal.
|
||||
* Off by default: proofing is a delivery workflow for album handovers, and a
|
||||
* published story is not one. Album views opt in.
|
||||
*/
|
||||
proofing?: boolean;
|
||||
}
|
||||
|
||||
function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayViewProps) {
|
||||
function EssayViewContent({
|
||||
essay,
|
||||
assets,
|
||||
title,
|
||||
subtitle,
|
||||
watermark,
|
||||
proofing: proofingEnabled = false,
|
||||
}: EssayViewProps) {
|
||||
const proofing = useProofing();
|
||||
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
|
||||
|
||||
@@ -54,11 +67,7 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
|
||||
case 'paragraph':
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="essay-prose"
|
||||
dangerouslySetInnerHTML={{ __html: block.html }}
|
||||
/>
|
||||
<div key={idx} className="essay-prose" dangerouslySetInnerHTML={{ __html: block.html }} />
|
||||
);
|
||||
|
||||
case 'quote':
|
||||
@@ -94,8 +103,8 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
block.layout === 'fullbleed'
|
||||
? '100vw'
|
||||
: block.layout === 'wide'
|
||||
? '(max-width: 1100px) 100vw, 1100px'
|
||||
: '(max-width: 768px) 100vw, 680px'
|
||||
? '(max-width: 1100px) 100vw, 1100px'
|
||||
: '(max-width: 768px) 100vw, 680px'
|
||||
}
|
||||
loading={idx < 4 ? 'eager' : 'lazy'}
|
||||
{...(item.blurDataURL
|
||||
@@ -129,7 +138,14 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.6))',
|
||||
}}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" width="24" height="24" fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2">
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
height="24"
|
||||
fill={isFav ? 'currentColor' : 'none'}
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
|
||||
</svg>
|
||||
</button>
|
||||
@@ -164,7 +180,9 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
onClick={() => setLightboxIndex(index)}
|
||||
style={{
|
||||
...(item.dominantColor ? { backgroundColor: item.dominantColor } : {}),
|
||||
...(item.aspectRatio ? { aspectRatio: `${item.aspectRatio}` } : {}),
|
||||
// Width proportional to the ratio — see .essay-pair-grid.
|
||||
flexGrow: item.aspectRatio ?? 1.5,
|
||||
aspectRatio: `${item.aspectRatio ?? 1.5}`,
|
||||
}}
|
||||
>
|
||||
<Image
|
||||
@@ -203,7 +221,14 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.6))',
|
||||
}}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" width="24" height="24" fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2">
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
height="24"
|
||||
fill={isFav ? 'currentColor' : 'none'}
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
|
||||
</svg>
|
||||
</button>
|
||||
@@ -294,7 +319,9 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
type="button"
|
||||
onClick={() => proofing.setIsFilterActive((prev) => !prev)}
|
||||
style={{
|
||||
background: proofing.isFilterActive ? 'var(--accent, #e60012)' : 'rgba(255,255,255,0.15)',
|
||||
background: proofing.isFilterActive
|
||||
? 'var(--accent, #e60012)'
|
||||
: 'rgba(255,255,255,0.15)',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
padding: '6px 14px',
|
||||
@@ -324,16 +351,23 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ProofingModal />
|
||||
{proofingEnabled && <ProofingModal />}
|
||||
|
||||
{lightboxIndex !== null && (
|
||||
<Lightbox
|
||||
assets={assets}
|
||||
currentIndex={lightboxIndex}
|
||||
onClose={() => setLightboxIndex(null)}
|
||||
onNext={() => setLightboxIndex((prev) => (prev !== null ? (prev + 1) % assets.length : null))}
|
||||
onPrev={() => setLightboxIndex((prev) => (prev !== null ? (prev - 1 + assets.length) % assets.length : null))}
|
||||
onNext={() =>
|
||||
setLightboxIndex((prev) => (prev !== null ? (prev + 1) % assets.length : null))
|
||||
}
|
||||
onPrev={() =>
|
||||
setLightboxIndex((prev) =>
|
||||
prev !== null ? (prev - 1 + assets.length) % assets.length : null,
|
||||
)
|
||||
}
|
||||
watermark={watermark}
|
||||
showExifToggle={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -343,6 +377,12 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
|
||||
export function EssayView(props: EssayViewProps) {
|
||||
const albumTokens = useMemo(() => props.assets.map((a) => a.id), [props.assets]);
|
||||
|
||||
// Without the provider useProofing() returns null, and every proofing control
|
||||
// (hearts in the grid and in the lightbox, selection bar) drops out on its own.
|
||||
if (!props.proofing) {
|
||||
return <EssayViewContent {...props} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ProofingProvider albumTokens={albumTokens}>
|
||||
<EssayViewContent {...props} />
|
||||
|
||||
@@ -116,32 +116,7 @@ function PhotoGridInner({ assets, layout = 'masonry', gridStyle, watermark }: Ph
|
||||
setLightboxIndex((prev) => (prev !== null ? (prev - 1 + displayedAssets.length) % displayedAssets.length : null));
|
||||
}, [displayedAssets.length]);
|
||||
|
||||
// Keyboard navigation
|
||||
useEffect(() => {
|
||||
if (lightboxIndex === null) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
closeLightbox();
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
goNext();
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
goPrev();
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = 'hidden';
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = '';
|
||||
};
|
||||
}, [lightboxIndex, closeLightbox, goNext, goPrev]);
|
||||
// Keyboard navigation and the scroll lock live in <Lightbox/>.
|
||||
|
||||
const gridItems = useMemo(() => {
|
||||
return displayedAssets.map((asset, index) => {
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
/* Photo Essay & Storytelling Mode Styles */
|
||||
|
||||
.essay-container {
|
||||
/*
|
||||
* One shared measure for every block, so headings, prose and figures line up
|
||||
* on the same left edge. Deliberately in rem, not the `68ch` this replaces:
|
||||
* `ch` is relative to each element's own font, so a serif heading resolved to
|
||||
* a wider column than the body text and started further left. 40rem matches
|
||||
* what 68ch produced for the body font. Custom properties are substituted as
|
||||
* raw tokens, so a `ch` value here would be re-resolved per element and bring
|
||||
* the bug straight back — keep this font-independent.
|
||||
*
|
||||
* `--essay-bleed` / `--essay-wide` are viewport-based by default and get
|
||||
* overridden where the essay renders inside a narrower box (e.g. the admin
|
||||
* Journal Studio preview pane).
|
||||
*/
|
||||
--essay-measure: 40rem;
|
||||
--essay-wide: 1100px;
|
||||
--essay-bleed: 100vw;
|
||||
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
@@ -9,7 +26,7 @@
|
||||
|
||||
/* Header & Cover */
|
||||
.essay-header {
|
||||
max-width: 68ch;
|
||||
max-width: var(--essay-measure);
|
||||
margin: 0 auto 3.5rem auto;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -41,7 +58,7 @@
|
||||
|
||||
/* Reading column */
|
||||
.essay-prose {
|
||||
max-width: 68ch;
|
||||
max-width: var(--essay-measure);
|
||||
margin: 0 auto 2.5rem auto;
|
||||
font-family: var(--font-body, sans-serif);
|
||||
font-size: clamp(1.05rem, 2vw, 1.2rem);
|
||||
@@ -55,19 +72,25 @@
|
||||
|
||||
.essay-heading {
|
||||
font-family: var(--font-heading, serif);
|
||||
max-width: 68ch;
|
||||
max-width: var(--essay-measure);
|
||||
margin: 3.5rem auto 1.5rem auto;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.essay-heading--1 { font-size: clamp(1.8rem, 3.5vw, 2.5rem); }
|
||||
.essay-heading--2 { font-size: clamp(1.5rem, 3vw, 2rem); }
|
||||
.essay-heading--3 { font-size: clamp(1.25rem, 2.5vw, 1.6rem); }
|
||||
.essay-heading--1 {
|
||||
font-size: clamp(1.8rem, 3.5vw, 2.5rem);
|
||||
}
|
||||
.essay-heading--2 {
|
||||
font-size: clamp(1.5rem, 3vw, 2rem);
|
||||
}
|
||||
.essay-heading--3 {
|
||||
font-size: clamp(1.25rem, 2.5vw, 1.6rem);
|
||||
}
|
||||
|
||||
/* Pullquote */
|
||||
.essay-quote {
|
||||
max-width: 68ch;
|
||||
max-width: var(--essay-measure);
|
||||
margin: 3.5rem auto;
|
||||
padding: 1.5rem 2rem;
|
||||
border-left: 3px solid var(--accent, #e60012);
|
||||
@@ -96,17 +119,23 @@
|
||||
}
|
||||
|
||||
.essay-figure--contained {
|
||||
max-width: 68ch;
|
||||
max-width: var(--essay-measure);
|
||||
}
|
||||
|
||||
.essay-figure--wide {
|
||||
max-width: 1100px;
|
||||
max-width: var(--essay-wide);
|
||||
}
|
||||
|
||||
/*
|
||||
* `width` has to be set too, not just max-width: .essay-figure is width: 100%,
|
||||
* which over-constrains the box so the negative right margin is dropped and only
|
||||
* the left side bleeds.
|
||||
*/
|
||||
.essay-figure--fullbleed {
|
||||
max-width: 100vw;
|
||||
margin-left: calc(-50vw + 50%);
|
||||
margin-right: calc(-50vw + 50%);
|
||||
width: var(--essay-bleed);
|
||||
max-width: var(--essay-bleed);
|
||||
margin-left: calc(-0.5 * var(--essay-bleed) + 50%);
|
||||
margin-right: calc(-0.5 * var(--essay-bleed) + 50%);
|
||||
}
|
||||
|
||||
.essay-image-wrapper {
|
||||
@@ -131,7 +160,7 @@
|
||||
}
|
||||
|
||||
.essay-figcaption {
|
||||
max-width: 68ch;
|
||||
max-width: var(--essay-measure);
|
||||
margin: 0.75rem auto 0 auto;
|
||||
text-align: center;
|
||||
font-family: var(--font-caption, monospace);
|
||||
@@ -140,18 +169,34 @@
|
||||
}
|
||||
|
||||
/* Side by side photo pair */
|
||||
/*
|
||||
* Justified row: each photo keeps its own aspect ratio, and its width is given
|
||||
* by `flex-grow: <aspect ratio>` (set inline from the asset). Since width ∝ ratio
|
||||
* and height = width / ratio, both photos end up exactly the same height without
|
||||
* a single pixel being cropped — a shared baseline instead of one portrait
|
||||
* towering over a landscape.
|
||||
*/
|
||||
.essay-pair-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
max-width: var(--essay-wide);
|
||||
margin: 3.5rem auto;
|
||||
}
|
||||
|
||||
.essay-pair-grid > .essay-image-wrapper {
|
||||
flex-basis: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
/* Stacked: full width each, height from the photo's own ratio. */
|
||||
.essay-pair-grid {
|
||||
grid-template-columns: 1fr;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.essay-pair-grid > .essay-image-wrapper {
|
||||
flex: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,8 @@ import { AdminDiagnosticBanner } from '@/components/AdminDiagnosticBanner';
|
||||
import { AlbumDetailView } from './AlbumDetailView';
|
||||
import { SubpageGridView } from './SubpageGridView';
|
||||
import { EssayView } from './EssayView';
|
||||
import { parseEssayMarkdown, loadEssayFromFile } from '@/lib/essay';
|
||||
import { parseEssayMarkdown } from '@/lib/essay';
|
||||
import { loadEssayFromFile } from '@/lib/admin/journal-service';
|
||||
|
||||
// Render at request time — requires live Immich connection
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
58
app/admin/AdminShell.tsx
Normal file
58
app/admin/AdminShell.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, type ReactNode } from 'react';
|
||||
import AdminLogin from './components/AdminLogin';
|
||||
import AdminDashboard from './components/AdminDashboard';
|
||||
import './admin.css';
|
||||
|
||||
/**
|
||||
* Auth gate and panel chrome for every /admin route. Lives in the admin layout
|
||||
* rather than in each page, so navigating between tabs keeps the session check
|
||||
* and the header mounted instead of re-running them per route.
|
||||
*/
|
||||
export default function AdminShell({ children }: { children: ReactNode }) {
|
||||
const [authenticated, setAuthenticated] = useState<boolean | null>(null);
|
||||
const [enabled, setEnabled] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const res = await fetch('/api/admin/auth');
|
||||
const data = await res.json();
|
||||
setAuthenticated(data.authenticated);
|
||||
setEnabled(data.enabled);
|
||||
} catch {
|
||||
setAuthenticated(false);
|
||||
}
|
||||
}
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
if (authenticated === null) {
|
||||
return (
|
||||
<div className="admin-loading">
|
||||
<div className="admin-spinner" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
return (
|
||||
<div className="admin-disabled">
|
||||
<div className="admin-disabled-card">
|
||||
<h1>Admin Panel</h1>
|
||||
<p>
|
||||
The admin panel is not enabled. Set <code>ADMIN_PASSWORD</code> in your environment
|
||||
variables to activate it.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return <AdminLogin onSuccess={() => setAuthenticated(true)} />;
|
||||
}
|
||||
|
||||
return <AdminDashboard onLogout={() => setAuthenticated(false)}>{children}</AdminDashboard>;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
5
app/admin/analytics/page.tsx
Normal file
5
app/admin/analytics/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import AnalyticsView from '../components/AnalyticsView';
|
||||
|
||||
export default function AdminAnalyticsPage() {
|
||||
return <AnalyticsView />;
|
||||
}
|
||||
@@ -1,20 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import PageBuilder from './PageBuilder';
|
||||
import SettingsEditor from './SettingsEditor';
|
||||
import AnalyticsView from './AnalyticsView';
|
||||
import { useState, useEffect, type ReactNode } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import BackupManagerModal from './BackupManagerModal';
|
||||
import * as Icons from './Icons';
|
||||
|
||||
interface Props {
|
||||
onLogout: () => void;
|
||||
/** The active route's panel — Pages, Journal Studio, Settings or Analytics. */
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
type Tab = 'pages' | 'settings' | 'analytics';
|
||||
const TABS = [
|
||||
{ label: 'Pages', href: '/admin/pages', match: /^\/admin(\/pages)?$/ },
|
||||
{ label: 'Journal', href: '/admin/journal', match: /^\/admin\/journal/ },
|
||||
{ label: 'Settings', href: '/admin/settings', match: /^\/admin\/settings/ },
|
||||
{ label: 'Analytics', href: '/admin/analytics', match: /^\/admin\/analytics/ },
|
||||
];
|
||||
|
||||
export default function AdminDashboard({ onLogout }: Props) {
|
||||
const [activeTab, setActiveTab] = useState<Tab>('pages');
|
||||
export default function AdminDashboard({ onLogout, children }: Props) {
|
||||
const pathname = usePathname();
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Diagnostics & Backup state
|
||||
@@ -91,24 +97,15 @@ export default function AdminDashboard({ onLogout }: Props) {
|
||||
<div className="admin-header-left">
|
||||
<h1>Immich Folio</h1>
|
||||
<nav className="admin-tabs">
|
||||
<button
|
||||
className={`admin-tab ${activeTab === 'pages' ? 'active' : ''}`}
|
||||
onClick={() => setActiveTab('pages')}
|
||||
>
|
||||
Pages
|
||||
</button>
|
||||
<button
|
||||
className={`admin-tab ${activeTab === 'settings' ? 'active' : ''}`}
|
||||
onClick={() => setActiveTab('settings')}
|
||||
>
|
||||
Settings
|
||||
</button>
|
||||
<button
|
||||
className={`admin-tab ${activeTab === 'analytics' ? 'active' : ''}`}
|
||||
onClick={() => setActiveTab('analytics')}
|
||||
>
|
||||
Analytics
|
||||
</button>
|
||||
{TABS.map((t) => (
|
||||
<Link
|
||||
key={t.href}
|
||||
href={t.href}
|
||||
className={`admin-tab ${t.match.test(pathname) ? 'active' : ''}`}
|
||||
>
|
||||
{t.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
<div className="admin-header-right">
|
||||
@@ -195,12 +192,14 @@ export default function AdminDashboard({ onLogout }: Props) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<span className="admin-header-divider" aria-hidden="true" />
|
||||
|
||||
<a
|
||||
href="/"
|
||||
href="/?fresh=1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="admin-btn admin-btn-ghost"
|
||||
title="Open site in new tab"
|
||||
title="Open site in new tab (bypassing cache)"
|
||||
>
|
||||
<Icons.IconLink size={14} /> Site
|
||||
</a>
|
||||
@@ -225,11 +224,7 @@ export default function AdminDashboard({ onLogout }: Props) {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="admin-main">
|
||||
{activeTab === 'pages' && <PageBuilder />}
|
||||
{activeTab === 'settings' && <SettingsEditor />}
|
||||
{activeTab === 'analytics' && <AnalyticsView />}
|
||||
</main>
|
||||
<main className="admin-main">{children}</main>
|
||||
|
||||
<BackupManagerModal
|
||||
isOpen={showBackupModal}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useScrollLock } from './useScrollLock';
|
||||
import { IconFolder } from './Icons';
|
||||
|
||||
interface ImmichAlbumInfo {
|
||||
id: string;
|
||||
@@ -19,6 +21,7 @@ interface Props {
|
||||
}
|
||||
|
||||
export default function AlbumPicker({ albums, onSelect, onClose, usedAlbumIds }: Props) {
|
||||
useScrollLock(true);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
@@ -75,7 +78,9 @@ export default function AlbumPicker({ albums, onSelect, onClose, usedAlbumIds }:
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="picker-thumb-placeholder">📁</div>
|
||||
<div className="picker-thumb-placeholder">
|
||||
<IconFolder size={20} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="picker-item-info">
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
rectSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { useScrollLock } from './useScrollLock';
|
||||
|
||||
interface AssetInfo {
|
||||
id: string;
|
||||
@@ -92,6 +93,7 @@ export default function AssetOrderEditor({
|
||||
onSave,
|
||||
onClose,
|
||||
}: Props) {
|
||||
useScrollLock(true);
|
||||
const [assets, setAssets] = useState<AssetInfo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { IconFolder, IconImage, IconStar } from './Icons';
|
||||
import { IconCheck, IconFolder, IconImage, IconStar } from './Icons';
|
||||
import { useScrollLock } from './useScrollLock';
|
||||
|
||||
interface AssetInfo {
|
||||
id: string;
|
||||
@@ -27,6 +28,7 @@ export default function AssetPicker({
|
||||
albumId,
|
||||
title,
|
||||
}: Props) {
|
||||
useScrollLock(true);
|
||||
const [tab, setTab] = useState<Tab>(albumId ? 'album' : 'favorites');
|
||||
const [assets, setAssets] = useState<AssetInfo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -175,7 +177,11 @@ export default function AssetPicker({
|
||||
alt={asset.originalFileName}
|
||||
loading="lazy"
|
||||
/>
|
||||
{isUsed && <div className="asset-picker-used-badge">✓</div>}
|
||||
{isUsed && (
|
||||
<div className="asset-picker-used-badge">
|
||||
<IconCheck size={11} />
|
||||
</div>
|
||||
)}
|
||||
{asset.isFavorite && !isUsed && (
|
||||
<div className="asset-picker-fav-badge" title="Favorite in Immich">
|
||||
<IconStar size={14} />
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import type { BackupItem } from '@/app/api/admin/backups/route';
|
||||
import * as Icons from './Icons';
|
||||
import { useScrollLock } from './useScrollLock';
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean;
|
||||
@@ -49,6 +50,8 @@ export default function BackupManagerModal({ isOpen, onClose, onRestoreSuccess }
|
||||
}
|
||||
}, [isOpen, fetchBackups]);
|
||||
|
||||
useScrollLock(isOpen);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
async function handleRestore(filename: string) {
|
||||
@@ -96,7 +99,7 @@ export default function BackupManagerModal({ isOpen, onClose, onRestoreSuccess }
|
||||
</p>
|
||||
</div>
|
||||
<button className="backup-modal-close-btn" onClick={onClose} aria-label="Close">
|
||||
✕
|
||||
<Icons.IconX size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
42
app/admin/components/BlockBadge.tsx
Normal file
42
app/admin/components/BlockBadge.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
'use client';
|
||||
|
||||
import type { JournalBlock } from '@/lib/journal';
|
||||
import { IconFileText, IconSparkles, IconQuote, IconCamera, IconArrowLeftRight } from './Icons';
|
||||
|
||||
type BlockType = JournalBlock['type'];
|
||||
|
||||
/**
|
||||
* Block type chips for the Journal Studio and the Pages essay builder.
|
||||
*
|
||||
* Deliberately monochrome: the panel's colour language is neutral surfaces plus
|
||||
* a single accent, and these chips label a block rather than reporting a state,
|
||||
* so they carry no colour of their own. The block type is told apart by its
|
||||
* icon — the same icon the "Add Block" toolbar uses for it.
|
||||
*/
|
||||
const BLOCK_META: Record<BlockType, { label: string; Icon: typeof IconFileText }> = {
|
||||
paragraph: { label: 'Text', Icon: IconFileText },
|
||||
heading: { label: 'Heading', Icon: IconSparkles },
|
||||
quote: { label: 'Quote', Icon: IconQuote },
|
||||
photo: { label: 'Photo', Icon: IconCamera },
|
||||
'photo-pair': { label: 'Photo Pair', Icon: IconArrowLeftRight },
|
||||
};
|
||||
|
||||
interface BlockBadgeProps {
|
||||
type: BlockType;
|
||||
/** Optional position prefix, e.g. "3" renders as "3 · Quote". */
|
||||
index?: number;
|
||||
}
|
||||
|
||||
export function BlockBadge({ type, index }: BlockBadgeProps) {
|
||||
const meta = BLOCK_META[type];
|
||||
if (!meta) return <span className="essay-block-badge">{type}</span>;
|
||||
|
||||
const { label, Icon } = meta;
|
||||
return (
|
||||
<span className="essay-block-badge">
|
||||
<Icon size={11} />
|
||||
{index != null && <span className="essay-block-badge-index">{index}</span>}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
IconSparkles,
|
||||
IconArrowLeftRight,
|
||||
} from './Icons';
|
||||
import { BlockBadge } from './BlockBadge';
|
||||
|
||||
interface EssayBlockEditorProps {
|
||||
markdown: string;
|
||||
@@ -119,7 +120,7 @@ export function EssayBlockEditor({ markdown, onChange, onSelectPhoto }: EssayBlo
|
||||
<div className="essay-block-editor">
|
||||
{/* Sticky Dark Glass Toolbar */}
|
||||
<div className="essay-toolbar-sticky">
|
||||
<span className="essay-toolbar-label">✨ Add Story Block:</span>
|
||||
<span className="essay-toolbar-label">Add Story Block:</span>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn admin-btn-xs"
|
||||
@@ -171,19 +172,7 @@ export function EssayBlockEditor({ markdown, onChange, onSelectPhoto }: EssayBlo
|
||||
<div className="essay-block-card-header">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<IconGripVertical size={14} style={{ color: 'var(--admin-text-muted)', cursor: 'grab' }} />
|
||||
<span
|
||||
className={`essay-block-badge ${
|
||||
block.type === 'photo' || block.type === 'photo-pair'
|
||||
? 'badge-photo'
|
||||
: block.type === 'heading'
|
||||
? 'badge-heading'
|
||||
: block.type === 'quote'
|
||||
? 'badge-quote'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
Block {idx + 1}: {block.type}
|
||||
</span>
|
||||
<BlockBadge type={block.type} index={idx + 1} />
|
||||
</div>
|
||||
|
||||
<div className="essay-block-actions">
|
||||
|
||||
@@ -360,3 +360,123 @@ export function IconArrowLeftRight({ size = 16, className = 'svg-icon', strokeWi
|
||||
);
|
||||
}
|
||||
|
||||
export function IconCalendar({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
|
||||
<rect width="18" height="18" x="3" y="4" rx="2" />
|
||||
<path d="M8 2v4M16 2v4M3 10h18" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function IconArrowDown({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
|
||||
<path d="M12 5v14M19 12l-7 7-7-7" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function IconArrowUp({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
|
||||
<path d="M12 19V5M5 12l7-7 7 7" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** An "A→Z" marker for alphabetical / filename ordering. */
|
||||
export function IconSortAlpha({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
|
||||
<path d="M4 10 7 3l3 7M4.9 8.2h4.2" />
|
||||
<path d="M14 3h6l-6 7h6" />
|
||||
<path d="M17 14v7M14 18l3 3 3-3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function IconCheck({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
|
||||
<path d="M20 6 9 17l-5-5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Open book — journal entries and photo essays. */
|
||||
export function IconBook({
|
||||
size = 16,
|
||||
className = 'svg-icon',
|
||||
strokeWidth = 2,
|
||||
...props
|
||||
}: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
{...props}
|
||||
>
|
||||
<path d="M12 7v14" />
|
||||
<path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function IconEye({
|
||||
size = 16,
|
||||
className = 'svg-icon',
|
||||
strokeWidth = 2,
|
||||
...props
|
||||
}: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
{...props}
|
||||
>
|
||||
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Clock — reading time. */
|
||||
export function IconClock({
|
||||
size = 16,
|
||||
className = 'svg-icon',
|
||||
strokeWidth = 2,
|
||||
...props
|
||||
}: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
{...props}
|
||||
>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 7v5l3 2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
1270
app/admin/components/JournalStudio.tsx
Normal file
1270
app/admin/components/JournalStudio.tsx
Normal file
File diff suppressed because it is too large
Load Diff
345
app/admin/components/Listbox.tsx
Normal file
345
app/admin/components/Listbox.tsx
Normal file
@@ -0,0 +1,345 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { IconCheck, IconChevronDown } from './Icons';
|
||||
|
||||
/**
|
||||
* A single choice in a {@link Listbox}.
|
||||
*
|
||||
* `label` stays plain text so the same option table can feed a `title`
|
||||
* attribute or an aria-label; `icon` is the themed glyph shown beside it.
|
||||
*/
|
||||
export interface ListboxOption<T extends string> {
|
||||
value: T;
|
||||
label: string;
|
||||
icon?: React.ReactNode;
|
||||
}
|
||||
|
||||
export interface ListboxProps<T extends string> {
|
||||
value: T;
|
||||
options: readonly ListboxOption<T>[];
|
||||
onChange: (value: T) => void;
|
||||
/** Accessible name. Prefer `labelledBy` when a visible <label> exists. */
|
||||
ariaLabel?: string;
|
||||
/** id of the visible label element. */
|
||||
labelledBy?: string;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
/** Width of the trigger; the popup always matches it. */
|
||||
style?: React.CSSProperties;
|
||||
}
|
||||
|
||||
/** How long a type-ahead buffer keeps collecting characters. */
|
||||
const TYPEAHEAD_RESET_MS = 600;
|
||||
|
||||
/** Gap between the trigger and the popup. */
|
||||
const POPUP_GAP = 4;
|
||||
/** Space kept clear of the viewport edge. */
|
||||
const VIEWPORT_MARGIN = 8;
|
||||
/** Tallest the popup ever gets; beyond this it scrolls internally. */
|
||||
const POPUP_MAX_HEIGHT = 260;
|
||||
/** Below this the flipped side is not worth using. */
|
||||
const POPUP_MIN_HEIGHT = 96;
|
||||
|
||||
/** Viewport coordinates for the popup, measured from the trigger. */
|
||||
interface Placement {
|
||||
left: number;
|
||||
width: number;
|
||||
/** Set when the popup hangs below the trigger. */
|
||||
top?: number;
|
||||
/** Set when the popup is flipped above it. */
|
||||
bottom?: number;
|
||||
maxHeight: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A select replacement that can show markup in its options.
|
||||
*
|
||||
* The native `<option>` element strips markup, so the admin panel's
|
||||
* `currentColor` SVG set cannot be used inside a real `<select>`. This
|
||||
* implements the ARIA combobox/listbox pattern instead: DOM focus never leaves
|
||||
* the trigger button, and the active option is announced through
|
||||
* `aria-activedescendant`. Options are plain `<li>`s — not focusable — which
|
||||
* keeps focus management to a single element.
|
||||
*
|
||||
* The popup is portalled to `document.body` and positioned from the trigger's
|
||||
* viewport rect. An absolutely positioned popup is clipped by any ancestor with
|
||||
* a non-visible overflow — and z-index cannot rescue it, because clipping
|
||||
* happens before stacking — so inside a scrolling modal the list would be cut
|
||||
* off. Escaping to the body also lets it flip above the trigger when there is
|
||||
* more room there.
|
||||
*/
|
||||
export function Listbox<T extends string>({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
ariaLabel,
|
||||
labelledBy,
|
||||
disabled = false,
|
||||
className = '',
|
||||
style,
|
||||
}: ListboxProps<T>) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const selectedIndex = Math.max(
|
||||
0,
|
||||
options.findIndex((o) => o.value === value),
|
||||
);
|
||||
const [activeIndex, setActiveIndex] = React.useState(selectedIndex);
|
||||
const [placement, setPlacement] = React.useState<Placement | null>(null);
|
||||
|
||||
const wrapperRef = React.useRef<HTMLDivElement>(null);
|
||||
const buttonRef = React.useRef<HTMLButtonElement>(null);
|
||||
const listRef = React.useRef<HTMLUListElement>(null);
|
||||
const typeahead = React.useRef({ buffer: '', at: 0 });
|
||||
|
||||
const baseId = React.useId();
|
||||
const listId = `${baseId}-list`;
|
||||
const optionId = (index: number) => `${baseId}-opt-${index}`;
|
||||
|
||||
const selected = options[selectedIndex];
|
||||
|
||||
const openList = React.useCallback(
|
||||
(index = selectedIndex) => {
|
||||
if (disabled) return;
|
||||
setActiveIndex(index);
|
||||
setOpen(true);
|
||||
},
|
||||
[disabled, selectedIndex],
|
||||
);
|
||||
|
||||
const close = React.useCallback(() => {
|
||||
setOpen(false);
|
||||
setPlacement(null);
|
||||
typeahead.current = { buffer: '', at: 0 };
|
||||
}, []);
|
||||
|
||||
const commit = React.useCallback(
|
||||
(index: number) => {
|
||||
const option = options[index];
|
||||
if (option) onChange(option.value);
|
||||
close();
|
||||
// Focus never left the trigger, but a pointer selection can blur it.
|
||||
buttonRef.current?.focus();
|
||||
},
|
||||
[close, onChange, options],
|
||||
);
|
||||
|
||||
// Dismiss on outside pointer press. pointerdown (not click) so a press that
|
||||
// starts outside closes the popup before it can retarget the click. The popup
|
||||
// is portalled, so it is not inside the wrapper — without the second test a
|
||||
// press on an option would count as "outside" and close before it commits.
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
const target = event.target as Node;
|
||||
if (!wrapperRef.current?.contains(target) && !listRef.current?.contains(target)) close();
|
||||
};
|
||||
document.addEventListener('pointerdown', onPointerDown);
|
||||
return () => document.removeEventListener('pointerdown', onPointerDown);
|
||||
}, [open, close]);
|
||||
|
||||
// Measure once the popup is in the DOM but before paint, so it never shows at
|
||||
// a stale position. Until then it renders hidden purely to be measurable.
|
||||
React.useLayoutEffect(() => {
|
||||
if (!open) return;
|
||||
const trigger = buttonRef.current;
|
||||
const list = listRef.current;
|
||||
if (!trigger || !list) return;
|
||||
|
||||
const rect = trigger.getBoundingClientRect();
|
||||
// scrollHeight ignores our own max-height, so this is the natural height.
|
||||
const wanted = Math.min(POPUP_MAX_HEIGHT, list.scrollHeight + 2);
|
||||
const below = window.innerHeight - rect.bottom - POPUP_GAP - VIEWPORT_MARGIN;
|
||||
const above = rect.top - POPUP_GAP - VIEWPORT_MARGIN;
|
||||
const flip = wanted > below && above > below;
|
||||
const room = flip ? above : below;
|
||||
|
||||
setPlacement({
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
top: flip ? undefined : rect.bottom + POPUP_GAP,
|
||||
bottom: flip ? window.innerHeight - rect.top + POPUP_GAP : undefined,
|
||||
maxHeight: Math.max(POPUP_MIN_HEIGHT, Math.min(POPUP_MAX_HEIGHT, room)),
|
||||
});
|
||||
}, [open]);
|
||||
|
||||
// The popup is anchored in viewport coordinates, so anything that moves the
|
||||
// trigger invalidates it. Dismiss rather than re-measure — that is what a
|
||||
// native select does, and the measurement above only runs on open. Capture
|
||||
// phase, because the scroll usually happens on an ancestor container.
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
window.addEventListener('scroll', close, true);
|
||||
window.addEventListener('resize', close);
|
||||
return () => {
|
||||
window.removeEventListener('scroll', close, true);
|
||||
window.removeEventListener('resize', close);
|
||||
};
|
||||
}, [open, close]);
|
||||
|
||||
// Keep the active option visible while arrowing or typing through a long list.
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
listRef.current
|
||||
?.querySelector(`#${CSS.escape(optionId(activeIndex))}`)
|
||||
?.scrollIntoView({ block: 'nearest' });
|
||||
// optionId is derived from baseId, which is stable for the component's life.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, activeIndex, baseId]);
|
||||
|
||||
/** Jump to the next option whose label starts with the accumulated buffer. */
|
||||
const runTypeahead = (char: string) => {
|
||||
const now = Date.now();
|
||||
const buffer =
|
||||
now - typeahead.current.at > TYPEAHEAD_RESET_MS ? char : typeahead.current.buffer + char;
|
||||
typeahead.current = { buffer, at: now };
|
||||
|
||||
// A repeated single character cycles through matches instead of sticking.
|
||||
const repeat = buffer.length > 1 && buffer.split('').every((c) => c === buffer[0]);
|
||||
const needle = repeat ? buffer[0] : buffer;
|
||||
const from = repeat || buffer.length === 1 ? activeIndex + 1 : activeIndex;
|
||||
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
const index = (from + i) % options.length;
|
||||
if (options[index].label.toLowerCase().startsWith(needle.toLowerCase())) {
|
||||
setActiveIndex(index);
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const onKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => {
|
||||
if (disabled) return;
|
||||
const last = options.length - 1;
|
||||
|
||||
switch (event.key) {
|
||||
case 'ArrowDown':
|
||||
case 'ArrowUp': {
|
||||
event.preventDefault();
|
||||
const step = event.key === 'ArrowDown' ? 1 : -1;
|
||||
if (!open) {
|
||||
openList(Math.min(last, Math.max(0, selectedIndex + step)));
|
||||
} else {
|
||||
setActiveIndex((i) => Math.min(last, Math.max(0, i + step)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'Home':
|
||||
case 'End': {
|
||||
event.preventDefault();
|
||||
const index = event.key === 'Home' ? 0 : last;
|
||||
if (open) setActiveIndex(index);
|
||||
else openList(index);
|
||||
return;
|
||||
}
|
||||
case 'Enter':
|
||||
case ' ':
|
||||
event.preventDefault();
|
||||
if (open) commit(activeIndex);
|
||||
else openList();
|
||||
return;
|
||||
case 'Escape':
|
||||
if (open) {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}
|
||||
return;
|
||||
case 'Tab':
|
||||
// Let focus move on, but commit what the user was looking at.
|
||||
if (open) commit(activeIndex);
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Type-ahead: a single printable character, no modifiers.
|
||||
if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
|
||||
event.preventDefault();
|
||||
if (!open) {
|
||||
setOpen(true);
|
||||
const match = runTypeahead(event.key);
|
||||
if (match === null) setActiveIndex(selectedIndex);
|
||||
return;
|
||||
}
|
||||
runTypeahead(event.key);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className={`admin-listbox ${className}`.trim()} style={style}>
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
role="combobox"
|
||||
aria-controls={listId}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
aria-activedescendant={open ? optionId(activeIndex) : undefined}
|
||||
aria-label={ariaLabel}
|
||||
aria-labelledby={labelledBy}
|
||||
disabled={disabled}
|
||||
className="admin-listbox-trigger"
|
||||
onClick={() => (open ? close() : openList())}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
<span className="admin-listbox-value">
|
||||
{selected?.icon}
|
||||
<span>{selected?.label ?? ''}</span>
|
||||
</span>
|
||||
<IconChevronDown size={14} className="svg-icon admin-listbox-caret" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
{open &&
|
||||
createPortal(
|
||||
<ul
|
||||
ref={listRef}
|
||||
id={listId}
|
||||
role="listbox"
|
||||
className="admin-listbox-popup"
|
||||
tabIndex={-1}
|
||||
style={
|
||||
placement
|
||||
? {
|
||||
left: placement.left,
|
||||
width: placement.width,
|
||||
top: placement.top,
|
||||
bottom: placement.bottom,
|
||||
maxHeight: placement.maxHeight,
|
||||
}
|
||||
: // First pass: laid out but invisible, only so it can be measured.
|
||||
{ left: 0, top: 0, visibility: 'hidden' }
|
||||
}
|
||||
>
|
||||
{options.map((option, index) => (
|
||||
<li
|
||||
key={option.value}
|
||||
id={optionId(index)}
|
||||
role="option"
|
||||
aria-selected={option.value === value}
|
||||
className={`admin-listbox-option${index === activeIndex ? ' is-active' : ''}${
|
||||
option.value === value ? ' is-selected' : ''
|
||||
}`}
|
||||
// pointerdown would fire before the outside-press handler can run;
|
||||
// click is enough because that handler treats the popup as inside.
|
||||
onClick={() => commit(index)}
|
||||
onMouseEnter={() => setActiveIndex(index)}
|
||||
>
|
||||
{option.icon}
|
||||
<span className="admin-listbox-option-label">{option.label}</span>
|
||||
{option.value === value && (
|
||||
<IconCheck
|
||||
size={14}
|
||||
className="svg-icon admin-listbox-check"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useEffect, useCallback, type ReactNode } from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
@@ -23,6 +23,8 @@ import AlbumPicker from './AlbumPicker';
|
||||
import AssetPicker from './AssetPicker';
|
||||
import AssetOrderEditor from './AssetOrderEditor';
|
||||
import { EssayBlockEditor } from './EssayBlockEditor';
|
||||
import SaveBar from './SaveBar';
|
||||
import { useScrollLock } from './useScrollLock';
|
||||
import {
|
||||
ALBUM_SORT_MODES,
|
||||
DEFAULT_ALBUM_SORT,
|
||||
@@ -31,6 +33,10 @@ import {
|
||||
} from '@/lib/albumSort';
|
||||
import type { AlbumEntryObject } from '@/lib/config/schema';
|
||||
import {
|
||||
IconArrowDown,
|
||||
IconArrowUp,
|
||||
IconBook,
|
||||
IconCalendar,
|
||||
IconCamera,
|
||||
IconCopy,
|
||||
IconFolder,
|
||||
@@ -41,16 +47,17 @@ import {
|
||||
IconPencil,
|
||||
IconPlus,
|
||||
IconSearch,
|
||||
IconSortAlpha,
|
||||
IconTrash,
|
||||
IconX,
|
||||
} from './Icons';
|
||||
import { Listbox, type ListboxOption } from './Listbox';
|
||||
|
||||
/**
|
||||
* Labels for the per-album sort select. Order matches ALBUM_SORT_MODES.
|
||||
* Labels for the per-album sort control.
|
||||
*
|
||||
* Plain text, no emoji: an <option> cannot contain markup, so the SVG set from
|
||||
* `./Icons` is not available here — and a decorative emoji is not a substitute
|
||||
* for it. The badge on the album card uses a real icon instead.
|
||||
* Kept as plain text on their own because they also feed the `title` attribute
|
||||
* on the album card's sort badge, where markup is not an option.
|
||||
*/
|
||||
const SORT_LABELS: Record<AlbumSortMode, string> = {
|
||||
immich: 'Immich order (default)',
|
||||
@@ -60,6 +67,21 @@ const SORT_LABELS: Record<AlbumSortMode, string> = {
|
||||
manual: 'Manual',
|
||||
};
|
||||
|
||||
/** Manual reuses the drag glyph so the control matches the card's badge. */
|
||||
const SORT_ICONS: Record<AlbumSortMode, ReactNode> = {
|
||||
immich: <IconCalendar />,
|
||||
newest: <IconArrowDown />,
|
||||
oldest: <IconArrowUp />,
|
||||
filename: <IconSortAlpha />,
|
||||
manual: <IconGripVertical />,
|
||||
};
|
||||
|
||||
const SORT_OPTIONS: readonly ListboxOption<AlbumSortMode>[] = ALBUM_SORT_MODES.map((mode) => ({
|
||||
value: mode,
|
||||
label: SORT_LABELS[mode],
|
||||
icon: SORT_ICONS[mode],
|
||||
}));
|
||||
|
||||
// ── Types ──────────────────────────────────────────────────────
|
||||
interface AlbumEntry {
|
||||
id: string;
|
||||
@@ -366,6 +388,11 @@ export default function PageBuilder() {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [editingAlbumAddress, setEditingAlbumAddress] = useState<ActiveEditAlbumAddress | null>(null);
|
||||
|
||||
// Keep the builder still behind either drawer. One combined lock rather than
|
||||
// one per drawer: the album drawer opens from inside the subpage drawer, and
|
||||
// a single condition avoids two locks racing over the same inline style.
|
||||
useScrollLock(editingAlbumAddress !== null || expandedSubpage !== null);
|
||||
|
||||
// DnD sensors
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||
@@ -860,38 +887,14 @@ export default function PageBuilder() {
|
||||
|
||||
return (
|
||||
<div className="page-builder">
|
||||
{/* Save Bar */}
|
||||
<div className={`save-bar ${dirty ? 'dirty' : ''}`}>
|
||||
<div className="save-bar-left">
|
||||
{dirty && <span className="unsaved-badge">Unsaved changes</span>}
|
||||
{saveMessage && (
|
||||
<span
|
||||
className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`}
|
||||
>
|
||||
{saveMessage}
|
||||
</span>
|
||||
)}
|
||||
{!dirty && !saveMessage && <span className="save-hint">⌘S to save</span>}
|
||||
</div>
|
||||
<div className="save-bar-right">
|
||||
<a
|
||||
href="/?fresh=1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="admin-btn admin-btn-ghost admin-btn-preview"
|
||||
title="Open site in new tab (bypassing cache)"
|
||||
>
|
||||
↗ Preview Site
|
||||
</a>
|
||||
<button
|
||||
className="admin-btn admin-btn-primary"
|
||||
onClick={handleSave}
|
||||
disabled={!dirty || saving}
|
||||
>
|
||||
{saving ? 'Saving...' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<SaveBar
|
||||
dirty={dirty}
|
||||
saving={saving}
|
||||
saveMessage={saveMessage}
|
||||
onSave={handleSave}
|
||||
label="Save Changes"
|
||||
showPreview
|
||||
/>
|
||||
|
||||
{/* Search Bar */}
|
||||
<div className="builder-search-container">
|
||||
@@ -1106,7 +1109,7 @@ export default function PageBuilder() {
|
||||
onClick={() => setExpandedSubpage(null)}
|
||||
title="Close drawer"
|
||||
>
|
||||
✕
|
||||
<IconX size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1237,7 +1240,13 @@ export default function PageBuilder() {
|
||||
>
|
||||
<div className="toggle-card-info" style={{ textAlign: 'left' }}>
|
||||
<span className="toggle-card-title" style={{ fontWeight: 600 }}>
|
||||
{sp.enabled !== false ? '🟢 Page Active (Published)' : '🔴 Page Disabled (Hidden)'}
|
||||
<span
|
||||
className={`page-status-dot ${sp.enabled !== false ? 'is-on' : 'is-off'}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{sp.enabled !== false
|
||||
? 'Page Active (Published)'
|
||||
: 'Page Disabled (Hidden)'}
|
||||
</span>
|
||||
<span className="toggle-card-desc" style={{ fontSize: '0.8rem', display: 'block', opacity: 0.75 }}>
|
||||
{sp.enabled !== false
|
||||
@@ -1279,23 +1288,20 @@ export default function PageBuilder() {
|
||||
|
||||
{/* Visual Photo Essay Builder (if layout === 'essay') */}
|
||||
{(sp.grid?.layout === 'essay' || sp.essayText != null) && (
|
||||
<div className="subpage-drawer-section" style={{ background: 'var(--admin-surface, rgba(255,255,255,0.02))', padding: '1rem', borderRadius: '8px', border: '1px solid var(--admin-border, rgba(255,255,255,0.1))' }}>
|
||||
<div style={{ marginBottom: '1rem' }}>
|
||||
<h4 style={{ margin: 0, fontSize: '1rem', display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<span>📖 Storytelling & Photo Essay Builder</span>
|
||||
<div className="subpage-drawer-section">
|
||||
<div className="drawer-section-heading">
|
||||
<h4>
|
||||
<IconBook size={16} /> Storytelling & Photo Essay Builder
|
||||
</h4>
|
||||
<p style={{ margin: '4px 0 0 0', fontSize: '0.8rem', opacity: 0.75 }}>
|
||||
Compose text, quotes, and fullbleed/wide photos visually.
|
||||
</p>
|
||||
<p>Compose text, quotes, and fullbleed/wide photos visually.</p>
|
||||
</div>
|
||||
|
||||
<EssayBlockEditor
|
||||
markdown={sp.essayText || ''}
|
||||
onChange={(newMarkdown) => updateSubpage(spIndex, { essayText: newMarkdown })}
|
||||
onSelectPhoto={(callback) => {
|
||||
const firstAlbumId = sp.albums[0]?.id;
|
||||
setHeroPickerTarget({
|
||||
albumId: firstAlbumId,
|
||||
albumId: undefined,
|
||||
title: 'Select Photo for Photo Essay',
|
||||
onSelect: (assetId) => {
|
||||
callback(assetId);
|
||||
@@ -1493,182 +1499,133 @@ export default function PageBuilder() {
|
||||
<IconX size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{/* One scrolling column: cover banner, then the form. Anything the
|
||||
form already shows (password state, custom hero) is not
|
||||
repeated as a read-only stat. */}
|
||||
<div className="album-drawer-body">
|
||||
{/* Left Column - Visual Info & Stats */}
|
||||
<div className="modal-left-column">
|
||||
<div className="modal-cover-container">
|
||||
{heroThumb ? (
|
||||
<img src={`/api/admin/thumbnail/${heroThumb}`} alt="" loading="lazy" />
|
||||
) : (
|
||||
<div className="modal-cover-placeholder">
|
||||
<IconCamera />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="modal-meta-box">
|
||||
<span className="modal-album-title">{album.title || name}</span>
|
||||
<span className="modal-album-subtitle">Original: {name}</span>
|
||||
</div>
|
||||
<div className="modal-info-list">
|
||||
<div className="modal-info-item">
|
||||
<span className="modal-info-label">Photo Count:</span>
|
||||
<span className="modal-info-value">{count} photos</span>
|
||||
<div className="modal-cover-container">
|
||||
{heroThumb ? (
|
||||
<img src={`/api/admin/thumbnail/${heroThumb}`} alt="" loading="lazy" />
|
||||
) : (
|
||||
<div className="modal-cover-placeholder">
|
||||
<IconCamera />
|
||||
</div>
|
||||
<div className="modal-info-item">
|
||||
<span className="modal-info-label">Status:</span>
|
||||
<span className="modal-info-value">
|
||||
{album.password ? 'Password Protected' : 'Public Access'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="modal-info-item">
|
||||
<span className="modal-info-label">Custom Hero:</span>
|
||||
<span className="modal-info-value">
|
||||
{album.heroImage ? 'Yes' : 'No'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="modal-meta-box">
|
||||
<span className="modal-album-title">{album.title || name}</span>
|
||||
<span className="modal-album-subtitle">
|
||||
{count} {count === 1 ? 'photo' : 'photos'}
|
||||
{album.title ? ` · Original: ${name}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Technical UUID */}
|
||||
<div className="drawer-uuid-section">
|
||||
<label className="admin-field-label">IMMICH ALBUM UUID</label>
|
||||
<div className="uuid-copy-box">
|
||||
<code>{album.id}</code>
|
||||
<button
|
||||
className="uuid-copy-btn"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(album.id);
|
||||
}}
|
||||
title="Copy UUID"
|
||||
>
|
||||
<IconCopy size={12} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="admin-field">
|
||||
<label>Title override</label>
|
||||
<input
|
||||
value={album.title || ''}
|
||||
onChange={(e) => onUpdate({ title: e.target.value || undefined })}
|
||||
placeholder={name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="admin-field">
|
||||
<label>Description</label>
|
||||
<textarea
|
||||
value={album.description || ''}
|
||||
onChange={(e) => onUpdate({ description: e.target.value || undefined })}
|
||||
placeholder="Optional description for visitors"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="admin-field">
|
||||
<label>Password protection</label>
|
||||
<div className="input-with-icon">
|
||||
<input
|
||||
type="password"
|
||||
value={album.password || ''}
|
||||
onChange={(e) => onUpdate({ password: e.target.value || undefined })}
|
||||
placeholder="Leave empty for public access"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Column - Form Fields */}
|
||||
<div className="modal-right-column">
|
||||
<div className="admin-field">
|
||||
<label>Title override</label>
|
||||
<input
|
||||
value={album.title || ''}
|
||||
onChange={(e) => onUpdate({ title: e.target.value || undefined })}
|
||||
placeholder={name}
|
||||
/>
|
||||
{/* Hero Image Selection */}
|
||||
<div className="admin-field">
|
||||
<label>Custom Hero Image</label>
|
||||
<div className="album-hero-field">
|
||||
{album.heroImage ? (
|
||||
<div className="album-hero-preview">
|
||||
<img src={`/api/admin/thumbnail/${album.heroImage}`} alt="Hero" />
|
||||
<button
|
||||
className="album-hero-remove"
|
||||
onClick={() => onUpdate({ heroImage: undefined })}
|
||||
title="Remove custom hero image"
|
||||
>
|
||||
<IconX size={14} />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<span className="album-hero-empty">Using default album cover</span>
|
||||
)}
|
||||
<button
|
||||
className="admin-btn admin-btn-sm"
|
||||
onClick={() =>
|
||||
setHeroPickerTarget({
|
||||
albumId: album.id,
|
||||
onSelect: (assetId) => {
|
||||
onUpdate({ heroImage: assetId });
|
||||
setHeroPickerTarget(null);
|
||||
},
|
||||
currentAssetIds: album.heroImage ? [album.heroImage] : [],
|
||||
title: `Pick Hero Image for ${name}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
<IconImage size={12} /> {album.heroImage ? 'Change Image' : 'Pick Hero Image'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="admin-field">
|
||||
<label>Description</label>
|
||||
<textarea
|
||||
value={album.description || ''}
|
||||
onChange={(e) => onUpdate({ description: e.target.value || undefined })}
|
||||
placeholder="Optional description for visitors"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
{/* Photo order */}
|
||||
<div className="admin-field">
|
||||
<label id="album-sort-label">Photo order</label>
|
||||
<Listbox
|
||||
labelledBy="album-sort-label"
|
||||
value={album.sort || DEFAULT_ALBUM_SORT}
|
||||
options={SORT_OPTIONS}
|
||||
onChange={(mode) => onUpdate({ sort: mode })}
|
||||
/>
|
||||
<span className="admin-field-hint">
|
||||
{album.sort === 'manual'
|
||||
? 'Pinned photos come first, in the order you set. Everything else follows in the album’s Immich order.'
|
||||
: 'Immich order follows the album’s own sort setting in Immich.'}
|
||||
</span>
|
||||
|
||||
<div className="admin-field">
|
||||
<label>Password protection</label>
|
||||
<div className="input-with-icon">
|
||||
<input
|
||||
type="password"
|
||||
value={album.password || ''}
|
||||
onChange={(e) => onUpdate({ password: e.target.value || undefined })}
|
||||
placeholder="Leave empty for public access"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hero Image Selection */}
|
||||
<div className="admin-field">
|
||||
<label>Custom Hero Image</label>
|
||||
<div className="album-hero-field">
|
||||
{album.heroImage ? (
|
||||
<div className="album-hero-preview">
|
||||
<img src={`/api/admin/thumbnail/${album.heroImage}`} alt="Hero" />
|
||||
<button
|
||||
className="album-hero-remove"
|
||||
onClick={() => onUpdate({ heroImage: undefined })}
|
||||
title="Remove custom hero image"
|
||||
>
|
||||
<IconX size={14} />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<span className="album-hero-empty">Using default album cover</span>
|
||||
)}
|
||||
{album.sort === 'manual' && (
|
||||
<div style={{ marginTop: '0.75rem' }}>
|
||||
<button
|
||||
className="admin-btn admin-btn-sm"
|
||||
onClick={() =>
|
||||
setHeroPickerTarget({
|
||||
setOrderEditorTarget({
|
||||
albumId: album.id,
|
||||
onSelect: (assetId) => {
|
||||
onUpdate({ heroImage: assetId });
|
||||
setHeroPickerTarget(null);
|
||||
albumName: album.title || name,
|
||||
assetOrder: album.assetOrder || [],
|
||||
onSave: (assetOrder) => {
|
||||
onUpdate({ assetOrder });
|
||||
setOrderEditorTarget(null);
|
||||
},
|
||||
currentAssetIds: album.heroImage ? [album.heroImage] : [],
|
||||
title: `Pick Hero Image for ${name}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
<IconImage size={12} /> {album.heroImage ? 'Change Image' : 'Pick Hero Image'}
|
||||
<IconGripVertical size={18} className="svg-icon svg-drag" />{' '}
|
||||
{album.assetOrder?.length
|
||||
? `Reorder photos (${album.assetOrder.length} pinned)`
|
||||
: 'Reorder photos'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Photo order */}
|
||||
<div className="admin-field">
|
||||
<label>Photo order</label>
|
||||
<select
|
||||
value={album.sort || DEFAULT_ALBUM_SORT}
|
||||
onChange={(e) =>
|
||||
onUpdate({
|
||||
sort: isAlbumSortMode(e.target.value) ? e.target.value : undefined,
|
||||
})
|
||||
}
|
||||
style={{
|
||||
padding: '8px 12px',
|
||||
borderRadius: '6px',
|
||||
width: '100%',
|
||||
fontSize: '0.9rem',
|
||||
}}
|
||||
>
|
||||
{ALBUM_SORT_MODES.map((mode) => (
|
||||
<option key={mode} value={mode}>
|
||||
{SORT_LABELS[mode]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="admin-field-hint">
|
||||
{album.sort === 'manual'
|
||||
? 'Pinned photos come first, in the order you set. Everything else follows in the album’s Immich order.'
|
||||
: 'Immich order follows the album’s own sort setting in Immich.'}
|
||||
</span>
|
||||
|
||||
{album.sort === 'manual' && (
|
||||
<div style={{ marginTop: '0.75rem' }}>
|
||||
<button
|
||||
className="admin-btn admin-btn-sm"
|
||||
onClick={() =>
|
||||
setOrderEditorTarget({
|
||||
albumId: album.id,
|
||||
albumName: album.title || name,
|
||||
assetOrder: album.assetOrder || [],
|
||||
onSave: (assetOrder) => {
|
||||
onUpdate({ assetOrder });
|
||||
setOrderEditorTarget(null);
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
<IconGripVertical size={18} className="svg-icon svg-drag" />{' '}
|
||||
{album.assetOrder?.length
|
||||
? `Reorder photos (${album.assetOrder.length} pinned)`
|
||||
: 'Reorder photos'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="album-drawer-footer">
|
||||
@@ -1679,6 +1636,19 @@ export default function PageBuilder() {
|
||||
>
|
||||
<IconTrash size={14} /> Remove Album
|
||||
</button>
|
||||
<div className="uuid-copy-box" title="Immich album UUID">
|
||||
<code>{album.id}</code>
|
||||
<button
|
||||
className="uuid-copy-btn"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(album.id);
|
||||
}}
|
||||
title="Copy UUID"
|
||||
aria-label="Copy Immich album UUID"
|
||||
>
|
||||
<IconCopy size={12} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
className="admin-btn admin-btn-primary"
|
||||
onClick={() => setEditingAlbumAddress(null)}
|
||||
|
||||
68
app/admin/components/SaveBar.tsx
Normal file
68
app/admin/components/SaveBar.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
'use client';
|
||||
|
||||
interface SaveBarProps {
|
||||
dirty: boolean;
|
||||
saving: boolean;
|
||||
saveMessage: string;
|
||||
onSave: () => void;
|
||||
label: string;
|
||||
/** Show the cache-bypassing preview link (page builder only). */
|
||||
showPreview?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating save bar pinned to the bottom of the viewport.
|
||||
*
|
||||
* It only mounts while there is something to act on (unsaved changes, an
|
||||
* in-flight save, or a result message) so it never covers content otherwise.
|
||||
* The success message is cleared by the caller after a few seconds, which
|
||||
* makes the bar disappear on its own.
|
||||
*/
|
||||
export default function SaveBar({
|
||||
dirty,
|
||||
saving,
|
||||
saveMessage,
|
||||
onSave,
|
||||
label,
|
||||
showPreview = false,
|
||||
}: SaveBarProps) {
|
||||
if (!dirty && !saving && !saveMessage) return null;
|
||||
|
||||
return (
|
||||
<div className={`floating-save-bar ${dirty ? 'dirty' : ''}`} role="status">
|
||||
<div className="save-bar-left">
|
||||
{saveMessage ? (
|
||||
<span className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`}>
|
||||
{saveMessage}
|
||||
</span>
|
||||
) : (
|
||||
<span className="unsaved-badge">
|
||||
<span className="badge-pulse-dot" aria-hidden="true" />
|
||||
Unsaved changes
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="save-bar-right">
|
||||
{showPreview && (
|
||||
<a
|
||||
href="/?fresh=1"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="admin-btn admin-btn-ghost admin-btn-preview"
|
||||
title="Open site in new tab (bypassing cache)"
|
||||
>
|
||||
↗ Preview Site
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
className="admin-btn admin-btn-primary"
|
||||
onClick={onSave}
|
||||
disabled={!dirty || saving}
|
||||
title="⌘S / Ctrl+S"
|
||||
>
|
||||
{saving ? 'Saving...' : label}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import * as Icons from './Icons';
|
||||
import SaveBar from './SaveBar';
|
||||
|
||||
interface Settings {
|
||||
title?: string;
|
||||
@@ -11,6 +13,7 @@ interface Settings {
|
||||
exifOnHover?: boolean;
|
||||
map?: boolean;
|
||||
transitions?: boolean;
|
||||
scrollToTop?: boolean;
|
||||
analytics?: boolean;
|
||||
theme?: {
|
||||
preset?: string;
|
||||
@@ -73,13 +76,37 @@ const PHOTO_FRAMES = ['none', 'passepartout', 'shadow'];
|
||||
const HERO_STYLES = ['split', 'fullbleed', 'minimal', 'stacked', 'typographic', 'mosaic'];
|
||||
const ASPECT_RATIOS = ['1', '3/2', '2/3', '16/9', 'auto'];
|
||||
|
||||
const THEME_INFO: Record<string, { desc: string; label: string; accent: string; bg: string; tile: string }> = {
|
||||
/**
|
||||
* Card metadata for the theme picker. `font`, `radius` and `frame` mirror the
|
||||
* real preset definitions in lib/config/theme.ts so the mini mockups show what
|
||||
* the preset actually does; `gap` is the visual density of its gallery grid.
|
||||
*/
|
||||
const THEME_INFO: Record<
|
||||
string,
|
||||
{
|
||||
desc: string;
|
||||
label: string;
|
||||
accent: string;
|
||||
bg: string;
|
||||
tile: string;
|
||||
font: string;
|
||||
type: 'serif' | 'sans' | 'mono';
|
||||
radius: number;
|
||||
frame: 'none' | 'passepartout' | 'shadow';
|
||||
gap: number;
|
||||
}
|
||||
> = {
|
||||
studio: {
|
||||
label: 'Studio',
|
||||
desc: 'Clean, high-contrast grid with sans-serif type.',
|
||||
bg: '#141414',
|
||||
tile: '#242424',
|
||||
accent: '#e60012',
|
||||
font: 'Playfair Display',
|
||||
type: 'serif',
|
||||
radius: 0,
|
||||
frame: 'passepartout',
|
||||
gap: 4,
|
||||
},
|
||||
'studio-modern': {
|
||||
label: 'Studio Modern',
|
||||
@@ -87,6 +114,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
|
||||
bg: '#121212',
|
||||
tile: '#191919',
|
||||
accent: '#e60012',
|
||||
font: 'Archivo',
|
||||
type: 'sans',
|
||||
radius: 0,
|
||||
frame: 'none',
|
||||
gap: 3,
|
||||
},
|
||||
minimal: {
|
||||
label: 'Minimal',
|
||||
@@ -94,6 +126,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
|
||||
bg: '#ffffff',
|
||||
tile: '#f3f3f3',
|
||||
accent: '#111111',
|
||||
font: 'Geist',
|
||||
type: 'sans',
|
||||
radius: 0,
|
||||
frame: 'none',
|
||||
gap: 2,
|
||||
},
|
||||
editorial: {
|
||||
label: 'Editorial',
|
||||
@@ -101,6 +138,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
|
||||
bg: '#fbf9f4',
|
||||
tile: '#e5dfd4',
|
||||
accent: '#b89053',
|
||||
font: 'Bodoni Moda',
|
||||
type: 'serif',
|
||||
radius: 0,
|
||||
frame: 'shadow',
|
||||
gap: 8,
|
||||
},
|
||||
classic: {
|
||||
label: 'Classic',
|
||||
@@ -108,6 +150,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
|
||||
bg: '#f7f7f7',
|
||||
tile: '#ffffff',
|
||||
accent: '#444444',
|
||||
font: 'Cinzel',
|
||||
type: 'serif',
|
||||
radius: 12,
|
||||
frame: 'passepartout',
|
||||
gap: 7,
|
||||
},
|
||||
noir: {
|
||||
label: 'Noir',
|
||||
@@ -115,6 +162,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
|
||||
bg: '#000000',
|
||||
tile: '#151515',
|
||||
accent: '#ffffff',
|
||||
font: 'Libre Baskerville',
|
||||
type: 'serif',
|
||||
radius: 0,
|
||||
frame: 'passepartout',
|
||||
gap: 6,
|
||||
},
|
||||
monograph: {
|
||||
label: 'Monograph',
|
||||
@@ -122,18 +174,44 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
|
||||
bg: '#f4f4f6',
|
||||
tile: '#ffffff',
|
||||
accent: '#555555',
|
||||
font: 'Instrument Serif',
|
||||
type: 'mono',
|
||||
radius: 0,
|
||||
frame: 'none',
|
||||
gap: 5,
|
||||
},
|
||||
};
|
||||
|
||||
export default function SettingsEditor() {
|
||||
const SETTINGS_SECTIONS = [
|
||||
{ id: 'general', label: 'General' },
|
||||
{ id: 'theme', label: 'Theme' },
|
||||
{ id: 'grid', label: 'Grid' },
|
||||
{ id: 'footer', label: 'Footer' },
|
||||
{ id: 'legal', label: 'Legal' },
|
||||
{ id: 'seo', label: 'SEO' },
|
||||
{ id: 'security', label: 'Security & Protection' },
|
||||
];
|
||||
|
||||
interface SettingsEditorProps {
|
||||
/** Sub-section to show, taken from the /admin/settings/[section] route. */
|
||||
section?: string;
|
||||
}
|
||||
|
||||
export default function SettingsEditor({ section }: SettingsEditorProps) {
|
||||
const router = useRouter();
|
||||
// An unknown section in the URL falls back to General instead of an empty panel.
|
||||
const activeSection = SETTINGS_SECTIONS.some((sec) => sec.id === section)
|
||||
? (section as string)
|
||||
: 'general';
|
||||
const [settings, setSettings] = useState<Settings>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [saveMessage, setSaveMessage] = useState('');
|
||||
const [activeSection, setActiveSection] = useState('general');
|
||||
|
||||
const [currentMode, setCurrentMode] = useState<'dark' | 'light'>('dark');
|
||||
const [faviconUploading, setFaviconUploading] = useState(false);
|
||||
const [faviconMessage, setFaviconMessage] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings();
|
||||
@@ -275,54 +353,31 @@ export default function SettingsEditor() {
|
||||
);
|
||||
}
|
||||
|
||||
const sections = [
|
||||
{ id: 'general', label: 'General' },
|
||||
{ id: 'theme', label: 'Theme' },
|
||||
{ id: 'grid', label: 'Grid' },
|
||||
{ id: 'footer', label: 'Footer' },
|
||||
{ id: 'legal', label: 'Legal' },
|
||||
{ id: 'seo', label: 'SEO' },
|
||||
{ id: 'security', label: 'Security & Protection' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="settings-editor">
|
||||
{/* Save Bar */}
|
||||
<div className={`save-bar ${dirty ? 'dirty' : ''}`}>
|
||||
<div className="save-bar-left">
|
||||
{dirty && <span className="unsaved-badge">Unsaved changes</span>}
|
||||
{saveMessage ? (
|
||||
<span
|
||||
className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`}
|
||||
>
|
||||
{saveMessage}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--admin-text-muted)', display: 'inline-flex', alignItems: 'center', gap: '0.25rem' }}>
|
||||
⚡ Live Sync (No Docker restart required)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className="admin-btn admin-btn-primary"
|
||||
onClick={handleSave}
|
||||
disabled={!dirty || saving}
|
||||
>
|
||||
{saving ? 'Saving...' : 'Save Settings'}
|
||||
</button>
|
||||
</div>
|
||||
<SaveBar
|
||||
dirty={dirty}
|
||||
saving={saving}
|
||||
saveMessage={saveMessage}
|
||||
onSave={handleSave}
|
||||
label="Save Settings"
|
||||
/>
|
||||
|
||||
<p className="settings-live-sync-note">
|
||||
<Icons.IconRefresh size={13} /> Live Sync (No Docker restart required)
|
||||
</p>
|
||||
|
||||
<div className="settings-layout">
|
||||
{/* Sidebar */}
|
||||
<nav className="settings-nav">
|
||||
{sections.map((sec) => (
|
||||
<button
|
||||
{SETTINGS_SECTIONS.map((sec) => (
|
||||
<Link
|
||||
key={sec.id}
|
||||
href={`/admin/settings/${sec.id}`}
|
||||
className={`settings-nav-item ${activeSection === sec.id ? 'active' : ''}`}
|
||||
onClick={() => setActiveSection(sec.id)}
|
||||
>
|
||||
{sec.label}
|
||||
</button>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -415,6 +470,20 @@ export default function SettingsEditor() {
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={`admin-toggle-card ${settings.scrollToTop !== false ? 'active' : ''}`}
|
||||
onClick={() => update('scrollToTop', settings.scrollToTop === false)}
|
||||
>
|
||||
<div className="toggle-card-info">
|
||||
<span className="toggle-card-title"><Icons.IconArrowUp size={16} /> Scroll-to-Top Button</span>
|
||||
<span className="toggle-card-desc">Show a floating arrow that returns visitors to the top of long pages</span>
|
||||
</div>
|
||||
<div className={`switch-toggle ${settings.scrollToTop !== false ? 'on' : ''}`}>
|
||||
<span className="switch-slider" />
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={`admin-toggle-card ${settings.analytics !== false ? 'active' : ''}`}
|
||||
@@ -443,6 +512,65 @@ export default function SettingsEditor() {
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="admin-field favicon-field">
|
||||
<label>Favicon</label>
|
||||
<div className="favicon-row">
|
||||
<input
|
||||
type="file"
|
||||
accept=".svg,.png,.ico,.jpg,.jpeg"
|
||||
disabled={faviconUploading}
|
||||
onChange={async (e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setFaviconMessage('');
|
||||
setFaviconUploading(true);
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
try {
|
||||
const res = await fetch('/api/admin/favicon', { method: 'PUT', body: form });
|
||||
const data = await res.json();
|
||||
setFaviconMessage(res.ok ? data.message : `Error: ${data.error}`);
|
||||
} catch {
|
||||
setFaviconMessage('Error: Upload failed');
|
||||
} finally {
|
||||
setFaviconUploading(false);
|
||||
e.target.value = '';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn"
|
||||
disabled={faviconUploading}
|
||||
onClick={async () => {
|
||||
setFaviconMessage('');
|
||||
setFaviconUploading(true);
|
||||
try {
|
||||
const res = await fetch('/api/admin/favicon', { method: 'DELETE' });
|
||||
const data = await res.json();
|
||||
setFaviconMessage(res.ok ? data.message : `Error: ${data.error}`);
|
||||
} catch {
|
||||
setFaviconMessage('Error: Reset failed');
|
||||
} finally {
|
||||
setFaviconUploading(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
{faviconUploading && <div className="admin-spinner" />}
|
||||
</div>
|
||||
{faviconMessage && (
|
||||
<p className={`save-message ${faviconMessage.startsWith('Error') ? 'error' : 'success'}`}>
|
||||
{faviconMessage}
|
||||
</p>
|
||||
)}
|
||||
<span className="admin-field-hint">
|
||||
SVG, PNG, ICO, or JPEG — max 512 kB. Stored in the content volume. Reset restores
|
||||
the bundled default.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -457,30 +585,52 @@ export default function SettingsEditor() {
|
||||
<label>Preset</label>
|
||||
<div className="preset-card-grid">
|
||||
{PRESETS.map((p) => {
|
||||
const info = THEME_INFO[p] || { label: p, desc: '', bg: '#fff', tile: '#eee', accent: '#333' };
|
||||
const info = THEME_INFO[p] || {
|
||||
label: p,
|
||||
desc: '',
|
||||
bg: '#fff',
|
||||
tile: '#eee',
|
||||
accent: '#333',
|
||||
font: 'System',
|
||||
type: 'sans' as const,
|
||||
radius: 0,
|
||||
frame: 'none' as const,
|
||||
gap: 4,
|
||||
};
|
||||
const isActive = (settings.theme?.preset || 'studio') === p;
|
||||
return (
|
||||
<button
|
||||
key={p}
|
||||
type="button"
|
||||
className={`preset-card ${isActive ? 'active' : ''}`}
|
||||
className={`preset-card theme-preset-card ${isActive ? 'active' : ''}`}
|
||||
onClick={() => update('theme.preset', p)}
|
||||
style={{ '--preset-accent': info.accent } as React.CSSProperties}
|
||||
style={
|
||||
{
|
||||
'--preset-accent': info.accent,
|
||||
'--preset-bg': info.bg,
|
||||
'--preset-tile': info.tile,
|
||||
'--preset-radius': `${info.radius}px`,
|
||||
'--preset-gap': `${info.gap}px`,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<div className="preset-card-preview" style={{ backgroundColor: info.bg }}>
|
||||
<div className="preset-card-preview" data-frame={info.frame}>
|
||||
<div className="mini-header">
|
||||
<span className="mini-dot" style={{ backgroundColor: info.accent }}></span>
|
||||
<span className="mini-line" style={{ backgroundColor: isActive ? info.accent : 'var(--admin-border)' }}></span>
|
||||
<span className={`mini-specimen type-${info.type}`}>Aa</span>
|
||||
<span className="mini-line" />
|
||||
</div>
|
||||
<div className="mini-grid">
|
||||
<div className="mini-tile" style={{ backgroundColor: info.tile }}></div>
|
||||
<div className="mini-tile" style={{ backgroundColor: info.tile }}></div>
|
||||
<div className="mini-tile" style={{ backgroundColor: info.tile }}></div>
|
||||
<div className="mini-tile" />
|
||||
<div className="mini-tile" />
|
||||
<div className="mini-tile" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="preset-card-info">
|
||||
<span className="preset-card-name">{info.label}</span>
|
||||
<span className="preset-card-desc">{info.desc}</span>
|
||||
<span className="preset-card-specs">
|
||||
{info.font} · radius {info.radius} · {info.frame}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
@@ -765,7 +915,7 @@ export default function SettingsEditor() {
|
||||
)}
|
||||
{l === 'showcase' && (
|
||||
<div className="demo-showcase-grid">
|
||||
<div className="demo-tile hero-tile" />
|
||||
<div className="demo-tile demo-hero" />
|
||||
<div className="demo-col"><div className="demo-tile" /><div className="demo-tile" /></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
485
app/admin/components/journal-studio.css
Normal file
485
app/admin/components/journal-studio.css
Normal file
@@ -0,0 +1,485 @@
|
||||
/* ── Journal Studio & Editor CSS ──────────────────────────────────── */
|
||||
|
||||
/*
|
||||
* The studio is a full-width workspace: it breaks out of the 1120px
|
||||
* `.admin-main` column so the split view has room for editor *and* preview.
|
||||
*/
|
||||
.admin-main:has(> .journal-studio),
|
||||
.admin-main:has(> .journal-editor-container) {
|
||||
max-width: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* ── Form controls ─────────────────────────────────────────────────
|
||||
* Local field styling for the studio. Scoped so the generic class name
|
||||
* cannot leak into the rest of the admin panel.
|
||||
*/
|
||||
.journal-studio .admin-input,
|
||||
.journal-editor-container .admin-input,
|
||||
.journal-modal-card .admin-input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.55rem 0.7rem;
|
||||
background: var(--admin-bg-input, #161616);
|
||||
border: 1px solid var(--admin-border, #2e2e2e);
|
||||
border-radius: 8px;
|
||||
color: var(--admin-text, #f0f0f0);
|
||||
font-family: inherit;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
transition:
|
||||
border-color 0.15s ease,
|
||||
background 0.15s ease;
|
||||
}
|
||||
|
||||
.journal-studio .admin-input:hover,
|
||||
.journal-editor-container .admin-input:hover,
|
||||
.journal-modal-card .admin-input:hover {
|
||||
border-color: var(--admin-border-hover, #444);
|
||||
}
|
||||
|
||||
.journal-studio .admin-input:focus,
|
||||
.journal-editor-container .admin-input:focus,
|
||||
.journal-modal-card .admin-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--admin-border-focus, #6366f1);
|
||||
}
|
||||
|
||||
.journal-studio .admin-input::placeholder,
|
||||
.journal-editor-container .admin-input::placeholder,
|
||||
.journal-modal-card .admin-input::placeholder {
|
||||
color: var(--admin-text-secondary, #a0a0a0);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.journal-editor-container textarea.admin-input,
|
||||
.journal-modal-card textarea.admin-input {
|
||||
resize: vertical;
|
||||
min-height: 88px;
|
||||
}
|
||||
|
||||
.journal-editor-container select.admin-input {
|
||||
cursor: pointer;
|
||||
appearance: none;
|
||||
padding-right: 2rem;
|
||||
background-image:
|
||||
linear-gradient(45deg, transparent 50%, currentColor 50%),
|
||||
linear-gradient(135deg, currentColor 50%, transparent 50%);
|
||||
background-position:
|
||||
calc(100% - 16px) calc(50% + 1px),
|
||||
calc(100% - 11px) calc(50% + 1px);
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
.journal-level-select {
|
||||
width: 5.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.journal-studio {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: calc(100vh - 70px);
|
||||
}
|
||||
|
||||
.journal-studio-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.5rem 2rem;
|
||||
border-bottom: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
|
||||
}
|
||||
|
||||
.journal-studio-header h2 {
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.journal-list-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
gap: 1.5rem;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.journal-admin-card {
|
||||
background: var(--admin-surface, rgba(255, 255, 255, 0.03));
|
||||
border: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
transition:
|
||||
border-color 0.2s ease,
|
||||
transform 0.2s ease;
|
||||
}
|
||||
|
||||
.journal-admin-card:hover {
|
||||
border-color: var(--admin-accent, #6366f1);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.journal-admin-card-cover {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.journal-admin-card-cover img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.journal-admin-card-body {
|
||||
padding: 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.journal-admin-card-title {
|
||||
font-size: 1.15rem;
|
||||
font-weight: 600;
|
||||
margin: 0 0 0.4rem;
|
||||
}
|
||||
|
||||
.journal-admin-card-slug {
|
||||
font-size: 0.75rem;
|
||||
font-family: monospace;
|
||||
opacity: 0.6;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.journal-admin-card-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 0.75rem;
|
||||
opacity: 0.7;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.journal-admin-card-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: auto;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--admin-border, rgba(255, 255, 255, 0.06));
|
||||
}
|
||||
|
||||
/* ── Split-Screen Studio Editor ────────────────────────────────────── */
|
||||
|
||||
.journal-editor-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 65px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.journal-editor-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.75rem 1.5rem;
|
||||
background: var(--admin-surface, #18181b);
|
||||
border-bottom: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
|
||||
gap: 1rem;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.journal-editor-topbar-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.journal-editor-title-input {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
color: inherit;
|
||||
padding: 4px 8px;
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.journal-editor-title-input:focus {
|
||||
border-color: var(--admin-accent, #6366f1);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.journal-editor-topbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.journal-editor-split {
|
||||
display: grid;
|
||||
/* Left width is driven by the draggable divider; the preview takes the rest. */
|
||||
grid-template-columns: var(--journal-split-left, 46%) 7px minmax(0, 1fr);
|
||||
flex-grow: 1;
|
||||
overflow: hidden;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Kill text selection and pointer flicker while the divider is being dragged. */
|
||||
.journal-editor-split.is-dragging {
|
||||
user-select: none;
|
||||
cursor: col-resize;
|
||||
}
|
||||
|
||||
.journal-editor-split.is-dragging .journal-editor-pane-right {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.journal-editor-resizer {
|
||||
position: relative;
|
||||
cursor: col-resize;
|
||||
background: var(--admin-border, rgba(255, 255, 255, 0.08));
|
||||
transition: background 0.15s ease;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.journal-editor-resizer:hover,
|
||||
.journal-editor-resizer:focus-visible,
|
||||
.journal-editor-split.is-dragging .journal-editor-resizer {
|
||||
background: var(--admin-accent, #6366f1);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* Grip dots, and a widened invisible hit area so the divider is easy to grab. */
|
||||
.journal-editor-resizer-grip {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 15px;
|
||||
height: 44px;
|
||||
border-radius: 4px;
|
||||
background: repeating-linear-gradient(to bottom, currentColor 0 2px, transparent 2px 5px);
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
background-clip: content-box;
|
||||
padding: 0 6px;
|
||||
}
|
||||
|
||||
.journal-editor-resizer:hover .journal-editor-resizer-grip {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.journal-editor-pane-left {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
padding: 1.5rem 2rem 4rem;
|
||||
background: var(--admin-bg, #09090b);
|
||||
}
|
||||
|
||||
.journal-editor-pane-right {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
background: var(--surface, #111);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.journal-preview-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.5rem 1rem;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
font-size: 0.75rem;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 5;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.journal-preview-frame {
|
||||
padding: 2.5rem 2rem;
|
||||
max-width: 1080px;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
transition: max-width 0.3s ease;
|
||||
}
|
||||
|
||||
/*
|
||||
* The essay's full-bleed and wide figures are sized against the viewport on the
|
||||
* live site. Inside the preview pane that overshoots — the photo would bleed out
|
||||
* of the pane and drift as the split is dragged — so they are re-anchored to the
|
||||
* frame. 100% is the container's content box, so reaching the pane edges means
|
||||
* adding back both horizontal paddings: 4rem for this frame plus 3rem for
|
||||
* .essay-container. Keep in sync if either padding changes.
|
||||
*/
|
||||
.journal-preview-frame .essay-container {
|
||||
--essay-bleed: calc(100% + 7rem);
|
||||
--essay-wide: 100%;
|
||||
}
|
||||
|
||||
.journal-preview-frame.mobile {
|
||||
max-width: 380px;
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-right: 1px solid rgba(255, 255, 255, 0.1);
|
||||
min-height: 100%;
|
||||
background: var(--background, #000);
|
||||
}
|
||||
|
||||
.journal-raw-markdown-editor {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 500px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.6;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
color: #f4f4f5;
|
||||
border: 1px solid var(--admin-border, rgba(255, 255, 255, 0.1));
|
||||
border-radius: 8px;
|
||||
padding: 1.25rem;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
.journal-raw-markdown-editor:focus {
|
||||
outline: none;
|
||||
border-color: var(--admin-accent, #6366f1);
|
||||
}
|
||||
|
||||
/* Modal styling for Entry creation / Metadata */
|
||||
.journal-modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.75);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 100;
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.journal-modal-card {
|
||||
background: var(--admin-surface, #18181b);
|
||||
border: 1px solid var(--admin-border, rgba(255, 255, 255, 0.1));
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 620px;
|
||||
max-height: 88vh;
|
||||
overflow-y: auto;
|
||||
padding: 1.75rem;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
/* ── Card meta & status ───────────────────────────────────────────── */
|
||||
|
||||
.journal-admin-card-meta span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.journal-card-cover-placeholder {
|
||||
opacity: 0.25;
|
||||
}
|
||||
|
||||
.journal-status-pill {
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.journal-status-pill.is-draft {
|
||||
background: rgba(234, 179, 8, 0.15);
|
||||
color: #eab308;
|
||||
border: 1px solid rgba(234, 179, 8, 0.3);
|
||||
}
|
||||
|
||||
.journal-status-pill.is-published {
|
||||
background: rgba(34, 197, 94, 0.15);
|
||||
color: #22c55e;
|
||||
border: 1px solid rgba(34, 197, 94, 0.3);
|
||||
}
|
||||
|
||||
.journal-preview-bar-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* ── Block field rows ─────────────────────────────────────────────
|
||||
* The generic `.admin-input { width: 100% }` would blow these rows apart,
|
||||
* so the fixed-width controls are pinned here (higher specificity wins).
|
||||
*/
|
||||
.journal-heading-row,
|
||||
.journal-photo-layout-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.journal-editor-container .journal-heading-row .journal-level-select {
|
||||
flex: 0 0 5.5rem;
|
||||
width: 5.5rem;
|
||||
}
|
||||
|
||||
.journal-editor-container .journal-heading-row input {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.journal-editor-container .journal-photo-layout-row select {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.journal-photo-layout-row .admin-btn {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Stack the split view on narrow screens instead of squeezing both panes. */
|
||||
@media (max-width: 1100px) {
|
||||
.journal-editor-split {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.journal-editor-resizer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.journal-editor-pane-left {
|
||||
border-bottom: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
|
||||
}
|
||||
}
|
||||
|
||||
/* An unresolvable photo reference — shown in the block editor, not to visitors. */
|
||||
.journal-block-warning {
|
||||
margin: 0 0 0.75rem;
|
||||
padding: 0.55rem 0.7rem;
|
||||
border-radius: 8px;
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.45;
|
||||
color: #fca5a5;
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border: 1px solid rgba(239, 68, 68, 0.3);
|
||||
}
|
||||
41
app/admin/components/useScrollLock.ts
Normal file
41
app/admin/components/useScrollLock.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Freezes the page behind a modal for as long as `active` is true.
|
||||
*
|
||||
* An overlay covers the page but does not absorb wheel events: a scroll that
|
||||
* starts over the backdrop — or one that continues past the end of the modal's
|
||||
* own scroll container — reaches the document and moves the page underneath.
|
||||
* `overscroll-behavior` alone cannot fix that, because it only applies to
|
||||
* scroll containers, and the backdrop is not one.
|
||||
*
|
||||
* Nesting works without a counter: each lock captures whatever inline value it
|
||||
* found and restores exactly that, so a picker opened from the album drawer
|
||||
* restores the drawer's `hidden` rather than clearing it.
|
||||
*/
|
||||
export function useScrollLock(active: boolean) {
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
|
||||
const { body } = document;
|
||||
const previousOverflow = body.style.overflow;
|
||||
const previousPaddingRight = body.style.paddingRight;
|
||||
|
||||
// Hiding the scrollbar widens the viewport and shifts the page under the
|
||||
// overlay. Pad by exactly the width it gave up so nothing moves. Overlay
|
||||
// scrollbars (most touch devices) measure 0 and need no compensation.
|
||||
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
|
||||
if (scrollbarWidth > 0) {
|
||||
const current = parseFloat(getComputedStyle(body).paddingRight) || 0;
|
||||
body.style.paddingRight = `${current + scrollbarWidth}px`;
|
||||
}
|
||||
body.style.overflow = 'hidden';
|
||||
|
||||
return () => {
|
||||
body.style.overflow = previousOverflow;
|
||||
body.style.paddingRight = previousPaddingRight;
|
||||
};
|
||||
}, [active]);
|
||||
}
|
||||
10
app/admin/journal/[slug]/page.tsx
Normal file
10
app/admin/journal/[slug]/page.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { JournalStudio } from '../../components/JournalStudio';
|
||||
|
||||
export default async function AdminJournalEntryPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ slug: string }>;
|
||||
}) {
|
||||
const { slug } = await params;
|
||||
return <JournalStudio slug={slug} />;
|
||||
}
|
||||
5
app/admin/journal/page.tsx
Normal file
5
app/admin/journal/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { JournalStudio } from '../components/JournalStudio';
|
||||
|
||||
export default function AdminJournalPage() {
|
||||
return <JournalStudio />;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from 'next';
|
||||
import AdminShell from './AdminShell';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Immich Folio Admin',
|
||||
@@ -16,5 +17,9 @@ export const metadata: Metadata = {
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
return <div className="admin-layout">{children}</div>;
|
||||
return (
|
||||
<div className="admin-layout">
|
||||
<AdminShell>{children}</AdminShell>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,54 +1,5 @@
|
||||
'use client';
|
||||
import PageBuilder from './components/PageBuilder';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import AdminLogin from './components/AdminLogin';
|
||||
import AdminDashboard from './components/AdminDashboard';
|
||||
import './admin.css';
|
||||
|
||||
export default function AdminPage() {
|
||||
const [authenticated, setAuthenticated] = useState<boolean | null>(null);
|
||||
const [enabled, setEnabled] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const res = await fetch('/api/admin/auth');
|
||||
const data = await res.json();
|
||||
setAuthenticated(data.authenticated);
|
||||
setEnabled(data.enabled);
|
||||
} catch {
|
||||
setAuthenticated(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (authenticated === null) {
|
||||
return (
|
||||
<div className="admin-loading">
|
||||
<div className="admin-spinner" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
return (
|
||||
<div className="admin-disabled">
|
||||
<div className="admin-disabled-card">
|
||||
<h1>Admin Panel</h1>
|
||||
<p>
|
||||
The admin panel is not enabled. Set <code>ADMIN_PASSWORD</code> in your environment
|
||||
variables to activate it.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return <AdminLogin onSuccess={() => setAuthenticated(true)} />;
|
||||
}
|
||||
|
||||
return <AdminDashboard onLogout={() => setAuthenticated(false)} />;
|
||||
export default function AdminHomePage() {
|
||||
return <PageBuilder />;
|
||||
}
|
||||
|
||||
5
app/admin/pages/page.tsx
Normal file
5
app/admin/pages/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import PageBuilder from '../components/PageBuilder';
|
||||
|
||||
export default function AdminPagesPage() {
|
||||
return <PageBuilder />;
|
||||
}
|
||||
10
app/admin/settings/[section]/page.tsx
Normal file
10
app/admin/settings/[section]/page.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import SettingsEditor from '../../components/SettingsEditor';
|
||||
|
||||
export default async function AdminSettingsSectionPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ section: string }>;
|
||||
}) {
|
||||
const { section } = await params;
|
||||
return <SettingsEditor section={section} />;
|
||||
}
|
||||
5
app/admin/settings/page.tsx
Normal file
5
app/admin/settings/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import SettingsEditor from '../components/SettingsEditor';
|
||||
|
||||
export default function AdminSettingsPage() {
|
||||
return <SettingsEditor />;
|
||||
}
|
||||
@@ -121,6 +121,64 @@ const ROUTES: {
|
||||
method: 'POST',
|
||||
args: () => [new Request('http://localhost/api/admin/backups', { method: 'POST', body: '{}' })],
|
||||
},
|
||||
{
|
||||
name: 'PUT /api/admin/favicon',
|
||||
path: 'favicon',
|
||||
load: () => import('../favicon/route'),
|
||||
method: 'PUT',
|
||||
args: () => [new Request('http://localhost/api/admin/favicon', { method: 'PUT' })],
|
||||
},
|
||||
{
|
||||
name: 'DELETE /api/admin/favicon',
|
||||
path: 'favicon',
|
||||
load: () => import('../favicon/route'),
|
||||
method: 'DELETE',
|
||||
args: () => [],
|
||||
},
|
||||
{
|
||||
name: 'GET /api/admin/journal',
|
||||
path: 'journal',
|
||||
load: () => import('../journal/route'),
|
||||
method: 'GET',
|
||||
args: () => [],
|
||||
},
|
||||
{
|
||||
name: 'POST /api/admin/journal',
|
||||
path: 'journal',
|
||||
load: () => import('../journal/route'),
|
||||
method: 'POST',
|
||||
args: () => [new Request('http://localhost/api/admin/journal', { method: 'POST', body: '{}' })],
|
||||
},
|
||||
{
|
||||
name: 'GET /api/admin/journal/[slug]',
|
||||
path: 'journal/[slug]',
|
||||
load: () => import('../journal/[slug]/route'),
|
||||
method: 'GET',
|
||||
args: () => [
|
||||
new Request('http://localhost/api/admin/journal/test-slug'),
|
||||
{ params: Promise.resolve({ slug: 'test-slug' }) },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'PUT /api/admin/journal/[slug]',
|
||||
path: 'journal/[slug]',
|
||||
load: () => import('../journal/[slug]/route'),
|
||||
method: 'PUT',
|
||||
args: () => [
|
||||
new Request('http://localhost/api/admin/journal/test-slug', { method: 'PUT', body: '{}' }),
|
||||
{ params: Promise.resolve({ slug: 'test-slug' }) },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'DELETE /api/admin/journal/[slug]',
|
||||
path: 'journal/[slug]',
|
||||
load: () => import('../journal/[slug]/route'),
|
||||
method: 'DELETE',
|
||||
args: () => [
|
||||
new Request('http://localhost/api/admin/journal/test-slug', { method: 'DELETE' }),
|
||||
{ params: Promise.resolve({ slug: 'test-slug' }) },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe('admin route guards', () => {
|
||||
@@ -165,7 +223,7 @@ describe('admin route guards', () => {
|
||||
if (entry.name === '__tests__') continue;
|
||||
walk(full);
|
||||
} else if (entry.name === 'route.ts') {
|
||||
found.push(path.relative(adminDir, path.dirname(full)));
|
||||
found.push(path.relative(adminDir, path.dirname(full)).replace(/\\/g, '/'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -44,7 +44,7 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'Password is too long' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!verifyAdminPassword(body.password)) {
|
||||
if (!(await verifyAdminPassword(body.password))) {
|
||||
return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
|
||||
}
|
||||
|
||||
|
||||
111
app/api/admin/favicon/route.ts
Normal file
111
app/api/admin/favicon/route.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
|
||||
|
||||
const CONTENT_DIR = path.resolve(process.cwd(), 'content');
|
||||
const DEST = 'favicon.svg';
|
||||
|
||||
const MAX_SIZE = 512 * 1024; // 512 kB
|
||||
|
||||
/**
|
||||
* Write via temp file + rename, the same pattern yaml-service uses: GET
|
||||
* /api/favicon reads this path on every request, so a plain writeFile would
|
||||
* let a concurrent read see a half-written icon.
|
||||
*/
|
||||
async function writeFavicon(content: Buffer | string): Promise<void> {
|
||||
await fs.mkdir(CONTENT_DIR, { recursive: true });
|
||||
const dest = path.join(CONTENT_DIR, DEST);
|
||||
const tmpPath = `${dest}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
await fs.writeFile(tmpPath, content);
|
||||
await fs.rename(tmpPath, dest);
|
||||
} catch (err) {
|
||||
await fs.unlink(tmpPath).catch(() => {});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
if (!(await isAdminAuthenticated())) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: FormData;
|
||||
try {
|
||||
body = await request.formData();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid form data' }, { status: 400 });
|
||||
}
|
||||
|
||||
// A plain text field named "file" also satisfies `body.get('file')`, and the
|
||||
// .size/.arrayBuffer() calls below would then throw a 500 on what is really
|
||||
// a malformed request.
|
||||
const file = body.get('file');
|
||||
if (!(file instanceof File)) {
|
||||
return NextResponse.json({ error: 'Missing file' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (file.size > MAX_SIZE) {
|
||||
return NextResponse.json({ error: 'File must be under 512 kB' }, { status: 400 });
|
||||
}
|
||||
|
||||
const buf = Buffer.from(await file.arrayBuffer());
|
||||
|
||||
// SVG passes through directly — CSP on the GET route protects the origin.
|
||||
if (file.type === 'image/svg+xml') {
|
||||
const text = buf.toString('utf-8');
|
||||
if (!text.includes('<svg')) {
|
||||
return NextResponse.json({ error: 'Invalid SVG file' }, { status: 400 });
|
||||
}
|
||||
await writeFavicon(buf);
|
||||
return NextResponse.json({ success: true, message: 'Favicon updated.' });
|
||||
}
|
||||
|
||||
// Raster formats (PNG, ICO, JPEG) — wrap in an SVG container so the favicon
|
||||
// reference and CSP apply uniformly regardless of the uploaded format.
|
||||
const mime = file.type || 'image/png';
|
||||
if (
|
||||
mime !== 'image/png' &&
|
||||
mime !== 'image/x-icon' &&
|
||||
mime !== 'image/vnd.microsoft.icon' &&
|
||||
mime !== 'image/jpeg'
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: `Unsupported file type: ${mime}. Use SVG, PNG, ICO, or JPEG.` },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const b64 = buf.toString('base64');
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
|
||||
<image href="data:${mime};base64,${b64}" width="32" height="32"/>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
await writeFavicon(svg);
|
||||
return NextResponse.json({ success: true, message: 'Favicon updated.' });
|
||||
}
|
||||
|
||||
/** Clean up stale favicon files left by a previous upload of a different format. */
|
||||
export async function DELETE() {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
if (!(await isAdminAuthenticated())) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.unlink(path.join(CONTENT_DIR, DEST));
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Custom favicon removed. Default restored.',
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'No custom favicon to remove' }, { status: 404 });
|
||||
}
|
||||
}
|
||||
119
app/api/admin/journal/[slug]/route.ts
Normal file
119
app/api/admin/journal/[slug]/route.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
|
||||
import {
|
||||
isValidSlug,
|
||||
sanitizeSlug,
|
||||
parseJournalMarkdown,
|
||||
} from '@/lib/journal';
|
||||
import {
|
||||
readJournalEntry,
|
||||
writeJournalEntry,
|
||||
deleteJournalEntry,
|
||||
} from '@/lib/admin/journal-service';
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ slug: string }>;
|
||||
}
|
||||
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
if (!(await isAdminAuthenticated())) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { slug } = await context.params;
|
||||
if (!isValidSlug(slug)) {
|
||||
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const entry = await readJournalEntry(slug);
|
||||
if (!entry) {
|
||||
return NextResponse.json({ error: 'Journal entry not found' }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ entry });
|
||||
} catch (err) {
|
||||
console.error(`[Admin API] Failed to get journal entry "${slug}":`, err);
|
||||
return NextResponse.json({ error: 'Failed to read journal entry' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request, context: RouteContext) {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
if (!(await isAdminAuthenticated())) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { slug } = await context.params;
|
||||
if (!isValidSlug(slug)) {
|
||||
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const rawMarkdown = body.rawMarkdown ?? body.content;
|
||||
|
||||
if (typeof rawMarkdown !== 'string') {
|
||||
return NextResponse.json({ error: 'Missing rawMarkdown content' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Verify markdown can be parsed safely
|
||||
parseJournalMarkdown(rawMarkdown);
|
||||
|
||||
const targetSlug =
|
||||
typeof body.newSlug === 'string' && body.newSlug
|
||||
? sanitizeSlug(body.newSlug)
|
||||
: slug;
|
||||
|
||||
if (!isValidSlug(targetSlug)) {
|
||||
return NextResponse.json({ error: 'Invalid target slug' }, { status: 400 });
|
||||
}
|
||||
|
||||
// If renaming, ensure target doesn't already exist
|
||||
if (targetSlug !== slug) {
|
||||
const existing = await readJournalEntry(targetSlug);
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: 'Target slug already exists' }, { status: 409 });
|
||||
}
|
||||
await writeJournalEntry(targetSlug, rawMarkdown);
|
||||
await deleteJournalEntry(slug);
|
||||
} else {
|
||||
await writeJournalEntry(slug, rawMarkdown);
|
||||
}
|
||||
|
||||
const updated = await readJournalEntry(targetSlug);
|
||||
return NextResponse.json({ success: true, entry: updated });
|
||||
} catch (err) {
|
||||
console.error(`[Admin API] Failed to update journal entry "${slug}":`, err);
|
||||
return NextResponse.json({ error: 'Failed to update journal entry' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, context: RouteContext) {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
if (!(await isAdminAuthenticated())) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { slug } = await context.params;
|
||||
if (!isValidSlug(slug)) {
|
||||
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const deleted = await deleteJournalEntry(slug);
|
||||
if (!deleted) {
|
||||
return NextResponse.json({ error: 'Journal entry not found' }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ success: true, deletedSlug: slug });
|
||||
} catch (err) {
|
||||
console.error(`[Admin API] Failed to delete journal entry "${slug}":`, err);
|
||||
return NextResponse.json({ error: 'Failed to delete journal entry' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
75
app/api/admin/journal/route.ts
Normal file
75
app/api/admin/journal/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
|
||||
import {
|
||||
sanitizeSlug,
|
||||
isValidSlug,
|
||||
type JournalFrontmatter,
|
||||
} from '@/lib/journal';
|
||||
import {
|
||||
listJournalEntries,
|
||||
writeJournalEntry,
|
||||
readJournalEntry,
|
||||
} from '@/lib/admin/journal-service';
|
||||
|
||||
export async function GET() {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
if (!(await isAdminAuthenticated())) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = await listJournalEntries();
|
||||
return NextResponse.json({ entries });
|
||||
} catch (err) {
|
||||
console.error('[Admin API] Failed to list journal entries:', err);
|
||||
return NextResponse.json({ error: 'Failed to list journal entries' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
if (!(await isAdminAuthenticated())) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const rawTitle = typeof body.title === 'string' ? body.title.trim() : 'Untitled';
|
||||
const slug = sanitizeSlug(typeof body.slug === 'string' && body.slug ? body.slug : rawTitle);
|
||||
|
||||
if (!isValidSlug(slug)) {
|
||||
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
|
||||
}
|
||||
|
||||
const existing = await readJournalEntry(slug);
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: 'A journal entry with this slug already exists' }, { status: 409 });
|
||||
}
|
||||
|
||||
const frontmatter: JournalFrontmatter = {
|
||||
title: rawTitle,
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
draft: true,
|
||||
...(typeof body.subtitle === 'string' && body.subtitle ? { subtitle: body.subtitle } : {}),
|
||||
...(typeof body.author === 'string' && body.author ? { author: body.author } : {}),
|
||||
...(typeof body.coverAssetId === 'string' && body.coverAssetId ? { coverAssetId: body.coverAssetId } : {}),
|
||||
};
|
||||
|
||||
let initialMarkdown = body.content;
|
||||
if (typeof initialMarkdown !== 'string' || !initialMarkdown) {
|
||||
initialMarkdown = `---\ntitle: "${frontmatter.title}"\ndate: "${frontmatter.date}"\ndraft: true\n---\n\nWrite your story here...`;
|
||||
}
|
||||
|
||||
await writeJournalEntry(slug, initialMarkdown);
|
||||
const created = await readJournalEntry(slug);
|
||||
|
||||
return NextResponse.json({ success: true, entry: created }, { status: 201 });
|
||||
} catch (err) {
|
||||
console.error('[Admin API] Failed to create journal entry:', err);
|
||||
return NextResponse.json({ error: 'Failed to create journal entry' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -46,14 +46,15 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'Invalid password format or length' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (type !== 'subpage' && type !== 'album') {
|
||||
if (type !== 'subpage' && type !== 'album' && type !== 'journal') {
|
||||
return NextResponse.json({ error: 'Invalid type' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!isProtected(slug, type)) {
|
||||
const typeLabel = type === 'journal' ? 'Journal entry' : type === 'subpage' ? 'Subpage' : 'Album';
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `${type === 'subpage' ? 'Subpage' : 'Album'} is not password-protected`,
|
||||
error: `${typeLabel} is not password-protected`,
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
|
||||
48
app/api/favicon/route.ts
Normal file
48
app/api/favicon/route.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const PUBLIC_DIR = path.resolve(process.cwd(), 'public');
|
||||
const CONTENT_DIR = path.resolve(process.cwd(), 'content');
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
// Prefer the uploaded favicon in content/ (writable, mounted volume).
|
||||
// Fall back to the bundled default in public/.
|
||||
let filePath = path.join(CONTENT_DIR, 'favicon.svg');
|
||||
let stat;
|
||||
try {
|
||||
stat = await fs.stat(filePath);
|
||||
} catch {
|
||||
filePath = path.join(PUBLIC_DIR, 'favicon.svg');
|
||||
try {
|
||||
stat = await fs.stat(filePath);
|
||||
} catch {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
}
|
||||
|
||||
// The URL is fixed but its content is not — an upload replaces the file in
|
||||
// place. A far-future `immutable` would hide the new icon for as long as the
|
||||
// browser kept the old one, so revalidate every time and answer with a 304
|
||||
// when nothing changed. The ETag is derived from the file itself, so it moves
|
||||
// the moment the admin uploads a new one.
|
||||
const etag = `"${stat.mtimeMs.toString(36)}-${stat.size.toString(36)}"`;
|
||||
const headers = {
|
||||
'Content-Type': 'image/svg+xml',
|
||||
'Cache-Control': 'public, max-age=0, must-revalidate',
|
||||
ETag: etag,
|
||||
// /api routes are excluded from the CSP nonce in proxy.ts, so the
|
||||
// response must carry its own policy. An uploaded SVG must not be
|
||||
// allowed to execute script on the origin.
|
||||
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||
};
|
||||
|
||||
if (request.headers.get('if-none-match') === etag) {
|
||||
return new NextResponse(null, { status: 304, headers });
|
||||
}
|
||||
|
||||
const buf = await fs.readFile(filePath);
|
||||
return new NextResponse(new Uint8Array(buf), { status: 200, headers });
|
||||
}
|
||||
91
app/api/install/albums/route.ts
Normal file
91
app/api/install/albums/route.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { isInstalled, normalizeApiBase, validateSetupToken } from '@/lib/install';
|
||||
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
|
||||
|
||||
/** Album discovery attempts per minute per IP — only live before install. */
|
||||
const INSTALL_ALBUMS_RPM = 30;
|
||||
|
||||
interface AlbumSummary {
|
||||
id: string;
|
||||
albumName: string;
|
||||
description: string;
|
||||
assetCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: list shared Immich albums for the wizard's picker, using the
|
||||
* credentials the user just typed. The configured Immich client cannot be used
|
||||
* here — it reads getConfig(), which is still in setup mode.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
if (isInstalled()) {
|
||||
return NextResponse.json({ error: 'Setup is already complete' }, { status: 403 });
|
||||
}
|
||||
|
||||
const token = request.nextUrl.searchParams.get('token') ?? request.headers.get('x-setup-token');
|
||||
if (!validateSetupToken(token)) {
|
||||
return NextResponse.json({ error: 'Invalid or missing setup token' }, { status: 403 });
|
||||
}
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const rl = checkRateLimit(`install-albums:${ip}`, INSTALL_ALBUMS_RPM);
|
||||
if (!rl.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many requests' },
|
||||
{
|
||||
status: 429,
|
||||
headers: { 'Retry-After': String(retryAfterSeconds(rl.resetAt)) },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const apiUrl = typeof body?.apiUrl === 'string' ? body.apiUrl.trim() : '';
|
||||
const apiKey = typeof body?.apiKey === 'string' ? body.apiKey.trim() : '';
|
||||
|
||||
if (!apiUrl || !apiKey) {
|
||||
return NextResponse.json({ error: 'Immich URL and API key are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const apiBase = normalizeApiBase(apiUrl);
|
||||
if (!apiBase) {
|
||||
return NextResponse.json({ error: 'Invalid Immich URL' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${apiBase}/albums?shared=true`, {
|
||||
headers: {
|
||||
'x-api-key': apiKey,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: `Immich returned HTTP ${res.status} — check the URL and API key` },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('Content-Type') || '';
|
||||
if (!contentType.includes('application/json')) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Immich returned a non-JSON response — is the URL a server base URL?' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
const albums = (await res.json()) as AlbumSummary[];
|
||||
return NextResponse.json({
|
||||
albums: albums.map((album) => ({
|
||||
id: album.id,
|
||||
albumName: album.albumName,
|
||||
assetCount: album.assetCount,
|
||||
description: album.description || '',
|
||||
})),
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Could not reach Immich at this URL' }, { status: 502 });
|
||||
}
|
||||
}
|
||||
116
app/api/install/route.ts
Normal file
116
app/api/install/route.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { completeInstall, isInstalled, normalizeApiBase, validateSetupToken } from '@/lib/install';
|
||||
import { invalidateConfigCache } from '@/lib/config';
|
||||
import { immich } from '@/lib/immich';
|
||||
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
|
||||
|
||||
/** Install submissions per minute per IP — only live before install. */
|
||||
const INSTALL_RPM = 10;
|
||||
|
||||
const THEME_PRESETS = [
|
||||
'studio',
|
||||
'studio-modern',
|
||||
'minimal',
|
||||
'editorial',
|
||||
'classic',
|
||||
'noir',
|
||||
'monograph',
|
||||
];
|
||||
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
/** POST: run the install wizard's final step — verify, then write config. */
|
||||
export async function POST(request: NextRequest) {
|
||||
if (isInstalled()) {
|
||||
return NextResponse.json({ error: 'Setup is already complete' }, { status: 403 });
|
||||
}
|
||||
|
||||
const token = request.nextUrl.searchParams.get('token') ?? request.headers.get('x-setup-token');
|
||||
if (!validateSetupToken(token)) {
|
||||
return NextResponse.json({ error: 'Invalid or missing setup token' }, { status: 403 });
|
||||
}
|
||||
|
||||
const ip = getClientIp(request);
|
||||
const rl = checkRateLimit(`install:${ip}`, INSTALL_RPM);
|
||||
if (!rl.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many requests' },
|
||||
{
|
||||
status: 429,
|
||||
headers: { 'Retry-After': String(retryAfterSeconds(rl.resetAt)) },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ error: 'Missing request body' }, { status: 400 });
|
||||
}
|
||||
|
||||
const apiUrl = typeof body.apiUrl === 'string' ? body.apiUrl.trim() : '';
|
||||
const apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
|
||||
if (!apiUrl || !apiKey) {
|
||||
return NextResponse.json({ error: 'Immich URL and API key are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const apiBase = normalizeApiBase(apiUrl);
|
||||
if (!apiBase) {
|
||||
return NextResponse.json({ error: 'Invalid Immich URL' }, { status: 400 });
|
||||
}
|
||||
|
||||
const theme = THEME_PRESETS.includes(body.theme) ? body.theme : 'studio';
|
||||
|
||||
// Album selection is optional: an empty gallery is a valid install.
|
||||
const rawAlbums: unknown[] = Array.isArray(body.albums) ? (body.albums as unknown[]) : [];
|
||||
const albums: string[] = rawAlbums
|
||||
.filter((id): id is string => typeof id === 'string' && UUID_REGEX.test(id.trim()))
|
||||
.map((id) => id.trim());
|
||||
|
||||
let adminPassword = '';
|
||||
if (typeof body.adminPassword === 'string' && body.adminPassword.length > 0) {
|
||||
adminPassword = body.adminPassword;
|
||||
if (adminPassword.length > 1024) {
|
||||
return NextResponse.json({ error: 'Admin password is too long' }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the credentials against Immich before writing anything, so a typo
|
||||
// does not produce an "installed" app that cannot load a single photo.
|
||||
try {
|
||||
const res = await fetch(`${apiBase}/server/ping`, {
|
||||
headers: { 'x-api-key': apiKey, Accept: 'application/json' },
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: `Immich rejected the connection (HTTP ${res.status})` },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Could not reach Immich at this URL' }, { status: 502 });
|
||||
}
|
||||
|
||||
try {
|
||||
await completeInstall({
|
||||
apiUrl,
|
||||
apiKey,
|
||||
siteTitle: typeof body.siteTitle === 'string' ? body.siteTitle : undefined,
|
||||
siteSubtitle: typeof body.siteSubtitle === 'string' ? body.siteSubtitle : undefined,
|
||||
theme,
|
||||
albums,
|
||||
adminPassword,
|
||||
});
|
||||
|
||||
// The wizard wrote new YAML; the running process must not keep serving
|
||||
// setup mode. The install.json mtime cache is dropped inside completeInstall.
|
||||
invalidateConfigCache();
|
||||
immich.invalidateAll();
|
||||
revalidatePath('/', 'layout');
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('[Install] Failed to write configuration files:', err);
|
||||
return NextResponse.json({ error: 'Failed to write configuration files' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1210,8 +1210,7 @@
|
||||
border: 1px solid var(--border-subtle);
|
||||
background: var(--bg-card);
|
||||
color: var(--text-secondary);
|
||||
font-size: 1.1rem;
|
||||
font-weight: 300;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -1227,6 +1226,26 @@
|
||||
color var(--transition-fast);
|
||||
}
|
||||
|
||||
.scroll-to-top__icon {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
transition: transform var(--transition-fast);
|
||||
}
|
||||
|
||||
.scroll-to-top:hover .scroll-to-top__icon {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.scroll-to-top__icon {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.scroll-to-top:hover .scroll-to-top__icon {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.scroll-to-top--visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
|
||||
458
app/install/InstallWizard.tsx
Normal file
458
app/install/InstallWizard.tsx
Normal file
@@ -0,0 +1,458 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useMemo, useState } from 'react';
|
||||
import '../admin/admin.css';
|
||||
import './install.css';
|
||||
|
||||
interface Album {
|
||||
id: string;
|
||||
albumName: string;
|
||||
assetCount: number;
|
||||
description: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
initialApiUrl: string;
|
||||
setupToken: string;
|
||||
}
|
||||
|
||||
const STEPS = ['Connect', 'Albums', 'Site', 'Finish'] as const;
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{ value: 'studio', label: 'Studio', description: 'Classic portfolio, red accent' },
|
||||
{ value: 'studio-modern', label: 'Studio Modern', description: 'Clean with soft corners' },
|
||||
{ value: 'minimal', label: 'Minimal', description: 'Bare-bones, monochrome' },
|
||||
{ value: 'editorial', label: 'Editorial', description: 'Magazine-style serif' },
|
||||
{ value: 'classic', label: 'Classic', description: 'Warm gold, traditional' },
|
||||
{ value: 'noir', label: 'Noir', description: 'Dark, high-contrast' },
|
||||
{ value: 'monograph', label: 'Monograph', description: 'Typographic, text-first' },
|
||||
];
|
||||
|
||||
export function InstallWizard({ initialApiUrl, setupToken }: Props) {
|
||||
const [step, setStep] = useState(0);
|
||||
|
||||
// Step 1 — connection
|
||||
const [apiUrl, setApiUrl] = useState(initialApiUrl);
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [testError, setTestError] = useState('');
|
||||
|
||||
// Step 2 — album selection (optional)
|
||||
const [albums, setAlbums] = useState<Album[]>([]);
|
||||
const [selected, setSelected] = useState<Record<string, boolean>>({});
|
||||
const [search, setSearch] = useState('');
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
|
||||
// Step 3 — site settings
|
||||
const [siteTitle, setSiteTitle] = useState('');
|
||||
const [siteSubtitle, setSiteSubtitle] = useState('');
|
||||
const [theme, setTheme] = useState('studio');
|
||||
const [adminPassword, setAdminPassword] = useState('');
|
||||
const [adminConfirm, setAdminConfirm] = useState('');
|
||||
const [passwordError, setPasswordError] = useState('');
|
||||
|
||||
// Step 4 — finish
|
||||
const [installing, setInstalling] = useState(false);
|
||||
const [installError, setInstallError] = useState('');
|
||||
const [done, setDone] = useState(false);
|
||||
|
||||
const selectedCount = Object.values(selected).filter(Boolean).length;
|
||||
|
||||
const filteredAlbums = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
if (!q) return albums;
|
||||
return albums.filter((a) => a.albumName.toLowerCase().includes(q));
|
||||
}, [albums, search]);
|
||||
|
||||
async function testConnection() {
|
||||
setTesting(true);
|
||||
setTestError('');
|
||||
try {
|
||||
const res = await fetch('/api/install/albums', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'x-setup-token': setupToken },
|
||||
body: JSON.stringify({ apiUrl: apiUrl.trim(), apiKey: apiKey.trim() }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
setTestError(data.error || 'Could not connect to Immich');
|
||||
return;
|
||||
}
|
||||
setAlbums(data.albums || []);
|
||||
setLoaded(true);
|
||||
setStep(1);
|
||||
} catch {
|
||||
setTestError('Could not reach the install service');
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleAlbum(id: string) {
|
||||
setSelected((prev) => ({ ...prev, [id]: !prev[id] }));
|
||||
}
|
||||
|
||||
function validateSiteStep(): boolean {
|
||||
if (adminPassword && adminPassword !== adminConfirm) {
|
||||
setPasswordError('Passwords do not match');
|
||||
return false;
|
||||
}
|
||||
setPasswordError('');
|
||||
return true;
|
||||
}
|
||||
|
||||
async function runInstall() {
|
||||
setInstalling(true);
|
||||
setInstallError('');
|
||||
try {
|
||||
const res = await fetch('/api/install', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'x-setup-token': setupToken },
|
||||
body: JSON.stringify({
|
||||
apiUrl: apiUrl.trim(),
|
||||
apiKey: apiKey.trim(),
|
||||
siteTitle,
|
||||
siteSubtitle,
|
||||
theme,
|
||||
albums: Object.keys(selected).filter((id) => selected[id]),
|
||||
...(adminPassword ? { adminPassword } : {}),
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
setInstallError(data.error || 'Install failed');
|
||||
return;
|
||||
}
|
||||
setDone(true);
|
||||
} catch {
|
||||
setInstallError('Could not reach the install service');
|
||||
} finally {
|
||||
setInstalling(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (done) {
|
||||
return (
|
||||
<div className="admin-layout">
|
||||
<div className="install-page">
|
||||
<div className="install-card">
|
||||
<div className="install-card__header">
|
||||
<span className="install-card__kicker">Immich Folio</span>
|
||||
<h1>Install complete</h1>
|
||||
<p>Your portfolio is ready. Add or rearrange albums any time from the admin panel.</p>
|
||||
</div>
|
||||
{/* install-body carries the card's padding — every other step
|
||||
renders inside it, and skipping it here left the buttons
|
||||
flush against the bottom edge. */}
|
||||
<div className="install-body">
|
||||
<div className="install-actions">
|
||||
<Link className="admin-btn admin-btn-primary" href="/">
|
||||
Visit your gallery
|
||||
</Link>
|
||||
{adminPassword && (
|
||||
<Link className="admin-btn" href="/admin">
|
||||
Open admin panel
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-layout">
|
||||
<div className="install-page">
|
||||
<div className="install-card">
|
||||
<div className="install-card__header">
|
||||
<span className="install-card__kicker">Immich Folio</span>
|
||||
<h1>Install wizard</h1>
|
||||
<p>Connect your Immich server, choose what to show, and publish your portfolio.</p>
|
||||
</div>
|
||||
|
||||
<ol className="install-steps" aria-label="Install steps">
|
||||
{STEPS.map((label, i) => (
|
||||
<li key={label} className={i < step ? 'is-done' : i === step ? 'is-active' : ''}>
|
||||
<span className="install-steps__dot">{i < step ? '✓' : i + 1}</span>
|
||||
<span className="install-steps__label">{label}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
<div className="install-body">
|
||||
{step === 0 && (
|
||||
<form
|
||||
className="install-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
testConnection();
|
||||
}}
|
||||
>
|
||||
<div className="admin-field">
|
||||
<label htmlFor="install-url">Immich server URL</label>
|
||||
<input
|
||||
id="install-url"
|
||||
type="url"
|
||||
value={apiUrl}
|
||||
onChange={(e) => setApiUrl(e.target.value)}
|
||||
placeholder="https://photos.example.com"
|
||||
required
|
||||
autoFocus
|
||||
disabled={testing}
|
||||
/>
|
||||
<p className="admin-hint">
|
||||
The base URL of your Immich instance (no /api). Example:{' '}
|
||||
<code>https://photos.example.com</code>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="admin-field">
|
||||
<label htmlFor="install-key">Immich API key</label>
|
||||
<input
|
||||
id="install-key"
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="Your Immich API key"
|
||||
required
|
||||
disabled={testing}
|
||||
/>
|
||||
<p className="admin-hint">
|
||||
Create one in Immich under Admin Settings → API Keys.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{testError && <div className="admin-error">{testError}</div>}
|
||||
|
||||
<div className="install-actions">
|
||||
<button
|
||||
type="submit"
|
||||
className="admin-btn admin-btn-primary"
|
||||
disabled={testing || !apiUrl || !apiKey}
|
||||
>
|
||||
{testing ? 'Testing connection…' : 'Test connection & continue'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === 1 && (
|
||||
<div className="install-albums">
|
||||
<p className="admin-hint">
|
||||
Pick albums to publish. This step is <strong>optional</strong> — you can add
|
||||
albums later from the admin panel.
|
||||
</p>
|
||||
|
||||
{albums.length === 0 ? (
|
||||
<div className="install-empty">
|
||||
<p>
|
||||
{loaded
|
||||
? 'No shared albums found on this Immich server.'
|
||||
: 'Albums could not be loaded.'}
|
||||
</p>
|
||||
<p className="admin-hint">
|
||||
Immich only lists albums that have been shared. You can still continue and add
|
||||
them later.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="admin-field">
|
||||
<input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search albums…"
|
||||
aria-label="Search albums"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ul className="install-albums__list">
|
||||
{filteredAlbums.map((album) => (
|
||||
<li key={album.id}>
|
||||
<label className="install-albums__item">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!!selected[album.id]}
|
||||
onChange={() => toggleAlbum(album.id)}
|
||||
/>
|
||||
<span className="install-albums__name">{album.albumName}</span>
|
||||
<span className="install-albums__meta">
|
||||
{album.assetCount} photo{album.assetCount === 1 ? '' : 's'}
|
||||
</span>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
{filteredAlbums.length === 0 && (
|
||||
<li className="install-empty">No albums match “{search}”.</li>
|
||||
)}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="install-actions">
|
||||
<button className="admin-btn" onClick={() => setStep(0)} disabled={installing}>
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
className="admin-btn admin-btn-primary"
|
||||
onClick={() => setStep(2)}
|
||||
disabled={installing}
|
||||
>
|
||||
{selectedCount > 0
|
||||
? `Continue with ${selectedCount} album${selectedCount === 1 ? '' : 's'}`
|
||||
: 'Skip — continue with no albums'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<form
|
||||
className="install-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (validateSiteStep()) setStep(3);
|
||||
}}
|
||||
>
|
||||
<div className="admin-field">
|
||||
<label htmlFor="install-title">Site title</label>
|
||||
<input
|
||||
id="install-title"
|
||||
type="text"
|
||||
value={siteTitle}
|
||||
onChange={(e) => setSiteTitle(e.target.value)}
|
||||
placeholder="My Photography"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="admin-field">
|
||||
<label htmlFor="install-subtitle">Subtitle</label>
|
||||
<input
|
||||
id="install-subtitle"
|
||||
type="text"
|
||||
value={siteSubtitle}
|
||||
onChange={(e) => setSiteSubtitle(e.target.value)}
|
||||
placeholder="A visual journal"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="admin-field">
|
||||
<label htmlFor="install-theme">Theme</label>
|
||||
<select
|
||||
id="install-theme"
|
||||
value={theme}
|
||||
onChange={(e) => setTheme(e.target.value)}
|
||||
>
|
||||
{THEME_OPTIONS.map((t) => (
|
||||
<option key={t.value} value={t.value}>
|
||||
{t.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="admin-hint">
|
||||
{THEME_OPTIONS.find((t) => t.value === theme)?.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="install-divider">
|
||||
<span>Optional — admin panel</span>
|
||||
</div>
|
||||
|
||||
<div className="admin-field">
|
||||
<label htmlFor="install-admin-password">Admin password</label>
|
||||
<input
|
||||
id="install-admin-password"
|
||||
type="password"
|
||||
value={adminPassword}
|
||||
onChange={(e) => setAdminPassword(e.target.value)}
|
||||
placeholder="Leave empty to disable the admin panel"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{adminPassword && (
|
||||
<div className="admin-field">
|
||||
<label htmlFor="install-admin-confirm">Repeat admin password</label>
|
||||
<input
|
||||
id="install-admin-confirm"
|
||||
type="password"
|
||||
value={adminConfirm}
|
||||
onChange={(e) => setAdminConfirm(e.target.value)}
|
||||
placeholder="Repeat the password"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{passwordError && <div className="admin-error">{passwordError}</div>}
|
||||
|
||||
<div className="install-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="admin-btn"
|
||||
onClick={() => setStep(1)}
|
||||
disabled={installing}
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
<button type="submit" className="admin-btn admin-btn-primary">
|
||||
Review install
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<div className="install-review">
|
||||
<dl className="install-review__list">
|
||||
<div>
|
||||
<dt>Immich server</dt>
|
||||
<dd>{apiUrl}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Albums</dt>
|
||||
<dd>
|
||||
{selectedCount > 0
|
||||
? `${selectedCount} selected`
|
||||
: 'None — you can add them later'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Site title</dt>
|
||||
<dd>{siteTitle || 'Gallery'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Theme</dt>
|
||||
<dd>{THEME_OPTIONS.find((t) => t.value === theme)?.label}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Admin panel</dt>
|
||||
<dd>{adminPassword ? 'Enabled' : 'Disabled'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{installError && <div className="admin-error">{installError}</div>}
|
||||
|
||||
<div className="install-actions">
|
||||
<button className="admin-btn" onClick={() => setStep(2)} disabled={installing}>
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
className="admin-btn admin-btn-primary"
|
||||
onClick={runInstall}
|
||||
disabled={installing}
|
||||
>
|
||||
{installing ? 'Installing…' : 'Install'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
280
app/install/install.css
Normal file
280
app/install/install.css
Normal file
@@ -0,0 +1,280 @@
|
||||
/* ── Install Wizard Styles ───────────────────────────────────── */
|
||||
/* Sits on top of the admin theme variables (.admin-layout scope). */
|
||||
|
||||
.install-page {
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem 1rem;
|
||||
}
|
||||
|
||||
.install-card {
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
background: var(--admin-bg-raised);
|
||||
border: 1px solid var(--admin-border);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.install-card__header {
|
||||
padding: 1.75rem 2rem 1.25rem;
|
||||
border-bottom: 1px solid var(--admin-border);
|
||||
}
|
||||
|
||||
.install-card__kicker {
|
||||
display: block;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.12em;
|
||||
color: var(--admin-accent);
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.install-card__header h1 {
|
||||
margin: 0 0 0.4rem;
|
||||
font-size: 1.5rem;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.install-card__header p {
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
color: var(--admin-text-secondary);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* ── Step indicator ──────────────────────────────────────────── */
|
||||
|
||||
.install-steps {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 1rem 2rem;
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
border-bottom: 1px solid var(--admin-border);
|
||||
}
|
||||
|
||||
.install-steps li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
color: var(--admin-text-muted);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.install-steps__dot {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.7rem;
|
||||
border: 1px solid var(--admin-border);
|
||||
background: var(--admin-bg-input);
|
||||
}
|
||||
|
||||
.install-steps li.is-active {
|
||||
color: var(--admin-text);
|
||||
}
|
||||
|
||||
.install-steps li.is-active .install-steps__dot {
|
||||
border-color: var(--admin-accent);
|
||||
color: var(--admin-accent);
|
||||
}
|
||||
|
||||
.install-steps li.is-done .install-steps__dot {
|
||||
background: var(--admin-accent);
|
||||
border-color: var(--admin-accent);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
/* ── Body ────────────────────────────────────────────────────── */
|
||||
|
||||
.install-body {
|
||||
padding: 1.5rem 2rem 2rem;
|
||||
}
|
||||
|
||||
.install-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.install-form .admin-field {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.admin-hint {
|
||||
font-size: 0.78rem;
|
||||
color: var(--admin-text-muted);
|
||||
margin: 0.35rem 0 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.admin-hint code {
|
||||
background: var(--admin-bg-elevated);
|
||||
padding: 0.1em 0.35em;
|
||||
border-radius: 4px;
|
||||
color: var(--admin-text-secondary);
|
||||
}
|
||||
|
||||
.install-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.6rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.install-actions .admin-btn {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* ── Albums ──────────────────────────────────────────────────── */
|
||||
|
||||
.install-albums__list {
|
||||
list-style: none;
|
||||
margin: 0.75rem 0 0;
|
||||
padding: 0;
|
||||
max-height: 320px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--admin-border);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.install-albums__list li + li {
|
||||
border-top: 1px solid var(--admin-border);
|
||||
}
|
||||
|
||||
.install-albums__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.install-albums__item:hover {
|
||||
background: var(--admin-bg-elevated);
|
||||
}
|
||||
|
||||
.install-albums__item input[type='checkbox'] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
accent-color: var(--admin-btn-primary-bg);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.install-albums__name {
|
||||
flex: 1;
|
||||
color: var(--admin-text);
|
||||
}
|
||||
|
||||
.install-albums__meta {
|
||||
font-size: 0.75rem;
|
||||
color: var(--admin-text-muted);
|
||||
}
|
||||
|
||||
.install-empty {
|
||||
padding: 0.75rem 0.5rem;
|
||||
color: var(--admin-text-muted);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.install-empty p {
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
|
||||
.install-empty .admin-hint {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ── Divider ─────────────────────────────────────────────────── */
|
||||
|
||||
.install-divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin: 0.75rem 0 1rem;
|
||||
color: var(--admin-text-muted);
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.install-divider::before,
|
||||
.install-divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--admin-border);
|
||||
}
|
||||
|
||||
/* ── Review ──────────────────────────────────────────────────── */
|
||||
|
||||
.install-review__list {
|
||||
margin: 0;
|
||||
border: 1px solid var(--admin-border);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.install-review__list > div {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
padding: 0.65rem 0.9rem;
|
||||
}
|
||||
|
||||
.install-review__list > div + div {
|
||||
border-top: 1px solid var(--admin-border);
|
||||
}
|
||||
|
||||
.install-review__list dt {
|
||||
flex: 0 0 120px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--admin-text-secondary);
|
||||
padding-top: 0.1rem;
|
||||
}
|
||||
|
||||
.install-review__list dd {
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
color: var(--admin-text);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* ── Responsive ──────────────────────────────────────────────── */
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.install-steps {
|
||||
padding: 0.85rem 1rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.install-steps__label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.install-body {
|
||||
padding: 1.25rem 1rem 1.5rem;
|
||||
}
|
||||
|
||||
.install-review__list > div {
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.install-review__list dt {
|
||||
flex: none;
|
||||
}
|
||||
}
|
||||
70
app/install/page.tsx
Normal file
70
app/install/page.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { redirect } from 'next/navigation';
|
||||
import {
|
||||
isInstalled,
|
||||
getInstallCredentials,
|
||||
getSetupToken,
|
||||
validateSetupToken,
|
||||
} from '@/lib/install';
|
||||
import { InstallWizard } from './InstallWizard';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Install Immich Folio',
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
/**
|
||||
* Rendered per request so the CSP nonce issued by proxy.ts lands on the script
|
||||
* tags — same reason /admin is force-dynamic. Also what lets the redirect once
|
||||
* setup is complete take effect on the next navigation, not a future build.
|
||||
*/
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function InstallPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ token?: string }>;
|
||||
}) {
|
||||
if (isInstalled()) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
const { token } = await searchParams;
|
||||
if (!validateSetupToken(token ?? null)) {
|
||||
// Force evaluation of the token so it is logged.
|
||||
getSetupToken();
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minHeight: '60dvh',
|
||||
padding: '2rem',
|
||||
fontFamily: 'system-ui, sans-serif',
|
||||
}}
|
||||
>
|
||||
<div style={{ maxWidth: '600px', width: '100%', textAlign: 'center' }}>
|
||||
<h1
|
||||
style={{
|
||||
fontSize: 'clamp(2rem, 5vw, 3rem)',
|
||||
fontWeight: 500,
|
||||
marginBottom: '0.5rem',
|
||||
letterSpacing: '-0.02em',
|
||||
}}
|
||||
>
|
||||
Setup Token Required
|
||||
</h1>
|
||||
<p style={{ fontSize: '1.125rem', opacity: 0.7, lineHeight: 1.5 }}>
|
||||
Check your server logs for the one-time setup token and append <code>?token=</code> to
|
||||
this URL.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const creds = getInstallCredentials();
|
||||
|
||||
return <InstallWizard initialApiUrl={creds.apiUrl} setupToken={token!} />;
|
||||
}
|
||||
203
app/journal/[slug]/page.tsx
Normal file
203
app/journal/[slug]/page.tsx
Normal file
@@ -0,0 +1,203 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { cookies } from 'next/headers';
|
||||
import type { Metadata } from 'next';
|
||||
import { readJournalEntry } from '@/lib/admin/journal-service';
|
||||
import type { ParsedJournal } from '@/lib/journal';
|
||||
import { isAdminAuthenticated } from '@/lib/admin/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { immich } from '@/lib/immich';
|
||||
import {
|
||||
imageUrl,
|
||||
exifUrl,
|
||||
assetPlaceholder,
|
||||
assetAspectRatio,
|
||||
assetExifSummary,
|
||||
} from '@/lib/urls';
|
||||
import { encodeAssetId } from '@/lib/tokens';
|
||||
import { EssayView } from '@/app/[...path]/EssayView';
|
||||
import type { PhotoItem } from '@/app/[...path]/PhotoGrid';
|
||||
import type { ImmichAsset } from '@/lib/immich';
|
||||
import PasswordGate from '@/components/PasswordGate';
|
||||
import { BackLink } from '@/components/BackLink';
|
||||
import { verifyScrypt, isScryptHash } from '@/lib/password';
|
||||
import crypto from 'crypto';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
interface JournalDetailPageProps {
|
||||
params: Promise<{ slug: string }>;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: JournalDetailPageProps): Promise<Metadata> {
|
||||
const { slug } = await params;
|
||||
const entry = await readJournalEntry(slug);
|
||||
if (!entry) return { title: 'Not Found' };
|
||||
|
||||
const { frontmatter } = entry.parsed;
|
||||
const title = frontmatter.title || slug;
|
||||
const description = frontmatter.subtitle || 'Journal entry on Immich Folio';
|
||||
|
||||
const ogImages = frontmatter.coverAssetId
|
||||
? [{ url: imageUrl(frontmatter.coverAssetId, 'preview') }]
|
||||
: [];
|
||||
|
||||
return {
|
||||
title,
|
||||
description,
|
||||
openGraph: {
|
||||
title,
|
||||
description,
|
||||
images: ogImages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Check if journal entry password cookie is valid */
|
||||
function isJournalAuthenticated(
|
||||
slug: string,
|
||||
storedPassword?: string,
|
||||
cookieVal?: string,
|
||||
): boolean {
|
||||
if (!storedPassword) return true;
|
||||
if (!cookieVal) return false;
|
||||
|
||||
const sep = cookieVal.indexOf('.');
|
||||
if (sep === -1) return false;
|
||||
|
||||
const expiresAt = Number(cookieVal.slice(0, sep));
|
||||
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return false;
|
||||
|
||||
const hmac = crypto
|
||||
.createHmac('sha256', getConfig().authSecret)
|
||||
.update(`${slug}:${storedPassword}:${expiresAt}`)
|
||||
.digest('hex');
|
||||
|
||||
const expected = `${expiresAt}.${hmac}`;
|
||||
try {
|
||||
const a = Buffer.from(cookieVal, 'utf8');
|
||||
const b = Buffer.from(expected, 'utf8');
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default async function JournalDetailPage({ params }: JournalDetailPageProps) {
|
||||
const { slug } = await params;
|
||||
const entry = await readJournalEntry(slug);
|
||||
|
||||
if (!entry) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const { frontmatter, blocks, referencedAssetIds } = entry.parsed;
|
||||
const isAuthedAdmin = await isAdminAuthenticated();
|
||||
|
||||
// If draft, only visible to authenticated admin
|
||||
if (frontmatter.draft && !isAuthedAdmin) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Password protection check
|
||||
if (frontmatter.password) {
|
||||
const cookieStore = await cookies();
|
||||
const cookieVal = cookieStore.get(`lb_auth_journal_${slug}`)?.value;
|
||||
|
||||
if (!isJournalAuthenticated(slug, frontmatter.password, cookieVal)) {
|
||||
return <PasswordGate slug={slug} title={frontmatter.title || slug} type="journal" />;
|
||||
}
|
||||
}
|
||||
|
||||
const config = getConfig();
|
||||
|
||||
// Fetch all referenced assets from Immich
|
||||
const assetPromises = referencedAssetIds.map(async (assetId) => {
|
||||
try {
|
||||
const asset = await immich.getAssetInfo(assetId);
|
||||
return asset;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
const rawAssets = (await Promise.all(assetPromises)).filter((a): a is ImmichAsset => a !== null);
|
||||
|
||||
// EssayView drops photo blocks it cannot resolve, which is right for visitors
|
||||
// but leaves no trace of *why* a photo vanished. Legacy positional references
|
||||
// ("1", "2") are the usual cause: they only resolved against a subpage album,
|
||||
// and a standalone journal entry has none.
|
||||
if (rawAssets.length < referencedAssetIds.length) {
|
||||
const resolved = new Set(rawAssets.map((a) => a.id));
|
||||
const missing = referencedAssetIds.filter((id) => !resolved.has(id));
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
`[journal] ${slug}: ${missing.length} photo reference(s) could not be resolved and will not render: ${missing.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
* EssayView resolves a block's photo through PhotoItem.id, and those ids are
|
||||
* encrypted tokens — while the blocks coming out of the Markdown carry raw
|
||||
* asset UUIDs. Without this translation every photo block fails its lookup and
|
||||
* is dropped, so a correctly authored entry renders text only. Doing it here
|
||||
* also keeps raw UUIDs out of the client payload, per the project rule that
|
||||
* they must never reach the browser. Unresolvable references collapse to an
|
||||
* empty string, which EssayView skips.
|
||||
*/
|
||||
const tokenByAssetId = new Map(rawAssets.map((a) => [a.id, encodeAssetId(a.id)]));
|
||||
const toToken = (assetId: string) => tokenByAssetId.get(assetId) ?? '';
|
||||
|
||||
const essayForClient: ParsedJournal = {
|
||||
frontmatter: {
|
||||
...frontmatter,
|
||||
coverAssetId: frontmatter.coverAssetId ? toToken(frontmatter.coverAssetId) : undefined,
|
||||
},
|
||||
blocks: blocks.map((block) => {
|
||||
if (block.type === 'photo') {
|
||||
return { ...block, assetId: toToken(block.assetId) };
|
||||
}
|
||||
if (block.type === 'photo-pair') {
|
||||
return {
|
||||
...block,
|
||||
assetIds: [toToken(block.assetIds[0]), toToken(block.assetIds[1])] as [string, string],
|
||||
};
|
||||
}
|
||||
return block;
|
||||
}),
|
||||
referencedAssetIds: rawAssets.map((a) => encodeAssetId(a.id)),
|
||||
};
|
||||
|
||||
const images: PhotoItem[] = rawAssets
|
||||
.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO')
|
||||
.map((a) => {
|
||||
const ph = assetPlaceholder(a);
|
||||
const exif = config.exifOnHover && a.type === 'IMAGE' ? assetExifSummary(a) : undefined;
|
||||
const isVideo = a.type === 'VIDEO';
|
||||
return {
|
||||
id: encodeAssetId(a.id),
|
||||
type: isVideo ? 'video' : 'image',
|
||||
thumbUrl: imageUrl(a.id, 'preview'),
|
||||
previewUrl: imageUrl(a.id, 'preview'),
|
||||
exifUrl: exifUrl(a.id),
|
||||
...(ph ? { blurDataURL: ph.blurDataURL, dominantColor: ph.dominantColor } : {}),
|
||||
...(exif ?? {}),
|
||||
aspectRatio: assetAspectRatio(a),
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div style={{ paddingTop: '2rem' }}>
|
||||
<div style={{ maxWidth: '1100px', margin: '0 auto', padding: '0 1.5rem 1rem' }}>
|
||||
<BackLink href="/journal" label="Back to Journal" />
|
||||
</div>
|
||||
<EssayView
|
||||
essay={essayForClient}
|
||||
assets={images}
|
||||
title={frontmatter.title}
|
||||
subtitle={frontmatter.subtitle}
|
||||
watermark={config.watermark}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
176
app/journal/journal.css
Normal file
176
app/journal/journal.css
Normal file
@@ -0,0 +1,176 @@
|
||||
/* ── Journal Index & Reader Styling ───────────────────────────── */
|
||||
|
||||
.journal-index-container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 3rem 1.5rem 6rem;
|
||||
}
|
||||
|
||||
.journal-index-header {
|
||||
margin-bottom: 3.5rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.journal-index-header__kicker {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.15em;
|
||||
opacity: 0.6;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.journal-index-header__title {
|
||||
font-size: clamp(2.2rem, 4.5vw, 3.5rem);
|
||||
font-weight: 700;
|
||||
line-height: 1.1;
|
||||
letter-spacing: -0.02em;
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.journal-index-header__subtitle {
|
||||
font-size: 1.1rem;
|
||||
opacity: 0.75;
|
||||
margin: 0;
|
||||
max-width: 600px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.journal-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
|
||||
gap: 2.5rem;
|
||||
}
|
||||
|
||||
.journal-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
background: var(--surface, rgba(255, 255, 255, 0.03));
|
||||
border: 1px solid var(--border, rgba(255, 255, 255, 0.08));
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
transition: transform 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease;
|
||||
}
|
||||
|
||||
.journal-card:hover {
|
||||
transform: translateY(-4px);
|
||||
border-color: var(--border-hover, rgba(255, 255, 255, 0.2));
|
||||
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.journal-card__cover {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 10;
|
||||
background: var(--surface-subtle, rgba(255, 255, 255, 0.02));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.journal-card__cover img {
|
||||
object-fit: cover;
|
||||
transition: transform 0.4s ease;
|
||||
}
|
||||
|
||||
.journal-card:hover .journal-card__cover img {
|
||||
transform: scale(1.03);
|
||||
}
|
||||
|
||||
.journal-card__cover-empty {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0.3;
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.journal-card__content {
|
||||
padding: 1.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.journal-card__meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
opacity: 0.6;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.journal-card__title {
|
||||
font-size: 1.35rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
margin: 0 0 0.5rem;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.journal-card__subtitle {
|
||||
font-size: 0.95rem;
|
||||
line-height: 1.45;
|
||||
opacity: 0.8;
|
||||
margin: 0 0 1rem;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.journal-card__excerpt {
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.5;
|
||||
opacity: 0.65;
|
||||
margin: 0 0 1.25rem;
|
||||
flex-grow: 1;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.journal-card__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--border, rgba(255, 255, 255, 0.06));
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.journal-card__read-more {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--accent, #6366f1);
|
||||
transition: gap 0.2s ease;
|
||||
}
|
||||
|
||||
.journal-card:hover .journal-card__read-more {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.journal-card__draft-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
background: rgba(234, 179, 8, 0.15);
|
||||
color: #eab308;
|
||||
border-radius: 4px;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.journal-empty-state {
|
||||
text-align: center;
|
||||
padding: 5rem 1rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
147
app/journal/page.tsx
Normal file
147
app/journal/page.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import type { Metadata } from 'next';
|
||||
import { type JournalEntrySummary } from '@/lib/journal';
|
||||
import { listJournalEntries } from '@/lib/admin/journal-service';
|
||||
import { isAdminAuthenticated } from '@/lib/admin/auth';
|
||||
import { immich } from '@/lib/immich';
|
||||
import { imageUrl, assetPlaceholder } from '@/lib/urls';
|
||||
import { BackLink } from '@/components/BackLink';
|
||||
import './journal.css';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Journal',
|
||||
description: 'Photo essays, travel stories, and behind-the-scenes journals.',
|
||||
};
|
||||
|
||||
interface EnrichedJournalEntry extends JournalEntrySummary {
|
||||
coverUrl?: string;
|
||||
blurDataURL?: string;
|
||||
dominantColor?: string;
|
||||
}
|
||||
|
||||
export default async function JournalIndexPage() {
|
||||
const isAuthedAdmin = await isAdminAuthenticated();
|
||||
const allEntries = await listJournalEntries();
|
||||
|
||||
// Non-admins only see published entries
|
||||
const visibleEntries = isAuthedAdmin
|
||||
? allEntries
|
||||
: allEntries.filter((e) => !e.frontmatter.draft);
|
||||
|
||||
// Fetch cover image placeholders and URLs
|
||||
const enrichedEntries: EnrichedJournalEntry[] = await Promise.all(
|
||||
visibleEntries.map(async (entry) => {
|
||||
if (!entry.frontmatter.coverAssetId) {
|
||||
return entry;
|
||||
}
|
||||
|
||||
try {
|
||||
const asset = await immich.getAssetInfo(entry.frontmatter.coverAssetId);
|
||||
const ph = asset ? assetPlaceholder(asset) : null;
|
||||
return {
|
||||
...entry,
|
||||
coverUrl: imageUrl(entry.frontmatter.coverAssetId, 'preview'),
|
||||
blurDataURL: ph?.blurDataURL,
|
||||
dominantColor: ph?.dominantColor,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
...entry,
|
||||
coverUrl: imageUrl(entry.frontmatter.coverAssetId, 'preview'),
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="journal-index-container">
|
||||
<div className="journal-index-header">
|
||||
<BackLink href="/" label="Back to Gallery" />
|
||||
<p className="journal-index-header__kicker" aria-hidden="true">
|
||||
Stories & Essays
|
||||
</p>
|
||||
<h1 className="journal-index-header__title">Journal</h1>
|
||||
<p className="journal-index-header__subtitle">
|
||||
Photo essays, visual stories, and field notes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{enrichedEntries.length === 0 ? (
|
||||
<div className="journal-empty-state">
|
||||
<p>No journal entries published yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="journal-grid">
|
||||
{enrichedEntries.map((entry) => {
|
||||
const dateStr = entry.frontmatter.date
|
||||
? new Date(entry.frontmatter.date).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Link key={entry.slug} href={`/journal/${entry.slug}`} className="journal-card">
|
||||
<div
|
||||
className="journal-card__cover"
|
||||
style={{
|
||||
...(entry.dominantColor ? { backgroundColor: entry.dominantColor } : {}),
|
||||
}}
|
||||
>
|
||||
{entry.coverUrl ? (
|
||||
<Image
|
||||
src={entry.coverUrl}
|
||||
alt={entry.frontmatter.title || entry.slug}
|
||||
fill
|
||||
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 380px"
|
||||
placeholder={entry.blurDataURL ? 'blur' : 'empty'}
|
||||
blurDataURL={entry.blurDataURL}
|
||||
/>
|
||||
) : (
|
||||
<div className="journal-card__cover-empty">📖</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="journal-card__content">
|
||||
<div className="journal-card__meta">
|
||||
{dateStr && <span>{dateStr}</span>}
|
||||
{dateStr && entry.readingTimeMinutes && <span>•</span>}
|
||||
{entry.readingTimeMinutes && <span>{entry.readingTimeMinutes} min read</span>}
|
||||
{entry.frontmatter.draft && (
|
||||
<span className="journal-card__draft-badge">Draft</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h2 className="journal-card__title">{entry.frontmatter.title || entry.slug}</h2>
|
||||
|
||||
{entry.frontmatter.subtitle && (
|
||||
<p className="journal-card__subtitle">{entry.frontmatter.subtitle}</p>
|
||||
)}
|
||||
|
||||
{/*
|
||||
extractExcerpt() falls back to the subtitle when there is
|
||||
one, so rendering both printed the same sentence twice.
|
||||
*/}
|
||||
{entry.excerpt && entry.excerpt !== entry.frontmatter.subtitle && (
|
||||
<p className="journal-card__excerpt">{entry.excerpt}</p>
|
||||
)}
|
||||
|
||||
<div className="journal-card__footer">
|
||||
<span className="journal-card__read-more">Read Story →</span>
|
||||
{entry.frontmatter.author && (
|
||||
<span style={{ opacity: 0.65 }}>by {entry.frontmatter.author}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { Footer } from '@/components/Footer';
|
||||
import { SetupScreen } from '@/components/SetupScreen';
|
||||
import { getConfigOrNull, getGoogleFontsUrl, AppConfig } from '@/lib/config';
|
||||
import { isAdminPath } from '@/lib/admin/paths';
|
||||
import { isInstallPath } from '@/lib/install';
|
||||
// DevToolbarLoader is a Client Component (ssr: false is only allowed there)
|
||||
import { DevToolbarLoader } from '@/components/DevToolbarLoader';
|
||||
import AssetProtection from '@/components/AssetProtection';
|
||||
@@ -24,7 +25,11 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
const config = getConfigOrNull();
|
||||
if (!config) {
|
||||
// Nothing to describe, and nothing that should be indexed while broken.
|
||||
return { title: 'Setup Required', robots: { index: false, follow: false } };
|
||||
return {
|
||||
title: 'Setup Required',
|
||||
robots: { index: false, follow: false },
|
||||
icons: { icon: '/api/favicon' },
|
||||
};
|
||||
}
|
||||
|
||||
const siteTitle = config.seo.title;
|
||||
@@ -42,6 +47,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
description: siteDescription,
|
||||
robots,
|
||||
icons: {
|
||||
icon: '/api/favicon',
|
||||
apple: '/apple-touch-icon.png',
|
||||
},
|
||||
openGraph: {
|
||||
@@ -71,7 +77,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
if (!config) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body>{isAdminPath(pathname) ? children : <SetupScreen />}</body>
|
||||
<body>{isAdminPath(pathname) || isInstallPath(pathname) ? children : <SetupScreen />}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -90,9 +96,14 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
'--radius-lg': `${theme.radius * 2}px`,
|
||||
};
|
||||
|
||||
// /admin stays reachable during setup — it is the tool that completes the
|
||||
// setup, so the setup screen must not lock it out (#326).
|
||||
if ((config as AppConfig & { needsSetup?: boolean }).needsSetup && !isAdminPath(pathname)) {
|
||||
// /admin and /install stay reachable during setup — /admin is the tool that
|
||||
// completes an existing setup, /install is the wizard that performs the first
|
||||
// one, so the setup screen must not lock either of them out (#326).
|
||||
if (
|
||||
(config as AppConfig & { needsSetup?: boolean }).needsSetup &&
|
||||
!isAdminPath(pathname) &&
|
||||
!isInstallPath(pathname)
|
||||
) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body>
|
||||
@@ -153,7 +164,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
<ScrollToTop />
|
||||
{config.scrollToTop && <ScrollToTop />}
|
||||
<AssetProtection
|
||||
disableRightClick={config.protection?.disableRightClick}
|
||||
disableImageDrag={config.protection?.disableImageDrag}
|
||||
|
||||
Reference in New Issue
Block a user