@sveltia/ui 0.87.4 → 0.88.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.
@@ -160,12 +160,7 @@
160
160
 
161
161
  <style>.code-editor {
162
162
  margin: var(--sui-focus-ring-width);
163
- border-radius: var(--sui-textbox-border-radius);
164
163
  width: calc(100% - var(--sui-focus-ring-width) * 2);
165
- transition: all 200ms;
166
- }
167
- .code-editor:focus-within {
168
- outline: var(--sui-focus-ring-width) solid var(--sui-focus-ring-color);
169
164
  }
170
165
  .code-editor.flex:not([hidden]) {
171
166
  display: block;
@@ -5,8 +5,12 @@ export function getSelectionTypes(): TextEditorSelectionState;
5
5
  export function exportMarkdown(enabledTransformers: Transformer[]): string;
6
6
  export function onEditorUpdate(editor: LexicalEditor, enabledTransformers: Transformer[], cachedValue?: string, format?: TextEditorValueFormat): string;
7
7
  export function getComponentMarkdown({ node, createNode, transformer, createMarkdown }: TextEditorComponent): string;
8
+ export function isInlineComponent({ transformer }: TextEditorComponent): boolean;
9
+ export function limitToSingleLine(config: TextEditorConfig): TextEditorConfig;
10
+ export function $joinIntoSingleParagraph(root: RootNode): void;
11
+ export function $replaceLineBreak(node: LineBreakNode): void;
8
12
  export function removePlaceholdersFromMatch(transformer: Transformer): Transformer;
9
- export function initEditor({ enabledButtons, components, useMarkdownShortcuts, isCodeEditor, defaultLanguage, format, }: TextEditorConfig): InitEditorResult;
13
+ export function initEditor(config: TextEditorConfig): InitEditorResult;
10
14
  export function loadCodeHighlighter(lang: string): Promise<void>;
11
15
  export function convertMarkdownToLexical(editor: LexicalEditor, value: string, enabledTransformers: Transformer[]): Promise<string | undefined>;
12
16
  export function convertHtmlToLexical(editor: LexicalEditor, value: string): Promise<string | undefined>;
@@ -37,4 +41,6 @@ import type { Transformer } from '@lexical/markdown';
37
41
  import type { TextEditorValueFormat } from '../../typedefs.js';
38
42
  import type { TextEditorComponent } from '../../typedefs.js';
39
43
  import type { TextEditorConfig } from '../../typedefs.js';
44
+ import { RootNode } from 'lexical';
45
+ import { LineBreakNode } from 'lexical';
40
46
  import type { LinkAttributes } from '@lexical/link';
@@ -49,6 +49,7 @@ import {
49
49
  import { sleep } from '@sveltia/utils/misc';
50
50
  import { isURL } from '@sveltia/utils/string';
51
51
  import {
52
+ COMMAND_PRIORITY_HIGH,
52
53
  COMMAND_PRIORITY_LOW,
53
54
  COMMAND_PRIORITY_NORMAL,
54
55
  configExtension,
@@ -63,11 +64,14 @@ import {
63
64
  $getSelection as getSelection,
64
65
  HISTORY_MERGE_TAG,
65
66
  INDENT_CONTENT_COMMAND,
67
+ INSERT_LINE_BREAK_COMMAND,
66
68
  INSERT_PARAGRAPH_COMMAND,
67
69
  KEY_ENTER_COMMAND,
70
+ LineBreakNode,
68
71
  $insertNodes as insertNodes,
69
72
  $isDecoratorNode as isDecoratorNode,
70
73
  $isElementNode as isElementNode,
74
+ $isParagraphNode as isParagraphNode,
71
75
  $isRangeSelection as isRangeSelection,
72
76
  $isTextNode as isTextNode,
73
77
  OUTDENT_CONTENT_COMMAND,
@@ -79,6 +83,7 @@ import {
79
83
  DISABLED_MARKDOWN_TAGS,
80
84
  EDITOR_THEME,
81
85
  IMPORT_UPDATE_TAG,
86
+ INLINE_BUTTON_TYPES,
82
87
  NODE_MAP,
83
88
  TEXT_FORMAT_BUTTON_TYPES,
84
89
  TRANSFORMER_MAP,
@@ -689,6 +694,157 @@ const registerCodeEditorCommands = (editor, defaultLanguage) =>
689
694
  }),
690
695
  );
691
696
 
697
+ /**
698
+ * Check if the given editor component is inline, which means its Markdown is matched within a line
699
+ * of text by a text match transformer. Only an inline component can be inserted into a Markdown
700
+ * table cell or a single-line editor.
701
+ * @param {TextEditorComponent} component Editor component.
702
+ * @returns {boolean} Result.
703
+ */
704
+ export const isInlineComponent = ({ transformer }) => transformer.type === 'text-match';
705
+
706
+ /**
707
+ * Limit the given editor configuration to what a single-line editor can hold, if it’s one: only
708
+ * the inline buttons and components, and no plain text mode for HTML, whose source can’t be kept to
709
+ * a single paragraph by keeping it on a single line. Any other configuration is returned as is.
710
+ * @param {TextEditorConfig} config Editor configuration.
711
+ * @returns {TextEditorConfig} Limited configuration.
712
+ */
713
+ export const limitToSingleLine = (config) => {
714
+ if (config.multiline !== false || config.isCodeEditor) {
715
+ return config;
716
+ }
717
+
718
+ return {
719
+ ...config,
720
+ modes: config.format === 'html' ? ['rich-text'] : config.modes,
721
+ enabledButtons: (config.enabledButtons ?? []).filter((button) =>
722
+ /** @type {TextEditorNodeType[]} */ (INLINE_BUTTON_TYPES).includes(button),
723
+ ),
724
+ components: (config.components ?? []).filter(isInlineComponent),
725
+ };
726
+ };
727
+
728
+ /**
729
+ * Get the inline content of the given top-level node, looking into any block within it.
730
+ * @param {LexicalNode} node Node.
731
+ * @returns {LexicalNode[]} Inline nodes, or an empty array for a block that has no inline content,
732
+ * like a horizontal rule.
733
+ */
734
+ const getInlineContent = (node) => {
735
+ if (isElementNode(node) && !node.isInline()) {
736
+ return node.getChildren().flatMap(getInlineContent);
737
+ }
738
+
739
+ return node.isInline() ? [node] : [];
740
+ };
741
+
742
+ /**
743
+ * Join the top-level nodes of the given root into a single paragraph, with a space between the
744
+ * content of each, for a single-line editor.
745
+ * @param {RootNode} root Root node.
746
+ */
747
+ export const $joinIntoSingleParagraph = (root) => {
748
+ const children = root.getChildren();
749
+ const [firstChild] = children;
750
+
751
+ if (!firstChild || (children.length === 1 && isParagraphNode(firstChild))) {
752
+ return;
753
+ }
754
+
755
+ const paragraph = isParagraphNode(firstChild) ? firstChild : createParagraphNode();
756
+
757
+ if (paragraph !== firstChild) {
758
+ firstChild.insertBefore(paragraph);
759
+ }
760
+
761
+ // Keep track of the last character rather than reading the growing text of the paragraph again
762
+ // for each block, which would take quadratic time on a long pasted document
763
+ let lastChar = paragraph.getTextContent().at(-1) ?? '';
764
+
765
+ children
766
+ .filter((child) => child !== paragraph)
767
+ .forEach((child) => {
768
+ const content = getInlineContent(child);
769
+ const text = content.map((node) => node.getTextContent()).join('');
770
+
771
+ // Add a space between the content of each block, unless there’s one already
772
+ if (content.length && paragraph.getChildrenSize() && !/\s/.test(lastChar + text.charAt(0))) {
773
+ paragraph.append(createTextNode(' '));
774
+ }
775
+
776
+ paragraph.append(...content);
777
+ lastChar = text.at(-1) ?? lastChar;
778
+ // Lexical moves the selection out of a removed node on its own
779
+ child.remove();
780
+ });
781
+ };
782
+
783
+ /**
784
+ * Replace the given line break with a space for a single-line editor, with the formats the text on
785
+ * both sides shares, so a line break within bold text doesn’t split it. With a space on either side
786
+ * already, or nothing at all, the line break is just removed.
787
+ * @param {LineBreakNode} node Line break.
788
+ */
789
+ export const $replaceLineBreak = (node) => {
790
+ const previous = node.getPreviousSibling();
791
+ const next = node.getNextSibling();
792
+
793
+ // A line break at either end of the paragraph separates nothing, so it leaves no space
794
+ if (
795
+ !previous ||
796
+ !next ||
797
+ /\s$/.test(previous.getTextContent()) ||
798
+ /^\s/.test(next.getTextContent())
799
+ ) {
800
+ node.remove();
801
+
802
+ return;
803
+ }
804
+
805
+ const space = createTextNode(' ');
806
+
807
+ if (isTextNode(previous) && isTextNode(next)) {
808
+ // Keep the formats both sides share, e.g. italic between italic and bold italic text
809
+ TEXT_FORMAT_BUTTON_TYPES.forEach((format) => {
810
+ if (previous.hasFormat(format) && next.hasFormat(format)) {
811
+ space.toggleFormat(format);
812
+ }
813
+ });
814
+
815
+ if (previous.getStyle() === next.getStyle()) {
816
+ space.setStyle(previous.getStyle());
817
+ }
818
+ }
819
+
820
+ node.replace(space);
821
+ };
822
+
823
+ /**
824
+ * Register the commands and transforms that keep a single-line editor on one line. Neither a new
825
+ * paragraph nor a line break can be inserted, and any content that brings them in anyway, like
826
+ * pasted text or an imported value, is joined into a single paragraph with spaces.
827
+ * @param {LexicalEditor} editor Editor instance.
828
+ * @returns {() => void} Cleanup handler.
829
+ */
830
+ const registerSingleLine = (editor) =>
831
+ mergeUnregisters(
832
+ // The emoji autocomplete, which selects an emoji with the Enter key, takes priority
833
+ editor.registerCommand(
834
+ KEY_ENTER_COMMAND,
835
+ (event) => {
836
+ event?.preventDefault();
837
+
838
+ return true;
839
+ },
840
+ COMMAND_PRIORITY_HIGH,
841
+ ),
842
+ editor.registerCommand(INSERT_PARAGRAPH_COMMAND, () => true, COMMAND_PRIORITY_HIGH),
843
+ editor.registerCommand(INSERT_LINE_BREAK_COMMAND, () => true, COMMAND_PRIORITY_HIGH),
844
+ editor.registerNodeTransform(LineBreakNode, $replaceLineBreak),
845
+ editor.registerNodeTransform(RootNode, $joinIntoSingleParagraph),
846
+ );
847
+
692
848
  /**
693
849
  * Register the link command, the paste handler that turns a pasted URL into a link, and the
694
850
  * transform that removes a link with an unsafe URL.
@@ -1069,17 +1225,22 @@ export const removePlaceholdersFromMatch = (transformer) => {
1069
1225
  * @param {TextEditorConfig} config Editor configuration.
1070
1226
  * @returns {InitEditorResult} Editor instance and cleanup.
1071
1227
  */
1072
- export const initEditor = ({
1073
- enabledButtons = [],
1074
- components = [],
1075
- useMarkdownShortcuts,
1076
- isCodeEditor = false,
1077
- defaultLanguage = 'plain',
1078
- format = 'markdown',
1079
- }) => {
1228
+ export const initEditor = (config) => {
1229
+ const {
1230
+ enabledButtons = [],
1231
+ components = [],
1232
+ useMarkdownShortcuts,
1233
+ isCodeEditor = false,
1234
+ defaultLanguage = 'plain',
1235
+ format = 'markdown',
1236
+ multiline = true,
1237
+ } = limitToSingleLine(config);
1238
+
1080
1239
  const hasCodeBlock = enabledButtons.includes('code-block') || isCodeEditor;
1081
1240
  const hasTable = enabledButtons.includes('table') && !isCodeEditor;
1082
1241
  const hasHorizontalRule = enabledButtons.includes('horizontal-rule') && !isCodeEditor;
1242
+ /** Whether to support horizontal rules and tables in Markdown, even without their buttons. */
1243
+ const hasBlockSyntax = !isCodeEditor && multiline;
1083
1244
 
1084
1245
  const editorExtension = defineExtension({
1085
1246
  name: '@sveltia/ui/editor',
@@ -1114,11 +1275,11 @@ export const initEditor = ({
1114
1275
  .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))
1115
1276
  .flatMap(([, nodes]) => nodes),
1116
1277
  ),
1117
- ...(isCodeEditor
1118
- ? [CodeNode, CodeHighlightNode]
1119
- : // We haven’t implemented buttons for horizontal rules and tables yet, but we still want
1120
- // to support them in Markdown, so always include them in the node list
1121
- [HorizontalRuleNode, TableNode, TableCellNode, TableRowNode]),
1278
+ ...(isCodeEditor ? [CodeNode, CodeHighlightNode] : []),
1279
+ // We haven’t implemented buttons for horizontal rules and tables yet, but we still want to
1280
+ // support them in Markdown, so always include them in the node list, unless the editor is
1281
+ // limited to a single line
1282
+ ...(hasBlockSyntax ? [HorizontalRuleNode, TableNode, TableCellNode, TableRowNode] : []),
1122
1283
  ],
1123
1284
  theme: EDITOR_THEME,
1124
1285
  // Export clean HTML without the attributes and elements only meant for the editor, and import
@@ -1155,10 +1316,10 @@ export const initEditor = ({
1155
1316
  .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))
1156
1317
  .flatMap(([, transformers]) => transformers),
1157
1318
  ),
1158
- ...(isCodeEditor
1159
- ? [CODE]
1160
- : // See the comment above for why we always include horizontal rules and tables
1161
- [
1319
+ ...(isCodeEditor ? [CODE] : []),
1320
+ // See the comment above for why we always include horizontal rules and tables
1321
+ ...(hasBlockSyntax
1322
+ ? [
1162
1323
  HR,
1163
1324
  // A table cell can only have inline content, so only the components with a text match
1164
1325
  // transformer can be used there
@@ -1167,9 +1328,10 @@ export const initEditor = ({
1167
1328
  componentTransformers.filter(({ type }) => type === 'text-match')
1168
1329
  ),
1169
1330
  ),
1170
- // Last, so the syntax of the editor’s own comes first
1171
- RAW_SYNTAX,
1172
- ]),
1331
+ ]
1332
+ : []),
1333
+ // Last, so the syntax of the editor’s own comes first
1334
+ ...(isCodeEditor ? [] : [RAW_SYNTAX]),
1173
1335
  ];
1174
1336
 
1175
1337
  const editor = buildEditorFromExtensions(editorExtension);
@@ -1191,6 +1353,7 @@ export const initEditor = ({
1191
1353
  HISTORY_MAX_DEPTH,
1192
1354
  ),
1193
1355
  isCodeEditor ? registerCodeEditorCommands(editor, defaultLanguage) : undefined,
1356
+ multiline || isCodeEditor ? undefined : registerSingleLine(editor),
1194
1357
  useMarkdownShortcuts ? registerMarkdownShortcuts(editor, enabledTransformers) : undefined,
1195
1358
  hasCodeBlock
1196
1359
  ? registerCodeHighlighting(editor, {
@@ -240,7 +240,7 @@
240
240
  bind:this={lexicalRoot}
241
241
  {...restProps}
242
242
  role="textbox"
243
- aria-multiline="true"
243
+ aria-multiline={editorStore.config.multiline !== false}
244
244
  aria-hidden={hidden}
245
245
  aria-disabled={disabled}
246
246
  aria-readonly={readonly}
@@ -264,6 +264,9 @@
264
264
  font-family: var(--sui-textbox-font-family);
265
265
  font-size: var(--sui-textbox-font-size);
266
266
  line-height: var(--sui-textbox-multiline-line-height);
267
+ transition-duration: 200ms;
268
+ transition-property: outline-color, border-color, color, background-color;
269
+ outline-offset: calc(var(--sui-focus-ring-width) * -1);
267
270
  }
268
271
  .lexical-root:not(:first-child) {
269
272
  border-start-start-radius: 0 !important;
@@ -276,8 +279,9 @@
276
279
  border-radius: 0 !important;
277
280
  min-height: 120px;
278
281
  }
279
- .lexical-root:focus-visible {
280
- outline: 0;
282
+ .lexical-root:focus {
283
+ color: var(--sui-textbox-foreground-color-focus, var(--sui-textbox-foreground-color));
284
+ background-color: var(--sui-textbox-background-color-focus, var(--sui-textbox-background-color));
281
285
  }
282
286
  .lexical-root[aria-invalid=true] {
283
287
  border-color: var(--sui-error-border-color);
@@ -15,6 +15,14 @@ export function applyRawTextEdit(textArea: HTMLTextAreaElement, { start, end, te
15
15
  export function editRawText(textArea: HTMLTextAreaElement | undefined, getEdit: (state: RawTextState) => RawTextEdit): Promise<void>;
16
16
  export function registerRawTextShortcut(textArea: HTMLTextAreaElement, key: string, handler: () => void): () => void;
17
17
  export function insertComponent(textArea: HTMLTextAreaElement, component: TextEditorComponent): Promise<void>;
18
+ export function joinLines({ value, caret }: {
19
+ value: string;
20
+ caret: number;
21
+ }): {
22
+ value: string;
23
+ caret: number;
24
+ };
25
+ export function registerRawTextSingleLine(textArea: HTMLTextAreaElement): () => void;
18
26
  /**
19
27
  * Current value and selection of the `<textarea>`.
20
28
  */
@@ -553,3 +553,88 @@ export const insertComponent = async (textArea, component) => {
553
553
 
554
554
  await applyRawTextEdit(textArea, insertMarkdown(getRawTextState(textArea), markdown, { block }));
555
555
  };
556
+
557
+ /**
558
+ * Line breaks, along with the spaces and tabs around them, to replace with a single space.
559
+ */
560
+ const LINE_BREAK_REGEX = /[ \t]*(?:\r?\n[ \t]*)+/g;
561
+
562
+ /**
563
+ * Join the lines of the given value with spaces, for a single-line editor, keeping the caret where
564
+ * it was in the text.
565
+ * @param {object} state Value and caret position.
566
+ * @param {string} state.value Value.
567
+ * @param {number} state.caret Caret position.
568
+ * @returns {{ value: string, caret: number }} Joined value and the new caret position.
569
+ */
570
+ export const joinLines = ({ value, caret }) => {
571
+ const before = value.slice(0, caret).replace(LINE_BREAK_REGEX, ' ');
572
+
573
+ return {
574
+ value: before + value.slice(caret).replace(LINE_BREAK_REGEX, ' '),
575
+ caret: before.length,
576
+ };
577
+ };
578
+
579
+ /**
580
+ * Keep the `<textarea>` on a single line: the Enter key doesn’t insert a line break, and the lines
581
+ * of pasted or dropped text are joined with spaces before the value is read.
582
+ * @param {HTMLTextAreaElement} textArea `<textarea>` element.
583
+ * @returns {() => void} Function to stop handling the events.
584
+ */
585
+ export const registerRawTextSingleLine = (textArea) => {
586
+ /**
587
+ * Handle the `beforeinput` event. The emoji autocomplete, which selects an emoji with the Enter
588
+ * key, cancels the `keydown` event first, so there’s no `beforeinput` event then. Pasted text is
589
+ * inserted with its lines joined instead, which keeps the edit in the native undo history.
590
+ * @param {InputEvent} event `beforeinput` event.
591
+ */
592
+ const onBeforeInput = (event) => {
593
+ const { inputType } = event;
594
+
595
+ if (inputType === 'insertLineBreak' || inputType === 'insertParagraph') {
596
+ event.preventDefault();
597
+
598
+ return;
599
+ }
600
+
601
+ const text = event.data || event.dataTransfer?.getData('text/plain') || '';
602
+
603
+ if (
604
+ (inputType === 'insertFromPaste' || inputType === 'insertReplacementText') &&
605
+ text.includes('\n') &&
606
+ // `execCommand()` is deprecated, but it’s still the only way to keep the edit in the native
607
+ // undo history. If it’s unavailable, the `input` listener below joins the lines instead
608
+ typeof document.execCommand === 'function'
609
+ ) {
610
+ event.preventDefault();
611
+ document.execCommand('insertText', false, text.replace(LINE_BREAK_REGEX, ' '));
612
+ }
613
+ };
614
+
615
+ /**
616
+ * Handle the `input` event, in the capture phase, so the value is joined before the bound value
617
+ * is updated. It catches the line breaks the `beforeinput` listener can’t, like those of dropped
618
+ * text, but the edit then leaves the native undo history.
619
+ */
620
+ const onInput = () => {
621
+ const { value, selectionStart } = textArea;
622
+
623
+ if (!value.includes('\n')) {
624
+ return;
625
+ }
626
+
627
+ const joined = joinLines({ value, caret: selectionStart });
628
+
629
+ textArea.value = joined.value;
630
+ textArea.setSelectionRange(joined.caret, joined.caret);
631
+ };
632
+
633
+ textArea.addEventListener('beforeinput', onBeforeInput);
634
+ textArea.addEventListener('input', onInput, { capture: true });
635
+
636
+ return () => {
637
+ textArea.removeEventListener('beforeinput', onBeforeInput);
638
+ textArea.removeEventListener('input', onInput, { capture: true });
639
+ };
640
+ };
@@ -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.87.4";
4
+ export const UI_VERSION: "0.88.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.87.4';
6
+ export const UI_VERSION = '0.88.0';
@@ -1,5 +1,5 @@
1
1
  import { generateElementId } from '@sveltia/utils/element';
2
- import { convertHtmlToLexical, convertMarkdownToLexical } from './core.js';
2
+ import { convertHtmlToLexical, convertMarkdownToLexical, limitToSingleLine } from './core.js';
3
3
 
4
4
  /**
5
5
  * @import { LexicalEditor } from 'lexical';
@@ -152,8 +152,8 @@ export const createEditorStore = () => {
152
152
  return config;
153
153
  },
154
154
  set config(newValue) {
155
- config = newValue;
156
- useRichText = newValue.modes[0] === 'rich-text' || newValue.isCodeEditor;
155
+ config = limitToSingleLine(newValue);
156
+ useRichText = config.modes[0] === 'rich-text' || config.isCodeEditor;
157
157
  },
158
158
  get inputValue() {
159
159
  return inputValue;
@@ -14,7 +14,7 @@
14
14
  import FloatingLinkEditor from './floating-link-editor.svelte';
15
15
  import LexicalRoot from './lexical-root.svelte';
16
16
  import TableCellMenuButton from './table-cell-menu-button.svelte';
17
- import { getBlockType, getRawTextState } from './raw-markdown.js';
17
+ import { getBlockType, getRawTextState, registerRawTextSingleLine } from './raw-markdown.js';
18
18
  import { highlightCodeToTokens } from './shiki/facade.js';
19
19
  import { getCodeTheme, onCodeThemeChange } from './shiki/theme.js';
20
20
  import { createEditorStore } from './store.svelte.js';
@@ -50,6 +50,14 @@
50
50
  * @property {TextEditorMode[]} [modes] Enabled modes.
51
51
  * @property {TextEditorNodeType[]} [buttons] Enabled buttons.
52
52
  * @property {TextEditorComponent[]} [components] Editor components.
53
+ * @property {boolean} [multiline] Whether the content can span multiple paragraphs and lines.
54
+ * With `false`, the content is kept in a single paragraph: the Enter key does nothing, and the
55
+ * paragraphs and lines of pasted or imported content are joined with spaces. Only the inline
56
+ * buttons and the editor components with a text match transformer are enabled then, horizontal
57
+ * rules and tables in Markdown are kept as text, and the HTML format has no plain text mode.
58
+ * @property {boolean} [minimal] Whether to make the editor compact: it starts with the height of
59
+ * a single line, like a single-line editor, and stops growing at 240 pixels, scrolling the
60
+ * content beyond that.
53
61
  * @property {boolean} [useMarkdownShortcuts] Whether to enable Markdown keyboard shortcuts in the
54
62
  * rich text editor.
55
63
  * @property {boolean} [useEmojiAutocomplete] Whether to autocomplete emojis when the user
@@ -85,6 +93,8 @@
85
93
  modes = ['rich-text', 'plain-text'],
86
94
  buttons = [...INLINE_BUTTON_TYPES, ...BLOCK_BUTTON_TYPES],
87
95
  components = [],
96
+ multiline = true,
97
+ minimal = false,
88
98
  useMarkdownShortcuts = true,
89
99
  useEmojiAutocomplete = true,
90
100
  hidden = false,
@@ -121,6 +131,7 @@
121
131
  modes,
122
132
  enabledButtons: buttons,
123
133
  components,
134
+ multiline,
124
135
  useMarkdownShortcuts,
125
136
  useEmojiAutocomplete,
126
137
  format,
@@ -263,6 +274,16 @@
263
274
  };
264
275
  });
265
276
 
277
+ $effect(() => {
278
+ const { textArea } = editorStore;
279
+
280
+ if (!textArea || multiline) {
281
+ return undefined;
282
+ }
283
+
284
+ return registerRawTextSingleLine(textArea);
285
+ });
286
+
266
287
  $effect(() => {
267
288
  pending = editorStore.pending;
268
289
  });
@@ -309,6 +330,8 @@
309
330
  role="none"
310
331
  class="sui text-editor"
311
332
  class:flex
333
+ class:single-line={!multiline}
334
+ class:minimal
312
335
  {hidden}
313
336
  style:--sui-text-editor-toolbar-height="{editorStore.toolbarHeight}px"
314
337
  >
@@ -327,6 +350,8 @@
327
350
  bind:element={editorStore.textArea}
328
351
  id="{editorStore.editorId}-plain-text"
329
352
  autoResize={true}
353
+ rows={multiline ? undefined : 1}
354
+ aria-multiline={multiline ? undefined : false}
330
355
  bind:value={editorStore.inputValue}
331
356
  {useEmojiAutocomplete}
332
357
  highlight={highlightSource}
@@ -358,16 +383,28 @@
358
383
  <style>.text-editor {
359
384
  position: relative;
360
385
  margin: var(--sui-focus-ring-width);
361
- border-radius: var(--sui-textbox-border-radius);
362
386
  width: calc(100% - var(--sui-focus-ring-width) * 2);
363
- transition: all 200ms;
364
- }
365
- .text-editor:focus-within {
366
- outline: var(--sui-focus-ring-width) solid var(--sui-focus-ring-color);
367
387
  }
368
388
  .text-editor.flex:not([hidden]) {
369
389
  display: block;
370
390
  }
391
+ .text-editor:is(.single-line, .minimal) > :global(.lexical-root), .text-editor:is(.single-line, .minimal) > :global(.text-area) > :global(:is(textarea, .clone)) {
392
+ min-height: 0;
393
+ }
394
+ .text-editor.minimal > :global(.lexical-root),
395
+ .text-editor.minimal > :global(.text-area) > :global(:is(textarea, .clone)) {
396
+ max-height: 240px;
397
+ }
398
+ .text-editor.minimal > :global(.lexical-root),
399
+ .text-editor.minimal > :global(.text-area) > :global(textarea) {
400
+ overflow: auto;
401
+ }
402
+ .text-editor.minimal > :global(.lexical-root) {
403
+ --sui-text-editor-inner-toolbar-top: 0px;
404
+ }
405
+ .text-editor.minimal > :global(.text-area) > :global(:is(textarea, .clone)) {
406
+ scrollbar-gutter: stable;
407
+ }
371
408
  .text-editor :global(.sui.text-area) {
372
409
  margin: 0 !important;
373
410
  width: 100% !important;
@@ -378,6 +415,7 @@
378
415
  border-start-end-radius: 0 !important;
379
416
  border-end-start-radius: var(--sui-textbox-border-radius) !important;
380
417
  border-end-end-radius: var(--sui-textbox-border-radius) !important;
418
+ outline-offset: calc(var(--sui-focus-ring-width) * -1);
381
419
  }
382
420
  .text-editor {
383
421
  --sui-text-editor-toolbar-top: var(--sui-text-editor-inner-toolbar-top, 0px);
@@ -46,6 +46,20 @@ declare const TextEditor: import("svelte").Component<{
46
46
  * Editor components.
47
47
  */
48
48
  components?: TextEditorComponent[] | undefined;
49
+ /**
50
+ * Whether the content can span multiple paragraphs and lines.
51
+ * With `false`, the content is kept in a single paragraph: the Enter key does nothing, and the
52
+ * paragraphs and lines of pasted or imported content are joined with spaces. Only the inline
53
+ * buttons and the editor components with a text match transformer are enabled then, horizontal
54
+ * rules and tables in Markdown are kept as text, and the HTML format has no plain text mode.
55
+ */
56
+ multiline?: boolean | undefined;
57
+ /**
58
+ * Whether to make the editor compact: it starts with the height of
59
+ * a single line, like a single-line editor, and stops growing at 240 pixels, scrolling the
60
+ * content beyond that.
61
+ */
62
+ minimal?: boolean | undefined;
49
63
  /**
50
64
  * Whether to enable Markdown keyboard shortcuts in the
51
65
  * rich text editor.
@@ -145,6 +159,20 @@ type Props = {
145
159
  * Editor components.
146
160
  */
147
161
  components?: TextEditorComponent[] | undefined;
162
+ /**
163
+ * Whether the content can span multiple paragraphs and lines.
164
+ * With `false`, the content is kept in a single paragraph: the Enter key does nothing, and the
165
+ * paragraphs and lines of pasted or imported content are joined with spaces. Only the inline
166
+ * buttons and the editor components with a text match transformer are enabled then, horizontal
167
+ * rules and tables in Markdown are kept as text, and the HTML format has no plain text mode.
168
+ */
169
+ multiline?: boolean | undefined;
170
+ /**
171
+ * Whether to make the editor compact: it starts with the height of
172
+ * a single line, like a single-line editor, and stops growing at 240 pixels, scrolling the
173
+ * content beyond that.
174
+ */
175
+ minimal?: boolean | undefined;
148
176
  /**
149
177
  * Whether to enable Markdown keyboard shortcuts in the
150
178
  * rich text editor.
@@ -1,4 +1,3 @@
1
- export function isInlineComponent({ transformer }: TextEditorComponent): boolean;
2
1
  export function insertEditorComponent(editorStore: TextEditorStore, component: TextEditorComponent): void;
3
- import type { TextEditorComponent } from '../../../typedefs.js';
4
2
  import type { TextEditorStore } from '../../../typedefs.js';
3
+ import type { TextEditorComponent } from '../../../typedefs.js';
@@ -5,15 +5,6 @@ import { insertComponent } from '../raw-markdown.js';
5
5
  * @import { TextEditorComponent, TextEditorStore } from '../../../typedefs.js';
6
6
  */
7
7
 
8
- /**
9
- * Check if the given editor component is inline, which means its Markdown is matched within a line
10
- * of text by a text match transformer. Only an inline component can be inserted into a Markdown
11
- * table cell.
12
- * @param {TextEditorComponent} component Editor component.
13
- * @returns {boolean} Result.
14
- */
15
- export const isInlineComponent = ({ transformer }) => transformer.type === 'text-match';
16
-
17
8
  /**
18
9
  * Insert a new instance of the given editor component into the editor: its Markdown in the plain
19
10
  * text mode, or its node in the rich text mode.
@@ -10,6 +10,7 @@
10
10
  import MenuButton from '../../menu/menu-button.svelte';
11
11
  import Menu from '../../menu/menu.svelte';
12
12
  import { AVAILABLE_BUTTONS, BLOCK_BUTTON_TYPES, INLINE_BUTTON_TYPES } from '../constants.js';
13
+ import { isInlineComponent } from '../core.js';
13
14
  import CodeLanguageSwitcher from './code-language-switcher.svelte';
14
15
  import AlignMenuButton from './align-menu-button.svelte';
15
16
  import FormatTextButton from './format-text-button.svelte';
@@ -17,7 +18,6 @@
17
18
  import InsertItemButton from './insert-item-button.svelte';
18
19
  import InsertLinkButton from './insert-link-button.svelte';
19
20
  import InsertMenuButton from './insert-menu-button.svelte';
20
- import { isInlineComponent } from './insert-component.js';
21
21
  import InsertTableButton from './insert-table-button.svelte';
22
22
  import TableActionMenu from './table-action-menu.svelte';
23
23
  import ToggleBlockMenuItem from './toggle-block-menu-item.svelte';
@@ -37,37 +37,32 @@ const isWordChar = (char) => !!char && /[^\s\p{P}\p{S}]/u.test(char);
37
37
  * needed, so `snake_case` and `C:\Users` aren’t exported as `snake\_case` and `C:\\Users`. Unlike
38
38
  * a global replacement, the escapes that are needed are kept: an underscore that could open or
39
39
  * close emphasis, like that in `\_not italic\_`, and a backslash that would otherwise escape the
40
- * next character or make a hard line break. Also replace the encoded spaces Lexical outputs around
41
- * formatted text, which can appear with a combination of bold and italic text.
40
+ * next character or make a hard line break.
42
41
  * @param {string} markdown Markdown exported from a text node with its format, in which every
43
42
  * backslash starts an escape.
44
43
  * @returns {string} Tidied Markdown.
45
44
  * @see https://github.com/sveltia/sveltia-cms/issues/430
46
45
  * @see https://github.com/sveltia/sveltia-cms/issues/512
47
- * @see https://github.com/sveltia/sveltia-cms/issues/511
48
- * @see https://github.com/sveltia/sveltia-cms/issues/534
49
46
  */
50
47
  export const unescapeText = (markdown) =>
51
- markdown
52
- .replace(/((?:\\_)+)|\\(.)/gs, (match, underscores, char, offset, string) => {
53
- if (underscores) {
54
- return isWordChar(string[offset - 1]) && isWordChar(string[offset + match.length])
55
- ? underscores.replaceAll('\\', '')
56
- : match;
57
- }
58
-
59
- if (char === '\\') {
60
- const next = string[offset + 2];
61
-
62
- // The backslash is literal unless it’s followed by ASCII punctuation, which it would
63
- // escape, or a line break, which it would turn into a hard line break. The end of the node
64
- // is kept escaped, as the next node may start with either
65
- return next && !/[\n\r!-/:-@[-`{-~]/.test(next) ? char : match;
66
- }
67
-
68
- return match;
69
- })
70
- .replace(/&#32;/g, ' ');
48
+ markdown.replace(/((?:\\_)+)|\\(.)/gs, (match, underscores, char, offset, string) => {
49
+ if (underscores) {
50
+ return isWordChar(string[offset - 1]) && isWordChar(string[offset + match.length])
51
+ ? underscores.replaceAll('\\', '')
52
+ : match;
53
+ }
54
+
55
+ if (char === '\\') {
56
+ const next = string[offset + 2];
57
+
58
+ // The backslash is literal unless it’s followed by ASCII punctuation, which it would
59
+ // escape, or a line break, which it would turn into a hard line break. The end of the node
60
+ // is kept escaped, as the next node may start with either
61
+ return next && !/[\n\r!-/:-@[-`{-~]/.test(next) ? char : match;
62
+ }
63
+
64
+ return match;
65
+ });
71
66
 
72
67
  /**
73
68
  * Check if the given text node is italic and the italic text it’s part of is next to a word
@@ -94,9 +94,9 @@
94
94
  let cloneElement = $state();
95
95
 
96
96
  $effect(() => {
97
- // Keep the highlighted text scrolled along with the `<textarea>`. It never scrolls when it’s
98
- // auto-resized
99
- if (!element || !cloneElement || autoResize) {
97
+ // Keep the highlighted text scrolled along with the `<textarea>`, which can also scroll when
98
+ // it’s auto-resized, if its height is capped with `max-height`
99
+ if (!element || !cloneElement) {
100
100
  return undefined;
101
101
  }
102
102
 
@@ -232,12 +232,12 @@ textarea[aria-invalid=true] {
232
232
  .clone {
233
233
  overflow: hidden;
234
234
  visibility: hidden;
235
+ scroll-behavior: auto;
235
236
  }
236
237
  .clone:not(.auto-resize) {
237
238
  position: absolute;
238
239
  inset: 0;
239
240
  min-height: 0;
240
- scroll-behavior: auto;
241
241
  }
242
242
 
243
243
  .highlighted textarea {
@@ -809,6 +809,11 @@ export type TextEditorConfig = {
809
809
  * Format of the value. Default: `markdown`.
810
810
  */
811
811
  format?: TextEditorValueFormat | undefined;
812
+ /**
813
+ * Whether the content can span multiple paragraphs and lines. With
814
+ * `false`, it’s kept in a single paragraph without line breaks. Default: `true`.
815
+ */
816
+ multiline?: boolean | undefined;
812
817
  };
813
818
  export type EmojiEntry = {
814
819
  /**
package/dist/typedefs.js CHANGED
@@ -347,6 +347,8 @@
347
347
  * shortcode, like `:smi`. Default: `false`.
348
348
  * @property {string} [defaultLanguage] Default language for the code editor.
349
349
  * @property {TextEditorValueFormat} [format] Format of the value. Default: `markdown`.
350
+ * @property {boolean} [multiline] Whether the content can span multiple paragraphs and lines. With
351
+ * `false`, it’s kept in a single paragraph without line breaks. Default: `true`.
350
352
  */
351
353
 
352
354
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltia/ui",
3
- "version": "0.87.4",
3
+ "version": "0.88.0",
4
4
  "description": "A collection of Svelte components and utilities for building user interfaces.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -69,7 +69,7 @@
69
69
  "@fontsource-variable/material-symbols-outlined": "5.3.9",
70
70
  "@fontsource-variable/source-sans-3": "5.3.1",
71
71
  "@fontsource/noto-mono": "5.3.0",
72
- "@rollup/plugin-yaml": "^5.0.0",
72
+ "@rollup/plugin-yaml": "^5.0.1",
73
73
  "@sveltejs/adapter-auto": "^8.0.0",
74
74
  "@sveltejs/kit": "^3.1.0",
75
75
  "@sveltejs/package": "^3.0.1",
@@ -81,8 +81,8 @@
81
81
  "eslint-config-airbnb-extended": "^3.3.0",
82
82
  "eslint-config-prettier": "^10.1.8",
83
83
  "eslint-plugin-import": "^2.32.0",
84
- "eslint-plugin-jsdoc": "^65.4.0",
85
- "eslint-plugin-package-json": "^1.10.1",
84
+ "eslint-plugin-jsdoc": "^65.4.2",
85
+ "eslint-plugin-package-json": "^1.11.0",
86
86
  "eslint-plugin-svelte": "^3.23.1",
87
87
  "globals": "^17.13.0",
88
88
  "happy-dom": "^21.0.4",
@@ -93,7 +93,7 @@
93
93
  "prettier": "^3.9.10",
94
94
  "prettier-plugin-svelte": "^4.1.1",
95
95
  "rolldown": "^1.2.15",
96
- "sass": "^1.106.0",
96
+ "sass": "^1.106.1",
97
97
  "shiki": "^4.5.0",
98
98
  "stylelint": "^17.16.0",
99
99
  "stylelint-config-recommended-scss": "^17.0.1",