feat: Integrate input rules and paste rules into the core (#1997)

* refactoring

* improve link regex

* WIP: add new markPasteRule und linkify to image mark

* move copy of inputrule to core

* trigger codeblock inputrule on enter

* refactoring

* add regex match to markpasterulematch

* refactoring

* improve link regex

* WIP: add new markPasteRule und linkify to image mark

* move copy of inputrule to core

* trigger codeblock inputrule on enter

* refactoring

* add regex match to markpasterulematch

* update linkify

* wip

* wip

* log

* wip

* remove debug code

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* rename matcher

* add data to ExtendedRegExpMatchArray

* remove logging

* add code option to marks, prevent inputrules in code mark

* remove link regex

* fix codeblock inputrule on enter

* refactoring

* refactoring

* refactoring

* refactoring

* fix position bug

* add test

* export InputRule and PasteRule

* clean up link demo

* fix types
This commit is contained in:
Philipp Kühn
2021-10-08 15:02:09 +02:00
committed by GitHub
parent ace4964d97
commit 723b955cec
57 changed files with 1150 additions and 383 deletions

View File

@@ -1,5 +1,6 @@
import { EditorState, Transaction } from 'prosemirror-state'
import { Transaction } from 'prosemirror-state'
import { Editor } from './Editor'
import createChainableState from './helpers/createChainableState'
import {
SingleCommands,
ChainedCommands,
@@ -106,7 +107,10 @@ export default class CommandManager {
tr,
editor,
view,
state: this.chainableState(tr, state),
state: createChainableState({
state,
transaction: tr,
}),
dispatch: shouldDispatch
? () => undefined
: undefined,
@@ -124,36 +128,4 @@ export default class CommandManager {
return props
}
public chainableState(tr: Transaction, state: EditorState): EditorState {
let { selection } = tr
let { doc } = tr
let { storedMarks } = tr
return {
...state,
schema: state.schema,
plugins: state.plugins,
apply: state.apply.bind(state),
applyTransaction: state.applyTransaction.bind(state),
reconfigure: state.reconfigure.bind(state),
toJSON: state.toJSON.bind(state),
get storedMarks() {
return storedMarks
},
get selection() {
return selection
},
get doc() {
return doc
},
get tr() {
selection = tr.selection
doc = tr.doc
storedMarks = tr.storedMarks
return tr
},
}
}
}

View File

@@ -15,6 +15,7 @@ import getText from './helpers/getText'
import isNodeEmpty from './helpers/isNodeEmpty'
import getTextSeralizersFromSchema from './helpers/getTextSeralizersFromSchema'
import createStyleTag from './utilities/createStyleTag'
import isFunction from './utilities/isFunction'
import CommandManager from './CommandManager'
import ExtensionManager from './ExtensionManager'
import EventEmitter from './EventEmitter'
@@ -184,7 +185,7 @@ export class Editor extends EventEmitter<EditorEvents> {
* @param handlePlugins Control how to merge the plugin into the existing plugins.
*/
public registerPlugin(plugin: Plugin, handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[]): void {
const plugins = typeof handlePlugins === 'function'
const plugins = isFunction(handlePlugins)
? handlePlugins(plugin, this.state.plugins)
: [...this.state.plugins, plugin]

View File

@@ -1,5 +1,6 @@
import { Plugin, Transaction } from 'prosemirror-state'
import { InputRule } from 'prosemirror-inputrules'
import { InputRule } from './InputRule'
import { PasteRule } from './PasteRule'
import { Editor } from './Editor'
import { Node } from './Node'
import { Mark } from './Mark'
@@ -81,7 +82,7 @@ declare module '@tiptap/core' {
options: Options,
editor: Editor,
parent: ParentConfig<ExtensionConfig<Options>>['addPasteRules'],
}) => Plugin[],
}) => PasteRule[],
/**
* ProseMirror plugins

View File

@@ -1,6 +1,7 @@
import { keymap } from 'prosemirror-keymap'
import { Schema, Node as ProsemirrorNode } from 'prosemirror-model'
import { inputRules as inputRulesPlugin } from 'prosemirror-inputrules'
import { inputRulesPlugin } from './InputRule'
import { pasteRulesPlugin } from './PasteRule'
import { EditorView, Decoration } from 'prosemirror-view'
import { Plugin } from 'prosemirror-state'
import { Editor } from './Editor'
@@ -210,7 +211,12 @@ export default class ExtensionManager {
// so it feels more natural to run plugins at the end of an array first.
// Thats why we have to reverse the `extensions` array and sort again
// based on the `priority` option.
return ExtensionManager.sort([...this.extensions].reverse())
const extensions = ExtensionManager.sort([...this.extensions].reverse())
const inputRules: any[] = []
const pasteRules: any[] = []
const allPlugins = extensions
.map(extension => {
const context = {
name: extension.name,
@@ -248,12 +254,7 @@ export default class ExtensionManager {
)
if (this.editor.options.enableInputRules && addInputRules) {
const inputRules = addInputRules()
const inputRulePlugins = inputRules.length
? [inputRulesPlugin({ rules: inputRules })]
: []
plugins.push(...inputRulePlugins)
inputRules.push(...addInputRules())
}
const addPasteRules = getExtensionField<AnyConfig['addPasteRules']>(
@@ -263,9 +264,7 @@ export default class ExtensionManager {
)
if (this.editor.options.enablePasteRules && addPasteRules) {
const pasteRulePlugins = addPasteRules()
plugins.push(...pasteRulePlugins)
pasteRules.push(...addPasteRules())
}
const addProseMirrorPlugins = getExtensionField<AnyConfig['addProseMirrorPlugins']>(
@@ -283,6 +282,12 @@ export default class ExtensionManager {
return plugins
})
.flat()
return [
inputRulesPlugin(inputRules),
pasteRulesPlugin(pasteRules),
...allPlugins,
]
}
get attributes() {

View File

@@ -0,0 +1,245 @@
import { EditorView } from 'prosemirror-view'
import { EditorState, Plugin, TextSelection } from 'prosemirror-state'
import createChainableState from './helpers/createChainableState'
import isRegExp from './utilities/isRegExp'
import { Range, ExtendedRegExpMatchArray } from './types'
export type InputRuleMatch = {
index: number,
text: string,
replaceWith?: string,
match?: RegExpMatchArray,
data?: Record<string, any>,
}
export type InputRuleFinder =
| RegExp
| ((text: string) => InputRuleMatch | null)
export class InputRule {
find: InputRuleFinder
handler: (props: {
state: EditorState,
range: Range,
match: ExtendedRegExpMatchArray,
}) => void
constructor(config: {
find: InputRuleFinder,
handler: (props: {
state: EditorState,
range: Range,
match: ExtendedRegExpMatchArray,
}) => void,
}) {
this.find = config.find
this.handler = config.handler
}
}
const inputRuleMatcherHandler = (text: string, find: InputRuleFinder): ExtendedRegExpMatchArray | null => {
if (isRegExp(find)) {
return find.exec(text)
}
const inputRuleMatch = find(text)
if (!inputRuleMatch) {
return null
}
const result: ExtendedRegExpMatchArray = []
result.push(inputRuleMatch.text)
result.index = inputRuleMatch.index
result.input = text
result.data = inputRuleMatch.data
if (inputRuleMatch.replaceWith) {
if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".')
}
result.push(inputRuleMatch.replaceWith)
}
return result
}
function run(config: {
view: EditorView,
from: number,
to: number,
text: string,
rules: InputRule[],
plugin: Plugin,
}): any {
const {
view,
from,
to,
text,
rules,
plugin,
} = config
if (view.composing) {
return false
}
const $from = view.state.doc.resolve(from)
if (
// check for code node
$from.parent.type.spec.code
// check for code mark
|| !!($from.nodeBefore || $from.nodeAfter)?.marks.find(mark => mark.type.spec.code)
) {
return false
}
let matched = false
const maxMatch = 500
const textBefore = $from.parent.textBetween(
Math.max(0, $from.parentOffset - maxMatch),
$from.parentOffset,
undefined,
'\ufffc',
) + text
rules.forEach(rule => {
if (matched) {
return
}
const match = inputRuleMatcherHandler(textBefore, rule.find)
if (!match) {
return
}
const tr = view.state.tr
const state = createChainableState({
state: view.state,
transaction: tr,
})
const range = {
from: from - (match[0].length - text.length),
to,
}
rule.handler({
state,
range,
match,
})
// stop if there are no changes
if (!tr.steps.length) {
return
}
// store transform as meta data
// so we can undo input rules within the `undoInputRules` command
tr.setMeta(plugin, {
transform: tr,
from,
to,
text,
})
view.dispatch(tr)
matched = true
})
return matched
}
/**
* Create an input rules plugin. When enabled, it will cause text
* input that matches any of the given rules to trigger the rules
* action.
*/
export function inputRulesPlugin(rules: InputRule[]): Plugin {
const plugin = new Plugin({
state: {
init() {
return null
},
apply(tr, prev) {
const stored = tr.getMeta(this)
if (stored) {
return stored
}
return tr.selectionSet || tr.docChanged
? null
: prev
},
},
props: {
handleTextInput(view, from, to, text) {
return run({
view,
from,
to,
text,
rules,
plugin,
})
},
handleDOMEvents: {
compositionend: view => {
setTimeout(() => {
const { $cursor } = view.state.selection as TextSelection
if ($cursor) {
run({
view,
from: $cursor.pos,
to: $cursor.pos,
text: '',
rules,
plugin,
})
}
})
return false
},
},
// add support for input rules to trigger on enter
// this is useful for example for code blocks
handleKeyDown(view, event) {
if (event.key !== 'Enter') {
return false
}
const { $cursor } = view.state.selection as TextSelection
if ($cursor) {
return run({
view,
from: $cursor.pos,
to: $cursor.pos,
text: '\n',
rules,
plugin,
})
}
return false
},
},
// @ts-ignore
isInputRules: true,
}) as Plugin
return plugin
}

View File

@@ -5,7 +5,8 @@ import {
MarkType,
} from 'prosemirror-model'
import { Plugin, Transaction } from 'prosemirror-state'
import { InputRule } from 'prosemirror-inputrules'
import { InputRule } from './InputRule'
import { PasteRule } from './PasteRule'
import mergeDeep from './utilities/mergeDeep'
import {
Extensions,
@@ -91,7 +92,7 @@ declare module '@tiptap/core' {
editor: Editor,
type: MarkType,
parent: ParentConfig<MarkConfig<Options>>['addPasteRules'],
}) => Plugin[],
}) => PasteRule[],
/**
* ProseMirror plugins
@@ -281,6 +282,15 @@ declare module '@tiptap/core' {
parent: ParentConfig<MarkConfig<Options>>['spanning'],
}) => MarkSpec['spanning']),
/**
* Code
*/
code?: boolean | ((this: {
name: string,
options: Options,
parent: ParentConfig<MarkConfig<Options>>['code'],
}) => boolean),
/**
* Parse HTML
*/

