mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 04:45:33 -08:00
Add Notebook tabs and a CodeMirror editor, rename Notepad to Notebook, add Back to Questions
AI Assisted
This commit is contained in:
1 parent
2075d235d8
commit
d4adb53a3a
55 files changed
+4017
-9231
No files matched your search
@@ -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,50 @@
|
||||
</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-tab-tools" id="notepad-tab-tools" role="group" aria-label="This tab" hidden>
|
||||
<button type="button" class="btn tiny ghost" id="notepad-tab-rename">Rename</button>
|
||||
<button type="button" class="btn tiny ghost" id="notepad-tab-left">Move left</button>
|
||||
<button type="button" class="btn tiny ghost" id="notepad-tab-right">Move right</button>
|
||||
<button type="button" class="btn tiny ghost notepad-tab-delete" id="notepad-tab-delete">Delete</button>
|
||||
</div>
|
||||
<form class="notepad-name-form" id="notepad-name-form" hidden novalidate>
|
||||
<label for="notepad-name" id="notepad-name-label">Name this tab</label>
|
||||
<div class="notepad-name-row">
|
||||
<input type="text" id="notepad-name" autocomplete="off" spellcheck="false" aria-describedby="notepad-name-error" />
|
||||
<button type="submit" class="btn small primary" id="notepad-name-save">Save</button>
|
||||
<button type="button" class="btn small ghost" id="notepad-name-cancel">Cancel</button>
|
||||
</div>
|
||||
<p class="help notepad-name-error" id="notepad-name-error" aria-live="polite"></p>
|
||||
</form>
|
||||
<div class="notepad-delete" id="notepad-delete" role="group" aria-labelledby="notepad-delete-text" hidden>
|
||||
<p id="notepad-delete-text"></p>
|
||||
<div class="notepad-delete-row">
|
||||
<button type="button" class="btn small" id="notepad-delete-keep">Keep tab</button>
|
||||
<button type="button" class="btn small danger" id="notepad-delete-go">Delete tab…</button>
|
||||
</div>
|
||||
</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 +2655,7 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notepad's full-screen picture preview, opened over the Notepad
|
||||
<!-- 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,145 @@
|
||||
// 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 the keyboard or a
|
||||
// drag, or ask to rename (onChange). No fetches here: the screen owns every
|
||||
// request, and notepad.js owns the rules for order.
|
||||
|
||||
import { dropTab, moveTab } 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) and `{ type: "rename", 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;
|
||||
|
||||
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();
|
||||
if (e.altKey) return reorder(moveTab(ids(), id, left ? -1 : 1), id);
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
b.addEventListener("dragover", (e) => {
|
||||
if (dragging === null) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "move";
|
||||
clearMarks();
|
||||
if (tab.id !== dragging) b.classList.add("is-drop-before");
|
||||
});
|
||||
b.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 b;
|
||||
}
|
||||
|
||||
// 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;
|
||||
$("notepad-tab-tools").hidden = empty;
|
||||
const at = tabs.findIndex((t) => t.id === activeId);
|
||||
$("notepad-tab-left").disabled = at <= 0;
|
||||
$("notepad-tab-right").disabled = at < 0 || at >= tabs.length - 1;
|
||||
// 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,106 @@
|
||||
// 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,
|
||||
moveTab,
|
||||
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 +110,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 +126,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 +192,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 +213,310 @@ 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 || "";
|
||||
|
||||
const ids = () => tabs.map((t) => t.id);
|
||||
|
||||
function drawTabs() {
|
||||
tabBar.draw(tabs, activeId);
|
||||
const none = !activeId;
|
||||
$("notepad-tab-rename").disabled = none || busy;
|
||||
$("notepad-tab-delete").disabled = none || busy;
|
||||
$("notepad-tab-new").disabled = busy;
|
||||
$("notepad-empty-new").disabled = busy;
|
||||
if (busy) {
|
||||
$("notepad-tab-left").disabled = true;
|
||||
$("notepad-tab-right").disabled = true;
|
||||
}
|
||||
$("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();
|
||||
}
|
||||
|
||||
// The current tab one place to the left or right.
|
||||
function moveCurrent(delta) {
|
||||
if (!activeId || busy) return;
|
||||
const order = moveTab(ids(), activeId, delta);
|
||||
if (order.join() !== ids().join()) reorder(order, activeId);
|
||||
}
|
||||
|
||||
// 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-form").hidden = false;
|
||||
$("notepad-name-error").textContent = "";
|
||||
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-form").hidden = true;
|
||||
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() {
|
||||
$("notepad-delete").hidden = stage === "none";
|
||||
if (stage === "none") return;
|
||||
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 +545,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 +578,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 +625,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 +720,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 +742,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 +768,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 +790,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 +873,93 @@ 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-form").hidden = true;
|
||||
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 acts on the current tab: a double-click or F2 on another one picks it first.
|
||||
if (event.id && event.id !== activeId) await switchTo(event.id);
|
||||
if (!event.id || event.id === activeId) 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-tab-rename").addEventListener("click", () => openNameForm("rename"));
|
||||
$("notepad-tab-left").addEventListener("click", () => moveCurrent(-1));
|
||||
$("notepad-tab-right").addEventListener("click", () => moveCurrent(1));
|
||||
$("notepad-tab-delete").addEventListener("click", openDelete);
|
||||
$("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();
|
||||
});
|
||||
// Esc backs out of the name form or the delete question first, and only
|
||||
// then closes the dialog.
|
||||
dlg.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape" || (!naming && stage === "none")) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (naming) closeNameForm();
|
||||
else 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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,13 @@
|
||||
.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 .notepad-tab-tools .btn,
|
||||
.modal.notepad .notepad-name-row .btn,
|
||||
.modal.notepad .notepad-delete-row .btn,
|
||||
.notepad-tab { min-height: 44px; }
|
||||
.notepad-name-row { flex-wrap: wrap; }
|
||||
.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; }
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+30
@@ -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
|
||||
-7528
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user