Skip to content

Move a TOC section with its sub-headings and keep the Title fixed #500

Closed

Description

@HMarzban

Part of #499. Read the parent first. Step 1.

Work on main. Read AGENTS.md, apps/webapp/CLAUDE.md and apps/webapp/src/components/TipTap/CLAUDE.md first. Do the steps in this order.

Summary

  • Today. A TOC drag writes the new level to the dragged heading alone. So a demote ejects its sub-headings (measured: current code, case 1b, gives H3:A a0 H3:A1 a1 H3:A2 a2).
  • Today. A drop above the Title replaces the Title (measured: current code, case 5a, gives H1:B b0 H1:Title t0 ...). The TOC move and Delete section never check the editing lock (read from code).
  • After. One pure planner, planMove, and one effect function, applyMove, do every TOC move. They ship the R1 cascade, the R4 squash, R2 capture, the R3 Title refusals, the same-slot no-op and the lock refusal. The same-slot test is exported as the pure function isSameSlot, so Set the drag level from the row above and indent the drop line #504 can call it at each gap change. Delete section gets the same lock gate.
  • Why first. This issue adds no new visual. Every later child in [Tracking] Move TOC sections like folders: cascade, drop inside, and a menu path #499 calls this planner, so it must land first.

Claim tags: measured means run on a scratch copy on 2026-10-15 or 2026-10-16. Read from code means read at commit 85295b8cf2fc8f78efd5a3eaa4ecc05af413c2b2, not run. Inferred means a deduction that nobody ran. Primary source and secondary name a URL and a short exact quote.

Maintainer rulings that bind this issue

The full text of R1–R6 is on #499. One line each:

  • R1. A level change of d on the dragged heading shifts every sub-heading in its section by the same d.
  • R2. Think like a flat document. After a move, following deeper headings fall inside the moved heading ("capture"). No rule blocks capture.
  • R3. The first H1 of the document is the Title. Nothing drops above it, and its level never changes.
  • R4. Never block a move because of depth. A sub-heading whose shifted level would pass H6 stays at H6 ("squash").
  • R6. A set is one heading plus its whole subtree. There is no multi-select.

R5 (drop inside) is built by #508. This issue only adds the inside arm to the planner, so that child has nothing to change here.

This ruling is overturned: docs/DEMO.md:229 says "The new level is written to the dragged heading alone, so sub-headings keep the levels they had." Step 6 rewrites it.

Depends on / Blocks

Current behaviour

  1. No cascade (R1 broken). The level write is one setNodeMarkup on the dragged heading (moveHeading.ts:99-112; read from code). Measured, current code case 1b, moveHeadingSection(A, P, after, 3):
    • before: H1:Title t0 H2:P p0 H2:A a0 H3:A1 a1 H3:A2 a2 H2:B b0
    • after: H1:Title t0 H2:P p0 H3:A a0 H3:A1 a1 H3:A2 a2 H2:B b0. A1 and A2 leave A.
  2. A promote skips a level. Measured, current code case 2, moveHeadingSection(Q1, Q2, before, 2) gives H2:Q1 q1 H4:Q1a q1a. Q1a is not shifted.
  3. The Title can be replaced. moveHeadingSection has no Title guard (moveHeading.ts:49-122; read from code). enforceH1Title only resets the first node's level to 1 (title-document.ts:23-35; read from code). Measured:
    • Case 5a, moveHeadingSection(B, Title, before) gives H1:B b0 H1:Title t0 H2:A a0 H3:A1 a1. B is now the Title.
    • Case 5e, with a later H1, moveHeadingSection(Title, Part2, after) gives H1:Part2 p2 H2:B b0 H1:Title t0 H2:A a0.
    • Case 5b, a Title drag with no later H1, is refused today only as "inside itself". The Title's section spans the whole document, so this refusal is a side effect, not a guard.
  4. A same-slot drop dispatches. isSamePosition compares the target's bounds, not the insert position (moveHeading.ts:75-82; read from code). Measured, current code case 6a, moveHeadingSection(A, P, after): dispatched steps=[delete,insert], docChanged=false undoSteps+=1.
    • That empty undo step is measured in prosemirror-history only. The pad sets undoRedo: false (TipTap.tsx:109-115) and loads UndoRedo only without Collaboration (TipTap.tsx:245-254). The effect on Y.UndoManager is not measured. Step 0 part C measures it.
  5. No lock check. handleDragEnd calls moveHeadingSection with no lock read (useTocDrag.ts:176-214; read from code). A grep of components/toc/ finds no selectDocumentEditingLocked (read from code). The user-visible effect on a locked pad is not measured.
    • Delete section has the same gap. removeSectionNow reads the editor and dispatches tr.delete(section.from, section.to) with no lock read (tocActions.ts:22-45; read from code). The confirm dialog calls it at confirm time (tocActions.ts:119; read from code).
  6. The drop union has two arms in six places (read from code: git grep "'before' | 'after'" at 85295b8cf):
  7. Return contract. moveHeadingSection returns boolean. A same-slot no-op returns true (moveHeading.ts:80-82). cy.dragTocItem throws on a falsy return (commands.ts:985-988). Three specs call it: toc-render-and-drag.cy.js:36, :79 and editing-flows.cy.js:274 (read from code).

What must keep working. These were measured on a scratch copy with the planner draft, which uses the same moveSection plus setNodeMarkup steps as today. Step 0 part B checks today's code on the playground.

  • A move keeps every toc-id, in a single editor and in the collab path (measured with the planner draft: 8a-1 to 8a-5 print toc-ids re-keyed: none | new ids: none | duplicates: none; 7b prints dup B: none). UniqueID skips change-origin transactions (TipTap.tsx:147-152).
  • One move is one Y.UndoManager stack item (measured with the planner draft, 7b: undoStack after one move+cascade: 1, one undo restores original: true).
  • moveSection is one transaction (move-section.ts:8-26; read from code).
  • The NEW_HEADING_CREATED meta makes the TOC rebuild (headingTransaction.ts:76-93; read from code).

Target behaviour

  • Cascade (R1). Every heading in the set shifts by d, in one transaction and one undo step.
  • Squash (R4). A shifted level above 6 stays at 6. Nothing is refused because of depth. The planner never reads the children to decide whether a drop is allowed.
  • Capture (R2). After the move, following headings deeper than the new level fall inside the moved heading. They keep their own levels. The planner adds no rule for this; computeSection derives it (compute-section.ts:7-34).
  • Title (R3). A Title source is refused. A drop whose insert point is inside the Title node is refused. The Title's level never changes.
  • after on the Title. It moves the set to the end of the Title's section: the document end, or before the next H1 (measured with the planner draft, cases 5f and 5g). Today's hit test sends after on the Title only when the Title has no open child row (dnd/utils.ts:133-149; read from code). So a drop just under a folded Title row jumps to the end (inferred). If the maintainer wants first-child placement there, it goes to Rebuild the TOC drop hit test so folded rows and gaps land right #503.
  • Inside an H6. An inside drop on an H6 target lands at H6 as the target's next sibling (R4 squash). It is not refused (measured with the planner draft, case 4d). D4 rules on this.
  • Same slot. A drop on the source's own slot with no level change dispatches nothing. With a level change it emits setNodeMarkup steps only. One exported pure function, isSameSlot, answers the slot question for planMove and for Set the drag level from the row above and indent the drop line #504.
  • Lock. On a locked pad every TOC move is refused, and the document does not change. Delete section on a locked pad also changes nothing.
  • Insert points. Every insert point is the start of a top-level heading node or the document end. So no body paragraph ever changes owner (measured: case 4a shows the unsafe placement; cases 4b, 4c and 5c are safe).

Not in this issue: the grip on the Title row and on a locked pad still shows until #501 removes it. A drag there now ends with no change.

Micro-interactions

This issue adds no visual and no motion token. It owns one slice of the release step:

Release outcome What the user sees Motion
moved Today's result: the card vanishes, the rows rebuild, the editor heading scrolls into view. Unchanged (dropAnimation={null}).
noop or refused The same as a cancel today: resetState(), no transaction, no scroll. None.

The settle step (fade, flash, Undo toast) belongs to #506. The live region belongs to #507.

Implementation steps

Step 0. Measure before you build

Part A (settled; quote it, do not re-run). A headless real Tiptap editor ran on a scratch copy on 2026-10-15. It used the repo UniqueID config (filterTransaction: !isChangeOrigin), the repo TitleDocument and the real Collaboration extension.

  • 8a-1, "UPWARD move of X{X1{X1a}} before A", printed toc-ids re-keyed: none | new ids: none | duplicates: none.
  • 8a-2 to 8a-5 printed the same line. They cover an upward move with cascade, a downward move and an empty H3 inside the section.
  • 8b-1, "both peers move X before A (same upward move, offline, then sync)", printed duplicates=Ax2,Bx2. Today's path does the same, so this goes to Design a fix for concurrent TOC section moves that duplicate sections #510. It does not block this issue.

Part B (open; run before you build). Start make dev-local. Read the WEBAPP port from the make dev-local output first. Port 3000 may be a backend there (AGENTS.md §Test Policy). Open http://localhost:<WEBAPP port>/editor?localPersistence=true&docName=toc-drag-lab. localPersistence=true is required: without it the playground has no Y.Doc and loads UndoRedo, not y-undo (TipTap.tsx:245-254; read from code). In DevTools:

