Добавление настраиваемого раскрывающегося списка в редактор Quill с помощью JavaScript

Обратите внимание, что это вопрос, на который вы отвечаете сами.

Модуль панели инструментов редактора Quill, похоже, не предлагает способа добавлять в него собственные инструменты с помощью JavaScript API. Вы можете просто выбрать из списка предопределенных инструментов, или вам придется полностью переписать весь HTML-код панели инструментов, что кажется очень хакерским и часто не подходит. Из-за этого механизма инструменты не могут быть просто добавлены или удалены во время выполнения и всегда статичны, что означает, что (например) у вас не может быть динамического раскрывающегося списка, который загружает или изменяет его записи во время выполнения.

Сам редактор Quill предлагает только API для добавления другого модуля. Таким образом, вы можете написать еще один модуль панели инструментов, который поддерживает вышеупомянутые функции, отсутствующие в исходном модуле, но было бы гораздо лучше иметь возможность продолжать использовать исходный модуль из-за объема работы, которая потребовалась бы для его эффективного переписывания.

Возникает вопрос: как добавить потенциально динамический инструмент, например раскрывающееся меню, на панель инструментов существующего экземпляра Quill Editor.


person Forivin    schedule 19.11.2019    source источник


Ответы (1)


Я написал библиотеку под названием DynamicQuillTools, которая может выполнить эту работу.

Его можно использовать так:

const dropDownItems = {
    'Mike Smith': '[email protected]',
    'Jonathan Dyke': '[email protected]',
    'Max Anderson': '[email protected]'
}

const myDropDown = new QuillToolbarDropDown({
    label: "Email Addresses",
    rememberSelection: false
})

myDropDown.setItems(dropDownItems)

myDropDown.onSelect = function(label, value, quill) {
    // Do whatever you want with the new dropdown selection here

    // For example, insert the value of the dropdown selection:
    const { index, length } = quill.selection.savedRange
    quill.deleteText(index, length)
    quill.insertText(index, value)
    quill.setSelection(index + value.length)
}

myDropDown.attach(quill)

Вот полная демонстрация добавления настраиваемого раскрывающегося списка и настраиваемой кнопки в экземпляр редактора Quill:

// Create a Quill Editor instance with some built-in toolbar tools
const quill = new Quill('#editor', {
    theme: 'snow',
    modules: {
        toolbar: {
            container: [
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],

                [{ 'header': 1 }, { 'header': 2 }],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'script': 'sub' }, { 'script': 'super' }],
                [{ 'indent': '-1' }, { 'indent': '+1' }],
                [{ 'direction': 'rtl' }],

                [{ 'size': ['small', false, 'large', 'huge'] }],
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

                [{ 'color': [] }, { 'background': [] }],
                [{ 'font': [] }],
                [{ 'align': [] }],

                ['clean'],
            ]
        }
    }
})


// Add a custom DropDown Menu to the Quill Editor's toolbar:

const dropDownItems = {
    'Mike Smith': '[email protected]',
    'Jonathan Dyke': '[email protected]',
    'Max Anderson': '[email protected]'
}

const myDropDown = new QuillToolbarDropDown({
    label: "Email Addresses",
    rememberSelection: false
})

myDropDown.setItems(dropDownItems)

myDropDown.onSelect = function(label, value, quill) {
    // Do whatever you want with the new dropdown selection here

    // For example, insert the value of the dropdown selection:
    const { index, length } = quill.selection.savedRange
    quill.deleteText(index, length)
    quill.insertText(index, value)
    quill.setSelection(index + value.length)
}

myDropDown.attach(quill)


// Add a custom Button to the Quill Editor's toolbar:

const myButton = new QuillToolbarButton({
    icon: `<svg viewBox="0 0 18 18"> <path class="ql-stroke" d="M5,3V9a4.012,4.012,0,0,0,4,4H9a4.012,4.012,0,0,0,4-4V3"></path></svg>`
})
myButton.onClick = function(quill) {
    // Do whatever you want here. You could use this.getValue() or this.setValue() if you wanted.

    // For example, get the selected text and convert it to uppercase:
    const { index, length } = quill.selection.savedRange
    const selectedText = quill.getText(index, length)
    const newText = selectedText.toUpperCase()
    quill.deleteText(index, length)
    quill.insertText(index, newText)
    quill.setSelection(index, newText.length)
}
myButton.attach(quill)
<script src="https://cdn.quilljs.com/1.3.7/quill.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.quilljs.com/1.3.7/quill.bubble.css"></link>
<link rel="stylesheet" type="text/css" href="https://cdn.quilljs.com/1.3.7/quill.snow.css"></link>
<script src="https://cdn.jsdelivr.net/gh/T-vK/DynamicQuillTools@master/DynamicQuillTools.js"></script>

<div id="editor">The last two elements in the toolbar are our custom tools. The first one (<b>Email Addresses</b>) is a simple drop down menu that inserts the email address of the person selected and the second one (<b>U</b>) is a simple button that makes the selected text uppercase.</div>

person Forivin    schedule 19.11.2019
comment
Наконец-то рабочее решение. Автор DynamicQuillTools сделал потрясающую вещь. Но было бы здорово, если бы они опубликовали его npmjs или хотя бы package.json, чтобы его можно было установить с помощью npm. - person Rafik Farhad; 19.03.2021
comment
Не стесняйтесь делать запрос на слияние - person Forivin; 20.03.2021