• Stars
    star
    418
  • Rank 103,620 (Top 3 %)
  • Language
    TypeScript
  • License
    Other
  • Created almost 2 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library for safely integrating ProseMirror and React.

React ProseMirror

A fully featured library for safely integrating ProseMirror and React.

Installation

npm:

npm install @nytimes/react-prosemirror

yarn:

yarn add @nytimes/react-prosemirror

The Problem

React is a framework for developing reactive user interfaces. To make updates efficient, React separates updates into phases so that it can process updates in batches. In the first phase, application code renders a virtual document. In the second phase, the React DOM renderer finalizes the update by reconciling the real document with the virtual document. The ProseMirror View library renders ProseMirror documents in a single-phase update. Unlike React, it also allows built-in editing features of the browser to modify the document under some circumstances, deriving state updates from view updates rather than the other way around.

It is possible to use both React DOM and ProseMirror View, but using React DOM to render ProseMirror View components safely requires careful consideration of differences between the rendering approaches taken by each framework. The first phase of a React update should be free of side effects, which requires that updates to the ProseMirror View happen in the second phase. This means that during the first phase, React components actually have access to a different (newer) version of the EditorState than the one in the Editorview. As a result code that dispatches transactions may dispatch transactions based on incorrect state. Code that invokes methods of the ProseMirror view may make bad assumptions about its state that cause incorrect behavior or errors.

The Solution

There are two different directions to integrate ProseMirror and React: you can render a ProseMirror EditorView inside of a React component, and you can use React components to render ProseMirror NodeViews. This library provides tools for accomplishing both of these goals.

Rendering ProseMirror Views within React

This library provides a set of React contexts and hooks for consuming them that ensure safe access to the EditorView from React components. This allows us to build React applications that contain ProseMirror Views, even when the EditorState is lifted into React state, or a global state management system like Redux.

The simplest way to make use of these contexts is with the <ProseMirror/> component. The <ProseMirror/> component can be used controlled or uncontrolled, and takes a "mount" prop, used to specify which DOM node the ProseMirror EditorView should be mounted on.

import { EditorState } from "prosemirror-state";
import { ProseMirror } from "@nytimes/react-prosemirror";

export function ProseMirrorEditor() {
  // It's important that mount is stored as state,
  // rather than a ref, so that the ProseMirror component
  // is re-rendered when it's set
  const [mount, setMount] = useState();

  return (
    <ProseMirror mount={mount} defaultState={EditorState.create({ schema })}>
      <div ref={setMount} />
    </ProseMirror>
  );
}

The EditorState can also easily be lifted out of the ProseMirror component and passed as a prop.

import { EditorState } from "prosemirror-state";
import { schema } from "prosemirror-schema-basic";
import { ProseMirror } from "@nytimes/react-prosemirror";

export function ProseMirrorEditor() {
  const [mount, setMount] = useState();
  const [editorState, setEditorState] = useState(
    EditorState.create({ schema })
  );

  return (
    <ProseMirror
      mount={mount}
      state={editorState}
      dispatchTransaction={(tr) => {
        setEditorState((s) => s.apply(tr));
      }}
    >
      <div ref={setMount} />
    </ProseMirror>
  );
}

The ProseMirror component will take care to ensure that the EditorView is always updated with the latest EditorState after each render cycle. Because synchronizing the EditorView is a side effect, it must happen in the effects phase of the React render lifecycle, after all of the ProseMirror component's children have run their render functions. This means that special care must be taken to access the EditorView from within other React components. In order to abstract away this complexity, React ProseMirror provides two hooks: useEditorEffect and useEditorEventCallback. Both of these hooks can be used from any children of the ProseMirror component.

useEditorEffect

Often, it's necessary to position React components relative to specific positions in the ProseMirror document. For example, you might have some widget that needs to be positioned at the user's cursor. In order to ensure that this positioning happens when the EditorView is in sync with the latest EditorState, we can use useEditorEffect.

// SelectionWidget.tsx
import { useRef } from "react"
import { useEditorEffect } from "@nytimes/react-prosemirror"

