From e9ed1ba5d1e65bc6ea853f3ac5db8eaec5880d9d Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Tue, 27 Jan 2026 04:56:41 +0530 Subject: [PATCH] Toggle block (#8317) * fix: modify input rules for heading to wrap it in a toggle block * fix: leave heading node untouched * feat: add toggle block menu item * feat: first prototype * toggle_head and toggle_body * fix: indent toggle block * fix: cleanup * fix: allow only one heading or one para inside toggle head * fix: cleanup * fix: cursor becomes invisible as soon as toggle block is inserted This happened because the containing paragraph had ~0px as width which hid the cursor. I attemped setting the `style.minWidth` to 1px for the containing `span` and cursor became visible. Hence, set the `flexGrow` prop so that it occupies all the avaible space. * fix: keep the toggle button vertically center-aligned Adjusts the toggle button and keeps it center-aligned vertically as the toggle head's content node changes from, say a paragraph to a heading(of any level), or the other way around... * chore: style using css * fix: nesting of toggle blocks `toggleWrap` resorted to lifting out the active node when attempting to create a new nested toggle block inside existing toggle block, which made it impossible to nest toggle block. Hence, bypassing the `toggleWrap` flow in favor of `wrapIn`, which provides nesting of toggle blocks. * fix: assign unique id to each toggle head node This will be later used to persist toggle state of the toggle block * feat: attempt at using node view for toggle block * fix: get rid of nanoid, we can use existing uuid pkg * feat: plugin to manage toggling behaviour This includes a plugin which, for now handles the following behaviours: 1. Sync collapsed state from localStorage, and correspondingly initialize decorations for all the toggle block nodes in doc 2. Handle the fold/unfold behaviour of toggle block, triggered through the toggle button from within the node view * fix: don't trigger toggle behavior if secondary button on mouse is pressed * fix: restore decorations which are removed upon `joinBackward` When the selection is at the start of block node just after the toggle block node, pressing backspace triggers `joinBackward` command which attempts to "join" this block node with the toggle block node just before it. The `joinBackward` command works by adding a replacement step, which, in turn drops the decorations in the affected range. As a result, the toggle block collapses. In order to prevent the collapse, we restore back the dropped decoration to its corresponding node(if it exists). * chore: can find spec using id now * chore: this.name in favor of hardcoding * fix: collapse all children of toggle block except the first As a result of setting `content: block+` for the toggle block node, all its children are rendered flat in DOM, making it difficult to distinguish which one corresponds to its first child node. This, in turn, makes it hard to identify which one should not be collapsed when pressing the toggle button to collapse. The solution here is to wrap the first child node in a separate DOM node via a decoration. So, hopefully, we don't need to break up `toggle_block` node as one containing `toggle_head` and `toggle_body` nodes and setting `content: block+` should suffice. * fix: properly restore lost decorations A weird issue surfaced when a toggle block was erased and then the erase was undone. It was observed that all the toggle blocks ended up being collapsed and the one restored by undo had lost the decoration on first child(which prevents first child from hiding), and, as a result ended up with all its children hidden. Here, we collect all dropped decorations in a single array and later add them back in a single pass. * fix: we don't yet need and as nodes * fix: command mapped to `Backspace` key for `ToggleBlock` failed to invoke It happened because of `Math` node being placed before `ToggleBlock` in the array of exported nodes, which caused the `Math` node's `Backspace` handling command to _successfully_ run before `ToggleBlock` node's `Backspace` handling command. Therefore, moving `ToggleBlock` before `Math` fixed the issue. * fix: nested toggle blocks behaving differently than top level ones It was observed that the decoration which wraps the first child of a toggle block in a separate DOM wasn't being restored as and when expected for nested toggle blocks while it worked fine for top level toggle blocks. The reason was that the `findBlockNodes` skips the nested blocks in its default behavior, so, passing `descend` as `true` fixed the issue. * feat: lift all children up upon backspacing at the start of toggle block * fix: remove/reapply decorations which get misaligned as a result of doc change The decoration which is applied to the first child of toggle block, may get misaligned and go out of sync with the corresponding decoration on the toggle block as a result of document changes. Here, we simply remove *all* the decorations and then reapply to their target i.e, first child of each toggle block. We're trading off perf with implementation simplicity here since we don't actually need to remove all decos, only the misaligned ones. An alternate solution here might be to map the first child decoration in accordance with corresponding decoration on the toggle block, such that the first child deco _never_ goes out of sync with its parent decoration. As for now, not sure how that could be achieved. * fix: bring cursor out and set at the end of toggle block head upon folding * fix: cleanup * fix: if cursor ends up within the hidden range of toggle block while it is folded, immediately unfold it * fix: check parentNode * feat: `prependParagraph` and `splitHead` * fix: cleanup * fix: handle `Delete` when the node just after the cursor is a toggle block * fix: cleanup * fix: restrict toggle block head to contain heading or paragraph Certain behavioral aspects of toggle block are implemented assuming head to be a heading or paragraph, for simplicity. Makes sense for majority of use cases but still something presumptuous about user expectation. Proposition is to lauch it with this restriction and see if the users actually start requesting otherwise. Till then, this keeps things simple. * feat: `Tab` into a toggle block, `Shift-Tab` out of toggle block As part of this, we've modified handling `Enter` within a toggle block in a way that prevents it to trigger `liftEmptyBlock`, so that the cursor remains within the toggle block body and is only taken out of it when pressing `Shift-Tab` combo. * fix: Toggle block not unfolding when a node having `block+` content attempted to `Tab` into it * feat: beautification * feat: markdown for `toggle_block` This declares markdown spec for a toggle block, which enables users to download a doc containing toggle blocks, as markdown. Also, supports importing a markdown doc containing markdown corresponding to a toggle block. * fix: margins between toggle block contents * fix: `Action.INIT` for publicly shared and deleted docs It was observed that decorations weren't initialized for publicly shared and deleted docs because of init being under the `docChanged` cond. This change fixes the issue. * fix: all toggle blocks end up folded when navigated from collection to doc page This happened because `{ fold: true }` was forcibly set. This is fixed by applying decorations in accordance with the fold state fetched from local storage. * fix: disable overflow being set to scroll on Brave * fix: cleanup * fix: prevent joining two toggle blocks when backspaced from the start of a text block between them Consider two toggle blocks with a text block between them. If backspaced from the beginning of the text block, the toggle block below is joined to the toggle block before along with the text block, because of https://github.com/ProseMirror/prosemirror-commands/blob/20c7d42ab8b5d8642fb9efc6261b7541c9dc23c2/src/commands.ts#L468-L469. On the contrary, what's desirable is just joining back of the text block, retaining the toggle block below as it is. * fix: sync collapsed state across browser tabs * fix: cleanup * fix: upon unfold, append an empty para if toggle block's body is empty * fix: unfold upon `Enter` if the toggle block body is empty * feat: placeholder * feat: inputRule * feat: `Mod-Enter` shortcut to toggle * fix: do not split when body is empty * fix: do not unfold is head is empty * fix: assign uuid to newly split toggle block * feat: list keyboard shortcuts * fix: replace with `wrapIn` * fix: `container_toggle_block` -> `container_toggle` * fix: importing a markdown doc with toggle blocks let to them being created without ids * fix: pressing `Enter` at the end of list item within toggle block should create a new list item below * fix: repeated backspacing from an empty list item within toggle block * fix: prevent joining back when input rule is matched * fix: prevent button from shrinking when an image is added under content area * fix: tsc * Fixes: 1. Toggle block starts off unfolded when created 2. Trigger `liftEmptyBlock` when a toggle block consists of just an empty head, without any body 3. `Shift-Tab` behavior confuses when all nodes following the cursor position, inclusive of the one holding cursor, are empty. It seems at first, that it should simply outdent except it doesn't, because the node holding cursor isn't the `lastChild` of toggle block. So, `Shift-Tab` behavior is modified such that all nodes following the cursor, up till the last node of toggle block, should be lifted out of it * Fixes: 1. Upon pressing Enter, lift out all children of toggle block if cursor lies at the start, there's no text content 2. Prevent lifting out of an empty block when it's a direct child of a toggle block * fix: lint * fix: placeholder to inform how to exit toggle block * fix: prevent tables within toggle block from horizontally scrolling * fix: align toggle block with lists * fix: push toggle block down if it ends up as the first child of a list item * fix: don't consider toggle body empty if it consists of an empty table or notice * fix: CollapsedIcon * fix: Delete press * fix: mainly early return when `deleteBarrier` or `joinMaybeClear` succeed, rest is cleanup * fix: rename * fix: simplify commands * fix: simplify commands * fix: remove unused commands * fix: lint * chore: cleanup `splitBlockPreservingBody` * chore: `sinkBlockInto` -> `indentBlock` & `liftConsecutiveBlocks` -> `dedentBlocks` * fix: cleanup related to `getUtils` * fix: simplify `bodyIsEmpty` * fix: no need of separate func * fix: `bodyIsEmpty` -> `ToggleBlock.isBodyEmpty` && `headIsEmpty` -> `ToggleBlock.isHeadEmpty` * fix: cleanup * fix: move to utils * fix: update comment * fix: rename * fix: update comment * fix: update comment * fix: comments * fix: cleanup * fix: `splitBlock` was problematic here because it would run for block nodes other than toggle block. As an example, consider a `blockquote` containing and empty para. Here, `liftEmptyBlock` should run upon `Enter`, instead `splitBlock` runs. Same goes for other nodes like task lists. This commit fixes the issue. * fix: wrap heading and its children together within toggle block * trigger ci * fix: copy for used funcs from sorted-array-functions * fix: remove pkg * fix: remove pkg * fix: rearrage dep * fix: restore yarn.lock from main branch * fix: restore yarn.lock from main branch * feat: triggering toggle block on an already wrapped toggle block should unwrap it * fix: get rid of `HeadingTracker` in favor of directly querying doc * fix: headings under toggle blocks weren't tracked in toc * fix: don't hide the anchor associated with a heading otherwise the heading can't be scrolled to * fix: unfold toggle block when hidden heading is clicked from toc * fix: backspacing into an unfolded toggle block should attempt to join with the last node of body * `Tab` in a selected `embed` within a folded toggle block. Notice that toggle block remains folded. It should be unfolded as the `embed` is pushed inside. Same goes for some other nodes like `math_block` * Can only `Tab` in and `Shift-Tab` out once when a node of type `attachment|video|hr` is the last node of a toggle block. Beyond once, pressing those keys have no effect. * fix: Server build * refactor * Combine enum * perf: Merge plugins, avoid multiple appendTransaction * Remove getUtils * fix: Default new toggle blocks to closed * fix: Infinite loop * refactor: Separate ToggleBlockView * Centralize class names * fix: Align nested headings with lists * fix: Toggle block disclosure different sizes * fix: Toggle flash when clicking fold button while focus within toggle content * refactor: Plugin keys * Exit toggle block when pressing Enter in the last empty paragraph within the body * Placeholders * fix: Fallback line-height, font-size for empty title * fix: Incorrect decoration on title node change * doc * fix: Enter in last list item in toggle body exits * fix: Allow toggling headings in diff viewer * fix: Toggle button animation on first load --------- Co-authored-by: Tom Moor --- app/editor/index.tsx | 11 +- app/editor/menus/block.tsx | 7 + app/editor/menus/formatting.tsx | 9 + app/hooks/useDictionary.ts | 3 + app/scenes/KeyboardShortcuts.tsx | 33 + server/storage/files/S3Storage.test.ts | 7 +- server/storage/files/S3Storage.ts | 9 +- shared/editor/commands/toggleBlock.ts | 485 +++++++++++++++ shared/editor/components/Styles.ts | 119 +++- shared/editor/extensions/Diff.ts | 5 +- shared/editor/nodes/Heading.ts | 7 + shared/editor/nodes/Node.ts | 4 + shared/editor/nodes/ToggleBlock.ts | 601 +++++++++++++++++++ shared/editor/nodes/ToggleBlockView.ts | 137 +++++ shared/editor/nodes/index.ts | 3 + shared/editor/queries/findCutAfterHeading.ts | 33 + shared/editor/queries/isNodeActive.ts | 9 +- shared/editor/queries/toggleBlock.ts | 199 ++++++ shared/editor/rules/toggleBlocks.ts | 9 + shared/editor/styles/EditorStyleHelper.ts | 17 + shared/editor/utils.ts | 560 +++++++++++++++++ shared/i18n/locales/en_US/translation.json | 7 + shared/styles/globals.ts | 14 +- shared/utils/ProsemirrorHelper.ts | 2 +- 24 files changed, 2272 insertions(+), 18 deletions(-) create mode 100644 shared/editor/commands/toggleBlock.ts create mode 100644 shared/editor/nodes/ToggleBlock.ts create mode 100644 shared/editor/nodes/ToggleBlockView.ts create mode 100644 shared/editor/queries/findCutAfterHeading.ts create mode 100644 shared/editor/queries/toggleBlock.ts create mode 100644 shared/editor/rules/toggleBlocks.ts create mode 100644 shared/editor/utils.ts diff --git a/app/editor/index.tsx b/app/editor/index.tsx index 82064df5e3..67fae6efc9 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -9,11 +9,11 @@ import { gapCursor } from "prosemirror-gapcursor"; import type { InputRule } from "prosemirror-inputrules"; import { inputRules } from "prosemirror-inputrules"; import { keymap } from "prosemirror-keymap"; -import type { MarkdownParser } from "prosemirror-markdown"; import type { NodeSpec, MarkSpec } from "prosemirror-model"; import { Schema, Node as ProsemirrorNode } from "prosemirror-model"; import type { Plugin, Transaction } from "prosemirror-state"; -import { EditorState, Selection } from "prosemirror-state"; +import { EditorState, Selection, TextSelection } from "prosemirror-state"; +import type { MarkdownParser } from "prosemirror-markdown"; import { AddMarkStep, RemoveMarkStep, @@ -531,6 +531,13 @@ export class Editor extends React.PureComponent< this.mutationObserver = observe( hash, (element) => { + const pos = this.view.posAtDOM(element, 0, 1); + this.view.dispatch( + this.view.state.tr.setSelection( + TextSelection.near(this.view.state.doc.resolve(pos), 1) + ) + ); + if (isVisible(element)) { element.scrollIntoView(); } diff --git a/app/editor/menus/block.tsx b/app/editor/menus/block.tsx index d4bab0269f..599b5a0efe 100644 --- a/app/editor/menus/block.tsx +++ b/app/editor/menus/block.tsx @@ -22,6 +22,7 @@ import { MathIcon, DoneIcon, EmbedIcon, + CollapseIcon, } from "outline-icons"; import * as React from "react"; import styled from "styled-components"; @@ -242,6 +243,12 @@ export default function blockMenuItems( icon: Diagrams.net Diagram, keywords: "diagram flowchart draw.io", }, + { + name: "container_toggle", + title: dictionary.toggleBlock, + icon: , + keywords: "toggle collapsible collapse fold", + }, ]; // Filter out diagrams.net in desktop app diff --git a/app/editor/menus/formatting.tsx b/app/editor/menus/formatting.tsx index 820533fbbd..89c467cc82 100644 --- a/app/editor/menus/formatting.tsx +++ b/app/editor/menus/formatting.tsx @@ -20,7 +20,9 @@ import { TableMergeCellsIcon, TableSplitCellsIcon, PaletteIcon, + CollapsedIcon, } from "outline-icons"; +import { v4 as uuidv4 } from "uuid"; import CellBackgroundColorPicker from "../components/CellBackgroundColorPicker"; import type { EditorState } from "prosemirror-state"; import Highlight from "@shared/editor/marks/Highlight"; @@ -283,6 +285,13 @@ export default function formattingMenuItems( icon: , visible: isMergedCellSelection(state), }, + { + name: "container_toggle", + icon: , + active: isNodeActive(schema.nodes.container_toggle), + attrs: { id: uuidv4() }, + visible: !isCodeBlock && (!isMobile || isEmpty), + }, { name: "separator", }, diff --git a/app/hooks/useDictionary.ts b/app/hooks/useDictionary.ts index e108f24c8b..438ec7da6c 100644 --- a/app/hooks/useDictionary.ts +++ b/app/hooks/useDictionary.ts @@ -113,6 +113,9 @@ export default function useDictionary() { video: t("Video"), untitled: t("Untitled"), none: t("None"), + toggleBlock: t("Toggle block"), + emptyToggleBlockHead: `${t("Add title")}…`, + emptyToggleBlockBody: `${t("Add content")}…`, deleteEmbed: t("Delete embed"), uploadImage: t("Upload an image"), formattingControls: t("Formatting controls"), diff --git a/app/scenes/KeyboardShortcuts.tsx b/app/scenes/KeyboardShortcuts.tsx index b9932eb136..1ad434c398 100644 --- a/app/scenes/KeyboardShortcuts.tsx +++ b/app/scenes/KeyboardShortcuts.tsx @@ -346,6 +346,31 @@ function KeyboardShortcuts() { }, ], }, + { + title: t("Toggle blocks"), + items: [ + { + shortcut: ( + <> + {metaDisplay} + Enter + + ), + label: t("Open / Close"), + }, + { + shortcut: {t("Tab")}, + label: t("Indent item"), + }, + { + shortcut: ( + <> + ⇧ + {t("Tab")} + + ), + label: t("Outdent item"), + }, + ], + }, { title: t("Tables"), items: [ @@ -450,6 +475,14 @@ function KeyboardShortcuts() { ), label: t("LaTeX block"), }, + { + shortcut: ( + <> + +++ {t("Space")} + + ), + label: t("Toggle block"), + }, { shortcut: {":::"}, label: t("Info notice"), diff --git a/server/storage/files/S3Storage.test.ts b/server/storage/files/S3Storage.test.ts index 8cb8e4e184..2060d72aa4 100644 --- a/server/storage/files/S3Storage.test.ts +++ b/server/storage/files/S3Storage.test.ts @@ -31,8 +31,11 @@ describe("S3Storage", () => { it("should clamp values that exceed the limit", () => { const thirtyDays = 30 * Day.seconds; - const clampedValue = Math.min(thirtyDays, BaseStorage.maxSignedUrlExpires); - + const clampedValue = Math.min( + thirtyDays, + BaseStorage.maxSignedUrlExpires + ); + expect(clampedValue).toBe(BaseStorage.maxSignedUrlExpires); expect(clampedValue).toBe(Week.seconds); }); diff --git a/server/storage/files/S3Storage.ts b/server/storage/files/S3Storage.ts index 70de5f8b1a..4ca014147e 100644 --- a/server/storage/files/S3Storage.ts +++ b/server/storage/files/S3Storage.ts @@ -153,10 +153,15 @@ export default class S3Storage extends BaseStorage { return `${this.getPublicEndpoint()}/${key}`; } else { // Ensure expiration does not exceed AWS S3 Signature V4 limit of 7 days - const clampedExpiresIn = Math.min(expiresIn, S3Storage.maxSignedUrlExpires); + const clampedExpiresIn = Math.min( + expiresIn, + S3Storage.maxSignedUrlExpires + ); const command = new GetObjectCommand(params); - const url = await getSignedUrl(this.client, command, { expiresIn: clampedExpiresIn }); + const url = await getSignedUrl(this.client, command, { + expiresIn: clampedExpiresIn, + }); if (env.AWS_S3_ACCELERATE_URL) { return url.replace( diff --git a/shared/editor/commands/toggleBlock.ts b/shared/editor/commands/toggleBlock.ts new file mode 100644 index 0000000000..37a6ca17d6 --- /dev/null +++ b/shared/editor/commands/toggleBlock.ts @@ -0,0 +1,485 @@ +import { + chainCommands, + joinTextblockBackward, + splitBlock, +} from "prosemirror-commands"; +import { Slice, Fragment } from "prosemirror-model"; +import type { Command } from "prosemirror-state"; +import { NodeSelection, TextSelection } from "prosemirror-state"; +import { liftTarget, ReplaceAroundStep } from "prosemirror-transform"; +import { v4 } from "uuid"; +import ToggleBlock, { + Action, + toggleEventPluginKey, + toggleFoldPluginKey, +} from "../nodes/ToggleBlock"; +import { + isToggleBlock, + isToggleBlockFolded, + getToggleBlockDepth, + isSelectionInToggleBlock, + isSelectionInToggleBlockHead, + isSelectionInToggleBlockBody, + isSelectionAtStartOfToggleBlockHead, + isSelectionInMiddleOfToggleBlockHead, + isSelectionAtEndOfToggleBlockHead, + detachToggleBlockBody, + attachToggleBlockBody, +} from "../queries/toggleBlock"; +import { + ancestors, + atBlockEnd, + atBlockStart, + deleteSelectionTr, + findCutAfter, + findCutBefore, + joinBackwardTr, + joinForwardTr, + liftChildrenOfNodeAt, + nearest, + prevSibling, + selectNodeBackwardTr, + selectNodeForwardTr, + wrapNodeAt, +} from "../utils"; + +// Commands +export const deleteSelectionPreservingBody: Command = (state, dispatch) => { + if (state.selection.empty) { + return false; + } + + const { $from } = state.selection; + if (!isSelectionInToggleBlockHead(state)) { + return false; + } + + const toggleBlock = $from.node($from.depth - 1); + if (!isToggleBlockFolded(state, toggleBlock)) { + return false; + } + + const pos = $from.before($from.depth - 1); + const { tr: tr1, body } = detachToggleBlockBody(pos, state.tr); + let tr = deleteSelectionTr(tr1); + tr = attachToggleBlockBody(pos, body, tr); + dispatch?.(tr.scrollIntoView()); + return true; +}; + +export const joinForwardPreservingBody: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + + if (!isSelectionAtEndOfToggleBlockHead(state)) { + return false; + } + + const toggleBlock = $cursor!.node($cursor!.depth - 1); + if (!isToggleBlockFolded(state, toggleBlock)) { + return false; + } + + const pos = $cursor!.before($cursor!.depth - 1); + + const { tr: tr1, body } = detachToggleBlockBody(pos, state.tr); + let tr = liftChildrenOfNodeAt(pos, tr1); + tr = joinForwardTr(tr); + tr = wrapNodeAt(pos, toggleBlock.type, toggleBlock.attrs, tr); + tr = attachToggleBlockBody(pos, body, tr); + dispatch?.(tr); + return true; +}; + +export const joinBackwardWithHead: Command = (state, dispatch) => { + const $cursor = atBlockStart(state.selection); + if (!$cursor) { + return false; + } + + const $cut = findCutBefore($cursor); + if (!$cut) { + return false; + } + if (!$cut.nodeBefore || $cut.nodeBefore.type.name !== "container_toggle") { + return false; + } + + const toggleBlock = $cut.nodeBefore; + if (isToggleBlockFolded(state, toggleBlock)) { + const pos = $cut.pos - toggleBlock.nodeSize; + + const { tr: tr1, body } = detachToggleBlockBody(pos, state.tr); + let tr = liftChildrenOfNodeAt(pos, tr1); + tr = joinBackwardTr(tr); + tr = wrapNodeAt(pos, toggleBlock.type, toggleBlock.attrs, tr); + tr = attachToggleBlockBody(pos, body, tr); + dispatch?.(tr); + return true; + } + + return joinTextblockBackward(state, dispatch); +}; + +export const joinBackwardWithBody: Command = (state, dispatch) => { + const $cursor = atBlockStart(state.selection); + if (!$cursor) { + return false; + } + + const $cut = findCutBefore($cursor); + if (!$cut) { + return false; + } + if (!$cut.nodeBefore || $cut.nodeBefore.type.name !== "container_toggle") { + return false; + } + + const toggleBlock = $cut.nodeBefore; + if (isToggleBlockFolded(state, toggleBlock)) { + return false; + } + + return joinTextblockBackward(state, dispatch); +}; + +export const joinBackwardWithToggleblock: Command = chainCommands( + joinBackwardWithHead, + joinBackwardWithBody +); + +export const selectNodeForwardPreservingBody: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + + if (!isSelectionAtEndOfToggleBlockHead(state)) { + return false; + } + + const toggleBlock = $cursor!.node($cursor!.depth - 1); + if (!isToggleBlockFolded(state, toggleBlock)) { + return false; + } + + const pos = $cursor!.before($cursor!.depth - 1); + const { tr: tr1, body } = detachToggleBlockBody(pos, state.tr); + let tr = selectNodeForwardTr(tr1); + tr = attachToggleBlockBody(pos, body, tr); + dispatch?.(tr); + return true; +}; + +export const selectNodeBackwardPreservingBody: Command = (state, dispatch) => { + const $cursor = atBlockStart(state.selection); + if (!$cursor) { + return false; + } + + const $cut = findCutBefore($cursor); + if (!$cut) { + return false; + } + + if (!$cut.nodeBefore || $cut.nodeBefore.type.name !== "container_toggle") { + return false; + } + + const toggleBlock = $cut.nodeBefore; + if (!isToggleBlockFolded(state, toggleBlock)) { + return false; + } + + const pos = $cursor.before() - toggleBlock.nodeSize; + const { tr: tr1, body } = detachToggleBlockBody(pos, state.tr); + let tr = selectNodeBackwardTr(tr1); + tr = attachToggleBlockBody(pos, body, tr); + dispatch?.(tr); + return true; +}; + +export const indentBlock: Command = (state, dispatch) => { + const { $from } = state.selection; + + let before = -1; + for (let d = $from.depth; d >= 0; d--) { + const nodeBefore = prevSibling($from, d); + if (nodeBefore && nodeBefore.type === state.schema.nodes.container_toggle) { + // before of nodeBefore + before = $from.posAtIndex($from.index(d) - 1, d); + break; + } + } + + if (before === -1) { + return false; + } + + const slice = new Slice( + Fragment.from(state.schema.nodes.container_toggle.create()), + 1, + 0 + ); + + const from = before + state.doc.nodeAt(before)!.nodeSize; + const to = from + state.doc.nodeAt(from)!.nodeSize; + const step = new ReplaceAroundStep(from - 1, to, from, to, slice, 0, true); + + const tr = state.tr.step(step).scrollIntoView(); + if (dispatch) { + dispatch(tr); + } + + return true; +}; + +export const toggleBlock: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + if (!isSelectionInToggleBlock(state)) { + return false; + } + + const isToggle = isToggleBlock(state); + const toggle = nearest(ancestors($cursor!).filter(isToggle)); + if (!toggle) { + return false; + } + + const d = getToggleBlockDepth($cursor!, toggle); + const pos = $cursor!.before(d); + const isFolded = isToggleBlockFolded(state, toggle); + + dispatch?.( + state.tr + .setMeta(toggleFoldPluginKey, { + type: isFolded ? Action.UNFOLD : Action.FOLD, + at: pos, + }) + .setMeta(toggleEventPluginKey, { + type: isFolded ? Action.UNFOLD : Action.FOLD, + at: pos, + }) + ); + + return true; +}; + +export const createParagraphNearPreservingBody: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + if (!$cursor) { + return false; + } + + const atStart = isSelectionAtStartOfToggleBlockHead(state); + const atEnd = isSelectionAtEndOfToggleBlockHead(state); + if (!atStart && !atEnd) { + return false; + } + + const toggle = $cursor.node(-1); + if (ToggleBlock.isHeadEmpty(toggle)) { + return false; + } + if (!isToggleBlockFolded(state, toggle)) { + return false; + } + + const pos = atBlockStart(state.selection) + ? $cursor.before(-1) + : $cursor.after(-1); + + let tr = state.tr; + tr = tr.insert(pos, state.schema.nodes.paragraph.create()); + const $before = tr.doc.resolve(tr.selection.$from.before(-1)); + const $after = tr.doc.resolve(tr.selection.$to.after(-1)); + tr = atBlockStart(tr.selection) + ? tr.setSelection(TextSelection.near($before)) + : tr.setSelection(TextSelection.near($after)); + + dispatch?.(tr); + return true; +}; + +export const liftAllEmptyChildBlocks: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + if (!$cursor || !isSelectionAtStartOfToggleBlockHead(state)) { + return false; + } + + const toggle = $cursor.node(-1); + if (!ToggleBlock.isEmpty(toggle)) { + return false; + } + + dispatch?.(liftChildrenOfNodeAt($cursor.before(-1), state.tr)); + return true; +}; + +export const liftAllChildBlocksOfNodeBefore: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + if (!$cursor || !isSelectionAtStartOfToggleBlockHead(state)) { + return false; + } + + dispatch?.(liftChildrenOfNodeAt($cursor.before(-1), state.tr)); + return true; +}; + +export const liftAllChildBlocksOfNodeAfter: Command = (state, dispatch) => { + const $cursor = atBlockEnd(state.selection); + if (!$cursor) { + return false; + } + + const $cut = findCutAfter($cursor); + if (!$cut) { + return false; + } + if (!$cut.nodeAfter || $cut.nodeAfter.type.name !== "container_toggle") { + return false; + } + + dispatch?.(liftChildrenOfNodeAt($cut.pos, state.tr)); + + return true; +}; + +export const dedentBlocks: Command = (state, dispatch) => { + const { $from } = state.selection; + + const isToggle = isToggleBlock(state); + const ancestor = nearest(ancestors($from).filter(isToggle)); + + if (!ancestor) { + return false; + } + + const d = getToggleBlockDepth($from, ancestor); + const $fr_ = + state.selection instanceof NodeSelection + ? state.doc.resolve($from.pos + 1) + : $from; + const $to_ = state.doc.resolve($from.end(d) - 1); + const range = $fr_.blockRange($to_, (node) => node.eq(ancestor)); + if (range === null) { + return false; + } + + const target = liftTarget(range); + if (target === null) { + return false; + } + + const tr = state.tr; + tr.lift(range, target); + if (dispatch) { + dispatch(tr); + } + + return true; +}; + +/** + * Exit toggle block when pressing Enter in the last empty paragraph within the body. + */ +export const exitToggleBlockOnEmptyParagraph: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + if (!$cursor) { + return false; + } + + if (!isSelectionInToggleBlockBody(state)) { + return false; + } + + // Check if current node is an empty paragraph + const node = $cursor.parent; + if (node.type !== state.schema.nodes.paragraph || node.content.size > 0) { + return false; + } + + // Check if this is the last node in the toggle block body + const parentOfParagraph = $cursor.node(-1); + if ($cursor.index(-1) !== parentOfParagraph.childCount - 1) { + return false; + } + + // Check if the paragraph is a direct child of the toggle block + if (parentOfParagraph.type !== state.schema.nodes.container_toggle) { + return false; + } + + // Find the toggle block ancestor + const isToggle = isToggleBlock(state); + const ancestor = nearest(ancestors($cursor).filter(isToggle)); + if (!ancestor) { + return false; + } + + // Create a range scoped to the toggle block ancestor + const d = getToggleBlockDepth($cursor, ancestor); + const $start = state.doc.resolve($cursor.start(d + 1)); + const $end = state.doc.resolve($cursor.end(d + 1)); + const range = $start.blockRange($end, (n) => n.eq(ancestor)); + if (range === null) { + return false; + } + + const target = liftTarget(range); + if (target === null) { + return false; + } + + const tr = state.tr; + tr.lift(range, target); + dispatch?.(tr); + + return true; +}; + +export const splitBlockPreservingBody: Command = (state, dispatch) => { + const { $cursor } = state.selection as TextSelection; + + if (!isSelectionInMiddleOfToggleBlockHead(state)) { + return false; + } + + const toggle = $cursor!.node($cursor!.depth - 1); + if (!isToggleBlockFolded(state, toggle)) { + return false; + } + + let tr = state.tr; + tr = tr.insert( + $cursor!.after(-1), + toggle.firstChild!.type.create( + undefined, + tr.doc.slice($cursor!.pos, $cursor!.end()).content + ) + ); + tr = wrapNodeAt($cursor!.after(-1), toggle.type, { id: v4() }, tr); + tr = tr.setSelection( + TextSelection.near(tr.doc.resolve($cursor!.after(-1)), 1) + ); + tr = tr.delete($cursor!.pos, $cursor!.end()); + dispatch?.(tr); + return true; +}; + +export const splitTopLevelBlockWithinBody: Command = (state, dispatch) => { + const { $from } = state.selection; + if (!isSelectionInToggleBlockBody(state)) { + return false; + } + + const isToggle = isToggleBlock(state); + const ancestor = nearest(ancestors($from).filter(isToggle)); + if (!ancestor) { + return false; + } + + const d = getToggleBlockDepth($from, ancestor); + if (d === $from.depth - 1) { + // split if the block containing cursor is a direct child of a toggle block + return splitBlock(state, dispatch); + } + + return false; +}; diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index 26a862f838..05da422e83 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -515,6 +515,14 @@ const textStyle = () => css` `; const style = (props: Props) => css` +--font-size-p: var(--font-size-body); +--font-size-h1: 28px; +--font-size-h2: 22px; +--font-size-h3: 18px; +--font-size-h4: 16px; +--font-size-h5: 15px; +--font-size-h6: 15px; + flex-grow: ${props.grow ? 1 : 0}; justify-content: start; color: ${props.theme.text}; @@ -644,12 +652,12 @@ width: 100%; // all of heading sizes are stepped down one from global styles, except h1 // which is between h1 and h2 - h1 { font-size: 28px; } - h2 { font-size: 22px; } - h3 { font-size: 18px; } - h4 { font-size: 16px; } - h5 { font-size: 15px; } - h6 { font-size: 15px; } + h1 { font-size: var(--font-size-h1); } + h2 { font-size: var(--font-size-h2); } + h3 { font-size: var(--font-size-h3); } + h4 { font-size: var(--font-size-h4); } + h5 { font-size: var(--font-size-h5); } + h6 { font-size: var(--font-size-h6); } .ProseMirror-yjs-selection { transition: background-color 500ms ease-in-out; @@ -2403,6 +2411,105 @@ del { font-family: "SF Pro Text", ${props.theme.fontFamily}; } } + +.toggle-block { + display: flex; + + &:focus-within { + transition-delay: 0.1s; + } + + &.folded { + &:dir(rtl) { + --rotate-by: 90deg; + } + &:dir(ltr) { + --rotate-by: -90deg; + } + > .toggle-block-content > :is(:not(.toggle-block-head)) { + display: none; + } + > .toggle-block-content > :is(a.heading-name) { + display: unset; + } + > .toggle-block-button { + svg { + transform: rotate(var(--rotate-by)); + pointer-events: none; + } + opacity: 1; + } + } + + > .toggle-block-button { + flex-shrink: 0; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + + --line-height: var(--line-height-p); + --font-size: var(--font-size-p); + + &:has(+ .toggle-block-content > .toggle-block-head > h1) { + --line-height: calc(var(--line-height-h) + 0.2); + --font-size: var(--font-size-h1); + } + + &:has(+ .toggle-block-content > .toggle-block-head > h2) { + --line-height: calc(var(--line-height-h) + 0.2); + --font-size: var(--font-size-h2); + } + + &:has(+ .toggle-block-content > .toggle-block-head > h3) { + --line-height: calc(var(--line-height-h) + 0.2); + --font-size: var(--font-size-h3); + } + + &:has(+ .toggle-block-content > .toggle-block-head > h4) { + --line-height: calc(var(--line-height-h) + 0.2); + --font-size: var(--font-size-h4); + } + + color: ${props.theme.text}; + opacity: 0.75; + cursor: var(--pointer); + background: none; + outline: none; + border: 0; + margin: 0; + padding: 0; + height: calc(var(--line-height) * var(--font-size)); + width: 20px; + overflow: unset; + + &:focus, + &:hover { + opacity: 1; + } + + > svg { + transition: transform 200ms ease-out; + flex-shrink: 0; + } + } + + > .toggle-block-content { + > :is(:not(.toggle-block-head)) { + margin-top: 0.5em; + } + > :is(:first-child) { + margin-top: 0; + } + > .toggle-block-head { + > * { + margin-top: 0; + } + } + flex-grow: 1; + overflow: unset; + } +} `; const EditorContainer = styled.div` diff --git a/shared/editor/extensions/Diff.ts b/shared/editor/extensions/Diff.ts index d49f921efe..d4e84fc98b 100644 --- a/shared/editor/extensions/Diff.ts +++ b/shared/editor/extensions/Diff.ts @@ -9,6 +9,7 @@ import Extension from "../lib/Extension"; import type { ExtendedChange } from "../lib/ChangesetHelper"; import { cn } from "../styles/utils"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; +import { toggleFoldPluginKey } from "../nodes/ToggleBlock"; const pluginKey = new PluginKey("diffs"); @@ -130,7 +131,9 @@ export default class Diff extends Extension { }, // Allow meta transactions to bypass filtering filterTransaction: (tr) => - tr.getMeta("codeHighlighting") || tr.getMeta(pluginKey) + tr.getMeta("codeHighlighting") || + tr.getMeta(pluginKey) || + tr.getMeta(toggleFoldPluginKey) ? true : false, }), diff --git a/shared/editor/nodes/Heading.ts b/shared/editor/nodes/Heading.ts index f5a6de0467..5949e0ddf6 100644 --- a/shared/editor/nodes/Heading.ts +++ b/shared/editor/nodes/Heading.ts @@ -22,6 +22,13 @@ import { findCollapsedNodes } from "../queries/findCollapsedNodes"; import Node from "./Node"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; +export enum HeadingLevel { + One = 1, + Two, + Three, + Four, +} + export default class Heading extends Node { get name() { return "heading"; diff --git a/shared/editor/nodes/Node.ts b/shared/editor/nodes/Node.ts index 8d1df871f4..8e206857e9 100644 --- a/shared/editor/nodes/Node.ts +++ b/shared/editor/nodes/Node.ts @@ -20,6 +20,10 @@ export default abstract class Node extends Extension { return {}; } + get attrs(): NodeSpec["attrs"] { + return {}; + } + get markdownToken(): string { return ""; } diff --git a/shared/editor/nodes/ToggleBlock.ts b/shared/editor/nodes/ToggleBlock.ts new file mode 100644 index 0000000000..7882bceb06 --- /dev/null +++ b/shared/editor/nodes/ToggleBlock.ts @@ -0,0 +1,601 @@ +import { chainCommands, newlineInCode } from "prosemirror-commands"; +import { wrappingInputRule } from "prosemirror-inputrules"; +import type { ParseSpec } from "prosemirror-markdown"; +import type { + NodeSpec, + NodeType, + Node as ProsemirrorNode, + Schema, +} from "prosemirror-model"; +import type { Command, Transaction } from "prosemirror-state"; +import { Plugin, PluginKey, TextSelection } from "prosemirror-state"; +import { findWrapping } from "prosemirror-transform"; +import { Decoration, DecorationSet } from "prosemirror-view"; +import { v4 } from "uuid"; +import Storage from "../../utils/Storage"; +import { + deleteSelectionPreservingBody, + joinForwardPreservingBody, + selectNodeForwardPreservingBody, + joinBackwardWithToggleblock, + selectNodeBackwardPreservingBody, + createParagraphNearPreservingBody, + liftAllEmptyChildBlocks, + liftAllChildBlocksOfNodeAfter, + splitBlockPreservingBody, + toggleBlock, + liftAllChildBlocksOfNodeBefore, + indentBlock, + dedentBlocks, + splitTopLevelBlockWithinBody, + exitToggleBlockOnEmptyParagraph, +} from "../commands/toggleBlock"; +import type { CommandFactory } from "../lib/Extension"; +import type { MarkdownSerializerState } from "../lib/markdown/serializer"; +import { PlaceholderPlugin } from "../plugins/PlaceholderPlugin"; +import { findBlockNodes } from "../queries/findChildren"; +import { findCutAfterHeading } from "../queries/findCutAfterHeading"; +import { isNodeActive } from "../queries/isNodeActive"; +import toggleBlocksRule from "../rules/toggleBlocks"; +import { EditorStyleHelper } from "../styles/EditorStyleHelper"; +import { ancestors, height, liftChildrenOfNodeAt } from "../utils"; +import { isToggleBlock, getToggleBlockDepth } from "../queries/toggleBlock"; +import Node from "./Node"; +import { ToggleBlockView } from "./ToggleBlockView"; + +export enum Action { + INIT, + FOLD, + UNFOLD, +} + +interface ToggleFoldState { + foldedIds: Set; + decorations: DecorationSet; +} + +/** Plugin key for toggle block fold state management. */ +export const toggleFoldPluginKey = new PluginKey("toggleFold"); + +/** Plugin key for toggle block fold/unfold events. */ +export const toggleEventPluginKey = new PluginKey("toggleBlockEvent"); + +/** + * Build decorations for all toggle blocks based on fold state. + * + * @param doc - the document to build decorations for. + * @param foldedIds - set of folded toggle block IDs. + * @returns decoration set for all toggle blocks. + */ +function buildDecorations( + doc: ProsemirrorNode, + foldedIds: Set +): DecorationSet { + const decorations: Decoration[] = []; + + findBlockNodes(doc, true) + .filter((b) => b.node.type.name === "container_toggle" && b.node.attrs.id) + .forEach((block) => { + const id = block.node.attrs.id as string; + const isFolded = foldedIds.has(id); + + // Decoration on the toggle block itself (for fold state) + decorations.push( + Decoration.node( + block.pos, + block.pos + block.node.nodeSize, + {}, + { nodeId: id, fold: isFolded, target: "container_toggle" } + ) + ); + + // Decoration on the head (first child) for styling + decorations.push( + Decoration.node( + block.pos + 1, + block.pos + 1 + block.node.firstChild!.nodeSize, + { nodeName: "div", class: EditorStyleHelper.toggleBlockHead }, + { nodeId: id, target: "container_toggle>:firstChild" } + ) + ); + }); + + return DecorationSet.create(doc, decorations); +} + +export default class ToggleBlock extends Node { + get name() { + return "container_toggle"; + } + + get schema(): NodeSpec { + return { + content: "(paragraph | heading) block*", + group: "block", + attrs: { + id: { default: undefined }, + }, + toDOM: () => [ + "div", + { class: EditorStyleHelper.toggleBlock }, + ["div", { class: EditorStyleHelper.toggleBlockContent }, 0], + ], + }; + } + + get plugins() { + const userId = this.editor.props.userId; + + // Assign IDs, fix positions, auto-fold empty + const fixToggleBlocksPlugin = new Plugin({ + appendTransaction: (transactions, _oldState, newState) => { + if (!transactions.some((tr) => tr.docChanged)) { + return null; + } + + // Single pass to find all toggle blocks + const toggleBlocks = findBlockNodes(newState.doc, true).filter( + (b) => b.node.type.name === this.name + ); + + if (toggleBlocks.length === 0) { + return null; + } + + let tr: Transaction | null = null; + + // 1. Assign IDs to blocks that need them and set fold state for creator + const blocksNeedingIds = toggleBlocks.filter((b) => !b.node.attrs.id); + if (blocksNeedingIds.length > 0) { + tr = newState.tr; + blocksNeedingIds.forEach((block) => { + const id = v4(); + tr!.setNodeAttribute(block.pos, "id", id); + // Set unfolded for the user who created the toggle + Storage.set(`${id}:${userId}`, { fold: false }); + }); + } + + // 2. Fix invalid positions (toggle at start of list item) + // Use the updated doc if we made changes, process in reverse order + const doc = tr?.doc ?? newState.doc; + const currentBlocks = tr + ? findBlockNodes(doc, true).filter( + (b) => b.node.type.name === this.name + ) + : toggleBlocks; + + const invalidBlocks = currentBlocks.filter((block) => { + const $pos = doc.resolve(block.pos); + return ( + $pos.parent.type === newState.schema.nodes.list_item && + $pos.parentOffset === 0 + ); + }); + + if (invalidBlocks.length > 0) { + tr = tr ?? newState.tr; + for (let i = invalidBlocks.length - 1; i >= 0; i--) { + tr.insert( + invalidBlocks[i].pos, + newState.schema.nodes.paragraph.create({}) + ); + } + } + + // 3. Auto-fold toggle blocks with empty bodies + // Only if no structural changes were made (positions would be invalid) + if (!tr) { + const pluginState = toggleFoldPluginKey.getState(newState); + if (pluginState) { + const emptyBodyBlock = toggleBlocks.find( + (b) => + b.node.childCount === 1 && + b.node.attrs.id && + !pluginState.foldedIds.has(b.node.attrs.id) + ); + + if (emptyBodyBlock) { + return newState.tr.setMeta(toggleFoldPluginKey, { + type: Action.FOLD, + at: emptyBodyBlock.pos, + }); + } + } + } + + return tr; + }, + }); + + // Main fold state management + const foldPlugin = new Plugin({ + key: toggleFoldPluginKey, + + state: { + init: () => ({ + foldedIds: new Set(), + decorations: DecorationSet.empty, + }), + + apply: (tr, pluginState, _oldState, newState) => { + const action = tr.getMeta(toggleFoldPluginKey); + + // No action - just map decorations through the transaction + if (!action) { + if (!tr.docChanged) { + return pluginState; + } + + // Check if any toggle blocks were added and need fold state + const currentBlocks = findBlockNodes(tr.doc, true).filter( + (b) => b.node.type.name === this.name && b.node.attrs.id + ); + + const newFoldedIds = new Set(pluginState.foldedIds); + + // For any new blocks, check storage and default to folded + currentBlocks.forEach((block) => { + const id = block.node.attrs.id as string; + if (!pluginState.foldedIds.has(id)) { + const stored = Storage.get(`${id}:${userId}`); + // Default to folded if no stored state (new block from sync) + if (stored?.fold !== false) { + newFoldedIds.add(id); + } + } + }); + + // Always rebuild decorations to ensure head positions are correct + // (mapping can produce incorrect positions when first child changes) + return { + foldedIds: newFoldedIds, + decorations: buildDecorations(tr.doc, newFoldedIds), + }; + } + + // Handle actions that change fold state + const newFoldedIds = new Set(pluginState.foldedIds); + + switch (action.type) { + case Action.INIT: { + // Initialize fold states from Storage for all toggle blocks + findBlockNodes(newState.doc, true) + .filter( + (b) => b.node.type.name === this.name && b.node.attrs.id + ) + .forEach((block) => { + const id = block.node.attrs.id as string; + const stored = Storage.get(`${id}:${userId}`); + // Default to folded if no stored state + if (stored?.fold !== false) { + newFoldedIds.add(id); + } + // Ensure storage has a value + if (stored === null || stored === undefined) { + Storage.set(`${id}:${userId}`, { fold: true }); + } + }); + break; + } + + case Action.FOLD: { + const node = newState.doc.nodeAt(action.at); + if (node?.attrs.id) { + newFoldedIds.add(node.attrs.id); + Storage.set(`${node.attrs.id}:${userId}`, { fold: true }); + } + break; + } + + case Action.UNFOLD: { + const node = newState.doc.nodeAt(action.at); + if (node?.attrs.id) { + newFoldedIds.delete(node.attrs.id); + Storage.set(`${node.attrs.id}:${userId}`, { fold: false }); + } + break; + } + } + + return { + foldedIds: newFoldedIds, + decorations: buildDecorations(newState.doc, newFoldedIds), + }; + }, + }, + + props: { + decorations: (state) => + toggleFoldPluginKey.getState(state)?.decorations, + nodeViews: { + [this.name]: (node, view, getPos, decorations, innerDecorations) => + new ToggleBlockView( + node, + view, + getPos, + decorations, + innerDecorations, + this.editor.props + ), + }, + }, + }); + + // Initialize fold state on document load + const initPlugin = new Plugin({ + view: () => { + let initialized = false; + return { + update: (view, prevState) => { + if (initialized) { + return; + } + + const hasContent = view.state.doc.content.size > 2; + if (!hasContent) { + return; + } + + const isMultiplayer = this.editor.props.extensions?.some( + (e: { name: string }) => e.name === "multiplayer" + ); + + // For multiplayer, wait for first real content load + if (isMultiplayer && prevState.doc.content.size > 2) { + return; + } + + // Set flag before dispatch to prevent re-entry + initialized = true; + view.dispatch( + view.state.tr.setMeta(toggleFoldPluginKey, { + type: Action.INIT, + }) + ); + }, + }; + }, + }); + + // Handle fold/unfold side effects (cursor management, empty body handling) + const eventPlugin = new Plugin({ + key: toggleEventPluginKey, + + appendTransaction: (transactions, _oldState, newState) => { + const eventTr = transactions.find((tr) => + tr.getMeta(toggleEventPluginKey) + ); + + let tr: Transaction | null = null; + + if (eventTr) { + const event = eventTr.getMeta(toggleEventPluginKey); + const node = newState.doc.nodeAt(event.at); + + if (node) { + if (event.type === Action.FOLD) { + // Move cursor out of body if folding + const { $anchor } = newState.selection; + const startOfNode = event.at + 1; + const endOfFirstChild = startOfNode + node.firstChild!.nodeSize; + const endOfNode = startOfNode + node.nodeSize - 1; + + if ($anchor.pos > endOfFirstChild && $anchor.pos < endOfNode) { + const $endOfFirstChild = newState.doc.resolve(endOfFirstChild); + tr = newState.tr.setSelection( + TextSelection.near($endOfFirstChild, -1) + ); + } + } else if (event.type === Action.UNFOLD) { + // Insert empty paragraph if body is empty (for placeholder visibility) + if (node.childCount === 1) { + tr = newState.tr.insert( + event.at + 1 + node.content.size, + newState.schema.nodes.paragraph.create({}) + ); + } + } + } + } + + // Auto-unfold if cursor is in body of folded toggle + // Skip if we're handling a fold event (cursor will be moved out of body) + const isFoldEvent = + eventTr?.getMeta(toggleEventPluginKey)?.type === Action.FOLD; + + if (!isFoldEvent) { + const { $from } = newState.selection; + const pluginState = toggleFoldPluginKey.getState(newState); + const isToggle = isToggleBlock(newState); + + if (pluginState) { + const toggleBlockAncestor = ancestors($from).find( + (node) => + isToggle(node) && pluginState.foldedIds.has(node.attrs.id) + ); + + if (toggleBlockAncestor) { + const d = getToggleBlockDepth($from, toggleBlockAncestor); + const posAfterHead = + $from.start(d) + toggleBlockAncestor.firstChild!.nodeSize; + const posAtEnd = $from.end(d); + + if ($from.pos > posAfterHead && $from.pos < posAtEnd) { + tr = (tr ?? newState.tr).setMeta(toggleFoldPluginKey, { + type: Action.UNFOLD, + at: $from.before(d), + }); + } + } + } + } + + return tr; + }, + }); + + return [ + fixToggleBlocksPlugin, + foldPlugin, + initPlugin, + eventPlugin, + new PlaceholderPlugin([ + { + condition: ({ node, $start, parent }) => + parent !== null && + parent.type.name === "container_toggle" && + $start.index($start.depth - 1) === 0 && + node.textContent === "", + text: this.options.dictionary?.emptyToggleBlockHead, + }, + { + condition: ({ parent, $start, state }) => + parent !== null && + parent.type.name === "container_toggle" && + $start.index($start.depth - 1) === 1 && + ToggleBlock.isBodyEmpty(parent) && + (state.selection.$from.pos < $start.pos || + state.selection.$from.pos > $start.end($start.depth - 1)), + text: this.options.dictionary?.emptyToggleBlockBody, + }, + { + condition: ({ node, parent, $start, state }) => + parent !== null && + parent.type.name === "container_toggle" && + node.isTextblock && + node.textContent === "" && + (state.selection as TextSelection).$cursor?.pos === $start.pos, + text: this.options.dictionary?.newLineEmpty, + }, + ]), + ]; + } + + get rulePlugins() { + return [toggleBlocksRule]; + } + + keys(): Record { + return { + Backspace: chainCommands( + deleteSelectionPreservingBody, + liftAllChildBlocksOfNodeBefore, + joinBackwardWithToggleblock, + selectNodeBackwardPreservingBody + ), + Enter: chainCommands( + newlineInCode, + createParagraphNearPreservingBody, + liftAllEmptyChildBlocks, + exitToggleBlockOnEmptyParagraph, + splitBlockPreservingBody, + splitTopLevelBlockWithinBody + ), + Delete: chainCommands( + deleteSelectionPreservingBody, + liftAllChildBlocksOfNodeAfter, + joinForwardPreservingBody, + selectNodeForwardPreservingBody + ), + Tab: indentBlock, + "Shift-Tab": dedentBlocks, + "Mod-Enter": toggleBlock, + }; + } + + inputRules({ type }: { type: NodeType }) { + return [ + wrappingInputRule( + /^\s*\+\+\+\s$/, + type, + undefined, + (_match, _node) => false + ), + ]; + } + + commands({ + type, + schema, + }: { + type: NodeType; + schema: Schema; + }): CommandFactory { + return () => (state, dispatch) => { + const { $from, $to } = state.selection; + if (isNodeActive(type)(state)) { + dispatch?.(liftChildrenOfNodeAt($from.before(-1), state.tr)); + return true; + } + // if heading + if ($from.parent.type === state.schema.nodes.heading) { + const $fr_ = TextSelection.near($from, 1).$from; + const $to_ = TextSelection.near(findCutAfterHeading($from), -1).$to; + const id = v4(); + const range = $fr_.blockRange($to_), + wrapping = range && findWrapping(range, type, { id }); + if (!wrapping) { + return false; + } + Storage.set(`${id}:${this.editor.props.userId}`, { fold: false }); + const tr = state.tr.wrap(range!, wrapping); + dispatch?.(tr); + return true; + } + // if para + if ($from.parent.type === state.schema.nodes.paragraph) { + const id = v4(); + const range = $from.blockRange($to), + wrapping = range && findWrapping(range, type, { id }); + if (!wrapping) { + return false; + } + + Storage.set(`${id}:${this.editor.props.userId}`, { fold: false }); + const tr = state.tr.wrap(range!, wrapping); + dispatch?.( + tr.insert( + tr.selection.$from.after(), + schema.nodes.paragraph.create({}) + ) + ); + return true; + } + + return false; + }; + } + + toMarkdown(state: MarkdownSerializerState, node: ProsemirrorNode) { + state.write(state.repeat("+", 3 + height(node)) + "\n"); + state.renderContent(node); + state.write(state.repeat("+", 3 + height(node)) + "\n"); + } + + parseMarkdown(): ParseSpec | void { + return { + block: "container_toggle", + }; + } + + static isEmpty(toggleBlock: ProsemirrorNode) { + return ( + ToggleBlock.isHeadEmpty(toggleBlock) && + ToggleBlock.isBodyEmpty(toggleBlock) + ); + } + + static isHeadEmpty(toggleBlock: ProsemirrorNode) { + return toggleBlock.firstChild!.content.size === 0; + } + + static isBodyEmpty(toggleBlock: ProsemirrorNode) { + for (let i = 1; i < toggleBlock.childCount; i++) { + if (toggleBlock.child(i).content.size > 0) { + return false; + } + } + return true; + } +} diff --git a/shared/editor/nodes/ToggleBlockView.ts b/shared/editor/nodes/ToggleBlockView.ts new file mode 100644 index 0000000000..312ce87a7c --- /dev/null +++ b/shared/editor/nodes/ToggleBlockView.ts @@ -0,0 +1,137 @@ +import type { Node as ProsemirrorNode } from "prosemirror-model"; +import type { EditorView, NodeView, DecorationSource } from "prosemirror-view"; +import type { Decoration } from "prosemirror-view"; +import { EditorStyleHelper } from "../styles/EditorStyleHelper"; +import { + Action, + toggleEventPluginKey, + toggleFoldPluginKey, +} from "./ToggleBlock"; + +/** + * Custom NodeView for toggle blocks that handles fold/unfold UI interactions. + */ +export class ToggleBlockView implements NodeView { + dom: HTMLDivElement; + contentDOM: HTMLDivElement; + private button: HTMLButtonElement; + private node: ProsemirrorNode; + private view: EditorView; + private getPos: () => number | undefined; + private editorProps: Record; + private boundBroadcastFoldState: (event: StorageEvent) => void; + + constructor( + node: ProsemirrorNode, + view: EditorView, + getPos: () => number | undefined, + decorations: readonly Decoration[], + _innerDecorations: DecorationSource, + editorProps: Record + ) { + this.node = node; + this.view = view; + this.getPos = getPos; + this.editorProps = editorProps; + + // Create DOM structure + this.dom = document.createElement("div"); + this.dom.className = EditorStyleHelper.toggleBlock; + + this.button = document.createElement("button"); + this.button.className = EditorStyleHelper.toggleBlockButton; + this.button.contentEditable = "false"; + this.button.innerHTML = + ''; + this.button.addEventListener("mousedown", this.handleToggle); + + this.contentDOM = document.createElement("div"); + this.contentDOM.className = EditorStyleHelper.toggleBlockContent; + + this.dom.appendChild(this.button); + this.dom.appendChild(this.contentDOM); + + // Set initial fold state from decorations + this.syncFoldState(decorations); + + // Listen for cross-tab storage changes + this.boundBroadcastFoldState = this.broadcastFoldState.bind(this); + window.addEventListener("storage", this.boundBroadcastFoldState); + } + + private handleToggle = (event: MouseEvent) => { + event.preventDefault(); + if (event.button !== 0) { + return; + } + + const pos = this.getPos(); + if (pos === undefined) { + return; + } + + const isFolded = this.dom.classList.contains( + EditorStyleHelper.toggleBlockFolded + ); + + this.view.dispatch( + this.view.state.tr + .setMeta(toggleFoldPluginKey, { + type: isFolded ? Action.UNFOLD : Action.FOLD, + at: pos, + }) + .setMeta(toggleEventPluginKey, { + type: isFolded ? Action.UNFOLD : Action.FOLD, + at: pos, + }) + ); + }; + + private broadcastFoldState(event: StorageEvent) { + const key = `${this.node.attrs.id}:${this.editorProps.userId}`; + if (event.key !== key || !event.newValue || !event.oldValue) { + return; + } + + const newFoldState = JSON.parse(event.newValue); + const oldFoldState = JSON.parse(event.oldValue); + + if (newFoldState.fold !== oldFoldState.fold) { + const pos = this.getPos(); + if (pos === undefined) { + return; + } + + this.view.dispatch( + this.view.state.tr + .setMeta(toggleFoldPluginKey, { + type: newFoldState.fold ? Action.FOLD : Action.UNFOLD, + at: pos, + }) + .setMeta(toggleEventPluginKey, { + type: newFoldState.fold ? Action.FOLD : Action.UNFOLD, + at: pos, + }) + ); + } + } + + private syncFoldState(decorations: readonly Decoration[]) { + const isFolded = decorations.some((d) => d.spec.fold === true); + this.dom.classList.toggle(EditorStyleHelper.toggleBlockFolded, isFolded); + } + + update(node: ProsemirrorNode, decorations: readonly Decoration[]) { + if (node.type !== this.node.type) { + return false; + } + this.node = node; + this.syncFoldState(decorations); + return true; + } + + destroy() { + this.button.removeEventListener("mousedown", this.handleToggle); + window.removeEventListener("storage", this.boundBroadcastFoldState); + } +} diff --git a/shared/editor/nodes/index.ts b/shared/editor/nodes/index.ts index d9538d5374..4c6a6b953b 100644 --- a/shared/editor/nodes/index.ts +++ b/shared/editor/nodes/index.ts @@ -42,6 +42,8 @@ import TableCell from "./TableCell"; import TableHeader from "./TableHeader"; import TableRow from "./TableRow"; import Text from "./Text"; +import ToggleBlock from "./ToggleBlock"; + import Video from "./Video"; type Nodes = (typeof Node | typeof Mark | typeof Extension)[]; @@ -114,6 +116,7 @@ export const richExtensions: Nodes = [ Math, MathBlock, Mention, + ToggleBlock, // Container type nodes should be last so that key handlers are registered for content inside // the container nodes first. ...listExtensions, diff --git a/shared/editor/queries/findCutAfterHeading.ts b/shared/editor/queries/findCutAfterHeading.ts new file mode 100644 index 0000000000..7e83094ff1 --- /dev/null +++ b/shared/editor/queries/findCutAfterHeading.ts @@ -0,0 +1,33 @@ +import filter from "lodash/filter"; +import type { ResolvedPos } from "prosemirror-model"; +import { findBlockNodes } from "./findChildren"; + +export function findCutAfterHeading($pos: ResolvedPos): ResolvedPos { + const blocksAfterPos = filter( + findBlockNodes($pos.doc, true), + (block) => block.pos > $pos.pos + ); + + const d = $pos.depth - 1; + const l = $pos.parent.attrs.level; + let cut = $pos.end(-1); + for (let i = blocksAfterPos.length - 1; i >= 0; i--) { + const block = blocksAfterPos[i]; + const di = $pos.doc.resolve(block.pos).depth; + const pi = block.pos; + + if (di < d) { + cut = pi - 1; + continue; + } + + if (block.node.type.name === "heading") { + const li = block.node.attrs.level; + if (di === d && li <= l) { + cut = pi - 1; + } + } + } + + return $pos.doc.resolve(cut); +} diff --git a/shared/editor/queries/isNodeActive.ts b/shared/editor/queries/isNodeActive.ts index 13f699fc40..761796abf1 100644 --- a/shared/editor/queries/isNodeActive.ts +++ b/shared/editor/queries/isNodeActive.ts @@ -1,8 +1,9 @@ +import { NodeSelection } from "prosemirror-state"; import type { NodeType } from "prosemirror-model"; import type { EditorState } from "prosemirror-state"; -import { NodeSelection } from "prosemirror-state"; import type { Primitive } from "utility-types"; import { findParentNode } from "./findParentNode"; +import { isSelectionInToggleBlockHead } from "./toggleBlock"; type Options = { /** Only return match if the range and attrs is exact */ @@ -26,6 +27,12 @@ export const isNodeActive = return false; } + if (type === state.schema.nodes.container_toggle) { + // `container_toggle` is a special case where it's considered active + // only when the selection lies within its head + return isSelectionInToggleBlockHead(state); + } + let nodeWithPos; const { from, to } = state.selection; diff --git a/shared/editor/queries/toggleBlock.ts b/shared/editor/queries/toggleBlock.ts new file mode 100644 index 0000000000..22cace913e --- /dev/null +++ b/shared/editor/queries/toggleBlock.ts @@ -0,0 +1,199 @@ +import type { Node as ProsemirrorNode, ResolvedPos } from "prosemirror-model"; +import type { EditorState, Transaction } from "prosemirror-state"; +import { Slice } from "prosemirror-model"; +import { toggleFoldPluginKey } from "../nodes/ToggleBlock"; +import { ancestors } from "../utils"; +import { findParentNodeClosestToPos } from "./findParentNode"; + +/** + * Check if a node is a toggle block. + * + * @param state - the editor state. + * @returns a predicate function. + */ +export const isToggleBlock = + (state: EditorState) => + (node: ProsemirrorNode): boolean => + node.type === state.schema.nodes.container_toggle; + +/** + * Check if a toggle block is currently folded. + * + * @param state - the editor state. + * @param toggleBlock - the toggle block node to check. + * @returns true if the toggle block is folded. + */ +export function isToggleBlockFolded( + state: EditorState, + toggleBlock: ProsemirrorNode +): boolean { + const pluginState = toggleFoldPluginKey.getState(state); + return pluginState?.foldedIds.has(toggleBlock.attrs.id) ?? false; +} + +/** + * Find the depth of a toggle block relative to the selection. + * + * @param $pos - the resolved position to search from. + * @param toggleBlock - the toggle block node to find. + * @returns the depth of the toggle block, or -1 if not found. + */ +export function getToggleBlockDepth( + $pos: ResolvedPos, + toggleBlock: ProsemirrorNode +): number { + return ancestors($pos).findIndex((node) => node.eq(toggleBlock)); +} + +/** + * Find the nearest parent toggle block from a position. + * + * @param state - the editor state. + * @param $pos - the resolved position to search from. + * @returns the toggle block node and position info, or undefined. + */ +export function findParentToggleBlock(state: EditorState, $pos: ResolvedPos) { + return findParentNodeClosestToPos($pos, isToggleBlock(state)); +} + +/** + * Check if the selection is within a toggle block. + * + * @param state - the editor state. + * @returns true if the selection is within a toggle block. + */ +export function isSelectionInToggleBlock(state: EditorState): boolean { + return ancestors(state.selection.$from).some(isToggleBlock(state)); +} + +/** + * Check if the selection is within the head (first child) of a toggle block. + * + * @param state - the editor state. + * @returns true if the selection is within a toggle block head. + */ +export function isSelectionInToggleBlockHead(state: EditorState): boolean { + const parent = findParentToggleBlock(state, state.selection.$from); + if (!parent) { + return false; + } + return state.selection.$from.index(parent.depth) === 0; +} + +/** + * Check if the selection is within the body of a toggle block. + * + * @param state - the editor state. + * @returns true if the selection is within a toggle block body. + */ +export function isSelectionInToggleBlockBody(state: EditorState): boolean { + return ( + isSelectionInToggleBlock(state) && !isSelectionInToggleBlockHead(state) + ); +} + +/** + * Check if the cursor is at the start of a toggle block head. + * + * @param state - the editor state. + * @returns true if the cursor is at the start of a toggle block head. + */ +export function isSelectionAtStartOfToggleBlockHead( + state: EditorState +): boolean { + return ( + isSelectionInToggleBlockHead(state) && + state.selection.$from.parentOffset === 0 + ); +} + +/** + * Check if the cursor is in the middle of a toggle block head. + * + * @param state - the editor state. + * @returns true if the cursor is in the middle of a toggle block head. + */ +export function isSelectionInMiddleOfToggleBlockHead( + state: EditorState +): boolean { + if (!isSelectionInToggleBlockHead(state)) { + return false; + } + const { $from } = state.selection; + return ( + $from.parentOffset > 0 && $from.parentOffset < $from.node().content.size + ); +} + +/** + * Check if the cursor is at the end of a toggle block head. + * + * @param state - the editor state. + * @returns true if the cursor is at the end of a toggle block head. + */ +export function isSelectionAtEndOfToggleBlockHead(state: EditorState): boolean { + if (!isSelectionInToggleBlockHead(state)) { + return false; + } + const { $from } = state.selection; + return $from.parentOffset === $from.node().content.size; +} + +/** + * Result of detaching the body from a toggle block. + */ +export interface DetachBodyResult { + /** The modified transaction. */ + tr: Transaction; + /** The detached body content. */ + body: ProsemirrorNode[]; +} + +/** + * Detach the body content from a toggle block, returning both the modified + * transaction and the detached content. + * + * @param pos - the position of the toggle block. + * @param tr - the transaction to modify. + * @returns the modified transaction and detached body content. + */ +export function detachToggleBlockBody( + pos: number, + tr: Transaction +): DetachBodyResult { + const $start = tr.doc.resolve(pos + 1); + const toggleBlock = tr.doc.nodeAt(pos); + + const posBeforeBody = $start.pos + toggleBlock!.firstChild!.nodeSize; + const posAfterBody = $start.end(); + + // Extract body content before deleting + const bodySlice = tr.doc.slice(posBeforeBody, posAfterBody); + const body: ProsemirrorNode[] = []; + bodySlice.content.forEach((node) => body.push(node)); + + // Delete the body from the document + const newTr = tr.replace(posBeforeBody, posAfterBody, Slice.empty); + + return { tr: newTr, body }; +} + +/** + * Attach body content back to a toggle block. + * + * @param pos - the position of the toggle block. + * @param body - the body content to attach. + * @param tr - the transaction to modify. + * @returns the modified transaction. + */ +export function attachToggleBlockBody( + pos: number, + body: ProsemirrorNode[], + tr: Transaction +): Transaction { + const $start = tr.doc.resolve(pos + 1); + const toggleBlock = tr.doc.nodeAt(pos); + + const posAfterHead = $start.pos + toggleBlock!.firstChild!.nodeSize; + return tr.insert(posAfterHead, body); +} diff --git a/shared/editor/rules/toggleBlocks.ts b/shared/editor/rules/toggleBlocks.ts new file mode 100644 index 0000000000..6aff14e422 --- /dev/null +++ b/shared/editor/rules/toggleBlocks.ts @@ -0,0 +1,9 @@ +import type MarkdownIt from "markdown-it"; +import customFence from "markdown-it-container"; + +export default function toggleBlocks(md: MarkdownIt): void { + return customFence(md, "toggle", { + marker: "+", + validate: () => true, + }); +} diff --git a/shared/editor/styles/EditorStyleHelper.ts b/shared/editor/styles/EditorStyleHelper.ts index 5ef21f946f..f61b0e6854 100644 --- a/shared/editor/styles/EditorStyleHelper.ts +++ b/shared/editor/styles/EditorStyleHelper.ts @@ -42,6 +42,23 @@ export class EditorStyleHelper { static readonly diffCurrentChange = "current-diff"; + // Toggle blocks + + /** Toggle block wrapper */ + static readonly toggleBlock = "toggle-block"; + + /** Toggle block button */ + static readonly toggleBlockButton = "toggle-block-button"; + + /** Toggle block content area */ + static readonly toggleBlockContent = "toggle-block-content"; + + /** Toggle block head (first child) */ + static readonly toggleBlockHead = "toggle-block-head"; + + /** Toggle block folded state */ + static readonly toggleBlockFolded = "folded"; + // Tables /** Table wrapper */ diff --git a/shared/editor/utils.ts b/shared/editor/utils.ts new file mode 100644 index 0000000000..808febf1c2 --- /dev/null +++ b/shared/editor/utils.ts @@ -0,0 +1,560 @@ +import filter from "lodash/filter"; +import isNull from "lodash/isNull"; +import type { Node, NodeType, ResolvedPos, Attrs } from "prosemirror-model"; +import { Slice, Fragment } from "prosemirror-model"; +import type { TextSelection, Transaction } from "prosemirror-state"; +import { NodeSelection, Selection } from "prosemirror-state"; +import type { ReplaceStep } from "prosemirror-transform"; +import { + canJoin, + findWrapping, + liftTarget, + ReplaceAroundStep, + replaceStep, +} from "prosemirror-transform"; + +const textblockAt = (node: Node, side: "start" | "end", only = false) => { + for ( + let scan: Node | null = node; + scan; + scan = side === "start" ? scan.firstChild : scan.lastChild + ) { + if (scan.isTextblock) { + return true; + } + if (only && scan.childCount !== 1) { + return false; + } + } + return false; +}; + +const joinMaybeClear = ( + tr: Transaction, + $pos: ResolvedPos +): Transaction | null => { + const before = $pos.nodeBefore, + after = $pos.nodeAfter, + index = $pos.index(); + if (!before || !after || !before.type.compatibleContent(after.type)) { + return null; + } + if (!before.content.size && $pos.parent.canReplace(index - 1, index)) { + return tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView(); + } + if ( + !$pos.parent.canReplace(index, index + 1) || + !(after.isTextblock || canJoin(tr.doc, $pos.pos)) + ) { + return null; + } + return tr.join($pos.pos).scrollIntoView(); +}; + +const deleteBarrier = ( + tr: Transaction, + $cut: ResolvedPos, + dir: number +): Transaction | null => { + const before = $cut.nodeBefore!, + after = $cut.nodeAfter!; + let conn, match; + const isolated = before.type.spec.isolating || after.type.spec.isolating; + if (!isolated) { + const joinMaybeTr = joinMaybeClear(tr, $cut); + if (joinMaybeTr) { + return joinMaybeTr; + } + } + + const canDelAfter = + !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1); + if ( + canDelAfter && + (conn = (match = before.contentMatchAt(before.childCount)).findWrapping( + after.type + )) && + match.matchType(conn[0] || after.type)!.validEnd + ) { + const end = $cut.pos + after.nodeSize; + let wrap = Fragment.empty; + for (let i = conn.length - 1; i >= 0; i--) { + wrap = Fragment.from(conn[i].create(null, wrap)); + } + + wrap = Fragment.from(before.copy(wrap)); + tr = tr.step( + new ReplaceAroundStep( + $cut.pos - 1, + end, + $cut.pos, + end, + new Slice(wrap, 1, 0), + conn.length, + true + ) + ); + const $joinAt = tr.doc.resolve(end + 2 * conn.length); + if ( + $joinAt.nodeAfter && + $joinAt.nodeAfter.type === before.type && + canJoin(tr.doc, $joinAt.pos) + ) { + tr = tr.join($joinAt.pos); + } + return tr.scrollIntoView(); + } + + const selAfter = + after.type.spec.isolating || (dir > 0 && isolated) + ? null + : Selection.findFrom($cut, 1); + const range = selAfter && selAfter.$from.blockRange(selAfter.$to), + target = range && liftTarget(range); + if (target !== null && target >= $cut.depth) { + return tr.lift(range!, target).scrollIntoView(); + } + + if ( + canDelAfter && + textblockAt(after, "start", true) && + textblockAt(before, "end") + ) { + let at = before; + const wrap = []; + for (;;) { + wrap.push(at); + if (at.isTextblock) { + break; + } + at = at.lastChild!; + } + let afterText = after, + afterDepth = 1; + for (; !afterText.isTextblock; afterText = afterText.firstChild!) { + afterDepth++; + } + + if (at.canReplace(at.childCount, at.childCount, afterText.content)) { + let end = Fragment.empty; + for (let i = wrap.length - 1; i >= 0; i--) { + end = Fragment.from(wrap[i].copy(end)); + } + + tr = tr.step( + new ReplaceAroundStep( + $cut.pos - wrap.length, + $cut.pos + after.nodeSize, + $cut.pos + afterDepth, + $cut.pos + after.nodeSize - afterDepth, + new Slice(end, wrap.length, 0), + 0, + true + ) + ); + return tr.scrollIntoView(); + } + } + + return null; +}; + +/** + * Finds the position after the current block where a cut can be made. + * + * @param $pos - the resolved position to search from. + * @returns the resolved position after the cut point, or null if none found. + */ +export const findCutAfter = ($pos: ResolvedPos): ResolvedPos | null => { + if (!$pos.parent.type.spec.isolating) { + for (let i = $pos.depth - 1; i >= 0; i--) { + const parent = $pos.node(i); + if ($pos.index(i) + 1 < parent.childCount) { + return $pos.doc.resolve($pos.after(i + 1)); + } + if (parent.type.spec.isolating) { + break; + } + } + } + return null; +}; + +/** + * Returns the cursor position if it's at the end of a text block. + * + * @param selection - the current selection. + * @returns the cursor position if at block end, or null otherwise. + */ +export const atBlockEnd = (selection: Selection): ResolvedPos | null => { + const { $cursor } = selection as TextSelection; + if (!$cursor || $cursor.parentOffset < $cursor.parent.content.size) { + return null; + } + return $cursor; +}; + +/** + * Deletes the current selection if it's not empty. + * + * @param tr - the transaction to modify. + * @returns the modified transaction. + */ +export const deleteSelectionTr = (tr: Transaction): Transaction => { + if (tr.selection.empty) { + return tr; + } + return tr.deleteSelection(); +}; + +/** + * Joins the current block with the next block when at the end of a text block. + * + * @param tr - the transaction to modify. + * @returns the modified transaction. + */ +export const joinForwardTr = (tr: Transaction): Transaction => { + const $cursor = atBlockEnd(tr.selection); + if (!$cursor) { + return tr; + } + + const $cut = findCutAfter($cursor); + // If there is no node after this, there's nothing to do + if (!$cut) { + return tr; + } + + const after = $cut.nodeAfter!; + // Try the joining algorithm + const delBarrierTr = deleteBarrier(tr, $cut, 1); + if (delBarrierTr) { + return delBarrierTr; + } + + // If the node above has no content and the node below is + // selectable, delete the node above and select the one below. + if ( + $cursor.parent.content.size === 0 && + (textblockAt(after, "start") || NodeSelection.isSelectable(after)) + ) { + const delStep = replaceStep( + tr.doc, + $cursor.before(), + $cursor.after(), + Slice.empty + ); + if ( + delStep && + (delStep as ReplaceStep).slice.size < + (delStep as ReplaceStep).to - (delStep as ReplaceStep).from + ) { + tr = tr.step(delStep); + tr = tr.setSelection( + textblockAt(after, "start") + ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)! + : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)) + ); + return tr.scrollIntoView(); + } + } + + // If the next node is an atom, delete it + if (after.isAtom && $cut.depth === $cursor.depth - 1) { + return tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView(); + } + + return tr; +}; + +/** + * Selects the next node when at the end of a text block. + * + * @param tr - the transaction to modify. + * @returns the modified transaction with the next node selected. + */ +export const selectNodeForwardTr = (tr: Transaction): Transaction => { + const { $head, empty } = tr.selection; + let $cut: ResolvedPos | null = $head; + if (!empty) { + return tr; + } + if ($head.parent.isTextblock) { + if ($head.parentOffset < $head.parent.content.size) { + return tr; + } + $cut = findCutAfter($head); + } + const node = $cut && $cut.nodeAfter; + if (!node || !NodeSelection.isSelectable(node)) { + return tr; + } + return tr + .setSelection(NodeSelection.create(tr.doc, $cut!.pos)) + .scrollIntoView(); +}; + +/** + * Wraps the node at the given position with the specified node type. + * + * @param pos - the position of the node to wrap. + * @param nodeType - the type of wrapper node to create. + * @param attrs - optional attributes for the wrapper node. + * @param tr - the transaction to modify. + * @returns the modified transaction. + */ +export const wrapNodeAt = ( + pos: number, + nodeType: NodeType, + attrs: Attrs | null = null, + tr: Transaction +): Transaction => { + const $from = tr.doc.resolve(pos + 1); + const $to = tr.doc.resolve($from.end()); + const range = $from.blockRange($to), + wrapping = range && findWrapping(range, nodeType, attrs); + if (!wrapping) { + return tr; + } + return tr.wrap(range!, wrapping).scrollIntoView(); +}; + +/** + * Finds the position before the current block where a cut can be made. + * + * @param $pos - the resolved position to search from. + * @returns the resolved position before the cut point, or null if none found. + */ +export const findCutBefore = ($pos: ResolvedPos): ResolvedPos | null => { + if (!$pos.parent.type.spec.isolating) { + for (let i = $pos.depth - 1; i >= 0; i--) { + if ($pos.index(i) > 0) { + return $pos.doc.resolve($pos.before(i + 1)); + } + if ($pos.node(i).type.spec.isolating) { + break; + } + } + } + return null; +}; + +/** + * Selects the previous node when at the start of a text block. + * + * @param tr - the transaction to modify. + * @returns the modified transaction with the previous node selected. + */ +export const selectNodeBackwardTr = (tr: Transaction): Transaction => { + const { $head, empty } = tr.selection; + let $cut: ResolvedPos | null = $head; + if (!empty) { + return tr; + } + + if ($head.parent.isTextblock) { + if ($head.parentOffset > 0) { + return tr; + } + $cut = findCutBefore($head); + } + const node = $cut && $cut.nodeBefore; + if (!node || !NodeSelection.isSelectable(node)) { + return tr; + } + return tr + .setSelection(NodeSelection.create(tr.doc, $cut!.pos - node.nodeSize)) + .scrollIntoView(); +}; + +/** + * Returns the cursor position if it's at the start of a text block. + * + * @param selection - the current selection. + * @returns the cursor position if at block start, or null otherwise. + */ +export const atBlockStart = (selection: Selection): ResolvedPos | null => { + const { $cursor } = selection as TextSelection; + if (!$cursor || $cursor.parentOffset > 0) { + return null; + } + return $cursor; +}; + +/** + * Joins the current block with the previous block when at the start of a text block. + * + * @param tr - the transaction to modify. + * @returns the modified transaction. + */ +export const joinBackwardTr = (tr: Transaction): Transaction => { + const $cursor = atBlockStart(tr.selection); + if (!$cursor) { + return tr; + } + + const $cut = findCutBefore($cursor); + + // If there is no node before this, try to lift + if (!$cut) { + const range = $cursor.blockRange(), + target = range && liftTarget(range); + if (target === null) { + return tr; + } + return tr.lift(range!, target).scrollIntoView(); + } + + const before = $cut.nodeBefore!; + // Apply the joining algorithm + const delBarrierTr = deleteBarrier(tr, $cut, 1); + if (delBarrierTr) { + return delBarrierTr; + } + + // If the node below has no content and the node above is + // selectable, delete the node below and select the one above. + if ( + $cursor.parent.content.size === 0 && + (textblockAt(before, "end") || NodeSelection.isSelectable(before)) + ) { + for (let depth = $cursor.depth; ; depth--) { + const delStep = replaceStep( + tr.doc, + $cursor.before(depth), + $cursor.after(depth), + Slice.empty + ); + if ( + delStep && + (delStep as ReplaceStep).slice.size < + (delStep as ReplaceStep).to - (delStep as ReplaceStep).from + ) { + tr = tr.step(delStep); + tr.setSelection( + textblockAt(before, "end") + ? Selection.findFrom( + tr.doc.resolve(tr.mapping.map($cut.pos, -1)), + -1 + )! + : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize) + ); + return tr.scrollIntoView(); + } + if (depth === 1 || $cursor.node(depth - 1).childCount > 1) { + break; + } + } + } + + // If the node before is an atom, delete it + if (before.isAtom && $cut.depth === $cursor.depth - 1) { + return tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView(); + } + + return tr; +}; + +/** + * Returns an array of ancestor nodes for the given position, ordered by increasing depth. + * + * @param $from - the resolved position to get ancestors for. + * @param pred - optional predicate to filter ancestors. + * @returns an array of ancestor nodes, where index corresponds to depth in the document. + */ +export const ancestors = ( + $from: ResolvedPos, + pred?: (ancestor: Node, index?: number, arr?: Node[]) => boolean +): Node[] => { + const ancestorArray: Node[] = []; + + // Notice that ancestors are arranged in increasing order of depth + // within the array, which implies that the index of an ancestor + // within the array actually represents its depth within the document. + for (let d = 0; d <= $from.depth; d++) { + ancestorArray.push($from.node(d)); + } + + if (pred) { + return filter(ancestorArray, (ancestor, index, ancestorArray) => + pred(ancestor, index, ancestorArray as Node[]) + ); + } + + return ancestorArray; +}; + +/** + * Returns the nearest ancestor from an array produced by the `ancestors` function. + * + * @param ancestors - an array of ancestor nodes ordered by increasing depth. + * @returns the nearest (deepest) ancestor node. + */ +export const nearest = (ancestors: Node[]): Node | undefined => ancestors.pop(); + +/** + * Calculates the height of a ProseMirror node tree. + * + * @param node - the node to calculate the height for. + * @returns the height of the node (0 for leaf nodes). + */ +export const height = (node: Node): number => { + if (node.isLeaf) { + return 0; + } + + let h = 0; + for (let i = 0; i < node.childCount; i++) { + const child = node.child(i); + h = Math.max(h, height(child)); + } + + return 1 + h; +}; + +/** + * Returns the previous sibling node at the specified depth. + * + * @param $from - the resolved position to search from. + * @param depth - optional depth level to look for siblings. + * @returns the previous sibling node, or null if none exists. + */ +export const prevSibling = ( + $from: ResolvedPos, + depth?: number +): Node | null => { + const ancestor = $from.node(depth); + const index = $from.index(depth); + if (index === 0) { + return null; + } + return ancestor.child(index - 1); +}; + +/** + * Lifts all children of the node at the given position up one level. + * + * @param pos - the position of the parent node whose children should be lifted. + * @param tr - the transaction to modify. + * @returns the modified transaction. + */ +export const liftChildrenOfNodeAt = ( + pos: number, + tr: Transaction +): Transaction => { + const node = tr.doc.nodeAt(pos); + const start = pos + 1; + const end = start + node!.content.size; + const $start = tr.doc.resolve(start); + const $end = tr.doc.resolve(end); + const range = $start.blockRange($end); + if (isNull(range)) { + return tr; + } + const target = liftTarget(range); + if (isNull(target)) { + return tr; + } + + return tr.lift(range, target); +}; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 25eef33fae..0677265b8e 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -623,6 +623,9 @@ "Outdent": "Outdent", "Video": "Video", "None": "None", + "Toggle block": "Toggle block", + "Add title": "Add title", + "Add content": "Add content", "Delete embed": "Delete embed", "Formatting controls": "Formatting controls", "Distribute columns": "Distribute columns", @@ -897,6 +900,10 @@ "Outdent list item": "Outdent list item", "Move list item up": "Move list item up", "Move list item down": "Move list item down", + "Toggle blocks": "Toggle blocks", + "Open / Close": "Open / Close", + "Indent item": "Indent item", + "Outdent item": "Outdent item", "Tables": "Tables", "Insert row": "Insert row", "Next cell": "Next cell", diff --git a/shared/styles/globals.ts b/shared/styles/globals.ts index 764cfcbff6..53506eb71b 100644 --- a/shared/styles/globals.ts +++ b/shared/styles/globals.ts @@ -15,6 +15,11 @@ export default createGlobalStyle` box-sizing: border-box; } + html { + --line-height-body: 1.5; + --font-size-body: 16px; + } + html, body { width: 100%; @@ -29,6 +34,9 @@ export default createGlobalStyle` @media print { background: none !important; } + + --line-height-p: var(--line-height-body); + --line-height-h: 1.25; } body, @@ -41,8 +49,8 @@ export default createGlobalStyle` } body { - font-size: 16px; - line-height: 1.5; + font-size: var(--font-size-body); + line-height: var(--line-height-body); color: ${s("text")}; overscroll-behavior-y: none; -moz-osx-font-smoothing: grayscale; @@ -88,7 +96,7 @@ export default createGlobalStyle` h5, h6 { font-weight: 500; - line-height: 1.25; + line-height: var(--line-height-h); margin-top: 1em; margin-bottom: 0.5em; } diff --git a/shared/utils/ProsemirrorHelper.ts b/shared/utils/ProsemirrorHelper.ts index d53e90c530..be44133600 100644 --- a/shared/utils/ProsemirrorHelper.ts +++ b/shared/utils/ProsemirrorHelper.ts @@ -414,7 +414,7 @@ export class ProsemirrorHelper { const headings: Heading[] = []; const previouslySeen: Record = {}; - doc.forEach((node) => { + doc.descendants((node) => { if (node.type.name === "heading") { // calculate the optimal id const id = headingToSlug(node);