소스 검색

Add focus (#2570)

* wip

* Prevent x-bind objects from being observed

* Force $id to return a plain string instead of an Alpine object

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* Add tests and documentation
Caleb Porzio 3 년 전
부모
커밋
198192655e

+ 1 - 1
README.md

@@ -34,7 +34,7 @@ Package | Description
 [history](packages/history) | A plugin for binding data to query string parameters using the history API (name is likely to change)
 [intersect](packages/intersect) | A plugin for triggering JS expressions based on elements intersecting with the viewport
 [morph](packages/morph) | A plugin for morphing HTML (like morphdom) inside the page intelligently
-[trap](packages/trap) | A plugin that allows you to conditionally trap focus inside an element
+[focus](packages/focus) | A plugin that allows you to manage focus inside an element
 
 The compiled JS files (as a result of running `npm run [build/watch]`) to be included as a `<script>` tag for example are stored in each package's `packages/[package]/dist` directory.
 

+ 1 - 1
index.html

@@ -3,7 +3,7 @@
     <script src="./packages/morph/dist/cdn.js" defer></script>
     <script src="./packages/history/dist/cdn.js"></script>
     <script src="./packages/persist/dist/cdn.js"></script>
-    <script src="./packages/trap/dist/cdn.js"></script>
+    <script src="./packages/focus/dist/cdn.js"></script>
     <script src="./packages/alpinejs/dist/cdn.js" defer></script>
     <!-- <script src="https://unpkg.com/alpinejs@3.0.0/dist/cdn.min.js" defer></script> -->
 

+ 8 - 2
packages/alpinejs/src/alpine.js

@@ -1,12 +1,13 @@
 import { setReactivityEngine, disableEffectScheduling, reactive, effect, release, raw } from './reactivity'
 import { mapAttributes, directive, setPrefix as prefix, prefix as prefixed } from './directives'
-import { start, addRootSelector, addInitSelector, closestRoot, initTree } from './lifecycle'
+import { start, addRootSelector, addInitSelector, closestRoot, findClosest, initTree } from './lifecycle'
 import { mutateDom, deferMutations, flushAndStopDeferringMutations } from './mutation'
-import { mergeProxies, closestDataStack, addScopeToNode } from './scope'
+import { mergeProxies, closestDataStack, addScopeToNode, scope as $data } from './scope'
 import { setEvaluator, evaluate, evaluateLater } from './evaluator'
 import { transition } from './directives/x-transition'
 import { clone, skipDuringClone } from './clone'
 import { interceptor } from './interceptor'
+import { getBinding as bound } from './utils/bind'
 import { debounce } from './utils/debounce'
 import { throttle } from './utils/throttle'
 import { setStyles } from './utils/styles'
@@ -14,6 +15,7 @@ import { nextTick } from './nextTick'
 import { plugin } from './plugin'
 import { magic } from './magics'
 import { store } from './store'
+import { bind } from './binds'
 import { data } from './datas'
 
 let Alpine = {
@@ -35,6 +37,7 @@ let Alpine = {
     evaluateLater,
     setEvaluator,
     mergeProxies,
+    findClosest,
     closestRoot,
     interceptor, // INTERNAL: not public API and is subject to change without major release.
     transition, // INTERNAL
@@ -53,7 +56,10 @@ let Alpine = {
     store,
     start,
     clone,
+    bound,
+    $data,
     data,
+    bind,
 }
 
 export default Alpine

+ 20 - 0
packages/alpinejs/src/binds.js

@@ -0,0 +1,20 @@
+
+let binds = {}
+
+export function bind(name, object) {
+    binds[name] = typeof object !== 'function' ? () => object : object
+}
+
+export function injectBindingProviders(obj) {
+    Object.entries(binds).forEach(([name, callback]) => {
+        Object.defineProperty(obj, name, {
+            get() {
+                return (...args) => {
+                    return callback(...args)
+                }
+            }
+        })
+    })
+
+    return obj
+}

+ 27 - 24
packages/alpinejs/src/directives/x-bind.js

@@ -2,11 +2,14 @@ import { attributesOnly, directive, directives, into, mapAttributes, prefix, sta
 import { evaluateLater } from '../evaluator'
 import { mutateDom } from '../mutation'
 import bind from '../utils/bind'
+import { injectBindingProviders } from '../binds'
 
 mapAttributes(startingWith(':', into(prefix('bind:'))))
 
 directive('bind', (el, { value, modifiers, expression, original }, { effect }) => {
-    if (! value) return applyBindingsObject(el, expression, original, effect)
+    if (! value) {
+        return applyBindingsObject(el, expression, original, effect)
+    }
 
     if (value === 'key') return storeKeyForXFor(el, expression)
 
@@ -21,38 +24,38 @@ directive('bind', (el, { value, modifiers, expression, original }, { effect }) =
 })
 
 function applyBindingsObject(el, expression, original, effect) {
+    let bindingProviders = {}
+    injectBindingProviders(bindingProviders)
+   
     let getBindings = evaluateLater(el, expression)
 
     let cleanupRunners = []
 
-    effect(() => {
-        while (cleanupRunners.length) cleanupRunners.pop()()
-
-        getBindings(bindings => {
-            let attributes = Object.entries(bindings).map(([name, value]) => ({ name, value }))
-
-            let staticAttributes = attributesOnly(attributes)
-            
-            // Handle binding normal HTML attributes (non-Alpine directives).
-            attributes = attributes.map(attribute => {
-                if (staticAttributes.find(attr => attr.name === attribute.name)) {
-                    return {
-                        name: `x-bind:${attribute.name}`,
-                        value: `"${attribute.value}"`,
-                    }
-                }
+    while (cleanupRunners.length) cleanupRunners.pop()()
 
-                return attribute
-            })
+    getBindings(bindings => {
+        let attributes = Object.entries(bindings).map(([name, value]) => ({ name, value }))
 
-            directives(el, attributes, original).map(handle => {
-                cleanupRunners.push(handle.runCleanups)
+        let staticAttributes = attributesOnly(attributes)
+        
+        // Handle binding normal HTML attributes (non-Alpine directives).
+        attributes = attributes.map(attribute => {
+            if (staticAttributes.find(attr => attr.name === attribute.name)) {
+                return {
+                    name: `x-bind:${attribute.name}`,
+                    value: `"${attribute.value}"`,
+                }
+            }
 
-                handle()
-            })
+            return attribute
         })
 
-    })
+        directives(el, attributes, original).map(handle => {
+            cleanupRunners.push(handle.runCleanups)
+
+            handle()
+        })
+    }, { scope: bindingProviders } )
 }
 
 function storeKeyForXFor(el, expression) {

+ 2 - 4
packages/alpinejs/src/magics/$data.js

@@ -1,6 +1,4 @@
-import { closestDataStack, mergeProxies } from '../scope'
+import { scope } from '../scope'
 import { magic } from '../magics'
 
-magic('data', el => {
-    return mergeProxies(closestDataStack(el))
-})
+magic('data', el => scope(el))

+ 2 - 13
packages/alpinejs/src/magics/$id.js

@@ -9,17 +9,6 @@ magic('id', el => (name, key = null) => {
         : findAndIncrementId(name)
 
     return key
-        ? new AlpineId(`${name}-${id}-${key}`)
-        : new AlpineId(`${name}-${id}`)
+        ? `${name}-${id}-${key}`
+        : `${name}-${id}`
 })
-
-class AlpineId {
-    constructor(id) {
-        this.id = id
-    }
-
-    toString() {
-        return this.id
-    }
-}
-

+ 21 - 1
packages/alpinejs/src/utils/bind.js

@@ -7,7 +7,7 @@ export default function bind(el, name, value, modifiers = []) {
     if (! el._x_bindings) el._x_bindings = reactive({})
 
     el._x_bindings[name] = value
-
+   
     name = modifiers.includes('camel') ? camelCase(name) : name
 
     switch (name) {
@@ -127,3 +127,23 @@ function isBooleanAttr(attrName) {
 function attributeShouldntBePreservedIfFalsy(name) {
     return ! ['aria-pressed', 'aria-checked', 'aria-expanded'].includes(name)
 }
+
+export function getBinding(el, name, fallback) {
+    // First let's get it out of Alpine bound data. 
+    if (el._x_bindings && el._x_bindings[name] !== undefined) return el._x_bindings[name]
+
+    // If not, we'll return the literal attribute. 
+    let attr = el.getAttribute(name)
+
+    // Nothing bound:
+    if (attr === null) return typeof fallback === 'function' ? fallback() : fallback
+   
+    if (isBooleanAttr(name)) {
+        return !! [name, 'true'].includes(attr)
+    }
+
+    // The case of a custom attribute with no value. Ex: <div manual> 
+    if (attr === '') return true
+   
+    return attr
+}

+ 134 - 16
packages/docs/src/en/plugins/trap.md → packages/docs/src/en/plugins/focus.md

@@ -1,15 +1,15 @@
 ---
 order: 3
-title: Trap
-description: Easily trap page focus within an element (modals, dialogs, etc...)
-graph_image: https://alpinejs.dev/social_trap.jpg
+title: Focus
+description: Easily manage focus within the page
+graph_image: https://alpinejs.dev/social_focus.jpg
 ---
 
-# Trap Plugin
+# Focus Plugin
 
-Alpine's Trap plugin allows you to conditionally trap focus inside an element.
+Alpine's Focus plugin allows you to manage focus on a page.
 
-This is useful for modals and other dialog elements.
+> This plugin internally makes heavy use of the open source tool: [Tabbable](https://github.com/focus-trap/tabbable). Big thanks to that team for providing a much needed solution to this problem.
 
 <a name="installation"></a>
 ## Installation
@@ -22,7 +22,7 @@ You can include the CDN build of this plugin as a `<script>` tag, just make sure
 
 ```alpine
 <!-- Alpine Plugins -->
-<script defer src="https://unpkg.com/@alpinejs/trap@3.x.x/dist/cdn.min.js"></script>
+<script defer src="https://unpkg.com/@alpinejs/focus@3.x.x/dist/cdn.min.js"></script>
 
 <!-- Alpine Core -->
 <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
@@ -30,19 +30,19 @@ You can include the CDN build of this plugin as a `<script>` tag, just make sure
 
 ### Via NPM
 
-You can install Trap from NPM for use inside your bundle like so:
+You can install Focus from NPM for use inside your bundle like so:
 
 ```shell
-npm install @alpinejs/trap
+npm install @alpinejs/focus
 ```
 
 Then initialize it from your bundle:
 
 ```js
 import Alpine from 'alpinejs'
-import trap from '@alpinejs/trap'
+import focus from '@alpinejs/focus'
 
-Alpine.plugin(trap)
+Alpine.plugin(focus)
 
 ...
 ```
@@ -50,7 +50,7 @@ Alpine.plugin(trap)
 <a name="x-trap"></a>
 ## x-trap
 
-The primary API for using this plugin is the `x-trap` directive.
+Focus offers a dedicated API for trapping focus within an element: the `x-trap` directive.
 
 `x-trap` accepts a JS expression. If the result of that expression is true, then the focus will be trapped inside that element until the expression becomes false, then at that point, focus will be returned to where it was previously.
 
@@ -99,7 +99,7 @@ For example:
 <!-- END_VERBATIM -->
 
 <a name="nesting"></a>
-## Nesting dialogs
+### Nesting dialogs
 
 Sometimes you may want to nest one dialog inside another. `x-trap` makes this trivial and handles it automatically.
 
@@ -180,10 +180,10 @@ Here is nesting in action:
 <!-- END_VERBATIM -->
 
 <a name="modifiers"></a>
-## Modifiers
+### Modifiers
 
 <a name="inert"></a>
-### .inert
+#### .inert
 
 When building things like dialogs/modals, it's recommended to hide all the other elements on the page from screenreaders when trapping focus.
 
@@ -214,7 +214,7 @@ By adding `.inert` to `x-trap`, when focus is trapped, all other elements on the
 ```
 
 <a name="noscroll"></a>
-### .noscroll
+#### .noscroll
 
 When building dialogs/modals with Alpine, it's recommended that you disable scrollling for the surrounding content when the dialog is open.
 
@@ -251,3 +251,121 @@ For example:
     </div>
 </div>
 <!-- END_VERBATIM -->
+
+<a name="focus-magic"></a>
+## $focus
+
+This plugin offers many smaller utilities for managing focus within a page. These utilities are exposed via the `$focus` magic.
+
+| Property | Description |
+| ---       | --- |
+| `focus(el)`   | Focus the passed element (handling annoyances internally: using nextTick, etc.) |
+| `focusable(el)`   | Detect weather or not an element is focusable |
+| `focusables()`   | Get all "focusable" elements within the current element |
+| `focused()`   | Get the currently focused element on the page |
+| `lastFocused()`   | Get the last focused element on the page |
+| `within(el)`   | Specify an element to scope the `$focus` magic to (the current element by default) |
+| `first()`   | Focus the first focusable element |
+| `last()`   | Focus the last focusable element |
+| `next()`   | Focus the next focusable element |
+| `previous()`   | Focus the previous focusable element |
+| `noscroll()`   | Prevent scrolling to the element about to be focused |
+| `wrap()`   | When retrieving "next" or "previous" use "wrap around" (ex. returning the first element if getting the "next" element of the last element) |
+| `getFirst()`   | Retrieve the first focusable element |
+| `getLast()`   | Retrieve the last focusable element |
+| `getNext()`   | Retrieve the next focusable element |
+| `getPrevious()`   | Retrieve the previous focusable element |
+
+Let's walk through a few examples of these utilities in use. The example below allows the user to control focus within the group of buttons using the arrow keys. You can test this by clicking on a button, then using the arrow keys to move focus around:
+
+```alpine
+<div
+    @keydown.right="$focus.next()"
+    @keydown.left="$focus.previous()"
+>
+    <button>First</button>
+    <button>Second</button>
+    <button>Third</button>
+</div>
+```
+
+<!-- START_VERBATIM -->
+<div class="demo">
+<div
+    x-data
+    @keydown.right="$focus.next()"
+    @keydown.left="$focus.previous()"
+>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">First</button>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">Second</button>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">Third</button>
+</div>
+(Click a button, then use the arrow keys to move left and right)
+</div>
+<!-- END_VERBATIM -->
+
+Notice how if the last button is focused, pressing "right arrow" won't do anything. Let's add the `.wrap()` method so that focus "wraps around":
+
+```alpine
+<div
+    @keydown.right="$focus.wrap().next()"
+    @keydown.left="$focus.wrap().previous()"
+>
+    <button>First</button>
+    <button>Second</button>
+    <button>Third</button>
+</div>
+```
+
+<!-- START_VERBATIM -->
+<div class="demo">
+<div
+    x-data
+    @keydown.right="$focus.wrap().next()"
+    @keydown.left="$focus.wrap().previous()"
+>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">First</button>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">Second</button>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">Third</button>
+</div>
+(Click a button, then use the arrow keys to move left and right)
+</div>
+<!-- END_VERBATIM -->
+
+Now, let's add two buttons, one to focus the first element in the button group, and another focus the last element:
+
+```alpine
+<button @click="$focus.within($refs.buttons).first()">Focus "First"</button>
+<button @click="$focus.within($refs.buttons).last()">Focus "Last"</button>
+
+<div
+    x-ref="buttons"
+    @keydown.right="$focus.wrap().next()"
+    @keydown.left="$focus.wrap().previous()"
+>
+    <button>First</button>
+    <button>Second</button>
+    <button>Third</button>
+</div>
+```
+
+<!-- START_VERBATIM -->
+<div class="demo" x-data>
+<button @click="$focus.within($refs.buttons).first()">Focus "First"</button>
+<button @click="$focus.within($refs.buttons).last()">Focus "Last"</button>
+
+<hr class="mt-2 mb-2"/>
+
+<div
+    x-ref="buttons"
+    @keydown.right="$focus.wrap().next()"
+    @keydown.left="$focus.wrap().previous()"
+>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">First</button>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">Second</button>
+    <button class="focus:outline-none focus:ring-2 focus:ring-aqua-400">Third</button>
+</div>
+</div>
+<!-- END_VERBATIM -->
+
+Notice that we needed to add a `.within()` method for each button so that `$focus` knows to scope itself to a different element (the `div` wrapping the buttons).

+ 0 - 0
packages/trap/.gitignore → packages/focus/.gitignore


+ 0 - 0
packages/trap/builds/cdn.js → packages/focus/builds/cdn.js


+ 3 - 0
packages/focus/builds/module.js

@@ -0,0 +1,3 @@
+import registerFocusPlugin from '../src/index.js'
+
+export default registerFocusPlugin

+ 2 - 2
packages/trap/package.json → packages/focus/package.json

@@ -1,7 +1,7 @@
 {
-    "name": "@alpinejs/trap",
+    "name": "@alpinejs/focus",
     "version": "3.7.1",
-    "description": "Trap focus on a page within a specific element",
+    "description": "Manage focus within a page",
     "author": "Caleb Porzio",
     "license": "MIT",
     "main": "dist/module.cjs.js",

+ 189 - 0
packages/focus/src/index.js

@@ -0,0 +1,189 @@
+import { createFocusTrap } from 'focus-trap'
+import { focusable, tabbable, isFocusable } from 'tabbable'
+
+export default function (Alpine) {
+    let lastFocused
+    let currentFocused 
+
+    window.addEventListener('focusin', () => {
+        lastFocused = currentFocused
+        currentFocused = document.activeElement
+    })
+
+    Alpine.magic('focus', el => {
+        let within = el
+       
+        return {
+            __noscroll: false, 
+            __wrapAround: false, 
+            within(el) { within = el; return this },
+            withoutScrolling() { this.__noscroll = true; return this },
+            noscroll() { this.__noscroll = true; return this },
+            withWrapAround() { this.__wrapAround = true; return this },
+            wrap() { return this.withWrapAround() },
+            focusable(el) {
+                return isFocusable(el)
+            },
+            previouslyFocused() {
+                return lastFocused
+            },
+            lastFocused() {
+                return lastFocused
+            },
+            focused() {
+                return currentFocused
+            },
+            focusables() {
+                if (Array.isArray(within)) return within 
+
+                return focusable(within, { displayCheck: 'none' })
+            },
+            all() { return this.focusables() },
+            isFirst(el) {
+                let els = this.all() 
+                
+                return els[0] && els[0].isSameNode(el)
+            },
+            isLast(el) {
+                let els = this.all() 
+                
+                return els.length && els.slice(-1)[0].isSameNode(el)
+            },
+            getFirst() { return this.all()[0] },
+            getLast() { return this.all().slice(-1)[0] },
+            getNext() {
+                let list = this.all()
+                let current = document.activeElement
+
+                // Can't find currently focusable element in list.
+                if (list.indexOf(current) === -1) return
+
+                // This is the last element in the list and we want to wrap around.
+                if (this.__wrapAround && list.indexOf(current) === list.length - 1) {
+                    return list[0]
+                }
+
+                return list[list.indexOf(current) + 1]
+            },
+            getPrevious() {
+                let list = this.all()
+                let current = document.activeElement
+
+                // Can't find currently focusable element in list.
+                if (list.indexOf(current) === -1) return
+
+                // This is the first element in the list and we want to wrap around.
+                if (this.__wrapAround && list.indexOf(current) === 0) {
+                    return list.slice(-1)[0]
+                }
+
+                return list[list.indexOf(current) - 1]
+            },
+            first() { this.focus(this.getFirst()) },
+            last() { this.focus(this.getLast()) },
+            next() { this.focus(this.getNext()) },
+            previous() { this.focus(this.getPrevious()) },
+            prev() { return this.previous() },
+            focus(el) {
+                if (! el) return 
+
+                setTimeout(() => {
+                    if (! el.hasAttribute('tabindex')) el.setAttribute('tabindex', '0')
+
+                    el.focus({ preventScroll: this._noscroll })
+                })
+            }
+        }
+    })
+
+    Alpine.directive('trap', Alpine.skipDuringClone(
+        (el, { expression, modifiers }, { effect, evaluateLater }) => {
+            let evaluator = evaluateLater(expression)
+
+            let oldValue = false
+
+            let trap = createFocusTrap(el, { 
+                escapeDeactivates: false,
+                allowOutsideClick: true,
+                fallbackFocus: () => el,
+            })
+
+            let undoInert = () => {}
+            let undoDisableScrolling = () => {}
+
+            effect(() => evaluator(value => {
+                if (oldValue === value) return
+
+                // Start trapping.
+                if (value && ! oldValue) {
+                    setTimeout(() => {
+                        if (modifiers.includes('inert')) undoInert = setInert(el)
+                        if (modifiers.includes('noscroll')) undoDisableScrolling = disableScrolling()
+
+                        trap.activate()
+                    });
+                }
+
+                // Stop trapping.
+                if (! value && oldValue) {
+                    undoInert()
+                    undoInert = () => {}
+
+                    undoDisableScrolling()
+                    undoDisableScrolling = () => {}
+
+                    trap.deactivate()
+                }
+
+                oldValue = !! value
+            }))
+        },
+        // When cloning, we only want to add aria-hidden attributes to the
+        // DOM and not try to actually trap, as trapping can mess with the
+        // live DOM and isn't just isolated to the cloned DOM.
+        (el, { expression, modifiers }, { evaluate }) => {
+            if (modifiers.includes('inert') && evaluate(expression)) setInert(el)
+        },
+    ))
+}
+
+function setInert(el) {
+    let undos = []
+
+    crawlSiblingsUp(el, (sibling) => {
+        let cache = sibling.hasAttribute('aria-hidden')
+
+        sibling.setAttribute('aria-hidden', 'true')
+
+        undos.push(() => cache || sibling.removeAttribute('aria-hidden'))
+    })
+
+    return () => {
+        while(undos.length) undos.pop()()
+    }
+}
+
+function crawlSiblingsUp(el, callback) {
+    if (el.isSameNode(document.body) || ! el.parentNode) return
+
+    Array.from(el.parentNode.children).forEach(sibling => {
+        if (! sibling.isSameNode(el)) callback(sibling)
+
+        crawlSiblingsUp(el.parentNode, callback)
+    })
+}
+
+function disableScrolling() {
+    let overflow = document.documentElement.style.overflow
+    let paddingRight = document.documentElement.style.paddingRight
+
+    let scrollbarWidth = window.innerWidth - document.documentElement.clientWidth
+
+    document.documentElement.style.overflow = 'hidden'
+    document.documentElement.style.paddingRight = `${scrollbarWidth}px`
+
+    return () => {
+        document.documentElement.style.overflow = overflow
+        document.documentElement.style.paddingRight = paddingRight
+    }
+}

+ 0 - 3
packages/trap/builds/module.js

@@ -1,3 +0,0 @@
-import registerTrapDirective from '../src/index.js'
-
-export default registerTrapDirective

+ 0 - 94
packages/trap/src/index.js

@@ -1,94 +0,0 @@
-import { createFocusTrap } from 'focus-trap';
-
-export default function (Alpine) {
-    Alpine.directive('trap', Alpine.skipDuringClone(
-        (el, { expression, modifiers }, { effect, evaluateLater }) => {
-            let evaluator = evaluateLater(expression)
-
-            let oldValue = false
-
-            let trap = createFocusTrap(el, { 
-                escapeDeactivates: false,
-                allowOutsideClick: true,
-                fallbackFocus: () => el,
-            })
-
-            let undoInert = () => {}
-            let undoDisableScrolling = () => {}
-
-            effect(() => evaluator(value => {
-                if (oldValue === value) return
-
-                // Start trapping.
-                if (value && ! oldValue) {
-                    setTimeout(() => {
-                        if (modifiers.includes('inert')) undoInert = setInert(el)
-                        if (modifiers.includes('noscroll')) undoDisableScrolling = disableScrolling()
-
-                        trap.activate()
-                    });
-                }
-
-                // Stop trapping.
-                if (! value && oldValue) {
-                    undoInert()
-                    undoInert = () => {}
-
-                    undoDisableScrolling()
-                    undoDisableScrolling = () => {}
-
-                    trap.deactivate()
-                }
-
-                oldValue = !! value
-            }))
-        },
-        // When cloning, we only want to add aria-hidden attributes to the
-        // DOM and not try to actually trap, as trapping can mess with the
-        // live DOM and isn't just isolated to the cloned DOM.
-        (el, { expression, modifiers }, { evaluate }) => {
-            if (modifiers.includes('inert') && evaluate(expression)) setInert(el)
-        },
-    ))
-}
-
-function setInert(el) {
-    let undos = []
-
-    crawlSiblingsUp(el, (sibling) => {
-        let cache = sibling.hasAttribute('aria-hidden')
-
-        sibling.setAttribute('aria-hidden', 'true')
-
-        undos.push(() => cache || sibling.removeAttribute('aria-hidden'))
-    })
-
-    return () => {
-        while(undos.length) undos.pop()()
-    }
-}
-
-function crawlSiblingsUp(el, callback) {
-    if (el.isSameNode(document.body) || ! el.parentNode) return
-
-    Array.from(el.parentNode.children).forEach(sibling => {
-        if (! sibling.isSameNode(el)) callback(sibling)
-
-        crawlSiblingsUp(el.parentNode, callback)
-    })
-}
-
-function disableScrolling() {
-    let overflow = document.documentElement.style.overflow
-    let paddingRight = document.documentElement.style.paddingRight
-
-    let scrollbarWidth = window.innerWidth - document.documentElement.clientWidth
-
-    document.documentElement.style.overflow = 'hidden'
-    document.documentElement.style.paddingRight = `${scrollbarWidth}px`
-
-    return () => {
-        document.documentElement.style.overflow = overflow
-        document.documentElement.style.paddingRight = paddingRight
-    }
-}

+ 1 - 1
scripts/build.js

@@ -11,7 +11,7 @@ let brotliSize = require('brotli-size');
     'persist',
     'collapse',
     'morph',
-    'trap',
+    'focus',
 ]).forEach(package => {
     if (! fs.existsSync(`./packages/${package}/dist`)) {
         fs.mkdirSync(`./packages/${package}/dist`, 0744);

+ 4 - 4
scripts/release.js

@@ -45,8 +45,8 @@ function writeNewAlpineVersion() {
     writeToPackageDotJson('persist', 'version', version)
     console.log('Bumping @alpinejs/persist package.json: '+version)
 
-    writeToPackageDotJson('trap', 'version', version)
-    console.log('Bumping @alpinejs/trap package.json: '+version)
+    writeToPackageDotJson('focus', 'version', version)
+    console.log('Bumping @alpinejs/focus package.json: '+version)
 
     writeToPackageDotJson('collapse', 'version', version)
     console.log('Bumping @alpinejs/collapse package.json: '+version)
@@ -80,8 +80,8 @@ function publish() {
     console.log('Publishing @alpinejs/persist on NPM...');
     runFromPackage('persist', 'npm publish --access public')
 
-    console.log('Publishing @alpinejs/trap on NPM...');
-    runFromPackage('trap', 'npm publish --access public')
+    console.log('Publishing @alpinejs/focus on NPM...');
+    runFromPackage('focus', 'npm publish --access public')
 
     console.log('Publishing @alpinejs/collapse on NPM...');
     runFromPackage('collapse', 'npm publish --access public')

+ 46 - 0
tests/cypress/integration/custom-bind.spec.js

@@ -0,0 +1,46 @@
+import { haveText, html, test } from '../utils'
+
+test('can register custom bind object',
+    html`
+        <script>
+            document.addEventListener('alpine:init', () => {
+                Alpine.bind('Foo', {
+                    'x-init'() { this.$el.innerText = 'bar' },
+                })
+            })
+        </script>
+
+        <div x-data x-bind="Foo"></div>
+    `,
+    ({ get }) => get('div').should(haveText('bar'))
+)
+
+test('can register custom bind as function',
+    html`
+        <script>
+            document.addEventListener('alpine:init', () => {
+                Alpine.bind('Foo', () => ({
+                    'x-init'() { this.$el.innerText = 'bar' },
+                }))
+            })
+        </script>
+
+        <div x-data x-bind="Foo"></div>
+    `,
+    ({ get }) => get('div').should(haveText('bar'))
+)
+
+test('can consume custom bind as function',
+    html`
+        <script>
+            document.addEventListener('alpine:init', () => {
+                Alpine.bind('Foo', (subject) => ({
+                    'x-init'() { this.$el.innerText = subject },
+                }))
+            })
+        </script>
+
+        <div x-data x-bind="Foo('bar')"></div>
+    `,
+    ({ get }) => get('div').should(haveText('bar'))
+)

+ 41 - 0
tests/cypress/integration/directives/x-bind.spec.js

@@ -409,3 +409,44 @@ test('x-bind object syntax event handlers defined as functions receive the event
         get('span').should(haveText('bar'))
     }
 )
+
+test('x-bind object syntax event handlers defined as functions receive the event object as their first argument',
+    html`
+        <script>
+            window.data = () => { return {
+                button: {
+                    ['@click']() {
+                        this.$refs.span.innerText = this.$el.id
+                    }
+                }
+            }}
+        </script>
+        <div x-data="window.data()">
+            <button x-bind="button" id="bar">click me</button>
+
+            <span x-ref="span">foo</span>
+        </div>
+    `,
+    ({ get }) => {
+        get('span').should(haveText('foo'))
+        get('button').click()
+        get('span').should(haveText('bar'))
+    }
+)
+
+test('Can retrieve Alpine bound data with global bound method',
+    html`
+        <div id="1" x-data foo="bar" x-text="Alpine.bound($el, 'foo')"></div>
+        <div id="2" x-data :foo="'bar'" x-text="Alpine.bound($el, 'foo')"></div>
+        <div id="3" x-data foo x-text="Alpine.bound($el, 'foo')"></div>
+        <div id="4" x-data x-text="Alpine.bound($el, 'foo')"></div>
+        <div id="5" x-data x-text="Alpine.bound($el, 'foo', 'bar')"></div>
+    `,
+    ({ get }) => {
+        get('#1').should(haveText('bar'))
+        get('#2').should(haveText('bar'))
+        get('#3').should(haveText('true'))
+        get('#4').should(haveText(''))
+        get('#5').should(haveText('bar'))
+    }
+)

+ 273 - 0
tests/cypress/integration/plugins/focus.spec.js

@@ -0,0 +1,273 @@
+import { haveText, test, html, haveFocus, notHaveAttribute, haveAttribute, notHaveFocus, notHaveText } from '../../utils'
+
+test('can trap focus',
+    [html`
+        <div x-data="{ open: false }">
+            <input type="text" id="1">
+            <button id="2" @click="open = true">open</button>
+            <div>
+                <div x-trap="open">
+                    <input type="text" id="3">
+                    <button @click="open = false" id="4">close</button>
+                </div>
+            </div>
+        </div>
+    `],
+    ({ get }, reload) => {
+        get('#1').click()
+        get('#1').should(haveFocus())
+        get('#2').click()
+        get('#3').should(haveFocus())
+        cy.focused().tab()
+        get('#4').should(haveFocus())
+        cy.focused().tab()
+        get('#3').should(haveFocus())
+        cy.focused().tab({shift: true})
+        get('#4').should(haveFocus())
+        cy.focused().click()
+        get('#2').should(haveFocus())
+    },
+)
+
+test('works with clone',
+    [html`
+        <div id="foo" x-data="{
+            open: false,
+            triggerClone() {
+                var original = document.getElementById('foo');
+                var copy = original.cloneNode(true);
+                Alpine.clone(original, copy);
+                var p = document.createElement('p');
+                p.textContent = 'bar';
+                copy.appendChild(p);
+                original.parentNode.replaceChild(copy, original);
+            }
+        }">
+            <button id="one" @click="open = true">Trap</button>
+            <div x-trap="open">
+                <input type="text">
+                <button id="two" @click="triggerClone()">Test</button>
+            </div>
+        </div>
+    `],
+    ({ get, wait }, reload) => {
+        get('#one').click()
+        get('#two').click()
+        get('p').should(haveText('bar'))
+    }
+)
+
+test('can trap focus with inert',
+    [html`
+        <div x-data="{ open: false }">
+            <h1>I should have aria-hidden when outside trap</h1>
+
+            <button id="open" @click="open = true">open</button>
+
+            <div x-trap.inert="open">
+                <button @click="open = false" id="close">close</button>
+            </div>
+        </div>
+    `],
+    ({ get }, reload) => {
+        get('#open').should(notHaveAttribute('aria-hidden', 'true'))
+        get('#open').click()
+        get('#open').should(haveAttribute('aria-hidden', 'true'))
+        get('#close').click()
+        get('#open').should(notHaveAttribute('aria-hidden', 'true'))
+    },
+)
+
+test('can trap focus with noscroll',
+    [html`
+        <div x-data="{ open: false }">
+            <button id="open" @click="open = true">open</button>
+
+            <div x-trap.noscroll="open">
+                <button @click="open = false" id="close">close</button>
+            </div>
+
+            <div style="height: 100vh">&nbsp;</div>
+        </div>
+    `],
+    ({ get, window }, reload) => {
+        window().then((win) => {
+            let scrollbarWidth = win.innerWidth - win.document.documentElement.clientWidth
+            get('#open').click()
+            get('html').should(haveAttribute('style', `overflow: hidden; padding-right: ${scrollbarWidth}px;`))
+            get('#close').click()
+            get('html').should(notHaveAttribute('style', `overflow: hidden; padding-right: ${scrollbarWidth}px;`))
+        })
+    },
+)
+
+test('$focus.focus',
+    [html`
+        <div x-data>
+            <button id="press-me" @click="$focus.focus(document.querySelector('#focus-me'))">Focus Other</button>
+
+            <button id="focus-me">Other</button>
+        </div>
+    `],
+    ({ get }) => {
+        get('#focus-me').should(notHaveFocus())
+        get('#press-me').click()
+        get('#focus-me').should(haveFocus())
+    },
+)
+
+test('$focus.focusable',
+    [html`
+        <div x-data>
+            <div id="1" x-text="$focus.focusable($el)"></div>
+            <button id="2" x-text="$focus.focusable($el)"></button>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').should(haveText('false'))
+        get('#2').should(haveText('true'))
+    },
+)
+
+test('$focus.focusables',
+    [html`
+        <div x-data>
+            <h1 x-text="$focus.within($refs.container).focusables().length"></h1>
+            <div x-ref="container">
+                <button>1</button>
+                <div>2</div>
+                <button>3</button>
+            </div>
+        </div>
+    `],
+    ({ get }) => {
+        get('h1').should(haveText('2'))
+    },
+)
+
+test('$focus.focused',
+    [html`
+        <div x-data>
+            <button @click="$el.textContent = $el.isSameNode($focus.focused())">im-focused</button>
+        </div>
+    `],
+    ({ get }) => {
+        get('button').click()
+        get('button').should(haveText('true'))
+    },
+)
+
+test('$focus.lastFocused',
+    [html`
+        <div x-data>
+            <button id="1" x-ref="first">first-focused</button>
+            <button id="2" @click="$el.textContent = $refs.first.isSameNode($focus.lastFocused())">second-focused</button>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').click()
+        get('#2').click()
+        get('#2').should(haveText('true'))
+    },
+)
+
+test('$focus.within',
+    [html`
+        <div x-data>
+            <button id="1" x-text="$focus.within($refs.first).focusables().length"></button>
+
+            <div x-ref="first">
+                <button>1</button>
+                <button>2</button>
+            </div>
+
+            <div>
+                <button>1</button>
+                <button>2</button>
+                <button>3</button>
+            </div>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').should(haveText('2'))
+    },
+)
+
+test('$focus.next',
+    [html`
+        <div x-data>
+            <div x-ref="first">
+                <button id="1" @click="$focus.within($refs.first).next(); $nextTick(() => $el.textContent = $focus.focused().textContent)">1</button>
+                <button>2</button>
+            </div>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').click()
+        get('#1').should(haveText('2'))
+    },
+)
+
+test('$focus.prev',
+    [html`
+        <div x-data>
+            <div x-ref="first">
+                <button>2</button>
+                <button id="1" @click="$focus.within($refs.first).prev(); $nextTick(() => $el.textContent = $focus.focused().textContent)">1</button>
+            </div>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').click()
+        get('#1').should(haveText('2'))
+    },
+)
+
+test('$focus.wrap',
+    [html`
+        <div x-data>
+            <div x-ref="first">
+                <button>2</button>
+                <button id="1" @click="$focus.within($refs.first).wrap().next(); $nextTick(() => $el.textContent = $focus.focused().textContent)">1</button>
+            </div>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').click()
+        get('#1').should(haveText('2'))
+    },
+)
+
+test('$focus.first',
+    [html`
+        <div x-data>
+            <button id="1" @click="$focus.within($refs.first).first(); $nextTick(() => $el.textContent = $focus.focused().textContent)">1</button>
+
+            <div x-ref="first">
+                <button>2</button>
+                <button>3</button>
+            </div>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').click()
+        get('#1').should(haveText('2'))
+    },
+)
+
+test('$focus.last',
+    [html`
+        <div x-data>
+            <button id="1" @click="$focus.within($refs.first).last(); $nextTick(() => $el.textContent = $focus.focused().textContent)">1</button>
+
+            <div x-ref="first">
+                <button>2</button>
+                <button>3</button>
+            </div>
+        </div>
+    `],
+    ({ get }) => {
+        get('#1').click()
+        get('#1').should(haveText('3'))
+    },
+)

+ 0 - 102
tests/cypress/integration/plugins/trap.spec.js

@@ -1,102 +0,0 @@
-import { haveText, test, html, haveFocus, notHaveAttribute, haveAttribute } from '../../utils'
-
-test('can trap focus',
-    [html`
-        <div x-data="{ open: false }">
-            <input type="text" id="1">
-            <button id="2" @click="open = true">open</button>
-            <div>
-                <div x-trap="open">
-                    <input type="text" id="3">
-                    <button @click="open = false" id="4">close</button>
-                </div>
-            </div>
-        </div>
-    `],
-    ({ get }, reload) => {
-        get('#1').click()
-        get('#1').should(haveFocus())
-        get('#2').click()
-        get('#3').should(haveFocus())
-        cy.focused().tab()
-        get('#4').should(haveFocus())
-        cy.focused().tab()
-        get('#3').should(haveFocus())
-        cy.focused().tab({shift: true})
-        get('#4').should(haveFocus())
-        cy.focused().click()
-        get('#2').should(haveFocus())
-    },
-)
-
-test('works with clone',
-    [html`
-        <div id="foo" x-data="{
-            open: false,
-            triggerClone() {
-                var original = document.getElementById('foo');
-                var copy = original.cloneNode(true);
-                Alpine.clone(original, copy);
-                var p = document.createElement('p');
-                p.textContent = 'bar';
-                copy.appendChild(p);
-                original.parentNode.replaceChild(copy, original);
-            }
-        }">
-            <button id="one" @click="open = true">Trap</button>
-            <div x-trap="open">
-                <input type="text">
-                <button id="two" @click="triggerClone()">Test</button>
-            </div>
-        </div>
-    `],
-    ({ get, wait }, reload) => {
-        get('#one').click()
-        get('#two').click()
-        get('p').should(haveText('bar'))
-    }
-)
-
-test('can trap focus with inert',
-    [html`
-        <div x-data="{ open: false }">
-            <h1>I should have aria-hidden when outside trap</h1>
-
-            <button id="open" @click="open = true">open</button>
-
-            <div x-trap.inert="open">
-                <button @click="open = false" id="close">close</button>
-            </div>
-        </div>
-    `],
-    ({ get }, reload) => {
-        get('#open').should(notHaveAttribute('aria-hidden', 'true'))
-        get('#open').click()
-        get('#open').should(haveAttribute('aria-hidden', 'true'))
-        get('#close').click()
-        get('#open').should(notHaveAttribute('aria-hidden', 'true'))
-    },
-)
-
-test('can trap focus with noscroll',
-    [html`
-        <div x-data="{ open: false }">
-            <button id="open" @click="open = true">open</button>
-
-            <div x-trap.noscroll="open">
-                <button @click="open = false" id="close">close</button>
-            </div>
-
-            <div style="height: 100vh">&nbsp;</div>
-        </div>
-    `],
-    ({ get, window }, reload) => {
-        window().then((win) => {
-            let scrollbarWidth = win.innerWidth - win.document.documentElement.clientWidth
-            get('#open').click()
-            get('html').should(haveAttribute('style', `overflow: hidden; padding-right: ${scrollbarWidth}px;`))
-            get('#close').click()
-            get('html').should(notHaveAttribute('style', `overflow: hidden; padding-right: ${scrollbarWidth}px;`))
-        })
-    },
-)

+ 1 - 1
tests/cypress/spec.html

@@ -9,7 +9,7 @@
     <script src="/../../packages/history/dist/cdn.js"></script>
     <script src="/../../packages/morph/dist/cdn.js"></script>
     <script src="/../../packages/persist/dist/cdn.js"></script>
-    <script src="/../../packages/trap/dist/cdn.js"></script>
+    <script src="/../../packages/focus/dist/cdn.js"></script>
     <script src="/../../packages/intersect/dist/cdn.js"></script>
     <script src="/../../packages/collapse/dist/cdn.js"></script>
     <script>