@astryxdesign/richtext 0.7.16-canary.ge95b87c → 0.7.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @astryxdesign/richtext
2
2
 
3
+ # 0.7.16
4
+
5
+ #### New Features
6
+
7
+ - `RichTextEditorToolbar`'s Link button, and Cmd/Ctrl+K in the editor, open a popover anchored to the button instead of a modal dialog. The popover holds one URL field, applied with Enter, and Apply, Remove (when the selection is in a link), and Cancel icon buttons with tooltips. It is not modal: Escape or Cancel closes it and returns focus and the selection to the editor, and a URL that cannot be linked shows an error under the field, which keeps focus. The URL rules (`sanitizeUrl`), `hasNewTabLinks`, and `promptForUrl` are unchanged; with `promptForUrl` the Link button opens no popover, as it opened no dialog. ([#8717](https://github.com/meta/astryx/pull/8717))
8
+ The popover opens above the toolbar and flips below it only when there is no room above. Apply and Cancel use the shared `check` and `close` icons, so a theme that restyles those icons restyles them too; Remove's glyph is fixed artwork. `RICHTEXT_ICON_KEYS` is unchanged.
9
+
10
+ #### Fixes
11
+
12
+ - Pasting into a `RichTextEditor` table no longer drops the paste or empties cells. A pasted table fills the cells one by one from the caret's cell, or within the selected cells. A merged cell in it fills only the cell where it starts instead of emptying the cells it covered, and a table whose rows differ in length arrives whole. A table pasted together with other content, as a web page copies it, goes into the cell as text instead of being discarded. ([#8577](https://github.com/meta/astryx/pull/8577))
13
+ - A link typed without a scheme, whose host has a dot or is `localhost`, followed by a port, such as `example.com:8080`, `www.example.com:8080/docs` or `localhost:3000`, now gets the default `https://` like `example.com` does, instead of being read as an unknown scheme and turned into `about:blank` ([#11042](https://github.com/meta/astryx/pull/11042))
14
+
15
+ #### Contributors
16
+
17
+ Thanks to everyone who contributed to this release:
18
+
19
+ - @emilyhorsman
20
+ - @ernestt
21
+ - @kevin9327
22
+
23
+ ---
24
+
3
25
  # 0.7.15
4
26
 
5
27
  #### Fixes
@@ -3,10 +3,11 @@
3
3
  * @input Uses React, @lexical/react (composer context), @lexical/rich-text,
4
4
  * @lexical/selection, @lexical/list, @lexical/utils, and the lexical core
5
5
  * command constants, plus Astryx Toolbar / IconButton / Selector /
6
- * ToggleButton / Divider / Dialog / TextInput / Button / Layout primitives.
6
+ * ToggleButton / Divider / Popover / TextInput / Layout primitives.
7
7
  * @output Exports RichTextEditorToolbar (a compact formatting toolbar with a
8
- * RichText-owned 4px control gutter and horizontally scrollable action row)
9
- * and RichTextEditorToolbarProps.
8
+ * RichText-owned 4px control gutter, a horizontally scrollable action row,
9
+ * and a link popover anchored to its Link button) and
10
+ * RichTextEditorToolbarProps.
10
11
  * @position @astryxdesign/richtext. Drop into RichTextEditor's `toolbar` slot to
11
12
  * add a flush top formatting toolbar. Themed via Astryx Toolbar, Selector,
12
13
  * IconButton, and ToggleButton, so it inherits the active theme. Base props
@@ -83,11 +84,14 @@ export interface RichTextEditorToolbarProps extends BaseProps<HTMLDivElement> {
83
84
  */
84
85
  size?: 'sm' | 'md' | 'lg';
85
86
  /**
86
- * Whether to show the insert/edit-link button. By default, pressing it opens
87
- * an Astryx Dialog. The form can add, update, or remove a link without
88
- * losing the editor selection. With a collapsed selection, Insert link
89
- * inserts the entered URL as link text at the caret; with a non-empty
90
- * selection it links the selected text.
87
+ * Whether to show the insert/edit-link button. By default, pressing it (or
88
+ * Cmd/Ctrl+K in the editor) opens an Astryx Popover anchored to the button:
89
+ * one URL field, applied with Enter, with Remove when the selection is in a
90
+ * link. The popover is not modal. Escape or Cancel closes it and returns
91
+ * focus and the selection to the editor; a URL that cannot be linked shows
92
+ * an error under the field, which keeps focus. With a collapsed selection,
93
+ * applying inserts the entered URL as link text at the caret; with a
94
+ * non-empty selection it links the selected text.
91
95
  *
92
96
  * Requires `LinkNode` to be registered (it is, by default) — no extra setup.
93
97
  * The entered URL is sanitized (see `sanitizeUrl`) so only
@@ -99,7 +103,7 @@ export interface RichTextEditorToolbarProps extends BaseProps<HTMLDivElement> {
99
103
  * Called to obtain a URL when the link button is pressed on a non-link
100
104
  * selection. Return the URL string to link, or `null`/`''` to cancel.
101
105
  * Receives the currently selected text as a hint. When omitted, the built-in
102
- * Astryx Dialog is used. This synchronous override is retained
106
+ * link popover is used. This synchronous override is retained
103
107
  * for consumers that already provide their own URL UI.
104
108
  */
105
109
  promptForUrl?: (selectedText: string) => string | null | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"RichTextEditorToolbar.d.ts","sourceRoot":"","sources":["../src/RichTextEditorToolbar.tsx"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,EAML,KAAK,SAAS,EACd,KAAK,GAAG,EACT,MAAM,OAAO,CAAC;AAmBf,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,oBAAoB,CAAC;AA8HlD;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;CAgBrB,CAAC;AAmPX,MAAM,WAAW,0BAA2B,SAAQ,SAAS,CAAC,cAAc,CAAC;IAC3E;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,GAAG,CAAC,cAAc,CAAC,CAAC;IAC1B;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;IAClD;;;;OAIG;IACH,IAAI,CAAC,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC1B;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACnE;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;OAIG;IACH,UAAU,CAAC,EAAE,SAAS,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,KAAK,EAAE,cAAc,EACrB,aAAkC,EAClC,IAAW,EACX,OAAc,EACd,YAAY,EACZ,cAAqB,EACrB,UAAU,EACV,MAAM,EACN,GAAG,EACH,GAAG,IAAI,EACR,EAAE,0BAA0B,+BAmhB5B;yBA9hBe,qBAAqB"}
1
+ {"version":3,"file":"RichTextEditorToolbar.d.ts","sourceRoot":"","sources":["../src/RichTextEditorToolbar.tsx"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,EAKL,KAAK,SAAS,EACd,KAAK,GAAG,EAET,MAAM,OAAO,CAAC;AAmBf,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,oBAAoB,CAAC;AAgIlD;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;CAgBrB,CAAC;AA8XX,MAAM,WAAW,0BAA2B,SAAQ,SAAS,CAAC,cAAc,CAAC;IAC3E;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,GAAG,CAAC,cAAc,CAAC,CAAC;IAC1B;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC,CAAC;IAClD;;;;OAIG;IACH,IAAI,CAAC,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAC1B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACnE;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;;OAIG;IACH,UAAU,CAAC,EAAE,SAAS,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,KAAK,EAAE,cAAc,EACrB,aAAkC,EAClC,IAAW,EACX,OAAc,EACd,YAAY,EACZ,cAAqB,EACrB,UAAU,EACV,MAAM,EACN,GAAG,EACH,GAAG,IAAI,EACR,EAAE,0BAA0B,+BAyhB5B;yBApiBe,qBAAqB"}
@@ -7,10 +7,11 @@
7
7
  * @input Uses React, @lexical/react (composer context), @lexical/rich-text,
8
8
  * @lexical/selection, @lexical/list, @lexical/utils, and the lexical core
9
9
  * command constants, plus Astryx Toolbar / IconButton / Selector /
10
- * ToggleButton / Divider / Dialog / TextInput / Button / Layout primitives.
10
+ * ToggleButton / Divider / Popover / TextInput / Layout primitives.
11
11
  * @output Exports RichTextEditorToolbar (a compact formatting toolbar with a
12
- * RichText-owned 4px control gutter and horizontally scrollable action row)
13
- * and RichTextEditorToolbarProps.
12
+ * RichText-owned 4px control gutter, a horizontally scrollable action row,
13
+ * and a link popover anchored to its Link button) and
14
+ * RichTextEditorToolbarProps.
14
15
  * @position @astryxdesign/richtext. Drop into RichTextEditor's `toolbar` slot to
15
16
  * add a flush top formatting toolbar. Themed via Astryx Toolbar, Selector,
16
17
  * IconButton, and ToggleButton, so it inherits the active theme. Base props
@@ -49,14 +50,12 @@ import { IconButton } from '@astryxdesign/core/IconButton';
49
50
  import { Selector } from '@astryxdesign/core/Selector';
50
51
  import { ToggleButton } from '@astryxdesign/core/ToggleButton';
51
52
  import { Divider } from '@astryxdesign/core/Divider';
52
- import { Dialog, DialogHeader } from '@astryxdesign/core/Dialog';
53
+ import { Popover } from '@astryxdesign/core/Popover';
53
54
  import { TextInput } from '@astryxdesign/core/TextInput';
54
- import { Button } from '@astryxdesign/core/Button';
55
- import { Stack } from '@astryxdesign/core/Stack';
56
- import { HStack, Layout, LayoutContent, LayoutFooter } from '@astryxdesign/core/Layout';
57
- import { getExtendedIcon } from '@astryxdesign/core/Icon';
55
+ import { HStack, StackItem } from '@astryxdesign/core/Layout';
56
+ import { Icon, getExtendedIcon } from '@astryxdesign/core/Icon';
58
57
  import { useThemeName } from '@astryxdesign/core/theme';
59
- import { isRenderable, rtlStyles } from '@astryxdesign/core/utils';
58
+ import { isImeKeyEvent, isRenderable, rtlStyles } from '@astryxdesign/core/utils';
60
59
  import '@astryxdesign/core/theme/tokens.stylex';
61
60
  import { fontWeightVars, spacingVars, typeScaleVars } from '@astryxdesign/core/theme/tokens.stylex';
62
61
  import { useTranslator } from '@astryxdesign/core/i18n';
@@ -75,6 +74,10 @@ const CONTROL_OR_META = {
75
74
  ctrlKey: !IS_APPLE,
76
75
  metaKey: IS_APPLE
77
76
  };
77
+
78
+ // The link popover's anchor: a box around the Link button that takes no
79
+ // space of its own.
80
+
78
81
  // A vertical Divider's default 100% height needs a definite parent height.
79
82
  // Toolbar slots are sized by their controls instead, so let flexbox stretch
80
83
  // these group separators across the slot's resolved height.
@@ -392,6 +395,126 @@ function DirectionalGlyph({
392
395
  children: children
393
396
  });
394
397
  }
398
+
399
+ /**
400
+ * Remove's glyph. No shared icon name means "unlink", so it is fixed
401
+ * component artwork until component icon slots exist.
402
+ */
403
+ const REMOVE_LINK_GLYPH = /*#__PURE__*/_jsx("svg", {
404
+ width: "16",
405
+ height: "16",
406
+ viewBox: "0 0 24 24",
407
+ fill: "none",
408
+ "aria-hidden": "true",
409
+ children: /*#__PURE__*/_jsx("path", {
410
+ d: "M18 13l2-2a5 5 0 0 0-7-7l-2 2M6 11l-2 2a5 5 0 0 0 7 7l2-2M8 2v3M2 8h3M16 22v-3M22 16h-3",
411
+ stroke: "currentColor",
412
+ strokeWidth: "2",
413
+ strokeLinecap: "round",
414
+ strokeLinejoin: "round"
415
+ })
416
+ });
417
+
418
+ /** Room for a typical address beside the link form's icon buttons. */
419
+ const LINK_POPOVER_WIDTH = 320;
420
+ /**
421
+ * The link popover's content: one URL field, then Apply, Remove (only when
422
+ * the selection is in a link), and Cancel as icon buttons. Enter in the field
423
+ * applies, and Escape anywhere in the form cancels. A refused address shows
424
+ * the field's error status and keeps focus in the field.
425
+ */
426
+ function ToolbarLinkForm({
427
+ url,
428
+ error,
429
+ isEditing,
430
+ size,
431
+ onUrlChange,
432
+ onApply,
433
+ onRemove,
434
+ onCancel
435
+ }) {
436
+ const t = useTranslator();
437
+ const inputRef = useRef(null);
438
+ const apply = () => {
439
+ if (!onApply()) {
440
+ inputRef.current?.focus();
441
+ }
442
+ };
443
+ const applyLabel = isEditing ? t('@astryx.richTextEditor.link.update') : t('@astryx.richTextEditor.link.add');
444
+ const removeLabel = t('@astryx.richTextEditor.link.remove');
445
+ const cancelLabel = t('@astryx.richTextEditor.link.cancel');
446
+ return /*#__PURE__*/_jsxs(HStack, {
447
+ gap: 1,
448
+ vAlign: "start",
449
+ onKeyDown: event => {
450
+ // Escape that ends an IME composition is the input method's.
451
+ if (event.key === 'Escape' && !isImeKeyEvent(event.nativeEvent)) {
452
+ // Claimed here, so the popover's own Escape handling leaves it to
453
+ // Cancel, which also gives the editor back its selection.
454
+ event.preventDefault();
455
+ onCancel();
456
+ }
457
+ },
458
+ children: [/*#__PURE__*/_jsx(StackItem, {
459
+ size: "fill",
460
+ children: /*#__PURE__*/_jsx(TextInput, {
461
+ ref: inputRef,
462
+ label: t('@astryx.richTextEditor.link.url'),
463
+ isLabelHidden: true,
464
+ value: url,
465
+ size: size,
466
+ width: "100%",
467
+ autoComplete: "url"
468
+ // A URL keyboard on touch screens and no spelling marks under an
469
+ // address. The field stays plain text, so a bare domain reaches
470
+ // the toolbar's own check, which makes it an https link.
471
+ ,
472
+ inputMode: "url",
473
+ hasSpellCheck: false,
474
+ placeholder: t('@astryx.richTextEditor.link.urlPlaceholder'),
475
+ status: error ? {
476
+ type: 'error',
477
+ message: error
478
+ } : undefined,
479
+ statusVariant: "detached",
480
+ onChange: onUrlChange,
481
+ onEnter: apply,
482
+ onKeyDown: event => {
483
+ // Applying hands focus to the editor, which must not receive the
484
+ // rest of this Enter as a new line over the linked words.
485
+ if (event.key === 'Enter' && !isImeKeyEvent(event.nativeEvent)) {
486
+ event.preventDefault();
487
+ }
488
+ }
489
+ })
490
+ }), /*#__PURE__*/_jsx(IconButton, {
491
+ label: applyLabel,
492
+ icon: /*#__PURE__*/_jsx(Icon, {
493
+ icon: "check"
494
+ }),
495
+ variant: "ghost",
496
+ size: size,
497
+ tooltip: applyLabel,
498
+ onClick: apply
499
+ }), isEditing && /*#__PURE__*/_jsx(IconButton, {
500
+ label: removeLabel,
501
+ icon: REMOVE_LINK_GLYPH,
502
+ variant: "ghost",
503
+ size: size,
504
+ tooltip: removeLabel,
505
+ onClick: onRemove
506
+ }), /*#__PURE__*/_jsx(IconButton, {
507
+ label: cancelLabel,
508
+ icon: /*#__PURE__*/_jsx(Icon, {
509
+ icon: "close"
510
+ }),
511
+ variant: "ghost",
512
+ size: size,
513
+ tooltip: cancelLabel,
514
+ onClick: onCancel
515
+ })]
516
+ });
517
+ }
395
518
  /**
396
519
  * A composable formatting toolbar for {@link RichTextEditor}, built from Astryx
397
520
  * `Toolbar` / `ToggleButton` primitives so it matches the active theme. Reads
@@ -454,7 +577,9 @@ export function RichTextEditorToolbar({
454
577
  url: '',
455
578
  isLink: false
456
579
  });
457
- const [isLinkDialogOpen, setIsLinkDialogOpen] = useState(false);
580
+ const linkButtonRef = useRef(null);
581
+ const linkAnchorRef = useRef(null);
582
+ const [isLinkPopoverOpen, setIsLinkPopoverOpen] = useState(false);
458
583
  const [isEditingLink, setIsEditingLink] = useState(false);
459
584
  const [linkUrl, setLinkUrl] = useState('');
460
585
  const [linkError, setLinkError] = useState('');
@@ -593,33 +718,63 @@ export function RichTextEditorToolbar({
593
718
  }
594
719
  return;
595
720
  }
596
- setLinkUrl(context.url || (context.selectedText.startsWith('http') ? context.selectedText : 'https://'));
721
+
722
+ // The field starts from the link's address, or from selected text that
723
+ // already reads as one; otherwise it is empty and shows its placeholder.
724
+ setLinkUrl(context.url || (context.selectedText.startsWith('http') ? context.selectedText : ''));
597
725
  setIsEditingLink(context.isLink);
598
726
  setLinkError('');
599
- setIsLinkDialogOpen(true);
727
+ // Cmd/Ctrl+K can open the form while the Link button is scrolled out of
728
+ // view, in the page or in the toolbar's own row. Bring it back so the
729
+ // popover opens beside it.
730
+ linkButtonRef.current?.scrollIntoView?.({
731
+ block: 'nearest',
732
+ inline: 'nearest'
733
+ });
734
+ setIsLinkPopoverOpen(true);
600
735
  }, [applyLinkValue, editor, promptForUrl, readLinkContext, restoreLinkSelection]);
601
- const handleLinkDialogOpenChange = useCallback(open => {
602
- setIsLinkDialogOpen(open);
736
+ const closeLinkPopover = useCallback(() => {
737
+ setIsLinkPopoverOpen(false);
603
738
  setLinkError('');
604
739
  }, []);
605
- const closeLinkDialogToEditor = useCallback(() => {
606
- setIsLinkDialogOpen(false);
607
- setLinkError('');
608
- requestAnimationFrame(() => editor.focus());
609
- }, [editor]);
610
- const handleLinkSubmit = useCallback(event => {
611
- event.preventDefault();
740
+
741
+ // The popover reports its own opening (a press on the Link button) and its
742
+ // closing (a press outside it).
743
+ const handleLinkPopoverOpenChange = useCallback(open => {
744
+ if (open) {
745
+ toggleLink();
746
+ } else {
747
+ closeLinkPopover();
748
+ }
749
+ }, [closeLinkPopover, toggleLink]);
750
+
751
+ // Closes the popover and gives the editor back its focus. The editable root
752
+ // takes focus first and Lexical then draws its selection into it, so the
753
+ // selection survives the field having held the page's selection.
754
+ const closeLinkPopoverToEditor = useCallback(() => {
755
+ closeLinkPopover();
756
+ editor.getRootElement()?.focus({
757
+ preventScroll: true
758
+ });
759
+ editor.focus();
760
+ }, [closeLinkPopover, editor]);
761
+ const cancelLinkPopover = useCallback(() => {
762
+ restoreLinkSelection();
763
+ closeLinkPopoverToEditor();
764
+ }, [closeLinkPopoverToEditor, restoreLinkSelection]);
765
+ const applyLink = useCallback(() => {
612
766
  if (!applyLinkValue(linkUrl)) {
613
767
  setLinkError(t('@astryx.richTextEditor.link.invalidUrl'));
614
- return;
768
+ return false;
615
769
  }
616
- closeLinkDialogToEditor();
617
- }, [applyLinkValue, closeLinkDialogToEditor, linkUrl, t]);
770
+ closeLinkPopoverToEditor();
771
+ return true;
772
+ }, [applyLinkValue, closeLinkPopoverToEditor, linkUrl, t]);
618
773
  const removeLink = useCallback(() => {
619
774
  restoreLinkSelection();
620
775
  editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
621
- closeLinkDialogToEditor();
622
- }, [closeLinkDialogToEditor, editor, restoreLinkSelection]);
776
+ closeLinkPopoverToEditor();
777
+ }, [closeLinkPopoverToEditor, editor, restoreLinkSelection]);
623
778
  useEffect(() => {
624
779
  return mergeRegister(editor.registerUpdateListener(({
625
780
  editorState
@@ -771,75 +926,66 @@ export function RichTextEditorToolbar({
771
926
  isPressed: activeFormats.has(action.format),
772
927
  isDisabled: !isEditable,
773
928
  onPressedChange: () => toggleInlineFormat(action.format)
774
- }, action.format)), hasLink && /*#__PURE__*/_jsx(ToggleButton, {
775
- label: t('@astryx.richTextEditor.toolbar.link'),
776
- icon: icon('link'),
777
- size: size,
778
- isIconOnly: true,
779
- isPressed: isLink || isLinkDialogOpen,
780
- isDisabled: !isEditable,
781
- "aria-haspopup": "dialog",
782
- "aria-expanded": isLinkDialogOpen,
783
- onMouseDown: event => event.preventDefault(),
784
- onPressedChange: toggleLink
929
+ }, action.format)), hasLink &&
930
+ /*#__PURE__*/
931
+ // The popover anchors to this wrapper, which a press never
932
+ // scales, and finds the button inside it for its handlers.
933
+ _jsx("span", {
934
+ ref: linkAnchorRef,
935
+ ...{
936
+ className: "x3nfvp2 x2lah0s"
937
+ },
938
+ children: /*#__PURE__*/_jsx(ToggleButton, {
939
+ ref: linkButtonRef,
940
+ label: t('@astryx.richTextEditor.toolbar.link'),
941
+ icon: icon('link'),
942
+ size: size,
943
+ isIconOnly: true,
944
+ isPressed: isLink || isLinkPopoverOpen,
945
+ isDisabled: !isEditable,
946
+ onMouseDown: event => event.preventDefault()
947
+ // The link popover owns a press on the button, and with it
948
+ // the button's popup state; `promptForUrl` replaces both.
949
+ ,
950
+ onPressedChange: promptForUrl ? toggleLink : undefined
951
+ })
785
952
  }, "link"), isRenderable(endContent) && /*#__PURE__*/_jsxs(_Fragment, {
786
953
  children: [/*#__PURE__*/_jsx(Divider, {
787
954
  orientation: "vertical"
788
955
  }), endContent]
789
956
  })]
790
957
  })
