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
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ Every attribute the widget reads from the `#garrul` host element
| `data-url` | no | Canonical permalink; sent on every comment create (top-level and reply). The first non-null value wins and later values are ignored. Used in RSS and notification emails. |
| `data-published` | no | Article publish time (epoch ms or ISO 8601). On the iframe variant pass it as `?published=` (§6). The widget sends it as `post_published` on every comment create (top-level and reply); the server records it only on the request that creates the post row and never changes it after that — it arrives on an unauthenticated POST, and an old enough value closes the thread for good, so a later request cannot supply or move it. Anchors age-based auto-close (`AUTO_CLOSE_DAYS`). Omit it and Garrul anchors on first-engagement time, which closes a bit later than intended. If a reaction, page vote or admin action created the row before the first comment, the slug keeps that first-engagement anchor. Repair today is direct D1 SQL on `posts.published_at`; an admin edit surface is a separate backlog item. |
| `data-lang` | no | BCP-47 tag pinning the widget's interface language (see "Language" below). Unrecognized tags fall back to English rather than erroring. |
| `data-remember` | no | `off` stops the widget saving an anonymous reader's name and notify email in `localStorage`, and deletes any saved entry on mount. Any other value (or absent) keeps it on. Script embed only. |
| `data-mode` | no | `reactions` mounts only the page-level reactions/votes bar (no thread, no composer) in one request (`/api/v1/bootstrap?…&view=engagement`). Needs `PAGE_REACTIONS_ENABLED` and/or `PAGE_VOTES_ENABLED`; with both off it renders nothing and logs one console warning. Any other value is the normal thread. |

The host element MUST have `id="garrul"`; the widget looks it up by ID
Expand Down Expand Up @@ -1323,6 +1324,12 @@ both `data-api` and the `<script src>`.
autosave keys are `garrul:draft:<api origin>:<slug>[:<parent>]` (since
v2.27.0), so a draft belongs to one Worker origin. Pre-v2.27.0 drafts
(`garrul:draft:<slug>`) are adopted once on the next mount.
Anonymous commenter details follow the same rule: after an accepted
post the widget saves `{name, email}` under `garrul:author:<api origin>`
and prefills the name field (and the hidden notify email field, box left
unticked) on later mounts. The email is saved only when notify was ticked.
A prefilled top-level form shows a "Not you?" button (`.gr-forget`) that
deletes the entry and empties both fields.
- Don't render two `#garrul` elements on one page; only the first is
picked up. Multi-thread is not a supported mode in v1.
- Don't try to style internals via host CSS. Shadow DOM blocks it on
Expand Down
16 changes: 16 additions & 0 deletions docs/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,22 @@ reviewed:
Resolution order, the iframe variant's `?lang=`, what is and isn't
translated, and how timestamps render: [`i18n.md`](i18n.md).

## Remembered name and email

After an anonymous reader posts, the widget saves their name in the host
page's `localStorage` and fills it in on their next visit. If they ticked
"notify me", it saves that address too. Nothing is sent to the server for this.
A "Not you? Clear saved details" link under the prefilled name deletes it.

If your privacy policy can't cover that, turn it off:

```html
<div id="garrul" data-slug="my-post" data-remember="off"></div>
```

With `off`, the widget saves nothing and deletes any details it saved before.
The iframe variant has no equivalent setting.

## Lazy-loading

The widget fires one Worker request on page load, before the reader has
Expand Down
7 changes: 7 additions & 0 deletions docs/privacy-policy.template.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,13 @@ browser's `localStorage` so it survives an accidental reload. It never
leaves your device — it is not sent to us — and it is cleared as soon as
you submit or cancel the comment.

After you post without signing in, the name you used is saved there too,
along with the email address if you asked to be notified of replies, so
the form is filled in on your next visit. This also stays on your device.
Use the "Not you? Clear saved details" link under your name, or clear this
site's data in your browser settings, to remove it.
<!-- Delete the paragraph above if your embed sets data-remember="off". -->

## Who sees your data

