@usememos/editor 26.10.24 → 26.10.26

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
@@ -50,12 +50,13 @@ The same names work in `new Editor(options)` and as React props, except that Rea
50
50
  | `value` | `string` | React only. The editor updates only when `value` differs from the last Markdown it emitted. |
51
51
  | `defaultValue` | `string` | React only. Initial Markdown for uncontrolled use. |
52
52
  | `markdown` | `{ breaks?, setext?, autolinks?, callouts?, details? }` | Markdown dialect. `breaks: true` reads a single newline as a line break and saves line breaks as plain newlines (as GitHub comments do). `setext: false` turns off setext headings, so `Title`⏎`---` is a paragraph and a divider. `autolinks: false` turns off GFM autolink literals, so a bare `https://…`, `www.…` or e-mail address stays text. `callouts: false` reads a GitHub alert such as `> [!NOTE]` as a plain quote and drops Callout from the slash menu. `details: false` reads `<details>` as raw HTML and drops Collapsible section from the slash menu. See [docs/syntax.md](docs/syntax.md). |
53
- | `extensions` | `Extension[]` | Adds syntax and behavior. Built in: `math()` (`$…$` and `$$` blocks), `footnotes()` (`[^1]` and `[^1]: …`, shown as a raised label and a small note; `footnotes({ render: false })` keeps the source), `tags()` (`#tag`) and `mentions()` (`@name`). Extension syntax is saved verbatim, and shown as source unless the extension renders it (see `views`). |
53
+ | `extensions` | `Extension[]` | Adds syntax and behavior. Built in: `math()` (`$…$` and `$$` blocks), `footnotes()` (`[^1]` and `[^1]: …`, shown as a raised label and a small note whose text renders as Markdown, collected at the end as on GitHub when read-only; `footnotes({ render: false })` keeps the source), `tags()` (`#tag`) and `mentions()` (`@name`). Extension syntax is saved verbatim, and shown as source unless the extension renders it (see `views`). |
54
54
  | `placeholder` | `string` | Shown when the document is empty. |
55
55
  | `editable` | `boolean` | Default `true`. With `false`, no editing, and links open on click. |
56
56
  | `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`. |
