import { mergeAttributes } from '@tiptap/core';
import { VueNodeViewRenderer } from '@tiptap/vue-2';
import Component from './text-entity-component.vue';
import { TextSelection } from 'prosemirror-state';
import { guidGenerator } from '@csnext/cs-core';
import Text from '@tiptap/extension-text';
function getSelection(selection) {
}
export default Text.extend({
    name: 'text-entity',
    group: 'inline',
    draggable: true,
    inline: true,
    atom: true,
    addAttributes() {
        return {
            id: { default: null },
            type: { default: 'person' },
            text: { default: '' }
        };
    },
    parseHTML() {
        return [
            {
                tag: 'text-entity',
            },
        ];
    },
    renderText({ node }) {
        return `${node.attrs.text}`;
    },
    addCommands() {
        return {
            setTextEntity: (entity) => ({ tr, dispatch }) => {
                var _a, _b, _c, _d;
                if (dispatch) {
                    const node = tr.doc.nodeAt(tr.selection.from);
                    let text = tr.doc.textBetween(tr.selection.from, tr.selection.to - 1);
                    if ((entity === null || entity === void 0 ? void 0 : entity.text) !== text) {
                        tr.selection.$from.pos = tr.selection.from - 1;
                        text = tr.doc.textBetween(tr.selection.from, tr.selection.to).trim();
                    }
                    const { parent, pos } = tr.selection.$from;
                    const posAfter = pos + 1;
                    const nodeAfter = tr.doc.nodeAt(posAfter);
                    const id = (_a = entity === null || entity === void 0 ? void 0 : entity.entity_idx) !== null && _a !== void 0 ? _a : guidGenerator();
                    const type = (_c = (_b = entity === null || entity === void 0 ? void 0 : entity.class) !== null && _b !== void 0 ? _b : entity === null || entity === void 0 ? void 0 : entity.entity_class) !== null && _c !== void 0 ? _c : 'node';
                    const newEntity = this.type.create();
                    newEntity.attrs = { id: id, type, text: text };
                    newEntity.text = text;
                    tr.replaceSelectionWith(newEntity);
                    if (!nodeAfter) {
                        const node = (_d = parent.type.contentMatch.defaultType) === null || _d === void 0 ? void 0 : _d.create();
                        if (node) {
                            tr.insert(posAfter, node);
                            tr.setSelection(TextSelection.create(tr.doc, posAfter));
                        }
                    }
                    tr.scrollIntoView();
                }
                return true;
            },
        };
    },
    renderHTML({ node, HTMLAttributes }) {
        return ['text-entity', mergeAttributes(HTMLAttributes)];
    },
    addNodeView() {
        return VueNodeViewRenderer(Component);
    },
});
//# sourceMappingURL=text-extension.js.map