Skip to content

Instantly share code, notes, and snippets.

@hanspagel
Last active September 17, 2022 17:10
Show Gist options
  • Save hanspagel/de6cd0c30ece7afb3f2ba663768f373f to your computer and use it in GitHub Desktop.
Save hanspagel/de6cd0c30ece7afb3f2ba663768f373f to your computer and use it in GitHub Desktop.

Revisions

  1. hanspagel revised this gist Oct 16, 2021. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions CustomTable.js
    Original file line number Diff line number Diff line change
    @@ -49,6 +49,10 @@ const CustomTable = Table.extend({
    width,
    })
    })

    if (!tr.steps.length) {
    return
    }

    return tr
    },
  2. hanspagel created this gist Oct 16, 2021.
    60 changes: 60 additions & 0 deletions CustomTable.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    const CustomTable = Table.extend({
    // Add a `width` attribute
    addAttributes() {
    return {
    ...this.parent?.(),
    width: {
    default: null,
    },
    }
    },
    // Add a ProseMirror plugin to listen for colwidth changes
    // and update the `width` attribute
    addProseMirrorPlugins() {
    return [
    ...this.parent?.(),
    new Plugin({
    appendTransaction: (transactions, oldState, state) => {
    const transaction = transactions[0]
    const resizingState = columnResizingPluginKey.getState(state)

    // Check if it’s a resize transaction
    if (!resizingState.activeHandle || !resizingState.dragging) {
    return
    }

    // Loop only through the range that has been modified
    const { doc, before } = transaction
    const from = before.content.findDiffStart(doc.content)
    const to = before.content.findDiffEnd(doc.content)

    if (!from || !to || from === to.b) {
    return
    }

    // Create a new transaction first
    const tr = state.tr

    state.doc.nodesBetween(from, to.b, (node, pos) => {
    if (node.type.name !== 'table') {
    return
    }

    // Get the table width from the DOM
    const width = this.editor.view.nodeDOM(pos)?.offsetWidth

    // Update the `width` attribute
    tr.setNodeMarkup(pos, undefined, {
    ...node.attrs,
    width,
    })
    })

    return tr
    },
    }),
    ]
    },
    }).configure({
    resizable: true,
    })