Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
75b0c10
Add initial specification for collapsible headings 2.
egazizuly Nov 30, 2026
fdea6a0
Clarify collapsible heading behavior after first LLM review
egazizuly Nov 30, 2026
3d1a263
Resolve second-round collapsible headings specification findings
egazizuly Nov 30, 2026
681785b
Remove redundant heading state requirements
egazizuly Nov 30, 2026
39fe074
Add draft submission with specification review history
egazizuly Nov 30, 2026
1a6e8c0
Implement collapsible Markdown headings with regression tests
egazizuly Dec 1, 2026
7a5f4dc
Implement collapsible headings across mixed code and documentation
egazizuly Dec 1, 2026
092ebdd
Preserve collapsed heading states after document edits
egazizuly Dec 1, 2026
6f4e905
Fix TinyMCE heading controls lifecycle cleanup
egazizuly Dec 1, 2026
fd28a32
Fix duplicate heading identities and preserve independent fold states
egazizuly Dec 1, 2026
0cfd190
Complete Project 2 final submission documentation
egazizuly Dec 1, 2026
2f785ae
Address CodeRabbit review findings for collapsible headings
egazizuly Dec 1, 2026
413a2ff
Document CodeRabbit review fixes and final test results
egazizuly Dec 1, 2026
46736d4
docs: clarify heading folding strategy and record draft review
makuanyshbekov Dec 1, 2026
e8ef98d
docs: align draft submission format
makuanyshbekov Dec 1, 2026
042aaf0
New round findings
makuanyshbekov Dec 1, 2026
43670a0
docs: simplify folding strategy and record round 3 review
makuanyshbekov Dec 1, 2026
f0655b5
Merge pull request #1 from makuanyshbekov/improve-heading-folding
egazizuly Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions client/src/CodeChatEditor.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
264 changes: 264 additions & 0 deletions client/src/CodeMirror-integration.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
// -------
Expand Down Expand Up @@ -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<string>();

type MixedFoldState = {
headings: MixedHeading[];
plan: ReturnType<typeof getMixedFoldPlan>;
collapsed: ReadonlySet<string>;
lineDecorations: DecorationSet;
};

function computeMixedFoldState(
state: EditorState,
collapsed: ReadonlySet<string>,
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<ReturnType<Decoration["range"]>> = [];
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<number, (typeof ranges)[number]>();
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<MixedFoldState>({
create(state) {
return computeMixedFoldState(state, new Set<string>());
},
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<string, HTMLButtonElement>();
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<string, HTMLElement>();
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
Expand Down Expand Up @@ -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`.
Expand Down
Loading