_editor.commands.setContent('<h1>Title</h1><p>t0</p><h2>A</h2><p>a0</p><h2>B</h2><p>b0</p><h2>X</h2><p>x0</p><h3>X1</h3><p>x1</p><h4>X1a</h4><p>x1a</p><h2>Z</h2><p>z0</p>')
const heads = () => { const out = []; _editor.state.doc.forEach((n) => { if (n.type.name === 'heading') out.push(`${n.textContent || '<empty>'}#${n.attrs['toc-id']}@H${n.attrs.level}`) }); return out }
const idOf = (t) => { let id; _editor.state.doc.forEach((n) => { if (n.type.name === 'heading' && n.textContent === t) id = n.attrs['toc-id'] }); return id }
heads()                                          // before
_moveHeading(idOf('X'), idOf('A'), 'before')     // 8a-1
heads()                                          // after 8a-1
  • Reload and seed again. Paste heads and idOf again, because a reload clears them. Run _moveHeading(idOf('X'), idOf('B'), 'before', 3), which is today's form of 8a-2 (X lands as A's last child). Post heads() before and after.
  • heads() reads attrs['toc-id'], which renders as data-toc-id (TipTap/CLAUDE.md §Heading Schema).
  • The trailing empty H1 is gone. Stop the pad adding an empty H1 at the end of every document #572 set trailingNode: false in StarterKit (read from code: apps/webapp/src/components/TipTap/TipTap.tsx:163 at HEAD). So no empty H1 ends the Title's section. Check that the last heading in the heads() list is Z.
  • Stop and report on this issue if any id changes or repeats.

Part C (open). Paste the heads and idOf helpers from Part B again after any reload. On the same playground, with today's code, seed <h1>Title</h1><p>t0</p><h2>P</h2><p>p0</p><h2>A</h2><p>a0</p><h3>A1</h3><p>a1</p><h2>B</h2><p>b0</p>. Wait 1 second, so the seed and the drop do not merge. Then:

const um = () => _editor.state.plugins.find((p) => p.key.startsWith('y-undo'))?.getState(_editor.state)?.undoManager
um().undoStack.length                            // before
_moveHeading(idOf('A'), idOf('P'), 'after')      // same slot, no level
um().undoStack.length                            // after
  • The y-undo plugin key is new PluginKey('y-undo') (read from code: apps/webapp/node_modules/@tiptap/y-tiptap/dist/y-tiptap.js line 35). A PluginKey adds a $ suffix, so match with startsWith.
  • Post both numbers. If the length grows by one, today's same-slot drop adds an empty y-undo item. If it does not grow, record that the bug exists in prosemirror-history only.

Step 1. Widen the drop union in all six places, in one change

Add these exported types in moveHeading.ts:6-47 and use them everywhere:

export type HeadingInfo = {
  id: string          // the heading's toc-id
  pos: number
  end: number
  level: number
  node: ProseMirrorNode
  childIndex: number
  sectionFrom: number
  sectionTo: number
  childStart: number  // first top-level heading after pos and before sectionTo; else sectionTo
}
export type MovePosition = 'before' | 'after' | 'inside'
export type MoveDrop = { position: MovePosition; targetId: string; level?: number }
export type MoveRefusal = 'locked' | 'not-found' | 'title-fixed' | 'inside-own-set' | 'above-title' | 'apply-failed'
export type MovePlan = {
  src: HeadingInfo
  insertPos: number
  L: number
  d: number
  rows: { rel: number; id: string; from: number; to: number }[]
  squashed: number
  sameSlot: boolean
}
export type MoveResult = {
  movedId: string
  fromLevel: number
  L: number
  d: number
  squashed: number
  captured: string[]
  capturedAll: string[]
  capturedTotal: number
}
export type MoveOutcome =
  | { ok: true; kind: 'moved'; result: MoveResult }
  | { ok: true; kind: 'noop' }
  | { ok: false; reason: MoveRefusal }
  • HeadingInfo exists today as a private interface with no id and no childStart (moveHeading.ts:6-14; read from code). Export it. findHeadingById (:16-39) fills both new fields. It finds childStart with one more walk over top-level children, empty headings included.
  • dnd/types.ts:11-17: DropTarget.position becomes MovePosition | null. Use import type { MovePosition } from '../utils/moveHeading', so no runtime import chain forms. Today's hit test still sets only 'before' or 'after'.
  • pointerCollisionDetection.ts:33-37: widen currentPosition to MovePosition | null. Keep the return type 'before' | 'after'. Today's hit test never returns 'inside'. Without this change, tsc fails at dnd/utils.ts:129 (inferred; not run).
  • EditorPlayground.tsx:21-36 and :77-112: _moveHeading(sourceId, targetId, position: MovePosition, newLevel?) returns MoveOutcome.
  • commands.ts:6-17: the EditorWindow._moveHeading position becomes 'before' | 'after' | 'inside'. Its return type becomes { ok: true; kind: 'moved' | 'noop' } | { ok: false; reason: string }. Cypress cannot import the app type, so repeat the literals.
  • commands.ts:927-934 and :963: position?: 'before' | 'after' | 'inside'.
  • commands.ts:985-988: throw when !outcome.ok, and name outcome.reason in the error. Never test the outcome object for truthiness: a refusal object is truthy, so the specs would pass silently.
  • tsc does not check cypress/: apps/webapp/tsconfig.json:48-50 lists "cypress" in exclude (read from code). So prove the throw by sabotage. In toc-render-and-drag.cy.js:36, make the source 'TOC Test Document', the Title from the seed on line 11. See the spec fail with title-fixed in the error. Then restore it.

Step 2. Add the pure planner planMove and the exported isSameSlot

In moveHeading.ts, keep findHeadingById. Add:

export function planMove(doc: PMNode, sourceId: string, drop: MoveDrop, locked: boolean): MovePlan | { refused: MoveRefusal } | { noop: true }
export function isSameSlot(doc: PMNode, sourceId: string, drop: MoveDrop): boolean

