diff --git a/client/src/CodeChatEditor.mts b/client/src/CodeChatEditor.mts index 6acdca48..3f939340 100644 --- a/client/src/CodeChatEditor.mts +++ b/client/src/CodeChatEditor.mts @@ -80,6 +80,11 @@ import { rand, } from "./shared.mjs"; import { showToast } from "./show_toast.mjs"; +import { installCollapsibleHeadings } from "./collapsible-headings.mjs"; + +// TinyMCE collapse controls are external to the editable DOM and must be +// disposed when the editor is replaced or a mixed source file is loaded. +let disposeDocOnlyHeadings: (() => void) | undefined; // ### CSS import "./css/CodeChatEditor.css"; @@ -329,6 +334,10 @@ const _openLp = async ( const source = codechatForWeb["source"]; const codechatBody = document.getElementById("CodeChat-body"); assert(codechatBody instanceof HTMLDivElement); + if (!isDocOnly()) { + disposeDocOnlyHeadings?.(); + disposeDocOnlyHeadings = undefined; + } if (getIsDirty() && "Diff" in source) { // Send an `OutOfSync` response, so that the IDE will send the full // text to overwrite these changes with. @@ -395,6 +404,9 @@ const _openLp = async ( ); }, }); + // Doc-only collapsing UI lives outside TinyMCE's saved HTML. + disposeDocOnlyHeadings?.(); + disposeDocOnlyHeadings = installCollapsibleHeadings(tinymceInstance()!); tinymceInstance()!.focus(); } else { // Save the cursor location before the update, then restore it diff --git a/client/src/CodeMirror-integration.mts b/client/src/CodeMirror-integration.mts index d44628ba..dc05bafd 100644 --- a/client/src/CodeMirror-integration.mts +++ b/client/src/CodeMirror-integration.mts @@ -102,6 +102,8 @@ import { import { assert } from "./assert.mjs"; import { showToast } from "./show_toast.mjs"; import { CursorPosition } from "./rust-types/CursorPosition"; +import { getMixedFoldPlan, remapMixedCollapsedKeys } from "./mixed-heading-ranges.mjs"; +import type { MixedHeading, MixedBlock } from "./mixed-heading-ranges.mjs"; // Globals // ------- @@ -1619,6 +1621,266 @@ export const DocBlockPlugin = ViewPlugin.fromClass( // [Facet](https://codemirror.net/docs/ref/#state.Facet) with an // [of function](https://codemirror.net/docs/ref/#state.Facet.of) that creates a // CodeMirror extension. +// Presentation-only folding for interleaved source code and Markdown blocks. +// This StateField is NOT included in codeMirrorJsonFields, so it cannot be +// saved as a source change. CodeMirror's direct decorations provide the line +// layout information before it computes the viewport. +const toggleMixedHeadingFold = StateEffect.define(); + +type MixedFoldState = { + headings: MixedHeading[]; + plan: ReturnType; + collapsed: ReadonlySet; + lineDecorations: DecorationSet; +}; + +function computeMixedFoldState( + state: EditorState, + collapsed: ReadonlySet, + previousHeadings?: readonly MixedHeading[], + mapPosition: (position: number, assoc: -1 | 1) => number = (pos) => pos, +): MixedFoldState { + const blocks: MixedBlock[] = []; + const headings: MixedHeading[] = []; + const field = state.field(docBlockField); + for (const iter = field.iter(); iter.value !== null; iter.next()) { + const widget = iter.value.spec.widget; + if (!(widget instanceof DocBlockWidget)) continue; + const content = document.createElement("div"); + content.innerHTML = widget.contents; + const children = Array.from(content.children); + blocks.push({ from: iter.from, to: iter.to, childCount: children.length }); + for (let i = 0; i < children.length; ++i) { + const child = children[i]; + if (/^H[1-6]$/.test(child.tagName)) { + headings.push({ + key: `${iter.from}:${i + 1}`, + level: Number(child.tagName.slice(1)), + blockFrom: iter.from, + childIndex: i + 1, + label: child.textContent?.trim() ?? "", + id: child.id || undefined, + }); + } + } + } + // Heading positions/child indices may shift after editing. Match headings + // using their identity or visible text before discarding old fold state. + const currentCollapsed = previousHeadings !== undefined + ? remapMixedCollapsedKeys( + previousHeadings, headings, collapsed, mapPosition, + ) + : new Set( + [...collapsed].filter((key) => headings.some((h) => h.key === key)), + ); + const plan = getMixedFoldPlan( + blocks, headings, currentCollapsed, state.doc.length, + ); + const ranges: Array> = []; + for (const span of plan.codeSpans) { + let pos = span.from; + while (pos < span.to && pos < state.doc.length) { + const line = state.doc.lineAt(pos); + const insideDocBlock = blocks.some( + (block) => line.from >= block.from && line.from < block.to, + ); + if (line.from >= span.from && line.from < span.to && !insideDocBlock) { + ranges.push( + Decoration.line({ + attributes: { class: "cc-mixed-fold-hidden" }, + }).range(line.from), + ); + } + pos = line.to + 1; + } + } + const unique = new Map(); + for (const range of ranges) unique.set(range.from, range); + return { + headings, + plan, + collapsed: currentCollapsed, + lineDecorations: Decoration.set( + [...unique.values()].sort((a, b) => a.from - b.from), + ), + }; +} + +const mixedFoldField = StateField.define({ + create(state) { + return computeMixedFoldState(state, new Set()); + }, + update(old, tr) { + const toggles = tr.effects.filter((effect) => effect.is(toggleMixedHeadingFold)); + const docBlocksChanged = tr.effects.some( + (effect) => + effect.is(addDocBlock) || + effect.is(updateDocBlock) || + effect.is(deleteDocBlock), + ); + if (!tr.docChanged && !docBlocksChanged && toggles.length === 0) { + return old; + } + const collapsed = new Set(old.collapsed); + for (const effect of toggles) { + const key = effect.value; + if (collapsed.has(key)) collapsed.delete(key); + else collapsed.add(key); + } + // While applying an upstream text diff, docBlockFreezeAnnotation + // intentionally prevents doc block offsets from being mapped. Respect + // that here; the next transaction installs the new doc blocks. + const freeze = tr.annotation(docBlockFreezeAnnotation) !== undefined; + return computeMixedFoldState( + tr.state, + collapsed, + old.headings, + (position, assoc) => freeze + ? position + : tr.changes.mapPos(position, assoc), + ); + }, + provide: (field) => + EditorView.decorations.from(field, (value) => value.lineDecorations), +}); + +const mixedHeadingFoldUI = ViewPlugin.fromClass( + class { + private readonly view: EditorView; + private readonly layer: HTMLDivElement; + private readonly stylesheet: HTMLStyleElement; + private readonly buttons = new Map(); + private readonly onScroll = () => this.schedulePaint(); + private readonly onResize = () => this.schedulePaint(); + private frame: number | undefined; + private foldState: MixedFoldState; + + constructor(view: EditorView) { + this.view = view; + this.foldState = view.state.field(mixedFoldField); + this.layer = document.createElement("div"); + this.layer.className = "cc-mixed-fold-controls"; + this.layer.style.cssText = + "position:fixed;left:0;top:0;width:0;height:0;" + + "pointer-events:none;z-index:5000;"; + document.body.appendChild(this.layer); + this.stylesheet = document.createElement("style"); + document.head.appendChild(this.stylesheet); + document.addEventListener("scroll", this.onScroll, true); + window.addEventListener("resize", this.onResize); + this.updateStyles(); + this.schedulePaint(); + } + + update(update: ViewUpdate) { + const current = update.state.field(mixedFoldField); + if (current !== this.foldState) { + this.foldState = current; + this.updateStyles(); + } + this.schedulePaint(); + } + + private updateStyles() { + const docSelectors = this.foldState.plan.docSlices.map( + (slice) => + `.CodeChat-doc[data-cc-mixed-block="${slice.blockFrom}"] > ` + + `.CodeChat-doc-contents > ` + + `:nth-child(n+${slice.firstChild}):nth-child(-n+${slice.lastChild})`, + ); + this.stylesheet.textContent = + ".cm-line.cc-mixed-fold-hidden { display:none !important; }\n" + + (docSelectors.length + ? `${docSelectors.join(",\n")} { display:none !important; }\n` + : ""); + } + + private schedulePaint() { + if (this.frame !== undefined) return; + this.frame = requestAnimationFrame(() => { + this.frame = undefined; + this.paint(); + }); + } + + private paint() { + const headingElements = new Map(); + for (const widgetElement of this.view.dom.querySelectorAll(".CodeChat-doc")) { + if (!(widgetElement instanceof HTMLElement)) continue; + let from: number; + try { + from = this.view.posAtDOM(widgetElement); + } catch { + continue; + } + widgetElement.dataset.ccMixedBlock = String(from); + const contents = Array.from(widgetElement.children).find( + (child) => child.classList.contains("CodeChat-doc-contents"), + ); + if (!(contents instanceof HTMLElement)) continue; + for (let index = 0; index < contents.children.length; ++index) { + const child = contents.children[index]; + if (child instanceof HTMLElement && /^H[1-6]$/.test(child.tagName)) { + headingElements.set(`${from}:${index + 1}`, child); + } + } + } + const validKeys = new Set(this.foldState.headings.map((h) => h.key)); + const scrollRect = this.view.scrollDOM.getBoundingClientRect(); + for (const heading of this.foldState.headings) { + if (!this.buttons.has(heading.key)) { + const button = document.createElement("button"); + button.type = "button"; + button.style.cssText = + "position:fixed;pointer-events:auto;cursor:pointer;" + + "border:0;background:transparent;padding:0 3px;" + + "color:inherit;font:16px sans-serif;"; + button.addEventListener("mousedown", (event) => event.preventDefault()); + button.addEventListener("click", () => { + this.view.dispatch({ + effects: toggleMixedHeadingFold.of(heading.key), + annotations: noAutosaveAnnotation.of(true), + }); + }); + this.layer.appendChild(button); + this.buttons.set(heading.key, button); + } + const button = this.buttons.get(heading.key)!; + const el = headingElements.get(heading.key); + const rect = el?.getBoundingClientRect(); + button.hidden = + !rect || rect.height === 0 || + rect.bottom < scrollRect.top || rect.top > scrollRect.bottom; + if (rect) { + button.style.left = `${Math.max(0, rect.left - 22)}px`; + button.style.top = `${rect.top + 2}px`; + } + const isCollapsed = this.foldState.collapsed.has(heading.key); + button.textContent = isCollapsed ? "▸" : "▾"; + button.setAttribute("aria-expanded", String(!isCollapsed)); + button.setAttribute( + "aria-label", + `${isCollapsed ? "Expand" : "Collapse"} ${el?.textContent?.trim() ?? "section"}`, + ); + } + for (const [key, button] of this.buttons) { + if (!validKeys.has(key)) { + button.remove(); + this.buttons.delete(key); + } + } + } + + destroy() { + if (this.frame !== undefined) cancelAnimationFrame(this.frame); + document.removeEventListener("scroll", this.onScroll, true); + window.removeEventListener("resize", this.onResize); + this.layer.remove(); + this.stylesheet.remove(); + } + }, +); + const autosaveExtension = EditorView.updateListener.of( // CodeMirror passes this function a // [ViewUpdate](https://codemirror.net/docs/ref/#view.ViewUpdate) which @@ -1818,6 +2080,8 @@ export const codeMirrorLoad = async ( { extensions: [ DocBlockPlugin, + mixedFoldField, + mixedHeadingFoldUI, // Move focus into adjacent doc blocks on arrow-key // navigation. High precedence so it runs before the default // arrow-key commands in `basicSetup`. diff --git a/client/src/collapsible-headings.mts b/client/src/collapsible-headings.mts new file mode 100644 index 00000000..90015178 --- /dev/null +++ b/client/src/collapsible-headings.mts @@ -0,0 +1,293 @@ +/** + * Collapsible headings for doc-only CodeChat documents. + * + * UI buttons live OUTSIDE TinyMCE's editable region. Collapsing uses an + * external stylesheet rather than editing the document's HTML, so the + * generated controls and hidden state are not serialized with Markdown. + * + * NOTE: This implementation deliberately does not fold across CodeMirror + * code/doc widgets. That requires a separate CodeMirror integration. + */ + +interface HeadingEditor { + getElement(): Element; + on(name: string, callback: () => void): void; + off(name: string, callback: () => void): void; +} + +type HeadingInfo = { + element: HTMLElement; + key: string; + label: string; + id: string; + level: number; + childIndex: number; // one-based index within its own parent container + parent: Element; +}; + +let instanceCounter = 0; +// Only one control layer and set of listeners may be active per TinyMCE editor. +const activeInstallations = new WeakMap void>(); +const HEADING_SELECTOR = "h1,h2,h3,h4,h5,h6"; + +const getHeadingLevel = (heading: HTMLElement): number => + Number(heading.tagName.substring(1)); + +let headingKeyCounter = 0; + +/** + * Assign an independent UI identity to every heading (including duplicates). + * Reuse a key for an unchanged DOM element, an unambiguous explicit ID, or a + * globally unique label. If duplicate nodes are recreated without an ID, do + * not guess: reset their fold state rather than transferring it incorrectly. + * UI keys exist only in memory and are never serialized into source HTML. + */ +export function collectHeadings(root: HTMLElement, previous: readonly HeadingInfo[]): HeadingInfo[] { + // Markdown headings may occur inside list items and blockquotes, not only + // directly below the editor root. Retain the parent for local folding. + const nodes: { element: HTMLElement; parent: Element; childIndex: number }[] = []; + const visit = (parent: Element) => { + const children = Array.from(parent.children ?? []); + children.forEach((child, index) => { + if (!(child instanceof HTMLElement)) return; + if (child.matches(HEADING_SELECTOR)) { + nodes.push({ element: child, parent, childIndex: index + 1 }); + } + visit(child); + }); + }; + visit(root); + const current = nodes.map(({ element, parent, childIndex }) => ({ + element, + parent, + label: `${element.tagName}:${element.textContent?.trim().replace(/\s+/g, " ") ?? ""}`, + id: element.id, + level: getHeadingLevel(element), + childIndex, + key: "", + })); + const seenKeys = new Set(); + const count = ( + entries: readonly T[], property: "id" | "label", value: string, + ) => entries.filter((entry) => entry[property] === value).length; + + // Prefer exact element identity. Editing its text or its position must not + // accidentally transfer state to another heading. + for (const item of current) { + const old = previous.find((heading) => heading.element === item.element); + if (old && !seenKeys.has(old.key)) { + item.key = old.key; + seenKeys.add(old.key); + } + } + for (const item of current) { + if (item.key) continue; + let candidate: HeadingInfo | undefined; + if (item.id && count(current, "id", item.id) === 1 && + count(previous, "id", item.id) === 1) { + candidate = previous.find((old) => old.id === item.id && old.level === item.level); + } + if (!candidate && count(current, "label", item.label) === 1 && + count(previous, "label", item.label) === 1) { + candidate = previous.find((old) => old.label === item.label); + } + if (candidate && !seenKeys.has(candidate.key)) { + item.key = candidate.key; + seenKeys.add(candidate.key); + } else { + item.key = `heading:${++headingKeyCounter}`; + seenKeys.add(item.key); + } + } + return current; +} + +/** Return the direct-child boundaries covered by a heading (exclusive start). */ +export function sectionEnd( + headings: ReadonlyArray>, + headingIndex: number, + childCount: number, +): number { + const current = headings[headingIndex]; + for (let i = headingIndex + 1; i < headings.length; i++) { + if (headings[i].level <= current.level) return headings[i].childIndex - 1; + } + return childCount; +} + +/** + * Attach to an inline TinyMCE instance associated with a doc-only document. + * Call only after TinyMCE is initialized. No changes are made to source HTML. + */ +export function installCollapsibleHeadings(editor: HeadingEditor): () => void { + // Reinstallation must not leave the previous observer, listeners, or UI behind. + activeInstallations.get(editor)?.(); + const root = editor.getElement(); + if (!(root instanceof HTMLElement)) return () => undefined; + const documentForEditor = root.ownerDocument; + const instanceId = `cc-collapse-${++instanceCounter}`; + root.setAttribute("data-cc-collapse-host", instanceId); + + const style = documentForEditor.createElement("style"); + style.setAttribute("data-cc-collapse-ui", instanceId); + documentForEditor.head.appendChild(style); + + const buttonLayer = documentForEditor.createElement("div"); + buttonLayer.className = "cc-collapse-controls"; + buttonLayer.setAttribute("data-cc-collapse-ui", instanceId); + Object.assign(buttonLayer.style, { + position: "fixed", + left: "0px", + top: "0px", + width: "0px", + height: "0px", + overflow: "visible", + pointerEvents: "none", + zIndex: "5000", + }); + // Never append generated controls to the TinyMCE editable root. + documentForEditor.body.appendChild(buttonLayer); + + const collapsed = new Set(); + let headings: HeadingInfo[] = []; + let buttons: HTMLButtonElement[] = []; + let destroyed = false; + let scheduled = false; + let scheduledFrame: number | undefined; + + const positionButtons = () => { + if (destroyed) return; + for (let i = 0; i < headings.length; i++) { + const rect = headings[i].element.getBoundingClientRect(); + const button = buttons[i]; + if (!button) continue; + button.style.left = `${Math.max(0, rect.left - 25)}px`; + button.style.top = `${rect.top + 2}px`; + // A heading inside a collapsed ancestor has no rendered boxes. + // Hide its external control rather than leave it at (0, 0) where + // it would overlap other buttons and remain keyboard-focusable. + const hasBox = headings[i].element.getClientRects().length > 0; + button.hidden = !hasBox || rect.bottom < 0 || rect.top > window.innerHeight; + } + }; + + // Generate a selector for a parent container using its DOM path from + // the TinyMCE root. No attributes/styles are written to editable descendants, + // so hiding sections cannot be serialized into document Markdown. + const pathToParent = (parent: Element): string | undefined => { + const indices: number[] = []; + let current: Element | null = parent; + while (current !== root) { + const ancestor: Element | null = current.parentElement; + if (!ancestor) return undefined; + const index = Array.from(ancestor.children).indexOf(current); + if (index < 0) return undefined; + indices.unshift(index + 1); + current = ancestor; + } + return `[data-cc-collapse-host="${instanceId}"]` + + indices.map((index) => ` > :nth-child(${index})`).join(""); + }; + + const applyVisibility = () => { + const selectors: string[] = []; + headings.forEach((heading) => { + if (!collapsed.has(heading.key)) return; + // A heading inside a blockquote or list item folds only siblings + // in that container, never paragraphs outside its parent. + const siblings = headings.filter((other) => other.parent === heading.parent); + const index = siblings.indexOf(heading); + const end = sectionEnd(siblings, index, heading.parent.children.length); + if (end <= heading.childIndex) return; + const prefix = pathToParent(heading.parent); + if (!prefix) return; + const start = heading.childIndex + 1; + selectors.push( + `${prefix} > :nth-child(n+${start}):nth-child(-n+${end})`, + ); + }); + style.textContent = selectors.length + ? `${selectors.join(",\n")} { display: none !important; }` + : ""; + headings.forEach((heading, index) => { + const isCollapsed = collapsed.has(heading.key); + buttons[index].textContent = isCollapsed ? "▸" : "▾"; + buttons[index].setAttribute("aria-expanded", String(!isCollapsed)); + buttons[index].setAttribute( + "aria-label", + `${isCollapsed ? "Expand" : "Collapse"} ${heading.element.textContent?.trim() || "section"}`, + ); + }); + positionButtons(); + }; + + const update = () => { + if (destroyed) return; + headings = collectHeadings(root, headings); + const validKeys = new Set(headings.map((heading) => heading.key)); + for (const key of collapsed) if (!validKeys.has(key)) collapsed.delete(key); + buttonLayer.replaceChildren(); + buttons = headings.map((heading) => { + const button = documentForEditor.createElement("button"); + button.type = "button"; + button.className = "cc-collapse-toggle"; + button.style.cssText = + "position:fixed;pointer-events:auto;border:0;border-radius:3px;" + + "background:transparent;cursor:pointer;padding:0 4px;" + + "font:inherit;line-height:1.5;color:inherit;"; + button.addEventListener("mousedown", (event) => event.preventDefault()); + button.addEventListener("click", () => { + if (collapsed.has(heading.key)) collapsed.delete(heading.key); + else collapsed.add(heading.key); + applyVisibility(); + }); + buttonLayer.appendChild(button); + return button; + }); + applyVisibility(); + }; + + const scheduleUpdate = () => { + if (destroyed || scheduled) return; + scheduled = true; + scheduledFrame = requestAnimationFrame(() => { + scheduledFrame = undefined; + scheduled = false; + update(); + }); + }; + + const observer = new MutationObserver(scheduleUpdate); + observer.observe(root, { childList: true, subtree: true, characterData: true }); + documentForEditor.addEventListener("scroll", positionButtons, true); + window.addEventListener("resize", positionButtons); + editor.on("SetContent", scheduleUpdate); + editor.on("input", scheduleUpdate); + + // TinyMCE fires "remove" when an editor is disposed. Dispose the outside + // controls before the editor's DOM can be detached or replaced. + const onRemove = () => dispose(); + const dispose = () => { + if (destroyed) return; + destroyed = true; + if (scheduledFrame !== undefined) cancelAnimationFrame(scheduledFrame); + scheduledFrame = undefined; + scheduled = false; + observer.disconnect(); + documentForEditor.removeEventListener("scroll", positionButtons, true); + window.removeEventListener("resize", positionButtons); + editor.off("SetContent", scheduleUpdate); + editor.off("input", scheduleUpdate); + editor.off("remove", onRemove); + buttonLayer.remove(); + style.remove(); + root.removeAttribute("data-cc-collapse-host"); + if (activeInstallations.get(editor) === dispose) { + activeInstallations.delete(editor); + } + }; + editor.on("remove", onRemove); + activeInstallations.set(editor, dispose); + update(); + return dispose; +} diff --git a/client/src/mixed-heading-ranges.mts b/client/src/mixed-heading-ranges.mts new file mode 100644 index 00000000..c3b07dc5 --- /dev/null +++ b/client/src/mixed-heading-ranges.mts @@ -0,0 +1,184 @@ +// The CodeChat Editor, a word processor for software developers. +// Copyright (C) 2024-2026 Bryan A. Jones, and contributors. +// +// SPDX-License-Identifier: GPL-3.0-or-later +// This file is part of the CodeChat Editor. + +/** + * Pure section-boundary logic for CodeChat's mixed code/documentation view. + * All positions are offsets in CodeMirror's (unmodified) document. + */ +export type MixedHeading = { + key: string; + level: number; + blockFrom: number; + childIndex: number; // one-based direct child index in the HTML doc block + label?: string; // heading text, used to recognize it after edits + id?: string; // heading ID, when supplied by the document +}; + +export type MixedBlock = { + from: number; + to: number; + childCount: number; +}; + +export type DocHideSlice = { + blockFrom: number; + firstChild: number; // one-based, inclusive + lastChild: number; // one-based, inclusive +}; + +export type CodeHideSpan = { from: number; to: number }; + +export type MixedFoldPlan = { + docSlices: DocHideSlice[]; + codeSpans: CodeHideSpan[]; +}; + +/** A heading owns everything until the next heading of the same or higher rank. */ +export function getMixedFoldPlan( + blocks: readonly MixedBlock[], + headings: readonly MixedHeading[], + collapsedKeys: ReadonlySet, + documentLength: number, +): MixedFoldPlan { + const docSlices: DocHideSlice[] = []; + const codeSpans: CodeHideSpan[] = []; + const blocksByFrom = new Map(blocks.map((block, index) => [block.from, index])); + + for (let i = 0; i < headings.length; ++i) { + const start = headings[i]; + if (!collapsedKeys.has(start.key)) continue; + const startIndex = blocksByFrom.get(start.blockFrom); + if (startIndex === undefined) continue; + + let endHeading: MixedHeading | undefined; + for (let j = i + 1; j < headings.length; ++j) { + if (headings[j].level <= start.level) { + endHeading = headings[j]; + break; + } + } + const endIndex = endHeading + ? blocksByFrom.get(endHeading.blockFrom) + : blocks.length - 1; + if (endIndex === undefined || endIndex < startIndex) continue; + + for (let k = startIndex; k <= endIndex; ++k) { + const block = blocks[k]; + const firstChild = k === startIndex ? start.childIndex + 1 : 1; + const lastChild = endHeading && k === endIndex + ? endHeading.childIndex - 1 + : block.childCount; + if (firstChild <= lastChild) { + docSlices.push({ blockFrom: block.from, firstChild, lastChild }); + } + } + const from = blocks[startIndex].to; + const to = endHeading ? blocks[endIndex].from : documentLength; + if (from < to) codeSpans.push({ from, to }); + } + return { docSlices, codeSpans }; +} + +/** + * Preserve collapsed headings across CodeMirror transactions that shift source + * positions or rebuild doc blocks. A heading's offset/child index is a + * presentation address, not a permanent identity. + * + * Prefer an explicitly supplied heading ID, then matching heading text and + * level near the mapped position. As a fallback, an exactly corresponding + * block and child index can retain state after a heading is renamed. Never + * assign one old heading to multiple new headings. + */ +export function remapMixedCollapsedKeys( + before: readonly MixedHeading[], + after: readonly MixedHeading[], + collapsedKeys: ReadonlySet, + mapPosition: (position: number, assoc: -1 | 1) => number, +): Set { + const result = new Set(); + const claimed = new Set(); + for (const old of before) { + if (!collapsedKeys.has(old.key)) continue; + const mappedLeft = mapPosition(old.blockFrom, -1); + const mappedRight = mapPosition(old.blockFrom, 1); + const available = after.filter((candidate) => + candidate.level === old.level && !claimed.has(candidate.key), + ); + // IDs may be used only when they uniquely identify one heading on + // both sides of the transaction. A repeated ID is not an identity. + const oldIdCount = old.id ? before.filter((h) => h.id === old.id).length : 0; + const newIdCount = old.id ? after.filter((h) => h.id === old.id).length : 0; + const byId = old.id && oldIdCount === 1 && newIdCount === 1 + ? available.filter((candidate) => candidate.id === old.id) + : []; + const beforeSameLabel = old.label + ? before.filter((h) => h.label === old.label && h.level === old.level) + : []; + const afterSameLabel = old.label + ? after.filter((h) => h.label === old.label && h.level === old.level) + : []; + const labelIsUnique = beforeSameLabel.length === 1 && afterSameLabel.length === 1; + const byLabel = labelIsUnique + ? available.filter((candidate) => candidate.label === old.label) + : []; + + // Repeated labels do not by themselves identify a particular heading. + // A same-block duplicate may change its child index when paragraphs + // are inserted before it; even an unchanged number of duplicates is + // not evidence of continuity. Only preserve an exact stable signature + // for a duplicate when the indices of *all* same-label headings in + // its mapped block are unchanged. Otherwise default to expanded. + const duplicate = beforeSameLabel.length > 1 || afterSameLabel.length > 1; + // Adding/removing one same-label heading makes all of its surviving + // siblings ambiguous without a stable explicit ID. + if (duplicate && beforeSameLabel.length !== afterSameLabel.length && + byId.length === 0) continue; + let byStableDuplicate: MixedHeading[] = []; + if (duplicate && old.label) { + const sameOldBlock = beforeSameLabel + .filter((h) => h.blockFrom === old.blockFrom) + .map((h) => h.childIndex).sort((a, b) => a - b); + const matchingBlocks = [mappedLeft, mappedRight]; + for (const blockFrom of new Set(matchingBlocks)) { + const sameNewBlock = afterSameLabel + .filter((h) => h.blockFrom === blockFrom) + .map((h) => h.childIndex).sort((a, b) => a - b); + // Each block must have the same heading-index signature. + // This is deliberately conservative: an ambiguous edit resets + // fold state instead of collapsing the wrong section. + if (sameOldBlock.length === 0 || + sameOldBlock.length !== sameNewBlock.length || + sameOldBlock.some((index, i) => index !== sameNewBlock[i])) { + continue; + } + byStableDuplicate = available.filter((candidate) => + candidate.blockFrom === blockFrom && + candidate.childIndex === old.childIndex && + candidate.label === old.label, + ); + if (byStableDuplicate.length === 1) break; + } + } + + const byPosition = !duplicate && byLabel.length === 0 + ? available.filter((candidate) => + (candidate.blockFrom === mappedLeft || candidate.blockFrom === mappedRight) && + candidate.childIndex === old.childIndex) + : []; + + // Prefer a unique ID, then a unique heading label. Position is the + // last resort for a rename without an ID; a new heading at the old + // position must not steal the state of a known, relocated heading. + const candidates = byId.length > 0 ? byId + : byLabel.length > 0 ? byLabel + : duplicate ? byStableDuplicate : byPosition; + if (candidates.length !== 1) continue; + const selected = candidates[0]; + result.add(selected.key); + claimed.add(selected.key); + } + return result; +} diff --git a/client/src/tests/collapsible-headings-lifecycle.test.mjs b/client/src/tests/collapsible-headings-lifecycle.test.mjs new file mode 100644 index 00000000..1667a84d --- /dev/null +++ b/client/src/tests/collapsible-headings-lifecycle.test.mjs @@ -0,0 +1,144 @@ +// Tests for controls/observer/event cleanup without a running browser. +// These complement (but do not replace) a TinyMCE integration smoke test. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { installCollapsibleHeadings } from '../collapsible-headings.mts'; + +function fixture() { + const saved = Object.fromEntries( + ['HTMLElement', 'MutationObserver', 'window', 'requestAnimationFrame', 'cancelAnimationFrame'] + .map((key) => [key, globalThis[key]]), + ); + const observers = []; + const frames = new Map(); + let nextFrameId = 0; + class FakeElement { + constructor(doc = null) { + this.ownerDocument = doc; + this.children = []; + this.attributes = new Map(); + this.style = {}; + this.hidden = false; + this.parent = null; + } + setAttribute(key, value) { this.attributes.set(key, value); } + removeAttribute(key) { this.attributes.delete(key); } + appendChild(child) { + child.parent = this; + this.children.push(child); + return child; + } + replaceChildren(...children) { + for (const child of this.children) child.parent = null; + this.children = []; + for (const child of children) this.appendChild(child); + } + remove() { + if (!this.parent) return; + this.parent.children.splice(this.parent.children.indexOf(this), 1); + this.parent = null; + } + } + class Emitter { + constructor() { this.events = new Map(); } + on(name, callback) { + if (!this.events.has(name)) this.events.set(name, new Set()); + this.events.get(name).add(callback); + } + off(name, callback) { this.events.get(name)?.delete(callback); } + addEventListener(name, callback) { this.on(name, callback); } + removeEventListener(name, callback) { this.off(name, callback); } + count(name) { return this.events.get(name)?.size ?? 0; } + emit(name) { for (const callback of [...(this.events.get(name) ?? [])]) callback(); } + } + class FakeObserver { + disconnected = false; + constructor(callback) { this.callback = callback; observers.push(this); } + observe() { this.observing = true; } + disconnect() { this.disconnected = true; } + } + const doc = new Emitter(); + doc.head = new FakeElement(doc); + doc.body = new FakeElement(doc); + doc.createElement = () => new FakeElement(doc); + const win = new Emitter(); + win.innerHeight = 1000; + const root = new FakeElement(doc); + const editor = new Emitter(); + editor.getElement = () => root; + + globalThis.HTMLElement = FakeElement; + globalThis.MutationObserver = FakeObserver; + globalThis.window = win; + globalThis.requestAnimationFrame = (callback) => { + const id = ++nextFrameId; + frames.set(id, callback); + return id; + }; + globalThis.cancelAnimationFrame = (id) => frames.delete(id); + return { + root, editor, doc, win, observers, frames, + restore() { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete globalThis[key]; + else globalThis[key] = value; + } + }, + }; +} + +test('removing TinyMCE editor disposes controls, observer and listeners', () => { + const f = fixture(); + try { + const dispose = installCollapsibleHeadings(f.editor); + assert.equal(f.doc.head.children.length, 1); + assert.equal(f.doc.body.children.length, 1); + assert.equal(f.editor.count('remove'), 1); + assert.equal(f.editor.count('SetContent'), 1); + assert.equal(f.editor.count('input'), 1); + assert.equal(f.doc.count('scroll'), 1); + assert.equal(f.win.count('resize'), 1); + assert.ok(f.root.attributes.has('data-cc-collapse-host')); + f.editor.emit('remove'); + assert.equal(f.doc.head.children.length, 0); + assert.equal(f.doc.body.children.length, 0); + assert.ok(f.observers[0].disconnected); + assert.equal(f.editor.count('remove'), 0); + assert.equal(f.editor.count('SetContent'), 0); + assert.equal(f.editor.count('input'), 0); + assert.equal(f.doc.count('scroll'), 0); + assert.equal(f.win.count('resize'), 0); + assert.ok(!f.root.attributes.has('data-cc-collapse-host')); + dispose(); // Must be safe even after the remove event. + } finally { f.restore(); } +}); + +test('reinstalling for the same editor does not duplicate controls', () => { + const f = fixture(); + try { + const first = installCollapsibleHeadings(f.editor); + const second = installCollapsibleHeadings(f.editor); + assert.ok(f.observers[0].disconnected); + assert.equal(f.doc.head.children.length, 1); + assert.equal(f.doc.body.children.length, 1); + assert.equal(f.editor.count('remove'), 1); + assert.equal(f.doc.count('scroll'), 1); + assert.equal(f.win.count('resize'), 1); + first(); // An old disposal callback must not break the second installation. + assert.equal(f.doc.head.children.length, 1); + second(); + assert.equal(f.doc.head.children.length, 0); + assert.equal(f.doc.body.children.length, 0); + } finally { f.restore(); } +}); + +test('dispose cancels pending mutation-driven refresh frames', () => { + const f = fixture(); + try { + installCollapsibleHeadings(f.editor); + f.editor.emit('input'); + assert.equal(f.frames.size, 1); + f.editor.emit('remove'); + assert.equal(f.frames.size, 0); + } finally { f.restore(); } +}); diff --git a/client/src/tests/collapsible-headings-nested.test.mjs b/client/src/tests/collapsible-headings-nested.test.mjs new file mode 100644 index 00000000..7a5da95b --- /dev/null +++ b/client/src/tests/collapsible-headings-nested.test.mjs @@ -0,0 +1,141 @@ +// Regression tests for CodeRabbit comments on nested Markdown headings and +// external control visibility. These validate our DOM-selection logic; the +// real TinyMCE renderer still needs an interactive browser smoke test. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { collectHeadings, installCollapsibleHeadings } from '../collapsible-headings.mts'; + +const originals = Object.fromEntries( + ['HTMLElement', 'MutationObserver', 'window', 'requestAnimationFrame', 'cancelAnimationFrame'] + .map((key) => [key, globalThis[key]]), +); + +function fixture() { + const listeners = new Map(); + const makeEmitter = (obj) => { + obj.addEventListener = (name, fn) => { + if (!listeners.has(obj)) listeners.set(obj, new Map()); + const map = listeners.get(obj); + if (!map.has(name)) map.set(name, new Set()); + map.get(name).add(fn); + }; + obj.removeEventListener = (name, fn) => listeners.get(obj)?.get(name)?.delete(fn); + obj.emit = (name) => { + for (const fn of listeners.get(obj)?.get(name) ?? []) fn(); + }; + return obj; + }; + class FakeElement { + constructor(tagName, doc, text = '') { + this.tagName = tagName.toUpperCase(); + this.ownerDocument = doc; + this.textContent = text; + this.id = ''; + this.children = []; + this.parentElement = null; + this.style = {}; + this.hidden = false; + this.rendered = true; + this.attributes = new Map(); + makeEmitter(this); + } + matches(selector) { return selector.toUpperCase().split(',').includes(this.tagName); } + setAttribute(name, value) { this.attributes.set(name, value); } + removeAttribute(name) { this.attributes.delete(name); } + appendChild(child) { child.parentElement = this; this.children.push(child); return child; } + replaceChildren(...children) { + this.children.forEach((c) => { c.parentElement = null; }); + this.children = []; + children.forEach((c) => this.appendChild(c)); + } + remove() { + if (!this.parentElement) return; + const siblings = this.parentElement.children; + siblings.splice(siblings.indexOf(this), 1); + this.parentElement = null; + } + getBoundingClientRect() { + return this.rendered + ? { left: 60, top: 20, bottom: 40, height: 20 } + : { left: 0, top: 0, bottom: 0, height: 0 }; + } + getClientRects() { return this.rendered ? [this.getBoundingClientRect()] : []; } + } + const doc = makeEmitter({}); + doc.createElement = (name) => new FakeElement(name, doc); + doc.head = doc.createElement('head'); + doc.body = doc.createElement('body'); + const win = makeEmitter({ innerHeight: 900 }); + const root = doc.createElement('div'); + const editor = { getElement: () => root, ...makeEmitter({}) }; + editor.on = editor.addEventListener; + editor.off = editor.removeEventListener; + globalThis.HTMLElement = FakeElement; + globalThis.MutationObserver = class { + observe() {} + disconnect() {} + }; + globalThis.window = win; + globalThis.requestAnimationFrame = (fn) => { fn(); return 1; }; + globalThis.cancelAnimationFrame = () => {}; + return { + root, doc, editor, win, + element(name, text = '') { return new FakeElement(name, doc, text); }, + restore() { + for (const [key, value] of Object.entries(originals)) { + if (value === undefined) delete globalThis[key]; + else globalThis[key] = value; + } + }, + }; +} + +test('finds headings nested in blockquotes and list items', () => { + const f = fixture(); + try { + const quote = f.root.appendChild(f.element('blockquote')); + const quoted = quote.appendChild(f.element('h2', 'Quoted')); + quote.appendChild(f.element('p', 'Inside')); + const list = f.root.appendChild(f.element('ul')); + const item = list.appendChild(f.element('li')); + const listed = item.appendChild(f.element('h3', 'Listed')); + const headings = collectHeadings(f.root, []); + assert.deepEqual(headings.map((h) => h.element), [quoted, listed]); + assert.deepEqual(headings.map((h) => h.childIndex), [1, 1]); + assert.deepEqual(headings.map((h) => h.parent), [quote, item]); + } finally { f.restore(); } +}); + +test('folding quoted heading hides only within the quote, not outside content', () => { + const f = fixture(); + try { + const quote = f.root.appendChild(f.element('blockquote')); + quote.appendChild(f.element('h2', 'Quoted')); + quote.appendChild(f.element('p', 'Inside')); + f.root.appendChild(f.element('p', 'Outside')); + const dispose = installCollapsibleHeadings(f.editor); + const button = f.doc.body.children[0].children[0]; + button.emit('click'); + const css = f.doc.head.children[0].textContent; + assert.match(css, /nth-child\(1\) > :nth-child\(n\+2\):nth-child\(-n\+2\)/); + assert.doesNotMatch(css, /\[data-cc-collapse-host="[^"]+"\] > :nth-child\(n\+2\)/); + dispose(); + } finally { f.restore(); } +}); + +test('external buttons are hidden when their heading has no rendered rectangle', () => { + const f = fixture(); + try { + const outer = f.root.appendChild(f.element('h2', 'Parent')); + const quote = f.root.appendChild(f.element('blockquote')); + const nested = quote.appendChild(f.element('h3', 'Child')); + quote.appendChild(f.element('p', 'Nested details')); + const dispose = installCollapsibleHeadings(f.editor); + assert.equal(f.doc.body.children[0].children.length, 2); + nested.rendered = false; // Simulate CSS display:none on the parent container. + f.doc.emit('scroll'); + assert.equal(f.doc.body.children[0].children[1].hidden, true); + assert.equal(f.doc.body.children[0].children[0].hidden, false); + dispose(); + } finally { f.restore(); } +}); diff --git a/client/src/tests/collapsible-headings.test.mjs b/client/src/tests/collapsible-headings.test.mjs new file mode 100644 index 00000000..7643035b --- /dev/null +++ b/client/src/tests/collapsible-headings.test.mjs @@ -0,0 +1,51 @@ +// Tests for the pure section-boundary algorithm used by the +// Collapsing headings 2 prototype. These do not replace browser UI tests. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { sectionEnd } from '../collapsible-headings.mts'; + +// childIndex is 1-based and refers to a direct child of the editor root. +test('h2 section stops immediately before the next h2', () => { + const headings = [{ level: 2, childIndex: 1 }, { level: 2, childIndex: 5 }]; + assert.equal(sectionEnd(headings, 0, 7), 4); +}); + +test('h2 section includes nested h3 and h4 headings', () => { + const headings = [ + { level: 2, childIndex: 1 }, + { level: 3, childIndex: 3 }, + { level: 4, childIndex: 5 }, + { level: 2, childIndex: 8 }, + ]; + assert.equal(sectionEnd(headings, 0, 10), 7); +}); + +test('section ends before a higher-level heading', () => { + const headings = [ + { level: 3, childIndex: 2 }, + { level: 2, childIndex: 6 }, + ]; + assert.equal(sectionEnd(headings, 0, 9), 5); +}); + +test('last heading section continues through the end of the document', () => { + assert.equal(sectionEnd([{ level: 1, childIndex: 2 }], 0, 12), 12); +}); + +test('empty section ends at its own heading', () => { + const headings = [ + { level: 2, childIndex: 3 }, + { level: 2, childIndex: 4 }, + ]; + assert.equal(sectionEnd(headings, 0, 8), 3); +}); + +test('nested h3 section stops at another h3 within the same h2', () => { + const headings = [ + { level: 2, childIndex: 1 }, + { level: 3, childIndex: 3 }, + { level: 3, childIndex: 6 }, + { level: 2, childIndex: 10 }, + ]; + assert.equal(sectionEnd(headings, 1, 12), 5); +}); diff --git a/client/src/tests/duplicate-heading-identity.test.mjs b/client/src/tests/duplicate-heading-identity.test.mjs new file mode 100644 index 00000000..be3220ff --- /dev/null +++ b/client/src/tests/duplicate-heading-identity.test.mjs @@ -0,0 +1,54 @@ +import test, { after } from 'node:test'; +import assert from 'node:assert/strict'; +import { collectHeadings } from '../collapsible-headings.mts'; + +const savedHTMLElement = globalThis.HTMLElement; +class Heading { + constructor(name, text, id = '') { + this.tagName = name; + this.textContent = text; + this.id = id; + } + matches(selector) { return selector.split(',').includes(this.tagName.toLowerCase()); } +} +globalThis.HTMLElement = Heading; +after(() => { globalThis.HTMLElement = savedHTMLElement; }); + +test('identically named headings each receive independent active identities', () => { + const a = new Heading('H2', 'Overview'); + const b = new Heading('H2', 'Overview'); + const initial = collectHeadings({children: [a, b]}, []); + assert.equal(initial.length, 2); + assert.ok(initial.every((entry) => typeof entry.key === 'string' && entry.key.length > 0)); + assert.notEqual(initial[0].key, initial[1].key); + const reloaded = collectHeadings({children: [a, b]}, initial); + assert.deepEqual(reloaded.map((entry) => entry.key), initial.map((entry) => entry.key)); + }); + + test('editing text of one duplicate preserves its own identity', () => { + const a = new Heading('H2', 'Overview'); + const b = new Heading('H2', 'Overview'); + const initial = collectHeadings({children: [a, b]}, []); + a.textContent = 'Introduction'; + const updated = collectHeadings({children: [a, b]}, initial); + assert.deepEqual(updated.map((entry) => entry.key), initial.map((entry) => entry.key)); + }); + + test('recreated identical nodes are not mistakenly assigned the old fold states', () => { + const initial = collectHeadings({children: [new Heading('H2', 'Overview'), new Heading('H2', 'Overview')]}, []); + const updated = collectHeadings({children: [new Heading('H2', 'Overview'), new Heading('H2', 'Overview')]}, initial); + assert.equal(new Set(updated.map((entry) => entry.key)).size, 2); + assert.ok(updated.every((entry) => !initial.some((old) => old.key === entry.key))); + }); + + test('a unique explicit heading ID survives DOM replacement', () => { + const initial = collectHeadings({children: [new Heading('H2', 'Overview', 'section-1')]}, []); + const updated = collectHeadings({children: [new Heading('H2', 'Renamed', 'section-1')]}, initial); + assert.equal(updated[0].key, initial[0].key); + }); + + test('a unique heading label survives DOM replacement', () => { + const initial = collectHeadings({children: [new Heading('H3', 'Unique title')]}, []); + const updated = collectHeadings({children: [new Heading('H3', 'Unique title')]}, initial); + assert.equal(updated[0].key, initial[0].key); + }); diff --git a/client/src/tests/mixed-heading-ranges.test.mjs b/client/src/tests/mixed-heading-ranges.test.mjs new file mode 100644 index 00000000..56d0b56c --- /dev/null +++ b/client/src/tests/mixed-heading-ranges.test.mjs @@ -0,0 +1,60 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { getMixedFoldPlan } from '../mixed-heading-ranges.mts'; + +const blocks = [ + { from: 0, to: 8, childCount: 4 }, // Title, intro, Section A, description + { from: 15, to: 21, childCount: 2 }, // Nested section + paragraph + { from: 28, to: 35, childCount: 2 }, // Section B + paragraph + { from: 42, to: 49, childCount: 2 }, // Final Section + paragraph +]; +const headings = [ + { key: 'h1', level: 1, blockFrom: 0, childIndex: 1 }, + { key: 'a', level: 2, blockFrom: 0, childIndex: 3 }, + { key: 'nested', level: 3, blockFrom: 15, childIndex: 1 }, + { key: 'b', level: 2, blockFrom: 28, childIndex: 1 }, + { key: 'final', level: 1, blockFrom: 42, childIndex: 1 }, +]; +const plan = (keys) => getMixedFoldPlan(blocks, headings, new Set(keys), 60); + +test('Section A hides its paragraph, nested doc block and code before B', () => { + assert.deepEqual(plan(['a']), { + docSlices: [ + { blockFrom: 0, firstChild: 4, lastChild: 4 }, + { blockFrom: 15, firstChild: 1, lastChild: 2 }, + ], + codeSpans: [{ from: 8, to: 28 }], + }); +}); + +test('Nested subsection stops at next h2', () => { + assert.deepEqual(plan(['nested']), { + docSlices: [{ blockFrom: 15, firstChild: 2, lastChild: 2 }], + codeSpans: [{ from: 21, to: 28 }], + }); +}); + +test('Section B stops before Final Section', () => { + assert.deepEqual(plan(['b']), { + docSlices: [{ blockFrom: 28, firstChild: 2, lastChild: 2 }], + codeSpans: [{ from: 35, to: 42 }], + }); +}); + +test('Last heading continues through end of source', () => { + assert.deepEqual(plan(['final']), { + docSlices: [{ blockFrom: 42, firstChild: 2, lastChild: 2 }], + codeSpans: [{ from: 49, to: 60 }], + }); +}); + +test('Multiple collapsed sections preserve their independent boundaries', () => { + assert.deepEqual(plan(['nested', 'b']).docSlices, [ + { blockFrom: 15, firstChild: 2, lastChild: 2 }, + { blockFrom: 28, firstChild: 2, lastChild: 2 }, + ]); +}); + +test('No folds means no hidden source', () => { + assert.deepEqual(plan([]), { docSlices: [], codeSpans: [] }); +}); diff --git a/client/src/tests/mixed-heading-state.test.mjs b/client/src/tests/mixed-heading-state.test.mjs new file mode 100644 index 00000000..c77a882e --- /dev/null +++ b/client/src/tests/mixed-heading-state.test.mjs @@ -0,0 +1,80 @@ + +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { remapMixedCollapsedKeys } from '../mixed-heading-ranges.mts'; +const heading = (key, blockFrom, childIndex, label, level = 2, id) => ({ key, blockFrom, childIndex, label, level, id }); +const remap = (before, after, keys, change = (pos) => pos) => + remapMixedCollapsedKeys(before, after, new Set(keys), change); + +test('preserves Section A after inserting source code before its doc block', () => { + const before = [heading('10:1', 10, 1, 'Section A')]; + const after = [heading('32:1', 32, 1, 'Section A')]; + const mapped = remap(before, after, ['10:1'], (pos) => pos + 22); + assert.deepEqual([...mapped], ['32:1']); +}); + +test('preserves a heading in a block at zero when a prefix is inserted', () => { + const before = [heading('0:3', 0, 3, 'Section A')]; + const after = [heading('0:3', 0, 3, 'Section A')]; + assert.deepEqual([...remap(before, after, ['0:3'], (pos, assoc) => assoc < 0 ? pos : pos + 20)], ['0:3']); +}); + +test('preserves a heading after doc-block restructuring', () => { + const before = [heading('0:3', 0, 3, 'Section A')]; + const after = [heading('24:1', 24, 1, 'Section A')]; + assert.deepEqual([...remap(before, after, ['0:3'])], ['24:1']); +}); + +test('does not transfer a deleted heading state to an unrelated heading', () => { + const before = [heading('8:1', 8, 1, 'Section A')]; + const after = [heading('20:1', 20, 1, 'Section B')]; + assert.deepEqual([...remap(before, after, ['8:1'])], []); +}); + +test('uses heading IDs before labels', () => { + const before = [heading('2:1', 2, 1, 'Old title', 2, 'stable-heading')]; + const after = [heading('8:2', 8, 2, 'New title', 2, 'stable-heading')]; + assert.deepEqual([...remap(before, after, ['2:1'])], ['8:2']); +}); + +test('keeps two same-named headings separate when positions shift', () => { + const before = [heading('10:1', 10, 1, 'Overview'), heading('80:1', 80, 1, 'Overview')]; + const after = [heading('15:1', 15, 1, 'Overview'), heading('85:1', 85, 1, 'Overview')]; + assert.deepEqual([...remap(before, after, ['10:1', '80:1'], (pos) => pos + 5)].sort(), ['15:1', '85:1']); +}); + +test('preserves a renamed heading at the identical mapped block and child index', () => { + const before = [heading('15:2', 15, 2, 'Old name')]; + const after = [heading('18:2', 18, 2, 'New name')]; + assert.deepEqual([...remap(before, after, ['15:2'], (pos) => pos + 3)], ['18:2']); +}); + +test('deleted duplicate heading cannot transfer its collapse state to remaining twin', () => { + const before = [heading('10:1', 10, 1, 'Overview'), heading('80:1', 80, 1, 'Overview')]; + const after = [heading('80:1', 80, 1, 'Overview')]; + assert.deepEqual([...remap(before, after, ['10:1'])], []); +}); + +test('inserting another equal heading resets ambiguous matching rather than folding a new sibling', () => { + const before = [heading('10:1', 10, 1, 'Overview'), heading('80:1', 80, 1, 'Overview')]; + const after = [heading('10:1', 10, 1, 'Overview'), heading('45:1', 45, 1, 'Overview'), heading('80:1', 80, 1, 'Overview')]; + assert.deepEqual([...remap(before, after, ['10:1'])], []); +}); + +test('unchanged duplicate count does not transfer state to a sibling after inserting paragraphs', () => { + const before = [heading('0:1', 0, 1, 'Overview'), heading('0:3', 0, 3, 'Overview')]; + const after = [heading('0:3', 0, 3, 'Overview'), heading('0:5', 0, 5, 'Overview')]; + assert.deepEqual([...remap(before, after, ['0:3'])], []); +}); + +test('a unique label takes priority over an old positional address', () => { + const before = [heading('0:1', 0, 1, 'Section A')]; + const after = [heading('0:1', 0, 1, 'Section X'), heading('0:3', 0, 3, 'Section A')]; + assert.deepEqual([...remap(before, after, ['0:1'])], ['0:3']); +}); + +test('stable same-block duplicate signatures can retain distinct fold states', () => { + const before = [heading('0:1', 0, 1, 'Overview'), heading('0:3', 0, 3, 'Overview')]; + const after = [heading('0:1', 0, 1, 'Overview'), heading('0:3', 0, 3, 'Overview')]; + assert.deepEqual([...remap(before, after, ['0:3'])], ['0:3']); +}); diff --git a/docs/design.md b/docs/design.md index 0f9a568e..5afd5955 100644 --- a/docs/design.md +++ b/docs/design.md @@ -108,8 +108,7 @@ These form a set of high-level requirements to guide the project. * A report view: an extended gathering element that operates more like a query, producing nested, hierarchical results from the codebase. - * Headings can be collapsed, which code code and doc blocks until the next - same-level heading. + * Headings can be collapsed, hiding all content, including nested headings, code blocks, and doc blocks, until the next heading of the same or a higher level. * A graph view: shows the entire document as a directed graph of hyperlinks. @@ -157,6 +156,101 @@ These form a set of high-level requirements to guide the project. -------------------------------------- The requirements expand on the vision by providing additional details. +### Collapsible headings + +The CodeChat Editor shall allow users to collapse and expand sections of a document by interacting with a control displayed next to each heading. +All headings shall initially be displayed in the expanded state when a document is first opened. + +#### 1. Collapse and expand controls + +- Each rendered Markdown heading, from level 1 to level 6, shall display a collapse/expand control. +- The control shall indicate whether the corresponding section is currently expanded or collapsed. +- Clicking an expanded heading's control shall collapse its section. +- Clicking a collapsed heading's control shall expand its section. +- The heading itself shall remain visible in both states. + +#### 2. Section boundaries + +A heading's section consists of all content following that heading, up to but not including the next heading of the same or a higher level. + +For example, collapsing a level 2 heading shall hide its paragraphs, code blocks, and nested level 3 through level 6 headings. It shall not hide the next level 2 or level 1 heading. + +If no subsequent heading of the same or a higher level exists, the section continues to the end of the document. +Only headings recognized by the Markdown parser shall define collapsible sections. Heading-like text inside fenced code blocks shall not be treated as a heading. + +A heading with no content before the next heading of the same or a higher level shall still display a collapse/expand control. Collapsing an empty section shall update the control to its collapsed state without hiding any unrelated content. Expanding it shall restore the control to its expanded state. + +#### 3. Nested headings + +- Collapsing a parent heading shall hide all content belonging to its section, including nested headings and their content. +- Expanding the parent shall restore its section. +- Nested headings shall retain their previous expanded or collapsed states while the parent section is collapsed. +- Collapsing one heading shall not affect independent sections outside its boundaries. + +#### 4. Code blocks and document blocks + +- All code blocks and documentation blocks within a collapsed section shall be hidden. +- Expanding the section shall restore those blocks without modifying their contents. +- The collapse operation shall affect visibility only and shall not delete or rewrite source content. + +#### 5. User interaction + +- Collapse and expand controls shall be operable with a mouse and keyboard. +- The current expanded or collapsed state shall be available to assistive technologies. +- A user shall be able to repeatedly collapse and expand a section without losing content. +- Each collapse/expand control shall be keyboard-focusable and activated using Enter or Space. Its accessible name and expanded state shall be exposed to assistive technologies. + +#### 6. Document updates + +When a document is edited, the displayed heading structure and the boundaries of collapsible sections shall reflect the updated document. Collapsing and expanding shall not alter the Markdown source. + +A heading's expanded or collapsed state shall be preserved when the editor can associate the heading before and after an edit using its existing document identity information. If the heading cannot be matched unambiguously, its state shall default to expanded. This requirement does not prescribe a new heading identification mechanism. + +#### 7. Verification scenarios + +The implementation shall be verified using the following scenarios: + +1. Collapse a heading containing a paragraph and verify that the paragraph becomes hidden. +2. Expand the same heading and verify that its content becomes visible again. +3. Collapse a parent heading containing nested headings and verify that all nested content becomes hidden. +4. Collapse a heading containing code blocks and verify that the code blocks become hidden without modification. +5. Verify that a heading of the same or a higher level remains visible when the preceding section is collapsed. +6. Collapse a nested heading, collapse its parent, then expand the parent and verify that the nested heading retains its collapsed state. +7. Verify that the controls can be activated using a keyboard. +8. Edit a document's heading structure and verify that subsequent collapse operations use the updated section boundaries. + +#### 8. Additional findings and implementation considerations + +These notes supplement the existing requirements and leave implementation +choices open. + +Extend the existing heading-collapse implementation, using the specified +section boundaries to coordinate visibility across documentation and code +blocks. + +Use the existing heading-boundary rule to determine the content to hide, +independently of the chosen visibility mechanism. + +* HTML [`
` and ``](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/details) + provide a useful disclosure model: the label remains visible while the + contents are hidden. If used, the initial `open` state must match the + expanded-by-default requirement. A shared `name` creates an exclusive + accordion, which would conflict with independent sections. Any generated + disclosure markup must preserve the existing source-preservation requirement. +* CodeMirror's [language-data](https://codemirror.net/docs/ref/#language-data) + package lists available language descriptions; folding support is documented + under [`codeFolding`](https://codemirror.net/docs/ref/#language.codeFolding) + and [`foldService`](https://codemirror.net/docs/ref/#language.foldService). + These are options to evaluate for mixed code/documentation sections, whose + heading boundaries may span several editor blocks. +* The current implementation discovers headings inside lists and blockquotes + in Markdown-only mode, but only direct-child headings in mixed mode. Check + these cases against the existing heading requirements. Browser verification + should also cover scrolling and cursor movement across large collapsed + sections: the current mixed-mode implementation hides code lines with CSS, + and the focused tests do not establish correct editor layout behavior. + Verify that expanding a section restores its content and that scrolling + and cursor movement remain usable across folded regions. ### Code blocks and doc blocks diff --git a/submission.md b/submission.md new file mode 100644 index 00000000..d9fb5987 --- /dev/null +++ b/submission.md @@ -0,0 +1,670 @@ +# Project 2 Submission — Collapsing Headings 2 + +## Team + +- **Gazizuly Yerassyl** — GitHub: `egazizuly` — e_gazizuly@kbtu.kz +- **Koshkinbayeva Aidana** — ai_koshkinbayeva@kbtu.kz +- **Kuanyshbekov Madi** — ma_kuanyshbekov@kbtu.kz +- **Shyngysuly Sanzhar** — s_shyngysuly@kbtu.kz + +**Project:** Collapsing Headings 2 + +**Repository:** `egazizuly/CodeChat_Editor` + +**Branch:** `collapsing-headings-2` + +**Specification:** `docs/design.md`, under **Requirements → Collapsible headings**. + +--- + +# Draft Submission + +## Contributions + +### Gazizuly Yerassyl + +Developed the initial specification for collapsible headings in the CodeChat Editor. + +The specification addressed the following requirements: + +- Identification of Markdown headings from levels H1 to H6. +- Collapse and expand controls next to headings. +- Definition of section boundaries based on heading hierarchy. +- Support for nested headings and subsections. +- Visibility of code blocks and documentation blocks. +- Preservation of source content during collapsing and expanding. +- Keyboard accessibility and document-update behavior. +- Verification scenarios for ordinary, nested, and empty sections. + +The specification was refined through three LLM-assisted review rounds. The revisions focused on improving consistency, resolving ambiguities, and clarifying the expected behavior of the feature. + +### Other Team Members + +- **Koshkinbayeva Aidana:** Individual draft contribution and commit identifier pending confirmation. +- **Kuanyshbekov Madi:** See the individual draft contribution and review below. +- **Shyngysuly Sanzhar:** Individual draft contribution and commit identifier pending confirmation. + +## Compiler / Build-and-Run Test + +**Draft-stage status:** The complete local implementation and build had not yet been verified during the initial specification review. + +The documented build procedure included installing Rust and Node.js/npm, installing project dependencies, and building the CodeChat Editor. + +The implementation and successful local build were completed later and are recorded in the Final Submission section. + +On Windows, the documented `cargo run -- start ../README.md` command was attempted from the `server` directory but failed because the selected package did not provide a binary target. The working editor was subsequently tested using the VS Code Extension Development Host. + +## Specification Review Rounds + +| Round | Findings | Main Changes Made | +|---|---|---| +| 1 | 5 findings | Clarified Markdown heading recognition, initially expanded headings, empty-section behavior, document updates, and keyboard accessibility. | +| 2 | 3 findings | Corrected the inconsistency between Vision and Requirements regarding section boundaries. Clarified state preservation and behavior when collapsing empty sections. | +| 3 | 1 low-severity finding | Identified redundant wording regarding heading-state preservation and recommended simplifying the Document updates requirements. | + +## Last Specification Review + +**LLM:** ChatGPT (GPT-6) + +**Review prompt (recorded review objective):** + +> Review the revised Collapsible headings requirements in docs/design.md after the second review round. Check whether the previous issues concerning conflicting section boundaries, ambiguous state preservation, and empty-section behavior have been addressed. Identify any remaining substantive contradictions or redundant requirements. Report findings by severity. + +### LLM Review Output (Summarized) + +The revised specification resolved the major inconsistencies identified during the previous rounds. + +The section-boundary rule consistently specifies that a section extends from its heading to the next heading of the same or higher level. + +Empty-section behavior is explicitly described, and the requirements clarify how expanded and collapsed states should be managed after document updates. + +**Remaining finding — Low severity:** + +The Document updates subsection contained repeated wording about preserving heading states. + +**Recommendation:** + +Consolidate the duplicated requirements while retaining the following behavior: + +- Changes to the document must update the displayed heading structure. +- Collapsing and expanding must not modify the original Markdown source. +- A heading's previous state should be preserved when the editor can reliably identify the corresponding heading after an edit. +- If a heading cannot be matched unambiguously, it should default to expanded. + +No other substantive contradictions were identified within the reviewed scope. + +--- + +# Draft Submission — Kuanyshbekov Madi + +## Contributions + +### Kuanyshbekov Madi + +**GitHub userid:** `makuanyshbekov` + +Added a concise implementation strategy, reference findings, and verification +considerations to [Section 8 of the specification](docs/design.md#8-additional-findings-and-implementation-considerations). + +The additional section addressed the following considerations: + +- Extending the existing implementation using the specified heading boundaries. +- HTML disclosure behavior and preservation of independent section states. +- CodeMirror folding references for mixed code/documentation sections. +- Differences in heading discovery inside lists and blockquotes. +- Verification of content restoration, scrolling, and cursor movement. + +The section was refined through three LLM-assisted review rounds. Small +clarifications made the strategy, expected verification outcomes, and the +distinction between section boundaries and folding mechanisms explicit without +changing the teammate's existing requirements. + +## Compiler / Build-and-Run Test + +**Draft-stage status:** Build and run verification has not been performed for +this documentation contribution. + +The prompt "Verify that +you can build and run the project in the current git repo." has not yet been +executed for this contribution; the teammate's results elsewhere in this +document are separate evidence. + +## Specification Review Rounds + +Only the added Section 8 was reviewed; the existing requirements were outside +the review scope. + +| Round | Findings | Main Changes Made | +| ----- | -------- | ----------------- | +| 1 | 2 findings | Clarified the strategy of extending the existing implementation and the expected outcome of mixed-mode scrolling and cursor checks. | +| 2 | 1 minor finding | Clarified that the existing heading hierarchy determines section boundaries independently of the chosen folding mechanism. | +| 3 | 1 minor finding | Simplified the boundary clarification to keep the visibility mechanism an implementation choice. | + +## Last Specification Review + +**LLM:** GPT-6 (Codex) + +**Review prompt (recorded review objective):** + +> Review only "8. Additional findings and implementation considerations" again +> for relevant severe, medium, or minor findings and small clarifications. +> Avoid significant changes or overspecification. Refer to the MDN details +> element documentation and the CodeMirror language-data reference. + +References: [MDN details](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/details) +and [CodeMirror language-data](https://codemirror.net/docs/ref/#language-data), +with folding behavior documented under +[foldService](https://codemirror.net/docs/ref/#language.foldService). + +### LLM Review Output (Summarized) + +**Finding — Minor wording issue: preserve implementation choice:** + +The statement that HTML disclosure elements or CodeMirror folding support +"provide the visibility mechanism" sounded like a required implementation +choice, despite the section's intent to leave implementation choices open. + +**Recommendation:** + +Use the existing heading-boundary rule to determine the content to hide, +independently of the chosen visibility mechanism. + +The finding was addressed by simplifying the existing sentence in Section 8. +No severe or medium findings were identified in Round 3. This is a wording +improvement, not a demonstrated functional defect; the review does not +establish successful build/run verification. + +--- + +# Final Submission — reviewed on 2026-12-01 + +## Contributions + +### Gazizuly Yerassyl + +**GitHub userid:** `egazizuly` + +**University email:** `e_gazizuly@kbtu.kz` + +Implemented collapsible headings in the CodeChat Editor for Markdown-only documents and mixed code/documentation files. + +### Implementation Contributions + +**1. Markdown-only heading collapsing** + +Developed `client/src/collapsible-headings.mts` to provide interactive collapsing and expanding of Markdown sections. + +The implementation supports: + +- Heading levels H1 through H6. +- Collapse and expand controls. +- Nested section boundaries. +- Preservation of unrelated sections. +- Restoration of hidden content when a section is expanded. + +Integrated the functionality into `client/src/CodeChatEditor.mts`, using the existing TinyMCE-based editor architecture. + +**2. Mixed code/documentation support** + +Implemented collapsing for mixed-source documents, including C++ files containing Markdown documentation comments. + +Modified `client/src/CodeMirror-integration.mts` and added `client/src/mixed-heading-ranges.mts`. + +The implementation supports: + +- Collapsing documentation sections. +- Hiding associated source-code blocks. +- Collapsing nested documentation and code. +- Preserving independent sections. +- Expanding hidden content without deleting the original source. + +**3. Heading-state preservation** + +Identified and reproduced a problem where inserting text before a collapsed heading caused the heading to expand automatically. + +Developed a local correction to preserve heading states when document positions change. + +Manual testing confirmed that the collapsed section remained collapsed after inserting a new comment before its heading. + +The section could still be expanded and collapsed manually after editing. + +The correction was subsequently verified through a successful local build and 7 focused heading-state regression tests. It was committed and pushed as `092ebdd`. + +**4. TinyMCE lifecycle cleanup** + +Updated `client/src/CodeChatEditor.mts` and `client/src/collapsible-headings.mts` to dispose of heading controls and event listeners when TinyMCE is removed or reinstalled. Added `client/src/tests/collapsible-headings-lifecycle.test.mjs` with three mocked lifecycle tests. The author manually confirmed that controls continued working after reopening a document. This work was committed as `6f4e905`. + +**5. Duplicate heading identities and ambiguous state matching** + +Updated `client/src/collapsible-headings.mts` so repeated Markdown headings without unique HTML IDs receive independent active collapse/expand controls. The UI assigns transient per-heading identities and does not write them into the Markdown source. + +Updated `client/src/mixed-heading-ranges.mts` to avoid transferring collapsed state to an unrelated same-named heading in tested ambiguous deletion/insertion scenarios. Added `client/src/tests/duplicate-heading-identity.test.mjs` and extended `mixed-heading-state.test.mjs`. + +The correction was validated by the 29-test Node.js regression suite and a successful subsequent Windows build, and committed as `fd28a32`. The complete browser-level duplicate-heading scenario still requires a separately recorded result if it has not been performed. + +**6. Testing and validation** + +Created automated tests covering: + +- Heading boundaries. +- Nested sections. +- Independent sections. +- Empty sections. +- Code and documentation visibility. +- Section boundaries extending to the end of a document. + +Conducted manual testing in the VS Code Extension Development Host. + +Verified the behavior using `docs/design.md`, `docs/style_guide.cpp`, and the temporary `examples/collapsing-headings-smoke.cpp` file. + +### Confirmed Git Commits + +| Commit | Description | +|---|---| +| `1a6e8c0` | Implement collapsible Markdown headings with regression tests | +| `7a5f4dc` | Implement collapsible headings across mixed code and documentation | +| `092ebdd` | Preserve collapsed heading states after document edits | +| `6f4e905` | Fix TinyMCE heading controls lifecycle cleanup | +| `fd28a32` | Fix duplicate heading identities and preserve independent fold states | + +All five commits were authored by Gazizuly Yerassyl using the university email address and pushed to the `collapsing-headings-2` branch (confirmed by the supplied Git terminal screenshots). + +### Other Team Members + +- **Koshkinbayeva Aidana:** Individual contribution and commit identifier pending verification. +- **Kuanyshbekov Madi:** Individual contribution and commit identifier pending verification. +- **Shyngysuly Sanzhar:** Individual contribution and commit identifier pending verification. + +The reported contributions are limited to work that can be confirmed. Additional team-member contributions should be added after verifying their Git history. + +## Compiler / Build-and-Run Test + +### Development Environment + +- Operating system: Windows +- Programming languages: Rust, TypeScript, JavaScript +- Development environment: Visual Studio Code +- Package and build tools: Cargo, Node.js, npm, CodeChat Editor build tool +- Test framework: Node.js built-in test runner +- Application testing: VS Code Extension Development Host + +### Build Command + +Executed from the repository root: + +`.\bt build` + +**Result: Passed** + +The CodeChat Editor completed the build process without critical compilation errors. + +Warnings concerning unused Rust dependencies were reported, but they did not prevent the build from completing. + +### Automated Tests + +| Verification | Result | +|---|---| +| CodeChat Editor build | Passed | +| Markdown heading boundary tests | 6 passed | +| Mixed-mode heading boundary tests | 6 passed | +| Mixed-mode heading-state regression tests | 9 passed | +| TinyMCE lifecycle mock tests | 3 passed | +| Duplicate heading identity tests | 5 passed | +| Five Node.js test suites after the duplicate-heading fix | **29 passed, 0 failed** (user terminal and independent rerun, 2026-12-01) | +| Rust server tests during build | 13 passed, 196 skipped | +| Manual Markdown collapse/expand testing | Passed | +| Manual mixed-mode collapse/expand testing | Passed | +| Nested heading and code visibility | Passed | +| Source-file preservation in the final save comparison | Passed | +| Heading-state preservation after source editing | Passed in the tested manual scenario | + +The five suites can be run together from the repository root: + +```powershell +node --experimental-strip-types --test .\client\src\tests\*.test.mjs +``` + +The reviewer reran all 29 tests successfully using the final patched source and test files in their expected relative directory structure. This does **not** establish a successful complete Rust/VS Code build in that environment, because the partial source package omits the full repository and dependencies. A successful full Windows build after the duplicate-heading fix is supported by the author's terminal screenshot. + +### Manual Testing + +**Test 1 — Markdown-only document** + +Opened `docs/design.md` in CodeChat Editor. + +Collapsed and expanded headings at different levels. + +**Result:** The heading controls operated successfully, and the tested nested sections followed the expected boundaries. + +**Test 2 — Mixed code/documentation document** + +Opened `docs/style_guide.cpp`. + +Confirmed that the editor displayed both Markdown documentation and C++ source code. + +**Result:** The mixed-mode document rendered successfully. + +**Test 3 — Nested mixed-mode sections** + +Created a temporary C++ test document containing: + +- Section A +- Nested Section +- Section B +- Final Section + +Collapsed Section A. + +**Expected behavior:** Section A's documentation, associated code, and nested subsection should be hidden, while Section B and Final Section remain visible. + +**Observed result:** The tested sections behaved as expected. + +**Test 4 — Source-file preservation** + +Compared SHA-256 hashes before and after collapse, expand, and save operations. + +**Observed result:** The final comparison returned `True`, indicating identical file contents in that test. + +An earlier comparison had returned `False`, but the original C++ statements remained intact. A subsequent controlled comparison returned `True`. + +**Test 5 — State preservation after editing** + +Collapsed Section A, inserted a temporary comment before the section, and observed its state. + +**Initial result:** Section A expanded unexpectedly. + +**After the local correction:** Section A remained collapsed after editing and could still be manually expanded or collapsed. + +This confirmed the correction in the tested scenario. + +--- + +## Specification Review Rounds + +| Round | Findings | Main Changes Made | +|---|---|---| +| 1 | 1 medium-severity implementation-conformance risk | Compared the finalized requirements with the Markdown-only and mixed-mode implementation. Identified a potential mismatch involving preservation of collapsed heading states after document edits. No specification change was necessary in the reviewed scope; implementation verification was recommended. | + +## Last Specification Review + +**LLM:** ChatGPT (GPT-6) + +### Review Prompt + +> Review the Collapsible headings requirements in docs/design.md against the implemented functionality. Check section boundaries, nested headings, code and documentation blocks, preservation of source content, and heading-state behavior after document updates. Identify specification contradictions and implementation-conformance risks. Report findings by severity. + +### LLM Review Output (Summarized) + +The specification consistently defines the expected boundaries of collapsible sections. + +A section extends to the next heading of the same or higher level. Nested sections are included within their parent section. + +The tested implementation demonstrated correct behavior for Markdown-only documents and mixed code/documentation examples. + +**Finding 1 — Medium severity: Heading-state preservation** + +The implementation originally identified mixed-mode headings using document positions and child indices. + +When source content was inserted before a heading, the heading position could change and cause the previously collapsed state to be lost. + +**Recommendation:** + +Test heading-state preservation after edits and improve the heading identification or state-mapping mechanism if necessary. + +**Follow-up:** + +The issue was subsequently reproduced through manual testing. A local implementation fix was developed, and the tested scenario passed after the correction. + +This follow-up is recorded as an implementation change, not as an additional specification-review round. + +**Conclusion:** + +No other substantive specification contradictions were identified within the scope of the review. + +--- + +## Implementation Review Rounds + +| Round | Findings | Main Changes Made | +|---|---|---| +| 1 | 3 findings: 1 medium-severity state-preservation issue, 1 low-severity lifecycle risk, and 1 medium-severity testing gap | Reproduced and fixed state loss (`092ebdd`), addressed lifecycle cleanup (`6f4e905`), and added tests. The browser integration coverage gap remains partially open. | +| 2 (2026-12-01) | 2 reproducible source-level conformance concerns and 2 verification risks | Reran four test suites (22/22 passed) and reviewed post-fix code against `docs/design.md`. Identified inoperable controls for duplicate no-ID headings, unsafe state association for ambiguous matches, a CodeMirror layout risk, and missing end-to-end coverage. These observations led to the fifth commit. | +| 3 (2026-12-01) | 2 earlier source-level findings addressed in focused tests; 2 verification limitations remain | Added independent identities for duplicate Markdown headings and safer mixed-mode state remapping (`fd28a32`); added seven regression cases, bringing the total to 29 passing tests. The author rebuilt the project successfully on Windows. The review still recommends browser-level accessibility and large-document scrolling checks. | + +## Implementation Review Round 1 — Details + +**LLM:** ChatGPT (GPT-6) + +**Review scope:** Implementation before the local heading-state preservation correction. + +### Review Prompt + +> Review the Collapsible headings implementation in client/src/collapsible-headings.mts, client/src/CodeChatEditor.mts, client/src/CodeMirror-integration.mts, and client/src/mixed-heading-ranges.mts against the requirements in docs/design.md. +> +> Evaluate heading boundaries, nested sections, code and documentation visibility, preservation of source content, heading-state behavior after document edits, lifecycle cleanup, and test coverage. +> +> Identify implementation defects and risks by severity. Distinguish verified behavior from untested assumptions. + +### LLM Review Output (Summarized) + +**Verified behavior in the reviewed implementation:** + +- Markdown-only heading collapsing and expanding operated successfully. +- Mixed-mode sections could hide documentation and associated source code. +- Nested sections followed the expected boundaries in the tested scenarios. +- Independent sections remained visible. +- The recorded 12 section-boundary tests passed. +- The project completed a successful local build. +- A controlled SHA-256 comparison confirmed source-file preservation in the tested save scenario. + +### Finding 1 — Medium Severity: Heading-State Preservation + +**Issue:** + +Mixed-mode heading identifiers depended on document positions and child indices. + +When text was inserted before an existing heading, the identifier could change and the collapsed state could be lost. + +**Recommendation:** + +Introduce more reliable heading-state mapping and add regression tests for document edits. + +**Action taken after the review:** + +The issue was reproduced by inserting a temporary comment before a collapsed section. + +A local correction was implemented to associate headings across source edits. + +Manual testing confirmed that the heading remained collapsed after the edit and could still be manually expanded or collapsed. + +**Status:** Fixed and verified in the documented scenario; 7 regression tests passed and commit `092ebdd` was pushed. + +### Finding 2 — Low Severity: UI Lifecycle Cleanup + +**Issue:** + +The Markdown-only implementation creates event listeners and a MutationObserver. + +The installation function provides a cleanup callback, but the reviewed integration did not clearly retain and invoke that callback when the editor was replaced or disposed of. + +This could result in redundant listeners or controls after repeated initialization. + +**Recommendation:** + +Connect the cleanup callback to the editor lifecycle and verify behavior across repeated initialization and document loading. + +**Status:** The cleanup changes were committed as `6f4e905`; 3 mocked lifecycle tests passed and manual reopening was reported successful. Full browser-level leak checks were not performed. + +### Finding 3 — Medium Severity: Integration Test Coverage + +**Issue:** + +The automated tests primarily validate heading-boundary calculations rather than complete TinyMCE and CodeMirror integration behavior. + +**Recommendation:** + +Expand testing to include: + +- Repeated editor initialization. +- Document updates and heading edits. +- Nested collapse-state restoration. +- Scrolling and layout behavior. +- Keyboard accessibility. +- Source-file preservation. +- Multiple document loading and reloading. + +**Action taken after the review:** + +Manual regression testing was conducted for mixed-mode collapsing, nested headings, document updates, and source preservation. + +Seven heading-state regression tests and three lifecycle mock tests were added and passed. + +**Status:** Partially addressed. Complete integration and lifecycle test coverage has not yet been demonstrated. + +### Implementation Review Conclusion + +The implemented feature demonstrates the required core Collapse/Expand behavior in the tested Markdown-only and mixed code/documentation scenarios. + +The identified heading-state preservation issue was reproduced and corrected locally, with successful manual verification of the tested scenario. + +The original lifecycle cleanup issue was addressed; broader browser integration coverage remained open at the end of this earlier review. + +A further implementation review should be performed after resolving or verifying these remaining issues. The original findings are retained here to document the iterative review process. + +--- + +## Implementation Review Round 2 (before duplicate-heading correction, 2026-12-01) + +**LLM:** ChatGPT (GPT-6). + +**Inputs reviewed:** `CodeChat_final_review.zip` containing `docs/design.md`, `submission.md`, the four TypeScript implementation files, and all four JavaScript test files. The review did not include the full repository, a running browser session, or the extension's entire build environment. + +### Review Prompt + +> Review the latest supplied Collapsing Headings 2 implementation against `docs/design.md`, including Markdown-only and mixed-mode section boundaries, repeat headings, heading identity and state updates, TinyMCE lifecycle cleanup, CodeMirror folding and editor layout, accessibility, test coverage, and the claims in `submission.md`. Independently rerun the supplied automated tests, classify verified findings by severity, distinguish risks from demonstrated defects, and do not invent fixes or test results. + +### LLM Review Output (Summarized) + +**Verified in this review:** All four supplied automated test suites ran successfully: **22 passed, 0 failed** (6 Markdown boundary + 3 lifecycle mock + 6 mixed boundary + 7 state remapping). The source code includes removal of TinyMCE event listeners, disconnection of the `MutationObserver`, and cancellation of pending animation frames. Earlier user-provided screenshots showed a successful complete build, successful basic manual interaction, and four pushed implementation commits. + +**Finding 1 — Medium severity, source-level conformance defect: repeated headings without IDs.** In `client/src/collapsible-headings.mts`, `collectHeadings` assigns `key: null` to repeated headings with the same level and text when they lack an explicit HTML ID (approximately lines 39–53). `update()` then disables the corresponding buttons (approximately line 167). This conflicts with the specification that each rendered H1–H6 heading must have an operable collapse/expand control. The reviewer did not run this case in TinyMCE, but the disabled-button condition follows directly from the implementation. **Action required:** assign independent identities to all headings, including duplicate titles, and regression-test them. + +**Finding 2 — Medium severity, independently demonstrated state-mapping risk: ambiguous matches.** In `client/src/mixed-heading-ranges.mts`, `remapMixedCollapsedKeys` selects a matching heading label even when it does not establish unambiguous identity (approximately lines 113–132). A focused invocation mapped a collapsed `Overview` at offset 10 to an unrelated `Overview` at offset 900. A second invocation selected one of two equally plausible duplicate candidates. Both contradict the intended default-to-expanded behavior if the old heading cannot be associated unambiguously. **Action required:** reject ambiguous mappings and add tests for deleted/recreated or duplicate headings. + +**Finding 3 — Medium severity, unverified layout risk: hiding CodeMirror lines with CSS.** `client/src/CodeMirror-integration.mts` uses line decorations and a CSS rule `.cm-line.cc-mixed-fold-hidden { display:none !important; }` (approximately lines 1680–1705 and 1791–1795). This works in the user's small manual example, but scrolling, cursor navigation, viewport height, and large folded regions were not verified. CodeMirror has replacement decorations that explicitly represent hidden text and communicate vertical layout changes. **Action required:** add larger-file scrolling/caret tests and consider using `Decoration.replace` for hidden ranges if layout problems are found. + +**Finding 4 — Medium severity, coverage limitation:** The supplied tests validate pure boundary/state logic and simulated TinyMCE lifecycle behavior, but they do not run a complete browser-level TinyMCE + CodeMirror integration. Keyboard focus order, repeated document switching, large-document folding, and the cases described in Findings 1–3 remain unverified. **Action required:** extend tests and manual regression evidence. + +**Review conclusion:** Core folding works in the reported manual cases and all 22 supplied automated tests pass; the earlier heading-state and TinyMCE lifecycle corrections are present. However, Findings 1 and 2 mean the implementation cannot yet be described as fully compliant with the specification. This is a truthful post-correction review with actionable remaining issues, **not** a passing final audit with only trivial findings. Record a new review round after fixing and retesting these cases. + + +--- + +## Last Implementation Review — Round 3 (after fifth commit, 2026-12-01) + +**LLM:** ChatGPT (GPT-6) + +**Review scope:** Follow-up inspection of the four changed files from the duplicate-heading patch, the prior source review findings, and the supplied automated test suite. The complete running browser interface and a full keyboard/scrolling audit were not available in this review. + +### Exact review instruction + +> Re-evaluate the two demonstrated duplicate-heading problems after the latest implementation changes. Check whether each repeated Markdown heading receives an independent control and whether mixed-mode state remapping avoids assigning the old collapsed state to an unrelated same-named heading after ambiguous changes. Rerun the provided tests, identify any remaining verified defects or unverified integration risks, and distinguish the successful Windows build reported by the author from tests runnable in the review environment. + +### Review findings and results + +- **Previously identified issue 1 — Duplicate Markdown heading controls:** The updated `collectHeadings` logic assigns independent in-memory UI identities even when headings have identical labels and no IDs. It retains the old state when the same DOM node or an unambiguous identifier can be matched; otherwise it creates a new identity rather than disabling a control. Focused regression tests cover duplicate controls, independent operation and recreated nodes. **Status:** addressed in focused source review and tests. +- **Previously identified issue 2 — Ambiguous mixed-mode state transfer:** The updated remapping logic rejects the tested cases where same-named headings are deleted or inserted and a previous collapsed state might otherwise attach to a different heading. The regression suite includes those ambiguity scenarios. **Status:** addressed in focused source review and tests, not a proof for every possible document edit. +- **Automated verification:** The five suites ran with **29 tests passed, 0 failed** in the reviewer environment. The author independently reported the same result in PowerShell. +- **Build verification:** The author's Windows screenshot shows a successful `bt build` after this correction, including 13 server tests passed and 196 skipped. The review environment did not build the complete extension from the partial files. +- **Residual risks / limitations:** End-to-end verification of duplicate headings in the actual TinyMCE UI was not provided with this final screenshot. Very large folded CodeMirror sections, scrolling/cursor geometry, full keyboard accessibility and repeated cross-document navigation have not been demonstrated through systematic browser-level tests. No new **confirmed** source-level functional defect was established in this focused follow-up; the remaining concerns are unverified integration behavior rather than claims of failure. + +**Review conclusion:** The two previously demonstrated heading-identity issues have been addressed in the latest source and regression tests. The documented build and 29-test suite pass. The implementation demonstrates the requested core behavior in the tested modes; broader end-to-end behavior should not be claimed as comprehensively verified without additional manual or browser automation evidence. + +--- + +## Current Project Status + +**Completed and supported by available evidence:** + +- Core Markdown-only and mixed code/documentation Collapse/Expand in the manually tested examples. +- Nested section visibility and source preservation in the recorded scenarios. +- Heading-state preservation fix (`092ebdd`) and TinyMCE lifecycle cleanup (`6f4e905`). +- Independent duplicate-heading identity and safer ambiguous-state mapping (`fd28a32`) with regression tests. +- **29/29 JavaScript tests passed** after the fifth implementation commit; **0 failures**. +- Successful local Windows `bt build` following the latest fix; the build output reported **13 server tests passed and 196 skipped**. +- Five authored and pushed Git commits in the `collapsing-headings-2` branch. + +**Remaining verification and submission requirements:** + +- Record a manual check in the actual TinyMCE editor showing two identical headings with independently functioning buttons, if not already done. +- Do not claim exhaustive testing of large CodeMirror folds, scrolling/cursor navigation or keyboard accessibility without evidence. +- Verify and document the actual contributions and individual Git commits of Aidana, Madi and Sanzhar. The assignment requires each team member to author at least one commit; the available screenshots presently confirm Yerassyl's five commits only. +- Commit this updated `submission.md` after final checks, then open the Pull Request to the intended instructor repository/branch and confirm its status and required reviewers. + +**Repository:** https://github.com/egazizuly/CodeChat_Editor + +**Working branch:** `collapsing-headings-2` + +## Post-Review Follow-up — CodeRabbit + +**Review date:** December 1, 2026 + +**Reviewer:** CodeRabbit AI + +**Pull Request:** https://github.com/bjones1/CodeChat_Editor/pull/174 + +### Implementation Review Round 4 + +A full CodeRabbit review identified four functional correctness findings. + +| Finding | Severity | Resolution | +|---|---|---| +| Headings inside blockquotes and list items lack collapse controls | Minor | Extended heading discovery to include nested Markdown headings and handle container boundaries. | +| Controls for hidden nested headings remain visible | Minor | Improved visibility detection to hide controls when their headings have no rendered layout. | +| Duplicate heading counts do not guarantee identity continuity | Minor | Improved ambiguous duplicate-heading matching to prevent incorrect state transfers. | +| Positional matching takes priority over unique heading labels | Minor | Changed the matching priority to use explicit identity and unique labels before positional fallback. | + +### Changes Made + +The issues were addressed in the following files: + +- `client/src/collapsible-headings.mts` +- `client/src/mixed-heading-ranges.mts` +- `client/src/tests/collapsible-headings-nested.test.mjs` +- `client/src/tests/mixed-heading-state.test.mjs` + +**Git commit:** `2f785ae` — Address CodeRabbit review findings for collapsible headings. + +### Verification Results + +The complete automated test suite was executed using: + +`node --experimental-strip-types --test .\client\src\tests\*.test.mjs` + +**Results:** + +- Tests executed: 35 +- Passed: 35 +- Failed: 0 +- Cancelled: 0 +- Skipped: 0 + +The CodeChat Editor build was also completed successfully using `.\bt build`. + +The build included 13 successful Rust server tests, with 196 skipped. + +### Review Follow-up Status + +The corrected implementation was pushed to the existing Pull Request #174. + +The previous CodeRabbit inline comments were marked as outdated after the changes. + +A subsequent full CodeRabbit review was requested, but the included review limit had been reached. Therefore, an independent CodeRabbit approval of the latest changes has not yet been confirmed. + +The pull request remains in Draft status. Two GitHub workflows are awaiting maintainer approval. + +### Conclusion + +All four reported issues have been addressed in the implementation, and the updated automated test suite passes. + +The changes have been verified through local automated tests and a successful build. Further maintainer review and any required integration checks remain pending. \ No newline at end of file