@joist/element 4.2.1 → 4.2.3-next.0

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 (76) hide show
  1. package/package.json +4 -1
  2. package/src/lib/metadata.ts +1 -1
  3. package/src/lib/query.ts +1 -1
  4. package/src/lib/templating/README.md +292 -0
  5. package/src/lib/templating/bind.ts +40 -0
  6. package/src/lib/templating/define.ts +4 -0
  7. package/src/lib/templating/elements/for.element.test.ts +39 -0
  8. package/src/lib/templating/elements/for.element.ts +151 -0
  9. package/src/lib/templating/elements/if.element.test.ts +55 -0
  10. package/src/lib/templating/elements/if.element.ts +67 -0
  11. package/src/lib/templating/elements/props.element.test.ts +62 -0
  12. package/src/lib/templating/elements/props.element.ts +80 -0
  13. package/src/lib/templating/elements/scope.ts +45 -0
  14. package/src/lib/templating/elements/value.element.test.ts +20 -0
  15. package/src/lib/templating/elements/value.element.ts +41 -0
  16. package/src/lib/templating/events.ts +21 -0
  17. package/src/lib/templating/token.test.ts +74 -0
  18. package/src/lib/templating/token.ts +34 -0
  19. package/src/lib/templating.ts +2 -0
  20. package/src/lib.ts +1 -0
  21. package/target/lib/metadata.d.ts +1 -1
  22. package/target/lib/query.d.ts +1 -1
  23. package/target/lib/templating/bind.d.ts +1 -0
  24. package/target/lib/templating/bind.js +30 -0
  25. package/target/lib/templating/bind.js.map +1 -0
  26. package/target/lib/templating/define.d.ts +4 -0
  27. package/target/lib/templating/define.js +5 -0
  28. package/target/lib/templating/define.js.map +1 -0
  29. package/target/lib/templating/elements/for.element.d.ts +23 -0
  30. package/target/lib/templating/elements/for.element.js +168 -0
  31. package/target/lib/templating/elements/for.element.js.map +1 -0
  32. package/target/lib/templating/elements/for.element.test.d.ts +2 -0
  33. package/target/lib/templating/elements/for.element.test.js +34 -0
  34. package/target/lib/templating/elements/for.element.test.js.map +1 -0
  35. package/target/lib/templating/elements/if.element.d.ts +13 -0
  36. package/target/lib/templating/elements/if.element.js +71 -0
  37. package/target/lib/templating/elements/if.element.js.map +1 -0
  38. package/target/lib/templating/elements/if.element.test.d.ts +1 -0
  39. package/target/lib/templating/elements/if.element.test.js +47 -0
  40. package/target/lib/templating/elements/if.element.test.js.map +1 -0
  41. package/target/lib/templating/elements/props.element.d.ts +11 -0
  42. package/target/lib/templating/elements/props.element.js +92 -0
  43. package/target/lib/templating/elements/props.element.js.map +1 -0
  44. package/target/lib/templating/elements/props.element.test.d.ts +1 -0
  45. package/target/lib/templating/elements/props.element.test.js +53 -0
  46. package/target/lib/templating/elements/props.element.test.js.map +1 -0
  47. package/target/lib/templating/elements/scope.d.ts +13 -0
  48. package/target/lib/templating/elements/scope.js +59 -0
  49. package/target/lib/templating/elements/scope.js.map +1 -0
  50. package/target/lib/templating/elements/value.element.d.ts +9 -0
  51. package/target/lib/templating/elements/value.element.js +56 -0
  52. package/target/lib/templating/elements/value.element.js.map +1 -0
  53. package/target/lib/templating/elements/value.element.test.d.ts +1 -0
  54. package/target/lib/templating/elements/value.element.test.js +16 -0
  55. package/target/lib/templating/elements/value.element.test.js.map +1 -0
  56. package/target/lib/templating/events.d.ts +12 -0
  57. package/target/lib/templating/events.js +10 -0
  58. package/target/lib/templating/events.js.map +1 -0
  59. package/target/lib/templating/token.d.ts +8 -0
  60. package/target/lib/templating/token.js +27 -0
  61. package/target/lib/templating/token.js.map +1 -0
  62. package/target/lib/templating/token.test.js +56 -0
  63. package/target/lib/templating/token.test.js.map +1 -0
  64. package/target/lib/templating.d.ts +2 -0
  65. package/target/lib/templating.js +3 -0
  66. package/target/lib/templating.js.map +1 -0
  67. package/target/lib.d.ts +1 -0
  68. package/target/lib.js.map +1 -1
  69. package/src/lib/template.test.ts +0 -123
  70. package/src/lib/template.ts +0 -130
  71. package/target/lib/template.d.ts +0 -11
  72. package/target/lib/template.js +0 -89
  73. package/target/lib/template.js.map +0 -1
  74. package/target/lib/template.test.js +0 -91
  75. package/target/lib/template.test.js.map +0 -1
  76. /package/target/lib/{template.test.d.ts → templating/token.test.d.ts} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joist/element",
3
- "version": "4.2.1",
3
+ "version": "4.2.3-next.0",
4
4
  "type": "module",
5
5
  "main": "./target/lib.js",
6
6
  "module": "./target/lib.js",
@@ -49,6 +49,9 @@
49
49
  "output": [
50
50
  "target/**",
51
51
  "tsconfig.tsbuildinfo"
52
+ ],
53
+ "dependencies": [
54
+ "../observable:build"
52
55
  ]
53
56
  },
54
57
  "test": {
@@ -8,7 +8,7 @@ export interface AttrDef {
8
8
  setPropValue: (value: unknown) => void;
9
9
  }
10
10
 
11
- export type ListenerSelector<T> = (el: T) => Element | ShadowRoot | null;
11
+ export type ListenerSelector<T> = (el: T) => EventTarget | null;
12
12
 
13
13
  export interface Listener<T> {
14
14
  event: string;
package/src/lib/query.ts CHANGED
@@ -4,7 +4,7 @@ type MathTags = keyof MathMLElementTagNameMap;
4
4
 
5
5
  type NodeUpdate<T extends Node> = Partial<T> | ((node: T) => Partial<T>);
6
6
 
7
- type QueryResult<T extends Node> = (updates?: NodeUpdate<T>) => T;
7
+ export type QueryResult<T extends Node> = (updates?: NodeUpdate<T>) => T;
8
8
 
9
9
  export function query<K extends Tags>(
10
10
  selectors: K,
@@ -0,0 +1,292 @@
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/element/templating.js';
13
+
14
+ class MyElement extends HTMLElement {
15
+ @bind()
16
+ myProperty: string;
17
+ }
18
+ ```
19
+
20
+ The decorator:
21
+ - Creates a two-way binding between component properties and templates
22
+ - Automatically handles value propagation through the `joist::value` event
23
+ - Integrates with Joist's observable system for efficient change detection
24
+
25
+ ### Token System (`token.ts`)
26
+
27
+ The `JToken` class handles parsing and evaluation of binding expressions. It supports:
28
+
29
+ - Simple property bindings: `propertyName`
30
+ - Nested property access: `user.profile.name`
31
+ - Negation operator: `!isVisible`
32
+
33
+ Example usage:
34
+ ```typescript
35
+ const token = new JToken('user.name');
36
+ const value = token.readTokenValueFrom(context);
37
+ ```
38
+
39
+ ### Events (`events.ts`)
40
+
41
+ The system uses custom events for value propagation:
42
+
43
+ - `JoistValueEvent`: A custom event that handles value updates in the templating system
44
+ - Bubbles through the DOM tree
45
+ - Carries both the token and update mechanism
46
+
47
+ ## Built-in Template Elements
48
+
49
+ Joist provides several built-in template elements for common templating needs:
50
+
51
+ ### Conditional Rendering (`j-if`)
52
+
53
+ Conditionally renders content based on a boolean expression:
54
+
55
+ ```html
56
+ <j-if bind="isVisible">
57
+ <template>
58
+ <div>This content is only shown when isVisible is true</div>
59
+ </template>
60
+ </j-if>
61
+
62
+ <!-- With negation -->
63
+ <j-if bind="!isHidden">
64
+ <template>
65
+ <div>This content is shown when isHidden is false</div>
66
+ </template>
67
+ </j-if>
68
+ ```
69
+
70
+ ### Property Binding (`j-props`)
71
+
72
+ Binds values to element properties (rather than attributes). This is particularly useful for boolean properties, form inputs, and other cases where attribute binding isn't sufficient:
73
+
74
+ ```html
75
+ <j-props>
76
+ <!-- Bind to boolean properties -->
77
+ <input type="checkbox" $.checked="isComplete">
78
+
79
+ <!-- Bind to form input values -->
80
+ <input type="text" $.value="userName">
81
+
82
+ <!-- Bind to custom element properties -->
83
+ <my-element $.data="complexObject">
84
+ </j-props>
85
+ ```
86
+
87
+ Note the `$.` prefix for property bindings. This distinguishes property bindings from attribute bindings.
88
+
89
+ Common use cases:
90
+ - Form input states (`checked`, `value`, `disabled`)
91
+ - Boolean properties that don't work well as attributes
92
+ - Complex objects that need to be passed as properties
93
+ - Custom element properties
94
+
95
+ ### List Rendering (`j-for`)
96
+
97
+ Renders lists of items with support for keyed updates:
98
+
99
+ ```html
100
+ <j-for bind="todos" key="id">
101
+ <template>
102
+ <j-props>
103
+ <div
104
+ class="todo-item"
105
+ $.dataset.id="each.value.id"
106
+ $.dataset.completed="each.value.completed"
107
+ >
108
+ <j-props>
109
+ <input type="checkbox" $.checked="each.value.completed">
110
+ </j-props>
111
+
112
+ <j-value bind="each.value.text"></j-value>
113
+
114
+ <j-props>
115
+ <button $.disabled="!each.value.text">×</button>
116
+ </j-props>
117
+ </div>
118
+ </j-props>
119
+ </template>
120
+ </j-for>
121
+ ```
122
+
123
+ The `j-for` element provides context variables:
124
+ - `each.value`: The current item
125
+ - `each.index`: Zero-based index
126
+ - `each.position`: One-based position
127
+
128
+ ### Value Display (`j-value`)
129
+
130
+ Displays a bound value as text content:
131
+
132
+ ```html
133
+ <j-value bind="user.name"></j-value>
134
+ <j-value bind="formattedPrice"></j-value>
135
+ ```
136
+
137
+ ## Complete Example
138
+
139
+ Here's a complete todo application in a single component:
140
+
141
+ ```typescript
142
+ import { bind } from '@joist/element/templating.js';
143
+ import { element, html, css, listen, query } from '@joist/element';
144
+
145
+ interface Todo {
146
+ id: number;
147
+ text: string;
148
+ completed: boolean;
149
+ }
150
+
151
+ @element({
152
+ tagName: 'todo-list',
153
+ shadowDom: [
154
+ css`
155
+ :host {
156
+ display: block;
157
+ max-width: 600px;
158
+ margin: 2rem auto;
159
+ }
160
+ .form {
161
+ display: flex;
162
+ gap: 1rem;
163
+ }
164
+ .todo-item {
165
+ display: flex;
166
+ gap: 0.5rem;
167
+ margin: 0.5rem 0;
168
+ }
169
+ .todo-text {
170
+ flex: 1;
171
+ }
172
+ [data-completed="true"] .todo-text {
173
+ text-decoration: line-through;
174
+ opacity: 0.6;
175
+ }
176
+ `,
177
+ html`
178
+ <form class="form">
179
+ <input type="text" placeholder="What needs to be done?">
180
+ <button type="submit">Add</button>
181
+ </form>
182
+
183
+ <j-if bind="!todos.length">
184
+ <template>
185
+ <p>No todos yet!</p>
186
+ </template>
187
+ </j-if>
188
+
189
+ <j-for id="todos" bind="todos" key="id">
190
+ <template>
191
+ <j-props class="todo-item" $.dataset.completed="each.value.completed">
192
+ <j-props>
193
+ <input type="checkbox" $.id="each.value.id" $.checked="each.value.completed">
194
+ <j-value class="todo-text" bind="each.value.text"></j-value>
195
+ <button $.id="each.value.id" $.disabled="!each.value.text">×</button>
196
+ </j-props>
197
+ </j-props>
198
+ </template>
199
+ </j-for>
200
+
201
+ <j-value bind="stats.remaining"></j-value> remaining
202
+ `
203
+ ]
204
+ })
205
+ export class TodoList extends HTMLElement {
206
+ @bind()
207
+ accessor todos: Todo[] = [];
208
+
209
+ @bind()
210
+ accessor stats = {
211
+ remaining: 0,
212
+ completed: 0
213
+ };
214
+
215
+ #nextId = 1;
216
+ #input = query('input');
217
+
218
+ #updateStats() {
219
+ this.stats = {
220
+ completed: this.todos.filter(todo => todo.completed).length,
221
+ remaining: this.todos.length - this.stats.completed
222
+ };
223
+ }
224
+
225
+ @listen('submit', 'form')
226
+ onSubmit(e: SubmitEvent) {
227
+ e.preventDefault();
228
+ const input = this.#input();
229
+ const text = input.value.trim();
230
+
231
+ if (text) {
232
+ this.todos = [
233
+ ...this.todos,
234
+ { id: this.#nextId++, text, completed: false }
235
+ ];
236
+
237
+ input.value = '';
238
+
239
+ this.#updateStats();
240
+ }
241
+ }
242
+
243
+ @listen('change', '#todos')
244
+ onToggle(e: Event) {
245
+ if(e.target instanceof HTMLInputElement) {
246
+ const id = Number(e.target.id);
247
+
248
+ this.todos = this.todos.map(todo => {
249
+ if (todo.id === id) {
250
+ return { ...todo, completed: checkbox.checked };
251
+ }
252
+
253
+ return todo;
254
+ });
255
+
256
+ this.#updateStats();
257
+ }
258
+ }
259
+
260
+ @listen('click', '#todos')
261
+ onDelete(e: Event) {
262
+ if(e.target instanceof HTMLElement) {
263
+ const id = Number(e.target.id);
264
+
265
+ this.todos = this.todos.filter(todo => todo.id !== id);
266
+
267
+ this.#updateStats();
268
+ }
269
+ }
270
+ }
271
+ ```
272
+
273
+ ## Usage
274
+
275
+ 1. Use the `@bind()` decorator on properties you want to make bindable
276
+ 2. Properties will automatically integrate with the templating system
277
+ 3. Changes are propagated through the component tree using the custom event system
278
+
279
+ ## Integration with Observable
280
+
281
+ The templating system is built on top of Joist's observable system (`@joist/observable`), providing:
282
+ - Automatic change detection
283
+ - Efficient updates
284
+ - Integration with the component lifecycle
285
+
286
+ ## Best Practices
287
+
288
+ 1. Use the `@bind()` decorator only on properties that need reactivity
289
+ 2. Keep binding expressions simple and avoid deep nesting
290
+ 3. Consider performance implications when binding to frequently changing values
291
+ 4. Always use a `key` attribute with `j-for` when items can be reordered
292
+ 5. Place template content directly inside `j-if` and `j-for` elements
@@ -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,4 @@
1
+ import "./elements/for.element.js";
2
+ import "./elements/if.element.js";
3
+ import "./elements/props.element.js";
4
+ import "./elements/value.element.js";
@@ -0,0 +1,39 @@
1
+ import "./for.element.js";
2
+ import "./value.element.js";
3
+
4
+ import { fixtureSync, html } from "@open-wc/testing";
5
+ import { assert } from "chai";
6
+
7
+ import type { JoistValueEvent } from "../events.js";
8
+
9
+ it("should iterate over an iterable", () => {
10
+ const element = fixtureSync(html`
11
+ <div
12
+ @joist::value=${(e: JoistValueEvent) => {
13
+ e.update({
14
+ oldValue: null,
15
+ newValue: new Set([
16
+ { id: "123", label: "Hello" },
17
+ { id: "456", label: "World" },
18
+ ]),
19
+ });
20
+ }}
21
+ >
22
+ <ul>
23
+ <j-for bind="items" key="id">
24
+ <template>
25
+ <li>
26
+ <j-value bind="each.value.label"></j-value>
27
+ </li>
28
+ </template>
29
+ </j-for>
30
+ </ul>
31
+ </div>
32
+ `);
33
+
34
+ const listItems = element.querySelectorAll("li");
35
+
36
+ assert.equal(listItems.length, 2);
37
+ assert.equal(listItems[0].textContent?.trim(), "Hello");
38
+ assert.equal(listItems[1].textContent?.trim(), "World");
39
+ });
@@ -0,0 +1,151 @@
1
+ import { attr } from "../../attr.js";
2
+ import { element } from "../../element.js";
3
+ import { query } from "../../query.js";
4
+ import { css, html } from "../../tags.js";
5
+
6
+ import { bind } from "../bind.js";
7
+ import { JoistValueEvent } from "../events.js";
8
+ import { JToken } from "../token.js";
9
+
10
+ declare global {
11
+ interface HTMLElementTagNameMap {
12
+ "j-for": JositForElement;
13
+ "j-for-scope": JForScope;
14
+ }
15
+ }
16
+
17
+ export interface EachCtx<T> {
18
+ value: T | null;
19
+ index: number | null;
20
+ position: number | null;
21
+ }
22
+
23
+ @element({
24
+ tagName: "j-for-scope",
25
+ // prettier-ignore
26
+ shadowDom: [css`:host{display: contents;}`, html`<slot></slot>`],
27
+ })
28
+ export class JForScope<T = unknown> extends HTMLElement {
29
+ @bind()
30
+ accessor each: EachCtx<T> = {
31
+ value: null,
32
+ index: null,
33
+ position: null,
34
+ };
35
+
36
+ @attr()
37
+ accessor key = "";
38
+ }
39
+
40
+ @element({
41
+ tagName: "j-for",
42
+ // prettier-ignore
43
+ shadowDom: [css`:host{display:contents;}`, html`<slot></slot>`],
44
+ })
45
+ export class JositForElement extends HTMLElement {
46
+ @attr()
47
+ accessor bind = "";
48
+
49
+ @attr()
50
+ accessor key = "";
51
+
52
+ #template = query("template", this);
53
+ #items: Iterable<unknown> = [];
54
+ #scopes = new Map<unknown, JForScope>();
55
+
56
+ connectedCallback(): void {
57
+ const template = this.#template();
58
+
59
+ if (this.firstElementChild !== template) {
60
+ throw new Error("The first Node in j-for needs to be a template");
61
+ }
62
+
63
+ let currentScope = template.nextElementSibling;
64
+
65
+ while (currentScope instanceof JForScope) {
66
+ this.#scopes.set(currentScope.key, currentScope);
67
+ currentScope = currentScope.nextElementSibling;
68
+ }
69
+
70
+ const token = new JToken(this.bind);
71
+
72
+ this.dispatchEvent(
73
+ new JoistValueEvent(token, ({ newValue, oldValue }) => {
74
+ if (newValue !== oldValue) {
75
+ if (isIterable(newValue)) {
76
+ this.#items = newValue;
77
+ } else {
78
+ this.#items = [];
79
+ }
80
+
81
+ this.updateItems();
82
+ }
83
+ }),
84
+ );
85
+ }
86
+
87
+ updateItems(): void {
88
+ const template = this.#template();
89
+ const leftoverScopes = new Map<unknown, JForScope>(this.#scopes);
90
+
91
+ let index = 0;
92
+
93
+ for (const item of this.#items) {
94
+ const key = hasProperty(item, this.key) ? item[this.key] : index;
95
+
96
+ let scope = leftoverScopes.get(key);
97
+
98
+ if (!scope) {
99
+ scope = new JForScope();
100
+ scope.append(document.importNode(template.content, true));
101
+ } else {
102
+ leftoverScopes.delete(key); // Remove from map to track unused scopes
103
+ }
104
+
105
+ scope.key = String(key);
106
+ scope.each = {
107
+ position: index + 1,
108
+ index: index,
109
+ value: item,
110
+ };
111
+
112
+ if (!scope.isConnected) {
113
+ const child = this.children[index + 1]; // skip first child since it should be the template element
114
+
115
+ if (child) {
116
+ child.before(scope);
117
+ } else {
118
+ this.append(scope);
119
+ }
120
+
121
+ this.#scopes.set(key, scope);
122
+ }
123
+
124
+ index++;
125
+ }
126
+
127
+ // Remove unused scopes
128
+ for (const scope of leftoverScopes.values()) {
129
+ scope.remove();
130
+ }
131
+ }
132
+
133
+ disconnectedCallback(): void {
134
+ for (const scope of this.#scopes.values()) {
135
+ scope.remove();
136
+ }
137
+
138
+ this.#scopes.clear();
139
+ this.#items = [];
140
+ }
141
+ }
142
+
143
+ function isIterable<T = unknown>(obj: any): obj is Iterable<T> {
144
+ return obj != null && typeof obj[Symbol.iterator] === "function";
145
+ }
146
+ function hasProperty(
147
+ item: unknown,
148
+ key: string,
149
+ ): item is Record<string, unknown> {
150
+ return Object.prototype.hasOwnProperty.call(item, key);
151
+ }
@@ -0,0 +1,55 @@
1
+ import "./if.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 render content when the bind value is truthy", () => {
9
+ const element = fixtureSync(html`
10
+ <div
11
+ @joist::value=${(e: JoistValueEvent) => {
12
+ e.update({ oldValue: null, newValue: true });
13
+ }}
14
+ >
15
+ <j-if bind="test">
16
+ <template>Visible Content</template>
17
+ </j-if>
18
+ </div>
19
+ `);
20
+
21
+ assert.equal(element.textContent?.trim(), "Visible Content");
22
+ });
23
+
24
+ it("should not render content when the bind value is falsy", () => {
25
+ const element = fixtureSync(html`
26
+ <div
27
+ @joist::value=${(e: JoistValueEvent) => {
28
+ e.update({ oldValue: null, newValue: true });
29
+ e.update({ oldValue: null, newValue: false });
30
+ }}
31
+ >
32
+ <j-if bind="test">
33
+ <template>Visible Content</template>
34
+ </j-if>
35
+ </div>
36
+ `);
37
+
38
+ assert.equal(element.textContent?.trim(), "");
39
+ });
40
+
41
+ it("should handle negated tokens correctly", () => {
42
+ const element = fixtureSync(html`
43
+ <div
44
+ @joist::value=${(e: JoistValueEvent) => {
45
+ e.update({ oldValue: null, newValue: false });
46
+ }}
47
+ >
48
+ <j-if bind="!test">
49
+ <template>Visible Content</template>
50
+ </j-if>
51
+ </div>
52
+ `);
53
+
54
+ assert.equal(element.textContent?.trim(), "Visible Content");
55
+ });
@@ -0,0 +1,67 @@
1
+ import { attr } from "../../attr.js";
2
+ import { element } from "../../element.js";
3
+ import { type QueryResult, query } from "../../query.js";
4
+ import { css, html } from "../../tags.js";
5
+
6
+ import { JoistValueEvent } from "../events.js";
7
+ import { JToken } from "../token.js";
8
+
9
+ declare global {
10
+ interface HTMLElementTagNameMap {
11
+ "j-if": JoistIfElement;
12
+ }
13
+ }
14
+
15
+ @element({
16
+ tagName: "j-if",
17
+ // prettier-ignore
18
+ shadowDom: [css`:host{display: contents;}`, html`<slot></slot>`],
19
+ })
20
+ export class JoistIfElement extends HTMLElement {
21
+ @attr()
22
+ accessor bind = "";
23
+
24
+ childTemplate: QueryResult<HTMLTemplateElement> = query("template", this);
25
+
26
+ connectedCallback(): void {
27
+ // make sure there are no other nodes after the template
28
+ this.#clean();
29
+
30
+ const token = new JToken(this.bind);
31
+
32
+ this.dispatchEvent(
33
+ new JoistValueEvent(token, ({ newValue, oldValue }) => {
34
+ if (newValue !== oldValue) {
35
+ if (typeof newValue === "object" && newValue !== null) {
36
+ this.apply(token.readTokenValueFrom(newValue), token.isNegated);
37
+ } else {
38
+ this.apply(newValue, token.isNegated);
39
+ }
40
+ }
41
+ }),
42
+ );
43
+ }
44
+
45
+ apply(value: unknown, isNegative: boolean): void {
46
+ const childTemplate = this.childTemplate();
47
+
48
+ if (isNegative ? !value : value) {
49
+ // only clone the template if it is not already in the DOM
50
+ if (childTemplate.nextSibling === null) {
51
+ const res = document.importNode(childTemplate.content, true);
52
+
53
+ this.appendChild(res);
54
+ }
55
+ } else {
56
+ this.#clean();
57
+ }
58
+ }
59
+
60
+ #clean() {
61
+ const childTemplate = this.childTemplate();
62
+
63
+ while (childTemplate.nextSibling) {
64
+ childTemplate.nextSibling.remove();
65
+ }
66
+ }
67
+ }