-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
:sparkes: Creates Alpine Scope (#21)
* ✨ Adds $scope * 🔧 Adjusts configs * 🏷️ Fixes Types * 📝 Updates Documentation
- Loading branch information
Showing
13 changed files
with
1,602 additions
and
687 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2021 Eric Kwoka | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
# Alpine Scope: Scoped Context Naming for AlpineJS | ||
|
||
[<img src="https://img.shields.io/npm/v/@ekwoka/alpine-scope?label=%20&style=for-the-badge&logo=pnpm&logoColor=white">](https://www.npmjs.com/package/@ekwoka/alpine-scope) | ||
<img src="https://img.shields.io/npm/types/@ekwoka/alpine-scope?label=%20&logo=typescript&logoColor=white&style=for-the-badge"> | ||
<img src="https://img.shields.io/npm/dt/@ekwoka/alpine-scope?style=for-the-badge&logo=npm&logoColor=white" > | ||
[<img src="https://img.shields.io/bundlephobia/minzip/@ekwoka/alpine-scope?style=for-the-badge&logo=esbuild&logoColor=white">](https://bundlephobia.com/package/@ekwoka/alpine-scope) | ||
|
||
> This exposes a simple magic `$scope` to allow accessing specific component scopes in the tree by name. | ||
## Install | ||
|
||
```sh | ||
npm i @ekwoka/alpine-scope | ||
``` | ||
|
||
Import to Build (Simple Version): | ||
|
||
```js | ||
import Alpine from 'alpinejs'; | ||
import Scope from '@ekwoka/alpine-scope'; | ||
|
||
Alpine.plugin(Scope); | ||
|
||
window.Alpine = Alpine; | ||
Alpine.start(); | ||
``` | ||
|
||
## Usage: | ||
|
||
When using Alpine, it can sometimes be difficult to access the values you want in some component trees. While often this is a case of poor design, sometimes the best design can still run into some conflicts that require awkward workarounds. | ||
|
||
With this plugin, you can use the magic `$scope` to directly access the data context of a specific component in the tree. | ||
|
||
### Implicit Naming | ||
|
||
```html | ||
<div x-data="foo"> | ||
// { value: 'hello' } | ||
<div x-data="bar"> | ||
// { value: 'world' } | ||
<span x-text="$scope.foo.value"></span> // 'hello' | ||
<span x-text="value"></span> // 'world' | ||
</div> | ||
</div> | ||
``` | ||
|
||
The above is an example of implicitely scoped contexts. The expression passed to `x-data` is used as the key. This works great when the contexts are defined with `Alpine.data` and referenced by name. Obviously, this would become an issue if you your expression is like | ||
|
||
```html | ||
<div | ||
x-data="{ foo: { bar: [1,2,3 ]}, doStuff() { console.log(this.foo.bar) } }"></div> | ||
``` | ||
|
||
### Explicit Naming | ||
|
||
Conveniently included is the `x-scope` directive, which allows you to explicitly name the scope. This is useful for cases where the expression may be unknown at the point of needing the scoping, and cases where the expression is unwieldly. | ||
|
||
```html | ||
<div x-data="{ value: 'hello' }" x-scope="foo"> | ||
<div x-data="{ value: 'world' }"> | ||
<span x-text="$scope.foo.value"></span> // 'hello' | ||
<span x-text="value"></span> // 'world' | ||
</div> | ||
</div> | ||
``` | ||
|
||
Pretty nifty!!! | ||
|
||
And don't worry, scopes won't leak into other trees. They are only accessible within the tree they are defined. | ||
|
||
## How it works | ||
|
||
### `x-scope="expression"` | ||
|
||
`x-scope` adds a `Map` of scopes to the current elements nearest component, that contains any scopes from the parent component and then the current component. These are placed in the context under a special `Symbol` so as not to conflict with your components directly. | ||
|
||
This adds the scope to the current context, not the specific elements subtree. This means that children of the `root` element can provide a name to the scope, and that all elements in the component will see the same list of scopes, even if they are not in the same subtree. This can be useful for some more dynamic use cases. The same component scope can be named multiple times from multiple `x-scope` directives in the component tree, and they will not remove the others. | ||
|
||
However, the scopes are isolated to the component and its decendents, and will not leak into the parent or other components. | ||
|
||
### `$scope.name` | ||
|
||
`$scope` is a magic property available in expressions and component methods that exposes a `Proxy` that allows access to the Parent components. | ||
|
||
When a key is access, like `$scope.foo`, the `Proxy` first looks in the current contexts `Map` of scopes (from `x-scope`) for a context. If no context is found, it will look up the tree for an element with a matching `x-data` expression to use its context. | ||
|
||
This means that explicitely named scopes will always take precedence over implicitely named scopes, and that scopes will not leak to sibling or parent trees. | ||
|
||
## Author | ||
|
||
👤 **Eric Kwoka** | ||
|
||
- Website: http://thekwoka.net | ||
- Github: [@ekwoka](https://github.com/ekwoka) | ||
|
||
## Show your support | ||
|
||
Give a ⭐️ if this project helped you! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
{ | ||
"name": "@ekwoka/alpine-scope", | ||
"version": "0.0.1", | ||
"description": "Access component scopes by name", | ||
"author": { | ||
"name": "Eric Kwoka", | ||
"email": "[email protected]", | ||
"url": "https://thekwoka.net/" | ||
}, | ||
"license": "MIT", | ||
"keywords": [ | ||
"AlpineJS" | ||
], | ||
"type": "module", | ||
"files": [ | ||
"dist", | ||
"src" | ||
], | ||
"sideEffects": false, | ||
"main": "dist/", | ||
"types": "dist/", | ||
"exports": { | ||
".": { | ||
"import": "./dist/index.js", | ||
"require": "./dist/index.js" | ||
}, | ||
"./dist": "./dist/", | ||
"./src": "./src/" | ||
}, | ||
"scripts": { | ||
"build": "vite build", | ||
"coverage": "vitest run --coverage", | ||
"lint": "eslint --fix ./src; prettier --write ./src --loglevel error", | ||
"lint:check": "eslint --max-warnings 10 ./src && prettier --check ./src", | ||
"lint:types": "tsc --noEmit", | ||
"prebuild": "rm -rf dist", | ||
"test": "vitest" | ||
}, | ||
"peerDependencies": { | ||
"alpinejs": "3.x" | ||
}, | ||
"prettier": { | ||
"singleQuote": true, | ||
"bracketSameLine": true | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/ekwoka/alpine-plugins" | ||
}, | ||
"homepage": "https://github.com/ekwoka/alpine-plugins/blob/main/packages/scope/README.md" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
import type { Alpine } from 'alpinejs'; | ||
import type { Assertion } from 'vitest'; | ||
|
||
export const $scope = Symbol('$scope'); | ||
|
||
/** | ||
* Alpine Scope Plugin registers `$scope` magic property and `x-scope` directive. | ||
* Allows reaching into specific parent component contexts to access their data. | ||
* @param Alpine {Alpine} | ||
*/ | ||
export const Scope = (Alpine: Alpine) => { | ||
type Scopable = { [$scope]?: Map<string, HTMLElement> }; | ||
Alpine.directive('scope', (el, { expression }) => { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
const context = Alpine.$data(el) as Scopable; | ||
|
||
const rootContext = Alpine.closestDataStack(el)[0]; | ||
if (!rootContext) return; | ||
rootContext[$scope] = new Map(context[$scope]).set(expression, el); | ||
}); | ||
Alpine.magic('scope', (el) => { | ||
return new Proxy( | ||
{}, | ||
{ | ||
get(_, name: string) { | ||
const scopes = (Alpine.$data(el) as Scopable)[$scope]; | ||
if (scopes?.has(name)) return Alpine.$data(scopes.get(name)!); | ||
const root = Alpine.findClosest(el, (el) => | ||
el.matches(`[x-data="${name}"]`), | ||
) as HTMLElement | undefined; | ||
if (root) return Alpine.$data(root); | ||
return undefined; | ||
}, | ||
}, | ||
); | ||
}); | ||
}; | ||
|
||
export default Scope; | ||
|
||
declare module 'alpinejs' { | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
export interface Magics<T> { | ||
/** | ||
* A `Proxy` of the parent component scopes | ||
*/ | ||
$scope: Record<string, unknown>; | ||
} | ||
} | ||
|
||
if (import.meta.vitest) { | ||
describe('$scope', () => { | ||
it('can access implicitely scoped context', async () => { | ||
const root = await render( | ||
` | ||
<div x-data="foo"> | ||
<div x-data="bar"> | ||
<span id="naked" x-text="value"></span> | ||
<span id="foo" x-text="$scope.foo?.value"></span> | ||
<span id="bar" x-text="$scope.bar?.value"></span> | ||
</div> | ||
</div> | ||
`.trim(), | ||
) | ||
.withComponent('foo', () => ({ value: 'foo' })) | ||
.withComponent('bar', () => ({ value: 'bar' })) | ||
.withPlugin(Scope); | ||
expect((root as HTMLElement).querySelector('#naked')).toHaveTextContent( | ||
'bar', | ||
); | ||
expect((root as HTMLElement).querySelector('#foo')).toHaveTextContent( | ||
'foo', | ||
); | ||
expect((root as HTMLElement).querySelector('#bar')).toHaveTextContent( | ||
'bar', | ||
); | ||
}); | ||
it('can access explicitely scoped context', async () => { | ||
const root = await render( | ||
` | ||
<div x-data="{ value: 'foo' }" x-scope="foo"> | ||
<div x-data="{ value: 'bar' }" x-scope="bar"> | ||
<span id="naked" x-text="value"></span> | ||
<span id="foo" x-text="$scope.foo?.value"></span> | ||
<span id="bar" x-text="$scope.bar?.value"></span> | ||
</div> | ||
</div> | ||
`.trim(), | ||
).withPlugin(Scope); | ||
expect((root as HTMLElement).querySelector('#naked')).toHaveTextContent( | ||
'bar', | ||
); | ||
expect((root as HTMLElement).querySelector('#foo')).toHaveTextContent( | ||
'foo', | ||
); | ||
expect((root as HTMLElement).querySelector('#bar')).toHaveTextContent( | ||
'bar', | ||
); | ||
}); | ||
it('favors explicitely scoped contexts', async () => { | ||
const root = await render( | ||
` | ||
<div x-data="foo" x-scope="bar"> | ||
<div x-data="bar"> | ||
<span id="naked" x-text="value"></span> | ||
<span id="bar" x-text="$scope.bar?.value"></span> | ||
</div> | ||
</div> | ||
`.trim(), | ||
) | ||
.withComponent('foo', () => ({ value: 'foo' })) | ||
.withComponent('bar', () => ({ value: 'bar' })) | ||
.withPlugin(Scope); | ||
expect((root as HTMLElement).querySelector('#naked')).toHaveTextContent( | ||
'bar', | ||
); | ||
expect((root as HTMLElement).querySelector('#bar')).toHaveTextContent( | ||
'foo', | ||
); | ||
}); | ||
it('does not leak', async () => { | ||
const root = await render( | ||
` | ||
<div x-data="{ value: 'root' }"> | ||
<div x-data="foo" x-scope="foo"></div> | ||
<div x-data="bar"> | ||
</div> | ||
<span id="naked" x-text="value"></span> | ||
<span id="foo" x-text="$scope.foo?.value ?? 'not found'"></span> | ||
<span id="bar" x-text="$scope.bar?.value ?? 'not found'"></span> | ||
</div> | ||
`.trim(), | ||
) | ||
.withComponent('foo', () => ({ value: 'foo' })) | ||
.withComponent('bar', () => ({ value: 'bar' })) | ||
.withPlugin(Scope); | ||
expect((root as HTMLElement).querySelector('#naked')).toHaveTextContent( | ||
'root', | ||
); | ||
expect((root as HTMLElement).querySelector('#foo')).toHaveTextContent( | ||
'not found', | ||
); | ||
expect((root as HTMLElement).querySelector('#bar')).toHaveTextContent( | ||
'not found', | ||
); | ||
}); | ||
}); | ||
} | ||
declare module 'vitest' { | ||
interface Assertion<T> extends AlpineMatchers<T> {} | ||
} | ||
|
||
interface AlpineMatchers<T> { | ||
toHaveTextContent: (expected: string) => Assertion<T>; | ||
} |
Oops, something went wrong.