Add Notebook tabs and a CodeMirror editor, rename Notepad to Notebook, add Back to Questions

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-20 10:15:36 -07:00
1 parent 2075d235d8
commit d4adb53a3a
55 files changed
+4017 -9231

No files matched your search

+94 -51
View File
@@ -1,8 +1,8 @@
// Plan2Code Web Console - the Notepad's save rules, status words and error sentences.
// Plan2Code Web Console - the Notebook's save rules, status words and error sentences.
//
// The source of truth for when the page saves the note, how it retries, what
// the status line says and the sentence each server refusal becomes. The
// Notepad screen only runs timers and requests on what these return. No DOM
// Notebook screen only runs timers and requests on what these return. No DOM
// access at module scope and no imports: the page and `node --test` both
// import this file. The limits mirror notepads.mjs (a test keeps them equal),
// copied rather than imported because the page cannot load server modules.
@@ -12,9 +12,23 @@ export const RETRY_STEPS_MS = Object.freeze([1000, 2000, 4000, 8000, 16000, 3000
export const NOTE_MAX_BYTES = 1024 * 1024;
export const NOTEPAD_MAX_IMAGES = 200;
export const IMAGE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
export const TAB_ID_RE = /^[0-9a-f]{12}$/;
export const TAB_NAME_MAX = 40;
export const NOTEPAD_MAX_TABS = 20;
// The codes the /notepad routes send as `{ error: code }`.
export const ERROR_CODES = Object.freeze(["bad", "too-long", "not-jpeg", "too-large", "too-many", "not-found"]);
export const ERROR_CODES = Object.freeze([
"bad",
"too-long",
"not-jpeg",
"too-large",
"too-many",
"not-found",
"bad-name",
"duplicate-name",
"too-many-tabs",
"no-such-tab",
]);
// UTF-8 bytes, the unit the server's cap is in (a character count would let
// non-ASCII text past the page's check and into a 413).
@@ -121,6 +135,10 @@ const ERROR_SENTENCES = Object.freeze({
"too-large": "That picture is too large to add. Try a smaller one.",
"too-many": `This notepad already holds ${NOTEPAD_MAX_IMAGES} pictures, the most it can keep. Delete one to add another.`,
"not-found": "That picture is no longer in this notepad.",
"bad-name": `A tab name needs 1 to ${TAB_NAME_MAX} characters, with no control characters.`,
"duplicate-name": "There is already a tab with that name.",
"too-many-tabs": `This notepad already has ${NOTEPAD_MAX_TABS} tabs, the most it can have. Delete one to add another.`,
"no-such-tab": "That tab is no longer in this notepad.",
});
const LOST_CONTACT = "Lost contact with Plan2Code. Your text is kept here and will be saved once it's back.";
@@ -129,66 +147,91 @@ const LOST_CONTACT = "Lost contact with Plan2Code. Your text is kept here and wi
// stays read-only, since anything typed would be saved over the real note.
export const NOT_LOADED = "Could not read the note. Close the notepad and open it again.";
// The status line when the editor itself could not be loaded.
export const EDITOR_NOT_LOADED = "The editor could not be loaded. Close the notepad and open it again.";
// One plain sentence for a server refusal; anything else (status 0, an
// unknown code) is treated as a lost connection.
export function errorSentence(code) {
return typeof code === "string" && Object.prototype.hasOwnProperty.call(ERROR_SENTENCES, code) ? ERROR_SENTENCES[code] : LOST_CONTACT;
}
/* ------------------------------------------------------------ editor */
/* ------------------------------------------------------------ tabs */
// OverType's HTML without its inline style attributes, which the page's
// policy refuses. A link's `anchor-name` (what OverType's link tooltip finds
// the link by) moves to `data-anchor`; any other style attribute is dropped,
// and the tooltip's own look comes from notepad.css instead. Typed text never
// matches: OverType escapes the quotes in it.
const STYLE_ATTR = / style="([^"]*)"/g;
const ANCHOR_NAME = /^anchor-name: (--link-\d+)$/;
export function withoutStyleAttrs(html) {
return html.replace(STYLE_ATTR, (_, css) => {
const anchor = ANCHOR_NAME.exec(css);
return anchor ? ` data-anchor="${anchor[1]}"` : "";
});
// A tab name as the server will keep it (notepads.mjs normalizeTabName):
// trimmed, inner whitespace collapsed, 1 to TAB_NAME_MAX code points, no
// control characters. `{ ok: true, name }` or `{ ok: false, reason }`.
export function cleanTabName(name) {
const clean = typeof name === "string" ? name.trim().replace(/\s+/g, " ") : "";
if (!clean) return { ok: false, reason: "empty" };
if ([...clean].length > TAB_NAME_MAX) return { ok: false, reason: "too-long" };
if (/[\u0000-\u001f\u007f]/.test(clean)) return { ok: false, reason: "control" };
return { ok: true, name: clean };
}
// OverType's HTML cut into its top-level elements (one per line, or one per
// run of list items), as strings, so the page can tell which lines changed
// without parsing the whole note into elements on every key. Tags are
// counted, not parsed: OverType escapes `<` and `>` in text and attribute
// values, so every `<` here starts a real tag. null when the HTML does not
// end balanced, so the caller redraws everything instead.
const TAG = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*?(\/?)>/g;
const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
const nameKey = (name) => name.toLocaleLowerCase("en-US");
export function topLevelParts(html) {
const parts = [];
let depth = 0;
let start = 0;
TAG.lastIndex = 0;
for (let m; (m = TAG.exec(html)); ) {
if (depth === 0 && m.index > start) return null;
const [, closing, name, selfClosing] = m;
if (closing) depth -= 1;
else if (!selfClosing && !VOID_TAGS.has(name.toLowerCase())) depth += 1;
if (depth < 0) return null;
if (depth === 0) {
parts.push(html.slice(start, TAG.lastIndex));
start = TAG.lastIndex;
}
}
return depth === 0 && start === html.length ? parts : null;
// Whether another tab (not `exceptId`) already has this name, in any case.
export function nameTaken(tabs, name, exceptId) {
const clean = cleanTabName(name);
if (!clean.ok) return false;
const key = nameKey(clean.name);
return (Array.isArray(tabs) ? tabs : []).some((tab) => tab && tab.id !== exceptId && typeof tab.name === "string" && nameKey(cleanTabName(tab.name).name || tab.name) === key);
}
// How many parts at the start (`head`) and at the end (`tail`) are the same
// in both lists, never overlapping: everything between them changed.
export function changedRange(before, after) {
const most = Math.min(before.length, after.length);
let head = 0;
while (head < most && before[head] === after[head]) head++;
let tail = 0;
while (tail < most - head && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail++;
return { head, tail };
const NAME_PROBLEMS = Object.freeze({
empty: "Give the tab a name.",
"too-long": `Use ${TAB_NAME_MAX} characters or fewer.`,
control: "Use plain letters, numbers and punctuation in the name.",
});
// The sentence to show under the name field, or "" when the name will do.
export function tabNameProblem(tabs, name, exceptId) {
const clean = cleanTabName(name);
if (!clean.ok) return NAME_PROBLEMS[clean.reason];
return nameTaken(tabs, clean.name, exceptId) ? ERROR_SENTENCES["duplicate-name"] : "";
}
// A new order with `id` moved `delta` places: clamped at both ends, never
// wrapping; the same order when `id` is not in it.
export function moveTab(order, id, delta) {
const list = Array.isArray(order) ? [...order] : [];
const from = list.indexOf(id);
if (from < 0 || !Number.isInteger(delta)) return list;
const at = Math.max(0, Math.min(list.length - 1, from + delta));
list.splice(from, 1);
list.splice(at, 0, id);
return list;
}
// A new order with `id` just before `beforeId` (the end when `beforeId` is
// null), for a drop; unchanged for an unknown id or a drop on itself.
export function dropTab(order, id, beforeId) {
const list = Array.isArray(order) ? [...order] : [];
if (!list.includes(id) || id === beforeId) return list;
const rest = list.filter((x) => x !== id);
const at = beforeId == null ? rest.length : rest.indexOf(beforeId);
rest.splice(at < 0 ? rest.length : at, 0, id);
return rest;
}
// Whether leaving the tab now must first save it: there is text the stored
// note must not lose (keepsText) or text not yet on disk (unsaved).
export function tabSwitch(state) {
return keepsText(state) || unsaved(state);
}
// The two-confirm delete: "none" until Delete is pressed, then "ask", then
// "sure"; the second confirm finishes it ("done"). Cancel or Escape at either
// step goes back to "none". Anything else leaves the stage as it was.
export const DELETE_STAGES = Object.freeze({ none: "none", ask: "ask", sure: "sure" });
export function nextDelete(stage, event) {
if (event === "cancel" || event === "escape") return "none";
if (stage === "none" && event === "click") return "ask";
if (stage === "ask" && event === "confirm") return "sure";
if (stage === "sure" && event === "confirm") return "done";
return stage;
}
/* ------------------------------------------------------------ viewer */