chore: Move editor into codebase (#2930)
This commit is contained in:
193
shared/editor/plugins/BlockMenuTrigger.tsx
Normal file
193
shared/editor/plugins/BlockMenuTrigger.tsx
Normal file
@@ -0,0 +1,193 @@
|
||||
import { PlusIcon } from "outline-icons";
|
||||
import { InputRule } from "prosemirror-inputrules";
|
||||
import { EditorState, Plugin } from "prosemirror-state";
|
||||
import { isInTable } from "prosemirror-tables";
|
||||
import { findParentNode } from "prosemirror-utils";
|
||||
import { Decoration, DecorationSet, EditorView } from "prosemirror-view";
|
||||
import * as React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import Extension from "../lib/Extension";
|
||||
|
||||
const MAX_MATCH = 500;
|
||||
const OPEN_REGEX = /^\/(\w+)?$/;
|
||||
const CLOSE_REGEX = /(^(?!\/(\w+)?)(.*)$|^\/(([\w\W]+)\s.*|\s)$|^\/((\W)+)$)/;
|
||||
|
||||
// based on the input rules code in Prosemirror, here:
|
||||
// https://github.com/ProseMirror/prosemirror-inputrules/blob/master/src/inputrules.js
|
||||
export function run(
|
||||
view: EditorView,
|
||||
from: number,
|
||||
to: number,
|
||||
regex: RegExp,
|
||||
handler: (
|
||||
state: EditorState,
|
||||
match: RegExpExecArray | null,
|
||||
from?: number,
|
||||
to?: number
|
||||
) => boolean | null
|
||||
) {
|
||||
if (view.composing) {
|
||||
return false;
|
||||
}
|
||||
const state = view.state;
|
||||
const $from = state.doc.resolve(from);
|
||||
if ($from.parent.type.spec.code) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const textBefore = $from.parent.textBetween(
|
||||
Math.max(0, $from.parentOffset - MAX_MATCH),
|
||||
$from.parentOffset,
|
||||
undefined,
|
||||
"\ufffc"
|
||||
);
|
||||
|
||||
const match = regex.exec(textBefore);
|
||||
const tr = handler(state, match, match ? from - match[0].length : from, to);
|
||||
if (!tr) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export default class BlockMenuTrigger extends Extension {
|
||||
get name() {
|
||||
return "blockmenu";
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
const button = document.createElement("button");
|
||||
button.className = "block-menu-trigger";
|
||||
button.type = "button";
|
||||
ReactDOM.render(<PlusIcon color="currentColor" />, button);
|
||||
|
||||
return [
|
||||
new Plugin({
|
||||
props: {
|
||||
handleClick: () => {
|
||||
this.options.onClose();
|
||||
return false;
|
||||
},
|
||||
handleKeyDown: (view, event) => {
|
||||
// Prosemirror input rules are not triggered on backspace, however
|
||||
// we need them to be evaluted for the filter trigger to work
|
||||
// correctly. This additional handler adds inputrules-like handling.
|
||||
if (event.key === "Backspace") {
|
||||
// timeout ensures that the delete has been handled by prosemirror
|
||||
// and any characters removed, before we evaluate the rule.
|
||||
setTimeout(() => {
|
||||
const { pos } = view.state.selection.$from;
|
||||
return run(view, pos, pos, OPEN_REGEX, (state, match) => {
|
||||
if (match) {
|
||||
this.options.onOpen(match[1]);
|
||||
} else {
|
||||
this.options.onClose();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// If the query is active and we're navigating the block menu then
|
||||
// just ignore the key events in the editor itself until we're done
|
||||
if (
|
||||
event.key === "Enter" ||
|
||||
event.key === "ArrowUp" ||
|
||||
event.key === "ArrowDown" ||
|
||||
event.key === "Tab"
|
||||
) {
|
||||
const { pos } = view.state.selection.$from;
|
||||
|
||||
return run(view, pos, pos, OPEN_REGEX, (state, match) => {
|
||||
// just tell Prosemirror we handled it and not to do anything
|
||||
return match ? true : null;
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
decorations: (state) => {
|
||||
const parent = findParentNode(
|
||||
(node) => node.type.name === "paragraph"
|
||||
)(state.selection);
|
||||
|
||||
if (!parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const decorations: Decoration[] = [];
|
||||
const isEmpty = parent && parent.node.content.size === 0;
|
||||
const isSlash = parent && parent.node.textContent === "/";
|
||||
const isTopLevel = state.selection.$from.depth === 1;
|
||||
|
||||
if (isTopLevel) {
|
||||
if (isEmpty) {
|
||||
decorations.push(
|
||||
Decoration.widget(parent.pos, () => {
|
||||
button.addEventListener("click", () => {
|
||||
this.options.onOpen("");
|
||||
});
|
||||
return button;
|
||||
})
|
||||
);
|
||||
|
||||
decorations.push(
|
||||
Decoration.node(
|
||||
parent.pos,
|
||||
parent.pos + parent.node.nodeSize,
|
||||
{
|
||||
class: "placeholder",
|
||||
"data-empty-text": this.options.dictionary.newLineEmpty,
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (isSlash) {
|
||||
decorations.push(
|
||||
Decoration.node(
|
||||
parent.pos,
|
||||
parent.pos + parent.node.nodeSize,
|
||||
{
|
||||
class: "placeholder",
|
||||
"data-empty-text": ` ${this.options.dictionary.newLineWithSlash}`,
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return DecorationSet.create(state.doc, decorations);
|
||||
}
|
||||
|
||||
return;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
inputRules() {
|
||||
return [
|
||||
// main regex should match only:
|
||||
// /word
|
||||
new InputRule(OPEN_REGEX, (state, match) => {
|
||||
if (
|
||||
match &&
|
||||
state.selection.$from.parent.type.name === "paragraph" &&
|
||||
!isInTable(state)
|
||||
) {
|
||||
this.options.onOpen(match[1]);
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
// invert regex should match some of these scenarios:
|
||||
// /<space>word
|
||||
// /<space>
|
||||
// /word<space>
|
||||
new InputRule(CLOSE_REGEX, (state, match) => {
|
||||
if (match) {
|
||||
this.options.onClose();
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
93
shared/editor/plugins/EmojiTrigger.tsx
Normal file
93
shared/editor/plugins/EmojiTrigger.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import { InputRule } from "prosemirror-inputrules";
|
||||
import { Plugin } from "prosemirror-state";
|
||||
import Extension from "../lib/Extension";
|
||||
import isInCode from "../queries/isInCode";
|
||||
import { run } from "./BlockMenuTrigger";
|
||||
|
||||
const OPEN_REGEX = /(?:^|\s):([0-9a-zA-Z_+-]+)?$/;
|
||||
const CLOSE_REGEX = /(?:^|\s):(([0-9a-zA-Z_+-]*\s+)|(\s+[0-9a-zA-Z_+-]+)|[^0-9a-zA-Z_+-]+)$/;
|
||||
|
||||
export default class EmojiTrigger extends Extension {
|
||||
get name() {
|
||||
return "emojimenu";
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
props: {
|
||||
handleClick: () => {
|
||||
this.options.onClose();
|
||||
return false;
|
||||
},
|
||||
handleKeyDown: (view, event) => {
|
||||
// Prosemirror input rules are not triggered on backspace, however
|
||||
// we need them to be evaluted for the filter trigger to work
|
||||
// correctly. This additional handler adds inputrules-like handling.
|
||||
if (event.key === "Backspace") {
|
||||
// timeout ensures that the delete has been handled by prosemirror
|
||||
// and any characters removed, before we evaluate the rule.
|
||||
setTimeout(() => {
|
||||
const { pos } = view.state.selection.$from;
|
||||
return run(view, pos, pos, OPEN_REGEX, (state, match) => {
|
||||
if (match) {
|
||||
this.options.onOpen(match[1]);
|
||||
} else {
|
||||
this.options.onClose();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// If the query is active and we're navigating the block menu then
|
||||
// just ignore the key events in the editor itself until we're done
|
||||
if (
|
||||
event.key === "Enter" ||
|
||||
event.key === "ArrowUp" ||
|
||||
event.key === "ArrowDown" ||
|
||||
event.key === "Tab"
|
||||
) {
|
||||
const { pos } = view.state.selection.$from;
|
||||
|
||||
return run(view, pos, pos, OPEN_REGEX, (state, match) => {
|
||||
// just tell Prosemirror we handled it and not to do anything
|
||||
return match ? true : null;
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
inputRules() {
|
||||
return [
|
||||
// main regex should match only:
|
||||
// :word
|
||||
new InputRule(OPEN_REGEX, (state, match) => {
|
||||
if (
|
||||
match &&
|
||||
state.selection.$from.parent.type.name === "paragraph" &&
|
||||
!isInCode(state)
|
||||
) {
|
||||
this.options.onOpen(match[1]);
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
// invert regex should match some of these scenarios:
|
||||
// :<space>word
|
||||
// :<space>
|
||||
// :word<space>
|
||||
// :)
|
||||
new InputRule(CLOSE_REGEX, (state, match) => {
|
||||
if (match) {
|
||||
this.options.onClose();
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
72
shared/editor/plugins/Folding.tsx
Normal file
72
shared/editor/plugins/Folding.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { Plugin } from "prosemirror-state";
|
||||
import { findBlockNodes } from "prosemirror-utils";
|
||||
import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import Extension from "../lib/Extension";
|
||||
import { headingToPersistenceKey } from "../lib/headingToSlug";
|
||||
import findCollapsedNodes from "../queries/findCollapsedNodes";
|
||||
|
||||
export default class Folding extends Extension {
|
||||
get name() {
|
||||
return "folding";
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
let loaded = false;
|
||||
|
||||
return [
|
||||
new Plugin({
|
||||
view: (view) => {
|
||||
loaded = false;
|
||||
view.dispatch(view.state.tr.setMeta("folding", { loaded: true }));
|
||||
return {};
|
||||
},
|
||||
appendTransaction: (transactions, oldState, newState) => {
|
||||
if (loaded) return;
|
||||
if (
|
||||
!transactions.some((transaction) => transaction.getMeta("folding"))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let modified = false;
|
||||
const tr = newState.tr;
|
||||
const blocks = findBlockNodes(newState.doc);
|
||||
|
||||
for (const block of blocks) {
|
||||
if (block.node.type.name === "heading") {
|
||||
const persistKey = headingToPersistenceKey(
|
||||
block.node,
|
||||
this.editor.props.id
|
||||
);
|
||||
const persistedState = localStorage?.getItem(persistKey);
|
||||
|
||||
if (persistedState === "collapsed") {
|
||||
tr.setNodeMarkup(block.pos, undefined, {
|
||||
...block.node.attrs,
|
||||
collapsed: true,
|
||||
});
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loaded = true;
|
||||
return modified ? tr : null;
|
||||
},
|
||||
props: {
|
||||
decorations: (state) => {
|
||||
const { doc } = state;
|
||||
const decorations: Decoration[] = findCollapsedNodes(doc).map(
|
||||
(block) =>
|
||||
Decoration.node(block.pos, block.pos + block.node.nodeSize, {
|
||||
class: "folded-content",
|
||||
})
|
||||
);
|
||||
|
||||
return DecorationSet.create(doc, decorations);
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
22
shared/editor/plugins/History.ts
Normal file
22
shared/editor/plugins/History.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { history, undo, redo } from "prosemirror-history";
|
||||
import { undoInputRule } from "prosemirror-inputrules";
|
||||
import Extension from "../lib/Extension";
|
||||
|
||||
export default class History extends Extension {
|
||||
get name() {
|
||||
return "history";
|
||||
}
|
||||
|
||||
keys() {
|
||||
return {
|
||||
"Mod-z": undo,
|
||||
"Mod-y": redo,
|
||||
"Shift-Mod-z": redo,
|
||||
Backspace: undoInputRule,
|
||||
};
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [history()];
|
||||
}
|
||||
}
|
||||
91
shared/editor/plugins/Keys.ts
Normal file
91
shared/editor/plugins/Keys.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { GapCursor } from "prosemirror-gapcursor";
|
||||
import {
|
||||
Plugin,
|
||||
Selection,
|
||||
AllSelection,
|
||||
TextSelection,
|
||||
} from "prosemirror-state";
|
||||
import Extension from "../lib/Extension";
|
||||
import isModKey from "../lib/isModKey";
|
||||
|
||||
export default class Keys extends Extension {
|
||||
get name() {
|
||||
return "keys";
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
props: {
|
||||
handleDOMEvents: {
|
||||
blur: this.options.onBlur,
|
||||
focus: this.options.onFocus,
|
||||
},
|
||||
// we can't use the keys bindings for this as we want to preventDefault
|
||||
// on the original keyboard event when handled
|
||||
handleKeyDown: (view, event) => {
|
||||
if (view.state.selection instanceof AllSelection) {
|
||||
if (event.key === "ArrowUp") {
|
||||
const selection = Selection.atStart(view.state.doc);
|
||||
view.dispatch(view.state.tr.setSelection(selection));
|
||||
return true;
|
||||
}
|
||||
if (event.key === "ArrowDown") {
|
||||
const selection = Selection.atEnd(view.state.doc);
|
||||
view.dispatch(view.state.tr.setSelection(selection));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// edge case where horizontal gap cursor does nothing if Enter key
|
||||
// is pressed. Insert a newline and then move the cursor into it.
|
||||
if (view.state.selection instanceof GapCursor) {
|
||||
if (event.key === "Enter") {
|
||||
view.dispatch(
|
||||
view.state.tr.insert(
|
||||
view.state.selection.from,
|
||||
view.state.schema.nodes.paragraph.create({})
|
||||
)
|
||||
);
|
||||
view.dispatch(
|
||||
view.state.tr.setSelection(
|
||||
TextSelection.near(
|
||||
view.state.doc.resolve(view.state.selection.from),
|
||||
-1
|
||||
)
|
||||
)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// All the following keys require mod to be down
|
||||
if (!isModKey(event)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (event.key === "s") {
|
||||
event.preventDefault();
|
||||
this.options.onSave();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
this.options.onSaveAndExit();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
this.options.onCancel();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
23
shared/editor/plugins/MaxLength.ts
Normal file
23
shared/editor/plugins/MaxLength.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Plugin, Transaction } from "prosemirror-state";
|
||||
import Extension from "../lib/Extension";
|
||||
|
||||
export default class MaxLength extends Extension {
|
||||
get name() {
|
||||
return "maxlength";
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
filterTransaction: (tr: Transaction) => {
|
||||
if (this.options.maxLength) {
|
||||
const result = tr.doc && tr.doc.nodeSize > this.options.maxLength;
|
||||
return !result;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
152
shared/editor/plugins/PasteHandler.ts
Normal file
152
shared/editor/plugins/PasteHandler.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
import { toggleMark } from "prosemirror-commands";
|
||||
import { Plugin } from "prosemirror-state";
|
||||
import { isInTable } from "prosemirror-tables";
|
||||
import Extension from "../lib/Extension";
|
||||
import isMarkdown from "../lib/isMarkdown";
|
||||
import isUrl from "../lib/isUrl";
|
||||
import selectionIsInCode from "../queries/isInCode";
|
||||
import { LANGUAGES } from "./Prism";
|
||||
|
||||
/**
|
||||
* Add support for additional syntax that users paste even though it isn't
|
||||
* supported by the markdown parser directly by massaging the text content.
|
||||
*
|
||||
* @param text The incoming pasted plain text
|
||||
*/
|
||||
function normalizePastedMarkdown(text: string): string {
|
||||
// find checkboxes not contained in a list and wrap them in list items
|
||||
const CHECKBOX_REGEX = /^\s?(\[(X|\s|_|-)\]\s(.*)?)/gim;
|
||||
|
||||
while (text.match(CHECKBOX_REGEX)) {
|
||||
text = text.replace(CHECKBOX_REGEX, (match) => `- ${match.trim()}`);
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
export default class PasteHandler extends Extension {
|
||||
get name() {
|
||||
return "markdown-paste";
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
props: {
|
||||
handlePaste: (view, event: ClipboardEvent) => {
|
||||
if (view.props.editable && !view.props.editable(view.state)) {
|
||||
return false;
|
||||
}
|
||||
if (!event.clipboardData) return false;
|
||||
|
||||
const text = event.clipboardData.getData("text/plain");
|
||||
const html = event.clipboardData.getData("text/html");
|
||||
const vscode = event.clipboardData.getData("vscode-editor-data");
|
||||
const { state, dispatch } = view;
|
||||
|
||||
// first check if the clipboard contents can be parsed as a single
|
||||
// url, this is mainly for allowing pasted urls to become embeds
|
||||
if (isUrl(text)) {
|
||||
// just paste the link mark directly onto the selected text
|
||||
if (!state.selection.empty) {
|
||||
toggleMark(this.editor.schema.marks.link, { href: text })(
|
||||
state,
|
||||
dispatch
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Is this link embeddable? Create an embed!
|
||||
const { embeds } = this.editor.props;
|
||||
|
||||
if (embeds && !isInTable(state)) {
|
||||
for (const embed of embeds) {
|
||||
const matches = embed.matcher(text);
|
||||
if (matches) {
|
||||
this.editor.commands.embed({
|
||||
href: text,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// well, it's not an embed and there is no text selected – so just
|
||||
// go ahead and insert the link directly
|
||||
const transaction = view.state.tr
|
||||
.insertText(text, state.selection.from, state.selection.to)
|
||||
.addMark(
|
||||
state.selection.from,
|
||||
state.selection.to + text.length,
|
||||
state.schema.marks.link.create({ href: text })
|
||||
);
|
||||
view.dispatch(transaction);
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the users selection is currently in a code block then paste
|
||||
// as plain text, ignore all formatting and HTML content.
|
||||
if (selectionIsInCode(view.state)) {
|
||||
event.preventDefault();
|
||||
|
||||
view.dispatch(view.state.tr.insertText(text));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Because VSCode is an especially popular editor that places metadata
|
||||
// on the clipboard, we can parse it to find out what kind of content
|
||||
// was pasted.
|
||||
const vscodeMeta = vscode ? JSON.parse(vscode) : undefined;
|
||||
const pasteCodeLanguage = vscodeMeta?.mode;
|
||||
|
||||
if (pasteCodeLanguage && pasteCodeLanguage !== "markdown") {
|
||||
event.preventDefault();
|
||||
view.dispatch(
|
||||
view.state.tr
|
||||
.replaceSelectionWith(
|
||||
view.state.schema.nodes.code_fence.create({
|
||||
language: Object.keys(LANGUAGES).includes(vscodeMeta.mode)
|
||||
? vscodeMeta.mode
|
||||
: null,
|
||||
})
|
||||
)
|
||||
.insertText(text)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the HTML on the clipboard is from Prosemirror then the best
|
||||
// compatability is to just use the HTML parser, regardless of
|
||||
// whether it "looks" like Markdown, see: outline/outline#2416
|
||||
if (html?.includes("data-pm-slice")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If the text on the clipboard looks like Markdown OR there is no
|
||||
// html on the clipboard then try to parse content as Markdown
|
||||
if (
|
||||
isMarkdown(text) ||
|
||||
html.length === 0 ||
|
||||
pasteCodeLanguage === "markdown"
|
||||
) {
|
||||
event.preventDefault();
|
||||
|
||||
const paste = this.editor.pasteParser.parse(
|
||||
normalizePastedMarkdown(text)
|
||||
);
|
||||
const slice = paste.slice(0);
|
||||
|
||||
const transaction = view.state.tr.replaceSelection(slice);
|
||||
view.dispatch(transaction);
|
||||
return true;
|
||||
}
|
||||
|
||||
// otherwise use the default HTML parser which will handle all paste
|
||||
// "from the web" events
|
||||
return false;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
50
shared/editor/plugins/Placeholder.ts
Normal file
50
shared/editor/plugins/Placeholder.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Plugin } from "prosemirror-state";
|
||||
import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import Extension from "../lib/Extension";
|
||||
|
||||
export default class Placeholder extends Extension {
|
||||
get name() {
|
||||
return "empty-placeholder";
|
||||
}
|
||||
|
||||
get defaultOptions() {
|
||||
return {
|
||||
emptyNodeClass: "placeholder",
|
||||
placeholder: "",
|
||||
};
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
props: {
|
||||
decorations: (state) => {
|
||||
const { doc } = state;
|
||||
const decorations: Decoration[] = [];
|
||||
const completelyEmpty =
|
||||
doc.textContent === "" &&
|
||||
doc.childCount <= 1 &&
|
||||
doc.content.size <= 2;
|
||||
|
||||
doc.descendants((node, pos) => {
|
||||
if (!completelyEmpty) {
|
||||
return;
|
||||
}
|
||||
if (pos !== 0 || node.type.name !== "paragraph") {
|
||||
return;
|
||||
}
|
||||
|
||||
const decoration = Decoration.node(pos, pos + node.nodeSize, {
|
||||
class: this.options.emptyNodeClass,
|
||||
"data-empty-text": this.options.placeholder,
|
||||
});
|
||||
decorations.push(decoration);
|
||||
});
|
||||
|
||||
return DecorationSet.create(doc, decorations);
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
151
shared/editor/plugins/Prism.ts
Normal file
151
shared/editor/plugins/Prism.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
import { flattenDeep } from "lodash";
|
||||
import { Node } from "prosemirror-model";
|
||||
import { Plugin, PluginKey, Transaction } from "prosemirror-state";
|
||||
import { findBlockNodes } from "prosemirror-utils";
|
||||
import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import refractor from "refractor/core";
|
||||
|
||||
export const LANGUAGES = {
|
||||
none: "None", // additional entry to disable highlighting
|
||||
bash: "Bash",
|
||||
css: "CSS",
|
||||
clike: "C",
|
||||
csharp: "C#",
|
||||
go: "Go",
|
||||
markup: "HTML",
|
||||
objectivec: "Objective-C",
|
||||
java: "Java",
|
||||
javascript: "JavaScript",
|
||||
json: "JSON",
|
||||
perl: "Perl",
|
||||
php: "PHP",
|
||||
powershell: "Powershell",
|
||||
python: "Python",
|
||||
ruby: "Ruby",
|
||||
rust: "Rust",
|
||||
sql: "SQL",
|
||||
typescript: "TypeScript",
|
||||
yaml: "YAML",
|
||||
};
|
||||
|
||||
type ParsedNode = {
|
||||
text: string;
|
||||
classes: string[];
|
||||
};
|
||||
|
||||
const cache: Record<number, { node: Node; decorations: Decoration[] }> = {};
|
||||
|
||||
function getDecorations({ doc, name }: { doc: Node; name: string }) {
|
||||
const decorations: Decoration[] = [];
|
||||
const blocks: { node: Node; pos: number }[] = findBlockNodes(doc).filter(
|
||||
(item) => item.node.type.name === name
|
||||
);
|
||||
|
||||
function parseNodes(
|
||||
nodes: refractor.RefractorNode[],
|
||||
classNames: string[] = []
|
||||
): any {
|
||||
return nodes.map((node) => {
|
||||
if (node.type === "element") {
|
||||
const classes = [...classNames, ...(node.properties.className || [])];
|
||||
return parseNodes(node.children, classes);
|
||||
}
|
||||
|
||||
return {
|
||||
text: node.value,
|
||||
classes: classNames,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
blocks.forEach((block) => {
|
||||
let startPos = block.pos + 1;
|
||||
const language = block.node.attrs.language;
|
||||
if (!language || language === "none" || !refractor.registered(language)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!cache[block.pos] || !cache[block.pos].node.eq(block.node)) {
|
||||
const nodes = refractor.highlight(block.node.textContent, language);
|
||||
const _decorations = flattenDeep(parseNodes(nodes))
|
||||
.map((node: ParsedNode) => {
|
||||
const from = startPos;
|
||||
const to = from + node.text.length;
|
||||
|
||||
startPos = to;
|
||||
|
||||
return {
|
||||
...node,
|
||||
from,
|
||||
to,
|
||||
};
|
||||
})
|
||||
.filter((node) => node.classes && node.classes.length)
|
||||
.map((node) =>
|
||||
Decoration.inline(node.from, node.to, {
|
||||
class: node.classes.join(" "),
|
||||
})
|
||||
);
|
||||
|
||||
cache[block.pos] = {
|
||||
node: block.node,
|
||||
decorations: _decorations,
|
||||
};
|
||||
}
|
||||
cache[block.pos].decorations.forEach((decoration) => {
|
||||
decorations.push(decoration);
|
||||
});
|
||||
});
|
||||
|
||||
Object.keys(cache)
|
||||
.filter((pos) => !blocks.find((block) => block.pos === Number(pos)))
|
||||
.forEach((pos) => {
|
||||
delete cache[Number(pos)];
|
||||
});
|
||||
|
||||
return DecorationSet.create(doc, decorations);
|
||||
}
|
||||
|
||||
export default function Prism({ name }: { name: string }) {
|
||||
let highlighted = false;
|
||||
|
||||
return new Plugin({
|
||||
key: new PluginKey("prism"),
|
||||
state: {
|
||||
init: (_: Plugin, { doc }) => {
|
||||
return DecorationSet.create(doc, []);
|
||||
},
|
||||
apply: (transaction: Transaction, decorationSet, oldState, state) => {
|
||||
const nodeName = state.selection.$head.parent.type.name;
|
||||
const previousNodeName = oldState.selection.$head.parent.type.name;
|
||||
const codeBlockChanged =
|
||||
transaction.docChanged && [nodeName, previousNodeName].includes(name);
|
||||
const ySyncEdit = !!transaction.getMeta("y-sync$");
|
||||
|
||||
if (!highlighted || codeBlockChanged || ySyncEdit) {
|
||||
highlighted = true;
|
||||
return getDecorations({ doc: transaction.doc, name });
|
||||
}
|
||||
|
||||
return decorationSet.map(transaction.mapping, transaction.doc);
|
||||
},
|
||||
},
|
||||
view: (view) => {
|
||||
if (!highlighted) {
|
||||
// we don't highlight code blocks on the first render as part of mounting
|
||||
// as it's expensive (relative to the rest of the document). Instead let
|
||||
// it render un-highlighted and then trigger a defered render of Prism
|
||||
// by updating the plugins metadata
|
||||
setTimeout(() => {
|
||||
view.dispatch(view.state.tr.setMeta("prism", { loaded: true }));
|
||||
}, 10);
|
||||
}
|
||||
return {};
|
||||
},
|
||||
props: {
|
||||
decorations(state) {
|
||||
return this.getState(state);
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
14
shared/editor/plugins/SmartText.ts
Normal file
14
shared/editor/plugins/SmartText.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ellipsis, smartQuotes, InputRule } from "prosemirror-inputrules";
|
||||
import Extension from "../lib/Extension";
|
||||
|
||||
const rightArrow = new InputRule(/->$/, "→");
|
||||
|
||||
export default class SmartText extends Extension {
|
||||
get name() {
|
||||
return "smart_text";
|
||||
}
|
||||
|
||||
inputRules() {
|
||||
return [rightArrow, ellipsis, ...smartQuotes];
|
||||
}
|
||||
}
|
||||
58
shared/editor/plugins/TrailingNode.ts
Normal file
58
shared/editor/plugins/TrailingNode.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { NodeType } from "prosemirror-model";
|
||||
import { Plugin, PluginKey } from "prosemirror-state";
|
||||
import Extension from "../lib/Extension";
|
||||
|
||||
export default class TrailingNode extends Extension {
|
||||
get name() {
|
||||
return "trailing_node";
|
||||
}
|
||||
|
||||
get defaultOptions() {
|
||||
return {
|
||||
node: "paragraph",
|
||||
notAfter: ["paragraph", "heading"],
|
||||
};
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
const plugin = new PluginKey(this.name);
|
||||
const disabledNodes = Object.entries(this.editor.schema.nodes)
|
||||
.map(([, value]) => value)
|
||||
.filter((node: NodeType) => this.options.notAfter.includes(node.name));
|
||||
|
||||
return [
|
||||
new Plugin({
|
||||
key: plugin,
|
||||
view: () => ({
|
||||
update: (view) => {
|
||||
const { state } = view;
|
||||
const insertNodeAtEnd = plugin.getState(state);
|
||||
|
||||
if (!insertNodeAtEnd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { doc, schema, tr } = state;
|
||||
const type = schema.nodes[this.options.node];
|
||||
const transaction = tr.insert(doc.content.size, type.create());
|
||||
view.dispatch(transaction);
|
||||
},
|
||||
}),
|
||||
state: {
|
||||
init: (_, state) => {
|
||||
const lastNode = state.tr.doc.lastChild;
|
||||
return lastNode ? !disabledNodes.includes(lastNode.type) : false;
|
||||
},
|
||||
apply: (tr, value) => {
|
||||
if (!tr.docChanged) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const lastNode = tr.doc.lastChild;
|
||||
return lastNode ? !disabledNodes.includes(lastNode.type) : false;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user