Files
co-lite/solvway-admin-portal/app/lib/frameHtml.ts
T
ngqileandClaude Opus 5.5 92e62fb3fd fix(pages): reserve the reg- prefix for the sign-up form's field ids
A block named reg-email would have duplicated the form's input id, so its
label and #reg-email links would bind to the wrong element.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-03 09:43:23 +08:00

86 lines
4.9 KiB
TypeScript

// add-custom-html-block: a Custom HTML block runs sealed. It is served as its own document whose
// Content-Security-Policy `sandbox` gives it an opaque origin, even when its address is opened directly, and it is
// shown in an <iframe sandbox> with the same grants. No same-origin, forms, top navigation or modals.
export const FRAME_SANDBOX = "allow-scripts allow-popups allow-popups-to-escape-sandbox";
/** The frame document's own policy. next.config sends it too: config headers replace a route's header of the same name. */
export const FRAME_CSP = `sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`;
export const FRAME_MESSAGE = "colite-frame-height";
export const START_HEIGHT = 600;
const MIN_HEIGHT = 100;
const MAX_HEIGHT = 20000;
export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
/** A block link name, as in cmsPages (kept here as a string for the frame script). */
const ANCHOR_SOURCE = "^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$";
const ANCHOR = new RegExp(ANCHOR_SOURCE);
// Posts the document height to the parent page on load and whenever it changes. A click on a #name link
// (add-page-anchor-links) asks the page to scroll instead: the frame is as tall as its content and never scrolls.
const FRAME_SCRIPT =
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s();` +
`document.addEventListener("click",function(e){var a=e.target&&e.target.closest&&e.target.closest('a[href^="#"]');if(!a)return;` +
`var n=a.getAttribute("href").slice(1);if(!/${ANCHOR_SOURCE}/.test(n))return;e.preventDefault();var t=document.getElementById(n);` +
`parent.postMessage({type:"${FRAME_ANCHOR_MESSAGE}",name:n,y:t?Math.round(t.getBoundingClientRect().top+scrollY):null},"*")})})();</script>`;
/** The pasted HTML with the frame script before its last </body>, or appended when it is a fragment. */
export function frameDocument(html: string): string {
const at = html.toLowerCase().lastIndexOf("</body>");
return at < 0 ? html + FRAME_SCRIPT : html.slice(0, at) + FRAME_SCRIPT + html.slice(at);
}
export function frameResponse(html: string, { preview }: { preview: boolean }): Response {
return new Response(frameDocument(html), {
headers: {
"Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": FRAME_CSP,
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Cache-Control": preview ? "no-store" : "public, max-age=60",
},
});
}
/** The same empty answer for every frame miss. */
export const frameNotFound = () => new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
/** The HTML of block `index` when it is an HTML block, else null. */
export function htmlBlock(blocks: unknown, index: string): string | null {
if (!/^\d{1,2}$/.test(index) || !Array.isArray(blocks)) return null;
const block = blocks[Number(index)] as { type?: unknown; html?: unknown } | undefined;
return block?.type === "HTML" && typeof block.html === "string" ? block.html : null;
}
export interface FrameHeight {
height: number;
/** The last growth steps, to spot content that grows with the frame. */
steps: number[];
}
/**
* The frame's next height after a message from it. Junk leaves the state as it is. A section sized by the viewport
* (100vh) grows with the frame, so each report is the frame plus the same remainder: after two equal steps the
* frame stops growing.
* ponytail: equal-step heuristic; a page that grows by the same step three times for another reason stops early.
*/
export function nextFrameHeight(state: FrameHeight, data: unknown): FrameHeight {
const d = data as { type?: unknown; height?: unknown } | null;
if (!d || typeof d !== "object" || d.type !== FRAME_MESSAGE || typeof d.height !== "number" || !Number.isFinite(d.height)) return state;
const height = Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(d.height)));
if (height <= state.height) return { height, steps: [] };
const step = height - state.height;
const [a, b] = state.steps.slice(-2);
if (a !== undefined && b !== undefined && Math.abs(a - step) <= 2 && Math.abs(b - step) <= 2) return state;
return { height, steps: [...state.steps, step].slice(-2) };
}
/** A same-page link request from a frame: a valid link name and the target's offset in the frame (null when the frame lacks it). Junk is null. */
export function frameAnchor(data: unknown): { name: string; y: number | null } | null {
const d = data as { type?: unknown; name?: unknown; y?: unknown } | null;
if (!d || typeof d !== "object" || d.type !== FRAME_ANCHOR_MESSAGE || typeof d.name !== "string" || !ANCHOR.test(d.name)) return null;
if (d.y === null) return { name: d.name, y: null };
if (typeof d.y !== "number" || !Number.isFinite(d.y)) return null;
return { name: d.name, y: Math.min(MAX_HEIGHT, Math.max(0, Math.round(d.y))) };
}