import { tooltip } from "./host.ts";
/** Find within the Markdown field, using the host's shared Find presentation. */
export function createDescriptionFind(textarea: HTMLTextAreaElement) {
const element = document.createElement("section");
element.className = "rs-find-bar";
element.setAttribute("aria-label", "Find in description");
element.hidden = true;
element.innerHTML = `
`;
const input = element.querySelector("input")!;
const actions = element.querySelector(".rs-find-actions")!;
const options = element.querySelector(".rs-find-options")!;
const status = document.createElement("span");
status.setAttribute("role", "status");
status.setAttribute("aria-live", "polite");
let current = -1;
let matches: { from: number; to: number }[] = [];
let returnStart = 0, returnEnd = 0;
const highlights = document.createElement("div");
highlights.className = "pm-description-find-highlights";
highlights.setAttribute("aria-hidden", "true"); highlights.hidden = true;
textarea.parentElement!.append(highlights);
function paint() {
highlights.replaceChildren();
highlights.hidden = element.hidden || !matches.length;
if (highlights.hidden) return;
const style = getComputedStyle(textarea);
for (const property of ["font", "line-height", "padding", "letter-spacing", "tab-size"])
highlights.style.setProperty(property, style.getPropertyValue(property));
let end = 0;
for (const [index, match] of matches.entries()) {
highlights.append(document.createTextNode(textarea.value.slice(end, match.from)));
const mark = document.createElement("mark"); mark.textContent = textarea.value.slice(match.from, match.to);
if (index === current) mark.className = "pm-description-find-current";
highlights.append(mark); end = match.to;
}
highlights.append(document.createTextNode(textarea.value.slice(end)));
}
function option(label: string) {
const wrapper = document.createElement("label");
const checkbox = document.createElement("input"); checkbox.type = "checkbox";
checkbox.onchange = refresh;
wrapper.append(checkbox, document.createTextNode(label)); options.append(wrapper);
return checkbox;
}
const matchCase = option("Match case");
const wholeWord = option("Whole word");
const regex = option("Regex");
options.append(status);
function close() {
hide();
textarea.focus({ preventScroll: true });
textarea.setSelectionRange(returnStart, returnEnd);
}
function hide() { element.hidden = highlights.hidden = true; }
function action(label: string, path: string, run: () => void) {
const button = document.createElement("button");
button.type = "button"; button.className = "rs-find-button pm-icon-button";
button.setAttribute("aria-label", label);
button.innerHTML = ``;
tooltip(button, label);
button.onclick = run; actions.append(button);
return button;
}
const previous = action("Previous match (Shift+Enter)", "m18 15-6-6-6 6", () => next(true));
const following = action("Next match (Enter)", "m6 9 6 6 6-6", () => next());
action("Close find (Escape)", "m6 6 12 12M18 6 6 18", close);
function announce() {
status.textContent = input.value ? (matches.length ? `${current < 0 ? 0 : current + 1} of ${matches.length}` : "No matches") : "";
}
function refresh() {
current = -1; matches = [];
input.setAttribute("aria-invalid", "false"); status.classList.remove("rs-find-error");
if (input.value) {
try {
const pattern = regex.checked ? input.value : input.value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const expression = new RegExp(wholeWord.checked ? `\\b(?:${pattern})\\b` : pattern, `gmu${matchCase.checked ? "" : "i"}`);
for (const match of textarea.value.matchAll(expression)) {
if (match[0].length) matches.push({ from: match.index, to: match.index + match[0].length });
}
} catch {
input.setAttribute("aria-invalid", "true"); status.classList.add("rs-find-error");
}
}
previous.disabled = following.disabled = !matches.length;
if (input.getAttribute("aria-invalid") === "true") status.textContent = "Invalid expression";
else announce();
paint();
}
function next(backward = false) {
if (!matches.length) return;
current = current < 0 ? (backward ? matches.length - 1 : 0) : (current + (backward ? -1 : 1) + matches.length) % matches.length;
const match = matches[current];
returnStart = match.from; returnEnd = match.to;
textarea.setSelectionRange(match.from, match.to);
// Reveal the matching line without moving focus out of the Find controls.
const style = getComputedStyle(textarea);
const mirror = document.createElement("div");
mirror.style.cssText = `position:absolute;visibility:hidden;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`;
mirror.textContent = textarea.value.slice(0, match.from);
const marker = document.createElement("span"); marker.textContent = textarea.value.slice(match.from, match.to);
mirror.append(marker); document.body.append(mirror);
const dialog = textarea.closest("dialog");
if (dialog) dialog.scrollTop += textarea.getBoundingClientRect().top + marker.offsetTop - dialog.getBoundingClientRect().top - dialog.clientHeight / 2;
mirror.remove(); announce(); paint();
}
input.oninput = refresh;
element.addEventListener("keydown", event => {
if (event.key === "Escape" || event.key === "Enter" && event.target === input) {
event.preventDefault(); event.stopPropagation();
if (event.key === "Escape") close(); else next(event.shiftKey);
}
});
textarea.addEventListener("input", refresh);
return {
element,
open() {
if (element.hidden) {
returnStart = textarea.selectionStart; returnEnd = textarea.selectionEnd;
const selected = textarea.value.slice(returnStart, returnEnd);
if (selected && !selected.includes("\n")) input.value = selected;
refresh();
}
element.hidden = false; paint(); element.scrollIntoView({ block: "nearest" }); input.focus(); input.select();
},
close,
hide,
dispose() { textarea.removeEventListener("input", refresh); highlights.remove(); },
};
}