Laurensius Adi
Laurensius Adi

Reputation: 272

Give uuid to check list item in Quill editor with custom blots

I want to add a unique id to each checklist item inside Quill editor.
Here's my code so far:

import Quill from 'quill'
import uuid from 'uuid'
var ListItem = Quill.import('formats/list/item')

class CustomListItem extends ListItem {
  static create() {
    const node = super.create()
    // check if list item is check
    if (node.hasAttribute('data-checked')) { //should check parent?
      node.setAttribute("id", "task"+uuid.v4())
    }
    return node
  }

  split(index, force = false) {
    if (force && (index === 0 || index >= this.length() - 1)) {
      const clone = this.clone()
      clone.domNode.id = 'task'+uuid.v4()
      if (index === 0) {
        this.parent.insertBefore(clone, this)
        return this
      }
      this.parent.insertBefore(clone, this.next)
      return clone
    }
    const next = super.split(index, force)
    next.domNode.id = 'task'+uuid.v4()
    this.cache = {}
    return next
  }
}

CustomListItem.className = 'task'
CustomListItem.blotName = 'list-item'
CustomListItem.tagName = 'LI'

export default CustomListItem

My problem is every list item including ordered and unordered list gets the same id too.

How can I check whether this list item belongs to parent List with attribute data-checked in it?

Relation between list and list item is here -> Quill List Item formats

I got a hard time understanding what's going on inside that format component too.

Upvotes: 1

Views: 729

Answers (1)

Laurensius Adi
Laurensius Adi

Reputation: 272

There were 3 types of list item: ordered, bullet, and check. Check is the one I'm going to work with. I end up giving all types of list item a unique ID, then look for the list item I need by looking on it's parent node on editor change instead on node creation like on the code above. So the node create function just become this:

static create() {
    const node = super.create()
    node.setAttribute("id", uuid.v4())
    return node
}

So all types all list item gets an UUID. Then I make a function to iterate over all list item which has a parent with attribute data-checked meaning it is a check list item.

var lists = document.querySelectorAll('li');
  [].forEach.call(lists, (list) => {
    if (list.parentNode.nodeName === 'UL'
      && list.parentNode.hasAttribute('data-checked')
      && list.innerText) {
      // do something with check list item

Upvotes: 1

Related Questions