export function SelectionWidget() {
  const ref = useRef()

  useEditorEffect((view) => {
    if (!view || !ref.current) return

    const viewClientRect = view.dom.getBoundingClientRect()
    const coords = view.coordsAtPos(view.state.selection.anchor))

    ref.current.style.top = coords.top - viewClientRect.top;
    ref.current.style.left = coords.left - viewClientRect.left;
  })

  return (
    <div
      ref={ref}
      style={{
        position: "absolute"
      }}
    />
  )
}

// ProseMirrorEditor.tsx
import { EditorState } from "prosemirror-state";
import { schema } from "prosemirror-schema-basic";

import { SelectionWidget } from "./SelectionWidget.tsx";

export function ProseMirrorEditor() {
  const [mount, setMount] = useState()
  const [editorState, setEditorState] = useState(EditorState.create({ schema }))

  return (
    <ProseMirror
      mount={mount}
      state={editorState}
      dispatchTransaction={(tr) => {
        setEditorState(s => s.apply(tr))
      }}
    >
      {/*
        We have to mount all components that need to access the
        EditorView as children of the ProseMirror component
      */}
      <SelectionWidget />
      <div ref={setMount} />
    </ProseMirror>
  )
}

useEditorEventCallback

It's also often necessary to dispatch transactions or execute side effects in response to user actions, like mouse clicks and keyboard events. Note: if you need to respond to keyboard events from within the contenteditable element, you should instead use useEditorEventListener.

However, if you need to dispatch a transaction in response to some event dispatched from a React component, like a tooltip or a toolbar button, you can use useEditorEventCallback to create a stable function reference that can safely access the latest value of the EditorView.

// BoldButton.tsx
import { toggleMark } from "prosemirror-commands";
import { useEditorEventCallback } from "@nytimes/react-prosemirror";

export function BoldButton() {
  const onClick = useEditorEventCallback((view) => {
    const toggleBoldMark = toggleMark(view.state.schema.marks.bold);
    toggleBoldMark(view.state, view.dispatch, view);
  });

  return <button onClick={onClick}>Bold</button>;
}

// ProseMirrorEditor.tsx
import { EditorState } from "prosemirror-state";
import { schema } from "prosemirror-schema-basic";

import { BoldButton } from "./BoldButton.tsx";

export function ProseMirrorEditor() {
  const [mount, setMount] = useState();
  const [editorState, setEditorState] = useState(
    EditorState.create({ schema })
  );

  return (
    <ProseMirror
      mount={mount}
      state={editorState}
      dispatchTransaction={(tr) => {
        setEditorState((s) => s.apply(tr));
      }}
    >
      {/*
        We have to mount all components that need to access the
        EditorView as children of the ProseMirror component
      */}
      <BoldButton />
      <div ref={setMount} />
    </ProseMirror>
  );
}

useEditorEventListener

useEditorEventCallback produces functions that can be passed to React components as event handlers. If you need to listen to events that originate within the contenteditable node, however, those event listeners need to be registered with the EditorView's handleDOMEvents prop.

You can use the useEditorEventListener hook to accomplish this. It takes an eventType and an event listener. The event listener follows the usual semantics for ProseMirror's handleDOMEvents prop:

  • Returning true or calling event.preventDefault will prevent other listeners from running.
  • Returning true will not automatically call event.preventDefault; if you want to prevent the default contenteditable behavior, you must call event.preventDefault.

You can use this hook to implement custom behavior in your NodeViews:

import { useEditorEventListener } from "@nytimes/react-prosemirror";

function Paragraph({ node, getPos, children }) {
  useEditorEventListener("keydown", (view, event) => {
    if (event.code !== "ArrowDown") {
      return false;
    }
    const nodeStart = getPos();
    const nodeEnd = nodeStart + node.nodeSize;
    const { selection } = view.state;
    if (selection.anchor < nodeStart || selection.anchor > nodeEnd) {
      return false;
    }
    event.preventDefault();
    alert("No down keys allowed!");
    return true;
  });

  return <p>{children}</p>;
}

useEditorView, EditorProvider and LayoutGroup

Under the hood, the ProseMirror component essentially just composes three separate tools: useEditorView, EditorProvider, and LayoutGroup. If you find yourself in need of more control over these, they can also be used independently.

useEditorView is a relatively simple hook that takes a mount point and EditorProps as arguments and returns an EditorView instance.

EditorProvider is a simple React context, which should be provided the current EditorView and EditorState.

