diff --git a/README.md b/README.md index 18e61eb..f3d51e5 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ browser. The author's dashboard hands out this tag and the invite links: |---|---| | `data-api` | The backend origin. Without it the page stays local-only, exactly as above. | | `data-review-id` | The review this page belongs to. | +| `data-credentials` | `omit` (default), `same-origin` or `include`. Whether backend and `data-post-url` requests carry cookies. Use `same-origin` when the backend shares the page's origin behind a cookie sign-in (an identity-aware proxy, for example). A cross-origin backend needs CORS with `Access-Control-Allow-Credentials` for `include`. | Reviewers arrive through a personal link, `https://your-site/page?an_invite=…`. The token is stored for that review in the reviewer's browser and removed from @@ -167,6 +168,27 @@ site addresses registered on the review may use it. - In a synced review there is nothing to submit: the footer reads "Sent to the review" as soon as a comment is posted. +#### Your own sign-in (`auth`) + +When the backend sits behind your site's own sign-in, skip invite links and +hand Annotate the session yourself (programmatic config only): + +```js +Annotate.init({ + api: "/review-api", // same origin, behind your proxy + reviewId: "rvw_…", + credentials: "same-origin", // send the proxy's session cookie + auth: { + getToken: () => mySession.token, // bearer token, or null when signed out + getReviewer: () => ({ id: me.id, name: me.name, role: me.isOwner ? "author" : "reviewer" }), + onUnauthorized: () => mySession.signIn(), + }, +}); +``` + +`getReviewer` is optional. Without it the viewer is unnamed and never gets +the review author's controls. + ## Framework integration For a bundler, install `@reviewjs/annotate`, call `init()` after mount, and @@ -299,6 +321,11 @@ Sharing is an explicit action: 4. You open the same page, click **Import** (⬆), pick the file — every comment reappears anchored in place. +Reviewing a whole site? When other pages have comments too, the footer offers +**All pages** under the buttons: one file with every page's comments. Import it +on any page of the site and each comment goes back to the page it was made on +(the project name may differ between the two browsers). + To paste feedback directly into another tool, click **Copy** to copy the same complete, import-compatible JSON payload to the clipboard. @@ -362,7 +389,8 @@ Annotate.disable(); // collapse to the launcher Annotate.setTool("highlight");// show the layer, then choose cursor | highlight | rect | circle | pen | pin Annotate.comments(); // → array of comment objects for this page Annotate.focus(id); // scroll to & highlight a comment -Annotate.export(); // trigger the JSON download +Annotate.export(); // trigger the JSON download for this page +Annotate.export({ scope: "site" }); // one file with every page's comments Annotate.import(); // open the file picker await Annotate.submit(); // POST the JSON export to postUrl Annotate.refresh(); // manually re-read the current page when spa is off diff --git a/annotate.d.mts b/annotate.d.mts index 0bd9c07..e591d55 100644 --- a/annotate.d.mts +++ b/annotate.d.mts @@ -24,6 +24,12 @@ export interface AnnotateConfig { inviteParam?: string; /** Poll interval in milliseconds for remote reads. Default 20000, minimum 500. */ pollInterval?: number; + /** + * Fetch credentials mode for backend (api) and postUrl requests. Default + * "omit". Use "same-origin" for a same-origin backend behind a cookie + * sign-in, or "include" for a cross-origin one that allows credentials. + */ + credentials?: 'omit' | 'same-origin' | 'include'; /** Integrator-managed auth. Replaces the built-in invite-link exchange. */ auth?: AnnotateAuth; } @@ -33,6 +39,17 @@ export interface AnnotateAuth { getToken(): Promise | string | null; /** Called when the backend refuses the token after one refresh. */ onUnauthorized?(): void; + /** + * Optional: who the signed-in viewer is. Without it the viewer is unnamed + * and never a review author (no owner controls). + */ + getReviewer?(): Promise | AnnotateReviewer | null; +} + +export interface AnnotateReviewer { + id: string; + name: string; + role: 'author' | 'reviewer'; } export interface ResolvedAnnotateConfig { @@ -51,6 +68,7 @@ export interface ResolvedAnnotateConfig { reviewId: string; inviteParam: string; pollInterval: number; + credentials: 'omit' | 'same-origin' | 'include'; } export type AnnotateStatus = 'open' | 'in_progress' | 'resolved' | 'wont_fix'; @@ -116,6 +134,8 @@ export interface FeedbackExport { url: string; project: string; exportedViewport: { vw: number; vh: number; dpr: number }; + /** "site" when the file holds every page of the project; absent for a page export. */ + scope?: 'site'; comments: AnnotateComment[]; } @@ -134,7 +154,8 @@ export interface AnnotateAPI { comments(): AnnotateComment[]; focus(id: string): void; toast(message: string, options?: { kind?: 'info' | 'error' | 'success'; duration?: number }): void; - export(): void; + /** Download this page's comments, or every page's with { scope: 'site' } (local mode). */ + export(options?: { scope?: 'page' | 'site' }): void; import(): void; /** * Local mode: sends the current page's export JSON to postUrl; rejects on failure. diff --git a/annotate.d.ts b/annotate.d.ts index 58134c4..2cbc7b9 100644 --- a/annotate.d.ts +++ b/annotate.d.ts @@ -23,6 +23,12 @@ export interface AnnotateConfig { inviteParam?: string; /** Poll interval in milliseconds for remote reads. Default 20000, minimum 500. */ pollInterval?: number; + /** + * Fetch credentials mode for backend (api) and postUrl requests. Default + * "omit". Use "same-origin" for a same-origin backend behind a cookie + * sign-in, or "include" for a cross-origin one that allows credentials. + */ + credentials?: 'omit' | 'same-origin' | 'include'; /** Integrator-managed auth. Replaces the built-in invite-link exchange. */ auth?: AnnotateAuth; } @@ -32,6 +38,17 @@ export interface AnnotateAuth { getToken(): Promise | string | null; /** Called when the backend refuses the token after one refresh. */ onUnauthorized?(): void; + /** + * Optional: who the signed-in viewer is. Without it the viewer is unnamed + * and never a review author (no owner controls). + */ + getReviewer?(): Promise | AnnotateReviewer | null; +} + +export interface AnnotateReviewer { + id: string; + name: string; + role: 'author' | 'reviewer'; } export interface ResolvedAnnotateConfig { @@ -50,6 +67,7 @@ export interface ResolvedAnnotateConfig { reviewId: string; inviteParam: string; pollInterval: number; + credentials: 'omit' | 'same-origin' | 'include'; } export type AnnotateStatus = 'open' | 'in_progress' | 'resolved' | 'wont_fix'; @@ -115,6 +133,8 @@ export interface FeedbackExport { url: string; project: string; exportedViewport: { vw: number; vh: number; dpr: number }; + /** "site" when the file holds every page of the project; absent for a page export. */ + scope?: 'site'; comments: AnnotateComment[]; } @@ -133,7 +153,8 @@ export interface AnnotateAPI { comments(): AnnotateComment[]; focus(id: string): void; toast(message: string, options?: { kind?: 'info' | 'error' | 'success'; duration?: number }): void; - export(): void; + /** Download this page's comments, or every page's with { scope: 'site' } (local mode). */ + export(options?: { scope?: 'page' | 'site' }): void; import(): void; /** * Local mode: sends the current page's export JSON to postUrl; rejects on failure. diff --git a/annotate.js b/annotate.js index 2e47492..03e7024 100644 --- a/annotate.js +++ b/annotate.js @@ -24,6 +24,8 @@ * With data-review-id set, comments sync to that review. * data-review-id review to sync with when data-api is set * data-invite-param query parameter carrying the invite token (default an_invite) + * data-credentials "omit" (default) | "same-origin" | "include" — whether + * backend and data-post-url requests carry cookies * …or via `window.AnnotateConfig = { project, page, … }` before the script. * * Tools: text highlight, rectangle, circle, pin, freehand ink and section @@ -112,6 +114,13 @@ // CONFIG — resolved from (in priority order) the script tag's data-* attrs, // then a global window.AnnotateConfig object, then built-in defaults. // -------------------------------------------------------------------------- + // Cookies stay out of backend and postUrl requests unless the integrator + // opts in (a same-origin backend behind a cookie sign-in, for example). + // Anything other than the three Fetch values falls back to "omit". + function fetchCredentials(v) { + v = String(v || "").trim().toLowerCase(); + return v === "same-origin" || v === "include" ? v : "omit"; + } var scriptData = (SCRIPT && SCRIPT.dataset) || {}; // data-* attributes var globalConfig = config || window.AnnotateConfig || {}; // window.AnnotateConfig var explicitPage = scriptData.page || globalConfig.page || ""; @@ -131,8 +140,9 @@ reviewId: String(scriptData.reviewId || globalConfig.reviewId || "").trim(), inviteParam: String(scriptData.inviteParam || globalConfig.inviteParam || "an_invite").trim(), pollInterval: Math.max(500, Number(scriptData.pollInterval || globalConfig.pollInterval) || 20000), + credentials: fetchCredentials(scriptData.credentials || globalConfig.credentials), }; - // Integrator-supplied auth ({ getToken, onUnauthorized }) is object-only, + // Integrator-supplied auth ({ getToken, onUnauthorized, getReviewer }) is object-only, // so it can come from AnnotateConfig / init() but never from data-*. var authHook = globalConfig.auth && typeof globalConfig.auth.getToken === "function" ? globalConfig.auth : null; // An explicit data-page / AnnotateConfig.page is fixed; otherwise the page key @@ -382,6 +392,27 @@ // and address them; reviewers only ever receive their own. function isReviewAuthor() { return REMOTE && !!sync.reviewer && sync.reviewer.role === "author"; } + // Every comment this browser holds for the project, across all pages — + // the source of a site export. Same validation and unsaved overlay as + // pageComments(); comments inside a delete's undo window are left out. + function projectComments() { + var listed = dbRead().comments.filter(function (c) { + return isValidComment(c) && !pendingDeletes[c.id]; + }).map(normalizeComment); + var at = {}; + listed.forEach(function (c, i) { at[c.id] = i; }); + Object.keys(unsaved).forEach(function (id) { + var u = unsaved[id]; + if (!u || pendingDeletes[id]) return; + if (at[id] !== undefined) listed[at[id]] = u; else listed.push(u); + }); + return listed; + } + function pageCount(comments) { + var pages = {}; + comments.forEach(function (c) { pages[c.page] = true; }); + return Object.keys(pages).length; + } function pageComments() { // Validate stored records before touching properties: a corrupt/legacy // entry (e.g. [null]) must be skipped rather than crash rendering. @@ -652,7 +683,7 @@ if (sync.token) h.Authorization = "Bearer " + sync.token; if (body !== undefined) h["Content-Type"] = "application/json"; return window.fetch(API_BASE + path, { - method: method, headers: h, credentials: "omit", cache: "no-store", + method: method, headers: h, credentials: CFG.credentials, cache: "no-store", body: body === undefined ? undefined : JSON.stringify(body), signal: controller ? controller.signal : undefined, }).then(function (res) { @@ -710,8 +741,8 @@ p = Promise.resolve().then(function () { return authHook.getToken(); }).then(function (token) { sync.token = typeof token === "string" && token ? token : null; sync.expiresAt = sync.token ? Infinity : 0; - return sync.token; - }); + return sync.token ? hookReviewer() : null; + }).then(function () { return sync.token; }); } else { var invite = store.get(INVITE_KEY); var body = invite ? { invite: invite } : state.author ? { name: state.author } : null; @@ -726,16 +757,28 @@ sync.sessionPromise = p.finally(function () { sync.sessionPromise = null; }); return sync.sessionPromise; } + // With integrator auth there is no /session response to name the viewer, + // so an optional auth.getReviewer() supplies it ({ id, name, role }). A + // failing or malformed answer leaves the viewer unnamed, as before. + function hookReviewer() { + if (typeof authHook.getReviewer !== "function") return null; + return Promise.resolve().then(function () { return authHook.getReviewer(); }).then(function (r) { + if (destroyed || !r || typeof r !== "object" || typeof r.id !== "string" || !r.id) return; + setReviewer(r); + dispatch("annotate:auth", { reviewer: sync.reviewer }); + if (booted) renderPanel(); + }, function () {}); + } + function setReviewer(r) { + sync.reviewer = { id: r.id, name: String(r.name || ""), role: r.role === "author" ? "author" : "reviewer" }; + state.authorId = sync.reviewer.id; + if (sync.reviewer.name) state.author = sync.reviewer.name; + } function acceptSession(data) { sync.token = data.token; sync.expiresAt = Date.parse(data.expiresAt) || Date.now() + 3600000; sync.held = false; - if (data.reviewer && typeof data.reviewer.id === "string") { - sync.reviewer = { id: data.reviewer.id, name: String(data.reviewer.name || ""), - role: data.reviewer.role === "author" ? "author" : "reviewer" }; - state.authorId = sync.reviewer.id; - if (sync.reviewer.name) state.author = sync.reviewer.name; - } + if (data.reviewer && typeof data.reviewer.id === "string") setReviewer(data.reviewer); if (data.review && typeof data.review.note === "string" && data.review.note) { state.note = data.review.note; renderNote(); } dispatch("annotate:auth", { reviewer: sync.reviewer }); syncChanged(); @@ -1426,6 +1469,11 @@ #__an_foot .an-footrow.an-four .an-fbtn { flex-basis:calc(50% - 4px); } #__an_foot .an-fbtn:hover { background: var(--an-surface-2); border-color: var(--an-btn-bg); } #__an_foot .an-fbtn svg { width:15px; height:15px; } + #__an_foot .an-sitebtn { width:100%; border:0; background:none; color: var(--an-muted); + font:600 11.5px var(--an-font); cursor:pointer; display:flex; align-items:center; + justify-content:center; gap:6px; padding:2px; border-radius:6px; } + #__an_foot .an-sitebtn:hover { color: var(--an-fg); text-decoration:underline; } + #__an_foot .an-sitebtn svg { width:13px; height:13px; } /* ---- composer popover -------------------------------------------------- */ #__an_compose { position:absolute; z-index:2147483300; width:304px; @@ -3264,10 +3312,14 @@ setTimeout(function () { URL.revokeObjectURL(url); objectUrls.delete(url); }, 1000); } - function buildExportPayload(allowEmpty) { - var comments = state.comments.map(serialize); + // scope "site" exports every page of the project in one file and marks it + // so import can put each comment back on its own page. Files without a + // scope are page exports, imported onto the page that opens them. + function buildExportPayload(allowEmpty, scope) { + var site = scope === "site"; + var comments = (site ? projectComments() : state.comments).map(serialize); if (!comments.length && !allowEmpty) return null; - return { + var payload = { annotate: VERSION, schema: SCHEMA, kind: "annotate-export", @@ -3278,19 +3330,28 @@ exportedViewport: { vw: window.innerWidth, vh: window.innerHeight, dpr: window.devicePixelRatio || 1 }, comments: comments, }; + if (site) payload.scope = "site"; + return payload; } - function exportComments() { - var payload = buildExportPayload(); + function exportComments(options) { + var site = !!(options && options.scope === "site"); + // A synced review's pages live on the backend; this browser only caches + // the pages it has visited, so a site file from it would be incomplete. + if (site && REMOTE) { toast("This review keeps every page on the server — download one page at a time", { kind: "info" }); return; } + var payload = buildExportPayload(false, site ? "site" : "page"); if (!payload) { - toast("No comments on this page to export", { kind: "info" }); + toast(site ? "No comments in this project to export" : "No comments on this page to export", { kind: "info" }); return; } var comments = payload.comments; - var slug = (PAGE || "page").replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "page"; + var name = site ? (CFG.project || location.host || "site") + "-all-pages" : PAGE || "page"; + var slug = name.replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "page"; var stamp = new Date().toISOString().slice(0, 10); downloadJSON(payload, "annotate-" + slug + "-" + stamp + ".json"); - toast("Exported " + comments.length + " comment" + (comments.length === 1 ? "" : "s"), { kind: "success" }); + var pages = site ? pageCount(comments) : 1; + toast("Exported " + comments.length + " comment" + (comments.length === 1 ? "" : "s") + + (pages > 1 ? " across " + pages + " pages" : ""), { kind: "success" }); } // With a backend, submit means "every queued change is acknowledged"; @@ -3319,7 +3380,7 @@ var timeout = setTimeout(function () { if (postController) postController.abort(); }, 30000); toast("Sending feedback…", { kind: "info" }); submitting = window.fetch(endpoint.href, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), credentials: "omit", signal: postController ? postController.signal : undefined }) + body: JSON.stringify(payload), credentials: CFG.credentials, signal: postController ? postController.signal : undefined }) .then(function (response) { if (!response.ok) throw new Error("HTTP " + response.status); if (!destroyed) toast("Feedback sent", { kind: "success" }); @@ -3426,8 +3487,9 @@ if (incoming.length > MAX_EXPORT_COMMENTS) { toast("That file has too many comments to import", { kind: "error" }); return; } - // Warn if the export came from a different page - if (data.page && data.page !== PAGE) + var site = data.scope === "site"; + // Warn if a page export came from a different page + if (!site && data.page && data.page !== PAGE) toast("These comments were from a different page — positions may not match.", { kind: "info", duration: 6000 }); // Existing IDs span the WHOLE project (all pages), not just the current // route — so importing one page's export onto another page cannot create @@ -3442,7 +3504,7 @@ if (exists[c.id]) { skipped++; return; } // already imported to this project (any page) seenIds[c.id] = true; var copy = normalizeComment(serialize(c)); - copy.page = PAGE; + copy.page = site ? sitePageKey(c.page, data.project) : PAGE; prepared.push(copy); }); if (!prepared.length) { @@ -3459,7 +3521,19 @@ prepared.forEach(function (c) { remotePut(c, ["*"]); }); loadData(); var ok = prepared.length + (skipped ? " (" + skipped + " skipped)" : ""); - toast("Imported " + ok + " comment" + (prepared.length === 1 ? "" : "s"), { kind: "success" }); + var pages = site ? pageCount(prepared) : 1; + toast("Imported " + ok + " comment" + (prepared.length === 1 ? "" : "s") + + (pages > 1 ? " across " + pages + " pages" : ""), { kind: "success" }); + } + // A site file's page keys carry the exporting project's prefix. Re-key + // them to this project so the same site imports under any project name; + // a missing page falls back to the importing page, as a page export does. + function sitePageKey(page, exportedProject) { + var key = typeof page === "string" ? page : ""; + if (exportedProject && typeof exportedProject === "string" && key.indexOf(exportedProject + ":") === 0) + key = key.slice(exportedProject.length + 1); + if (!key) return PAGE; + return (CFG.project ? CFG.project + ":" : "") + key; } function copyLink(id) { @@ -3554,6 +3628,15 @@ canShare ? el("button", { class: "an-fbtn", title: "Send comments to " + state.share, html: ICONS.share + "Share", onclick: shareComments }) : null, el("button", { class: "an-fbtn", html: ICONS.upload + "Import", onclick: pickImportFile }), ])); + if (!REMOTE) { + var all = projectComments(), pages = pageCount(all); + if (all.length > n && pages > 1) footEl.appendChild(el("button", { + class: "an-sitebtn", "data-action": "download-site", + title: "Download the comments from every page of this site as one JSON file", + html: ICONS.download + "All pages (" + all.length + " comment" + (all.length === 1 ? "" : "s") + ", " + pages + " pages)", + onclick: function () { exportComments({ scope: "site" }); }, + })); + } } // Copy text to the clipboard with graceful fallback + toast feedback. @@ -3862,7 +3945,7 @@ comments: function () { return state.comments.map(serialize); }, focus: function (id) { focusComment(id, false); }, toast: toast, - export: function () { exportComments(); }, + export: function (options) { exportComments(options); }, import: function () { pickImportFile(); }, submit: submitAll, setStatus: function (id, status) { return setCommentStatus(id, status); }, diff --git a/annotate.mjs b/annotate.mjs index 640a184..09ae45f 100644 --- a/annotate.mjs +++ b/annotate.mjs @@ -71,6 +71,13 @@ const createController = function (host) { // CONFIG — resolved from (in priority order) the script tag's data-* attrs, // then a global window.AnnotateConfig object, then built-in defaults. // -------------------------------------------------------------------------- + // Cookies stay out of backend and postUrl requests unless the integrator + // opts in (a same-origin backend behind a cookie sign-in, for example). + // Anything other than the three Fetch values falls back to "omit". + function fetchCredentials(v) { + v = String(v || "").trim().toLowerCase(); + return v === "same-origin" || v === "include" ? v : "omit"; + } var scriptData = (SCRIPT && SCRIPT.dataset) || {}; // data-* attributes var globalConfig = config || window.AnnotateConfig || {}; // window.AnnotateConfig var explicitPage = scriptData.page || globalConfig.page || ""; @@ -90,8 +97,9 @@ const createController = function (host) { reviewId: String(scriptData.reviewId || globalConfig.reviewId || "").trim(), inviteParam: String(scriptData.inviteParam || globalConfig.inviteParam || "an_invite").trim(), pollInterval: Math.max(500, Number(scriptData.pollInterval || globalConfig.pollInterval) || 20000), + credentials: fetchCredentials(scriptData.credentials || globalConfig.credentials), }; - // Integrator-supplied auth ({ getToken, onUnauthorized }) is object-only, + // Integrator-supplied auth ({ getToken, onUnauthorized, getReviewer }) is object-only, // so it can come from AnnotateConfig / init() but never from data-*. var authHook = globalConfig.auth && typeof globalConfig.auth.getToken === "function" ? globalConfig.auth : null; // An explicit data-page / AnnotateConfig.page is fixed; otherwise the page key @@ -341,6 +349,27 @@ const createController = function (host) { // and address them; reviewers only ever receive their own. function isReviewAuthor() { return REMOTE && !!sync.reviewer && sync.reviewer.role === "author"; } + // Every comment this browser holds for the project, across all pages — + // the source of a site export. Same validation and unsaved overlay as + // pageComments(); comments inside a delete's undo window are left out. + function projectComments() { + var listed = dbRead().comments.filter(function (c) { + return isValidComment(c) && !pendingDeletes[c.id]; + }).map(normalizeComment); + var at = {}; + listed.forEach(function (c, i) { at[c.id] = i; }); + Object.keys(unsaved).forEach(function (id) { + var u = unsaved[id]; + if (!u || pendingDeletes[id]) return; + if (at[id] !== undefined) listed[at[id]] = u; else listed.push(u); + }); + return listed; + } + function pageCount(comments) { + var pages = {}; + comments.forEach(function (c) { pages[c.page] = true; }); + return Object.keys(pages).length; + } function pageComments() { // Validate stored records before touching properties: a corrupt/legacy // entry (e.g. [null]) must be skipped rather than crash rendering. @@ -611,7 +640,7 @@ const createController = function (host) { if (sync.token) h.Authorization = "Bearer " + sync.token; if (body !== undefined) h["Content-Type"] = "application/json"; return window.fetch(API_BASE + path, { - method: method, headers: h, credentials: "omit", cache: "no-store", + method: method, headers: h, credentials: CFG.credentials, cache: "no-store", body: body === undefined ? undefined : JSON.stringify(body), signal: controller ? controller.signal : undefined, }).then(function (res) { @@ -669,8 +698,8 @@ const createController = function (host) { p = Promise.resolve().then(function () { return authHook.getToken(); }).then(function (token) { sync.token = typeof token === "string" && token ? token : null; sync.expiresAt = sync.token ? Infinity : 0; - return sync.token; - }); + return sync.token ? hookReviewer() : null; + }).then(function () { return sync.token; }); } else { var invite = store.get(INVITE_KEY); var body = invite ? { invite: invite } : state.author ? { name: state.author } : null; @@ -685,16 +714,28 @@ const createController = function (host) { sync.sessionPromise = p.finally(function () { sync.sessionPromise = null; }); return sync.sessionPromise; } + // With integrator auth there is no /session response to name the viewer, + // so an optional auth.getReviewer() supplies it ({ id, name, role }). A + // failing or malformed answer leaves the viewer unnamed, as before. + function hookReviewer() { + if (typeof authHook.getReviewer !== "function") return null; + return Promise.resolve().then(function () { return authHook.getReviewer(); }).then(function (r) { + if (destroyed || !r || typeof r !== "object" || typeof r.id !== "string" || !r.id) return; + setReviewer(r); + dispatch("annotate:auth", { reviewer: sync.reviewer }); + if (booted) renderPanel(); + }, function () {}); + } + function setReviewer(r) { + sync.reviewer = { id: r.id, name: String(r.name || ""), role: r.role === "author" ? "author" : "reviewer" }; + state.authorId = sync.reviewer.id; + if (sync.reviewer.name) state.author = sync.reviewer.name; + } function acceptSession(data) { sync.token = data.token; sync.expiresAt = Date.parse(data.expiresAt) || Date.now() + 3600000; sync.held = false; - if (data.reviewer && typeof data.reviewer.id === "string") { - sync.reviewer = { id: data.reviewer.id, name: String(data.reviewer.name || ""), - role: data.reviewer.role === "author" ? "author" : "reviewer" }; - state.authorId = sync.reviewer.id; - if (sync.reviewer.name) state.author = sync.reviewer.name; - } + if (data.reviewer && typeof data.reviewer.id === "string") setReviewer(data.reviewer); if (data.review && typeof data.review.note === "string" && data.review.note) { state.note = data.review.note; renderNote(); } dispatch("annotate:auth", { reviewer: sync.reviewer }); syncChanged(); @@ -1385,6 +1426,11 @@ const createController = function (host) { #__an_foot .an-footrow.an-four .an-fbtn { flex-basis:calc(50% - 4px); } #__an_foot .an-fbtn:hover { background: var(--an-surface-2); border-color: var(--an-btn-bg); } #__an_foot .an-fbtn svg { width:15px; height:15px; } + #__an_foot .an-sitebtn { width:100%; border:0; background:none; color: var(--an-muted); + font:600 11.5px var(--an-font); cursor:pointer; display:flex; align-items:center; + justify-content:center; gap:6px; padding:2px; border-radius:6px; } + #__an_foot .an-sitebtn:hover { color: var(--an-fg); text-decoration:underline; } + #__an_foot .an-sitebtn svg { width:13px; height:13px; } /* ---- composer popover -------------------------------------------------- */ #__an_compose { position:absolute; z-index:2147483300; width:304px; @@ -3223,10 +3269,14 @@ const createController = function (host) { setTimeout(function () { URL.revokeObjectURL(url); objectUrls.delete(url); }, 1000); } - function buildExportPayload(allowEmpty) { - var comments = state.comments.map(serialize); + // scope "site" exports every page of the project in one file and marks it + // so import can put each comment back on its own page. Files without a + // scope are page exports, imported onto the page that opens them. + function buildExportPayload(allowEmpty, scope) { + var site = scope === "site"; + var comments = (site ? projectComments() : state.comments).map(serialize); if (!comments.length && !allowEmpty) return null; - return { + var payload = { annotate: VERSION, schema: SCHEMA, kind: "annotate-export", @@ -3237,19 +3287,28 @@ const createController = function (host) { exportedViewport: { vw: window.innerWidth, vh: window.innerHeight, dpr: window.devicePixelRatio || 1 }, comments: comments, }; + if (site) payload.scope = "site"; + return payload; } - function exportComments() { - var payload = buildExportPayload(); + function exportComments(options) { + var site = !!(options && options.scope === "site"); + // A synced review's pages live on the backend; this browser only caches + // the pages it has visited, so a site file from it would be incomplete. + if (site && REMOTE) { toast("This review keeps every page on the server — download one page at a time", { kind: "info" }); return; } + var payload = buildExportPayload(false, site ? "site" : "page"); if (!payload) { - toast("No comments on this page to export", { kind: "info" }); + toast(site ? "No comments in this project to export" : "No comments on this page to export", { kind: "info" }); return; } var comments = payload.comments; - var slug = (PAGE || "page").replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "page"; + var name = site ? (CFG.project || location.host || "site") + "-all-pages" : PAGE || "page"; + var slug = name.replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "page"; var stamp = new Date().toISOString().slice(0, 10); downloadJSON(payload, "annotate-" + slug + "-" + stamp + ".json"); - toast("Exported " + comments.length + " comment" + (comments.length === 1 ? "" : "s"), { kind: "success" }); + var pages = site ? pageCount(comments) : 1; + toast("Exported " + comments.length + " comment" + (comments.length === 1 ? "" : "s") + + (pages > 1 ? " across " + pages + " pages" : ""), { kind: "success" }); } // With a backend, submit means "every queued change is acknowledged"; @@ -3278,7 +3337,7 @@ const createController = function (host) { var timeout = setTimeout(function () { if (postController) postController.abort(); }, 30000); toast("Sending feedback…", { kind: "info" }); submitting = window.fetch(endpoint.href, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), credentials: "omit", signal: postController ? postController.signal : undefined }) + body: JSON.stringify(payload), credentials: CFG.credentials, signal: postController ? postController.signal : undefined }) .then(function (response) { if (!response.ok) throw new Error("HTTP " + response.status); if (!destroyed) toast("Feedback sent", { kind: "success" }); @@ -3385,8 +3444,9 @@ const createController = function (host) { if (incoming.length > MAX_EXPORT_COMMENTS) { toast("That file has too many comments to import", { kind: "error" }); return; } - // Warn if the export came from a different page - if (data.page && data.page !== PAGE) + var site = data.scope === "site"; + // Warn if a page export came from a different page + if (!site && data.page && data.page !== PAGE) toast("These comments were from a different page — positions may not match.", { kind: "info", duration: 6000 }); // Existing IDs span the WHOLE project (all pages), not just the current // route — so importing one page's export onto another page cannot create @@ -3401,7 +3461,7 @@ const createController = function (host) { if (exists[c.id]) { skipped++; return; } // already imported to this project (any page) seenIds[c.id] = true; var copy = normalizeComment(serialize(c)); - copy.page = PAGE; + copy.page = site ? sitePageKey(c.page, data.project) : PAGE; prepared.push(copy); }); if (!prepared.length) { @@ -3418,7 +3478,19 @@ const createController = function (host) { prepared.forEach(function (c) { remotePut(c, ["*"]); }); loadData(); var ok = prepared.length + (skipped ? " (" + skipped + " skipped)" : ""); - toast("Imported " + ok + " comment" + (prepared.length === 1 ? "" : "s"), { kind: "success" }); + var pages = site ? pageCount(prepared) : 1; + toast("Imported " + ok + " comment" + (prepared.length === 1 ? "" : "s") + + (pages > 1 ? " across " + pages + " pages" : ""), { kind: "success" }); + } + // A site file's page keys carry the exporting project's prefix. Re-key + // them to this project so the same site imports under any project name; + // a missing page falls back to the importing page, as a page export does. + function sitePageKey(page, exportedProject) { + var key = typeof page === "string" ? page : ""; + if (exportedProject && typeof exportedProject === "string" && key.indexOf(exportedProject + ":") === 0) + key = key.slice(exportedProject.length + 1); + if (!key) return PAGE; + return (CFG.project ? CFG.project + ":" : "") + key; } function copyLink(id) { @@ -3513,6 +3585,15 @@ const createController = function (host) { canShare ? el("button", { class: "an-fbtn", title: "Send comments to " + state.share, html: ICONS.share + "Share", onclick: shareComments }) : null, el("button", { class: "an-fbtn", html: ICONS.upload + "Import", onclick: pickImportFile }), ])); + if (!REMOTE) { + var all = projectComments(), pages = pageCount(all); + if (all.length > n && pages > 1) footEl.appendChild(el("button", { + class: "an-sitebtn", "data-action": "download-site", + title: "Download the comments from every page of this site as one JSON file", + html: ICONS.download + "All pages (" + all.length + " comment" + (all.length === 1 ? "" : "s") + ", " + pages + " pages)", + onclick: function () { exportComments({ scope: "site" }); }, + })); + } } // Copy text to the clipboard with graceful fallback + toast feedback. @@ -3821,7 +3902,7 @@ const createController = function (host) { comments: function () { return state.comments.map(serialize); }, focus: function (id) { focusComment(id, false); }, toast: toast, - export: function () { exportComments(); }, + export: function (options) { exportComments(options); }, import: function () { pickImportFile(); }, submit: submitAll, setStatus: function (id, status) { return setCommentStatus(id, status); }, diff --git a/tests/integration.spec.js b/tests/integration.spec.js index ccf07d4..0b2199d 100644 --- a/tests/integration.spec.js +++ b/tests/integration.spec.js @@ -250,6 +250,120 @@ test.describe('public integration contract', () => { .toEqual(['Please review this']); }); + test('credentials option controls whether backend and postUrl requests carry cookies', async ({ page, context, browserName }) => { + // Playwright's WebKit does not expose the Cookie header to route handlers, + // even for fetch(..., { credentials: 'include' }). Record the credentials + // mode passed to fetch in every browser, and check the header elsewhere. + const cookieHeaderVisible = browserName !== 'webkit'; + await page.addInitScript(() => { + const realFetch = window.fetch; + window.__credsSeen = []; + window.fetch = function (input, init) { + const url = typeof input === 'string' ? input : input.url; + if (url.includes('/__creds/')) window.__credsSeen.push({ url, credentials: init && init.credentials }); + return realFetch.apply(this, arguments); + }; + }); + await context.addCookies([{ name: 'proxy_session', value: 'signed-in', url: 'http://localhost:4200' }]); + const seen = []; + await page.route('**/__creds/**', async route => { + const request = route.request(); + seen.push({ path: new URL(request.url()).pathname, cookie: (await request.allHeaders()).cookie || '' }); + const body = request.method() === 'GET' ? '{"comments":[]}' : '{"ok":true}'; + await route.fulfill({ status: 200, contentType: 'application/json', body }); + }); + await page.goto('/'); + await page.waitForFunction(() => !!window.Annotate); + + async function run(credentials) { + seen.length = 0; + await page.evaluate(credentials => { + window.__credsSeen.length = 0; + window.Annotate.destroy(); + const config = { + project: 'creds-' + (credentials || 'default'), postUrl: '/__creds/feedback', + api: '/__creds/api', reviewId: 'rvw_creds', pollInterval: 500, + auth: { getToken: () => 'token' }, + }; + if (credentials) config.credentials = credentials; + window.Annotate.init(config); + }, credentials); + await expect.poll(() => seen.some(r => r.path.includes('/comments'))).toBe(true); + await page.evaluate(() => { + window.Annotate.destroy(); + const project = 'creds-post'; + localStorage.setItem('annotate:' + project, JSON.stringify({ comments: [{ + id: 'creds-1', page: project + ':/', type: 'note', author: 'Test', text: 'Hi', + color: '#f59e0b', resolved: false, replies: [], + createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), + }] })); + }); + await page.evaluate(credentials => { + const config = { project: 'creds-post', postUrl: '/__creds/feedback' }; + if (credentials) config.credentials = credentials; + return window.Annotate.init(config).submit(); + }, credentials); + return { + api: seen.filter(r => r.path.includes('/comments')).map(r => r.cookie), + post: seen.filter(r => r.path.endsWith('/feedback')).map(r => r.cookie), + resolved: await page.evaluate(() => window.Annotate.config.credentials), + modes: await page.evaluate(() => [...new Set(window.__credsSeen.map(r => r.credentials))]), + }; + } + + const omitted = await run(undefined); + expect(omitted.resolved).toBe('omit'); + expect(omitted.modes).toEqual(['omit']); + expect(omitted.api[0]).toBe(''); + expect(omitted.post).toEqual(['']); + + const sameOrigin = await run('same-origin'); + expect(sameOrigin.resolved).toBe('same-origin'); + expect(sameOrigin.modes).toEqual(['same-origin']); + expect(sameOrigin.post).toHaveLength(1); + if (cookieHeaderVisible) { + expect(sameOrigin.api[0]).toContain('proxy_session=signed-in'); + expect(sameOrigin.post).toEqual(['proxy_session=signed-in']); + } + + const bogus = await run('everything'); + expect(bogus.resolved).toBe('omit'); + expect(bogus.modes).toEqual(['omit']); + expect(bogus.post).toEqual(['']); + }); + + test('auth.getReviewer names the signed-in viewer and a failing one is ignored', async ({ page }) => { + let polls = 0; + await page.route('**/__who/**', route => { + if (route.request().url().includes('/comments')) polls++; + return route.fulfill({ status: 200, contentType: 'application/json', body: '{"comments":[]}' }); + }); + await page.goto('/'); + await page.waitForFunction(() => !!window.Annotate); + const auth = await page.evaluate(() => new Promise(resolve => { + window.Annotate.destroy(); + window.addEventListener('annotate:auth', e => resolve(e.detail), { once: true }); + window.Annotate.init({ + project: 'who', api: '/__who', reviewId: 'rvw_who', + auth: { getToken: () => 'token', getReviewer: () => Promise.resolve({ id: 'rvr_me', name: 'Me', role: 'author' }) }, + }); + })); + expect(auth.reviewer).toEqual({ id: 'rvr_me', name: 'Me', role: 'author' }); + + polls = 0; + await page.evaluate(() => { + window.Annotate.destroy(); + window.__authEvents = 0; + window.addEventListener('annotate:auth', () => window.__authEvents++); + window.Annotate.init({ + project: 'who-broken', api: '/__who', reviewId: 'rvw_who', + auth: { getToken: () => 'token', getReviewer: () => { throw new Error('nope'); } }, + }); + }); + await expect.poll(() => polls).toBeGreaterThan(0); + expect(await page.evaluate(() => window.__authEvents)).toBe(0); + }); + test('share destination expands page, count, and summary placeholders', async ({ page }) => { await page.context().route('https://example.test/**', route => route.fulfill({ contentType: 'text/html', body: '

