mirror of
https://github.com/outline/outline.git
synced 2026-12-06 03:05:08 +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>
967 lines
28 KiB
TypeScript
967 lines
28 KiB
TypeScript
/* global File Promise */
|
|
import type { PluginSimple } from "markdown-it";
|
|
import { observable } from "mobx";
|
|
import { Observer } from "mobx-react";
|
|
import { darken, transparentize } from "polished";
|
|
import { baseKeymap } from "prosemirror-commands";
|
|
import { dropCursor } from "prosemirror-dropcursor";
|
|
import { gapCursor } from "prosemirror-gapcursor";
|
|
import type { InputRule } from "prosemirror-inputrules";
|
|
import { inputRules } from "prosemirror-inputrules";
|
|
import { keymap } from "prosemirror-keymap";
|
|
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, TextSelection } from "prosemirror-state";
|
|
import type { MarkdownParser } from "prosemirror-markdown";
|
|
import {
|
|
AddMarkStep,
|
|
RemoveMarkStep,
|
|
ReplaceAroundStep,
|
|
ReplaceStep,
|
|
} from "prosemirror-transform";
|
|
import type { Decoration, NodeViewConstructor } from "prosemirror-view";
|
|
import { EditorView } from "prosemirror-view";
|
|
import * as React from "react";
|
|
import type { DefaultTheme, ThemeProps } from "styled-components";
|
|
import styled, { css } from "styled-components";
|
|
import insertFiles from "@shared/editor/commands/insertFiles";
|
|
import Styles from "@shared/editor/components/Styles";
|
|
import type { EmbedDescriptor } from "@shared/editor/embeds";
|
|
import type { CommandFactory, WidgetProps } from "@shared/editor/lib/Extension";
|
|
import type Extension from "@shared/editor/lib/Extension";
|
|
import ExtensionManager from "@shared/editor/lib/ExtensionManager";
|
|
import type { MarkdownSerializer } from "@shared/editor/lib/markdown/serializer";
|
|
import textBetween from "@shared/editor/lib/textBetween";
|
|
import type Mark from "@shared/editor/marks/Mark";
|
|
import { basicExtensions as extensions } from "@shared/editor/nodes";
|
|
import type Node from "@shared/editor/nodes/Node";
|
|
import type ReactNode from "@shared/editor/nodes/ReactNode";
|
|
import type { ComponentProps } from "@shared/editor/types";
|
|
import type { ProsemirrorData, UserPreferences } from "@shared/types";
|
|
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
|
import EventEmitter from "@shared/utils/events";
|
|
import type Document from "~/models/Document";
|
|
import Flex from "~/components/Flex";
|
|
import { PortalContext } from "~/components/Portal";
|
|
import type { Dictionary } from "~/hooks/useDictionary";
|
|
import type { Properties } from "~/types";
|
|
import Logger from "~/utils/Logger";
|
|
import ComponentView from "./components/ComponentView";
|
|
import EditorContext from "./components/EditorContext";
|
|
import type { NodeViewRenderer } from "./components/NodeViewRenderer";
|
|
|
|
import WithTheme from "./components/WithTheme";
|
|
import isNull from "lodash/isNull";
|
|
import { isArray, map } from "lodash";
|
|
import type { LightboxImage } from "@shared/editor/lib/Lightbox";
|
|
import { LightboxImageFactory } from "@shared/editor/lib/Lightbox";
|
|
import Lightbox from "~/components/Lightbox";
|
|
import { anchorPlugin } from "@shared/editor/plugins/AnchorPlugin";
|
|
|
|
export type Props = {
|
|
/** An optional identifier for the editor context. It is used to persist local settings */
|
|
id?: string;
|
|
/** The user id of the current user */
|
|
userId?: string;
|
|
/** The editor content, should only be changed if you wish to reset the content */
|
|
value?: string | ProsemirrorData | ProsemirrorNode;
|
|
/** The initial editor content as a markdown string, JSON object, or ProsemirrorNode */
|
|
defaultValue: string | ProsemirrorData | ProsemirrorNode;
|
|
/** Placeholder displayed when the editor is empty */
|
|
placeholder: string;
|
|
/** Extensions to load into the editor */
|
|
extensions?: (typeof Node | typeof Mark | typeof Extension | Extension)[];
|
|
/** If the editor should be focused on mount */
|
|
autoFocus?: boolean;
|
|
/** The focused comment, if any */
|
|
focusedCommentId?: string;
|
|
/** If the editor should not allow editing */
|
|
readOnly?: boolean;
|
|
/** If the editor should still allow editing checkboxes when it is readOnly */
|
|
canUpdate?: boolean;
|
|
/** If the editor should still allow commenting when it is readOnly */
|
|
canComment?: boolean;
|
|
/** A dictionary of translated strings used in the editor */
|
|
dictionary: Dictionary;
|
|
/** The reading direction of the text content, if known */
|
|
dir?: "rtl" | "ltr";
|
|
/** If the editor should vertically grow to fill available space */
|
|
grow?: boolean;
|
|
/** If the editor should display template options such as inserting placeholders */
|
|
template?: boolean;
|
|
/** An enforced maximum content length */
|
|
maxLength?: number;
|
|
/** Heading id to scroll to when the editor has loaded */
|
|
scrollTo?: string;
|
|
/** Callback for handling uploaded images, should return the url of uploaded file */
|
|
uploadFile?: (
|
|
file: File | string,
|
|
options?: { id?: string; onProgress?: (fractionComplete: number) => void }
|
|
) => Promise<string>;
|
|
/** Callback when prosemirror nodes are initialized on document mount. */
|
|
onInit?: () => void;
|
|
/** Callback when prosemirror nodes are destroyed on document unmount. */
|
|
onDestroy?: () => void;
|
|
/** Callback when editor is blurred, as native input */
|
|
onBlur?: () => void;
|
|
/** Callback when editor is focused, as native input */
|
|
onFocus?: () => void;
|
|
/** Callback when user uses save key combo */
|
|
onSave?: (options: { done: boolean }) => void;
|
|
/** Callback when user uses cancel key combo */
|
|
onCancel?: () => void;
|
|
/** Callback when user changes editor content */
|
|
onChange?: (value: () => any) => void;
|
|
/** Callback when a comment mark is clicked */
|
|
onClickCommentMark?: (commentId: string) => void;
|
|
/** Callback when a comment mark is created */
|
|
onCreateCommentMark?: (commentId: string, userId: string) => void;
|
|
/** Callback when a comment mark is removed */
|
|
onDeleteCommentMark?: (commentId: string) => void;
|
|
/** Callback when comments sidebar should be opened */
|
|
onOpenCommentsSidebar?: () => void;
|
|
/** Callback when a file upload begins */
|
|
onFileUploadStart?: () => void;
|
|
/** Callback when a file upload ends */
|
|
onFileUploadStop?: () => void;
|
|
/** Callback when file upload progress changes */
|
|
onFileUploadProgress?: (id: string, fractionComplete: number) => void;
|
|
/** Callback when a link is created, should return url to created document */
|
|
onCreateLink?: (params: Properties<Document>) => Promise<string>;
|
|
/** Callback when user clicks on any link in the document */
|
|
onClickLink: (
|
|
href: string,
|
|
event?: MouseEvent | React.MouseEvent<HTMLButtonElement>
|
|
) => void;
|
|
/** Callback when user presses any key with document focused */
|
|
onKeyDown?: (event: React.KeyboardEvent<HTMLDivElement>) => void;
|
|
/** Collection of embed types to render in the document */
|
|
embeds: EmbedDescriptor[];
|
|
/** Display preferences for the logged in user, if any. */
|
|
userPreferences?: UserPreferences | null;
|
|
/** Whether embeds should be rendered without an iframe */
|
|
embedsDisabled?: boolean;
|
|
className?: string;
|
|
/** Optional style overrides for the container*/
|
|
style?: React.CSSProperties;
|
|
/** Optional style overrides for the contenteeditable */
|
|
editorStyle?: React.CSSProperties;
|
|
lang?: string;
|
|
};
|
|
|
|
type State = {
|
|
/** If the document text has been detected as using RTL script */
|
|
isRTL: boolean;
|
|
/** If the editor is currently focused */
|
|
isEditorFocused: boolean;
|
|
/** Image that's being currently viewed in Lightbox */
|
|
activeLightboxImage: LightboxImage | null;
|
|
};
|
|
|
|
/**
|
|
* The shared editor at the root of all rich editable text in Outline. Do not
|
|
* use this component directly, it should by lazy loaded. Use
|
|
* ~/components/Editor instead.
|
|
*/
|
|
export class Editor extends React.PureComponent<
|
|
Props & ThemeProps<DefaultTheme>,
|
|
State
|
|
> {
|
|
static defaultProps = {
|
|
defaultValue: "",
|
|
dir: "auto",
|
|
placeholder: "Write something nice…",
|
|
readOnly: false,
|
|
onFileUploadStart: () => {
|
|
// no default behavior
|
|
},
|
|
onFileUploadStop: () => {
|
|
// no default behavior
|
|
},
|
|
embeds: [],
|
|
extensions,
|
|
};
|
|
|
|
state: State = {
|
|
isRTL: false,
|
|
isEditorFocused: false,
|
|
activeLightboxImage: null,
|
|
};
|
|
|
|
isInitialized = false;
|
|
isBlurred = true;
|
|
extensions: ExtensionManager;
|
|
elementRef = React.createRef<HTMLDivElement>();
|
|
wrapperRef = React.createRef<HTMLDivElement>();
|
|
view: EditorView;
|
|
schema: Schema;
|
|
serializer: MarkdownSerializer;
|
|
parser: MarkdownParser;
|
|
pasteParser: MarkdownParser;
|
|
plugins: Plugin[];
|
|
keymaps: Plugin[];
|
|
inputRules: InputRule[];
|
|
nodeViews: {
|
|
[name: string]: NodeViewConstructor;
|
|
};
|
|
|
|
widgets: { [name: string]: (props: WidgetProps) => React.ReactElement };
|
|
renderers = observable.set<NodeViewRenderer<ComponentProps>>();
|
|
nodes: { [name: string]: NodeSpec };
|
|
marks: { [name: string]: MarkSpec };
|
|
commands: Record<string, CommandFactory>;
|
|
rulePlugins: PluginSimple[];
|
|
events = new EventEmitter();
|
|
mutationObserver?: MutationObserver;
|
|
|
|
/**
|
|
* We use componentDidMount instead of constructor as the init method requires
|
|
* that the dom is already mounted.
|
|
*/
|
|
public componentDidMount() {
|
|
this.init();
|
|
window.addEventListener("theme-changed", this.dispatchThemeChanged);
|
|
|
|
if (this.props.scrollTo) {
|
|
void this.scrollToAnchor(this.props.scrollTo);
|
|
}
|
|
|
|
this.calculateDir();
|
|
|
|
if (this.props.readOnly) {
|
|
return;
|
|
}
|
|
|
|
if (this.props.autoFocus) {
|
|
this.focusAtEnd();
|
|
}
|
|
}
|
|
|
|
public componentDidUpdate(prevProps: Props) {
|
|
// Allow changes to the 'value' prop to update the editor from outside
|
|
if (this.props.value && prevProps.value !== this.props.value) {
|
|
const newState = this.createState(this.props.value);
|
|
this.view.updateState(newState);
|
|
}
|
|
|
|
// pass readOnly changes through to underlying editor instance
|
|
if (prevProps.readOnly !== this.props.readOnly) {
|
|
this.view.update({
|
|
...this.view.props,
|
|
editable: () => !this.props.readOnly,
|
|
});
|
|
|
|
// NodeView will not automatically render when editable changes so we must trigger an update
|
|
// manually, see: https://discuss.prosemirror.net/t/re-render-custom-nodeview-when-view-editable-changes/6441
|
|
Array.from(this.renderers).forEach((view) =>
|
|
view.setProp("isEditable", !this.props.readOnly)
|
|
);
|
|
}
|
|
|
|
if (this.props.scrollTo && this.props.scrollTo !== prevProps.scrollTo) {
|
|
void this.scrollToAnchor(this.props.scrollTo);
|
|
}
|
|
|
|
// Focus at the end of the document if switching from readOnly and autoFocus
|
|
// is set to true
|
|
if (prevProps.readOnly && !this.props.readOnly && this.props.autoFocus) {
|
|
this.focusAtEnd();
|
|
}
|
|
|
|
if (prevProps.dir !== this.props.dir) {
|
|
this.calculateDir();
|
|
}
|
|
|
|
if (!this.isBlurred && !this.state.isEditorFocused) {
|
|
this.isBlurred = true;
|
|
this.props.onBlur?.();
|
|
}
|
|
|
|
if (this.isBlurred && this.state.isEditorFocused) {
|
|
this.isBlurred = false;
|
|
this.props.onFocus?.();
|
|
}
|
|
}
|
|
|
|
public componentWillUnmount(): void {
|
|
window.removeEventListener("theme-changed", this.dispatchThemeChanged);
|
|
this.view?.destroy();
|
|
this.mutationObserver?.disconnect();
|
|
this.handleEditorDestroy();
|
|
}
|
|
|
|
private init() {
|
|
this.extensions = this.createExtensions();
|
|
this.nodes = this.createNodes();
|
|
this.marks = this.createMarks();
|
|
this.schema = this.createSchema();
|
|
this.widgets = this.createWidgets();
|
|
this.plugins = this.createPlugins();
|
|
this.rulePlugins = this.createRulePlugins();
|
|
this.keymaps = this.createKeymaps();
|
|
this.serializer = this.createSerializer();
|
|
this.parser = this.createParser();
|
|
this.pasteParser = this.createPasteParser();
|
|
this.inputRules = this.createInputRules();
|
|
this.nodeViews = this.createNodeViews();
|
|
this.view = this.createView();
|
|
this.commands = this.createCommands();
|
|
}
|
|
|
|
private createExtensions() {
|
|
return new ExtensionManager(this.props.extensions, this);
|
|
}
|
|
|
|
private createPlugins() {
|
|
return this.extensions.plugins;
|
|
}
|
|
|
|
private createRulePlugins() {
|
|
return this.extensions.rulePlugins;
|
|
}
|
|
|
|
private createKeymaps() {
|
|
return this.extensions.keymaps({
|
|
schema: this.schema,
|
|
});
|
|
}
|
|
|
|
private createInputRules() {
|
|
return this.extensions.inputRules({
|
|
schema: this.schema,
|
|
});
|
|
}
|
|
|
|
private createNodeViews() {
|
|
return this.extensions.extensions
|
|
.filter((extension: ReactNode) => extension.component)
|
|
.reduce(
|
|
(nodeViews, extension: ReactNode) => ({
|
|
...nodeViews,
|
|
[extension.name]: (
|
|
node: ProsemirrorNode,
|
|
view: EditorView,
|
|
getPos: () => number,
|
|
decorations: Decoration[]
|
|
) =>
|
|
new ComponentView(extension.component, {
|
|
editor: this,
|
|
extension,
|
|
node,
|
|
view,
|
|
getPos,
|
|
decorations,
|
|
}),
|
|
}),
|
|
{}
|
|
);
|
|
}
|
|
|
|
private createCommands() {
|
|
return this.extensions.commands({
|
|
schema: this.schema,
|
|
view: this.view,
|
|
});
|
|
}
|
|
|
|
private createWidgets() {
|
|
return this.extensions.widgets;
|
|
}
|
|
|
|
private createNodes() {
|
|
return this.extensions.nodes;
|
|
}
|
|
|
|
private createMarks() {
|
|
return this.extensions.marks;
|
|
}
|
|
|
|
private createSchema() {
|
|
return new Schema({
|
|
nodes: this.nodes,
|
|
marks: this.marks,
|
|
});
|
|
}
|
|
|
|
private createSerializer() {
|
|
return this.extensions.serializer();
|
|
}
|
|
|
|
private createParser() {
|
|
return this.extensions.parser({
|
|
schema: this.schema,
|
|
plugins: this.rulePlugins,
|
|
});
|
|
}
|
|
|
|
private createPasteParser() {
|
|
return this.extensions.parser({
|
|
schema: this.schema,
|
|
rules: { linkify: true },
|
|
plugins: this.rulePlugins,
|
|
});
|
|
}
|
|
|
|
private createState(value?: string | ProsemirrorData | ProsemirrorNode) {
|
|
const doc = this.createDocument(value || this.props.defaultValue);
|
|
|
|
return EditorState.create({
|
|
schema: this.schema,
|
|
doc,
|
|
plugins: [
|
|
...this.keymaps,
|
|
...this.plugins,
|
|
anchorPlugin(),
|
|
dropCursor({
|
|
color: this.props.theme.cursor,
|
|
}),
|
|
gapCursor(),
|
|
inputRules({
|
|
rules: this.inputRules,
|
|
}),
|
|
keymap(baseKeymap),
|
|
],
|
|
});
|
|
}
|
|
|
|
private createDocument(content: string | object | ProsemirrorNode) {
|
|
// Already a ProsemirrorNode
|
|
if (content instanceof ProsemirrorNode) {
|
|
return content;
|
|
}
|
|
|
|
// Looks like Markdown
|
|
if (typeof content === "string") {
|
|
return this.parser.parse(content) || undefined;
|
|
}
|
|
|
|
return ProsemirrorNode.fromJSON(this.schema, content);
|
|
}
|
|
|
|
private createView() {
|
|
if (!this.elementRef.current) {
|
|
throw new Error("createView called before ref available");
|
|
}
|
|
|
|
const isEditingCheckbox = (tr: Transaction) =>
|
|
tr.steps.some(
|
|
(step) =>
|
|
(step instanceof ReplaceAroundStep || step instanceof ReplaceStep) &&
|
|
step.slice.content?.firstChild?.type.name ===
|
|
this.schema.nodes.checkbox_item.name
|
|
);
|
|
|
|
const isEditingComment = (tr: Transaction) =>
|
|
tr.steps.some(
|
|
(step) =>
|
|
(step instanceof AddMarkStep || step instanceof RemoveMarkStep) &&
|
|
step.mark.type.name === this.schema.marks.comment.name
|
|
);
|
|
|
|
const self = this; // oxlint-disable-line
|
|
const view = new EditorView(this.elementRef.current, {
|
|
handleDOMEvents: {
|
|
blur: this.handleEditorBlur,
|
|
focus: this.handleEditorFocus,
|
|
},
|
|
attributes: {
|
|
translate: this.props.readOnly ? "yes" : "no",
|
|
},
|
|
state: this.createState(this.props.value),
|
|
editable: () => !this.props.readOnly,
|
|
nodeViews: this.nodeViews,
|
|
dispatchTransaction(this: EditorView, transaction) {
|
|
if (this.isDestroyed) {
|
|
return;
|
|
}
|
|
|
|
// callback is bound to have the view instance as its this binding
|
|
const { state, transactions } =
|
|
this.state.applyTransaction(transaction);
|
|
|
|
this.updateState(state);
|
|
|
|
// If any of the transactions being dispatched resulted in the doc
|
|
// changing then call our own change handler to let the outside world
|
|
// know
|
|
if (
|
|
transactions.some((tr) => tr.docChanged) &&
|
|
(!self.props.readOnly ||
|
|
(self.props.canUpdate && transactions.some(isEditingCheckbox)) ||
|
|
(self.props.canComment && transactions.some(isEditingComment)))
|
|
) {
|
|
self.handleChange();
|
|
}
|
|
|
|
self.handleEditorInit();
|
|
|
|
self.calculateDir();
|
|
|
|
// Because Prosemirror and React are not linked we must tell React that
|
|
// a render is needed whenever the Prosemirror state changes.
|
|
self.forceUpdate();
|
|
},
|
|
});
|
|
|
|
// Tell third-party libraries and screen-readers that this is an input
|
|
view.dom.setAttribute("role", "textbox");
|
|
view.dom.setAttribute("aria-label", "Editor content");
|
|
|
|
return view;
|
|
}
|
|
|
|
public async scrollToAnchor(hash: string) {
|
|
if (!hash) {
|
|
return;
|
|
}
|
|
|
|
function isVisible(element: HTMLElement | null) {
|
|
for (let e = element; e; e = e.parentElement) {
|
|
const s = getComputedStyle(e);
|
|
if (s.display === "none" || s.opacity === "0") {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
try {
|
|
this.mutationObserver?.disconnect();
|
|
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();
|
|
}
|
|
},
|
|
this.elementRef.current || undefined
|
|
);
|
|
} catch (_err) {
|
|
// querySelector will throw an error if the hash begins with a number
|
|
// or contains a period. This is protected against now by safeSlugify
|
|
// however previous links may be in the wild.
|
|
Logger.debug("editor", `Attempted to scroll to invalid hash: ${hash}`);
|
|
}
|
|
}
|
|
|
|
public value = (asString = true, trim?: boolean) => {
|
|
if (asString) {
|
|
const content = this.serializer.serialize(this.view.state.doc);
|
|
return trim ? content.trim() : content;
|
|
}
|
|
|
|
return (
|
|
trim ? ProsemirrorHelper.trim(this.view.state.doc) : this.view.state.doc
|
|
).toJSON();
|
|
};
|
|
|
|
private calculateDir = () => {
|
|
if (!this.elementRef.current) {
|
|
return;
|
|
}
|
|
|
|
const isRTL =
|
|
this.props.dir === "rtl" ||
|
|
getComputedStyle(this.elementRef.current).direction === "rtl";
|
|
|
|
if (this.state.isRTL !== isRTL) {
|
|
this.setState({ isRTL });
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Focus the editor at the start of the content.
|
|
*/
|
|
public focusAtStart = () => {
|
|
const selection = Selection.atStart(this.view.state.doc);
|
|
const transaction = this.view.state.tr.setSelection(selection);
|
|
this.view.dispatch(transaction);
|
|
this.view.focus();
|
|
};
|
|
|
|
/**
|
|
* Focus the editor at the end of the content.
|
|
*/
|
|
public focusAtEnd = () => {
|
|
const selection = Selection.atEnd(this.view.state.doc);
|
|
const transaction = this.view.state.tr.setSelection(selection);
|
|
this.view.dispatch(transaction);
|
|
this.view.focus();
|
|
};
|
|
|
|
/**
|
|
* Focus the editor and scroll to the current selection.
|
|
*/
|
|
public focus = () => {
|
|
this.view.focus();
|
|
this.view.dispatch(this.view.state.tr.scrollIntoView());
|
|
};
|
|
|
|
/**
|
|
* Blur the editor.
|
|
*/
|
|
public blur = () => {
|
|
(this.view.dom as HTMLElement).blur();
|
|
|
|
// Have Safari remove the caret.
|
|
window?.getSelection()?.removeAllRanges();
|
|
};
|
|
|
|
/**
|
|
* Insert files at the current selection.
|
|
* =
|
|
* @param event The source event
|
|
* @param files The files to insert
|
|
* @returns True if the files were inserted
|
|
*/
|
|
public insertFiles = (
|
|
event: React.ChangeEvent<HTMLInputElement>,
|
|
files: File[]
|
|
) =>
|
|
insertFiles(
|
|
this.view,
|
|
event,
|
|
this.view.state.selection.to,
|
|
files,
|
|
this.props
|
|
);
|
|
|
|
/**
|
|
* Returns true if the trimmed content of the editor is an empty string.
|
|
*
|
|
* @returns True if the editor is empty
|
|
*/
|
|
public isEmpty = () => ProsemirrorHelper.isEmpty(this.view.state.doc);
|
|
|
|
/**
|
|
* Return the headings in the current editor.
|
|
*
|
|
* @returns A list of headings in the document
|
|
*/
|
|
public getHeadings = () => ProsemirrorHelper.getHeadings(this.view.state.doc);
|
|
|
|
/**
|
|
* Return the images in the current editor.
|
|
*
|
|
* @returns A list of images in the document
|
|
*/
|
|
public getImages = () => ProsemirrorHelper.getImages(this.view.state.doc);
|
|
|
|
public getLightboxImages = (): LightboxImage[] => {
|
|
const lightboxNodes = ProsemirrorHelper.getLightboxNodes(
|
|
this.view.state.doc
|
|
);
|
|
|
|
return map(lightboxNodes, (node) =>
|
|
LightboxImageFactory.createLightboxImage(this.view, node.pos)
|
|
);
|
|
};
|
|
|
|
/**
|
|
* Return the tasks/checkmarks in the current editor.
|
|
*
|
|
* @returns A list of tasks in the document
|
|
*/
|
|
public getTasks = () => ProsemirrorHelper.getTasks(this.view.state.doc);
|
|
|
|
/**
|
|
* Return the comments in the current editor.
|
|
*
|
|
* @returns A list of comments in the document
|
|
*/
|
|
public getComments = () => ProsemirrorHelper.getComments(this.view.state.doc);
|
|
|
|
/**
|
|
* Remove all marks related to a specific comment from the document.
|
|
*
|
|
* @param commentId The id of the comment to remove
|
|
*/
|
|
public removeComment = (commentId: string) => {
|
|
const { state, dispatch } = this.view;
|
|
const tr = state.tr;
|
|
let markRemoved = false;
|
|
|
|
state.doc.descendants((node, pos) => {
|
|
if (markRemoved) {
|
|
return false;
|
|
}
|
|
const mark = node.marks.find(
|
|
(m) => m.type === state.schema.marks.comment && m.attrs.id === commentId
|
|
);
|
|
|
|
if (mark) {
|
|
tr.removeMark(pos, pos + node.nodeSize, mark);
|
|
markRemoved = true;
|
|
return;
|
|
}
|
|
|
|
if (isArray(node.attrs?.marks)) {
|
|
const existingMarks = node.attrs.marks;
|
|
const updatedMarks = existingMarks.filter(
|
|
(mark: any) => mark.attrs.id !== commentId
|
|
);
|
|
const attrs = {
|
|
...node.attrs,
|
|
marks: updatedMarks,
|
|
};
|
|
tr.setNodeMarkup(pos, undefined, attrs);
|
|
markRemoved = true;
|
|
}
|
|
|
|
return;
|
|
});
|
|
|
|
dispatch(tr);
|
|
};
|
|
|
|
/**
|
|
* Update all marks related to a specific comment in the document.
|
|
*
|
|
* @param commentId The id of the comment to update
|
|
* @param attrs The attributes to update
|
|
*/
|
|
public updateComment = (
|
|
commentId: string,
|
|
attrs: { resolved?: boolean; draft?: boolean }
|
|
) => {
|
|
const { state, dispatch } = this.view;
|
|
const tr = state.tr;
|
|
let markUpdated = false;
|
|
|
|
state.doc.descendants((node, pos) => {
|
|
if (markUpdated) {
|
|
return false;
|
|
}
|
|
|
|
const mark = node.marks.find(
|
|
(m) => m.type === state.schema.marks.comment && m.attrs.id === commentId
|
|
);
|
|
|
|
if (mark) {
|
|
const from = pos;
|
|
const to = pos + node.nodeSize;
|
|
const newMark = state.schema.marks.comment.create({
|
|
...mark.attrs,
|
|
...attrs,
|
|
});
|
|
tr.removeMark(from, to, mark).addMark(from, to, newMark);
|
|
markUpdated = true;
|
|
return;
|
|
}
|
|
|
|
if (isArray(node.attrs?.marks)) {
|
|
const existingMarks = node.attrs.marks;
|
|
const updatedMarks = existingMarks.map((mark: any) =>
|
|
mark.type === "comment" && mark.attrs.id === commentId
|
|
? { ...mark, attrs: { ...mark.attrs, ...attrs } }
|
|
: mark
|
|
);
|
|
const newAttrs = {
|
|
...node.attrs,
|
|
marks: updatedMarks,
|
|
};
|
|
tr.setNodeMarkup(pos, undefined, newAttrs);
|
|
markUpdated = true;
|
|
}
|
|
|
|
return;
|
|
});
|
|
|
|
dispatch(tr);
|
|
};
|
|
|
|
public updateActiveLightboxImage = (activeImage: LightboxImage | null) => {
|
|
this.setState((state) => ({
|
|
...state,
|
|
activeLightboxImage: activeImage,
|
|
}));
|
|
};
|
|
|
|
/**
|
|
* Return the plain text content of the current editor.
|
|
*
|
|
* @returns A string of text
|
|
*/
|
|
public getPlainText = () => {
|
|
const { doc } = this.view.state;
|
|
|
|
return textBetween(doc, 0, doc.content.size);
|
|
};
|
|
|
|
private dispatchThemeChanged = (event: CustomEvent) => {
|
|
this.view.dispatch(this.view.state.tr.setMeta("theme", event.detail));
|
|
};
|
|
|
|
private handleChange = () => {
|
|
if (!this.props.onChange) {
|
|
return;
|
|
}
|
|
|
|
this.props.onChange((asString = true, trim = false) =>
|
|
this.view ? this.value(asString, trim) : undefined
|
|
);
|
|
};
|
|
|
|
private handleEditorInit = () => {
|
|
if (!this.props.onInit || this.isInitialized) {
|
|
return;
|
|
}
|
|
|
|
this.props.onInit();
|
|
this.isInitialized = true;
|
|
};
|
|
|
|
private handleEditorDestroy = () => {
|
|
if (!this.props.onDestroy) {
|
|
return;
|
|
}
|
|
this.props.onDestroy();
|
|
};
|
|
|
|
private handleEditorBlur = () => {
|
|
this.setState({ isEditorFocused: false });
|
|
return false;
|
|
};
|
|
|
|
private handleEditorFocus = () => {
|
|
this.setState({ isEditorFocused: true });
|
|
return false;
|
|
};
|
|
|
|
public render() {
|
|
const { readOnly, canUpdate, grow, style, className, onKeyDown } =
|
|
this.props;
|
|
const { isRTL } = this.state;
|
|
|
|
return (
|
|
<PortalContext.Provider value={this.wrapperRef.current}>
|
|
<EditorContext.Provider value={this}>
|
|
<Flex
|
|
ref={this.wrapperRef}
|
|
onKeyDown={onKeyDown}
|
|
style={style}
|
|
className={className}
|
|
align="flex-start"
|
|
justify="center"
|
|
column
|
|
>
|
|
<EditorContainer
|
|
rtl={isRTL}
|
|
grow={grow}
|
|
readOnly={readOnly}
|
|
readOnlyWriteCheckboxes={canUpdate}
|
|
focusedCommentId={this.props.focusedCommentId}
|
|
userId={this.props.userId}
|
|
editorStyle={this.props.editorStyle}
|
|
commenting={!!this.props.onClickCommentMark}
|
|
ref={this.elementRef}
|
|
lang={this.props.lang ?? ""}
|
|
/>
|
|
|
|
{this.widgets &&
|
|
Object.values(this.widgets).map((Widget, index) => (
|
|
<Widget
|
|
key={String(index)}
|
|
rtl={isRTL}
|
|
readOnly={readOnly}
|
|
selection={this.view.state.selection}
|
|
/>
|
|
))}
|
|
<Observer>
|
|
{() => (
|
|
<>{Array.from(this.renderers).map((view) => view.content)}</>
|
|
)}
|
|
</Observer>
|
|
</Flex>
|
|
{!isNull(this.state.activeLightboxImage) && (
|
|
<Lightbox
|
|
readOnly={readOnly}
|
|
images={this.getLightboxImages()}
|
|
activeImage={this.state.activeLightboxImage}
|
|
onUpdate={this.updateActiveLightboxImage}
|
|
onClose={this.view.focus}
|
|
/>
|
|
)}
|
|
</EditorContext.Provider>
|
|
</PortalContext.Provider>
|
|
);
|
|
}
|
|
}
|
|
|
|
const EditorContainer = styled(Styles)<{
|
|
userId?: string;
|
|
focusedCommentId?: string;
|
|
}>`
|
|
${(props) =>
|
|
props.focusedCommentId &&
|
|
css`
|
|
span#comment-${props.focusedCommentId} {
|
|
background: ${transparentize(0.5, props.theme.brand.marine)};
|
|
border-bottom: 2px solid ${props.theme.commentMarkBackground};
|
|
}
|
|
a#comment-${props.focusedCommentId}
|
|
~ span.component-image
|
|
div.image-wrapper {
|
|
outline: ${props.theme.commentMarkBackground} solid 2px;
|
|
}
|
|
`}
|
|
|
|
${(props) =>
|
|
props.userId &&
|
|
css`
|
|
.mention[data-id="${props.userId}"] {
|
|
color: ${props.theme.textHighlightForeground};
|
|
background: ${props.theme.textHighlight};
|
|
|
|
&.ProseMirror-selectednode {
|
|
outline-color: ${props.readOnly
|
|
? "transparent"
|
|
: darken(0.2, props.theme.textHighlight)};
|
|
}
|
|
}
|
|
`}
|
|
`;
|
|
|
|
const LazyLoadedEditor = React.forwardRef<Editor, Props>(
|
|
function LazyLoadedEditor_(props: Props, ref) {
|
|
return (
|
|
<WithTheme>
|
|
{(theme) => <Editor theme={theme} {...props} ref={ref} />}
|
|
</WithTheme>
|
|
);
|
|
}
|
|
);
|
|
|
|
const observe = (
|
|
selector: string,
|
|
callback: (element: HTMLElement) => void,
|
|
targetNode = document.body
|
|
) => {
|
|
const observer = new MutationObserver((mutations) => {
|
|
const match = [...mutations]
|
|
.flatMap((mutation) => [...mutation.addedNodes])
|
|
.find((node: HTMLElement) => node.matches?.(selector));
|
|
if (match) {
|
|
callback(match as HTMLElement);
|
|
}
|
|
});
|
|
|
|
if (targetNode.querySelector(selector)) {
|
|
callback(targetNode.querySelector(selector) as HTMLElement);
|
|
} else {
|
|
observer.observe(targetNode, { childList: true, subtree: true });
|
|
}
|
|
|
|
return observer;
|
|
};
|
|
|
|
export default LazyLoadedEditor;
|