Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Decorations API #5437

Draft
wants to merge 3 commits into
base: next
Choose a base branch
from
Draft

WIP: Decorations API #5437

wants to merge 3 commits into from

Conversation

bdbch
Copy link
Member

@bdbch bdbch commented Aug 3, 2024

image

  • Decorations API
    • Positions
      • Attach Decorations to specific Nodes
      • Attach Decorations to the cursor
      • Manually set positions of a decoration
    • We should use a DecorationManager that
      • Handles the state for decorations
      • Communicates with a DecorationPlugin to handle creation and rendering of Prosemirror Decorations
    • Decoration Plugin
      • Syncs it’s state with the decoration manager state
      • uses the attached positions of decorations to determine what type of decoration is needed
    • DecorationManager.create => editor.decorations.create
      • The create api is similar to how we create extensions
        • render: handles rendering and allows return of html or react / vue components
        • binding events, f.e. onUpdate, onTransaction, etc.
    • TiptapDecoration
      • attachTo(x)
        • Can take a position, a range or a node
        • The type of decoration is inferred from this attachTo value

Copy link

changeset-bot bot commented Aug 3, 2024

⚠️ No Changeset found

Latest commit: 57ac4ae

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@bdbch bdbch changed the base branch from develop to next August 3, 2024 01:53
Copy link

netlify bot commented Aug 3, 2024

Deploy Preview for tiptap-embed ready!

Name Link
🔨 Latest commit 57ac4ae
🔍 Latest deploy log https://app.netlify.com/sites/tiptap-embed/deploys/67853c8700fd28000849a725
😎 Deploy Preview https://deploy-preview-5437--tiptap-embed.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@nperez0111
Copy link
Contributor

Some ideas for how we might wanna structure this:

const editor = new Editor()

editor.on('transaction', () => {

  const removeDecoration = editor.addDecorationWidget({ ...options })

  removeDecoration()

  editor.getDecorationSet('myDecoration').forEach(({ from, to }) => {
    editor.removeDecoration(from, to, 'myDecoration')
  })

})

DecorationSet.create({
  onTransaction,
  shouldShow,
  onCreate,
  onRemove,
  onUpdate,
  name: 'myDecoration',
  onEvent: (eventName, meta)=>{
    if (eventName === 'eventName') {
      // I want this decoration active
      editor.addDecorationSet('myDecoration', decorationSet)
      return;
    }
  }
  onTransaction: tr => {
    if (!tr.isOneIWant) {
      editor.clearDecorationSet('myDecoration')
      return
    }

    this.editor.addDecorationWidget()
  },
})

class DecorationManager {

  allDecorationSets: Record<string, DecorationSet> = {}

  addDecorationSet(key: string, decorationSet: DecorationSet) {
    this.allDecorationSets[key] = decorationSet
  }

  removeDecorationSet(key: string) {
    this.allDecorationSets[key].destroy()
    this.allDecorationSets[key] = undefined
  }

  listDecorationSets() {
    return ['myDecoration', 'anotherDecorationSet']
  }

  getDecorationSet(key: string) {

  }

  triggerEvent(eventName: string) {
    // re-run decoration sets
  }

  getProsemirrorPlugin() {
    return new Plugin({
      key: new PluginKey('decorationManager'),
      state: {
        init: () => this,
        apply: (tr, plugin) => {
          const decorationManager = plugin.getState(tr)

          // map through transactions for all decorations that still exist

          decorationManager.allDecorationSets.forEach(decorationSet => {
            decorationSet.onTransaction(tr)
          })
        },
      },
    })
  }
}

editor.triggerDecoration('eventName', meta)
editor.addDecorationSet('myDecoration', decorationSet)
editor.removeDecorationSet('myDecoration')

@nperez0111 nperez0111 force-pushed the decorations-api branch 2 times, most recently from 3290131 to 36489ba Compare November 13, 2024 12:54
@Gregoor
Copy link

Gregoor commented Jan 25, 2025

I'm not sure if this helps, so here goes nothing: I'm currently using addProseMirrorPlugins to create inline decorations, but I'm struggling with having them be dynamic. This is what I'm doing:

View Code
const buildTermHighlighter = (name: string) =>
  Extension.create<{
    terms: string[];
    className: string;
  }>({
    name: `termHighlighter-${name}`,
    addProseMirrorPlugins() {
      const findTerms = (doc: Node): DecorationSet => {
        const decorations: Decoration[] = [];
        for (let i = 0; i < doc.nodeSize - 2; i++) {
          for (const term of this.options.terms) {
            const end = Math.min(i + term.length, doc.nodeSize - 2);
            if (doc.textBetween(i, end, " ", " ") === term) {
              decorations.push(
                Decoration.inline(i, end, { class: this.options.className }),
              );
            }
          }
        }
        return DecorationSet.create(doc, decorations);
      };
      return [
        new Plugin({
          key: new PluginKey("termHighlighter"),
          state: {
            init: (_, { doc }) => findTerms(doc),
            apply: (transaction, oldState) =>
              transaction.docChanged ? findTerms(transaction.doc) : oldState,
          },
          props: {
            decorations(state) {
              return this.getState(state);
            },
          },
        }),
      ];
    },
  });

Unfortunately there's no update when terms change, so currently I'm literally react key=ing the editor component with the terms list to have it reload. So what I'm looking forward to with a tiptap-native Decorations API is to be able to do dynamic state-driven decoration changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
No open projects
Status: Triage open
Development

Successfully merging this pull request may close these issues.

3 participants