Merge pull request #15 from jparkerweb/notepad
Add Notebook tabs and a CodeMirror editor, rename Notepad to Notebook…
No files matched your search
@@ -52,7 +52,7 @@ plan2code/
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
|
||||
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
|
||||
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
|
||||
│ ├── vendor-overtype.mjs # Dev-only: loads the vendored OverType in a browser and writes the CSS it would inject into `public/styles/notepad.css`, above the `/* end OverType */` marker; run it after upgrading the vendored file
|
||||
│ ├── vendor-codemirror.mjs # Dev-only: bundles the pinned CodeMirror 6 packages with esbuild into `public/vendor/codemirror.esm.js` (installed in a temp folder from `vendor-codemirror-lock.json`, never in the repo)
|
||||
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
|
||||
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
||||
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
||||
@@ -252,11 +252,14 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
|
||||
| `notepads.mjs` | the notepad store, the only code that names, reads, writes and removes notepads, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests): `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `readNotepad()` (never creates or writes anything), `saveNote()` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures at most, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notepad's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `IMAGE_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), `withoutStyleAttrs()` (OverType's HTML without its inline `style` attributes, which the policy refuses: a link's `anchor-name` moves to `data-anchor`), `topLevelParts()` and `changedRange()` (the styled layer cut into its top-level elements as strings, and which run of them changed) and `step()` (wrapping through the pictures) |
|
||||
| `public/screens/notepad.js` | the Notepad: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one OverType editor (made on first open, after setting `OverType.stylesInjected = true`), the text read from `GET /notepad` on every open (the editor is read-only until the first read lands, so nothing typed into an empty editor is saved over the note), and autosave through `nextSave()` to `POST /notepad/text`, flushed on close and when the tab is hidden. Three things lean on OverType's internals: `buildWithoutStyleAttrs()` swaps `document.createElement` only while the editor is built, so the elements OverType makes (its preview and its link tooltip among them) get an `innerHTML` that runs `withoutStyleAttrs()`; `patchPreview()`, behind that same `innerHTML` on the preview, swaps only the lines that changed (a whole-note redraw took about 310 ms a key at 200 KB) and clears the code-fence shading OverType re-applies right after; and `linkTooltip.findAnchorElement` is pointed at `data-anchor` |
|
||||
| `public/vendor/overtype.esm.js` | OverType 2.6.1 (MIT), vendored unchanged from `https://cdn.jsdelivr.net/npm/overtype@2.6.1/dist/overtype.esm.js` (sha256 `87bc797660d2b1cf6bc13551be6fa9ffa6393a98af453293c0530d5ca4950874`): the Notepad's styled-in-place Markdown editor over a real textarea. Regenerate the CSS with `scripts/vendor-overtype.mjs` after any upgrade, then recheck what `screens/notepad.js` relies on: `updatePreview()` setting `preview.innerHTML` then calling `_applyCodeBlockBackgrounds()`, the elements `_createDOM()` and `LinkTooltip.createTooltip()` make with `document.createElement`, `_init()` reporting its first value through `onChange`, the `anchor-name` style on links and `linkTooltip.findAnchorElement()`, and `OverType.stylesInjected` |
|
||||
| `public/styles/notepad.css` | OverType's generated CSS (between its header and `/* end OverType */`, rewritten by `scripts/vendor-overtype.mjs`, since the page's `style-src 'self'` blocks the `<style>` OverType would inject), then the notepad's own rules: OverType's theme mapped onto the console's tokens, one monospace font at one size, the top bar button and the dialog |
|
||||
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
|
||||
| `public/screens/notepad.js` | the Notebook: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one CodeMirror editor (made on first open by a dynamic import of `notepad-editor.js`), the page's view of the notepad as `{ tabs, activeId }`, the name form (New tab and Rename, never `window.prompt`), the in-modal two-step delete, and autosave through `nextSave()` to `POST /notepad/text?tab=<id>`, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. **Every save and every picture is bound to the tab it was made in**: `saveTab` is fixed when the change is made, a picture entry carries its `tab`, and a switch waits for the save (`settled()`), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it |
|
||||
| `public/notepad-tabs.js` | the tab bar: `createTabs({ onSwitch, onChange })` with `draw(tabs, activeId)` (`role="tab"` buttons, roving `tabindex`, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an `.is-drop-before` mark that only a tab drag lights, focus kept across redraws, `#notepad-empty` and `#notepad-body` toggled) and `focusTab()`. No fetches: it calls back, and `screens/notepad.js` owns every request |
|
||||
| `public/notepad-editor.js` | the Notebook's live-preview editor on CodeMirror 6 (`makeCodeMirrorEditor(parent, { onChange, label })` returning `{ getValue, setValue, setReadOnly, focus, destroy }`). A `ViewPlugin` decorates only the lines in view from the Markdown syntax tree: heading line classes `cm-h1` to `cm-h6`, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (`.notepad-cm-host`), because CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, and adopts them as a constructed stylesheet inside a shadow root. `setValue()` is `setState()`: not reported through `onChange`, and the undo history is cleared (so each tab starts with a clean one) |
|
||||
| `public/notepad-editor.css` | the one stylesheet of that shadow root, linked from `notepad-editor.js` (a `<link>` inside the root, in `SERVABLE`, not in `CSS_ORDER`): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use `div.cm-editor` for the specificity |
|
||||
| `public/vendor/codemirror.esm.js` | CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by `scripts/vendor-codemirror.mjs` (sha256 `4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4`, the six top-level versions in the script and the file's header comment, everything they pull in pinned by `scripts/vendor-codemirror-lock.json` and installed with `npm ci`, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run `node scripts/vendor-codemirror.mjs --update-lock` (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock |
|
||||
| `public/styles/notepad.css` | the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is `notepad-editor.css`, inside its shadow root |
|
||||
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
|
||||
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
||||
@@ -282,7 +285,7 @@ Key design points:
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`), `notepad:<key>` (a month-old notepad, whole; see Notepad below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
@@ -319,7 +322,7 @@ Key design points:
|
||||
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
|
||||
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
|
||||
- **Notepad: the person's, one per folder, in `~/.plan2code/notepads/`, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads), and holds `meta.json` (`{ v, folder, created }`, written once), `note.md` and `images/<uuid>.jpg` with `<uuid>.thumb.jpg`. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. The page reaches it through six routes, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad` (`{ text, savedAt, images: [{ id, url, thumb }] }`), `POST /notepad/text` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image` and `POST /notepad/thumb?id=<uuid>` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete` (`{ id }`) and `GET /notepad/images/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`); the four POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }`. None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The CSP workaround.** OverType 2.6.1 (MIT, vendored unchanged as `public/vendor/overtype.esm.js`) adds a `<style>` element and inline `style` attributes, both of which `style-src 'self'` refuses: `screens/notepad.js` sets `OverType.stylesInjected = true` before making the one editor, OverType's own CSS ships at the top of `styles/notepad.css` (in `CSS_ORDER`, so it rides the joined stylesheet), and `withoutStyleAttrs()` strips the attributes from what OverType renders. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading OverType:** replace the vendored file from `https://cdn.jsdelivr.net/npm/overtype@<version>/dist/overtype.esm.js`, update its version and sha256 in its files-table row and the version in `HEADER` in `scripts/vendor-overtype.mjs`, run `node scripts/vendor-overtype.mjs` (needs a local Chrome or Edge; it rewrites only what sits above `/* end OverType */` and refuses a `notepad.css` without the marker), recheck the internals listed in the vendored file's row, then run the two notepad test files. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notepad for <folder>" by `screens/cleanup.js`, the key when it is missing) only when `staleNotepads()` finds the newest file in it (`newestMtime()` in `files.mjs`) `SESSION_MAX_AGE_MS` (30 days) old or more; `removeCleanup()` removes the whole folder through `removeNotepad()` (key checked against `NOTEPAD_KEY_RE`, contained in `notepadsDir()`, a link refused).
|
||||
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notebook for <folder>"Line truncated
|
||||
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
|
||||
@@ -146,8 +146,9 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
|
||||
- **Files in your notes.** Show instead of describe: attach a screenshot, a
|
||||
photo or a document to any note or quick question (see *Attachments in notes
|
||||
and questions* below).
|
||||
- **A notepad of your own.** One per project folder, for jottings and
|
||||
screenshots that are yours, not the agent's (see *Your notepad* below).
|
||||
- **A notebook of your own.** One per project folder, in named tabs, for
|
||||
jottings and screenshots that are yours, not the agent's (see *Your notebook*
|
||||
below).
|
||||
- **A nudge when it might be waiting on you.** Your agent may stop in the
|
||||
terminal to ask permission for something, and the page cannot see that. So
|
||||
the dashboard and every starting screen carry a one-line tip about hands-off
|
||||
@@ -410,34 +411,47 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
||||
they show in the tab too.
|
||||
|
||||
### Your notepad
|
||||
### Your notebook
|
||||
|
||||
The **Notepad** icon in the top bar, on the dashboard, every skill and the
|
||||
The **Notebook** icon in the top bar, on the dashboard, every skill and the
|
||||
finished screen, opens a large dialog with a scratch pad for the folder you are
|
||||
working in.
|
||||
|
||||
- **Markdown, styled as you type.** Headings, lists, bold and code take their
|
||||
look in place while the text itself stays plain Markdown (saved as
|
||||
`note.md`, up to 1 MB).
|
||||
- **Tabs.** A row of named tabs sits across the top, each with its own text and
|
||||
its own pictures. **+ New tab** asks for a name first (1 to 40 characters, no
|
||||
two the same in any case, up to 20 tabs), in a small dialog. There is no
|
||||
toolbar under the row: a double-click (or **F2**) on a tab renames it, the **x**
|
||||
beside its name deletes it (the **Delete** key does too), and tabs are moved
|
||||
only by dragging them. The tab you left open is the one you come back to.
|
||||
Delete opens a dialog that asks twice and takes the tab's text and pictures
|
||||
with it; with no tab left, the dialog asks you to make one. A notebook from before tabs opens
|
||||
as one tab called **Notes**.
|
||||
- **Markdown, styled as you type.** The editor shows Markdown in place:
|
||||
headings grow, bullets draw, bold, code, quotes and links take their look, and
|
||||
the marks come back on the line you are on. The text itself stays plain
|
||||
Markdown (saved as the tab's `note.md`, up to 1 MB).
|
||||
- **Pictures beside it.** Paste a screenshot, drop files on the dialog or press
|
||||
**Add image**: each becomes a thumbnail in a strip under the text (up to 200).
|
||||
Click one for a full-screen preview (arrow keys step through, Esc closes);
|
||||
its **X** asks before it deletes.
|
||||
- **It saves itself**, about a second after you stop typing and when you close
|
||||
the dialog. If the connection drops, your text stays in the page and is
|
||||
retried, and the tab warns before you close it with something unsaved.
|
||||
**Add image**: each becomes a thumbnail in a strip under the text (up to 200
|
||||
per tab). Click one for a full-screen preview (arrow keys step through, Esc
|
||||
closes); its **X** asks before it deletes.
|
||||
- **It saves itself**, about a second after you stop typing, when you close the
|
||||
dialog and before you switch tabs. If a tab's text cannot be saved, switching
|
||||
is refused ("Not saved yet, so staying on this tab") rather than losing it.
|
||||
If the connection drops, your text stays in the page and is retried, and the
|
||||
browser tab warns before you close it with something unsaved.
|
||||
- **One per folder, kept between sessions.** Every session started in the same
|
||||
folder (each git worktree counts as its own) opens the same notepad, in
|
||||
folder (each git worktree counts as its own) opens the same notebook, in
|
||||
`~/.plan2code/notepads/<folder-name>-<12 hex>/`: `meta.json` (which folder it
|
||||
belongs to), `note.md` and `images/`. Two pages open on one folder share it,
|
||||
and the last save wins.
|
||||
belongs to), `tabs.json` (the tabs, their order and the last one open) and one
|
||||
folder per tab, `tabs/<id>/`, holding its `note.md` and `images/`. Two pages
|
||||
open on one folder share it, and the last save wins.
|
||||
- **Private.** It never goes into your project, your session or anything the
|
||||
agent reads, so the agent never sees it. It stays on this machine.
|
||||
- **Removed only when you say.** No automatic cleanup touches it. Once the
|
||||
newest file in a notepad is 30 days old or more, *User Preferences →
|
||||
newest file in a notebook is 30 days old or more, *User Preferences →
|
||||
Cleanup* offers it as one item named after its folder's full path
|
||||
(*Notepad for /home/sam/code/shop*),
|
||||
and deleting it removes the whole notepad, text and pictures.
|
||||
(*Notebook for /home/sam/code/shop*),
|
||||
and deleting it removes the whole notebook, every tab's text and pictures.
|
||||
|
||||
### Session meter
|
||||
|
||||
@@ -748,7 +762,7 @@ exception being the note attachments the agent keeps for a spec, above):
|
||||
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
|
||||
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notepad for one folder: `meta.json`, `note.md` and `images/` (`notepads.mjs` is their one owner; the agent never reads them) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
|
||||
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
|
||||
@@ -781,8 +795,8 @@ the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
||||
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
||||
`console/`, `bin/`, `launcher.json`, `install.json` (what you installed, which
|
||||
`plan2code update` reads), `models.json`, `handoffs/` (old handoffs go by
|
||||
age, above) and `notepads/`. Each notepad whose newest file is 30 days old or
|
||||
more is listed as one item, *Notepad for* its folder, and goes whole; no
|
||||
age, above) and `notepads/`. Each notebook whose newest file is 30 days old or
|
||||
more is listed as one item, *Notebook for* its folder, and goes whole; no
|
||||
automatic sweep ever removes one. It also lists each
|
||||
folder in the project's `specs--completed/` whose newest file is more than 30
|
||||
days old: archived specs Finalize moved there. Deleting one is permanent:
|
||||
@@ -822,7 +836,7 @@ this:
|
||||
|
||||
### Routes
|
||||
|
||||
The upload routes, the send, the overview and handoff reads, the workspace and the notepad. Like every page route, they are on `127.0.0.1`
|
||||
The upload routes, the send, the overview and handoff reads, the workspace and the notebook. Like every page route, they are on `127.0.0.1`
|
||||
behind the session cookie, and the ones that write also check the request's
|
||||
origin.
|
||||
|
||||
@@ -841,12 +855,17 @@ origin.
|
||||
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
||||
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
||||
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
||||
| `GET /notepad` | The notepad for the folder this session runs in: `{ text, savedAt, images: [{ id, url, thumb }] }`. Reading never creates a file. |
|
||||
| `POST /notepad/text` | `{ text }`. Saves `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 413 `too-long` (over 1 MB). |
|
||||
| `POST /notepad/image` | Raw `image/jpeg` (the page re-encodes every picture first). Writes `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures). |
|
||||
| `POST /notepad/thumb?id=<uuid>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found`, 415 `not-jpeg`, 413 `too-large`. |
|
||||
| `POST /notepad/image/delete` | `{ id }`. Deletes a picture and its thumbnail; 404 `not-found`. |
|
||||
| `GET /notepad/images/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
|
||||
| `GET /notepad[?tab=<id>]` | The notepad for the folder this session runs in: `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images: [{ id, url, thumb }] } | null }`, with the tab's `text`, `savedAt` and `images` repeated at the top. Without `tab` it answers the last one used; 404 `no-such-tab` for an id it does not have. A notepad in the first shape answers one virtual tab, Notes. Reading never creates or moves a file. |
|
||||
| `POST /notepad/text?tab=<id>` | `{ text }`. Saves that tab's `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 404 `no-such-tab`, 413 `too-long` (over 1 MB). |
|
||||
| `POST /notepad/image?tab=<id>` | Raw `image/jpeg` (the page re-encodes every picture first). Writes the tab's `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures in the tab). |
|
||||
| `POST /notepad/thumb?id=<uuid>&tab=<id>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found` or `no-such-tab`, 415 `not-jpeg`, 413 `too-large`. |
|
||||
| `POST /notepad/image/delete?tab=<id>` | `{ id }`. Deletes a picture and its thumbnail; 404 `not-found` or `no-such-tab`. |
|
||||
| `POST /notepad/tab` | `{ name }`. Makes a tab, which becomes the last one used, and answers `{ ok, id, name }`; 400 `bad-name`, 409 `duplicate-name` (any case) or `too-many-tabs` (20). |
|
||||
| `POST /notepad/tab/rename` | `{ id, name }`. Answers `{ ok, id, name }`; 400 `bad-name`, 404 `no-such-tab`, 409 `duplicate-name`. |
|
||||
| `POST /notepad/tab/delete` | `{ id }`. Removes the tab from the index, then its folder (text and pictures); 404 `no-such-tab`. |
|
||||
| `POST /notepad/tab/order` | `{ order: [id] }`, every current id exactly once; 400 `bad` otherwise. |
|
||||
| `POST /notepad/tab/last` | `{ id }`. Remembers the open tab; 404 `no-such-tab`. |
|
||||
| `GET /notepad/images/<tab>/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a tab id and a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
|
||||
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
|
||||
|
||||
## For maintainers
|
||||
@@ -860,7 +879,7 @@ origin.
|
||||
| Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and OverType 2.6.1 (MIT) for the notepad's editor; the page's policy blocks the `<style>` OverType injects, so its CSS ships in `public/styles/notepad.css`, regenerated by `node scripts/vendor-overtype.mjs` after an upgrade (steps in the architecture doc's Notepad point) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and CodeMirror 6 (MIT) for the notebook's editor as one bundled file, `public/vendor/codemirror.esm.js`, made by the dev-only `node scripts/vendor-codemirror.mjs` from a pinned lock (about 500 KB, loaded only when the Notebook is first opened); the page's policy blocks the `<style>` element CodeMirror writes, so the editor lives in a shadow root where it adopts its rules as a constructed stylesheet (steps in the architecture doc's Notebook point) |
|
||||
|
||||
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
|
||||
`npm run build:skills` and commit it with the source change, since `npm test`
|
||||
|
||||
@@ -42,7 +42,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notepad** in the top bar (Markdown and pictures, one per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
## Skill Scripts
|
||||
|
||||
@@ -2,6 +2,21 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v2.11.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web console**: the Notebook has named **tabs**. Each tab is its own Markdown note with its own pictures, kept in its own folder under the notebook's (`tabs/<id>/note.md` and `images/`, with a `tabs.json` index). **+ New tab** asks for a name (1 to 40 characters, no two alike in any case, up to 20 tabs). A tab can be renamed (button, double-click or F2), reordered (drag, Move left and Move right, or Alt with the arrow keys) and deleted, which asks twice and removes its text and pictures. The tab left open is the one that opens next, and with no tab left the dialog offers to make one. Saves and pictures are bound to the tab they were made in, so switching never moves either; a switch that cannot save first stays put and says why.
|
||||
- **web console**: five routes (`POST /notepad/tab`, `/tab/rename`, `/tab/delete`, `/tab/order`, `/tab/last`), `?tab=` on the text and picture routes, and picture addresses that carry the tab (`/notepad/images/<tab>/<uuid>.jpg`).
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the Notepad is now called the **Notebook** (the icon is unchanged), in the top bar, the dialog, the Help, the docs and the screenshots. Code names, routes and the `~/.plan2code/notepads/` folder keep their names, so nothing already saved moves. The dialog's line about it being never shared to the AI Agent is bold, in the highlight color.
|
||||
- **web console**: every document tab and the Overview has a **Back to Questions** button (Dashboard or Git on those screens) left of Print and Download, with a highlight border, and that header row stays at the top of the pane while the document scrolls.
|
||||
- **web console**: the Notebook editor is now CodeMirror 6 with live in-place Markdown: headings grow, bullets draw and the marks come back on the line the cursor is on. It replaces OverType after a spike showed typing in a 200 KB note about four times faster. The editor ships as one vendored file loaded only when the Notebook first opens, and runs in a shadow root so the page's content-security policy stays as strict as before.
|
||||
- **web console**: an existing notebook opens as one tab called **Notes**. Reading it writes nothing; the first edit moves the note and pictures into the tab, and a crash part way is finished by the next write.
|
||||
- **contributors**: `scripts/vendor-codemirror.mjs` and its lock file build the editor bundle reproducibly; the OverType vendor script, its CSS and its page helpers are gone.
|
||||
|
||||
## v2.10.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
@@ -23,7 +23,7 @@ The install command always opens a menu. Back at your prompt with no output at a
|
||||
|
||||
Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md).
|
||||
|
||||
The **Notepad** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`, never shown to the agent).
|
||||
The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`, never shown to the agent).
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
|
||||
|
||||
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||
|
||||
Version 2.10.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 2.11.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -150,7 +150,7 @@ next check-in, and it never holds up your answers.
|
||||
|
||||
There is more on the page when you need it. Notes on any question can carry screenshots and
|
||||
documents. The folder label in the bottom bar opens your workspace, where you add other folders
|
||||
as read-only context and point at them by `@name`. The **Notepad** in the top bar is a private pad of your own for the
|
||||
as read-only context and point at them by `@name`. The **Notebook** in the top bar is a private pad of your own for the
|
||||
folder, in Markdown with pictures, that the agent never sees. The session meter in the top bar turns from green
|
||||
to red as a session grows long and suggests a fresh one. **Stop session** saves your place and gives
|
||||
you the command to carry on later, and **Back to the dashboard** takes you home to pick the next
|
||||
@@ -418,7 +418,7 @@ edits out through the skills CLI.
|
||||
|
||||
Core reference:
|
||||
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notepad in the top bar
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notebook in the top bar
|
||||
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
|
||||
- **[.readme/walkthrough.md](.readme/walkthrough.md)** — one feature from a sentence to archived specs, session by session
|
||||
- **[AGENTS.md](AGENTS.md)** — architecture and contributor guide for this repo
|
||||
|
||||
@@ -335,7 +335,7 @@ footer a { color: inherit; }
|
||||
<div><h3>Review before you approve</h3><p>Review the code first, on the sign-off card, reviews exactly the files the phase changed. You tick which findings get fixed, then approve.</p></div>
|
||||
<div><h3>The Ask tab</h3><p>A chat beside the cards for anything you want to know. It is answered at the agent's next check-in and never holds up your answers.</p></div>
|
||||
<div><h3>Attachments on notes</h3><p>Paste a screenshot or attach a document to a note on any question, and show instead of describe.</p></div>
|
||||
<div><h3>A notepad of your own</h3><p>A private pad for each project folder, in Markdown with pictures. It never goes into your project, and the agent never sees it.</p></div>
|
||||
<div><h3>A notebook of your own</h3><p>A private pad for each project folder, in Markdown with pictures. It never goes into your project, and the agent never sees it.</p></div>
|
||||
<div><h3>Workspace folders</h3><p>Add a shared library or a design folder as read-only context, and point at it by its <code>@name</code>.</p></div>
|
||||
<div><h3>Session meter</h3><p>A ring in the top bar turns from green to red as a session grows long, and suggests when a fresh one would serve you better.</p></div>
|
||||
<div><h3>Runs on your machine</h3><p>A small program Plan2Code starts for you serves the page on <code>127.0.0.1</code>. No account, no dependencies, and nothing leaves your computer.</p></div>
|
||||
@@ -358,9 +358,9 @@ footer a { color: inherit; }
|
||||
<figure style="grid-column:1/-1;max-width:calc(50% - 12px);justify-self:center">
|
||||
<picture class="shot">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="screenshots/notepad-dark.webp">
|
||||
<img src="screenshots/notepad-light.webp" width="2560" height="1600" loading="lazy" alt="The Notepad open over a question: a few lines of Markdown styled as they are typed.">
|
||||
<img src="screenshots/notepad-light.webp" width="2560" height="1600" loading="lazy" alt="The Notebook open over a question: two named tabs, and a heading, bullets and bold styled in place as they are typed.">
|
||||
</picture>
|
||||
<figcaption>Your own notepad, private to the folder.</figcaption>
|
||||
<figcaption>Your own notebook, private to the folder.</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 107 KiB After Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 114 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 78 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 116 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 104 KiB |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "2.10.0",
|
||||
"version": "2.11.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
|
||||
@@ -81,18 +81,46 @@ const SHOTS = {
|
||||
// The git board draws itself from a real repository, so this shot runs in
|
||||
// its own git sample project; the post only hands the board back to you.
|
||||
git: { workflow: "git", posts: ["git"], repo: true },
|
||||
// The Notepad dialog over the plan question, with a few lines of Markdown
|
||||
// typed into it. The store is the scratch folder's, never the real one.
|
||||
// The Notebook dialog over the plan question, with two named tabs: Call notes
|
||||
// (a heading, bullets and bold, shown live) and Ideas, with the first one
|
||||
// open. The store is the scratch folder's, never the real one.
|
||||
notepad: {
|
||||
workflow: "plan",
|
||||
posts: ["question"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-notepad");
|
||||
await page.waitForSelector("#notepad-modal[open]", { timeout: 10000 });
|
||||
await page.waitForFunction(() => !document.querySelector("#notepad-modal textarea").readOnly, null, { timeout: 10000 });
|
||||
await page.locator("#notepad-modal textarea").fill(
|
||||
"# Before the call\n\n- Ask about **paging**: cursor or offset?\n- Who signs in to the API?\n- Check the `/tasks` limit with the team\n"
|
||||
const editor = page.locator("#notepad-editor .cm-content");
|
||||
const newTab = async (name) => {
|
||||
await page.click((await page.locator("#notepad-empty").isVisible()) ? "#notepad-empty-new" : "#notepad-tab-new");
|
||||
await page.fill("#notepad-name", name);
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(
|
||||
(n) => [...document.querySelectorAll("#notepad-tabs .notepad-tab")].some((b) => b.textContent === n && b.getAttribute("aria-selected") === "true"),
|
||||
name,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
await editor.click();
|
||||
};
|
||||
// The second theme's run finds the first one's tabs, kept in the same store.
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector("#notepad-tabs .notepad-tab") || !document.getElementById("notepad-empty").hidden,
|
||||
null,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
if (!(await page.locator("#notepad-tabs .notepad-tab").count())) {
|
||||
// The list marker is typed once: the editor carries a list on at Enter.
|
||||
await newTab("Call notes");
|
||||
await page.keyboard.type(
|
||||
"# Before the call\n\n- Ask about **paging**: cursor or offset?\nWho signs in to the API?\nCheck the `/tasks` limit with the team\n\n"
|
||||
);
|
||||
await newTab("Ideas");
|
||||
await page.keyboard.type("Retry policy for the export job.\nWhat should the page size cap be?");
|
||||
}
|
||||
await sleep(1000);
|
||||
await page.locator("#notepad-tabs .notepad-tab", { hasText: /^Call notes$/ }).click();
|
||||
await page.locator("#notepad-editor .cm-h1").waitFor({ timeout: 10000 });
|
||||
await page.locator("#notepad-editor .cm-line").last().click();
|
||||
await sleep(1800);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -669,6 +669,30 @@ test("Download offers a Markdown file with the doc's title, blocks and marks", a
|
||||
assert.equal(Buffer.concat(chunks).toString("utf8"), "# What we've agreed\n\nRuns nightly.\n\n> **Assumed for now, still open.**\n\nOutput is CSV.");
|
||||
});
|
||||
|
||||
// What a person sees break: a long document has no way home but the first
|
||||
// tab, or its header scrolls away with the text.
|
||||
test("a document's header stays on screen and its Back to Questions button returns to the questions", async (t) => {
|
||||
const blocks = Array.from({ length: 60 }, (_, i) => ({ id: "b" + i, state: "settled", md: `Paragraph ${i}. ` + "More words. ".repeat(40) }));
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [{ id: "q1", kind: "text", title: "A question", body: "Say something." }],
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks }],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const back = s.page.getByRole("button", { name: "Back to Questions" });
|
||||
await back.waitFor();
|
||||
await s.page.evaluate(() => { document.getElementById("main").scrollTop = 4000; });
|
||||
const box = await back.boundingBox();
|
||||
const main = await s.page.locator("#main").boundingBox();
|
||||
assert.ok(box && box.y >= main.y - 1 && box.y < main.y + 80, "the header row is still at the top of the pane after scrolling");
|
||||
await back.click();
|
||||
await s.page.getByText("Say something.").waitFor();
|
||||
assert.equal(await s.page.getByRole("button", { name: "Back to Questions" }).count(), 0, "the questions view has no Back button");
|
||||
});
|
||||
|
||||
// What a person sees break: the brief button turns up where no playbook
|
||||
// answers it, or sends a different range than the one picked.
|
||||
test("a pathfinder session offers Write a brief, and the picked range reaches the agent", async (t) => {
|
||||
|
||||
@@ -1,50 +1,93 @@
|
||||
// Page tests for the Notepad: the top bar icon on every screen, the styled
|
||||
// editor, autosave and what survives a reload or a restart, one notepad per
|
||||
// folder, the page's content-security policy with the editor open, hostile
|
||||
// Markdown, typing speed on a long note, the editor's two layers lining up,
|
||||
// both themes, and the pictures: adding, deleting, the preview and the cap.
|
||||
// Page tests for the Notebook: the top bar icon on every screen, the tabs (made
|
||||
// by naming them, renamed, reordered, deleted after two confirms), the live
|
||||
// Markdown editor, autosave per tab and what survives a reload or a restart,
|
||||
// one notepad per folder, the page's content-security policy with the editor
|
||||
// open, hostile Markdown, typing speed on a long note, both themes, and the
|
||||
// pictures: adding, deleting, the preview and the cap.
|
||||
// Run with:
|
||||
// node --test scripts/test-web-console-page-notepad.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test. Notes land in the file's throwaway NOTEPADS_DIR.
|
||||
//
|
||||
// The editor lives in the open shadow root of `.notepad-cm-host`: Playwright's
|
||||
// CSS locators pierce it, `page.evaluate` code reaches in through `shadowRoot`,
|
||||
// and the text is read from the editor's own state (`docText`), since lines
|
||||
// the cursor is not on draw without their Markdown marks.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, drawn } from "./page-test-helpers.mjs";
|
||||
import { backdate, cli, until } from "./web-console-test-helpers.mjs";
|
||||
import { JPEG, backdate, cli, until } from "./web-console-test-helpers.mjs";
|
||||
import {
|
||||
LEGACY_TAB_ID,
|
||||
NOTEPAD_MAX_IMAGES,
|
||||
NOTE_MAX_BYTES,
|
||||
addImage,
|
||||
addImage as addImageTo,
|
||||
createTab,
|
||||
defaultTabId,
|
||||
deleteTab,
|
||||
listTabs,
|
||||
notepadFolder,
|
||||
notepadKey,
|
||||
readNotepad,
|
||||
removeImage,
|
||||
saveNote,
|
||||
removeImage as removeImageFrom,
|
||||
saveNote as saveNoteTo,
|
||||
} from "../src/web-console/notepads.mjs";
|
||||
import { NOT_LOADED, SAVE_DEBOUNCE_MS, errorSentence } from "../src/web-console/public/notepad.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// The store calls here name the tab they use: the last one, with Notes made
|
||||
// first when the notepad has none.
|
||||
const openTab = (folder) => defaultTabId(folder) ?? createTab(folder, "Notes").id;
|
||||
const saveNote = (folder, text) => saveNoteTo(folder, openTab(folder), text);
|
||||
const addImage = (folder, buf) => addImageTo(folder, openTab(folder), buf);
|
||||
const removeImage = (folder, id) => removeImageFrom(folder, openTab(folder), id);
|
||||
|
||||
// A plan session on the person's turn.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
const input = (s) => s.page.locator("#notepad-editor .overtype-input");
|
||||
// The editor's editable surface (the locator pierces the shadow root).
|
||||
const input = (s) => s.page.locator("#notepad-editor .cm-content");
|
||||
|
||||
// The editor's whole text.
|
||||
const docText = (s) =>
|
||||
s.page.evaluate(async () => {
|
||||
const { EditorView } = await import("/vendor/codemirror.esm.js");
|
||||
const content = document.querySelector(".notepad-cm-host").shadowRoot.querySelector(".cm-content");
|
||||
return EditorView.findFromDOM(content).state.doc.toString();
|
||||
});
|
||||
|
||||
// Replaces the text the way typing does: through the editor, so autosave runs.
|
||||
const setDoc = (s, text) =>
|
||||
s.page.evaluate(async (t) => {
|
||||
const { EditorView } = await import("/vendor/codemirror.esm.js");
|
||||
const content = document.querySelector(".notepad-cm-host").shadowRoot.querySelector(".cm-content");
|
||||
const view = EditorView.findFromDOM(content);
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: t }, selection: { anchor: t.length } });
|
||||
}, text);
|
||||
|
||||
// Opens the notepad and, unless told the note cannot load, waits until it has:
|
||||
// the editor is read-only until then.
|
||||
async function openNotepad(s, { loads = true } = {}) {
|
||||
// the editor is read-only until then. A notepad with no tab gets Notes first,
|
||||
// unless `tabs: false`, since an empty one shows the empty state instead.
|
||||
async function openNotepad(s, { loads = true, tabs = true } = {}) {
|
||||
if (tabs && !listTabs(s.project).tabs.length) createTab(s.project, "Notes");
|
||||
await s.page.click("#btn-notepad");
|
||||
await s.page.locator("#notepad-modal[open]").waitFor();
|
||||
await input(s).waitFor();
|
||||
if (loads) await s.page.waitForFunction(() => !document.querySelector("#notepad-editor .overtype-input").readOnly);
|
||||
if (tabs) await input(s).waitFor();
|
||||
if (loads && tabs) {
|
||||
await s.page.waitForFunction(() => {
|
||||
const c = document.querySelector(".notepad-cm-host")?.shadowRoot?.querySelector(".cm-content");
|
||||
return Boolean(c) && c.getAttribute("aria-readonly") !== "true";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function closeNotepad(s) {
|
||||
@@ -55,19 +98,39 @@ async function closeNotepad(s) {
|
||||
// The editor's text once the page has read the note in: opening reads it from
|
||||
// the server, so the first value can still be the empty editor.
|
||||
async function shows(s, text) {
|
||||
await s.page.waitForFunction((want) => document.querySelector("#notepad-editor .overtype-input").value === want, text, { timeout: 5000 });
|
||||
return input(s).inputValue();
|
||||
await until(async () => (await docText(s)) === text, 5000);
|
||||
return docText(s);
|
||||
}
|
||||
|
||||
// The note on disk for the session's folder, as the store reads it.
|
||||
// Types as a person does, into the end of the text.
|
||||
async function typeInto(s, text) {
|
||||
await input(s).click();
|
||||
await s.page.keyboard.press("Control+End");
|
||||
await s.page.keyboard.type(text);
|
||||
}
|
||||
|
||||
// The note on disk for the session's folder (its last tab), as the store reads it.
|
||||
const onDisk = (s) => readNotepad(s.project).text;
|
||||
|
||||
// Records content-security violations from now on; the getter lists them.
|
||||
async function watchViolations(s) {
|
||||
await s.context.addInitScript(() => {
|
||||
window.__violations = [];
|
||||
document.addEventListener("securitypolicyviolation", (e) =>
|
||||
window.__violations.push(`${e.violatedDirective} ${e.blockedURI} ${e.sourceFile}:${e.lineNumber} ${e.sample}`),
|
||||
);
|
||||
});
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
return () => s.page.evaluate(() => window.__violations);
|
||||
}
|
||||
|
||||
async function iconUsable(s, where) {
|
||||
const btn = s.page.locator("#btn-notepad");
|
||||
assert.ok(await btn.isVisible(), `the icon shows on ${where}`);
|
||||
assert.ok(await btn.isEnabled(), `the icon is usable on ${where}`);
|
||||
assert.equal(await btn.getAttribute("aria-label"), "Notepad");
|
||||
assert.equal(await btn.getAttribute("title"), "Notepad");
|
||||
assert.equal(await btn.getAttribute("aria-label"), "Notebook");
|
||||
assert.equal(await btn.getAttribute("title"), "Notebook");
|
||||
}
|
||||
|
||||
test("the notepad icon shows on the dashboard, a skill session and a finished screen", async (t) => {
|
||||
@@ -93,14 +156,19 @@ test("the notepad icon shows on the dashboard, a skill session and a finished sc
|
||||
test("typing Markdown styles it in place, saves within two seconds, and survives close, reload and a restart", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
assert.equal(await input(s).getAttribute("aria-label"), "Notepad text");
|
||||
await input(s).focus();
|
||||
await s.page.keyboard.type("# Shopping list\n\nSome **bold** text");
|
||||
assert.equal(await input(s).getAttribute("aria-label"), "Notebook text");
|
||||
await typeInto(s, "# Shopping list\n\nSome **bold** text");
|
||||
const typedAt = Date.now();
|
||||
// Styled in place: the preview layer under the textarea holds a heading.
|
||||
await s.page.locator("#notepad-editor .overtype-preview h1").waitFor();
|
||||
assert.match(await s.page.locator("#notepad-editor .overtype-preview h1").innerText(), /Shopping list/);
|
||||
assert.equal(await s.page.locator("#notepad-editor .overtype-preview strong").count(), 1);
|
||||
// Styled in place: the heading line is drawn large, the bold run bold.
|
||||
await s.page.locator("#notepad-editor .cm-h1").waitFor();
|
||||
assert.match(await s.page.locator("#notepad-editor .cm-h1").innerText(), /Shopping list/);
|
||||
const sizes = await s.page.evaluate(() => {
|
||||
const root = document.querySelector(".notepad-cm-host").shadowRoot;
|
||||
const px = (el) => parseFloat(getComputedStyle(el).fontSize);
|
||||
return { heading: px(root.querySelector(".cm-h1")), body: px(root.querySelector(".cm-content")) };
|
||||
});
|
||||
assert.ok(sizes.heading > sizes.body * 1.4, `the heading is larger than the text (${sizes.heading}px against ${sizes.body}px)`);
|
||||
assert.equal(await s.page.locator("#notepad-editor .cm-strong").count(), 1);
|
||||
|
||||
await until(() => onDisk(s) === "# Shopping list\n\nSome **bold** text", 4000);
|
||||
assert.ok(Date.now() - typedAt < 2000, `saved ${Date.now() - typedAt} ms after the last key`);
|
||||
@@ -135,11 +203,11 @@ test("two sessions in two folders keep two separate notepads", async (t) => {
|
||||
const a = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const b = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(a);
|
||||
await input(a).fill("Folder A's note");
|
||||
await setDoc(a, "Folder A's note");
|
||||
await until(() => onDisk(a) === "Folder A's note", 4000);
|
||||
await openNotepad(b);
|
||||
assert.equal(await input(b).inputValue(), "", "the second folder starts empty");
|
||||
await input(b).fill("Folder B's note");
|
||||
assert.equal(await docText(b), "", "the second folder starts empty");
|
||||
await setDoc(b, "Folder B's note");
|
||||
await until(() => onDisk(b) === "Folder B's note", 4000);
|
||||
assert.equal(onDisk(a), "Folder A's note");
|
||||
// Reopening each shows its own.
|
||||
@@ -154,46 +222,42 @@ test("the editor breaks no content-security rule, and hostile Markdown runs noth
|
||||
s.page.on("console", (m) => {
|
||||
if (m.type() === "error") consoleErrors.push(m.text());
|
||||
});
|
||||
await s.context.addInitScript(() => {
|
||||
window.__violations = [];
|
||||
document.addEventListener("securitypolicyviolation", (e) =>
|
||||
window.__violations.push(`${e.violatedDirective} ${e.blockedURI} ${e.sourceFile}:${e.lineNumber} ${e.sample}`),
|
||||
);
|
||||
});
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
const violations = await watchViolations(s);
|
||||
await openNotepad(s);
|
||||
await input(s).focus();
|
||||
await s.page.keyboard.type(
|
||||
await typeInto(
|
||||
s,
|
||||
"# Title\n\n- a list with `code` and [a link](https://example.com)\n> quoted\n\n" +
|
||||
'<img src=x onerror="window.__pwned = 1">\n<script>window.__pwned2 = 1</script>\n' +
|
||||
'<a href="javascript:window.__pwned3 = 1">click</a>\n',
|
||||
);
|
||||
await until(() => onDisk(s).includes("__pwned3"), 4000);
|
||||
await s.page.waitForTimeout(300);
|
||||
const result = await s.page.evaluate(() => ({
|
||||
violations: window.__violations,
|
||||
pwned: [window.__pwned, window.__pwned2, window.__pwned3],
|
||||
imgs: document.querySelectorAll("#notepad-editor .overtype-preview img").length,
|
||||
scripts: document.querySelectorAll("#notepad-editor script").length,
|
||||
styleTag: Boolean(document.querySelector("style.overtype-styles")),
|
||||
}));
|
||||
assert.deepEqual(result.violations, [], "no content-security violations with the notepad open");
|
||||
const result = await s.page.evaluate(() => {
|
||||
const root = document.querySelector(".notepad-cm-host").shadowRoot;
|
||||
return {
|
||||
pwned: [window.__pwned, window.__pwned2, window.__pwned3],
|
||||
// CodeMirror's own empty spacer images (aria-hidden) beside widgets are not typed HTML.
|
||||
imgs: root.querySelectorAll("img:not(.cm-widgetBuffer)").length,
|
||||
scripts: root.querySelectorAll("script").length,
|
||||
styleTags: root.querySelectorAll("style").length + document.querySelectorAll("style").length,
|
||||
};
|
||||
});
|
||||
assert.deepEqual(await violations(), [], "no content-security violations with the notepad open");
|
||||
assert.deepEqual(result.pwned, [undefined, undefined, undefined], "nothing typed ran");
|
||||
assert.equal(result.imgs, 0, "typed HTML stays text");
|
||||
assert.equal(result.scripts, 0);
|
||||
assert.equal(result.styleTag, false, "OverType injected no <style>");
|
||||
assert.equal(result.styleTags, 0, "the editor added no <style> element");
|
||||
assert.deepEqual(consoleErrors.filter((e) => /Content.Security.Policy|Refused to/i.test(e)), []);
|
||||
// The heading is styled from the stylesheet the page ships.
|
||||
const h1 = await s.page.locator("#notepad-editor .overtype-preview h1").evaluate((el) => getComputedStyle(el).fontWeight);
|
||||
const h1 = await s.page.locator("#notepad-editor .cm-h1").evaluate((el) => getComputedStyle(el).fontWeight);
|
||||
assert.ok(Number(h1) >= 600 || h1 === "bold", `the heading is bold (${h1})`);
|
||||
});
|
||||
|
||||
// The editor redraws only the lines that changed (patchPreview in
|
||||
// screens/notepad.js): about 90 ms a key at 200 KB on a quiet machine, against
|
||||
// about 310 ms when every key redrew the whole note. The bar is higher than
|
||||
// that because `npm test` runs every test file at once, which alone adds 50 ms
|
||||
// or more; it still catches a slide back toward whole-note redraws.
|
||||
// The editor redraws only the lines in view, so a key costs the same at 200 KB
|
||||
// as at 2 KB: about 25 ms on a quiet machine (OverType, which it replaced,
|
||||
// took about 95). The bar is higher than that because `npm test` runs every
|
||||
// test file at once, which alone adds 50 ms or more; it still catches a slide
|
||||
// back toward whole-note redraws.
|
||||
const KEY_BUDGET_MS = 200;
|
||||
|
||||
test("typing into a 200 KB note keeps input-to-paint under the key budget on average", async (t) => {
|
||||
@@ -201,7 +265,9 @@ test("typing into a 200 KB note keeps input-to-paint under the key budget on ave
|
||||
const block = "## Heading\n\nSome **bold** text with `code` and a [link](https://example.com).\n\n- an item\n- another\n\n";
|
||||
saveNote(s.project, block.repeat(Math.ceil((200 * 1024) / block.length)));
|
||||
await openNotepad(s);
|
||||
await s.page.waitForFunction(() => document.querySelector("#notepad-editor .overtype-input").value.length > 200000);
|
||||
await until(async () => (await docText(s)).length > 200000, 5000);
|
||||
await input(s).click();
|
||||
await s.page.keyboard.press("Control+End");
|
||||
await s.page.evaluate(() => {
|
||||
window.__lags = [];
|
||||
window.addEventListener(
|
||||
@@ -212,9 +278,6 @@ test("typing into a 200 KB note keeps input-to-paint under the key budget on ave
|
||||
},
|
||||
{ capture: true },
|
||||
);
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
ta.focus();
|
||||
ta.setSelectionRange(ta.value.length, ta.value.length);
|
||||
});
|
||||
// `npm test` runs every test file at once, and a round that lands in another
|
||||
// file's busiest moment measures the machine rather than the editor: the
|
||||
@@ -233,45 +296,11 @@ test("typing into a 200 KB note keeps input-to-paint under the key budget on ave
|
||||
assert.ok(best < KEY_BUDGET_MS, `average input-to-paint ${averages.map((a) => a.toFixed(1)).join(", ")} ms`);
|
||||
});
|
||||
|
||||
test("the textarea and the styled layer line up, line for line", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await input(s).fill(
|
||||
"# A heading\n## A smaller one\nPlain text with **bold**, *em* and `code`.\n> a quote\n- a list item\n\n" +
|
||||
"A long line that wraps: " + "word ".repeat(80) + "\nThe last line",
|
||||
);
|
||||
const m = await s.page.evaluate(() => {
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const pv = document.querySelector("#notepad-editor .overtype-preview");
|
||||
const cs = (el) => getComputedStyle(el);
|
||||
const lineHeight = parseFloat(cs(ta).lineHeight);
|
||||
const lines = [...pv.children];
|
||||
const top0 = lines[0].getBoundingClientRect().top;
|
||||
return {
|
||||
lineHeight,
|
||||
count: lines.length,
|
||||
offsets: lines.map((el) => (el.getBoundingClientRect().top - top0) / lineHeight),
|
||||
heights: [ta.scrollHeight, pv.scrollHeight],
|
||||
fonts: [ta, pv, pv.querySelector("h1"), pv.querySelector("h2"), pv.querySelector("strong"), pv.querySelector("code")].map(
|
||||
(el) => `${cs(el).fontFamily} ${cs(el).fontSize}`,
|
||||
),
|
||||
padding: [cs(ta).paddingTop, cs(pv).paddingTop, cs(ta).paddingLeft, cs(pv).paddingLeft],
|
||||
};
|
||||
});
|
||||
assert.equal(m.count, 8, "one preview line per text line");
|
||||
for (const [i, offset] of m.offsets.entries()) {
|
||||
assert.ok(Math.abs(offset - Math.round(offset)) < 0.05, `line ${i + 1} sits on the grid (${offset})`);
|
||||
}
|
||||
assert.ok(Math.abs(m.heights[0] - m.heights[1]) <= 1, `same height: ${m.heights.join(" vs ")}`);
|
||||
assert.equal(new Set(m.fonts).size, 1, `one font and size everywhere: ${[...new Set(m.fonts)].join(" | ")}`);
|
||||
assert.equal(m.padding[0], m.padding[1]);
|
||||
assert.equal(m.padding[2], m.padding[3]);
|
||||
});
|
||||
|
||||
test("the editor follows the console's light and dark themes", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await input(s).fill("# Heading\n\nText");
|
||||
await setDoc(s, "# Heading\n\nText");
|
||||
await s.page.locator("#notepad-editor .cm-h1").waitFor();
|
||||
const colours = (theme) =>
|
||||
s.page.evaluate((th) => {
|
||||
document.documentElement.setAttribute("data-theme", th);
|
||||
@@ -284,16 +313,16 @@ test("the editor follows the console's light and dark themes", async (t) => {
|
||||
el.remove();
|
||||
return out;
|
||||
};
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const pv = document.querySelector("#notepad-editor .overtype-preview");
|
||||
const shadow = document.querySelector(".notepad-cm-host").shadowRoot;
|
||||
const content = shadow.querySelector(".cm-content");
|
||||
return {
|
||||
ink: probe(root.getPropertyValue("--ink")),
|
||||
accent: probe(root.getPropertyValue("--accent")),
|
||||
panel: probe(root.getPropertyValue("--panel"), "backgroundColor"),
|
||||
text: getComputedStyle(pv).color,
|
||||
heading: getComputedStyle(pv.querySelector("h1")).color,
|
||||
caret: getComputedStyle(ta).caretColor,
|
||||
background: getComputedStyle(document.querySelector("#notepad-editor .overtype-wrapper")).backgroundColor,
|
||||
text: getComputedStyle(content).color,
|
||||
heading: getComputedStyle(shadow.querySelector(".cm-h1")).color,
|
||||
caret: getComputedStyle(content).caretColor,
|
||||
background: getComputedStyle(shadow.querySelector(".cm-editor")).backgroundColor,
|
||||
};
|
||||
}, theme);
|
||||
const light = await colours("light");
|
||||
@@ -308,84 +337,42 @@ test("the editor follows the console's light and dark themes", async (t) => {
|
||||
assert.notEqual(light.background, dark.background);
|
||||
});
|
||||
|
||||
test("after edits anywhere, the styled layer matches a full redraw", async (t) => {
|
||||
test("headings grow, bullets draw, and marks come back on the line the cursor is on", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const block = "## Heading\n\nSome **bold** and a [link](https://example.com).\n\n- an item\n- another\n1. first\n2. second\n\n```js\nconst x = 1;\n```\n> quote\n";
|
||||
saveNote(s.project, block.repeat(40));
|
||||
saveNote(s.project, "# Big\n\n## Smaller\n\n- one\n- two\n\nplain\n");
|
||||
await openNotepad(s);
|
||||
await s.page.waitForFunction(() => document.querySelector("#notepad-editor .overtype-input").value.length > 1000);
|
||||
// The layer on the page against one drawn from scratch from the same text.
|
||||
const matches = () =>
|
||||
s.page.evaluate(async () => {
|
||||
const { withoutStyleAttrs } = await import("/notepad.js");
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const pv = document.querySelector("#notepad-editor .overtype-preview");
|
||||
const parser = ta.closest(".overtype-wrapper")._instance.constructor.MarkdownParser;
|
||||
const fresh = document.createElement("div");
|
||||
fresh.className = "overtype-preview";
|
||||
// Parsed into an inert template, so nothing in it reaches the page.
|
||||
const tpl = document.createElement("template");
|
||||
tpl.innerHTML = withoutStyleAttrs(parser.parse(ta.value, -1, false, undefined, false));
|
||||
fresh.append(tpl.content);
|
||||
// OverType shades code fences in pairs, in order, after drawing
|
||||
// (_applyCodeBlockBackgrounds): the fresh copy gets the same, so a stale
|
||||
// mark left on the page shows as a difference.
|
||||
const fences = fresh.querySelectorAll(".code-fence");
|
||||
for (let i = 0; i < fences.length - 1; i += 2) {
|
||||
for (const f of [fences[i], fences[i + 1]]) {
|
||||
f.parentElement.classList.add("code-block-line");
|
||||
f.style.display = "block";
|
||||
}
|
||||
}
|
||||
// An emptied style or class attribute looks exactly like none.
|
||||
const plain = (html) => html.replace(/ (style|class)=""/g, "");
|
||||
return plain(pv.innerHTML) === plain(fresh.innerHTML);
|
||||
await until(async () => (await docText(s)).startsWith("# Big"), 5000);
|
||||
const lines = () =>
|
||||
s.page.evaluate(() => {
|
||||
const root = document.querySelector(".notepad-cm-host").shadowRoot;
|
||||
return [...root.querySelectorAll(".cm-line")].map((l) => ({ text: l.textContent, size: parseFloat(getComputedStyle(l).fontSize) }));
|
||||
});
|
||||
const at = (pos) =>
|
||||
s.page.evaluate((p) => {
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const i = p < 0 ? ta.value.length + p : p;
|
||||
ta.focus();
|
||||
ta.setSelectionRange(i, i);
|
||||
}, pos);
|
||||
await at(0);
|
||||
await s.page.keyboard.type("# A new first line\n");
|
||||
assert.ok(await matches(), "typing at the top");
|
||||
await at(600);
|
||||
await s.page.keyboard.type("\n- a list item added in the middle\n[another link](https://example.org) ");
|
||||
assert.ok(await matches(), "typing in the middle, adding a link before others");
|
||||
await at(900);
|
||||
for (let i = 0; i < 30; i++) await s.page.keyboard.press("Backspace");
|
||||
assert.ok(await matches(), "deleting across lines");
|
||||
await at(-5);
|
||||
await s.page.keyboard.type("\n```\nopen fence at the end");
|
||||
assert.ok(await matches(), "an unclosed fence at the end");
|
||||
await s.page.keyboard.press("Control+a");
|
||||
await s.page.keyboard.press("Backspace");
|
||||
assert.ok(await matches(), "clearing it all");
|
||||
await s.page.keyboard.type("# Back again");
|
||||
assert.ok(await matches(), "typing into the empty note");
|
||||
// Four fences, two shaded blocks; deleting the first fence leaves three, and
|
||||
// the last one, kept from the drawing before, is no longer paired.
|
||||
// Ending on the last fence, so its line is the one kept unchanged.
|
||||
await s.page.keyboard.type("\n```\ncode\n```\ntext\n```\nmore\n```");
|
||||
assert.ok(await matches(), "two fenced blocks");
|
||||
const firstFence = await s.page.evaluate(() => document.querySelector("#notepad-editor .overtype-input").value.indexOf("```"));
|
||||
await at(firstFence + 4);
|
||||
for (let i = 0; i < 4; i++) await s.page.keyboard.press("Backspace");
|
||||
assert.ok(await matches(), "the first fence deleted, unpairing the last");
|
||||
// The cursor starts on line 1 (the "# Big" heading): its mark shows, the
|
||||
// second heading's does not.
|
||||
let seen = await lines();
|
||||
assert.equal(seen[0].text, "# Big");
|
||||
assert.equal(seen[2].text, "Smaller", "off the cursor line the mark is hidden");
|
||||
assert.ok(seen[0].size > seen[2].size && seen[2].size > seen[7].size, `heading sizes step down: ${seen.map((l) => l.size).join(", ")}`);
|
||||
assert.ok(seen[4].text.startsWith("•") || !seen[4].text.startsWith("-"), `a bullet is drawn, not a hyphen: "${seen[4].text}"`);
|
||||
// Click the second heading: its mark comes back.
|
||||
await s.page.locator("#notepad-editor .cm-h2").click();
|
||||
seen = await lines();
|
||||
assert.equal(seen[2].text, "## Smaller");
|
||||
assert.equal(seen[0].text, "Big");
|
||||
});
|
||||
|
||||
test("a note that cannot be read leaves the editor read-only, and nothing typed reaches the stored note", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
saveNote(s.project, "The real note");
|
||||
await s.page.route("**/notepad", (route) => (route.request().method() === "GET" ? route.abort() : route.continue()));
|
||||
await openNotepad(s, { loads: false });
|
||||
await s.page.click("#btn-notepad");
|
||||
await s.page.locator("#notepad-modal[open]").waitFor();
|
||||
await input(s).waitFor();
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent === want, NOT_LOADED);
|
||||
assert.equal(await input(s).evaluate((el) => el.readOnly), true);
|
||||
await input(s).focus();
|
||||
assert.equal(await input(s).getAttribute("aria-readonly"), "true");
|
||||
await input(s).click();
|
||||
await s.page.keyboard.type("typed into the empty editor");
|
||||
assert.equal(await input(s).inputValue(), "", "nothing could be typed");
|
||||
assert.equal(await docText(s), "", "nothing could be typed");
|
||||
await s.page.waitForTimeout(SAVE_DEBOUNCE_MS + 400);
|
||||
assert.equal(onDisk(s), "The real note");
|
||||
// Once it can be read, reopening loads it and the editor opens up.
|
||||
@@ -401,22 +388,443 @@ test("a note too long to save keeps its text when the notepad is closed and open
|
||||
await openNotepad(s);
|
||||
await shows(s, "Saved earlier");
|
||||
const long = "x".repeat(NOTE_MAX_BYTES) + " and some more";
|
||||
await input(s).fill(long);
|
||||
await setDoc(s, long);
|
||||
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent.startsWith("Too long to save"));
|
||||
await closeNotepad(s);
|
||||
await openNotepad(s);
|
||||
await s.page.waitForTimeout(300);
|
||||
assert.equal((await input(s).inputValue()).length, long.length, "the long text is still in the editor");
|
||||
assert.equal((await docText(s)).length, long.length, "the long text is still in the editor");
|
||||
assert.equal(onDisk(s), "Saved earlier", "and nothing over the cap was saved");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ tabs */
|
||||
|
||||
const tabButtons = (s) => s.page.locator("#notepad-tabs .notepad-tab");
|
||||
const tabNamed = (s, name) => s.page.locator("#notepad-tabs .notepad-tab", { hasText: new RegExp(`^${name}$`) });
|
||||
const tabNames = (s) => tabButtons(s).evaluateAll((bs) => bs.map((b) => b.textContent));
|
||||
const selectedName = (s) => s.page.locator('#notepad-tabs .notepad-tab[aria-selected="true"]').evaluateAll((bs) => bs.map((b) => b.textContent));
|
||||
const status = (s) => s.page.locator("#notepad-status").textContent();
|
||||
const idOf = (s, name) => listTabs(s.project).tabs.find((tab) => tab.name === name)?.id;
|
||||
// The x beside a tab's name: the current tab's, or the one named.
|
||||
const X_SELECTED = '#notepad-tabs .notepad-tab[aria-selected="true"] + .notepad-tab-x';
|
||||
const xOf = (s, name) => s.page.locator(`#notepad-tabs .notepad-tab-x[aria-label="Delete ${name}"]`);
|
||||
const nameError = (s) => s.page.locator("#notepad-name-error").textContent();
|
||||
|
||||
// Makes a tab through the page: the button, the name form, Enter.
|
||||
async function newTab(s, name, shown = name) {
|
||||
await s.page.click("#notepad-tab-new");
|
||||
await s.page.locator("#notepad-name-dlg[open]").waitFor();
|
||||
await s.page.fill("#notepad-name", name);
|
||||
await s.page.keyboard.press("Enter");
|
||||
await s.page.waitForFunction((n) => [...document.querySelectorAll("#notepad-tabs .notepad-tab")].some((b) => b.textContent === n && b.getAttribute("aria-selected") === "true"), shown);
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-name-dlg").open);
|
||||
}
|
||||
|
||||
// A notepad in its first shape: meta.json v1, note.md and images/ at the top.
|
||||
const U1 = "11111111-1111-4111-8111-111111111111";
|
||||
const U2 = "22222222-2222-4222-8222-222222222222";
|
||||
function legacyNotepad(folder, note) {
|
||||
const dir = notepadFolder(folder);
|
||||
fs.mkdirSync(path.join(dir, "images"), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "meta.json"), JSON.stringify({ v: 1, folder: path.resolve(folder), created: "2026-01-01T00:00:00.000Z" }));
|
||||
fs.writeFileSync(path.join(dir, "note.md"), note);
|
||||
for (const id of [U1, U2]) fs.writeFileSync(path.join(dir, "images", id + ".jpg"), JPEG);
|
||||
fs.writeFileSync(path.join(dir, "images", U1 + ".thumb.jpg"), JPEG);
|
||||
return dir;
|
||||
}
|
||||
|
||||
test("an old notepad opens as one tab, Notes, with its text and pictures, and reading it writes nothing", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const dir = legacyNotepad(s.project, "old note\n");
|
||||
const before = fs.readdirSync(dir).sort();
|
||||
await openNotepad(s, { tabs: false });
|
||||
await input(s).waitFor();
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 2);
|
||||
assert.deepEqual(await tabNames(s), ["Notes"]);
|
||||
assert.deepEqual(await selectedName(s), ["Notes"]);
|
||||
assert.equal(await shows(s, "old note\n"), "old note\n");
|
||||
assert.equal(await s.page.locator("#notepad-empty").isHidden(), true);
|
||||
assert.deepEqual(fs.readdirSync(dir).sort(), before, "opening it moved and wrote nothing");
|
||||
// The first edit moves it into the Notes tab.
|
||||
await typeInto(s, "more");
|
||||
await until(() => fs.existsSync(path.join(dir, "tabs.json")), 4000);
|
||||
await until(() => readNotepad(s.project, LEGACY_TAB_ID).text === "old note\nmore", 4000);
|
||||
assert.equal(fs.existsSync(path.join(dir, "note.md")), false, "the top-level note moved into the tab");
|
||||
assert.equal(readNotepad(s.project, LEGACY_TAB_ID).images.length, 2, "and so did the pictures");
|
||||
});
|
||||
|
||||
test("New tab asks for a name, refuses a bad or duplicate one, and Escape backs out", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const violations = await watchViolations(s);
|
||||
await openNotepad(s);
|
||||
await s.page.click("#notepad-tab-new");
|
||||
await s.page.locator("#notepad-name-dlg[open]").waitFor();
|
||||
assert.equal(await s.page.locator("#notepad-name-label").textContent(), "Name this tab");
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.id), "notepad-name", "the field has the focus");
|
||||
assert.equal(await s.page.inputValue("#notepad-name"), "");
|
||||
|
||||
await s.page.keyboard.press("Enter");
|
||||
assert.equal(await nameError(s), "Give the tab a name.");
|
||||
await s.page.fill("#notepad-name", " ");
|
||||
await s.page.click("#notepad-name-save");
|
||||
assert.equal(await nameError(s), "Give the tab a name.");
|
||||
await s.page.fill("#notepad-name", "x".repeat(41));
|
||||
await s.page.keyboard.press("Enter");
|
||||
assert.match(await nameError(s), /40 characters or fewer/);
|
||||
await s.page.fill("#notepad-name", "nOtEs");
|
||||
await s.page.keyboard.press("Enter");
|
||||
assert.equal(await nameError(s), errorSentence("duplicate-name"));
|
||||
assert.deepEqual(await tabNames(s), ["Notes"], "nothing was made");
|
||||
assert.equal(listTabs(s.project).tabs.length, 1);
|
||||
|
||||
// Escape closes the form, not the Notebook, and gives the focus back.
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-name-dlg").open);
|
||||
assert.equal(await s.page.evaluate(() => document.getElementById("notepad-modal").open), true);
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.id), "notepad-tab-new");
|
||||
// Cancel does the same.
|
||||
await s.page.click("#notepad-tab-new");
|
||||
await s.page.click("#notepad-name-cancel");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-name-dlg").open);
|
||||
|
||||
await newTab(s, " Big ideas ", "Big ideas");
|
||||
assert.deepEqual(await tabNames(s), ["Notes", "Big ideas"]);
|
||||
assert.deepEqual(await selectedName(s), ["Big ideas"]);
|
||||
assert.equal(await docText(s), "", "the new tab starts empty");
|
||||
assert.equal(await input(s).getAttribute("aria-readonly"), null, "and can be typed in");
|
||||
assert.deepEqual(listTabs(s.project).tabs.map((tab) => tab.name), ["Notes", "Big ideas"]);
|
||||
assert.deepEqual(await violations(), []);
|
||||
});
|
||||
|
||||
test("each tab keeps its own text and pictures, and switching never saves into the wrong tab", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const violations = await watchViolations(s);
|
||||
await openNotepad(s);
|
||||
await typeInto(s, "notes text");
|
||||
await newTab(s, "Ideas");
|
||||
const notes = idOf(s, "Notes");
|
||||
const ideas = idOf(s, "Ideas");
|
||||
await until(() => readNotepad(s.project, notes).text === "notes text", 4000);
|
||||
await typeInto(s, "ideas text");
|
||||
// Switch at once, before the debounce: the text still goes to Ideas.
|
||||
await tabNamed(s, "Notes").click();
|
||||
assert.equal(await shows(s, "notes text"), "notes text");
|
||||
assert.equal(readNotepad(s.project, ideas).text, "ideas text", "typed just before the switch, saved into its own tab");
|
||||
assert.equal(readNotepad(s.project, notes).text, "notes text", "and not into the other");
|
||||
|
||||
await typeInto(s, " (edited)");
|
||||
await tabNamed(s, "Ideas").click();
|
||||
assert.equal(await shows(s, "ideas text"), "ideas text");
|
||||
assert.equal(readNotepad(s.project, notes).text, "notes text (edited)");
|
||||
assert.equal(await selectedName(s).then((n) => n.join()), "Ideas");
|
||||
|
||||
// A picture added to Ideas is not in Notes.
|
||||
const png = await s.page.evaluate(async () => {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = c.height = 40;
|
||||
c.getContext("2d").fillRect(0, 0, 40, 40);
|
||||
const blob = await new Promise((r) => c.toBlob(r, "image/png"));
|
||||
let bin = "";
|
||||
for (const b of new Uint8Array(await blob.arrayBuffer())) bin += String.fromCharCode(b);
|
||||
return btoa(bin);
|
||||
});
|
||||
await s.page.setInputFiles("#notepad-file", { name: "p.png", mimeType: "image/png", buffer: Buffer.from(png, "base64") });
|
||||
await until(() => readNotepad(s.project, ideas).images.length === 1, 5000);
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1);
|
||||
assert.equal(readNotepad(s.project, notes).images.length, 0);
|
||||
await tabNamed(s, "Notes").click();
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 0);
|
||||
await tabNamed(s, "Ideas").click();
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1);
|
||||
const src = await s.page.locator("#notepad-strip img").getAttribute("src");
|
||||
assert.match(src, new RegExp(`^/notepad/images/${ideas}/`), "the picture's address names its tab");
|
||||
|
||||
// A save that cannot reach the server keeps you on the tab, with why.
|
||||
await s.page.route("**/notepad/text*", (route) => route.abort());
|
||||
await typeInto(s, " unsaved");
|
||||
await tabNamed(s, "Notes").click();
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), "Not saved yet, so staying on this tab.");
|
||||
assert.deepEqual(await selectedName(s), ["Ideas"], "still on the tab with the unsaved text");
|
||||
assert.equal(await docText(s), "ideas text unsaved");
|
||||
await s.page.unroute("**/notepad/text*");
|
||||
await until(() => readNotepad(s.project, ideas).text === "ideas text unsaved", 40000);
|
||||
await tabNamed(s, "Notes").click();
|
||||
assert.equal(await shows(s, "notes text (edited)"), "notes text (edited)");
|
||||
|
||||
// The last tab is remembered across a reload.
|
||||
await tabNamed(s, "Ideas").click();
|
||||
await until(() => listTabs(s.project).last === ideas, 4000);
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await openNotepad(s);
|
||||
assert.deepEqual(await selectedName(s), ["Ideas"]);
|
||||
assert.equal(await shows(s, "ideas text unsaved"), "ideas text unsaved");
|
||||
assert.deepEqual(await violations(), []);
|
||||
});
|
||||
|
||||
test("Double-click opens the rename modal with the name selected; F2 works too, and there is no Rename button", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await newTab(s, "Ideas");
|
||||
const ideas = idOf(s, "Ideas");
|
||||
|
||||
assert.equal(await s.page.locator("#notepad-tab-rename, #notepad-tab-tools").count(), 0, "the bottom toolbar is gone");
|
||||
await tabNamed(s, "Ideas").dblclick();
|
||||
await s.page.locator("#notepad-name-dlg[open]").waitFor();
|
||||
assert.equal(await s.page.locator("#notepad-name-label").textContent(), "Rename this tab");
|
||||
assert.equal(await s.page.inputValue("#notepad-name"), "Ideas");
|
||||
assert.equal(await s.page.evaluate(() => document.getElementById("notepad-name").selectionEnd - document.getElementById("notepad-name").selectionStart), 5, "the name is selected");
|
||||
// Its own name is not a duplicate; another tab's is.
|
||||
await s.page.keyboard.press("Enter");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-name-dlg").open);
|
||||
await tabNamed(s, "Ideas").dblclick();
|
||||
await s.page.fill("#notepad-name", "notes");
|
||||
await s.page.keyboard.press("Enter");
|
||||
assert.equal(await nameError(s), errorSentence("duplicate-name"));
|
||||
await s.page.fill("#notepad-name", "Plans");
|
||||
await s.page.keyboard.press("Enter");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-name-dlg").open);
|
||||
assert.deepEqual(await tabNames(s), ["Notes", "Plans"]);
|
||||
assert.equal(listTabs(s.project).tabs.find((tab) => tab.id === ideas).name, "Plans");
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Plans", "the focus is back on the tab");
|
||||
|
||||
// F2 on a focused tab, and a double-click.
|
||||
await tabNamed(s, "Plans").focus();
|
||||
await s.page.keyboard.press("F2");
|
||||
await s.page.locator("#notepad-name-dlg[open]").waitFor();
|
||||
assert.equal(await s.page.inputValue("#notepad-name"), "Plans");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await tabNamed(s, "Notes").dblclick();
|
||||
await s.page.locator("#notepad-name-dlg[open]").waitFor();
|
||||
assert.equal(await s.page.inputValue("#notepad-name"), "Notes");
|
||||
assert.deepEqual(await selectedName(s), ["Notes"], "double-click picked the tab it renames");
|
||||
});
|
||||
|
||||
// A drag the way the browser sends one: the events, in order, with one shared
|
||||
// DataTransfer, so the page's handlers see what a person's drag would.
|
||||
const drag = (s, from, to, { kind = "tab" } = {}) =>
|
||||
s.page.evaluate(
|
||||
({ from, to, kind }) => {
|
||||
const tabs = [...document.querySelectorAll("#notepad-tabs .notepad-tab")];
|
||||
const source = tabs.find((b) => b.textContent === from);
|
||||
const target = tabs.find((b) => b.textContent === to);
|
||||
const dt = new DataTransfer();
|
||||
if (kind === "text") dt.setData("text/plain", "dragged text");
|
||||
const fire = (el, type) => el.dispatchEvent(new DragEvent(type, { dataTransfer: dt, bubbles: true, cancelable: true }));
|
||||
if (kind === "tab") fire(source, "dragstart");
|
||||
fire(target, "dragover");
|
||||
const marked = target.classList.contains("is-drop-before");
|
||||
fire(target, "drop");
|
||||
if (kind === "tab") fire(source, "dragend");
|
||||
return marked;
|
||||
},
|
||||
{ from, to, kind },
|
||||
);
|
||||
|
||||
test("tabs reorder by drag only, and the order is kept", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
for (const name of ["Ideas", "Plans", "Done"]) await newTab(s, name);
|
||||
assert.deepEqual(await tabNames(s), ["Notes", "Ideas", "Plans", "Done"]);
|
||||
const order = () => listTabs(s.project).tabs.map((tab) => tab.name);
|
||||
|
||||
// No buttons and no Alt+Arrow: a drag is the only way to move a tab.
|
||||
assert.equal(await s.page.locator("#notepad-tab-left, #notepad-tab-right").count(), 0);
|
||||
await tabNamed(s, "Done").focus();
|
||||
await s.page.keyboard.press("Alt+ArrowLeft");
|
||||
await s.page.waitForTimeout(300);
|
||||
assert.equal(order().join(), "Notes,Ideas,Plans,Done", "Alt+Arrow moved nothing");
|
||||
// Arrows only move the focus, with or without Alt, and never the tab.
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Plans");
|
||||
await s.page.keyboard.press("ArrowLeft");
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Ideas");
|
||||
assert.equal(order().join(), "Notes,Ideas,Plans,Done");
|
||||
|
||||
// Drag: the target shows a mark, the dragged tab lands just before it.
|
||||
assert.equal(await drag(s, "Done", "Notes"), true, "the target is marked while dragged over");
|
||||
await until(() => order().join() === "Done,Notes,Ideas,Plans", 4000);
|
||||
assert.deepEqual(await tabNames(s), ["Done", "Notes", "Ideas", "Plans"]);
|
||||
assert.equal(await s.page.locator("#notepad-tabs .is-drop-before").count(), 0, "the mark is gone after the drop");
|
||||
|
||||
// Text dragged over a tab does nothing.
|
||||
const posted = [];
|
||||
s.page.on("request", (r) => r.url().includes("/notepad/tab/order") && posted.push(r.url()));
|
||||
assert.equal(await drag(s, "Plans", "Ideas", { kind: "text" }), false);
|
||||
await s.page.waitForTimeout(300);
|
||||
assert.equal(order().join(), "Done,Notes,Ideas,Plans");
|
||||
assert.equal(posted.length, 0);
|
||||
|
||||
// Reopened, the order stands.
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await openNotepad(s);
|
||||
assert.deepEqual(await tabNames(s), ["Done", "Notes", "Ideas", "Plans"]);
|
||||
});
|
||||
|
||||
test("Delete asks twice, Escape backs out of either, and only the second confirm removes the tab and its folder", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const violations = await watchViolations(s);
|
||||
await openNotepad(s);
|
||||
await typeInto(s, "keep me");
|
||||
await newTab(s, "Ideas");
|
||||
await typeInto(s, "doomed text");
|
||||
const ideas = idOf(s, "Ideas");
|
||||
const folder = path.join(notepadFolder(s.project), "tabs", ideas);
|
||||
await until(() => readNotepad(s.project, ideas).text === "doomed text", 4000);
|
||||
addImageTo(s.project, ideas, JPEG);
|
||||
addImageTo(s.project, ideas, JPEG);
|
||||
await tabNamed(s, "Notes").click();
|
||||
await tabNamed(s, "Ideas").click();
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 2);
|
||||
|
||||
const panel = s.page.locator("#notepad-delete");
|
||||
const text = () => s.page.locator("#notepad-delete-text").textContent();
|
||||
await s.page.click(X_SELECTED);
|
||||
await panel.waitFor({ state: "visible" });
|
||||
assert.equal(await text(), "This deletes the tab Ideas, its text and its 2 pictures. This cannot be undone.");
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Keep tab", "Keep tab has the focus");
|
||||
assert.equal(await s.page.locator("#notepad-delete-go").textContent(), "Delete tab…");
|
||||
// Keep tab: nothing happens.
|
||||
await s.page.click("#notepad-delete-keep");
|
||||
await panel.waitFor({ state: "hidden" });
|
||||
assert.equal(fs.existsSync(folder), true);
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Ideas");
|
||||
|
||||
// Step one then Escape: nothing deleted, and the Notebook stays open.
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.click("#notepad-delete-go");
|
||||
assert.equal(await text(), "Really delete Ideas for good?");
|
||||
assert.equal(await s.page.locator("#notepad-delete-go").textContent(), "Yes, delete it");
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Keep tab", "Keep tab has the focus on the second step too");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await panel.waitFor({ state: "hidden" });
|
||||
assert.equal(await s.page.evaluate(() => document.getElementById("notepad-modal").open), true);
|
||||
assert.equal(fs.existsSync(folder), true);
|
||||
// Escape at the first step too.
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.keyboard.press("Escape");
|
||||
await panel.waitFor({ state: "hidden" });
|
||||
assert.equal(fs.existsSync(folder), true);
|
||||
|
||||
// Both confirms: gone, with its folder, and the neighbour is shown.
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await until(() => !fs.existsSync(folder), 4000);
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-tabs .notepad-tab").length === 1);
|
||||
assert.deepEqual(await selectedName(s), ["Notes"]);
|
||||
assert.equal(await shows(s, "keep me"), "keep me");
|
||||
assert.equal(listTabs(s.project).last, idOf(s, "Notes"), "the neighbour became the last tab");
|
||||
|
||||
// Delete the last tab: the empty state, with the focus on its button.
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.locator("#notepad-empty").waitFor({ state: "visible" });
|
||||
assert.equal(await s.page.locator("#notepad-body").isHidden(), true, "the editor and pictures are hidden");
|
||||
assert.equal(await s.page.locator("#notepad-empty").innerText().then((x) => x.startsWith("No tabs yet. Make one to start writing.")), true);
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.id), "notepad-empty-new");
|
||||
assert.equal(listTabs(s.project).tabs.length, 0);
|
||||
// Reopened, still empty; a new tab from the empty state works.
|
||||
await closeNotepad(s);
|
||||
await openNotepad(s, { tabs: false });
|
||||
await s.page.locator("#notepad-empty").waitFor({ state: "visible" });
|
||||
await s.page.click("#notepad-empty-new");
|
||||
await s.page.fill("#notepad-name", "Fresh");
|
||||
await s.page.keyboard.press("Enter");
|
||||
await s.page.locator("#notepad-body").waitFor({ state: "visible" });
|
||||
assert.deepEqual(await tabNames(s), ["Fresh"]);
|
||||
assert.deepEqual(await violations(), []);
|
||||
});
|
||||
|
||||
test("text typed into a tab that is then deleted is never saved, and a tab deleted elsewhere leaves the bar with why", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await newTab(s, "Ideas");
|
||||
const ideas = idOf(s, "Ideas");
|
||||
const saves = [];
|
||||
s.page.on("request", (r) => r.url().includes("/notepad/text") && saves.push(r.url()));
|
||||
await typeInto(s, "typed then deleted");
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-tabs .notepad-tab").length === 1);
|
||||
await s.page.waitForTimeout(SAVE_DEBOUNCE_MS + 500);
|
||||
assert.equal(saves.filter((u) => u.includes("tab=" + ideas)).length, 0, "no save was sent for the deleted tab");
|
||||
assert.equal(fs.existsSync(path.join(notepadFolder(s.project), "tabs", ideas)), false);
|
||||
|
||||
// Deleted from another page: picking it says so and shows what is left.
|
||||
await newTab(s, "Elsewhere");
|
||||
const elsewhere = idOf(s, "Elsewhere");
|
||||
await tabNamed(s, "Notes").click();
|
||||
deleteTab(s.project, elsewhere);
|
||||
await tabNamed(s, "Elsewhere").click();
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence("no-such-tab"));
|
||||
assert.deepEqual(await tabNames(s), ["Notes"]);
|
||||
});
|
||||
|
||||
test("a double-click or an x acts on the tab it was made on, even when another is showing", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await newTab(s, "Ideas");
|
||||
const notes = idOf(s, "Notes");
|
||||
assert.deepEqual(await selectedName(s), ["Ideas"]);
|
||||
|
||||
// Double-click on Notes while Ideas shows: Notes is picked and is the one renamed.
|
||||
await tabNamed(s, "Notes").dblclick();
|
||||
await s.page.locator("#notepad-name-dlg[open]").waitFor();
|
||||
assert.equal(await s.page.inputValue("#notepad-name"), "Notes");
|
||||
await until(async () => (await selectedName(s)).join() === "Notes", 4000);
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-name-dlg").open);
|
||||
assert.equal(listTabs(s.project).tabs.find((tab) => tab.id === notes).name, "Notes", "Escape left the name alone");
|
||||
|
||||
// The x on Ideas while Notes shows: the question names Ideas, and Keep leaves both.
|
||||
await xOf(s, "Ideas").click();
|
||||
await s.page.locator("#notepad-delete").waitFor({ state: "visible" });
|
||||
assert.match(await s.page.locator("#notepad-delete-text").textContent(), /^This deletes the tab Ideas,/);
|
||||
await s.page.click("#notepad-delete-keep");
|
||||
await s.page.locator("#notepad-delete").waitFor({ state: "hidden" });
|
||||
assert.deepEqual(await tabNames(s), ["Notes", "Ideas"], "nothing was deleted");
|
||||
|
||||
// Both confirms on the x of the tab that is not showing now remove that one.
|
||||
await tabNamed(s, "Notes").click();
|
||||
await until(async () => (await selectedName(s)).join() === "Notes", 4000);
|
||||
await xOf(s, "Ideas").click();
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-tabs .notepad-tab").length === 1);
|
||||
assert.deepEqual(await tabNames(s), ["Notes"]);
|
||||
});
|
||||
|
||||
test("when the tab after a delete cannot be loaded, the deleted text is not left on screen", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await typeInto(s, "notes text");
|
||||
await newTab(s, "Ideas");
|
||||
await typeInto(s, "doomed text");
|
||||
const ideas = idOf(s, "Ideas");
|
||||
await until(() => readNotepad(s.project, ideas).text === "doomed text", 4000);
|
||||
// The neighbour's read fails, as if the connection dropped right after the delete.
|
||||
await s.page.route("**/notepad?tab=*", (route) => route.abort());
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-tabs .notepad-tab").length === 1);
|
||||
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent.length > 0);
|
||||
assert.equal(await docText(s), "", "the deleted tab's text is gone from the editor");
|
||||
assert.equal(await input(s).getAttribute("aria-readonly"), "true", "and the editor does not take typing it would never save");
|
||||
await s.page.unroute("**/notepad?tab=*");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ pictures */
|
||||
|
||||
|
||||
// The stored pictures for the session's folder, and whether each of a
|
||||
// picture's two files is on disk.
|
||||
const stored = (s) => readNotepad(s.project).images;
|
||||
const filesOf = (s, id) => {
|
||||
const dir = path.join(notepadFolder(s.project), "images");
|
||||
const dir = path.join(notepadFolder(s.project), "tabs", openTab(s.project), "images");
|
||||
return [fs.existsSync(path.join(dir, id + ".jpg")), fs.existsSync(path.join(dir, id + ".thumb.jpg"))];
|
||||
};
|
||||
|
||||
@@ -464,11 +872,11 @@ const sendPicture = (s, kind, colour) =>
|
||||
const blob = await new Promise((resolve) => c.toBlob(resolve, "image/png"));
|
||||
const dt = new DataTransfer();
|
||||
dt.items.add(new File([blob], "pasted.png", { type: "image/png" }));
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
if (kind === "paste") return !ta.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true }));
|
||||
ta.dispatchEvent(new DragEvent("dragover", { dataTransfer: dt, bubbles: true, cancelable: true }));
|
||||
const ta = document.querySelector(".notepad-cm-host").shadowRoot.querySelector(".cm-content");
|
||||
if (kind === "paste") return !ta.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true, composed: true }));
|
||||
ta.dispatchEvent(new DragEvent("dragover", { dataTransfer: dt, bubbles: true, cancelable: true, composed: true }));
|
||||
const lit = document.getElementById("notepad-modal").classList.contains("is-drop");
|
||||
ta.dispatchEvent(new DragEvent("drop", { dataTransfer: dt, bubbles: true, cancelable: true }));
|
||||
ta.dispatchEvent(new DragEvent("drop", { dataTransfer: dt, bubbles: true, cancelable: true, composed: true }));
|
||||
return lit;
|
||||
},
|
||||
{ kind, fill: colour },
|
||||
@@ -488,10 +896,10 @@ test("Add image, paste and drop each add a thumbnail whose files are on disk and
|
||||
await until(() => stored(s).length === 3 && filesOf(s, stored(s)[2].id).every(Boolean), 5000);
|
||||
await readyCount(s, 3);
|
||||
assert.equal(await s.page.locator("#notepad-modal.is-drop").count(), 0, "the highlight is gone after the drop");
|
||||
assert.equal(await input(s).inputValue(), "", "no picture landed in the text");
|
||||
assert.equal(await docText(s), "", "no picture landed in the text");
|
||||
|
||||
const alts = await s.page.locator("#notepad-strip img").evaluateAll((imgs) => imgs.map((i) => i.alt));
|
||||
assert.deepEqual(alts, ["Notepad image 1", "Notepad image 2", "Notepad image 3"]);
|
||||
assert.deepEqual(alts, ["Notebook image 1", "Notebook image 2", "Notebook image 3"]);
|
||||
const xs = await s.page.locator("#notepad-strip .notepad-thumb-delete").evaluateAll((b) => b.map((x) => x.getAttribute("aria-label")));
|
||||
assert.deepEqual(xs, ["Delete image 1", "Delete image 2", "Delete image 3"]);
|
||||
|
||||
@@ -506,7 +914,7 @@ test("Add image, paste and drop each add a thumbnail whose files are on disk and
|
||||
return imgs.length === 3 && imgs.every((i) => new URL(i.src).pathname.startsWith("/notepad/images/"));
|
||||
});
|
||||
const srcs = await s.page.locator("#notepad-strip img").evaluateAll((imgs) => imgs.map((i) => new URL(i.src).pathname));
|
||||
assert.deepEqual(srcs, ids.map((id) => `/notepad/images/${id}.thumb.jpg`));
|
||||
assert.deepEqual(srcs, ids.map((id) => `/notepad/images/${openTab(s.project)}/${id}.thumb.jpg`));
|
||||
await s.page.waitForFunction(() => [...document.querySelectorAll("#notepad-strip img")].every((i) => i.complete && i.naturalWidth > 0));
|
||||
});
|
||||
|
||||
@@ -515,7 +923,7 @@ test("a pasted text snippet still lands in the editor", async (t) => {
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
await openNotepad(s);
|
||||
await s.page.evaluate(() => navigator.clipboard.writeText("a pasted snippet"));
|
||||
await input(s).focus();
|
||||
await input(s).click();
|
||||
await s.page.keyboard.press("Control+V");
|
||||
await shows(s, "a pasted snippet");
|
||||
await until(() => onDisk(s) === "a pasted snippet", 4000);
|
||||
@@ -546,10 +954,10 @@ test("the X asks first: Keep keeps the picture, Delete removes both its files",
|
||||
await until(() => !filesOf(s, first).some(Boolean), 4000);
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 1);
|
||||
assert.deepEqual(stored(s).map((img) => img.id), [second]);
|
||||
assert.equal(await s.page.locator("#notepad-strip img").getAttribute("alt"), "Notepad image 1");
|
||||
assert.equal(await s.page.locator("#notepad-strip img").getAttribute("alt"), "Notebook image 1");
|
||||
});
|
||||
|
||||
test("the preview opens at the clicked picture, steps and wraps, and Esc closes it before the Notepad", async (t) => {
|
||||
test("the preview opens at the clicked picture, steps and wraps, and Esc closes it before the Notebook", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
for (const colour of ["#c33", "#3c3", "#33c"]) await addViaButton(s, colour);
|
||||
@@ -580,7 +988,7 @@ test("the preview opens at the clicked picture, steps and wraps, and Esc closes
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-preview").open);
|
||||
assert.equal(await s.page.evaluate(() => document.getElementById("notepad-modal").open), true, "the Notepad stays open");
|
||||
assert.equal(await s.page.evaluate(() => document.getElementById("notepad-modal").open), true, "the Notebook stays open");
|
||||
assert.equal(
|
||||
await s.page.evaluate(() => document.activeElement.closest("li") === document.querySelector("#notepad-strip li:nth-child(2)")),
|
||||
true,
|
||||
@@ -693,11 +1101,11 @@ test("User Preferences, Cleanup offers a month-old notepad by its folder and rem
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.click("#cleanup-scan");
|
||||
const list = s.page.locator("#cleanup-list");
|
||||
const row = list.locator(".cleanup-row").filter({ hasText: "Notepad for" });
|
||||
const row = list.locator(".cleanup-row").filter({ hasText: "Notebook for" });
|
||||
await row.waitFor();
|
||||
assert.equal(await row.count(), 1, "one item for the whole notepad");
|
||||
assert.equal((await row.locator("span").first().innerText()).trim(), "Notepad for " + path.resolve(s.project));
|
||||
assert.ok((await list.locator(".cleanup-summary").innerText()).includes("1 old notepad"), "the summary counts it as a notepad");
|
||||
assert.equal((await row.locator("span").first().innerText()).trim(), "Notebook for " + path.resolve(s.project));
|
||||
assert.ok((await list.locator(".cleanup-summary").innerText()).includes("1 old notebook"), "the summary counts it as a notepad");
|
||||
assert.equal(await list.locator(".cleanup-row").filter({ hasText: "notepads/" }).count(), 0, "the notepads folder is no stray");
|
||||
assert.equal(fs.existsSync(notepadFolder(s.project)), true, "a scan only looks");
|
||||
|
||||
@@ -746,9 +1154,9 @@ test("Help's Getting around panel describes the notepad", async (t) => {
|
||||
await s.page.locator("#help-modal").waitFor();
|
||||
await s.page.click("#help-tab-around");
|
||||
const panel = s.page.locator("#help-panel-around");
|
||||
await panel.getByRole("heading", { name: "Your notepad" }).waitFor();
|
||||
await panel.getByRole("heading", { name: "Your notebook" }).waitFor();
|
||||
const text = await panel.innerText();
|
||||
for (const words of ["Notepad", "never sent to Plan2Code", "last save wins", "Cleanup"]) {
|
||||
for (const words of ["Notebook", "never sent to Plan2Code", "last save wins", "Cleanup"]) {
|
||||
assert.ok(text.includes(words), `the panel mentions ${words}`);
|
||||
}
|
||||
});
|
||||
@@ -186,7 +186,8 @@ test("shape: no page module sets a style attribute from script", () => {
|
||||
const ROUTE_ORDER = [
|
||||
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
|
||||
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
|
||||
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/images/",
|
||||
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
|
||||
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/images/",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
|
||||
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
|
||||
];
|
||||
|
||||
@@ -0,0 +1,703 @@
|
||||
{
|
||||
"name": "cm-build",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "cm-build",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.11.1",
|
||||
"@codemirror/lang-markdown": "6.5.2",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"esbuild": "0.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/autocomplete": {
|
||||
"version": "6.20.4",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz",
|
||||
"integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/common": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/commands": {
|
||||
"version": "6.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz",
|
||||
"integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.7.0",
|
||||
"@codemirror/view": "^6.27.0",
|
||||
"@lezer/common": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-css": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
|
||||
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.0.0",
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@lezer/common": "^1.0.2",
|
||||
"@lezer/css": "^1.1.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-html": {
|
||||
"version": "6.4.12",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz",
|
||||
"integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.0.0",
|
||||
"@codemirror/lang-css": "^6.0.0",
|
||||
"@codemirror/lang-javascript": "^6.0.0",
|
||||
"@codemirror/language": "^6.4.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/common": "^1.0.0",
|
||||
"@lezer/css": "^1.1.0",
|
||||
"@lezer/html": "^1.3.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-javascript": {
|
||||
"version": "6.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
|
||||
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.0.0",
|
||||
"@codemirror/language": "^6.6.0",
|
||||
"@codemirror/lint": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/common": "^1.0.0",
|
||||
"@lezer/javascript": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lang-markdown": {
|
||||
"version": "6.5.2",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz",
|
||||
"integrity": "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.7.1",
|
||||
"@codemirror/lang-html": "^6.0.0",
|
||||
"@codemirror/language": "^6.3.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.0.0",
|
||||
"@lezer/common": "^1.2.1",
|
||||
"@lezer/markdown": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/language": {
|
||||
"version": "6.13.1",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz",
|
||||
"integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/streamparser": "^6.0.0",
|
||||
"@codemirror/view": "^6.23.0",
|
||||
"@lezer/common": "^1.5.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@lezer/lr": "^1.0.0",
|
||||
"style-mod": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lint": {
|
||||
"version": "6.9.7",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
|
||||
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.42.0",
|
||||
"crelt": "^1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/state": {
|
||||
"version": "6.7.6",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz",
|
||||
"integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@marijn/find-cluster-break": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/streamparser": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz",
|
||||
"integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@codemirror/view": {
|
||||
"version": "6.43.15",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz",
|
||||
"integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.7.0",
|
||||
"crelt": "^1.0.6",
|
||||
"style-mod": "^4.1.0",
|
||||
"w3c-keyname": "^2.2.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"aix"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
|
||||
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
|
||||
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
|
||||
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
|
||||
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
|
||||
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
|
||||
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
|
||||
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
|
||||
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openharmony"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
|
||||
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/common": {
|
||||
"version": "1.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.3.tgz",
|
||||
"integrity": "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@lezer/css": {
|
||||
"version": "1.3.9",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.9.tgz",
|
||||
"integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.2.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@lezer/lr": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/highlight": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz",
|
||||
"integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/html": {
|
||||
"version": "1.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
|
||||
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.2.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@lezer/lr": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/javascript": {
|
||||
"version": "1.5.6",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.6.tgz",
|
||||
"integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.2.0",
|
||||
"@lezer/highlight": "^1.1.3",
|
||||
"@lezer/lr": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/lr": {
|
||||
"version": "1.4.11",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.11.tgz",
|
||||
"integrity": "sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/markdown": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.8.1.tgz",
|
||||
"integrity": "sha512-M5YmEcKWO4mJ45Y1hECwqyu8cLv25EiXOK554PVOvDOWOP0olwelHHQUWr9sjF+d1bENVhy0nfJ8E57XZUTiXg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.5.0",
|
||||
"@lezer/highlight": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@marijn/find-cluster-break": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz",
|
||||
"integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/crelt": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
|
||||
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
|
||||
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.28.2",
|
||||
"@esbuild/android-arm": "0.28.2",
|
||||
"@esbuild/android-arm64": "0.28.2",
|
||||
"@esbuild/android-x64": "0.28.2",
|
||||
"@esbuild/darwin-arm64": "0.28.2",
|
||||
"@esbuild/darwin-x64": "0.28.2",
|
||||
"@esbuild/freebsd-arm64": "0.28.2",
|
||||
"@esbuild/freebsd-x64": "0.28.2",
|
||||
"@esbuild/linux-arm": "0.28.2",
|
||||
"@esbuild/linux-arm64": "0.28.2",
|
||||
"@esbuild/linux-ia32": "0.28.2",
|
||||
"@esbuild/linux-loong64": "0.28.2",
|
||||
"@esbuild/linux-mips64el": "0.28.2",
|
||||
"@esbuild/linux-ppc64": "0.28.2",
|
||||
"@esbuild/linux-riscv64": "0.28.2",
|
||||
"@esbuild/linux-s390x": "0.28.2",
|
||||
"@esbuild/linux-x64": "0.28.2",
|
||||
"@esbuild/netbsd-arm64": "0.28.2",
|
||||
"@esbuild/netbsd-x64": "0.28.2",
|
||||
"@esbuild/openbsd-arm64": "0.28.2",
|
||||
"@esbuild/openbsd-x64": "0.28.2",
|
||||
"@esbuild/openharmony-arm64": "0.28.2",
|
||||
"@esbuild/sunos-x64": "0.28.2",
|
||||
"@esbuild/win32-arm64": "0.28.2",
|
||||
"@esbuild/win32-ia32": "0.28.2",
|
||||
"@esbuild/win32-x64": "0.28.2"
|
||||
}
|
||||
},
|
||||
"node_modules/style-mod": {
|
||||
"version": "4.1.4",
|
||||
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz",
|
||||
"integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/w3c-keyname": {
|
||||
"version": "2.2.8",
|
||||
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
|
||||
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env node
|
||||
// Builds the one vendored CodeMirror file the Notebook's live-preview editor
|
||||
// imports. Dev-only: lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// node scripts/vendor-codemirror.mjs rebuild from the lock file
|
||||
// node scripts/vendor-codemirror.mjs --update-lock after changing a version below
|
||||
//
|
||||
// The console has no dependencies and no build step for users, so CodeMirror 6
|
||||
// is bundled once, here, into src/web-console/public/vendor/codemirror.esm.js
|
||||
// (Markdown only, minified, one ES module). The packages and esbuild are
|
||||
// installed into a throwaway folder under the OS temp directory, never into
|
||||
// the repo. Only the six packages below are named; everything they pull in
|
||||
// (@lezer/*, style-mod, w3c-keyname, crelt) is pinned by
|
||||
// scripts/vendor-codemirror-lock.json, installed with npm ci, so the same
|
||||
// lock gives the same bytes. Needs Node 18+, npm and network access.
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const OUT = path.join(ROOT, "src", "web-console", "public", "vendor", "codemirror.esm.js");
|
||||
const LOCK = path.join(ROOT, "scripts", "vendor-codemirror-lock.json");
|
||||
|
||||
export const VERSIONS = Object.freeze({
|
||||
esbuild: "0.28.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
"@codemirror/lang-markdown": "6.5.2",
|
||||
});
|
||||
|
||||
export const HEADER =
|
||||
"/* CodeMirror 6 (state, view, language, commands, lang-markdown), MIT licence, (c) Marijn Haverbeke and others.\n" +
|
||||
" * https://codemirror.net/ . Bundled by scripts/vendor-codemirror.mjs; do not edit by hand.\n" +
|
||||
" * Versions: " +
|
||||
Object.entries(VERSIONS)
|
||||
.filter(([name]) => name !== "esbuild")
|
||||
.map(([name, version]) => name + " " + version)
|
||||
.join(", ") +
|
||||
" */\n";
|
||||
|
||||
// What the page may import: exactly what notepad-editor.js uses, since an
|
||||
// entry export is never tree-shaken. indentWithTab is left out on purpose: it
|
||||
// would trap the Tab key and keyboard users could not leave the editor.
|
||||
export const ENTRY = `export { Compartment, EditorState } from "@codemirror/state";
|
||||
export { Decoration, EditorView, ViewPlugin, WidgetType, keymap } from "@codemirror/view";
|
||||
export { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
export { syntaxTree } from "@codemirror/language";
|
||||
export { defaultKeymap, history, historyKeymap, redo } from "@codemirror/commands";
|
||||
`;
|
||||
|
||||
// npm is a .cmd file on Windows, which only a shell can start; node never needs one
|
||||
// (its path may hold spaces).
|
||||
function run(cmd, args, cwd) {
|
||||
const res = spawnSync(cmd, args, { cwd, encoding: "utf8", shell: process.platform === "win32" && cmd === "npm" });
|
||||
if (res.status !== 0) {
|
||||
process.stderr.write((res.stdout || "") + (res.stderr || ""));
|
||||
throw new Error(`${cmd} ${args.join(" ")} failed (${res.status})`);
|
||||
}
|
||||
return res.stdout;
|
||||
}
|
||||
|
||||
export function build({ updateLock = false } = {}) {
|
||||
const work = fs.mkdtempSync(path.join(os.tmpdir(), "plan2code-codemirror-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(work, "package.json"), JSON.stringify({ name: "cm-build", private: true, type: "module", dependencies: VERSIONS }));
|
||||
if (updateLock || !fs.existsSync(LOCK)) {
|
||||
run("npm", ["install", "--no-audit", "--no-fund", "--ignore-scripts", "--package-lock-only"], work);
|
||||
fs.copyFileSync(path.join(work, "package-lock.json"), LOCK);
|
||||
} else {
|
||||
fs.copyFileSync(LOCK, path.join(work, "package-lock.json"));
|
||||
}
|
||||
run("npm", ["ci", "--no-audit", "--no-fund", "--ignore-scripts"], work);
|
||||
fs.writeFileSync(path.join(work, "entry.js"), ENTRY);
|
||||
const esbuild = path.join(work, "node_modules", "esbuild", "bin", "esbuild");
|
||||
run(process.execPath, [esbuild, "entry.js", "--bundle", "--format=esm", "--minify", "--target=es2022", "--legal-comments=none", "--outfile=out.js"], work);
|
||||
const body = fs.readFileSync(path.join(work, "out.js"), "utf8");
|
||||
fs.mkdirSync(path.dirname(OUT), { recursive: true });
|
||||
fs.writeFileSync(OUT, HEADER + body);
|
||||
} finally {
|
||||
fs.rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
const bytes = fs.readFileSync(OUT);
|
||||
return { file: path.relative(ROOT, OUT), bytes: bytes.length, sha256: crypto.createHash("sha256").update(bytes).digest("hex") };
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
console.log(JSON.stringify(build({ updateLock: process.argv.includes("--update-lock") }), null, 2));
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Captures the CSS the vendored OverType would inject, as a real stylesheet.
|
||||
// Dev-only: lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// node scripts/vendor-overtype.mjs
|
||||
//
|
||||
// The console's content-security policy (`style-src 'self'`) blocks the
|
||||
// <style> OverType adds to the page, so the notepad sets
|
||||
// `OverType.stylesInjected = true` and ships the same rules in
|
||||
// src/web-console/public/styles/notepad.css instead. This script loads
|
||||
// public/vendor/overtype.esm.js in a blank page, calls
|
||||
// `OverType.injectStyles(true)` and writes what landed in
|
||||
// `style.overtype-styles` between the header and the end marker below. The
|
||||
// notepad's own rules, after the marker, are kept as they are. Run it again
|
||||
// after upgrading the vendored file.
|
||||
//
|
||||
// Needs playwright-core (a root devDependency) and a local Chrome or Edge,
|
||||
// launched through scripts/browser.mjs.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const PUBLIC = path.join(ROOT, "src", "web-console", "public");
|
||||
const VENDOR = path.join(PUBLIC, "vendor", "overtype.esm.js");
|
||||
const OUT = path.join(PUBLIC, "styles", "notepad.css");
|
||||
|
||||
export const HEADER = "/* OverType 2.6.1 generated CSS: regenerate with node scripts/vendor-overtype.mjs */";
|
||||
export const END_MARKER = "/* end OverType */";
|
||||
|
||||
// A made-up origin served from here, so the module loads as it does on the
|
||||
// page: as a module, from a URL, with nothing else around it.
|
||||
const ORIGIN = "http://overtype.invalid";
|
||||
|
||||
async function capture() {
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.route(`${ORIGIN}/**`, (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.pathname === "/overtype.esm.js") {
|
||||
return route.fulfill({ contentType: "text/javascript", body: fs.readFileSync(VENDOR) });
|
||||
}
|
||||
return route.fulfill({ contentType: "text/html", body: "<!doctype html><title>OverType CSS</title>" });
|
||||
});
|
||||
await page.goto(`${ORIGIN}/`);
|
||||
return await page.evaluate(async (src) => {
|
||||
const { OverType } = await import(src);
|
||||
OverType.injectStyles(true);
|
||||
const style = document.querySelector("style.overtype-styles");
|
||||
return style ? style.textContent : null;
|
||||
}, `${ORIGIN}/overtype.esm.js`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
// The generated block, then whatever followed the marker before (the
|
||||
// notepad's own rules), or nothing on a first run. A stylesheet with rules but
|
||||
// no marker is refused: rewriting it would delete them.
|
||||
export function assemble(css, existing) {
|
||||
const at = existing.indexOf(END_MARKER);
|
||||
if (at === -1 && existing.trim()) {
|
||||
throw new Error(`notepad.css has no "${END_MARKER}" marker, so its own rules cannot be told apart: put the marker back, then run this again.`);
|
||||
}
|
||||
const own = at === -1 ? "" : existing.slice(at + END_MARKER.length);
|
||||
const body = css.trim().split("\n").map((line) => line.replace(/\s+$/, "")).join("\n");
|
||||
return `${HEADER}\n${body}\n${END_MARKER}${own || "\n"}`;
|
||||
}
|
||||
|
||||
const css = await capture().catch((e) => {
|
||||
console.error(e.browserProblem ? e.message : `Could not capture OverType's CSS: ${e.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
if (!css) {
|
||||
console.error("OverType injected no style.overtype-styles element.");
|
||||
process.exit(1);
|
||||
}
|
||||
const existing = fs.existsSync(OUT) ? fs.readFileSync(OUT, "utf8") : "";
|
||||
let out;
|
||||
try {
|
||||
out = assemble(css, existing);
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
fs.writeFileSync(OUT, out);
|
||||
console.log(`Wrote ${path.relative(ROOT, OUT)} (${css.length} characters of OverType CSS).`);
|
||||
@@ -1,13 +1,19 @@
|
||||
// Plan2Code Web Console - the notepad store.
|
||||
//
|
||||
// One notepad per folder Plan2Code runs in (the session's worktree, else its
|
||||
// project), outside every repo and every session:
|
||||
// project), outside every repo and every session, split into named tabs:
|
||||
//
|
||||
// ~/.plan2code/notepads/<folder-name>-<12 hex>/
|
||||
// meta.json { v: 1, folder, created }, written once
|
||||
// note.md the text, UTF-8, written atomically
|
||||
// images/<uuid>.jpg a picture, JPEG from the page
|
||||
// images/<uuid>.thumb.jpg its thumbnail, when the page sent one
|
||||
// meta.json { v: 2, folder, created }
|
||||
// tabs.json { v: 1, order: [id], last: id|null, tabs: { id: { name, created } } }
|
||||
// tabs/<id>/note.md the tab's text, UTF-8, written atomically
|
||||
// tabs/<id>/images/<uuid>.jpg a picture, JPEG from the page
|
||||
// tabs/<id>/images/<uuid>.thumb.jpg its thumbnail, when the page sent one
|
||||
//
|
||||
// The first shape (v: 1) kept one note.md and images/ at the top. Reading that
|
||||
// shape answers one virtual tab called Notes and writes nothing; the first
|
||||
// write moves the files into tabs/<LEGACY_TAB_ID>/ and writes tabs.json last,
|
||||
// every step safe to run again after a crash.
|
||||
//
|
||||
// This module is the only code that names, reads, writes, lists and removes
|
||||
// them. The page reaches it through the /notepad routes; the agent CLI never
|
||||
@@ -22,7 +28,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { ensureDir, newestMtime, nowIso, readJson, withStateLock, writeJsonAtomic, writeTextAtomic } from "./files.mjs";
|
||||
import { ensureDir, newestMtime, nowIso, readJson, sleepSync, withStateLock, writeJsonAtomic, writeTextAtomic } from "./files.mjs";
|
||||
import { foldKey } from "./workspace.mjs";
|
||||
|
||||
// Read at call time, so a test that sets the variable after import sees it.
|
||||
@@ -34,8 +40,15 @@ 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 NOTEPAD_KEY_RE = /^[a-z0-9-]{1,40}-[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 fixed id of the tab the first-shape note and pictures move into.
|
||||
export const LEGACY_TAB_ID = "0000000000a1";
|
||||
|
||||
// A refusal the routes turn into `{ error: code }` with this status.
|
||||
// A refusal the routes turn into `{ error: code }` with this status. Codes:
|
||||
// bad, too-long, too-many, not-jpeg, not-found, and for tabs bad-name (400),
|
||||
// duplicate-name (409), too-many-tabs (409), no-such-tab (404).
|
||||
export class NotepadError extends Error {
|
||||
constructor(code, status) {
|
||||
super(code);
|
||||
@@ -66,17 +79,223 @@ export function notepadFolder(folder) {
|
||||
return path.join(notepadsDir(), notepadKey(folder));
|
||||
}
|
||||
|
||||
/** A tab name, trimmed and with inner whitespace collapsed, or a `bad-name` refusal. */
|
||||
export function normalizeTabName(name) {
|
||||
if (typeof name !== "string") throw new NotepadError("bad-name", 400);
|
||||
const clean = name.trim().replace(/\s+/g, " ");
|
||||
// Code points, not UTF-16 units, so one emoji counts as one.
|
||||
if (!clean || [...clean].length > TAB_NAME_MAX || /[\u0000-\u001f\u007f]/.test(clean)) throw new NotepadError("bad-name", 400);
|
||||
return clean;
|
||||
}
|
||||
|
||||
/** What two names are compared by: the same name however its case is typed. */
|
||||
export const nameKey = (name) => normalizeTabName(name).toLocaleLowerCase("en-US");
|
||||
|
||||
/* ------------------------------------------------------------------ index */
|
||||
|
||||
const INDEX_FILE = "tabs.json";
|
||||
const META_FILE = "meta.json";
|
||||
|
||||
const isDir = (p) => {
|
||||
try {
|
||||
return fs.lstatSync(p).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const isFile = (p) => {
|
||||
try {
|
||||
return fs.lstatSync(p).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// `{ order, last, tabs: { id: { name, created } } }` from tabs.json with every
|
||||
// part of its shape checked, or null when it is missing or does not hold up.
|
||||
function readIndex(dir) {
|
||||
const raw = readJson(path.join(dir, INDEX_FILE));
|
||||
if (!raw || typeof raw !== "object" || !Array.isArray(raw.order)) return null;
|
||||
if (!raw.tabs || typeof raw.tabs !== "object" || Array.isArray(raw.tabs)) return null;
|
||||
if (raw.order.length !== Object.keys(raw.tabs).length || new Set(raw.order).size !== raw.order.length) return null;
|
||||
const tabs = {};
|
||||
for (const id of raw.order) {
|
||||
if (typeof id !== "string" || !TAB_ID_RE.test(id)) return null;
|
||||
const t = raw.tabs[id];
|
||||
if (!t || typeof t !== "object") return null;
|
||||
try {
|
||||
tabs[id] = { name: normalizeTabName(t.name), created: typeof t.created === "string" ? t.created : null };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (raw.last !== null && !(typeof raw.last === "string" && Object.hasOwn(tabs, raw.last))) return null;
|
||||
return { order: [...raw.order], last: raw.last, tabs };
|
||||
}
|
||||
|
||||
function writeIndex(dir, index) {
|
||||
writeJsonAtomic(path.join(dir, INDEX_FILE), { v: 1, order: index.order, last: index.last, tabs: index.tabs });
|
||||
}
|
||||
|
||||
// True while the notepad still has the first shape: no tabs.json, and a note
|
||||
// or a picture at the top, or a half-finished move into the first tab.
|
||||
function legacyShape(dir) {
|
||||
if (fs.existsSync(path.join(dir, INDEX_FILE))) return false;
|
||||
if (isFile(path.join(dir, "note.md")) || isDir(path.join(dir, "tabs", LEGACY_TAB_ID))) return true;
|
||||
try {
|
||||
return fs.readdirSync(path.join(dir, "images")).some((n) => n.endsWith(".jpg"));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Read only: is this a tab the notepad has (or, still in the first shape, the
|
||||
// one it will have)? A damaged index answers by the folders on disk, since the
|
||||
// next write rebuilds it from them.
|
||||
function knownTab(dir, tab) {
|
||||
if (typeof tab !== "string" || !TAB_ID_RE.test(tab)) return false;
|
||||
const index = readIndex(dir);
|
||||
if (index) return Object.hasOwn(index.tabs, tab);
|
||||
if (fs.existsSync(path.join(dir, INDEX_FILE))) return isDir(path.join(dir, "tabs", tab));
|
||||
return tab === LEGACY_TAB_ID && legacyShape(dir);
|
||||
}
|
||||
|
||||
function requireTab(folder, tab) {
|
||||
if (!knownTab(notepadFolder(folder), tab)) throw new NotepadError("no-such-tab", 404);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ write */
|
||||
|
||||
// Every write goes through here: the folder, its images/ and meta.json come
|
||||
// into being on the first one, and each runs under the notepad's own lock so
|
||||
// two pages on one folder never interleave. Nothing that only reads calls it.
|
||||
// A rename, retried while Windows still holds the file or folder.
|
||||
function moveEntry(from, to) {
|
||||
let lastErr;
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
fs.renameSync(from, to);
|
||||
return;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
|
||||
sleepSync(40 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
throw lastErr;
|
||||
}
|
||||
|
||||
function writeMeta(dir, folder) {
|
||||
const file = path.join(dir, META_FILE);
|
||||
const meta = readJson(file);
|
||||
if (meta && meta.v === 2) return;
|
||||
const had = meta && typeof meta === "object";
|
||||
writeJsonAtomic(file, {
|
||||
v: 2,
|
||||
folder: had && typeof meta.folder === "string" ? meta.folder : path.resolve(String(folder)),
|
||||
created: had && typeof meta.created === "string" ? meta.created : nowIso(),
|
||||
});
|
||||
}
|
||||
|
||||
// The first shape into the first tab: the note, then the pictures, then the
|
||||
// index, then meta.json's version. Each step looks at what is already there,
|
||||
// so running it again after a crash at any point finishes the move and loses
|
||||
// or duplicates nothing.
|
||||
function migrate(dir, folder) {
|
||||
if (!legacyShape(dir)) return;
|
||||
const leg = path.join(dir, "tabs", LEGACY_TAB_ID);
|
||||
ensureDir(leg);
|
||||
const rootNote = path.join(dir, "note.md");
|
||||
if (isFile(rootNote) && !fs.existsSync(path.join(leg, "note.md"))) moveEntry(rootNote, path.join(leg, "note.md"));
|
||||
const rootImages = path.join(dir, "images");
|
||||
const target = path.join(leg, "images");
|
||||
if (isDir(rootImages)) {
|
||||
if (!fs.existsSync(target)) {
|
||||
moveEntry(rootImages, target);
|
||||
} else {
|
||||
for (const name of fs.readdirSync(rootImages)) {
|
||||
if (!fs.existsSync(path.join(target, name))) moveEntry(path.join(rootImages, name), path.join(target, name));
|
||||
}
|
||||
fs.rmSync(rootImages, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
ensureDir(target);
|
||||
writeIndex(dir, { order: [LEGACY_TAB_ID], last: LEGACY_TAB_ID, tabs: { [LEGACY_TAB_ID]: { name: "Notes", created: nowIso() } } });
|
||||
writeMeta(dir, folder);
|
||||
}
|
||||
|
||||
// A tabs.json that does not hold up is set aside and rebuilt from the tab
|
||||
// folders on disk, so a damaged index never costs a note.
|
||||
function recoverIndex(dir) {
|
||||
const file = path.join(dir, INDEX_FILE);
|
||||
try {
|
||||
moveEntry(file, file + ".corrupt");
|
||||
} catch {}
|
||||
let names = [];
|
||||
try {
|
||||
names = fs
|
||||
.readdirSync(path.join(dir, "tabs"), { withFileTypes: true })
|
||||
.filter((e) => e.isDirectory() && TAB_ID_RE.test(e.name))
|
||||
.map((e) => e.name)
|
||||
.sort();
|
||||
} catch {}
|
||||
const tabs = {};
|
||||
names.forEach((id, i) => (tabs[id] = { name: "Recovered " + (i + 1), created: nowIso() }));
|
||||
return { order: names, last: names[0] ?? null, tabs };
|
||||
}
|
||||
|
||||
// What every write starts from, under the lock: finish a move from the first
|
||||
// shape, give a fresh notepad its empty index, and settle meta.json at v: 2.
|
||||
function prepare(dir, folder) {
|
||||
migrate(dir, folder);
|
||||
let index = readIndex(dir);
|
||||
if (!index) {
|
||||
index = fs.existsSync(path.join(dir, INDEX_FILE)) ? recoverIndex(dir) : { order: [], last: null, tabs: {} };
|
||||
writeIndex(dir, index);
|
||||
try {
|
||||
fs.rmdirSync(path.join(dir, "images")); // an empty leftover of the first shape
|
||||
} catch {}
|
||||
}
|
||||
writeMeta(dir, folder);
|
||||
return index;
|
||||
}
|
||||
|
||||
// Every write goes through here: the folder and its index come into being on
|
||||
// the first one, and each runs under the notepad's own lock so two pages on
|
||||
// one folder never interleave. Nothing that only reads calls it.
|
||||
function withNotepad(folder, fn) {
|
||||
const dir = notepadFolder(folder);
|
||||
ensureDir(path.join(dir, "images"));
|
||||
const meta = path.join(dir, "meta.json");
|
||||
if (!fs.existsSync(meta)) writeJsonAtomic(meta, { v: 1, folder: path.resolve(String(folder)), created: nowIso() });
|
||||
return withStateLock(dir, () => fn(dir), "notepad.lock");
|
||||
ensureDir(dir);
|
||||
return withStateLock(
|
||||
dir,
|
||||
() => {
|
||||
const index = prepare(dir, folder);
|
||||
return fn(dir, index);
|
||||
},
|
||||
"notepad.lock",
|
||||
);
|
||||
}
|
||||
|
||||
// Index first, then the folders it no longer names: a crash between the two
|
||||
// leaves a stray folder the next structure change sweeps away.
|
||||
function commit(dir, index) {
|
||||
writeIndex(dir, index);
|
||||
sweepOrphanTabs(dir, index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove every `tabs/<id>` folder the index does not name: only real
|
||||
* directories (never a link) whose name is a tab id.
|
||||
*/
|
||||
export function sweepOrphanTabs(dir, index) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(path.join(dir, "tabs"), { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) {
|
||||
if (e.isDirectory() && TAB_ID_RE.test(e.name) && !Object.hasOwn(index.tabs, e.name)) {
|
||||
fs.rmSync(path.join(dir, "tabs", e.name), { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- read */
|
||||
@@ -91,119 +310,264 @@ function mtimeOf(file) {
|
||||
}
|
||||
}
|
||||
|
||||
// The full images' ids, oldest first (an image is never rewritten after it is
|
||||
// added, so its mtime is when it arrived).
|
||||
function imageIds(dir) {
|
||||
let names;
|
||||
try {
|
||||
names = fs.readdirSync(path.join(dir, "images"));
|
||||
} catch {
|
||||
return [];
|
||||
// The full images' ids across these folders, oldest first (an image is never
|
||||
// rewritten after it is added, so its mtime is when it arrived), each with the
|
||||
// folder it was found in.
|
||||
function imageEntries(dirs) {
|
||||
const seen = new Map();
|
||||
for (const d of dirs) {
|
||||
let names;
|
||||
try {
|
||||
names = fs.readdirSync(d);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const name of names.filter(fullImage)) {
|
||||
const id = name.slice(0, -4);
|
||||
if (!seen.has(id)) seen.set(id, { id, dir: d, at: mtimeOf(path.join(d, name)) ?? 0 });
|
||||
}
|
||||
}
|
||||
return names
|
||||
.filter(fullImage)
|
||||
.map((name) => ({ id: name.slice(0, -4), at: mtimeOf(path.join(dir, "images", name)) ?? 0 }))
|
||||
.sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
||||
.map((e) => e.id);
|
||||
return [...seen.values()].sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||
}
|
||||
|
||||
const imageUrl = (tab, id, thumb) => "/notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg";
|
||||
|
||||
/**
|
||||
* The tabs, as `[{ id, name }]` in order, and the one last used. Read only; a
|
||||
* notepad still in the first shape answers one virtual tab, Notes.
|
||||
*/
|
||||
export function listTabs(folder) {
|
||||
const dir = notepadFolder(folder);
|
||||
if (!fs.existsSync(dir)) return { tabs: [], last: null };
|
||||
const index = readIndex(dir);
|
||||
if (index) return { tabs: index.order.map((id) => ({ id, name: index.tabs[id].name })), last: index.last };
|
||||
if (legacyShape(dir)) return { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID };
|
||||
return { tabs: [], last: null };
|
||||
}
|
||||
|
||||
/** The tab an unnamed request means: the last one used, else the first, else null. */
|
||||
export function defaultTabId(folder) {
|
||||
const { tabs, last } = listTabs(folder);
|
||||
return last ?? (tabs[0] ? tabs[0].id : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the page shows: `{ text, savedAt, images: [{ id, url, thumb }] }`.
|
||||
* Never creates or writes anything; a folder with no notepad yet reads empty.
|
||||
* What the page shows:
|
||||
* `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images } | null }`
|
||||
* for the tab asked for (else the default one), plus that tab's `text`,
|
||||
* `savedAt` and `images` at the top, where the first page read them. A named
|
||||
* tab that does not exist is a `no-such-tab` refusal. Never creates or writes
|
||||
* anything; a folder with no notepad yet reads empty.
|
||||
*/
|
||||
export function readNotepad(folder) {
|
||||
export function readNotepad(folder, tabId) {
|
||||
if (tabId !== undefined && tabId !== null && !(typeof tabId === "string" && TAB_ID_RE.test(tabId))) {
|
||||
throw new NotepadError("no-such-tab", 404);
|
||||
}
|
||||
const { tabs, last } = listTabs(folder);
|
||||
const id = tabId ?? last ?? (tabs[0] ? tabs[0].id : null);
|
||||
if (tabId && !tabs.some((t) => t.id === tabId)) throw new NotepadError("no-such-tab", 404);
|
||||
if (id === null) return { tabs, last, tab: null, text: "", savedAt: null, images: [] };
|
||||
const dir = notepadFolder(folder);
|
||||
if (!fs.existsSync(dir)) return { text: "", savedAt: null, images: [] };
|
||||
const note = path.join(dir, "note.md");
|
||||
const legacy = id === LEGACY_TAB_ID && !readIndex(dir) && legacyShape(dir);
|
||||
const tabDir = path.join(dir, "tabs", id);
|
||||
// Still in the first shape: the note and pictures are at the top, or, in a
|
||||
// half-finished move, split between the top and the first tab.
|
||||
const noteFiles = legacy ? [path.join(dir, "note.md"), path.join(tabDir, "note.md")] : [path.join(tabDir, "note.md")];
|
||||
const imageDirs = legacy ? [path.join(tabDir, "images"), path.join(dir, "images")] : [path.join(tabDir, "images")];
|
||||
const note = noteFiles.find(isFile) ?? noteFiles[0];
|
||||
let text = "";
|
||||
try {
|
||||
text = fs.readFileSync(note, "utf8");
|
||||
} catch {}
|
||||
const at = mtimeOf(note);
|
||||
const images = imageIds(dir).map((id) => ({
|
||||
id,
|
||||
url: "/notepad/images/" + id + ".jpg",
|
||||
thumb: fs.existsSync(path.join(dir, "images", id + ".thumb.jpg")) ? "/notepad/images/" + id + ".thumb.jpg" : null,
|
||||
const images = imageEntries(imageDirs).map((e) => ({
|
||||
id: e.id,
|
||||
url: imageUrl(id, e.id, false),
|
||||
thumb: fs.existsSync(path.join(e.dir, e.id + ".thumb.jpg")) ? imageUrl(id, e.id, true) : null,
|
||||
}));
|
||||
return { text, savedAt: at === null ? null : new Date(at).toISOString(), images };
|
||||
const savedAt = at === null ? null : new Date(at).toISOString();
|
||||
return { tabs, last, tab: { id, text, savedAt, images }, text, savedAt, images };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ change */
|
||||
/* ------------------------------------------------------------- tab changes */
|
||||
|
||||
/** Add a tab named `name` and make it the last one used. Resolves to `{ id, name }`. */
|
||||
export function createTab(folder, name) {
|
||||
const clean = normalizeTabName(name);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
if (index.order.length >= NOTEPAD_MAX_TABS) throw new NotepadError("too-many-tabs", 409);
|
||||
const key = nameKey(clean);
|
||||
if (index.order.some((id) => nameKey(index.tabs[id].name) === key)) throw new NotepadError("duplicate-name", 409);
|
||||
let id;
|
||||
do id = crypto.randomBytes(6).toString("hex");
|
||||
while (Object.hasOwn(index.tabs, id) || id === LEGACY_TAB_ID || fs.existsSync(path.join(dir, "tabs", id)));
|
||||
ensureDir(path.join(dir, "tabs", id, "images"));
|
||||
index.order.push(id);
|
||||
index.tabs[id] = { name: clean, created: nowIso() };
|
||||
index.last = id;
|
||||
commit(dir, index);
|
||||
return { id, name: clean };
|
||||
});
|
||||
}
|
||||
|
||||
/** Give a tab a new name (the same name in another case is allowed). */
|
||||
export function renameTab(folder, id, name) {
|
||||
const clean = normalizeTabName(name);
|
||||
requireTab(folder, id);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
if (!Object.hasOwn(index.tabs, id)) throw new NotepadError("no-such-tab", 404);
|
||||
const key = nameKey(clean);
|
||||
if (index.order.some((other) => other !== id && nameKey(index.tabs[other].name) === key)) {
|
||||
throw new NotepadError("duplicate-name", 409);
|
||||
}
|
||||
index.tabs[id].name = clean;
|
||||
commit(dir, index);
|
||||
return { id, name: clean };
|
||||
});
|
||||
}
|
||||
|
||||
/** Remember which tab was open last. */
|
||||
export function setLastTab(folder, id) {
|
||||
requireTab(folder, id);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
if (!Object.hasOwn(index.tabs, id)) throw new NotepadError("no-such-tab", 404);
|
||||
if (index.last !== id) {
|
||||
index.last = id;
|
||||
commit(dir, index);
|
||||
}
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
const sameIds = (order, ids) =>
|
||||
Array.isArray(order) &&
|
||||
order.length === ids.length &&
|
||||
new Set(order).size === order.length &&
|
||||
order.every((id) => typeof id === "string" && ids.includes(id));
|
||||
|
||||
/** Put the tabs in a new order: the list must hold every current id exactly once. */
|
||||
export function reorderTabs(folder, order) {
|
||||
if (!sameIds(order, listTabs(folder).tabs.map((t) => t.id))) throw new NotepadError("bad", 400);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
if (!sameIds(order, index.order)) throw new NotepadError("bad", 400);
|
||||
index.order = [...order];
|
||||
commit(dir, index);
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/** Delete a tab, its note and its pictures: the index first, then the folder. */
|
||||
export function deleteTab(folder, id) {
|
||||
requireTab(folder, id);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
if (!Object.hasOwn(index.tabs, id)) throw new NotepadError("no-such-tab", 404);
|
||||
const at = index.order.indexOf(id);
|
||||
index.order.splice(at, 1);
|
||||
delete index.tabs[id];
|
||||
if (index.last === id) index.last = index.order[at] ?? index.order[at - 1] ?? null;
|
||||
writeIndex(dir, index);
|
||||
fs.rmSync(path.join(dir, "tabs", id), { recursive: true, force: true });
|
||||
sweepOrphanTabs(dir, index);
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ text, pictures */
|
||||
|
||||
const isJpeg = (buf) => Buffer.isBuffer(buf) && buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
||||
const isImageId = (id) => typeof id === "string" && IMAGE_ID_RE.test(id);
|
||||
|
||||
/** Replace the note's text. Resolves to `{ savedAt }`, the written file's time. */
|
||||
export function saveNote(folder, text) {
|
||||
// Inside the lock the tab must be one the (possibly just migrated) index has.
|
||||
function inTab(tab, index, dir) {
|
||||
if (!Object.hasOwn(index.tabs, tab)) throw new NotepadError("no-such-tab", 404);
|
||||
return path.join(dir, "tabs", tab);
|
||||
}
|
||||
|
||||
/** Replace a tab's text. Resolves to `{ savedAt }`, the written file's time. */
|
||||
export function saveNote(folder, tab, text) {
|
||||
if (typeof text !== "string") throw new NotepadError("bad", 400);
|
||||
if (Buffer.byteLength(text, "utf8") > NOTE_MAX_BYTES) throw new NotepadError("too-long", 413);
|
||||
return withNotepad(folder, (dir) => {
|
||||
const note = path.join(dir, "note.md");
|
||||
requireTab(folder, tab);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
const note = path.join(inTab(tab, index, dir), "note.md");
|
||||
writeTextAtomic(note, text);
|
||||
return { savedAt: new Date(fs.statSync(note).mtimeMs).toISOString() };
|
||||
});
|
||||
}
|
||||
|
||||
/** Add a picture (JPEG bytes). Resolves to `{ id, url }`. */
|
||||
export function addImage(folder, buf) {
|
||||
/** Add a picture (JPEG bytes) to a tab. Resolves to `{ id, url }`. */
|
||||
export function addImage(folder, tab, buf) {
|
||||
if (!isJpeg(buf)) throw new NotepadError("not-jpeg", 415);
|
||||
return withNotepad(folder, (dir) => {
|
||||
if (imageIds(dir).length >= NOTEPAD_MAX_IMAGES) throw new NotepadError("too-many", 409);
|
||||
requireTab(folder, tab);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
const images = path.join(inTab(tab, index, dir), "images");
|
||||
if (imageEntries([images]).length >= NOTEPAD_MAX_IMAGES) throw new NotepadError("too-many", 409);
|
||||
const id = crypto.randomUUID();
|
||||
fs.writeFileSync(path.join(dir, "images", id + ".jpg"), buf, { flag: "wx" });
|
||||
return { id, url: "/notepad/images/" + id + ".jpg" };
|
||||
ensureDir(images);
|
||||
fs.writeFileSync(path.join(images, id + ".jpg"), buf, { flag: "wx" });
|
||||
return { id, url: imageUrl(tab, id, false) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Set (or replace) a picture's thumbnail. */
|
||||
export function addThumb(folder, id, buf) {
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "images", id + ".jpg"))) {
|
||||
export function addThumb(folder, tab, id, buf) {
|
||||
requireTab(folder, tab);
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "tabs", tab, "images", id + ".jpg"))) {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
if (!isJpeg(buf)) throw new NotepadError("not-jpeg", 415);
|
||||
return withNotepad(folder, (dir) => {
|
||||
if (!fs.existsSync(path.join(dir, "images", id + ".jpg"))) throw new NotepadError("not-found", 404);
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
const images = path.join(inTab(tab, index, dir), "images");
|
||||
if (!fs.existsSync(path.join(images, id + ".jpg"))) throw new NotepadError("not-found", 404);
|
||||
// Replacing a file is the rename Windows can refuse for a moment, so it
|
||||
// takes the retrying write (a Buffer is written as is).
|
||||
writeTextAtomic(path.join(dir, "images", id + ".thumb.jpg"), buf);
|
||||
writeTextAtomic(path.join(images, id + ".thumb.jpg"), buf);
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/** Remove a picture and its thumbnail. */
|
||||
export function removeImage(folder, id) {
|
||||
export function removeImage(folder, tab, id) {
|
||||
requireTab(folder, tab);
|
||||
// Checked before the lock too, so a refused delete never brings an empty
|
||||
// notepad into being.
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "images", id + ".jpg"))) {
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "tabs", tab, "images", id + ".jpg"))) {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
return withNotepad(folder, (dir) => {
|
||||
const full = path.join(dir, "images", id + ".jpg");
|
||||
return withNotepad(folder, (dir, index) => {
|
||||
const images = path.join(inTab(tab, index, dir), "images");
|
||||
const full = path.join(images, id + ".jpg");
|
||||
if (!fs.existsSync(full)) throw new NotepadError("not-found", 404);
|
||||
fs.rmSync(full, { force: true });
|
||||
fs.rmSync(path.join(dir, "images", id + ".thumb.jpg"), { force: true });
|
||||
fs.rmSync(path.join(images, id + ".thumb.jpg"), { force: true });
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The file behind `/notepad/images/<id>[.thumb].jpg`, or null: the id must be
|
||||
* a UUID, the file a regular file (never a link) whose real path sits inside
|
||||
* the notepads folder's.
|
||||
* The file behind `/notepad/images/<tab>/<id>[.thumb].jpg`, or null: the tab
|
||||
* must be one this notepad has, the id a UUID, the file a regular file (never
|
||||
* a link) whose real path sits inside the notepads folder's. A notepad still
|
||||
* in the first shape also serves its top-level pictures as the Notes tab's.
|
||||
*/
|
||||
export function imagePath(folder, id, thumb) {
|
||||
export function imagePath(folder, tab, id, thumb) {
|
||||
if (!isImageId(id)) return null;
|
||||
const file = path.join(notepadFolder(folder), "images", id + (thumb ? ".thumb.jpg" : ".jpg"));
|
||||
try {
|
||||
if (!fs.lstatSync(file).isFile()) return null;
|
||||
const [realFile, realRoot] = [fs.realpathSync(file), fs.realpathSync(notepadsDir())];
|
||||
// path.relative, not a prefix test, as readOverview() in sessions.mjs does.
|
||||
const rel = path.relative(realRoot, realFile);
|
||||
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) return null;
|
||||
return realFile;
|
||||
} catch {
|
||||
return null;
|
||||
const dir = notepadFolder(folder);
|
||||
if (!knownTab(dir, tab)) return null;
|
||||
const name = id + (thumb ? ".thumb.jpg" : ".jpg");
|
||||
const candidates = [path.join(dir, "tabs", tab, "images", name)];
|
||||
if (tab === LEGACY_TAB_ID && legacyShape(dir)) candidates.push(path.join(dir, "images", name));
|
||||
for (const file of candidates) {
|
||||
try {
|
||||
if (!fs.lstatSync(file).isFile()) continue;
|
||||
const [realFile, realRoot] = [fs.realpathSync(file), fs.realpathSync(notepadsDir())];
|
||||
// path.relative, not a prefix test, as readOverview() in sessions.mjs does.
|
||||
const rel = path.relative(realRoot, realFile);
|
||||
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) continue;
|
||||
return realFile;
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- cleanup */
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
<link rel="modulepreload" href="/pr-url.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
<link rel="modulepreload" href="/notepad.js" />
|
||||
<link rel="modulepreload" href="/vendor/overtype.esm.js" />
|
||||
<link rel="modulepreload" href="/notepad-tabs.js" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/favicon.png" />
|
||||
</head>
|
||||
@@ -214,16 +214,16 @@
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
<!-- Notepad: every screen, never hidden. The person's private notes for this
|
||||
<!-- Notebook: every screen, never hidden. The person's private notes for this
|
||||
folder; nothing in it reaches the agent. -->
|
||||
<button type="button" class="btn ghost small notepad-btn" id="btn-notepad" title="Notepad" aria-label="Notepad">
|
||||
<button type="button" class="btn ghost small notepad-btn" id="btn-notepad" title="Notebook" aria-label="Notebook">
|
||||
<!-- A pocket notebook: a closed cover with a spine line and an elastic band. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<rect class="np-page" x="3.5" y="1.8" width="9" height="12.4" rx="1.3" />
|
||||
<path class="np-line" d="M10.2 1.8v12.4" />
|
||||
<rect class="np-band" x="9.4" y="6.5" width="1.6" height="3" rx=".5" />
|
||||
</svg>
|
||||
<span class="notepad-label">Notepad</span>
|
||||
<span class="notepad-label">Notebook</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
@@ -1174,40 +1174,59 @@
|
||||
right. See "Sending and what happens next".
|
||||
</li>
|
||||
</ul>
|
||||
<h4>Your notepad</h4>
|
||||
<h4>Your notebook</h4>
|
||||
<p>
|
||||
The <strong>Notepad</strong> button, a small notebook with an elastic
|
||||
band, sits beside Stop session on every screen. It opens a notepad of
|
||||
The <strong>Notebook</strong> button, a small notebook with an elastic
|
||||
band, sits beside Stop session on every screen. It opens a notebook of
|
||||
your own for this folder, somewhere to jot things down as you go.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
A notebook is a row of <strong>tabs</strong>, each with its own text
|
||||
and its own pictures. <strong>+ New tab</strong> asks for a name
|
||||
first. Notes you made before tabs existed show up as a tab called
|
||||
Notes.
|
||||
</li>
|
||||
<li>
|
||||
Under the row, <strong>Rename</strong> changes the current tab's
|
||||
name (double-click a tab or press <kbd>F2</kbd> works too). Drag a
|
||||
tab to reorder it, or use <strong>Move left</strong> and
|
||||
<strong>Move right</strong>, or <kbd>Alt</kbd> with the arrow keys.
|
||||
The tab you leave open is the one you come back to.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Delete</strong> asks twice before it removes a tab, and
|
||||
takes its text and its pictures with it. That cannot be undone.
|
||||
With no tabs left, you are asked to make one.
|
||||
</li>
|
||||
<li>
|
||||
Text is styled as you type. Write Markdown, such as
|
||||
<code>**bold**</code> or <code># Heading</code>, and it shows that
|
||||
way at once.
|
||||
<code>**bold**</code> or <code># Heading</code>, and headings grow
|
||||
and bullets draw in place. The marks come back on the line you are
|
||||
on.
|
||||
</li>
|
||||
<li>
|
||||
Images go in the strip under the text. Paste one, drop one on the
|
||||
notepad or press <strong>Add image</strong>. Click a picture to see
|
||||
notebook or press <strong>Add image</strong>. Click a picture to see
|
||||
it full screen: the arrow keys step through them and
|
||||
<kbd>Esc</kbd> closes it. The <strong>×</strong> on a picture asks
|
||||
before it deletes it.
|
||||
</li>
|
||||
<li>
|
||||
Everything saves as you go, one notepad per project folder. There is
|
||||
no Save button.
|
||||
Everything saves as you go, one notebook per project folder and one
|
||||
folder per tab on disk. There is no Save button.
|
||||
</li>
|
||||
<li>
|
||||
It is private to this machine and never sent to Plan2Code. Nothing
|
||||
in it is shown to the agent.
|
||||
</li>
|
||||
<li>
|
||||
Two open pages on the same folder share one notepad. If both change
|
||||
Two open pages on the same folder share one notebook. If both change
|
||||
it, the last save wins.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>, in User Preferences, offers to remove a
|
||||
notepad only after a month untouched. Nothing removes it on its own.
|
||||
notebook only after a month untouched. Nothing removes it on its own.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
@@ -1609,6 +1628,11 @@
|
||||
</p>
|
||||
<h4>Printing and saving</h4>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Back to Questions</strong> (Dashboard or Git on those
|
||||
screens) takes you back to the main flow. The row with it stays at
|
||||
the top of the tab while you scroll.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Print</strong> prints the document alone, without the rest of
|
||||
the page. Choose "Save as PDF" in the print dialog for a PDF.
|
||||
@@ -2580,18 +2604,28 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notepad: the person's own notes for this folder, autosaved under
|
||||
<!-- The Notebook: the person's own notes for this folder, autosaved under
|
||||
~/.plan2code/notepads/ by the /notepad routes. Never part of the
|
||||
session, so nothing in it reaches the agent. screens/notepad.js fills
|
||||
the editor on open. -->
|
||||
<dialog class="modal notepad" id="notepad-modal" aria-labelledby="notepad-title">
|
||||
<h2 id="notepad-title">Notepad</h2>
|
||||
<p class="modal-blurb">A private space to keep track of notes, uploaded images related to your in-progress work on this project. Saved on this machine and never shared to the AI Agent.</p>
|
||||
<div class="notepad-editor" id="notepad-editor"></div>
|
||||
<div class="notepad-images" id="notepad-images">
|
||||
<button type="button" class="btn small ghost notepad-add" id="notepad-add">Add image</button>
|
||||
<input type="file" accept="image/*" multiple id="notepad-file" hidden />
|
||||
<ul class="notepad-strip" id="notepad-strip" role="list" aria-label="Notepad images"></ul>
|
||||
<h2 id="notepad-title">Notebook</h2>
|
||||
<p class="modal-blurb">A private space to keep track of notes, uploaded images related to your in-progress work on this project. Saved on this machine and <strong class="private-note">never shared to the AI Agent</strong>.</p>
|
||||
<div class="notepad-tabbar">
|
||||
<div class="notepad-tabs" id="notepad-tabs" role="tablist" aria-label="Notebook tabs"></div>
|
||||
<button type="button" class="btn small ghost notepad-tab-new" id="notepad-tab-new">+ New tab</button>
|
||||
</div>
|
||||
<div class="notepad-empty" id="notepad-empty" hidden>
|
||||
<p>No tabs yet. Make one to start writing.</p>
|
||||
<button type="button" class="btn small primary" id="notepad-empty-new">+ New tab</button>
|
||||
</div>
|
||||
<div class="notepad-body" id="notepad-body">
|
||||
<div class="notepad-editor" id="notepad-editor"></div>
|
||||
<div class="notepad-images" id="notepad-images">
|
||||
<button type="button" class="btn small ghost notepad-add" id="notepad-add">Add image</button>
|
||||
<input type="file" accept="image/*" multiple id="notepad-file" hidden />
|
||||
<ul class="notepad-strip" id="notepad-strip" role="list" aria-label="Notebook images"></ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-actions notepad-actions">
|
||||
<p class="help notepad-status" id="notepad-status" aria-live="polite"></p>
|
||||
@@ -2599,7 +2633,31 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notepad's full-screen picture preview, opened over the Notepad
|
||||
<!-- The Notebook's name and delete questions: small dialogs over the Notebook.
|
||||
A tab's double-click (or F2) opens the name one for Rename, + New tab
|
||||
opens it for a new name, and a tab's x opens the delete one, which asks twice. -->
|
||||
<dialog class="modal notepad-sub" id="notepad-name-dlg" aria-labelledby="notepad-name-label">
|
||||
<form class="notepad-name-form" id="notepad-name-form" novalidate>
|
||||
<h2 id="notepad-name-label">Name this tab</h2>
|
||||
<input type="text" id="notepad-name" autocomplete="off" spellcheck="false" aria-describedby="notepad-name-error" />
|
||||
<p class="help notepad-name-error" id="notepad-name-error" aria-live="polite"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="notepad-name-cancel">Cancel</button>
|
||||
<button type="submit" class="btn primary" id="notepad-name-save">Save</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<dialog class="modal notepad-sub notepad-delete" id="notepad-delete" aria-labelledby="notepad-delete-title" aria-describedby="notepad-delete-text">
|
||||
<h2 id="notepad-delete-title">Delete this tab?</h2>
|
||||
<p id="notepad-delete-text"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="notepad-delete-keep">Keep tab</button>
|
||||
<button type="button" class="btn danger" id="notepad-delete-go">Delete tab…</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notebook's full-screen picture preview, opened over the Notebook
|
||||
from a thumbnail by screens/notepad.js. -->
|
||||
<dialog class="modal notepad-preview" id="notepad-preview" aria-label="Image preview">
|
||||
<img class="notepad-preview-img" id="notepad-preview-img" alt="" />
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/* The live-preview editor (notepad-editor.js, CodeMirror 6) lives in a shadow
|
||||
root, because CodeMirror writes its own rules as a <style> element, which the
|
||||
page's policy (`style-src 'self'`) refuses; inside a shadow root it adopts them as a
|
||||
constructed stylesheet instead, which the policy allows. This file is that
|
||||
shadow root's one stylesheet (a <link> to it, served from the allow-list),
|
||||
so the page's own CSS does not reach in: the console's tokens do, since custom
|
||||
properties inherit across the boundary, and one block covers both themes.
|
||||
Classes only: inline styles are refused too. */
|
||||
:host { display: block; height: 100%; }
|
||||
.notepad-cm { height: 100%; }
|
||||
.cm-editor { height: 100%; background: var(--panel); color: var(--ink); font-family: var(--sans); font-size: 15px; }
|
||||
div.cm-editor.cm-focused { outline: none; }
|
||||
div.cm-editor .cm-scroller { overflow: auto; line-height: 1.6; font-family: inherit; }
|
||||
div.cm-editor .cm-content { padding: 16px; caret-color: var(--accent); }
|
||||
div.cm-editor .cm-cursor { border-left-color: var(--accent); }
|
||||
div.cm-editor .cm-selectionBackground,
|
||||
div.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground { background: color-mix(in srgb, var(--accent) 25%, transparent) !important; }
|
||||
/* Any rule below that pads a line (headings, quotes) is written `div.cm-editor`
|
||||
too: at one class it would lose to this one. */
|
||||
div.cm-editor .cm-line { padding: 0 2px; }
|
||||
.cm-h1,
|
||||
.cm-h2,
|
||||
.cm-h3,
|
||||
.cm-h4,
|
||||
.cm-h5,
|
||||
.cm-h6 { font-weight: 700; color: var(--accent); line-height: 1.3; }
|
||||
div.cm-editor .cm-h1 { font-size: 1.8em; padding-top: 0.3em; }
|
||||
div.cm-editor .cm-h2 { font-size: 1.45em; padding-top: 0.25em; }
|
||||
.cm-h3 { font-size: 1.2em; }
|
||||
.cm-h4 { font-size: 1.05em; }
|
||||
.cm-h5,
|
||||
.cm-h6 { font-size: 1em; color: var(--ink-2); }
|
||||
.cm-strong { font-weight: 700; }
|
||||
.cm-em { font-style: italic; }
|
||||
.cm-strike { text-decoration: line-through; color: var(--ink-3); }
|
||||
.cm-link { color: var(--accent); text-decoration: underline; }
|
||||
.cm-code { font-family: var(--mono); font-size: 0.92em; background: color-mix(in srgb, var(--rule) 70%, transparent); border-radius: 4px; padding: 0 3px; }
|
||||
.cm-codeblock { font-family: var(--mono); font-size: 0.92em; background: color-mix(in srgb, var(--rule) 55%, transparent); }
|
||||
.cm-fence { color: var(--ink-3); }
|
||||
div.cm-editor .cm-quote { color: var(--ink-2); border-left: 3px solid var(--accent-line); padding-left: 10px; }
|
||||
.cm-hr { color: var(--ink-3); border-bottom: 1px solid var(--rule-2); }
|
||||
.cm-bullet { color: var(--accent); font-weight: 700; display: inline-block; width: 1em; text-align: center; }
|
||||
@@ -0,0 +1,234 @@
|
||||
// Plan2Code Web Console - the Notebook's live-preview editor, on CodeMirror 6.
|
||||
//
|
||||
// Markdown stays the stored format. The editor shows it formatted where it is
|
||||
// typed: headings grow, bullets become dots, the marks around bold, links and
|
||||
// quotes hide, and every mark comes back on the line the cursor is on. Only
|
||||
// the visible lines are decorated, so typing in a 200 KB note costs about what
|
||||
// it does in a short one. CodeMirror itself ships as one vendored file
|
||||
// (vendor/codemirror.esm.js, made by scripts/vendor-codemirror.mjs); every
|
||||
// look here is a class styled by notepad.css, never an inline style, because
|
||||
// the page's policy (`style-src 'self'`) refuses those. CodeMirror's own rules
|
||||
// are a <style> element too, so the editor sits in a shadow root, where they
|
||||
// are adopted as a constructed stylesheet instead; notepad-editor.css is that
|
||||
// root's one stylesheet.
|
||||
//
|
||||
// The editor is an object with four methods, plus destroy(), so
|
||||
// screens/notepad.js does not care which editor is behind it: getValue(),
|
||||
// setValue(text), setReadOnly(on) and focus(). setValue() is not reported
|
||||
// through onChange, and clears the undo history (it is a different note, not
|
||||
// an edit). Line endings: CodeMirror reads CRLF as LF, so a note stored with
|
||||
// CRLF is saved back with LF on its first edit (OverType's textarea did too).
|
||||
|
||||
import {
|
||||
Compartment,
|
||||
Decoration,
|
||||
EditorState,
|
||||
EditorView,
|
||||
ViewPlugin,
|
||||
WidgetType,
|
||||
defaultKeymap,
|
||||
history,
|
||||
historyKeymap,
|
||||
keymap,
|
||||
markdown,
|
||||
markdownLanguage,
|
||||
redo,
|
||||
syntaxTree,
|
||||
} from "./vendor/codemirror.esm.js";
|
||||
|
||||
// A bullet drawn in place of "-", "*" or "+" on a line the cursor is not on.
|
||||
class BulletWidget extends WidgetType {
|
||||
eq(other) {
|
||||
return other instanceof BulletWidget;
|
||||
}
|
||||
toDOM() {
|
||||
const dot = document.createElement("span");
|
||||
dot.className = "cm-bullet";
|
||||
dot.textContent = "•";
|
||||
return dot;
|
||||
}
|
||||
ignoreEvent() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const HIDE = Decoration.replace({});
|
||||
const BULLET = Decoration.replace({ widget: new BulletWidget() });
|
||||
const lineClass = (name) => Decoration.line({ class: name });
|
||||
const markClass = (name) => Decoration.mark({ class: name });
|
||||
|
||||
// A selection across more lines than this shows every mark, rather than
|
||||
// working out which lines are inside it.
|
||||
const MAX_ACTIVE_LINES = 400;
|
||||
|
||||
// The line numbers the selection touches: their marks stay visible so the
|
||||
// person sees and edits the Markdown there. null means all of them.
|
||||
function activeLines(state) {
|
||||
const lines = new Set();
|
||||
for (const range of state.selection.ranges) {
|
||||
const first = state.doc.lineAt(range.from).number;
|
||||
const last = state.doc.lineAt(range.to).number;
|
||||
if (last - first > MAX_ACTIVE_LINES) return null;
|
||||
for (let n = first; n <= last; n++) lines.add(n);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
// The decorations for the lines in view, from the Markdown syntax tree.
|
||||
function build(view) {
|
||||
const { state } = view;
|
||||
const { doc } = state;
|
||||
const active = activeLines(state);
|
||||
const out = [];
|
||||
const from = view.viewport.from;
|
||||
const to = view.viewport.to;
|
||||
|
||||
const onActiveLine = (pos) => active === null || active.has(doc.lineAt(pos).number);
|
||||
// A hidden range never runs past the end of its line: CodeMirror refuses a
|
||||
// replace decoration that covers a line break when a plugin makes it, and a
|
||||
// link can span lines ("[a](\nhttps://x)").
|
||||
const hide = (a, b) => {
|
||||
const end = Math.min(b, doc.lineAt(a).to);
|
||||
if (end > a && !onActiveLine(a)) out.push(HIDE.range(a, end));
|
||||
};
|
||||
// A mark and the single space after it ("# ", "> ", "- ").
|
||||
const hideWithSpace = (a, b) => hide(a, b < doc.length && doc.sliceString(b, b + 1) === " " ? b + 1 : b);
|
||||
const eachLine = (a, b, fn) => {
|
||||
const start = doc.lineAt(Math.max(a, from)).number;
|
||||
const end = doc.lineAt(Math.min(b, to)).number;
|
||||
for (let n = start; n <= end; n++) fn(doc.line(n));
|
||||
};
|
||||
|
||||
syntaxTree(state).iterate({
|
||||
from,
|
||||
to,
|
||||
enter(node) {
|
||||
const name = node.name;
|
||||
const heading = /^ATXHeading([1-6])$/.exec(name);
|
||||
if (heading) {
|
||||
out.push(lineClass("cm-h" + heading[1]).range(doc.lineAt(node.from).from));
|
||||
} else if (name === "HeaderMark") {
|
||||
// Only the leading "#" run of an ATX heading hides; a closing run stays.
|
||||
const parent = node.node.parent;
|
||||
if (parent && /^ATXHeading/.test(parent.name) && node.from === doc.lineAt(node.from).from) hideWithSpace(node.from, node.to);
|
||||
} else if (name === "StrongEmphasis") {
|
||||
out.push(markClass("cm-strong").range(node.from, node.to));
|
||||
} else if (name === "Emphasis") {
|
||||
out.push(markClass("cm-em").range(node.from, node.to));
|
||||
} else if (name === "Strikethrough") {
|
||||
out.push(markClass("cm-strike").range(node.from, node.to));
|
||||
} else if (name === "EmphasisMark" || name === "StrikethroughMark") {
|
||||
hide(node.from, node.to);
|
||||
} else if (name === "InlineCode") {
|
||||
out.push(markClass("cm-code").range(node.from, node.to));
|
||||
} else if (name === "CodeMark") {
|
||||
// The backticks of inline code hide; a fence's stay, dimmed.
|
||||
if (node.node.parent && node.node.parent.name === "InlineCode") hide(node.from, node.to);
|
||||
else out.push(markClass("cm-fence").range(node.from, node.to));
|
||||
} else if (name === "FencedCode") {
|
||||
eachLine(node.from, node.to, (line) => out.push(lineClass("cm-codeblock").range(line.from)));
|
||||
} else if (name === "Blockquote") {
|
||||
eachLine(node.from, node.to, (line) => out.push(lineClass("cm-quote").range(line.from)));
|
||||
} else if (name === "QuoteMark") {
|
||||
hideWithSpace(node.from, node.to);
|
||||
} else if (name === "HorizontalRule") {
|
||||
out.push(lineClass("cm-hr").range(doc.lineAt(node.from).from));
|
||||
} else if (name === "ListMark") {
|
||||
const parent = node.node.parent && node.node.parent.parent;
|
||||
const bulleted = parent && parent.name === "BulletList";
|
||||
if (bulleted && !onActiveLine(node.from)) out.push(BULLET.range(node.from, node.to));
|
||||
} else if (name === "Link") {
|
||||
out.push(markClass("cm-link").range(node.from, node.to));
|
||||
// "[text](url)": the opening "[" and everything from "](" on hide.
|
||||
const marks = [];
|
||||
for (let child = node.node.firstChild; child; child = child.nextSibling) {
|
||||
if (child.name === "LinkMark") marks.push(child);
|
||||
}
|
||||
// A link with no text ("[](u)") stays as written, or nothing would be left to click into.
|
||||
if (marks.length >= 2 && marks[0].to < marks[1].from) {
|
||||
hide(marks[0].from, marks[0].to);
|
||||
hide(marks[1].from, node.to);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
return Decoration.set(out, true);
|
||||
}
|
||||
|
||||
// Redraws on what can change the picture: the text, the selection (which
|
||||
// lines are active), the lines in view, and the parse catching up.
|
||||
const livePreview = ViewPlugin.fromClass(
|
||||
class {
|
||||
constructor(view) {
|
||||
this.decorations = build(view);
|
||||
}
|
||||
update(update) {
|
||||
if (
|
||||
update.docChanged ||
|
||||
update.selectionSet ||
|
||||
update.viewportChanged ||
|
||||
syntaxTree(update.state) !== syntaxTree(update.startState)
|
||||
) {
|
||||
this.decorations = build(update.view);
|
||||
}
|
||||
}
|
||||
},
|
||||
{ decorations: (plugin) => plugin.decorations },
|
||||
);
|
||||
|
||||
/**
|
||||
* Make the editor inside `parent`. `onChange(text)` is called with the whole
|
||||
* text after each edit the person makes; `label` is the screen-reader name.
|
||||
*/
|
||||
export function makeCodeMirrorEditor(parent, { onChange, label }) {
|
||||
// Read-only until the note has been read in, so nothing typed into the empty
|
||||
// editor is saved over the real note. Only the state is read-only, never
|
||||
// `editable`: a non-editable content element cannot take the focus, and the
|
||||
// person would find it gone when the note loads.
|
||||
let readOnly = false;
|
||||
const access = new Compartment();
|
||||
const accessOf = (on) => (on ? [EditorState.readOnly.of(true), EditorView.contentAttributes.of({ "aria-readonly": "true" })] : []);
|
||||
const extensions = [
|
||||
history(),
|
||||
// Ctrl+Shift+Z redoes on every platform (the history keymap binds it on Linux and Mac only).
|
||||
keymap.of([{ key: "Mod-Shift-z", run: redo, preventDefault: true }, ...defaultKeymap, ...historyKeymap]),
|
||||
markdown({ base: markdownLanguage }),
|
||||
livePreview,
|
||||
EditorView.lineWrapping,
|
||||
EditorView.contentAttributes.of({ "aria-label": label || "Notebook text", "aria-multiline": "true" }),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged && onChange) onChange(update.state.doc.toString());
|
||||
}),
|
||||
];
|
||||
const stateOf = (text) => EditorState.create({ doc: text, extensions: [...extensions, access.of(accessOf(readOnly))] });
|
||||
const host = document.createElement("div");
|
||||
host.className = "notepad-cm-host";
|
||||
parent.appendChild(host);
|
||||
const root = host.attachShadow({ mode: "open" });
|
||||
const sheet = document.createElement("link");
|
||||
sheet.rel = "stylesheet";
|
||||
sheet.href = "/notepad-editor.css";
|
||||
const mount = document.createElement("div");
|
||||
mount.className = "notepad-cm";
|
||||
root.append(sheet, mount);
|
||||
const view = new EditorView({ state: stateOf(""), parent: mount, root });
|
||||
// The stylesheet arrives after the first measure: measure again once it has,
|
||||
// or heading heights would stay at their unstyled size until the next edit.
|
||||
sheet.addEventListener("load", () => view.requestMeasure());
|
||||
return {
|
||||
getValue: () => view.state.doc.toString(),
|
||||
setValue(text) {
|
||||
// setState neither reports a change nor keeps the old note's undo steps.
|
||||
view.setState(stateOf(String(text)));
|
||||
},
|
||||
setReadOnly(on) {
|
||||
readOnly = Boolean(on);
|
||||
view.dispatch({ effects: access.reconfigure(accessOf(readOnly)) });
|
||||
},
|
||||
focus: () => view.focus(),
|
||||
destroy() {
|
||||
view.destroy();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Plan2Code Web Console - the Notebook's tab bar.
|
||||
//
|
||||
// Draws #notepad-tabs from a list of { id, name } and tells screens/notepad.js
|
||||
// what the person did: pick a tab (onSwitch), reorder with a drag, ask to
|
||||
// rename (a double-click or F2) or ask to delete (the x beside the name, or the
|
||||
// Delete key) (onChange). No fetches here: the screen owns every request, and
|
||||
// notepad.js owns the rules for order.
|
||||
|
||||
import { dropTab } from "./notepad.js";
|
||||
import { el } from "./render.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const DRAG_TYPE = "application/x-plan2code-notepad-tab";
|
||||
|
||||
/**
|
||||
* `onSwitch(id)` runs when a tab is picked. `onChange(event)` runs for
|
||||
* `{ type: "order", order, focus }` (a new order to save, focus the moved tab
|
||||
* afterwards), `{ type: "rename", id }` and `{ type: "delete", id }`.
|
||||
*/
|
||||
export function createTabs({ onSwitch, onChange }) {
|
||||
const bar = $("notepad-tabs");
|
||||
let tabs = [];
|
||||
let activeId = null;
|
||||
// The tab being dragged, so only a tab drag lights the drop marks: a picture
|
||||
// or text dragged over the bar does nothing.
|
||||
let dragging = null;
|
||||
|
||||
// The tab buttons; each sits in a wrapper with its x.
|
||||
const buttons = () => Array.from(bar.querySelectorAll(".notepad-tab"));
|
||||
const buttonFor = (id) => buttons().find((b) => b.dataset.id === id) || null;
|
||||
const ids = () => tabs.map((t) => t.id);
|
||||
|
||||
function clearMarks() {
|
||||
for (const b of buttons()) b.classList.remove("is-drop-before", "is-dragging");
|
||||
bar.classList.remove("is-drop-end");
|
||||
}
|
||||
|
||||
function reorder(order, focus) {
|
||||
if (order.join() === ids().join()) return;
|
||||
onChange({ type: "order", order, focus });
|
||||
}
|
||||
|
||||
function onKey(e, id) {
|
||||
const left = e.key === "ArrowLeft";
|
||||
if (left || e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
const list = buttons();
|
||||
const at = list.findIndex((b) => b.dataset.id === id);
|
||||
const next = list[Math.max(0, Math.min(list.length - 1, at + (left ? -1 : 1)))];
|
||||
if (next) next.focus();
|
||||
} else if (e.key === "Home" || e.key === "End") {
|
||||
e.preventDefault();
|
||||
const list = buttons();
|
||||
(e.key === "Home" ? list[0] : list[list.length - 1])?.focus();
|
||||
} else if (e.key === "F2") {
|
||||
e.preventDefault();
|
||||
onChange({ type: "rename", id });
|
||||
} else if (e.key === "Delete") {
|
||||
e.preventDefault();
|
||||
onChange({ type: "delete", id });
|
||||
}
|
||||
}
|
||||
|
||||
function tabButton(tab) {
|
||||
const active = tab.id === activeId;
|
||||
const b = el("button", "notepad-tab", tab.name);
|
||||
b.type = "button";
|
||||
b.id = "notepad-tab-" + tab.id;
|
||||
b.dataset.id = tab.id;
|
||||
b.title = tab.name;
|
||||
b.setAttribute("role", "tab");
|
||||
b.setAttribute("aria-selected", active ? "true" : "false");
|
||||
b.tabIndex = active ? 0 : -1;
|
||||
b.draggable = true;
|
||||
b.addEventListener("click", () => onSwitch(tab.id));
|
||||
b.addEventListener("dblclick", () => onChange({ type: "rename", id: tab.id }));
|
||||
b.addEventListener("keydown", (e) => onKey(e, tab.id));
|
||||
b.addEventListener("dragstart", (e) => {
|
||||
dragging = tab.id;
|
||||
e.dataTransfer.setData(DRAG_TYPE, tab.id);
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
b.classList.add("is-dragging");
|
||||
});
|
||||
b.addEventListener("dragend", () => {
|
||||
dragging = null;
|
||||
clearMarks();
|
||||
});
|
||||
// The x is a button of its own beside the name, so the tab's text stays
|
||||
// its name and a double-click or a drag on the name never reaches it.
|
||||
const x = el("button", "notepad-tab-x", "×");
|
||||
x.type = "button";
|
||||
x.setAttribute("aria-label", "Delete " + tab.name);
|
||||
x.title = "Delete tab";
|
||||
x.tabIndex = active ? 0 : -1;
|
||||
x.addEventListener("click", () => onChange({ type: "delete", id: tab.id }));
|
||||
const wrap = el("div", "notepad-tabwrap");
|
||||
wrap.setAttribute("role", "presentation");
|
||||
wrap.append(b, x);
|
||||
wrap.addEventListener("dragover", (e) => {
|
||||
if (dragging === null) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "move";
|
||||
clearMarks();
|
||||
if (tab.id !== dragging) b.classList.add("is-drop-before");
|
||||
});
|
||||
wrap.addEventListener("drop", (e) => {
|
||||
if (dragging === null) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const id = dragging;
|
||||
dragging = null;
|
||||
clearMarks();
|
||||
reorder(dropTab(ids(), id, tab.id), id);
|
||||
});
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Dropping on the empty part of the bar moves the tab to the end.
|
||||
bar.addEventListener("dragover", (e) => {
|
||||
if (dragging === null || e.target !== bar) return;
|
||||
e.preventDefault();
|
||||
clearMarks();
|
||||
bar.classList.add("is-drop-end");
|
||||
});
|
||||
bar.addEventListener("drop", (e) => {
|
||||
if (dragging === null || e.target !== bar) return;
|
||||
e.preventDefault();
|
||||
const id = dragging;
|
||||
dragging = null;
|
||||
clearMarks();
|
||||
reorder(dropTab(ids(), id, null), id);
|
||||
});
|
||||
|
||||
return {
|
||||
// Rebuilds the bar. Focus stays on the same tab across the redraw.
|
||||
draw(list, active) {
|
||||
const had = document.activeElement;
|
||||
const focusId = had && bar.contains(had) && had.dataset ? had.dataset.id : null;
|
||||
tabs = Array.isArray(list) ? list : [];
|
||||
activeId = tabs.some((t) => t.id === active) ? active : null;
|
||||
bar.replaceChildren(...tabs.map(tabButton));
|
||||
// With no current tab one still needs to be reachable by Tab.
|
||||
if (activeId === null && tabs.length) buttons()[0].tabIndex = 0;
|
||||
if (focusId) buttonFor(focusId)?.focus();
|
||||
const empty = tabs.length === 0;
|
||||
$("notepad-empty").hidden = !empty;
|
||||
$("notepad-body").hidden = empty;
|
||||
// A long row scrolls the current tab into view.
|
||||
buttonFor(activeId)?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
|
||||
},
|
||||
focusTab(id) {
|
||||
buttonFor(id)?.focus();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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 */
|
||||
|
||||
@@ -27,9 +27,9 @@ const CLEANUP_WHERE = { root: "~/.plan2code/", console: "~/.plan2code/console/",
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
// One notepad is one item, named by the folder it belongs to; its key only
|
||||
// One notebook is one item, named by the folder it belongs to; its key only
|
||||
// when its meta.json is gone.
|
||||
if (item.where === "notepad") return "Notepad for " + (item.folder || item.name);
|
||||
if (item.where === "notepad") return "Notebook for " + (item.folder || item.name);
|
||||
return CLEANUP_WHERE[item.where] + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ function cleanupSummary(items, bytes) {
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (completed) parts.push(completed + (completed === 1 ? " old completed spec" : " old completed specs"));
|
||||
if (notepads) parts.push(notepads + (notepads === 1 ? " old notepad" : " old notepads"));
|
||||
if (notepads) parts.push(notepads + (notepads === 1 ? " old notebook" : " old notebooks"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
@@ -132,6 +132,7 @@ export function renderDoc(main, id) {
|
||||
}
|
||||
|
||||
const tools = el("div", "doc-tools");
|
||||
tools.appendChild(backButton());
|
||||
// A brief is handed to people who were not in the room, so it gets a copy
|
||||
// that opens in any browser, formatting and all.
|
||||
if (doc.id === "brief") {
|
||||
@@ -193,6 +194,22 @@ export function renderDoc(main, id) {
|
||||
});
|
||||
}
|
||||
|
||||
// The way home from a document, in the highlight color so it is the easiest
|
||||
// thing to find after reading. A finished session's first tab is its finish
|
||||
// screen, the same as the tab itself.
|
||||
function backButton() {
|
||||
const flow = page.S.workflow;
|
||||
const home = flow === "dashboard" ? "Dashboard" : flow === "git" ? "Git" : "Questions";
|
||||
const back = el("button", "btn small back-home", "Back to " + home);
|
||||
back.type = "button";
|
||||
back.addEventListener("click", () => {
|
||||
page.view = finish() ? "end" : "questions";
|
||||
redraw();
|
||||
$("main").focus();
|
||||
});
|
||||
return back;
|
||||
}
|
||||
|
||||
function printButton() {
|
||||
const print = el("button", "btn small", "Print");
|
||||
print.type = "button";
|
||||
@@ -209,6 +226,7 @@ export function renderOverview(main) {
|
||||
const head = el("div", "doc-head");
|
||||
head.appendChild(el("h2", null, "Overview"));
|
||||
const tools = el("div", "doc-tools");
|
||||
tools.appendChild(backButton());
|
||||
tools.appendChild(printButton());
|
||||
head.appendChild(tools);
|
||||
main.appendChild(head);
|
||||
|
||||
@@ -1,80 +1,105 @@
|
||||
// Plan2Code Web Console - the Notepad: the top bar's icon, its dialog, the editor and autosave.
|
||||
// Plan2Code Web Console - the Notebook: the top bar's icon, its dialog, the tabs, the editor and autosave.
|
||||
//
|
||||
// The person's own notes for the folder this session runs in, kept by the
|
||||
// server under ~/.plan2code/notepads/ through the /notepad routes, never in
|
||||
// the session, so nothing typed here reaches the agent. The editor is the
|
||||
// vendored OverType, which styles Markdown in place over a real textarea. Its
|
||||
// CSS ships in styles/notepad.css, because the page's policy blocks the
|
||||
// <style> OverType would inject. When to save and what the status line says
|
||||
// are notepad.js's pure rules; this file only runs the timers and requests.
|
||||
// the session, so nothing typed here reaches the agent. A notepad is a row of
|
||||
// tabs, each its own note with its own pictures; one tab is on screen. The
|
||||
// editor is CodeMirror (notepad-editor.js), loaded the first time the Notebook
|
||||
// opens. When to save, what the status line says, the tab name rules and the
|
||||
// order moves are notepad.js's pure rules; the bar itself is notepad-tabs.js;
|
||||
// this file runs the timers and requests, and binds every save and every
|
||||
// picture to the tab it was made in, so a switch can never move either.
|
||||
|
||||
import { page } from "../state.js";
|
||||
import {
|
||||
EDITOR_NOT_LOADED,
|
||||
IMAGE_ID_RE,
|
||||
NOTEPAD_MAX_IMAGES,
|
||||
NOT_LOADED,
|
||||
SAVE_START,
|
||||
changedRange,
|
||||
TAB_ID_RE,
|
||||
cleanTabName,
|
||||
errorSentence,
|
||||
keepsText,
|
||||
nextDelete,
|
||||
nextSave,
|
||||
noteBytes,
|
||||
saveStatus,
|
||||
step,
|
||||
topLevelParts,
|
||||
tabNameProblem,
|
||||
tabSwitch,
|
||||
unsaved,
|
||||
withoutStyleAttrs,
|
||||
} from "../notepad.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { reencode } from "../uploads.js";
|
||||
import { OverType } from "../vendor/overtype.esm.js";
|
||||
import { createTabs } from "../notepad-tabs.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const NOT_CONNECTED = "Not connected right now.";
|
||||
const STAY = "Not saved yet, so staying on this tab.";
|
||||
|
||||
// One editor for the page's life, made on first open.
|
||||
// One editor for the page's life, made on first open, and the tab bar, made
|
||||
// when the page is wired.
|
||||
let editor = null;
|
||||
let tabBar = null;
|
||||
|
||||
// The page's view of the notepad: the tabs in order, and the one on screen
|
||||
// (null when there are none).
|
||||
let tabs = [];
|
||||
let activeId = null;
|
||||
|
||||
// The save state (notepad.js), the one timer it arms, and the request in
|
||||
// flight. `rev` counts changes, so an answer to an older text never marks a
|
||||
// newer one saved.
|
||||
// newer one saved. `saveTab` is the tab the unsaved text belongs to, fixed
|
||||
// when the change is made, never read when it is sent.
|
||||
let save = SAVE_START;
|
||||
let timer = null;
|
||||
let sending = false;
|
||||
let rev = 0;
|
||||
let problem = "";
|
||||
let saveTab = null;
|
||||
|
||||
// True while the page itself sets the editor's text: OverType reports that as
|
||||
// a change, and it is not the person typing.
|
||||
// True while the page itself sets the editor's text: the editor may report
|
||||
// that as a change, and it is not the person typing.
|
||||
let loading = false;
|
||||
|
||||
// Whether the note has been read into the editor yet. Until it has, the
|
||||
// editor is read-only: text typed into the empty editor would be saved over
|
||||
// the real note.
|
||||
// Whether a note has been read into the editor yet. Until it has, the editor
|
||||
// is read-only: text typed into the empty editor would be saved over the real
|
||||
// note.
|
||||
let loaded = false;
|
||||
|
||||
// While a create, a rename or a delete is out, the controls do nothing.
|
||||
let busy = false;
|
||||
|
||||
// What the one name form is open for ("new" or "rename"), or null; and the
|
||||
// two-confirm delete's stage ("none", "ask" or "sure": notepad.js nextDelete).
|
||||
let naming = null;
|
||||
let stage = "none";
|
||||
|
||||
// Drawn from the render pass beside Stop: always shown, unusable while the
|
||||
// server is gone (nothing could load or save).
|
||||
export function renderNotepadButton() {
|
||||
const btn = $("btn-notepad");
|
||||
btn.disabled = Boolean(page.gone);
|
||||
btn.title = page.gone ? NOT_CONNECTED : "Notepad";
|
||||
btn.title = page.gone ? NOT_CONNECTED : "Notebook";
|
||||
}
|
||||
|
||||
// The last thing a picture went wrong with, said after the save words until
|
||||
// the next batch of pictures starts or the notepad is opened again; and the
|
||||
// picture it was about, if one, whose Retry landing clears it.
|
||||
// picture it was about, if one, whose Retry landing clears it. `info` is a
|
||||
// plain announcement (a tab moved), not styled as a problem.
|
||||
let notice = "";
|
||||
let noticeKey = null;
|
||||
let info = "";
|
||||
|
||||
function paintStatus() {
|
||||
const line = $("notepad-status");
|
||||
const words = saveStatus(save);
|
||||
const failed = save.status === "failed" || save.status === "too-long";
|
||||
const saving = save.status === "failed" && problem ? `${words}. ${problem}` : words;
|
||||
line.textContent = [saving, notice].filter(Boolean).join(" ");
|
||||
line.textContent = [saving, notice, info].filter(Boolean).join(" ");
|
||||
line.classList.toggle("is-problem", failed || Boolean(notice));
|
||||
}
|
||||
|
||||
@@ -84,6 +109,11 @@ function tell(sentence, key = null) {
|
||||
paintStatus();
|
||||
}
|
||||
|
||||
function inform(sentence) {
|
||||
info = sentence;
|
||||
paintStatus();
|
||||
}
|
||||
|
||||
function arm(ms) {
|
||||
clearTimeout(timer);
|
||||
timer = ms == null ? null : setTimeout(() => dispatch(save.status === "failed" ? "retry" : "due"), ms);
|
||||
@@ -95,34 +125,64 @@ function dispatch(event) {
|
||||
arm(next.timer);
|
||||
paintStatus();
|
||||
if (save.status === "saving") send();
|
||||
check();
|
||||
}
|
||||
|
||||
// Everyone waiting for the text to reach the disk before the tab changes.
|
||||
const waiters = [];
|
||||
|
||||
// Resolves the waiters once nothing is pending or out: true when the text is
|
||||
// safe (saved, or nothing to save), false when a save failed or cannot be made.
|
||||
function check() {
|
||||
if (!waiters.length) return;
|
||||
if (save.status === "pending") return dispatch("due");
|
||||
if (sending || save.status === "saving") return;
|
||||
const ok = !keepsText(save);
|
||||
for (const resolve of waiters.splice(0)) resolve(ok);
|
||||
}
|
||||
|
||||
// Save the tab on screen now; whether its text is on disk.
|
||||
function settled() {
|
||||
if (!tabSwitch(save)) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
waiters.push(resolve);
|
||||
flush();
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
// One save at a time. A save that comes due while another is out goes as
|
||||
// soon as that one answers.
|
||||
async function send() {
|
||||
if (sending || !editor) return;
|
||||
if (sending || !editor || !saveTab) return;
|
||||
sending = true;
|
||||
const sent = rev;
|
||||
const res = await postJson("/notepad/text", { text: editor.getValue() });
|
||||
const tab = saveTab;
|
||||
const res = await postJson("/notepad/text?tab=" + tab, { text: editor.getValue() });
|
||||
sending = false;
|
||||
// The tab was deleted or left behind while this was out: nothing in the
|
||||
// answer applies to what is on screen now.
|
||||
if (tab !== saveTab) return check();
|
||||
if (rev !== sent) {
|
||||
// Typed while it was out: the newer text has its own debounce running, or
|
||||
// is already due and waiting for this request to finish.
|
||||
if (save.status === "saving") send();
|
||||
return;
|
||||
return check();
|
||||
}
|
||||
if (res.status === 200) {
|
||||
problem = "";
|
||||
return dispatch("ok");
|
||||
}
|
||||
const code = res.body && res.body.error;
|
||||
if (code === "no-such-tab") return gone(tab);
|
||||
problem = errorSentence(res.status === 0 ? null : code);
|
||||
dispatch({ type: "error", code });
|
||||
}
|
||||
|
||||
function changed(text) {
|
||||
if (loading) return;
|
||||
if (loading || !activeId) return;
|
||||
rev += 1;
|
||||
saveTab = activeId;
|
||||
dispatch({ type: "typed", bytes: noteBytes(text) });
|
||||
}
|
||||
|
||||
@@ -131,6 +191,18 @@ function flush() {
|
||||
if (save.status === "pending" || save.status === "failed") dispatch("due");
|
||||
}
|
||||
|
||||
// Forget the text on screen without saving it: the tab it belongs to is gone.
|
||||
function discard() {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
save = SAVE_START;
|
||||
saveTab = null;
|
||||
problem = "";
|
||||
rev += 1;
|
||||
paintStatus();
|
||||
check();
|
||||
}
|
||||
|
||||
function setText(text) {
|
||||
loading = true;
|
||||
try {
|
||||
@@ -140,120 +212,295 @@ function setText(text) {
|
||||
}
|
||||
}
|
||||
|
||||
// OverType writes inline style attributes into the HTML it sets: one on every
|
||||
// link it draws (its tooltip's anchor name) and two in the link tooltip. The
|
||||
// page's policy refuses each one with a report, on every keystroke. While the
|
||||
// editor is built, the elements it makes get an innerHTML that drops them
|
||||
// (withoutStyleAttrs); the preview and the tooltip are among them, so this
|
||||
// holds for every later render too. The tooltip then finds a link by the data
|
||||
// attribute its anchor name moved to.
|
||||
function buildWithoutStyleAttrs(build) {
|
||||
const create = document.createElement;
|
||||
const inner = Object.getOwnPropertyDescriptor(Element.prototype, "innerHTML");
|
||||
document.createElement = function (...args) {
|
||||
const node = create.apply(this, args);
|
||||
Object.defineProperty(node, "innerHTML", {
|
||||
configurable: true,
|
||||
get() {
|
||||
return inner.get.call(this);
|
||||
},
|
||||
set(html) {
|
||||
const clean = withoutStyleAttrs(String(html));
|
||||
if (this.classList.contains("overtype-preview")) patchPreview(this, clean);
|
||||
else inner.set.call(this, clean);
|
||||
},
|
||||
});
|
||||
return node;
|
||||
};
|
||||
try {
|
||||
return build();
|
||||
} finally {
|
||||
document.createElement = create;
|
||||
}
|
||||
}
|
||||
|
||||
// The styled layer as OverType last drew it, one HTML string per top-level
|
||||
// element (topLevelParts), matching the preview's children one for one.
|
||||
let drawn = [];
|
||||
|
||||
const parseParts = (html) => {
|
||||
const tpl = document.createElement("template");
|
||||
tpl.innerHTML = html;
|
||||
return [...tpl.content.childNodes];
|
||||
};
|
||||
|
||||
// OverType redraws the whole styled layer on every key: about 43,000 elements
|
||||
// in a 200 KB note, and parsing and laying those out is most of the wait for a
|
||||
// key to show. Only the lines between the first and the last that differ from
|
||||
// the last drawing are parsed and swapped; the rest stays as it was.
|
||||
function patchPreview(preview, html) {
|
||||
const parts = topLevelParts(html);
|
||||
const shown = [...preview.childNodes];
|
||||
const redraw = () => {
|
||||
preview.replaceChildren(...parseParts(html));
|
||||
drawn = parts && preview.childNodes.length === parts.length ? parts : [];
|
||||
};
|
||||
if (!parts || shown.length !== drawn.length) return redraw();
|
||||
const { head, tail } = changedRange(drawn, parts);
|
||||
const changed = parts.slice(head, parts.length - tail);
|
||||
const fresh = parseParts(changed.join(""));
|
||||
// One element per part, or the cut was wrong: draw it all.
|
||||
if (fresh.length !== changed.length) return redraw();
|
||||
const after = shown[shown.length - tail] || null;
|
||||
for (const old of shown.slice(head, shown.length - tail)) old.remove();
|
||||
for (const node of fresh) preview.insertBefore(node, after);
|
||||
drawn = parts;
|
||||
// OverType shades each pair of code fences right after this, and never
|
||||
// takes the shading off: a kept line whose fence lost its partner would keep
|
||||
// it. Cleared here (the attributes removed outright, so a cleared line is
|
||||
// the line OverType drew), and OverType marks only the pairs that still are.
|
||||
for (const line of preview.querySelectorAll(".code-block-line")) {
|
||||
line.classList.remove("code-block-line");
|
||||
if (!line.classList.length) line.removeAttribute("class");
|
||||
}
|
||||
for (const fence of preview.querySelectorAll(".code-fence")) fence.removeAttribute("style");
|
||||
}
|
||||
|
||||
function makeEditor() {
|
||||
// Before the first instance, or it injects its <style> (which the policy
|
||||
// blocks) and the flag would come too late.
|
||||
OverType.stylesInjected = true;
|
||||
// OverType reports its first, empty value as a change: not the person typing,
|
||||
// and saved it would wipe the note.
|
||||
async function makeEditor() {
|
||||
const { makeCodeMirrorEditor } = await import("../notepad-editor.js");
|
||||
// The editor may report its first, empty value as a change: not the person
|
||||
// typing, and saved it would wipe the note.
|
||||
loading = true;
|
||||
try {
|
||||
[editor] = buildWithoutStyleAttrs(
|
||||
() =>
|
||||
new OverType($("notepad-editor"), {
|
||||
toolbar: false,
|
||||
textareaProps: { "aria-label": "Notepad text" },
|
||||
onChange: changed,
|
||||
}),
|
||||
);
|
||||
editor = makeCodeMirrorEditor($("notepad-editor"), { onChange: changed, label: "Notebook text" });
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
editor.linkTooltip.findAnchorElement = (index) => editor.preview.querySelector(`a[data-anchor="--link-${index}"]`);
|
||||
}
|
||||
|
||||
// The stored note (`{ text, images }`), or null when it could not be read.
|
||||
async function readNote() {
|
||||
// One read of the notepad: `{ ok: true, body }`, or `{ ok: false, code }`
|
||||
// with the server's refusal (`no-such-tab`), or code null when it could not
|
||||
// be reached or answered oddly.
|
||||
async function readNote(tab) {
|
||||
try {
|
||||
const res = await fetch("/notepad", { cache: "no-store" });
|
||||
if (!res.ok) return null;
|
||||
const body = await res.json();
|
||||
return body && typeof body.text === "string" ? body : null;
|
||||
const res = await fetch("/notepad" + (tab ? "?tab=" + encodeURIComponent(tab) : ""), { cache: "no-store" });
|
||||
let body = null;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {}
|
||||
if (!res.ok) return { ok: false, code: body && typeof body.error === "string" ? body.error : null };
|
||||
return body && Array.isArray(body.tabs) ? { ok: true, body } : { ok: false, code: null };
|
||||
} catch {
|
||||
return null;
|
||||
return { ok: false, code: null };
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ tabs */
|
||||
|
||||
const nameOf = (id) => (tabs.find((t) => t.id === id) || {}).name || "";
|
||||
|
||||
function drawTabs() {
|
||||
tabBar.draw(tabs, activeId);
|
||||
$("notepad-tab-new").disabled = busy;
|
||||
$("notepad-empty-new").disabled = busy;
|
||||
$("notepad-name-save").disabled = busy;
|
||||
}
|
||||
|
||||
// Put a read tab on screen: its text, its pictures, the bar. `keep` leaves
|
||||
// the text and the tab alone (the notepad was only reopened while text was
|
||||
// still unsaved), taking the bar and the pictures from the server.
|
||||
function show(body, keep = false) {
|
||||
tabs = body.tabs.map((t) => ({ id: t.id, name: t.name }));
|
||||
const tab = body.tab;
|
||||
if (keep) {
|
||||
takeStored(tab && tab.id === activeId ? tab.images : [], activeId);
|
||||
return drawTabs();
|
||||
}
|
||||
activeId = tab ? tab.id : null;
|
||||
setText(tab ? tab.text : "");
|
||||
save = SAVE_START;
|
||||
saveTab = null;
|
||||
problem = "";
|
||||
rev += 1;
|
||||
loaded = true;
|
||||
editor.setReadOnly(!tab);
|
||||
takeStored(tab ? tab.images : [], activeId);
|
||||
drawTabs();
|
||||
paintStatus();
|
||||
}
|
||||
|
||||
// Put the tab `id` (the server's pick when null) on screen, after the one
|
||||
// before it was saved; whether it is there now.
|
||||
async function showTab(id, remember = true) {
|
||||
const mark = rev;
|
||||
let res = await readNote(id);
|
||||
if (!res.ok && res.code === "no-such-tab" && id) {
|
||||
// Gone since the bar was drawn: say so, and show what is there.
|
||||
tell(errorSentence("no-such-tab"));
|
||||
res = await readNote(null);
|
||||
}
|
||||
if (!res.ok) {
|
||||
tell(res.code ? errorSentence(res.code) : NOT_LOADED);
|
||||
return false;
|
||||
}
|
||||
// Typed while the tab was loading: that text is not saved yet, so stay.
|
||||
if (activeId && rev !== mark && tabSwitch(save)) {
|
||||
tell(STAY);
|
||||
return false;
|
||||
}
|
||||
show(res.body);
|
||||
if (remember && activeId) postJson("/notepad/tab/last", { id: activeId });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function switchTo(id) {
|
||||
if (id === activeId || busy) return;
|
||||
// The name form and the delete question belong to the tab they were opened on.
|
||||
closeNameForm(false);
|
||||
closeDelete();
|
||||
if (!(await settled())) {
|
||||
tell(STAY);
|
||||
return tabBar.focusTab(activeId);
|
||||
}
|
||||
tell("");
|
||||
inform("");
|
||||
if (await showTab(id)) tabBar.focusTab(activeId);
|
||||
}
|
||||
|
||||
async function reorder(order, focus) {
|
||||
const before = tabs;
|
||||
const byId = new Map(tabs.map((t) => [t.id, t]));
|
||||
tabs = order.map((id) => byId.get(id)).filter(Boolean);
|
||||
drawTabs();
|
||||
tabBar.focusTab(focus);
|
||||
const at = order.indexOf(focus);
|
||||
if (at >= 0) inform(`Moved ${nameOf(focus)} to position ${at + 1} of ${order.length}`);
|
||||
const res = await postJson("/notepad/tab/order", { order });
|
||||
if (res.status === 200) return;
|
||||
// Refused: draw what the server has, and say why.
|
||||
tabs = before;
|
||||
inform("");
|
||||
tell(errorSentence(res.status === 0 ? null : res.body && res.body.error));
|
||||
const again = await readNote(activeId);
|
||||
if (again.ok) tabs = again.body.tabs.map((t) => ({ id: t.id, name: t.name }));
|
||||
drawTabs();
|
||||
}
|
||||
|
||||
// A tab is no longer there (deleted here, or from another page): off the bar,
|
||||
// its unsaved text dropped without a save, and its neighbour on screen.
|
||||
async function gone(id, index = tabs.findIndex((t) => t.id === id), announce = true) {
|
||||
const here = id === activeId;
|
||||
if (here || id === saveTab) discard();
|
||||
const rest = tabs.filter((t) => t.id !== id);
|
||||
const next = here ? rest[index] || rest[index - 1] || null : null;
|
||||
tabs = rest;
|
||||
if (announce) tell(errorSentence("no-such-tab"));
|
||||
if (!here) return drawTabs();
|
||||
activeId = null;
|
||||
images = [];
|
||||
pending.clear();
|
||||
drawStrip();
|
||||
// Nothing of the deleted tab stays on screen or editable, whatever loads next.
|
||||
setText("");
|
||||
editor.setReadOnly(true);
|
||||
if (next) {
|
||||
drawTabs();
|
||||
if (await showTab(next.id)) tabBar.focusTab(activeId);
|
||||
return;
|
||||
}
|
||||
drawTabs();
|
||||
$("notepad-empty-new").focus();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ name form */
|
||||
|
||||
function nameError(sentence) {
|
||||
$("notepad-name-error").textContent = sentence;
|
||||
$("notepad-name").focus();
|
||||
}
|
||||
|
||||
function openNameForm(mode) {
|
||||
if (busy || (mode === "rename" && !activeId)) return;
|
||||
closeDelete();
|
||||
naming = mode;
|
||||
$("notepad-name-label").textContent = mode === "new" ? "Name this tab" : "Rename this tab";
|
||||
$("notepad-name-error").textContent = "";
|
||||
if (!$("notepad-name-dlg").open) $("notepad-name-dlg").showModal();
|
||||
const input = $("notepad-name");
|
||||
input.value = mode === "rename" ? nameOf(activeId) : "";
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
|
||||
function closeNameForm(toFocus = true) {
|
||||
if (!naming) return;
|
||||
const was = naming;
|
||||
naming = null;
|
||||
$("notepad-name-dlg").close();
|
||||
if (!toFocus) return;
|
||||
if (was === "rename") tabBar.focusTab(activeId);
|
||||
else (tabs.length ? $("notepad-tab-new") : $("notepad-empty-new")).focus();
|
||||
}
|
||||
|
||||
async function createNamed(name) {
|
||||
// The tab on screen is saved first, then the new one is made and shown.
|
||||
if (!(await settled())) return nameError(STAY);
|
||||
const res = await postJson("/notepad/tab", { name });
|
||||
const id = res.body && res.body.id;
|
||||
if (res.status !== 200 || !TAB_ID_RE.test(String(id))) {
|
||||
return nameError(errorSentence(res.status === 0 ? null : res.body && res.body.error));
|
||||
}
|
||||
closeNameForm(false);
|
||||
busy = false;
|
||||
tell("");
|
||||
inform("");
|
||||
if (await showTab(id, false)) tabBar.focusTab(activeId);
|
||||
}
|
||||
|
||||
async function renameTo(name) {
|
||||
const id = activeId;
|
||||
const res = await postJson("/notepad/tab/rename", { id, name });
|
||||
if (res.status !== 200) {
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
if (code !== "no-such-tab") return nameError(errorSentence(code));
|
||||
closeNameForm(false);
|
||||
return gone(id);
|
||||
}
|
||||
const kept = tabs.find((t) => t.id === id);
|
||||
if (kept) kept.name = (res.body && typeof res.body.name === "string" && res.body.name) || name;
|
||||
closeNameForm(false);
|
||||
busy = false;
|
||||
drawTabs();
|
||||
tabBar.focusTab(id);
|
||||
}
|
||||
|
||||
async function submitName() {
|
||||
if (!naming || busy) return;
|
||||
const mode = naming;
|
||||
const raw = $("notepad-name").value;
|
||||
const sentence = tabNameProblem(tabs, raw, mode === "rename" ? activeId : undefined);
|
||||
if (sentence) return nameError(sentence);
|
||||
busy = true;
|
||||
drawTabs();
|
||||
try {
|
||||
await (mode === "new" ? createNamed(cleanTabName(raw).name) : renameTo(cleanTabName(raw).name));
|
||||
} finally {
|
||||
busy = false;
|
||||
drawTabs();
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ delete */
|
||||
|
||||
function paintDelete() {
|
||||
const dlg = $("notepad-delete");
|
||||
if (stage === "none") return void (dlg.open && dlg.close());
|
||||
if (!dlg.open) dlg.showModal();
|
||||
const name = nameOf(activeId);
|
||||
const count = images.filter((img) => img.id).length;
|
||||
const pics = count === 1 ? "1 picture" : `${count} pictures`;
|
||||
$("notepad-delete-text").textContent =
|
||||
stage === "ask" ? `This deletes the tab ${name}, its text and its ${pics}. This cannot be undone.` : `Really delete ${name} for good?`;
|
||||
$("notepad-delete-go").textContent = stage === "ask" ? "Delete tab…" : "Yes, delete it";
|
||||
$("notepad-delete-keep").disabled = $("notepad-delete-go").disabled = busy;
|
||||
}
|
||||
|
||||
function openDelete() {
|
||||
if (!activeId || busy) return;
|
||||
closeNameForm(false);
|
||||
stage = nextDelete("none", "click");
|
||||
paintDelete();
|
||||
$("notepad-delete-keep").focus();
|
||||
}
|
||||
|
||||
function closeDelete(toFocus = false) {
|
||||
if (stage === "none") return;
|
||||
stage = nextDelete(stage, "cancel");
|
||||
paintDelete();
|
||||
if (toFocus) tabBar.focusTab(activeId);
|
||||
}
|
||||
|
||||
// Only the second press posts: the first moves to "Really delete…?".
|
||||
async function confirmDelete() {
|
||||
if (busy || stage === "none") return;
|
||||
stage = nextDelete(stage, "confirm");
|
||||
if (stage === "sure") {
|
||||
paintDelete();
|
||||
return $("notepad-delete-keep").focus();
|
||||
}
|
||||
const id = activeId;
|
||||
const at = tabs.findIndex((t) => t.id === id);
|
||||
busy = true;
|
||||
drawTabs();
|
||||
paintDelete();
|
||||
const res = await postJson("/notepad/tab/delete", { id });
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
busy = false;
|
||||
stage = "none";
|
||||
paintDelete();
|
||||
if (res.status !== 200 && code !== "no-such-tab") {
|
||||
drawTabs();
|
||||
tell(errorSentence(code));
|
||||
return tabBar.focusTab(id);
|
||||
}
|
||||
// Gone for good (deleted from another page counts, with its sentence).
|
||||
await gone(id, at, code === "no-such-tab");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ pictures */
|
||||
|
||||
// The strip's pictures, oldest first, as { key, id, url, thumb, status }:
|
||||
// `key` is the page's own handle, `id` and `url` come from the server once
|
||||
// the upload lands, `thumb` is the stored thumbnail's URL or, for one added
|
||||
// here, the data: URL reencode() made. `status` is ready, uploading or failed.
|
||||
// The strip's pictures, oldest first, as { key, id, tab, url, thumb, status }:
|
||||
// `key` is the page's own handle, `tab` the tab the picture was added to (fixed
|
||||
// then, so a switch mid-upload cannot move it), `id` and `url` come from the
|
||||
// server once the upload lands, `thumb` is the stored thumbnail's URL or, for
|
||||
// one added here, the data: URL reencode() made. `status` is ready, uploading
|
||||
// or failed. Only the tab on screen has entries here.
|
||||
let images = [];
|
||||
|
||||
// What a failed upload needs to go again, by key: the re-encoded picture and
|
||||
@@ -282,24 +529,30 @@ const drop = (key) => {
|
||||
pending.delete(key);
|
||||
};
|
||||
|
||||
// Whether the picture is still on screen: one added to a tab since left
|
||||
// finishes in the background and touches nothing here.
|
||||
const live = (entry) => images.includes(entry);
|
||||
|
||||
// The picture, then its thumbnail. One whose picture already landed (only
|
||||
// the thumbnail failed) sends just the thumbnail again.
|
||||
async function upload(entry) {
|
||||
const encoded = pending.get(entry.key);
|
||||
if (!encoded) return;
|
||||
entry.status = "uploading";
|
||||
drawStrip();
|
||||
if (live(entry)) drawStrip();
|
||||
if (!entry.id) {
|
||||
const res = await postJpeg("/notepad/image", encoded.blob);
|
||||
const res = await postJpeg("/notepad/image?tab=" + entry.tab, encoded.blob);
|
||||
const id = res.body && res.body.id;
|
||||
if (res.status !== 200 || !IMAGE_ID_RE.test(String(id))) return failed(entry, res);
|
||||
entry.id = id;
|
||||
entry.url = "/notepad/images/" + id + ".jpg";
|
||||
// The server names the URL (it carries the tab).
|
||||
entry.url = res.body.url;
|
||||
}
|
||||
const res = await postJpeg("/notepad/thumb?id=" + entry.id, encoded.thumbBlob);
|
||||
const res = await postJpeg("/notepad/thumb?id=" + entry.id + "&tab=" + entry.tab, encoded.thumbBlob);
|
||||
if (res.status !== 200) return failed(entry, res);
|
||||
pending.delete(entry.key);
|
||||
entry.status = "ready";
|
||||
if (!live(entry)) return;
|
||||
// Only this picture's own failure goes: a sentence about the batch (the
|
||||
// cap) or another picture stays up while the rest land.
|
||||
if (noticeKey === entry.key) tell("");
|
||||
@@ -309,26 +562,30 @@ async function upload(entry) {
|
||||
function failed(entry, res) {
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
// The server said no for good: going again would only be refused again.
|
||||
if (code === "too-many" || code === "not-jpeg" || code === "too-large" || code === "not-found") drop(entry.key);
|
||||
if (code === "too-many" || code === "not-jpeg" || code === "too-large" || code === "not-found" || code === "no-such-tab") drop(entry.key);
|
||||
else entry.status = "failed";
|
||||
// One added to a tab since left says nothing here.
|
||||
if (entry.tab !== activeId) return;
|
||||
drawStrip();
|
||||
tell(errorSentence(code), entry.key);
|
||||
}
|
||||
|
||||
export async function addNotepadImages(files) {
|
||||
const given = imageFiles(files);
|
||||
if (!given.length) return;
|
||||
const tab = activeId;
|
||||
if (!given.length || !tab) return;
|
||||
const room = Math.max(0, NOTEPAD_MAX_IMAGES - images.length);
|
||||
tell(given.length > room ? errorSentence("too-many") : "");
|
||||
await Promise.all(
|
||||
given.slice(0, room).map(async (file) => {
|
||||
const entry = { key: crypto.randomUUID(), id: null, url: null, thumb: null, status: "uploading" };
|
||||
const entry = { key: crypto.randomUUID(), id: null, tab, url: null, thumb: null, status: "uploading" };
|
||||
images.push(entry);
|
||||
drawStrip();
|
||||
let encoded;
|
||||
try {
|
||||
encoded = await reencode(file);
|
||||
} catch (err) {
|
||||
if (!live(entry)) return;
|
||||
drop(entry.key);
|
||||
drawStrip();
|
||||
return tell(err.message);
|
||||
@@ -352,9 +609,9 @@ function thumbItem(entry, n) {
|
||||
if (src) {
|
||||
const pic = el("img");
|
||||
pic.src = src;
|
||||
pic.alt = `Notepad image ${n}`;
|
||||
pic.alt = `Notebook image ${n}`;
|
||||
open.appendChild(pic);
|
||||
} else open.setAttribute("aria-label", `Notepad image ${n}`);
|
||||
} else open.setAttribute("aria-label", `Notebook image ${n}`);
|
||||
// Never `disabled`, which would push the focus out of the strip while the
|
||||
// picture uploads: it only does nothing until there is a picture to show.
|
||||
const viewable = Boolean(entry.url) && entry.status !== "uploading";
|
||||
@@ -447,17 +704,19 @@ async function remove(entry) {
|
||||
if (entry.id) {
|
||||
entry.deleting = true;
|
||||
drawStrip();
|
||||
const res = await postJson("/notepad/image/delete", { id: entry.id });
|
||||
const res = await postJson("/notepad/image/delete?tab=" + entry.tab, { id: entry.id });
|
||||
entry.deleting = false;
|
||||
// The tab was left (or deleted) while this was out: nothing here to update.
|
||||
if (!live(entry)) return;
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
if (res.status !== 200 && code !== "not-found") {
|
||||
if (res.status !== 200 && code !== "not-found" && code !== "no-such-tab") {
|
||||
entry.asking = false;
|
||||
drawStrip();
|
||||
focusIn(entry.key, ".notepad-thumb-delete");
|
||||
return tell(errorSentence(code));
|
||||
}
|
||||
// Already gone (deleted from another page): off the strip too, with why.
|
||||
if (code === "not-found") tell(errorSentence(code));
|
||||
if (code === "not-found" || code === "no-such-tab") tell(errorSentence(code));
|
||||
}
|
||||
const at = images.indexOf(entry);
|
||||
drop(entry.key);
|
||||
@@ -467,14 +726,15 @@ async function remove(entry) {
|
||||
else $("notepad-add").focus();
|
||||
}
|
||||
|
||||
// The stored pictures from GET /notepad, oldest first, then any added here
|
||||
// that are still on their way or waiting for Retry.
|
||||
function takeStored(list) {
|
||||
// The stored pictures of the tab `tabId` from GET /notepad, oldest first, then
|
||||
// any added to it here that are still on their way or waiting for Retry.
|
||||
// Pictures of any other tab are not kept: they finish in the background.
|
||||
function takeStored(list, tabId) {
|
||||
const stored = (Array.isArray(list) ? list : [])
|
||||
.filter((img) => img && IMAGE_ID_RE.test(String(img.id)))
|
||||
.map((img) => ({ key: img.id, id: img.id, url: img.url, thumb: img.thumb || null, status: "ready" }));
|
||||
.map((img) => ({ key: img.id, id: img.id, tab: tabId, url: img.url, thumb: img.thumb || null, status: "ready" }));
|
||||
const ids = new Set(stored.map((img) => img.id));
|
||||
const local = images.filter((img) => img.status !== "ready" && !(img.id && ids.has(img.id)));
|
||||
const local = images.filter((img) => img.tab === tabId && img.status !== "ready" && !(img.id && ids.has(img.id)));
|
||||
for (const key of pending.keys()) if (!local.some((img) => img.key === key)) pending.delete(key);
|
||||
images = [...stored, ...local];
|
||||
drawStrip();
|
||||
@@ -492,7 +752,7 @@ function showAt(index) {
|
||||
viewing.index = index;
|
||||
const pic = $("notepad-preview-img");
|
||||
pic.src = entry.url;
|
||||
pic.alt = `Notepad image ${images.indexOf(entry) + 1}`;
|
||||
pic.alt = `Notebook image ${images.indexOf(entry) + 1}`;
|
||||
$("notepad-preview-count").textContent = `${index + 1} of ${list.length}`;
|
||||
$("notepad-preview-prev").hidden = $("notepad-preview-next").hidden = list.length < 2;
|
||||
}
|
||||
@@ -514,7 +774,7 @@ function move(delta) {
|
||||
}
|
||||
|
||||
// Esc is taken here and closes the preview alone: left to the browser, it
|
||||
// could reach the Notepad underneath too.
|
||||
// could reach the Notebook underneath too.
|
||||
function wirePreview() {
|
||||
const dlg = $("notepad-preview");
|
||||
$("notepad-preview-prev").addEventListener("click", () => move(-1));
|
||||
@@ -597,45 +857,87 @@ function wireImages(dlg) {
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ opening */
|
||||
|
||||
// Read again on every open, so saves from another page on the same folder
|
||||
// show up. Text typed here and not yet saved (or too long to save) is never
|
||||
// replaced.
|
||||
// replaced; the tab it belongs to stays on screen.
|
||||
async function load() {
|
||||
const note = await readNote();
|
||||
if (note === null) {
|
||||
const keep = keepsText(save);
|
||||
let res = await readNote(activeId);
|
||||
if (!res.ok && res.code === "no-such-tab" && activeId && !keep) res = await readNote(null);
|
||||
if (!res.ok) {
|
||||
if (loaded) return;
|
||||
const line = $("notepad-status");
|
||||
line.textContent = NOT_LOADED;
|
||||
line.classList.add("is-problem");
|
||||
return;
|
||||
}
|
||||
takeStored(note.images);
|
||||
if (keepsText(save)) return;
|
||||
setText(note.text);
|
||||
save = SAVE_START;
|
||||
loaded = true;
|
||||
editor.textarea.readOnly = false;
|
||||
show(res.body, keep);
|
||||
paintStatus();
|
||||
if (!tabs.length) $("notepad-empty-new").focus();
|
||||
}
|
||||
|
||||
// The one editor being made, so a second click while it loads waits for it
|
||||
// instead of building another beside it.
|
||||
let making = null;
|
||||
|
||||
export async function openNotepad() {
|
||||
if ($("btn-notepad").disabled) return;
|
||||
const dlg = $("notepad-modal");
|
||||
if (!editor) makeEditor();
|
||||
editor.textarea.readOnly = !loaded;
|
||||
if (!editor) {
|
||||
try {
|
||||
await (making ??= makeEditor().finally(() => (making = null)));
|
||||
} catch {
|
||||
// The editor file could not be loaded: say so, and let the next click try again.
|
||||
if (!dlg.open) dlg.showModal();
|
||||
return tell(EDITOR_NOT_LOADED);
|
||||
}
|
||||
}
|
||||
editor.setReadOnly(!loaded || !activeId);
|
||||
tell("");
|
||||
inform("");
|
||||
naming = null;
|
||||
$("notepad-name-dlg").close();
|
||||
stage = "none";
|
||||
paintDelete();
|
||||
if (!dlg.open) dlg.showModal();
|
||||
editor.textarea.focus();
|
||||
editor.focus();
|
||||
await load();
|
||||
}
|
||||
|
||||
export function wireNotepad() {
|
||||
const dlg = $("notepad-modal");
|
||||
tabBar = createTabs({
|
||||
onSwitch: (id) => switchTo(id),
|
||||
onChange: async (event) => {
|
||||
if (event.type === "order") return reorder(event.order, event.focus);
|
||||
// Rename and delete act on the current tab: a double-click, F2 or x on
|
||||
// another one picks it first.
|
||||
if (event.id && event.id !== activeId) await switchTo(event.id);
|
||||
if (event.id && event.id !== activeId) return;
|
||||
if (event.type === "delete") openDelete();
|
||||
else openNameForm("rename");
|
||||
},
|
||||
});
|
||||
lightDismiss(dlg);
|
||||
wireImages(dlg);
|
||||
wirePreview();
|
||||
$("btn-notepad").addEventListener("click", openNotepad);
|
||||
$("notepad-close").addEventListener("click", () => dlg.close());
|
||||
$("notepad-tab-new").addEventListener("click", () => openNameForm("new"));
|
||||
$("notepad-empty-new").addEventListener("click", () => openNameForm("new"));
|
||||
$("notepad-delete-keep").addEventListener("click", () => closeDelete(true));
|
||||
$("notepad-delete-go").addEventListener("click", confirmDelete);
|
||||
$("notepad-name-cancel").addEventListener("click", () => closeNameForm());
|
||||
$("notepad-name-form").addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
submitName();
|
||||
});
|
||||
// The two small dialogs are modal over the Notebook, so Esc (or any other
|
||||
// way they close) backs out of them alone and the state follows the dialog.
|
||||
$("notepad-name-dlg").addEventListener("close", () => closeNameForm());
|
||||
$("notepad-delete").addEventListener("close", () => closeDelete(true));
|
||||
dlg.addEventListener("close", () => {
|
||||
flush();
|
||||
$("btn-notepad").focus();
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
max-width: min(var(--card-width), 100%);
|
||||
display: flex; gap: 12px; align-items: center; flex-wrap: wrap;
|
||||
margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px solid var(--rule);
|
||||
/* Stays put while the document scrolls under it. The ::before paints over
|
||||
the pane's own padding, so nothing shows through above the row. */
|
||||
position: sticky; top: 0; z-index: 5; background: var(--bg);
|
||||
}
|
||||
.doc-head::before { content: ""; position: absolute; left: 0; right: 0; bottom: 100%; height: 24px; background: var(--bg); }
|
||||
.doc-version { font: 700 12px/1 var(--mono); color: var(--ink-3); }
|
||||
|
||||
.block { max-width: min(var(--card-width), 100%); border-left: 3px solid transparent; padding: 2px 0 2px 14px; margin: 0 auto 4px; position: relative; }
|
||||
@@ -30,6 +34,8 @@
|
||||
/* ----------------------------------------------------------- doc tools */
|
||||
|
||||
.doc-tools { display: flex; gap: 8px; margin-left: auto; flex: none; align-items: center; }
|
||||
.btn.back-home { border-color: var(--accent); color: var(--accent); }
|
||||
.btn.back-home:hover { background: var(--accent-soft); }
|
||||
.doc-saved { font-size: 12px; color: var(--ink-3); }
|
||||
.doc-saved code { font-family: var(--mono); font-size: 11.5px; color: var(--ink-2); }
|
||||
.doc-head { align-items: center; }
|
||||
|
||||
@@ -50,6 +50,8 @@
|
||||
hover it may never get. This one IS the screen's reason to exist. */
|
||||
.handoff-copy { flex: none; }
|
||||
.handoff-note { margin: 8px 0 0; font-size: 12.5px; color: var(--ink-3); }
|
||||
/* Continue here sits under the command row: keep a gap so the two do not touch. */
|
||||
.continue-offer { margin-top: 14px; }
|
||||
|
||||
/* A session with nothing left to run. Quieter than a real next step: no
|
||||
accented box, plain body text and a small command, because there is
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
the one that is only nice to have. */
|
||||
.pager { gap: 8px; }
|
||||
.pager-count { display: none; }
|
||||
/* The Notepad takes the whole screen, and every control in it is a
|
||||
/* The Notebook takes the whole screen, and every control in it is a
|
||||
fingertip wide. The pictures go under Add image rather than beside it, so
|
||||
the strip gets the full width, and the preview's side columns narrow to
|
||||
give the picture their room. */
|
||||
@@ -62,6 +62,12 @@
|
||||
.modal.notepad .modal-actions .btn,
|
||||
.btn.notepad-preview-close { min-height: 44px; }
|
||||
.notepad-images { flex-direction: column; align-items: stretch; }
|
||||
.notepad-tabbar { flex-wrap: wrap; }
|
||||
.modal.notepad .notepad-tab-new,
|
||||
.modal.notepad-sub .modal-actions .btn,
|
||||
.notepad-tab,
|
||||
.notepad-tab-x { min-height: 44px; }
|
||||
.notepad-tab-x { width: 32px; }
|
||||
.notepad-add { align-self: flex-start; }
|
||||
.notepad-thumb .notepad-thumb-delete { width: 30px; height: 30px; font-size: 18px; }
|
||||
.modal.notepad-preview[open] { grid-template-columns: 52px minmax(0, 1fr) 52px; }
|
||||
|
||||
@@ -333,7 +333,7 @@ h1 {
|
||||
font: inherit;
|
||||
font-size: 13.5px;
|
||||
padding: 7px 9px;
|
||||
border-radius: 8px;
|
||||
border-radius: 0;
|
||||
cursor: pointer;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
@@ -178,7 +178,7 @@ const toJpeg = (canvas, quality) =>
|
||||
|
||||
// The upload (a JPEG no longer than IMAGE_LONG_EDGE) and its thumbnail, as a
|
||||
// small data: URL for a tray (`thumb`) and as a JPEG for a server that keeps
|
||||
// one (`thumbBlob`, the Notepad's), from one decode.
|
||||
// one (`thumbBlob`, the Notebook's), from one decode.
|
||||
export async function reencode(file) {
|
||||
const source = await decodeImage(file);
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/* CodeMirror 6 (state, view, language, commands, lang-markdown), MIT licence, (c) Marijn Haverbeke and others.
|
||||
* https://codemirror.net/ . Bundled by scripts/vendor-codemirror.mjs; do not edit by hand.
|
||||
* Versions: @codemirror/state 6.7.6, @codemirror/view 6.43.15, @codemirror/language 6.13.1, @codemirror/commands 6.11.1, @codemirror/lang-markdown 6.5.2 */
|
||||
var Br=[],Fl=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<n.length;e++)(e%2?Fl:Br).push(t=t+n[e])})();function td(n){if(n<768)return!1;for(let e=0,t=Br.length;;){let i=e+t>>1;if(n<Br[i])t=i;else if(n>=Fl[i])e=i+1;else return!0;if(e==t)return!1}}function Nl(n){return n>=127462&&n<=127487}var Ul=8205;function Hl(n,e,t=!0,i=!0){return(t?Kl:id)(n,e,i)}function Kl(n,e,t){if(e==n.length)return e;e&&Jl(n.charCodeAt(e))&&ea(n.charCodeAt(e-1))&&e--;let i=Dr(n,e);for(e+=Gl(i);e<n.length;){let r=Dr(n,e);if(i==Ul||r==Ul||t&&td(r))e+=Gl(r),i=r;else if(Nl(r)){let s=0,o=e-2;for(;o>=0&&Nl(Dr(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function id(n,e,t){for(;e>1;){let i=Kl(n,e-2,t);if(i<e)return i;e--}return 0}function Dr(n,e){let t=n.charCodeAt(e);if(!ea(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return Jl(i)?(t-55296<<10)+(i-56320)+65536:t}function Jl(n){return n>=56320&&n<57344}function ea(n){return n>=55296&&n<56320}function Gl(n){return n<65536?1:2}var j=class n{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=li(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),ri.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=li(this,e,t);let i=[];return this.decompose(e,t,i,0),ri.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new _t(this),s=new _t(e);for(let o=t,l=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(l+=r.value.length,r.done||l>=i)return!0}}iter(e=1){return new _t(this,e)}iterRange(e,t=this.length){return new Rn(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Mn(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?n.empty:e.length<=32?new Se(e):ri.from(Se.split(e,[]))}},Se=class n extends j{constructor(e,t=nd(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],l=r+o.length;if((t?i:l)>=e)return new Wr(r,l,i,o);r=l+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new n(ta(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),l=An(s.text,o.text.slice(),0,s.length);if(l.length<=32)i.push(new n(l,o.length+s.length));else{let a=l.length>>1;i.push(new n(l.slice(0,a)),new n(l.slice(a)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof n))return super.replace(e,t,i);[e,t]=li(this,e,t);let r=An(this.text,An(i.text,ta(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new n(r,s):ri.from(n.split(r,[]),s)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=li(this,e,t);let r="";for(let s=0,o=0;s<=t&&o<this.text.length;o++){let l=this.text[o],a=s+l.length;s>e&&o&&(r+=i),e<a&&t>s&&(r+=l.slice(Math.max(0,e-s),t-s)),s=a+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new n(i,r)),i=[],r=-1);return r>-1&&t.push(new n(i,r)),t}},ri=class n extends j{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],l=r+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,r);r=l+1,i=a+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s<this.children.length;s++){let l=this.children[s],a=o+l.length;if(e<=a&&t>=o){let h=r&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=li(this,e,t),i.lines<this.lines)for(let r=0,s=0;r<this.children.length;r++){let o=this.children[r],l=s+o.length;if(e>=s&&t<=l){let a=o.replace(e-s,t-s,i),h=this.lines-o.lines+a.lines;if(a.lines<h>>4&&a.lines>h>>6){let f=this.children.slice();return f[r]=a,new n(f,this.length-(t-e)+i.length)}return super.replace(s,l,a)}s=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=`
|
||||
`){[e,t]=li(this,e,t);let r="";for(let s=0,o=0;s<this.children.length&&o<=t;s++){let l=this.children[s],a=o+l.length;o>e&&s&&(r+=i),e<a&&t>o&&(r+=l.sliceString(e-o,t-o,i)),o=a+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof n))return 0;let i=0,[r,s,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==l)return i;let a=this.children[r],h=e.children[s];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let O of e)O.flatten(d);return new Se(d,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,l=[],a=0,h=-1,f=[];function c(d){let O;if(d.lines>s&&d instanceof n)for(let p of d.children)c(p);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof Se&&a&&(O=f[f.length-1])instanceof Se&&d.lines+O.lines<=32?(a+=d.lines,h+=d.length+1,f[f.length-1]=new Se(O.text.concat(d.text),O.length+1+d.length)):(a+d.lines>r&&u(),a+=d.lines,h+=d.length+1,f.push(d))}function u(){a!=0&&(l.push(f.length==1?f[0]:n.from(f,h)),h=-1,a=f.length=0)}for(let d of e)c(d);return u(),l.length==1?l[0]:new n(l,t)}};j.empty=new Se([""],0);function nd(n){let e=-1;for(let t of n)e+=t.length+1;return e}function An(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s<n.length&&r<=i;s++){let l=n[s],a=r+l.length;a>=t&&(a>i&&(l=l.slice(0,i-r)),r<t&&(l=l.slice(t-r)),o?(e[e.length-1]+=l,o=!1):e.push(l)),r=a+1}return e}function ta(n,e,t){return An(n,[""],e,t)}var _t=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof Se?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,l=r instanceof Se?r.text.length:r.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=`
|
||||
`,this;e--}else if(r instanceof Se){let a=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=r.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof Se?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Rn=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new _t(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},Mn=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(j.prototype[Symbol.iterator]=function(){return this.iter()},_t.prototype[Symbol.iterator]=Rn.prototype[Symbol.iterator]=Mn.prototype[Symbol.iterator]=function(){return this});var Wr=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function li(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function ie(n,e,t=!0,i=!0){return Hl(n,e,t,i)}function rd(n){return n>=56320&&n<57344}function sd(n){return n>=55296&&n<56320}function ns(n,e){let t=n.charCodeAt(e);if(!sd(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return rd(i)?(t-55296<<10)+(i-56320)+65536:t}function rs(n){return n<65536?1:2}var Vr=/\r\n?|\n/,oe=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(oe||(oe={})),tt=class n{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,r=0;t<this.sections.length;){let s=this.sections[t++],o=this.sections[t++];o<0?(e(i,r,s),r+=s):r+=o,i+=s}}iterChangedRanges(e,t=!1){Ir(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let i=this.sections[t++],r=this.sections[t++];r<0?e.push(i,r):e.push(r,i)}return new n(e)}composeDesc(e){return this.empty?e:e.empty?this:oa(this,e)}mapDesc(e,t=!1){return e.empty?this:Nr(this,e,t)}mapPos(e,t=-1,i=oe.Simple){let r=0,s=0;for(let o=0;o<this.sections.length;){let l=this.sections[o++],a=this.sections[o++],h=r+l;if(a<0){if(h>e)return s+(e-r);s+=l}else{if(i!=oe.Simple&&h>=e&&(i==oe.TrackDel&&r<e&&h>e||i==oe.TrackBefore&&r<e||i==oe.TrackAfter&&h>e))return null;if(h>e||h==e&&t<0&&!l)return e==r||t<0?s:s+a;s+=a}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i<this.sections.length&&r<=t;){let s=this.sections[i++],o=this.sections[i++],l=r+s;if(o>=0&&r<=t&&l>=e)return r<e&&l>t?"cover":!0;r=l}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let i=this.sections[t++],r=this.sections[t++];e+=(e?" ":"")+i+(r>=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new n(e)}static create(e){return new n(e)}},he=class n extends tt{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ir(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Nr(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r<t.length;r+=2){let o=t[r],l=t[r+1];if(l>=0){t[r]=l,t[r+1]=o;let a=r>>1;for(;i.length<a;)i.push(j.empty);i.push(o?e.slice(s,s+o):j.empty)}s+=o}return new n(t,i)}compose(e){return this.empty?e:e.empty?this:oa(this,e,!0)}map(e,t=!1){return e.empty?this:Nr(this,e,t,!0)}iterChanges(e,t=!1){Ir(this,e,t)}get desc(){return tt.create(this.sections)}filter(e){let t=[],i=[],r=[],s=new Dt(this);e:for(let o=0,l=0;;){let a=o==e.length?1e9:e[o++
Line truncated
|
||||
`}get readOnly(){return this.facet(da)}phrase(e,...t){for(let i of this.facet(n.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let s=+(r||1);return!s||s>t.length?i:t[s-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let s of this.facet(aa))for(let o of s(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&r.push(o[e]);return r}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return Od(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),s=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=ie(t,o,!1);if(s(t.slice(a,o))!=Ce.Word)break;o=a}for(;l<r;){let a=ie(t,l);if(s(t.slice(l,a))!=Ce.Word)break;l=a}return o==l?null:S.range(o+i,l+i)}};V.allowMultipleSelections=Gr;V.tabSize=X.define({combine:n=>n.length?n[0]:4});V.lineSeparator=ha;V.readOnly=da;V.phrases=X.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(r=>n[r]==e[r])}});V.languageData=aa;V.changeFilter=fa;V.transactionFilter=ca;V.transactionExtender=ua;Li.reconfigure=_.define();function zi(n,e,t={}){let i={};for(let r of n)for(let s of Object.keys(r)){let o=r[s],l=i[s];if(l===void 0)i[s]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,s))i[s]=t[s](l,o);else throw new Error("Config merge conflict for field "+s)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}var Xe=class{eq(e){return this==e}range(e,t=e){return Yi.create(e,t,this)}};Xe.prototype.startSide=Xe.prototype.endSide=0;Xe.prototype.point=!1;Xe.prototype.mapMode=oe.TrackDel;function ls(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}var Yi=class n{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new n(e,t,i)}};function es(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var ts=class n{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return ni(this.to)}findIndex(e,t,i,r=0){let s=i?this.to:this.from;for(let o=r,l=s.length;;){if(o==l)return o;let a=o+l>>1,h=s[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,r){for(let s=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,s);s<o;s++)if(r(this.from[s]+e,this.to[s]+e,this.value[s])===!1)return!1}map(e,t,i,r,s){let o=[],l=[],a=[],h=-1,f=-1;e:for(let c=0;c<this.value.length;c++){let u=this.value[c],d=this.from[c]+e,O=this.to[c]+e,p,g;if(d==O){let b=t.mapPos(d,u.startSide,u.mapMode);if(b==null||(p=g=b,u.startSide!=u.endSide&&(g=t.mapPos(d,u.endSide),g<p)))continue}else if(p=t.mapPos(d,u.startSide),g=t.mapPos(O,u.endSide),p>g||p==g&&u.startSide>0&&u.endSide<=0)continue;if(!((g-p||u.endSide-u.startSide)<0))if(h<0&&(h=p),u.point&&(f=Math.max(f,g-p)),(p-i||u.startSide-r)>=0)o.push(u),l.push(p-h),a.push(g-h),i=g,r=u.endSide;else{if(p==g)for(let b=o.length;b>0;b--){if((p-(a[b-1]+h)||u.startSide-o[b-1].endSide)>=0){o.splice(b,0,u),l.splice(b,0,p-h),a.splice(b,0,g-h);continue e}if((p-(l[b-1]+h)||u.endSide-o[b-1].startSide)>0)break}s(p,g,u)}}return{mapped:o.length?new n(l,a,o,f):null,pos:h}}},I=class n{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new n(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:s=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(es)),this.isEmpty)return t.length?n.of(t):this;let l=new Yn(this,null,-1).goto(0),a=0,h=[],f=new zt;for(;l.value||a<t.length;)if(a<t.length&&(l.from-t[a].from||l.startSide-t[a].value.startSide)>=0){let c=t[a++];f.addInner(c.from,c.to,c.value,!1)||h.push(c)}else l.rangeIndex==1&&l.chunkIndex<this.chunk.length&&(a==t.length||this.chunkEnd(l.chunkIndex)<t[a].from)&&(!o||r>this.chunkEnd(l.chunkIndex)||s<this.chunkPos[l.chunkIndex])&&f.addChunk(this.chunkPos[l.chunkIndex],this.chunk[l.chunkIndex])?l.nextChunk():((!o||r>l.to||s<l.from||o(l.from,l.to,l.value))&&(f.addInner(l.from,l.to,l.value,!1)||h.push(Yi.create(l.from,l.to,l.value))),l.next());return f.finishInner(this.nextLayer.isEmpty&&!h.length?n.empty:this.nextLayer.update({add:h,filter:o,filterFrom:r,filterTo:s}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],r=-1,s,o=(a,h,f)=>{s||(s=new zt),s.addRange(a,h,f,!1)};for(let a=0;a<this.chunk.length;a++){let h=this.chunkPos[a],f=this.chunk[a],c=e.touchesRange(h,h+f.length);if(c===!1)r=Math.max(r,f.maxPoint),t.push(f),i.push(e.mapPos(h));else if(c===!0){let[u,d]=t.length?[ni(i)+ni(t).length,ni(ni(t).value).endSide]:[-1,-1],{mapped:O,pos:p}=f.map(h,e,u,d,o);O&&(r=Math.max(r,O.maxPoint),t.push(O),i.push(p))}}let l=this.nextLayer.map(e);return s&&(l=s.finishInner(l)),t.length==0?l:new n(i,t,l||n.emp
Line truncated
|
||||
`)}static newName(){let e=ba[ga]||1;return ba[ga]=e+1,"\u037C"+e.toString(36)}static mount(e,t,i){let r=e[as],s=i&&i.nonce;r?s&&r.setNonce(s):r=new hs(e,s),r.mount(Array.isArray(t)?t:[t],e)}},Sa=new Map,hs=class{constructor(e,t){let i=e.ownerDocument||e,r=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let s=Sa.get(i);if(s)return e[as]=s;this.sheet=new r.CSSStyleSheet,Sa.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[as]=this}mount(e,t){let i=this.sheet,r=0,s=0,o=!1;for(let l=0;l<e.length;l++){let a=e[l],h=this.modules.indexOf(a);if(h<s&&h>-1&&(this.modules.splice(h,1),o=!0,s--,h=-1),h==-1){if(this.modules.splice(s++,0,a),o=!0,i)for(let f=0;f<a.rules.length;f++)i.insertRule(a.rules[f],r++)}else{for(;s<h;)r+=this.modules[s++].rules.length;r+=a.rules.length,s++}}if(i)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{if(o){let a="";for(let h=0;h<this.modules.length;h++)a+=this.modules[h].getRules()+`
|
||||
`;this.styleTag.textContent=a}let l=t.head||t;this.styleTag.parentNode!=l&&l.insertBefore(this.styleTag,l.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var nt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},ai={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},md=typeof navigator<"u"&&/Mac/.test(navigator.platform),gd=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(te=0;te<10;te++)nt[48+te]=nt[96+te]=String(te);var te;for(te=1;te<=24;te++)nt[te+111]="F"+te;var te;for(te=65;te<=90;te++)nt[te]=String.fromCharCode(te+32),ai[te]=String.fromCharCode(te);var te;for(_n in nt)ai.hasOwnProperty(_n)||(ai[_n]=nt[_n]);var _n;function Qa(n){var e=md&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||gd&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?ai:nt)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}var fe=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},ps=typeof document<"u"?document:{documentElement:{style:{}}},ms=/Edge\/(\d+)/.exec(fe.userAgent),Ua=/MSIE \d/.test(fe.userAgent),gs=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(fe.userAgent),lr=!!(Ua||gs||ms),ya=!lr&&/gecko\/(\d+)/i.test(fe.userAgent),fs=!lr&&/Chrome\/(\d+)/.exec(fe.userAgent),ka="webkitFontSmoothing"in ps.documentElement.style,bs=!lr&&/Apple Computer/.test(fe.vendor),xa=bs&&(/Mobile\/\w+/.test(fe.userAgent)||fe.maxTouchPoints>2),w={mac:xa||/Mac/.test(fe.platform),windows:/Win/.test(fe.platform),linux:/Linux|X11/.test(fe.platform),ie:lr,ie_version:Ua?ps.documentMode||6:gs?+gs[1]:ms?+ms[1]:0,gecko:ya,gecko_version:ya?+(/Firefox\/(\d+)/.exec(fe.userAgent)||[0,0])[1]:0,chrome:!!fs,chrome_version:fs?+fs[1]:0,ios:xa,android:/Android\b/.test(fe.userAgent),webkit:ka,webkit_version:ka?+(/\bAppleWebKit\/(\d+)/.exec(fe.userAgent)||[0,0])[1]:0,safari:bs,safari_version:bs?+(/\bVersion\/(\d+(\.\d+)?)/.exec(fe.userAgent)||[0,0])[1]:0,tabSize:ps.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function to(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}var Gn=Object.create(null);function io(n,e,t){if(n==e)return!0;n||(n=Gn),e||(e=Gn);let i=Object.keys(n),r=Object.keys(e);if(i.length-0!=r.length-0)return!1;for(let s of i)if(s!=t&&(r.indexOf(s)==-1||n[s]!==e[s]))return!1;return!0}function bd(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function wa(n,e,t){let i=!1;if(e)for(let r in e)t&&r in t||(i=!0,r=="style"?n.style.cssText="":n.removeAttribute(r));if(t)for(let r in t)e&&e[r]==t[r]||(i=!0,r=="style"?n.style.cssText=t[r]:n.setAttribute(r,t[r]));return i}function Sd(n){let e=Object.create(null);for(let t=0;t<n.attributes.length;t++){let i=n.attributes[t];e[i.name]=i.value}return e}var Fe=class{eq(e){return!1}updateDOM(e,t,i){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,i){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}},je=(function(n){return n[n.Text=0]="Text",n[n.WidgetBefore=1]="WidgetBefore",n[n.WidgetAfter=2]="WidgetAfter",n[n.WidgetRange=3]="WidgetRange",n})(je||(je={})),W=class extends Xe{constructor(e,t,i,r){super(),this.startSide=e,this.endSide=t,this.widget=i,this.spec=r}get heightRelevant(){return!1}static mark(e){return new Fi(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),i=!!e.block;return t+=i&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new Wt(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,r;if(e.isBlockGap)i=-5e8,r=4e8;else{let{start:s,end:o}=Ga(e,t);i=(s?t?-3e8:-1:5e8)-1,r=(o?t?2e8:1:-6e8)+1}return new Wt(e,i,r,t,e.widget||null,!0)}static line(e){return new Hi(e)}static set(e,t=!1){return I.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};W.none=I.empty;var Fi=class n extends W{constructor(e){let{start:t,end:i}=Ga(e);super(t?-1:5e8,i?1:-6e8,null,e),this.taLine truncated
|
||||
`,r=n.state.doc.line(r.number+(t?1:-1)),s=n.bidiSpans(r),h=t?S.cursor(r.from,-1):S.cursor(r.to,1)}if(a){if(!a(f))return l}else{if(!i)return h;a=i(f)}l=h}}function eO(n,e,t){let i=n.state.charCategorizer(e),r=i(t);return s=>{let o=i(s);return r==Ce.Space&&(r=o),r==o}}function tO(n,e,t,i){let r=e.head,s=t?1:-1;if(r==(t?n.state.doc.length:0))return S.cursor(r,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(r,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),f=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=s<0?h.top:h.bottom;else{let O=n.viewState.lineBlockAt(r);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(r-O.from))),l=(s<0?O.top:O.bottom)+f}let c=a.left+o,u=n.viewState.heightOracle.textHeight>>1,d=i??u;for(let O=0;;O+=u){let p=l+(d+O)*s,g=Rs(n,{x:c,y:p},!1,s);if(t?p>a.bottom:p<a.top)return S.cursor(g.pos,g.assoc);let b=n.coordsAtPos(g.pos,g.assoc),k=b?(b.top+b.bottom)/2:0;if(!b||(t?k>l:k<l))return S.cursor(g.pos,g.assoc,void 0,o)}}function Ui(n,e,t){for(;;){let i=0;for(let r of n)r.between(e-1,e+1,(s,o,l)=>{if(e>s&&e<o){let a=i||t||(e-s<o-e?-1:1);e=a<0?s:o,i=a}});if(!i)return e}}function Ph(n,e){let t=null;for(let i=0;i<e.ranges.length;i++){let r=e.ranges[i],s=null;if(r.empty){let o=Ui(n,r.from,0);o!=r.from&&(s=S.cursor(o,-1))}else{let o=Ui(n,r.from,-1),l=Ui(n,r.to,1);(o!=r.from||l!=r.to)&&(r.undirectional?s=S.undirectionalRange(r.from,r.to):s=S.range(r.from==r.anchor?o:l,r.from==r.head?o:l))}s&&(t||(t=e.ranges.slice()),t[i]=s)}return t?S.create(t,e.mainIndex):e}function ds(n,e,t){let i=Ui(n.state.facet(en).map(r=>r(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:S.cursor(i,i<t.from?1:-1)}var Ae=class{constructor(e,t){this.pos=e,this.assoc=t}};function Rs(n,e,t,i){let r=n.contentDOM.getBoundingClientRect(),s=r.top+n.viewState.paddingTop,{x:o,y:l}=e,a=l-s,h;for(;;){if(a<0)return new Ae(0,1);if(a>n.viewState.docHeight)return new Ae(n.state.doc.length,-1);if(h=n.elementAtHeight(a),i==null)break;if(h.type==je.Text){if(i<0?h.to<n.viewport.from:h.from>n.viewport.to)break;let u=n.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+s:u.bottom>=a+s))break}let c=n.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+c:h.top-c}if(n.viewport.from>=h.to||n.viewport.to<=h.from){if(t)return null;if(h.type==je.Text){let c=Hd(n,r,h,o,l);return new Ae(c,c==h.from?1:-1)}}if(h.type!=je.Text)return a<(h.top+h.bottom)/2?new Ae(h.from,1):new Ae(h.to,-1);let f=n.docView.lineAt(h.from,2);return(!f||f.length!=h.length)&&(f=n.docView.lineAt(h.from,-2)),new Ms(n,o,l,n.textDirectionAt(h.from)).scanTile(f,h.from)}var Ms=class{constructor(e,t,i,r){this.view=e,this.x=t,this.y=i,this.baseDir=r,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to<e)&&(this.line=this.view.state.doc.lineAt(e),this.spans=this.view.bidiSpans(this.line)),this}baseDirAt(e,t){let{line:i,spans:r}=this.bidiSpansAt(e);return r[Re.find(r,e-i.from,-1,t)].level==this.baseDir}dirAt(e,t){let{line:i,spans:r}=this.bidiSpansAt(e);return r[Re.find(r,e-i.from,-1,t)].dir}bidiIn(e,t){let{spans:i,line:r}=this.bidiSpansAt(e);return i.length>1||i.length&&(i[0].level!=this.baseDir||i[0].to+r.from<t)}scan(e,t,i=!1){let r=0,s=e.length-1,o=new Set,l=this.bidiIn(e[0],e[s]),a,h,f=-1,c=1e9,u;e:for(;r<s;){let O=s-r,p=r+s>>1;t:if(o.has(p)){for(let k=1;k<O;k++){let Q=p+k;if(Q>=s&&(Q-=O),!o.has(Q)){p=Q;break t}}break e}o.add(p);let g=t(p),b=0;if(g)for(let k=0;k<g.length;k++){let Q=g[k];if(!(Q.width==0&&g.length>1))if(Q.bottom<this.y)(!a||a.bottom<Q.bottom)&&(a=Q),b=1;else if(Q.top>this.y)(!h||h.top>Q.top)&&(h=Q),b=-1;else{let A=Q.left>this.x?this.x-Q.left:Q.right<this.x?this.x-Q.right:0,$=Math.abs(A);$<c&&(f=p,c=$,u=Q),A&&(b=A<0==(this.baseDir==G.LTR)?-1:1)}}b==-1&&(!l||this.baseDirAt(e[p],1))?s=p:b==1&&(!l||this.baseDirAt(e[p+1],-1))&&(r=p+1)}if(!u){if(!h&&!a)return{i:0,after:!1};let O=a&&(!h||this.y-a.bottom<h.top-this.y)?a:h;return this.y=(O.top+O.bottom)/2,this.scan(e,t,!0)}if(c&&!i){let{top:O,bottom:p}=u;if(a&&a.bottom>(O+O+p)/3)return this.y=a.bottom-1,this.scan(e,t,!0);if(h&&h.top<(O+p+p)/3)return this.y=h.top+1,this.scan(e,t,!0)}let d=(l?this.dirAt(e[f],1):this.baseDir)==G.LTR;return{i:f,after:this.x>(u.left+u.right)/2==d}}scanText(e,t){let i=[];for(let s=0;s<e.length;s=ie(e.text,s))i.push(t+s);i.push(t+e.length);let r=this.scan(i,s=>{let o=i[s]-t,l=i[s+1]-t;return Ji(e.dom,o,l).getClientRects()});return r.after?new Ae(i[r.i+1],-1):new Ae(i[r.i],1)}scanTile(e,t){if(!e.length)return new Ae(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l<e.children.length;l++)i.push(a+=e.children[l].length);let r=this.scan(i,l=>{let a=e.children[l];return a.flags&48?null:(ne(a.dom)?a.dom:Ji(a.dom,0,a.length)).getClientRects()}),s=e.children[r.i],o=i[r.i];return s.isText()?this.scanText(s,o):s.isComposite()?this.scanTile(s,o):r.after?new Ae(i[r.i+1],-1):new Ae(o,1)}},hi="\uFFFF",js=class{cons
Line truncated
|
||||
`&&n.lineWrapping&&(i&&(i=S.single(i.main.anchor-1,i.main.head-1)),t={from:s.from,to:s.to,insert:j.of([" "])}),t)return ao(n,t,i,o);if(i&&!Es(i,s)){let l=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(l=!0),a=n.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=Ph(r.facet(en).map(h=>h(n)),i))),n.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function ao(n,e,t,i=-1){if(w.ios&&n.inputState.flushIOSKey(e))return!0;let r=n.state.selection.main;if(w.android&&(e.to==r.to&&(e.from==r.from||e.from==r.from-1&&n.state.sliceDoc(e.from,r.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&di(n.contentDOM,"Enter",13)||(e.from==r.from-1&&e.to==r.to&&e.insert.length==0||i==8&&e.insert.length<e.to-e.from&&e.to>r.head)&&di(n.contentDOM,"Backspace",8)||e.from==r.from&&e.to==r.to+1&&e.insert.length==0&&di(n.contentDOM,"Delete",46)))return!0;let s=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=rO(n,e,t));return n.state.facet(dh).some(a=>a(n,e.from,e.to,s,l))||n.dispatch(l()),!0}function rO(n,e,t){let i,r=n.state,s=r.selection.main,o=-1;if(e.from==e.to&&e.from<s.from||e.from>s.to){let a=e.from<s.from?-1:1,h=a<0?s.from:s.to,f=Ui(r.facet(en).map(c=>c(n)),h,a);e.from==f&&(o=f)}if(o>-1)i={changes:e,selection:S.cursor(e.from+e.insert.length,-1)};else if(e.from>=s.from&&e.to<=s.to&&e.to-e.from>=(s.to-s.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=s.from<e.from?r.sliceDoc(s.from,e.from):"",h=s.to>e.to?r.sliceDoc(e.to,s.to):"";i=r.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let a=r.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=s.to+10&&e.to>=s.to-10){let f=n.state.sliceDoc(e.from,e.to),c,u=t&&$h(n,t.main.head);if(u){let O=e.insert.length-(e.to-e.from);c={from:u.from,to:u.to-O}}else c=n.state.doc.lineAt(s.head);let d=s.to-e.to;i=r.changeByRange(O=>{if(O.from==s.from&&O.to==s.to)return{changes:a,range:h||O.map(a)};let p=O.to-d,g=p-f.length;if(n.state.sliceDoc(g,p)!=f||p>=c.from&&g<=c.to)return{range:O};let b=r.changes({from:g,to:p,insert:e.insert}),k=O.to-s.to;return{changes:b,range:h?S.range(Math.max(0,h.anchor+k),Math.max(0,h.head+k)):O.map(b)}})}else i={changes:a,selection:h&&r.selection.replaceRange(h)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),r.update(i,{userEvent:l,scrollIntoView:!0})}function Xh(n,e,t,i){let r=Math.min(n.length,e.length),s=0;for(;s<r&&n.charCodeAt(s)==e.charCodeAt(s);)s++;if(s==r&&n.length==e.length)return null;let o=n.length,l=e.length;for(;o>0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,s-Math.min(o,l));t-=o+a-s}if(o<s&&n.length<e.length){let a=t<=s&&t>=o?s-t:0;s-=a,l=s+(l-o),o=s}else if(l<s){let a=t<=s&&t>=l?s-t:0;s-=a,o=s+(o-l),l=s}return{from:s,toA:o,toB:l}}function sO(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:s}=n.observer.selectionRange;return t&&(e.push(new ir(t,i)),(r!=t||s!=i)&&e.push(new ir(r,s))),e}function oO(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t<0||i<0?null:t==i?S.create([S.cursor(i+e,-1)]):S.single(t+e,i+e)}function Es(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}var Ys=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,w.safari&&e.contentDOM.addEventListener("input",()=>null),w.gecko&&yO(e.contentDOM.ownerDocument)}handleEvent(e){!OO(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let r of i.observers)r(this.view,t);for(let r of i.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDef
Line truncated
|
||||
`))};if((w.mac||w.android)&&c.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(c={from:l,to:a,insert:j.of([i.text.replace("."," ")])}),this.pendingContextChange=c,!e.state.readOnly){let u=this.to-this.from+(c.to-c.from+c.insert.length);ao(e,c,S.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),c.from<c.to&&!c.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let r=[],s=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o<l;o++){let a=e.coordsForChar(o);s=a&&new DOMRect(a.left,a.top,a.right-a.left,a.bottom-a.top)||s||new DOMRect,r.push(s)}t.updateCharacterBounds(i.rangeStart,r)},this.handlers.textformatupdate=i=>{let r=[];for(let s of i.getTextFormats()){let o=s.underlineStyle,l=s.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(s.rangeStart),h=this.toEditorPos(s.rangeEnd);if(a<h){let f=`text-decoration: underline ${/^[a-z]/.test(o)?o+" ":o=="Dashed"?"dashed ":o=="Squiggle"?"wavy ":""}${/thin/i.test(l)?1:2}px`;r.push(W.mark({attributes:{style:f}}).range(a,h))}}}e.dispatch({effects:gh.of(W.set(r))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let r=Ki(i.root);r&&r.rangeCount&&this.editContext.updateSelectionBounds(r.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,r=this.pendingContextChange;return e.changes.iterChanges((s,o,l,a,h)=>{if(i)return;let f=h.length-(o-s);if(r&&o>=r.to)if(r.from==s&&r.to==o&&r.insert.eq(h)){r=this.pendingContextChange=null,t+=f,this.to+=f;return}else r=null,this.revertPending(e.state);if(s+=t,o+=t,o<=this.from)this.from+=f,this.to+=f;else if(s<this.to){if(s<this.from||o>this.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(s),this.toContextPos(o),h.toString()),this.to+=f}t+=f}),r&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(r=>!r.isUserEvent("input.type")&&r.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),r=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=r)&&this.editContext.updateSelection(i,r)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},Z=class n{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.clearAnnouncement=-1,this.contentDOM=document.createElement(
Line truncated
|
||||
`+t.scrub(),s=this.advance(r);return s>-1&&s<r.length?this.complete(e,i,s):!1}finish(e,t){return(this.stage==2||this.stage==3)&&On(t.content,this.pos)==t.content.length?this.complete(e,t,t.content.length):!1}complete(e,t,i){return e.addLeafElement(t,Y(y.LinkReference,this.start,this.start+i,this.elts)),!0}nextStage(e){return e?(this.pos=e.to-this.start,this.elts.push(e),this.stage++,!0):(e===!1&&(this.stage=-1),!1)}advance(e){for(;;){if(this.stage==-1)return-1;if(this.stage==0){if(!this.nextStage(Df(e,this.pos,this.start,!0)))return-1;if(e.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(Y(y.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(_f(e,On(e,this.pos),this.start)))return-1}else if(this.stage==2){let t=On(e,this.pos),i=0;if(t>this.pos){let r=zf(e,t,this.start);if(r){let s=Yo(e,r.to-this.start);s>0&&(this.nextStage(r),i=s)}}return i||(i=Yo(e,this.pos)),i>0&&i<e.length?i:-1}else return Yo(e,this.pos)}}};function Yo(n,e){for(;e<n.length;e++){let t=n.charCodeAt(e);if(t==10)break;if(!we(t))return-1}return e}var Vo=class{nextLine(e,t,i){let r=t.depth<e.stack.length?-1:Af(t),s=t.next;if(r<0)return!1;let o=Y(y.HeaderMark,e.lineStart+t.pos,e.lineStart+r);return e.nextLine(),e.addLeafElement(i,Y(s==61?y.SetextHeading1:y.SetextHeading2,i.start,e.prevLineEnd(),[...e.parser.parseInline(i.content,i.start),o])),!0}finish(){return!1}},Lf={LinkReference(n,e){return e.content.charCodeAt(0)==91?new Wo(e):null},SetextHeading(){return new Vo}},Xp=[(n,e)=>Zf(e)>=0,(n,e)=>Cf(e)>=0,(n,e)=>Xf(e)>=0,(n,e)=>Ko(e,n,!0)>=0,(n,e)=>Jo(e,n,!0)>=0,(n,e)=>Ho(e,n,!0)>=0,(n,e)=>jf(e,n,!0)>=0],Tp={text:"",end:0},Io=class{constructor(e,t,i,r){this.parser=e,this.input=t,this.ranges=r,this.line=new Do,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=r[r.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=r[0].from,this.block=$r.create(y.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=i.length?new Go(i,t):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:e}=this;for(;;){for(let i=0;;){let r=e.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;i<e.markers.length&&(!r||e.markers[i].from<r.end);){let s=e.markers[i++];this.addNode(s.type,s.from,s.to)}if(!r)break;this.finishContext()}if(e.pos<e.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(e.basePos))return null;e:for(;;){for(let i of this.parser.blockParsers)if(i){let r=i(this,e);if(r!=!1){if(r==!0)return null;e.forward();continue e}}break}if(e.pos==e.text.length)return this.nextLine()?null:this.finish();let t=new zo(this.lineStart+e.pos,e.text.slice(e.pos));for(let i of this.parser.leafBlockParsers)if(i){let r=i(this,t);r&&t.parsers.push(r)}e:for(;this.nextLine()&&e.pos!=e.text.length;){if(e.indent<e.baseIndent+4){for(let i of this.parser.endLeafBlock)if(i(this,e,t))break e}for(let i of t.parsers)if(i.nextLine(this,e,t))return null;t.content+=`
|
||||
`+e.scrub();for(let i of e.markers)t.marks.push(i)}return this.finishLeaf(t),null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}reuseFragment(e){if(!this.fragments.moveTo(this.absoluteLineStart+e,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let t=this.fragments.takeNodes(this);return t?(this.absoluteLineStart+=t,this.lineStart=qf(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(e=this.depth-1){return this.parser.nodeSet.types[this.stack[e].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(e){let t=Tp;if(t.end=e,e>=this.to)t.text="";else if(t.text=this.lineChunkAt(e),t.end+=t.text.length,this.ranges.length>1){let i=this.absoluteLineStart,r=this.rangeI;for(;this.ranges[r].to<t.end;){r++;let s=this.ranges[r].from,o=this.lineChunkAt(s);t.end=s+o.length,t.text=t.text.slice(0,this.ranges[r-1].to-i)+o,i=t.end-t.text.length}}return t}readLine(){let{line:e}=this,{text:t,end:i}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=i,e.reset(t);e.depth<this.stack.length;e.depth++){let r=this.stack[e.depth],s=this.parser.skipContextMarkup[r.type];if(!s)throw new Error("Unhandled block context "+y[r.type]);let o=this.line.markers.length;if(!s(r,this,e)){this.line.markers.length>o&&(r.end=this.line.markers[this.line.markers.length-1].to),e.forward();break}e.forward()}}lineChunkAt(e){let t=this.input.chunk(e),i;if(this.input.lineChunks)i=t==`
|
||||
`?"":t;else{let r=t.indexOf(`
|
||||
`);i=r<0?t:t.slice(0,r)}return e+i.length>this.to?i.slice(0,this.to-e):i}prevLineEnd(){return this.atEnd?this.lineStart:this.lineStart-1}startContext(e,t,i=0){this.block=$r.create(e,i,this.lineStart+t,this.block.hash,this.lineStart+this.line.text.length),this.stack.push(this.block)}startComposite(e,t,i=0){this.startContext(this.parser.getNodeType(e),t,i)}addNode(e,t,i){typeof e=="number"&&(e=new E(this.parser.nodeSet.types[e],Ci,Ci,(i??this.prevLineEnd())-t)),this.block.addChild(e,t-this.block.from)}addElement(e){this.block.addChild(e.toTree(this.parser.nodeSet),e.from-this.block.from)}addLeafElement(e,t){this.addNode(this.buffer.writeElements(Uo(t.children,e.marks),-t.from).finish(t.type,t.to-t.from),t.from)}finishContext(){let e=this.stack.pop(),t=this.stack[this.stack.length-1];t.addChild(e.toTree(this.parser.nodeSet),e.from-t.from),this.block=t}finish(){for(;this.stack.length>1;)this.finishContext();return this.addGaps(this.block.toTree(this.parser.nodeSet,this.lineStart))}addGaps(e){return this.ranges.length>1?Ef(this.ranges,0,e.topNode,this.ranges[0].from,this.reusePlaceholders):e}finishLeaf(e){for(let i of e.parsers)if(i.finish(this,e))return;let t=Uo(this.parser.parseInline(e.content,e.start),e.marks);this.addNode(this.buffer.writeElements(t,-e.start).finish(y.Paragraph,e.content.length),e.start)}elt(e,t,i,r){return typeof e=="string"?Y(this.parser.getNodeType(e),t,i,r):new vr(e,t)}get buffer(){return new Pr(this.parser.nodeSet)}};function Ef(n,e,t,i,r){let s=n[e].to,o=[],l=[],a=t.from+i;function h(f,c){for(;c?f>=s:f>s;){let u=n[e+1].from-s;i+=u,f+=u,e++,s=n[e].to}}for(let f=t.firstChild;f;f=f.nextSibling){h(f.from+i,!0);let c=f.from+i,u,d=r.get(f.tree);d?u=d:f.to+i>s?(u=Ef(n,e,f,i,r),h(f.to+i,!1)):u=f.toTree(),o.push(u),l.push(c-a)}return h(t.to+i,!1),new E(t.type,o,l,t.to+i-a,t.tree?t.tree.propValues:void 0)}var mn=class n extends xt{constructor(e,t,i,r,s,o,l,a,h){super(),this.nodeSet=e,this.blockParsers=t,this.leafBlockParsers=i,this.blockNames=r,this.endLeafBlock=s,this.skipContextMarkup=o,this.inlineParsers=l,this.inlineNames=a,this.wrappers=h,this.nodeTypes=Object.create(null);for(let f of e.types)this.nodeTypes[f.name]=f.id}createParse(e,t,i){let r=new Io(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}configure(e){let t=No(e);if(!t)return this;let{nodeSet:i,skipContextMarkup:r}=this,s=this.blockParsers.slice(),o=this.leafBlockParsers.slice(),l=this.blockNames.slice(),a=this.inlineParsers.slice(),h=this.inlineNames.slice(),f=this.endLeafBlock.slice(),c=this.wrappers;if(dn(t.defineNodes)){r=Object.assign({},r);let u=i.types.slice(),d;for(let O of t.defineNodes){let{name:p,block:g,composite:b,style:k}=typeof O=="string"?{name:O}:O;if(u.some($=>$.name==p))continue;b&&(r[u.length]=($,P,v)=>b(P,v,$.value));let Q=u.length,A=b?["Block","BlockContext"]:g?Q>=y.ATXHeading1&&Q<=y.SetextHeading2?["Block","LeafBlock","Heading"]:["Block","LeafBlock"]:void 0;u.push(J.define({id:Q,name:p,props:A&&[[T.group,A]]})),k&&(d||(d={}),Array.isArray(k)||k instanceof xe?d[p]=k:Object.assign(d,k))}i=new yt(u),d&&(i=i.extend(De(d)))}if(dn(t.props)&&(i=i.extend(...t.props)),dn(t.remove))for(let u of t.remove){let d=this.blockNames.indexOf(u),O=this.inlineNames.indexOf(u);d>-1&&(s[d]=o[d]=void 0),O>-1&&(a[O]=void 0)}if(dn(t.parseBlock))for(let u of t.parseBlock){let d=l.indexOf(u.name);if(d>-1)s[d]=u.parse,o[d]=u.leaf;else{let O=u.before?wr(l,u.before):u.after?wr(l,u.after)+1:l.length-1;s.splice(O,0,u.parse),o.splice(O,0,u.leaf),l.splice(O,0,u.name)}u.endLeaf&&f.push(u.endLeaf)}if(dn(t.parseInline))for(let u of t.parseInline){let d=h.indexOf(u.name);if(d>-1)a[d]=u.parse;else{let O=u.before?wr(h,u.before):u.after?wr(h,u.after)+1:h.length-1;a.splice(O,0,u.parse),h.splice(O,0,u.name)}}return t.wrap&&(c=c.concat(t.wrap)),new n(i,s,o,l,f,r,a,h,c)}getNodeType(e){let t=this.nodeTypes[e];if(t==null)throw new RangeError(`Unknown node type '${e}'`);return t}parseInline(e,t){let i=new Kt(this,e,t);e:for(let r=t;r<i.end;){let s=i.char(r);for(let o of this.inlineParsers)if(o){let l=o(i,s,r);if(l>=0){r=l;continue e}}r++}return i.resolveMarkers(0)}};function dn(n){return n!=null&&n.length>0}function No(n){if(!Array.isArray(n))return n;if(n.length==0)return null;let e=No(n[0]);if(n.length==1)return e;let t=No(n.slice(1));if(!t||!e)return e||t;let i=(o,l)=>(o||Ci).concat(l||Ci),r=e.wrap,s=t.wrap;return{props:i(e.props,t.props),defineNodes:i(e.defineNodes,t.defineNodes),parseBlock:i(e.parseBlock,t.parseBlock),parseInline:i(e.parseInline,t.parseInline),remove:i(e.remove,t.remove),wrap:r?s?(o,l,a,h)=>r(s(o,l,a,h),l,a,h):r:s}}function wr(n,e){let t=n.indexOf(e);if(t<0)throw new RangeError(`Position specified relative to unknown parser ${e}`);return t}var Yf=[J.none];for(let n=1,e;e=y[n];n++)Yf[n]=J.define({id:n,name:e,props:n>=y.Escape?[]:[[T.group,n in vf?["Block","BlockContext"]:["Block","LeafBlock"]]],top:e=="Document"});var Ci=[],Pr=class{constructor(e){this.nodeSet=e,this.content=[],this.nodes=[]}write(e,t,i,r=0){return thi
Line truncated
|
||||
`;)s--;this.fragmentEnd=s?s-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(M.IncludeAnonymous|M.IgnoreMounts),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;for(;t&&t.type.isAnonymous&&t.children[0]instanceof E;)t=t.children[0];return t&&t.prop(T.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),s=e.absoluteLineStart,o=s,l=e.block.children.length,a=e.lineStart-e.block.from>>2,h=o,f=l;e:for(;;){if(t.to-i>Math.min(r,e.to)||t.type.isAnonymous&&t.tree&&(t.to-t.from>a||!Ap(t.tree))){if(t.type.isAnonymous&&t.firstChild())continue;break}let c=qf(t.from-i,e.ranges);if(t.to-i<=e.ranges[e.rangeI].to)e.addNode(t.tree,c);else{let u=new E(e.parser.nodeSet.types[y.Paragraph],[],[],0,e.block.hashProp);e.reusePlaceholders.set(u,t.tree),e.addNode(u,c)}for((t.type.isAnonymous||t.type.is("Block"))&&(t.type.isAnonymous||Bf.indexOf(t.type.id)<0?(o=t.to-i,l=e.block.children.length):(o=h,l=f),h=t.to-i,f=e.block.children.length);;){if(t.nextSibling())continue e;if(!t.parent()||!t.type.isAnonymous)break e}}for(;e.block.children.length>l;)e.block.children.pop(),e.block.positions.pop();return o-s}};function Ap(n){for(;n.type.isAnonymous;){let e=n.children[n.children.length-1];if(e instanceof E)n=e;else return!1}return n.type.is("Block")&&Bf.indexOf(n.type.id)<0}function qf(n,e){let t=n;for(let i=1;i<e.length;i++){let r=e[i-1].to,s=e[i].from;r<n&&(t-=s-r)}return t}var Rp=De({"Blockquote/...":m.quote,HorizontalRule:m.contentSeparator,"ATXHeading1/... SetextHeading1/...":m.heading1,"ATXHeading2/... SetextHeading2/...":m.heading2,"ATXHeading3/...":m.heading3,"ATXHeading4/...":m.heading4,"ATXHeading5/...":m.heading5,"ATXHeading6/...":m.heading6,"Comment CommentBlock":m.comment,Escape:m.escape,Entity:m.character,"Emphasis/...":m.emphasis,"StrongEmphasis/...":m.strong,"Link/... Image/...":m.link,"OrderedList/... BulletList/...":m.list,"BlockQuote/...":m.quote,"InlineCode CodeText":m.monospace,"URL Autolink":m.url,"HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark":m.processingInstruction,"CodeInfo LinkLabel":m.labelName,LinkTitle:m.string,Paragraph:m.content}),Wf=new mn(new yt(Yf).extend(Rp),Object.keys(xr).map(n=>xr[n]),Object.keys(xr).map(n=>Lf[n]),Object.keys(xr),Xp,vf,Object.keys(_o).map(n=>_o[n]),Object.keys(_o),[]);function Mp(n,e,t){let i=[];for(let r=n.firstChild,s=e;;r=r.nextSibling){let o=r?r.from:t;if(o>s&&i.push({from:s,to:o}),!r)break;s=r.to}return i}function Vf(n){let{codeParser:e,htmlParser:t}=n;return{wrap:pr((r,s)=>{let o=r.type.id;if(e&&(o==y.CodeBlock||o==y.FencedCode)){let l="";if(o==y.FencedCode){let h=r.node.getChild(y.CodeInfo);h&&(l=s.read(h.from,h.to))}let a=e(l);if(a)return{parser:a,overlay:h=>h.type.id==y.CodeText,bracketed:o==y.FencedCode}}else if(t&&(o==y.HTMLBlock||o==y.HTMLTag||o==y.CommentBlock))return{parser:t,overlay:Mp(r.node,r.from,r.to)};return null})}}var jp={resolve:"Strikethrough",mark:"StrikethroughMark"},Lp={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":m.strikethrough}},{name:"StrikethroughMark",style:m.processingInstruction}],parseInline:[{name:"Strikethrough",parse(n,e,t){if(e!=126||n.char(t+1)!=126||n.char(t+2)==126)return-1;let i=n.slice(t-1,t),r=n.slice(t+2,t+3),s=/\s|^$/.test(i),o=/\s|^$/.test(r),l=gn.test(i),a=gn.test(r);return n.addDelimiter(jp,t,t+2,!o&&(!a||s||l),!s&&(!l||o||a))},after:"Emphasis"}]};function pn(n,e,t=0,i,r=0){let s=0,o=!0,l=-1,a=-1,h=!1,f=()=>{i.push(n.elt("TableCell",r+l,r+a,n.parser.parseInline(e.slice(l,a),r+l)))};for(let c=t;c<e.length;c++){let u=e.charCodeAt(c);u==124&&!h?((!o||l>-1)&&s++,o=!1,i&&(l>-1&&f(),i.push(n.elt("TableDelimiter",c+r,c+r+1))),l=a=-1):(h||u!=32&&u!=9)&&(l<0&&(l=c),a=c+1),h=!h&&u==92}return l>-1&&(s++,i&&f()),s}function Qf(n,e){for(let t=e;t<n.length;t++){let i=n.charCodeAt(t);if(i==124)return!0;i==92&&t++}return!1}var If=/^[>\s]*\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?$/,Xr=class{constructor(){this.rows=null}nextLine(e,t,i){if(this.rows==null){this.rows=!1;let r;if((t.next==45||t.next==58||t.next==124)&&If.test(r=t.text.slice(t.pos))){let s=[];pn(e,i.content,0,s,i.start)==pn(e,r,0)&&(this.rows=[e.elt("TableHeader",i.start,i.start+i.content.length,s),e.elt("TableDelimiter",e.lineStart+t.pos,e.lineStart+t.text.length)])}}else if(this.rows){let r=[];pn(e,t.text,t.pos,r,e.lineStart),this.rows.push(e.elt("TableRow",e.lineStart+t.pos,e.lineStart+t.text.length,r))}return!1}finish(e,t){return this.rows?(e.addLeafElement(t,e.elt("Table",t.start,t.start+t.content.length,this.rows)),!0):!1}},Ep={defineNodes:[{name:"Table",block:!0},{name:"TableHeader",style:{"TableHeader/...":m.heading}},"TableRow",{name:"TableCell",style:m.content},{name:"TableDelimiter",style:m.processingInstruction}],parseBlock:[{name:"Table",leaf(n,e){return Qf(e.content,0)?new Xr:null},endLeaf(n,e,t){if(t.parsers.some(r
Line truncated
|
||||
\${}
|
||||
} catch (\${error}) {
|
||||
\${}
|
||||
}`,{label:"try",detail:"/ catch block",type:"keyword"}),de("if (${}) {\n ${}\n}",{label:"if",detail:"block",type:"keyword"}),de(`if (\${}) {
|
||||
\${}
|
||||
} else {
|
||||
\${}
|
||||
}`,{label:"if",detail:"/ else block",type:"keyword"}),de(`class \${name} {
|
||||
constructor(\${params}) {
|
||||
\${}
|
||||
}
|
||||
}`,{label:"class",detail:"definition",type:"keyword"}),de('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),de('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],_g=Dc.concat([de("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),de("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),de("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Yc=new xi,Bc=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function yn(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}var zg=["FunctionDeclaration"],Dg={FunctionDeclaration:yn("function"),ClassDeclaration:yn("class"),ClassExpression:()=>!0,EnumDeclaration:yn("constant"),TypeAliasDeclaration:yn("type"),NamespaceDeclaration:yn("namespace"),VariableDefinition(n,e){n.matchContext(zg)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function qc(n,e){let t=Yc.get(e);if(t)return t;let i=[],r=!0;function s(o,l){let a=n.sliceString(o.from,o.to);i.push({label:a,type:l})}return e.cursor(M.IncludeAnonymous).iterate(o=>{if(r)r=!1;else if(o.name){let l=Dg[o.name];if(l&&l(o,s)||Bc.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of qc(n,o.node))i.push(l);return!1}}),Yc.set(e,i),i}var _c=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Wc=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Bg(n){let e=D(n.state).resolveInner(n.pos,-1);if(Wc.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&_c.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let r=e;r;r=r.parent)Bc.has(r.name)&&(i=i.concat(qc(n.state.doc,r)));return{options:i,from:t?e.from:n.pos,validFor:_c}}var qe=vt.define({name:"javascript",parser:Ec.configure({props:[ht.add({IfStatement:Pi({except:/^\s*({|else\b)/}),TryStatement:Pi({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:af,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:of({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Pi({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),ft.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":yr,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Vc={test:n=>/^JSX/.test(n.name),facet:an({commentTokens:{block:{open:"{/*",close:"*/}"}}})},Pl=qe.configure({dialect:"ts"},"typescript"),vl=qe.configure({dialect:"jsx",props:[Qr.add(n=>n.isTop?[Vc]:void 0)]}),Cl=qe.configure({dialect:"jsx ts",props:[Qr.add(n=>n.isTop?[Vc]:void 0)]},"typescript"),Ic=n=>({label:n,type:"keyword"}),Nc="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Ic),qg=Nc.concat(["declare","implements","private","protected","public"].map(Ic));function Uc(n={}){let e=n.jsx?n.typescript?Cl:vl:n.typescript?Pl:qe,t=n.typescript?_g.concat(qg):Dc.concat(Nc);return new Be(e,[qe.data.of({autocomplete:df(Wc,uf(t))}),qe.data.of({autocomplete:Bg}),n.jsx?Ig:[]])}function Wg(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function zc(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}var Vg=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Ig=Z.inputHandler.of((n,e,t,i,r)=>{if((Vg?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!qe.isActiveAt(n.state,e,-1))return!1;let s=r(),{state:o}=s,l=o.changeByRange(a=>{var h;let{head:f}=a,c=D(o).resolveInner(f-1,-1),u
Line truncated
|
||||
@@ -42,7 +42,21 @@ import { cleanSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { SERVABLE, TYPES, asset } from "./static.mjs";
|
||||
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
|
||||
import { NotepadError, addImage, addThumb, imagePath, readNotepad, removeImage, saveNote } from "./notepads.mjs";
|
||||
import {
|
||||
NotepadError,
|
||||
addImage,
|
||||
addThumb,
|
||||
createTab,
|
||||
defaultTabId,
|
||||
deleteTab,
|
||||
imagePath,
|
||||
readNotepad,
|
||||
removeImage,
|
||||
renameTab,
|
||||
reorderTabs,
|
||||
saveNote,
|
||||
setLastTab,
|
||||
} from "./notepads.mjs";
|
||||
|
||||
/* ---------------------------------------------------------------- routes */
|
||||
|
||||
@@ -75,6 +89,11 @@ const ROUTES = [
|
||||
{ path: "/notepad/image", method: "POST", origin: true, run: notepadImage },
|
||||
{ path: "/notepad/thumb", method: "POST", origin: true, run: notepadThumb },
|
||||
{ path: "/notepad/image/delete", method: "POST", origin: true, run: notepadDelete },
|
||||
{ path: "/notepad/tab", method: "POST", origin: true, run: notepadTabNew },
|
||||
{ path: "/notepad/tab/rename", method: "POST", origin: true, run: notepadTabRename },
|
||||
{ path: "/notepad/tab/delete", method: "POST", origin: true, run: notepadTabDelete },
|
||||
{ path: "/notepad/tab/order", method: "POST", origin: true, run: notepadTabOrder },
|
||||
{ path: "/notepad/tab/last", method: "POST", origin: true, run: notepadTabLast },
|
||||
{ match: (p, req) => p.startsWith("/notepad/images/") || req.url.startsWith("/notepad/images/"), method: "GET", run: notepadImageGet },
|
||||
{ match: (p, req) => p.startsWith("/attachments/") || req.url.startsWith("/attachments/"), run: attachment },
|
||||
{ match: (p, req) => p.startsWith("/shots/") || req.url.startsWith("/shots/"), run: shot },
|
||||
@@ -558,19 +577,30 @@ function notepadFail(res, e) {
|
||||
return json(res, 500, { error: "bad" });
|
||||
}
|
||||
|
||||
function notepadGet(req, res, ctx) {
|
||||
function notepadGet(req, res, ctx, url) {
|
||||
try {
|
||||
return json(res, 200, readNotepad(notepadRoot(ctx)));
|
||||
return json(res, 200, readNotepad(notepadRoot(ctx), url.searchParams.get("tab")));
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
}
|
||||
|
||||
function notepadText(req, res, ctx) {
|
||||
// The tab a text or picture request means: the `tab` query value when there
|
||||
// is one (the store refuses an unknown or malformed id), else the last tab
|
||||
// used, else the first. With no tab at all, `create` makes the first one,
|
||||
// Notes, so a page that never sends `tab` keeps working; the rest refuse.
|
||||
function notepadTab(ctx, url, create) {
|
||||
const given = url.searchParams.get("tab");
|
||||
if (given !== null) return given;
|
||||
const root = notepadRoot(ctx);
|
||||
return defaultTabId(root) ?? (create ? createTab(root, "Notes").id : null);
|
||||
}
|
||||
|
||||
function notepadText(req, res, ctx, url) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-long" : "bad" });
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...saveNote(notepadRoot(ctx), body && body.text) });
|
||||
return json(res, 200, { ok: true, ...saveNote(notepadRoot(ctx), notepadTab(ctx, url, true), body && body.text) });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
@@ -589,10 +619,10 @@ function readJpeg(req, res, then) {
|
||||
});
|
||||
}
|
||||
|
||||
function notepadImage(req, res, ctx) {
|
||||
function notepadImage(req, res, ctx, url) {
|
||||
return readJpeg(req, res, (buf) => {
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...addImage(notepadRoot(ctx), buf) });
|
||||
return json(res, 200, { ok: true, ...addImage(notepadRoot(ctx), notepadTab(ctx, url, true), buf) });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
@@ -602,7 +632,7 @@ function notepadImage(req, res, ctx) {
|
||||
function notepadThumb(req, res, ctx, url) {
|
||||
return readJpeg(req, res, (buf) => {
|
||||
try {
|
||||
addThumb(notepadRoot(ctx), url.searchParams.get("id"), buf);
|
||||
addThumb(notepadRoot(ctx), notepadTab(ctx, url, false), url.searchParams.get("id"), buf);
|
||||
return json(res, 200, { ok: true });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
@@ -610,11 +640,11 @@ function notepadThumb(req, res, ctx, url) {
|
||||
});
|
||||
}
|
||||
|
||||
function notepadDelete(req, res, ctx) {
|
||||
function notepadDelete(req, res, ctx, url) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
|
||||
try {
|
||||
removeImage(notepadRoot(ctx), body && body.id);
|
||||
removeImage(notepadRoot(ctx), notepadTab(ctx, url, false), body && body.id);
|
||||
return json(res, 200, { ok: true });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
@@ -622,13 +652,45 @@ function notepadDelete(req, res, ctx) {
|
||||
});
|
||||
}
|
||||
|
||||
// The tab routes: each reads a small JSON body, calls the store and answers
|
||||
// `{ ok, ... }`. Like the rest of the notepad they write nothing under
|
||||
// ctx.dir and add nothing to the event log.
|
||||
function notepadTabRoute(act) {
|
||||
return (req, res, ctx) =>
|
||||
readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...act(notepadRoot(ctx), body && typeof body === "object" ? body : {}) });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Declarations, not consts: ROUTES above names them before this line runs.
|
||||
function notepadTabNew(req, res, ctx) {
|
||||
return notepadTabRoute((root, body) => createTab(root, body.name))(req, res, ctx);
|
||||
}
|
||||
function notepadTabRename(req, res, ctx) {
|
||||
return notepadTabRoute((root, body) => renameTab(root, body.id, body.name))(req, res, ctx);
|
||||
}
|
||||
function notepadTabDelete(req, res, ctx) {
|
||||
return notepadTabRoute((root, body) => deleteTab(root, body.id))(req, res, ctx);
|
||||
}
|
||||
function notepadTabOrder(req, res, ctx) {
|
||||
return notepadTabRoute((root, body) => reorderTabs(root, body.order))(req, res, ctx);
|
||||
}
|
||||
function notepadTabLast(req, res, ctx) {
|
||||
return notepadTabRoute((root, body) => setLastTab(root, body.id))(req, res, ctx);
|
||||
}
|
||||
|
||||
// Matched on the raw request line too, as /uploads/ is: URL parsing folds
|
||||
// `..` away, and nothing that needed folding is a notepad picture.
|
||||
const NOTEPAD_IMAGE_ROUTE = /^\/notepad\/images\/([0-9a-f-]{36})(\.thumb)?\.jpg$/;
|
||||
const NOTEPAD_IMAGE_ROUTE = /^\/notepad\/images\/([0-9a-f]{12})\/([0-9a-f-]{36})(\.thumb)?\.jpg$/;
|
||||
|
||||
function notepadImageGet(req, res, ctx, url) {
|
||||
const m = NOTEPAD_IMAGE_ROUTE.exec(req.url);
|
||||
const file = m && m[0] === url.pathname ? imagePath(notepadRoot(ctx), m[1], Boolean(m[2])) : null;
|
||||
const file = m && m[0] === url.pathname ? imagePath(notepadRoot(ctx), m[1], m[2], Boolean(m[3])) : null;
|
||||
if (!file) return json(res, 404, { error: "not-found" });
|
||||
let buf;
|
||||
try {
|
||||
|
||||
@@ -70,10 +70,13 @@ export const SERVABLE = new Set([
|
||||
"screens/workspace.js",
|
||||
"screens/ask.js",
|
||||
"screens/notepad.js",
|
||||
"notepad-tabs.js",
|
||||
"net.js",
|
||||
"notepad.js",
|
||||
"notepad-editor.js",
|
||||
"notepad-editor.css",
|
||||
"vendor/marked.esm.js",
|
||||
"vendor/overtype.esm.js",
|
||||
"vendor/codemirror.esm.js",
|
||||
]);
|
||||
|
||||
/* ------------------------------------------------------------ stylesheet */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.10.0",
|
||||
"version": "2.11.0",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-19",
|
||||
"releaseDate": "2026-10-20",
|
||||
"mode": "utility"
|
||||
}
|
||||