@sveltia/ui 0.89.2 → 0.89.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.
Files changed (98) hide show
  1. package/dist/components/checkbox/checkbox.svelte +5 -8
  2. package/dist/components/emoji/emoji-suggestions.svelte +7 -7
  3. package/dist/components/grid/grid-col-header.svelte +4 -0
  4. package/dist/components/grid/grid-head.svelte +1 -1
  5. package/dist/components/grid/grid-head.svelte.d.ts +1 -1
  6. package/dist/components/radio/radio.svelte +9 -9
  7. package/dist/components/resizable-pane/resizable-pane-group.svelte +5 -20
  8. package/dist/components/resizable-pane/sizing.d.ts +6 -0
  9. package/dist/components/resizable-pane/sizing.js +31 -0
  10. package/dist/components/text-editor/code-editor.svelte +22 -39
  11. package/dist/components/text-editor/constants.js +3 -3
  12. package/dist/components/text-editor/conversion/editor-components.d.ts +5 -0
  13. package/dist/components/text-editor/conversion/editor-components.js +228 -0
  14. package/dist/components/text-editor/{html.d.ts → conversion/html.d.ts} +1 -1
  15. package/dist/components/text-editor/{html.js → conversion/html.js} +2 -2
  16. package/dist/components/text-editor/conversion/import.d.ts +12 -0
  17. package/dist/components/text-editor/conversion/import.js +327 -0
  18. package/dist/components/text-editor/conversion/paste.d.ts +4 -0
  19. package/dist/components/text-editor/conversion/paste.js +166 -0
  20. package/dist/components/text-editor/{transformers → conversion/transformers}/raw-syntax.js +4 -4
  21. package/dist/components/text-editor/conversion/transformers/table.js +342 -0
  22. package/dist/components/text-editor/conversion/update.d.ts +6 -0
  23. package/dist/components/text-editor/conversion/update.js +125 -0
  24. package/dist/components/text-editor/core.d.ts +50 -26
  25. package/dist/components/text-editor/core.js +133 -1694
  26. package/dist/components/text-editor/editing/caret.d.ts +4 -0
  27. package/dist/components/text-editor/editing/caret.js +248 -0
  28. package/dist/components/text-editor/editing/commands.d.ts +5 -0
  29. package/dist/components/text-editor/editing/commands.js +205 -0
  30. package/dist/components/text-editor/editing/link.d.ts +19 -0
  31. package/dist/components/text-editor/editing/link.js +222 -0
  32. package/dist/components/text-editor/{raw-markdown.d.ts → editing/raw-markdown.d.ts} +3 -3
  33. package/dist/components/text-editor/{raw-markdown.js → editing/raw-markdown.js} +2 -2
  34. package/dist/components/text-editor/editing/selection.d.ts +5 -0
  35. package/dist/components/text-editor/editing/selection.js +122 -0
  36. package/dist/components/text-editor/editing/single-line.d.ts +8 -0
  37. package/dist/components/text-editor/editing/single-line.js +190 -0
  38. package/dist/components/text-editor/{table.js → editing/table.js} +1 -1
  39. package/dist/components/text-editor/lexical-root.svelte +61 -10
  40. package/dist/components/text-editor/shiki/preload.d.ts +1 -0
  41. package/dist/components/text-editor/shiki/preload.js +30 -0
  42. package/dist/components/text-editor/shiki/version.d.ts +1 -1
  43. package/dist/components/text-editor/shiki/version.js +1 -1
  44. package/dist/components/text-editor/store.svelte.d.ts +5 -0
  45. package/dist/components/text-editor/store.svelte.js +55 -1
  46. package/dist/components/text-editor/text-editor.svelte +29 -41
  47. package/dist/components/text-editor/toolbar/align-menu-button.svelte +1 -1
  48. package/dist/components/text-editor/toolbar/code-language-switcher.svelte +2 -1
  49. package/dist/components/text-editor/toolbar/format-text-button.svelte +6 -2
  50. package/dist/components/text-editor/toolbar/insert-component.js +1 -1
  51. package/dist/components/text-editor/toolbar/insert-horizontal-rule-button.svelte +4 -4
  52. package/dist/components/text-editor/toolbar/insert-link-button.svelte +3 -2
  53. package/dist/components/text-editor/toolbar/insert-table-button.svelte +7 -3
  54. package/dist/components/text-editor/toolbar/table-action-menu.svelte +3 -3
  55. package/dist/components/text-editor/toolbar/text-editor-toolbar.svelte +1 -1
  56. package/dist/components/text-editor/toolbar/toggle-block-menu-item.svelte +2 -2
  57. package/dist/components/text-editor/utils.d.ts +1 -0
  58. package/dist/components/text-editor/utils.js +17 -0
  59. package/dist/components/text-editor/{emoji-autocomplete.svelte → widgets/emoji-autocomplete.svelte} +3 -3
  60. package/dist/components/text-editor/{floating-link-editor.svelte → widgets/floating-link-editor.svelte} +36 -79
  61. package/dist/components/text-editor/{table-cell-menu-button.svelte → widgets/table-cell-menu-button.svelte} +15 -5
  62. package/dist/components/text-field/date-time-input.svelte +8 -8
  63. package/dist/components/text-field/text-area.svelte +10 -10
  64. package/dist/components/text-field/text-input.svelte +7 -7
  65. package/dist/components/util/popup.svelte +1 -1
  66. package/dist/index.d.ts +1 -1
  67. package/dist/index.js +1 -1
  68. package/dist/services/label.d.ts +8 -0
  69. package/dist/services/label.js +15 -0
  70. package/dist/services/popup-position.d.ts +9 -0
  71. package/dist/services/popup-position.js +52 -55
  72. package/dist/styles/mixins.scss +69 -0
  73. package/package.json +5 -3
  74. package/dist/components/text-editor/transformers/table.js +0 -296
  75. /package/dist/components/text-editor/{markdown.d.ts → conversion/markdown.d.ts} +0 -0
  76. /package/dist/components/text-editor/{markdown.js → conversion/markdown.js} +0 -0
  77. /package/dist/components/text-editor/{transformers → conversion/transformers}/block-escape.d.ts +0 -0
  78. /package/dist/components/text-editor/{transformers → conversion/transformers}/block-escape.js +0 -0
  79. /package/dist/components/text-editor/{transformers → conversion/transformers}/code.d.ts +0 -0
  80. /package/dist/components/text-editor/{transformers → conversion/transformers}/code.js +0 -0
  81. /package/dist/components/text-editor/{transformers → conversion/transformers}/formatted-code.d.ts +0 -0
  82. /package/dist/components/text-editor/{transformers → conversion/transformers}/formatted-code.js +0 -0
  83. /package/dist/components/text-editor/{transformers → conversion/transformers}/hr.d.ts +0 -0
  84. /package/dist/components/text-editor/{transformers → conversion/transformers}/hr.js +0 -0
  85. /package/dist/components/text-editor/{transformers → conversion/transformers}/inline-code.d.ts +0 -0
  86. /package/dist/components/text-editor/{transformers → conversion/transformers}/inline-code.js +0 -0
  87. /package/dist/components/text-editor/{transformers → conversion/transformers}/link.d.ts +0 -0
  88. /package/dist/components/text-editor/{transformers → conversion/transformers}/link.js +0 -0
  89. /package/dist/components/text-editor/{transformers → conversion/transformers}/raw-syntax.d.ts +0 -0
  90. /package/dist/components/text-editor/{transformers → conversion/transformers}/table.d.ts +0 -0
  91. /package/dist/components/text-editor/{alignment.d.ts → editing/alignment.d.ts} +0 -0
  92. /package/dist/components/text-editor/{alignment.js → editing/alignment.js} +0 -0
  93. /package/dist/components/text-editor/{block.d.ts → editing/block.d.ts} +0 -0
  94. /package/dist/components/text-editor/{block.js → editing/block.js} +0 -0
  95. /package/dist/components/text-editor/{table.d.ts → editing/table.d.ts} +0 -0
  96. /package/dist/components/text-editor/{emoji-autocomplete.svelte.d.ts → widgets/emoji-autocomplete.svelte.d.ts} +0 -0
  97. /package/dist/components/text-editor/{floating-link-editor.svelte.d.ts → widgets/floating-link-editor.svelte.d.ts} +0 -0
  98. /package/dist/components/text-editor/{table-cell-menu-button.svelte.d.ts → widgets/table-cell-menu-button.svelte.d.ts} +0 -0
