Procházet zdrojové kódy

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 před 3 roky
rodič
revize
be9a12c2f3

+ 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
             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)
             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'))
         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;'))
+    }
+)