tldraw 5.6.0 → 5.6.2

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 (90) hide show
  1. package/DOCS.md +21 -9
  2. package/RELEASE_NOTES.md +161 -3
  3. package/dist-cjs/index.d.ts +31 -1
  4. package/dist-cjs/index.js +4 -1
  5. package/dist-cjs/index.js.map +2 -2
  6. package/dist-cjs/lib/shapes/bookmark/BookmarkShapeUtil.js +11 -4
  7. package/dist-cjs/lib/shapes/bookmark/BookmarkShapeUtil.js.map +2 -2
  8. package/dist-cjs/lib/shapes/bookmark/bookmarks.js +25 -4
  9. package/dist-cjs/lib/shapes/bookmark/bookmarks.js.map +2 -2
  10. package/dist-cjs/lib/shapes/shared/HyperlinkButton.js +4 -0
  11. package/dist-cjs/lib/shapes/shared/HyperlinkButton.js.map +2 -2
  12. package/dist-cjs/lib/shapes/shared/RichTextLabel.js +13 -1
  13. package/dist-cjs/lib/shapes/shared/RichTextLabel.js.map +2 -2
  14. package/dist-cjs/lib/shapes/shared/useOpenLinkHandler.js +38 -0
  15. package/dist-cjs/lib/shapes/shared/useOpenLinkHandler.js.map +7 -0
  16. package/dist-cjs/lib/ui/components/ConfirmOpenLinkDialog.js +57 -0
  17. package/dist-cjs/lib/ui/components/ConfirmOpenLinkDialog.js.map +7 -0
  18. package/dist-cjs/lib/ui/components/EditLinkDialog.js +15 -17
  19. package/dist-cjs/lib/ui/components/EditLinkDialog.js.map +2 -2
  20. package/dist-cjs/lib/ui/components/Toolbar/LinkEditor.js +47 -19
  21. package/dist-cjs/lib/ui/components/Toolbar/LinkEditor.js.map +3 -3
  22. package/dist-cjs/lib/ui/context/actions.js +2 -1
  23. package/dist-cjs/lib/ui/context/actions.js.map +2 -2
  24. package/dist-cjs/lib/ui/hooks/useEditorEvents.js +12 -1
  25. package/dist-cjs/lib/ui/hooks/useEditorEvents.js.map +2 -2
  26. package/dist-cjs/lib/ui/hooks/useTranslation/TLUiTranslationKey.js.map +1 -1
  27. package/dist-cjs/lib/ui/version.js +2 -2
  28. package/dist-cjs/lib/ui/version.js.map +1 -1
  29. package/dist-cjs/lib/utils/linkUrl.js +39 -0
  30. package/dist-cjs/lib/utils/linkUrl.js.map +7 -0
  31. package/dist-cjs/lib/utils/openLink.js +68 -0
  32. package/dist-cjs/lib/utils/openLink.js.map +7 -0
  33. package/dist-cjs/lib/utils/text/richText.js +4 -1
  34. package/dist-cjs/lib/utils/text/richText.js.map +2 -2
  35. package/dist-esm/index.d.mts +31 -1
  36. package/dist-esm/index.mjs +4 -1
  37. package/dist-esm/index.mjs.map +2 -2
  38. package/dist-esm/lib/shapes/bookmark/BookmarkShapeUtil.mjs +12 -4
  39. package/dist-esm/lib/shapes/bookmark/BookmarkShapeUtil.mjs.map +2 -2
  40. package/dist-esm/lib/shapes/bookmark/bookmarks.mjs +25 -4
  41. package/dist-esm/lib/shapes/bookmark/bookmarks.mjs.map +2 -2
  42. package/dist-esm/lib/shapes/shared/HyperlinkButton.mjs +4 -0
  43. package/dist-esm/lib/shapes/shared/HyperlinkButton.mjs.map +2 -2
  44. package/dist-esm/lib/shapes/shared/RichTextLabel.mjs +13 -2
  45. package/dist-esm/lib/shapes/shared/RichTextLabel.mjs.map +2 -2
  46. package/dist-esm/lib/shapes/shared/useOpenLinkHandler.mjs +18 -0
  47. package/dist-esm/lib/shapes/shared/useOpenLinkHandler.mjs.map +7 -0
  48. package/dist-esm/lib/ui/components/ConfirmOpenLinkDialog.mjs +43 -0
  49. package/dist-esm/lib/ui/components/ConfirmOpenLinkDialog.mjs.map +7 -0
  50. package/dist-esm/lib/ui/components/EditLinkDialog.mjs +16 -18
  51. package/dist-esm/lib/ui/components/EditLinkDialog.mjs.map +2 -2
  52. package/dist-esm/lib/ui/components/Toolbar/LinkEditor.mjs +38 -20
  53. package/dist-esm/lib/ui/components/Toolbar/LinkEditor.mjs.map +2 -2
  54. package/dist-esm/lib/ui/context/actions.mjs +2 -1
  55. package/dist-esm/lib/ui/context/actions.mjs.map +2 -2
  56. package/dist-esm/lib/ui/hooks/useEditorEvents.mjs +13 -2
  57. package/dist-esm/lib/ui/hooks/useEditorEvents.mjs.map +2 -2
  58. package/dist-esm/lib/ui/version.mjs +2 -2
  59. package/dist-esm/lib/ui/version.mjs.map +1 -1
  60. package/dist-esm/lib/utils/linkUrl.mjs +19 -0
  61. package/dist-esm/lib/utils/linkUrl.mjs.map +7 -0
  62. package/dist-esm/lib/utils/openLink.mjs +48 -0
  63. package/dist-esm/lib/utils/openLink.mjs.map +7 -0
  64. package/dist-esm/lib/utils/text/richText.mjs +5 -1
  65. package/dist-esm/lib/utils/text/richText.mjs.map +2 -2
  66. package/package.json +6 -6
  67. package/src/index.ts +1 -0
  68. package/src/lib/shapes/bookmark/BookmarkShapeUtil.tsx +12 -6
  69. package/src/lib/shapes/bookmark/bookmarks.ts +38 -5
  70. package/src/lib/shapes/shared/HyperlinkButton.tsx +4 -0
  71. package/src/lib/shapes/shared/RichTextLabel.tsx +18 -2
  72. package/src/lib/shapes/shared/useOpenLinkHandler.ts +20 -0
  73. package/src/lib/ui/components/ConfirmOpenLinkDialog.tsx +53 -0
  74. package/src/lib/ui/components/EditLinkDialog.tsx +22 -26
  75. package/src/lib/ui/components/Toolbar/LinkEditor.tsx +40 -21
  76. package/src/lib/ui/context/actions.tsx +2 -1
  77. package/src/lib/ui/hooks/useEditorEvents.ts +14 -2
  78. package/src/lib/ui/hooks/useTranslation/TLUiTranslationKey.ts +4 -0
  79. package/src/lib/ui/version.ts +2 -2
  80. package/src/lib/ui.css +19 -2
  81. package/src/lib/utils/linkUrl.test.ts +33 -0
  82. package/src/lib/utils/linkUrl.ts +30 -0
  83. package/src/lib/utils/openLink.test.ts +83 -0
  84. package/src/lib/utils/openLink.ts +75 -0
  85. package/src/lib/utils/text/richText.ts +4 -0
  86. package/src/test/bookmark-shapes.test.ts +62 -2
  87. package/src/test/ui/ConfirmOpenLinkDialog.test.tsx +128 -0
  88. package/src/test/ui/EditLinkDialog.test.tsx +53 -2
  89. package/src/test/ui/LinkEditor.test.tsx +71 -0
  90. package/tldraw.css +19 -2
