import { tr } from '../i18n/index.ts'; import { StateField, type EditorState, type Range } from "@codemirror/state"; import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view"; import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language"; import { actionIcon } from "../ui/actionIcons"; import { attachTooltip } from "../ui/tooltip"; const tooltipCleanups = new WeakMap void>(); export type HeadingRange = { start: number; from: number; to: number; level: number; label: string }; export function headingRanges(state: EditorState): HeadingRange[] { const headings: HeadingRange[] = []; syntaxTree(state).iterate({ enter(node) { if (/^(?:FencedCode|CodeBlock|Blockquote|ListItem)$/.test(node.name)) return false; const match = /^(?:ATX|Setext)Heading([1-6])$/.exec(node.name); if (!match) return; const line = state.doc.lineAt(node.from); headings.push({ start: line.from, from: node.to, to: state.doc.length, level: Number(match[1]), label: line.text.replace(/^\s*#+\s*/, "").replace(/\s+#+\s*$/, "") }); return false; } }); headings.forEach((heading, index) => { const next = headings.slice(index + 1).find(other => other.level <= heading.level); heading.to = next ? Math.max(heading.from, next.start - 1) : state.doc.length; }); return headings.filter(heading => state.sliceDoc(heading.from, heading.to).trim().length > 0); } export function headingButton(label: string, collapsed: boolean): HTMLButtonElement { const button = document.createElement("button"); button.type = "button"; button.className = "rs-heading-toggle"; button.setAttribute("aria-expanded", String(!collapsed)); const title = tr(collapsed ? "Expand {name}" : "Collapse {name}", { name: label || tr("heading") }); button.setAttribute("aria-label", title); tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || "")); const icon = actionIcon("chevron"); button.append(icon); return button; } class HeadingToggle extends WidgetType { constructor(readonly heading: HeadingRange, readonly collapsed: boolean) { super(); } eq(other: HeadingToggle) { return this.heading.from === other.heading.from && this.heading.to === other.heading.to && this.heading.label === other.heading.label && this.collapsed === other.collapsed; } toDOM(view: EditorView) { const button = headingButton(this.heading.label, this.collapsed); button.dataset.headingStart = String(this.heading.start); button.onmousedown = event => event.preventDefault(); button.onclick = event => { event.preventDefault(); event.stopPropagation(); const restoreFocus = document.activeElement === button; const { from, to } = this.heading; const selection = !this.collapsed && view.state.selection.ranges.some(range => range.to > from && range.from <= to) ? { anchor: from } : undefined; view.dispatch({ effects: (this.collapsed ? unfoldEffect : foldEffect).of({ from, to }), selection }); if (restoreFocus) view.dom.querySelector(`[data-heading-start="${this.heading.start}"]`)?.focus({ preventScroll: true }); }; return button; } destroy(dom: HTMLElement) { tooltipCleanups.get(dom)?.(); } ignoreEvent() { return true; } } export const headingFolding = [ codeFolding({ placeholderText: "…" }), keymap.of(foldKeymap), foldService.of((state, start) => { const heading = headingRanges(state).find(heading => heading.start === start); return heading ? { from: heading.from, to: heading.to } : null; }), StateField.define({ create: decorations, update(value, transaction) { return transaction.docChanged || transaction.effects.some(effect => effect.is(foldEffect) || effect.is(unfoldEffect)) || syntaxTree(transaction.state) !== syntaxTree(transaction.startState) ? decorations(transaction.state) : value; }, provide: field => EditorView.decorations.from(field), }), ]; function decorations(state: EditorState) { const ranges: Range[] = []; const folds = foldedRanges(state); for (const heading of headingRanges(state)) { let collapsed = false, hidden = false; folds.between(0, state.doc.length, (from, to) => { if (from === heading.from) collapsed = true; if (from < heading.start && to >= heading.start) hidden = true; }); if (!hidden) ranges.push(Decoration.widget({ widget: new HeadingToggle(heading, collapsed), side: -1 }).range(heading.start)); } return Decoration.set(ranges, true); } export function readerHeadingFolding(root: HTMLElement, collapsed: Set) { const elements = [...root.children].filter(element => !element.classList.contains("document-title")) as HTMLElement[]; const headings = elements.flatMap((element, index) => { const heading = /^H[1-6]$/.test(element.tagName) ? element : element.querySelector(":scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > h5, :scope > h6"); return heading ? [{ element, heading, index, level: Number(heading.tagName.slice(1)), label: heading.textContent || "heading", key: `${index}:${heading.textContent}` }] : []; }); function apply() { elements.forEach(element => { element.hidden = false; }); headings.forEach(item => { const button = item.heading.querySelector(".rs-heading-toggle"); if (button) { const label = tr(collapsed.has(item.key) ? "Expand {name}" : "Collapse {name}", { name: item.label }); button.setAttribute("aria-expanded", String(!collapsed.has(item.key))); button.setAttribute("aria-label", label); item.heading.classList.toggle("rs-heading-collapsed", collapsed.has(item.key)); } if (!collapsed.has(item.key)) return; const next = headings.find(other => other.index > item.index && other.level <= item.level); for (let index = item.index + 1; index < (next?.index ?? elements.length); index++) elements[index].hidden = true; }); } for (const item of headings) { const next = headings.find(other => other.index > item.index && other.level <= item.level); if ((next?.index ?? elements.length) <= item.index + 1) continue; const button = headingButton(item.label, collapsed.has(item.key)); button.onclick = event => { event.stopPropagation(); if (collapsed.has(item.key)) collapsed.delete(item.key); else collapsed.add(item.key); apply(); }; item.heading.classList.add("rs-foldable-heading"); item.heading.prepend(button); } apply(); return { reveal(target: HTMLElement) { const index = elements.findIndex(element => element === target || element.contains(target)); if (index < 0) return; for (const item of headings) { const next = headings.find(other => other.index > item.index && other.level <= item.level); if (item.index < index && (next?.index ?? elements.length) > index) collapsed.delete(item.key); } apply(); }, destroy() { elements.forEach(element => { element.hidden = false; }); headings.forEach(item => { const button = item.heading.querySelector(".rs-heading-toggle"); if (button) tooltipCleanups.get(button)?.(); button?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); }); }, }; }