Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
},
"devDependencies": {
"esbuild": "^0.24.0",
"happy-dom": "^20.10.6",
"typescript": "^5.6.0",
"vitest": "^2.1.0",
"wrangler": "^4.0.0"
Expand Down
16 changes: 16 additions & 0 deletions src/app/history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export interface TextEditMarker {
field: string;
at: number;
}

/** Only adjacent keystrokes in the same control share one undo snapshot. */
export function shouldCoalesceHistory(
previous: TextEditMarker | undefined,
structural: boolean,
textField: string | undefined,
now: number,
atHistoryTip: boolean,
): boolean {
return !structural && textField !== undefined && previous?.field === textField
&& now - previous.at < 800 && atHistoryTip;
}
34 changes: 20 additions & 14 deletions src/app/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { el } from './dom.js';
import { shouldCoalesceHistory, type TextEditMarker } from './history.js';
import { renderGallery } from './gallery.js';
import { decodeShare } from './share.js';
import { renderSharedView } from './shared-view.js';
Expand Down Expand Up @@ -27,47 +28,52 @@ function initWizard(): void {

// "Draft saved" pulse: autosave is invisible otherwise, and invisible
// safety reads as no safety.
const savedNote = el('span', { class: 'saved-note', text: 'Draft saved', 'aria-hidden': 'true' });
const savedNote = el('span', { class: 'saved-note', text: 'Draft saved', 'aria-live': 'polite' });
document.querySelector('.topbar')?.insertBefore(savedNote, document.getElementById('preview-toggle'));
let savedTimer: ReturnType<typeof setTimeout> | undefined;
function pulseSaved(): void {
function showSaveStatus(saved: boolean): void {
savedNote.textContent = saved ? 'Draft saved' : 'Draft not saved - browser storage is unavailable or full.';
savedNote.classList.toggle('unsaved', !saved);
savedNote.classList.add('show');
clearTimeout(savedTimer);
savedTimer = setTimeout(() => savedNote.classList.remove('show'), 1200);
if (saved) savedTimer = setTimeout(() => savedNote.classList.remove('show'), 1200);
}

// App-level undo/redo: snapshots of the whole draft, rapid typing coalesced
const undoBtn = document.getElementById('undo') as HTMLButtonElement;
const redoBtn = document.getElementById('redo') as HTMLButtonElement;
const history: string[] = [JSON.stringify(state.data)];
let hIndex = 0;
let lastPush = 0;
let lastTextEdit: TextEditMarker | undefined;
function updateUndoButtons(): void {
undoBtn.disabled = hIndex === 0;
redoBtn.disabled = hIndex === history.length - 1;
}
function recordHistory(): void {
function recordHistory(structural: boolean, textField?: string): void {
const snap = JSON.stringify(state.data);
if (snap === history[hIndex]) return;
const now = performance.now();
if (now - lastPush < 800 && hIndex === history.length - 1 && hIndex > 0) {
const coalesce = hIndex > 0 && shouldCoalesceHistory(
lastTextEdit, structural, textField, now, hIndex === history.length - 1,
);
if (coalesce) {
history[hIndex] = snap; // coalesce keystrokes into one step
} else {
history.splice(hIndex + 1);
history.push(snap);
if (history.length > 60) history.shift();
hIndex = history.length - 1;
}
lastPush = now;
lastTextEdit = !structural && textField !== undefined ? { field: textField, at: now } : undefined;
updateUndoButtons();
}
function restore(idx: number): void {
if (idx < 0 || idx > history.length - 1) return;
hIndex = idx;
lastPush = 0;
lastTextEdit = undefined;
state.data = JSON.parse(history[idx]!) as typeof state.data;
ctx.data = state.data;
saveState(state);
showSaveStatus(saveState(state));
schedulePreview(iframe, state.data);
renderPane();
updateUndoButtons();
Expand All @@ -82,19 +88,19 @@ function initWizard(): void {

const ctx: StepCtx = {
data: state.data,
onChange(structural = false) {
onChange(structural = false, textField) {
ctx.data = state.data;
saveState(state);
recordHistory();
pulseSaved();
const saved = saveState(state);
recordHistory(structural, textField);
showSaveStatus(saved);
schedulePreview(iframe, state.data);
if (structural) renderPane();
},
};

function goto(step: AppState['step']): void {
state.step = step;
saveState(state);
showSaveStatus(saveState(state));
renderPane();
window.scrollTo({ top: 0 });
}
Expand Down
49 changes: 48 additions & 1 deletion src/app/og.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,49 @@
import { effectivePalette, resolveFont } from '../engine/render.js';
import type { SiteData, ThemePack } from '../engine/types.js';

function graphemes(text: string): string[] {
const Segmenter = (Intl as unknown as {
Segmenter?: new (locale?: string, options?: { granularity: 'grapheme' }) => {
segment(input: string): Iterable<{ segment: string }>;
};
}).Segmenter;
if (!Segmenter) {
const clusters: string[] = [];
for (const part of Array.from(text)) {
const previous = clusters[clusters.length - 1];
const joinsPrevious = /\p{Mark}/u.test(part) || /[\ufe0e\ufe0f\u{1f3fb}-\u{1f3ff}]/u.test(part)
|| part === '\u200d' || previous?.endsWith('\u200d');
if (previous && joinsPrevious) clusters[clusters.length - 1] += part;
else clusters.push(part);
}
return clusters;
}
return [...new Segmenter(undefined, { granularity: 'grapheme' }).segment(text)]
.map((part) => part.segment);
}

/** Wrap to two lines, then truncate without splitting a grapheme cluster. */
export function wrapOgName(name: string, measure: (text: string) => number, maxWidth: number): string[] {
const parts = graphemes(name);
const lines: string[] = [];
let line = '';
for (let i = 0; i < parts.length; i += 1) {
const next = line + parts[i]!;
if (!line || measure(next) <= maxWidth) {
line = next;
continue;
}
if (lines.length === 1) {
while (line && measure(`${line}…`) > maxWidth) line = graphemes(line).slice(0, -1).join('');
return [...lines, `${line.trimEnd()}…`];
}
lines.push(line.trimEnd());
line = parts[i]!.trimStart();
}
if (line) lines.push(line.trimEnd());
return lines;
}

/**
* 1200x630 social-share card rendered on a canvas: palette background,
* name huge, tagline under it, accent bar. Used by hosted publish (where
Expand Down Expand Up @@ -30,7 +73,11 @@ export function renderOgCard(data: SiteData, theme: ThemePack): string {
size -= 4;
g.font = `700 ${size}px ${heading}`;
}
g.fillText(name, 60, 280);
const nameLines = g.measureText(name).width > 1080
? wrapOgName(name, (text) => g.measureText(text).width, 1080)
: [name];
const nameY = nameLines.length > 1 ? 245 : 280;
nameLines.forEach((line, i) => g.fillText(line, 60, nameY + i * 52));

const tagline = data.tagline?.trim();
if (tagline) {
Expand Down
9 changes: 7 additions & 2 deletions src/app/photo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { el } from './dom.js';
import { validImageDataUrl } from './site-data.js';
import type { StepCtx } from './steps/content.js';

const VIEW = 220; // on-screen crop viewport (CSS px)
Expand All @@ -13,7 +14,9 @@ export async function fileToResizedDataUrl(file: File, maxEdge = 1024): Promise<
canvas.height = Math.round(bitmap.height * scale);
canvas.getContext('2d')!.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
bitmap.close();
return canvas.toDataURL('image/jpeg', 0.82);
const dataUrl = canvas.toDataURL('image/jpeg', 0.82);
if (!validImageDataUrl(dataUrl)) throw new Error('image too large');
return dataUrl;
}

/**
Expand Down Expand Up @@ -136,7 +139,9 @@ function cropUi(bitmap: ImageBitmap, ctx: StepCtx): HTMLElement {
out.width = OUT;
out.height = OUT;
draw(out.getContext('2d')!, OUT);
data.photo = { dataUrl: out.toDataURL('image/jpeg', 0.85) };
const dataUrl = out.toDataURL('image/jpeg', 0.85);
if (!validImageDataUrl(dataUrl)) return;
data.photo = { dataUrl };
bitmap.close();
onChange(true);
});
Expand Down
6 changes: 5 additions & 1 deletion src/app/preview.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { renderSite } from '../engine/render.js';
import { escAttr } from '../engine/escape.js';
import { collectImages, type SiteData } from '../engine/types.js';
import { getTheme } from '../themes/index.js';
import { validImageDataUrl } from './site-data.js';

/**
* Self-contained preview document: stylesheet inlined, photo swapped to its
Expand All @@ -16,7 +18,9 @@ export function previewHtml(data: SiteData): string {
`<style>${css}</style>`,
);
for (const [path, dataUrl] of collectImages(shown)) {
doc = doc.replace(`src="${path}"`, `src="${dataUrl}"`);
if (validImageDataUrl(dataUrl)) {
doc = doc.replace(`src="${path}"`, `src="${escAttr(dataUrl)}"`);
}
}
return doc;
}
Expand Down
16 changes: 12 additions & 4 deletions src/app/qr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ import qrcode from 'qrcode-generator';
import { esc } from '../engine/escape.js';
import type { SiteData } from '../engine/types.js';

/** QR version 40, byte mode, error correction M. */
export const QR_MAX_BYTES = 2331;

/** Deterministic QR of a URL as a scalable SVG string. */
export function qrSvg(url: string): string {
const qr = qrcode(0, 'M');
qr.addData(url);
qr.make();
return qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
if (new TextEncoder().encode(url).length > QR_MAX_BYTES) throw new Error('address too long');
try {
const qr = qrcode(0, 'M');
qr.addData(url);
qr.make();
return qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
} catch {
throw new Error('address too long');
}
}

/**
Expand Down
Loading
Loading