View File

@@ -5,7 +5,8 @@ import {
NodeType,
} from 'prosemirror-model'
import { Plugin, Transaction } from 'prosemirror-state'
import { InputRule } from 'prosemirror-inputrules'
import { InputRule } from './InputRule'
import { PasteRule } from './PasteRule'
import mergeDeep from './utilities/mergeDeep'
import {
Extensions,
@@ -91,7 +92,7 @@ declare module '@tiptap/core' {
editor: Editor,
type: NodeType,
parent: ParentConfig<NodeConfig<Options>>['addPasteRules'],
}) => Plugin[],
}) => PasteRule[],
/**
* ProseMirror plugins

View File

@@ -0,0 +1,177 @@
import { EditorState, Plugin } from 'prosemirror-state'
import createChainableState from './helpers/createChainableState'
import isRegExp from './utilities/isRegExp'
import { Range, ExtendedRegExpMatchArray } from './types'
export type PasteRuleMatch = {
index: number,
text: string,
replaceWith?: string,
match?: RegExpMatchArray,
data?: Record<string, any>,
}
export type PasteRuleFinder =
| RegExp
| ((text: string) => PasteRuleMatch[] | null | undefined)
export class PasteRule {
find: PasteRuleFinder
handler: (props: {
state: EditorState,
range: Range,
match: ExtendedRegExpMatchArray,
}) => void
constructor(config: {
find: PasteRuleFinder,
handler: (props: {
state: EditorState,
range: Range,
match: ExtendedRegExpMatchArray,
}) => void,
}) {
this.find = config.find
this.handler = config.handler
}
}
const pasteRuleMatcherHandler = (text: string, find: PasteRuleFinder): ExtendedRegExpMatchArray[] => {
if (isRegExp(find)) {
return [...text.matchAll(find)]
}
const matches = find(text)
if (!matches) {
return []
}
return matches.map(pasteRuleMatch => {
const result: ExtendedRegExpMatchArray = []
result.push(pasteRuleMatch.text)
result.index = pasteRuleMatch.index
result.input = text
result.data = pasteRuleMatch.data
if (pasteRuleMatch.replaceWith) {
if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {
console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".')
}
result.push(pasteRuleMatch.replaceWith)
}
return result
})
}
function run(config: {
state: EditorState,
from: number,
to: number,
rules: PasteRule[],
plugin: Plugin,
}): any {
const {
state,
from,
to,
rules,
} = config
state.doc.nodesBetween(from, to, (node, pos) => {
if (!node.isTextblock || node.type.spec.code) {
return
}
const resolvedFrom = Math.max(from, pos)
const resolvedTo = Math.min(to, pos + node.content.size)
const textToMatch = node.textBetween(
resolvedFrom - pos,
resolvedTo - pos,
undefined,
'\ufffc',
)
rules.forEach(rule => {
const matches = pasteRuleMatcherHandler(textToMatch, rule.find)
matches.forEach(match => {
if (match.index === undefined) {
return
}
const start = resolvedFrom + match.index
const end = start + match[0].length
const range = {
from: state.tr.mapping.map(start),
to: state.tr.mapping.map(end),
}
rule.handler({
state,
range,
match,
})
})
})
}, from)
}
/**
* Create an paste rules plugin. When enabled, it will cause pasted
* text that matches any of the given rules to trigger the rules
* action.
*/
export function pasteRulesPlugin(rules: PasteRule[]): Plugin {
const plugin = new Plugin({
appendTransaction: (transactions, oldState, state) => {
const transaction = transactions[0]
// stop if there is not a paste event
if (!transaction.getMeta('paste')) {
return
}
// stop if there is no changed range
const { doc, before } = transaction
const from = before.content.findDiffStart(doc.content)
const to = before.content.findDiffEnd(doc.content)
if (!from || !to) {
return
}
// build a chainable state
// so we can use a single transaction for all paste rules
const tr = state.tr
const chainableState = createChainableState({
state,
transaction: tr,
})
run({
state: chainableState,
from,
to: to.b,
rules,
plugin,
})
// stop if there are no changes
if (!tr.steps.length) {
return
}
return tr
},
// @ts-ignore
isPasteRules: true,
})
return plugin
}