LayoutGroup must be rendered as a parent of the component using useEditorView.

Building NodeViews with React

The other way to integrate React and ProseMirror is to have ProseMirror render NodeViews using React components. This is somewhat more complex than the previous section. This library provides a useNodeViews hook, a factory for augmenting NodeView constructors with React components.

useNodeViews takes a map from node name to an extended NodeView constructor. The NodeView constructor must return at least a dom attribute and a component attribute, but can also return any other NodeView attributes. Here's an example of its usage:

import {
  useNodeViews,
  useEditorEventCallback,
  NodeViewComponentProps,
} from "@nytimes/react-prosemirror";
import { EditorState } from "prosemirror-state";
import { schema } from "prosemirror-schema-basic";

// Paragraph is more or less a normal React component, taking and rendering
// its children. The actual children will be constructed by ProseMirror and
// passed in here. Take a look at the NodeViewComponentProps type to
// see what other props will be passed to NodeView components.
function Paragraph({ children }: NodeViewComponentProps) {
  const onClick = useEditorEventCallback((view) => view.dispatch(whatever));
  return <p onClick={onClick}>{children}</p>;
}

// Make sure that your ReactNodeViews are defined outside of
// your component, or are properly memoized. ProseMirror will
// teardown and rebuild all NodeViews if the nodeView prop is
// updated, leading to unbounded recursion if this object doesn't
// have a stable reference.
const reactNodeViews = {
  paragraph: () => ({
    component: Paragraph,
    // We render the Paragraph component itself into a div element
    dom: document.createElement("div"),
    // We render the paragraph node's ProseMirror contents into
    // a span, which will be passed as children to the Paragraph
    // component.
    contentDOM: document.createElement("span"),
  }),
};

function ProseMirrorEditor() {
  const { nodeViews, renderNodeViews } = useNodeViews(reactNodeViews);

  const [mount, setMount] = useState();

  return (
    <ProseMirror
      mount={mount}
      defaultState={EditorState.create({ schema })}
      nodeViews={nodeViews}
    >
      <div ref={setMount} />
      {renderNodeViews()}
    </ProseMirror>
  );
}

API

ProseMirror

type ProseMirror = (
  props: {
    mount: HTMLElement;
    children: ReactNode;
  } & DirectEditorProps &
    ({ defaultState: EditorState } | { state: EditorState })
) => JSX.Element;

Renders the ProseMirror View onto a DOM mount.

The mount prop must be an actual HTMLElement instance. The JSX element representing the mount should be passed as a child to the ProseMirror component.

Example usage:

function MyProseMirrorField() {
  const [mount, setMount] = useState(null);

  return (
    <ProseMirror mount={mount}>
      <div ref={setMount} />
    </ProseMirror>
  );
}

EditorProvider

type EditorProvider = React.Provider<{
  editorView: EditorView | null;
  editorState: EditorState | null;
  registerEventListener<EventType extends keyof DOMEventMap>(
    eventType: EventType,
    handler: EventHandler<EventType>
  ): void;
  unregisterEventListener<EventType extends keyof DOMEventMap>(
    eventType: EventType,
    handler: EventHandler<EventType>
  ): void;
}>;

Provides the EditorView, as well as the current EditorState. Should not be consumed directly; instead see useEditorState, useEditorEventCallback, and useEditorEffect.

See ProseMirrorInner.tsx for example usage. Note that if you are using the ProseMirror component, you don't need to use this provider directly.

LayoutGroup

type LayoutGroup = (props: { children: React.ReactNode }) => JSX.Element;

Provides a deferral point for grouped layout effects. All effects registered with useLayoutGroupEffect by children of this provider will execute after all effects registered by useLayoutEffect by children of this provider.

See ProseMirror.tsx for example usage. Note that if you are using the ProseMirror component, you don't need to use this context directly.

useLayoutGroupEffect

type useLayoutGroupEffect = (
  effect: React.EffectCallback,
  deps?: React.DependencyList
) => void;

Like useLayoutEffect, but all effect executions are run after the LayoutGroup layout effects phase.

This hook allows child components to enqueue layout effects that won't be safe to run until after a parent component's layout effects have run.

Note that components that use this hook must be descendants of the LayoutGroup component.

