@sveltia/ui 0.88.3 → 0.89.0

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.
@@ -10,8 +10,9 @@ export function limitToSingleLine(config: TextEditorConfig): TextEditorConfig;
10
10
  export function $joinIntoSingleParagraph(root: RootNode): void;
11
11
  export function $replaceLineBreak(node: LineBreakNode): void;
12
12
  export function removePlaceholdersFromMatch(transformer: Transformer): Transformer;
13
- export function initEditor(config: TextEditorConfig): InitEditorResult;
14
13
  export function loadCodeHighlighter(lang: string): Promise<void>;
14
+ export function pasteMarkdown(editor: LexicalEditor, value: string, enabledTransformers: Transformer[]): Promise<void>;
15
+ export function initEditor(config: TextEditorConfig): InitEditorResult;
15
16
  export function convertMarkdownToLexical(editor: LexicalEditor, value: string, enabledTransformers: Transformer[]): Promise<string | undefined>;
16
17
  export function convertHtmlToLexical(editor: LexicalEditor, value: string): Promise<string | undefined>;
17
18
  export function focusEditor(editor: LexicalEditor): Promise<void>;
@@ -33,6 +33,7 @@ import {
33
33
  HEADING,
34
34
  $convertFromMarkdownString as convertFromMarkdownString,
35
35
  $convertToMarkdownString as convertToMarkdownString,
36
+ $generateNodesFromMarkdownString as generateNodesFromMarkdownString,
36
37
  registerMarkdownShortcuts,
37
38
  } from '@lexical/markdown';
