dipson88 / treeselectjs

Treeselect on vanilla JS
MIT License
82 stars 15 forks source link

Ability to Select Which Children are Expanded #75

Closed KuzonCode closed 1 year ago

KuzonCode commented 1 year ago

It would be great if there was an option to set expanded when initialising the list.

I know that expandSelected exists. But I would like to be to expand only the top level items and not their children which are also selected by default.

dipson88 commented 1 year ago

Hello @KuzonCode. It can be too difficult I guess because now all works around openLevel prop. But you can try to use workaround like this:

const options = [
  {
    name: 'England',
    value: 1,
    htmlAttr: {
      'init-open': 'true'
    }
    ....
]

  const domElement = document.querySelector(className)
  const treeselect = new Treeselect({
    parentHtmlContainer: domElement,
    value: [4, 7, 8],
    options: options,
    openCallback: () => {
      const list = Array.from(document.querySelectorAll('[init-open="true"]'))
      list.forEach((item) => {
        const arrow = item.querySelector('.treeselect-list__item-icon')
        arrow.dispatchEvent(new Event('mousedown'))
      })
    }
  })

1) you need to add an attribute. 2) then onOpenCallback finds elements with this attribute. 3) find an arrow and emulate mosedown.

It works for me. I don't know what will be with performance if we try to do this in a huge array of data. Need to check.

KuzonCode commented 1 year ago

@dipson88, Mate! Your an absolute legend! Thank you.

Just one thing for anyone else who wants to use this in the future, I would recommend changing const list = Array.from(document.querySelectorAll('[init-open="true"]')) to be const list = Array.from(document.querySelectorAll('[init-open="true"].treeselect-list__item--closed')) This means that if the dropdown is closed an opened again it won't toggle the item closed.

Thanks again.