useEditorState

type useEditorState = () => EditorState | null;

Provides access to the current EditorState value.

useEditorView

type useEditorView = <T extends HTMLElement = HTMLElement>(
  mount: T | null,
  props: DirectEditorProps
) => EditorView | null;

Creates, mounts, and manages a ProseMirror EditorView.

All state and props updates are executed in a layout effect. To ensure that the EditorState and EditorView are never out of sync, it's important that the EditorView produced by this hook is only accessed through the hooks exposed by this library.

See ProseMirrorInner.tsx for example usage. Note that if you are using the ProseMirror component, you don't need to use this hook directly.

useEditorEventCallback

type useEditorEventCallback = <T extends unknown[]>(
  callback: (view: EditorView | null, ...args: T) => void
) => void;

Returns a stable function reference to be used as an event handler callback.

The callback will be called with the EditorView instance as its first argument.

This hook is dependent on both the EditorProvider.Provider and the LayoutGroup. It can only be used in a component that is mounted as a child of both of these providers.

useEditorEventListener

type useEditorEventListener = <EventType extends DOMEventMap>(
  eventType: EventType,
  listener: (view: EditorView, event: DOMEventMap[EventType]) => boolean
) => void;

Attaches an event listener at the EditorView's DOM node. See the ProseMirror docs for more details.

useEditorEffect

type useEditorEffect = (
  effect: (editorView: EditorView | null) => void | (() => void),
  dependencies?: React.DependencyList
) => void;

Registers a layout effect to run after the EditorView has been updated with the latest EditorState and Decorations.

Effects can take an EditorView instance as an argument. This hook should be used to execute layout effects that depend on the EditorView, such as for positioning DOM nodes based on ProseMirror positions.

Layout effects registered with this hook still fire synchronously after all DOM mutations, but they do so after the EditorView has been updated, even when the EditorView lives in an ancestor component.

Example usage:

import { useRef } from "react"
import { useEditorEffect } from "@nytimes/react-prosemirror"

export function SelectionWidget() {
  const ref = useRef()

  useEditorEffect((view) => {
    if (!view || !ref.current) return

    const viewClientRect = view.dom.getBoundingClientRect()
    const coords = view.coordsAtPos(view.state.selection.anchor))

    ref.current.style.top = coords.top - viewClientRect.top;
    ref.current.style.left = coords.left - viewClientRect.left;
  })

  return (
    <div
      ref={ref}
      style={{
        position: "absolute"
      }}
    />
  )
}

useNodeViews

/**
 * Extension of ProseMirror's NodeViewConstructor type to include
 * `component`, the React component to used render the NodeView.
 * All properties other than `component` and `dom` are optional.
 */
type ReactNodeViewConstructor = (
  node: Node,
  view: EditorView,
  getPos: () => number,
  decorations: readonly Decoration[],
  innerDecorations: DecorationSource
) => {
  dom: HTMLElement | null;
  component: React.ComponentType<NodeViewComponentProps>;
  contentDOM?: HTMLElement | null;
  selectNode?: () => void;
  deselectNode?: () => void;
  setSelection?: (
    anchor: number,
    head: number,
    root: Document | ShadowRoot
  ) => void;
  stopEvent?: (event: Event) => boolean;
  ignoreMutation?: (mutation: MutationRecord) => boolean;
  destroy?: () => void;
  update?: (
    node: Node,
    decorations: readonly Decoration[],
    innerDecoration: DecorationSource
  ) => boolean;
};

type useNodeViews = (nodeViews: Record<string, ReactNodeViewConstructor>) => {
  nodeViews: Record<string, NodeViewConstructor>;
  renderNodeViews: () => ReactElement[];
};

Hook for creating and rendering NodeViewConstructors that are powered by React components.

component can be any React component that takes NodeViewComponentProps. It will be passed as props all of the arguments to the nodeViewConstructor except for editorView. NodeView components that need access directly to the EditorView should use the useEditorEventCallback and useEditorEffect hooks to ensure safe access.

For contentful Nodes, the NodeView component will also be passed a children prop containing an empty element. ProseMirror will render content nodes into this element. Like in ProseMirror, the existence of a contentDOM attribute determines whether a NodeView is contentful (i.e. the NodeView has editable content that should be managed by ProseMirror).

More Repositories

1

covid-19-data

A repository of data on coronavirus cases and deaths in the U.S.
6,989
star
2

objective-c-style-guide

The Objective-C Style Guide used by The New York Times
5,848
star
3

gizmo

A Microservice Toolkit from The New York Times
Go
3,753
star
4

Store

Android Library for Async Data Loading and Caching
Java
3,531
star
5

NYTPhotoViewer

A modern photo viewing experience for iOS.
Objective-C
2,847
star
6

pourover

A library for simple, fast filtering and sorting of large collections in the browser. There is a community-maintained fork that addresses a handful of post-NYT issues available via @hhsnopek's https://github.com/hhsnopek/pourover
JavaScript
2,393
star
7

kyt

Starting a new JS app? Build, test and run advanced apps with kyt ๐Ÿ”ฅ
JavaScript
1,922
star
8

react-tracking

๐ŸŽฏ Declarative tracking for React apps.
JavaScript
1,876
star
9

ice

track changes with javascript
JavaScript
1,708
star
10

backbone.stickit

Backbone data binding, model binding plugin. The real logic-less templates.
JavaScript
1,641
star
11

library

A collaborative documentation site, powered by Google Docs.
JavaScript
1,143
star
12

openapi2proto

A tool for generating Protobuf v3 schemas and gRPC service definitions from OpenAPI specifications
Go
940
star
13

gziphandler

Go middleware to gzip HTTP responses
Go
857
star
14

svg-crowbar

Extracts an SVG node and accompanying styles from an HTML document and allows you to download it all as an SVG file.
JavaScript
840
star
15

ingredient-phrase-tagger

Extract structured data from ingredient phrases using conditional random fields
Python
784
star
16

Emphasis

Dynamic Deep-Linking and Highlighting
JavaScript
576
star
17

tamper

Ruby
499
star
18

three-loader-3dtiles

This is a Three.js loader module for handling OGC 3D Tiles, created by Cesium. It currently supports the two main formats, Batched 3D Model (b3dm) - based on glTF Point cloud.
TypeScript
444
star
19

rd-blender-docker

A collection of Docker containers for running Blender headless or distributed โœจ
Python
415
star
20

Register

Android Library and App for testing Play Store billing
Kotlin
381
star
21

text-balancer

Eliminate typographic widows and other type crimes with this javascript module
JavaScript
373
star
22

document-viewer

The NYTimes Document Viewer
JavaScript
310
star
23

ios-360-videos

NYT360Video plays 360-degree video streamed from an AVPlayer on iOS.
Objective-C
273
star
24

three-story-controls

A three.js camera toolkit for creating interactive 3d stories
TypeScript
247
star
25

backbone.trackit

Manage unsaved changes in a Backbone Model.
JavaScript
202
star
26

aframe-loader-3dtiles-component

A-Frame component using 3D-Tiles
JavaScript
187
star
27

marvin

A go-kit HTTP server for the App Engine Standard Environment
Go
177
star
28

drone-gke

Drone plugin for deploying containers to Google Kubernetes Engine (GKE)
Go
165
star
29

Chronicler

A better way to write your release notes.
JavaScript
162
star
30

nginx-vod-module-docker

Docker image for nginx with Kaltura's VoD module used by The New York Times
Dockerfile
161
star
31

collectd-rabbitmq

A collected plugin, written in python, to collect statistics from RabbitMQ.
Python
143
star
32

public_api_specs

The API Specs (in OpenAPI/Swagger) for the APIs available from developer.nytimes.com
136
star
33

gunsales

Statistical analysis of monthly background checks of gun purchases
R
130
star
34

gcp-vault

A client for securely retrieving secrets from Vault in Google Cloud infrastructure
Go
119
star
35

rd-bundler-3d-plugins

Bundler plugins for optimizing glTF 3D models
JavaScript
119
star
36

Fech

Deprecated. Please see https://github.com/dwillis/Fech for a maintained fork.
Ruby
115
star
37

data-training

Files from the NYT data training program, available for public use.
114
star
38

drone-gae

Drone plugin for managing deployments and services on Google App Engine (GAE)
Go
97
star
39

mock-ec2-metadata

Go
95
star
40

encoding-wrapper

