diff --git a/.gitignore b/.gitignore index 3274721..e35ba54 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ node_modules/ -dist/ .superpowers/ .kiln/tmp/ diff --git a/README.md b/README.md index 0f1dd11..d25f38b 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- +

Notelet

@@ -33,6 +33,8 @@ - **Feels like Notes.** Title, Heading and Body styles, bulleted, dashed, numbered and check lists, pinned notes, Recently Deleted, light and dark themes. In a narrow window it switches to the iPhone layout and its slide between screens. - **Sprints in one note.** Every sprint and a Backlog live in one Sprints note: a points donut, goals per sprint and per month, drag-and-drop tasks and a rich-text note for each task. +- **Type it plainly, see it typeset.** `->`, `<-`, `==>`, `<=` and friends become →, ←, ⇒, ≤ drawn in JetBrains Mono's style; `--` becomes —, `...` becomes …, and quotes curl. `# `, `- ` and ```` ```php ```` start a heading, a list or a code block, and Ctrl+Z right after gives back what you typed. +- **Code blocks.** Pick the language from the block's corner for syntax colours, copy the block with one click, and copy it with other text to get a Markdown code fence. - **Keyboard first.** Every button has a shortcut, and you can change any of them. - **Back and forward.** The mouse's side buttons and Alt+← / Alt+→ step through screens. - **Private.** Notes stay in one file on your PC. Export a backup file whenever you like. @@ -51,7 +53,7 @@ Title, Heading and Subheading, **bold**, *italic*, underline and ~~strikethrough ### The iPhone layout -In a narrow window, such as the popup, Notelet shows one screen at a time and slides between them like iPhone Notes. +In a narrow window, Notelet shows one screen at a time and slides between them like iPhone Notes. @@ -80,14 +82,6 @@ Closing the window (X) only hides it; click the tray icon to bring it back. To q Right-click the tray icon → **Check for updates**. If there is a new version, Notelet asks first, then installs it and reopens. Nothing is lost: any change you are typing is saved first. -## Moving from the Chrome extension - -1. In the extension, export a backup (**⋯** above the notes list → **Export**). -2. Install the desktop app. -3. On first start it offers **Import backup**; choose the file. Or use **⋯** → **Import** any time. - -Notes, deleted notes, sprints, statuses, settings and custom shortcuts come across. The theme and the notes list width don't; set them again once. You can remove the extension afterwards. - ## Back up and restore Notes live in `%APPDATA%\com.ttncode.notelet\notelet.json`, with the previous save kept beside it as `notelet.json.bak`. If the file is ever damaged, Notelet opens the last good copy, or moves the damaged file aside (it is never deleted) and offers Import. The file stays on this PC only, so export regularly. @@ -125,6 +119,7 @@ Press `Ctrl+/` (`⌘/` on Mac) for the full list, grouped by topic. Every button | Go to the notes list / the note | `Alt+1` / `Alt+3` | `⌥1` / `⌥3` | | Text styles menu | `Alt+A` | `⌥A` | | Checklist | `Ctrl+Shift+L` | `⇧⌘L` | +| Block quote | `Ctrl+'` | `⌘'` | | Move line / duplicate line | `Alt+↑↓` / `Ctrl+Alt+Shift+↑↓` | `⌥↑↓` / `⌘⌥⇧↑↓` | | Change case: lower, UPPER, Title | `Shift+F3` | `⇧F3` | | Back / Forward | mouse side buttons, `Alt+←` / `Alt+→` | mouse side buttons, `⌘[` / `⌘]` | @@ -132,9 +127,9 @@ Press `Ctrl+/` (`⌘/` on Mac) for the full list, grouped by topic. Every button `Ctrl+click` (`⌘`-click on Mac) opens a link in a note; a plain click only places the caret. -Text styles follow Notes for Mac with Ctrl in place of Cmd; where Chrome kept a key for itself (Ctrl+N, Ctrl+Shift+T) Notelet uses Alt instead, the same keys as the extension had. +Text styles follow Notes for Mac with Ctrl in place of Cmd. A few actions use Alt instead, such as `Alt+N` for a new note. -**To change a shortcut**, click its key in the list and press the new one. Esc, Tab or a click elsewhere cancels; Backspace removes the key. Keys Windows keeps, and those Chrome kept, are refused; a key another shortcut uses asks before taking it over. ↺ resets one shortcut; **Reset All to Default** resets them all. +**To change a shortcut**, click its key in the list and press the new one. Esc, Tab or a click elsewhere cancels; Backspace removes the key. Keys Windows keeps, and browser keys such as `Ctrl+N`, `Ctrl+T` and `Ctrl+W`, are refused; a key another shortcut uses asks before taking it over. ↺ resets one shortcut; **Reset All to Default** resets them all. ## Development @@ -142,10 +137,11 @@ Text styles follow Notes for Mac with Ctrl in place of Cmd; where Chrome kept a npm install npm test # unit tests for the UI modules node tools/make-icons.mjs # regenerate icons, then: npx tauri icon desktop/icons/source.png -o desktop/icons +python3 tools/build-arrow-font.py … # rebuild the arrow font; see the script for the steps npm run tauri dev # run the app (Windows, with Rust and the MSVC build tools) ``` -The UI lives in `extension/` and runs unchanged inside the Tauri shell in `desktop/`. CI on Windows runs the unit tests, `cargo test`, clippy, a release build and end-to-end tests that press every shortcut in the built app. Working in WSL, where the Windows toolchain is not available, push a branch and let CI build it. +The UI lives in `app/` (HTML, CSS and plain ES modules, no build step) and runs inside the Tauri shell in `desktop/`. CI on Windows runs the unit tests, `cargo test`, clippy, a release build and end-to-end tests that press every shortcut in the built app. Working in WSL, where the Windows toolchain is not available, push a branch and let CI build it. Pushing a `v*` tag builds the installer, signs the update, and publishes the release with the `latest.json` the app checks. diff --git a/extension/app.js b/app/app.js similarity index 98% rename from extension/app.js rename to app/app.js index 3a0faab..6b78d4d 100644 --- a/extension/app.js +++ b/app/app.js @@ -95,7 +95,7 @@ async function main() { store.onChange(applyRemoteChanges); openInitialNote(); steps = createNavigation({ readView, showView }); - whenShown(document, window, () => showStartupNotice(recovery, loaded.notes.length === 0)); + whenShown(document, window, () => showStartupNotice(recovery)); } // shortcut: an edit typed under SAVE_DELAY_MS before Windows shuts down can be lost, since WebView2 @@ -120,16 +120,10 @@ function onHistoryKey(event) { else history.forward(); } -// A damaged notes file is explained once; a first launch with no notes offers the backup from the extension. -function showStartupNotice(recovery, isEmpty) { +// A damaged notes file is explained once. +function showStartupNotice(recovery) { const message = recoveryMessage(recovery); - if (message) { - showToast(message); - return; - } - if (!isEmpty || state.ui.importOffered) return; - saveUiSoon({ importOffered: true }); - showToast("Moving from the Chrome extension? Export a backup there, then choose Import backup.", { label: "Import backup", run: () => importNotes().catch(reportImportError) }); + if (message) showToast(message); } const toggleMaximize = () => tauri.core.invoke("toggle_maximize").catch((error) => console.error("Notelet: could not resize the window", error)); diff --git a/extension/backup.js b/app/backup.js similarity index 98% rename from extension/backup.js rename to app/backup.js index 1073037..8768db4 100644 --- a/extension/backup.js +++ b/app/backup.js @@ -23,7 +23,7 @@ export function parseBackup(text) { if (data === undefined) return failure("This file is not a valid backup: it is not JSON."); if (data?.app !== BACKUP_APP) return failure("This file is not a Notelet backup."); if (typeof data.version === "number" && data.version > BACKUP_VERSION) { - return failure("This backup comes from a newer version of Notelet. Update the extension, then import again."); + return failure("This backup comes from a newer version of Notelet. Update Notelet, then import again."); } if (!SUPPORTED_VERSIONS.has(data.version) || !Array.isArray(data.notes)) return failure("This backup is damaged and cannot be imported."); if (data.version >= 2 && !isValidSettings(data.settings)) return failure("The status settings in this backup are damaged, so nothing was imported."); diff --git a/extension/board-merge.js b/app/board-merge.js similarity index 100% rename from extension/board-merge.js rename to app/board-merge.js diff --git a/extension/board-view.js b/app/board-view.js similarity index 100% rename from extension/board-view.js rename to app/board-view.js diff --git a/extension/board.js b/app/board.js similarity index 100% rename from extension/board.js rename to app/board.js diff --git a/extension/case.js b/app/case.js similarity index 100% rename from extension/case.js rename to app/case.js diff --git a/extension/clipboard.js b/app/clipboard.js similarity index 81% rename from extension/clipboard.js rename to app/clipboard.js index 65bab76..41681ef 100644 --- a/extension/clipboard.js +++ b/app/clipboard.js @@ -1,9 +1,11 @@ +import { codeBlockLines, languageOf } from "./code-block.js"; + // What a copy from a note puts on the clipboard. The plain text marks list items the way // Markdown and Notes do; the HTML keeps the structure but none of the page's colours or sizes, // so the text takes on the look of wherever it is pasted. -const BLOCKS = new Set(["H1", "H2", "H3", "P", "PRE", "DIV"]); +const BLOCKS = new Set(["H1", "H2", "H3", "P", "PRE", "BLOCKQUOTE", "DIV"]); const LISTS = new Set(["UL", "OL"]); -const STYLED_LINES = "h1, h2, h3, pre"; +const STYLED_LINES = "h1, h2, h3, pre, blockquote"; const NESTED_INDENT = " "; const HTML_MARKERS = { checked: "☑ ", unchecked: "☐ ", dashed: "– " }; const TEXT_NODE = 3; @@ -28,7 +30,29 @@ export function selectedContent(range) { const styledLineAround = (node) => (node.nodeType === TEXT_NODE ? node.parentElement : node).closest(STYLED_LINES); export function clipboardText(root) { - return linesOf(root, "").join("\n"); + return linesOf(withCodeFences(root), "").join("\n"); +} + +// Code copied along with other lines is marked as Markdown code, so it stays code where it is +// pasted; code copied on its own stays bare, ready for a terminal. +function withCodeFences(root) { + if ([...root.children].every((block) => block.tagName === "PRE")) return root; + const copy = root.cloneNode(true); + const firstLines = [...copy.children].filter((block) => block.tagName === "PRE" && block.previousElementSibling?.tagName !== "PRE"); + for (const firstLine of firstLines) { + const lines = codeBlockLines(firstLine); + const language = languageOf(lines); + if (!language) continue; + firstLine.before(fenceLine(copy, `\`\`\`${language}`)); + lines.at(-1).after(fenceLine(copy, "```")); + } + return copy; +} + +function fenceLine(root, text) { + const line = root.ownerDocument.createElement("p"); + line.textContent = text; + return line; } // Notes keep line breaks three ways: separate blocks,
, and "\n" inside the text (what a diff --git a/app/code-block.js b/app/code-block.js new file mode 100644 index 0000000..681ff4c --- /dev/null +++ b/app/code-block.js @@ -0,0 +1,60 @@ +// A code block is a run of Monostyled lines (
) next to each other. Its language is kept on
+// each line as data-language, so it survives the first line being deleted or moved.
+export const CODE_LANGUAGES = [
+  ["", "Plain text"],
+  ["bash", "Bash"],
+  ["css", "CSS"],
+  ["html", "HTML"],
+  ["javascript", "JavaScript"],
+  ["json", "JSON"],
+  ["markdown", "Markdown"],
+  ["php", "PHP"],
+  ["python", "Python"],
+  ["sql", "SQL"],
+  ["typescript", "TypeScript"],
+  ["yaml", "YAML"],
+];
+const LANGUAGE_IDS = new Set(CODE_LANGUAGES.map(([id]) => id).filter(Boolean));
+const FENCE_ALIASES = { js: "javascript", ts: "typescript", sh: "bash", shell: "bash", py: "python", yml: "yaml", md: "markdown" };
+const FENCE = /^```([a-z]*)$/i;
+
+export const isCodeLanguage = (id) => LANGUAGE_IDS.has(id);
+
+export function codeBlockLines(line) {
+  let first = line;
+  while (first.previousElementSibling?.tagName === "PRE") first = first.previousElementSibling;
+  const lines = [first];
+  while (lines.at(-1).nextElementSibling?.tagName === "PRE") lines.push(lines.at(-1).nextElementSibling);
+  return lines;
+}
+
+export const codeBlockFirstLines = (root) => [...root.querySelectorAll("pre")].filter((line) => line.previousElementSibling?.tagName !== "PRE");
+
+export const languageOf = (lines) => lines.map((line) => line.getAttribute("data-language")).find(isCodeLanguage) ?? "";
+
+// An empty language makes the block plain text.
+export function setLanguage(lines, language) {
+  for (const line of lines) {
+    if (language) line.setAttribute("data-language", language);
+    else line.removeAttribute("data-language");
+  }
+}
+
+// A line that joins a code block (made Monostyled above it, moved or pasted next to it) takes
+// the block's language, so the corner label, the colours and a copy all agree.
+export function unifyCodeLanguages(root) {
+  for (const firstLine of codeBlockFirstLines(root)) {
+    const lines = codeBlockLines(firstLine);
+    const language = languageOf(lines);
+    if (lines.some((line) => (line.getAttribute("data-language") ?? "") !== language)) setLanguage(lines, language);
+  }
+}
+
+// "```" gives "", "```php" or "```js" the language's id; anything else, null.
+export function fenceLanguage(text) {
+  const match = FENCE.exec(text);
+  if (!match) return null;
+  const name = match[1].toLowerCase();
+  const id = FENCE_ALIASES[name] ?? name;
+  return id === "" || isCodeLanguage(id) ? id : null;
+}
diff --git a/app/code-highlight.js b/app/code-highlight.js
new file mode 100644
index 0000000..e7f1ee2
--- /dev/null
+++ b/app/code-highlight.js
@@ -0,0 +1,104 @@
+import { codeBlockFirstLines, codeBlockLines, languageOf } from "./code-block.js";
+
+// Syntax colours for code blocks. Prism (vendor/prism.js) finds the tokens; the CSS Custom
+// Highlight API colours them without adding any element to the note, so the saved HTML, the
+// caret and Undo never see them.
+
+// Prism's token types, folded into the few colours code is shown in.
+const TOKEN_GROUPS = {
+  comment: "comment", prolog: "comment", doctype: "comment", cdata: "comment",
+  keyword: "keyword", boolean: "keyword", important: "keyword", atrule: "keyword", title: "keyword",
+  string: "string", char: "string", "attr-value": "string", regex: "string", url: "string",
+  number: "number", constant: "number",
+  function: "function", "class-name": "function", builtin: "function",
+  tag: "tag", selector: "tag", property: "tag", "attr-name": "tag", key: "tag",
+  variable: "variable",
+};
+export const HIGHLIGHT_GROUPS = [...new Set(Object.values(TOKEN_GROUPS))];
+
+// The coloured stretches of text, as { group, start, end } offsets. Text inside a token that
+// has no colour of its own takes the colour of the token around it.
+export function tokenRanges(text, language) {
+  const grammar = globalThis.Prism?.languages[language];
+  if (!grammar) return [];
+  const ranges = [];
+  collectRanges(globalThis.Prism.tokenize(text, grammar), { start: 0, group: null, ranges });
+  return ranges;
+}
+
+function collectRanges(stream, { start, group, ranges }) {
+  let offset = start;
+  for (const token of stream) {
+    if (typeof token === "string") {
+      if (group) ranges.push({ group, start: offset, end: offset + token.length });
+    } else {
+      collectRanges([].concat(token.content), { start: offset, group: groupOf(token) ?? group, ranges });
+    }
+    offset += token.length;
+  }
+}
+
+function groupOf(token) {
+  const names = [token.type, ...[].concat(token.alias ?? [])];
+  return names.map((name) => TOKEN_GROUPS[name]).find(Boolean) ?? null;
+}
+
+const editorRoots = new Set();
+let paintFrame = 0;
+
+// Colours the code in root on the next frame, along with every other editor's code, since the
+// page has one set of highlights for all of them.
+export function refreshCodeColours(root) {
+  if (!globalThis.CSS?.highlights || !globalThis.Prism) return;
+  editorRoots.add(root);
+  cancelAnimationFrame(paintFrame);
+  paintFrame = requestAnimationFrame(paintCodeColours);
+}
+
+function paintCodeColours() {
+  const highlights = new Map(HIGHLIGHT_GROUPS.map((group) => [group, new Highlight()]));
+  for (const root of editorRoots) {
+    for (const firstLine of codeBlockFirstLines(root)) paintCodeBlock(codeBlockLines(firstLine), highlights);
+  }
+  for (const [group, highlight] of highlights) CSS.highlights.set(`code-${group}`, highlight);
+}
+
+function paintCodeBlock(lines, highlights) {
+  const language = languageOf(lines);
+  if (!language) return;
+  const { text, pieces } = codeText(lines);
+  for (const { group, start, end } of tokenRanges(text, language)) {
+    const range = new Range();
+    const from = positionAt(pieces, start);
+    const to = positionAt(pieces, end);
+    range.setStart(from.node, from.offset);
+    range.setEnd(to.node, to.offset);
+    highlights.get(group).add(range);
+  }
+}
+
+// The block's text as Prism reads it, with "\n" for each 
and between lines, and where each +// text node starts in it. +function codeText(lines) { + let text = ""; + const pieces = []; + lines.forEach((line, index) => { + if (index > 0) text += "\n"; + const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT); + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + if (node.nodeName === "BR") { + text += "\n"; + } else if (node.nodeType === Node.TEXT_NODE) { + pieces.push({ node, start: text.length }); + text += node.data; + } + } + }); + return { text, pieces }; +} + +// An offset that falls on a line break moves to the start of the next text. +function positionAt(pieces, offset) { + const piece = pieces.find(({ node, start }) => offset <= start + node.length) ?? pieces.at(-1); + return { node: piece.node, offset: Math.min(Math.max(0, offset - piece.start), piece.node.length) }; +} diff --git a/app/code-toolbar.js b/app/code-toolbar.js new file mode 100644 index 0000000..dc94bd5 --- /dev/null +++ b/app/code-toolbar.js @@ -0,0 +1,81 @@ +import { clipboardText } from "./clipboard.js"; +import { CODE_LANGUAGES, codeBlockLines, languageOf } from "./code-block.js"; +import { showToast } from "./dialogs.js"; +import { caretElement } from "./selection.js"; + +const INSET_PX = 6; +const COPY_ICON = ''; + +// Notion's code block toolbar: the language menu and a copy button in the block's top-right +// corner, shown while the pointer is over the block or the caret is in it. It sits in the +// editor's scroll area, outside the note text, so it is never saved with the note. +export function createCodeToolbar({ editorElement, onPickLanguage }) { + const toolbar = createToolbarElement(); + const [select, copyButton] = toolbar.children; + const scroller = editorElement.parentElement; + let hoveredBlock = null; + let shownBlock = null; + + select.addEventListener("change", () => onPickLanguage(shownBlock, select.value)); + copyButton.addEventListener("click", () => copyCode(shownBlock)); + scroller.addEventListener("pointerover", (event) => { + if (toolbar.contains(event.target)) return; + hoveredBlock = editorElement.contains(event.target) ? event.target.closest("pre") : null; + update(); + }); + scroller.addEventListener("pointerleave", () => { + hoveredBlock = null; + update(); + }); + window.addEventListener("resize", update); + editorElement.after(toolbar); + + function update() { + // An open language menu keeps the toolbar where it is, wherever the pointer goes. + if (document.activeElement === select && shownBlock?.isConnected) return; + const hovered = hoveredBlock?.isConnected ? hoveredBlock : null; + shownBlock = editorElement.isContentEditable ? hovered ?? caretElement(editorElement)?.closest("pre") ?? null : null; + toolbar.hidden = !shownBlock; + if (!shownBlock) return; + const lines = codeBlockLines(shownBlock); + select.value = languageOf(lines); + placeOver(lines[0]); + } + + function placeOver(firstLine) { + const line = firstLine.getBoundingClientRect(); + const area = scroller.getBoundingClientRect(); + toolbar.style.top = `${line.top - area.top + scroller.scrollTop + INSET_PX}px`; + toolbar.style.left = `${line.right - area.left + scroller.scrollLeft - toolbar.offsetWidth - INSET_PX}px`; + } + + return { update }; +} + +function createToolbarElement() { + const toolbar = document.createElement("div"); + toolbar.className = "code-toolbar"; + toolbar.hidden = true; + const select = document.createElement("select"); + select.setAttribute("aria-label", "Code language"); + select.append(...CODE_LANGUAGES.map(([id, name]) => new Option(name, id))); + const copyButton = document.createElement("button"); + copyButton.type = "button"; + copyButton.title = "Copy code"; + copyButton.setAttribute("aria-label", "Copy code"); + copyButton.innerHTML = COPY_ICON; + toolbar.append(select, copyButton); + return toolbar; +} + +// The whole block as bare code, without Markdown fences, ready for a terminal. +async function copyCode(block) { + const holder = block.ownerDocument.createElement("div"); + holder.append(...codeBlockLines(block).map((line) => line.cloneNode(true))); + try { + await navigator.clipboard.writeText(clipboardText(holder)); + showToast("Code copied"); + } catch (error) { + showToast(`Couldn't copy the code: ${error.message}`); + } +} diff --git a/extension/desktop.js b/app/desktop.js similarity index 97% rename from extension/desktop.js rename to app/desktop.js index d0c905c..a909917 100644 --- a/extension/desktop.js +++ b/app/desktop.js @@ -1,7 +1,7 @@ // Glue between the UI and the Tauri desktop shell. Nothing here touches window.__TAURI__ at // load time, so the tests can import it in Node. -// A stand-in for chrome.storage.local backed by one JSON file that Rust writes. The whole map +// A key-value storage area backed by one JSON file that Rust writes. The whole map // is kept in memory and rewritten on every change; writes run one after another so an older // map never lands on disk after a newer one. export function createFileArea(invoke) { diff --git a/extension/dialogs.js b/app/dialogs.js similarity index 100% rename from extension/dialogs.js rename to app/dialogs.js diff --git a/extension/dom.js b/app/dom.js similarity index 100% rename from extension/dom.js rename to app/dom.js diff --git a/extension/editor.js b/app/editor.js similarity index 78% rename from extension/editor.js rename to app/editor.js index ceae8c4..a9f38c6 100644 --- a/extension/editor.js +++ b/app/editor.js @@ -1,24 +1,33 @@ import { nextCase, wordAt } from "./case.js"; import { clipboardHtml, clipboardText, selectedContent } from "./clipboard.js"; +import { codeBlockLines, fenceLanguage, setLanguage, unifyCodeLanguages } from "./code-block.js"; +import { refreshCodeColours } from "./code-highlight.js"; +import { createCodeToolbar } from "./code-toolbar.js"; import { History } from "./history.js"; import { matchHotkey } from "./hotkeys.js"; import { - ABOVE, BELOW, duplicateLine, endingInsideText, indentText, insertLine, lineOf, moveLines, nextLine, outdentText, previousLine, removeLine, selectedLines, withoutNextLineStart, + ABOVE, BELOW, duplicateLine, endingInsideText, indentCodeLines, indentText, insertLine, lineOf, moveLines, nextLine, outdentCodeLines, outdentText, previousLine, removeLine, + selectedLines, withoutNextLineStart, } from "./lines.js"; import { - checkboxForShortcut, clearItemState, itemCreatedBySplit, liftListOutOfParagraph, listKindForShortcut, removeLeadingText, setBlockType, splitParagraphsIntoItems, + blockTagForShortcut, checkboxForShortcut, clearItemState, endsWithTwoEmptyLines, itemCreatedBySplit, liftListOutOfParagraph, listKindForShortcut, removeTwoEmptyLines, + removeLeadingText, setBlockType, splitParagraphsIntoItems, } from "./lists.js"; import { EMPTY_NOTE_HTML } from "./model.js"; import { linkableUrl, normalizeLineBreaks, plainTextToHtml, sanitizeHtml, sanitizePastedHtml } from "./sanitize.js"; import { caretBlock, caretElement, caretOffset, isCaretAtEndOf, placeCaret, placeCaretAfter, placeCaretAtEnd, placeCaretAtStart, restoreSelection, saveSelection, setCaretOffset, } from "./selection.js"; +import { isStraightQuote, smartQuote, substitutionBefore } from "./typography.js"; const TYPING_PAUSE_MS = 1000; const IME_PROCESS_KEYCODE = 229; const URL_BEFORE_CARET = /(https?:\/\/[^\s<>"]+)$/; const HEADING_TAGS = new Set(["H1", "H2", "H3"]); -const BLOCK_ACTIONS = { title: "h1", heading: "h2", subheading: "h3", body: "p", monostyled: "pre" }; +const BLOCK_ACTIONS = { title: "h1", heading: "h2", subheading: "h3", body: "p", monostyled: "pre", quote: "blockquote" }; +const TEXT_LINES = "h1,h2,h3,p,pre,blockquote,li"; +// Where typed text stays exactly as typed. +const LITERAL_TEXT = "pre, a"; const INLINE_ACTIONS = { bold: "bold", italic: "italic", underline: "underline", strikethrough: "strikeThrough" }; const LIST_ACTIONS = new Set(["bulleted", "dashed", "numbered", "checklist"]); const LINE_DIRECTIONS = { @@ -43,11 +52,13 @@ export class NoteEditor { #savedRange = null; #itemBeforeEnter = null; #emptyHtml = EMPTY_NOTE_HTML; + #codeToolbar; constructor({ element, isMac, onChange }) { this.#element = element; this.#isMac = isMac; this.#onChange = onChange; + this.#codeToolbar = createCodeToolbar({ editorElement: element, onPickLanguage: (block, language) => this.#setCodeLanguage(block, language) }); document.execCommand("defaultParagraphSeparator", false, "p"); this.#listen(); } @@ -60,6 +71,8 @@ export class NoteEditor { this.#history.clear(); this.#lastInput = { at: 0, kind: "" }; this.#savedRange = null; + this.#codeToolbar.update(); + refreshCodeColours(this.#element); } // Text merged from another window replaces what is shown; the caret stays in the paragraph it @@ -72,6 +85,7 @@ export class NoteEditor { this.#checkpoint(); this.#element.innerHTML = html; this.#savedRange = null; + refreshCodeColours(this.#element); if (!hadFocus || !caret) return; const blocks = [...this.#element.children]; const distance = (candidate) => Math.abs(blocks.indexOf(candidate) - caret.index); @@ -82,6 +96,7 @@ export class NoteEditor { setReadOnly(readOnly) { this.#element.contentEditable = String(!readOnly); + this.#codeToolbar.update(); } isFocused() { @@ -92,7 +107,7 @@ export class NoteEditor { focus() { this.#element.focus(); if (!this.#savedRange) { - const blocks = this.#element.querySelectorAll("h1,h2,h3,p,pre,li"); + const blocks = this.#element.querySelectorAll(TEXT_LINES); placeCaretAtEnd(blocks[blocks.length - 1] ?? this.#element); return; } @@ -103,7 +118,7 @@ export class NoteEditor { // A new note's empty title line is where typing starts. focusStart() { this.#element.focus(); - const blocks = [...this.#element.querySelectorAll("h1,h2,h3,p,pre,li")]; + const blocks = [...this.#element.querySelectorAll(TEXT_LINES)]; const firstEmpty = blocks.find((block) => block.textContent === ""); placeCaretAtStart(firstEmpty ?? this.#element.firstElementChild ?? this.#element); } @@ -162,8 +177,15 @@ export class NoteEditor { return; } const lines = this.#selectedLines(); - if (lines.length > 1) { - lines.forEach(command === "indent" ? indentText : outdentText); + const selection = document.getSelection(); + if (lines.length > 1 || !selection.isCollapsed) { + const range = selection.getRangeAt(0); + const shiftCode = command === "indent" ? indentCodeLines : outdentCodeLines; + const shiftText = command === "indent" ? indentText : outdentText; + for (const line of lines) { + if (line.tagName === "PRE") shiftCode(line, range); + else shiftText(line); + } return; } const [line] = lines; @@ -240,7 +262,10 @@ export class NoteEditor { element.addEventListener("copy", (event) => this.#onCopy(event)); element.addEventListener("cut", (event) => this.#onCut(event)); element.addEventListener("paste", (event) => this.#onPaste(event)); - document.addEventListener("selectionchange", () => this.#rememberSelection()); + document.addEventListener("selectionchange", () => { + this.#rememberSelection(); + this.#codeToolbar.update(); + }); } #onKeydown(event) { @@ -255,6 +280,8 @@ export class NoteEditor { this.#onTab(event); } else if (event.key === " ") { this.#onSpace(event); + } else if (isStraightQuote(event.key) && !event.ctrlKey && !event.metaKey) { + this.#typeSmartQuote(event); } } @@ -281,7 +308,8 @@ export class NoteEditor { #onEnter(event) { this.#linkifyBeforeCaret(); const block = caretBlock(this.#element); - if (!block || !HEADING_TAGS.has(block.tagName) || !isCaretAtEndOf(block)) return; + if (!block || this.#startCodeBlock(event, block) || this.#leaveQuoteOrCode(event, block)) return; + if (!HEADING_TAGS.has(block.tagName) || !isCaretAtEndOf(block)) return; event.preventDefault(); this.#checkpoint(); if (!document.getSelection().isCollapsed) document.execCommand("delete"); @@ -292,10 +320,61 @@ export class NoteEditor { this.#changed(); } + // "```" or "```php" then Enter on a body line starts a Monostyled block, as in Markdown. + #startCodeBlock(event, block) { + const language = isBodyLine(block) ? fenceLanguage(block.textContent) : null; + if (language === null) return false; + event.preventDefault(); + this.#checkpoint(); + block.replaceChildren(document.createElement("br")); + placeCaretAtStart(block); + this.#retype([block], "pre"); + this.#labelCodeAtCaret(language); + this.#changed(); + return true; + } + + #labelCodeAtCaret(language) { + const block = caretElement(this.#element)?.closest("pre"); + if (block && language) setLanguage(codeBlockLines(block), language); + } + + #setCodeLanguage(block, language) { + if (!block?.isConnected) return; + this.#checkpoint(); + setLanguage(codeBlockLines(block), language); + this.#changed(); + this.focus(); + } + + // As Enter on an empty list item leaves the list, Enter on an empty quote line goes back to body + // text. Code may hold a blank line, so a Monostyled block is left by a second one at its end. + #leaveQuoteOrCode(event, block) { + if (!isCaretAtEndOf(block)) return false; + const isEmptyQuote = block.tagName === "BLOCKQUOTE" && block.textContent === ""; + const isLastCodeLine = block.tagName === "PRE" && block.nextElementSibling?.tagName !== "PRE"; + const isEmptyCode = isLastCodeLine && block.textContent === ""; + if (!isEmptyQuote && !isEmptyCode && !(isLastCodeLine && endsWithTwoEmptyLines(block))) return false; + event.preventDefault(); + this.#checkpoint(); + if (isEmptyQuote || isEmptyCode) { + this.#retype([block], "p"); + } else { + removeTwoEmptyLines(block); + const paragraph = document.createElement("p"); + paragraph.append(document.createElement("br")); + block.after(paragraph); + placeCaretAtStart(paragraph); + } + this.#changed(); + return true; + } + #onTab(event) { event.preventDefault(); this.#checkpoint(); - if (caretElement(this.#element)?.closest("li") || this.#selectedLines().length > 1) { + // Tab over a selection indents its lines, as in VS Code, instead of typing over it. + if (caretElement(this.#element)?.closest("li") || !document.getSelection().isCollapsed) { this.#indentLine(event.shiftKey ? "outdent" : "indent"); } else if (!event.shiftKey) { document.execCommand("insertText", false, "\t"); @@ -304,7 +383,7 @@ export class NoteEditor { } #onSpace(event) { - if (this.#applyListShortcut(event)) return; + if (this.#applyLineShortcut(event) || this.#substituteBeforeCaret(event)) return; const link = this.#linkifyBeforeCaret(); if (!link) return; event.preventDefault(); @@ -315,27 +394,63 @@ export class NoteEditor { } // Notes turns "- ", "* ", "1. " at the start of a body line into a list, and "[ ] " at the - // start of a list item into a checklist item. The space goes in first so Ctrl+Z gives the text back. - #applyListShortcut(event) { + // start of a list item into a checklist item; "# " to "### " and "``` " or "```php " give a + // heading or Monostyled line, as in Markdown. The space goes in first so Ctrl+Z gives the text back. + #applyLineShortcut(event) { const block = caretBlock(this.#element); if (!block || !document.getSelection().isCollapsed) return false; const prefix = block.textContent.slice(0, caretOffset(block)); - const isItem = block.tagName === "LI"; - const kind = !isItem && (block.tagName === "P" || block.tagName === "DIV") ? listKindForShortcut(prefix) : null; - const checkbox = isItem ? checkboxForShortcut(prefix) : null; - if (!kind && !checkbox) return false; + const kind = isBodyLine(block) ? listKindForShortcut(prefix) : null; + const language = isBodyLine(block) ? fenceLanguage(prefix) : null; + const tag = isBodyLine(block) ? blockTagForShortcut(prefix) ?? (language === null ? null : "pre") : null; + const checkbox = block.tagName === "LI" ? checkboxForShortcut(prefix) : null; + if (!kind && !tag && !checkbox) return false; event.preventDefault(); document.execCommand("insertText", false, " "); this.#checkpoint(); removeLeadingText(block, prefix.length + 1); if (!block.textContent && !block.querySelector("br")) block.append(document.createElement("br")); placeCaretAtStart(block); - if (kind) this.#toggleList(kind); + if (tag) { + this.#retype([block], tag); + this.#labelCodeAtCaret(language); + } else if (kind) this.#toggleList(kind); else this.#makeChecklistItem(block, checkbox.checked); this.#changed(); return true; } + // "->" then space becomes "→", as macOS Text Replacement does. The space goes in first so + // Ctrl+Z gives back what was typed. + #substituteBeforeCaret(event) { + const { focusNode: node, focusOffset: offset, isCollapsed } = document.getSelection(); + if (!isCollapsed || node?.nodeType !== Node.TEXT_NODE || !this.#element.contains(node) || node.parentElement.closest(LITERAL_TEXT)) return false; + const substitution = substitutionBefore(node.data.slice(0, offset)); + if (!substitution) return false; + event.preventDefault(); + document.execCommand("insertText", false, " "); + this.#checkpoint(); + const { focusNode: text, focusOffset: afterSpace } = document.getSelection(); + const start = afterSpace - 1 - substitution.typed.length; + text.replaceData(start, substitution.typed.length, substitution.replacement); + placeCaret(text, start + substitution.replacement.length + 1); + this.#changed(); + return true; + } + + // macOS smart quotes: the straight quote goes in first so Ctrl+Z gives it back. + #typeSmartQuote(event) { + if (caretElement(this.#element)?.closest(LITERAL_TEXT)) return; + event.preventDefault(); + document.execCommand("insertText", false, event.key); + const { focusNode: text, focusOffset: offset } = document.getSelection(); + if (text?.nodeType !== Node.TEXT_NODE) return; + this.#checkpoint(); + text.replaceData(offset - 1, 1, smartQuote(event.key, text.data[offset - 2])); + placeCaret(text, offset); + this.#changed(); + } + #makeChecklistItem(item, checked) { if (item.parentElement.tagName === "UL") applyListKind(item.parentElement, "checklist"); else this.#toggleList("checklist"); @@ -465,8 +580,11 @@ export class NoteEditor { if (opensLink) window.open(link.href, "_blank", "noopener"); } + // Block quote toggles, as in Notes; the other styles only set. #setBlock(tag) { - this.#retype(this.#selectedLines(), tag); + const lines = this.#selectedLines(); + const isQuoteOff = tag === "blockquote" && lines.length > 0 && lines.every((line) => line.tagName === "BLOCKQUOTE"); + this.#retype(lines, isQuoteOff ? "p" : tag); } #retype(lines, tag) { @@ -551,7 +669,7 @@ export class NoteEditor { #ensureContent() { const element = this.#element; - if (element.textContent !== "" || element.querySelector("h1,h2,h3,p,pre,li")) return; + if (element.textContent !== "" || element.querySelector(TEXT_LINES)) return; element.innerHTML = this.#emptyHtml; placeCaretAtStart(element.firstElementChild); } @@ -605,7 +723,10 @@ export class NoteEditor { #changed() { this.#stripBrowserStyling(); + unifyCodeLanguages(this.#element); this.#onChange(this.#element.innerHTML); + this.#codeToolbar.update(); + refreshCodeColours(this.#element); } // Chrome pins the old look on text with inline styles when lines merge, a list changes type or @@ -621,6 +742,8 @@ export class NoteEditor { } } +const isBodyLine = (block) => block.tagName === "P" || block.tagName === "DIV"; + function listKind(list) { if (list.tagName === "OL") return "numbered"; if (list.classList.contains("checklist")) return "checklist"; diff --git a/extension/find.js b/app/find.js similarity index 100% rename from extension/find.js rename to app/find.js diff --git a/app/fonts/OFL.txt b/app/fonts/OFL.txt new file mode 100644 index 0000000..8bee414 --- /dev/null +++ b/app/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/fonts/notelet-arrows-bold.woff2 b/app/fonts/notelet-arrows-bold.woff2 new file mode 100644 index 0000000..77c3960 Binary files /dev/null and b/app/fonts/notelet-arrows-bold.woff2 differ diff --git a/app/fonts/notelet-arrows-regular.woff2 b/app/fonts/notelet-arrows-regular.woff2 new file mode 100644 index 0000000..a9c9734 Binary files /dev/null and b/app/fonts/notelet-arrows-regular.woff2 differ diff --git a/extension/format.js b/app/format.js similarity index 100% rename from extension/format.js rename to app/format.js diff --git a/extension/history.js b/app/history.js similarity index 100% rename from extension/history.js rename to app/history.js diff --git a/extension/hotkeys.js b/app/hotkeys.js similarity index 97% rename from extension/hotkeys.js rename to app/hotkeys.js index 545839f..a318105 100644 --- a/extension/hotkeys.js +++ b/app/hotkeys.js @@ -6,6 +6,7 @@ const DEFAULT_HOTKEYS = [ { group: "Text styles", action: "body", label: "Body", mod: true, shift: true, code: "KeyB" }, // Notes uses Shift+Cmd+M, but Ctrl+Shift+M is Chrome's profile menu. { group: "Text styles", action: "monostyled", label: "Monostyled", mod: true, shift: true, code: "KeyK" }, + { group: "Text styles", action: "quote", label: "Block quote", mod: true, code: "Quote" }, { group: "Text styles", action: "formatMenu", label: "Text styles menu", alt: true, code: "KeyA" }, { group: "Formatting", action: "bold", label: "Bold", mod: true, code: "KeyB", native: true }, { group: "Formatting", action: "italic", label: "Italic", mod: true, code: "KeyI", native: true }, @@ -120,8 +121,8 @@ export function reservedReason(combo, isMac) { const label = hotkeyLabel(combo, isMac); if (!combo.mod && !combo.alt && !FUNCTION_KEY.test(combo.code)) return `Add ${isMac ? "⌘ or ⌥" : "Ctrl or Alt"}, so the key doesn't just type.`; if (!isMac && combo.alt && combo.shift && !combo.mod) return "Alt+Shift switches the keyboard language on Windows."; - if (combo.mod && !combo.alt && (combo.shift ? CHROME_MOD_SHIFT_KEYS : CHROME_MOD_KEYS).has(combo.code)) return `Chrome keeps ${label} for itself.`; - if (!isMac && combo.alt && !combo.mod && !combo.shift && WINDOWS_ALT_KEYS.has(combo.code)) return `${label} is kept by Chrome or Windows.`; + if (combo.mod && !combo.alt && (combo.shift ? CHROME_MOD_SHIFT_KEYS : CHROME_MOD_KEYS).has(combo.code)) return `${label} is reserved by the browser engine Notelet runs on.`; + if (!isMac && combo.alt && !combo.mod && !combo.shift && WINDOWS_ALT_KEYS.has(combo.code)) return `${label} is reserved by Windows or the browser engine.`; return null; } diff --git a/extension/icons/icon-128.png b/app/icons/icon-128.png similarity index 100% rename from extension/icons/icon-128.png rename to app/icons/icon-128.png diff --git a/extension/icons/icon-32.png b/app/icons/icon-32.png similarity index 100% rename from extension/icons/icon-32.png rename to app/icons/icon-32.png diff --git a/extension/layout.js b/app/layout.js similarity index 100% rename from extension/layout.js rename to app/layout.js diff --git a/extension/lines.js b/app/lines.js similarity index 71% rename from extension/lines.js rename to app/lines.js index 8c2009d..d2faf3b 100644 --- a/extension/lines.js +++ b/app/lines.js @@ -1,6 +1,6 @@ // Line editing works on blocks: a paragraph, heading, Monostyled block or list item is one line. // shortcut: a block broken by Shift+Enter or "\n" still moves as one line; split on those if users ask. -export const LINE_SELECTOR = "h1,h2,h3,p,pre,li,div"; +export const LINE_SELECTOR = "h1,h2,h3,p,pre,blockquote,li,div"; export const ABOVE = -1; export const BELOW = 1; @@ -51,6 +51,44 @@ export function outdentText(line) { return true; } +// A Monostyled block holds several lines, split by
or "\n"; Tab over a selection in it +// indents each of those the selection touches, as in VS Code. Inserting into the text nodes keeps +// the selection on the same text. +export function indentCodeLines(block, range) { + for (const { node, offset } of codeLineStarts(block, range)) node.insertData(offset, "\t"); +} + +export function outdentCodeLines(block, range) { + for (const { node, offset } of codeLineStarts(block, range)) if (node.data[offset] === "\t") node.deleteData(offset, 1); +} + +// Where each line with text starts, last first so edits don't move the ones still to come. A +// selection that ends at the very start of a line leaves that line out. +function codeLineStarts(block, range) { + const starts = []; + let atLineStart = true; + const walker = block.ownerDocument.createTreeWalker(block, 5); + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + if (node.nodeName === "BR") { + atLineStart = true; + } else if (node.nodeType === TEXT_NODE && node.length > 0) { + [...node.data].forEach((character, index) => { + if (index === 0 ? atLineStart : node.data[index - 1] === "\n") starts.push({ node, offset: index }); + }); + atLineStart = node.data.endsWith("\n"); + } + } + const touched = starts.filter((start, index) => { + const next = starts[index + 1]; + const startsBeforeEnd = range.comparePoint(start.node, start.offset) <= 0 && !isPoint(start, range.endContainer, range.endOffset); + const endsAfterStart = !next || (range.comparePoint(next.node, next.offset) >= 0 && !isPoint(next, range.startContainer, range.startOffset)); + return startsBeforeEnd && endsAfterStart; + }); + return touched.reverse(); +} + +const isPoint = (point, node, offset) => point.node === node && point.offset === offset; + export function lineOf(root, node) { const line = (node.nodeType === TEXT_NODE ? node.parentElement : node).closest(LINE_SELECTOR); return line && line !== root && root.contains(line) ? line : null; diff --git a/extension/lists.js b/app/lists.js similarity index 86% rename from extension/lists.js rename to app/lists.js index 8caf0a9..587cdb0 100644 --- a/extension/lists.js +++ b/app/lists.js @@ -105,10 +105,28 @@ export function splitParagraphsIntoItems(item) { const LIST_SHORTCUTS = { "-": "dashed", "*": "bulleted", "•": "bulleted", "1.": "numbered", "1)": "numbered" }; const CHECKBOX_SHORTCUTS = { "[ ]": false, "[]": false, "[x]": true, "[X]": true }; +const BLOCK_SHORTCUTS = { "#": "h1", "##": "h2", "###": "h3" }; const TEXT_NODE = 3; export const listKindForShortcut = (prefix) => (Object.hasOwn(LIST_SHORTCUTS, prefix) ? LIST_SHORTCUTS[prefix] : null); +export const blockTagForShortcut = (prefix) => (Object.hasOwn(BLOCK_SHORTCUTS, prefix) ? BLOCK_SHORTCUTS[prefix] : null); + +const isLineBreak = (node) => node?.nodeName === "BR"; + +// Chrome ends a Monostyled block whose last two lines are empty with three
s: the break after +// the last text, the first empty line's, and the one that lets the second empty line show. +export function endsWithTwoEmptyLines(block) { + const last = block.lastChild; + return isLineBreak(last) && isLineBreak(last.previousSibling) && isLineBreak(last.previousSibling.previousSibling); +} + +export function removeTwoEmptyLines(block) { + block.lastChild.remove(); + block.lastChild.remove(); + block.lastChild.remove(); +} + export const checkboxForShortcut = (prefix) => (Object.hasOwn(CHECKBOX_SHORTCUTS, prefix) ? { checked: CHECKBOX_SHORTCUTS[prefix] } : null); export function removeLeadingText(element, count) { diff --git a/extension/merge.js b/app/merge.js similarity index 100% rename from extension/merge.js rename to app/merge.js diff --git a/extension/model.js b/app/model.js similarity index 97% rename from extension/model.js rename to app/model.js index 346d728..4ae8e51 100644 --- a/extension/model.js +++ b/app/model.js @@ -2,8 +2,8 @@ import { trackerTitle } from "./tracker.js"; const DAY_MS = 86_400_000; const RECENTLY_DELETED_DAYS = 30; -const TEXT_BLOCKS = "h1,h2,h3,p,pre,li,div"; -const NESTED_BLOCKS = "ul,ol,p,h1,h2,h3,pre,div"; +const TEXT_BLOCKS = "h1,h2,h3,p,pre,blockquote,li,div"; +const NESTED_BLOCKS = "ul,ol,p,h1,h2,h3,pre,blockquote,div"; const FALLBACK_TITLE = "New Note"; const FALLBACK_PREVIEW = "No additional text"; diff --git a/extension/navigation.js b/app/navigation.js similarity index 100% rename from extension/navigation.js rename to app/navigation.js diff --git a/extension/notes.css b/app/notes.css similarity index 88% rename from extension/notes.css rename to app/notes.css index 84e2ba0..7be0dc3 100644 --- a/extension/notes.css +++ b/app/notes.css @@ -19,6 +19,14 @@ --sheet-card: #ffffff; --toast-bg: #1c1c1e; --toast-text: #ffffff; + /* Code colours (code-highlight.js), GitHub's. */ + --code-comment: #6e7781; + --code-keyword: #cf222e; + --code-string: #0a3069; + --code-number: #0550ae; + --code-function: #8250df; + --code-tag: #116329; + --code-variable: #953800; --check-mark: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 8.5l2.5 2.5L12 5.5' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); } @@ -43,6 +51,13 @@ --sheet-card: #2c2c2e; --toast-bg: #f2f2f7; --toast-text: #1c1c1e; + --code-comment: #8b949e; + --code-keyword: #ff7b72; + --code-string: #a5d6ff; + --code-number: #79c0ff; + --code-function: #d2a8ff; + --code-tag: #7ee787; + --code-variable: #ffa657; --check-mark: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 8.5l2.5 2.5L12 5.5' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); } } @@ -67,6 +82,13 @@ --sheet-card: #2c2c2e; --toast-bg: #f2f2f7; --toast-text: #1c1c1e; + --code-comment: #8b949e; + --code-keyword: #ff7b72; + --code-string: #a5d6ff; + --code-number: #79c0ff; + --code-function: #d2a8ff; + --code-tag: #7ee787; + --code-variable: #ffa657; --check-mark: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 8.5l2.5 2.5L12 5.5' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); } @@ -75,7 +97,10 @@ * { box-sizing: border-box; } [hidden] { display: none !important; } html, body { height: 100%; margin: 0; } -body { background: var(--bg); color: var(--text); font: 1rem/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; } +/* → ← ↔ ⟶ ⟵ ⟷ ⇒ ⇐ ⇔ ⟹ ⟸ ⟺ ≤ ≥ ≠ drawn as JetBrains Mono's wide ligatures (fonts/OFL.txt); every other character keeps the system font. */ +@font-face { font-family: "Notelet Arrows"; src: url("fonts/notelet-arrows-regular.woff2") format("woff2"); font-weight: 100 599; unicode-range: U+2190, U+2192, U+2194, U+21D0, U+21D2, U+21D4, U+2260, U+2264, U+2265, U+27F5-27FA; } +@font-face { font-family: "Notelet Arrows"; src: url("fonts/notelet-arrows-bold.woff2") format("woff2"); font-weight: 600 900; unicode-range: U+2190, U+2192, U+2194, U+21D0, U+21D2, U+21D4, U+2260, U+2264, U+2265, U+27F5-27FA; } +body { background: var(--bg); color: var(--text); font: 1rem/1.45 "Notelet Arrows", system-ui, -apple-system, "Segoe UI", sans-serif; } button { font: inherit; color: inherit; } button, input[type="color"], input[type="date"]::-webkit-calendar-picker-indicator { cursor: pointer; } button:disabled { cursor: default; } @@ -147,7 +172,7 @@ body:not(.viewing-deleted) #recover-button { display: none; } ::highlight(search-match) { background-color: rgb(255 214 10 / 0.3); } .find-lozenge { position: fixed; z-index: 10; padding: 0 3px; border-radius: 4px; background: #ffd60a; color: #000000; box-shadow: 0 1px 4px rgb(0 0 0 / 0.4); white-space: pre; pointer-events: none; } /* A 46rem column keeps lines readable on wide screens. */ -.editor-scroll { flex: 1; overflow-y: auto; padding: 0 max(clamp(1.5rem, 5vw, 3rem), (100% - 46rem) / 2) 4rem; } +.editor-scroll { position: relative; flex: 1; overflow-y: auto; padding: 0 max(clamp(1.5rem, 5vw, 3rem), (100% - 46rem) / 2) 4rem; } .note-date { margin: 0.25rem 0 1rem; text-align: center; font-size: 0.8rem; color: var(--secondary); } .empty-state { margin: 30vh 0 0; text-align: center; color: var(--secondary); } @@ -158,7 +183,33 @@ body:not(.viewing-deleted) #recover-button { display: none; } .editor h3 { margin: 0.9rem 0 0.35rem; font-size: 1rem; font-weight: 700; } .editor > :first-child { margin-top: 0; } .editor p { margin: 0; } -.editor pre { margin: 0; font: 0.95rem/1.5 ui-monospace, Consolas, monospace; white-space: pre-wrap; } +/* Monostyled lines in a row read as one rounded block, as in Notes. */ +.editor pre { margin: 0; padding: 0 0.75rem; background: var(--fill); font: 0.95rem/1.5 ui-monospace, Consolas, monospace; white-space: pre-wrap; } +.editor pre:not(pre + pre) { position: relative; margin-top: 0.4rem; padding-top: 1.7rem; border-top-left-radius: 8px; border-top-right-radius: 8px; } +/* The block's language in its top-right corner; the toolbar (code-toolbar.js) covers it on hover. */ +.editor pre:not(pre + pre)::before { + content: attr(data-language) / ""; position: absolute; top: 0.4rem; right: 0.75rem; + font: 0.75rem/1.2 system-ui, -apple-system, "Segoe UI", sans-serif; color: var(--secondary); pointer-events: none; user-select: none; +} +.editor pre:not(pre + pre):not([data-language])::before { content: "plain text" / ""; } +::highlight(code-comment) { color: var(--code-comment); } +::highlight(code-keyword) { color: var(--code-keyword); } +::highlight(code-string) { color: var(--code-string); } +::highlight(code-number) { color: var(--code-number); } +::highlight(code-function) { color: var(--code-function); } +::highlight(code-tag) { color: var(--code-tag); } +::highlight(code-variable) { color: var(--code-variable); } +.code-toolbar { + position: absolute; display: flex; align-items: center; height: 1.6rem; border: 1px solid var(--separator); border-radius: 6px; + background: var(--card); color: var(--secondary); font: 0.75rem/1.2 system-ui, -apple-system, "Segoe UI", sans-serif; +} +.code-toolbar[hidden] { display: none; } +.code-toolbar select { field-sizing: content; height: 100%; padding: 0 0.3rem; border: 0; border-radius: 5px 0 0 5px; background: none; color: inherit; font: inherit; } +.code-toolbar button { display: grid; place-items: center; height: 100%; padding: 0 0.4rem; border: 0; border-left: 1px solid var(--separator); border-radius: 0 5px 5px 0; background: none; color: inherit; } +.code-toolbar :is(select, button):hover { background: var(--hover); color: var(--text); } +.code-toolbar .icon { width: 0.95rem; height: 0.95rem; } +.editor pre:not(:has(+ pre)) { margin-bottom: 0.4rem; padding-bottom: 0.5rem; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; } +.editor blockquote { margin: 0; padding-left: 0.85rem; border-left: 3px solid var(--separator); } .editor ul, .editor ol { margin: 0; padding-left: 2rem; } .editor ul.dashed { list-style: none; } .editor ul.dashed > li { position: relative; } @@ -269,7 +320,7 @@ body:not(.viewing-deleted) #recover-button { display: none; } /* The note text belongs to a sprint screen; the other screens hide it. */ .board[data-screen="all"] ~ .editor, .board[data-screen="task"] ~ .editor { display: none; } .board-notes-label { margin: 0 0 0.4rem; font-size: 1.05rem; font-weight: 700; } -/* In the popup the status moves under the task so the title keeps most of the row. */ +/* In a narrow window the status moves under the task so the title keeps most of the row. */ @container (max-width: 300px) { .task-row { grid-template-columns: minmax(0, 1fr) 3.25rem; } .task-row .task-status { grid-column: 1; justify-self: start; margin: 0 0 0.45rem 1rem; } diff --git a/extension/notes.html b/app/notes.html similarity index 98% rename from extension/notes.html rename to app/notes.html index 08bd9e0..89e46d8 100644 --- a/extension/notes.html +++ b/app/notes.html @@ -6,6 +6,7 @@ Notelet + @@ -82,6 +83,7 @@

