tldraw 5.6.0 → 5.6.1

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 (46) hide show
  1. package/DOCS.md +2 -1
  2. package/RELEASE_NOTES.md +106 -3
  3. package/dist-cjs/index.js +1 -1
  4. package/dist-cjs/lib/shapes/bookmark/BookmarkShapeUtil.js +5 -4
  5. package/dist-cjs/lib/shapes/bookmark/BookmarkShapeUtil.js.map +2 -2
  6. package/dist-cjs/lib/shapes/bookmark/bookmarks.js +25 -4
  7. package/dist-cjs/lib/shapes/bookmark/bookmarks.js.map +2 -2
  8. package/dist-cjs/lib/ui/components/EditLinkDialog.js +15 -17
  9. package/dist-cjs/lib/ui/components/EditLinkDialog.js.map +2 -2
  10. package/dist-cjs/lib/ui/components/Toolbar/LinkEditor.js +46 -19
  11. package/dist-cjs/lib/ui/components/Toolbar/LinkEditor.js.map +3 -3
  12. package/dist-cjs/lib/ui/version.js +2 -2
  13. package/dist-cjs/lib/ui/version.js.map +1 -1
  14. package/dist-cjs/lib/utils/linkUrl.js +39 -0
  15. package/dist-cjs/lib/utils/linkUrl.js.map +7 -0
  16. package/dist-cjs/lib/utils/text/richText.js +4 -1
  17. package/dist-cjs/lib/utils/text/richText.js.map +2 -2
  18. package/dist-esm/index.mjs +1 -1
  19. package/dist-esm/lib/shapes/bookmark/BookmarkShapeUtil.mjs +6 -4
  20. package/dist-esm/lib/shapes/bookmark/BookmarkShapeUtil.mjs.map +2 -2
  21. package/dist-esm/lib/shapes/bookmark/bookmarks.mjs +25 -4
  22. package/dist-esm/lib/shapes/bookmark/bookmarks.mjs.map +2 -2
  23. package/dist-esm/lib/ui/components/EditLinkDialog.mjs +16 -18
  24. package/dist-esm/lib/ui/components/EditLinkDialog.mjs.map +2 -2
  25. package/dist-esm/lib/ui/components/Toolbar/LinkEditor.mjs +36 -19
  26. package/dist-esm/lib/ui/components/Toolbar/LinkEditor.mjs.map +2 -2
  27. package/dist-esm/lib/ui/version.mjs +2 -2
  28. package/dist-esm/lib/ui/version.mjs.map +1 -1
  29. package/dist-esm/lib/utils/linkUrl.mjs +19 -0
  30. package/dist-esm/lib/utils/linkUrl.mjs.map +7 -0
  31. package/dist-esm/lib/utils/text/richText.mjs +5 -1
  32. package/dist-esm/lib/utils/text/richText.mjs.map +2 -2
  33. package/package.json +6 -6
  34. package/src/lib/shapes/bookmark/BookmarkShapeUtil.tsx +6 -6
  35. package/src/lib/shapes/bookmark/bookmarks.ts +38 -5
  36. package/src/lib/ui/components/EditLinkDialog.tsx +22 -26
  37. package/src/lib/ui/components/Toolbar/LinkEditor.tsx +38 -20
  38. package/src/lib/ui/version.ts +2 -2
  39. package/src/lib/ui.css +9 -2
  40. package/src/lib/utils/linkUrl.test.ts +33 -0
  41. package/src/lib/utils/linkUrl.ts +30 -0
  42. package/src/lib/utils/text/richText.ts +4 -0
  43. package/src/test/bookmark-shapes.test.ts +62 -2
  44. package/src/test/ui/EditLinkDialog.test.tsx +53 -2
  45. package/src/test/ui/LinkEditor.test.tsx +71 -0
  46. package/tldraw.css +9 -2
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tldraw",
3
3
  "description": "A tiny little drawing editor.",
