Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@prosekit/core

Package Overview
Dependencies
Maintainers
1
Versions
110
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@prosekit/core - npm Package Compare versions

Comparing version 0.0.0-next-20230709094459 to 0.0.0-next-20231120040948

dist/_tsup-dts-rollup.d.ts

349

dist/prosekit-core.d.ts

@@ -1,283 +0,66 @@

import { MarkType, Attrs, Schema, ProseMirrorNode, NodeType, MarkSpec, NodeSpec } from '@prosekit/pm/model';
import { Command, EditorStateConfig, Plugin } from '@prosekit/pm/state';
import { EditorView, NodeViewConstructor, DirectEditorProps } from '@prosekit/pm/view';
import { ConditionalExcept, EmptyObject, Simplify, UnionToIntersection } from 'type-fest';
import { InputRule } from '@prosekit/pm/inputrules';
interface ToggleMarkOptions {
type: string | MarkType;
attrs?: Attrs | null;
}
declare function toggleMark(options: ToggleMarkOptions): Command;
type CommandDispatcher<Args extends any[] = any[]> = (...arg: Args) => boolean;
type CommandCreator<Args extends any[] = any[]> = (...arg: Args) => Command;
/** @internal */
interface CommandArgs {
[name: string]: any[];
}
type ToCommandCreators<T extends CommandArgs> = {
[K in keyof T]: CommandCreator<T[K]>;
};
type ToCommandDispatcher<T extends CommandArgs> = {
[K in keyof T]: CommandDispatcher<T[K]>;
};
type EmptyValue = never | undefined | null | EmptyObject;
type ExceptEmptyValue<T> = ConditionalExcept<T, EmptyValue>;
/**
* @intneral
*/
type ExtractKey<T, K extends string> = Extract<T, Record<K, any>>[K];
/**
* @internal
*/
interface ExtensionTyping<Node extends string = string, Mark extends string = string, Commands extends CommandArgs = CommandArgs> {
NODES?: Node;
MARKS?: Mark;
COMMAND_ARGS?: Commands;
}
type ExtractNodesFromTyping<T extends ExtensionTyping> = ExtractKey<T, 'NODES'>;
type ExtractMarksFromTyping<T extends ExtensionTyping> = ExtractKey<T, 'MARKS'>;
type ExtractCommandArgsFromTyping<T extends ExtensionTyping> = ExtractKey<T, 'COMMAND_ARGS'>;
/**
* @public
*/
declare const enum Priority {
lowest = 4,
low = 3,
default = 2,
high = 1,
highest = 0
}
/**
* @public
*/
interface Extension<T extends ExtensionTyping = ExtensionTyping> {
extension: Extension | Extension[];
priority?: Priority;
_type?: T;
}
/**
* @internal
*/
type ExtractTyping<E extends Extension> = E extends Extension<infer T> ? T : never;
/**
* @public
*/
type ExtractNodes<E extends Extension> = ExtractNodesFromTyping<ExtractTyping<E>>;
/**
* @public
*/
type ExtractMarks<E extends Extension> = ExtractMarksFromTyping<ExtractTyping<E>>;
/**
* @internal
*/
type ExtractCommandArgs<E extends Extension> = ExtractCommandArgsFromTyping<ExtractTyping<E>>;
/**
* @public
*/
type ExtractCommandCreators<E extends Extension> = ToCommandCreators<ExtractCommandArgs<E>>;
/**
* @public
*/
type ExtractCommandDispatchers<E extends Extension> = ToCommandDispatcher<ExtractCommandArgs<E>>;
/**
* @internal
*/
type SimplifyExtension<E extends Extension | Extension[]> = E extends Extension[] ? Extension<ExceptEmptyValue<{
NODES: ExtractNodes<E[number]>;
MARKS: ExtractMarks<E[number]>;
COMMAND_ARGS: SimplifyUnion<ExtractCommandArgs<E[number]>>;
}>> : E;
/** @public */
interface EditorOptions<E extends Extension> {
extension: E;
}
/** @public */
declare function createEditor<E extends Extension>({ extension, }: EditorOptions<E>): Editor<E>;
/** @public */
declare class Editor<E extends Extension = any> {
private instance;
private constructor();
private afterMounted;
/** @internal */
static create(instance: any): Editor<any>;
get mounted(): boolean;
get view(): EditorView;
get schema(): Schema<ExtractNodes<E>, ExtractMarks<E>>;
get commands(): ExtractCommandDispatchers<E>;
mount(place: HTMLElement | null | undefined | void): void;
unmount(): void;
use(extension: Extension): VoidFunction;
}
/** @public */
interface FacetOptions<Input, Output> {
combine: (inputs: Input[]) => Output;
next: Facet<Output, any>;
}
/** @public */
declare class Facet<Input, Output> {
/** @internal */
readonly index: number;
/** @internal */
readonly combine: (inputs: Input[]) => Output;
/** @internal */
readonly next: Facet<Output, any> | null;
private constructor();
static define<Input, Output>({ combine, next }: FacetOptions<Input, Output>): Facet<Input, Output>;
/** @internal */
static defineSlot<Input>({ combine, }: Omit<FacetOptions<Input, Input>, 'next'>): Facet<Input, Input>;
extension(inputs: Input[]): FacetExtension<Input, Output>;
}
/** @public */
declare class FacetExtension<Input, Output> {
readonly facet: Facet<Input, Output>;
readonly inputs: Input[];
extension: Extension;
constructor(facet: Facet<Input, Output>, inputs: Input[]);
}
declare function defineExtension<E extends Extension | Extension[]>(extension: E): SimplifyExtension<E>;
/** @public */
declare function withPriority<T extends Extension>(extension: T, priority: Priority): T;
/**
* Base class for all ProseKit errors.
*/
declare class ProseKitError extends Error {
}
declare function addCommands<T extends Record<string, CommandCreator> = Record<string, CommandCreator>>(commands: T): Extension<{
COMMAND_ARGS: {
[K in keyof T]: Parameters<T[K]>;
};
}>;
/**
* Add some base commands
*
* @public
*/
declare function addBaseCommands(): Extension<{
COMMAND_ARGS: {
insertText: [{
text: string;
from?: number | undefined;
to?: number | undefined;
}];
insertNode: [{
node: ProseMirrorNode;
pos?: number | undefined;
}];
wrap: [{
nodeType: NodeType;
attrs?: Attrs | null | undefined;
}];
setBlockType: [{
nodeType: NodeType;
attrs?: Attrs | null | undefined;
from?: number | undefined;
to?: number | undefined;
}];
selectAll: [];
};
}>;
/** @public */
declare function addDoc(): Extension<{
NODES: "doc";
}>;
/** @public */
declare function addInputRule(rules: (context: {
schema: Schema;
}) => InputRule[]): Extension;
/** @public */
interface Keymap {
[key: string]: Command;
}
/** @public */
declare function addKeymap(keymap: Keymap): Extension;
/** @public */
declare function addBaseKeymap(): Extension<ExtensionTyping<string, string, CommandArgs>>;
/**
* @public
*/
interface MarkSpecOptions<M extends string = string> {
name: M;
spec: MarkSpec;
}
/**
* @public
*/
declare function addMarkSpec<Mark extends string>(options: MarkSpecOptions<Mark>): Extension<{
MARKS: Mark;
}>;
/**
* @public
*/
interface NodeSpecOptions<N extends string = string> {
name: N;
spec: NodeSpec;
topNode?: boolean;
}
/**
* @public
*/
declare function addNodeSpec<Node extends string>(options: NodeSpecOptions<Node>): Extension<{
NODES: Node;
}>;
interface NodeViewOptions {
name: string;
constructor: NodeViewConstructor;
}
declare function addNodeView(options: NodeViewOptions): Extension;
/** @public */
declare function addParagraph(): Extension<{
NODES: "paragraph";
}>;
interface StateConfigContext {
schema: Schema;
}
type StateConfigCallback = (ctx: StateConfigContext) => EditorStateConfig;
type ViewProps = Omit<DirectEditorProps, 'state'>;
/** @public */
interface PluginOptions {
plugins: Plugin[] | ((context: {
schema: Schema;
}) => Plugin[]);
}
/** @public */
declare function addPlugin({ plugins }: PluginOptions): Extension;
/** @public */
declare function addText(): Extension<{
NODES: "text";
}>;
/**
* @intneral
*/
type SimplifyUnion<T> = Simplify<UnionToIntersection<T>>;
/** @internal */
declare function getMarkType(schema: Schema, type: string | MarkType): MarkType;
/** @internal */
declare function getNodeType(schema: Schema, type: string | NodeType): NodeType;
export { CommandArgs, Editor, EditorOptions, Extension, ExtensionTyping, ExtractCommandCreators, ExtractCommandDispatchers, ExtractMarks, ExtractNodes, Facet, FacetExtension, FacetOptions, Keymap, MarkSpecOptions, NodeSpecOptions, NodeViewOptions, PluginOptions, Priority, ProseKitError, SimplifyUnion, StateConfigCallback, StateConfigContext, ViewProps, addBaseCommands, addBaseKeymap, addCommands, addDoc, addInputRule, addKeymap, addMarkSpec, addNodeSpec, addNodeView, addParagraph, addPlugin, addText, createEditor, defineExtension, getMarkType, getNodeType, toggleMark, withPriority };
export { addMark } from './_tsup-dts-rollup';
export { insertNode } from './_tsup-dts-rollup';
export { removeMark } from './_tsup-dts-rollup';
export { setBlockType } from './_tsup-dts-rollup';
export { toggleMark } from './_tsup-dts-rollup';
export { toggleNode } from './_tsup-dts-rollup';
export { Editor } from './_tsup-dts-rollup';
export { createEditor } from './_tsup-dts-rollup';
export { EditorOptions } from './_tsup-dts-rollup';
export { union } from './_tsup-dts-rollup';
export { withPriority } from './_tsup-dts-rollup';
export { ProseKitError_alias_1 as ProseKitError } from './_tsup-dts-rollup';
export { defineBaseCommands } from './_tsup-dts-rollup';
export { defineCommands } from './_tsup-dts-rollup';
export { defineDefaultState } from './_tsup-dts-rollup';
export { DefaultStateOptions } from './_tsup-dts-rollup';
export { defineDoc } from './_tsup-dts-rollup';
export { defineHistory } from './_tsup-dts-rollup';
export { defineInputRule } from './_tsup-dts-rollup';
export { defineBaseKeymap } from './_tsup-dts-rollup';
export { defineKeymap } from './_tsup-dts-rollup';
export { Keymap } from './_tsup-dts-rollup';
export { defineMarkSpec } from './_tsup-dts-rollup';
export { MarkSpecOptions } from './_tsup-dts-rollup';
export { defineNodeSpec } from './_tsup-dts-rollup';
export { NodeSpecOptions } from './_tsup-dts-rollup';
export { defineNodeView } from './_tsup-dts-rollup';
export { NodeViewOptions } from './_tsup-dts-rollup';
export { defineNodeViewEffect } from './_tsup-dts-rollup';
export { NodeViewEffectOptions } from './_tsup-dts-rollup';
export { defineParagraph } from './_tsup-dts-rollup';
export { definePlugin } from './_tsup-dts-rollup';
export { pluginFacet } from './_tsup-dts-rollup';
export { PluginPayload } from './_tsup-dts-rollup';
export { defineText } from './_tsup-dts-rollup';
export { defineUpdateHandler } from './_tsup-dts-rollup';
export { Facet } from './_tsup-dts-rollup';
export { FacetOptions } from './_tsup-dts-rollup';
export { CommandArgs } from './_tsup-dts-rollup';
export { Extension } from './_tsup-dts-rollup';
export { ExtractCommandAppliers } from './_tsup-dts-rollup';
export { ExtractCommandCreators } from './_tsup-dts-rollup';
export { ExtractMarks } from './_tsup-dts-rollup';
export { ExtractNodes } from './_tsup-dts-rollup';
export { SimplifyExtension } from './_tsup-dts-rollup';
export { ExtensionTyping } from './_tsup-dts-rollup';
export { NodeJSON } from './_tsup-dts-rollup';
export { SelectionJSON } from './_tsup-dts-rollup';
export { StateJSON } from './_tsup-dts-rollup';
export { Priority } from './_tsup-dts-rollup';
export { SimplifyUnion } from './_tsup-dts-rollup';
export { getMarkType } from './_tsup-dts-rollup';
export { getNodeType } from './_tsup-dts-rollup';
export { jsonFromElement } from './_tsup-dts-rollup';
export { jsonFromHTML } from './_tsup-dts-rollup';
export { jsonFromNode } from './_tsup-dts-rollup';
export { jsonFromState } from './_tsup-dts-rollup';
export { nodeFromElement } from './_tsup-dts-rollup';
export { nodeFromHTML } from './_tsup-dts-rollup';
export { nodeFromJSON } from './_tsup-dts-rollup';
export { stateFromJSON } from './_tsup-dts-rollup';
export { isAllSelection } from './_tsup-dts-rollup';
export { isMark } from './_tsup-dts-rollup';
export { isNodeSelection } from './_tsup-dts-rollup';
export { isProseMirrorNode } from './_tsup-dts-rollup';
export { isTextSelection } from './_tsup-dts-rollup';

