export function insertOrEditLink(root: HTMLElement, href?: string) {
const sel = document.getSelection();
if (!sel || sel.rangeCount === 0) return;
const range = sel.getRangeAt(0);
let n: Node | null = range.startContainer;
let a: HTMLAnchorElement | null = null;
while (n && n !== root) {
if (n instanceof HTMLAnchorElement) {
a = n;
break;
}
n = n.parentNode;
}
const url =
href ??
(typeof window !== 'undefined'
? window.prompt('Enter URL', a?.href || 'https://') || ''
: '');
if (!url) return;
if (a) {
a.href = url;
return;
}
if (range.collapsed) {
const link = document.createElement('a');
link.href = url;
link.textContent = url;
range.insertNode(link);
const r = document.createRange();
r.setStartAfter(link);
r.collapse(true);
sel.removeAllRanges();
sel.addRange(r);
return;
}
const link = document.createElement('a');
link.href = url;
try {
range.surroundContents(link);
} catch {
const frag = range.extractContents();
link.appendChild(frag);
range.insertNode(link);
}
}