sprae 1.0.0 → 2.0.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.
@@ -0,0 +1,30 @@
1
+ # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2
+ # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
3
+
4
+ name: Tests
5
+
6
+ on:
7
+ push:
8
+ branches: [ "main" ]
9
+ pull_request:
10
+ branches: [ "main" ]
11
+
12
+ jobs:
13
+ build:
14
+
15
+ runs-on: ubuntu-latest
16
+
17
+ strategy:
18
+ matrix:
19
+ node-version: [18.x]
20
+
21
+ steps:
22
+ - uses: actions/checkout@v3
23
+ - name: Use Node.js ${{ matrix.node-version }}
24
+ uses: actions/setup-node@v3
25
+ with:
26
+ node-version: ${{ matrix.node-version }}
27
+ cache: 'npm'
28
+ - run: npm ci
29
+ - run: npm run build --if-present
30
+ - run: npm test
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "sprae",
3
3
  "description": "Reactive directives with expressions for DOM microtemplating.",
4
- "version": "1.0.0",
4
+ "version": "2.0.0",
5
5
  "main": "sprae.js",
6
6
  "type": "module",
7
7
  "dependencies": {
8
+ "@preact/signals-core": "^1.2.2",
8
9
  "element-props": "^2.3.0",
9
- "sube": "^2.2.1"
10
+ "primitive-pool": "^2.0.0",
11
+ "signal-struct": "^1.5.0",
12
+ "sube": "^2.2.1",
13
+ "swapdom": "^1.1.1"
10
14
  },
11
15
  "devDependencies": {
12
16
  "@preact/signals": "^1.1.2",
@@ -16,6 +20,7 @@
16
20
  "hyperf": "^1.4.0",
17
21
  "terser": "^5.15.1",
18
22
  "tst": "^7.1.1",
23
+ "usignal": "^0.8.9",
19
24
  "value-ref": "^2.1.0",
20
25
  "wait-please": "^3.1.0"
21
26
  },
package/plan.md CHANGED
@@ -1,6 +1,20 @@
1
- * [ ] finish directives
2
- * [ ] better list diffing
3
- * [?] ordered directives init (:each + :if vs :if + :each) -> find out if really needed
4
- * [x] ~~autoinit~~ -> too much maintenance burden
5
- * [ ] node tests
6
- * [ ] better deps updating
1
+ * [x] finish directives
2
+ * [x] better list diffing
3
+ * [x] ordered directives init (:each + :if vs :if + :each) -> find out if really needed and which is faster
4
+ -> yes, needed and solve many init issues.
5
+ * [?] autoinit -> too much maintenance burden
6
+ * [x] node tests
7
+ * [x] better deps updating -> cumulative signal
8
+ * [x] combinations: :else :if
9
+ * [x] :each :if, :if :each
10
+ * [x] :each :each
11
+ * [x] :with must be able to write state value as well
12
+ * [x] docs: give example to each directive
13
+ * [x] initialize per-element: <x :each><y :if></y><x> - tree-dependent (:each comes first).
14
+ * [x] generalize common attributes :prop="xyz"
15
+ * [x] spread props
16
+ * [x] optimization: arrays with multiple elements can be slow on creation. Maybe signal-struct must ignore arrays.
17
+ -> yep: arrays are rarely changed as `a[i]=newItem` and regularly they're mapped.
18
+ * [x] expand to any subscribables: both as state vars
19
+ * [ ] optimization: replace element-props with direct (better) setters
20
+ * [ ] report usignal problem
package/r&d.md CHANGED
@@ -32,7 +32,12 @@
32
32
  + reference to sporae and similar assoication
33
33
  + simpler word
34
34
  + better assoc with hydration
35
-
35
+ + spree
36
+ + spread
37
+ * sprinkle
38
+ + better meaning
39
+ - stands out less than sprae
40
+ * aerosol
36
41
 
37
42
  ## [x] :attr, :data, :id, :class, :style, :on, :aria - do we enforce JS syntax or support unscoped expression? -> Use JS convention, too many use-cases.
38
43
 
@@ -50,14 +55,14 @@
50
55
  + Custom expressions are shorter: `:attr="a:1, b:2, c:3"`
51
56
  - Custom expressions are confusing for style: `:style="a:1, b:2, c:3"` - very similar to direct style string
52
57
 
53
- ## [x] Attribute directive: `:={a:1}` vs `:attr={a:1}` vs `:prop={a:1}`
58
+ ## [x] Attribute directive: `:={a:1}` vs `:attr={a:1}` vs `:prop={a:1}` -> hold on for now
54
59
 
55
60
  + `:=obj` reminds pascal assignment operator, which is cool
56
61
  + `:={a:1,b:2}` is natural convention from vue/alpine as - all props in object are assigned as `:{attr}`
57
62
  - We can use `:="{data}"` fro sprae autoinit, since scope has confusing name: `:scope={}`, `:sprae={}`, `:with={}`
58
63
  -> let's use :prop= for now, since `:={}` can have multiple interpretations
59
64
 
60
- ## [x] Scopes mechanism: prototype inheritance chain vs multiple `with` wrappers
65
+ ## [x] Scopes mechanism: prototype inheritance chain vs multiple `with` wrappers -> init subtrees, no need for explicit mechanism
61
66
 
62
67
  - prototype inheritance chain causes deps update difficulties
63
68
  - prototype chain is messy-ish
@@ -81,7 +86,7 @@
81
86
 
82
87
  -> possibly we have to just subscribe via mechanism of signals-like deps, and :with just initializes subtree with extended object
83
88
 
84
- ## [ ] Should we inherit values from `init` in `sprae(el, init)`, instead of creating a snapshot of reactive values in `init`?
89
+ ## [x] Should we inherit values from `init` in `sprae(el, init)`, instead of creating a snapshot of reactive values in `init`? -> nah, nice idea but too little use. Better create signals struct.
85
90
 
86
91
  + it allows passing any arbitrary scope to initialize from.
87
92
  - it can make hard finding reactive sources...
@@ -89,23 +94,69 @@
89
94
  -> can be delegated to a separate functionality - init just gets converted to reactive store
90
95
  + it sort-of makes `init` directly a scope (a parent of scope), which is more natural-ish rather than 2 independent entities
91
96
  + can pass both observables and direct state anywhere, eg. init child components from it
92
- -> worthy of a separate library
97
+ -> worthy of a separate library, signal-struct?
93
98
 
94
- ## [ ] Per-directive initialize vs per-element initialize
99
+ ## [x] Per-directive initialize vs per-element initialize -> directives can immediately initialize rest on elements
95
100
 
96
101
  + Per-directive is very simple and trivial approach
97
102
  - Per-directive doesn't read attributes order and init directives independently
98
103
  ~ Practically linear in-order init doesn't make much service either here
99
104
  - Per-directive is a bit hard to deal with scopes
105
+ -> gotta benchmark, vs just walker.
106
+ -> seems unavoidable to combine :if within :each, since :each should remove elements and init on find only
100
107
 
101
- ## [ ] avoid updating unchanged directives if values don't affect them
108
+ ## [x] avoid updating unchanged directives if values don't affect them -> signal struct
102
109
 
103
110
  ? what if we use preact/signals to subscribe only to required props?
104
111
  -> parseExpr is going to need to be handled by core.js (not directives), and detect & subscribe to dependencies itself
105
112
  -> so that directive updator gets invoked only when any of expr dependencies change
113
+ -> gotta solve via signal-struct
106
114
 
107
- ## [ ] Replace :else-if with :else :if
115
+ ## [x] Replace :else-if with :else :if -> not ideal technically, but done
108
116
 
109
117
  + `:else :if=""` is meaningful expansion of both directives
110
118
  + `:else :if` is coming from JS
111
- + `:else :if` doesn't throw error in JSDOM tests
119
+ + `:else :if` doesn't throw error in JSDOM tests
120
+ - less resemblance with vue: who cares, we already remotely resemble it
121
+
122
+ ## [x] Keep className marker of directive or not?
123
+
124
+ -> No: first, there's :class directive changing the class itself;
125
+ -> Second, there's easier way to just "evaporate" directive = not initialize twice;
126
+ -> Third, there's too much pollution with class markers
127
+
128
+ ## [ ] Plugins
129
+
130
+ * init/connected/mount, unmount/disconnected?
131
+ * init and connected are different apparently
132
+ * :html?
133
+ * :effect?
134
+ * @sprae/tailwind: `<x :tw="mt-1 mx-2"></x>` - separate tailwind utility classes from main ones; allow conditional setters.
135
+ * @sprae/item: `<x :item="{type:a, scope:b}"` – provide microdata
136
+ * @sprae/hcodes: `<x :h=""` – provide microformats
137
+
138
+ ## [x] Write any-attributes via :<prop>?
139
+
140
+ + Since we support attr walking, maybe instead of :on and :prop just allow any attributes?
141
+ + that would allow event and attr modifiers...
142
+ + that would allow somewhat alpine/vue-compatible code
143
+ + makes sense for `:="{}"` spread
144
+ + makes place for other specific directives `:init=""` etc
145
+
146
+ ## [x] :value is confusing: <option> also uses that.
147
+
148
+ ? :model="value"
149
+ + v-model, x-model
150
+ - confusing
151
+ ? :in="text"
152
+ ? :input="text"
153
+ ? :bind="value"
154
+ + more accurate logically
155
+ - conflicts with existing naming (bind is used for attrs)
156
+ - conflict if used along with `:value="x" :bind="y"`
157
+ ? :value="value" :onchange="e=>value=e.target.value"
158
+ + more apparent and explicit
159
+ + less mental load, "model" is too heavy term
160
+ + overhead is minimal
161
+ + react-like
162
+ + it has better control over serialization
package/readme.md CHANGED
@@ -1,48 +1,29 @@
1
- # ∴ spræ [![size](https://img.shields.io/bundlephobia/minzip/sprae?label=size)](https://bundlephobia.com/result?p=sprae)
1
+ # ∴ spræ [![tests](https://github.com/dy/sprae/actions/workflows/node.js.yml/badge.svg)](https://github.com/dy/sprae/actions/workflows/node.js.yml) [![size](https://img.shields.io/bundlephobia/minzip/sprae?label=size)](https://bundlephobia.com/result?p=sprae)
2
2
 
3
- > Reactive microdirectives for soft DOM hydration.
3
+ > Soft DOM hydration with reactive microdirectives
4
4
 
5
5
  A lightweight essential alternative to [alpine](https://github.com/alpinejs/alpine), [petite-vue](https://github.com/vuejs/petite-vue), [templize](https://github.com/dy/templize) or JSX with better ergonomics[*](#justification).
6
6
 
7
7
 
8
8
  ## Usage
9
9
 
10
- Sprae enables directives as attributes starting with `:`.
10
+ Spraedrops (directives) are attributes starting with `:` that contain regular JS expressions:
11
11
 
12
12
  ```html
13
- <div id="element" :if="user">
13
+ <div id="container" :if="user">
14
14
  Logged in as <span :text="user.displayName">Guest.</span>
15
15
  </div>
16
16
 
17
17
  <script type="module">
18
18
  import sprae from 'sprae';
19
19
 
20
- const init = { user: { displayName: 'Dmitry Ivanov' } }
21
- const state = sprae(user, init);
22
-
23
- state.user.displayName = 'dy' // automatically updates DOM
20
+ const state = sprae(container, { user: { displayName: 'Dmitry Ivanov' } });
21
+ state.user.displayName = 'dy'; // automatically updates DOM
24
22
  </script>
25
23
  ```
26
24
 
27
- * `sprae` initializes directives within an `element` subtree with passed `init` data.
28
- * `state` is proxy reflecting directives values, changing any of its props updates directives.
29
- * `init` is the initial state to render the template. It can include reactive values, see [reactivity](#reactivity).
30
-
31
-
32
- <details>
33
- <summary><strong>Bulk update</strong></summary>
34
-
35
- To update multiple values at once, state can be expanded as:
36
-
37
- ```js
38
- let [values, update] = state;
39
- update({ user: { displayName: 'dy' } });
40
- ```
41
-
42
- * `values` holds actual rendered state values. Changing it doesn't rerender DOM, unlike `state`.
43
- * `update` useful for bulk-updating multiple values at once.
44
-
45
- </details>
25
+ * `sprae` initializes directives with data (can include [signals](https://github.com/preactjs/signals) or [reactive values](https://github.com/dy/sube)). Once initialized, they immediately evaporate.
26
+ * `state` is object reflecting values, changing any of its props rerenders directives.
46
27
 
47
28
  <!--
48
29
  <details>
@@ -51,12 +32,10 @@ update({ user: { displayName: 'dy' } });
51
32
  Sprae can be used without build step or JS, autoinitializing document:
52
33
 
53
34
  ```html
54
- <script src="./sprae.js" defer init></script>
35
+ <script src="./sprae.js" defer init="{ count: 0 }"></script>
55
36
 
56
- <div :with="{ count: 0 }">
57
- <span :text="count">
58
- <button :on="{ click: e => count++ }">inc</button>
59
- </div>
37
+ <span :text="count">
38
+ <button :on="{ click: e => count++ }">inc</button>
60
39
  ```
61
40
 
62
41
  * `:with` defines data for regions of the tree to autoinit sprae on.
@@ -67,62 +46,130 @@ Sprae can be used without build step or JS, autoinitializing document:
67
46
 
68
47
  ## Directives
69
48
 
70
- * `:if="condition"`, `:else` - controls flow of elements.
71
- * `:each="item, i? in list|number"` - create multiple instances of element from list or 1..number range.
72
- * `:text="value"` - set text content of an element.
73
- * `:value="value"` – bind value to input or textarea (reflected in model).
74
- * `:id`, `:name`, `:for`, `:type`, `:hidden`, `:disabled`, `:href`, `:src` – common attributes setters.
75
- * `:class="[ foo, 'bar' ]"` – set element class from an array, object or a string.
76
- * `:style="{ top:1, position:'absolute' }"` – set element style from a string or an object.
77
- * `:prop="{ alt:'foo', title:'bar' }"` – set any other attribute / property.
78
- * `:on="{ click:e=>{}, touch:e=>{} }"` – add event listeners.
79
- * `:data="{ foo:1, bar:2 }"` – set [data-*](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*) attributes.
80
- * `:aria="{ role:'progressbar' }"` – set [aria-role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) attributes.
81
- * `:with="data"` – provide data alias for subtree fragment.
82
- <!-- * [ ] `:item="{ id: 1 }"` – set [item*](https://developer.mozilla.org/en-US/docs/Web/HTML/Microdata) microdata attribute. -->
83
-
84
-
49
+ #### `:if="condition"`, `:else`
85
50
 
86
- <details>
87
- <summary><strong>Combining directives</strong></summary>
88
-
89
- Directives can be naturally combined as:
51
+ Control flow of elements.
90
52
 
91
53
  ```html
92
54
  <span :if="foo">foo</span>
93
55
  <span :else :if="bar">bar</span>
94
56
  <span :else>baz</span>
57
+ ```
58
+
59
+ #### `:each="item, index in items"`
95
60
 
96
- <span :if="items" :each="item in items"></span>
97
- <span :else>Empty list</span>
61
+ Multiply element. `index` value starts from 1.
62
+
63
+ ```html
64
+ <ul :with="{items: ['a','b','c']}">
65
+ <li :each="item in items" :text="item">Untitled</li>
66
+ </ul>
67
+
68
+ <!-- Cases -->
69
+ <li :each="item, idx in list" />
70
+ <li :each="val, key in obj" />
71
+ <li :each="idx in 10" />
72
+
73
+ <!-- Loop by condition -->
74
+ <li :if="items" :each="item in items" :text="item" />
75
+ <li :else>Empty list</li>
98
76
  ```
99
- </details>
100
77
 
78
+ #### `:text="value"`
101
79
 
102
- <details>
103
- <summary><strong>Adding directives</strong></summary>
80
+ Set text content of an element. Default text can be used as fallback:
104
81
 
105
- Directives can be added by registering them via `directive(name, initializer)`:
82
+ ```html
83
+ Welcome, <span :text="user.name">Guest</span>.
84
+ ```
106
85
 
107
- ```js
108
- import { directive, parseExpr } from 'sprae';
86
+ #### `:class="value"`
109
87
 
110
- directive(':html', (el, expr) => {
111
- // ...initialize here
112
- const evaluate = parseExpr(expr);
113
- return (state) => {
114
- // ...update here
115
- el.innerHTML = evaluate(state);
116
- }
117
- });
88
+ Set class value from either string, array or object.
89
+
90
+ ```html
91
+ <div :class="`foo ${bar}`"></div>
92
+ <div :class="['foo', 'bar']"></div>
93
+ <div :class="{foo: true, bar: false}"></div>
118
94
  ```
119
95
 
120
- </details>
96
+ #### `:style="value"`
97
+
98
+ Set style value from object or a string.
99
+
100
+ ```html
101
+ <div :style="foo: bar"></div>
102
+ <div :style="{foo: 'bar'}"></div>
103
+ ```
121
104
 
105
+ <!--
106
+ #### `:value="value"`
122
107
 
123
- ## Reactivity
108
+ Bind (2-way) value to input, textarea or select.
124
109
 
125
- Directive expressions are naturally reactive, ie. data may contain any async/reactive values, such as:
110
+ ```html
111
+ <input :with="{text: ''}" :value="text" />
112
+ <textarea :with="{text: ''}" :value="text" />
113
+
114
+ <select :with="{selected: 0}" :value="selected">
115
+ <option :each="i in 5" :value="i" :text="i"></option>
116
+ </select>
117
+ ```
118
+ -->
119
+
120
+ #### `:<prop>="value"`, `:="props"`
121
+
122
+ Set any other prop or props value.
123
+
124
+ ```html
125
+ <label :for="name" :text="name" />
126
+ <input :="{ id: name, name, type, value }" :onchange="e => value=e.target.value" />
127
+ ```
128
+
129
+ #### `:on="events"`
130
+
131
+ Add event listeners.
132
+
133
+ ```html
134
+ <button :on="{ click: handler, touch: handler }">Submit</button>
135
+ ```
136
+
137
+ #### `:data="values"`
138
+
139
+ Set [data-*](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*) attributes. CamelCase is converted to dash-case.
140
+
141
+ ```html
142
+ <input :data="{foo: 1, barBaz: true}" />
143
+ ```
144
+
145
+ #### `:aria="values"`
146
+
147
+ Set [aria-role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) attributes. Boolean values are stringified.
148
+
149
+ ```html
150
+ <input type="text" id="jokes" role="combobox" :aria="{
151
+ controls: 'joketypes',
152
+ autocomplete: 'list',
153
+ expanded: false,
154
+ activeOption: 'item1',
155
+ activedescendant: ''
156
+ }" />
157
+ ```
158
+
159
+ #### `:with="data"`
160
+
161
+ Set data for a subtree fragment scope.
162
+
163
+ ```html
164
+ <x :with="{ foo: 'bar' }">
165
+ <y :with="{ baz: 'qux' }" :text="foo + baz"></y>
166
+ </x>
167
+ ```
168
+
169
+ <!--
170
+ ### Reactive values
171
+
172
+ Directive expressions are natively reactive, ie. data may contain any async/reactive values, such as:
126
173
 
127
174
  * _Promise_ / _Thenable_
128
175
  * _Observable_ / _Subject_ / _Subscribable_
@@ -156,14 +203,15 @@ Update happens when any value changes:
156
203
  </script>
157
204
  ```
158
205
 
159
- Note: observers don't require disposal, since they're connected in weak fashion. Once element is disposed, observables are disconnected.
206
+ Internally directives trigger updates only for used properties change. They subscribe in weak fashion and get disposed when element is disposed.
207
+ -->
160
208
 
161
209
 
162
210
  ## Justification
163
211
 
164
212
  * [Template-parts](https://github.com/dy/template-parts) / [templize](https://github.com/dy/templize) is progressive, but is stuck with native HTML quirks ([parsing table](https://github.com/github/template-parts/issues/24), [svg attributes](https://github.com/github/template-parts/issues/25), [liquid syntax](https://shopify.github.io/liquid/tags/template/#raw) conflict etc). Also ergonomics of `attr="{{}}"` is inferior to `:attr=""` since it creates flash of uninitialized values.
165
213
  * [Alpine](https://github.com/alpinejs/alpine) / [vue](https://github.com/vuejs/petite-vue) / [lit](https://github.com/lit/lit/tree/main/packages/lit-html) escapes native HTML quirks, but the syntax is a bit scattered: `:attr`, `v-*`,`x-*`, `@evt`, `{{}}` can be expressed with single convention. Besides, functionality is too broad and can be reduced to essence. Also they tend to [self-encapsulate](https://github.com/alpinejs/alpine/discussions/3223), making interop hard.
166
- * [preact](https://ghub.io/preact) with HTML as JSX is a nice way to wire JS to templates, but it doesn't really support reactive fields (needs render call). Also migrating HTML to JS is an extreme with unwanted side-effects.
214
+ * [preact](https://ghub.io/preact) with HTML as JSX is a nice way to wire JS to templates, but it doesn't really support reactive fields (needs render call). Also migrating all HTML to JS is an extreme: SPAs are not organic for HTML.
167
215
 
168
216
  _Sprae_ takes elegant syntax convention of _alpine_ and method of _templize_ to connect any reactive values (like [@preact/signals](https://ghub.io/@preact/signals) or observables) to static HTML.
169
217
 
@@ -174,4 +222,5 @@ _Sprae_ takes elegant syntax convention of _alpine_ and method of _templize_ to
174
222
  * It doesn'y introduce syntax scatter.
175
223
  * It supports simple expressions with exposed reactive data types.
176
224
 
225
+
177
226
  <p align="center"><a href="https://github.com/krsnzd/license/">🕉</a></p>