View File

@@ -1,4 +1,3 @@
import { undoInputRule as originalUndoInputRule } from 'prosemirror-inputrules'
import { RawCommands } from '../types'
declare module '@tiptap/core' {
@@ -13,5 +12,34 @@ declare module '@tiptap/core' {
}
export const undoInputRule: RawCommands['undoInputRule'] = () => ({ state, dispatch }) => {
return originalUndoInputRule(state, dispatch)
const plugins = state.plugins
for (let i = 0; i < plugins.length; i += 1) {
const plugin = plugins[i]
let undoable
// @ts-ignore
// eslint-disable-next-line
if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
if (dispatch) {
const tr = state.tr
const toUndo = undoable.transform
for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {
tr.step(toUndo.steps[j].invert(toUndo.docs[j]))
}
if (undoable.text) {
const marks = tr.doc.resolve(undoable.from).marks()
tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))
} else {
tr.delete(undoable.from, undoable.to)
}
}
return true
}
}
return false
}

View File

@@ -0,0 +1,37 @@
import { EditorState, Transaction } from 'prosemirror-state'
export default function createChainableState(config: {
transaction: Transaction,
state: EditorState,
}): EditorState {
const { state, transaction } = config
let { selection } = transaction
let { doc } = transaction
let { storedMarks } = transaction
return {
...state,
schema: state.schema,
plugins: state.plugins,
apply: state.apply.bind(state),
applyTransaction: state.applyTransaction.bind(state),
reconfigure: state.reconfigure.bind(state),
toJSON: state.toJSON.bind(state),
get storedMarks() {
return storedMarks
},
get selection() {
return selection
},
get doc() {
return doc
},
get tr() {
selection = transaction.selection
doc = transaction.doc
storedMarks = transaction.storedMarks
return transaction
},
}
}

