瀏覽代碼

x-collapse not working properly when used with click.away (#2201)

* Add failing test

* Make x-collapse compatible with @click.away

* Extend fix to elements with borders
Simone Todaro 3 年之前
父節點
當前提交
be9a12c2f3
共有 2 個文件被更改,包括 35 次插入0 次删除
  1. 4 0
      packages/alpinejs/src/utils/on.js
  2. 31 0
      tests/cypress/integration/plugins/collapse.spec.js

+ 4 - 0
packages/alpinejs/src/utils/on.js

@@ -30,6 +30,10 @@ export default function on (el, event, modifiers, callback) {
 
             if (el.offsetWidth < 1 && el.offsetHeight < 1) return
 
+            // Additional check for special implementations like x-collapse
+            // where the element doesn't have display: none
+            if (el._x_isShown === false) return
+
             next(e)
         })
     }

+ 31 - 0
tests/cypress/integration/plugins/collapse.spec.js

@@ -15,3 +15,34 @@ test('can collapse and expand element',
         get('h1').should(haveComputedStyle('height', '0px'))
     },
 )
+
+test('@click.away with x-collapse (prevent race condition)',
+    html`
+        <div x-data="{ show: false }">
+            <button @click="show = true">Show</button>
+
+            <h1 x-show="show" @click.away="show = false" x-collapse>h1</h1>
+        </div>
+    `,
+    ({ get }) => {
+        get('h1').should(haveComputedStyle('height', '0px'))
+        get('button').click()
+        get('h1').should(haveAttribute('style', 'overflow: hidden; height: auto;'))
+    }
+)
+
+
+test('@click.away with x-collapse and borders (prevent race condition)',
+    html`
+        <div x-data="{ show: false }">
+            <button @click="show = true">Show</button>
+
+            <h1 style="border: 1x solid" x-show="show" @click.away="show = false" x-collapse>h1</h1>
+        </div>
+    `,
+    ({ get }) => {
+        get('h1').should(haveComputedStyle('height', '0px'))
+        get('button').click()
+        get('h1').should(haveAttribute('style', 'overflow: hidden; height: auto;'))
+    }
+)