@@ -1,5 +1,6 @@
1
- import { defineMessages, T, TLShape, track, useEditor } from '@tldraw/editor'
1
+ import { defineMessages, TLShape, track, useEditor } from '@tldraw/editor'
2
2
  import { useCallback, useEffect, useRef, useState } from 'react'
3
+ import { normalizeLinkUrl } from '../../utils/linkUrl'
3
4
  import { isShapeWithLink, TLShapeWithLink } from '../../utils/shapes/shapes'
4
5
  import { TLUiDialogProps } from '../context/dialogs'
5
6
  import { F } from '../context/i18n'
@@ -14,22 +15,9 @@ import {
14
15
  } from './primitives/TldrawUiDialog'
15
16
  import { TldrawUiInput } from './primitives/TldrawUiInput'
16
17
 
17
- // A url can either be invalid, or valid with a protocol, or valid without a protocol.
18
- // For example, "aol.com" would be valid with a protocol ()
19
- function validateUrl(url: string) {
20
- if (T.linkUrl.isValid(url)) {
21
- return { isValid: true, hasProtocol: true }
22
- }
23
- if (T.linkUrl.isValid('https://' + url)) {
24
- return { isValid: true, hasProtocol: false }
25
- }
26
- return { isValid: false, hasProtocol: false }
27
- }
28
-
29
18
  function getUrlInputState(url: string) {
30
- const { isValid, hasProtocol } = validateUrl(url)
31
- const safe = isValid ? (hasProtocol ? url : 'https://' + url) : 'https://'
32
- return { actual: url, safe, valid: isValid }
19
+ const normalized = normalizeLinkUrl(url)
20
+ return { actual: url, safe: normalized ?? '', valid: normalized !== null }
33
21
  }
