@joist/templating 4.2.3-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +370 -0
  3. package/package.json +69 -0
  4. package/src/lib/bind.ts +40 -0
  5. package/src/lib/define.ts +5 -0
  6. package/src/lib/elements/async.element.test.ts +90 -0
  7. package/src/lib/elements/async.element.ts +119 -0
  8. package/src/lib/elements/for.element.test.ts +221 -0
  9. package/src/lib/elements/for.element.ts +176 -0
  10. package/src/lib/elements/if.element.test.ts +90 -0
  11. package/src/lib/elements/if.element.ts +85 -0
  12. package/src/lib/elements/props.element.test.ts +62 -0
  13. package/src/lib/elements/props.element.ts +76 -0
  14. package/src/lib/elements/scope.ts +39 -0
  15. package/src/lib/elements/value.element.test.ts +20 -0
  16. package/src/lib/elements/value.element.ts +39 -0
  17. package/src/lib/events.ts +21 -0
  18. package/src/lib/token.test.ts +74 -0
  19. package/src/lib/token.ts +34 -0
  20. package/src/lib.ts +2 -0
  21. package/target/lib/bind.d.ts +1 -0
  22. package/target/lib/bind.js +30 -0
  23. package/target/lib/bind.js.map +1 -0
  24. package/target/lib/define.d.ts +5 -0
  25. package/target/lib/define.js +6 -0
  26. package/target/lib/define.js.map +1 -0
  27. package/target/lib/elements/async.element.d.ts +17 -0
  28. package/target/lib/elements/async.element.js +112 -0
  29. package/target/lib/elements/async.element.js.map +1 -0
  30. package/target/lib/elements/async.element.test.d.ts +1 -0
  31. package/target/lib/elements/async.element.test.js +75 -0
  32. package/target/lib/elements/async.element.test.js.map +1 -0
  33. package/target/lib/elements/for.element.d.ts +24 -0
  34. package/target/lib/elements/for.element.js +182 -0
  35. package/target/lib/elements/for.element.js.map +1 -0
  36. package/target/lib/elements/for.element.test.d.ts +2 -0
  37. package/target/lib/elements/for.element.test.js +153 -0
  38. package/target/lib/elements/for.element.test.js.map +1 -0
  39. package/target/lib/elements/if.element.d.ts +12 -0
  40. package/target/lib/elements/if.element.js +81 -0
  41. package/target/lib/elements/if.element.js.map +1 -0
  42. package/target/lib/elements/if.element.test.d.ts +1 -0
  43. package/target/lib/elements/if.element.test.js +78 -0
  44. package/target/lib/elements/if.element.test.js.map +1 -0
  45. package/target/lib/elements/props.element.d.ts +11 -0
  46. package/target/lib/elements/props.element.js +90 -0
  47. package/target/lib/elements/props.element.js.map +1 -0
  48. package/target/lib/elements/props.element.test.d.ts +1 -0
  49. package/target/lib/elements/props.element.test.js +53 -0
  50. package/target/lib/elements/props.element.test.js.map +1 -0
  51. package/target/lib/elements/scope.d.ts +13 -0
  52. package/target/lib/elements/scope.js +56 -0
  53. package/target/lib/elements/scope.js.map +1 -0
  54. package/target/lib/elements/value.element.d.ts +9 -0
  55. package/target/lib/elements/value.element.js +54 -0
  56. package/target/lib/elements/value.element.js.map +1 -0
  57. package/target/lib/elements/value.element.test.d.ts +1 -0
  58. package/target/lib/elements/value.element.test.js +16 -0
  59. package/target/lib/elements/value.element.test.js.map +1 -0
  60. package/target/lib/events.d.ts +12 -0
  61. package/target/lib/events.js +10 -0
  62. package/target/lib/events.js.map +1 -0
  63. package/target/lib/token.d.ts +8 -0
  64. package/target/lib/token.js +27 -0
  65. package/target/lib/token.js.map +1 -0
  66. package/target/lib/token.test.d.ts +1 -0
  67. package/target/lib/token.test.js +56 -0
  68. package/target/lib/token.test.js.map +1 -0
  69. package/target/lib.d.ts +2 -0
  70. package/target/lib.js +3 -0
  71. package/target/lib.js.map +1 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2019-2020 Danny Blue
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,370 @@
1
+ # Joist Templating System
2
+
3
+ The Joist templating system provides a powerful and flexible way to handle data binding and templating in web components. This documentation covers the core components and their usage.
4
+
5
+ ## Core Components
6
+
7
+ ### Bind Decorator (`bind.ts`)
8
+
9
+ The `bind` decorator enables reactive data binding for web component properties. It integrates with Joist's observable system to automatically track and propagate changes.
10
+
11
+ ```typescript
12
+ import { bind } from "@joist/templating";
13
+
14
+ class MyElement extends HTMLElement {
15
+ @bind()
16
+ myProperty: string;
17
+ }
18
+ ```
19
+
20
+ The decorator:
21
+
22
+ - Creates a two-way binding between component properties and templates
23
+ - Automatically handles value propagation through the `joist::value` event
24
+ - Integrates with Joist's observable system for efficient change detection
25
+
26
+ ### Token System (`token.ts`)
27
+
28
+ The `JToken` class handles parsing and evaluation of binding expressions. It supports:
29
+
30
+ - Simple property bindings: `propertyName`
31
+ - Nested property access: `user.profile.name`
32
+ - Negation operator: `!isVisible`
33
+
34
+ Example usage:
35
+
36
+ ```typescript
37
+ const token = new JToken("user.name");
38
+ const value = token.readTokenValueFrom(context);
39
+ ```
40
+
41
+ ### Events (`events.ts`)
42
+
43
+ The system uses custom events for value propagation:
44
+
45
+ - `JoistValueEvent`: A custom event that handles value updates in the templating system
46
+ - Bubbles through the DOM tree
47
+ - Carries both the token and update mechanism
48
+
49
+ ## Built-in Template Elements
50
+
51
+ Joist provides several built-in template elements for common templating needs:
52
+
53
+ ### Conditional Rendering (`j-if`)
54
+
55
+ Conditionally renders content based on a boolean expression:
56
+
57
+ ```html
58
+ <j-if bind="isVisible">
59
+ <template>
60
+ <div>This content is only shown when isVisible is true</div>
61
+ </template>
62
+ </j-if>
63
+
64
+ <!-- With negation -->
65
+ <j-if bind="!isHidden">
66
+ <template>
67
+ <div>This content is shown when isHidden is false</div>
68
+ </template>
69
+ </j-if>
70
+
71
+ <!-- With else template -->
72
+ <j-if bind="isLoggedIn">
73
+ <template>
74
+ <div>Welcome back!</div>
75
+ </template>
76
+ <template else>
77
+ <div>Please log in</div>
78
+ </template>
79
+ </j-if>
80
+ ```
81
+
82
+ The `j-if` element supports:
83
+
84
+ - Boolean expressions for conditional rendering
85
+ - Negation operator (`!`) for inverse conditions
86
+ - Optional `else` template for fallback content
87
+ - Automatic cleanup of removed content
88
+
89
+ Common use cases:
90
+
91
+ - Toggling visibility of UI elements
92
+ - Conditional form fields
93
+ - Feature flags
94
+ - Authentication states
95
+ - Loading states
96
+
97
+ ### Property Binding (`j-props`)
98
+
99
+ Binds values to element properties and attributes. The prefix determines the binding type:
100
+
101
+ - `$.` prefix: Binds to element properties
102
+ - `$` prefix: Binds to element attributes
103
+
104
+ ```html
105
+ <j-props>
106
+ <!-- Bind to boolean properties -->
107
+ <input type="checkbox" $.checked="isComplete">
108
+
109
+ <!-- Bind to form input values -->
110
+ <input type="text" $.value="userName">
111
+
112
+ <!-- Bind to custom element properties -->
113
+ <my-element $.data="complexObject">
114
+
115
+ <!-- Bind to attributes -->
116
+ <div $class="dynamicClass">
117
+ <img $src="imageUrl">
118
+ <input $placeholder="placeholderText">
119
+ </j-props>
120
+ ```
121
+
122
+ ### List Rendering (`j-for`)
123
+
124
+ Renders lists of items with support for keyed updates:
125
+
126
+ ```html
127
+ <j-for bind="todos" key="id">
128
+ <template>
129
+ <j-props>
130
+ <div
131
+ class="todo-item"
132
+ $.dataset.id="each.value.id"
133
+ $.dataset.completed="each.value.completed"
134
+ >
135
+ <j-props>
136
+ <input type="checkbox" $.checked="each.value.completed" />
137
+ </j-props>
138
+
139
+ <j-value bind="each.value.text"></j-value>
140
+
141
+ <j-props>
142
+ <button $.disabled="!each.value.text">×</button>
143
+ </j-props>
144
+ </div>
145
+ </j-props>
146
+ </template>
147
+ </j-for>
148
+ ```
149
+
150
+ The `j-for` element provides context variables:
151
+
152
+ - `each.value`: The current item in the iteration
153
+ - `each.index`: The zero-based index of the current item
154
+ - `each.position`: The one-based position of the current item
155
+
156
+ ### Value Display (`j-value`)
157
+
158
+ Displays a bound value as text content:
159
+
160
+ ```html
161
+ <j-value bind="user.name"></j-value> <j-value bind="formattedPrice"></j-value>
162
+ ```
163
+
164
+ ### Async State Handling (`j-async`)
165
+
166
+ Handles asynchronous operations and state management with loading, success, and error states. The element accepts either a Promise or an AsyncState object:
167
+
168
+ ```typescript
169
+ // AsyncState type
170
+ type AsyncState<T = unknown, E = unknown> = {
171
+ status: "loading" | "error" | "success";
172
+ data?: T;
173
+ error?: E;
174
+ };
175
+ ```
176
+
177
+ Example usage with a Promise:
178
+
179
+ ```typescript
180
+ // In your component
181
+ @bind()
182
+ accessor userPromise = fetch('/api/user').then(r => r.json());
183
+ ```
184
+
185
+ ```html
186
+ <j-async bind="userPromise">
187
+ <template loading>Loading...</template>
188
+
189
+ <template success>
190
+ <div>Welcome, <j-value bind="state.data.name"></j-value>!</div>
191
+ </template>
192
+
193
+ <template error>
194
+ <div>Error: <j-value bind="state.error"></j-value></div>
195
+ </template>
196
+ </j-async>
197
+ ```
198
+
199
+ The `j-async` element supports:
200
+
201
+ - Promise handling with automatic state transitions
202
+ - Loading, success, and error templates
203
+ - Automatic cleanup on disconnection
204
+ - State object with typed data and error fields
205
+
206
+ ## Complete Example
207
+
208
+ Here's a complete todo application in a single component:
209
+
210
+ ```typescript
211
+ import { bind } from "@joist/templating";
212
+ import { element, html, css, listen, query } from "@joist/element";
213
+
214
+ interface Todo {
215
+ id: number;
216
+ text: string;
217
+ }
218
+
219
+ @element({
220
+ tagName: "todo-list",
221
+ shadowDom: [
222
+ css`
223
+ :host {
224
+ display: block;
225
+ max-width: 600px;
226
+ margin: 2rem auto;
227
+ }
228
+ .form {
229
+ display: flex;
230
+ gap: 1rem;
231
+ }
232
+ .todo-item {
233
+ display: flex;
234
+ gap: 0.5rem;
235
+ margin: 0.5rem 0;
236
+ }
237
+ .todo-text {
238
+ flex: 1;
239
+ }
240
+ `,
241
+ html`
242
+ <form class="form">
243
+ <input type="text" placeholder="What needs to be done?" />
244
+ <button type="submit">Add</button>
245
+ </form>
246
+
247
+ <j-if bind="!todos.length">
248
+ <template>
249
+ <p>No todos yet!</p>
250
+ </template>
251
+ </j-if>
252
+
253
+ <j-for id="todos" bind="todos" key="id">
254
+ <template>
255
+ <j-props class="todo-item">
256
+ <j-value class="todo-text" bind="each.value.text"></j-value>
257
+ <button $.id="each.value.id" $.disabled="!each.value.text">×</button>
258
+ </j-props>
259
+ </template>
260
+ </j-for>
261
+
262
+ <j-value bind="todos.length"></j-value> remaining
263
+ `,
264
+ ],
265
+ })
266
+ export class TodoList extends HTMLElement {
267
+ @bind()
268
+ accessor todos: Todo[] = [];
269
+
270
+ #nextId = 1;
271
+ #input = query("input");
272
+
273
+ @listen("submit", "form")
274
+ onSubmit(e: SubmitEvent) {
275
+ e.preventDefault();
276
+
277
+ const input = this.#input();
278
+
279
+ this.todos = [...this.todos, { id: this.#nextId++, text: input.value.trim() }];
280
+
281
+ input.value = "";
282
+ }
283
+
284
+ @listen("click", "#todos")
285
+ onDelete(e: Event) {
286
+ if (e.target instanceof HTMLButtonElement) {
287
+ const id = Number(e.target.id);
288
+
289
+ this.todos = this.todos.filter((todo) => todo.id !== id);
290
+ }
291
+ }
292
+ }
293
+ ```
294
+
295
+ ## Usage
296
+
297
+ 1. Use the `@bind()` decorator on properties you want to make bindable
298
+ 2. Properties will automatically integrate with the templating system
299
+ 3. Changes are propagated through the component tree using the custom event system
300
+
301
+ ## Integration with Observable
302
+
303
+ The templating system is built on top of Joist's observable system (`@joist/observable`), providing:
304
+
305
+ - Automatic change detection
306
+ - Efficient updates
307
+ - Integration with the component lifecycle
308
+
309
+ ## Best Practices
310
+
311
+ 1. Use the `@bind()` decorator only on properties that need reactivity
312
+ 2. Keep binding expressions simple and avoid deep nesting
313
+ 3. Consider performance implications when binding to frequently changing values
314
+ 4. Always use a `key` attribute with `j-for` when items can be reordered
315
+ 5. Place template content directly inside `j-if` and `j-for` elements
316
+
317
+ ## Manual Value Handling
318
+
319
+ You can manually handle value requests and updates by listening for the `joist::value` event. This is useful when you need more control over the binding process or want to implement custom binding logic:
320
+
321
+ ```typescript
322
+ import { JoistValueEvent } from "@joist/templating";
323
+
324
+ class MyElement extends HTMLElement {
325
+ connectedCallback() {
326
+ // Listen for value requests
327
+ this.addEventListener("joist::value", (e: JoistValueEvent) => {
328
+ const token = e.token;
329
+
330
+ // Handle the value request
331
+ if (token.bindTo === "myValue") {
332
+ // Update the value
333
+ e.update({
334
+ oldValue: this.myValue,
335
+ newValue: this.myValue,
336
+ });
337
+ }
338
+ });
339
+ }
340
+ }
341
+ ```
342
+
343
+ Example with async value handling:
344
+
345
+ ```typescript
346
+ import { JoistValueEvent } from "@joist/templating";
347
+
348
+ class MyElement extends HTMLElement {
349
+ connectedCallback() {
350
+ this.addEventListener("joist::value", (e: JoistValueEvent) => {
351
+ const token = e.token;
352
+
353
+ if (token.bindTo === "userData") {
354
+ e.update({
355
+ oldValue: this.userData,
356
+ newValue: data,
357
+ });
358
+ }
359
+ });
360
+ }
361
+ }
362
+ ```
363
+
364
+ Common use cases for manual value handling:
365
+
366
+ - Custom data transformation before binding
367
+ - Async data loading and caching
368
+ - Complex state management
369
+ - Integration with external data sources
370
+ - Custom validation or error handling
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@joist/templating",
3
+ "version": "4.2.3-next.10",
4
+ "type": "module",
5
+ "main": "./target/lib.js",
6
+ "module": "./target/lib.js",
7
+ "exports": {
8
+ ".": "./target/lib.js",
9
+ "./*": "./target/lib/*",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "target"
15
+ ],
16
+ "description": "Intelligently apply styles to WebComponents",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/joist-framework/joist.git"
20
+ },
21
+ "keywords": [
22
+ "TypeScript",
23
+ "WebComponents",
24
+ "CSS",
25
+ "ShadowDOM"
26
+ ],
27
+ "author": "deebloo",
28
+ "license": "MIT",
29
+ "bugs": {
30
+ "url": "https://github.com/joist-framework/joist/issues"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "test": "wireit",
37
+ "build": "wireit"
38
+ },
39
+ "wireit": {
40
+ "build": {
41
+ "command": "tsc --build --pretty",
42
+ "clean": "if-file-deleted",
43
+ "files": [
44
+ "src/**",
45
+ "tsconfig.json",
46
+ "../../tsconfig.json"
47
+ ],
48
+ "output": [
49
+ "target/**",
50
+ "tsconfig.tsbuildinfo"
51
+ ],
52
+ "dependencies": [
53
+ "../observable:build",
54
+ "../element:build"
55
+ ]
56
+ },
57
+ "test": {
58
+ "command": "wtr --config wtr.config.mjs",
59
+ "files": [
60
+ "vitest.config.js",
61
+ "target/**"
62
+ ],
63
+ "output": [],
64
+ "dependencies": [
65
+ "build"
66
+ ]
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,40 @@
1
+ import { instanceMetadataStore, observe } from "@joist/observable";
2
+
3
+ export function bind() {
4
+ return function bindDecorator<This extends HTMLElement, Value>(
5
+ base: ClassAccessorDecoratorTarget<This, Value>,
6
+ ctx: ClassAccessorDecoratorContext<This, Value>,
7
+ ): ClassAccessorDecoratorResult<This, Value> {
8
+ const internalObserve = observe()(base, ctx);
9
+
10
+ return {
11
+ init(value) {
12
+ this.addEventListener("joist::value", (e) => {
13
+ if (e.token.bindTo === ctx.name) {
14
+ const instanceMeta = instanceMetadataStore.read<This>(this);
15
+
16
+ e.stopPropagation();
17
+
18
+ e.update({ oldValue: null, newValue: ctx.access.get(this) });
19
+
20
+ instanceMeta.bindings.add((changes) => {
21
+ const key = ctx.name as keyof This;
22
+ const res = changes.get(key);
23
+
24
+ if (res) {
25
+ e.update(res);
26
+ }
27
+ });
28
+ }
29
+ });
30
+
31
+ if (internalObserve.init) {
32
+ return internalObserve.init.call(this, value);
33
+ }
34
+
35
+ return value;
36
+ },
37
+ set: internalObserve.set,
38
+ };
39
+ };
40
+ }
@@ -0,0 +1,5 @@
1
+ import "./elements/async.element.js";
2
+ import "./elements/for.element.js";
3
+ import "./elements/if.element.js";
4
+ import "./elements/props.element.js";
5
+ import "./elements/value.element.js";
@@ -0,0 +1,90 @@
1
+ import "./async.element.js";
2
+
3
+ import { fixtureSync, html } from "@open-wc/testing";
4
+ import { assert } from "chai";
5
+
6
+ import type { JoistValueEvent } from "../events.js";
7
+
8
+ it("should show loading template when promise is pending", async () => {
9
+ const element = fixtureSync(html`
10
+ <div
11
+ @joist::value=${(e: JoistValueEvent) => {
12
+ e.update({ oldValue: null, newValue: new Promise(() => {}) });
13
+ }}
14
+ >
15
+ <j-async bind="test">
16
+ <template loading>Loading...</template>
17
+ <template success>Success!</template>
18
+ <template error>Error!</template>
19
+ </j-async>
20
+ </div>
21
+ `);
22
+
23
+ assert.equal(element.textContent?.trim(), "Loading...");
24
+ });
25
+
26
+ it("should show success template when promise resolves", async () => {
27
+ const element = fixtureSync(html`
28
+ <div
29
+ @joist::value=${(e: JoistValueEvent) => {
30
+ e.update({ oldValue: null, newValue: Promise.resolve("data") });
31
+ }}
32
+ >
33
+ <j-async bind="test">
34
+ <template loading>Loading...</template>
35
+ <template success>Success!</template>
36
+ <template error>Error!</template>
37
+ </j-async>
38
+ </div>
39
+ `);
40
+
41
+ // Wait for promise to resolve
42
+ await new Promise((resolve) => setTimeout(resolve, 0));
43
+ assert.equal(element.textContent?.trim(), "Success!");
44
+ });
45
+
46
+ it("should show error template when promise rejects", async () => {
47
+ const element = fixtureSync(html`
48
+ <div
49
+ @joist::value=${(e: JoistValueEvent) => {
50
+ e.update({ oldValue: null, newValue: Promise.reject("error") });
51
+ }}
52
+ >
53
+ <j-async bind="test">
54
+ <template loading>Loading...</template>
55
+ <template success>Success!</template>
56
+ <template error>Error!</template>
57
+ </j-async>
58
+ </div>
59
+ `);
60
+
61
+ // Wait for promise to reject
62
+ await new Promise((resolve) => setTimeout(resolve, 0));
63
+ assert.equal(element.textContent?.trim(), "Error!");
64
+ });
65
+
66
+ it("should handle state transitions", async () => {
67
+ const element = fixtureSync(html`
68
+ <div
69
+ @joist::value=${(e: JoistValueEvent) => {
70
+ const promise = new Promise((resolve) => {
71
+ setTimeout(() => resolve("data"), 100);
72
+ });
73
+ e.update({ oldValue: null, newValue: promise });
74
+ }}
75
+ >
76
+ <j-async bind="test">
77
+ <template loading>Loading...</template>
78
+ <template success>Success!</template>
79
+ <template error>Error!</template>
80
+ </j-async>
81
+ </div>
82
+ `);
83
+
84
+ // Initially should show loading
85
+ assert.equal(element.textContent?.trim(), "Loading...");
86
+
87
+ // Wait for promise to resolve
88
+ await new Promise((resolve) => setTimeout(resolve, 150));
89
+ assert.equal(element.textContent?.trim(), "Success!");
90
+ });