fix(session-ui): keep a URL's own closing bracket when linking plain text

Plain-text links dropped every trailing bracket, so a URL like https://en.wikipedia.org/wiki/Mercury_(planet) linked to the truncated path and left the bracket in the text. Only unbalanced trailing brackets are punctuation now.
This commit is contained in:
Kit Langton
2026-11-06 17:12:08 -08:00
Unverified
parent b2b5da600e
commit e1233481af
2 changed files with 48 additions and 2 deletions
@@ -21,6 +21,28 @@ describe("linkSegments", () => {
])
})
test("keeps closing brackets that belong to the URL", () => {
expect(linkSegments("see https://en.wikipedia.org/wiki/Mercury_(planet) now")).toEqual([
{ text: "see " },
{
text: "https://en.wikipedia.org/wiki/Mercury_(planet)",
href: "https://en.wikipedia.org/wiki/Mercury_(planet)",
},
{ text: " now" },
])
expect(linkSegments("(see https://en.wikipedia.org/wiki/Mercury_(planet)).")).toEqual([
{ text: "(see " },
{
text: "https://en.wikipedia.org/wiki/Mercury_(planet)",
href: "https://en.wikipedia.org/wiki/Mercury_(planet)",
},
{ text: ")." },
])
expect(linkSegments("https://example.com/list[0]")).toEqual([
{ text: "https://example.com/list[0]", href: "https://example.com/list[0]" },
])
})
test("returns text without URLs as one run", () => {
expect(linkSegments("no links here")).toEqual([{ text: "no links here" }])
expect(linkSegments("")).toEqual([])
@@ -1,11 +1,35 @@
const openers: Readonly<Record<string, string | undefined>> = { ")": "(", "]": "[" }
/** Drops punctuation trailing a URL, but keeps a closing bracket that pairs with one inside it (`…/Mercury_(planet)`). */
function trimTrailing(url: string) {
let end = url.length
while (end > 0) {
const char = url[end - 1]!
const opener = openers[char]
if (opener) {
const head = url.slice(0, end)
if (count(head, opener) >= count(head, char)) break
} else if (!",.;:!?".includes(char)) break
end -= 1
}
return url.slice(0, end)
}
function count(text: string, char: string) {
return text.split(char).length - 1
}
/** Splits plain text into runs, marking each http(s) URL with its link target. */
export function linkSegments(text: string) {
const result: { text: string; href?: string }[] = []
let last = 0
for (const match of text.matchAll(/https?:\/\/[^\s<>"'`]+/g)) {
// Sentence punctuation and closing brackets after a URL are almost never part of it.
const href = match[0].replace(/[),.;:!?\]]+$/, "")
const href = trimTrailing(match[0])
if (!URL.canParse(href)) continue