Collection of Go wrappers for Video encoding cloud providers (moved to @video-dev)
Go
85
star
41

redux-taxi

๐Ÿš• Component-driven asynchronous SSR in isomorphic Redux apps
JavaScript
70
star
42

video-captions-api

Agnostic API to generate captions for media assets across different transcription services.
Go
61
star
43

lifeline

A cron-based alternative to running daemons
Ruby
58
star
44

gcs-helper

Tool for proxying and mapping HTTP requests to Google Cloud Storage (GCS).
Go
54
star
45

logrotate

Go
54
star
46

httptest

A simple concurrent HTTP testing tool
Go
48
star
47

kyt-starter-universal

Deprecated, see: https://github.com/NYTimes/kyt/tree/master/packages/kyt-starter-universal
JavaScript
33
star
48

nytcampfin

A thin Python client for The New York Times Campaign Finance API
Python
27
star
49

safejson

safeJSON provides replacements for the 'load' and 'loads' methods in the standard Python 'json' module.
Python
27
star
50

thumbor-docker-image

Docker image for Thumbor smart imaging service
26
star
51

times_wire

A thin Ruby client for The New York Times Newswire API
Ruby
26
star
52

haiti-debt

Historical data on Haitiโ€™s debt payments to France collected by The New York Times.
21
star
53

hhs-child-migrant-data

Data from the U.S. Department of Human Health and Services on children who have migrated to the United States without an adult.
21
star
54

jsonlogic

Clojure
20
star
55

elemental-live-client

JS library to communicate with Elemental live API.
JavaScript
19
star
56

Open-Source-Science-Fair

The New York Times Open Source Science Fair
JavaScript
19
star
57

tweetftp

Ruby Implementation of the Tweet File Transfer Protocol (APRIL FOOLS JOKE)
Ruby
19
star
58

prosemirror-change-tracking-prototype

JavaScript
18
star
59

plumbook

Data from the Plum Book, published by the GPO every 4 years
17
star
60

libvmod-queryfilter

Simple querystring filter/sort module for Varnish Cache v3-v6
M4
16
star
61

sneeze

Python
16
star
62

querqy-clj

Search Query Rewriting for Elasticsearch and more! Built on Querqy.
Clojure
14
star
63

sqliface

handy interfaces and test implementations for Go's database/sql package
Go
14
star
64

grocery

The grocery package provides easy mechanisms for storing, loading, and updating Go structs in Redis.
Go
13
star
65

oak-byo-react-prosemirror-redux

JavaScript
13
star
66

vase.elasticsearch

Vase Bindings for Elasticsearch
Clojure
11
star
67

library-customization-example

An example repo that customizes Library behavior
SCSS
11
star
68

counter

count things, either as a one-off or aggregated over time
Ruby
11
star
69

kyt-starter

The default starter-kyt for kyt apps.
JavaScript
10
star
70

tulsa-1921-data

Data files associated with our story on the 1921 race massacre in Tulsa, Oklahoma.
10
star
71

open-blog-projects

A repository for code examples that are paired with our Open Blog posts
Swift
9
star
72

rd-mobile-pg-demos

HTML
9
star
73

pocket_change

Python
9
star
74

mentorship

7
star
75

sort_by_str

SQL-like sorts on your Enumerables
Ruby
7
star
76

drone-gdm

Drone.io plugin to facilitate the use of Google Deployment Manager in drone deploy phase.
Go
6
star
77

kyt-starter-static

Deprecated, see: https://github.com/NYTimes/kyt/tree/master/packages/kyt-starter-static
JavaScript
6
star
78

s3yum

Python
5
star
79

pocket

Python
5
star
80

drone-openapi

A Drone plugin for publishing Open API service specifications
Go
5
star
81

threeplay

Go client for the 3Play API.
Go
4
star
82

amara

Amara client for Go
Go
4
star
83

go-compare-expressions

Go
3
star
84

kaichu

Python
3
star
85

license

NYT Apache 2.0 license
3
star
86

prosemirror-tooltip

JavaScript
2
star
87

photon-dev_demo

A "Sustainable Systems, Powered By Python" Demo Repository (1 of 3)
Shell
2
star
88

std-cat

Content Aggregation Technology โ€” a standard for content aggregation on the Web
HTML
1
star