Issue form

' })); await page.goto('/'); diff --git a/tests/site-export.spec.js b/tests/site-export.spec.js new file mode 100644 index 0000000..2cbeba3 --- /dev/null +++ b/tests/site-export.spec.js @@ -0,0 +1,122 @@ +// @ts-check +// Multi-page review: one download carries every page of the project, and +// importing it puts each comment back on the page it was made on. +const { test, expect } = require('@playwright/test'); + +const PAGES = ['/__site/a', '/__site/b', '/__site/c']; + +function comment(id, page, text) { + const now = new Date().toISOString(); + return { + id, page, url: 'http://localhost:4200' + page.replace(/^[^:]*:/, ''), type: 'note', author: 'Rev', + text, color: '#f59e0b', resolved: false, replies: [], createdAt: now, updatedAt: now, + }; +} + +test.beforeEach(async ({ page }) => { + // Same private hook injection as annotate.spec.js: the published script + // carries no test hooks, so only this browser's copy gets one. + await page.route('**/annotate.js', async route => { + const response = await route.fetch(); + const source = await response.text(); + const marker = '// ANNOTATE TEST INJECTION POINT'; + if (!source.includes(marker)) throw new Error('annotate.js is missing the private test injection marker'); + const hooks = 'Object.assign(controller, { _annotateImportForTest: function (data) { importComments(data); } });'; + await route.fulfill({ response, body: source.replace(marker, hooks) }); + }); + await page.route('**/__site/*', route => route.fulfill({ + contentType: 'text/html', + body: '