package/dist/index.d.ts CHANGED
@@ -85,7 +85,7 @@ export { default as Placeholder } from "./components/util/placeholder.svelte";
85
85
  export { default as Popup } from "./components/util/popup.svelte";
86
86
  export { default as VisibilityObserver } from "./components/util/visibility-observer.svelte";
87
87
  export { IMPORT_UPDATE_TAG } from "./components/text-editor/constants.js";
88
- export { loadCodeHighlighter } from "./components/text-editor/core.js";
88
+ export { loadCodeHighlighter } from "./components/text-editor/shiki/preload.js";
89
89
  export { setCodeHighlighterCacheEnabled } from "./components/text-editor/shiki/cache.js";
90
90
  export { highlightCodeToHTML } from "./components/text-editor/shiki/facade.js";
91
91
  export { setCodeHighlighterLoaders } from "./components/text-editor/shiki/loader.js";
package/dist/index.js CHANGED
@@ -85,7 +85,7 @@ export { default as Placeholder } from './components/util/placeholder.svelte';
85
85
  export { default as Popup } from './components/util/popup.svelte';
86
86
  export { default as VisibilityObserver } from './components/util/visibility-observer.svelte';
87
87
  export { IMPORT_UPDATE_TAG } from './components/text-editor/constants.js';
