security: add Trivy container scan to Docker publish workflow (#399)
* feat(admin): add backup manager UI with 1-click restore * feat(admin): collapse older backup entries by default * fix(theme): isolate admin layout, instant DOM theme updates, and add Light/Dark mode toggle * feat(admin): replace text controls for Photo Frame and Hero Style with visual preview cards * fix(admin): define missing CSS rules for button system (.btn, .preset-btn) * feat(admin): redesign theme settings with segmented mode toggle, accent color swatches, and custom iOS-style toggle cards * feat(admin): upgrade all settings tabs with visual grid previews, Google SEO snippet preview, and toggle cards * feat(admin): overhaul Pages Builder UX with slide-over drawer, card hover badges, real-time search, and floating save bar * fix(admin): remove leftover dangling syntax snippet in PageBuilder.tsx * fix(admin): add position: relative to subpage-tile so hover overlay is contained inside the tile * style(admin): replace all emojis with clean Leica-style vector SVG icons * fix(types): extend IconProps with SVGProps to allow style prop on Leica SVG icons * feat(admin): add subpage live-preview, privacy analytics, and asset protection settings * fix(typecheck): fix AlbumEntry property access in subpage drawer preview mode * fix(types): fix ImmichAlbumInfo property names thumbnailAssetId and albumName in PageBuilder.tsx * fix(types): add protection and watermark optional properties to AppConfig interface * feat(settings): add toggle for disabling analytics tracking (defaults to enabled) * feat(ux): show status banner when analytics tracking is disabled + add live sync indicator * feat(watermark): render customizable watermark overlay on Lightbox images + rename section to Portfolio Features & Modules * fix(types): import type LightboxWatermark in PhotoGrid.tsx * fix(types): destructure watermark prop in PhotoGrid function signature * feat(seo): add configurable subpage title template and metadata descriptions * feat(seo): add generateMetadata to about page for title template support * feat(proofing): add client proofing, favorites selection, compact URL bitmasking, and export modal * feat(essay): add Photo Essay storytelling mode with RSC markdown parser and fullbleed/pair layouts * feat(subpages): add page enabled toggle to deactivate subpages without deleting them * feat(admin): add visual essay block builder for photo essay storytelling pages * security: add Trivy container scan to Docker publish workflow Scans the built image for CRITICAL/HIGH CVEs on every release and uploads results to the GitHub Security tab. Non-blocking for now (exit-code 0) so releases aren't gated on findings. Also documents the scan and existing Dependabot coverage in the README. --------- Co-authored-by: ralksta <ralksta@users.noreply.github.com>
This commit is contained in:
@@ -103,4 +103,16 @@ describe('deriveGallery accepts valid structures', () => {
|
||||
expect(result.albumDescriptions[A]).toBe('A note');
|
||||
expect(result.albumHeroImages[A]).toBe(B);
|
||||
});
|
||||
|
||||
it('parses enabled property on subpages correctly', () => {
|
||||
const result = deriveGallery({
|
||||
subpages: [
|
||||
{ name: 'Active Page', albums: [A], enabled: true },
|
||||
{ name: 'Disabled Page', albums: [B], enabled: false },
|
||||
],
|
||||
} as unknown as GalleryYaml);
|
||||
|
||||
expect(result.subpages[0].enabled).toBe(true);
|
||||
expect(result.subpages[1].enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
120
lib/__tests__/essay.test.ts
Normal file
120
lib/__tests__/essay.test.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseEssayMarkdown, parseFrontmatter, sanitizeHtml, renderInlineMarkdown, serializeEssayMarkdown } from '../essay';
|
||||
|
||||
describe('Essay Parser', () => {
|
||||
it('sanitizes script tags to prevent XSS', () => {
|
||||
const input = 'Hello <script>alert("XSS")</script> World';
|
||||
expect(sanitizeHtml(input)).toBe('Hello World');
|
||||
});
|
||||
|
||||
it('renders inline markdown formatting correctly', () => {
|
||||
const text = 'This is **bold** and *italic* with a [link](https://example.com)';
|
||||
const rendered = renderInlineMarkdown(text);
|
||||
expect(rendered).toContain('<strong>bold</strong>');
|
||||
expect(rendered).toContain('<em>italic</em>');
|
||||
expect(rendered).toContain('<a href="https://example.com" target="_blank" rel="noopener noreferrer">link</a>');
|
||||
});
|
||||
|
||||
it('parses frontmatter correctly', () => {
|
||||
const markdown = `---
|
||||
title: "The Icelandic Highlands"
|
||||
subtitle: "A visual journey across black sand and glaciers"
|
||||
author: "Ralf"
|
||||
date: "2026-08-05"
|
||||
coverAssetId: "asset-123"
|
||||
---
|
||||
|
||||
# Section 1
|
||||
First paragraph text.`;
|
||||
|
||||
const { frontmatter, body } = parseFrontmatter(markdown);
|
||||
expect(frontmatter.title).toBe('The Icelandic Highlands');
|
||||
expect(frontmatter.subtitle).toBe('A visual journey across black sand and glaciers');
|
||||
expect(frontmatter.author).toBe('Ralf');
|
||||
expect(frontmatter.date).toBe('2026-08-05');
|
||||
expect(frontmatter.coverAssetId).toBe('asset-123');
|
||||
expect(body.trim()).toMatch(/^# Section 1/);
|
||||
});
|
||||
|
||||
it('parses structured essay blocks (headings, quotes, photos, photo-pairs)', () => {
|
||||
const markdown = `---
|
||||
title: "Test Story"
|
||||
---
|
||||
|
||||
# Highland Sunrise
|
||||
|
||||
> Silence was absolute across the tundra. -- Ralf
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
A closing paragraph with **bold** details.`;
|
||||
|
||||
const parsed = parseEssayMarkdown(markdown);
|
||||
expect(parsed.frontmatter.title).toBe('Test Story');
|
||||
expect(parsed.blocks.length).toBe(5);
|
||||
|
||||
// Block 0: Heading
|
||||
expect(parsed.blocks[0]).toEqual({
|
||||
type: 'heading',
|
||||
level: 1,
|
||||
text: 'Highland Sunrise',
|
||||
});
|
||||
|
||||
// Block 1: Quote
|
||||
expect(parsed.blocks[1]).toEqual({
|
||||
type: 'quote',
|
||||
text: 'Silence was absolute across the tundra.',
|
||||
author: 'Ralf',
|
||||
});
|
||||
|
||||
// Block 2: Fullbleed Photo
|
||||
expect(parsed.blocks[2]).toEqual({
|
||||
type: 'photo',
|
||||
assetId: 'asset-1',
|
||||
caption: 'Sunrise over the ridge',
|
||||
layout: 'fullbleed',
|
||||
});
|
||||
|
||||
// Block 3: Photo Pair
|
||||
expect(parsed.blocks[3]).toEqual({
|
||||
type: 'photo-pair',
|
||||
assetIds: ['asset-2', 'asset-3'],
|
||||
caption: 'Side-by-side details',
|
||||
});
|
||||
|
||||
// Block 4: Paragraph
|
||||
expect(parsed.blocks[4].type).toBe('paragraph');
|
||||
if (parsed.blocks[4].type === 'paragraph') {
|
||||
expect(parsed.blocks[4].html).toContain('<strong>bold</strong>');
|
||||
}
|
||||
|
||||
// Referenced Assets
|
||||
expect(parsed.referencedAssetIds).toContain('asset-1');
|
||||
expect(parsed.referencedAssetIds).toContain('asset-2');
|
||||
expect(parsed.referencedAssetIds).toContain('asset-3');
|
||||
});
|
||||
|
||||
it('serializes structured essay blocks back to markdown', () => {
|
||||
const parsed = {
|
||||
frontmatter: { title: 'Story Title', author: 'Author' },
|
||||
blocks: [
|
||||
{ type: 'heading' as const, level: 1, text: 'Chapter One' },
|
||||
{ type: 'paragraph' as const, html: 'This is <strong>bold</strong> text.' },
|
||||
{ type: 'quote' as const, text: 'A great quote', author: 'Person' },
|
||||
{ type: 'photo' as const, assetId: 'photo-1', caption: 'Caption', layout: 'fullbleed' as const },
|
||||
{ type: 'photo-pair' as const, assetIds: ['p1', 'p2'] as [string, string], caption: 'Pair caption' },
|
||||
],
|
||||
referencedAssetIds: ['photo-1', 'p1', 'p2'],
|
||||
};
|
||||
|
||||
const markdown = serializeEssayMarkdown(parsed);
|
||||
expect(markdown).toContain('title: "Story Title"');
|
||||
expect(markdown).toContain('# Chapter One');
|
||||
expect(markdown).toContain('This is **bold** text.');
|
||||
expect(markdown).toContain('> A great quote -- Person');
|
||||
expect(markdown).toContain('');
|
||||
expect(markdown).toContain('');
|
||||
});
|
||||
});
|
||||
38
lib/__tests__/proofing.test.ts
Normal file
38
lib/__tests__/proofing.test.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { encodeProofBitmask, decodeProofBitmask } from '../proofing';
|
||||
|
||||
describe('lib/proofing', () => {
|
||||
it('returns empty string for empty or invalid indices', () => {
|
||||
expect(encodeProofBitmask([])).toBe('');
|
||||
expect(encodeProofBitmask([-1])).toBe('');
|
||||
});
|
||||
|
||||
it('encodes and decodes simple asset indices', () => {
|
||||
const indices = [0, 3, 5, 12];
|
||||
const encoded = encodeProofBitmask(indices);
|
||||
expect(typeof encoded).toBe('string');
|
||||
expect(encoded.length).toBeGreaterThan(0);
|
||||
|
||||
const decoded = decodeProofBitmask(encoded);
|
||||
expect(decoded).toEqual([0, 3, 5, 12]);
|
||||
});
|
||||
|
||||
it('handles duplicate and unsorted indices gracefully', () => {
|
||||
const indices = [15, 2, 2, 7, 0];
|
||||
const encoded = encodeProofBitmask(indices);
|
||||
const decoded = decodeProofBitmask(encoded);
|
||||
expect(decoded).toEqual([0, 2, 7, 15]);
|
||||
});
|
||||
|
||||
it('clamps indices to totalCount if provided', () => {
|
||||
const indices = [1, 5, 10];
|
||||
const encoded = encodeProofBitmask(indices);
|
||||
const decoded = decodeProofBitmask(encoded, 6);
|
||||
expect(decoded).toEqual([1, 5]);
|
||||
});
|
||||
|
||||
it('returns empty array for invalid bitmask strings', () => {
|
||||
expect(decodeProofBitmask('invalid-junk-!!!')).toEqual([]);
|
||||
expect(decodeProofBitmask('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -194,6 +194,10 @@ export function deriveGallery(gallery: GalleryYaml): GalleryDerivation {
|
||||
albumIds,
|
||||
sections,
|
||||
password: sp.password,
|
||||
proofing: sp.proofing,
|
||||
essayFile: sp.essayFile,
|
||||
essayText: sp.essayText,
|
||||
enabled: sp.enabled !== false,
|
||||
...buildSubpageGrid(sp.grid),
|
||||
};
|
||||
});
|
||||
@@ -204,6 +208,7 @@ export function deriveGallery(gallery: GalleryYaml): GalleryDerivation {
|
||||
name,
|
||||
slug: slugify(name),
|
||||
albumIds: value.map((entry) => processAlbumEntry(entry, `subpage "${name}"`)),
|
||||
enabled: true,
|
||||
};
|
||||
}
|
||||
const sp = value as SubpageObjectValue;
|
||||
@@ -215,6 +220,10 @@ export function deriveGallery(gallery: GalleryYaml): GalleryDerivation {
|
||||
subtitle: sp.subtitle,
|
||||
albumIds: albumEntries.map((entry) => processAlbumEntry(entry, `subpage "${name}"`)),
|
||||
password: sp.password,
|
||||
proofing: sp.proofing,
|
||||
essayFile: sp.essayFile,
|
||||
essayText: sp.essayText,
|
||||
enabled: sp.enabled !== false,
|
||||
...buildSubpageGrid(sp.grid),
|
||||
};
|
||||
});
|
||||
@@ -260,6 +269,7 @@ export function getConfig(): AppConfig {
|
||||
seo: {
|
||||
title: 'Setup Required',
|
||||
description: 'Please configure Immich Folio',
|
||||
titleTemplate: '%s | Setup Required',
|
||||
noIndex: true,
|
||||
noFollow: true,
|
||||
},
|
||||
@@ -271,6 +281,8 @@ export function getConfig(): AppConfig {
|
||||
legal: { enabled: false, name: '', address: '', zipCity: '', country: '' },
|
||||
map: false,
|
||||
transitions: false,
|
||||
analytics: true,
|
||||
proofing: { enabled: false, allowMailto: false },
|
||||
albumOverrides: {},
|
||||
albumDescriptions: {},
|
||||
albumPasswords: {},
|
||||
@@ -296,6 +308,8 @@ export function getConfig(): AppConfig {
|
||||
albumHeroImages,
|
||||
} = deriveGallery(gallery);
|
||||
|
||||
const siteSeoTitle = settings.seo?.title || settings.title || env.SITE_TITLE || 'Gallery';
|
||||
|
||||
return {
|
||||
immich: { apiUrl: `${apiUrl}/api`, apiKey },
|
||||
authSecret,
|
||||
@@ -306,12 +320,13 @@ export function getConfig(): AppConfig {
|
||||
siteSubtitle: settings.subtitle ?? env.SITE_SUBTITLE,
|
||||
lang: settings.lang ?? 'en',
|
||||
seo: {
|
||||
title: settings.seo?.title || settings.title || env.SITE_TITLE || 'Gallery',
|
||||
title: siteSeoTitle,
|
||||
description:
|
||||
settings.seo?.description ||
|
||||
settings.subtitle ||
|
||||
env.SITE_SUBTITLE ||
|
||||
'A curated photography portfolio',
|
||||
titleTemplate: settings.seo?.titleTemplate || `%s | ${siteSeoTitle}`,
|
||||
noIndex: settings.seo?.noIndex === true,
|
||||
noFollow: settings.seo?.noFollow === true,
|
||||
},
|
||||
@@ -352,6 +367,13 @@ export function getConfig(): AppConfig {
|
||||
},
|
||||
map: settings.map === true,
|
||||
transitions: settings.transitions !== false,
|
||||
analytics: settings.analytics !== false,
|
||||
proofing: {
|
||||
enabled: settings.proofing?.enabled !== false,
|
||||
allowMailto: settings.proofing?.allowMailto !== false,
|
||||
},
|
||||
protection: settings.protection,
|
||||
watermark: settings.watermark,
|
||||
albumOverrides,
|
||||
albumDescriptions,
|
||||
albumPasswords,
|
||||
|
||||
@@ -14,6 +14,10 @@ export interface SubpageConfig {
|
||||
sections?: SubpageSectionConfig[];
|
||||
password?: string;
|
||||
grid?: Partial<GridConfig>;
|
||||
proofing?: boolean;
|
||||
essayFile?: string;
|
||||
essayText?: string;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface SubpageObjectValue {
|
||||
@@ -21,6 +25,10 @@ export interface SubpageObjectValue {
|
||||
subtitle?: string;
|
||||
password?: string;
|
||||
grid?: Partial<GridConfig>;
|
||||
proofing?: boolean;
|
||||
essayFile?: string;
|
||||
essayText?: string;
|
||||
enabled?: boolean;
|
||||
albums?: Array<
|
||||
string | Record<string, string | { title: string; description?: string; password?: string }>
|
||||
>;
|
||||
@@ -68,7 +76,7 @@ export interface GridConfig {
|
||||
columns: number;
|
||||
gap: number;
|
||||
aspectRatio: string;
|
||||
layout: 'masonry' | 'uniform' | 'showcase' | 'filmstrip' | 'editorial-flow';
|
||||
layout: 'masonry' | 'uniform' | 'showcase' | 'filmstrip' | 'editorial-flow' | 'essay';
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
@@ -83,6 +91,7 @@ export interface AppConfig {
|
||||
seo: {
|
||||
title: string;
|
||||
description: string;
|
||||
titleTemplate: string;
|
||||
noIndex: boolean;
|
||||
noFollow: boolean;
|
||||
};
|
||||
@@ -94,6 +103,11 @@ export interface AppConfig {
|
||||
legal: LegalConfig;
|
||||
map: boolean;
|
||||
transitions: boolean;
|
||||
analytics: boolean;
|
||||
proofing: {
|
||||
enabled: boolean;
|
||||
allowMailto: boolean;
|
||||
};
|
||||
albumOverrides: Record<string, string>;
|
||||
albumDescriptions: Record<string, string>;
|
||||
albumPasswords: Record<string, string>;
|
||||
@@ -106,6 +120,16 @@ export interface AppConfig {
|
||||
rateLimitRpm: number;
|
||||
trustedProxyHops: number;
|
||||
needsSetup?: boolean;
|
||||
protection?: {
|
||||
disableRightClick?: boolean;
|
||||
disableImageDrag?: boolean;
|
||||
};
|
||||
watermark?: {
|
||||
enabled?: boolean;
|
||||
text?: string;
|
||||
opacity?: number;
|
||||
position?: 'bottom-right' | 'bottom-left' | 'center';
|
||||
};
|
||||
}
|
||||
|
||||
export interface AlbumEntryObject {
|
||||
@@ -131,6 +155,10 @@ export interface GalleryYaml {
|
||||
albums: Array<string | Record<string, string | AlbumEntryObject>>;
|
||||
}>;
|
||||
password?: string;
|
||||
proofing?: boolean;
|
||||
essayFile?: string;
|
||||
essayText?: string;
|
||||
enabled?: boolean;
|
||||
grid?: {
|
||||
columns?: number;
|
||||
gap?: number;
|
||||
@@ -147,12 +175,18 @@ export interface SettingsYaml {
|
||||
seo?: {
|
||||
title?: string;
|
||||
description?: string;
|
||||
titleTemplate?: string;
|
||||
noIndex?: boolean;
|
||||
noFollow?: boolean;
|
||||
};
|
||||
exifOnHover?: boolean;
|
||||
map?: boolean;
|
||||
transitions?: boolean;
|
||||
analytics?: boolean;
|
||||
proofing?: {
|
||||
enabled?: boolean;
|
||||
allowMailto?: boolean;
|
||||
};
|
||||
theme?:
|
||||
| string
|
||||
| {
|
||||
@@ -173,6 +207,16 @@ export interface SettingsYaml {
|
||||
};
|
||||
footer?: FooterConfig;
|
||||
legal?: Partial<LegalConfig>;
|
||||
protection?: {
|
||||
disableRightClick?: boolean;
|
||||
disableImageDrag?: boolean;
|
||||
};
|
||||
watermark?: {
|
||||
enabled?: boolean;
|
||||
text?: string;
|
||||
opacity?: number;
|
||||
position?: 'bottom-right' | 'bottom-left' | 'center';
|
||||
};
|
||||
}
|
||||
|
||||
export function slugify(name: string): string {
|
||||
|
||||
@@ -72,7 +72,7 @@ export const VALID_HERO_STYLES = [
|
||||
'typographic',
|
||||
'mosaic',
|
||||
];
|
||||
export const VALID_LAYOUTS = ['masonry', 'uniform', 'showcase', 'filmstrip', 'editorial-flow'];
|
||||
export const VALID_LAYOUTS = ['masonry', 'uniform', 'showcase', 'filmstrip', 'editorial-flow', 'essay'];
|
||||
|
||||
export function resolveTheme(raw?: SettingsYaml['theme']): ThemeConfig {
|
||||
if (!raw) return { ...THEME_PRESETS.studio };
|
||||
|
||||
273
lib/essay.ts
Normal file
273
lib/essay.ts
Normal file
@@ -0,0 +1,273 @@
|
||||
export interface EssayFrontmatter {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
date?: string;
|
||||
author?: string;
|
||||
coverAssetId?: string;
|
||||
layout?: string;
|
||||
}
|
||||
|
||||
export type EssayBlock =
|
||||
| { type: 'heading'; level: number; text: string }
|
||||
| { type: 'paragraph'; html: string }
|
||||
| { type: 'quote'; text: string; author?: string }
|
||||
| { type: 'photo'; assetId: string; caption?: string; layout: 'fullbleed' | 'wide' | 'contained' }
|
||||
| { type: 'photo-pair'; assetIds: [string, string]; caption?: string };
|
||||
|
||||
export interface ParsedEssay {
|
||||
frontmatter: EssayFrontmatter;
|
||||
blocks: EssayBlock[];
|
||||
referencedAssetIds: string[];
|
||||
}
|
||||
|
||||
/** Sanitize inline HTML strings to prevent XSS attacks in essay blocks */
|
||||
export function sanitizeHtml(input: string): string {
|
||||
return input
|
||||
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
|
||||
.replace(/on\w+="[^"]*"/gi, '')
|
||||
.replace(/javascript:/gi, '');
|
||||
}
|
||||
|
||||
/** Simple Markdown inline formatting (bold, italic, links, code) */
|
||||
export function renderInlineMarkdown(text: string): string {
|
||||
let html = sanitizeHtml(text);
|
||||
// Bold: **text** or __text__
|
||||
html = html.replace(/(\*\*|__)(.*?)\1/g, '<strong>$2</strong>');
|
||||
// Italic: *text* or _text_
|
||||
html = html.replace(/(\*|_)(.*?)\1/g, '<em>$2</em>');
|
||||
// Links: [label](url)
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, label, url) => {
|
||||
const safeUrl = url.trim().replace(/^javascript:/i, '');
|
||||
return `<a href="${safeUrl}" target="_blank" rel="noopener noreferrer">${label}</a>`;
|
||||
});
|
||||
return html;
|
||||
}
|
||||
|
||||
/** Parse frontmatter (YAML block delimited by ---) */
|
||||
export function parseFrontmatter(content: string): { frontmatter: EssayFrontmatter; body: string } {
|
||||
const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
|
||||
if (!frontmatterMatch) {
|
||||
return { frontmatter: {}, body: content };
|
||||
}
|
||||
|
||||
const rawYaml = frontmatterMatch[1];
|
||||
const body = content.slice(frontmatterMatch[0].length);
|
||||
const frontmatter: EssayFrontmatter = {};
|
||||
|
||||
for (const line of rawYaml.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
const colonIdx = trimmed.indexOf(':');
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
const key = trimmed.slice(0, colonIdx).trim();
|
||||
let val = trimmed.slice(colonIdx + 1).trim();
|
||||
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
|
||||
val = val.slice(1, -1);
|
||||
}
|
||||
|
||||
if (key === 'title') frontmatter.title = val;
|
||||
else if (key === 'subtitle') frontmatter.subtitle = val;
|
||||
else if (key === 'date') frontmatter.date = val;
|
||||
else if (key === 'author') frontmatter.author = val;
|
||||
else if (key === 'coverAssetId') frontmatter.coverAssetId = val;
|
||||
else if (key === 'layout') frontmatter.layout = val;
|
||||
}
|
||||
|
||||
return { frontmatter, body };
|
||||
}
|
||||
|
||||
/** Parse Essay Markdown content into structured blocks */
|
||||
export function parseEssayMarkdown(rawContent: string): ParsedEssay {
|
||||
const { frontmatter, body } = parseFrontmatter(rawContent);
|
||||
const blocks: EssayBlock[] = [];
|
||||
const referencedAssetIds = new Set<string>();
|
||||
|
||||
if (frontmatter.coverAssetId) {
|
||||
referencedAssetIds.add(frontmatter.coverAssetId);
|
||||
}
|
||||
|
||||
// Split body into paragraph chunks separated by blank lines
|
||||
const chunks = body
|
||||
.split(/\r?\n\s*\r?\n/)
|
||||
.map((c) => c.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
for (const chunk of chunks) {
|
||||
// 1. Headings (# H1, ## H2, ### H3)
|
||||
const headingMatch = chunk.match(/^(#{1,6})\s+(.+)$/);
|
||||
if (headingMatch) {
|
||||
blocks.push({
|
||||
type: 'heading',
|
||||
level: headingMatch[1].length,
|
||||
text: headingMatch[2].trim(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2. Blockquote (> Quote text)
|
||||
if (chunk.startsWith('>')) {
|
||||
const quoteText = chunk
|
||||
.split('\n')
|
||||
.map((l) => l.replace(/^>\s?/, ''))
|
||||
.join(' ')
|
||||
.trim();
|
||||
|
||||
// Check for quote author (-- Author Name)
|
||||
const authorMatch = quoteText.match(/^(.*?)(?:\s+--\s+(.+))?$/);
|
||||
if (authorMatch) {
|
||||
blocks.push({
|
||||
type: 'quote',
|
||||
text: renderInlineMarkdown(authorMatch[1]),
|
||||
author: authorMatch[2] ? authorMatch[2].trim() : undefined,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 3. Image syntax:  or 
|
||||
const imgMatch = chunk.match(/^!\[([^\]]+)\]\(([^)]*)\)$/);
|
||||
if (imgMatch) {
|
||||
const rawTarget = imgMatch[1].trim();
|
||||
const caption = imgMatch[2].trim() ? renderInlineMarkdown(imgMatch[2].trim()) : undefined;
|
||||
|
||||
// Side-by-side pair: 
|
||||
if (rawTarget.includes(',')) {
|
||||
const parts = rawTarget.split(',').map((s) => s.trim());
|
||||
if (parts.length >= 2) {
|
||||
const id1 = parts[0];
|
||||
const id2 = parts[1];
|
||||
referencedAssetIds.add(id1);
|
||||
referencedAssetIds.add(id2);
|
||||
blocks.push({
|
||||
type: 'photo-pair',
|
||||
assetIds: [id1, id2],
|
||||
caption,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Single photo: 
|
||||
let assetId = rawTarget;
|
||||
let layout: 'fullbleed' | 'wide' | 'contained' = 'contained';
|
||||
|
||||
if (rawTarget.includes(':')) {
|
||||
const [id, l] = rawTarget.split(':');
|
||||
assetId = id.trim();
|
||||
const normLayout = l.trim().toLowerCase();
|
||||
if (normLayout === 'fullbleed') layout = 'fullbleed';
|
||||
else if (normLayout === 'wide') layout = 'wide';
|
||||
}
|
||||
|
||||
referencedAssetIds.add(assetId);
|
||||
blocks.push({
|
||||
type: 'photo',
|
||||
assetId,
|
||||
caption,
|
||||
layout,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// 4. Standard Text Paragraph
|
||||
blocks.push({
|
||||
type: 'paragraph',
|
||||
html: renderInlineMarkdown(chunk.replace(/\r?\n/g, ' ')),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
frontmatter,
|
||||
blocks,
|
||||
referencedAssetIds: Array.from(referencedAssetIds),
|
||||
};
|
||||
}
|
||||
|
||||
/** Load and parse an essay file from content/essays/ */
|
||||
export function loadEssayFromFile(filename: string): ParsedEssay | null {
|
||||
if (typeof window !== 'undefined') return null;
|
||||
try {
|
||||
// Dynamic require for Node.js modules so client bundler doesn't fail
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodeFs = require('fs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const nodePath = require('path');
|
||||
|
||||
const filePath = nodePath.isAbsolute(filename)
|
||||
? filename
|
||||
: nodePath.join(process.cwd(), 'content', 'essays', filename);
|
||||
|
||||
if (!nodeFs.existsSync(filePath)) {
|
||||
console.warn(`[Essay] File not found: ${filePath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = nodeFs.readFileSync(filePath, 'utf-8');
|
||||
return parseEssayMarkdown(content);
|
||||
} catch (error) {
|
||||
console.error(`[Essay] Failed to load essay file "${filename}":`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Converts a ParsedEssay structure back into clean Markdown syntax */
|
||||
export function serializeEssayMarkdown(essay: ParsedEssay): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Frontmatter
|
||||
const fmKeys = Object.keys(essay.frontmatter) as Array<keyof EssayFrontmatter>;
|
||||
if (fmKeys.length > 0 && fmKeys.some((k) => essay.frontmatter[k])) {
|
||||
lines.push('---');
|
||||
for (const key of fmKeys) {
|
||||
const val = essay.frontmatter[key];
|
||||
if (val) {
|
||||
lines.push(`${key}: "${val.replace(/"/g, '\\"')}"`);
|
||||
}
|
||||
}
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
// Blocks
|
||||
for (const block of essay.blocks) {
|
||||
switch (block.type) {
|
||||
case 'heading': {
|
||||
const hashes = '#'.repeat(Math.min(Math.max(block.level, 1), 6));
|
||||
lines.push(`${hashes} ${block.text}`);
|
||||
break;
|
||||
}
|
||||
case 'paragraph': {
|
||||
const text = block.html.replace(/<[^>]+>/g, (tag) => {
|
||||
if (tag.startsWith('<strong>') || tag.startsWith('<b>')) return '**';
|
||||
if (tag.startsWith('</strong>') || tag.startsWith('</b>')) return '**';
|
||||
if (tag.startsWith('<em>') || tag.startsWith('<i>')) return '*';
|
||||
if (tag.startsWith('</em>') || tag.startsWith('</i>')) return '*';
|
||||
return '';
|
||||
});
|
||||
lines.push(text);
|
||||
break;
|
||||
}
|
||||
case 'quote': {
|
||||
const authorSuffix = block.author ? ` -- ${block.author}` : '';
|
||||
const text = block.text.replace(/<[^>]+>/g, '');
|
||||
lines.push(`> ${text}${authorSuffix}`);
|
||||
break;
|
||||
}
|
||||
case 'photo': {
|
||||
const layoutSuffix = block.layout !== 'contained' ? `:${block.layout}` : '';
|
||||
const caption = block.caption ? block.caption.replace(/<[^>]+>/g, '') : '';
|
||||
lines.push(``);
|
||||
break;
|
||||
}
|
||||
case 'photo-pair': {
|
||||
const caption = block.caption ? block.caption.replace(/<[^>]+>/g, '') : '';
|
||||
lines.push(`![${block.assetIds[0]}, ${block.assetIds[1]}](${caption})`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n').trim();
|
||||
}
|
||||
@@ -452,12 +452,13 @@ class ImmichClient {
|
||||
* Get enriched subpage summaries for the homepage.
|
||||
*/
|
||||
async getSubpages(): Promise<SubpageSummary[]> {
|
||||
if (this.config.subpages.length === 0) return [];
|
||||
const activeSubpages = this.config.subpages.filter((sp) => sp.enabled !== false);
|
||||
if (activeSubpages.length === 0) return [];
|
||||
|
||||
const albums = await this.getAlbums();
|
||||
const albumMap = new Map(albums.map((a) => [a.id, a]));
|
||||
|
||||
return this.config.subpages.map((sp) => {
|
||||
return activeSubpages.map((sp) => {
|
||||
const spAlbums = sp.albumIds
|
||||
.map((id) => albumMap.get(id))
|
||||
.filter((a): a is ImmichAlbum => a !== undefined);
|
||||
@@ -478,7 +479,9 @@ class ImmichClient {
|
||||
async getSubpageAlbums(
|
||||
subpageSlug: string,
|
||||
): Promise<{ subpage: SubpageConfig; albums: ImmichAlbum[] } | null> {
|
||||
const subpage = this.config.subpages.find((sp) => sp.slug === subpageSlug);
|
||||
const subpage = this.config.subpages.find(
|
||||
(sp) => sp.slug === subpageSlug && sp.enabled !== false,
|
||||
);
|
||||
if (!subpage) return null;
|
||||
|
||||
const allAlbums = await this.getAlbums();
|
||||
@@ -626,7 +629,7 @@ class ImmichClient {
|
||||
* Check if a slug corresponds to a subpage.
|
||||
*/
|
||||
isSubpageSlug(slug: string): boolean {
|
||||
return this.config.subpages.some((sp) => sp.slug === slug);
|
||||
return this.config.subpages.some((sp) => sp.slug === slug && sp.enabled !== false);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
65
lib/proofing.ts
Normal file
65
lib/proofing.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Bitmask encoder/decoder for compact proofing URL query parameters.
|
||||
* Serializes selected asset indices in an album into a short base64url string.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Encode an array of 0-based asset indices into a compact base64url bitmask.
|
||||
*/
|
||||
export function encodeProofBitmask(indices: number[]): string {
|
||||
if (!indices || indices.length === 0) return '';
|
||||
const sorted = Array.from(new Set(indices)).sort((a, b) => a - b);
|
||||
const maxIndex = sorted[sorted.length - 1];
|
||||
if (maxIndex < 0) return '';
|
||||
|
||||
const numBytes = Math.ceil((maxIndex + 1) / 8);
|
||||
const bytes = new Uint8Array(numBytes);
|
||||
|
||||
for (const idx of sorted) {
|
||||
if (idx < 0) continue;
|
||||
const byteIdx = Math.floor(idx / 8);
|
||||
const bitIdx = idx % 8;
|
||||
bytes[byteIdx] |= 1 << bitIdx;
|
||||
}
|
||||
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
|
||||
return btoa(binary)
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a base64url bitmask string back into an array of selected asset indices.
|
||||
*/
|
||||
export function decodeProofBitmask(code: string, totalCount?: number): number[] {
|
||||
if (!code || typeof code !== 'string') return [];
|
||||
try {
|
||||
let base64 = code.trim().replace(/-/g, '+').replace(/_/g, '/');
|
||||
while (base64.length % 4) {
|
||||
base64 += '=';
|
||||
}
|
||||
const binary = atob(base64);
|
||||
const result: number[] = [];
|
||||
|
||||
for (let byteIdx = 0; byteIdx < binary.length; byteIdx++) {
|
||||
const byte = binary.charCodeAt(byteIdx);
|
||||
for (let bitIdx = 0; bitIdx < 8; bitIdx++) {
|
||||
if (byte & (1 << bitIdx)) {
|
||||
const index = byteIdx * 8 + bitIdx;
|
||||
if (totalCount === undefined || index < totalCount) {
|
||||
result.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user