import { Node, mergeAttributes } from '@tiptap/core' import TiptapImage from '@tiptap/extension-image' import type { DOMOutputSpec } from '@tiptap/pm/model' export type ImageMapAreaAttributes = { shape?: string coords?: string href?: string alt?: string title?: string target?: string } const readAttribute = (element: Element, name: string): string | undefined => element.getAttribute(name) ?? undefined export const ImageWithMap = TiptapImage.extend({ addAttributes() { return { ...this.parent?.(), usemap: { default: null, parseHTML: (element) => element.getAttribute('usemap'), renderHTML: (attributes) => attributes.usemap ? { usemap: attributes.usemap } : {}, }, align: { default: null, parseHTML: (element) => element.getAttribute('align'), renderHTML: (attributes) => attributes.align ? { align: attributes.align } : {}, }, style: { default: null, parseHTML: (element) => element.getAttribute('style'), renderHTML: (attributes) => attributes.style ? { style: attributes.style } : {}, }, loading: { default: null, parseHTML: (element) => element.getAttribute('loading'), renderHTML: (attributes) => attributes.loading ? { loading: attributes.loading } : {}, }, } }, }) export const ImageMap = Node.create({ name: 'imageMap', group: 'block', atom: true, addAttributes() { return { name: { default: null, parseHTML: (element) => element.getAttribute('name'), renderHTML: (attributes) => attributes.name ? { name: attributes.name } : {}, }, id: { default: null, parseHTML: (element) => element.getAttribute('id'), renderHTML: (attributes) => attributes.id ? { id: attributes.id } : {}, }, areas: { default: [], parseHTML: (element) => Array.from(element.children) .filter((child) => child.tagName.toLowerCase() === 'area') .map((area): ImageMapAreaAttributes => ({ shape: readAttribute(area, 'shape'), coords: readAttribute(area, 'coords'), href: readAttribute(area, 'href'), alt: readAttribute(area, 'alt'), title: readAttribute(area, 'title'), target: readAttribute(area, 'target'), })), renderHTML: () => ({}), }, } }, parseHTML() { return [{ tag: 'map' }] }, renderHTML({ node, HTMLAttributes }) { const mapAttributes = { ...HTMLAttributes } delete mapAttributes.areas const areas = (node.attrs.areas as ImageMapAreaAttributes[]).map((area): DOMOutputSpec => [ 'area', Object.fromEntries(Object.entries(area).filter(([, value]) => Boolean(value))), ]) return ['map', mergeAttributes(mapAttributes), ...areas] as DOMOutputSpec }, })