88
- export { loadCodeHighlighter } from './components/text-editor/core.js';
88
+ export { loadCodeHighlighter } from './components/text-editor/shiki/preload.js';
89
89
  export { setCodeHighlighterCacheEnabled } from './components/text-editor/shiki/cache.js';
90
90
  export { highlightCodeToHTML } from './components/text-editor/shiki/facade.js';
91
91
  export { setCodeHighlighterLoaders } from './components/text-editor/shiki/loader.js';
@@ -0,0 +1,8 @@
1
+ export function getToggleLabelAttrs({ id, ariaLabel, hasVisibleLabel }: {
2
+ id: string;
3
+ ariaLabel: string | undefined;
4
+ hasVisibleLabel: boolean;
5
+ }): {
6
+ "aria-label": string | undefined;
7
+ "aria-labelledby": string | undefined;
8
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Get the labelling attributes of the `<button>` in a `<Checkbox>` or `<Radio>`. An accessible name
3
+ * given as a prop or as a plain `aria-label` attribute takes the place of the visible label, which
4
+ * the button otherwise points at — but only when there is one to point at.
5
+ * @param {object} args Arguments.
6
+ * @param {string} args.id Component ID. The visible label has the `${id}-label` ID.
7
+ * @param {string | undefined} args.ariaLabel Accessible name, if any.
8
+ * @param {boolean} args.hasVisibleLabel Whether the component has a visible label.
9
+ * @returns {{ 'aria-label': string | undefined, 'aria-labelledby': string | undefined }}
10
+ * Attributes.
11
+ */
12
+ export const getToggleLabelAttrs = ({ id, ariaLabel, hasVisibleLabel }) => ({
13
+ 'aria-label': ariaLabel || undefined,
14
+ 'aria-labelledby': !ariaLabel && hasVisibleLabel ? `${id}-label` : undefined,
15
+ });
@@ -16,6 +16,15 @@ export function flip({ position, from, to, size, room, otherRoom }: {
16
16
  position: PopupPosition;
17
17
  cap: number | undefined;
18
18
  };
19
+ export function flipEither({ position, sides, size, rooms }: {
20
+ position: PopupPosition;
21
+ sides: [string, string];
22
+ size: number;
23
+ rooms: [number, number];
24
+ }): {
25
+ position: PopupPosition;
26
+ cap: number | undefined;
27
+ };
19
28
  export function calculatePopupStyle({ position: preferredPosition, anchorRect, viewport, contentWidth, contentHeight, }: {
20
29
  position: PopupPosition;
21
30
  anchorRect: {
@@ -110,6 +110,39 @@ export const flip = ({ position, from, to, size, room, otherRoom }) => {
110
110
  return { position, cap: room };
111
111
  };
112
112
 
113
+ /**
114
+ * Apply {@link flip} to whichever of the two opposite sides the position is on, if any.
115
+ * @internal
116
+ * @param {object} args Arguments.
117
+ * @param {PopupPosition} args.position Current position.
118
+ * @param {[string, string]} args.sides Parts of the position denoting the two sides, either both
119
+ * prefixes like `bottom-` or both suffixes like `-left`.
120
+ * @param {number} args.size Content size along the axis.
121
+ * @param {[number, number]} args.rooms Room on each side, in the same order as `sides`.
122
+ * @returns {{ position: PopupPosition, cap: number | undefined }} New position, and the size limit
123
+ * if the content doesn’t fit, `undefined` otherwise or if the position is on neither side.
124
+ */
125
+ export const flipEither = ({ position, sides, size, rooms }) => {
126
+ /**
127
+ * Check if the position is on the given side.
128
+ * @param {string} side Prefix or suffix.
129
+ * @returns {boolean} Result.
130
+ */
131
+ const isOn = (side) => (side.endsWith('-') ? position.startsWith(side) : position.endsWith(side));
132
+ const [sideA, sideB] = sides;
133
+ const [roomA, roomB] = rooms;
134
+
135
+ if (isOn(sideA)) {
136
+ return flip({ position, from: sideA, to: sideB, size, room: roomA, otherRoom: roomB });
137
+ }
138
+
139
+ if (isOn(sideB)) {
140
+ return flip({ position, from: sideB, to: sideA, size, room: roomB, otherRoom: roomA });
141
+ }
142
+
143
+ return { position, cap: undefined };
144
+ };
145
+
113
146
  /**
114
147
  * Calculate the popup’s inset and size from the anchor’s rect, the viewport size and the content’s
115
148
  * natural size. The position may be altered if the space is limited.
@@ -145,84 +178,48 @@ export const calculatePopupStyle = ({
145
178
  let height;
146
179
 
147
180
  /**
148
- * Apply {@link flip} vertically, keeping any height limit already set if the content fits.
149
- * @param {string} from Current side.
150
- * @param {string} to Opposite side.
151
- * @param {number} room Room on the current side.
152
- * @param {number} otherRoom Room on the opposite side.
181
+ * Apply {@link flipEither} vertically, keeping any height limit already set if the content fits.
182
+ * @param {[string, string]} sides Parts of the position denoting the two sides.
183
+ * @param {[number, number]} rooms Room on each side.
153
184
  */
154
- const flipVertically = (from, to, room, otherRoom) => {
155
- const result = flip({ position, from, to, size: contentHeight, room, otherRoom });
185
+ const flipVertically = (sides, rooms) => {
186
+ const result = flipEither({ position, sides, size: contentHeight, rooms });
156
187
 
157
188
  position = result.position;
158
189
  height = result.cap ?? height;
159
190
  };
160
191
 
161
192
  // Alter the position if the space is limited
162
- if (position.startsWith('bottom-')) {
163
- flipVertically('bottom-', 'top-', bottomMargin, topMargin);
164
- } else if (position.startsWith('top-')) {
165
- flipVertically('top-', 'bottom-', topMargin, bottomMargin);
166
- }
193
+ flipVertically(['bottom-', 'top-'], [bottomMargin, topMargin]);
167
194
 
168
195
  // Only a popup that opens beside its anchor carries a `-top`/`-bottom` suffix, and it grows
169
196
  // away from the edge it’s aligned with: down from the anchor’s top, or up from its bottom. It
170
197
  // gets the same treatment as the dropdown above — align with the other edge when the content
171
198
  // doesn’t fit and that edge has more room, and cap it either way, so a long submenu scrolls
172
199
  // instead of running past the viewport
173
- if (position.endsWith('-top')) {
174
- flipVertically('-top', '-bottom', downwardMargin, upwardMargin);
175
- } else if (position.endsWith('-bottom')) {
176
- flipVertically('-bottom', '-top', upwardMargin, downwardMargin);
177
- }
200
+ flipVertically(['-top', '-bottom'], [downwardMargin, upwardMargin]);
178
201
 
179
202
  // If the popup overflows the viewport, align it with the anchor’s other edge, but only when that
180
203
  // side has more room. Checking each side on its own would flip a popup that fits neither way
181
204
  // over and straight back, leaving it on whichever side was checked last
182
- if (position.endsWith('-left')) {
183
- ({ position } = flip({
184
- position,
185
- from: '-left',
186
- to: '-right',
187
- size: contentWidth,
188
- room: viewport.width - rect.left - 8,
189
- otherRoom: rect.right - 8,
190
- }));
191
- } else if (position.endsWith('-right')) {
192
- ({ position } = flip({
193
- position,
194
- from: '-right',
195
- to: '-left',
196
- size: contentWidth,
197
- room: rect.right - 8,
198
- otherRoom: viewport.width - rect.left - 8,
199
- }));
200
- }
205
+ ({ position } = flipEither({
206
+ position,
207
+ sides: ['-left', '-right'],
208
+ size: contentWidth,
209
+ rooms: [viewport.width - rect.left - 8, rect.right - 8],
210
+ }));
201
211
 
202
212
  // The two checks above align a dropdown that opens below or above its anchor, so neither
203
213
  // covers a popup that opens beside one — a submenu — running off the edge it opens towards.
204
214
  // That gets the same treatment as the vertical flip above: switch to the other side, but only
205
215
  // when it has more room, so a submenu with nowhere to go stays where the caller put it. The
206
216
  // width isn’t capped here; that’s done with `maxWidth` below.
207
- if (position.startsWith('right-')) {
208
- ({ position } = flip({
209
- position,
210
- from: 'right-',
211
- to: 'left-',
212
- size: contentWidth,
213
- room: rightMargin,
214
- otherRoom: leftMargin,
215
- }));
216
- } else if (position.startsWith('left-')) {
217
- ({ position } = flip({
218
- position,
219
- from: 'left-',
220
- to: 'right-',
221
- size: contentWidth,
222
- room: leftMargin,
223
- otherRoom: rightMargin,
224
- }));
225
- }
217
+ ({ position } = flipEither({
218
+ position,
219
+ sides: ['right-', 'left-'],
220
+ size: contentWidth,
221
+ rooms: [rightMargin, leftMargin],
222
+ }));
226
223
 
227
224
  const top = position.startsWith('bottom-')
228
225
  ? `${Math.round(rect.bottom)}px`
@@ -24,6 +24,57 @@
24
24
  }
25
25
  }
26
26
 
27
+ // The box of a `<TextInput>`, `<TextArea>` or `<DateTimeInput>`. `$line-mode` is `singleline` or
28
+ // `multiline`, picking the padding and line height. `$text-formatting` adds the alignment, indent,
29
+ // case and word spacing options, which don’t apply to a date/time input. The read-only and disabled
30
+ // styles are left to `textbox-disabled`, because a `<TextArea>` clone also matches `:read-only`.
31
+ // Include this after the other declarations, since it ends with nested rules.
32
+ @mixin textbox($line-mode: singleline, $text-formatting: true) {
33
+ border-width: var(--sui-textbox-border-width, 1px);
34
+ border-color: var(--sui-textbox-border-color);
35
+ border-radius: var(--sui-textbox-border-radius);
36
+ padding: var(--sui-textbox-#{$line-mode}-padding);
37
+ color: var(--sui-textbox-foreground-color);
38
+ background-color: var(--sui-textbox-background-color);
39
+ font-family: var(--sui-textbox-font-family);
40
+ font-size: var(--sui-textbox-font-size);
41
+ line-height: var(--sui-textbox-#{$line-mode}-line-height);
42
+ font-weight: var(--sui-textbox-font-weight, var(--sui-font-weight-normal, normal));
43
+ letter-spacing: var(--sui-textbox-letter-spacing, normal);
44
+ transition: all 200ms;
45
+
46
+ @if $text-formatting {
47
+ text-align: var(--sui-textbox-text-align, start);
48
+ text-indent: var(--sui-textbox-text-indent, 0);
49
+ text-transform: var(--sui-textbox-text-transform, none);
50
+ word-spacing: var(--sui-word-spacing-normal, normal);
51
+ }
52
+
53
+ &:focus {
54
+ color: var(--sui-textbox-foreground-color-focus, var(--sui-textbox-foreground-color));
55
+ background-color: var(
56
+ --sui-textbox-background-color-focus,
57
+ var(--sui-textbox-background-color)
58
+ );
59
+ }
60
+
61
+ &[aria-invalid="true"] {
62
+ border-color: var(--sui-error-border-color);
63
+ }
64
+ }
65
+
66
+ // The read-only and disabled states of a single-line text box, e.g. `<TextInput>`.
67
+ @mixin textbox-disabled {
68
+ &:read-only {
69
+ color: var(--sui-secondary-foreground-color);
70
+ border-color: var(--sui-textbox-border-color) !important;
71
+ }
72
+
73
+ &:is(:disabled, :read-only) {
74
+ background-color: var(--sui-disabled-background-color);
75
+ }
76
+ }
77
+
27
78
  // A square button attached to the end of a text field, sharing its border. `$size-property` is the
28
79
  // dimension tied to the field height (`width` or `height`), the other one following the aspect
29
80
  // ratio.
@@ -47,6 +98,24 @@
47
98
  }
48
99
  }
49
100
 
101
+ // The translucent, blurred and shadowed surface of a floating panel, like a `<Popup>`.
102
+ @mixin popup-surface {
103
+ color: var(--sui-primary-foreground-color);
104
+ background-color: var(--sui-secondary-background-color-translucent);
105
+ box-shadow: 0 8px 16px var(--sui-popup-shadow-color);
106
+ -webkit-backdrop-filter: blur(16px);
107
+ backdrop-filter: blur(16px);
108
+ }
109
+
110
+ // The border of a floating panel, customizable with the CSS variables of `$widget`, e.g. `listbox`
111
+ // or `menu`.
112
+ @mixin popup-border($widget: listbox) {
113
+ border-width: var(--sui-#{$widget}-border-width, 1px);
114
+ border-style: var(--sui-#{$widget}-border-style, solid);
115
+ border-color: var(--sui-#{$widget}-border-color, var(--sui-secondary-border-color));
116
+ border-radius: var(--sui-#{$widget}-border-radius, 4px);
117
+ }
118
+
50
119
  // The label wrapper of a checkbox or radio button.
51
120
  @mixin toggle-control-wrapper {
52
121
  display: inline-flex;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltia/ui",
3
- "version": "0.89.2",
3
+ "version": "0.89.3",
4
4
  "description": "A collection of Svelte components and utilities for building user interfaces.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -86,7 +86,8 @@
86
86
  "eslint-plugin-svelte": "^3.24.1",
87
87
  "globals": "^17.14.0",
88
88
  "happy-dom": "^21.0.4",
89
- "oxlint": "^1.92.0",
89
+ "jscpd": "^5.4.3",
90
+ "oxlint": "^1.93.0",
90
91
  "playwright": "^1.65.0",
91
92
  "postcss": "^8.5.32",
92
93
  "postcss-html": "^2.0.0",
@@ -119,6 +120,7 @@
119
120
  "check": "pnpm run --no-bail '/^check:.*/'",
120
121
  "check:audit": "pnpm audit --ignore-registry-errors",
121
122
  "check:cspell": "cspell --no-progress",
123
+ "check:duplicates": "jscpd --silent",
122
124
  "check:eslint": "eslint .",
123
125
  "check:oxlint": "oxlint .",
124
126
  "check:prettier": "prettier --check .",
@@ -131,7 +133,7 @@
131
133
  "generate:shiki": "node scripts/generate-shiki-metadata.js",
132
134
  "preview": "vite preview",
133
135
  "test": "vitest run",
134
- "test:coverage": "vitest run --coverage",
136
+ "test:coverage": "vitest run --coverage --browser.name=chromium",
135
137
  "test:watch": "vitest"
136
138
  }
137
139
  }
@@ -1,296 +0,0 @@
1
- // Adopted from https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/plugins/MarkdownTransformers/index.ts
2
-
3
- /* eslint-disable jsdoc/require-jsdoc */
4
- /* eslint-disable jsdoc/require-returns-description */
5
- /* eslint-disable jsdoc/require-param-description */
6
-
7
- import {
8
- $convertFromMarkdownString as convertFromMarkdownString,
9
- $convertToMarkdownString as convertToMarkdownString,
10
- LINK as LEXICAL_LINK,
11
- TRANSFORMERS,
12
- } from '@lexical/markdown';
13
- import {
14
- $createTableCellNode as createTableCellNode,
15
- $createTableNode as createTableNode,
16
- $createTableRowNode as createTableRowNode,
17
- $isTableCellNode as isTableCellNode,
18
- $isTableNode as isTableNode,
19
- $isTableRowNode as isTableRowNode,
20
- TableCellHeaderStates,
21
- TableCellNode,
22
- TableNode,
23
- TableRowNode,
24
- } from '@lexical/table';
25
- import { $isParagraphNode as isParagraphNode, $isTextNode as isTextNode } from 'lexical';
26
-
27
- import { BLOCK_SYNTAX_ESCAPE } from './block-escape.js';
28
- import { LEADING_INLINE_CODE } from './inline-code.js';
29
- import { LINK } from './link.js';
30
- import { RAW_HTML, RAW_SYNTAX } from './raw-syntax.js';
31
-
32
- /**
33
- * @import { ElementTransformer, TextMatchTransformer, Transformer } from '@lexical/markdown';
34
- * @import { ElementFormatType } from 'lexical';
35
- */
36
-
37
- const TABLE_ROW_REG_EXP = /^(?:\|)(.+)(?:\|)\s?$/;
38
- /**
39
- * Regular expression to match a delimiter row, like `| --- | :-: |`. Each cell needs a hyphen, so a
40
- * row of empty cells, like `| | |`, is an empty header row, not a delimiter row.
41
- * @see https://github.github.com/gfm/#delimiter-row
42
- */
43
- const TABLE_ROW_DIVIDER_REG_EXP = /^(?:\|[ \t]*:?-+:?[ \t]*)+\|\s?$/;
44
- /**
45
- * Delimiter row cell for each column alignment, which is kept as the format of the column’s cells.
46
- * @type {Record<string, string>}
47
- */
48
- const ALIGNMENT_DELIMITERS = { left: ':---', center: ':---:', right: '---:' };
49
-
50
- /**
51
- * Get the alignment of a column from its delimiter row cell, like `:-:`.
52
- * @param {string} delimiter Delimiter row cell.
53
- * @returns {ElementFormatType} Alignment, or an empty string for the default.
54
- */
55
- const getColumnAlignment = (delimiter) => {
56
- const text = delimiter.trim();
57
- const left = text.startsWith(':');
58
- const right = text.endsWith(':');
59
-
60
- return left && right ? 'center' : left ? 'left' : right ? 'right' : '';
61
- };
62
-
63
- /**
64
- * Returns the number of columns in the table.
65
- * @internal
66
- * @param {TableNode} table
67
- * @returns {number}
68
- */
69
- export const getTableColumnsSize = (table) => {
70
- const row = table.getFirstChild();
71
-
72
- return isTableRowNode(row) ? row.getChildrenSize() : 0;
73
- };
74
-
75
- /**
76
- * Creates a table cell with the given text content.
77
- * @param {string} textContent
78
- * @param {Transformer[]} transformers Transformers to import the cell content with.
79
- * @returns {TableCellNode}
80
- */
81
- const createTableCell = (textContent, transformers) => {
82
- // An escaped pipe is part of the cell, even within inline code, like GitHub Flavored Markdown.
83
- // The spaces around the content only separate it from the pipes
84
- textContent = textContent.trim().replace(/\\n/g, '\n').replace(/\\\|/g, '|');
85
-
86
- const cell = createTableCellNode(TableCellHeaderStates.NO_STATUS);
87
-
88
- convertFromMarkdownString(textContent, transformers, cell);
89
-
90
- return cell;
91
- };
92
-
93
- /**
94
- * Maps the given text content to an array of table cells.
95
- * @internal
96
- * @param {string} textContent
97
- * @param {Transformer[]} transformers Transformers to import the cell content with.
98
- * @returns {TableCellNode[] | null}
99
- */
100
- export const mapToTableCells = (textContent, transformers) => {
101
- const [, match] = textContent.match(TABLE_ROW_REG_EXP) ?? [];
102
-
103
- if (!match) {
104
- return null;
105
- }
106
-
107
- // Split the row at the pipes that are not escaped, which are preceded by an even number of
108
- // backslashes
109
- return match.split(/(?<=(?<!\\)(?:\\\\)*)\|/).map((text) => createTableCell(text, transformers));
110
- };
111
-
112
- /**
113
- * Create a table transformer. A cell can only have inline content, so it’s converted with the
114
- * standard Markdown transformers and the given text match transformers, like those of the inline
115
- * editor components, which come first to take priority, as they do for the rest of the document.
116
- * @param {TextMatchTransformer[]} [cellTransformers] Additional transformers for the cell content.
117
- * @returns {ElementTransformer}
118
- */
119
- export const createTableTransformer = (cellTransformers = []) => {
120
- /** @type {Transformer[]} */
121
- const transformers = [
122
- ...cellTransformers,
123
- ...TRANSFORMERS.map((transformer) => (transformer === LEXICAL_LINK ? LINK : transformer)),
124
- LEADING_INLINE_CODE,
125
- RAW_HTML,
126
- RAW_SYNTAX,
127
- ];
128
-
129
- /** @type {Transformer[]} */
130
- const exportTransformers = [...transformers, BLOCK_SYNTAX_ESCAPE];
131
-
132
- return {
133
- dependencies: [TableNode, TableRowNode, TableCellNode],
134
- export: (node) => {
135
- if (!isTableNode(node)) {
136
- return null;
137
- }
138
-
139
- /** @type {string[]} */
140
- const output = [];
141
-
142
- node.getChildren().forEach((row) => {
143
- /** @type {string[]} */
144
- const rowOutput = [];
145
- /** @type {TableCellNode[]} */
146
- const cells = [];
147
-
148
- if (!isTableRowNode(row)) {
149
- return;
150
- }
151
-
152
- let isHeaderRow = false;
153
-
154
- row.getChildren().forEach((cell) => {
155
- // It’s TableCellNode so it’s just to make flow happy
156
- if (isTableCellNode(cell)) {
157
- rowOutput.push(
158
- convertToMarkdownString(exportTransformers, cell)
159
- // Escape a pipe, which would otherwise end the cell, even within inline code
160
- .replace(/\|/g, '\\|')
161
- .replace(/\n/g, '\\n')
162
- .trim(),
163
- );
164
- cells.push(cell);
165
-
166
- if (cell.__headerState === TableCellHeaderStates.ROW) {
167
- isHeaderRow = true;
168
- }
169
- }
170
- });
171
-
172
- output.push(`| ${rowOutput.join(' | ')} |`);
173
-
174
- if (isHeaderRow) {
175
- output.push(
176
- `| ${cells.map((cell) => ALIGNMENT_DELIMITERS[cell.getFormatType()] ?? '---').join(' | ')} |`,
177
- );
178
- }
179
- });
180
-
181
- return output.join('\n');
182
- },
183
- regExp: TABLE_ROW_REG_EXP,
184
- replace: (parentNode, _children, [textContent]) => {
185
- // Header row
186
- if (TABLE_ROW_DIVIDER_REG_EXP.test(textContent)) {
187
- const table = parentNode.getPreviousSibling();
188
-
189
- if (!table || !isTableNode(table)) {
190
- return;
191
- }
192
-
193
- const rows = table.getChildren();
194
- const lastRow = rows[rows.length - 1];
195
-
196
- if (!lastRow || !isTableRowNode(lastRow)) {
197
- return;
198
- }
199
-
200
- const alignments = textContent.trim().slice(1, -1).split('|').map(getColumnAlignment);
201
-
202
- // Add header state to row cells, and the column alignment, which the rows that follow take
203
- // from the header row
204
- lastRow.getChildren().forEach((cell, index) => {
205
- if (!isTableCellNode(cell)) {
206
- return;
207
- }
208
-
209
- cell.setHeaderStyles(TableCellHeaderStates.ROW, TableCellHeaderStates.ROW);
210
- cell.setFormat(alignments[index] ?? '');
211
- });
212
-
213
- // Remove line
214
- parentNode.remove();
215
-
216
- return;
217
- }
218
-
219
- const matchCells = mapToTableCells(textContent, transformers);
220
-
221
- if (!matchCells) {
222
- return;
223
- }
224
-
225
- const rows = [matchCells];
226
- let sibling = parentNode.getPreviousSibling();
227
- let maxCells = matchCells.length;
228
-
229
- while (sibling) {
230
- if (!isParagraphNode(sibling)) {
231
- break;
232
- }
233
-
234
- if (sibling.getChildrenSize() !== 1) {
235
- break;
236
- }
237
-
238
- const firstChild = sibling.getFirstChild();
239
-
240
- if (!isTextNode(firstChild)) {
241
- break;
242
- }
243
-
244
- const cells = mapToTableCells(firstChild.getTextContent(), transformers);
245
-
246
- if (!cells) {
247
- break;
248
- }
249
-
250
- maxCells = Math.max(maxCells, cells.length);
251
- rows.unshift(cells);
252
-
253
- const previousSibling = sibling.getPreviousSibling();
254
-
255
- sibling.remove();
256
- sibling = previousSibling;
257
- }
258
-
259
- const table = createTableNode();
260
-
261
- rows.forEach((cells) => {
262
- const tableRow = createTableRowNode();
263
-
264
- table.append(tableRow);
265
-
266
- for (let i = 0; i < maxCells; i += 1) {
267
- tableRow.append(i < cells.length ? cells[i] : createTableCell('', transformers));
268
- }
269
- });
270
-
271
- const previousSibling = parentNode.getPreviousSibling();
272
-
273
- if (isTableNode(previousSibling) && getTableColumnsSize(previousSibling) === maxCells) {
274
- const headerCells = /** @type {TableRowNode} */ (
275
- previousSibling.getFirstChild()
276
- ).getChildren();
277
-
278
- table.getChildren().forEach((row) => {
279
- /** @type {TableRowNode} */ (row).getChildren().forEach((cell, index) => {
280
- /** @type {TableCellNode} */ (cell).setFormat(
281
- /** @type {TableCellNode} */ (headerCells[index]).getFormatType(),
282
- );
283
- });
284
- });
285
-
286
- previousSibling.append(...table.getChildren());
287
- parentNode.remove();
288
- } else {
289
- parentNode.replace(table);
290
- }
291
-
292
- table.selectEnd();
293
- },
294
- type: 'element',
295
- };
296
- };