@sveltia/ui 0.87.1 → 0.87.3

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.
@@ -0,0 +1,95 @@
1
+ import { CODE as LEXICAL_CODE } from '@lexical/markdown';
2
+
3
+ /**
4
+ * @import { MultilineElementTransformer } from '@lexical/markdown';
5
+ * @import { ElementNode, LexicalNode } from 'lexical';
6
+ */
7
+
8
+ /**
9
+ * Placeholder for a backtick in the info string of a code block fenced with tildes, which is
10
+ * converted to one fenced with backticks before the Markdown is imported; see
11
+ * `convertTildeFences()`. Unlike that of a tilde fence, the info string of a backtick fence can’t
12
+ * contain a backtick.
13
+ */
14
+ export const INFO_BACKTICK = '\uE001';
15
+
16
+ /**
17
+ * Regular expression to match the opening fence of a code block and its info string, if any. Like
18
+ * Lexical, the language is the leading word of the info string, and the rest is metadata.
19
+ */
20
+ const OPENING_FENCE_REGEX = /^([ \t]*`{3,})[ \t]*([\w-]+)?[ \t]*/;
21
+
22
+ /**
23
+ * Code block transformer that, unlike Lexical’s, doesn’t take a line with a backtick after the
24
+ * opening backtick fence for a code block. In CommonMark, the info string of a backtick fence
25
+ * can’t contain a backtick, so such a line is a paragraph starting with inline code, like a code
26
+ * span of three backticks, which the editor exports with a fence of four backticks. Lexical would
27
+ * turn it into a code block the next time the Markdown is read. It also reads the info string as
28
+ * CommonMark does when Lexical doesn’t: the language after spaces, like ```` ``` js ````, and the
29
+ * metadata after the language of a code block without a closing fence, like
30
+ * ```` ```js title=x ````, which Lexical would add to the code. Last, it exports a code block with
31
+ * a backtick in its info string, imported from a tilde fence, with a tilde fence again. The rest is
32
+ * Lexical’s.
33
+ * @type {MultilineElementTransformer}
34
+ * @see https://spec.commonmark.org/0.31.2/#fenced-code-blocks
35
+ */
36
+ export const CODE = {
37
+ ...LEXICAL_CODE,
38
+ /**
39
+ * Export a code block.
40
+ * @param {LexicalNode} node Node.
41
+ * @param {(node: ElementNode) => string} exportChildren Function to export the children of an
42
+ * element.
43
+ * @returns {string | null} Markdown, or `null` if the node isn’t a code block.
44
+ */
45
+ export: (node, exportChildren) => {
46
+ const markdown = LEXICAL_CODE.export?.(node, exportChildren) ?? null;
47
+ const [openingLine] = markdown?.split('\n', 1) ?? [];
48
+
49
+ if (!markdown || !openingLine.includes(INFO_BACKTICK)) {
50
+ return markdown;
51
+ }
52
+
53
+ // Lexical makes the fence longer than any backtick run in the code; do the same with tildes
54
+ const code = markdown.slice(openingLine.length, markdown.lastIndexOf('\n'));
55
+
56
+ const longestRun = Math.max(
57
+ 2,
58
+ ...(code.match(/^[ \t]*~+/gm) ?? []).map((run) => run.trim().length),
59
+ );
60
+
61
+ const fence = '~'.repeat(longestRun + 1);
62
+
63
+ return `${openingLine.replace(/^`+/, fence).replaceAll(INFO_BACKTICK, '`')}${code}\n${fence}`;
64
+ },
65
+ /**
66
+ * Import a code block, starting with the given opening fence.
67
+ * @param {object} args Arguments.
68
+ * @param {string[]} args.lines Lines of the Markdown.
69
+ * @param {ElementNode} args.rootNode Node to append the code block to.
70
+ * @param {number} args.startLineIndex Index of the line with the opening fence.
71
+ * @param {RegExpMatchArray} args.startMatch Match of the opening fence.
72
+ * @param {MultilineElementTransformer} args.transformer This transformer.
73
+ * @returns {[boolean, number] | null | undefined} Whether the code block has been imported, and
74
+ * the index of its last line.
75
+ */
76
+ handleImportAfterStartMatch: ({ lines, startLineIndex, ...args }) => {
77
+ const openingLine = lines[startLineIndex];
78
+ const startMatch = /** @type {RegExpMatchArray} */ (openingLine.match(OPENING_FENCE_REGEX));
79
+ const fence = startMatch[1].trim();
80
+ const closingFenceRegex = new RegExp(`^[ \\t]*\`{${fence.length},}$`);
81
+ // Lexical only reads the metadata of a code block with a closing fence, so close it at the end
82
+ // of the Markdown if it isn’t closed
83
+ const isClosed = lines.slice(startLineIndex + 1).some((line) => closingFenceRegex.test(line));
84
+
85
+ const result = LEXICAL_CODE.handleImportAfterStartMatch?.({
86
+ ...args,
87
+ lines: isClosed ? lines : [...lines, fence],
88
+ startLineIndex,
89
+ startMatch,
90
+ });
91
+
92
+ return result && [result[0], Math.min(result[1], lines.length - 1)];
93
+ },
94
+ regExpStart: new RegExp(`${LEXICAL_CODE.regExpStart.source}(?=[^\`]*$)`),
95
+ };
@@ -0,0 +1,38 @@
1
+ export function addCodeSpanSplit(transformers: Transformer[]): Transformer[];
2
+ export type Range = {
3
+ /**
4
+ * Start index.
5
+ */
6
+ start: number;
7
+ /**
8
+ * End index, exclusive.
9
+ */
10
+ end: number;
11
+ };
12
+ export type Delimiter = {
13
+ /**
14
+ * Delimiter character.
15
+ */
16
+ char: string;
17
+ /**
18
+ * Index of the remaining delimiter characters.
19
+ */
20
+ index: number;
21
+ /**
22
+ * Number of the remaining delimiter characters.
23
+ */
24
+ length: number;
25
+ /**
26
+ * Whether the run can open emphasis.
27
+ */
28
+ canOpen: boolean;
29
+ /**
30
+ * Whether the run can close emphasis.
31
+ */
32
+ canClose: boolean;
33
+ /**
34
+ * Whether the run can still be paired.
35
+ */
36
+ active: boolean;
37
+ };
38
+ import type { Transformer } from '@lexical/markdown';
@@ -0,0 +1,394 @@
1
+ import { findCodeSpans } from '../markdown.js';
2
+
3
+ /**
4
+ * @import { TextFormatTransformer, TextMatchTransformer, Transformer } from '@lexical/markdown';
5
+ * @import { TextNode } from 'lexical';
6
+ */
7
+
8
+ /**
9
+ * @typedef {object} Range
10
+ * @property {number} start Start index.
11
+ * @property {number} end End index, exclusive.
12
+ */
13
+
14
+ /**
15
+ * @typedef {object} Delimiter
16
+ * @property {string} char Delimiter character.
17
+ * @property {number} index Index of the remaining delimiter characters.
18
+ * @property {number} length Number of the remaining delimiter characters.
19
+ * @property {boolean} canOpen Whether the run can open emphasis.
20
+ * @property {boolean} canClose Whether the run can close emphasis.
21
+ * @property {boolean} active Whether the run can still be paired.
22
+ */
23
+
24
+ /**
25
+ * Whitespace, as Lexical reads it.
26
+ */
27
+ const WHITESPACE = /\s/;
28
+ /**
29
+ * ASCII punctuation, as Lexical reads it. Unlike CommonMark, Lexical leaves out the backslash.
30
+ */
31
+ const PUNCTUATION = /[!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~]/;
32
+
33
+ /**
34
+ * Check if the character at the given index is escaped with a backslash.
35
+ * @param {string} text Text.
36
+ * @param {number} index Index.
37
+ * @returns {boolean} Result.
38
+ */
39
+ const isEscaped = (text, index) => {
40
+ let count = 0;
41
+
42
+ while (text[index - count - 1] === '\\') {
43
+ count += 1;
44
+ }
45
+
46
+ return count % 2 === 1;
47
+ };
48
+
49
+ /**
50
+ * Check if a delimiter run is left-flanking or right-flanking, like Lexical does.
51
+ * @param {string} text Text.
52
+ * @param {number} index Index of the run.
53
+ * @param {number} length Length of the run.
54
+ * @param {boolean} isLeft Whether to check if it’s left-flanking.
55
+ * @returns {boolean} Result.
56
+ * @see https://spec.commonmark.org/0.31.2/#left-flanking-delimiter-run
57
+ */
58
+ const isFlanking = (text, index, length, isLeft) => {
59
+ const before = text[index - 1];
60
+ const after = text[index + length];
61
+ const [primary, secondary] = isLeft ? [after, before] : [before, after];
62
+
63
+ if (primary === undefined || WHITESPACE.test(primary)) {
64
+ return false;
65
+ }
66
+
67
+ return (
68
+ !PUNCTUATION.test(primary) ||
69
+ secondary === undefined ||
70
+ WHITESPACE.test(secondary) ||
71
+ PUNCTUATION.test(secondary)
72
+ );
73
+ };
74
+
75
+ /**
76
+ * Check if a delimiter run can open or close emphasis, like Lexical does.
77
+ * @param {string} text Text.
78
+ * @param {number} index Index of the run.
79
+ * @param {number} length Length of the run.
80
+ * @param {boolean} isOpen Whether to check if it can open emphasis.
81
+ * @returns {boolean} Result.
82
+ */
83
+ const canEmphasis = (text, index, length, isOpen) => {
84
+ if (!isFlanking(text, index, length, isOpen)) {
85
+ return false;
86
+ }
87
+
88
+ if (text[index] !== '_' || !isFlanking(text, index, length, !isOpen)) {
89
+ return true;
90
+ }
91
+
92
+ const adjacent = isOpen ? text[index - 1] : text[index + length];
93
+
94
+ return adjacent !== undefined && PUNCTUATION.test(adjacent);
95
+ };
96
+
97
+ /**
98
+ * Find the delimiter runs outside code spans that can open or close emphasis, like Lexical does.
99
+ * @param {string} text Text.
100
+ * @param {Set<string>} chars Delimiter characters.
101
+ * @param {Range[]} codeSpans Code spans.
102
+ * @returns {Delimiter[]} Delimiter runs.
103
+ */
104
+ const findDelimiters = (text, chars, codeSpans) => {
105
+ /** @type {Delimiter[]} */
106
+ const delimiters = [];
107
+ let spanIndex = 0;
108
+ let index = 0;
109
+
110
+ while (index < text.length) {
111
+ while (spanIndex < codeSpans.length && codeSpans[spanIndex].end <= index) {
112
+ spanIndex += 1;
113
+ }
114
+
115
+ const char = text[index];
116
+ const span = codeSpans[spanIndex];
117
+
118
+ if (span && span.start <= index) {
119
+ index = span.end;
120
+ } else if (!chars.has(char) || isEscaped(text, index)) {
121
+ index += 1;
122
+ } else {
123
+ let length = 1;
124
+
125
+ while (text[index + length] === char) {
126
+ length += 1;
127
+ }
128
+
129
+ const canOpen = canEmphasis(text, index, length, true);
130
+ const canClose = canEmphasis(text, index, length, false);
131
+
132
+ if (canOpen || canClose) {
133
+ delimiters.push({ char, index, length, canOpen, canClose, active: true });
134
+ }
135
+
136
+ index += length;
137
+ }
138
+ }
139
+
140
+ return delimiters;
141
+ };
142
+
143
+ /**
144
+ * Pair the delimiter runs like Lexical does, following the CommonMark algorithm.
145
+ * @param {Delimiter[]} delimiters Delimiter runs, which are updated as they’re paired.
146
+ * @param {string[]} tags Delimiters of the text formats, like `**`.
147
+ * @returns {Range[]} Emphasis, from the opening delimiters to the closing ones.
148
+ * @see https://spec.commonmark.org/0.31.2/#process-emphasis
149
+ */
150
+ const pairDelimiters = (delimiters, tags) => {
151
+ /** @type {Record<string, number>} */
152
+ const openersBottom = {};
153
+ /** @type {Range[]} */
154
+ const pairs = [];
155
+ let position = 0;
156
+
157
+ while (position < delimiters.length) {
158
+ const closer = delimiters[position];
159
+
160
+ if (!closer.active || !closer.canClose || !closer.length) {
161
+ position += 1;
162
+ } else {
163
+ const bottomKey = `${closer.char}${closer.canOpen}${closer.length % 3}`;
164
+ const bottom = openersBottom[bottomKey] ?? -1;
165
+ let found = false;
166
+
167
+ for (let openIndex = position - 1; openIndex > bottom && !found; openIndex -= 1) {
168
+ const opener = delimiters[openIndex];
169
+
170
+ const canPair =
171
+ opener.active &&
172
+ opener.canOpen &&
173
+ opener.length > 0 &&
174
+ opener.char === closer.char &&
175
+ // The rule of 3
176
+ !(
177
+ (opener.canClose || closer.canOpen) &&
178
+ (opener.length + closer.length) % 3 === 0 &&
179
+ opener.length % 3 !== 0 &&
180
+ closer.length % 3 !== 0
181
+ );
182
+
183
+ const maxLength = Math.min(opener.length, closer.length);
184
+
185
+ const tag = canPair
186
+ ? tags
187
+ .filter((t) => t[0] === opener.char && t.length <= maxLength)
188
+ .sort((a, b) => b.length - a.length)[0]
189
+ : undefined;
190
+
191
+ if (tag) {
192
+ found = true;
193
+ pairs.push({
194
+ start: opener.index + opener.length - tag.length,
195
+ end: closer.index + tag.length,
196
+ });
197
+
198
+ for (let index = openIndex + 1; index < position; index += 1) {
199
+ delimiters[index].active = false;
200
+ }
201
+
202
+ opener.length -= tag.length;
203
+ closer.length -= tag.length;
204
+ opener.active = opener.length > 0;
205
+
206
+ if (closer.length > 0) {
207
+ closer.index += tag.length;
208
+ } else {
209
+ closer.active = false;
210
+ position += 1;
211
+ }
212
+ }
213
+ }
214
+
215
+ if (!found) {
216
+ openersBottom[bottomKey] = position - 1;
217
+ closer.active = closer.canOpen;
218
+ position += 1;
219
+ }
220
+ }
221
+ }
222
+
223
+ return pairs;
224
+ };
225
+
226
+ /**
227
+ * Create a function that finds where a text node has to be split before Lexical imports it, so the
228
+ * formatting around a code span isn’t lost; see `addCodeSpanSplit()`.
229
+ * @param {string[]} tags Delimiters of the text formats other than code, like `**`.
230
+ * @param {TextMatchTransformer[]} textMatchTransformers Text match transformers.
231
+ * @returns {(text: string) => number | undefined} Function that returns the index to split the
232
+ * text at, or `undefined` if it doesn’t have to be split.
233
+ */
234
+ const createSplitIndexFinder = (tags, textMatchTransformers) => {
235
+ const chars = new Set(tags.map((tag) => tag[0]));
236
+
237
+ const regexes = textMatchTransformers.flatMap(({ importRegExp }) =>
238
+ importRegExp
239
+ ? [new RegExp(importRegExp.source, `${importRegExp.flags.replace('g', '')}g`)]
240
+ : [],
241
+ );
242
+
243
+ /** @type {{ text: string, index: number | undefined } | undefined} */
244
+ let cache;
245
+
246
+ /**
247
+ * Find the index to split the text at.
248
+ * @param {string} text Text.
249
+ * @returns {number | undefined} Index.
250
+ */
251
+ const findSplitIndex = (text) => {
252
+ const codeSpans = findCodeSpans(text);
253
+ const [code] = codeSpans;
254
+
255
+ if (!code) {
256
+ return undefined;
257
+ }
258
+
259
+ const pairs = pairDelimiters(findDelimiters(text, chars, codeSpans), tags);
260
+ /**
261
+ * Check if the given emphasis wraps the first code span.
262
+ * @param {Range} pair Emphasis.
263
+ * @returns {boolean} Result.
264
+ */
265
+ const wrapsCode = ({ start, end }) => start <= code.start && end >= code.end;
266
+ // The emphasis Lexical imports first: the one that starts first, or the longest of those
267
+ const [first] = [...pairs].sort((a, b) => a.start - b.start || b.end - a.end);
268
+
269
+ if (!first || wrapsCode(first)) {
270
+ return undefined;
271
+ }
272
+
273
+ // The outermost emphasis around the code span
274
+ const [outer] = pairs.filter(wrapsCode).sort((a, b) => a.start - b.start);
275
+
276
+ if (
277
+ !outer ||
278
+ // A text match, like a link, that the split would cut in two
279
+ regexes.some((regex) =>
280
+ [...text.matchAll(regex)].some(
281
+ ({ 0: { length }, index }) => index < outer.start && index + length > outer.start,
282
+ ),
283
+ )
284
+ ) {
285
+ return undefined;
286
+ }
287
+
288
+ return outer.start;
289
+ };
290
+
291
+ return (text) => {
292
+ if (cache?.text !== text) {
293
+ cache = { text, index: findSplitIndex(text) };
294
+ }
295
+
296
+ return cache.index;
297
+ };
298
+ };
299
+
300
+ /**
301
+ * Add a transformer to the given ones that keeps the formatting around a code span when Lexical
302
+ * imports it after other formatting or a link, like `` **`a`** `` in `` **b** **`a`** `` or
303
+ * `` [**b**](u)**`a`** ``. Lexical takes a code span before the formatting, unless the formatting
304
+ * it would take first wraps the code span, and that formatting is the one that starts first, like
305
+ * `**b**`. So Lexical takes the code span, splitting the text around it, and the formatting around
306
+ * the code span is lost, along with its delimiters, which are then escaped on export. The added
307
+ * transformer splits the text where the formatting around the code span starts, so each part is
308
+ * imported on its own. To find it, the delimiters are paired like Lexical does. Lexical only lets a
309
+ * text match take precedence over the code span if it wraps the code span, so the text is matched
310
+ * from there to its end. The other text match transformers are wrapped so they don’t match before
311
+ * that point, as Lexical takes the text match that starts first; they match in the part before it
312
+ * instead. The text isn’t split if it would cut a text match in two. It’s only for the import.
313
+ * @param {Transformer[]} transformers Transformers.
314
+ * @returns {Transformer[]} Transformers for the import.
315
+ * @see https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis
316
+ */
317
+ export const addCodeSpanSplit = (transformers) => {
318
+ const tags = transformers
319
+ .filter((transformer) => transformer.type === 'text-format')
320
+ .map((transformer) => /** @type {TextFormatTransformer} */ (transformer).tag);
321
+
322
+ if (!tags.includes('`')) {
323
+ return transformers;
324
+ }
325
+
326
+ const findSplitIndex = createSplitIndexFinder(
327
+ tags.filter((tag) => tag !== '`'),
328
+ /** @type {TextMatchTransformer[]} */ (
329
+ transformers.filter((transformer) => transformer.type === 'text-match')
330
+ ),
331
+ );
332
+
333
+ /** @type {TextMatchTransformer} */
334
+ const splitter = {
335
+ dependencies: [],
336
+ /**
337
+ * Leave the export to the other transformers.
338
+ * @returns {null} Nothing.
339
+ */
340
+ export: () => null,
341
+ // Lexical matches the text with `String.prototype.match()`, which calls this method
342
+ importRegExp: Object.assign(/(?!)/, {
343
+ /**
344
+ * Match the text from the index to split it at to its end.
345
+ * @param {string} text Text.
346
+ * @returns {RegExpMatchArray | null} Match.
347
+ */
348
+ [Symbol.match]: (text) => {
349
+ const index = findSplitIndex(text);
350
+
351
+ return index === undefined
352
+ ? null
353
+ : /** @type {RegExpMatchArray} */ (
354
+ Object.assign([text.slice(index)], { index, input: text })
355
+ );
356
+ },
357
+ }),
358
+ regExp: /(?!)/,
359
+ /**
360
+ * Leave the part of the text from the split to Lexical, which imports it on its own.
361
+ * @param {TextNode} node Text node with the matched text.
362
+ * @returns {TextNode} Same node.
363
+ */
364
+ replace: (node) => node,
365
+ type: 'text-match',
366
+ };
367
+
368
+ return [
369
+ splitter,
370
+ ...transformers.map((transformer) => {
371
+ if (transformer.type !== 'text-match') {
372
+ return transformer;
373
+ }
374
+
375
+ const { getEndIndex } = /** @type {TextMatchTransformer} */ (transformer);
376
+
377
+ return {
378
+ ...transformer,
379
+ /**
380
+ * Get the end index of a match, or `false` to skip it if it ends before the split.
381
+ * @param {TextNode} node Text node.
382
+ * @param {RegExpMatchArray} match Match.
383
+ * @returns {number | false} End index or `false`.
384
+ */
385
+ getEndIndex: (node, match) => {
386
+ const end = getEndIndex ? getEndIndex(node, match) : (match.index ?? 0) + match[0].length;
387
+ const splitIndex = findSplitIndex(node.getTextContent());
388
+
389
+ return end !== false && splitIndex !== undefined && end <= splitIndex ? false : end;
390
+ },
391
+ };
392
+ }),
393
+ ];
394
+ };
@@ -0,0 +1,20 @@
1
+ export function getFormatExportNode(node: TextNode): TextNode;
2
+ /**
3
+ * Import-only transformer for a code span at the start of a node, such as a table cell, a
4
+ * paragraph or bold text starting with inline code. Lexical’s `INLINE_CODE` transformer then reuses
5
+ * the node for the code, and removes the backslash escapes from the node once the inline syntax has
6
+ * been imported, so `` `C:\$MFT` `` would become `C:$MFT`, though backslashes are literal in a code
7
+ * span. Backslashes in a code span split from the text before it are kept. A text match wrapping a
8
+ * code span takes priority over it, and this one replaces the node with a new one, leaving the old
9
+ * node, which is no longer in the document, to be unescaped. It also exports a code span that
10
+ * starts and ends with whitespace, which Lexical pads with a space on both sides, though CommonMark
11
+ * only strips that padding if both ends are spaces and the content isn’t all spaces, so `` ` ` ``
12
+ * would get two spaces longer on every save, and `` `\t` `` would become `` ` \t ` ``.
13
+ * It exports code next to inline code made only of whitespace too; see `getFormatExportNode()`.
14
+ * @type {TextMatchTransformer}
15
+ * @see https://github.com/sveltia/sveltia-cms/issues/1100
16
+ * @see https://spec.commonmark.org/0.31.2/#code-spans
17
+ */
18
+ export const LEADING_INLINE_CODE: TextMatchTransformer;
19
+ import type { TextNode } from 'lexical';
20
+ import type { TextMatchTransformer } from '@lexical/markdown';