Site page

Body copy.

', + })); + await page.goto(PAGES[0]); + await page.evaluate(() => { localStorage.clear(); localStorage.setItem('an-author', 'Rev'); }); +}); + +async function boot(page, path, project) { + await page.goto(path); + await page.addScriptTag({ url: '/annotate.js' }); + await page.waitForFunction(() => !!window.Annotate); + await page.evaluate(project => { + window.Annotate.destroy(); + window.Annotate.init({ project }); + }, project); +} + +async function download(page, trigger) { + const [file] = await Promise.all([page.waitForEvent('download'), trigger()]); + const fs = require('node:fs/promises'); + return JSON.parse(await fs.readFile(await file.path(), 'utf8')); +} + +test('site export carries every page and import restores each comment to its own page', async ({ page }) => { + await page.evaluate(() => { + const now = new Date().toISOString(); + const mk = (id, path, text) => ({ id, page: 'site:' + path, url: location.origin + path, type: 'note', author: 'Rev', + text, color: '#f59e0b', resolved: false, replies: [], createdAt: now, updatedAt: now }); + localStorage.setItem('annotate:site', JSON.stringify({ comments: [ + mk('a1', '/__site/a', 'On A'), mk('b1', '/__site/b', 'On B'), mk('b2', '/__site/b', 'Also B'), + mk('x1', '/__site/x', 'Other'), + ] })); + localStorage.setItem('annotate:elsewhere', JSON.stringify({ comments: [mk('e1', '/__site/a', 'Wrong project')] })); + }); + await boot(page, PAGES[0], 'site'); + + const pageOnly = await download(page, () => page.evaluate(() => window.Annotate.export())); + expect(pageOnly.scope).toBeUndefined(); + expect(pageOnly.comments.map(c => c.id)).toEqual(['a1']); + + const site = await download(page, () => page.evaluate(() => window.Annotate.export({ scope: 'site' }))); + expect(site.scope).toBe('site'); + expect(site.project).toBe('site'); + expect(site.comments.map(c => c.id).sort()).toEqual(['a1', 'b1', 'b2', 'x1']); + + // Import into a fresh browser under a different project name: every + // comment lands on its own path, re-keyed to the importing project. + await page.evaluate(() => localStorage.clear()); + await boot(page, PAGES[2], 'renamed'); + await page.evaluate(data => window.Annotate._annotateImportForTest(data), site); + await expect(page.locator('.an-toast', { hasText: 'Imported 4 comments across 3 pages' })).toBeVisible(); + expect(await page.evaluate(() => window.Annotate.comments().length)).toBe(0); + const stored = await page.evaluate(() => JSON.parse(localStorage.getItem('annotate:renamed')).comments + .map(c => [c.id, c.page]).sort()); + expect(stored).toEqual([ + ['a1', 'renamed:/__site/a'], ['b1', 'renamed:/__site/b'], ['b2', 'renamed:/__site/b'], ['x1', 'renamed:/__site/x'], + ]); + + await boot(page, PAGES[1], 'renamed'); + expect(await page.evaluate(() => window.Annotate.comments().map(c => c.text).sort())).toEqual(['Also B', 'On B']); + + // Importing the same file again adds nothing. + await page.evaluate(data => window.Annotate._annotateImportForTest(data), site); + await expect(page.locator('.an-toast', { hasText: 'Nothing new to import' })).toBeVisible(); +}); + +test('a page export still lands on the importing page', async ({ page }) => { + await boot(page, PAGES[1], 'legacy'); + await page.evaluate(data => window.Annotate._annotateImportForTest(data), { + annotate: '1.5.3', kind: 'annotate-export', page: 'legacy:/__site/a', project: 'legacy', + comments: [comment('p1', 'legacy:/__site/a', 'From A')], + }); + expect(await page.evaluate(() => window.Annotate.comments().map(c => [c.id, c.page]))) + .toEqual([['p1', 'legacy:/__site/b']]); +}); + +test('the footer offers an all-pages download only when other pages have comments', async ({ page }) => { + await boot(page, PAGES[0], 'foot'); + await page.evaluate(() => window.Annotate.open()); + const allPages = page.locator('#__an_foot [data-action="download-site"]'); + await expect(allPages).toHaveCount(0); + + await page.evaluate(() => { + const now = new Date().toISOString(); + localStorage.setItem('annotate:foot', JSON.stringify({ comments: [ + { id: 'f1', page: 'foot:/__site/a', type: 'note', author: 'Rev', text: 'Here', color: '#f59e0b', resolved: false, replies: [], createdAt: now, updatedAt: now }, + { id: 'f2', page: 'foot:/__site/b', type: 'note', author: 'Rev', text: 'There', color: '#f59e0b', resolved: false, replies: [], createdAt: now, updatedAt: now }, + ] })); + window.Annotate.refresh(); + }); + await expect(allPages).toHaveText(/All pages \(2 comments, 2 pages\)/); + const data = await download(page, () => allPages.click()); + expect(data.scope).toBe('site'); + expect(data.comments.map(c => c.id).sort()).toEqual(['f1', 'f2']); +});