791
- }), hasLink && /*#__PURE__*/_jsx(Dialog, {
792
- isOpen: isLinkDialogOpen,
793
- onOpenChange: handleLinkDialogOpenChange,
794
- purpose: "form",
795
- width: 400,
796
- children: /*#__PURE__*/_jsx(Stack, {
797
- as: "form",
798
- onSubmit: handleLinkSubmit,
799
- children: /*#__PURE__*/_jsx(Layout, {
800
- height: "auto",
801
- header: /*#__PURE__*/_jsx(DialogHeader, {
802
- title: isEditingLink ? t('@astryx.richTextEditor.link.editTitle') : t('@astryx.richTextEditor.link.insertTitle'),
803
- onOpenChange: handleLinkDialogOpenChange
804
- }),
805
- content: /*#__PURE__*/_jsx(LayoutContent, {
806
- children: /*#__PURE__*/_jsx(TextInput, {
807
- label: t('@astryx.richTextEditor.link.url'),
808
- value: linkUrl,
809
- width: "100%",
810
- hasAutoFocus: true,
811
- status: linkError ? {
812
- type: 'error',
813
- message: linkError
814
- } : undefined,
815
- statusVariant: "detached",
816
- onChange: value => {
817
- setLinkUrl(value);
818
- setLinkError('');
819
- }
820
- })
821
- }),
822
- footer: /*#__PURE__*/_jsx(LayoutFooter, {
823
- children: /*#__PURE__*/_jsxs(HStack, {
824
- gap: 2,
825
- hAlign: "end",
826
- children: [isEditingLink && /*#__PURE__*/_jsx(Button, {
827
- label: t('@astryx.richTextEditor.link.remove'),
828
- variant: "destructive",
829
- onClick: removeLink
830
- }), /*#__PURE__*/_jsx(Button, {
831
- label: t('@astryx.richTextEditor.link.cancel'),
832
- variant: "secondary",
833
- onClick: () => handleLinkDialogOpenChange(false)
834
- }), /*#__PURE__*/_jsx(Button, {
835
- label: isEditingLink ? t('@astryx.richTextEditor.link.update') : t('@astryx.richTextEditor.link.add'),
836
- variant: "primary",
837
- type: "submit"
838
- })]
839
- })
840
- })
841
- })
842
- })
958
+ }), hasLink && promptForUrl == null && /*#__PURE__*/_jsx(Popover, {
959
+ anchorRef: linkAnchorRef,
960
+ label: isEditingLink ? t('@astryx.richTextEditor.link.editTitle') : t('@astryx.richTextEditor.link.insertTitle'),
961
+ isOpen: isLinkPopoverOpen,
962
+ onOpenChange: handleLinkPopoverOpenChange,
963
+ isModal: false
964
+ // Popover's focus entry focuses the URL field, the form's first
965
+ // control. Cancel is its close control.
966
+ ,
967
+ hasCloseButton: false
968
+ // Above the toolbar, so the popover does not cover the editor's
969
+ // first lines, where the linked words often are. It flips below
970
+ // only when there is no room above.
971
+ ,
972
+ placement: "above",
973
+ alignment: "start",
974
+ width: LINK_POPOVER_WIDTH,
975
+ padding: 2,
976
+ content: isLinkPopoverOpen ? /*#__PURE__*/_jsx(ToolbarLinkForm, {
977
+ url: linkUrl,
978
+ error: linkError,
979
+ isEditing: isEditingLink,
980
+ size: size,
981
+ onUrlChange: value => {
982
+ setLinkUrl(value);
983
+ setLinkError('');
984
+ },
985
+ onApply: applyLink,
986
+ onRemove: removeLink,
987
+ onCancel: cancelLinkPopover
988
+ }) : null
843
989
  })]