- **Site moderators** at `[YOUR DOMAIN]` (whose emails are in the
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export const ar = {
"w.preview.loading": "جارٍ تحميل المعاينة…",
"w.preview.failed": "تعذّرت المعاينة. حاول مرة أخرى.",
"w.name_ph": "اسمك",
"w.forget_me": "لست أنت؟ امسح البيانات المحفوظة",
"w.body_ph": "أضف تعليقًا…",
"w.email_ph": "you@example.com",
"w.email_label": "عنوان البريد الإلكتروني",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export const de = {
"w.preview.loading": "Vorschau wird geladen…",
"w.preview.failed": "Vorschau fehlgeschlagen. Bitte erneut versuchen.",
"w.name_ph": "Name",
"w.forget_me": "Nicht Sie? Gespeicherte Angaben löschen",
"w.body_ph": "Kommentar schreiben…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export const es = {
"w.preview.loading": "Cargando la vista previa…",
"w.preview.failed": "No se pudo generar la vista previa. Inténtalo de nuevo.",
"w.name_ph": "Tu nombre",
"w.forget_me": "¿No eres tú? Borrar datos guardados",
"w.body_ph": "Añade un comentario…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const fr = {
"w.preview.loading": "Chargement de l'aperçu…",
"w.preview.failed": "Échec de l'aperçu. Réessayez.",
"w.name_ph": "Votre nom",
"w.forget_me": "Ce n'est pas vous ? Effacer les données enregistrées",
"w.body_ph": "Ajouter un commentaire…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export const it = {
"w.preview.loading": "Caricamento dell'anteprima…",
"w.preview.failed": "Anteprima non riuscita. Riprova.",
"w.name_ph": "Il tuo nome",
"w.forget_me": "Non sei tu? Cancella i dati salvati",
"w.body_ph": "Aggiungi un commento…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const ja = {
"w.preview.loading": "プレビューを読み込んでいます…",
"w.preview.failed": "プレビューに失敗しました。もう一度お試しください。",
"w.name_ph": "名前",
"w.forget_me": "ご本人ではありませんか?保存された情報を消去",
"w.body_ph": "コメントを入力…",
// example.com is the RFC-2606 reserved example domain; a localized
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/nb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export const nb = {
"w.preview.loading": "Laster forhåndsvisning…",
"w.preview.failed": "Forhåndsvisningen mislyktes. Prøv igjen.",
"w.name_ph": "Navnet ditt",
"w.forget_me": "Ikke deg? Slett lagrede opplysninger",
"w.body_ph": "Skriv en kommentar…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/nl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export const nl = {
"w.preview.loading": "Voorbeeld laden…",
"w.preview.failed": "Voorbeeld mislukt. Probeer het opnieuw.",
"w.name_ph": "Naam",
"w.forget_me": "Niet jij? Opgeslagen gegevens wissen",
"w.body_ph": "Reactie toevoegen…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export const pl = {
"w.preview.failed": "Nie udało się wczytać podglądu. Spróbuj ponownie.",
// No "Twoje" — the file's no-pronoun rule.
"w.name_ph": "Imię lub nazwa",
"w.forget_me": "To nie Ty? Wyczyść zapisane dane",
"w.body_ph": "Dodaj komentarz…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/pt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export const pt = {
// variants split on the article ("Seu nome" / "O seu nome"), and a
// placeholder loses nothing by dropping it.
"w.name_ph": "Nome",
"w.forget_me": "Não é você? Apagar dados salvos",
"w.body_ph": "Adicione um comentário…",
// example.com is the RFC-2606 reserved example domain; a translated
// lookalike would be somebody's real domain.
Expand Down
1 change: 1 addition & 0 deletions src/i18n/widget/zh-Hant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export const zhHant = {
"w.preview.loading": "正在載入預覽…",
"w.preview.failed": "預覽失敗,請再試一次。",
"w.name_ph": "名稱",
"w.forget_me": "不是你?清除已儲存的資料",
"w.body_ph": "新增留言…",
"w.email_ph": "you@example.com",
"w.email_label": "電子郵件地址",
Expand Down
68 changes: 68 additions & 0 deletions src/widget/author.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* Remembered commenter details (name, notify email) for anonymous readers.
*
* DOM-free on purpose (tsconfig.widget.json, plain node tests). embed.ts owns
* the form wiring; this module owns the key, the stored shape and the merge.
*
* Saved only after the server accepts a post, never while typing: what gets
* remembered is a name the server took, not a half-typed one. The value goes
* back into inputs via `.value`, never as HTML, so a tampered entry is inert.
* Keyed by the Worker origin for the same reason drafts are (see ./drafts).
*
* Same trade-off as WordPress's comment_author cookies: the address sits in
* the host page's origin storage, readable by that page's own scripts. Those
* scripts can already read the input as it is typed, so persisting it widens
* the window, not the audience.
*/

const AUTHOR_PREFIX = "garrul:author:";

/** RFC 5321 path limit; names are clamped far lower server-side anyway. */
const FIELD_MAX = 254;

export type Author = { name: string; email: string };

/** The subset of Storage this module touches; lets tests pass a plain object. */
export type AuthorStorage = {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
};

export const authorKey = (origin: string): string => `${AUTHOR_PREFIX}${origin}`;

const clean = (v: unknown): string =>
typeof v === "string" ? v.trim().slice(0, FIELD_MAX) : "";

/**
* Read the saved details. Missing, corrupt or wrongly-typed entries read as
* empty; a null storage (blocked localStorage) does too.
*/
export const readAuthor = (storage: AuthorStorage | null, key: string): Author => {
try {
const raw = storage?.getItem(key);
const v = raw ? (JSON.parse(raw) as Record<string, unknown> | null) : null;
return { name: clean(v?.name), email: clean(v?.email) };
} catch {
return { name: "", email: "" };
}
};

/**
* Merge `next` into what is stored. An empty field keeps the stored value: a
* reply posted without the notify box must not forget the address.
*/
export const rememberAuthor = (
storage: AuthorStorage | null,
key: string,
next: Partial<Author>,
): void => {
if (!storage) return;
const cur = readAuthor(storage, key);
const merged = { name: clean(next.name) || cur.name, email: clean(next.email) || cur.email };
if (merged.name === cur.name && merged.email === cur.email) return;
try {
storage.setItem(key, JSON.stringify(merged));
} catch {
// Quota/disabled: not remembering is fine, breaking the post is not.
}
};
61 changes: 61 additions & 0 deletions src/widget/embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { loadErrorMessage } from "./load-error";
import { watchForSignIn } from "./auth-recovery";
import { autoSizeTextarea } from "./autosize";
import { DRAFT_MAX, adoptLegacyDraft, draftKey, legacyDraftKey } from "./drafts";
import { authorKey, readAuthor, rememberAuthor } from "./author";
import { createTurnstileGate, type TurnstileGate } from "./turnstile-gate";
import { makeS, type StringTable, type WidgetKey } from "./strings";
import {
Expand Down Expand Up @@ -382,6 +383,29 @@ const attachDraft = (ta: HTMLTextAreaElement, key: string, legacyKey: string): s
return key;
};

// ── Remembered author ───────────────────────────────────────────────────────
// Anonymous readers get their name (and notify email, when they gave one)
// prefilled on the next visit. Shape and merge rules live in ./author.

/**
* `localStorage`, or null where merely touching the getter throws — or where
* the operator opted out with `data-remember="off"` (a privacy policy that
* can't cover a stored address). Every author read and write goes through here.
*/
const authorStore = (host: HTMLElement): Storage | null => {
if (host.dataset.remember === "off") return null;
try {
return localStorage;
} catch {
return null;
}
};

/** Fill an input from saved details, only when the reader hasn't typed. */
const prefill = (input: HTMLInputElement | null, value: string): void => {
if (input && value && !input.value) input.value = value;
};

type MdFormat = {
before?: string;
after?: string;
Expand Down Expand Up @@ -2166,6 +2190,8 @@ const buildReplyForm = (parent: TreeNode, ctx: WidgetCtx): HTMLElement => {
nameInput.placeholder = s("w.name_ph");
nameInput.setAttribute("aria-label", s("w.name_ph"));
nameInput.required = true;
nameInput.setAttribute("autocomplete", "nickname");
prefill(nameInput, readAuthor(authorStore(ctx.host), authorKey(ctx.apiOrigin)).name);
wrap.appendChild(nameInput);
}
if (isStaff(ctx.me)) wrap.appendChild(buildStaffToggle());
Expand Down Expand Up @@ -2358,6 +2384,8 @@ const buildReplyForm = (parent: TreeNode, ctx: WidgetCtx): HTMLElement => {
}
// Reply landed — drop the saved draft before the list re-renders.
clearDraft(dkey);
if (nameInput)
rememberAuthor(authorStore(ctx.host), authorKey(ctx.apiOrigin), { name: nameInput.value });
// The 201 carries the whole comment, so render it rather than paying a
// GET to read it back (see insertPostedNode). Pending replies take the
// same path as approved ones: `status` comes from the echo, so the
Expand Down Expand Up @@ -2798,6 +2826,9 @@ const buildForm = (
name.placeholder = s("w.name_ph");
name.setAttribute("aria-label", s("w.name_ph"));
name.required = true;
// Overrides the form-level "off": a display name is the one field here a
// browser's autofill should offer.
name.setAttribute("autocomplete", "nickname");
card.prepend(name);
}

Expand Down Expand Up @@ -3862,6 +3893,31 @@ const loadOnce = async (
) as HTMLTextAreaElement | null;
if (composer)
attachDraft(composer, draftKey(apiOrigin, slug, null), legacyDraftKey(slug, null));
// Opted out: also drop what an earlier, opted-in deploy saved. clearDraft is
// a plain guarded removeItem, nothing draft-specific.
const akey = authorKey(apiOrigin);
if (host.dataset.remember === "off") clearDraft(akey);
const savedAuthor = readAuthor(authorStore(host), akey);
// Fields absent for a signed-in reader are null and skipped. The email lands
// in the still-hidden notify field: the box stays unticked, opt-in stays explicit.
const nameField = form.querySelector<HTMLInputElement>(".gr-name-input");
const emailField = form.querySelector<HTMLInputElement>(".gr-email-input");
prefill(nameField, savedAuthor.name);
prefill(emailField, savedAuthor.email);
// A shared computer shows the last commenter's name to the next reader, so
// offer the way out right where the name appears.
if (nameField && (savedAuthor.name || savedAuthor.email)) {
const forget = el("button", "gr-forget", s("w.forget_me"));
forget.type = "button";
forget.addEventListener("click", () => {
clearDraft(akey);
nameField.value = "";
if (emailField) emailField.value = "";
nameField.focus();
forget.remove();
});
nameField.after(forget);
}
const list = el("div", "gr-list");
if (data.threads.length === 0) {
// Don't invite a comment the reader can't leave: when comments are
Expand Down Expand Up @@ -4308,6 +4364,11 @@ const submit = async (
).catch(() => {});
}
}
// The address is remembered only when the reader used it for notify.
rememberAuthor(authorStore(host), authorKey(apiOrigin), {
name,
email: notifyCb?.checked ? (emailInput?.value ?? "") : "",
});

// The 201 carries the whole comment, so render it instead of spending a
// second request reading it back — and instead of re-fetching page one,
Expand Down
1 change: 1 addition & 0 deletions src/widget/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export const EN = {
"w.preview.loading": "Loading preview…",
"w.preview.failed": "Preview failed. Try again.",
"w.name_ph": "Your name",
"w.forget_me": "Not you? Clear saved details",
"w.body_ph": "Add a comment…",
"w.email_ph": "you@example.com",
"w.email_label": "Email address",
Expand Down
11 changes: 10 additions & 1 deletion src/widget/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ button:focus-visible, textarea:focus-visible, input:focus-visible, select:focus-
the composer's autosize into a rubber band. */
.gr-toolbar-btn, .gr-submit, .gr-actions button, .gr-low-score,
.gr-vote, .gr-reaction, .gr-sort select, .gr-loadmore, .gr-collapse, .gr-showmore,
.gr-signin button, .gr-signed button, .gr-attribution a {
.gr-signin button, .gr-signed button, .gr-attribution a, .gr-form .gr-forget {
transition: background-color var(--gr-motion), border-color var(--gr-motion),
color var(--gr-motion), opacity var(--gr-motion);
}
Expand Down Expand Up @@ -403,6 +403,15 @@ button:active:not([disabled]) { opacity: 0.75; }
.gr-honeypot { position: absolute; left: -9999px; top: -9999px; }
.gr-form .gr-notify { display: flex; align-items: center; gap: 0.4rem; font-size: 0.9em; cursor: pointer; }
.gr-form .gr-notify .gr-notify-cb { width: auto; }
/* "Not you?" under a remembered name. The bare text look of the comment
actions, muted until hover: an escape hatch, not a call to action. */
.gr-form .gr-forget {
align-self: flex-start;
font: inherit; font-size: 0.85em;
background: transparent; color: var(--gr-muted);
border: none; padding: 0; min-height: 24px; cursor: pointer;
}
.gr-form .gr-forget:hover { color: var(--gr-link); }
/* Reply forms are not .gr-form, so the staff toggle is styled unscoped. */
.gr-staff-toggle { display: flex; align-items: center; gap: 0.4rem; font-size: 0.9em; cursor: pointer; }
.gr-staff-toggle .gr-staff-cb { width: auto; }
Expand Down
Loading
Loading