Skip to content

Commit

Permalink
:sparkes: Creates Alpine Scope (#21)
Browse files Browse the repository at this point in the history
* ✨ Adds $scope

* 🔧 Adjusts configs

* 🏷️ Fixes Types

* 📝 Updates Documentation
  • Loading branch information
ekwoka authored Feb 28, 2024
1 parent dd40353 commit 2873afa
Show file tree
Hide file tree
Showing 13 changed files with 1,602 additions and 687 deletions.
36 changes: 18 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,26 @@
"@milahu/patch-package": "6.4.14",
"@trivago/prettier-plugin-sort-imports": "4.3.0",
"@types/alpinejs": "3.13.6",
"@types/node": "20.11.1",
"@typescript-eslint/eslint-plugin": "6.18.1",
"@typescript-eslint/parser": "6.18.1",
"@vitest/ui": "1.2.0",
"alpinejs": "3.13.3",
"esbuild": "0.19.11",
"eslint": "8.56.0",
"happy-dom": "13.1.4",
"husky": "8.0.3",
"lint-staged": "15.2.0",
"@types/node": "20.11.21",
"@typescript-eslint/eslint-plugin": "7.1.0",
"@typescript-eslint/parser": "7.1.0",
"@vitest/ui": "1.3.1",
"alpinejs": "3.13.5",
"esbuild": "0.20.1",
"eslint": "8.57.0",
"husky": "9.0.11",
"lint-staged": "15.2.2",
"npm-run-all": "4.1.5",
"prettier": "3.2.2",
"prettier": "3.2.5",
"pretty-bytes": "6.1.1",
"testing-library-alpine": "0.0.1-alpha.0",
"typescript": "5.3.3",
"vite": "5.0.11",
"vite-plugin-dts": "3.7.0",
"vite-tsconfig-paths": "4.2.3",
"vitest": "1.2.0",
"vitest-dom": "0.1.1"
"vite": "5.1.4",
"vite-plugin-dts": "3.7.3",
"vite-tsconfig-paths": "4.3.1",
"vitest": "1.3.1",
"vitest-dom": "0.1.1",
"vitest-environment-alpine": "0.0.2-alpha.1"
},
"lint-staged": {
"*.{js,ts,mjs}": [
Expand All @@ -67,13 +68,12 @@
},
"pnpm": {
"overrides": {
"happy-dom@>9.1.9": "9.1.9",
"typescript@<5.1.6": "5.1.6",
"semver@<7.5.2": ">=7.5.2"
}
},
"dependencies": {
"@vue/reactivity": "^3.4.13",
"@vue/reactivity": "^3.4.20",
"alpinets": "link:../alpinets/packages/alpinets"
}
}
2 changes: 1 addition & 1 deletion packages/params/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Import to Build (Simple Version):
import Alpine from 'alpinejs';
import Params from '@ekwoka/alpine-history';

Alpine.plugin(Params); // key used for your Cloudinary with Fetch API
Alpine.plugin(Params);

window.Alpine = Alpine;
Alpine.start();
Expand Down
21 changes: 21 additions & 0 deletions packages/scope/LICENSE
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.
98 changes: 98 additions & 0 deletions packages/scope/README.md
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&amp;logo=typescript&amp;logoColor=white&amp;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!
51 changes: 51 additions & 0 deletions packages/scope/package.json
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"
}
155 changes: 155 additions & 0 deletions packages/scope/src/index.ts
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>;
}
Loading

0 comments on commit 2873afa

Please sign in to comment.