How to use prosemirror-state - 10 common examples

To help you get started, we’ve selected a few prosemirror-state examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github guardian / prosemirror-noting / src / js / index.ts View on Github external
setTimeout(() => {
      const pluginState: PluginState = plugin.getState(localView.state);
      // If there's already a validation in flight, defer validation
      // for another throttle tick
      if (pluginState.validationInFlight) {
        return scheduleValidation();
      }
      localView.dispatch(
        localView.state.tr.setMeta(
          VALIDATION_PLUGIN_ACTION,
          validationRequestStart()
        )
      );
    }, plugin.getState(localView.state).currentThrottle);
  };
  const plugin: Plugin = new Plugin({
    state: {
      init(_, { doc }): PluginState {
        // getValidationRangesForDocument(doc);

        // Hook up our validation events.
        validationService.on(
          ValidationEvents.VALIDATION_SUCCESS,
          (validationResponse: ValidationResponse) =>
            localView.dispatch(
              localView.state.tr.setMeta(
                VALIDATION_PLUGIN_ACTION,
                validationRequestSuccess(validationResponse)
              )
            )
        );
        validationService.on(
github ProseMirror / website / example / upload / index.js View on Github external
// placeholderPlugin{
import {Plugin} from "prosemirror-state"
import {Decoration, DecorationSet} from "prosemirror-view"

let placeholderPlugin = new Plugin({
  state: {
    init() { return DecorationSet.empty },
    apply(tr, set) {
      // Adjust decoration positions to changes made by the transaction
      set = set.map(tr.mapping, tr.doc)
      // See if the transaction adds or removes any placeholders
      let action = tr.getMeta(this)
      if (action && action.add) {
        let widget = document.createElement("placeholder")
        let deco = Decoration.widget(action.add.pos, widget, {id: action.add.id})
        set = set.add(tr.doc, [deco])
      } else if (action && action.remove) {
        set = set.remove(set.find(null, null,
                                  spec => spec.id == action.remove.id))
      }
      return set
github pubpub / pubpub-editor / packages / pubpub-prose / src / prosemirror-setup / plugins / mentionsPlugin.js View on Github external
import { Plugin } from 'prosemirror-state';
import { getPluginState } from '../plugins';
import { keys } from './pluginKeys';
import { schema } from '../schema';

const { DecorationSet, Decoration } = require('prosemirror-view');

const mentionsPlugin = new Plugin({
	state: {
		init(config, instance) {
			// const set = DecorationSet.empty;
			return { decos: DecorationSet.empty, start: null };
		},
		apply(transaction, state, prevEditorState, editorState) {

			const sel = editorState.selection;
			const updateMentions = this.spec.editorView.props.viewHandlers.updateMentions;

			if (!sel.empty) {
				updateMentions('');
				return { decos: DecorationSet.empty, start: null, };
			}

			// const doc = editorState.doc;
github pubpub / pubpub-editor / stories / stepTestingPanelsStories.js View on Github external
import React, { useState, useRef } from 'react';
import { storiesOf } from '@storybook/react';
// import ReactDOM from 'react-dom';
// import { Node, DOMSerializer } from 'prosemirror-model';
// import { ChangeSet, simplifyChanges } from 'prosemirror-changeset';
import { Plugin, PluginKey } from 'prosemirror-state';
import { Transform, Step } from 'prosemirror-transform';
// import { DecorationSet, Decoration } from 'prosemirror-view';

import Editor, { buildSchema } from '../src/index';
// import sampleDoc from './initialDocs/plainDoc';
import emptyDoc from './initialDocs/emptyDoc';
import { adjustSteps2 } from './stepTestStories';

const editorSchema = buildSchema();
const captureStepsPluginKey = new PluginKey('captureSteps');

const createCaptureStepsPlugin = () =>
	new Plugin({
		key: captureStepsPluginKey,
		state: {
			init: () => {
				return [];
			},
			apply: (transaction, value) => {
				console.log('tr is', transaction);
				return [...value, ...transaction.steps];
			},
		},
	});

const createDiffDoc = (doc, schema, hydratedSteps, divergeKey) => {
github ProseMirror / website / example / lint / index.js View on Github external
return true
        }
      }
    }
  }
})
// }

// editor{
import {EditorState} from "prosemirror-state"
import {EditorView} from "prosemirror-view"
import {DOMParser} from "prosemirror-model"
import {schema} from "prosemirror-schema-basic"
import {exampleSetup} from "prosemirror-example-setup"

let state = EditorState.create({
  doc: DOMParser.fromSchema(schema).parse(document.querySelector("#content")),
  plugins: exampleSetup({schema}).concat(lintPlugin)
})

window.view = new EditorView(document.querySelector("#editor"), {state})
// }
github ProseMirror / website / example / footnote / index.js View on Github external
open() {
    // Append a tooltip to the outer node
    let tooltip = this.dom.appendChild(document.createElement("div"))
    tooltip.className = "footnote-tooltip"
    // And put a sub-ProseMirror into that
    this.innerView = new EditorView(tooltip, {
      // You can use any node as an editor document
      state: EditorState.create({
        doc: this.node,
        plugins: [keymap({
          "Mod-z": () => undo(this.outerView.state, this.outerView.dispatch),
          "Mod-y": () => redo(this.outerView.state, this.outerView.dispatch)
        })]
      }),
      // This is the magic part
      dispatchTransaction: this.dispatchInner.bind(this),
      handleDOMEvents: {
        mousedown: () => {
          // Kludge to prevent issues due to the fact that the whole
          // footnote is node-selected (and thus DOM-selected) when
          // the parent editor is focused.
          if (this.outerView.hasFocus()) this.innerView.focus()
        }
      }
github pubpub / pubpub-editor / src / plugins / collaborativeold.js View on Github external
uncompressStepJSON(compressedStepJSON),
						);
					});
					steps.push(...uncompressedSteps);
					stepClientIds.push(
						...new Array(compressedStepsJSON.length).fill(changesSnapshotVal[key].c),
					);
				});

				/* Update the prosemirror view with new doc */
				const newDoc = Node.fromJSON(
					this.view.state.schema,
					this.pluginProps.initialContent,
				);
				this.view.updateState(
					EditorState.create({
						doc: newDoc,
						plugins: this.view.state.plugins,
					}),
				);

				this.pluginProps.onUpdateLatestKey(this.mostRecentRemoteKey);

				const trans = receiveTransaction(this.view.state, steps, stepClientIds);
				this.view.dispatch(trans);

				/* Retrieve and Listen to Cursors */
				if (!this.pluginProps.isReadOnly) {
					const cursorsRef = this.pluginProps.firebaseRef.child('cursors');
					cursorsRef
						.child(this.pluginProps.localClientId)
						.onDisconnect()
github guardian / facia-tool / client-v2 / src / components / inputs / richtext / setup.ts View on Github external
export const createEditorView = (
  input: WrappedFieldInputProps,
  editorEl: RefObject,
  contentEl: HTMLDivElement
) => {
  if (!editorEl.current) {
    return;
  }
  const ed: EditorView = new EditorView(editorEl.current, {
    state: EditorState.create({
      doc: DOMParser.fromSchema(basicSchema).parse(contentEl),
      plugins: createBasePlugins(basicSchema)
    }),
    dispatchTransaction: (transaction: Transaction) => {
      const { state, transactions } = ed.state.applyTransaction(transaction);
      ed.updateState(state);

      if (transactions.some((tr: Transaction) => tr.docChanged)) {
        const serializer = DOMSerializer.fromSchema(basicSchema);
        const outputHtml = serializer.serializeFragment(state.doc.content);
        // to format the outputHtml as an html string rather than a document fragment, we are creating a temporary div, adding it as a child, then using innerHTML which returns an html string
        const tmp = document.createElement('div');
        tmp.appendChild(outputHtml);
        if (input.onChange) {
          input.onChange(tmp.innerHTML);
        }
github ProseMirror / website / example / menu / index.js View on Github external
function menuPlugin(items) {
  return new Plugin({
    view(editorView) {
      let menuView = new MenuView(items, editorView)
      editorView.dom.parentNode.insertBefore(menuView.dom, editorView.dom)
      return menuView
    }
  })
}
// }
github ifiokjr / remirror / @remirror / extension-enhanced-link / src / enhanced-link-utils.ts View on Github external
export const enhancedLinkHandler = ({ state, url, from, to, tr, type }: EnhancedLinkHandlerProps) => {
  const endPosition = state.selection.to;
  const enhancedLink = type.create({ href: extractHref(url) });

  tr = (tr ?? state.tr).replaceWith(from, to, state.schema.text(url, [enhancedLink]));

  // Ensure that the selection doesn't jump when the the current selection is within the range
  if (endPosition < to) {
    return tr.setSelection(TextSelection.create(tr.doc, endPosition));
  }

  return tr;
};