57
57
  | `mode` | `'rich' \| 'source'` | Default `'rich'`. `'source'` shows the whole document as its Markdown text, for people who prefer to edit the text itself. Switching changes no text, emits no `change` and keeps undo history. See [Source mode](#source-mode). |
58
58
  | `smartLists` | `boolean` | Default `true`. In source mode, Enter continues a list or task item and Tab and Shift+Tab nest list items. `false` makes Enter insert a line break and Tab indent as in a code block. No effect in rich mode, where list items are blocks. Fixed for the editor's lifetime. |
59
+ | `sourceHighlighting` | `boolean` | Default `true`. In source mode, the Markdown syntax is highlighted (see [Source mode](#source-mode)). `false` shows the text plain; the extensions' decorations show either way. Fixed for the editor's lifetime. |
59
60
  | `autofocus` | `boolean \| 'start' \| 'end'` | Focuses the editor on creation, with the caret at the start or the end. |
60
61
  | `attributes` | `Record<string, string>` | Attributes for the editable root, such as `autocorrect`, `autocapitalize` or `aria-label`. |
61
62
  | `resolveUrl` | `(url, kind) => string \| null` | The URL to use for a link (`kind` `'link'`) or an image (`'image'`), or `null` to drop it: the link is not clickable, the image has no `src`. The saved Markdown keeps the original. Default `defaultResolveUrl`, exported: relative URLs, `http`, `https`, `mailto` and `tel`. Call it from your own policy to extend it, for example to allow `sms:` or to block `http:` images. |
@@ -197,7 +198,8 @@ const extensions = [
197
198
  | `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. |
198
199
  | `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. |
199
200
  | `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. |
200
- | `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. |
201
+ | `allow({ block, cell, from, query, textBefore, excluded, explicit, mode, 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. In source mode (`mode`), `block` is the one block holding the Markdown text and `excluded` covers its syntax, code and URLs too. |
202
+ | `richOnly` | Never opens in source mode: for items that create blocks, as the slash menu's do. |
201
203
  | `allowSpaces`, `allowAnywhere` | Default matcher only: the query may contain single spaces; the trigger may follow any character. |
202
204
  | `debounce` | Waits this many ms after the last change of the query before calling `items`. Default 0. |
203
205
  | `limit` | Most items shown. Default 50. |
@@ -286,7 +288,7 @@ const linkCardsBelow: Extension = {
286
288
 
287
289
  ### Theming
288
290
 
289
- `style.css` is two stylesheets: `base.css` holds the layout the editor needs and all spacing between blocks, and `theme.css` the default look. The default look is quiet and compact, like a rendered Markdown view: a 16px body with 24px lines, 8px between blocks, headings close to the body size, muted quotes and list markers, code blocks on a light panel with no border whose long lines scroll sideways rather than wrap, and tables as a light grid with a shaded header row and columns sized to their content. Editing and read-only look the same; only the cursor on links and checkboxes changes. It has no border or background of its own, so it fits inside your own card, comment box or chat input.
291
+ `style.css` is two stylesheets: `base.css` holds the layout the editor needs and all spacing between blocks, and `theme.css` the default look. The default look is quiet and compact, like a rendered Markdown view: a 16px body with 24px lines, 8px between blocks, headings close to the body size, muted quotes and list markers, code blocks on a light panel with no border whose long lines scroll sideways rather than wrap, and tables that fill the width inside a round frame, with a tinted header row, a line between rows and no vertical lines, as claude.ai renders them. Editing and read-only look the same; only the cursor on links and checkboxes changes. It has no border or background of its own, so it fits inside your own card, comment box or chat input.
290
292
 
291
293
  Every color, font and size in `theme.css` is a CSS custom property (`--mbe-text`, `--mbe-accent`, `--mbe-font`, …). Set them with the `theme` option's tokens, with a color set for light and one for dark; colors you leave out keep the defaults:
292
294
 
@@ -305,7 +307,7 @@ new Editor({
305
307
  });
306
308
  ```
307
309
 
308
- Colors are `text`, `muted`, `background`, `accent`, `link`, `codeBackground`, `border`, `popupBackground`, `popupBorder`, `hover`, `danger`, `highlight` (behind `<mark>` in rendered HTML), and `calloutNote`, `calloutTip`, `calloutImportant`, `calloutWarning` and `calloutCaution` (each callout type's icon, and a light tint of it behind the text); the other tokens are `font`, `mono`, `fontSize`, `lineHeight`, `radius` and `blockGap` (numbers are pixels). Values can be any CSS, such as `var(--primary)`, so the editor can follow your app's own variables; `colors` sets such a value for both schemes at once, and `light` and `dark` override it per scheme. Menus, the toolbar and the link popover take the same tokens.
310
+ Colors are `text`, `muted`, `background`, `accent`, `link`, `codeBackground`, `border`, `popupBackground`, `popupBorder`, `hover`, `danger`, `highlight` (behind `<mark>` in rendered HTML), and `calloutNote`, `calloutTip`, `calloutImportant`, `calloutWarning` and `calloutCaution` (each callout type's icon, and a light tint of it behind the text); the other tokens are `font`, `mono`, `sourceFont` (source mode's text; defaults to `font`, and `mono` makes the whole source view monospace), `fontSize`, `lineHeight`, `radius` and `blockGap` (numbers are pixels). Values can be any CSS, such as `var(--primary)`, so the editor can follow your app's own variables; `colors` sets such a value for both schemes at once, and `light` and `dark` override it per scheme. Menus, the toolbar and the link popover take the same tokens.
309
311
 
310
312
  `fontSize` and `lineHeight` size the whole document, not only its paragraphs: headings are 1.5, 1.25 and 1.125 times `fontSize` (h4 to h6 the body size), code blocks, raw blocks and tables 0.875 times it, and the code block's language label 0.75. Each keeps the body's leading, the room `lineHeight` leaves around `fontSize`, so `fontSize: 14` with `lineHeight: 20` gives a 21px h1 on 27px lines, and code at 12.25px on 18.25px lines.
311
313
 
@@ -363,7 +365,7 @@ new Editor({
363
365
  });
364
366
  ```
365
367
 
366
- Keys use the names of `isActive`: `paragraph`, `heading` (by level), `blockquote`, `bulletList`, `orderedList` and `taskList` (each list item; blocks are flat, so there is no list element; an item in a quote also gets the `blockquote` classes), `codeBlock`, `table`, `divider` (the `<hr>`), `raw`, `image`, `bold`, `italic`, `strike`, `code`, `link`, and `token` (inline tokens of an extension syntax, by name). Extensions can add classes too; the editor's own `theme` wins for the same key. `setOptions({ theme })` changes them while the editor runs.
368
+ Keys use the names of `isActive`: `paragraph`, `heading` (by level), `blockquote`, `bulletList`, `orderedList` and `taskList` (each list item; blocks are flat, so there is no list element; an item in a quote also gets the `blockquote` classes), `codeBlock`, `table`, `divider` (the `<hr>`), `raw`, `image`, `bold`, `italic`, `strike`, `code`, `link`, `token` (inline tokens of an extension syntax, by name), and `source` (source mode's highlighting, by kind of markup: `marker`, `heading`, `strong`, `em`, `strike`, `code`, `link`, `url`, `html`, `token`, `escape` and `lang`). Extensions can add classes too; the editor's own `theme` wins for the same key. `setOptions({ theme })` changes them while the editor runs.
367
369
 
368
370
  To style the editor entirely with your own classes, import `@usememos/editor/base.css` instead of `style.css`. Spacing between blocks stays in `base.css`, and its rules are more specific than a single class, so margins in your classes do not change it.
369
371
 
@@ -393,7 +395,7 @@ To style the editor entirely with your own classes, import `@usememos/editor/bas
393
395
 
394
396
  With blocks selected: ArrowUp and ArrowDown select the block above or below, Shift extends the selection, Mod+A selects every block, Backspace and Delete delete them, Mod+C, Mod+X and paste copy, cut and replace them as whole blocks, Mod+D duplicates them, and the block type keys, Tab and the mark keys apply to all of them. Enter, ArrowLeft and ArrowRight go back to editing text. Typing does nothing. See [Block selection](docs/architecture.md#block-selection).
395
397
 
396
- In source mode the formatting keys do nothing, and Enter and Tab edit list items as text; see [Source mode](#source-mode).
398
+ In source mode the formatting keys edit the Markdown text, and Enter and Tab edit list items as text; see [Source mode](#source-mode).
397
399
 
398
400
  Markdown shortcuts at the start of a line: `#`–`######`, `-`, `*`, `+`, `1.`, `[ ]`, `[x]`, `>`, `[!note]` and the other callout types, `>>>` (collapsible section), ` ``` `, `---`. Inline: `**bold**`, `*italic*`, `_italic_`, `` `code` ``, `~~strike~~`.
399
401
 
@@ -444,11 +446,11 @@ With `mode: 'source'`, the editor shows the whole document as Markdown text, as
444
446
  <MarkdownEditor value={markdown} onChange={setMarkdown} mode={showSource ? 'source' : 'rich'} />
445
447
  ```
446
448
 
447
- The text is set in the `mono` font at the body's size and line height, as code blocks are, so list markers and indentation line up.
449
+ **Highlighting.** The Markdown syntax is highlighted in the text, as Obsidian does: markers (`#`, `**`, `*`, `~~`, backticks, list and quote markers, task boxes, link brackets, fences, table pipes) are dimmed, strong text is bold, emphasis italic, strike struck, headings heavier, inline and fenced code in the `mono` font, link destinations and bare URLs in the link color, and raw HTML, extension syntax and escapes dimmed. Nothing changes size and nothing is hidden: the text is in the body font at the body's size and line height, so a switch keeps the text's rhythm, and the `sourceFont` token makes the whole view monospace. What is highlighted is what the editor reads as syntax: a literal `*` stays plain, and a `#` inside a fence is code. The classes are `mbe-src-marker`, `mbe-src-heading`, `mbe-src-strong`, `mbe-src-em`, `mbe-src-strike`, `mbe-src-code`, `mbe-src-link`, `mbe-src-url`, `mbe-src-html`, `mbe-src-token`, `mbe-src-escape` and `mbe-src-lang`; the `theme` option's `source` classes add yours per kind, and `sourceHighlighting: false` turns the built-in highlighting off. The extensions' `decorations` run over the text too, with the same excluded ranges as in rich mode, so `tags()` and `mentions()` highlight `#tag` and `@name` in prose and not inside code or a URL, and `codeDecorations` runs on the code of each fence, so a code highlighter works in source mode as well.
448
450
 
449
- **Switching** is a change of view, not an edit. The text shown in source mode is exactly `getMarkdown()`. Going back to rich mode loads the text as `setMarkdown` does, so `getMarkdown()` returns it byte for byte, including lines edited in source mode. A switch emits no `change`, adds no undo step and does not move focus. Undo and redo work across it: undoing an edit made in the other mode restores it in the current mode. The caret stays in the same block, and keeps its column when the text before it in that block has no Markdown syntax; otherwise it goes to the start of the block's text. A switch requested while an input method is composing waits for the composition to end.
451
+ **Switching** is a change of view, not an edit. The text shown in source mode is exactly `getMarkdown()`. Going back to rich mode loads the text as `setMarkdown` does, so `getMarkdown()` returns it byte for byte, including lines edited in source mode. A switch emits no `change`, adds no undo step and does not move focus. Undo and redo work across it: undoing an edit made in the other mode restores it in the current mode. The caret stays in the same block, at the same place in its text, past any Markdown syntax before it: a caret on syntax goes to the text after it, one inside an image or an escape before it, and one in a table to the start of the table. A switch requested while an input method is composing waits for the composition to end.
450
452
 
451
- **What works in source mode.** Source mode is plain text editing, like a `<textarea>` or a code block, that knows Markdown lists. It has no autocomplete and no formatting keys.
453
+ **What works in source mode.** Source mode is plain text editing, like a `<textarea>` or a code block, that knows Markdown lists, opens the extensions' autocomplete popups, and makes the formatting keys edit the text.
452
454
 
453
455
  | | |
454
456
  | --- | --- |
@@ -456,20 +458,21 @@ The text is set in the `mono` font at the body's size and line height, as code b
456
458
  | Enter | On a list item, after its marker, starts the next item: the same marker and indentation, the next number, and an unticked `[ ]` after a task. Text after the caret moves to the new item, and the items after it in an ordered list are numbered again. On an empty item, removes the marker, or outdents a nested item, as in rich mode. Elsewhere, inside fenced code and before an item's marker, inserts a line break |
457
459
  | Shift+Enter | Inserts a line break |
458
460
  | Tab, Shift+Tab | On list items: Tab nests the items the selection touches under the item before them, at that item's text column, and Shift+Tab moves them out to their parent's level. Lines nested under them move with them, ordered lists they leave and join are numbered again, and an item that cannot move stays. Elsewhere, as in a code block: Tab inserts two spaces, or indents the selected lines by two spaces. Shift+Tab removes up to two spaces (or a tab) from the start of those lines |
459
- | Paste | The clipboard's plain text (`text/plain`). Files go to `fileHandler` as in rich mode |
461
+ | Paste | HTML pastes as Markdown, through the same conversion as in rich mode, and the editor's own HTML as the Markdown it was copied from; plain text as written, and always inside a fence. Mod+Shift+V pastes the plain text. A URL pasted over selected text makes it a link, `[text](url)`. Files go to `fileHandler` as in rich mode |
460
462
  | Copy and cut | The selected text, as `text/plain` |
461
463
  | Mod+Enter, undo, redo, Mod+A | As in rich mode |
462
464
  | Escape | Leaves the editor |
463
- | Formatting keys (Mod+B, Mod+I, Mod+E, Mod+Shift+X, Mod+Alt+0–4, Mod+Alt+C, Mod+Shift+6–9) | Do nothing. Mod+K is left to the app |
465
+ | Mod+B, Mod+I, Mod+E, Mod+Shift+X | Wrap the selection in `**`, `*`, backticks or `~~`, or unwrap it when it is already wrapped, whether or not the markers are selected; the wrapped range is trimmed of whitespace. With no selection, the word at the caret; on whitespace, the pair with the caret between the markers. Italic inside strong adds its own star, and a backtick run grows past any backticks in the code. One undo step each |
466
+ | Mod+Alt+0–4, Mod+Shift+7–9, Mod+Alt+C | Set or replace the `#` prefix of the selected lines (a level every line has, or Mod+Alt+0, removes it), toggle `1. `, `- ` or `- [ ] ` on them (new ordered items are numbered from the list they join), and wrap them in a code fence or remove the fence around the selection, all after any quote markers. `commands.toggleBlockquote` toggles `> `; rich mode binds no key to it either. Mod+Shift+6 (a section) and Mod+K are left to the app |
464
467
  | Markdown shortcuts, autolinks | Do not run: the text is the Markdown |
465
- | Autocomplete | Off. `suggestion()` popups, the slash menu and Ctrl+Space do not open |
468
+ | Autocomplete | `suggestion()` popups open for the tokens their extension owns, in prose and not inside code, a URL, raw HTML or extension syntax, and a pick inserts its text; Ctrl+Space opens one explicitly. The slash menu stays off, as does a suggestion with `richOnly` |
466
469
  | `fileHandler`, `handlePaste`, `handleDrop`, extension key bindings | As in rich mode |
467
- | `commands.*` | `insertText` and `insertMarkdown` insert the text as written; `insertMarkdown` with `block: true` puts it on lines of its own. `indent` and `outdent` work as Tab and Shift+Tab. `undo`, `undo`, `redo`, `selectAll`, `focus`, `blur` and `scrollIntoView` work. The mark, block type, link, image, table, divider, callout, section and `selectBlocks` commands return `false` |
470
+ | `commands.*` | `insertText` and `insertMarkdown` insert the text as written; `insertMarkdown` with `block: true` puts it on lines of its own. `indent` and `outdent` work as Tab and Shift+Tab. The mark commands, `setParagraph`, `toggleHeading`, the list commands, `toggleBlockquote` and `toggleCodeBlock` make the text edits above and return `true`. `undo`, `redo`, `selectAll`, `focus`, `blur` and `scrollIntoView` work. The link, image, table, divider, callout, section and `selectBlocks` commands return `false` |
468
471
  | Placeholder | Shown when the text is empty |
469
472
  | `addWidget` | Shown below the text. A widget remembers its place in the text, which moves with edits before it, and `insertMarkdown(md, { at: widget })` inserts there |
470
473
  | `editable: false` | The text is read-only and can be selected and copied. `taskToggle` has no effect |
471
474
 
472
- The toolbar, slash menu, autocomplete popup, block handle, block menu, link card, rendered views, decorations, images and syntax highlighting do not show. `isActive()` returns `false` and `getAttributes()` returns `{}`.
475
+ The toolbar, slash menu, block handle, block menu, link card, rendered views and images do not show. `isActive()` returns `false` and `getAttributes()` returns `{}`.
473
476
 
474
477
  **Positions.** In source mode the document is one block that holds all the text, so a `Position` names that block and its `offset` counts UTF-16 code units of the Markdown. `getSelection`, `setSelection`, `selectionToJSON` and `insertText({ range })` use that shape. A selection saved in the other mode is clamped.
475
478
 
package/dist/base.css CHANGED
@@ -243,6 +243,8 @@
243
243
  :is(.mbe-root, .mbe-flow) > pre.mbe-raw { white-space: pre-wrap; tab-size: 2; }
244
244
  /* Source mode: the document as plain text; theme.css sets its mono font. */
245
245
  .mbe-root > .mbe-source { white-space: pre-wrap; tab-size: 4; overflow-wrap: anywhere; }
246
+ /* One block per line, so a keystroke lays out only its line. */
247
+ .mbe-root > .mbe-source .mbe-source-line { display: block; }
246
248
  :is(.mbe-root, .mbe-flow) > .mbe-code pre { margin: 0; }
247
249
  :is(.mbe-root, .mbe-flow) > .mbe-code pre code { display: block; }
248
250
 
@@ -255,6 +257,17 @@
255
257
  .mbe-root > .mbe-block-view { overflow: visible; }
256
258
  /* A block view placed after its block, which stays editable text: not text itself, like a widget. */
257
259
  .mbe-root > .mbe-block-after { cursor: default; white-space: normal; }
260
+ /* A footnote definition: its label in a column beside the text, which may be
261
+ several blocks; the label sits on the first line's baseline. */
262
+ :is(.mbe-root, .mbe-flow, .mbe-footnotes) > .mbe-footnote { display: grid; grid-template-columns: auto 1fr; column-gap: 0.375em; align-items: baseline; }
263
+ :is(.mbe-root, .mbe-flow, .mbe-footnotes) > .mbe-footnote > :last-child { min-width: 0; }
264
+ /* Footnotes, read-only: the definitions hide where they are written and the
265
+ referenced ones are collected in a section at the end (see footnotes()). */
266
+ .mbe-root > .mbe-footnote-collected { display: none; }
267
+ .mbe-root > .mbe-footnotes { margin-top: 16px; cursor: default; }
268
+ .mbe-root > .mbe-footnotes > .mbe-footnote + .mbe-footnote { margin-top: 4px; }
269
+ .mbe-root .mbe-footnote-backref { display: inline-flex; align-items: center; vertical-align: -0.125em; }
270
+ .mbe-root .mbe-footnote-backref .mbe-icon { width: 0.875em; height: 0.875em; }
258
271
  /* Tags and mentions with an onClick, read-only: clickable, as links are. */
259
272
  .mbe-root.mbe-readonly :is([data-mbe-tag], [data-mbe-mention]) { cursor: pointer; }
260
273
  /* Rendered HTML: line breaks between its tags are not text. The Markdown
@@ -281,15 +294,19 @@
281
294
 
282
295
  /* Table */
283
296
  :is(.mbe-root, .mbe-flow) > .mbe-table { overflow-x: auto; }
284
- /* Columns fit their content and wrap at the editor's width, as GitHub lays
285
- tables out; wider tables scroll. No column has a minimum width, so a long
286
- column is not squeezed into wrapping by short ones. */
287
- :is(.mbe-root, .mbe-flow) > .mbe-table table { border-collapse: separate; border-spacing: 0; }
297
+ /* The table fills the editor's width and its columns share it by their
298
+ content, as claude.ai lays tables out; one whose longest words do not
299
+ fit scrolls. Cells wrap at words: the root's overflow-wrap: anywhere
300
+ would let the layout shrink any column to one character and break words
301
+ to make the table fit, break-word keeps every column as wide as its
302
+ longest word. */
303
+ :is(.mbe-root, .mbe-flow) > .mbe-table table { width: 100%; border-collapse: separate; border-spacing: 0; }
288
304
  :is(.mbe-root, .mbe-flow) > .mbe-table th,
289
305
  :is(.mbe-root, .mbe-flow) > .mbe-table td {
290
- padding: 4px 8px;
306
+ padding: 0.4375em 0.75em;
291
307
  vertical-align: top;
292
308
  text-align: start;
309
+ overflow-wrap: break-word;
293
310
  outline: none;
294
311
  }
295
312
  /* An empty cell keeps room to click into while editing. */
package/dist/emoji.js CHANGED
@@ -60,7 +60,8 @@ function emoji(options = {}) {
60
60
  while (end < range.to.offset && NAME_CHAR.test(text[end])) end++;
61
61
  const to = { ...range.from, offset: end };
62
62
  const next = text[end];
63
- const space = next !== void 0 && NO_SPACE_BEFORE.test(next) ? "" : " ";
63
+ const atLineEnd = next === "\n" && editor.mode === "source";
64
+ const space = next !== void 0 && !atLineEnd && NO_SPACE_BEFORE.test(next) ? "" : " ";
64
65
  editor.commands.insertText(item.value + space, { range: { from: range.from, to } });
65
66
  }
66
67
  });
package/dist/emoji.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/emoji/index.ts", "../src/emoji/search.ts"],
4
- "sourcesContent": ["// @usememos/editor/emoji: `:name` autocomplete that writes the emoji itself,\n// as GitHub, Notion and Linear offer. The names are GitHub's (gemoji). The\n// list of 1,870 emoji loads the first time the popup opens, so an app pays\n// for it only when someone types an emoji.\n\nimport { type Extension, type SuggestionItem, containerContent, inlineText, suggestion } from '@usememos/editor';\nimport { type Emoji, parseEmoji, searchEmoji } from './search';\n\nexport { type Emoji, parseEmoji, searchEmoji } from './search';\n\nexport interface EmojiOptions {\n /** The suggestion's name, for `editor.suggestion.open(name)`. Default `emoji`. */\n readonly name?: string;\n /** Most emoji shown. Default 8. */\n readonly limit?: number;\n /** Characters typed after `:` before the popup opens, so `:)` and `a :b` stay quiet. Default 2. Ctrl+Space opens it sooner. */\n readonly minLength?: number;\n /** Accessible name of the popup. Default `Emoji`. */\n readonly label?: string;\n}\n\ninterface EmojiItem extends SuggestionItem {\n readonly value: string;\n}\n\nlet loading: Promise<readonly Emoji[]> | null = null;\n\n/** Every emoji the extension offers, loaded once on first use. */\nexport function loadEmoji(): Promise<readonly Emoji[]> {\n loading ??= import('./data').then((m) => parseEmoji(m.EMOJI_DATA));\n return loading;\n}\n\n/** A character of an emoji name. */\nconst NAME_CHAR = /[a-z0-9_+-]/i;\n\n/** Characters before which a pick adds no space, as for the editor's other suggestions. */\nconst NO_SPACE_BEFORE = /[\\s.,;:!?)\\]}>'\"\u2019\u201D\u00BB\uFF09\u300D\u300F\u3011\u3001\u3002\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F]/;\n\n/**\n * Emoji autocomplete: typing `:` and two letters at the start of a word lists\n * emoji by GitHub's names and tags (`:tada`, `:party`). A pick replaces the\n * typed name with the emoji, so the Markdown holds the character itself.\n */\nexport function emoji(options: EmojiOptions = {}): Extension {\n const { name = 'emoji', limit = 8, minLength = 2 } = options;\n return suggestion<EmojiItem>({\n name,\n trigger: [':', '\uFF1A'],\n label: options.label ?? 'Emoji',\n className: 'mbe-emoji-menu',\n allow: ({ excluded, explicit, query }) => !excluded && (explicit || query.length >= minLength) && [...query].every((c) => NAME_CHAR.test(c)),\n items: async ({ query }) =>\n searchEmoji(await loadEmoji(), query, limit).map((e) => ({ id: e.names[0], label: `:${e.names[0]}:`, icon: e.emoji, value: e.emoji })),\n command: ({ editor, range, item, query }) => {\n // Replace the trigger and the name, also the part after the caret, but not what follows the name, such as \"!\".\n const block = editor.state.doc.blocks.find((b) => b.id === range.from.blockId);\n const content = block && containerContent(block, range.from.cell);\n const text = content ? inlineText(content) : '';\n let end = range.from.offset + 1 + query.length;\n while (end < range.to.offset && NAME_CHAR.test(text[end]!)) end++;\n const to = { ...range.from, offset: end };\n const next = text[end];\n const space = next !== undefined && NO_SPACE_BEFORE.test(next) ? '' : ' ';\n editor.commands.insertText(item.value + space, { range: { from: range.from, to } });\n },\n });\n}\n", "// Finding emoji by name for the `emoji()` extension.\n\nexport interface Emoji {\n /** The character, such as \"\uD83C\uDF89\". */\n readonly emoji: string;\n /** Its names, the first the main one, such as [\"tada\"]. Typed as `:tada:` on GitHub. */\n readonly names: readonly string[];\n /** Other words it is found by, such as [\"party\"]. */\n readonly tags: readonly string[];\n}\n\n/** Reads the lines of `data.ts`: the emoji, its names and its tags, separated by tabs. */\nexport function parseEmoji(data: string): Emoji[] {\n return data.split('\\n').map((line) => {\n const [emoji = '', names = '', tags = ''] = line.split('\\t');\n return { emoji, names: names.split(' ').filter(Boolean), tags: tags.split(' ').filter(Boolean) };\n });\n}\n\n/**\n * Emoji whose names or tags match `query`, best first: a name equal to it,\n * a name starting with it, a word of a name starting with it (\"smile\" finds\n * \"sweat_smile\"), a tag starting with it, then a name containing it. Within\n * a rank the data's order is kept, which puts common emoji first.\n */\nexport function searchEmoji(emoji: readonly Emoji[], query: string, limit = Infinity): Emoji[] {\n const q = query.toLowerCase();\n if (!q) return emoji.slice(0, limit);\n const ranked: Emoji[][] = [[], [], [], [], []];\n for (const e of emoji) {\n const rank = rankOf(e, q);\n if (rank !== null) ranked[rank]!.push(e);\n }\n return ranked.flat().slice(0, limit);\n}\n\nfunction rankOf(e: Emoji, q: string): number | null {\n let best: number | null = null;\n const take = (rank: number) => {\n if (best === null || rank < best) best = rank;\n };\n for (const name of e.names) {\n if (name === q) return 0;\n if (name.startsWith(q)) take(1);\n else if (name.includes(`_${q}`) || name.includes(`-${q}`)) take(2);\n else if (name.includes(q)) take(4);\n }\n if (best === null || best > 3) for (const tag of e.tags) if (tag.startsWith(q)) take(3);\n return best;\n}\n"],
5
- "mappings": ";AAKA,SAA8C,kBAAkB,YAAY,kBAAkB;;;ACOvF,SAAS,WAAW,MAAuB;AAChD,SAAO,KAAK,MAAM,IAAI,EAAE,IAAI,CAAC,SAAS;AACpC,UAAM,CAACA,SAAQ,IAAI,QAAQ,IAAI,OAAO,EAAE,IAAI,KAAK,MAAM,GAAI;AAC3D,WAAO,EAAE,OAAAA,QAAO,OAAO,MAAM,MAAM,GAAG,EAAE,OAAO,OAAO,GAAG,MAAM,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO,EAAE;AAAA,EACjG,CAAC;AACH;AAQO,SAAS,YAAYA,QAAyB,OAAe,QAAQ,UAAmB;AAC7F,QAAM,IAAI,MAAM,YAAY;AAC5B,MAAI,CAAC,EAAG,QAAOA,OAAM,MAAM,GAAG,KAAK;AACnC,QAAM,SAAoB,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAC7C,aAAW,KAAKA,QA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CAAC;AAAA,IAC3I,OAAO,OAAO,EAAE,MAAM,MACpB,YAAY,MAAM,UAAU,GAAG,OAAO,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,OAAO,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,MAAM,EAAE,OAAO,OAAO,EAAE,MAAM,EAAE;AAAA,IACvI,SAAS,CAAC,EAAE,QAAQ,OAAO,MAAM,MAAM,MAAM;AAE3C,YAAM,QAAQ,OAAO,MAAM,IAAI,OAAO,KAAK,CAAC,MAAM,EAAE,OAAO,MAAM,KAAK,OAAO;AAC7E,YAAM,UAAU,SAAS,iBAAiB,OAAO,MAAM,KAAK,IAAI;AAChE,YAAM,OAAO,UAAU,WAAW,OAAO,IAAI;AAC7C,UAAI,MAAM,MAAM,KAAK,SAAS,IAAI,MAAM;AACxC,aAAO,MAAM,MAAM,GAAG,UAAU,UAAU,KAAK,KAAK,GAAG,CAAE,EAAG;AAC5D,YAAM,KAAK,EAAE,GAAG,MAAM,MAAM,QAAQ,IAAI;AACxC,YAAM,OAAO,KAAK,GAAG;AACrB,YAAM,QAAQ,SAAS,UAAa,gBAAgB,KAAK,IAAI,IAAI,KAAK;AACtE,aAAO,SAAS,WAAW,KAAK,QAAQ,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,MAAM,GAAG,EAAE,CAAC;AAAA,IACpF;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["// @usememos/editor/emoji: `:name` autocomplete that writes the emoji itself,\n// as GitHub, Notion and Linear offer. The names are GitHub's (gemoji). The\n// list of 1,870 emoji loads the first time the popup opens, so an app pays\n// for it only when someone types an emoji.\n\nimport { type Extension, type SuggestionItem, containerContent, inlineText, suggestion } from '@usememos/editor';\nimport { type Emoji, parseEmoji, searchEmoji } from './search';\n\nexport { type Emoji, parseEmoji, searchEmoji } from './search';\n\nexport interface EmojiOptions {\n /** The suggestion's name, for `editor.suggestion.open(name)`. Default `emoji`. */\n readonly name?: string;\n /** Most emoji shown. Default 8. */\n readonly limit?: number;\n /** Characters typed after `:` before the popup opens, so `:)` and `a :b` stay quiet. Default 2. Ctrl+Space opens it sooner. */\n readonly minLength?: number;\n /** Accessible name of the popup. Default `Emoji`. */\n readonly label?: string;\n}\n\ninterface EmojiItem extends SuggestionItem {\n readonly value: string;\n}\n\nlet loading: Promise<readonly Emoji[]> | null = null;\n\n/** Every emoji the extension offers, loaded once on first use. */\nexport function loadEmoji(): Promise<readonly Emoji[]> {\n loading ??= import('./data').then((m) => parseEmoji(m.EMOJI_DATA));\n return loading;\n}\n\n/** A character of an emoji name. */\nconst NAME_CHAR = /[a-z0-9_+-]/i;\n\n/** Characters before which a pick adds no space, as for the editor's other suggestions. */\nconst NO_SPACE_BEFORE = /[\\s.,;:!?)\\]}>'\"\u2019\u201D\u00BB\uFF09\u300D\u300F\u3011\u3001\u3002\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F]/;\n\n/**\n * Emoji autocomplete: typing `:` and two letters at the start of a word lists\n * emoji by GitHub's names and tags (`:tada`, `:party`). A pick replaces the\n * typed name with the emoji, so the Markdown holds the character itself.\n */\nexport function emoji(options: EmojiOptions = {}): Extension {\n const { name = 'emoji', limit = 8, minLength = 2 } = options;\n return suggestion<EmojiItem>({\n name,\n trigger: [':', '\uFF1A'],\n label: options.label ?? 'Emoji',\n className: 'mbe-emoji-menu',\n allow: ({ excluded, explicit, query }) => !excluded && (explicit || query.length >= minLength) && [...query].every((c) => NAME_CHAR.test(c)),\n items: async ({ query }) =>\n searchEmoji(await loadEmoji(), query, limit).map((e) => ({ id: e.names[0], label: `:${e.names[0]}:`, icon: e.emoji, value: e.emoji })),\n command: ({ editor, range, item, query }) => {\n // Replace the trigger and the name, also the part after the caret, but not what follows the name, such as \"!\".\n const block = editor.state.doc.blocks.find((b) => b.id === range.from.blockId);\n const content = block && containerContent(block, range.from.cell);\n const text = content ? inlineText(content) : '';\n let end = range.from.offset + 1 + query.length;\n while (end < range.to.offset && NAME_CHAR.test(text[end]!)) end++;\n const to = { ...range.from, offset: end };\n const next = text[end];\n // In source mode a line ending is the end of the block: the space is added, as at a block's end.\n const atLineEnd = next === '\\n' && editor.mode === 'source';\n const space = next !== undefined && !atLineEnd && NO_SPACE_BEFORE.test(next) ? '' : ' ';\n editor.commands.insertText(item.value + space, { range: { from: range.from, to } });\n },\n });\n}\n", "// Finding emoji by name for the `emoji()` extension.\n\nexport interface Emoji {\n /** The character, such as \"\uD83C\uDF89\". */\n readonly emoji: string;\n /** Its names, the first the main one, such as [\"tada\"]. Typed as `:tada:` on GitHub. */\n readonly names: readonly string[];\n /** Other words it is found by, such as [\"party\"]. */\n readonly tags: readonly string[];\n}\n\n/** Reads the lines of `data.ts`: the emoji, its names and its tags, separated by tabs. */\nexport function parseEmoji(data: string): Emoji[] {\n return data.split('\\n').map((line) => {\n const [emoji = '', names = '', tags = ''] = line.split('\\t');\n return { emoji, names: names.split(' ').filter(Boolean), tags: tags.split(' ').filter(Boolean) };\n });\n}\n\n/**\n * Emoji whose names or tags match `query`, best first: a name equal to it,\n * a name starting with it, a word of a name starting with it (\"smile\" finds\n * \"sweat_smile\"), a tag starting with it, then a name containing it. Within\n * a rank the data's order is kept, which puts common emoji first.\n */\nexport function searchEmoji(emoji: readonly Emoji[], query: string, limit = Infinity): Emoji[] {\n const q = query.toLowerCase();\n if (!q) return emoji.slice(0, limit);\n const ranked: Emoji[][] = [[], [], [], [], []];\n for (const e of emoji) {\n const rank = rankOf(e, q);\n if (rank !== null) ranked[rank]!.push(e);\n }\n return ranked.flat().slice(0, limit);\n}\n\nfunction rankOf(e: Emoji, q: string): number | null {\n let best: number | null = null;\n const take = (rank: number) => {\n if (best === null || rank < best) best = rank;\n };\n for (const name of e.names) {\n if (name === q) return 0;\n if (name.startsWith(q)) take(1);\n else if (name.includes(`_${q}`) || name.includes(`-${q}`)) take(2);\n else if (name.includes(q)) take(4);\n }\n if (best === null || best > 3) for (const tag of e.tags) if (tag.starts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