@@ -1,4 +0,8 @@

// src/commands/toggle-mark.ts
import { toggleMark as baseToggleMark } from "@prosekit/pm/commands";
// src/commands/add-mark.ts
import "@prosekit/pm/model";
import "@prosekit/pm/state";
// src/utils/get-mark-type.ts
import "@prosekit/pm/model";
// src/error.ts

@@ -20,130 +24,295 @@ var ProseKitError = class extends Error {

// src/commands/add-mark.ts
function addMark(options) {
return (state, dispatch) => {
var _a, _b;
const mark = getMarkType(state.schema, options.type).create(options.attrs);
const from = (_a = options.from) != null ? _a : state.selection.from;
const to = (_b = options.to) != null ? _b : state.selection.to;
if (from > to) {
return false;
}
dispatch == null ? void 0 : dispatch(state.tr.addMark(from, to, mark));
return true;
};
}
// src/commands/insert-node.ts
import { TextSelection } from "@prosekit/pm/state";
import { insertPoint } from "@prosekit/pm/transform";
// src/utils/get-node-type.ts
import "@prosekit/pm/model";
function getNodeType(schema, type) {
if (typeof type === "string") {
const nodeType = schema.nodes[type];
if (!nodeType) {
throw new ProseKitError(`Cannot find ProseMirror node type "${type}"`);
}
return nodeType;
}
return type;
}
// src/commands/insert-node.ts
function insertNode(options) {
return (state, dispatch) => {
var _a;
const node = options.node ? options.node : options.type ? getNodeType(state.schema, options.type).createChecked(options.attrs) : null;
if (!node) {
throw new ProseKitError("You must provide either a node or a type");
}
const insertPos = insertPoint(
state.doc,
(_a = options.pos) != null ? _a : state.selection.to,
node.type
);
if (insertPos == null)
return false;
if (dispatch) {
const tr = state.tr.insert(insertPos, node);
tr.setSelection(TextSelection.near(tr.doc.resolve(insertPos)));
dispatch(tr);
}
return true;
};
}
// src/commands/remove-mark.ts
import "@prosekit/pm/model";
import "@prosekit/pm/state";
function removeMark(options) {
return (state, dispatch) => {
var _a, _b;
const markType = getMarkType(state.schema, options.type);
const mark = options.attrs ? markType.create(options.attrs) : markType;
const from = (_a = options.from) != null ? _a : state.selection.from;
const to = (_b = options.to) != null ? _b : state.selection.to;
if (from > to) {
return false;
}
dispatch == null ? void 0 : dispatch(state.tr.removeMark(from, to, mark));
return true;
};
}
// src/commands/set-block-type.ts
import "@prosekit/pm/state";
// src/utils/get-custom-selection.ts
import { TextSelection as TextSelection2 } from "@prosekit/pm/state";
function getCustomSelection(state, from, to) {
const pos = from != null ? from : to;
if (pos != null) {
const $from = state.doc.resolve(from != null ? from : pos);
const $to = state.doc.resolve(to != null ? to : pos);
return TextSelection2.between($from, $to);
}
return state.selection;
}
// src/commands/set-block-type.ts
function setBlockType(options) {
return (state, dispatch) => {
const nodeType = getNodeType(state.schema, options.type);
const selection = getCustomSelection(state, options.from, options.to);
const attrs = options.attrs;
let applicable = false;
for (let i = 0; i < selection.ranges.length && !applicable; i++) {
const {
$from: { pos: from },
$to: { pos: to }
} = selection.ranges[i];
state.doc.nodesBetween(from, to, (node, pos) => {
if (applicable)
return false;
if (!node.isTextblock || node.hasMarkup(nodeType, attrs))
return;
if (node.type == nodeType) {
applicable = true;
} else {
const $pos = state.doc.resolve(pos), index = $pos.index();
applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);
}
});
}
if (!applicable)
return false;
if (dispatch) {
const tr = state.tr;
for (const range of selection.ranges) {
const {
$from: { pos: from },
$to: { pos: to }
} = range;
tr.setBlockType(from, to, nodeType, attrs);
}
dispatch(tr.scrollIntoView());
}
return true;
};
}
// src/commands/toggle-mark.ts
function toggleMark(options) {
import { toggleMark as baseToggleMark } from "@prosekit/pm/commands";
import "@prosekit/pm/model";
import "@prosekit/pm/state";
function toggleMark({
type,
attrs
}) {
return (state, dispatch, view) => {
return baseToggleMark(
getMarkType(state.schema, options.type),
options.attrs
)(state, dispatch, view);
return baseToggleMark(getMarkType(state.schema, type), attrs)(
state,
dispatch,
view
);
};
}
// src/commands/toggle-node.ts
import { setBlockType as setBlockType2 } from "@prosekit/pm/commands";
import "@prosekit/pm/model";
import "@prosekit/pm/state";
// src/utils/attrs-match.ts
function attrsMatch(nodeOrMark, attrs) {
const currentAttrs = nodeOrMark.attrs;
for (const [key, value] of Object.entries(attrs)) {
if (currentAttrs[key] !== value) {
return false;
}
}
return true;
}
// src/utils/is-node-active.ts
function isNodeActive(state, type, attrs) {
const $pos = state.selection.$from;
const nodeType = getNodeType(state.schema, type);
for (let depth = $pos.depth; depth >= 0; depth--) {
const node = $pos.node(depth);
if (node.type === nodeType && (!attrs || attrsMatch(node, attrs))) {
return true;
}
}
return false;
}
// src/commands/toggle-node.ts
function toggleNode({
type,
attrs
}) {
return (state, dispatch, view) => {
if (isNodeActive(state, type, attrs)) {
const defaultType = state.schema.topNodeType.contentMatch.defaultType;
if (!defaultType) {
return false;
}
return setBlockType2(defaultType)(state, dispatch, view);
} else {
const nodeType = getNodeType(state.schema, type);
return setBlockType2(nodeType, attrs)(state, dispatch, view);
}
};
}
// src/editor/editor.ts
import { Schema } from "@prosekit/pm/model";
import { EditorState } from "@prosekit/pm/state";
import { Schema as Schema6 } from "@prosekit/pm/model";
import { EditorState as EditorState2 } from "@prosekit/pm/state";
import { EditorView } from "@prosekit/pm/view";
// src/types/void-function.ts
function voidFunction() {
// src/extensions/default-state.ts
import { Selection } from "@prosekit/pm/state";
// src/utils/uniq-array.ts
function uniqPush(prev, next) {
const result = [...prev];
for (const item of next) {
if (!result.includes(item)) {
result.push(item);
}
}
return result;
}
function uniqRemove(prev, next) {
const result = [...prev];
for (const item of next) {
const index = result.indexOf(item);
if (index !== -1) {
result.splice(index, 1);
}
}
return result;
}
// src/types/priority.ts
var Priority = /* @__PURE__ */ ((Priority2) => {
Priority2[Priority2["lowest"] = 4] = "lowest";
Priority2[Priority2["low"] = 3] = "low";
Priority2[Priority2["default"] = 2] = "default";
Priority2[Priority2["high"] = 1] = "high";
Priority2[Priority2["highest"] = 0] = "highest";
return Priority2;
})(Priority || {});
// src/facets/base-extension.ts
import "@prosekit/pm/model";
var BaseExtension = class {
constructor() {
this.extension = [];
}
};
// src/editor/facet.ts
var nextIndex = 0;
// src/facets/facet.ts
var facetCount = 0;
function getFacetCount() {
return facetCount;
}
var Facet = class _Facet {
constructor(combine, next) {
/** @internal */
this.index = nextIndex++;
this.combine = combine;
constructor(converter, next, singleton) {
/**
* @internal
*/
this.index = facetCount++;
/**
* @internal
*/
this.isSchema = false;
this.converter = converter;
this.next = next;
this.singleton = singleton;
}
static define({ combine, next }) {
return new _Facet(combine, next);
}
/** @internal */
static defineSlot({
combine
static define({
converter,
convert,
next,
singleton
}) {
return new _Facet(combine, null);
const converterFunction = converter ? converter : convert ? () => ({
create: convert,
update: convert
}) : null;
if (!converterFunction) {
throw new ProseKitError("Facet must have either 'convert' or 'converter'");
}
return new _Facet(converterFunction, next, singleton != null ? singleton : false);
}
extension(inputs) {
return new FacetExtension(this, inputs);
/**
* @internal
*/
static defineRootFacet(options) {
return _Facet.define(options);
}
extension(payloads) {
return new FacetExtensionImpl(this, payloads);
}
};
var FacetExtension = class {
constructor(facet, inputs) {
var FacetExtensionImpl = class extends BaseExtension {
constructor(facet, payloads) {
var _a;
super();
this.facet = facet;
this.inputs = inputs;
this.payloads = payloads;
this.schema = null;
this.hasSchema = !!(facet.isSchema || ((_a = facet.next) == null ? void 0 : _a.isSchema));
}
};
function sortFacets(unsorted) {
var _a;
const facets = unsorted.filter((val) => val);
const facetMap = [];
const inbounds = [];
let facetCount = 0;
for (const facet of facets) {
const index = facet.index;
if (facetMap[index] != null) {
continue;
}
if (inbounds[index] == null) {
inbounds[index] = 0;
}
facetCount++;
facetMap[index] = facet;
if (facet.next) {
const nextIndex2 = facet.next.index;
if (inbounds[nextIndex2] == null) {
inbounds[nextIndex2] = 0;
}
inbounds[nextIndex2] += 1;
if (facetMap[nextIndex2] == null) {
facets.push(facet.next);
}
}
}
const sortedFacets = [];
const sortedIndexes = [];
inbounds.forEach((inbound, index) => {
if (inbound === 0) {
sortedIndexes.push(index);
}
});
for (const index of sortedIndexes) {
const facet = facetMap[index];
sortedFacets.push(facet);
const nextIndex2 = (_a = facet.next) == null ? void 0 : _a.index;
if (nextIndex2 == null)
continue;
inbounds[nextIndex2] -= 1;
if (inbounds[nextIndex2] === 0) {
sortedIndexes.push(nextIndex2);
}
}
if (facetCount !== sortedFacets.length) {
throw new Error(`Facet has circular dependency`);
}
return sortedFacets;
}
// src/editor/slot.ts
import OrderedMap from "orderedmap";
var schemaSlot = Facet.defineSlot({
combine: (specs) => {
var _a;
let nodes = OrderedMap.from({});
let marks = OrderedMap.from({});
let topNode = void 0;
for (const spec of specs) {
nodes = nodes.append(spec.nodes);
marks = marks.append((_a = spec.marks) != null ? _a : {});
topNode = topNode != null ? topNode : spec.topNode;
}
return { nodes, marks, topNode };
}
});
var stateSlot = Facet.defineSlot({
combine: (callbacks) => {
// src/facets/state.ts
var stateFacet = Facet.defineRootFacet({
convert: (callbacks) => {
return (ctx) => {
var _a, _b, _c, _d, _e;
var _a, _b, _c, _d, _e, _f;
const configs = callbacks.map((cb) => cb(ctx));

@@ -160,6 +329,8 @@ const config = {

config.storedMarks = [...config.storedMarks, ...(_d = c.storedMarks) != null ? _d : []];
config.plugins = [...config.plugins, ...(_e = c.plugins) != null ? _e : []];
config.plugins = uniqPush((_e = config.plugins) != null ? _e : [], (_f = c.plugins) != null ? _f : []);
}
if (!config.doc && !config.schema) {
throw new Error("Can't create state without a schema nor a document");
throw new ProseKitError(
"Can't create state without a schema nor a document"
);
}

@@ -173,9 +344,114 @@ if (config.doc) {

});
var viewSlot = Facet.defineSlot({
combine: (props) => {
return Object.assign({}, ...props);
// src/utils/parse.ts
import { DOMParser } from "@prosekit/pm/model";
import { EditorState } from "@prosekit/pm/state";
// src/utils/get-dom-api.ts
function getGlobalBrowserDocument() {
if (typeof document !== "undefined") {
return document;
}
});
var commandSlot = Facet.defineSlot({
combine: (inputs) => {
if (typeof globalThis !== "undefined" && globalThis.document) {
return globalThis.document;
}
}
function getGlobalBrowserWindow() {
if (typeof window !== "undefined") {
return window;
}
if (typeof globalThis !== "undefined" && globalThis.window) {
return globalThis.window;
}
}
function getBrowserWindow() {
var _a;
const win = getGlobalBrowserWindow();
if (win) {
return win;
}
return (_a = getGlobalBrowserDocument()) == null ? void 0 : _a.defaultView;
}
// src/utils/parse.ts
function nodeFromElement(element, schema) {
return DOMParser.fromSchema(schema).parse(element);
}
function jsonFromElement(element, schema) {
return jsonFromNode(nodeFromElement(element, schema));
}
function nodeFromHTML(html, schema) {
return nodeFromElement(elementFromHTML(html), schema);
}
function jsonFromHTML(html, schema) {
return jsonFromElement(elementFromHTML(html), schema);
}
function elementFromHTML(html) {
const win = getBrowserWindow();
if (!win) {
throw new ProseKitError(
"No Browser Document Found. You can only parse a HTML string in the browser environment."
);
}
const parser = new win.DOMParser();
return parser.parseFromString(`<body>${html}</body>`, "text/html").body;
}
function jsonFromState(state) {
return state.toJSON();
}
function jsonFromNode(node) {
return node.toJSON();
}
function nodeFromJSON(json, schema) {
return schema.nodeFromJSON(json);
}
function stateFromJSON(json, schema) {
return EditorState.fromJSON({ schema }, json);
}
// src/extensions/default-state.ts
function defineDefaultState({
defaultDoc,
defaultHTML,
defaultSelection
}) {
if (defaultHTML && defaultDoc) {
throw new ProseKitError(
"Only one of defaultHTML and defaultDoc can be provided"
);
}
return stateFacet.extension([
({ schema }) => {
const config = {};
if (defaultHTML) {
if (typeof defaultHTML === "string") {
defaultDoc = jsonFromHTML(defaultHTML, schema);
} else {
defaultDoc = jsonFromElement(defaultHTML, schema);
}
}
if (defaultDoc) {
config.doc = schema.nodeFromJSON(defaultDoc);
if (defaultSelection) {
config.selection = Selection.fromJSON(config.doc, defaultSelection);
}
}
return config;
}
]);
}
// src/types/priority.ts
var Priority = /* @__PURE__ */ ((Priority2) => {
Priority2[Priority2["lowest"] = 4] = "lowest";
Priority2[Priority2["low"] = 3] = "low";
Priority2[Priority2["default"] = 2] = "default";
Priority2[Priority2["high"] = 1] = "high";
Priority2[Priority2["highest"] = 0] = "highest";
return Priority2;
})(Priority || {});
// src/facets/command.ts
var commandFacet = Facet.defineRootFacet({
convert: (inputs) => {
return Object.assign({}, ...inputs);

@@ -185,4 +461,68 @@ }

// src/editor/flatten.ts
function flatten(root) {
// src/facets/schema.ts
import OrderedMap from "orderedmap";
var schemaFacet = Facet.defineRootFacet({
convert: (specs) => {
var _a;
let nodes = OrderedMap.from({});
let marks = OrderedMap.from({});
let topNode = void 0;
for (const spec of specs) {
nodes = nodes.append(spec.nodes);
marks = marks.append((_a = spec.marks) != null ? _a : {});
topNode = topNode != null ? topNode : spec.topNode;
}
return { nodes, marks, topNode };
}
});
schemaFacet.isSchema = true;
// src/facets/view.ts
var viewFacet = Facet.defineRootFacet({
convert: (props) => {
return Object.assign({}, ...props);
}
});
// src/facets/flatten.ts
function flattenInputTuple(inputTuple) {
return [
...inputTuple[0],
...inputTuple[1],
...inputTuple[2],
...inputTuple[3],
...inputTuple[4]
];
}
function mergeInputTuple(tupleA, tupleB) {
if (!tupleA)
return tupleB;
if (!tupleB)
return tupleA;
const [a0, a1, a2, a3, a4] = tupleA;
const [b0, b1, b2, b3, b4] = tupleB;
return [
uniqPush(a0, b0),
uniqPush(a1, b1),
uniqPush(a2, b2),
uniqPush(a3, b3),
uniqPush(a4, b4)
];
}
function removeInputTuple(tupleA, tupleB) {
if (!tupleA)
return [[], [], [], [], []];
if (!tupleB)
return tupleA;
const [a0, a1, a2, a3, a4] = tupleA;
const [b0, b1, b2, b3, b4] = tupleB;
return [
uniqRemove(a0, b0),
uniqRemove(a1, b1),
uniqRemove(a2, b2),
uniqRemove(a3, b3),
uniqRemove(a4, b4)
];
}
function extractFacets(root) {
var _a;

@@ -192,14 +532,14 @@ const extensions = [root];

const facets = [];
const inputs = [];
const payloads = [];
while (extensions.length > 0) {
const ext = extensions.pop();
const pri = priorities.pop();
if (ext instanceof FacetExtension) {
if (ext instanceof FacetExtensionImpl) {
const facet = ext.facet;
if (!facets[facet.index]) {
facets[facet.index] = facet;
inputs[facet.index] = [[], [], [], [], []];
payloads[facet.index] = [[], [], [], [], []];
}
const facetInputs = ext.inputs;
inputs[facet.index][pri].push(...facetInputs);
const facetPayloads = ext.payloads;
payloads[facet.index][pri].push(...facetPayloads);
} else if (ext.extension) {

@@ -217,5 +557,11 @@ const p = (_a = ext.priority) != null ? _a : pri;

} else {
throw new Error("Invalid extension");
throw new ProseKitError("Invalid extension");
}
}
return [facets, payloads];
}
function updateExtension(prevInputs, prevConverters, extension, mode) {
var _a;
const modifyInputTuple = mode === "add" ? mergeInputTuple : removeInputTuple;
const [facets, inputs] = extractFacets(extension);
let schemaInput = null;

@@ -225,36 +571,89 @@ let stateInput = null;

let commandInput = null;
const sortedFacets = sortFacets(facets);
for (const facet of sortedFacets) {
for (let index = getFacetCount(); index >= 0; index--) {
const facet = facets[index];
if (!facet) {
continue;
}
const nextFacet = facet.next;
if (nextFacet) {
facets[_a = nextFacet.index] || (facets[_a] = nextFacet);
}
if (!inputs[facet.index]) {
continue;
}
const inputTuple = modifyInputTuple(prevInputs[index], inputs[index]);
prevInputs[index] = inputTuple;
if (facet.next && !facet.singleton) {
let hasOutput = false;
const outputTuple = [[], [], [], [], []];
for (let pri = 0; pri < 5; pri++) {
const input = inputs[facet.index][pri];
if (input.length > 0) {
const output = facet.combine(input);
if (!inputs[nextFacet.index]) {
inputs[nextFacet.index] = [[], [], [], [], []];
}
inputs[nextFacet.index][pri].push(output);
const inputArray = inputTuple[pri];
if (inputArray.length === 0) {
continue;
}
const converterTuple = prevConverters[index] || (prevConverters[index] = [
void 0,
void 0,
void 0,
void 0,
void 0
]);
const prevConverter = converterTuple[pri];
const converter = prevConverter || facet.converter();
prevConverters[index][pri] = converter;
const output = prevConverter ? converter.update(inputArray) : converter.create(inputArray);
if (!output) {
continue;
}
hasOutput = true;
outputTuple[pri].push(output);
}
} else if (inputs[facet.index]) {
const [i1, i2, i3, i4, i5] = inputs[facet.index];
const jointInputs = [...i1, ...i2, ...i3, ...i4, ...i5];
const output = facet.combine(jointInputs);
switch (facet) {
case schemaSlot:
schemaInput = output;
break;
case stateSlot:
stateInput = output;
break;
case viewSlot:
viewInput = output;
break;
case commandSlot:
commandInput = output;
break;
default:
throw new Error("Invalid facet");
if (!hasOutput) {
continue;
}
inputs[facet.next.index] = modifyInputTuple(
inputs[facet.next.index],
outputTuple
);
continue;
} else {
const inputArray = flattenInputTuple(inputTuple);
prevConverters[index] || (prevConverters[index] = [
void 0,
void 0,
void 0,
void 0,
void 0
]);
const prevConverter = prevConverters[index][2 /* default */];
const converter = prevConverter || facet.converter();
prevConverters[index][2 /* default */] = converter;
const output = prevConverter ? converter.update(inputArray) : converter.create(inputArray);
if (!output) {
continue;
}
if (facet.next) {
const outputTuple = [[], [], [output], [], []];
inputs[facet.next.index] = modifyInputTuple(
inputs[facet.next.index],
outputTuple
);
} else {
switch (facet) {
case schemaFacet:
schemaInput = output;
break;
case stateFacet:
stateInput = output;
break;
case viewFacet:
viewInput = output;
break;
case commandFacet:
commandInput = output;
break;
default:
throw new ProseKitError("Invalid root facet");
}
}
}

@@ -265,37 +664,251 @@ }

// src/utils/type-assertion.ts
import { Mark, ProseMirrorNode } from "@prosekit/pm/model";
import {
AllSelection,
NodeSelection,
TextSelection as TextSelection3
} from "@prosekit/pm/state";
function isProseMirrorNode(node) {
return node instanceof ProseMirrorNode;
}
function isMark(mark) {
return mark instanceof Mark;
}
function isTextSelection(sel) {
return sel instanceof TextSelection3;
}
function isNodeSelection(sel) {
return sel instanceof NodeSelection;
}
function isAllSelection(sel) {
return sel instanceof AllSelection;
}
// src/utils/is-mark-active.ts
function isMarkActive(state, type, attrs) {
const markType = getMarkType(state.schema, type);
const mark = attrs ? markType.create(attrs) : markType;
const { from, $from, to, empty } = state.selection;
if (empty) {
return hasMark(state.storedMarks || $from.marks(), mark);
} else {
return state.doc.rangeHasMark(from, to, mark);
}
}
function hasMark(marks, mark) {
if (marks.length === 0) {
return false;
}
if (isMark(mark)) {
return marks.some((m) => m.eq(mark));
} else {
return marks.some((m) => m.type === mark);
}
}
// src/editor/builder.ts
import "@prosekit/pm/model";
function createNodeBuilder(getState, type) {
const builder = (...args) => buildNode(type, args);
builder.isActive = (attrs) => {
const state = getState();
return state ? isNodeActive(state, type, attrs) : false;
};
return builder;
}
function createMarkBuilder(getState, type) {
const builder = (...args) => buildMark(type, args);
builder.isActive = (attrs) => {
const state = getState();
return state ? isMarkActive(state, type, attrs) : false;
};
return builder;
}
function buildMark(type, args) {
const [attrs, children] = normalizeArgs(args);
return flattenChildren(type.schema, children, type.create(attrs));
}
function buildNode(type, args) {
const [attrs, children] = normalizeArgs(args);
const node = type.createAndFill(attrs, flattenChildren(type.schema, children));
if (!node) {
throw new ProseKitError(`Couldn't create node ${type.name}`);
}
return node;
}
function flattenChildren(schema, children, mark) {
const nodes = [];
for (const child of children) {
if (typeof child === "string") {
if (child) {
nodes.push(schema.text(child, mark ? [mark] : null));
}
} else if (Array.isArray(child)) {
nodes.push(...flattenChildren(schema, child, mark));
} else if (isProseMirrorNode(child)) {
nodes.push(mark ? child.mark(mark.addToSet(child.marks)) : child);
} else {
throw new ProseKitError(`Invalid node child: ${typeof child}`);
}
}
return nodes;
}
function normalizeArgs(args) {
const [attrs, ...children] = args;
if (isNodeChild(attrs)) {
children.unshift(attrs);
return [null, children];
} else if (typeof attrs === "object") {
return [attrs, children];
} else {
return [null, children];
}
}
function isNodeChild(value) {
if (!value) {
return false;
}
return typeof value === "string" || Array.isArray(value) || isProseMirrorNode(value);
}
// src/facets/union-extension.ts
import { Schema as Schema5 } from "@prosekit/pm/model";
var UnionExtensionImpl = class extends BaseExtension {
constructor(extension = []) {
super();
this.extension = extension;
this._schema = void 0;
this.hasSchemaCount = 0;
for (const e of extension) {
if (e instanceof BaseExtension) {
this.hasSchemaCount += e.hasSchema ? 1 : 0;
} else {
throw new ProseKitError("Invalid extension");
}
}
}
get hasSchema() {
return this.hasSchemaCount > 0;
}
get schema() {
var _a;
if (this._schema !== void 0) {
return this._schema;
}
if (this.hasSchemaCount === 0) {
this._schema = null;
return this._schema;
}
if (this.hasSchemaCount === 1) {
const schema = (_a = this.extension.find((e) => e.hasSchema)) == null ? void 0 : _a.schema;
if (schema) {
this._schema = schema;
return this._schema;
}
}
const { schemaInput } = updateExtension([], [], this, "add");
this._schema = schemaInput ? new Schema5(schemaInput) : null;
return this._schema;
}
};
// src/editor/union.ts
function union(extension) {
const array = Array.isArray(extension) ? extension : [extension];
return new UnionExtensionImpl(
array
);
}
// src/editor/editor.ts
function createEditor({
extension
extension,
defaultDoc,
defaultHTML,
defaultSelection
}) {
const { schemaInput, stateInput, viewInput, commandInput } = flatten(extension);
if (!schemaInput) {
throw new Error("Schema must be defined");
if (defaultDoc || defaultHTML) {
extension = union([
extension,
defineDefaultState({
defaultDoc,
defaultHTML,
defaultSelection
})
]);
}
const schema = new Schema(schemaInput);
const stateConfig = stateInput ? stateInput({ schema }) : { schema };
const state = EditorState.create(stateConfig);
const directEditorProps = { state, ...viewInput };
const instance = new EditorInstance(directEditorProps);
if (commandInput) {
for (const [name, commandCreator] of Object.entries(commandInput)) {
instance.addCommand(name, commandCreator);
}
}
return Editor.create(instance);
return Editor.create(new EditorInstance(extension));
}
var EditorInstance = class {
constructor(directEditorProps) {
this.directEditorProps = directEditorProps;
constructor(extension) {
this.view = null;
this.commandDispatchers = {};
this.commandAppliers = {};
this.payloads = [];
this.converters = [];
this.mount = this.mount.bind(this);
this.unmount = this.unmount.bind(this);
this.schema = directEditorProps.state.schema;
const { schemaInput, stateInput, viewInput, commandInput } = updateExtension(this.payloads, this.converters, extension, "add");
if (!schemaInput) {
throw new ProseKitError("Schema must be defined");
}
const schema = new Schema6(schemaInput);
const stateConfig = stateInput ? stateInput({ schema }) : { schema };
const state = EditorState2.create(stateConfig);
if (commandInput) {
for (const [name, commandCreator] of Object.entries(commandInput)) {
this.defineCommand(name, commandCreator);
}
}
this.directEditorProps = { state, ...viewInput };
this.schema = this.directEditorProps.state.schema;
const getState = () => {
var _a;
return (_a = this.view) == null ? void 0 : _a.state;
};
this.nodeBuilders = Object.fromEntries(
Object.values(this.schema.nodes).map((type) => [
type.name,
createNodeBuilder(getState, type)
])
);
this.markBuilders = Object.fromEntries(
Object.values(this.schema.marks).map((type) => [
type.name,
createMarkBuilder(getState, type)
])
);
}
updateExtension(extension, mode) {
var _a;
const { schemaInput, stateInput, viewInput, commandInput } = updateExtension(this.payloads, this.converters, extension, mode);
if (schemaInput) {
throw new ProseKitError("Schema cannot be changed");
}
if (viewInput) {
throw new ProseKitError("View cannot be changed");
}
const plugins = (_a = stateInput == null ? void 0 : stateInput({ schema: this.schema })) == null ? void 0 : _a.plugins;
if (plugins && plugins.length > 0) {
if (!this.view) {
throw new ProseKitError(
"Unexpected inner state: EditorInstance.view is not defined"
);
}
const state = this.view.state.reconfigure({ plugins });
this.view.updateState(state);
}
if (commandInput) {
const names = Object.keys(commandInput);
for (const name of names) {
this.defineCommand(name, commandInput[name]);
}
}
}
mount(place) {
if (this.view) {
throw new Error("Editor is already mounted");
throw new ProseKitError("Editor is already mounted");
}
if (!place) {
throw new Error("Can't mount editor without a place");
throw new ProseKitError("Can't mount editor without a place");
}

@@ -306,3 +919,3 @@ this.view = new EditorView({ mount: place }, this.directEditorProps);

if (!this.view) {
throw new Error("Editor is not mounted yet");
throw new ProseKitError("Editor is not mounted yet");
}

@@ -313,7 +926,8 @@ this.view.destroy();

get assertView() {
if (!this.view)
throw new Error("Editor is not mounted");
if (!this.view) {
throw new ProseKitError("Editor is not mounted");
}
return this.view;
}
addPlugins(plugins) {
definePlugins(plugins) {
const view = this.assertView;

@@ -334,12 +948,23 @@ const state = view.state;

}
addCommand(name, commandCreator) {
const dispatcher = (...args) => {
const view = this.assertView;
defineCommand(name, commandCreator) {
const applier = (...args) => {
const view = this.view;
if (!view) {
return false;
}
const command = commandCreator(...args);
return command(view.state, view.dispatch.bind(view), view);
};
this.commandDispatchers[name] = dispatcher;
applier.canApply = (...args) => {
const view = this.view;
if (!view) {
return false;
}
const command = commandCreator(...args);
return command(view.state, void 0, view);
};
this.commandAppliers[name] = applier;
}
removeCommand(name) {
delete this.commandDispatchers[name];
delete this.commandAppliers[name];
}

@@ -355,6 +980,8 @@ };

}
/** @internal */
/**
* @internal
*/
static create(instance) {
if (!(instance instanceof EditorInstance)) {
throw new TypeError("Editor's instance is not EditorInstance");
throw new TypeError("Invalid EditorInstance");
}

@@ -373,3 +1000,3 @@ return new _Editor(instance);

get commands() {
return this.instance.commandDispatchers;
return this.instance.commandAppliers;
}

@@ -399,118 +1026,89 @@ mount(place) {

}
const { schemaInput, stateInput, viewInput, commandInput } = flatten(extension);
if (schemaInput) {
throw new ProseKitError("Schema cannot be changed");
}
if (viewInput) {
throw new ProseKitError("View cannot be changed");
}
if (stateInput) {
const stateConfig = stateInput({ schema: this.schema });
const plugins = stateConfig.plugins;
if (plugins && plugins.length > 0) {
this.instance.addPlugins(plugins);
return () => this.instance.removePlugins(plugins);
}
}
if (commandInput) {
const names = Object.keys(commandInput);
for (const name of names) {
this.instance.addCommand(name, commandInput[name]);
}
return () => {
for (const name of names) {
this.instance.removeCommand(name);
}
};
}
return voidFunction;
this.instance.updateExtension(extension, "add");
return () => this.instance.updateExtension(extension, "remove");
}
/**
* @deprecated
*/
isNodeActive(nodeType, attrs) {
return isNodeActive(this.view.state, nodeType, attrs);
}
/**
* @deprecated
*/
isMarkActive(markType, attrs) {
return isMarkActive(this.view.state, markType, attrs);
}
get nodes() {
return this.instance.nodeBuilders;
}
get marks() {
return this.instance.markBuilders;
}
};
// src/editor/type-utils.ts
function defineExtension(extension) {
if (extension && Array.isArray(extension)) {
return { extension };
}
return extension;
}
// src/editor/with-priority.ts
function withPriority(extension, priority) {
return { extension, priority };
const result = union(extension);
result.priority = priority;
return result;
}
// src/commands/insert-text.ts
function insertText({
text,
from,
to
}) {
return (state, dispatch) => {
if (text) {
dispatch == null ? void 0 : dispatch(state.tr.insertText(text, from, to));
}
return true;
};
}
// src/commands/select-all.ts
import { AllSelection as AllSelection2 } from "@prosekit/pm/state";
function selectAll() {
return (state, dispatch) => {
dispatch == null ? void 0 : dispatch(state.tr.setSelection(new AllSelection2(state.doc)));
return true;
};
}
// src/commands/wrap.ts
import "@prosekit/pm/model";
import "@prosekit/pm/state";
import { findWrapping } from "@prosekit/pm/transform";
function wrap({
nodeType,
attrs
}) {
return (state, dispatch) => {
const { $from, $to } = state.selection;
const range = $from.blockRange($to);
if (!range)
return false;
const wrapping = findWrapping(range, nodeType, attrs);
if (!wrapping)
return false;
dispatch == null ? void 0 : dispatch(state.tr.wrap(range, wrapping));
return true;
};
}
// src/extensions/command.ts
import { AllSelection, Selection } from "@prosekit/pm/state";
import { findWrapping, insertPoint } from "@prosekit/pm/transform";
function addCommands(commands) {
return commandSlot.extension([commands]);
function defineCommands(commands) {
return commandFacet.extension([commands]);
}
function addBaseCommands() {
return addCommands({
insertText: ({
text,
from,
to
}) => {
return (state, dispatch) => {
if (text) {
dispatch == null ? void 0 : dispatch(state.tr.insertText(text, from, to));
}
return true;
};
},
insertNode: ({ node, pos }) => {
return (state, dispatch) => {
const insertPos = insertPoint(
state.doc,
pos != null ? pos : state.selection.to,
node.type
);
if (insertPos == null)
return false;
if (dispatch) {
const tr = state.tr.insert(insertPos, node);
const $pos = tr.doc.resolve(insertPos);
tr.setSelection(Selection.near($pos));
dispatch(tr);
}
return true;
};
},
wrap: ({
nodeType,
attrs
}) => {
return (state, dispatch) => {
const { $from, $to } = state.selection;
const range = $from.blockRange($to);
if (!range)
return false;
const wrapping = findWrapping(range, nodeType, attrs);
if (!wrapping)
return false;
dispatch == null ? void 0 : dispatch(state.tr.wrap(range, wrapping));
return true;
};
},
setBlockType: ({
nodeType,
attrs,
from,
to
}) => {
return (state, dispatch) => {
from = from != null ? from : state.selection.from;
to = from != null ? from : state.selection.from;
dispatch == null ? void 0 : dispatch(state.tr.setBlockType(from, to, nodeType, attrs));
return true;
};
},
selectAll: () => {
return (state, dispatch) => {
dispatch == null ? void 0 : dispatch(state.tr.setSelection(new AllSelection(state.doc)));
return true;
};
}
function defineBaseCommands() {
return defineCommands({
insertText,
insertNode,
wrap,
setBlockType,
selectAll,
addMark,
removeMark
});

@@ -520,48 +1118,60 @@ }

// src/extensions/node-spec.ts
function addNodeSpec(options) {
function defineNodeSpec(options) {
return nodeSpecFacet.extension([options]);
}
var nodeSpecFacet = Facet.define({
combine: (options) => {
convert: (options) => {
const nodes = {};
let topNode = void 0;
for (const { name, spec, topNode: isTopNode } of options) {
let topNodeName = void 0;
for (const { name, topNode, ...spec } of options) {
if (nodes[name]) {
throw new Error(`Node type ${name} has already been defined`);
throw new ProseKitError(`Node type ${name} has already been defined`);
}
if (topNodeName && !topNode) {
topNodeName = name;
}
nodes[name] = spec;
if (isTopNode && !topNode) {
topNode = name;
}
}
return { nodes, topNode };
return { nodes, topNode: topNodeName };
},
next: schemaSlot
next: schemaFacet
});
// src/extensions/doc.ts
function addDoc() {
return addNodeSpec({
function defineDoc() {
return defineNodeSpec({
name: "doc",
spec: {
content: "block+"
}
content: "block+",
topNode: true
});
}
// src/extensions/input-rules.ts
import { inputRules } from "@prosekit/pm/inputrules";
// src/extensions/history.ts
import { history, redo, undo } from "@prosekit/pm/history";
// src/utils/env.ts
var isMac = typeof navigator !== "undefined" ? /Mac|iP(hone|[ao]d)/.test(navigator.platform) : false;
// src/extensions/keymap.ts
import { baseKeymap, chainCommands } from "@prosekit/pm/commands";
import { keydownHandler } from "@prosekit/pm/keymap";
import { Plugin as Plugin3, PluginKey } from "@prosekit/pm/state";
// src/extensions/plugin.ts
function addPlugin({ plugins }) {
if (typeof plugins === "function") {
return pluginFacet.extension([plugins]);
} else if (Array.isArray(plugins)) {
return pluginFacet.extension([() => plugins]);
} else {
throw new TypeError("plugins must be a function or an array");
import "@prosekit/pm/model";
import { Plugin as Plugin2 } from "@prosekit/pm/state";
function definePlugin(plugin) {
if (plugin instanceof Plugin2) {
return pluginFacet.extension([() => [plugin]]);
}
if (Array.isArray(plugin) && plugin.every((p) => p instanceof Plugin2)) {
return pluginFacet.extension([() => plugin]);
}
if (typeof plugin === "function") {
return pluginFacet.extension([plugin]);
}
throw new TypeError("Invalid plugin");
}
var pluginFacet = Facet.define({
combine: (callbacks) => {
convert: (callbacks) => {
return ({ schema }) => {

@@ -572,35 +1182,38 @@ const plugins = callbacks.flatMap((func) => func({ schema }));

},
next: stateSlot
next: stateFacet
});
// src/extensions/input-rules.ts
function addInputRule(rules) {
return inputRuleFacet.extension([rules]);
}
var inputRuleFacet = Facet.define({
combine: (inputs) => {
return (context) => {
const rules = inputs.flatMap((callback) => callback(context));
return [inputRules({ rules })];
};
},
next: pluginFacet
});
// src/extensions/keymap.ts
import { baseKeymap, chainCommands } from "@prosekit/pm/commands";
import { keymap as createKeymapPlugin } from "@prosekit/pm/keymap";
function addKeymap(keymap) {
function defineKeymap(keymap) {
return keymapFacet.extension([keymap]);
}
function addBaseKeymap() {
return addKeymap(baseKeymap);
function defineBaseKeymap() {
return defineKeymap(baseKeymap);
}
var keymapFacet = Facet.define({
combine: (keymaps) => {
const keymap = mergeKeymaps(keymaps);
const plugin = createKeymapPlugin(keymap);
return () => [plugin];
converter: () => {
let handler = null;
const handlerWrapper = (view, event) => {
if (handler)
return handler(view, event);
return false;
};
const plugin = new Plugin3({
key: keymapPluginKey,
props: { handleKeyDown: handlerWrapper }
});
const pluginFunc = () => [plugin];
return {
create: (keymaps) => {
handler = keydownHandler(mergeKeymaps(keymaps));
return pluginFunc;
},
update: (keymaps) => {
handler = keydownHandler(mergeKeymaps(keymaps));
return null;
}
};
},
next: pluginFacet
next: pluginFacet,
singleton: true
});

@@ -611,5 +1224,4 @@ function mergeKeymaps(keymaps) {

for (const [key, command] of Object.entries(keymap)) {
if (!bindings[key])
bindings[key] = [];
bindings[key].push(command);
const commands = bindings[key] || (bindings[key] = []);
commands.push(command);
}

@@ -624,13 +1236,59 @@ }

}
var keymapPluginKey = new PluginKey("prosekit-keymap");
// src/extensions/history.ts
function defineHistory() {
const keymap = {
"Mod-z": undo,
"Shift-Mod-z": redo
};
if (!isMac) {
keymap["Mod-y"] = redo;
}
return union([
definePlugin(history()),
defineKeymap(keymap),
defineCommands({
undo: () => undo,
redo: () => redo
})
]);
}
// src/extensions/input-rules.ts
import { InputRule, inputRules } from "@prosekit/pm/inputrules";
import "@prosekit/pm/model";
import "@prosekit/pm/state";
function defineInputRule(rule) {
if (rule instanceof InputRule) {
return inputRuleFacet.extension([() => rule]);
}
if (Array.isArray(rule) && rule.every((r) => r instanceof InputRule)) {
return inputRuleFacet.extension([() => rule]);
}
if (typeof rule === "function") {
return inputRuleFacet.extension([rule]);
}
throw new TypeError("Invalid input rule");
}
var inputRuleFacet = Facet.define({
convert: (inputs) => {
return (context) => {
const rules = inputs.flatMap((callback) => callback(context));
return [inputRules({ rules })];
};
},
next: pluginFacet
});
// src/extensions/mark-spec.ts
function addMarkSpec(options) {
function defineMarkSpec(options) {
return markSpecFacet.extension([options]);
}
var markSpecFacet = Facet.define({
combine: (options) => {
convert: (options) => {
const marks = {};
for (const { name, spec } of options) {
for (const { name, ...spec } of options) {
if (marks[name]) {
throw new Error(`Mark type ${name} has already been defined`);
throw new ProseKitError(`Mark type ${name} has already been defined`);
}

@@ -641,12 +1299,13 @@ marks[name] = spec;

},
next: schemaSlot
next: schemaFacet
});
// src/extensions/node-view.ts
import { Plugin as Plugin2 } from "@prosekit/pm/state";
function addNodeView(options) {
import { ProseMirrorPlugin } from "@prosekit/pm/state";
import "@prosekit/pm/view";
function defineNodeView(options) {
return nodeViewFacet.extension([options]);
}
var nodeViewFacet = Facet.define({
combine: (inputs) => {
convert: (inputs) => {
const nodeViews = {};

@@ -658,3 +1317,3 @@ for (const input of inputs) {

}
return () => [new Plugin2({ props: { nodeViews } })];
return () => [new ProseMirrorPlugin({ props: { nodeViews } })];
},

@@ -664,62 +1323,148 @@ next: pluginFacet

// src/extensions/node-view-effect.ts
import { ProseMirrorPlugin as ProseMirrorPlugin2 } from "@prosekit/pm/state";
import "@prosekit/pm/view";
function defineNodeViewEffect(options) {
return nodeViewEffectFacet.extension([options]);
}
var nodeViewEffectFacet = Facet.define({
convert: (inputs) => {
const nodeViews = {};
const options = {};
const factories = {};
for (const input of inputs) {
const group = input.group;
if (input.name == null) {
factories[group] = input.factory;
} else {
options[group] || (options[group] = []);
options[group].push({
name: input.name,
args: input.args
});
}
}
for (const [group, factory] of Object.entries(factories)) {
const groupOptions = options[group] || [];
for (const { name, args } of groupOptions) {
nodeViews[name] = factory(args);
}
}
return () => Object.keys(nodeViews).length > 0 ? [new ProseMirrorPlugin2({ props: { nodeViews } })] : [];
},
next: pluginFacet
});
// src/extensions/paragraph.ts
function addParagraph() {
return addNodeSpec({
function defineParagraphSpec() {
return defineNodeSpec({
name: "paragraph",
spec: {
content: "inline*",
group: "block",
parseDOM: [{ tag: "p" }],
toDOM() {
return ["p", 0];
}
content: "inline*",
group: "block",
parseDOM: [{ tag: "p" }],
toDOM() {
return ["p", 0];
}
});
}
function defineParagraph() {
return withPriority(defineParagraphSpec(), 0 /* highest */);
}
// src/extensions/text.ts
function addText() {
return addNodeSpec({
function defineText() {
return defineNodeSpec({
name: "text",
spec: {
group: "inline"
}
group: "inline"
});
}
// src/utils/get-node-type.ts
function getNodeType(schema, type) {
if (typeof type === "string") {
const nodeType = schema.nodes[type];
if (!nodeType) {
throw new ProseKitError(`Cannot find ProseMirror node type "${type}"`);
}
return nodeType;
}
return type;
// src/extensions/update-handler.ts
import { PluginKey as PluginKey2, ProseMirrorPlugin as ProseMirrorPlugin3 } from "@prosekit/pm/state";
// src/utils/is-not-null.ts
function isNotNull(value) {
return value != null;
}
// src/extensions/update-handler.ts
function defineUpdateHandler(handler) {
return updateHandlerFacet.extension([handler]);
}
var updateHandlerFacet = Facet.define({
converter: () => {
let updateHandlers = [];
const plugin = new ProseMirrorPlugin3({
key: pluginKey,
view: (view) => {
updateHandlers.forEach((fn) => fn({ view }));
return {
update: (view2, prevState) => {
updateHandlers.forEach((fn) => fn({ view: view2, prevState }));
}
};
}
});
const pluginFunc = () => [plugin];
return {
create: (handlers) => {
updateHandlers = handlers.filter(isNotNull);
return pluginFunc;
},
update: (handlers) => {
updateHandlers = handlers.filter(isNotNull);
return null;
}
};
},
next: pluginFacet,
singleton: true
});
var pluginKey = new PluginKey2("prosekit-event-handler");
export {
Editor,
Facet,
FacetExtension,
Priority,
ProseKitError,
addBaseCommands,
addBaseKeymap,
addCommands,
addDoc,
addInputRule,
addKeymap,
addMarkSpec,
addNodeSpec,
addNodeView,
addParagraph,
addPlugin,
addText,
addMark,
createEditor,
defineExtension,
defineBaseCommands,
defineBaseKeymap,
defineCommands,
defineDefaultState,
defineDoc,
defineHistory,
defineInputRule,
defineKeymap,
defineMarkSpec,
defineNodeSpec,
defineNodeView,
defineNodeViewEffect,
defineParagraph,
definePlugin,
defineText,
defineUpdateHandler,
getMarkType,
getNodeType,
insertNode,
isAllSelection,
isMark,
isNodeSelection,
isProseMirrorNode,
isTextSelection,
jsonFromElement,
jsonFromHTML,
jsonFromNode,
jsonFromState,
nodeFromElement,
nodeFromHTML,
nodeFromJSON,
pluginFacet,
removeMark,
setBlockType,
stateFromJSON,
toggleMark,
toggleNode,
union,
withPriority
};
{
"name": "@prosekit/core",
"type": "module",
"version": "0.0.0-next-20230709094459",
"version": "0.0.0-next-20231120040948",
"private": false,

@@ -41,11 +41,11 @@ "author": {

"dependencies": {
"@prosekit/pm": "0.0.0-next-20230709094459",
"@prosekit/pm": "0.0.0-next-20231120040948",
"orderedmap": "^2.1.1",
"type-fest": "^3.12.0"
"type-fest": "^4.8.0"
},
"devDependencies": {
"@prosekit/dev": "*",
"tsup": "^7.1.0",
"typescript": "^5.1.6",
"vitest": "^0.33.0"
"tsup": "^8.0.0",
"typescript": "^5.2.2",
"vitest": "^0.34.6"
},

@@ -52,0 +52,0 @@ "scripts": {

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc