/* eslint-disable @typescript-eslint/consistent-type-definitions */
import { Extension } from '@tiptap/core';
import '@tiptap/extension-text-style';
export default Extension.create({
    name: 'fontSize',
    addOptions() {
        return {
            types: ['textStyle'],
            nodeTypes: ['listItem'],
        };
    },
    addGlobalAttributes() {
        const fontSizeAttribute = {
            default: null,
            parseHTML: (element) => element.style.fontSize.replace(/['"]+/g, '') || null,
            renderHTML: (attributes) => {
                if (!attributes.fontSize) {
                    return {};
                }
                return {
                    style: `font-size: ${attributes.fontSize}`,
                };
            },
        };
        return [
            {
                types: this.options.types,
                attributes: {
                    fontSize: fontSizeAttribute,
                },
            },
            {
                types: this.options.nodeTypes,
                attributes: {
                    fontSize: fontSizeAttribute,
                },
            },
        ];
    },
    addCommands() {
        const { nodeTypes } = this.options;
        return {
            setFontSize: fontSize => ({ chain }) => {
                return chain()
                    .setMark('textStyle', { fontSize })
                    .command(({ tr, state }) => {
                    const { from, to } = state.selection;
                    if (from !== to) {
                        state.doc.nodesBetween(from, to, (node, pos) => {
                            if (nodeTypes.includes(node.type.name)) {
                                tr.setNodeAttribute(pos, 'fontSize', fontSize);
                            }
                        });
                    }
                    return true;
                })
                    .run();
            },
            unsetFontSize: () => ({ chain }) => {
                return chain()
                    .setMark('textStyle', { fontSize: null })
                    .removeEmptyTextStyle()
                    .command(({ tr, state }) => {
                    const { from, to } = state.selection;
                    if (from !== to) {
                        state.doc.nodesBetween(from, to, (node, pos) => {
                            if (nodeTypes.includes(node.type.name)) {
                                tr.setNodeAttribute(pos, 'fontSize', null);
                            }
                        });
                    }
                    return true;
                })
                    .run();
            },
        };
    },
});