View File

@@ -108,10 +108,11 @@ export default function getSchemaByResolvedExtensions(extensions: Extensions): S
const schema: MarkSpec = cleanUpSchemaItem({
...extraMarkFields,
inclusive: callOrReturn(getExtensionField<NodeConfig['inclusive']>(extension, 'inclusive', context)),
excludes: callOrReturn(getExtensionField<NodeConfig['excludes']>(extension, 'excludes', context)),
group: callOrReturn(getExtensionField<NodeConfig['group']>(extension, 'group', context)),
spanning: callOrReturn(getExtensionField<NodeConfig['spanning']>(extension, 'spanning', context)),
inclusive: callOrReturn(getExtensionField<MarkConfig['inclusive']>(extension, 'inclusive', context)),
excludes: callOrReturn(getExtensionField<MarkConfig['excludes']>(extension, 'excludes', context)),
group: callOrReturn(getExtensionField<MarkConfig['group']>(extension, 'group', context)),
spanning: callOrReturn(getExtensionField<MarkConfig['spanning']>(extension, 'spanning', context)),
code: callOrReturn(getExtensionField<MarkConfig['code']>(extension, 'code', context)),
attrs: Object.fromEntries(extensionAttributes.map(extensionAttribute => {
return [extensionAttribute.name, { default: extensionAttribute?.attribute?.default }]
})),

View File

@@ -7,11 +7,17 @@ export * from './Node'
export * from './Mark'
export * from './NodeView'
export * from './Tracker'
export * from './InputRule'
export * from './PasteRule'
export * from './types'
export { default as nodeInputRule } from './inputRules/nodeInputRule'
export { default as markInputRule } from './inputRules/markInputRule'
export { default as textblockTypeInputRule } from './inputRules/textblockTypeInputRule'
export { default as textInputRule } from './inputRules/textInputRule'
export { default as wrappingInputRule } from './inputRules/wrappingInputRule'
export { default as markPasteRule } from './pasteRules/markPasteRule'
export { default as textPasteRule } from './pasteRules/textPasteRule'
export { default as callOrReturn } from './utilities/callOrReturn'
export { default as mergeAttributes } from './utilities/mergeAttributes'

View File

@@ -1,50 +1,70 @@
import { InputRule } from 'prosemirror-inputrules'
import { InputRule, InputRuleFinder } from '../InputRule'
import { MarkType } from 'prosemirror-model'
import getMarksBetween from '../helpers/getMarksBetween'
import callOrReturn from '../utilities/callOrReturn'
import { ExtendedRegExpMatchArray } from '../types'
export default function (regexp: RegExp, markType: MarkType, getAttributes?: Function): InputRule {
return new InputRule(regexp, (state, match, start, end) => {
const attributes = getAttributes instanceof Function
? getAttributes(match)
: getAttributes
const { tr } = state
const captureGroup = match[match.length - 1]
const fullMatch = match[0]
let markEnd = end
/**
* Build an input rule that adds a mark when the
* matched text is typed into it.
*/
export default function markInputRule(config: {
find: InputRuleFinder,
type: MarkType,
getAttributes?:
| Record<string, any>
| ((match: ExtendedRegExpMatchArray) => Record<string, any>)
| false
| null
,
}) {
return new InputRule({
find: config.find,
handler: ({ state, range, match }) => {
const attributes = callOrReturn(config.getAttributes, undefined, match)
if (captureGroup) {
const startSpaces = fullMatch.search(/\S/)
const textStart = start + fullMatch.indexOf(captureGroup)
const textEnd = textStart + captureGroup.length
const excludedMarks = getMarksBetween(start, end, state)
.filter(item => {
// TODO: PR to add excluded to MarkType
// @ts-ignore
const { excluded } = item.mark.type
return excluded.find((type: MarkType) => type.name === markType.name)
})
.filter(item => item.to > textStart)
if (excludedMarks.length) {
return null
if (attributes === false || attributes === null) {
return
}
if (textEnd < end) {
tr.delete(textEnd, end)
const { tr } = state
const captureGroup = match[match.length - 1]
const fullMatch = match[0]
let markEnd = range.to
if (captureGroup) {
const startSpaces = fullMatch.search(/\S/)
const textStart = range.from + fullMatch.indexOf(captureGroup)
const textEnd = textStart + captureGroup.length
const excludedMarks = getMarksBetween(range.from, range.to, state)
.filter(item => {
// TODO: PR to add excluded to MarkType
// @ts-ignore
const { excluded } = item.mark.type
return excluded.find((type: MarkType) => type.name === config.type.name)
})
.filter(item => item.to > textStart)
if (excludedMarks.length) {
return null
}
if (textEnd < range.to) {
tr.delete(textEnd, range.to)
}
if (textStart > range.from) {
tr.delete(range.from + startSpaces, textStart)
}
markEnd = range.from + startSpaces + captureGroup.length
tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))
tr.removeStoredMark(config.type)
}
if (textStart > start) {
tr.delete(start + startSpaces, textStart)
}
markEnd = start + startSpaces + captureGroup.length
tr.addMark(start + startSpaces, markEnd, markType.create(attributes))
tr.removeStoredMark(markType)
}
return tr
},
})
}

View File

@@ -1,32 +1,49 @@
import { InputRule } from 'prosemirror-inputrules'
import { NodeType } from 'prosemirror-model'
import { InputRule, InputRuleFinder } from '../InputRule'
import { ExtendedRegExpMatchArray } from '../types'
import callOrReturn from '../utilities/callOrReturn'
export default function (regexp: RegExp, type: NodeType, getAttributes?: (match: any) => any): InputRule {
return new InputRule(regexp, (state, match, start, end) => {
const attributes = getAttributes instanceof Function
? getAttributes(match)
: getAttributes
const { tr } = state
/**
* Build an input rule that adds a node when the
* matched text is typed into it.
*/
export default function nodeInputRule(config: {
find: InputRuleFinder,
type: NodeType,
getAttributes?:
| Record<string, any>
| ((match: ExtendedRegExpMatchArray) => Record<string, any>)
| false
| null
,
}) {
return new InputRule({
find: config.find,
handler: ({ state, range, match }) => {
const attributes = callOrReturn(config.getAttributes, undefined, match) || {}
const { tr } = state
const start = range.from
let end = range.to
if (match[1]) {
const offset = match[0].lastIndexOf(match[1])
let matchStart = start + offset
if (matchStart > end) {
matchStart = end
} else {
end = matchStart + match[1].length
if (match[1]) {
const offset = match[0].lastIndexOf(match[1])
let matchStart = start + offset
if (matchStart > end) {
matchStart = end
} else {
end = matchStart + match[1].length
}
// insert last typed character
const lastChar = match[0][match[0].length - 1]
tr.insertText(lastChar, start + match[0].length - 1)
// insert node from input rule
tr.replaceWith(matchStart, end, config.type.create(attributes))
} else if (match[0]) {
tr.replaceWith(start, end, config.type.create(attributes))
}
// insert last typed character
const lastChar = match[0][match[0].length - 1]
tr.insertText(lastChar, start + match[0].length - 1)
// insert node from input rule
tr.replaceWith(matchStart, end, type.create(attributes))
} else if (match[0]) {
tr.replaceWith(start, end, type.create(attributes))
}
return tr
},
})
}

View File

@@ -0,0 +1,35 @@
import { InputRule, InputRuleFinder } from '../InputRule'
/**
* Build an input rule that replaces text when the
* matched text is typed into it.
*/
export default function textInputRule(config: {
find: InputRuleFinder,
replace: string,
}) {
return new InputRule({
find: config.find,
handler: ({ state, range, match }) => {
let insert = config.replace
let start = range.from
const end = range.to
if (match[1]) {
const offset = match[0].lastIndexOf(match[1])
insert += match[0].slice(offset + match[1].length)
start += offset
const cutOff = start - end
if (cutOff > 0) {
insert = match[0].slice(offset - cutOff, offset) + insert
start = end
}
}
state.tr.insertText(insert, start, end)
},
})
}

View File

@@ -0,0 +1,37 @@
import { InputRule, InputRuleFinder } from '../InputRule'
import { NodeType } from 'prosemirror-model'
import { ExtendedRegExpMatchArray } from '../types'
import callOrReturn from '../utilities/callOrReturn'
/**
* Build an input rule that changes the type of a textblock when the
* matched text is typed into it. When using a regular expresion youll
* probably want the regexp to start with `^`, so that the pattern can
* only occur at the start of a textblock.
*/
export default function textblockTypeInputRule(config: {
find: InputRuleFinder,
type: NodeType,
getAttributes?:
| Record<string, any>
| ((match: ExtendedRegExpMatchArray) => Record<string, any>)
| false
| null
,
}) {
return new InputRule({
find: config.find,
handler: ({ state, range, match }) => {
const $start = state.doc.resolve(range.from)
const attributes = callOrReturn(config.getAttributes, undefined, match) || {}
if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {
return null
}
state.tr
.delete(range.from, range.to)
.setBlockType(range.from, range.from, config.type, attributes)
},
})
}

View File

@@ -0,0 +1,59 @@
import { InputRule, InputRuleFinder } from '../InputRule'
import { NodeType, Node as ProseMirrorNode } from 'prosemirror-model'
import { findWrapping, canJoin } from 'prosemirror-transform'
import { ExtendedRegExpMatchArray } from '../types'
import callOrReturn from '../utilities/callOrReturn'
/**
* Build an input rule for automatically wrapping a textblock when a
* given string is typed. When using a regular expresion youll
* probably want the regexp to start with `^`, so that the pattern can
* only occur at the start of a textblock.
*
* `type` is the type of node to wrap in.
*
* By default, if theres a node with the same type above the newly
* wrapped node, the rule will try to join those
* two nodes. You can pass a join predicate, which takes a regular
* expression match and the node before the wrapped node, and can
* return a boolean to indicate whether a join should happen.
*/
export default function wrappingInputRule(config: {
find: InputRuleFinder,
type: NodeType,
getAttributes?:
| Record<string, any>
| ((match: ExtendedRegExpMatchArray) => Record<string, any>)
| false
| null
,
joinPredicate?: (match: ExtendedRegExpMatchArray, node: ProseMirrorNode) => boolean,
}) {
return new InputRule({
find: config.find,
handler: ({ state, range, match }) => {
const attributes = callOrReturn(config.getAttributes, undefined, match) || {}
const tr = state.tr.delete(range.from, range.to)
const $start = tr.doc.resolve(range.from)
const blockRange = $start.blockRange()
const wrapping = blockRange && findWrapping(blockRange, config.type, attributes)
if (!wrapping) {
return null
}
tr.wrap(blockRange, wrapping)
const before = tr.doc.resolve(range.from - 1).nodeBefore
if (
before
&& before.type === config.type
&& canJoin(tr.doc, range.from - 1)
&& (!config.joinPredicate || config.joinPredicate(match, before))
) {
tr.join(range.from - 1)
}
},
})
}

View File

@@ -1,76 +1,70 @@
import { Plugin, PluginKey } from 'prosemirror-state'
import { Slice, Fragment, MarkType } from 'prosemirror-model'
import { PasteRule, PasteRuleFinder } from '../PasteRule'
import { MarkType } from 'prosemirror-model'
import getMarksBetween from '../helpers/getMarksBetween'
import callOrReturn from '../utilities/callOrReturn'
import { ExtendedRegExpMatchArray } from '../types'
export default function (
regexp: RegExp,
/**
* Build an paste rule that adds a mark when the
* matched text is pasted into it.
*/
export default function markPasteRule(config: {
find: PasteRuleFinder,
type: MarkType,
getAttributes?:
| Record<string, any>
| ((match: RegExpExecArray) => Record<string, any>)
| ((match: ExtendedRegExpMatchArray) => Record<string, any>)
| false
| null
,
): Plugin {
const handler = (fragment: Fragment, parent?: any) => {
const nodes: any[] = []
}) {
return new PasteRule({
find: config.find,
handler: ({ state, range, match }) => {
const attributes = callOrReturn(config.getAttributes, undefined, match)
fragment.forEach(child => {
if (child.isText && child.text) {
const { text } = child
let pos = 0
let match
// eslint-disable-next-line
while ((match = regexp.exec(text)) !== null) {
const outerMatch = Math.max(match.length - 2, 0)
const innerMatch = Math.max(match.length - 1, 0)
if (parent?.type.allowsMarkType(type)) {
const start = match.index
const matchStart = start + match[0].indexOf(match[outerMatch])
const matchEnd = matchStart + match[outerMatch].length
const textStart = matchStart + match[outerMatch].lastIndexOf(match[innerMatch])
const textEnd = textStart + match[innerMatch].length
const attrs = getAttributes instanceof Function
? getAttributes(match)
: getAttributes
if (!attrs && attrs !== undefined) {
continue
}
// adding text before markdown to nodes
if (matchStart > 0) {
nodes.push(child.cut(pos, matchStart))
}
// adding the markdown part to nodes
nodes.push(child
.cut(textStart, textEnd)
.mark(type.create(attrs).addToSet(child.marks)))
pos = matchEnd
}
}
// adding rest of text to nodes
if (pos < text.length) {
nodes.push(child.cut(pos))
}
} else {
nodes.push(child.copy(handler(child.content, child)))
if (attributes === false || attributes === null) {
return
}
})
return Fragment.fromArray(nodes)
}
const { tr } = state
const captureGroup = match[match.length - 1]
const fullMatch = match[0]
let markEnd = range.to
return new Plugin({
key: new PluginKey('markPasteRule'),
props: {
transformPasted: slice => {
return new Slice(handler(slice.content), slice.openStart, slice.openEnd)
},
if (captureGroup) {
const startSpaces = fullMatch.search(/\S/)
const textStart = range.from + fullMatch.indexOf(captureGroup)
const textEnd = textStart + captureGroup.length
const excludedMarks = getMarksBetween(range.from, range.to, state)
.filter(item => {
// TODO: PR to add excluded to MarkType
// @ts-ignore
const { excluded } = item.mark.type
return excluded.find((type: MarkType) => type.name === config.type.name)
})
.filter(item => item.to > textStart)
if (excludedMarks.length) {
return null
}
if (textEnd < range.to) {
tr.delete(textEnd, range.to)
}
if (textStart > range.from) {
tr.delete(range.from + startSpaces, textStart)
}
markEnd = range.from + startSpaces + captureGroup.length
tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))
tr.removeStoredMark(config.type)
}
},
})
}

View File

@@ -0,0 +1,35 @@
import { PasteRule, PasteRuleFinder } from '../PasteRule'
/**
* Build an paste rule that replaces text when the
* matched text is pasted into it.
*/
export default function textPasteRule(config: {
find: PasteRuleFinder,
replace: string,
}) {
return new PasteRule({
find: config.find,
handler: ({ state, range, match }) => {
let insert = config.replace
let start = range.from
const end = range.to
if (match[1]) {
const offset = match[0].lastIndexOf(match[1])
insert += match[0].slice(offset + match[1].length)
start += offset
const cutOff = start - end
if (cutOff > 0) {
insert = match[0].slice(offset - cutOff, offset) + insert
start = end
}
}
state.tr.insertText(insert, start, end)
},
})
}

View File

@@ -229,3 +229,7 @@ export type TextSerializer = (props: {
parent: ProseMirrorNode,
index: number,
}) => string
export type ExtendedRegExpMatchArray = RegExpMatchArray & {
data?: Record<string, any>,
}

View File

@@ -1,4 +1,5 @@
import { MaybeReturnType } from '../types'
import isFunction from './isFunction'
/**
* Optionally calls `value` as a function.
@@ -8,7 +9,7 @@ import { MaybeReturnType } from '../types'
* @param props Optional props to pass to function.
*/
export default function callOrReturn<T>(value: T, context: any = undefined, ...props: any[]): MaybeReturnType<T> {
if (typeof value === 'function') {
if (isFunction(value)) {
if (context) {
return value.bind(context)(...props)
}

View File

@@ -1,5 +1,5 @@
export default function isClass(item: any): boolean {
if (item.constructor?.toString().substring(0, 5) !== 'class') {
export default function isClass(value: any): boolean {
if (value.constructor?.toString().substring(0, 5) !== 'class') {
return false
}

View File

@@ -1,3 +1,3 @@
export default function isEmptyObject(object = {}): boolean {
return Object.keys(object).length === 0 && object.constructor === Object
export default function isEmptyObject(value = {}): boolean {
return Object.keys(value).length === 0 && value.constructor === Object
}

View File

@@ -0,0 +1,3 @@
export default function isObject(value: any): value is Function {
return typeof value === 'function'
}

View File

@@ -1,10 +1,10 @@
import isClass from './isClass'
export default function isObject(item: any): boolean {
export default function isObject(value: any): boolean {
return (
item
&& typeof item === 'object'
&& !Array.isArray(item)
&& !isClass(item)
value
&& typeof value === 'object'
&& !Array.isArray(value)
&& !isClass(value)
)
}

View File

@@ -1,10 +1,10 @@
// see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts
function getType(payload: any): string {
return Object.prototype.toString.call(payload).slice(8, -1)
function getType(value: any): string {
return Object.prototype.toString.call(value).slice(8, -1)
}
export default function isPlainObject(payload: any): payload is Record<string, any> {
if (getType(payload) !== 'Object') return false
return payload.constructor === Object && Object.getPrototypeOf(payload) === Object.prototype
export default function isPlainObject(value: any): value is Record<string, any> {
if (getType(value) !== 'Object') return false
return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype
}

View File

@@ -1,3 +1,3 @@
export default function isRegExp(value: any): boolean {
export default function isRegExp(value: any): value is RegExp {
return Object.prototype.toString.call(value) === '[object RegExp]'
}

View File

@@ -0,0 +1,3 @@
export default function isString(value: any): value is string {
return typeof value === 'string'
}