mirror of
https://github.com/outline/outline.git
synced 2026-11-21 05:24:03 +03:00
* 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 <tom@getoutline.com>
548 lines
14 KiB
TypeScript
548 lines
14 KiB
TypeScript
import type { Schema } from "prosemirror-model";
|
|
import { Node } from "prosemirror-model";
|
|
import headingToSlug from "../editor/lib/headingToSlug";
|
|
import textBetween from "../editor/lib/textBetween";
|
|
import type { ProsemirrorData } from "../types";
|
|
import { TextHelper } from "./TextHelper";
|
|
import env from "../env";
|
|
import { findChildren } from "@shared/editor/queries/findChildren";
|
|
import { isLightboxNode } from "@shared/editor/lib/Lightbox";
|
|
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
|
|
|
export type Heading = {
|
|
/* The heading in plain text */
|
|
title: string;
|
|
/* The level of the heading */
|
|
level: number;
|
|
/* The unique id of the heading */
|
|
id: string;
|
|
};
|
|
|
|
export type CommentMark = {
|
|
/* The unique id of the comment */
|
|
id: string;
|
|
/* The id of the user who created the comment */
|
|
userId: string;
|
|
/* The text of the comment */
|
|
text: string;
|
|
};
|
|
|
|
export type NodeAnchor = { pos: number; id: string; className: string };
|
|
|
|
export type Task = {
|
|
/* The text of the task */
|
|
text: string;
|
|
/* Whether the task is completed or not */
|
|
completed: boolean;
|
|
};
|
|
|
|
interface User {
|
|
name: string;
|
|
language: string | null;
|
|
}
|
|
|
|
export const attachmentRedirectRegex =
|
|
/\/api\/attachments\.redirect\?id=(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi;
|
|
|
|
export const attachmentPublicRegex =
|
|
/public\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi;
|
|
|
|
export class ProsemirrorHelper {
|
|
/**
|
|
* Get a new empty document.
|
|
*
|
|
* @returns A new empty document as JSON.
|
|
*/
|
|
static getEmptyDocument(): ProsemirrorData {
|
|
return {
|
|
type: "doc",
|
|
content: [
|
|
{
|
|
content: [],
|
|
type: "paragraph",
|
|
},
|
|
],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Returns true if the data looks like an empty document.
|
|
*
|
|
* @param data The ProsemirrorData to check.
|
|
* @returns True if the document is empty.
|
|
*/
|
|
static isEmptyData(data: ProsemirrorData): boolean {
|
|
if (data.type !== "doc") {
|
|
return false;
|
|
}
|
|
|
|
if (data.content?.length === 1) {
|
|
const node = data.content[0];
|
|
return (
|
|
node.type === "paragraph" &&
|
|
(node.content === null ||
|
|
node.content === undefined ||
|
|
node.content.length === 0)
|
|
);
|
|
}
|
|
|
|
return !data.content || data.content.length === 0;
|
|
}
|
|
|
|
/**
|
|
* Returns the node as plain text.
|
|
*
|
|
* @param node The node to convert.
|
|
* @param schema The schema to use.
|
|
* @returns The document content as plain text without formatting.
|
|
*/
|
|
static toPlainText(root: Node) {
|
|
return textBetween(root, 0, root.content.size);
|
|
}
|
|
|
|
/**
|
|
* Removes any empty paragraphs from the beginning and end of the document.
|
|
*
|
|
* @returns True if the editor is empty
|
|
*/
|
|
static trim(doc: Node) {
|
|
let index = 0,
|
|
start = 0,
|
|
end = doc.nodeSize - 2,
|
|
isEmpty;
|
|
|
|
if (doc.childCount <= 1) {
|
|
return doc;
|
|
}
|
|
|
|
isEmpty = true;
|
|
while (isEmpty) {
|
|
const node = doc.maybeChild(index++);
|
|
if (!node) {
|
|
break;
|
|
}
|
|
isEmpty = ProsemirrorHelper.toPlainText(node).trim() === "";
|
|
if (isEmpty) {
|
|
start += node.nodeSize;
|
|
}
|
|
}
|
|
|
|
index = doc.childCount - 1;
|
|
isEmpty = true;
|
|
while (isEmpty) {
|
|
const node = doc.maybeChild(index--);
|
|
if (!node) {
|
|
break;
|
|
}
|
|
isEmpty = ProsemirrorHelper.toPlainText(node).trim() === "";
|
|
if (isEmpty) {
|
|
end -= node.nodeSize;
|
|
}
|
|
}
|
|
|
|
return doc.cut(start, end);
|
|
}
|
|
|
|
/**
|
|
* Returns true if the trimmed content of the passed document is an empty string.
|
|
*
|
|
* @returns True if the editor is empty
|
|
*/
|
|
static isEmpty(doc: Node, schema?: Schema) {
|
|
if (!schema) {
|
|
return !doc || doc.textContent.trim() === "";
|
|
}
|
|
|
|
let empty = true;
|
|
doc.descendants((child: Node) => {
|
|
// If we've already found non-empty data, we can stop descending further
|
|
if (!empty) {
|
|
return false;
|
|
}
|
|
|
|
if (child.type.spec.leafText) {
|
|
empty = !child.type.spec.leafText(child).trim();
|
|
} else if (child.isText) {
|
|
empty = !child.text?.trim();
|
|
}
|
|
|
|
return empty;
|
|
});
|
|
|
|
return empty;
|
|
}
|
|
|
|
/**
|
|
* Iterates through the document to find all of the comments that exist as marks.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Array<CommentMark>
|
|
*/
|
|
static getComments(doc: Node): CommentMark[] {
|
|
const comments: CommentMark[] = [];
|
|
|
|
doc.descendants((node) => {
|
|
node.marks.forEach((mark) => {
|
|
if (mark.type.name === "comment") {
|
|
comments.push({
|
|
...mark.attrs,
|
|
text: node.textContent,
|
|
} as CommentMark);
|
|
}
|
|
});
|
|
|
|
(node.attrs.marks ?? []).forEach((mark: any) => {
|
|
if (mark.type === "comment") {
|
|
comments.push({
|
|
...mark.attrs,
|
|
// For image nodes, we don't have any text content, so we set it to an empty string
|
|
text: "",
|
|
} as CommentMark);
|
|
}
|
|
});
|
|
|
|
return true;
|
|
});
|
|
|
|
return comments;
|
|
}
|
|
|
|
private static getAnchorsForHeadingNodes(doc: Node): NodeAnchor[] {
|
|
const previouslySeen: Record<string, number> = {};
|
|
const anchors: NodeAnchor[] = [];
|
|
doc.descendants((node, pos) => {
|
|
if (node.type.name !== "heading") {
|
|
return;
|
|
}
|
|
|
|
// calculate the optimal id
|
|
const slug = headingToSlug(node);
|
|
let id = slug;
|
|
|
|
// check if we've already used it, and if so how many times?
|
|
// Make the new id based on that number ensuring that we have
|
|
// unique ID's even when headings are identical
|
|
if (previouslySeen[slug] > 0) {
|
|
id = headingToSlug(node, previouslySeen[slug]);
|
|
}
|
|
|
|
// record that we've seen this slug for the next loop
|
|
previouslySeen[slug] =
|
|
previouslySeen[slug] !== undefined ? previouslySeen[slug] + 1 : 1;
|
|
|
|
anchors.push({
|
|
pos,
|
|
id,
|
|
className: EditorStyleHelper.headingPositionAnchor,
|
|
});
|
|
});
|
|
return anchors;
|
|
}
|
|
|
|
private static getAnchorsForImageNodes(doc: Node): NodeAnchor[] {
|
|
const anchors: NodeAnchor[] = [];
|
|
doc.descendants((node, pos) => {
|
|
if (Array.isArray(node.attrs?.marks)) {
|
|
node.attrs.marks.forEach((mark: any) => {
|
|
if (mark?.type === "comment" && mark?.attrs?.id) {
|
|
anchors.push({
|
|
pos,
|
|
id: `comment-${mark.attrs.id}`,
|
|
className: EditorStyleHelper.imagePositionAnchor,
|
|
});
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
return anchors;
|
|
}
|
|
|
|
static getAnchors(doc: Node): NodeAnchor[] {
|
|
return [
|
|
...ProsemirrorHelper.getAnchorsForHeadingNodes(doc),
|
|
...ProsemirrorHelper.getAnchorsForImageNodes(doc),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Builds the consolidated anchor text for the given comment-id.
|
|
*
|
|
* @param marks all available comment marks in a document.
|
|
* @param commentId the comment-id to build the anchor text.
|
|
* @returns consolidated anchor text.
|
|
*/
|
|
static getAnchorTextForComment(
|
|
marks: CommentMark[],
|
|
commentId: string
|
|
): string | undefined {
|
|
const anchorTexts = marks
|
|
.filter((mark) => mark.id === commentId)
|
|
.map((mark) => mark.text);
|
|
|
|
return anchorTexts.length ? anchorTexts.join("") : undefined;
|
|
}
|
|
|
|
/**
|
|
* Iterates through the document to find all of the images.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Array<Node> of images
|
|
*/
|
|
static getImages(doc: Node): Node[] {
|
|
const images: Node[] = [];
|
|
|
|
doc.descendants((node) => {
|
|
if (node.type.name === "image") {
|
|
images.push(node);
|
|
}
|
|
|
|
return true;
|
|
});
|
|
|
|
return images;
|
|
}
|
|
|
|
/**
|
|
* Iterates through the document to find all valid Lightbox nodes.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Array<NodeWithPos> of nodes allowed in Lightbox
|
|
*/
|
|
static getLightboxNodes = (doc: Node) =>
|
|
findChildren(doc, isLightboxNode, true);
|
|
|
|
/**
|
|
* Iterates through the document to find all of the videos.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Array<Node> of videos
|
|
*/
|
|
static getVideos(doc: Node): Node[] {
|
|
const videos: Node[] = [];
|
|
|
|
doc.descendants((node) => {
|
|
if (node.type.name === "video") {
|
|
videos.push(node);
|
|
}
|
|
|
|
return true;
|
|
});
|
|
|
|
return videos;
|
|
}
|
|
|
|
/**
|
|
* Iterates through the document to find all of the attachments.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Array<Node> of attachments
|
|
*/
|
|
static getAttachments(doc: Node): Node[] {
|
|
const attachments: Node[] = [];
|
|
|
|
doc.descendants((node) => {
|
|
if (node.type.name === "attachment") {
|
|
attachments.push(node);
|
|
}
|
|
|
|
return true;
|
|
});
|
|
|
|
return attachments;
|
|
}
|
|
|
|
/**
|
|
* Iterates through the document to find all of the tasks and their completion state.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Array<Task>
|
|
*/
|
|
static getTasks(doc: Node): Task[] {
|
|
const tasks: Task[] = [];
|
|
|
|
doc.descendants((node) => {
|
|
if (!node.isBlock) {
|
|
return false;
|
|
}
|
|
|
|
if (node.type.name === "checkbox_list") {
|
|
node.content.forEach((listItem) => {
|
|
let text = "";
|
|
|
|
listItem.forEach((contentNode) => {
|
|
if (contentNode.type.name === "paragraph") {
|
|
text += contentNode.textContent;
|
|
}
|
|
});
|
|
|
|
tasks.push({
|
|
text,
|
|
completed: listItem.attrs.checked,
|
|
});
|
|
});
|
|
}
|
|
|
|
return true;
|
|
});
|
|
|
|
return tasks;
|
|
}
|
|
|
|
/**
|
|
* Returns a summary of total and completed tasks in the node.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Object with completed and total keys
|
|
*/
|
|
static getTasksSummary(doc: Node): { completed: number; total: number } {
|
|
const tasks = ProsemirrorHelper.getTasks(doc);
|
|
|
|
return {
|
|
completed: tasks.filter((t) => t.completed).length,
|
|
total: tasks.length,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Iterates through the document to find all of the headings and their level.
|
|
*
|
|
* @param doc Prosemirror document node
|
|
* @returns Array<Heading>
|
|
*/
|
|
static getHeadings(doc: Node) {
|
|
const headings: Heading[] = [];
|
|
const previouslySeen: Record<string, number> = {};
|
|
|
|
doc.descendants((node) => {
|
|
if (node.type.name === "heading") {
|
|
// calculate the optimal id
|
|
const id = headingToSlug(node);
|
|
let name = id;
|
|
|
|
// check if we've already used it, and if so how many times?
|
|
// Make the new id based on that number ensuring that we have
|
|
// unique ID's even when headings are identical
|
|
if (previouslySeen[id] > 0) {
|
|
name = headingToSlug(node, previouslySeen[id]);
|
|
}
|
|
|
|
// record that we've seen this id for the next loop
|
|
previouslySeen[id] =
|
|
previouslySeen[id] !== undefined ? previouslySeen[id] + 1 : 1;
|
|
|
|
headings.push({
|
|
title: ProsemirrorHelper.toPlainText(node),
|
|
level: node.attrs.level,
|
|
id: name,
|
|
});
|
|
}
|
|
});
|
|
return headings;
|
|
}
|
|
|
|
/**
|
|
* Converts all attachment URLs in the ProsemirrorData to absolute URLs.
|
|
* This is useful for ensuring that attachments can be accessed correctly
|
|
* when the document is rendered in a different context or environment.
|
|
*
|
|
* @param data The ProsemirrorData object to process
|
|
* @returns The ProsemirrorData with absolute URLs for attachments
|
|
*/
|
|
static attachmentsToAbsoluteUrls(data: ProsemirrorData): ProsemirrorData {
|
|
function replace(node: ProsemirrorData) {
|
|
if (
|
|
node.type === "image" &&
|
|
node.attrs?.src &&
|
|
String(node.attrs.src).match(
|
|
new RegExp("^" + attachmentRedirectRegex.source)
|
|
)
|
|
) {
|
|
node.attrs.src = env.URL + node.attrs.src;
|
|
}
|
|
if (
|
|
node.type === "video" &&
|
|
node.attrs?.src &&
|
|
String(node.attrs.src).match(
|
|
new RegExp("^" + attachmentRedirectRegex.source)
|
|
)
|
|
) {
|
|
node.attrs.src = env.URL + node.attrs.src;
|
|
}
|
|
if (
|
|
node.type === "attachment" &&
|
|
node.attrs?.href &&
|
|
String(node.attrs.src).match(
|
|
new RegExp("^" + attachmentRedirectRegex.source)
|
|
)
|
|
) {
|
|
node.attrs.href = env.URL + node.attrs.href;
|
|
}
|
|
if (node.content) {
|
|
node.content.forEach(replace);
|
|
}
|
|
|
|
return node;
|
|
}
|
|
|
|
return replace(data);
|
|
}
|
|
|
|
/**
|
|
* Replaces all template variables in the node.
|
|
*
|
|
* @param data The ProsemirrorData object to replace variables in
|
|
* @param user The user to use for replacing variables
|
|
* @returns The content with variables replaced
|
|
*/
|
|
static replaceTemplateVariables(data: ProsemirrorData, user: User) {
|
|
function replace(node: ProsemirrorData) {
|
|
if (node.type === "text" && node.text) {
|
|
node.text = TextHelper.replaceTemplateVariables(node.text, user);
|
|
}
|
|
|
|
if (node.content) {
|
|
node.content.forEach(replace);
|
|
}
|
|
|
|
return node;
|
|
}
|
|
|
|
return replace(data);
|
|
}
|
|
|
|
/**
|
|
* Returns the paragraphs from the data if there are only plain paragraphs
|
|
* without any formatting. Otherwise returns undefined.
|
|
*
|
|
* @param data The ProsemirrorData object or ProsemirrorNode
|
|
* @returns An array of paragraph nodes or undefined
|
|
*/
|
|
static getPlainParagraphs(data: ProsemirrorData | Node) {
|
|
// Convert ProsemirrorNode to JSON if needed
|
|
const jsonData =
|
|
data instanceof Node ? (data.toJSON() as ProsemirrorData) : data;
|
|
|
|
const paragraphs: ProsemirrorData[] = [];
|
|
if (!jsonData.content) {
|
|
return paragraphs;
|
|
}
|
|
|
|
for (const node of jsonData.content) {
|
|
if (
|
|
node.type === "paragraph" &&
|
|
(!node.content ||
|
|
!node.content.some(
|
|
(item) =>
|
|
item.type !== "text" || (item.marks && item.marks.length > 0)
|
|
))
|
|
) {
|
|
paragraphs.push(node);
|
|
} else {
|
|
return undefined;
|
|
}
|
|
}
|
|
return paragraphs;
|
|
}
|
|
}
|