Gate order. Keep it exactly:

  1. locked → refuse 'locked'.
  2. Source not found → refuse 'not-found'.
  3. src.childIndex === 0 → refuse 'title-fixed' (R3).
  4. Target not found → refuse 'not-found'.
  5. Own-set check, before the same-slot check. inPlace = drop.position === 'before' && tgt.id === src.id. If not inPlace and src.sectionFrom <= tgt.pos < src.sectionTo → refuse 'inside-own-set'.
  6. Insert position and level:
    • 'before': insertPos = tgt.pos; L = drop.level ?? src.level.
    • 'after': insertPos = tgt.sectionTo; L = drop.level ?? src.level.
    • 'inside': insertPos = tgt.childStart; L = min(tgt.level + 1, 6). drop.level is ignored.
    • tgt.childStart is the position of the first top-level heading node after tgt, empty headings included, when it is before tgt.sectionTo. Otherwise it is tgt.sectionTo.
    • An inside drop on an H6 target lands at H6 as the target's next sibling (R4 squash). It is not refused. An H6 has no heading in its section, so childStart = sectionTo (read from code: compute-section.ts:29-31).
    • Put the three insertPos arms in one private helper, for example insertPointOf(tgt, position). Gate 6 and isSameSlot both call it, so the two cannot drift.
  7. insertPos < doc.firstChild.nodeSize → refuse 'above-title' (R3).
  8. L = clamp(L, 1, 6); d = L - src.level.

Cascade plan, from the BEFORE doc (R1, R4):

  • Walk top-level doc children only, as findHeadingById does. Include empty headings.
  • For each heading h with src.sectionFrom <= h.pos < src.sectionTo, add a row { rel: h.pos - src.sectionFrom, id: h.attrs['toc-id'], from: h.level, to: clamp(h.level + d, 1, 6) }.
  • squashed = the count of rows where from + d > 6.
  • Never read a row to refuse a drop (R4).

Same slot, through isSameSlot:

  • isSameSlot finds the source and the target with findHeadingById. It returns false when either is missing.
  • It computes insertPos with insertPointOf. It returns insertPos === src.sectionFrom || insertPos === src.sectionTo.
  • It answers the slot question only. It ignores drop.level, the lock, the Title and the own set. planMove runs those gates before it calls isSameSlot.
  • Set the drag level from the row above and indent the drop line #504 calls isSameSlot at each gap change, for the D1 cap on the source's own gap. So it never calls planMove outside moveHeading.ts.
  • In planMove: sameSlot = isSameSlot(doc, sourceId, drop).
  • sameSlot && d === 0 → return { noop: true }.
  • Otherwise return the MovePlan { src, insertPos, L, d, rows, squashed, sameSlot }.

Step 3. Add the effect function applyMove

export function applyMove(editor: Editor, plan: MovePlan): MoveResult
  1. Read the undo manager as the pad title does: yUndoPluginKey.getState(editor.state)?.undoManager (MobilePadTitle.tsx:153-158; the import is import { yUndoPluginKey } from '@tiptap/y-tiptap' at :31). It is undefined on the UndoRedo path, so use um?..
  2. Call um?.stopCapturing().
  3. Build one transaction. When !plan.sameSlot, call moveSection(tr, doc, src.sectionFrom, src.sectionTo, insertPos).
  4. newStart = sameSlot ? src.sectionFrom : insertPos < src.sectionFrom ? insertPos : insertPos - (src.sectionTo - src.sectionFrom).
  5. For each row with to !== from: read node = tr.doc.nodeAt(newStart + rel). Assert that node is a heading and its toc-id equals the row id. If not, throw. Never write the wrong node. Then tr.setNodeMarkup(newStart + rel, null, { ...node.attrs, level: to }).
  6. tr.setMeta(TIPTAP_EVENTS.NEW_HEADING_CREATED, true), then editor.view.dispatch(tr).
  7. Call um?.stopCapturing() again. Two moves within 500ms merge into one item without it (measured, 7b: two moves 10 ms apart -> undoStack 1; with um.stopCapturing() between -> undoStack 2).
  8. Return MoveResult, read from tr.doc:
    • movedId, fromLevel (src.level), L, d, squashed.
    • capturedAll: the run of headings right after the set's new end with level greater than L. The first heading at level L or above stops it.
    • captured: the members of capturedAll whose TOC parent is now the moved heading or a set member.
    • capturedTotal: the size of capturedAll.

A same-slot plan with d !== 0 emits markup steps only, with no delete and no insert (measured: case 6c steps : [markup(ReplaceAround), markup(ReplaceAround)]). This keeps a peer's concurrent typing (measured: re-level only (no move, delta+1 via moving A before B = same spot) printed peer edit kept: true).

A real move (delete plus insert) can still drop a peer's concurrent edit (measured: out-move-yjs.txt lines 5, 15, 20 and 35 print peer edit kept: false; line 30 prints true). The loss falls on the range that the Yjs diff deletes and inserts again. That range can be the moved section (lines 5, 15, 20) or the section that stayed (line 35). Today's code uses the same delete-plus-insert path (read from code). This goes to #510. That harness called updateYFragment directly, not through the ySync plugin.