38
39
  import {
@@ -48,6 +49,7 @@ import {
48
49
  } from '@lexical/utils';
49
50
  import { sleep } from '@sveltia/utils/misc';
50
51
  import { isURL } from '@sveltia/utils/string';
52
+ import { isMac, matchesShortcuts } from '@sveltia/utils/events';
51
53
  import {
52
54
  COMMAND_PRIORITY_HIGH,
53
55
  COMMAND_PRIORITY_LOW,
@@ -62,10 +64,12 @@ import {
62
64
  $getNearestNodeFromDOMNode as getNearestNodeFromDOMNode,
63
65
  $getRoot as getRoot,
64
66
  $getSelection as getSelection,
67
+ $setSelection as setSelection,
65
68
  HISTORY_MERGE_TAG,
66
69
  INDENT_CONTENT_COMMAND,
67
70
  INSERT_LINE_BREAK_COMMAND,
68
71
  INSERT_PARAGRAPH_COMMAND,
72
+ KEY_DOWN_COMMAND,
69
73
  KEY_ENTER_COMMAND,
70
74
  LineBreakNode,
71
75
  $insertNodes as insertNodes,
@@ -76,6 +80,7 @@ import {
76
80
  $isTextNode as isTextNode,
77
81
  OUTDENT_CONTENT_COMMAND,
78
82
  PASTE_COMMAND,
83
+ PASTE_TAG,
79
84
  RootNode,
80
85
  } from 'lexical';
81
86
  import {
@@ -1241,6 +1246,274 @@ export const removePlaceholdersFromMatch = (transformer) => {
1241
1246
  return /** @type {Transformer} */ ({ ...transformer, ...overrides });
1242
1247
  };
1243
1248
 
1249
+ /**
1250
+ * Preload the syntax highlighter for the given programming language.
1251
+ *
1252
+ * Highlighting also works without this — the transform loads whatever it needs and re-highlights
1253
+ * once it arrives — but preloading avoids a visible flash of unhighlighted code.
1254
+ * @param {string} lang Language name, like scss.
1255
+ */
1256
+ export const loadCodeHighlighter = async (lang) => {
1257
+ if (isPlainLanguage(lang)) {
1258
+ return;
1259
+ }
1260
+
1261
+ // The grammar and theme loaders are no-ops until the engine is in place
1262
+ await loadEngine();
1263
+
1264
+ await Promise.all([loadCodeLanguage(normalizeCodeLanguage(lang)), loadCodeTheme(getCodeTheme())]);
1265
+ };
1266
+
1267
+ /**
1268
+ * Remove the placeholders added by `addImportPlaceholders()` from the imported nodes: the text, the
1269
+ * Markdown of raw syntax, and the URL and title of a link. The text of raw syntax is restored from
1270
+ * the Markdown it was imported from, as Lexical has removed its escapes, which are not escapes in
1271
+ * raw HTML; see `RAW_HTML`.
1272
+ * @param {LexicalNode[]} nodes Imported nodes.
1273
+ */
1274
+ const removePlaceholders = (nodes) => {
1275
+ nodes
1276
+ .flatMap((node) => (isElementNode(node) ? node.getAllTextNodes() : node))
1277
+ .filter((node) => isTextNode(node))
1278
+ .forEach((node) => {
1279
+ const text = node.getTextContent();
1280
+ const newText = removeImportPlaceholders(getImportedRawSyntax(node) ?? text);
1281
+ const link = node.getParent();
1282
+
1283
+ if (newText !== text) {
1284
+ node.setTextContent(newText);
1285
+ }
1286
+
1287
+ if (isLinkNode(link)) {
1288
+ const url = link.getURL();
1289
+ const title = link.getTitle();
1290
+
1291
+ if (removeImportPlaceholders(url) !== url) {
1292
+ link.setURL(removeImportPlaceholders(url));
1293
+ }
1294
+
1295
+ if (title && removeImportPlaceholders(title) !== title) {
1296
+ link.setTitle(removeImportPlaceholders(title));
1297
+ }
1298
+ }
1299
+ });
1300
+ };
1301
+
1302
+ /**
1303
+ * Prepare Markdown for the import: convert the syntax Lexical doesn’t support to the one it does,
1304
+ * if the element is enabled, and list the programming languages used in the code blocks.
1305
+ * @param {string} value Markdown.
1306
+ * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1307
+ * @returns {{ markdown: string, languages: string[] }} Normalized Markdown and the languages.
1308
+ */
1309
+ const prepareMarkdown = (value, enabledTransformers) => {
1310
+ // Tilde code fences are converted to backtick ones, and setext headings to ATX ones. Otherwise
1311
+ // the syntax is kept as text, as written. A transformer is found by its regular expression,
1312
+ // because the transformers can come wrapped in a `$state` proxy, which leaves a regular
1313
+ // expression as is but not the transformer object itself
1314
+ const hasCodeBlocks = enabledTransformers.some(
1315
+ (transformer) => 'regExpStart' in transformer && transformer.regExpStart === CODE.regExpStart,
1316
+ );
1317
+
1318
+ const hasHeadings = enabledTransformers.some(
1319
+ (transformer) => 'regExp' in transformer && transformer.regExp === HEADING.regExp,
1320
+ );
1321
+
1322
+ const fencedValue = hasCodeBlocks ? convertTildeFences(value) : value;
1323
+ const markdown = hasHeadings ? convertSetextHeadings(fencedValue) : fencedValue;
1324
+
1325
+ return {
1326
+ markdown,
1327
+ // The language is the leading word of the info string, like `js` in ```` ``` js title=x ````;
1328
+ // see `CODE`
1329
+ languages: [...markdown.matchAll(/^`{3,}[ \t]*(?<lang>[\w-]+)/gm)].map(
1330
+ ({ groups: { lang = 'plain' } = {} }) => lang,
1331
+ ),
1332
+ };
1333
+ };
1334
+
1335
+ /**
1336
+ * Convert Markdown prepared with {@link prepareMarkdown} to Lexical nodes, either replacing the
1337
+ * content of the root or returning the nodes to be inserted somewhere. Called within an editor
1338
+ * update.
1339
+ * @param {string} markdown Markdown.
1340
+ * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1341
+ * @param {object} [options] Options.
1342
+ * @param {boolean} [options.toRoot] Whether to replace the content of the root.
1343
+ * @returns {LexicalNode[]} Imported nodes.
1344
+ */
1345
+ const $importMarkdown = (markdown, enabledTransformers, { toRoot = false } = {}) => {
1346
+ // Split multiline formatting into separate lines to prevent Markdown parsing issues
1347
+ const splitValue = splitMultilineFormatting(markdown);
1348
+ // Add placeholders so Lexical reads the backslashes, the tabs in code spans and raw HTML right
1349
+ const markedValue = addImportPlaceholders(splitValue);
1350
+ // Pad blank blockquote lines so they are not imported as literal `>` text
1351
+ const paddedValue = padBlankBlockquoteLines(markedValue);
1352
+ // Keep the formatting around a code span after other formatting
1353
+ const transformers = addCodeSpanSplit(enabledTransformers);
1354
+ /** @type {LexicalNode[]} */
1355
+ let nodes;
1356
+
1357
+ if (toRoot) {
1358
+ convertFromMarkdownString(paddedValue, transformers);
1359
+ nodes = getRoot().getChildren();
1360
+ } else {
1361
+ nodes = generateNodesFromMarkdownString(paddedValue, transformers);
1362
+ }
1363
+
1364
+ // The text of raw HTML and raw syntax is restored as well. The lines of an HTML block have a
1365
+ // placeholder. Other raw syntax, like an autolink or a definition label, only differs from its
1366
+ // text if Lexical has decoded an escape or a character reference in it
1367
+ if (markedValue !== splitValue || /[\\&]/.test(markedValue)) {
1368
+ removePlaceholders(nodes);
1369
+ }
1370
+
1371
+ return nodes;
1372
+ };
1373
+
1374
+ /**
1375
+ * Insert the given Markdown at the selection, converted to Lexical nodes, as if it were pasted. The
1376
+ * content stays as it is if the editor is read-only or has no selection.
1377
+ * @param {LexicalEditor} editor Editor instance.
1378
+ * @param {string} value Markdown.
1379
+ * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1380
+ * @returns {Promise<void>} Nothing.
1381
+ */
1382
+ export const pasteMarkdown = async (editor, value, enabledTransformers) => {
1383
+ const { markdown, languages } = prepareMarkdown(value, enabledTransformers);
1384
+
1385
+ // Preload the highlighter like the import does, but carry on without it if it fails to load: the
1386
+ // code is highlighted once it’s available, if ever
1387
+ await Promise.allSettled(languages.map((lang) => loadCodeHighlighter(lang)));
1388
+
1389
+ if (!editor.isEditable()) {
1390
+ return;
1391
+ }
1392
+
1393
+ editor.update(
1394
+ () => {
1395
+ // The Markdown import moves the selection to the nodes it creates, so keep a copy to insert
1396
+ // the nodes where the caret was
1397
+ const selection = getSelection()?.clone();
1398
+
1399
+ if (!selection) {
1400
+ return;
1401
+ }
1402
+
1403
+ /** @type {LexicalNode[] | undefined} */
1404
+ let nodes;
1405
+
1406
+ try {
1407
+ nodes = $importMarkdown(markdown, enabledTransformers);
1408
+ } catch (ex) {
1409
+ // The browser paste has been canceled, so paste the text as is rather than nothing
1410
+ // eslint-disable-next-line no-console
1411
+ console.error(ex);
1412
+ }
1413
+
1414
+ setSelection(selection);
1415
+
1416
+ if (nodes) {
1417
+ selection.insertNodes(nodes);
1418
+ } else {
1419
+ selection.insertRawText(value);
1420
+ }
1421
+ },
1422
+ { tag: PASTE_TAG },
1423
+ );
1424
+ };
1425
+
1426
+ /**
1427
+ * How long to wait for the `paste` event after a Paste as Markdown shortcut, in milliseconds.
1428
+ */
1429
+ const PASTE_AS_MARKDOWN_TIMEOUT = 1000;
1430
+
1431
+ /**
1432
+ * Keyboard shortcuts to paste the text on the clipboard as Markdown: the browser’s own shortcuts to
1433
+ * paste plain text, Accel+Shift+V, plus Command+Option+Shift+V, the macOS Paste and Match Style.
1434
+ * @returns {string} Shortcuts.
1435
+ */
1436
+ const getPasteAsMarkdownShortcuts = () =>
1437
+ isMac() ? 'Meta+Shift+V Meta+Alt+Shift+V' : 'Ctrl+Shift+V';
1438
+
1439
+ /**
1440
+ * Register the keyboard shortcuts to paste the text on the clipboard as Markdown. A regular paste
1441
+ * prefers the HTML on the clipboard, so text copied from a code editor or a terminal ends up in a
1442
+ * code block, while Markdown pasted as plain text is kept as literal text. The shortcuts make the
1443
+ * browser paste plain text, which is then converted from Markdown. The browser does the paste,
1444
+ * because a script can’t read the clipboard after a key combination in every browser: Firefox
1445
+ * doesn’t allow it after a key pressed with Ctrl, Alt or Command.
1446
+ * @param {LexicalEditor} editor Editor instance.
1447
+ * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1448
+ * @returns {() => void} Cleanup handler.
1449
+ */
1450
+ const registerPasteAsMarkdown = (editor, enabledTransformers) => {
1451
+ const shortcuts = getPasteAsMarkdownShortcuts();
1452
+ /** Whether the paste that follows was started with one of the shortcuts. */
1453
+ let pasteAsMarkdown = false;
1454
+ let timer = 0;
1455
+
1456
+ return mergeUnregisters(
1457
+ () => {
1458
+ clearTimeout(timer);
1459
+ },
1460
+ editor.registerCommand(
1461
+ KEY_DOWN_COMMAND,
1462
+ (event) => {
1463
+ // Any other key cancels the shortcut. Chrome on macOS fires the `paste` event in a later
1464
+ // task, so wait a moment for it, but not too long, in case the browser doesn’t paste with
1465
+ // the shortcut, like Safari with Command+Shift+V
1466
+ pasteAsMarkdown = matchesShortcuts(event, shortcuts);
1467
+ clearTimeout(timer);
1468
+
1469
+ if (pasteAsMarkdown) {
1470
+ timer = window.setTimeout(() => {
1471
+ pasteAsMarkdown = false;
1472
+ }, PASTE_AS_MARKDOWN_TIMEOUT);
1473
+ }
1474
+
1475
+ // Let the browser paste
1476
+ return false;
1477
+ },
1478
+ COMMAND_PRIORITY_NORMAL,
1479
+ ),
1480
+ editor.registerCommand(
1481
+ PASTE_COMMAND,
1482
+ (event) => {
1483
+ if (!pasteAsMarkdown) {
1484
+ return false;
1485
+ }
1486
+
1487
+ pasteAsMarkdown = false;
1488
+
1489
+ const isClipboardEvent = objectKlassEquals(event, ClipboardEvent);
1490
+
1491
+ // Safari pastes with an `insertFromPaste` input event instead of a `paste` event
1492
+ const dataTransfer = isClipboardEvent
1493
+ ? /** @type {ClipboardEvent} */ (event).clipboardData
1494
+ : objectKlassEquals(event, InputEvent)
1495
+ ? /** @type {InputEvent} */ (event).dataTransfer
1496
+ : null;
1497
+
1498
+ const text = dataTransfer?.getData('text/plain');
1499
+
1500
+ // Leave a URL to the link paste handler, which links the selected text. It only handles a
1501
+ // `paste` event, so Safari still pastes a URL as Markdown
1502
+ if (!text || (isClipboardEvent && isURL(text.trim()))) {
1503
+ return false;
1504
+ }
1505
+
1506
+ event.preventDefault();
1507
+ pasteMarkdown(editor, text, enabledTransformers);
1508
+
1509
+ return true;
1510
+ },
1511
+ // Before the link paste handler and Lexical’s own one
1512
+ COMMAND_PRIORITY_NORMAL,
1513
+ ),
1514
+ );
1515
+ };
1516
+
1244
1517
  /**
1245
1518
  * Initialize the Lexical editor.
1246
1519
  * @param {TextEditorConfig} config Editor configuration.
@@ -1399,6 +1672,7 @@ export const initEditor = (config) => {
1399
1672
  registerListCommands(editor, enabledButtons),
1400
1673
  registerUpdateEvent(editor, enabledTransformers, format),
1401
1674
  registerTabIndentation(editor),
1675
+ isCodeEditor ? undefined : registerPasteAsMarkdown(editor, enabledTransformers),
1402
1676
  );
1403
1677
 
1404
1678
  return {
@@ -1414,24 +1688,6 @@ export const initEditor = (config) => {
1414
1688
  };
1415
1689
  };
1416
1690
 
1417
- /**
1418
- * Preload the syntax highlighter for the given programming language.
1419
- *
1420
- * Highlighting also works without this — the transform loads whatever it needs and re-highlights
1421
- * once it arrives — but preloading avoids a visible flash of unhighlighted code.
1422
- * @param {string} lang Language name, like scss.
1423
- */
1424
- export const loadCodeHighlighter = async (lang) => {
1425
- if (isPlainLanguage(lang)) {
1426
- return;
1427
- }
1428
-
1429
- // The grammar and theme loaders are no-ops until the engine is in place
1430
- await loadEngine();
1431
-
1432
- await Promise.all([loadCodeLanguage(normalizeCodeLanguage(lang)), loadCodeTheme(getCodeTheme())]);
1433
- };
1434
-
1435
1691
  /**
1436
1692
  * Number of the latest import started for each editor.
1437
1693
  * @type {WeakMap<LexicalEditor, number>}
@@ -1509,39 +1765,6 @@ const importValue = async (editor, { languages, $import, $export, formatName })
1509
1765
  return editor.read($export);
1510
1766
  };
1511
1767
 
1512
- /**
1513
- * Remove the placeholders added by `addImportPlaceholders()` from the imported nodes: the text, the
1514
- * Markdown of raw syntax, and the URL and title of a link. The text of raw syntax is restored from
1515
- * the Markdown it was imported from, as Lexical has removed its escapes, which are not escapes in
1516
- * raw HTML; see `RAW_HTML`.
1517
- */
1518
- const removePlaceholders = () => {
1519
- getRoot()
1520
- .getAllTextNodes()
1521
- .forEach((node) => {
1522
- const text = node.getTextContent();
1523
- const newText = removeImportPlaceholders(getImportedRawSyntax(node) ?? text);
1524
- const link = node.getParent();
1525
-
1526
- if (newText !== text) {
1527
- node.setTextContent(newText);
1528
- }
1529
-
1530
- if (isLinkNode(link)) {
1531
- const url = link.getURL();
1532
- const title = link.getTitle();
1533
-
1534
- if (removeImportPlaceholders(url) !== url) {
1535
- link.setURL(removeImportPlaceholders(url));
1536
- }
1537
-
1538
- if (title && removeImportPlaceholders(title) !== title) {
1539
- link.setTitle(removeImportPlaceholders(title));
1540
- }
1541
- }
1542
- });
1543
- };
1544
-
1545
1768
  /**
1546
1769
  * Convert Markdown to Lexical nodes.
1547
1770
  * @param {LexicalEditor} editor Editor instance.
@@ -1553,51 +1776,15 @@ const removePlaceholders = () => {
1553
1776
  * @throws {Error} Failed to convert the value to Lexical nodes.
1554
1777
  */
1555
1778
  export const convertMarkdownToLexical = async (editor, value, enabledTransformers) => {
1556
- // Convert the syntax Lexical doesn’t support to the one it does, if the element is enabled: tilde
1557
- // code fences to backtick ones, and setext headings to ATX ones. Otherwise the syntax is kept as
1558
- // text, as written. A transformer is found by its regular expression, because the transformers
1559
- // can come wrapped in a `$state` proxy, which leaves a regular expression as is but not the
1560
- // transformer object itself
1561
- const hasCodeBlocks = enabledTransformers.some(
1562
- (transformer) => 'regExpStart' in transformer && transformer.regExpStart === CODE.regExpStart,
1563
- );
1564
-
1565
- const hasHeadings = enabledTransformers.some(
1566
- (transformer) => 'regExp' in transformer && transformer.regExp === HEADING.regExp,
1567
- );
1568
-
1569
- const fencedValue = hasCodeBlocks ? convertTildeFences(value) : value;
1570
- const normalizedValue = hasHeadings ? convertSetextHeadings(fencedValue) : fencedValue;
1779
+ const { markdown, languages } = prepareMarkdown(value, enabledTransformers);
1571
1780
 
1572
1781
  return importValue(editor, {
1573
- // The language is the leading word of the info string, like `js` in ```` ``` js title=x ````;
1574
- // see `CODE`
1575
- languages: [...normalizedValue.matchAll(/^`{3,}[ \t]*(?<lang>[\w-]+)/gm)].map(
1576
- ({ groups: { lang = 'plain' } = {} }) => lang,
1577
- ),
1782
+ languages,
1578
1783
  /**
1579
1784
  * Import the Markdown.
1580
1785
  */
1581
1786
  $import: () => {
1582
- // Split multiline formatting into separate lines to prevent Markdown parsing issues
1583
- const splitValue = splitMultilineFormatting(normalizedValue);
1584
- // Add placeholders so Lexical reads the backslashes, the tabs in code spans and raw HTML
1585
- // right
1586
- const markedValue = addImportPlaceholders(splitValue);
1587
-
1588
- convertFromMarkdownString(
1589
- // Pad blank blockquote lines so they are not imported as literal `>` text
1590
- padBlankBlockquoteLines(markedValue),
1591
- // Keep the formatting around a code span after other formatting
1592
- addCodeSpanSplit(enabledTransformers),
1593
- );
1594
-
1595
- // The text of raw HTML and raw syntax is restored as well. The lines of an HTML block have a
1596
- // placeholder. Other raw syntax, like an autolink or a definition label, only differs from
1597
- // its text if Lexical has decoded an escape or a character reference in it
1598
- if (markedValue !== splitValue || /[\\&]/.test(markedValue)) {
1599
- removePlaceholders();
1600
- }
1787
+ $importMarkdown(markdown, enabledTransformers, { toRoot: true });
1601
1788
  },
1602
1789
  /**
1603
1790
  * Export the content as Markdown.
@@ -3,7 +3,7 @@
3
3
  * version bundled into `dist/shiki-engine.js`, because grammar and theme payloads are only
4
4
  * guaranteed to be compatible with the matching engine.
5
5
  */
6
- export const SHIKI_VERSION: "4.5.0";
6
+ export const SHIKI_VERSION: "4.6.0";
7
7
  /**
8
8
  * Available syntax highlighting languages, sorted by display name.
9
9
  * @type {{ id: string, name: string, aliases?: string[] }[]}
@@ -5,7 +5,7 @@
5
5
  * version bundled into `dist/shiki-engine.js`, because grammar and theme payloads are only
6
6
  * guaranteed to be compatible with the matching engine.
7
7
  */
8
- export const SHIKI_VERSION = "4.5.0";
8
+ export const SHIKI_VERSION = "4.6.0";
9
9
 
10
10
  /**
11
11
  * Available syntax highlighting languages, sorted by display name.
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * Version of this package, used to resolve the prebuilt Shiki engine chunk from a CDN.
3
3
  */
4
- export const UI_VERSION: "0.88.3";
4
+ export const UI_VERSION: "0.89.0";
@@ -3,4 +3,4 @@
3
3
  /**
4
4
  * Version of this package, used to resolve the prebuilt Shiki engine chunk from a CDN.
5
5
  */
6
- export const UI_VERSION = '0.88.3';
6
+ export const UI_VERSION = '0.89.0';
@@ -34,7 +34,10 @@ export const HR = {
34
34
  parentNode.insertBefore(line);
35
35
  }
36
36
 
37
- line.selectNext();
37
+ // A pasted rule is created in a detached container, where there’s nothing to select
38
+ if (line.isAttached()) {
39
+ line.selectNext();
40
+ }
38
41
  },
39
42
  type: 'element',
40
43
  };