<script>
    import {onDestroy, onMount} from 'svelte';
    import {Editor} from '@tiptap/core'
    import Document from '@tiptap/extension-document'
    import Paragraph from '@tiptap/extension-paragraph'
    import Text from '@tiptap/extension-text'
    import Heading from '@tiptap/extension-heading'
    import Blockquote from '@tiptap/extension-blockquote';
    import Bold from '@tiptap/extension-bold';
    import BulletList from '@tiptap/extension-bullet-list';
    import Code from '@tiptap/extension-code';
    import History from '@tiptap/extension-history';
    import Italic from '@tiptap/extension-italic';
    import ListItem from '@tiptap/extension-list-item';
    import OrderedList from '@tiptap/extension-ordered-list';
    import Strike from '@tiptap/extension-strike';
    import Table from '@tiptap/extension-table';
    import TableRow from '@tiptap/extension-table-row';
    import TableCell from '@tiptap/extension-table-cell';
    import TableHeader from '@tiptap/extension-table-header';
    import Underline from '@tiptap/extension-underline';

    let element;
    let editor;
    export let value = "";

    onMount(() => {
        editor = new Editor({
            element: element,
            extensions: [
                Document,
                Paragraph,
                Text,
                Bold,
                BulletList,
                Code,
                History,
                Italic,
                ListItem,
                OrderedList,
                ListItem,
                Strike,
                Table,
                TableRow,
                TableCell,
                TableHeader,
                Underline,
                Heading.configure({
                    levels: [1, 2, 3],
                }),
                Blockquote
            ],
            content: value,
            editable: true,
            onTransaction: () => {
                // force re-render so `editor.isActive` works as expected
                editor = editor;
            },
        });
    });

    onDestroy(() => {
        if (editor) {
            editor.destroy();
        }
    });
</script>

{#if editor}
    <button
            on:click={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
            class:active={editor.isActive('heading', { level: 1 })}
    >
        H1
    </button>
    <button
            on:click={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
            class:active={editor.isActive('heading', { level: 2 })}
    >
        H2
    </button>
    <button
            on:click={() => editor.chain().focus().setParagraph().run()}
            class:active={editor.isActive('paragraph')}
    >
        P
    </button>
    <button
            on:click={() => editor.chain().focus().toggleBold().run()}
            class:active={editor.isActive('bold')}
    >
        Bold
    </button>
{/if}

<div bind:this={element} class="content"/>