Step 4. Route moveHeadingSection and its callers through the planner

  • Replace the body of moveHeadingSection (moveHeading.ts:49-122). Keep its name and callers. It returns MoveOutcome:
const planned = planMove(editor.state.doc, sourceId, { position, targetId, level: newLevel }, isDocumentEditingLocked())
  • The lock is read here, not in handleDragEnd. Then the drag and window._moveHeading share one gate. Use isDocumentEditingLocked() (isDocumentEditingLocked.ts:8-17), which wraps selectDocumentEditingLocked.
  • Never use editor.isEditable. Phone read mode sets editable to false, and a later phone slice needs the move there.
  • The playground is not locked by default: the store starts with providerStatus: 'saved', authorizedScope: null and no readOnly (workspace.ts:51-68; read from code). So the existing specs keep passing.
  • Keep the console.warn lines for a refusal. Keep the try/catch around applyMove. When it throws (for example the safety assert), log with console.error and return { ok: false, reason: 'apply-failed' }.
  • useTocDrag.ts:193-209: pass dropTarget.position and projectedLevel as today. Run the editor scroll only when outcome.kind === 'moved'. A refusal or a no-op runs resetState() only.
  • Keep today's sideways offset and hit test unchanged. Rebuild the TOC drop hit test so folded rows and gaps land right #503 and Set the drag level from the row above and indent the drop line #504 change them.

Step 4b. Gate Delete section on the lock

  • In removeSectionNow (tocActions.ts:22-45), return early when isDocumentEditingLocked() is true. Put the check right after if (!editor) return, before the walk and the dispatch.
  • Import it as import { isDocumentEditingLocked } from '@hooks/isDocumentEditingLocked', as slash-menu.ts:2 does.
  • The confirm dialog calls removeSectionNow at confirm time (tocActions.ts:119). So a lock that lands while the dialog is open also blocks the delete (read from code).
  • Delete is not a move, so it does not go through planMove. It shares the lock gate only.

Step 5. Unit test the planner (allowed by AGENTS.md §Test Policy)

The planner has dense branching (gates, insert points, cascade, squash, same slot). The failure mode in one sentence: a wrong branch silently ejects sub-headings, replaces the Title or adds an empty undo step.

  • File: apps/webapp/src/components/toc/utils/moveHeading.test.ts.
  • Build docs as match-section.test.ts does: getSchema with Document, Paragraph, Text and a Heading that has a toc-id attribute.
  • For applyMove, use a headless new Editor({ extensions, content }) in the jsdom test environment. yUndoPluginKey.getState is undefined there, which um?. covers.
  • If importing moveHeading.ts pulls in a store chain that Jest cannot load, stop and report. Do not mock the store.
  • Assert the outline string (H<level>:<text> plus body texts, as below), the toc-id list and the step kinds. Do not snapshot ProseMirror JSON.
  • Prove each row by sabotage. Break the rule it covers, see the row fail, then restore it. Examples:
    • Drop the cascade loop: case 1 fails.
    • Use tgt.sectionTo for inside: case 4b fails.
    • Remove the clamp to 6: case 4d fails.
    • Remove gate 3: case 5b fails. Remove gate 7: case 5a fails.
    • Remove the no-op return: case 6a fails.
    • Make isSameSlot return false: cases 6a and 6b fail.

The case table. The before and after lines are copied verbatim from the scratch runs with the planner draft (measured: issues-run/out-planner.txt; rows 4d, 5f and 5g from issues-run/planner-extra/out-4d5f.txt, run 2026-10-16). Each fixture keeps H1:Title t0, because child index 0 is the Title.

