Placeholder for broken images

I’m trying to create an editor plugin that replaces images that fails to load with a broken image graphic.

I’ve looked at using decorators but see no way to access the dom node from there to attach an onerror event listener. I’ve looked at attaching it in the toDOM method of my schema but that seems wrong, and I’m not sure how I would go about updating the state from there.

Anyone have suggestions on how to best implement such a feature?

A node view could probably do this (create the node, attach event handler that triggers some logic when an error event happens), but I think a cleaner way would be to create img nodes off the side to build up a table of the validity of urls, and use that to create the decorations.

1 Like

Hi Marijn,

cleaner way would be to create img nodes off the side

What exactly do you mean by “off the side”? Would I be adding this url logic to the schema

image: {
    ...defaultNodes.image,
    attrs: {
      ...defaultNodes.image.attrs,
      alt: { default: null },
      title: { default: null },
      width: { default: '30em' },
    },
    parseDOM: [
      {
        tag: 'img[src][width]',
        getAttrs: (dom: HTMLElement) => ({
          src: dom.getAttribute('src') || '',
          alt: dom.getAttribute('alt') || null,
          title: dom.getAttribute('title') || null,
          width: dom.getAttribute('width') || '30em',
        }),
      },
    ],
toDOM: (node: ProsemirrorNode): DOMOutputSpec => {
      const attrs = {
        style: `width: ${node.attrs.width}; max-width: 100%; height: auto; margin: 0 4px;`,
      }
      return ['img', { ...node.attrs, ...attrs }]
    },
  } as NodeSpec,

or would I add it to Decorators logic?

For my use case, the authentication within my website will prevent the src url from working (will show the broken image jpg) if the url is restricted to the logged in user. Logged in users with access to the image will show the image in prosemirror as expected. Ideally when rendering the editor, I would want to check for errors that the src url won’t render and instead of the broken image show a default image. I won’t know the urls ahead of time because they are created dynamically through another API, and the same url may be restricted to one user but not another based on their login credentials.