34
22
 
35
23
  function assertShapeWithLink(shape: TLShape | null | undefined): asserts shape is TLShapeWithLink {
@@ -81,10 +69,11 @@ export const EditLinkDialogInner = track(function EditLinkDialogInner({
81
69
  return { actual: safe, safe, valid: true }
82
70
  })
83
71
 
72
+ const [showInvalid, setShowInvalid] = useState(false)
73
+
84
74
  const handleChange = useCallback((rawValue: string) => {
85
- // Just auto-correct double https:// from a bad paste.
86
- const fixedRawValue = rawValue.replace(/https?:\/\/(https?:\/\/)/, '$1')
87
- setUrlInputState(getUrlInputState(fixedRawValue))
75
+ setUrlInputState(getUrlInputState(rawValue))
76
+ setShowInvalid(false)
88
77
  }, [])
89
78
 
90
79
  const handleClear = useCallback(() => {
@@ -103,7 +92,13 @@ export const EditLinkDialogInner = track(function EditLinkDialogInner({
103
92
  if (!onlySelectedShape) return
104
93
  assertShapeWithLink(onlySelectedShape)
105
94
 
106
- // Here would be a good place to validate the next shape—would setting the empty
95
+ // Enter reaches here even while the save button is disabled.
96
+ if (!urlInputState.valid) {
97
+ setShowInvalid(true)
98
+ rInput.current?.focus()
99
+ return
100
+ }
101
+
107
102
  if (onlySelectedShape.props.url !== urlInputState.safe) {
108
103
  editor.updateShapes([
109
104
  {
@@ -120,8 +115,9 @@ export const EditLinkDialogInner = track(function EditLinkDialogInner({
120
115
  onClose()
121
116
  }, [onClose])
122
117
 
123
- // Are we going from a valid state to an invalid state?
124
- const isRemoving = rInitialValue.current && !urlInputState.valid
118
+ const isEmpty = urlInputState.valid && urlInputState.safe === ''
119
+ // Only an empty field clears a link, so a typo can't delete it.
120
+ const isRemoving = !!rInitialValue.current && isEmpty
125
121
 
126
122
  return (
127
123
  <>
@@ -146,10 +142,10 @@ export const EditLinkDialogInner = track(function EditLinkDialogInner({
146
142
  onCancel={handleCancel}
147
143
  />
148
144
  <div>
149
- {urlInputState.valid ? (
150
- <F defaultMessage="Links will open in a new tab." id="edit-link-dialog.detail" />
151
- ) : (
145
+ {showInvalid ? (
152
146
  <F defaultMessage="A link must be a valid URL." id="edit-link-dialog.invalid-url" />
147
+ ) : (
148
+ <F defaultMessage="Links will open in a new tab." id="edit-link-dialog.detail" />
153
149
  )}
154
150
  </div>
155
151
  </div>
@@ -169,7 +165,7 @@ export const EditLinkDialogInner = track(function EditLinkDialogInner({
169
165
  ) : (
170
166
  <TldrawUiButton
171
167
  type="primary"
172
- disabled={!urlInputState.valid}
168
+ disabled={!urlInputState.valid || isEmpty}
173
169
  onTouchEnd={handleComplete}
174
170
  onClick={handleComplete}
175
171
  >
@@ -1,5 +1,8 @@
1
- import { defineMessages, openWindow, preventDefault, TiptapEditor, useEditor } from '@tldraw/editor'
1
+ import { defineMessages, preventDefault, TiptapEditor, useEditor } from '@tldraw/editor'
2
+ import classNames from 'classnames'
2
3
  import { useCallback, useEffect, useRef, useState } from 'react'
4
+ import { normalizeLinkUrl } from '../../../utils/linkUrl'
5
+ import { openLink } from '../../../utils/openLink'
3
6
  import { useUiEvents } from '../../context/events'
4
7
  import { useTranslation } from '../../hooks/useTranslation/useTranslation'
5
8
  import { TldrawUiButton } from '../primitives/Button/TldrawUiButton'
@@ -22,20 +25,34 @@ export interface LinkEditorProps {
22
25
  export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEditorProps) {
23
26
  const editor = useEditor()
24
27
  const [value, setValue] = useState(initialValue)
28
+ const [isInvalid, setIsInvalid] = useState(false)
25
29
  const msg = useTranslation()
26
30
  const ref = useRef<HTMLInputElement>(null)
27
31
  const trackEvent = useUiEvents()
28
32
  const source = 'rich-text-menu'
29
- const linkifiedValue = value.startsWith('http') ? value : `https://${value}`
33
+ const normalizedValue = normalizeLinkUrl(value)
34
+
35
+ const handleRemoveLink = useCallback(() => {
36
+ trackEvent('rich-text', { operation: 'link-remove', source })
37
+ textEditor.chain().unsetLink().focus().run()
38
+ onClose()
39
+ }, [trackEvent, source, textEditor, onClose])
30
40
 
31
41
  const handleLinkComplete = useCallback(
32
42
  (link: string) => {
33
- trackEvent('rich-text', { operation: 'link-edit', source })
34
- if (!link.startsWith('http://') && !link.startsWith('https://')) {
35
- link = `https://${link}`
43
+ const href = normalizeLinkUrl(link)
44
+ if (href === null) {
45
+ setIsInvalid(true)
46
+ ref.current?.focus()
47
+ return
48
+ }
49
+ if (href === '') {
50
+ handleRemoveLink()
51
+ return
36
52
  }
37
53
 
38
- textEditor.chain().setLink({ href: link }).run()
54
+ trackEvent('rich-text', { operation: 'link-edit', source })
55
+ textEditor.chain().setLink({ href }).run()
39
56
  // N.B. We shouldn't focus() on mobile because it causes the
40
57
  // Return key to replace the link with a newline :facepalm:
41
58
  if (editor.getInstanceState().isCoarsePointer) {
@@ -45,38 +62,32 @@ export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEdi
45
62
  }
46
63
  onClose()
47
64
  },
48
- [trackEvent, source, textEditor, editor, onClose]
65
+ [trackEvent, source, textEditor, editor, onClose, handleRemoveLink]
49
66
  )
50
67
 
51
68
  const handleVisitLink = () => {
52
69
  trackEvent('rich-text', { operation: 'link-visit', source })
53
- openWindow(linkifiedValue, '_blank')
70
+ if (normalizedValue) openLink(editor, normalizedValue)
54
71
  onClose()
55
72
  }
56
73
 
57
- const handleRemoveLink = useCallback(() => {
58
- trackEvent('rich-text', { operation: 'link-remove', source })
59
- textEditor.chain().unsetLink().focus().run()
60
- onClose()
61
- }, [trackEvent, source, textEditor, onClose])
62
-
63
74
  useEffect(() => {
64
75
  const doc = editor.getContainerDocument()
65
76
  const handlePointerDown = (e: PointerEvent) => {
66
77
  const toolbar = doc.querySelector('.tlui-rich-text__toolbar')
67
78
  if (toolbar?.contains(e.target as Node)) return
68
79
  // If the pointer down is not in the toolbar, complete the link
69
- if (value) {
70
- handleLinkComplete(value)
80
+ if (normalizedValue === null) {
81
+ onClose()
71
82
  } else {
72
- handleRemoveLink()
83
+ handleLinkComplete(value)
73
84
  }
74
85
  }
75
86
  doc.addEventListener('pointerdown', handlePointerDown, { capture: true })
76
87
  return () => {
77
88
  doc.removeEventListener('pointerdown', handlePointerDown, { capture: true })
78
89
  }
79
- }, [editor, handleLinkComplete, handleRemoveLink, value])
90
+ }, [editor, handleLinkComplete, onClose, normalizedValue, value])
80
91
 
81
92
  useEffect(() => {
82
93
  ref.current?.focus()
@@ -84,16 +95,24 @@ export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEdi
84
95
 
85
96
  useEffect(() => {
86
97
  setValue(initialValue)
98
+ setIsInvalid(false)
87
99
  }, [initialValue])
88
100
 
101
+ const handleValueChange = useCallback((nextValue: string) => {
102
+ setValue(nextValue)
103
+ setIsInvalid(false)
104
+ }, [])
105
+
89
106
  return (
90
107
  <>
91
108
  <TldrawUiInput
92
109
  ref={ref}
93
110
  data-testid="rich-text.link-input"
94
- className="tlui-rich-text__toolbar-link-input"
111
+ className={classNames('tlui-rich-text__toolbar-link-input', {
112
+ 'tlui-rich-text__toolbar-link-input--invalid': isInvalid,
113
+ })}
95
114
  value={value}
96
- onValueChange={setValue}
115
+ onValueChange={handleValueChange}
97
116
  onComplete={handleLinkComplete}
98
117
  onCancel={onClose}
99
118
  placeholder="example.com"
@@ -105,7 +124,7 @@ export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEdi
105
124
  type="icon"
106
125
  onPointerDown={preventDefault}
107
126
  onClick={handleVisitLink}
108
- disabled={!value}
127
+ disabled={!normalizedValue}
109
128
  >
110
129
  <TldrawUiButtonIcon small icon="external-link" />
111
130
  </TldrawUiButton>
@@ -29,6 +29,7 @@ import { defaultHandleExternalTextContent } from '../../defaultExternalContentHa
29
29
  import { createBookmarkFromUrl } from '../../shapes/bookmark/bookmarks'
30
30
  import { downloadFile } from '../../utils/export/exportAs'
31
31
  import { fitFrameToContent, getFrameableShapeIds, removeFrame } from '../../utils/frames/frames'
32
+ import { openLink } from '../../utils/openLink'
32
33
  import { generateShapeAnnouncementMessage } from '../components/A11y'
33
34
  import { EditLinkDialog } from '../components/EditLinkDialog'
34
35
  import { EmbedDialog } from '../components/EmbedDialog'
@@ -683,7 +684,7 @@ export function ActionsProvider({ overrides, children }: ActionsProviderProps) {
683
684
  return
684
685
  }
685
686
 
686
- openWindow(shape.props.url, '_blank')
687
+ openLink(editor, shape.props.url)
687
688
  },
688
689
  },
689
690
  {
@@ -1,11 +1,14 @@
1
1
  import { useEditor } from '@tldraw/editor'
2
- import { useEffect } from 'react'
2
+ import { createElement, useEffect } from 'react'
3
+ import { ConfirmOpenLinkDialog } from '../components/ConfirmOpenLinkDialog'
4
+ import { useDialogs } from '../context/dialogs'
3
5
  import { useToasts } from '../context/toasts'
4
6
 
5
7
  /** @internal */
6
8
  export function useEditorEvents() {
7
9
  const editor = useEditor()
8
10
  const { addToast } = useToasts()
11
+ const { addDialog } = useDialogs()
9
12
 
10
13
  useEffect(() => {
11
14
  function handleMaxShapes({ name, count }: { name: string; pageId: string; count: number }) {
@@ -16,9 +19,18 @@ export function useEditorEvents() {
16
19
  })
17
20
  }
18
21
 
22
+ function handleConfirmOpenLink({ url }: { url: string }) {
23
+ addDialog({
24
+ id: 'confirm-open-link',
25
+ component: ({ onClose }) => createElement(ConfirmOpenLinkDialog, { url, onClose }),
26
+ })
27
+ }
28
+
19
29
  editor.addListener('max-shapes', handleMaxShapes)
30
+ editor.addListener('confirm-open-link', handleConfirmOpenLink)
20
31
  return () => {
21
32
  editor.removeListener('max-shapes', handleMaxShapes)
33
+ editor.removeListener('confirm-open-link', handleConfirmOpenLink)
22
34
  }
23
- }, [editor, addToast])
35
+ }, [editor, addToast, addDialog])
24
36
  }
@@ -231,6 +231,10 @@ export type TLUiTranslationKey =
231
231
  | 'comments.thread-title'
232
232
  | 'comments.title'
233
233
  | 'comments.unknown-author'
234
+ | 'confirm-open-link-dialog.cancel'
235
+ | 'confirm-open-link-dialog.detail'
236
+ | 'confirm-open-link-dialog.open'
237
+ | 'confirm-open-link-dialog.title'
234
238
  | 'context-menu.arrange'
235
239
  | 'context-menu.copy-as'
236
240
  | 'context-menu.edit'
@@ -1,9 +1,9 @@
1
1
  // This file is automatically generated by internal/scripts/refresh-assets.ts.
2
2
  // Do not edit manually. Or do, I'm a comment, not a cop.
3
3
 
4
- export const version = '5.6.0'
4
+ export const version = '5.6.2'
5
5
  export const publishDates = {
6
6
  major: '2026-05-06T16:28:18.473Z',
7
7
  minor: '2026-10-28T14:20:57.238Z',
8
- patch: '2026-10-28T14:20:57.238Z',
8
+ patch: '2026-11-20T13:16:37.205Z',
9
9
  }
package/src/lib/ui.css CHANGED
@@ -1827,6 +1827,16 @@ tldraw? probably.
1827
1827
  padding: 0px var(--tl-space-4);
1828
1828
  }
1829
1829
 
1830
+ /* Confirm Open Link Dialog */
1831
+
1832
+ .tlui-confirm-open-link-dialog__url {
1833
+ margin-top: var(--tl-space-4);
1834
+ padding: var(--tl-space-3) var(--tl-space-4);
1835
+ border-radius: var(--tl-radius-2);
1836
+ background-color: var(--tl-color-muted-2);
1837
+ font-family: var(--tl-font-mono);
1838
+ }
1839
+
1830
1840
  /* Embed Dialog */
1831
1841
 
1832
1842
  .tlui-embed__spacer {
@@ -2259,12 +2269,19 @@ tldraw? probably.
2259
2269
  }
2260
2270
 
2261
2271
  .tlui-rich-text__toolbar-link-input {
2262
- margin-left: 12px;
2272
+ /* Padding rather than margin, so the invalid outline runs to the toolbar's left edge. */
2273
+ padding-left: 12px;
2263
2274
  /*
2264
2275
  * Nice touch tweak: keep the link editor toolbar the same as the default toolbar.
2265
2276
  * This is so the toolbar size stays stable going in and out of the link editor.
2266
2277
  */
2267
- width: 148px;
2278
+ width: 160px;
2279
+ }
2280
+
2281
+ .tlui-rich-text__toolbar-link-input--invalid {
2282
+ /* An inset shadow rather than a border, so the input doesn't change size. */
2283
+ box-shadow: inset 0 0 0 1px var(--tl-color-danger);
2284
+ border-radius: var(--tl-radius-3) var(--tl-radius-2) var(--tl-radius-2) var(--tl-radius-3);
2268
2285
  }
2269
2286
 
2270
2287
  .tlui-media__toolbar-alt-text-input {
@@ -0,0 +1,33 @@
1
+ import { normalizeLinkUrl } from './linkUrl'
2
+
3
+ describe('normalizeLinkUrl', () => {
4
+ it.each([
5
+ ['https://tldraw.com', 'https://tldraw.com'],
6
+ [' https://tldraw.com ', 'https://tldraw.com'],
7
+ ['https://https://tldraw.com', 'https://tldraw.com'],
8
+ ['mailto:hello@tldraw.com', 'mailto:hello@tldraw.com'],
9
+ ['vscode://file/src/index.ts', 'vscode://file/src/index.ts'],
10
+ ['/relative/path', '/relative/path'],
11
+ ['', ''],
12
+ ])('keeps a valid link as typed: %j', (input, expected) => {
13
+ expect(normalizeLinkUrl(input)).toBe(expected)
14
+ })
15
+
16
+ it.each([
17
+ ['tldraw.com', 'https://tldraw.com'],
18
+ ['www.tldraw.com/docs?x=1#y', 'https://www.tldraw.com/docs?x=1#y'],
19
+ ['httpbin.org', 'https://httpbin.org'],
20
+ ['example.com:8080', 'https://example.com:8080'],
21
+ ['localhost:3000', 'https://localhost:3000'],
22
+ ['hello@tldraw.com', 'mailto:hello@tldraw.com'],
23
+ ])('completes a bare host or email: %j', (input, expected) => {
24
+ expect(normalizeLinkUrl(input)).toBe(expected)
25
+ })
26
+
27
+ it.each(['hello', 'hello world', 'tldraw.', 'javascript:alert(1)', 'user@tldraw.com:8080'])(
28
+ 'rejects %j',
29
+ (input) => {
30
+ expect(normalizeLinkUrl(input)).toBeNull()
31
+ }
32
+ )
33
+ })
@@ -0,0 +1,30 @@
1
+ import { T } from '@tldraw/editor'
2
+
3
+ const emailRegex = /^[^\s@/:]+@[^\s@/:]+\.[^\s@/:]+$/
4
+
5
+ /**
6
+ * Turn what a user typed into a link field into the url to store, or null if it isn't a link.
7
+ *
8
+ * - Anything `T.linkUrl` accepts is kept as typed, so `mailto:` and app links (`vscode://…`)
9
+ * are never rewritten.
10
+ * - An email address becomes a `mailto:` link.
11
+ * - A bare host (`example.com`, `localhost:3000`) gets `https://`. A word with no dot, like
12
+ * `hello`, is not treated as a host, or every typo would become a dead `https://hello` link.
13
+ * - The empty string means "no link".
14
+ */
15
+ export function normalizeLinkUrl(input: string): string | null {
16
+ // Pasting a url into a field that already holds `https://` doubles the protocol.
17
+ const url = input.trim().replace(/^https?:\/\/(https?:\/\/)/i, '$1')
18
+
19
+ if (T.linkUrl.isValid(url)) return url
20
+ if (emailRegex.test(url)) return `mailto:${url}`
21
+
22
+ const withProtocol = `https://${url}`
23
+ if (!T.linkUrl.isValid(withProtocol)) return null
24
+ const { hostname, username } = new URL(withProtocol)
25
+ if (username) return null
26
+ if (hostname === 'localhost' || hostname.startsWith('[') || /[^.]\.[^.]+$/.test(hostname)) {
27
+ return withProtocol
28
+ }
29
+ return null
30
+ }
@@ -0,0 +1,83 @@
1
+ import { TestEditor } from '../../test/TestEditor'
2
+ import { getLinkOpenPolicy, openLink } from './openLink'
3
+
4
+ describe('getLinkOpenPolicy', () => {
5
+ it.each([
6
+ 'https://tldraw.com',
7
+ 'HTTP://tldraw.com',
8
+ 'mailto:hello@tldraw.com',
9
+ '/relative/path',
10
+ './relative/path',
11
+ 'vscode://file/src/index.ts',
12
+ 'Slack://channel?id=1',
13
+ 'figma:design/123',
14
+ ])('opens %j', (url) => {
15
+ expect(getLinkOpenPolicy(url)).toBe('open')
16
+ })
17
+
18
+ it.each(['chatgpt://chat/123', 'ChatGPT://chat/123', 'tel:5551234', 'some-new-app://thing'])(
19
+ 'asks before opening an unknown app link: %j',
20
+ (url) => {
21
+ expect(getLinkOpenPolicy(url)).toBe('confirm')
22
+ }
23
+ )
24
+
25
+ it.each([
26
+ '',
27
+ 'javascript:alert(1)',
28
+ 'JavaScript:alert(1)',
29
+ 'data:text/html,hi',
30
+ 'file:///etc',
31
+ 'ms-msdt:x',
32
+ 'localhost:3000',
33
+ 'not a url',
34
+ ])('blocks %j', (url) => {
35
+ expect(getLinkOpenPolicy(url)).toBe('block')
36
+ })
37
+ })
38
+
39
+ describe('openLink', () => {
40
+ let editor: TestEditor
41
+ let open: ReturnType<typeof vi.spyOn>
42
+
43
+ beforeEach(() => {
44
+ editor = new TestEditor()
45
+ open = vi.spyOn(window, 'open').mockImplementation(() => null)
46
+ })
47
+
48
+ afterEach(() => {
49
+ open.mockRestore()
50
+ })
51
+
52
+ it('opens a trusted link straight away', () => {
53
+ const onConfirm = vi.fn()
54
+ editor.on('confirm-open-link', onConfirm)
55
+ openLink(editor, 'vscode://file/src/index.ts')
56
+ expect(open).toHaveBeenCalledWith('vscode://file/src/index.ts', '_blank', 'noopener noreferrer')
57
+ expect(onConfirm).not.toHaveBeenCalled()
58
+ })
59
+
60
+ it('asks the listener to confirm an unknown app link instead of opening it', () => {
61
+ const onConfirm = vi.fn()
62
+ editor.on('confirm-open-link', onConfirm)
63
+ openLink(editor, 'chatgpt://chat/123')
64
+ expect(onConfirm).toHaveBeenCalledWith({ url: 'chatgpt://chat/123' })
65
+ expect(open).not.toHaveBeenCalled()
66
+ })
67
+
68
+ it('does not open an unknown app link when nothing can confirm it', () => {
69
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
70
+ openLink(editor, 'chatgpt://chat/123')
71
+ expect(open).not.toHaveBeenCalled()
72
+ expect(warn).toHaveBeenCalled()
73
+ warn.mockRestore()
74
+ })
75
+
76
+ it('never opens a blocked link', () => {
77
+ const onConfirm = vi.fn()
78
+ editor.on('confirm-open-link', onConfirm)
79
+ openLink(editor, 'javascript:alert(1)')
80
+ expect(open).not.toHaveBeenCalled()
81
+ expect(onConfirm).not.toHaveBeenCalled()
82
+ })
83
+ })
@@ -0,0 +1,75 @@
1
+ import { Editor, openWindow, T } from '@tldraw/editor'
2
+
3
+ /**
4
+ * How {@link openLink} treats a link. See {@link getLinkOpenPolicy}.
5
+ *
6
+ * @public
7
+ */
8
+ export type TLLinkOpenPolicy = 'open' | 'confirm' | 'block'
9
+
10
+ // This list only decides whether we ask before opening, so it can change in any release. Don't move
11
+ // it into `T.linkUrl`: every client and the sync server validate stored urls with that, so changing
12
+ // what it accepts breaks shared boards between versions.
13
+ const trustedLinkProtocols = new Set([
14
+ 'http:',
15
+ 'https:',
16
+ 'mailto:',
17
+ 'claude:',
18
+ 'codex:',
19
+ 'cursor:',
20
+ 'discord:',
21
+ 'figma:',
22
+ 'jetbrains:',
23
+ 'linear:',
24
+ 'notion:',
25
+ 'obsidian:',
26
+ 'slack:',
27
+ 'spotify:',
28
+ 'vscode:',
29
+ 'windsurf:',
30
+ 'zed:',
31
+ ])
32
+
33
+ /**
34
+ * Decide how a link from a shape or rich text should be opened.
35
+ *
36
+ * - `open`: a web link, mailto link, relative link, or a link into a well-known app.
37
+ * - `confirm`: any other link that `T.linkUrl` accepts, such as an app we don't know. Ask the
38
+ * user before opening it.
39
+ * - `block`: anything `T.linkUrl` rejects. Stored records are validated, but a link can also
40
+ * come from rendered rich text or a custom shape, so check again here.
41
+ *
42
+ * @public
43
+ */
44
+ export function getLinkOpenPolicy(url: string): TLLinkOpenPolicy {
45
+ if (!url || !T.linkUrl.isValid(url)) return 'block'
46
+ if (url.startsWith('/') || url.startsWith('./')) return 'open'
47
+ return trustedLinkProtocols.has(new URL(url).protocol) ? 'open' : 'confirm'
48
+ }
49
+
50
+ /**
51
+ * Open a user-provided link in a new window, following {@link getLinkOpenPolicy}. Links that need
52
+ * confirming emit a `confirm-open-link` event, which the default UI answers with a dialog. With no
53
+ * listener for that event (for example with `hideUi`), those links are not opened. To handle them
54
+ * yourself, add a listener that asks the user and calls `openWindow(url, '_blank')` if they agree.
55
+ *
56
+ * @public
57
+ */
58
+ export function openLink(editor: Editor, url: string) {
59
+ switch (getLinkOpenPolicy(url)) {
60
+ case 'open':
61
+ openWindow(url, '_blank')
62
+ return
63
+ case 'confirm':
64
+ if (editor.listenerCount('confirm-open-link') > 0) {
65
+ editor.emit('confirm-open-link', { url })
66
+ } else {
67
+ console.warn(
68
+ `Not opening ${url}: links into unknown apps need confirming, and nothing is listening for the editor's confirm-open-link event. Add a listener with editor.on('confirm-open-link', ({ url }) => ...) to ask the user, or render the default tldraw UI.`
69
+ )
70
+ }
71
+ return
72
+ case 'block':
73
+ return
74
+ }
75
+ }
@@ -16,6 +16,7 @@ import {
16
16
  Editor,
17
17
  getOwnProperty,
18
18
  RichTextFontVisitorState,
19
+ T,
19
20
  TLFontFace,
20
21
  TLRichText,
21
22
  WeakCache,
@@ -65,6 +66,9 @@ export function getTipTapDefaultExtensions(
65
66
  link: {
66
67
  openOnClick: false,
67
68
  autolink: true,
69
+ // TipTap strips hrefs outside its own protocol list, which would drop app links
70
+ // (`vscode://…`) that shape links accept.
71
+ isAllowedUri: (url, { defaultValidate }) => defaultValidate(url) || T.linkUrl.isValid(url),
68
72
  },
69
73
  // List every enabled block type: a missing one gets an empty paragraph appended after it
70
74
  // that the user can't delete (#7641 for lists, #11113 for headings).