844
990
  });
845
991
  }
@@ -1 +1 @@
1
- {"version":3,"file":"linkUtils.d.ts","sourceRoot":"","sources":["../src/linkUtils.ts"],"names":[],"mappings":"AAoCA;;;GAGG;AACH,eAAO,MAAM,WAAW,QAC0F,CAAC;AAEnH;;;;;GAKG;AACH,eAAO,MAAM,aAAa,QACyJ,CAAC;AAOpL;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAc/C;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAWhD"}
1
+ {"version":3,"file":"linkUtils.d.ts","sourceRoot":"","sources":["../src/linkUtils.ts"],"names":[],"mappings":"AAoCA;;;GAGG;AACH,eAAO,MAAM,WAAW,QAC0F,CAAC;AAEnH;;;;;GAKG;AACH,eAAO,MAAM,aAAa,QACyJ,CAAC;AAgBpL;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAc/C;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAWhD"}
package/dist/linkUtils.js CHANGED
@@ -48,9 +48,15 @@ export const URL_MATCHER = /((https?:\/\/(www\.)?)|(www\.))[-a-zA-Z0-9@:%._+~#=]
48
48
  */
49
49
  export const EMAIL_MATCHER = /((?<![^<>()[\]\\,;:\s@"])[^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*|("[^"\r\n]+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
50
50
 
51
+ /**
52
+ * A host with a port also looks like a scheme (`example.com:`).
53
+ * The host needs a dot or is `localhost`, so `tel:911` keeps its scheme.
54
+ */
55
+ const HOST_WITH_PORT = /^(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+):\d{1,5}(?:[/?#]|$)/i;
56
+
51
57
  /** Prepend a default `https://` scheme to a bare host so it parses as absolute. */
52
58
  function withDefaultScheme(url) {
53
- return HAS_SCHEME.test(url) ? url : `https://${url}`;
59
+ return HAS_SCHEME.test(url) && !HOST_WITH_PORT.test(url) ? url : `https://${url}`;
54
60
  }
55
61
 
56
62
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@astryxdesign/richtext",
3
3
  "displayName": "Rich Text",
4
- "version": "0.7.16-canary.ge95b87c",
4
+ "version": "0.7.16",
5
5
  "description": "Astryx rich text — a Lexical-based rich text editor and viewer, styled with Astryx design tokens.",
6
6
  "author": "Meta Open Source",
7
7
  "license": "MIT",
@@ -66,7 +66,7 @@
66
66
  },
67
67
  "peerDependencies": {
68
68
  "@stylexjs/stylex": ">=0.10.0",
69
- "@astryxdesign/core": "0.7.16-canary.ge95b87c",
69
+ "@astryxdesign/core": "0.7.16",
70
70
  "react": ">=19.0.0",
71
71
  "react-dom": ">=19.0.0",
72
72
  "lexical": "^0.52.0",
@@ -125,8 +125,6 @@
125
125
  }
126
126
  },
127
127
  "devDependencies": {
128
- "@astryxdesign/a11y-spec": "0.7.16-canary.ge95b87c",
129
- "@astryxdesign/cli": "0.7.16-canary.ge95b87c",
130
128
  "@babel/cli": "^7.29.7",
131
129
  "@babel/core": "^7.29.7",
132
130
  "@babel/preset-react": "^7.29.7",
@@ -145,7 +143,9 @@
145
143
  "@lexical/utils": "^0.52.0",
146
144
  "@stylexjs/babel-plugin": "^0.19.1",
147
145
  "@testing-library/react": "^16.3.3",
148
- "lexical": "^0.52.0"
146
+ "lexical": "^0.52.0",
147
+ "@astryxdesign/a11y-spec": "0.0.0",
148
+ "@astryxdesign/cli": "0.7.16"
149
149
  },
150
150
  "scripts": {
151
151
  "build": "node ../../scripts/clean-dist.mjs && pnpm build:esm && tsc --project tsconfig.build.json && node ../../scripts/add-declaration-extensions.mjs && pnpm build:css && node ../../scripts/check-no-dev-jsx.mjs && node ../../scripts/check-fully-specified.mjs",
@@ -281,7 +281,7 @@ export const docs = {
281
281
  {
282
282
  guidance: true,
283
283
  description:
284
- 'Links: the toolbar Link button (on by default; disable with hasLink={false}) and Cmd/Ctrl+K open an Astryx Dialog. The form preserves the Lexical selection while focus moves into the URL input and supports add, update, remove, Escape, and focus return. Pass promptForUrl only when integrating an existing synchronous URL flow. Entered URLs are sanitized (only http/https/mailto/tel are written; javascript:/data: are rejected). Links open in a new tab by default: target=_blank and rel=noopener noreferrer are written into the link node data; set hasNewTabLinks={false} for same-tab links. The toolbar takes base props and passes them to the Astryx Toolbar it renders: ref, className, style and xstyle on its root; data-*, other aria-* attributes and DOM handlers on the toolbar element (name it with label, not aria-label).',
284
+ 'Links: the toolbar Link button (on by default; disable with hasLink={false}) and Cmd/Ctrl+K open a non-modal Astryx Popover anchored to the button. It holds one URL field, applied with Enter, and Apply, Remove (when the selection is in a link), and Cancel icon buttons with tooltips. It keeps the Lexical selection while focus is in the field: Escape or Cancel closes it and returns focus and the selection to the editor, and a URL that cannot be linked shows an error under the field, which keeps focus. Pass promptForUrl only when integrating an existing synchronous URL flow; it replaces the popover. Entered URLs are sanitized (only http/https/mailto/tel are written; javascript:/data: are rejected). Links open in a new tab by default: target=_blank and rel=noopener noreferrer are written into the link node data; set hasNewTabLinks={false} for same-tab links. The toolbar takes base props and passes them to the Astryx Toolbar it renders: ref, className, style and xstyle on its root; data-*, other aria-* attributes and DOM handlers on the toolbar element (name it with label, not aria-label).',
285
285
  },
286
286
  {
287
287
  guidance: true,
@@ -40,14 +40,14 @@ export const docs = {
40
40
  name: 'hasLink',
41
41
  type: 'boolean',
42
42
  description:
43
- 'Whether to show the link button. It opens an Astryx Dialog that adds, updates or removes a link and keeps the editor selection. With a collapsed selection the URL is inserted as link text; otherwise the selected text is linked. Only http, https, mailto and tel URLs are written.',
43
+ 'Whether to show the link button. It opens a link popover anchored to the button, with one URL field applied with Enter and Remove when the selection is in a link. The popover is not modal; Escape or Cancel returns focus and the selection to the editor. With a collapsed selection the URL is inserted as link text; otherwise the selected text is linked. Only http, https, mailto and tel URLs are written.',
44
44
  default: 'true',
45
45
  },
46
46
  {
47
47
  name: 'promptForUrl',
48
48
  type: '(selectedText: string) => string | null | undefined',
49
49
  description:
50
- 'A synchronous URL prompt that replaces the built-in Dialog when the link button is pressed on a selection that is not a link. It gets the selected text; return the URL, or null or an empty string to cancel.',
50
+ 'A synchronous URL prompt that replaces the built-in link popover when the link button is pressed on a selection that is not a link. It gets the selected text; return the URL, or null or an empty string to cancel.',
51
51
  },
52
52
  {
53
53
  name: 'hasNewTabLinks',
@@ -7,10 +7,11 @@
7
7
  * @input Uses React, @lexical/react (composer context), @lexical/rich-text,
8
8
  * @lexical/selection, @lexical/list, @lexical/utils, and the lexical core
9
9
  * command constants, plus Astryx Toolbar / IconButton / Selector /
10
- * ToggleButton / Divider / Dialog / TextInput / Button / Layout primitives.
10
+ * ToggleButton / Divider / Popover / TextInput / Layout primitives.
11
11
  * @output Exports RichTextEditorToolbar (a compact formatting toolbar with a
12
- * RichText-owned 4px control gutter and horizontally scrollable action row)
13
- * and RichTextEditorToolbarProps.
12
+ * RichText-owned 4px control gutter, a horizontally scrollable action row,
13
+ * and a link popover anchored to its Link button) and
14
+ * RichTextEditorToolbarProps.
14
15
  * @position @astryxdesign/richtext. Drop into RichTextEditor's `toolbar` slot to
15
16
  * add a flush top formatting toolbar. Themed via Astryx Toolbar, Selector,
16
17
  * IconButton, and ToggleButton, so it inherits the active theme. Base props
@@ -42,9 +43,9 @@ import {
42
43
  useEffect,
43
44
  useRef,
44
45
  useState,
45
- type FormEvent,
46
46
  type ReactNode,
47
47
  type Ref,
48
+ type RefObject,
48
49
  } from 'react';
49
50
  import * as stylex from '@stylexjs/stylex';
50
51
  import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
@@ -70,19 +71,12 @@ import {IconButton} from '@astryxdesign/core/IconButton';
70
71
  import {Selector, type SelectorOptionType} from '@astryxdesign/core/Selector';
71
72
  import {ToggleButton} from '@astryxdesign/core/ToggleButton';
72
73
  import {Divider} from '@astryxdesign/core/Divider';
73
- import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
74
+ import {Popover} from '@astryxdesign/core/Popover';
74
75
  import {TextInput} from '@astryxdesign/core/TextInput';
75
- import {Button} from '@astryxdesign/core/Button';
76
- import {Stack} from '@astryxdesign/core/Stack';
77
- import {
78
- HStack,
79
- Layout,
80
- LayoutContent,
81
- LayoutFooter,
82
- } from '@astryxdesign/core/Layout';
83
- import {getExtendedIcon} from '@astryxdesign/core/Icon';
76
+ import {HStack, StackItem} from '@astryxdesign/core/Layout';
77
+ import {Icon, getExtendedIcon} from '@astryxdesign/core/Icon';
84
78
  import {useThemeName} from '@astryxdesign/core/theme';
85
- import {isRenderable, rtlStyles} from '@astryxdesign/core/utils';
79
+ import {isImeKeyEvent, isRenderable, rtlStyles} from '@astryxdesign/core/utils';
86
80
  import {
87
81
  fontWeightVars,
88
82
  spacingVars,
@@ -129,6 +123,15 @@ interface LinkContext {
129
123
  isLink: boolean;
130
124
  }
131
125
 
126
+ // The link popover's anchor: a box around the Link button that takes no
127
+ // space of its own.
128
+ const linkAnchorStyles = stylex.create({
129
+ wrapper: {
130
+ display: 'inline-flex',
131
+ flexShrink: 0,
132
+ },
133
+ });
134
+
132
135
  // A vertical Divider's default 100% height needs a definite parent height.
133
136
  // Toolbar slots are sized by their controls instead, so let flexbox stretch
134
137
  // these group separators across the slot's resolved height.
@@ -455,6 +458,145 @@ function DirectionalGlyph({children}: {children: ReactNode}) {
455
458
  );
456
459
  }
457
460
 
461
+ /**
462
+ * Remove's glyph. No shared icon name means "unlink", so it is fixed
463
+ * component artwork until component icon slots exist.
464
+ */
465
+ const REMOVE_LINK_GLYPH = (
466
+ <svg
467
+ width="16"
468
+ height="16"
469
+ viewBox="0 0 24 24"
470
+ fill="none"
471
+ aria-hidden="true">
472
+ <path
473
+ d="M18 13l2-2a5 5 0 0 0-7-7l-2 2M6 11l-2 2a5 5 0 0 0 7 7l2-2M8 2v3M2 8h3M16 22v-3M22 16h-3"
474
+ stroke="currentColor"
475
+ strokeWidth="2"
476
+ strokeLinecap="round"
477
+ strokeLinejoin="round"
478
+ />
479
+ </svg>
480
+ );
481
+
482
+ /** Room for a typical address beside the link form's icon buttons. */
483
+ const LINK_POPOVER_WIDTH = 320;
484
+
485
+ interface ToolbarLinkFormProps {
486
+ /** The field's value: the address being entered. */
487
+ url: string;
488
+ /** The message for an address the toolbar refused, or empty. */
489
+ error: string;
490
+ /** Whether the selection is in a link, which Remove then unlinks. */
491
+ isEditing: boolean;
492
+ /** The toolbar's size, so the form's controls match its buttons. */
493
+ size: 'sm' | 'md' | 'lg';
494
+ onUrlChange: (url: string) => void;
495
+ /** Applies the field's address; false when it was refused. */
496
+ onApply: () => boolean;
497
+ onRemove: () => void;
498
+ onCancel: () => void;
499
+ }
500
+
501
+ /**
502
+ * The link popover's content: one URL field, then Apply, Remove (only when
503
+ * the selection is in a link), and Cancel as icon buttons. Enter in the field
504
+ * applies, and Escape anywhere in the form cancels. A refused address shows
505
+ * the field's error status and keeps focus in the field.
506
+ */
507
+ function ToolbarLinkForm({
508
+ url,
509
+ error,
510
+ isEditing,
511
+ size,
512
+ onUrlChange,
513
+ onApply,
514
+ onRemove,
515
+ onCancel,
516
+ }: ToolbarLinkFormProps) {
517
+ const t = useTranslator();
518
+ const inputRef = useRef<HTMLInputElement | null>(null);
519
+ const apply = () => {
520
+ if (!onApply()) {
521
+ inputRef.current?.focus();
522
+ }
523
+ };
524
+ const applyLabel = isEditing
525
+ ? t('@astryx.richTextEditor.link.update')
526
+ : t('@astryx.richTextEditor.link.add');
527
+ const removeLabel = t('@astryx.richTextEditor.link.remove');
528
+ const cancelLabel = t('@astryx.richTextEditor.link.cancel');
529
+ return (
530
+ <HStack
531
+ gap={1}
532
+ vAlign="start"
533
+ onKeyDown={event => {
534
+ // Escape that ends an IME composition is the input method's.
535
+ if (event.key === 'Escape' && !isImeKeyEvent(event.nativeEvent)) {
536
+ // Claimed here, so the popover's own Escape handling leaves it to
537
+ // Cancel, which also gives the editor back its selection.
538
+ event.preventDefault();
539
+ onCancel();
540
+ }
541
+ }}>
542
+ <StackItem size="fill">
543
+ <TextInput
544
+ ref={inputRef}
545
+ label={t('@astryx.richTextEditor.link.url')}
546
+ isLabelHidden
547
+ value={url}
548
+ size={size}
549
+ width="100%"
550
+ autoComplete="url"
551
+ // A URL keyboard on touch screens and no spelling marks under an
552
+ // address. The field stays plain text, so a bare domain reaches
553
+ // the toolbar's own check, which makes it an https link.
554
+ inputMode="url"
555
+ hasSpellCheck={false}
556
+ placeholder={t('@astryx.richTextEditor.link.urlPlaceholder')}
557
+ status={error ? {type: 'error', message: error} : undefined}
558
+ statusVariant="detached"
559
+ onChange={onUrlChange}
560
+ onEnter={apply}
561
+ onKeyDown={event => {
562
+ // Applying hands focus to the editor, which must not receive the
563
+ // rest of this Enter as a new line over the linked words.
564
+ if (event.key === 'Enter' && !isImeKeyEvent(event.nativeEvent)) {
565
+ event.preventDefault();
566
+ }
567
+ }}
568
+ />
569
+ </StackItem>
570
+ <IconButton
571
+ label={applyLabel}
572
+ icon={<Icon icon="check" />}
573
+ variant="ghost"
574
+ size={size}
575
+ tooltip={applyLabel}
576
+ onClick={apply}
577
+ />
578
+ {isEditing && (
579
+ <IconButton
580
+ label={removeLabel}
581
+ icon={REMOVE_LINK_GLYPH}
582
+ variant="ghost"
583
+ size={size}
584
+ tooltip={removeLabel}
585
+ onClick={onRemove}
586
+ />
587
+ )}
588
+ <IconButton
589
+ label={cancelLabel}
590
+ icon={<Icon icon="close" />}
591
+ variant="ghost"
592
+ size={size}
593
+ tooltip={cancelLabel}
594
+ onClick={onCancel}
595
+ />
596
+ </HStack>
597
+ );
598
+ }
599
+
458
600
  export interface RichTextEditorToolbarProps extends BaseProps<HTMLDivElement> {
459
601
  /**
460
602
  * Ref to the toolbar's root element. Base props pass through to the
@@ -481,11 +623,14 @@ export interface RichTextEditorToolbarProps extends BaseProps<HTMLDivElement> {
481
623
  */
482
624
  size?: 'sm' | 'md' | 'lg';
483
625
  /**
484
- * Whether to show the insert/edit-link button. By default, pressing it opens
485
- * an Astryx Dialog. The form can add, update, or remove a link without
486
- * losing the editor selection. With a collapsed selection, Insert link
487
- * inserts the entered URL as link text at the caret; with a non-empty
488
- * selection it links the selected text.
626
+ * Whether to show the insert/edit-link button. By default, pressing it (or
627
+ * Cmd/Ctrl+K in the editor) opens an Astryx Popover anchored to the button:
628
+ * one URL field, applied with Enter, with Remove when the selection is in a
629
+ * link. The popover is not modal. Escape or Cancel closes it and returns
630
+ * focus and the selection to the editor; a URL that cannot be linked shows
631
+ * an error under the field, which keeps focus. With a collapsed selection,
632
+ * applying inserts the entered URL as link text at the caret; with a
633
+ * non-empty selection it links the selected text.
489
634
  *
490
635
  * Requires `LinkNode` to be registered (it is, by default) — no extra setup.
491
636
  * The entered URL is sanitized (see `sanitizeUrl`) so only
@@ -497,7 +642,7 @@ export interface RichTextEditorToolbarProps extends BaseProps<HTMLDivElement> {
497
642
  * Called to obtain a URL when the link button is pressed on a non-link
498
643
  * selection. Return the URL string to link, or `null`/`''` to cancel.
499
644
  * Receives the currently selected text as a hint. When omitted, the built-in
500
- * Astryx Dialog is used. This synchronous override is retained
645
+ * link popover is used. This synchronous override is retained
501
646
  * for consumers that already provide their own URL UI.
502
647
  */
503
648
  promptForUrl?: (selectedText: string) => string | null | undefined;
@@ -580,7 +725,9 @@ export function RichTextEditorToolbar({
580
725
  url: '',
581
726
  isLink: false,
582
727
  });
583
- const [isLinkDialogOpen, setIsLinkDialogOpen] = useState(false);
728
+ const linkButtonRef = useRef<HTMLButtonElement>(null);
729
+ const linkAnchorRef = useRef<HTMLSpanElement>(null);
730
+ const [isLinkPopoverOpen, setIsLinkPopoverOpen] = useState(false);
584
731
  const [isEditingLink, setIsEditingLink] = useState(false);
585
732
  const [linkUrl, setLinkUrl] = useState('');
586
733
  const [linkError, setLinkError] = useState('');
@@ -749,15 +896,22 @@ export function RichTextEditorToolbar({
749
896
  return;
750
897
  }
751
898
 
899
+ // The field starts from the link's address, or from selected text that
900
+ // already reads as one; otherwise it is empty and shows its placeholder.
752
901
  setLinkUrl(
753
902
  context.url ||
754
- (context.selectedText.startsWith('http')
755
- ? context.selectedText
756
- : 'https://'),
903
+ (context.selectedText.startsWith('http') ? context.selectedText : ''),
757
904
  );
758
905
  setIsEditingLink(context.isLink);
759
906
  setLinkError('');
760
- setIsLinkDialogOpen(true);
907
+ // Cmd/Ctrl+K can open the form while the Link button is scrolled out of
908
+ // view, in the page or in the toolbar's own row. Bring it back so the
909
+ // popover opens beside it.
910
+ linkButtonRef.current?.scrollIntoView?.({
911
+ block: 'nearest',
912
+ inline: 'nearest',
913
+ });
914
+ setIsLinkPopoverOpen(true);
761
915
  }, [
762
916
  applyLinkValue,
763
917
  editor,
@@ -766,34 +920,52 @@ export function RichTextEditorToolbar({
766
920
  restoreLinkSelection,
767
921
  ]);
768
922
 
769
- const handleLinkDialogOpenChange = useCallback((open: boolean) => {
770
- setIsLinkDialogOpen(open);
923
+ const closeLinkPopover = useCallback(() => {
924
+ setIsLinkPopoverOpen(false);
771
925
  setLinkError('');
772
926
  }, []);
773
927
 
774
- const closeLinkDialogToEditor = useCallback(() => {
775
- setIsLinkDialogOpen(false);
776
- setLinkError('');
777
- requestAnimationFrame(() => editor.focus());
778
- }, [editor]);
779
-
780
- const handleLinkSubmit = useCallback(
781
- (event: FormEvent<HTMLElement>) => {
782
- event.preventDefault();
783
- if (!applyLinkValue(linkUrl)) {
784
- setLinkError(t('@astryx.richTextEditor.link.invalidUrl'));
785
- return;
928
+ // The popover reports its own opening (a press on the Link button) and its
929
+ // closing (a press outside it).
930
+ const handleLinkPopoverOpenChange = useCallback(
931
+ (open: boolean) => {
932
+ if (open) {
933
+ toggleLink();
934
+ } else {
935
+ closeLinkPopover();
786
936
  }
787
- closeLinkDialogToEditor();
788
937
  },
789
- [applyLinkValue, closeLinkDialogToEditor, linkUrl, t],
938
+ [closeLinkPopover, toggleLink],
790
939
  );
791
940
 
941
+ // Closes the popover and gives the editor back its focus. The editable root
942
+ // takes focus first and Lexical then draws its selection into it, so the
943
+ // selection survives the field having held the page's selection.
944
+ const closeLinkPopoverToEditor = useCallback(() => {
945
+ closeLinkPopover();
946
+ editor.getRootElement()?.focus({preventScroll: true});
947
+ editor.focus();
948
+ }, [closeLinkPopover, editor]);
949
+
950
+ const cancelLinkPopover = useCallback(() => {
951
+ restoreLinkSelection();
952
+ closeLinkPopoverToEditor();
953
+ }, [closeLinkPopoverToEditor, restoreLinkSelection]);
954
+
955
+ const applyLink = useCallback((): boolean => {
956
+ if (!applyLinkValue(linkUrl)) {
957
+ setLinkError(t('@astryx.richTextEditor.link.invalidUrl'));
958
+ return false;
959
+ }
960
+ closeLinkPopoverToEditor();
961
+ return true;
962
+ }, [applyLinkValue, closeLinkPopoverToEditor, linkUrl, t]);
963
+
792
964
  const removeLink = useCallback(() => {
793
965
  restoreLinkSelection();
794
966
  editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
795
- closeLinkDialogToEditor();
796
- }, [closeLinkDialogToEditor, editor, restoreLinkSelection]);
967
+ closeLinkPopoverToEditor();
968
+ }, [closeLinkPopoverToEditor, editor, restoreLinkSelection]);
797
969
 
798
970
  useEffect(() => {
799
971
  return mergeRegister(
@@ -985,19 +1157,26 @@ export function RichTextEditorToolbar({
985
1157
  />
986
1158
  ))}
987
1159
  {hasLink && (
988
- <ToggleButton
1160
+ // The popover anchors to this wrapper, which a press never
1161
+ // scales, and finds the button inside it for its handlers.
1162
+ <span
989
1163
  key="link"
990
- label={t('@astryx.richTextEditor.toolbar.link')}
991
- icon={icon('link')}
992
- size={size}
993
- isIconOnly
994
- isPressed={isLink || isLinkDialogOpen}
995
- isDisabled={!isEditable}
996
- aria-haspopup="dialog"
997
- aria-expanded={isLinkDialogOpen}
998
- onMouseDown={event => event.preventDefault()}
999
- onPressedChange={toggleLink}
1000
- />
1164
+ ref={linkAnchorRef}
1165
+ {...stylex.props(linkAnchorStyles.wrapper)}>
1166
+ <ToggleButton
1167
+ ref={linkButtonRef}
1168
+ label={t('@astryx.richTextEditor.toolbar.link')}
1169
+ icon={icon('link')}
1170
+ size={size}
1171
+ isIconOnly
1172
+ isPressed={isLink || isLinkPopoverOpen}
1173
+ isDisabled={!isEditable}
1174
+ onMouseDown={event => event.preventDefault()}
1175
+ // The link popover owns a press on the button, and with it
1176
+ // the button's popup state; `promptForUrl` replaces both.
1177
+ onPressedChange={promptForUrl ? toggleLink : undefined}
1178
+ />
1179
+ </span>
1001
1180
  )}
1002
1181
  {isRenderable(endContent) && (
1003
1182
  <>
@@ -1008,75 +1187,47 @@ export function RichTextEditorToolbar({
1008
1187
  </HStack>
1009
1188
  }
1010
1189
  />
1011
- {hasLink && (
1012
- <Dialog
1013
- isOpen={isLinkDialogOpen}
1014
- onOpenChange={handleLinkDialogOpenChange}
1015
- purpose="form"
1016
- width={400}>
1017
- <Stack as="form" onSubmit={handleLinkSubmit}>
1018
- <Layout
1019
- height="auto"
1020
- header={
1021
- <DialogHeader
1022
- title={
1023
- isEditingLink
1024
- ? t('@astryx.richTextEditor.link.editTitle')
1025
- : t('@astryx.richTextEditor.link.insertTitle')
1026
- }
1027
- onOpenChange={handleLinkDialogOpenChange}
1028
- />
1029
- }
1030
- content={
1031
- <LayoutContent>
1032
- <TextInput
1033
- label={t('@astryx.richTextEditor.link.url')}
1034
- value={linkUrl}
1035
- width="100%"
1036
- hasAutoFocus
1037
- status={
1038
- linkError
1039
- ? {type: 'error', message: linkError}
1040
- : undefined
1041
- }
1042
- statusVariant="detached"
1043
- onChange={value => {
1044
- setLinkUrl(value);
1045
- setLinkError('');
1046
- }}
1047
- />
1048
- </LayoutContent>
1049
- }
1050
- footer={
1051
- <LayoutFooter>
1052
- <HStack gap={2} hAlign="end">
1053
- {isEditingLink && (
1054
- <Button
1055
- label={t('@astryx.richTextEditor.link.remove')}
1056
- variant="destructive"
1057
- onClick={removeLink}
1058
- />
1059
- )}
1060
- <Button
1061
- label={t('@astryx.richTextEditor.link.cancel')}
1062
- variant="secondary"
1063
- onClick={() => handleLinkDialogOpenChange(false)}
1064
- />
1065
- <Button
1066
- label={
1067
- isEditingLink
1068
- ? t('@astryx.richTextEditor.link.update')
1069
- : t('@astryx.richTextEditor.link.add')
1070
- }
1071
- variant="primary"
1072
- type="submit"
1073
- />
1074
- </HStack>
1075
- </LayoutFooter>
1076
- }
1077
- />
1078
- </Stack>
1079
- </Dialog>
1190
+ {/* A sibling of the toolbar, not inside it: the toolbar is one roving
1191
+ tab stop, which would leave the form's controls out of Tab. */}
1192
+ {hasLink && promptForUrl == null && (
1193
+ <Popover
1194
+ anchorRef={linkAnchorRef as RefObject<HTMLElement>}
1195
+ label={
1196
+ isEditingLink
1197
+ ? t('@astryx.richTextEditor.link.editTitle')
1198
+ : t('@astryx.richTextEditor.link.insertTitle')
1199
+ }
1200
+ isOpen={isLinkPopoverOpen}
1201
+ onOpenChange={handleLinkPopoverOpenChange}
1202
+ isModal={false}
1203
+ // Popover's focus entry focuses the URL field, the form's first
1204
+ // control. Cancel is its close control.
1205
+ hasCloseButton={false}
1206
+ // Above the toolbar, so the popover does not cover the editor's
1207
+ // first lines, where the linked words often are. It flips below
1208
+ // only when there is no room above.
1209
+ placement="above"
1210
+ alignment="start"
1211
+ width={LINK_POPOVER_WIDTH}
1212
+ padding={2}
1213
+ content={
1214
+ isLinkPopoverOpen ? (
1215
+ <ToolbarLinkForm
1216
+ url={linkUrl}
1217
+ error={linkError}
1218
+ isEditing={isEditingLink}
1219
+ size={size}
1220
+ onUrlChange={value => {
1221
+ setLinkUrl(value);
1222
+ setLinkError('');
1223
+ }}
1224
+ onApply={applyLink}
1225
+ onRemove={removeLink}
1226
+ onCancel={cancelLinkPopover}
1227
+ />
1228
+ ) : null
1229
+ }
1230
+ />
1080
1231
  )}
1081
1232
  </>
1082
1233
  );
package/src/linkUtils.ts CHANGED
@@ -50,9 +50,18 @@ export const URL_MATCHER =
50
50
  export const EMAIL_MATCHER =
51
51
  /((?<![^<>()[\]\\,;:\s@"])[^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*|("[^"\r\n]+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
52
52
 
53
+ /**
54
+ * A host with a port also looks like a scheme (`example.com:`).
55
+ * The host needs a dot or is `localhost`, so `tel:911` keeps its scheme.
56
+ */
57
+ const HOST_WITH_PORT =
58
+ /^(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+):\d{1,5}(?:[/?#]|$)/i;
59
+
53
60
  /** Prepend a default `https://` scheme to a bare host so it parses as absolute. */
54
61
  function withDefaultScheme(url: string): string {
55
- return HAS_SCHEME.test(url) ? url : `https://${url}`;
62
+ return HAS_SCHEME.test(url) && !HOST_WITH_PORT.test(url)
63
+ ? url
64
+ : `https://${url}`;
56
65
  }
57
66
 
58
67
  /**