Skip to content

The agent that grows with you

Port from block/buzz#6684: hyperlink selected composer text on link paste

Tekniume550dce93234
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index d2dda2df399..8cd701d1678 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -88,7 +88,7 @@ import { ComposerTriggerPopover } from './trigger-popover'
import type { ChatBarProps } from './types'
import { isRedoShortcut, isUndoShortcut } from './undo-history'
import { UrlDialog } from './url-dialog'
-import { chipTypedUrlOnSpace, linkifyUrls } from './url-refs'
+import { chipTypedUrlOnSpace, linkifyUrls, markdownLinkFor, resolveExactLinkPaste, selectionLinkLabel } from './url-refs'
import { VoiceActivity, VoicePlaybackActivity } from './voice-activity'
export function ChatBar({
@@ -564,6 +564,24 @@ export function ChatBar({
event.preventDefault()
+ // Pasting exactly one link while composer text is selected turns that text
+ // into a markdown link instead of replacing it — the behavior every rich
+ // editor ships (ported from block/buzz#6684). Selections that span chips
+ // or lines fall through to the normal replace-with-chip path.
+ const exactLink = resolveExactLinkPaste(pastedText)
+
+ if (exactLink) {
+ const label = selectionLinkLabel(event.currentTarget)
+
+ if (label) {
+ recordUndoPoint()
+ insertComposerContentsAtCaret(event.currentTarget, markdownLinkFor(label, exactLink))
+ scheduleFlushEditorToDraft(event.currentTarget)
+
+ return
+ }
+ }
+
// A paste past the large-paste threshold becomes a `.txt` attachment chip
// instead of flooding the composer.
// The instruction the user types stays in the input; the pasted source
diff --git a/apps/desktop/src/app/chat/composer/url-refs.test.ts b/apps/desktop/src/app/chat/composer/url-refs.test.ts
index febbd533ce4..565666e00ec 100644
--- a/apps/desktop/src/app/chat/composer/url-refs.test.ts
+++ b/apps/desktop/src/app/chat/composer/url-refs.test.ts
@@ -1,8 +1,8 @@
import type { KeyboardEvent } from 'react'
import { describe, expect, it } from 'vitest'
-import { composerPlainText, RICH_INPUT_SLOT } from './rich-editor'
-import { chipTypedUrlOnSpace, linkifyUrls } from './url-refs'
+import { composerPlainText, refChipElement, RICH_INPUT_SLOT } from './rich-editor'
+import { chipTypedUrlOnSpace, linkifyUrls, markdownLinkFor, resolveExactLinkPaste, selectionLinkLabel } from './url-refs'
/** An editor holding `text` with a collapsed caret at `caret`, plus the space
* keydown the composer would hand `chipTypedUrlOnSpace`. */
@@ -51,6 +51,95 @@ describe('linkifyUrls', () => {
})
})
+describe('resolveExactLinkPaste', () => {
+ it('accepts a lone bare link', () => {
+ expect(resolveExactLinkPaste('https://example.dev/a/b')).toBe('https://example.dev/a/b')
+ })
+
+ it('accepts a wrapped <link> and surrounding whitespace', () => {
+ expect(resolveExactLinkPaste(' <https://example.dev/a> ')).toBe('https://example.dev/a')
+ })
+
+ it('rejects prose around the link', () => {
+ expect(resolveExactLinkPaste('see https://example.dev')).toBeNull()
+ expect(resolveExactLinkPaste('https://example.dev is nice')).toBeNull()
+ })
+
+ it('rejects multiple links', () => {
+ expect(resolveExactLinkPaste('https://a.dev https://b.dev')).toBeNull()
+ })
+
+ it('rejects trailing sentence punctuation and hostless schemes', () => {
+ expect(resolveExactLinkPaste('https://example.dev.')).toBeNull()
+ expect(resolveExactLinkPaste('https://')).toBeNull()
+ })
+})
+
+describe('selectionLinkLabel', () => {
+ const selectAll = (build: (editor: HTMLElement) => void) => {
+ const editor = document.createElement('div')
+ editor.dataset.slot = RICH_INPUT_SLOT
+ build(editor)
+ document.body.append(editor)
+
+ const selection = window.getSelection()!
+ const range = document.createRange()
+
+ range.selectNodeContents(editor)
+ selection.removeAllRanges()
+ selection.addRange(range)
+
+ return editor
+ }
+
+ it('returns the selected text', () => {
+ const editor = selectAll(node => {
+ node.textContent = 'the docs'
+ })
+
+ expect(selectionLinkLabel(editor)).toBe('the docs')
+ editor.remove()
+ })
+
+ it('rejects a collapsed selection', () => {
+ const editor = document.createElement('div')
+ editor.textContent = 'text'
+ document.body.append(editor)
+ window.getSelection()?.removeAllRanges()
+
+ expect(selectionLinkLabel(editor)).toBeNull()
+ editor.remove()
+ })
+
+ it('rejects a selection containing a chip', () => {
+ const editor = selectAll(node => {
+ node.append(document.createTextNode('see '), refChipElement('url', '`https://a.dev`'))
+ })
+
+ expect(selectionLinkLabel(editor)).toBeNull()
+ editor.remove()
+ })
+
+ it('rejects a multi-line selection', () => {
+ const editor = selectAll(node => {
+ node.append(document.createTextNode('one'), document.createElement('br'), document.createTextNode('two'))
+ })
+
+ expect(selectionLinkLabel(editor)).toBeNull()
+ editor.remove()
+ })
+})
+
+describe('markdownLinkFor', () => {
+ it('builds a markdown link', () => {
+ expect(markdownLinkFor('the docs', 'https://example.dev')).toBe('[the docs](https://example.dev)')
+ })
+
+ it('escapes square brackets in the label', () => {
+ expect(markdownLinkFor('a [b] c', 'https://example.dev')).toBe('[a \\[b\\] c](https://example.dev)')
+ })
+})
+
describe('chipTypedUrlOnSpace', () => {
it('chips a link typed right before the caret and adds the space', () => {
const { editor, event } = spaceOn('see https://example.dev/a', 25)
diff --git a/apps/desktop/src/app/chat/composer/url-refs.ts b/apps/desktop/src/app/chat/composer/url-refs.ts
index 580abdc1c6f..027666caf38 100644
--- a/apps/desktop/src/app/chat/composer/url-refs.ts
+++ b/apps/desktop/src/app/chat/composer/url-refs.ts
@@ -59,6 +59,71 @@ export function linkifyUrls(text: string) {
return out + text.slice(cursor)
}
+/** The href to apply when a clipboard payload is exactly ONE supported link —
+ * a bare or `<…>`-wrapped `http(s)` URL with a host and nothing else. Null for
+ * anything that isn't a lone link (prose, multiple links, trailing text), so
+ * callers fall through to the normal paste pipeline. Ported from
+ * block/buzz#6684's `resolveExactLinkPaste`. */
+export function resolveExactLinkPaste(raw: string): string | null {
+ const text = raw.trim()
+ const unwrapped = text.startsWith('<') && text.endsWith('>') && text.length > 2 ? text.slice(1, -1).trim() : text
+
+ URL_RE.lastIndex = 0
+
+ const match = URL_RE.exec(unwrapped)
+
+ if (!match || match.index !== 0 || match[0].length !== unwrapped.length) {
+ return null
+ }
+
+ const { trailing, url } = splitUrlTail(unwrapped)
+
+ // Trailing sentence punctuation means the user copied prose, not a link.
+ if (trailing || !hasHost(url)) {
+ return null
+ }
+
+ return url
+}
+
+/** The selected composer text a link paste should hyperlink, or null when the
+ * selection can't take a link mark: collapsed, outside `editor`, spanning
+ * chips or line breaks, or whitespace-only. */
+export function selectionLinkLabel(editor: HTMLElement): string | null {
+ const selection = window.getSelection()
+
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
+ return null
+ }
+
+ const range = selection.getRangeAt(0)
+
+ if (!editor.contains(range.commonAncestorContainer)) {
+ return null
+ }
+
+ const probe = document.createElement('div')
+
+ probe.append(range.cloneContents())
+
+ // A chip inside the selection is a directive, not prose — linking over it
+ // would destroy the reference. Multi-line selections don't read as a label.
+ if (probe.querySelector('[data-ref-text], br')) {
+ return null
+ }
+
+ const label = probe.textContent?.replace(/\s+/g, ' ').trim() ?? ''
+
+ return label || null
+}
+
+/** Markdown link for a paste-over-selection: the label the user selected, the
+ * URL they pasted. Square brackets in the label are escaped so the link
+ * survives markdown parsing downstream. */
+export function markdownLinkFor(label: string, url: string): string {
+ return `[${label.replace(/([[\]])/g, '\\$1')}](${url})`
+}
+
/** A plain space finishing a typed link commits it as a chip (followed by
* whatever punctuation ended it, then the space). Returns whether it ran, so a
* keydown handler can fall through on anything else. */