@@ -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.
'
@@ -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 = '
")), "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("
");
+});
+
+test("one empty line at the end of a Monostyled block is kept as part of the code", () => {
+ assert.equal(endsWithTwoEmptyLines(parseHtml("
").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 bcde
'
@@ -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;