fczbkk/css-selector-generator

[Feature Request] Grouping Similar Elements

roniemartinez opened this issue · 1 comments

When a very different element is added to a group of very similar elements, the result tends to become the fallback instead of "grouping" similar elements. For example below, the simplest selector is [aaa], [ddd]. Regardless of the arrangements of the children, the selector should still be the same.

  it('should group similar elements (2-2)', () => {
    root.innerHTML = `
      <div aaa="bbb"></div>
      <div aaa="ccc"></div>
      <p ddd="eee"></p>
      <p ddd="fff"></p>
    `
    const result = getCssSelector(Array.from(root.children))
    assert.ok(testSelector(Array.from(root.children), '[aaa], [ddd]'))  // passes
    assert.equal(result, '[aaa], [ddd]')  // fails
  })

  it('should group similar elements (3-1)', () => {
    root.innerHTML = `
      <div aaa="bbb"></div>
      <div aaa="ccc"></div>
      <div aaa="ddd"></div>
      <p eee="fff"></p>
    `
    const result = getCssSelector(Array.from(root.children))
    assert.ok(testSelector(Array.from(root.children), '[aaa], [eee]'))  // passes
    assert.equal(result, '[aaa], [eee]')  // fails
  })

Output:

    ✖ should subgroup similar elements (2-2)
      Chrome Headless 92.0.4515.159 (Mac OS 10.15.7)
    AssertionError: expected '[aaa=\'bbb\'], [aaa=\'ccc\'], [ddd=\'eee\'], [ddd=\'fff\']' to equal '[aaa], [ddd]'

    ✖ should subgroup similar elements (3-1)
      Chrome Headless 92.0.4515.159 (Mac OS 10.15.7)
    AssertionError: expected '[aaa=\'bbb\'], [aaa=\'ccc\'], [aaa=\'ddd\'], p' to equal '[aaa], [eee]'

Here's how the algorithm works right now:

  • It tries to find a single selector that matches all elements.
  • Then it tries to find a selector for each element specifically and join them.

I think trying to create various group combinations for elements and looking for their selectors would add too much complexity. The problem is, that with each additional combination the total number of selectors that need to be generated and tested grows exponentially.

If I will come up with some smart solution for this, I'll try to implement it. But I really don't want to brute-force this, because I'm afraid it will become a performance issue.