# Before Drop (source → drop) Expected
1 H1:Title t0 H2:P p0 H2:A a0 H3:A1 a1 H3:A2 a2 H2:B b0 A → after P, level 3 H1:Title t0 H2:P p0 H3:A a0 H4:A1 a1 H4:A2 a2 H2:B b0; markup steps only
2 H1:Title t0 H2:P p0 H3:Q1 q1 H4:Q1a q1a H3:Q2 q2 H3:Q3 q3 H2:R r0 Q1 → before Q2, level 2 H1:Title t0 H2:P p0 H2:Q1 q1 H3:Q1a q1a H3:Q2 q2 H3:Q3 q3 H2:R r0; capturedAll = [Q2, Q3]
3 H1:Title t0 H2:A a0 H3:B b0 H4:D d0 H5:D1 d1 H6:D2 d2 H3:Z z0 D → before Z, level 6 H1:Title t0 H2:A a0 H3:B b0 H6:D d0 H6:D1 d1 H6:D2 d2 H3:Z z0; squashed = 2
3b H1:Title t0 H2:A a0 H3:B b0 H4:D d0 H5:D1 d1 H6:D2 d2 H5:D3 d3 H3:Z z0 D → before Z, level 5 H1:Title t0 H2:A a0 H3:B b0 H5:D d0 H6:D1 d1 H6:D2 d2 H6:D3 d3 H3:Z z0; squashed = 1
4b H1:Title t0 H2:X x0 H3:X1 x1 H2:T tBody0 tBody1 H3:C1 c1 H3:C2 c2 H2:Z z0 X → inside T H1:Title t0 H2:T tBody0 tBody1 H3:X x0 H4:X1 x1 H3:C1 c1 H3:C2 c2 H2:Z z0; tBody0 and tBody1 still belong to T
4b-skip H1:Title t0 H2:X x0 H2:T tBody0 H4:C1 c1 H2:Z z0 X → inside T H1:Title t0 H2:T tBody0 H3:X x0 H4:C1 c1 H2:Z z0; capturedAll = [C1]
4d H1:Title t0 H2:X x0 H3:X1 x1 H2:P p0 H6:T t6 H2:Z z0 X → inside T (T is H6) H1:Title t0 H2:P p0 H6:T t6 H6:X x0 H6:X1 x1 H2:Z z0; X and X1 are T's siblings under P; squashed = 1
5a H1:Title t0 H2:A a0 H3:A1 a1 H2:B b0 B → before Title refused 'above-title'; doc unchanged
5b same as 5a Title → after B refused 'title-fixed'; doc unchanged
5c same as 5a B → inside Title H1:Title t0 H2:B b0 H2:A a0 H3:A1 a1
5f H1:Title t0 H2:A a0 H3:A1 a1 H2:B b0 H2:C c0 B → after Title H1:Title t0 H2:A a0 H3:A1 a1 H2:C c0 H2:B b0; B goes to the document end
5g H1:Title t0 H2:A a0 H2:B b0 H2:C c0 H1:Part2 p2 H2:D d0 B → after Title H1:Title t0 H2:A a0 H2:C c0 H2:B b0 H1:Part2 p2 H2:D d0; B goes before the next H1
6a H1:Title t0 H2:P p0 H2:A a0 H3:A1 a1 H2:B b0 A → after P, no level no-op; no transaction
6b same as 6a A → before B, no level no-op; no transaction
6c same as 6a A → after P, level 3 H1:Title t0 H2:P p0 H3:A a0 H4:A1 a1 H2:B b0; markup steps only
6d same as 6a isSameSlot for A → after P, A → before B and A → after B true, true, false (new row, not measured)
7 same as 6a A → before A1 refused 'inside-own-set' (new row, not measured)
8 same as 6a, locked = true A → before P refused 'locked' (new row, not measured)

Step 6. Docs, in the same change

  • docs/DEMO.md:229: replace the last sentence. Proposed text: "Sub-headings move by the same number of levels as the dragged heading. A level past H6 stays at H6. The Title cannot move, and nothing can drop above it." Keep the sideways sentences on line 224; Set the drag level from the row above and indent the drop line #504 changes them.
  • apps/webapp/CHANGELOG.md:17: add one line under [Unreleased]. Say that a TOC move now carries its sub-headings to the new level. Say that a drop can no longer replace the Title. Say that a TOC move and Delete section do nothing on a locked pad.
  • apps/webapp/CLAUDE.md:311 (§TOC And Heading Actions): add one line: "Every TOC move goes through planMove and applyMove in components/toc/utils/moveHeading.ts. A caller that needs the same-slot test uses isSameSlot from the same file. Never add a second move path."
  • apps/webapp/src/components/TipTap/CLAUDE.md:30 (§Heading Schema): name planMove and applyMove in the "Section reorder is TOC-only" line.

Out of scope

Decisions