4
- "version": "5.6.0",
4
+ "version": "5.6.1",
5
5
  "author": {
6
6
  "name": "tldraw Inc.",
7
7
  "email": "hello@tldraw.com"
@@ -56,11 +56,11 @@
56
56
  "@tiptap/pm": "^3.12.1",
57
57
  "@tiptap/react": "^3.12.1",
58
58
  "@tiptap/starter-kit": "^3.12.1",
59
- "@tldraw/driver": "5.6.0",
60
- "@tldraw/editor": "5.6.0",
61
- "@tldraw/state": "5.6.0",
62
- "@tldraw/store": "5.6.0",
63
- "@tldraw/tlschema": "5.6.0",
59
+ "@tldraw/driver": "5.6.1",
60
+ "@tldraw/editor": "5.6.1",
61
+ "@tldraw/state": "5.6.1",
62
+ "@tldraw/store": "5.6.1",
63
+ "@tldraw/tlschema": "5.6.1",
64
64
  "classnames": "^2.5.1",
65
65
  "idb": "^7.1.1",
66
66
  "lz-string": "^1.5.0",
@@ -30,6 +30,7 @@ import {
30
30
  getBookmarkShapeHeight,
31
31
  getHumanReadableAddress,
32
32
  getResolvedBookmarkAssetId,
33
+ isUrlOnlyBookmarkUrl,
33
34
  setBookmarkHeight,
34
35
  resolveBookmarkAssetForUrlChange,
35
36
  } from './bookmarks'
@@ -135,7 +136,7 @@ export class BookmarkShapeUtil extends BaseBoxShapeUtil<TLBookmarkShape> {
135
136
  next = resolveBookmarkAssetForUrlChange(this.editor, shape)
136
137
  }
137
138
 
138
- if (prev.props.assetId !== next.props.assetId) {
139
+ if (prev.props.assetId !== next.props.assetId || prev.props.url !== next.props.url) {
139
140
  return setBookmarkHeight(this.editor, next)
140
141
  }
141
142
 
@@ -175,6 +176,7 @@ export function BookmarkShapeComponent({
175
176
  const isSafariExport = !!useSvgExportContext() && tlenv.isSafari
176
177
 
177
178
  const address = getHumanReadableAddress(url)
179
+ const title = asset ? asset.props.title : isUrlOnlyBookmarkUrl(url) ? url : ''
178
180
 
179
181
  const [isFaviconValid, setIsFaviconValid] = useState(true)
180
182
  const onFaviconError = () => setIsFaviconValid(false)
@@ -198,7 +200,7 @@ export function BookmarkShapeComponent({
198
200
  maxHeight: h,
199
201
  }}
200
202
  >
201
- {showImageContainer && (!asset || asset.props.image) && (
203
+ {showImageContainer && (asset ? asset.props.image : !isUrlOnlyBookmarkUrl(url)) && (
202
204
  <div className="tl-bookmark__image_container">
203
205
  {asset ? (
204
206
  <img
@@ -215,7 +217,7 @@ export function BookmarkShapeComponent({
215
217
  </div>
216
218
  )}
217
219
  <div className="tl-bookmark__copy_container">
218
- {asset?.props.title ? (
220
+ {title ? (
219
221
  <a
220
222
  className="tl-bookmark__link"
221
223
  href={url || ''}
@@ -225,9 +227,7 @@ export function BookmarkShapeComponent({
225
227
  onPointerDown={markAsHandledOnShiftKey}
226
228
  onPointerUp={markAsHandledOnShiftKey}
227
229
  >
228
- <h2 className="tl-bookmark__heading">
229
- {convertCommonTitleHTMLEntities(asset.props.title)}
230
- </h2>
230
+ <h2 className="tl-bookmark__heading">{convertCommonTitleHTMLEntities(title)}</h2>
231
231
  </a>
232
232
  ) : null}
233
233
  {asset?.props.description && asset?.props.image ? (
@@ -15,9 +15,32 @@ import {
15
15
  export const BOOKMARK_WIDTH = 300
16
16
  export const BOOKMARK_HEIGHT = 320
17
17
  export const BOOKMARK_JUST_URL_HEIGHT = 46
18
- const SHORT_BOOKMARK_HEIGHT = 101
18
+ export const SHORT_BOOKMARK_HEIGHT = 101
19
19
 
20
- export function getBookmarkHeight(editor: Editor, assetId?: TLAssetId | null) {
20
+ // A bookmark asset's `src` is a `T.srcUrl`, which rejects app links and `mailto:`. Not
21
+ // `T.httpUrl`: it accepts `''` and relative paths, so clearing a bookmark's url would unfurl.
22
+ function canUnfurlUrl(url: string) {
23
+ try {
24
+ const { protocol } = new URL(url)
25
+ return protocol === 'http:' || protocol === 'https:'
26
+ } catch {
27
+ return false
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Whether a bookmark without an asset will never get one, rather than still loading. Without
33
+ * this, an app link bookmark shows the loading placeholder forever.
34
+ */
35
+ export function isUrlOnlyBookmarkUrl(url: string) {
36
+ return url !== '' && !canUnfurlUrl(url)
37
+ }
38
+
39
+ export function getBookmarkHeight(
40
+ editor: Editor,
41
+ assetId: TLAssetId | null | undefined,
42
+ url: string
43
+ ) {
21
44
  const asset = (assetId ? editor.getAsset(assetId) : null) as TLBookmarkAsset | null
22
45
 
23
46
  if (asset) {
@@ -28,6 +51,8 @@ export function getBookmarkHeight(editor: Editor, assetId?: TLAssetId | null) {
28
51
  return SHORT_BOOKMARK_HEIGHT
29
52
  }
30
53
  }
54
+ } else if (isUrlOnlyBookmarkUrl(url)) {
55
+ return SHORT_BOOKMARK_HEIGHT
31
56
  }
32
57
 
33
58
  return BOOKMARK_HEIGHT
@@ -36,7 +61,10 @@ export function getBookmarkHeight(editor: Editor, assetId?: TLAssetId | null) {
36
61
  export function setBookmarkHeight(editor: Editor, shape: TLBookmarkShape) {
37
62
  return {
38
63
  ...shape,
39
- props: { ...shape.props, h: getBookmarkHeight(editor, shape.props.assetId) },
64
+ props: {
65
+ ...shape.props,
66
+ h: getBookmarkHeight(editor, shape.props.assetId, shape.props.url),
67
+ },
40
68
  }
41
69
  }
42
70
 
@@ -44,6 +72,8 @@ export function setBookmarkHeight(editor: Editor, shape: TLBookmarkShape) {
44
72
  export function getHumanReadableAddress(url: string) {
45
73
  try {
46
74
  const objUrl = new URL(url)
75
+ // An app link's host (`file` in `vscode://file/…`) doesn't say where it goes, but its app does.
76
+ if (isUrlOnlyBookmarkUrl(url)) return objUrl.protocol.slice(0, -1)
47
77
  // we want the hostname without any www
48
78
  return objUrl.hostname.replace(/^www\./, '')
49
79
  } catch {
@@ -113,13 +143,14 @@ export function getResolvedBookmarkAssetId(
113
143
  export function getBookmarkShapeHeight(editor: Editor, shape: TLBookmarkShape): number {
114
144
  const resolvedAssetId = getResolvedBookmarkAssetId(editor, shape.props.assetId, shape.props.url)
115
145
  if (resolvedAssetId === shape.props.assetId) return shape.props.h
116
- return getBookmarkHeight(editor, resolvedAssetId)
146
+ return getBookmarkHeight(editor, resolvedAssetId, shape.props.url)
117
147
  }
118
148
 
119
149
  async function _createBookmarkAssetOnUrlChange(editor: Editor, shape: TLBookmarkShape) {
120
150
  if (editor.isDisposed) return
121
151
 
122
152
  const { url } = shape.props
153
+ if (!canUnfurlUrl(url)) return
123
154
 
124
155
  // Create the asset using the external content manager's createAssetFromUrl method.
125
156
  // This may be overwritten by the user (for example, we overwrite it on tldraw.com)
@@ -200,7 +231,7 @@ export async function createBookmarkFromUrl(
200
231
  url,
201
232
  assetId: existingAsset?.id ?? null,
202
233
  w: BOOKMARK_WIDTH,
203
- h: getBookmarkHeight(editor, existingAsset?.id),
234
+ h: getBookmarkHeight(editor, existingAsset?.id, url),
204
235
  },
205
236
  }
206
237
 
@@ -230,6 +261,8 @@ export async function createBookmarkFromUrl(
230
261
  }
231
262
 
232
263
  async function hydrateBookmarkShape(editor: Editor, shapeId: TLShapeId, url: string) {
264
+ if (!canUnfurlUrl(url)) return
265
+
233
266
  let asset
234
267
  try {
235
268
  asset = await editor.getAssetForExternalContent({ type: 'url', url })
@@ -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,7 @@
1
1
  import { defineMessages, openWindow, 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'
3
5
  import { useUiEvents } from '../../context/events'
4
6
  import { useTranslation } from '../../hooks/useTranslation/useTranslation'
5
7
  import { TldrawUiButton } from '../primitives/Button/TldrawUiButton'
@@ -22,20 +24,34 @@ export interface LinkEditorProps {
22
24
  export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEditorProps) {
23
25
  const editor = useEditor()
24
26
  const [value, setValue] = useState(initialValue)
27
+ const [isInvalid, setIsInvalid] = useState(false)
25
28
  const msg = useTranslation()
26
29
  const ref = useRef<HTMLInputElement>(null)
27
30
  const trackEvent = useUiEvents()
28
31
  const source = 'rich-text-menu'
29
- const linkifiedValue = value.startsWith('http') ? value : `https://${value}`
32
+ const normalizedValue = normalizeLinkUrl(value)
33
+
34
+ const handleRemoveLink = useCallback(() => {
35
+ trackEvent('rich-text', { operation: 'link-remove', source })
36
+ textEditor.chain().unsetLink().focus().run()
37
+ onClose()
38
+ }, [trackEvent, source, textEditor, onClose])
30
39
 
31
40
  const handleLinkComplete = useCallback(
32
41
  (link: string) => {
33
- trackEvent('rich-text', { operation: 'link-edit', source })
34
- if (!link.startsWith('http://') && !link.startsWith('https://')) {
35
- link = `https://${link}`
42
+ const href = normalizeLinkUrl(link)
43
+ if (href === null) {
44
+ setIsInvalid(true)
45
+ ref.current?.focus()
46
+ return
47
+ }
48
+ if (href === '') {
49
+ handleRemoveLink()
50
+ return
36
51
  }
37
52
 
38
- textEditor.chain().setLink({ href: link }).run()
53
+ trackEvent('rich-text', { operation: 'link-edit', source })
54
+ textEditor.chain().setLink({ href }).run()
39
55
  // N.B. We shouldn't focus() on mobile because it causes the
40
56
  // Return key to replace the link with a newline :facepalm:
41
57
  if (editor.getInstanceState().isCoarsePointer) {
@@ -45,38 +61,32 @@ export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEdi
45
61
  }
46
62
  onClose()
47
63
  },
48
- [trackEvent, source, textEditor, editor, onClose]
64
+ [trackEvent, source, textEditor, editor, onClose, handleRemoveLink]
49
65
  )
50
66
 
51
67
  const handleVisitLink = () => {
52
68
  trackEvent('rich-text', { operation: 'link-visit', source })
53
- openWindow(linkifiedValue, '_blank')
69
+ if (normalizedValue) openWindow(normalizedValue, '_blank')
54
70
  onClose()
55
71
  }
56
72
 
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
73
  useEffect(() => {
64
74
  const doc = editor.getContainerDocument()
65
75
  const handlePointerDown = (e: PointerEvent) => {
66
76
  const toolbar = doc.querySelector('.tlui-rich-text__toolbar')
67
77
  if (toolbar?.contains(e.target as Node)) return
68
78
  // If the pointer down is not in the toolbar, complete the link
69
- if (value) {
70
- handleLinkComplete(value)
79
+ if (normalizedValue === null) {
80
+ onClose()
71
81
  } else {
72
- handleRemoveLink()
82
+ handleLinkComplete(value)
73
83
  }
74
84
  }
75
85
  doc.addEventListener('pointerdown', handlePointerDown, { capture: true })
76
86
  return () => {
77
87
  doc.removeEventListener('pointerdown', handlePointerDown, { capture: true })
78
88
  }
79
- }, [editor, handleLinkComplete, handleRemoveLink, value])
89
+ }, [editor, handleLinkComplete, onClose, normalizedValue, value])
80
90
 
81
91
  useEffect(() => {
82
92
  ref.current?.focus()
@@ -84,16 +94,24 @@ export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEdi
84
94
 
85
95
  useEffect(() => {
86
96
  setValue(initialValue)
97
+ setIsInvalid(false)
87
98
  }, [initialValue])
88
99
 
100
+ const handleValueChange = useCallback((nextValue: string) => {
101
+ setValue(nextValue)
102
+ setIsInvalid(false)
103
+ }, [])
104
+
89
105
  return (
90
106
  <>
91
107
  <TldrawUiInput
92
108
  ref={ref}
93
109
  data-testid="rich-text.link-input"
94
- className="tlui-rich-text__toolbar-link-input"
110
+ className={classNames('tlui-rich-text__toolbar-link-input', {
111
+ 'tlui-rich-text__toolbar-link-input--invalid': isInvalid,
112
+ })}
95
113
  value={value}
96
- onValueChange={setValue}
114
+ onValueChange={handleValueChange}
97
115
  onComplete={handleLinkComplete}
98
116
  onCancel={onClose}
99
117
  placeholder="example.com"
@@ -105,7 +123,7 @@ export function LinkEditor({ textEditor, value: initialValue, onClose }: LinkEdi
105
123
  type="icon"
106
124
  onPointerDown={preventDefault}
107
125
  onClick={handleVisitLink}
108
- disabled={!value}
126
+ disabled={!normalizedValue}
109
127
  >
110
128
  <TldrawUiButtonIcon small icon="external-link" />
111
129
  </TldrawUiButton>
@@ -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.1'
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-16T18:57:15.106Z',
9
9
  }
package/src/lib/ui.css CHANGED
@@ -2259,12 +2259,19 @@ tldraw? probably.
2259
2259
  }
2260
2260
 
2261
2261
  .tlui-rich-text__toolbar-link-input {
2262
- margin-left: 12px;
2262
+ /* Padding rather than margin, so the invalid outline runs to the toolbar's left edge. */
2263
+ padding-left: 12px;
2263
2264
  /*
2264
2265
  * Nice touch tweak: keep the link editor toolbar the same as the default toolbar.
2265
2266
  * This is so the toolbar size stays stable going in and out of the link editor.
2266
2267
  */
2267
- width: 148px;
2268
+ width: 160px;
2269
+ }
2270
+
2271
+ .tlui-rich-text__toolbar-link-input--invalid {
2272
+ /* An inset shadow rather than a border, so the input doesn't change size. */
2273
+ box-shadow: inset 0 0 0 1px var(--tl-color-danger);
2274
+ border-radius: var(--tl-radius-3) var(--tl-radius-2) var(--tl-radius-2) var(--tl-radius-3);
2268
2275
  }
2269
2276
 
2270
2277
  .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
+ }
@@ -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).
@@ -2,6 +2,8 @@ import { AssetRecordType, TLBookmarkShape, createShapeId, getHashForString } fro
2
2
  import { vi } from 'vitest'
3
3
  import { defaultHandleExternalUrlAsset } from '../lib/defaultExternalContentHandlers'
4
4
  import {
5
+ BOOKMARK_HEIGHT,
6
+ SHORT_BOOKMARK_HEIGHT,
5
7
  createBookmarkFromUrl,
6
8
  getBookmarkHeight,
7
9
  getBookmarkShapeHeight,
@@ -88,6 +90,7 @@ describe('The URL formatter', () => {
88
90
  expect(getHumanReadableAddress(d.props.url)).toBe('github.com')
89
91
  expect(getHumanReadableAddress(e.props.url)).toBe('github.com')
90
92
  expect(getHumanReadableAddress(f.props.url)).toBe('github.com')
93
+ expect(getHumanReadableAddress('vscode://file/src/index.ts')).toBe('vscode')
91
94
  })
92
95
 
93
96
  it("Doesn't resize bookmarks", () => {
@@ -197,6 +200,19 @@ describe('createBookmarkFromUrl', () => {
197
200
  expect(createdAsset?.type).toBe('bookmark')
198
201
  })
199
202
 
203
+ it('does not fetch metadata for an app link', async () => {
204
+ const fetchSpy = vi.spyOn(editor, 'getAssetForExternalContent')
205
+
206
+ const result = await createBookmarkFromUrl(editor, { url: 'vscode://file/src/index.ts' })
207
+
208
+ assert(result.ok, 'Failed to create bookmark')
209
+ expect(editor.getShape<TLBookmarkShape>(result.value.id)!.props).toMatchObject({
210
+ assetId: null,
211
+ h: SHORT_BOOKMARK_HEIGHT,
212
+ })
213
+ expect(fetchSpy).not.toHaveBeenCalled()
214
+ })
215
+
200
216
  it('creates a bookmark shape with default center when no center provided', async () => {
201
217
  const url = 'https://example.com'
202
218
  const viewportCenter = { x: 500, y: 300 }
@@ -518,7 +534,7 @@ describe('changing a bookmark url', () => {
518
534
  expect(editor.getShape<TLBookmarkShape>(id)!.props).toMatchObject({
519
535
  url: urlB,
520
536
  assetId: assetB,
521
- h: getBookmarkHeight(editor, assetB),
537
+ h: getBookmarkHeight(editor, assetB, urlB),
522
538
  })
523
539
  expect(fetchSpy).not.toHaveBeenCalled()
524
540
  })
@@ -549,7 +565,7 @@ describe('changing a bookmark url', () => {
549
565
  expect(editor.getShape<TLBookmarkShape>(id)!.props).toMatchObject({
550
566
  url: urlC,
551
567
  assetId: null,
552
- h: getBookmarkHeight(editor, null),
568
+ h: getBookmarkHeight(editor, null, urlC),
553
569
  })
554
570
 
555
571
  await vi.advanceTimersByTimeAsync(600)
@@ -559,6 +575,50 @@ describe('changing a bookmark url', () => {
559
575
  vi.useRealTimers()
560
576
  }
561
577
  })
578
+
579
+ it.each([
580
+ ['codex://threads/1', SHORT_BOOKMARK_HEIGHT],
581
+ ['/relative/path', SHORT_BOOKMARK_HEIGHT],
582
+ ['', BOOKMARK_HEIGHT],
583
+ ])('does not fetch metadata when the url changes to %j', async (url, h) => {
584
+ vi.useFakeTimers()
585
+ try {
586
+ const urlA = 'https://a.example.com'
587
+ const assetA = createBookmarkAsset(urlA, 'short')
588
+ const id = createShapeId()
589
+ editor.createShape<TLBookmarkShape>({
590
+ id,
591
+ type: 'bookmark',
592
+ props: { url: urlA, assetId: assetA },
593
+ })
594
+ const fetchSpy = vi.spyOn(editor, 'getAssetForExternalContent')
595
+
596
+ editor.updateShape<TLBookmarkShape>({ id, type: 'bookmark', props: { url } })
597
+
598
+ await vi.advanceTimersByTimeAsync(600)
599
+ expect(fetchSpy).not.toHaveBeenCalled()
600
+ expect(editor.getShape<TLBookmarkShape>(id)!.props).toMatchObject({ url, assetId: null, h })
601
+ } finally {
602
+ vi.useRealTimers()
603
+ }
604
+ })
605
+
606
+ it('shows the loading placeholder when an app link changes to an http url', () => {
607
+ const id = createShapeId()
608
+ editor.createShape<TLBookmarkShape>({
609
+ id,
610
+ type: 'bookmark',
611
+ props: { url: 'codex://threads/1' },
612
+ })
613
+ vi.spyOn(editor, 'getAssetForExternalContent').mockResolvedValue(undefined)
614
+
615
+ editor.updateShape<TLBookmarkShape>({
616
+ id,
617
+ type: 'bookmark',
618
+ props: { url: 'https://c.example.com' },
619
+ })
620
+ expect(editor.getShape<TLBookmarkShape>(id)!.props.h).toBe(BOOKMARK_HEIGHT)
621
+ })
562
622
  })
563
623
 
564
624
  describe('defaultHandleExternalUrlAsset', () => {