Notes

+ @@ -170,7 +172,6 @@

Keyboard Shortcuts

-

To open Notelet from anywhere, set a shortcut at chrome://extensions/shortcuts.

diff --git a/extension/sanitize.js b/app/sanitize.js similarity index 91% rename from extension/sanitize.js rename to app/sanitize.js index 82ac731..d084714 100644 --- a/extension/sanitize.js +++ b/app/sanitize.js @@ -1,3 +1,4 @@ +import { isCodeLanguage } from "./code-block.js"; import { parseHtml } from "./model.js"; const ELEMENT_NODE = 1; @@ -9,13 +10,13 @@ const KEPT_TAGS = { b: "b", strong: "b", i: "i", em: "i", u: "u", s: "s", strike: "s", del: "s", a: "a", br: "br", }; const PARAGRAPH_LIKE = new Set([ - "div", "section", "article", "blockquote", "tr", "header", "footer", "main", "figure", "figcaption", "dt", "dd", "address", "caption", + "div", "section", "article", "tr", "header", "footer", "main", "figure", "figcaption", "dt", "dd", "address", "caption", ]); const DROPPED = new Set([ "script", "style", "img", "picture", "video", "audio", "iframe", "object", "embed", "svg", "canvas", "template", "noscript", "head", "title", "meta", "link", "button", "input", "select", "textarea", ]); -const BLOCK_TAGS = new Set([...PARAGRAPH_LIKE, "h1", "h2", "h3", "h4", "h5", "h6", "p", "pre", "ul", "ol", "li", "table", "tbody", "thead", "tfoot"]); +const BLOCK_TAGS = new Set([...PARAGRAPH_LIKE, "h1", "h2", "h3", "h4", "h5", "h6", "p", "pre", "blockquote", "ul", "ol", "li", "table", "tbody", "thead", "tfoot"]); const CELL_TAGS = new Set(["td", "th"]); const LIST_CLASSES = new Set(["checklist", "dashed"]); const CHECKED_VALUES = new Set(["true", "false"]); @@ -23,7 +24,7 @@ const POINTS_VALUE = /^\d+(\.\d+)?$/; const STATUS_ID = /^[a-z0-9-]{1,24}$/; const SECTION_IDS = new Set(["last", "current"]); const SAFE_URL = /^(https?:|mailto:)/i; -const ROOT_BLOCKS = new Set(["h1", "h2", "h3", "p", "pre", "ul", "ol"]); +const ROOT_BLOCKS = new Set(["h1", "h2", "h3", "p", "pre", "blockquote", "ul", "ol"]); const BOLD_TAGS = new Set(["b", "strong"]); const NOT_BOLD_STYLE = /font-weight:\s*(normal|[1-4]00)\b/i; const LIST_TAGS = new Set(["UL", "OL"]); @@ -153,6 +154,8 @@ function cleanTagFor(element, tag) { // Google Docs wraps a whole copy in . if (BOLD_TAGS.has(tag) && NOT_BOLD_STYLE.test(element.getAttribute("style") ?? "")) return null; if (Object.hasOwn(KEPT_TAGS, tag)) return KEPT_TAGS[tag]; + // A quote is one line, like a paragraph; a pasted quote of several paragraphs comes in as them. + if (tag === "blockquote") return hasBlockChild(element) ? null : "blockquote"; if (PARAGRAPH_LIKE.has(tag)) return hasBlockChild(element) ? null : "p"; return null; } @@ -168,6 +171,7 @@ function copyAllowedAttributes(source, clean, tag) { if (kind) clean.setAttribute("class", kind); } if (tag === "li") copyTicketAttributes(source, clean); + if (tag === "pre" && isCodeLanguage(source.getAttribute("data-language"))) clean.setAttribute("data-language", source.getAttribute("data-language")); if (tag === "h2" && SECTION_IDS.has(source.getAttribute("data-section"))) clean.setAttribute("data-section", source.getAttribute("data-section")); } diff --git a/extension/scheduler.js b/app/scheduler.js similarity index 100% rename from extension/scheduler.js rename to app/scheduler.js diff --git a/extension/sections.js b/app/sections.js similarity index 100% rename from extension/sections.js rename to app/sections.js diff --git a/extension/selection.js b/app/selection.js similarity index 98% rename from extension/selection.js rename to app/selection.js index 325a8fa..be7d5b2 100644 --- a/extension/selection.js +++ b/app/selection.js @@ -1,4 +1,4 @@ -const BLOCK_SELECTOR = "h1,h2,h3,p,pre,li,div"; +const BLOCK_SELECTOR = "h1,h2,h3,p,pre,blockquote,li,div"; export function caretElement(root) { const selection = document.getSelection(); diff --git a/extension/shortcut-editor.js b/app/shortcut-editor.js similarity index 98% rename from extension/shortcut-editor.js rename to app/shortcut-editor.js index 726b675..9d4324a 100644 --- a/extension/shortcut-editor.js +++ b/app/shortcut-editor.js @@ -78,7 +78,7 @@ function recordKey(event, { id, keys, isMac }) { const reason = reservedReason(combo, isMac); if (reason) return { message: { id, text: reason } }; const other = hotkeysWith(keys).find((hotkey) => hotkey.id !== id && sameCombo(hotkey, combo)); - if (other && !isEditable(other)) return { message: { id, text: `${hotkeyLabel(combo, isMac)} is ${other.label}, which Chrome handles.` } }; + if (other && !isEditable(other)) return { message: { id, text: `${hotkeyLabel(combo, isMac)} is ${other.label}, which is built in.` } }; if (other) return { message: { id, combo, otherId: other.id, text: `${hotkeyLabel(combo, isMac)} is used by ${other.label}.` } }; return { keys: withKey(keys, id, combo) }; } @@ -127,7 +127,7 @@ function keyCell(hotkey, { isMac, changed, isRecording }) { const label = hotkeyLabel(hotkey, isMac) || "None"; if (!isEditable(hotkey)) { cell.append(createElement("span", "key-fixed", label)); - cell.title = "Chrome handles this key"; + cell.title = "Built-in key"; return cell; } const key = actionButton({ className: `key-button${changed ? " key-changed" : ""}${isRecording ? " key-recording" : ""}`, action: "record", text: isRecording ? "Press keys…" : label }); diff --git a/extension/sidebar.js b/app/sidebar.js similarity index 100% rename from extension/sidebar.js rename to app/sidebar.js diff --git a/extension/sprint-settings.js b/app/sprint-settings.js similarity index 100% rename from extension/sprint-settings.js rename to app/sprint-settings.js diff --git a/extension/sprint.js b/app/sprint.js similarity index 99% rename from extension/sprint.js rename to app/sprint.js index 9589c12..0ba1147 100644 --- a/extension/sprint.js +++ b/app/sprint.js @@ -19,7 +19,7 @@ const DONE_STATUS_ID = "s5"; const MAX_LABEL_LENGTH = 20; const STATUS_ID = /^[a-z0-9-]{1,24}$/; const HEX_COLOR = /^#[0-9a-f]{6}$/i; -const LINE_BLOCKS = "h1,h2,h3,p,pre,li,div"; +const LINE_BLOCKS = "h1,h2,h3,p,pre,blockquote,li,div"; const TARGET_LINE = /^Target:\s*(\d+(?:\.\d+)?)$/i; const TITLE_RANGE = /(\d{1,2})\/(\d{1,2})\s*[-–]\s*(\d{1,2})\/(\d{1,2})/; diff --git a/extension/store.js b/app/store.js similarity index 97% rename from extension/store.js rename to app/store.js index a425c10..1d8642c 100644 --- a/extension/store.js +++ b/app/store.js @@ -23,7 +23,7 @@ export function createStore(area) { async function load(area, today) { const stored = await area.get(null); const version = stored[SCHEMA_KEY] ?? 0; - if (version > SCHEMA_VERSION) throw new Error("These notes were saved by a newer version of Notelet. Update the extension to open them."); + if (version > SCHEMA_VERSION) throw new Error("These notes were saved by a newer version of Notelet. Update Notelet to open them."); const settings = stored[SETTINGS_KEY] ? normalizeSettings(stored[SETTINGS_KEY]) : defaultSettings(); const storedNotes = Object.entries(stored).filter(([key]) => key.startsWith(NOTE_PREFIX)).map(([, note]) => note); const notes = version < SCHEMA_VERSION ? upgradeNotes(storedNotes, { stored, settings, today }) : storedNotes; diff --git a/extension/theme.js b/app/theme.js similarity index 100% rename from extension/theme.js rename to app/theme.js diff --git a/extension/ticket-text.js b/app/ticket-text.js similarity index 100% rename from extension/ticket-text.js rename to app/ticket-text.js diff --git a/extension/tracker.js b/app/tracker.js similarity index 100% rename from extension/tracker.js rename to app/tracker.js diff --git a/app/typography.js b/app/typography.js new file mode 100644 index 0000000..034993e --- /dev/null +++ b/app/typography.js @@ -0,0 +1,45 @@ +// macOS-style substitutions: what was typed becomes the typographic character, and Undo +// right after gives the typed text back. +// Longest first, so "<=>" is not read as "=>" with a "<" before it. +const SUBSTITUTIONS = [ + ["<-->", "⟷"], + ["<==>", "⟺"], + ["===>", "⟹"], + ["<===", "⟸"], + ["<->", "↔"], + ["<=>", "⇔"], + ["-->", "⟶"], + ["<--", "⟵"], + ["==>", "⇒"], + ["<==", "⇐"], + ["...", "…"], + ["->", "→"], + ["<-", "←"], + ["<=", "≤"], + [">=", "≥"], + ["=>", "≥"], + ["!=", "≠"], + ["--", "—"], +]; +// "--->" or "<<=" is something else being typed, not a symbol with a stray character before it. +const TOKEN_CHARACTERS = new Set(["-", "<", ">", "=", ".", "!"]); +const OPENING_CONTEXT = /[\s([{“‘—–]/; +const SMART_QUOTES = { '"': ["“", "”"], "'": ["‘", "’"] }; + +// The substitution for the text just before the caret, or null when it ends with none. +export function substitutionBefore(text) { + const match = SUBSTITUTIONS.find(([typed]) => text.endsWith(typed)); + if (!match) return null; + const [typed, replacement] = match; + if (TOKEN_CHARACTERS.has(text.at(-typed.length - 1))) return null; + return { typed, replacement }; +} + +export const isStraightQuote = (key) => Object.hasOwn(SMART_QUOTES, key); + +// A quote at the start of a line or after a space or bracket opens; anywhere else, as in +// "don't", it closes. +export function smartQuote(quote, previousCharacter) { + const [opening, closing] = SMART_QUOTES[quote]; + return !previousCharacter || OPENING_CONTEXT.test(previousCharacter) ? opening : closing; +} diff --git a/app/vendor/prism-LICENSE.txt b/app/vendor/prism-LICENSE.txt new file mode 100644 index 0000000..528949f --- /dev/null +++ b/app/vendor/prism-LICENSE.txt @@ -0,0 +1,21 @@ +MIT LICENSE + +Copyright (c) 2012 Lea Verou + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/vendor/prism.js b/app/vendor/prism.js new file mode 100644 index 0000000..d430744 --- /dev/null +++ b/app/vendor/prism.js @@ -0,0 +1,16 @@ +/* Prism 1.29.0 (MIT, see prism-LICENSE.txt), https://prismjs.com: core with markup, css, clike, javascript, + markup-templating, php, bash, json, markdown, python, sql, typescript, yaml. Load with data-manual. */ +var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(e){var n=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,t=0,r={},a={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(n){return n instanceof i?new i(n.type,e(n.content),n.alias):Array.isArray(n)?n.map(e):n.replace(/&/g,"&").replace(/=g.reach);A+=w.value.length,w=w.next){var E=w.value;if(n.length>e.length)return;if(!(E instanceof i)){var P,L=1;if(y){if(!(P=l(b,A,e,m))||P.index>=e.length)break;var S=P.index,O=P.index+P[0].length,j=A;for(j+=w.value.length;S>=j;)j+=(w=w.next).value.length;if(A=j-=w.value.length,w.value instanceof i)continue;for(var C=w;C!==n.tail&&(jg.reach&&(g.reach=W);var z=w.prev;if(_&&(z=u(n,z,_),A+=_.length),c(n,z,L),w=u(n,z,new i(f,p?a.tokenize(N,p):N,k,N)),M&&u(n,w,M),L>1){var I={cause:f+","+d,reach:W};o(e,n,t,w.prev,A,I),g&&I.reach>g.reach&&(g.reach=I.reach)}}}}}}function s(){var e={value:null,prev:null,next:null},n={value:null,prev:e,next:null};e.next=n,this.head=e,this.tail=n,this.length=0}function u(e,n,t){var r=n.next,a={value:t,prev:n,next:r};return n.next=a,r.prev=a,e.length++,a}function c(e,n,t){for(var r=n.next,a=0;a"+i.content+""},!e.document)return e.addEventListener?(a.disableWorkerMessageHandler||e.addEventListener("message",(function(n){var t=JSON.parse(n.data),r=t.language,i=t.code,l=t.immediateClose;e.postMessage(a.highlight(i,a.languages[r],r)),l&&e.close()}),!1),a):a;var g=a.util.currentScript();function f(){a.manual||a.highlightAll()}if(g&&(a.filename=g.src,g.hasAttribute("data-manual")&&(a.manual=!0)),!a.manual){var h=document.readyState;"loading"===h||"interactive"===h&&g&&g.defer?document.addEventListener("DOMContentLoaded",f):window.requestAnimationFrame?window.requestAnimationFrame(f):window.setTimeout(f,16)}return a}(_self);"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); +Prism.languages.markup={comment:{pattern://,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern://i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity,Prism.languages.markup.doctype.inside["internal-subset"].inside=Prism.languages.markup,Prism.hooks.add("wrap",(function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&/,"&"))})),Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(a,e){var s={};s["language-"+e]={pattern:/(^$)/i,lookbehind:!0,inside:Prism.languages[e]},s.cdata=/^$/i;var t={"included-cdata":{pattern://i,inside:s}};t["language-"+e]={pattern:/[\s\S]+/,inside:Prism.languages[e]};var n={};n[a]={pattern:RegExp("(<__[^>]*>)(?:))*\\]\\]>|(?!)".replace(/__/g,(function(){return a})),"i"),lookbehind:!0,greedy:!0,inside:t},Prism.languages.insertBefore("markup","cdata",n)}}),Object.defineProperty(Prism.languages.markup.tag,"addAttribute",{value:function(a,e){Prism.languages.markup.tag.inside["special-attr"].push({pattern:RegExp("(^|[\"'\\s])(?:"+a+")\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s'\">=]+(?=[\\s>]))","i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[e,"language-"+e],inside:Prism.languages[e]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup,Prism.languages.xml=Prism.languages.extend("markup",{}),Prism.languages.ssml=Prism.languages.xml,Prism.languages.atom=Prism.languages.xml,Prism.languages.rss=Prism.languages.xml; +!function(s){var e=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;s.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:[^;{\\s\"']|\\s+(?!\\s)|"+e.source+")*?(?:;|(?=\\s*\\{))"),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+e.source+"|(?:[^\\\\\r\n()\"']|\\\\[^])*)\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+e.source+"$"),alias:"url"}}},selector:{pattern:RegExp("(^|[{}\\s])[^{}\\s](?:[^{};\"'\\s]|\\s+(?![\\s{])|"+e.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:e,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},s.languages.css.atrule.inside.rest=s.languages.css;var t=s.languages.markup;t&&(t.tag.addInlined("style","css"),t.tag.addAttribute("style","css"))}(Prism); +Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}; +Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp("(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])"),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp("((?:^|[^$\\w\\xA0-\\uFFFF.\"'\\])\\s]|\\b(?:return|yield))\\s*)/(?:(?:\\[(?:[^\\]\\\\\r\n]|\\\\.)*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}|(?:\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.)*\\])*\\])*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}v[dgimyus]{0,7})(?=(?:\\s|/\\*(?:[^*]|\\*(?!/))*\\*/)*(?:$|[\r\n,.;:})\\]]|//))"),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),Prism.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),Prism.languages.markup&&(Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.markup.tag.addAttribute("on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)","javascript")),Prism.languages.js=Prism.languages.javascript; +!function(e){function n(e,n){return"___"+e.toUpperCase()+n+"___"}Object.defineProperties(e.languages["markup-templating"]={},{buildPlaceholders:{value:function(t,a,r,o){if(t.language===a){var c=t.tokenStack=[];t.code=t.code.replace(r,(function(e){if("function"==typeof o&&!o(e))return e;for(var r,i=c.length;-1!==t.code.indexOf(r=n(a,i));)++i;return c[i]=e,r})),t.grammar=e.languages.markup}}},tokenizePlaceholders:{value:function(t,a){if(t.language===a&&t.tokenStack){t.grammar=e.languages[a];var r=0,o=Object.keys(t.tokenStack);!function c(i){for(var u=0;u=o.length);u++){var g=i[u];if("string"==typeof g||g.content&&"string"==typeof g.content){var l=o[r],s=t.tokenStack[l],f="string"==typeof g?g:g.content,p=n(a,l),k=f.indexOf(p);if(k>-1){++r;var m=f.substring(0,k),d=new e.Token(a,e.tokenize(s,t.grammar),"language-"+a,s),h=f.substring(k+p.length),v=[];m&&v.push.apply(v,c([m])),v.push(d),h&&v.push.apply(v,c([h])),"string"==typeof g?i.splice.apply(i,[u,1].concat(v)):g.content=v}}else g.content&&c(g.content)}return i}(t.tokens)}}}})}(Prism); +!function(e){var a=/\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/,t=[{pattern:/\b(?:false|true)\b/i,alias:"boolean"},{pattern:/(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,greedy:!0,lookbehind:!0},{pattern:/(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,greedy:!0,lookbehind:!0},/\b(?:null)\b/i,/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/],i=/\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i,n=/|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/,s=/[{}\[\](),:;]/;e.languages.php={delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"},comment:a,variable:/\$+(?:\w+\b|(?=\{))/,package:{pattern:/(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,lookbehind:!0,inside:{punctuation:/\\/}},"class-name-definition":{pattern:/(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,lookbehind:!0,alias:"class-name"},"function-definition":{pattern:/(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,lookbehind:!0,alias:"function"},keyword:[{pattern:/(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,alias:"type-casting",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,alias:"type-declaration",greedy:!0},{pattern:/(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,alias:"type-declaration",greedy:!0,lookbehind:!0},{pattern:/\b(?:parent|self|static)(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(\byield\s+)from\b/i,lookbehind:!0},/\bclass\b/i,{pattern:/((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,lookbehind:!0}],"argument-name":{pattern:/([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,lookbehind:!0},"class-name":[{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/(\|\s*)\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,greedy:!0},{pattern:/(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,alias:"class-name-fully-qualified",greedy:!0,inside:{punctuation:/\\/}},{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*\$)/i,alias:"type-declaration",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-declaration"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,alias:["class-name-fully-qualified","static-context"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-hint"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:["class-name-fully-qualified","return-type"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,function:{pattern:/(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,lookbehind:!0,inside:{punctuation:/\\/}},property:{pattern:/(->\s*)\w+/,lookbehind:!0},number:i,operator:n,punctuation:s};var l={pattern:/\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,lookbehind:!0,inside:e.languages.php},r=[{pattern:/<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,alias:"nowdoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},{pattern:/<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:l}},{pattern:/`(?:\\[\s\S]|[^\\`])*`/,alias:"backtick-quoted-string",greedy:!0},{pattern:/'(?:\\[\s\S]|[^\\'])*'/,alias:"single-quoted-string",greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,alias:"double-quoted-string",greedy:!0,inside:{interpolation:l}}];e.languages.insertBefore("php","variable",{string:r,attribute:{pattern:/#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,greedy:!0,inside:{"attribute-content":{pattern:/^(#\[)[\s\S]+(?=\]$)/,lookbehind:!0,inside:{comment:a,string:r,"attribute-class-name":[{pattern:/([^:]|^)\b[a-z_]\w*(?!\\)\b/i,alias:"class-name",greedy:!0,lookbehind:!0},{pattern:/([^:]|^)(?:\\?\b[a-z_]\w*)+/i,alias:["class-name","class-name-fully-qualified"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,number:i,operator:n,punctuation:s}},delimiter:{pattern:/^#\[|\]$/,alias:"punctuation"}}}}),e.hooks.add("before-tokenize",(function(a){/<\?/.test(a.code)&&e.languages["markup-templating"].buildPlaceholders(a,"php",/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g)})),e.hooks.add("after-tokenize",(function(a){e.languages["markup-templating"].tokenizePlaceholders(a,"php")}))}(Prism); +!function(e){var t="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",a={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:"punctuation",inside:null},n={bash:a,environment:{pattern:RegExp("\\$"+t),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+t),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+t),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:n},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:a}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:n},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:n.entity}}],environment:{pattern:RegExp("\\$?"+t),alias:"constant"},variable:n.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},a.inside=e.languages.bash;for(var s=["comment","function-name","for-or-select","assign-left","parameter","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],o=n.variable[1].inside,i=0;i/g,(function(){return"(?:\\\\.|[^\\\\\n\r]|(?:\n|\r\n?)(?![\r\n]))"})),RegExp("((?:^|[^\\\\])(?:\\\\{2})*)(?:"+n+")")}var t="(?:\\\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\\\|\r\n`])+",a="\\|?__(?:\\|__)+\\|?(?:(?:\n|\r\n?)|(?![^]))".replace(/__/g,(function(){return t})),i="\\|?[ \t]*:?-{3,}:?[ \t]*(?:\\|[ \t]*:?-{3,}:?[ \t]*)+\\|?(?:\n|\r\n?)";n.languages.markdown=n.languages.extend("markup",{}),n.languages.insertBefore("markdown","prolog",{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:["yaml","language-yaml"],inside:n.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+a+i+"(?:"+a+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+a+i+")(?:"+a+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(t),inside:n.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+a+")"+i+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+a+"$"),inside:{"table-header":{pattern:RegExp(t),alias:"important",inside:n.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:e("\\b__(?:(?!_)|_(?:(?!_))+_)+__\\b|\\*\\*(?:(?!\\*)|\\*(?:(?!\\*))+\\*)+\\*\\*"),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:e("\\b_(?:(?!_)|__(?:(?!_))+__)+_\\b|\\*(?:(?!\\*)|\\*\\*(?:(?!\\*))+\\*\\*)+\\*"),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:e("(~~?)(?:(?!~))+\\2"),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:["code","keyword"]},url:{pattern:e('!?\\[(?:(?!\\]))+\\](?:\\([^\\s)]+(?:[\t ]+"(?:\\\\.|[^"\\\\])*")?\\)|[ \t]?\\[(?:(?!\\]))+\\])'),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),["url","bold","italic","strike"].forEach((function(e){["url","bold","italic","strike","code-snippet"].forEach((function(t){e!==t&&(n.languages.markdown[e].inside.content.inside[t]=n.languages.markdown[t])}))})),n.hooks.add("after-tokenize",(function(n){"markdown"!==n.language&&"md"!==n.language||function n(e){if(e&&"string"!=typeof e)for(var t=0,a=e.length;t",quot:'"'},l=String.fromCodePoint||String.fromCharCode;n.languages.md=n.languages.markdown}(Prism); +Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python; +Prism.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/}; +!function(e){e.languages.typescript=e.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),e.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete e.languages.typescript.parameter,delete e.languages.typescript["literal-property"];var s=e.languages.extend("typescript",{});delete s["class-name"],e.languages.typescript["class-name"].inside=s,e.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:s}}}}),e.languages.ts=e.languages.typescript}(Prism); +!function(e){var n=/[*&][^\s[\]{},]+/,r=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,t="(?:"+r.source+"(?:[ \t]+"+n.source+")?|"+n.source+"(?:[ \t]+"+r.source+")?)",a="(?:[^\\s\\x00-\\x08\\x0e-\\x1f!\"#%&'*,\\-:>?@[\\]`{|}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]|[?:-])(?:[ \t]*(?:(?![#:])|:))*".replace(//g,(function(){return"[^\\s\\x00-\\x08\\x0e-\\x1f,[\\]{}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]"})),d="\"(?:[^\"\\\\\r\n]|\\\\.)*\"|'(?:[^'\\\\\r\n]|\\\\.)*'";function o(e,n){n=(n||"").replace(/m/g,"")+"m";var r="([:\\-,[{]\\s*(?:\\s<>[ \t]+)?)(?:<>)(?=[ \t]*(?:$|,|\\]|\\}|(?:[\r\n]\\s*)?#))".replace(/<>/g,(function(){return t})).replace(/<>/g,(function(){return e}));return RegExp(r,n)}e.languages.yaml={scalar:{pattern:RegExp("([\\-:]\\s*(?:\\s<>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\\S[^\r\n]*(?:\\2[^\r\n]+)*)".replace(/<>/g,(function(){return t}))),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp("((?:^|[:\\-,[{\r\n?])[ \t]*(?:<>[ \t]+)?)<>(?=\\s*:\\s)".replace(/<>/g,(function(){return t})).replace(/<>/g,(function(){return"(?:"+a+"|"+d+")"}))),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:o("\\d{4}-\\d\\d?-\\d\\d?(?:[tT]|[ \t]+)\\d\\d?:\\d{2}:\\d{2}(?:\\.\\d*)?(?:[ \t]*(?:Z|[-+]\\d\\d?(?::\\d{2})?))?|\\d{4}-\\d{2}-\\d{2}|\\d\\d?:\\d{2}(?::\\d{2}(?:\\.\\d*)?)?"),lookbehind:!0,alias:"number"},boolean:{pattern:o("false|true","i"),lookbehind:!0,alias:"important"},null:{pattern:o("null|~","i"),lookbehind:!0,alias:"important"},string:{pattern:o(d),lookbehind:!0,greedy:!0},number:{pattern:o("[+-]?(?:0x[\\da-f]+|0o[0-7]+|(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|\\.inf|\\.nan)","i"),lookbehind:!0},tag:r,important:n,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},e.languages.yml=e.languages.yaml}(Prism); diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index e9ded34..69a30f8 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "notelet" -version = "0.10.2" +version = "0.11.0" description = "Lightweight notes with sprint tracking" edition = "2021" publish = false diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.json index e127e6f..5485e29 100644 --- a/desktop/tauri.conf.json +++ b/desktop/tauri.conf.json @@ -1,10 +1,10 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Notelet", - "version": "0.10.2", + "version": "0.11.0", "identifier": "com.ttncode.notelet", "build": { - "frontendDist": "../extension" + "frontendDist": "../app" }, "app": { "withGlobalTauri": true, diff --git a/extension/icons/icon-16.png b/extension/icons/icon-16.png deleted file mode 100644 index 02b4944..0000000 Binary files a/extension/icons/icon-16.png and /dev/null differ diff --git a/extension/icons/icon-48.png b/extension/icons/icon-48.png deleted file mode 100644 index 3fc1419..0000000 Binary files a/extension/icons/icon-48.png and /dev/null differ diff --git a/package-lock.json b/package-lock.json index 5392745..7d1af29 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "notelet", - "version": "0.10.2", + "version": "0.11.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "notelet", - "version": "0.10.2", + "version": "0.11.0", "devDependencies": { "@tauri-apps/cli": "^2.12.4", "linkedom": "^0.18.13" diff --git a/package.json b/package.json index 36784bf..f37ef6e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "notelet", - "version": "0.10.2", + "version": "0.11.0", "private": true, "type": "module", "scripts": { diff --git a/tests-e2e/app.e2e.js b/tests-e2e/app.e2e.js index 8a6f228..e707351 100644 --- a/tests-e2e/app.e2e.js +++ b/tests-e2e/app.e2e.js @@ -1,7 +1,7 @@ // Runs against the built app through tauri-driver (see .github/workflows/ci.yml); not part of npm test. import { after, before, test } from "node:test"; import assert from "node:assert/strict"; -import { HOTKEYS } from "../extension/hotkeys.js"; +import { HOTKEYS } from "../app/hotkeys.js"; import { newSession } from "./webdriver.js"; const APPLICATION = process.env.NOTELET_APP ?? "desktop/target/release/notelet.exe"; diff --git a/tests/backup.test.js b/tests/backup.test.js index ae684e2..e51981a 100644 --- a/tests/backup.test.js +++ b/tests/backup.test.js @@ -1,8 +1,8 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { backupFileName, createBackup, parseBackup } from "../extension/backup.js"; -import { DEFAULT_SECTIONS } from "../extension/sections.js"; -import { defaultSettings } from "../extension/sprint.js"; +import { backupFileName, createBackup, parseBackup } from "../app/backup.js"; +import { DEFAULT_SECTIONS } from "../app/sections.js"; +import { defaultSettings } from "../app/sprint.js"; const SETTINGS = defaultSettings(); diff --git a/tests/board-merge.test.js b/tests/board-merge.test.js index eed91a6..8fe8ae1 100644 --- a/tests/board-merge.test.js +++ b/tests/board-merge.test.js @@ -1,8 +1,8 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { mergeTrackers } from "../extension/board-merge.js"; -import { isValidBoard, sprintName } from "../extension/board.js"; +import { mergeTrackers } from "../app/board-merge.js"; +import { isValidBoard, sprintName } from "../app/board.js"; const NOW = Date.UTC(2026, 9, 10); const DONE = "s5"; diff --git a/tests/board.test.js b/tests/board.test.js index 3412643..6cd4ea5 100644 --- a/tests/board.test.js +++ b/tests/board.test.js @@ -4,8 +4,8 @@ import assert from "node:assert/strict"; import { BACKLOG_ID, currentSprint, findTask, isValidBoard, monthProgress, monthsOf, moveOpenTasks, moveTask, newBoard, newSprint, removeSprint, pointsByStatus, setMonthGoal, sprintDays, sprintName, sprintPhase, sprintProgress, boardSearchText, -} from "../extension/board.js"; -import { DEFAULT_STATUSES } from "../extension/sprint.js"; +} from "../app/board.js"; +import { DEFAULT_STATUSES } from "../app/sprint.js"; const DONE = "s5"; const QC = "s4"; diff --git a/tests/case.test.js b/tests/case.test.js index 2375ef1..a74b598 100644 --- a/tests/case.test.js +++ b/tests/case.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { nextCase, wordAt } from "../extension/case.js"; +import { nextCase, wordAt } from "../app/case.js"; const press = (text) => nextCase(text)(text); diff --git a/tests/clipboard.test.js b/tests/clipboard.test.js index e0a61e5..1098436 100644 --- a/tests/clipboard.test.js +++ b/tests/clipboard.test.js @@ -1,9 +1,9 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { clipboardHtml, clipboardText, selectedContent } from "../extension/clipboard.js"; -import { parseHtml } from "../extension/model.js"; -import { sanitizeHtml } from "../extension/sanitize.js"; +import { clipboardHtml, clipboardText, selectedContent } from "../app/clipboard.js"; +import { parseHtml } from "../app/model.js"; +import { sanitizeHtml } from "../app/sanitize.js"; const NOTE = '

Todo

Heading

Body bold link

' + '
  • Done item
  • Open item
' @@ -88,3 +88,10 @@ test("inline styles left in a note by the browser stay out of the copied HTML", assert.doesNotMatch(html, /font-size|color/); assert.match(html, /]*style="list-style: none; padding-left: 0"/); }); + +test("code copied with other lines is fenced with its language; code alone and plain code are not", () => { + const code = '
echo 1;
echo 2;
'; + assert.equal(clipboardText(root(`

Run:

${code}

Done

`)), ["Run:", "```php", "echo 1;", "echo 2;", "```", "Done"].join("\n")); + assert.equal(clipboardText(root(code)), "echo 1;\necho 2;"); + assert.equal(clipboardText(root("

Run:

ls
")), "Run:\nls"); +}); diff --git a/tests/code-block.test.js b/tests/code-block.test.js new file mode 100644 index 0000000..8feb27a --- /dev/null +++ b/tests/code-block.test.js @@ -0,0 +1,49 @@ +import "./dom.js"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { codeBlockLines, fenceLanguage, isCodeLanguage, languageOf, setLanguage, unifyCodeLanguages } from "../app/code-block.js"; +import { parseHtml } from "../app/model.js"; + +const body = (html) => parseHtml(html).body; + +test("a code block is the run of Monostyled lines around a line", () => { + const note = body("

a

one
two
three

b

other
"); + const lines = codeBlockLines(note.querySelectorAll("pre")[1]); + assert.deepEqual(lines.map((line) => line.textContent), ["one", "two", "three"]); +}); + +test("setting a language marks every line of the block, and plain text clears it", () => { + const note = body("
one
two
"); + const lines = codeBlockLines(note.firstChild); + setLanguage(lines, "php"); + assert.equal(note.innerHTML, '
one
two
'); + setLanguage(lines, ""); + assert.equal(note.innerHTML, "
one
two
"); +}); + +test("a block's language is the first known one on its lines", () => { + const note = body('
one
two
three
'); + assert.equal(languageOf(codeBlockLines(note.firstChild)), "bash"); + assert.equal(languageOf(codeBlockLines(body("
x
").firstChild)), ""); +}); + +test("a code fence gives its language, with the usual short names", () => { + assert.equal(fenceLanguage("```"), ""); + assert.equal(fenceLanguage("```php"), "php"); + assert.equal(fenceLanguage("```JS"), "javascript"); + assert.equal(fenceLanguage("```sh"), "bash"); + assert.equal(fenceLanguage("```cobol"), null); + assert.equal(fenceLanguage("``"), null); + assert.equal(fenceLanguage("text ```php"), null); +}); + +test("plain text is not a language", () => { + assert.equal(isCodeLanguage(""), false); + assert.equal(isCodeLanguage("python"), true); +}); + +test("a line that joins a code block takes its language, and a block that already agrees is left alone", () => { + const note = body('
// header
echo 1;

x

SELECT 1;
'); + unifyCodeLanguages(note); + assert.equal(note.innerHTML, '
// header
echo 1;

x

SELECT 1;
'); +}); diff --git a/tests/code-highlight.test.js b/tests/code-highlight.test.js new file mode 100644 index 0000000..90b3db4 --- /dev/null +++ b/tests/code-highlight.test.js @@ -0,0 +1,38 @@ +import "./dom.js"; +import "../app/vendor/prism.js"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { HIGHLIGHT_GROUPS, tokenRanges } from "../app/code-highlight.js"; + +const coloured = (text, language) => tokenRanges(text, language).map(({ group, start, end }) => [group, text.slice(start, end)]); + +test("every menu language has a Prism grammar", () => { + for (const language of ["bash", "css", "html", "javascript", "json", "markdown", "php", "python", "sql", "typescript", "yaml"]) { + assert.ok(globalThis.Prism.languages[language], language); + } +}); + +test("bash commands, strings and comments get their colours", () => { + assert.deepEqual(coloured('echo "hi" # note', "bash"), [["function", "echo"], ["string", '"hi"'], ["comment", "# note"]]); +}); + +test("a token's plain inner text takes the colour of the token around it", () => { + assert.deepEqual(coloured("const s = `a ${b}`;", "javascript").filter(([group]) => group === "string"), [["string", "`"], ["string", "a "], ["string", "`"]]); +}); + +test("offsets run across lines", () => { + const text = " group === "comment" && part === "// say hi")); +}); + +test("plain text and unknown languages get no colours", () => { + assert.deepEqual(tokenRanges("echo hi", ""), []); + assert.deepEqual(tokenRanges("echo hi", "cobol"), []); +}); + +test("every colour group has a CSS rule", async () => { + const { readFile } = await import("node:fs/promises"); + const css = await readFile(new URL("../app/notes.css", import.meta.url), "utf8"); + for (const group of HIGHLIGHT_GROUPS) assert.match(css, new RegExp(`::highlight\\(code-${group}\\)`), group); +}); diff --git a/tests/desktop.test.js b/tests/desktop.test.js index 8fd82b4..9d41f1e 100644 --- a/tests/desktop.test.js +++ b/tests/desktop.test.js @@ -1,9 +1,9 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { createFileArea, historyKey, recoveryMessage, whenShown } from "../extension/desktop.js"; -import { DEFAULT_UI, SCHEMA_VERSION, createStore } from "../extension/store.js"; -import { defaultSettings } from "../extension/sprint.js"; +import { createFileArea, historyKey, recoveryMessage, whenShown } from "../app/desktop.js"; +import { DEFAULT_UI, SCHEMA_VERSION, createStore } from "../app/store.js"; +import { defaultSettings } from "../app/sprint.js"; function fakeBackend(initial = {}, { recovered = null, damagedPath = null } = {}) { const calls = []; diff --git a/tests/dialogs.test.js b/tests/dialogs.test.js index 9d43665..060d808 100644 --- a/tests/dialogs.test.js +++ b/tests/dialogs.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { isPointOutside } from "../extension/dialogs.js"; +import { isPointOutside } from "../app/dialogs.js"; const RECT = { left: 100, top: 50, right: 400, bottom: 300 }; @@ -21,13 +21,13 @@ test("a toast can carry one action button that runs and closes the toast", async const { parseHTML } = await import("linkedom"); const { document } = parseHTML(''); globalThis.document = document; - const { showToast } = await import("../extension/dialogs.js"); + const { showToast } = await import("../app/dialogs.js"); let ran = 0; - showToast("Moving from the extension?", { label: "Import backup", run: () => { ran += 1; } }); + showToast("Restore from a backup?", { label: "Import backup", run: () => { ran += 1; } }); const toast = document.getElementById("toast"); const button = toast.querySelector("button"); assert.equal(toast.hidden, false); - assert.match(toast.textContent, /Moving from the extension\?/); + assert.match(toast.textContent, /Restore from a backup\?/); assert.equal(button.textContent, "Import backup"); button.click(); assert.equal(ran, 1); diff --git a/tests/find.test.js b/tests/find.test.js index cda3b2e..65cd07a 100644 --- a/tests/find.test.js +++ b/tests/find.test.js @@ -1,8 +1,8 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { parseHtml } from "../extension/model.js"; -import { findMatches } from "../extension/find.js"; +import { parseHtml } from "../app/model.js"; +import { findMatches } from "../app/find.js"; const note = (html) => parseHtml(html).body; const spans = (matches) => matches.map(({ start, end }) => [start.node.data, start.offset, end.node.data, end.offset]); diff --git a/tests/format.test.js b/tests/format.test.js index fc9f8bc..2c7804f 100644 --- a/tests/format.test.js +++ b/tests/format.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { formatDayMonth, formatEditedDate, formatRowDate } from "../extension/format.js"; +import { formatDayMonth, formatEditedDate, formatRowDate } from "../app/format.js"; const NOW = new Date(2026, 9, 8, 22, 30).getTime(); diff --git a/tests/history.test.js b/tests/history.test.js index 705dde7..4acd857 100644 --- a/tests/history.test.js +++ b/tests/history.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { History } from "../extension/history.js"; +import { History } from "../app/history.js"; const state = (html) => ({ html, caret: html.length }); diff --git a/tests/hotkeys.test.js b/tests/hotkeys.test.js index 8bbe77f..560a290 100644 --- a/tests/hotkeys.test.js +++ b/tests/hotkeys.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { HOTKEYS, fillShortcuts, hotkeyLabel, matchHotkey, normalizeCustomKeys, reservedReason, setCustomKeys } from "../extension/hotkeys.js"; +import { HOTKEYS, fillShortcuts, hotkeyLabel, matchHotkey, normalizeCustomKeys, reservedReason, setCustomKeys } from "../app/hotkeys.js"; const key = (code, modifiers = {}) => ({ code, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, isComposing: false, ...modifiers, @@ -112,10 +112,10 @@ test("a changed shortcut matches its new key, and a removed one matches nothing" test("keys the browser or Windows keep, and keys without Ctrl or Alt, are refused with a reason", () => { const combo = (code, modifiers) => ({ mod: false, alt: false, shift: false, code, ...modifiers }); - assert.match(reservedReason(combo("KeyT", { mod: true }), false), /Chrome keeps Ctrl\+T/); - assert.match(reservedReason(combo("KeyN", { mod: true, shift: true }), false), /Chrome keeps/); + assert.match(reservedReason(combo("KeyT", { mod: true }), false), /Ctrl\+T is reserved by the browser engine/); + assert.match(reservedReason(combo("KeyN", { mod: true, shift: true }), false), /reserved by the browser engine/); assert.match(reservedReason(combo("KeyK", { alt: true, shift: true }), false), /keyboard language/); - assert.match(reservedReason(combo("KeyF", { alt: true }), false), /Chrome or Windows/); + assert.match(reservedReason(combo("KeyF", { alt: true }), false), /Windows or the browser engine/); assert.match(reservedReason(combo("KeyK", {}), false), /Ctrl or Alt/); assert.equal(reservedReason(combo("F3", { shift: true }), false), null); assert.equal(reservedReason(combo("KeyK", { mod: true, alt: true }), false), null); @@ -142,5 +142,5 @@ test("no shortcut works from other apps, and a key saved for the old one is drop }); test("in-app key rules are unchanged", () => { - assert.equal(reservedReason(plainCombo("KeyN", { mod: true }), false), "Chrome keeps Ctrl+N for itself."); + assert.equal(reservedReason(plainCombo("KeyN", { mod: true }), false), "Ctrl+N is reserved by the browser engine Notelet runs on."); }); diff --git a/tests/lines.test.js b/tests/lines.test.js index ddd3612..57fb673 100644 --- a/tests/lines.test.js +++ b/tests/lines.test.js @@ -1,10 +1,10 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { parseHtml } from "../extension/model.js"; +import { parseHtml } from "../app/model.js"; import { ABOVE, BELOW, duplicateLine, indentText, insertLine, lineOf, moveLines, nextLine, outdentText, previousLine, removeLine, -} from "../extension/lines.js"; +} from "../app/lines.js"; const NOTE = "

Title

one

  • a
    • nested
  • b

two

"; const note = (html = NOTE) => parseHtml(html).body; diff --git a/tests/lists.test.js b/tests/lists.test.js index 7e9c6ba..478d19e 100644 --- a/tests/lists.test.js +++ b/tests/lists.test.js @@ -1,10 +1,11 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { parseHtml } from "../extension/model.js"; +import { parseHtml } from "../app/model.js"; import { - checkboxForShortcut, itemCreatedBySplit, liftListOutOfParagraph, listKindForShortcut, removeLeadingText, setBlockType, splitParagraphsIntoItems, -} from "../extension/lists.js"; + blockTagForShortcut, checkboxForShortcut, endsWithTwoEmptyLines, itemCreatedBySplit, liftListOutOfParagraph, listKindForShortcut, removeTwoEmptyLines, removeLeadingText, + setBlockType, splitParagraphsIntoItems, +} from "../app/lists.js"; function paragraphWith(...children) { const doc = parseHtml(""); @@ -151,3 +152,23 @@ test("an item without pasted lines is left alone", () => { assert.equal(splitParagraphsIntoItems(body.querySelector("li")).size, 0); assert.equal(body.innerHTML, "
  • a
"); }); + +test("Markdown heading shortcuts give their line style", () => { + assert.equal(blockTagForShortcut("#"), "h1"); + assert.equal(blockTagForShortcut("##"), "h2"); + assert.equal(blockTagForShortcut("###"), "h3"); + assert.equal(blockTagForShortcut("####"), null); + assert.equal(blockTagForShortcut("#tag"), null); +}); + +test("a Monostyled block ending in two empty lines loses them and keeps the rest", () => { + const block = parseHtml("
abc

def


").body.firstChild; + assert.equal(endsWithTwoEmptyLines(block), true); + removeTwoEmptyLines(block); + assert.equal(block.outerHTML, "
abc

def
"); +}); + +test("one empty line at the end of a Monostyled block is kept as part of the code", () => { + assert.equal(endsWithTwoEmptyLines(parseHtml("
abc

").body.firstChild), false); + assert.equal(endsWithTwoEmptyLines(parseHtml("
abc
def
").body.firstChild), false); +}); diff --git a/tests/merge.test.js b/tests/merge.test.js index 0b79ce5..75c7ab3 100644 --- a/tests/merge.test.js +++ b/tests/merge.test.js @@ -1,9 +1,9 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { createOwnSaves, mergeBoard, mergeHtml, mergeNote, mergeSequence, mergeValue } from "../extension/merge.js"; -import { createFileArea } from "../extension/desktop.js"; -import { SCHEMA_VERSION, createStore } from "../extension/store.js"; +import { createOwnSaves, mergeBoard, mergeHtml, mergeNote, mergeSequence, mergeValue } from "../app/merge.js"; +import { createFileArea } from "../app/desktop.js"; +import { SCHEMA_VERSION, createStore } from "../app/store.js"; test("an older save that finishes after a newer one started is still this window's own", () => { const saves = createOwnSaves(); diff --git a/tests/model.test.js b/tests/model.test.js index 099a8f2..44e717a 100644 --- a/tests/model.test.js +++ b/tests/model.test.js @@ -4,7 +4,7 @@ import assert from "node:assert/strict"; import { EMPTY_NOTE_HTML, isEmptyNote, isExpired, newNote, noteLines, notePreview, noteText, noteTitle, orderedGroups, placeNote, stepNote, -} from "../extension/model.js"; +} from "../app/model.js"; const DAY_MS = 86_400_000; const NOW = new Date(2026, 9, 8, 15, 0).getTime(); diff --git a/tests/sanitize.test.js b/tests/sanitize.test.js index d18e409..177ce57 100644 --- a/tests/sanitize.test.js +++ b/tests/sanitize.test.js @@ -1,8 +1,8 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { parseHtml } from "../extension/model.js"; -import { linkableUrl, normalizeLineBreaks, plainTextToHtml, sanitizeHtml, sanitizePastedHtml } from "../extension/sanitize.js"; +import { parseHtml } from "../app/model.js"; +import { linkableUrl, normalizeLineBreaks, plainTextToHtml, sanitizeHtml, sanitizePastedHtml } from "../app/sanitize.js"; test("keeps the editor's own structure unchanged", () => { const html = '

T

H

S

a b c d e

' @@ -118,3 +118,13 @@ test("punctuation typed after a URL stays out of the link", () => { assert.equal(linkableUrl("https://a.com/wiki/A_(b)"), "https://a.com/wiki/A_(b)"); assert.equal(linkableUrl("https://a.com/?q=1"), "https://a.com/?q=1"); }); + +test("a one-line block quote is kept; a quote of several paragraphs comes in as the paragraphs", () => { + assert.equal(sanitizeHtml("
said so
"), "
said so
"); + assert.equal(sanitizePastedHtml("

one

two

"), "

one

two

"); +}); + +test("a code line keeps a known language and drops an unknown one", () => { + assert.equal(sanitizeHtml('
x
'), '
x
'); + assert.equal(sanitizeHtml('
x
'), "
x
"); +}); diff --git a/tests/scheduler.test.js b/tests/scheduler.test.js index d6090bd..05d69c0 100644 --- a/tests/scheduler.test.js +++ b/tests/scheduler.test.js @@ -1,6 +1,6 @@ import { test, mock } from "node:test"; import assert from "node:assert/strict"; -import { createSaveScheduler } from "../extension/scheduler.js"; +import { createSaveScheduler } from "../app/scheduler.js"; function setup() { mock.timers.enable({ apis: ["setTimeout", "Date"] }); diff --git a/tests/sections.test.js b/tests/sections.test.js index 844ffcb..22d5651 100644 --- a/tests/sections.test.js +++ b/tests/sections.test.js @@ -1,9 +1,9 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { parseHtml } from "../extension/model.js"; -import { DEFAULT_SECTIONS, ensureSprintSections, extractTracker, isValidSections } from "../extension/sections.js"; -import { DEFAULT_STATUSES } from "../extension/sprint.js"; +import { parseHtml } from "../app/model.js"; +import { DEFAULT_SECTIONS, ensureSprintSections, extractTracker, isValidSections } from "../app/sections.js"; +import { DEFAULT_STATUSES } from "../app/sprint.js"; const SECTIONED = '

Sprint

' + '

Last Sprint

  • old
' diff --git a/tests/sprint-migration.test.js b/tests/sprint-migration.test.js index 1cb49ac..1c0436b 100644 --- a/tests/sprint-migration.test.js +++ b/tests/sprint-migration.test.js @@ -1,8 +1,8 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { parseHtml } from "../extension/model.js"; -import { DEFAULT_STATUSES, migrateTargetNote } from "../extension/sprint.js"; +import { parseHtml } from "../app/model.js"; +import { DEFAULT_STATUSES, migrateTargetNote } from "../app/sprint.js"; const UPDATED_2026 = new Date(2026, 9, 1).getTime(); const TODAY = new Date(2026, 9, 8); diff --git a/tests/sprint.test.js b/tests/sprint.test.js index e3c7839..7d16972 100644 --- a/tests/sprint.test.js +++ b/tests/sprint.test.js @@ -1,11 +1,11 @@ import "./dom.js"; -import { DEFAULT_SECTIONS } from "../extension/sections.js"; +import { DEFAULT_SECTIONS } from "../app/sections.js"; import { test } from "node:test"; import assert from "node:assert/strict"; import { DEFAULT_STATUSES, addDays, defaultSettings, isIsoDate, isValidSprint, isValidStatus, parsePoints, normalizeSettings, sameSettings, statusFor, upgradeNote, validateSprintSettings, -} from "../extension/sprint.js"; +} from "../app/sprint.js"; test("an unknown status shows as the first", () => { assert.equal(statusFor(DEFAULT_STATUSES, "gone").id, "s1"); diff --git a/tests/store.test.js b/tests/store.test.js index 9efc208..2029d53 100644 --- a/tests/store.test.js +++ b/tests/store.test.js @@ -1,8 +1,8 @@ import "./dom.js"; import { test } from "node:test"; import assert from "node:assert/strict"; -import { DEFAULT_UI, SCHEMA_VERSION, createStore } from "../extension/store.js"; -import { defaultSettings } from "../extension/sprint.js"; +import { DEFAULT_UI, SCHEMA_VERSION, createStore } from "../app/store.js"; +import { defaultSettings } from "../app/sprint.js"; function fakeArea(initial = {}) { const data = { ...initial }; diff --git a/tests/theme.test.js b/tests/theme.test.js index b34d068..13fe51f 100644 --- a/tests/theme.test.js +++ b/tests/theme.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { nextTheme, themeLabel } from "../extension/theme.js"; +import { nextTheme, themeLabel } from "../app/theme.js"; test("the theme cycles System, Light, Dark and back", () => { assert.equal(nextTheme("system"), "light"); diff --git a/tests/tracker.test.js b/tests/tracker.test.js index dae4c32..aa53d31 100644 --- a/tests/tracker.test.js +++ b/tests/tracker.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { roundPoints, trackerTitle } from "../extension/tracker.js"; +import { roundPoints, trackerTitle } from "../app/tracker.js"; test("an old tracker with an empty title is called Task Tracking", () => { assert.equal(trackerTitle({ title: " " }), "Task Tracking"); diff --git a/tests/typography.test.js b/tests/typography.test.js new file mode 100644 index 0000000..6e0eeaa --- /dev/null +++ b/tests/typography.test.js @@ -0,0 +1,49 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { isStraightQuote, smartQuote, substitutionBefore } from "../app/typography.js"; + +test("arrows, the ellipsis and the em dash replace what was typed", () => { + const replaced = (text) => substitutionBefore(text)?.replacement ?? null; + assert.equal(replaced("C2 ->"), "→"); + assert.equal(replaced("C2->"), "→"); + assert.equal(replaced("back <-"), "←"); + assert.equal(replaced("A <->"), "↔"); + assert.equal(replaced("then -->"), "⟶"); + assert.equal(replaced("from <--"), "⟵"); + assert.equal(replaced("so ==>"), "⇒"); + assert.equal(replaced("from <=="), "⇐"); + assert.equal(replaced("so ===>"), "⟹"); + assert.equal(replaced("from <==="), "⟸"); + assert.equal(replaced("A <=>"), "⇔"); + assert.equal(replaced("A <==>"), "⟺"); + assert.equal(replaced("A <-->"), "⟷"); + assert.equal(replaced("a !="), "≠"); + assert.equal(replaced("a <="), "≤"); + assert.equal(replaced("a >="), "≥"); + assert.equal(replaced("a =>"), "≥"); + assert.equal(replaced("wait..."), "…"); + assert.equal(replaced("word --"), "—"); +}); + +test("the substitution reports the typed text it replaces", () => { + assert.deepEqual(substitutionBefore("A <->"), { typed: "<->", replacement: "↔" }); +}); + +test("longer runs of the same characters stay as typed", () => { + for (const text of ["--->", "<--->", "<===>", "<<=>", "....", "---", "<---", "====>", "<====", ">=>", "<<=", "!!=", "!==", "plain", ""]) assert.equal(substitutionBefore(text), null, text); +}); + +test("a quote opens at a line start or after a space or bracket, and closes elsewhere", () => { + assert.equal(smartQuote('"', undefined), "“"); + assert.equal(smartQuote('"', " "), "“"); + assert.equal(smartQuote('"', "("), "“"); + assert.equal(smartQuote('"', "d"), "”"); + assert.equal(smartQuote("'", "n"), "’"); + assert.equal(smartQuote("'", " "), "‘"); +}); + +test("only the two straight quotes are smart-quoted", () => { + assert.equal(isStraightQuote('"'), true); + assert.equal(isStraightQuote("'"), true); + assert.equal(isStraightQuote("`"), false); +}); diff --git a/tests/webdriver-keys.test.js b/tests/webdriver-keys.test.js index 9df4d0a..9e7ac35 100644 --- a/tests/webdriver-keys.test.js +++ b/tests/webdriver-keys.test.js @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { HOTKEYS } from "../extension/hotkeys.js"; +import { HOTKEYS } from "../app/hotkeys.js"; import { keyValue } from "../tests-e2e/webdriver.js"; test("WebDriver key values for letters, digits, function keys and punctuation", () => { diff --git a/tools/build-arrow-font.py b/tools/build-arrow-font.py new file mode 100644 index 0000000..a29558d --- /dev/null +++ b/tools/build-arrow-font.py @@ -0,0 +1,96 @@ +# Builds "Notelet Arrows": → ← ↔ ⟶ ⟵ ⟷ ⇒ ⇐ ⇔ ⟹ ⟸ ⟺ ≤ ≥ ≠ drawn as JetBrains Mono's ligatures. +# +# pip install fonttools brotli +# # JetBrainsMono-2.304.zip from https://github.com/JetBrains/JetBrainsMono/releases, unzipped +# python3 tools/build-arrow-font.py fonts/ttf/JetBrainsMono-Regular.ttf app/fonts/notelet-arrows-regular.woff2 Regular +# python3 tools/build-arrow-font.py fonts/ttf/JetBrainsMono-Bold.ttf app/fonts/notelet-arrows-bold.woff2 Bold +# +# A code point added here also goes in the unicode-range of "Notelet Arrows" in notes.css. +import sys +from fontTools.pens.reverseContourPen import ReverseContourPen +from fontTools.pens.transformPen import TransformPen +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.subset import Options, Subsetter +from fontTools.ttLib import TTFont + +# Space on each side of a glyph, so it sits in text like a letter rather than in a code cell. +SIDE_BEARING = 80 +CELL = 600 +# code point: the ligature glyphs drawn for it, as (glyph, whether it is mirrored). A second glyph +# is drawn one cell further right, over the first. +ARROWS = { + 0x2192: [("hyphen_greater.liga", False)], + 0x2190: [("less_hyphen.liga", False)], + 0x2194: [("less_hyphen_greater.liga", False)], + 0x27F6: [("hyphen_hyphen_greater.liga", False)], + 0x27F5: [("less_hyphen_hyphen.liga", False)], + # JetBrains Mono has no "<-->", so ⟷ is ⟵ and ⟶ with their shafts overlapping. + 0x27F7: [("less_hyphen_hyphen.liga", False), ("hyphen_hyphen_greater.liga", False)], + # JetBrains Mono has no short left double arrow, so ⇐ is ⇒ mirrored. + 0x21D2: [("equal_greater.liga", False)], + 0x21D0: [("equal_greater.liga", True)], + 0x21D4: [("less_equal_greater.liga", False)], + 0x27F9: [("equal_equal_greater.liga", False)], + 0x27F8: [("less_equal_equal.liga", False)], + 0x27FA: [("less_equal_equal_greater.liga", False)], + 0x2264: [("less_equal.liga", False)], + 0x2265: [("greater_equal.liga", False)], + 0x2260: [("exclam_equal.liga", False)], +} +FAMILY = "Notelet Arrows" + + +def build(source, target, style): + font = TTFont(source) + glyf, hmtx = font["glyf"], font["hmtx"] + glyph_set = font.getGlyphSet() + cmap = font.getBestCmap() + # The characters' own glyphs are replaced by their ligature drawing, moved right so it starts + # just after the glyph's origin instead of reaching back over the characters before it. + for code_point, parts in ARROWS.items(): + pen = TTGlyphPen(glyph_set) + for index, (ligature, mirrored) in enumerate(parts): + draw_part(glyf, glyph_set[ligature], pen, mirrored=mirrored, offset=index * CELL) + glyph = pen.glyph() + glyph.recalcBounds(glyf) + # JetBrains Mono has no glyphs for some of these (⟸ ⟹ ⟺), so those get new ones. + name = cmap.get(code_point, f"uni{code_point:04X}") + glyf[name] = glyph + hmtx[name] = (glyph.xMax + SIDE_BEARING, SIDE_BEARING) + for table in font["cmap"].tables: + if table.isUnicode(): + table.cmap[code_point] = name + font.setGlyphOrder(list(glyf.glyphOrder)) + + options = Options() + options.layout_features = [] + options.hinting = False + options.name_IDs = ["*"] + options.flavor = "woff2" + subsetter = Subsetter(options) + subsetter.populate(unicodes=list(ARROWS)) + subsetter.subset(font) + + for record in font["name"].names: + if record.nameID in (1, 16): + record.string = FAMILY + elif record.nameID in (4,): + record.string = f"{FAMILY} {style}" + elif record.nameID in (6,): + record.string = f"NoteletArrows-{style}" + font.flavor = "woff2" + font.save(target) + + +def draw_part(glyf, ligature, pen, mirrored, offset): + source = glyf[ligature.name] + source.recalcBounds(glyf) + if mirrored: + # Flipping reverses the outline's direction, so it is reversed back to stay filled. + ligature.draw(TransformPen(ReverseContourPen(pen), (-1, 0, 0, 1, source.xMax + SIDE_BEARING + offset, 0))) + else: + ligature.draw(TransformPen(pen, (1, 0, 0, 1, SIDE_BEARING - source.xMin + offset, 0))) + + +if __name__ == "__main__": + build(sys.argv[1], sys.argv[2], sys.argv[3]) diff --git a/tools/make-icons.mjs b/tools/make-icons.mjs index b58008f..0c6b787 100644 --- a/tools/make-icons.mjs +++ b/tools/make-icons.mjs @@ -1,7 +1,8 @@ import { mkdirSync, writeFileSync } from "node:fs"; import { crc32, deflateSync } from "node:zlib"; -const SIZES = [16, 32, 48, 128]; +// 32 is the window's page icon, 128 the README's. +const SIZES = [32, 128]; const SAMPLES_PER_AXIS = 4; const BACKGROUND = [232, 169, 0]; const FOREGROUND = [255, 255, 255]; @@ -12,7 +13,7 @@ const LINES = [ { top: 0.62, bottom: 0.7, left: 0.26, right: 0.58 }, ]; const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); -const OUT_DIR = new URL("../extension/icons/", import.meta.url); +const OUT_DIR = new URL("../app/icons/", import.meta.url); // Source for `npx tauri icon`, which builds the desktop app's .ico and PNGs from it. const DESKTOP_SOURCE = new URL("../desktop/icons/source.png", import.meta.url); const DESKTOP_SOURCE_SIZE = 1024;