@usememos/editor 26.10.0 → 26.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,11 +5,16 @@ A block editor for standard Markdown, for React or any web app.
5
5
  - Markdown in, Markdown out: CommonMark plus GFM tables, task lists, strikethrough and autolinks. Blocks you did not edit are saved byte for byte.
6
6
  - Block editing: slash menu, a formatting toolbar, Markdown shortcuts, and a block handle on tables and code blocks.
7
7
  - One package, `@usememos/editor`, with zero runtime dependencies. It works without a framework, and `@usememos/editor/react` is a thin React wrapper.
8
+ - About 55 KB minified and gzipped, plus 3 KB of CSS: a third of what a comparable CodeMirror 6, Tiptap or Lexical setup adds (see [Performance](docs/architecture.md#performance)).
8
9
 
9
- Status: v0 in development, not published yet. [docs/syntax.md](docs/syntax.md) specifies the Markdown it reads and writes, and [docs/architecture.md](docs/architecture.md) explains how it works.
10
+ Status: early releases, published to npm as [`@usememos/editor`](https://www.npmjs.com/package/@usememos/editor). Versions follow memos' CalVer (`26.10`, `26.10.1`) and do not signal breaking changes, so pin an exact version. [docs/syntax.md](docs/syntax.md) specifies the Markdown it reads and writes, and [docs/architecture.md](docs/architecture.md) explains how it works.
10
11
 
11
12
  ## Use it
12
13
 
14
+ ```sh
15
+ npm install @usememos/editor
16
+ ```
17
+
13
18
  React:
14
19
 
15
20
  ```tsx
@@ -49,21 +54,26 @@ The same names work in `new Editor(options)` and as React props, except that Rea
49
54
  | `extensions` | `Extension[]` | Adds syntax and behavior. Built in: `math()` (`$…$` and `$$` blocks), `footnotes()` (`[^1]` and `[^1]: …`), `tags()` (`#tag`) and `mentions()` (`@name`). Extension syntax is saved verbatim, and shown as source unless the extension renders it (see `views`). |
50
55
  | `placeholder` | `string` | Shown when the document is empty. |
51
56
  | `editable` | `boolean` | Default `true`. With `false`, no editing, and links open on click. |
57
+ | `taskToggle` | `boolean` | Default `false`. While `editable` is `false`, lets the user tick and untick task items, for example for a memo's owner. Each tick emits `change` with Markdown in which only that item's `[ ]` or `[x]` changed. Ignored while `editable` is `true`. |
52
58
  | `autofocus` | `boolean \| 'start' \| 'end'` | Focuses the editor on creation, with the caret at the start or the end. |
53
59
  | `attributes` | `Record<string, string>` | Attributes for the editable root, such as `autocorrect`, `autocapitalize` or `aria-label`. |
54
60
  | `resolveImageSrc` | `(src) => string` | The URL to display for an image. The saved Markdown keeps the original `src`. |
61
+ | `theme` | `{ classes?, tokens?, colorScheme? }` | Your own classes on rendered elements, colors and fonts, and light or dark. See [Theming](#theming). |
55
62
  | `toolbar` | `boolean` | Shows the formatting toolbar on selection. Default `true`. |
63
+ | `popupContainer` | `HTMLElement` | Where menus, the toolbar and the autocomplete popup are appended. Default: the nearest open `<dialog>` or `aria-modal` ancestor of `element`, else `document.body`. |
56
64
  | `slashMenu` | `false \| string[]` | Built-in slash menu items to show, in order, or `false` for none: `text`, `heading1`, `heading2`, `heading3`, `bulletList`, `numberedList`, `todoList`, `quote`, `code`, `table`, `divider`. |
57
65
  | `labels` | `Partial<Labels>` | Overrides UI strings, for localization. See `src/labels.ts`. |
58
- | `onChange` | `(markdown: string) => void` | Called after document changes, at most once per animation frame. |
59
- | `onSubmit` | `(markdown: string) => void` | Called on Mod+Enter or Ctrl+Enter with the current Markdown, for comment boxes and chat inputs. |
60
- | `onFocus`, `onBlur` | `() => void` | Focus events. |
66
+ | `icons` | `Partial<Record<IconName, string \| Element>>` | Replaces built-in icons, which are [Lucide](https://lucide.dev) icons. A string is shown as text; an element, such as an `<svg>`, is cloned for every place it appears. Names match the `labels` keys of the same controls: the slash menu items, `duplicate`, `delete`, the table actions, `bold`, `italic`, `strike`, `inlineCode`, `link` and `blockHandle`. |
67
+ | `onChange` | `(markdown: string, editor) => void` | Called after document changes, at most once per animation frame. |
68
+ | `onSubmit` | `(markdown: string, editor) => void` | Called on Mod+Enter or Ctrl+Enter with the current Markdown, for comment boxes and chat inputs. |
69
+ | `onFocus`, `onBlur` | `(editor) => void` | Focus events. |
70
+ | `className`, `style` | | React only. Set on the element that holds the editor. |
61
71
 
62
72
  For note-style Markdown, as in the playground, use `markdown: { breaks: true, setext: false }` and `extensions: [math(), footnotes(), tags(), mentions()]`.
63
73
 
64
- `editor.setOptions({ placeholder, editable, attributes, resolveImageSrc })` changes those options while the editor runs. The other options are fixed for the editor's lifetime.
74
+ `editor.setOptions({ placeholder, editable, taskToggle, attributes, resolveImageSrc, theme })` changes those options while the editor runs. `setOptions({ extensions })` takes new callbacks for `suggestion()` extensions of the same names. The other options are fixed for the editor's lifetime.
65
75
 
66
- In React, `placeholder`, `editable`, `attributes` and `resolveImageSrc` update live. A change to the names in `extensions` recreates the editor and keeps its Markdown, so an inline array is fine. Other props are read on mount; change the component's `key` to apply new values. A `ref` gives the core `Editor` instance. A `value` that arrives while an input method (IME) is composing text is applied when the composition ends.
76
+ In React, `placeholder`, `editable`, `taskToggle`, `attributes`, `resolveImageSrc` and `theme` update live. A change to the names in `extensions` recreates the editor and keeps its Markdown, so an inline array is fine; with the same names, the callbacks of `suggestion()` extensions update live, so `items` may read React state. Other props are read on mount; change the component's `key` to apply new values. A `ref` gives the core `Editor` instance. A `value` that arrives while an input method (IME) is composing text is applied when the composition ends.
67
77
 
68
78
  For apps that manage the editor instance themselves, `useEditor(options, deps)` creates one and `<EditorContent editor={editor} />` shows it:
69
79
 
@@ -84,17 +94,22 @@ function Composer() {
84
94
  | `setMarkdown(markdown, { history? })` | Replaces the document. `history: 'clear'` (default) clears undo history; `'keep'` makes the replacement one undo step. Does not emit `change`. |
85
95
  | `isEmpty` | True when the document holds only empty paragraphs. |
86
96
  | `state` | The document and selection, immutable. |
87
- | `commands.*` | Edits. Each applies one change, records one undo step, and returns `true` if it did something: `toggleBold`, `toggleItalic`, `toggleStrike`, `toggleCode`, `setParagraph`, `toggleHeading({ level })`, `toggleBulletList`, `toggleOrderedList`, `toggleTaskList`, `toggleBlockquote`, `toggleCodeBlock({ language? })`, `setLink({ href })`, `unsetLink`, `insertText(text, { range? })`, `insertMarkdown(markdown, options?)`, `insertTable({ rows?, cols? })`, `insertDivider`, `indent`, `outdent`, `undo`, `redo`, `selectAll`, `selectBlocks`, `focus(position?)`, `blur`. `selectBlocks` selects the blocks the selection touches as whole blocks, as Escape does; it returns `false` when read-only. |
97
+ | `commands.*` | Edits. Each applies one change, records one undo step, and returns `true` if it did something: `toggleBold`, `toggleItalic`, `toggleStrike`, `toggleCode`, `setParagraph`, `toggleHeading({ level })`, `toggleBulletList`, `toggleOrderedList`, `toggleTaskList`, `toggleBlockquote`, `toggleCodeBlock({ language? })`, `setLink({ href })`, `unsetLink`, `insertText(text, { range? })`, `insertMarkdown(markdown, options?)`, `insertTable({ rows?, cols? })`, `insertDivider`, `indent`, `outdent`, `undo`, `redo`, `selectAll`, `selectBlocks`, `focus(position?)`, `blur`, `scrollIntoView`. `selectBlocks` selects the blocks the selection touches as whole blocks, as Escape does; it returns `false` when read-only. `scrollIntoView` changes nothing in the document: it scrolls the caret into view in the editor's scrolling containers and the window, for example after an `insertMarkdown` from code. |
88
98
  | `run(fn)` | Applies a custom command: a function from state to a new state, or `null`. The pure commands are exported as `commands` from the package. |
89
99
  | `isActive(name, attrs?)` | `bold`, `italic`, `strike`, `code`, `link`, or the type of the block with the caret: `paragraph`, `heading`, `bulletList`, `orderedList`, `taskList`, `blockquote`, `codeBlock`, `table`, `divider`, `raw`. `attrs` narrows it, for example `isActive('heading', { level: 2 })`. |
90
100
  | `getAttributes(name)` | `href` of a link, `level` of a heading, `language` of a code block, `checked` of a task, `syntax` of a raw block. |
91
101
  | `selectedBlocks` | The blocks of a block selection, in document order, or an empty array when the selection is text. |
92
102
  | `getSelection()`, `setSelection(selection)` | Read or move the selection. `setSelection` also takes a `SelectionJSON`, and clamps one that does not fit the document. |
93
103
  | `selectionToJSON()` | The selection as JSON-safe data (block index and offset). It still fits after reloading the same Markdown, so an app can store the caret and restore it. |
94
- | `on(event, handler)` | Subscribes; returns an unsubscribe function. Events: `change` (at most once per frame), `selectionChange`, `focus`, `blur`, `submit`. |
104
+ | `on(event, handler)` | Subscribes; returns an unsubscribe function. Events: `change` (at most once per frame), `selectionChange`, `focus`, `blur`, `submit`, `suggestionChange` (see [Autocomplete](#autocomplete)). |
105
+ | `suggestion.*` | The autocomplete popup: `state`, `open(name?)`, `close()`, `move(delta)`, `accept(index?)`. See [Autocomplete](#autocomplete). |
95
106
  | `addWidget({ at, render })` | Shows app UI after the block that contains `at` (a position or `'end'`), such as an upload placeholder. Returns a widget with `update(render?)`, `remove()` and `isRemoved`. A widget is never saved and is not part of undo history. It moves with its block; if the block is deleted, it moves to the nearest remaining block. `insertMarkdown(md, { at: widget })` inserts after the widget's block. |
96
107
  | `positionAtPoint(x, y)` | The document position at a viewport point, or `null`. |
97
- | `hasFocus()`, `focus()`, `blur()`, `isEditable`, `setOptions(options)`, `destroy()` | |
108
+ | `submit()` | Emits a pending `change`, then `submit` with the current Markdown, as Mod+Enter does. Returns `false` when nothing listens for `submit`. |
109
+ | `root` | The editable element: `element`, or for `useEditor`, the element `<EditorContent>` shows. |
110
+ | `isComposing` | True while an input method (IME) is composing text. Replacing the document then would break the composition; the React wrapper waits for it to end. |
111
+ | `destroy()`, `isDestroyed` | Removes the editor's content, listeners and popups from the page. After it, every call that would change the editor does nothing and commands return `false`, so a late callback (an upload that finishes after the editor closed) is safe. `getMarkdown()` still returns the last Markdown. |
112
+ | `hasFocus()`, `focus()`, `blur()`, `isEditable`, `setOptions(options)` | |
98
113
 
99
114
  `insertMarkdown(markdown, { at, block, select })`: `at` is `'selection'` (default; replaces the selection, like a paste), `'end'`, a position, or a widget; the last three replace nothing. A single paragraph is inserted inline unless `block: true`, which inserts it as its own block and splits the block at the target. `select: 'keep'` keeps the current selection instead of moving the caret after the inserted content.
100
115
 
@@ -119,29 +134,81 @@ const tags: Extension = {
119
134
  textDecorator({ pattern: /\bTODO\b/, class: 'todo' })
120
135
  ```
121
136
 
122
- `tags()` and `mentions()` highlight `#tag` and `@name` (classes `mbe-tag` and `mbe-mention`), keep `\#` and `\@` as written so an escaped trigger survives edits, and take a `suggestion` for autocomplete. Tags and mentions stay plain text and are saved exactly as typed. `scan` replaces the default grammar (`scanTags`, `scanMentions`); see [docs/syntax.md](docs/syntax.md#tags-and-mentions):
137
+ `tags()` and `mentions()` highlight `#tag` and `@name` (classes `mbe-tag` and `mbe-mention`) and keep `\#` and `\@` as written, so an escaped trigger survives edits. Tags and mentions stay plain text and are saved exactly as typed. `scan` replaces the default grammar (`scanTags`, `scanMentions`); see [docs/syntax.md](docs/syntax.md#tags-and-mentions). For autocomplete, add a `suggestion()` next to them.
138
+
139
+ #### Autocomplete
140
+
141
+ `suggestion()` adds an autocomplete popup at the caret, like the ones in Linear, CodeMirror and Monaco. The editor implements the behavior: when the popup opens and closes, keys, async items, placement, IME input and accessibility. The caller decides the syntax: the triggers, what counts as a token, where the popup may open, the items, and what a pick writes. Add one per syntax:
123
142
 
124
143
  ```ts
125
- tags({
126
- class: 'tag',
127
- suggestion: {
128
- items: async ({ query }) => (await loadTags()).filter((t) => t.startsWith(query)).map((t) => ({ id: t, label: `#${t}` })),
129
- command: ({ editor, range, item }) => editor.commands.insertText(`#${item.id} `, { range }),
130
- },
131
- });
144
+ import { matchToken, mentions, scanMentions, scanTags, suggestion, tags } from '@usememos/editor';
145
+
146
+ const extensions = [
147
+ tags(),
148
+ mentions(),
149
+ // #tags: the popup opens exactly where tags are highlighted. A pick writes "#work/planning ".
150
+ suggestion({
151
+ name: 'tags',
152
+ trigger: ['#', '#'],
153
+ match: matchToken(scanTags),
154
+ label: 'Tags',
155
+ items: ({ query }) => knownTags.filter((t) => t.includes(query)).map((t) => ({ id: t, label: `#${t}` })),
156
+ }),
157
+ // @people from a server, searched as the user types.
158
+ suggestion({
159
+ name: 'people',
160
+ trigger: '@',
161
+ match: matchToken(scanMentions),
162
+ debounce: 120,
163
+ items: async ({ query, signal }) =>
164
+ (await searchPeople(query, { signal })).map((p) => ({ id: p.username, label: p.name, detail: `@${p.username}` })),
165
+ }),
166
+ // [[ links, written as Markdown links.
167
+ suggestion({
168
+ name: 'pages',
169
+ trigger: '[[',
170
+ allowSpaces: true,
171
+ items: ({ query }) => findPages(query).map((p) => ({ id: p.slug, label: p.title })),
172
+ command: ({ editor, range, item }) => {
173
+ editor.setSelection({ anchor: range.from, focus: range.to });
174
+ editor.commands.insertMarkdown(`[${item.label}](/p/${item.id})`);
175
+ },
176
+ }),
177
+ ];
132
178
  ```
133
179
 
134
- `suggestion({ char, items, command })` opens a menu when `char` is typed at the start of a line or after a space. `items({ query })` returns the items for the text typed after it, and may be async. `command({ editor, range, item })` applies the pick; `range` covers the trigger and the query. The slash menu is built on the same code. Suggestions do not open inside table cells.
180
+ | Option | Effect |
181
+ | --- | --- |
182
+ | `name` | Required, unique. Names the suggestion for `editor.suggestion.open(name)` and live updates. |
183
+ | `trigger` | One or more strings that start a token, of any length. The first is what the default command writes, so `['#', '#']` turns a full-width `#` into `#`. |
184
+ | `items({ query, signal, composing, explicit, editor })` | The items, as an array or a promise. Shown in the order given; the editor does not filter or sort. `signal` is aborted when the query changes or the popup closes. A rejection counts as no items. |
185
+ | `command({ editor, range, item, query })` | Applies a pick. `range` covers the whole token, from the trigger to its end, even when the caret is in the middle. Default: writes the first trigger, the item's `value` (default `id`, then `label`) and a space, which is left out before whitespace or closing punctuation. |
186
+ | `match` | Finds the token at the caret: `({ text, caret, content, triggers }) => ({ from, to, query }) \| null`. `matchToken(scan)` builds one from a scanner, such as the one given to `tags({ scan })`. Without `match`, the default matcher takes a trigger at the start of a line or after whitespace, followed by text with no whitespace. |
187
+ | `allow({ block, cell, from, query, textBefore, excluded, explicit, editor })` | Whether the popup may open for a match. Default: not when the trigger is in inline code, a link, an image, raw HTML or a token (`excluded`). Code and raw blocks never open a popup. `explicit` is true for Ctrl+Space. |
188
+ | `allowSpaces`, `allowAnywhere` | Default matcher only: the query may contain single spaces; the trigger may follow any character. |
189
+ | `debounce` | Waits this many ms after the last change of the query before calling `items`. Default 0. |
190
+ | `limit` | Most items shown. Default 50. |
191
+ | `maxLength` | Longest query that keeps the popup open. Default 30. |
192
+ | `emptyLabel` | Shown instead of hiding when nothing matches, for queries up to three characters. |
193
+ | `label` | Accessible name of the listbox. Default `labels.suggestions`. |
194
+ | `render: false` | Draws no popup; see below. |
195
+ | `className` | Extra classes on the popup. |
196
+
197
+ Items have `label`, and optionally `id`, `detail` (secondary text), `icon` (text or an element, such as an avatar `<img>`), `section` (a group heading) and `value`.
198
+
199
+ The popup opens when typing leaves the caret in a token: right after a trigger, or after typing inside an existing token. Moving the caret into a token does not open it, and deleting never does. Ctrl+Space (also Option+Escape on macOS) opens it for the token at the caret, even where `allow` refused, which is told `explicit: true`. It closes when the caret leaves the token; Escape closes it and keeps it closed for that token. ArrowUp and ArrowDown move through the items, Enter and Tab pick, Page Up and Page Down jump. It opens in table cells. The slash menu is a suggestion too.
200
+
201
+ With `render: false`, the editor draws nothing; the app draws the popup from `editor.suggestion.state` (`name`, `query`, `range`, `items`, `active`, `loading`, `listboxId`, `optionId(i)`, `anchorRect()`) and the `suggestionChange` event, and calls `editor.suggestion.accept(i)` on click. Keys, async items and the ARIA attributes on the editor root still work. In React, `useSuggestion(editor, name?)` returns the state and re-renders on each change:
135
202
 
136
- ```ts
137
- suggestion({
138
- char: '#',
139
- items: async ({ query }) => (await loadTags()).filter((t) => t.startsWith(query)).map((t) => ({ id: t, label: `#${t}` })),
140
- command: ({ editor, range, item }) => editor.commands.insertText(`#${item.id} `, { range }),
141
- });
203
+ ```tsx
204
+ const editor = useEditor({ extensions: [suggestion({ name: 'people', trigger: '@', render: false, items })] });
205
+ const state = useSuggestion(editor, 'people');
206
+ const rect = state?.anchorRect();
207
+ // <ul role="listbox" id={state.listboxId} style={{ position: 'fixed', left: rect.left, top: rect.bottom + 4 }}>
208
+ // {state.items.map((item, i) => <li role="option" id={state.optionId(i)} aria-selected={i === state.active} onClick={() => editor.suggestion.accept(i)}>…)}
142
209
  ```
143
210
 
144
- Other options: `allowSpaces` (the query may contain single spaces), `allowAnywhere` (open inside a word too), `maxLength` (default 30), `emptyLabel` (show this instead of hiding when nothing matches), `className`.
211
+ The popup lines up with the trigger under the caret's line, follows scrolling, resizing and the on-screen keyboard, and hides while the trigger is scrolled out of view. Its z-index is `var(--mbe-popup-z, 1000)`. See [docs/architecture.md](docs/architecture.md#autocomplete) for how it works.
145
212
 
146
213
  `fileHandler({ accept, onPaste, onDrop })` receives pasted and dropped files. `accept` takes MIME types or patterns such as `image/*`. `onPaste` runs only when the clipboard has no plain text, so text copied together with an image still pastes as text. `onDrop` gets the document position of the drop. Dropped text without files is inserted where it lands.
147
214
 
@@ -210,6 +277,8 @@ To style the editor entirely with your own classes, import `@usememos/editor/bas
210
277
  | Keys | Action |
211
278
  | --- | --- |
212
279
  | `/` | Slash menu |
280
+ | Ctrl+Space; Option+Escape on macOS | Open the autocomplete popup for the token at the caret |
281
+ | ArrowUp, ArrowDown, Enter, Tab, Escape | In an open autocomplete popup: move, pick, pick, close |
213
282
  | Mod+B, Mod+I, Mod+E | Bold, italic, inline code |
214
283
  | Mod+Shift+X, Mod+Shift+S | Strikethrough |
215
284
  | Mod+K | Link |
@@ -244,4 +313,5 @@ npm run test:e2e # browser tests (Playwright, Chromium)
244
313
  npm run test:perf # timing gates, run alone
245
314
  npm run typecheck
246
315
  npm run build # the published files, in packages/editor/dist
316
+ npm run size # what each published entry adds to an app, minified and gzipped
247
317
  ```
package/dist/base.css CHANGED
@@ -94,6 +94,7 @@
94
94
  cursor: pointer;
95
95
  }
96
96
  .mbe-root.mbe-readonly .mbe-checkbox { cursor: default; }
97
+ .mbe-root.mbe-readonly.mbe-tasks .mbe-checkbox { cursor: pointer; }
97
98
 
98
99
  /* Links: the text cursor while editing, so clicking places the caret. */
99
100
  .mbe-root a.mbe-link { cursor: text; }
@@ -135,7 +136,7 @@
135
136
  padding: 4px 8px;
136
137
  min-width: 4em;
137
138
  vertical-align: top;
138
- text-align: left;
139
+ text-align: start;
139
140
  outline: none;
140
141
  }
141
142
 
@@ -164,7 +165,8 @@
164
165
  /* Floating UI -------------------------------------------------------------
165
166
  System colors keep menus readable when theme.css is not loaded. */
166
167
 
167
- .mbe-ui { z-index: 1000; }
168
+ .mbe-ui { z-index: var(--mbe-popup-z, 1000); }
169
+ .mbe-icon { display: block; flex: none; width: 16px; height: 16px; }
168
170
  .mbe-ui[hidden] { display: none !important; }
169
171
  .mbe-menu,
170
172
  .mbe-toolbar,
@@ -188,7 +190,12 @@
188
190
  }
189
191
  .mbe-menu-icon:empty { display: none; }
190
192
  .mbe-menu-label { flex: 1; }
191
- .mbe-menu-empty { padding: 6px 8px; }
193
+ .mbe-suggestion-menu { max-width: 360px; }
194
+ .mbe-suggestion-menu .mbe-menu-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
195
+ .mbe-menu-detail { flex: none; white-space: nowrap; }
196
+ .mbe-menu-match { background: none; color: inherit; font-weight: 600; }
197
+ .mbe-menu-empty,
198
+ .mbe-menu-loading { padding: 6px 8px; }
192
199
 
193
200
  .mbe-toolbar { display: flex; align-items: center; gap: 2px; padding: 3px; }
194
201
  .mbe-tool {
@@ -196,8 +203,12 @@
196
203
  color: inherit;
197
204
  background: none;
198
205
  border: none;
199
- padding: 4px 8px;
206
+ padding: 4px 6px;
200
207
  min-width: 28px;
208
+ min-height: 28px;
209
+ display: inline-flex;
210
+ align-items: center;
211
+ justify-content: center;
201
212
  cursor: pointer;
202
213
  }
203
214
  .mbe-tool.mbe-active { background: Highlight; color: HighlightText; }
@@ -214,5 +225,8 @@
214
225
  border: none;
215
226
  background: none;
216
227
  color: inherit;
228
+ display: flex;
229
+ align-items: center;
230
+ justify-content: center;
217
231
  cursor: pointer;
218
232
  }