The recommended answer comes first. Owner: the maintainer. Rulings are posted as a comment on this issue. None of these is a design-system ruling.

  1. D3. How do extra H1s after the Title behave? Recommended: they are normal sections. They can move, and the planner clamps levels to 1..6, so a TOC move can create an H1.
    • Reason: Block style already offers H1, and HeadingScale treats each later H1 as a section (TipTap/CLAUDE.md §HeadingScale).
    • Alternative: a TOC move never creates an H1. Then the planner clamps L and every row to 2..6 for every source except the Title.
  2. D4. Where does a drop inside a heading put the set? Recommended: the first child, at T.childStart, as HT.level + 1.
    • Reason: it lands right under the target row, also on an open row and on the Title (measured safe: cases 4b and 5c). It can capture a skip-level first child (case 4b-skip), which R2 allows.
    • Alternative: the last child, at T.sectionTo. It never captures, but it can land far below the pointer. On the Title it lands at the document end.
    • The H6 case, ruled with D4. On an H6 target there is no deeper level. Recommended: accept the R4 result. The whole set flattens to H6 and lands as T's next siblings under T's parent (measured, case 4d: H2:P{H6:T H6:X H6:X1}). The set does not go inside T. Alternative: none that keeps R4, because R4 forbids a refusal. The UI cue for this case is D5 on Drop a section onto a TOC heading to put it inside #508.
  3. D23. Undo from the TOC, with quick moves kept apart? It has two parts. Both are ruled here. Announce TOC move results and return focus after a move #507 builds part (a); this issue builds part (b).
    • (a) The key. Recommended: yes. Ctrl+Z (Cmd+Z on Apple) with focus in the TOC runs the editor undo. Reason: a person who just moved a section from the TOC can undo it without first moving focus to the editor. Alternative: no TOC key; the person clicks into the editor and presses Ctrl/Cmd+Z there.
    • (b) stopCapturing(). Recommended: yes. applyMove calls stopCapturing() before and after its dispatch. Reason: two moves within 500ms merge into one Y.UndoManager item (measured), so one undo would revert both. Alternative: no stopCapturing(), and accept merged items.
    • Peer exception for part (a). No primary source was checked for what Google Docs, Word or Notion do with Ctrl/Cmd+Z while focus is in their outline. So part (a) goes against AGENTS.md:151 unless the maintainer names a peer source. Recommended: the ruling comment on this issue records it as a deliberate exception. Apple HIG says "Prefer letting people undo a drag-and-drop operation" (primary source: https://developer.apple.com/design/human-interface-guidelines/drag-and-drop), but Apple is not one of the three peers. Alternative: name a peer source in the ruling, or drop part (a).
  4. D26. Should editor-side level controls cascade? These are the Block style select, the phone stepper and Mod-Alt-1..6. Recommended: no. They change one line, and capture follows from the flat model. Only TOC moves cascade.
  5. The R2 reading. R2 says headings "at the new level or deeper" fall inside. Recommended reading: "deeper than the new level". A heading at the same level starts a new sibling section.
    • Reason: computeSection ends a section at the next heading of the same or a higher rank (compute-section.ts:29; read from code).
    • Alternative: none that keeps the flat model. Any other reading needs a new section rule.

Peer exceptions (AGENTS.md:151). The R-rulings are recorded on #499. The D23 key is recorded with the D23 ruling on this issue.

  • R1 has peer support (secondary: Texas HHS Word guide, https://accessibility.hhs.texas.gov/docs/word/HeadingGuidelinesWord.pdf, "The Promote option takes a heading and its sub-sections up the heading hierarchy"). Microsoft's own page confirms that a drag in the Navigation pane moves the heading (primary source: https://support.microsoft.com/en-us/word/use-the-navigation-pane-in-word, "To move part of the document, select the heading and drag it to a new location"). It does not say that a level change carries sub-headings.
  • R2 capture has no Google Docs, Word or Notion page that states it. Parity is inferred from their flat headings.
  • R4 squash has no peer. The one pattern found (Atlassian instruction-blocked) blocks the drop instead.
  • The D23 TOC undo key has no peer source checked (see D23 above).

Acceptance criteria

  • Step 0 parts B and C are posted on this issue, with the heads() lists and both y-undo stack numbers.
  • The maintainer has ruled D3, D4 (with its H6 case), D23 (both parts, with the peer exception for the key) and D26, and has confirmed the R2 reading, before merge. The rulings are on this issue.
  • On the playground, moving H2 A{H3 A1, H3 A2} with _moveHeading(A, P, 'after', 3) gives H3 A{H4 A1, H4 A2}. One Ctrl/Cmd+Z in the editor restores it.
  • On the playground, the case 2 outline with _moveHeading(Q1, Q2, 'before', 2) puts Q2 and Q3 under Q1 in the TOC. They keep level H3.
  • A demote past H6 leaves the deep rows at H6, and _moveHeading returns an outcome with ok: true and kind: 'moved'.
  • _moveHeading with a drop before the Title returns { ok: false, reason: 'above-title' }. With the Title as source it returns { ok: false, reason: 'title-fixed' }. The document is unchanged in both.
  • A same-slot drop with no level change returns { ok: true, kind: 'noop' }, and the y-undo stack length does not change.
  • isSameSlot is exported from moveHeading.ts, and planMove uses it for the same-slot test.
  • With _store.getState().setWorkspaceSettings({ authorizedScope: 'readonly' }), _moveHeading returns { ok: false, reason: 'locked' }. A real-pointer TOC drag then changes nothing.
  • On a locked pad, Delete section changes nothing.
  • Every toc-id is unchanged after each case. A heading chat room and the fold state follow the moved heading.
  • Two moves less than 500ms apart need two Ctrl/Cmd+Z presses to undo.
  • The case-table unit tests pass, and each row was proved by sabotage.
  • The cy.dragTocItem throw was proved by sabotage with the Title as source, and the error named title-fixed.
  • bun run --filter @docs.plus/webapp typecheck, bun run lint, bun run --filter @docs.plus/webapp test and the editor Cypress scope pass.
  • docs/DEMO.md:229 no longer states the overturned rule. The CHANGELOG line and both CLAUDE.md lines are in the same change.

Verification

Static and unit (Bun only):

bun run --filter @docs.plus/webapp typecheck
bun run lint
bun run --filter @docs.plus/webapp test

typecheck does not cover cypress/ (tsconfig.json exclude). The Step 1 sabotage covers commands.ts.

Do not run bun run test:unit here; it also runs the extension gates (about 45 minutes, per CONTRIBUTING.md). Do not run bun run build or next build against a live dev server (AGENTS.md §Test Policy).

E2E (it covers toc-render-and-drag.cy.js and editing-flows.cy.js):

make dev-local                       # read the WEBAPP port it prints
BASE_URL=http://localhost:<WEBAPP port> bash scripts/run-tests.sh --e2e --scope editor

scripts/run-tests.sh defaults BASE_URL to http://localhost:3001 (run-tests.sh:22; read from code), so always pass the port you read.

cy.dragTocItem calls window._moveHeading and skips dnd-kit. It proves planner results only. It proves nothing about hit zones or motion.

Browser checks, at 1440×900, in a visible tab (check document.visibilityState === 'visible'), in light and dark:

  1. On the playground with localPersistence=true, repeat Step 0 part B. Every id must stay the same. Then repeat it on the new code with a cascade: _moveHeading(idOf('X'), idOf('B'), 'before', 3) must give H3:X H4:X1 H5:X1a with the same ids.
  2. Repeat Step 0 part C on the new code. The stack length must not change.
  3. Use a real pointer on the case 6a outline. Drop A on the lower half of the P row, one 24px step to the right. A1 must shift with A. Press Ctrl/Cmd+Z once with focus in the editor; the outline must restore.
  4. Use a real pointer: drag a section above the Title row. The drop line still shows (until Rebuild the TOC drop hit test so folded rows and gaps land right #503), but nothing changes on release.
  5. Seed the Step 0 part B outline. Run _moveHeading(idOf('X'), idOf('A'), 'before'); _moveHeading(idOf('Z'), idOf('B'), 'before') in one console line. Two Ctrl/Cmd+Z presses must be needed to undo both.
  6. Set the lock with _store.getState().setWorkspaceSettings({ authorizedScope: 'readonly' }) (the recipe from slash-menu.cy.ts:185). A real-pointer drag must change nothing. Then open a heading's TOC menu, choose Delete section and confirm. The section must stay.
  7. Open a real pad at http://localhost:<WEBAPP port>/new. Sign in through the local inbox at http://127.0.0.1:54324. Open a heading chat, move that heading, and check that the chat stays on it.

Docs to update

  • docs/DEMO.md §Moving a section, line 229.
  • apps/webapp/CHANGELOG.md [Unreleased].
  • apps/webapp/CLAUDE.md §TOC And Heading Actions.
  • apps/webapp/src/components/TipTap/CLAUDE.md §Heading Schema.
  • No design-system.md row changes: this issue adds no visual.

Read first

  • AGENTS.md §Package Manager, §Test Policy, §Simplified English Mandate, §Workflow And Review Expectations (line 151, the peer rule).
  • apps/webapp/CLAUDE.md §TOC And Heading Actions (the "TOC menus + drag" bullet and the TOC data path).
  • apps/webapp/src/components/TipTap/CLAUDE.md §Heading Schema, §HeadingScale and §Editor State And References (doc.nodeAt can throw RangeError).
  • CONTEXT.md §Pad outline (Title, Block style).
  • [Tracking] Move TOC sections like folders: cascade, drop inside, and a menu path #499: the rulings R1–R6, D1, D2, the shared rules and the overturned list.

Generated by Claude Code

Activity

  1. added
    bug
    Editor
    Toc
    on Oct 16, 2026
  2. HMarzban commented on Oct 16, 2026

    @HMarzban
    CollaboratorAuthor

    Maintainer ruling, 2026-10-16

    The maintainer answered four of the five Decisions this issue owns. Each takes the recommended answer.

    • D3. Extra H1s after the Title: yes. They are normal sections. They can move, and Promote on a child of the Title makes an H1.
    • D4. Drop inside a heading: yes, the first child. The set lands at T.childStart as HT.level + 1.
    • D23. Undo from the TOC: yes. Ctrl/Cmd+Z in the TOC runs the editor undo. Each move calls stopCapturing() before and after, so quick moves stay separate undo steps.
    • R2r. Reading of R2: yes. "At the new level or deeper" means "deeper than the new level". A heading at the same level starts a new sibling section.

    Still open: D26 (do editor-side level controls cascade?). The maintainer asked for an explanation first. Do not build anything for D26 until a ruling comment lands here. The recommended answer stays "no": no change to the editor controls.

  3. added this to the v2.3.0 milestone on Oct 19, 2026
  4. HMarzban commented on Nov 3, 2026

    @HMarzban
    CollaboratorAuthor

    Status, 2026-11-03. Nothing from this issue is in the 2026-11-03 push (a9b0c69e8..8e25e83df). moveHeadingSection still re-levels only the dragged heading. So a demote still ejects sub-headings, and the Title row can still move.

    Left:

  5. HMarzban commented on Nov 4, 2026

    @HMarzban
    CollaboratorAuthor

    Maintainer ruling, 2026-11-04

    The 2026-10-24 hold on code still stands.

  6. HMarzban commented on Nov 5, 2026

    @HMarzban
    CollaboratorAuthor

    Fixed on main and pushed.

    • dd287cbfb: a TOC drag moves the section with all its sub-headings. Every sub-heading shifts by the same step, capped at H6. The Title row has no grip, and nothing lands above it.
    • 8d4ef6057: one move module (tocMove.ts) owns the lock rule, and a drop back in its own slot changes nothing.

    Covered by toc-drag-pointer.cy.js and planTreeMove.test.ts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    EditorTocbug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions