@manyducks.co/dolla 2.0.0-alpha.27 β†’ 2.0.0-alpha.29

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.
package/README.md CHANGED
@@ -7,110 +7,37 @@
7
7
 
8
8
  Dolla is a batteries-included JavaScript frontend framework covering the needs of moderate-to-complex single page apps:
9
9
 
10
- - ⚑ Reactive DOM updates with [State](). Inspired by Signals, but with more explicit tracking.
11
- - πŸ“¦ Reusable components with [Views](#section-views).
12
- - πŸ”€ Built in [routing]() with nested routes and middleware support (check login status, preload data, etc).
13
- - πŸ• Built in [HTTP]() client with middleware support (set auth headers, etc).
14
- - πŸ“ Built in [localization]() system (store translated strings in JSON files and call the `t` function to get them).
15
- - 🍳 Build system optional. Write views in JSX or use `html` tagged template literals.
10
+ - ⚑ Reactive DOM updates with [State](./docs/state.md). Inspired by Signals, but with explicit tracking.
11
+ - πŸ“¦ Reusable components with [Views](./docs/views.md).
12
+ - πŸ’Ύ Reusable state management with [Stores](./docs/stores.md).
13
+ - πŸ”€ Built-in [routing](./docs/router.md) with nested routes and middleware support (check login status, preload data, etc).
14
+ - πŸ• Built-in [HTTP](./docs/http.md) client with middleware support (set auth headers, etc).
15
+ - πŸ“ Built-in [localization](./docs/i18n.md) system (store translated strings in JSON files and call the `t` function to get them).
16
+ - 🍳 Build system optional. [Write views in JSX](./docs/setup.md) or use `html` tagged template literals.
16
17
 
17
- Let's first get into some examples.
18
+ Dolla's goals include:
18
19
 
19
- ## State
20
+ - Be fun to create with.
21
+ - Be snappy and responsive for real life apps.
22
+ - Be compact as possible but not at the expense of necessary features.
20
23
 
21
- ### Basic State API
24
+ ## Why Dolla?
22
25
 
23
- ```js
24
- import { createState, derive } from "@manyducks.co/dolla";
25
-
26
- const [$count, setCount] = createState(72);
27
-
28
- // Get value
29
- $count.get(): // 72
30
-
31
- // Replace the stored value with something else
32
- setCount(300);
33
- $count.get(); // 300
34
-
35
- // You can also pass a function that takes the current value and returns a new one
36
- setCount((current) => current + 1);
37
- $count.get(); // 301
38
- ```
39
-
40
- Now that you have a state you can derive more states from that one. Derived states automatically stay in sync with the values of their dependencies.
41
-
42
- ```js
43
- // Pass and array of one or more states followed by a function that computes a new value.
44
- const $doubled = derive([$count], (count) => count * 2);
45
-
46
- $doubled.get(); // 602
47
-
48
- setCount(500);
49
-
50
- $doubled.get(); // 1000
51
- ```
52
-
53
- ### In Views
54
-
55
- ```jsx
56
-
57
- ```
58
-
59
- States also come in a settable variety that includes the setter on the same object. Sometimes you want to pass around a two-way binding and this is what SettableState is for.
60
-
61
- ```jsx
62
- import { createSettableState, fromSettable, toSettable } from "@manyducks.co/dolla";
63
-
64
- // Settable states can be set by passing a value when they are called.
65
- const $$value = createSettableState("Test");
66
- $$value(); // "Test"
67
- $$value("New Value");
68
- $$value(); // "New Value"
69
-
70
- // They can also be split into a State and Setter
71
- const [$value, setValue] = fromSettableState($$value);
72
-
73
- // And a State and Setter can be combined into a SettableState.
74
- const $$otherValue = toSettableState($value, setValue);
75
-
76
- // Or discard the setter and make it read-only using the good old toState function:
77
- const $value = toState($$value);
78
- ```
79
-
80
- You can also do weird proxy things like this:
81
-
82
- ```jsx
83
- // Create an original place for the state to live
84
- const [$value, setValue] = createState(5);
85
-
86
- // Derive a state that doubles the value
87
- const $doubled = derive([$value], (value) => value * 2);
26
+ > TODO: Write about why Dolla was started and what it's all about.
88
27
 
89
- // Create a setter that takes the doubled value and sets the original $value accordingly.
90
- const setDoubled = createSetter($doubled, (next, current) => {
91
- setValue(next / 2);
92
- });
93
-
94
- // Bundle the derived state and setter into a SettableState to pass around.
95
- const $$doubled = toSettableState($doubled, setDoubled);
28
+ - Borne of frustration using React and similar libs (useEffect, referential equality, a pain to integrate other libs into its lifecycle, need to hunt for libraries to move beyond Hello World).
29
+ - Merges ideas from my favorite libraries and frameworks (Solid/Knockout, Choo, Svelte, i18next, etc) into one curated set designed to work well together.
30
+ - Opinionated (with the _correct_ opinions).
31
+ - Many mainstream libraries seem too big for what they do. The entirety of Dolla is less than half the size of [`react-router`](https://bundlephobia.com/package/react-router@7.1.5).
96
32
 
97
- // Setting the doubled state...
98
- $$doubled(100);
99
-
100
- // ... will be reflected everywhere.
101
- $$doubled(); // 100
102
- $doubled(); // 100
103
- $value(); // 50
104
- ```
33
+ ## An Example
105
34
 
106
- <h2 id="section-views">Views</h2>
107
-
108
- A basic view:
35
+ A basic view. Note that the view function is called exactly once when the view is first mounted. All changes to DOM nodes thereafter happen as a result of `$state` values changing.
109
36
 
110
37
  ```js
111
- import Dolla, { createState } from "@manyducks.co/dolla";
38
+ import Dolla, { createState, createView } from "@manyducks.co/dolla";
112
39
 
113
- function Counter(props, ctx) {
40
+ const Counter = createView(function (props) {
114
41
  const [$count, setCount] = createState(0);
115
42
 
116
43
  function increment() {
@@ -130,532 +57,20 @@ function Counter(props, ctx) {
130
57
  <p>Clicks: {$count}</p>
131
58
  <div>
132
59
  <button onClick={decrement}>-1</button>
133
- <button onClick={reset}>0</button>
134
- <button onClick={increment}>-1</button>
60
+ <button onClick={reset}>Reset</button>
61
+ <button onClick={increment}>+1</button>
135
62
  </div>
136
63
  </div>
137
64
  );
138
- }
139
-
140
- Dolla.mount(document.body, Counter);
141
- ```
142
-
143
- If you've ever used React before (and chances are you have if you're interested in obscure frameworks like this one) this should look very familiar to you.
144
-
145
- The biggest difference is that the Counter function runs only once when the component is mounted. All updates after that point are a direct result of `$count` being updated.
146
-
147
- ## Advanced Componentry
148
-
149
- Component functions take two arguments; props and a `Context` object. Props are passed from parent components to child components, and `Context` is provided by the app.
150
-
151
- > The following examples are shown in TypeScript for clarity. Feel free to omit the type annotations in your own code if you prefer vanilla JS.
152
-
153
- ### Props
154
-
155
- Props are values passed down from parent components. These can be static values, signals, callbacks and anything else the child component needs to do its job.
156
-
157
- ```tsx
158
- import { type State, type Context, html } from "@manyducks.co/dolla";
159
-
160
- type HeadingProps = {
161
- $text: State<string>;
162
- };
163
-
164
- function Heading(props: HeadingProps, c: Context) {
165
- return html`<h1>${props.$text}</h1>`;
166
- }
167
-
168
- function Layout() {
169
- const [$text, setText] = signal("HELLO THERE!");
170
-
171
- return (
172
- <section>
173
- <Heading $text={$text}>
174
- </section>
175
- );
176
- }
177
- ```
178
-
179
- ### Context
180
-
181
- ```tsx
182
- import { type State, type Context, html } from "@manyducks.co/dolla";
183
-
184
- type HeadingProps = {
185
- $text: State<string>;
186
- };
187
-
188
- function Heading(props: HeadingProps, c: Context) {
189
- // A full compliment of logging functions:
190
- // Log levels that get printed can be set at the app level.
191
-
192
- c.trace("What's going on? Let's find out.");
193
- c.info("This is low priority info.");
194
- c.log("This is normal priority info.");
195
- c.warn("Hey! This could be serious.");
196
- c.error("NOT GOOD! DEFINITELY NOT GOOD!!1");
197
-
198
- // And sometimes things are just too borked to press on:
199
- c.crash(new Error("STOP THE PRESSES! BURN IT ALL DOWN!!!"));
200
-
201
- // The four lifecycle hooks:
202
-
203
- // c.beforeMount(() => {
204
- // c.info("Heading is going to be mounted. Good time to set things up.");
205
- // });
206
-
207
- c.onMount(() => {
208
- c.info("Heading has just been mounted. Good time to access the DOM and finalize setup.");
209
- });
210
-
211
- // c.beforeUnmount(() => {
212
- // c.info("Heading is going to be unmounted. Good time to begin teardown.");
213
- // });
214
-
215
- c.onUnmount(() => {
216
- c.info("Heading has just been unmounted. Good time to finalize teardown.");
217
- });
218
-
219
- // States can be watched by the component context.
220
- // Watchers created this way are cleaned up automatically when the component unmounts.
221
-
222
- c.watch(props.$text, (value) => {
223
- c.warn(`text has changed to: ${value}`);
224
- });
225
-
226
- return html`<h1>${props.$text}</h1>`;
227
- }
228
- ```
229
-
230
- ## Signals
231
-
232
- Basics
233
-
234
- ```jsx
235
- const [$count, setCount] = signal(0);
236
-
237
- // Set the value directly.
238
- setCount(1);
239
- setCount(2);
240
-
241
- // Transform the previous value into a new one.
242
- setCount((current) => current + 1);
243
-
244
- // This can be used to create easy helper functions:
245
- function increment(amount = 1) {
246
- setCount((current) => current + amount);
247
- }
248
- increment();
249
- increment(5);
250
- increment(-362);
251
-
252
- // Get the current value
253
- $count.get(); // -354
254
-
255
- // Watch for new values. Don't forget to call stop() to clean up!
256
- const stop = $count.watch((current) => {
257
- console.log(`count is now ${current}`);
258
- });
259
-
260
- increment(); // "count is now -353"
261
- increment(); // "count is now -352"
262
-
263
- stop();
264
- ```
265
-
266
- Derive
267
-
268
- ```jsx
269
- import { signal, derive } from "@manyducks.co/dolla";
270
-
271
- const [$names, setNames] = signal(["Morg", "Ton", "Bon"]);
272
- const [$index, setIndex] = signal(0);
273
-
274
- // Create a new signal that depends on two existing signals:
275
- const $selected = derive([$names, $index], (names, index) => names[index]);
276
-
277
- $selected.get(); // "Morg"
278
-
279
- setIndex(2);
280
-
281
- $selected.get(); // "Bon"
282
- ```
283
-
284
- Proxy
285
-
286
- ```jsx
287
- import { createState, createProxyState } from "@manyducks.co/dolla";
288
-
289
- const [$names, setNames] = createState(["Morg", "Ton", "Bon"]);
290
- const [$index, setIndex] = createState(0);
291
-
292
- const [$selected, setSelected] = createProxyState([$names, $index], {
293
- get(names, index) {
294
- return names[index];
295
- },
296
- set(next, names, _) {
297
- const index = names.indexOf(next);
298
- if (index === -1) {
299
- throw new Error("Name is not in the list!");
300
- }
301
- setIndex(index);
302
- },
303
- });
304
-
305
- $selected.get(); // "Morg"
306
- $index.get(); // 0
307
-
308
- // Set selected directly by name through the proxy.
309
- setSelected("Ton");
310
-
311
- // Selected and the index have been updated to match.
312
- $selected.get(); // "Ton"
313
- $index.get(); // 1
314
- ```
315
-
316
- ## Views
317
-
318
- Views are what most frameworks would call Components. Dolla calls them Views because they deal specifically with stuff the user sees, and because Dolla also has another type of component called Stores that share data between views. We will get into those later.
319
-
320
- At its most basic, a view is a function that returns elements.
321
-
322
- ```jsx
323
- function ExampleView() {
324
- return <h1>Hello World!</h1>;
325
- }
326
- ```
327
-
328
- #### View Props
329
-
330
- A view function takes a `props` object as its first argument. This object contains all properties passed to the view when it's invoked.
331
-
332
- ```js
333
- import { html } from "@manyducks.co/dolla";
334
-
335
- function ListView(props, ctx) {
336
- return html`
337
- <ul>
338
- <${ListItemView} label="Squirrel" />
339
- <${ListItemView} label="Chipmunk" />
340
- <${ListItemView} label="Groundhog" />
341
- </ul>
342
- `;
343
- }
344
-
345
- function ListItemView(props, ctx) {
346
- return html`<li>${props.label}</li>`;
347
- }
348
- ```
349
-
350
- ```jsx
351
- function ListView() {
352
- return (
353
- <ul>
354
- <ListItemView label="Squirrel" />
355
- <ListItemView label="Chipmunk" />
356
- <ListItemView label="Groundhog" />
357
- </ul>
358
- );
359
- }
360
-
361
- function ListItemView(props) {
362
- return <li>{props.label}</li>;
363
- }
364
- ```
365
-
366
- As you may have guessed, you can pass States as props and slot them in in exactly the same way. This is important because Views do not re-render the way you might expect from other frameworks. Whatever you pass as props is what the View gets for its entire lifecycle.
367
-
368
- ### View Helpers
369
-
370
- #### `cond($condition, whenTruthy, whenFalsy)`
371
-
372
- The `cond` helper does conditional rendering. When `$condition` is truthy, the second argument is rendered. When `$condition` is falsy the third argument is rendered. Either case can be left null or undefined if you don't want to render something for that condition.
373
-
374
- ```jsx
375
- function ConditionalListView({ $show }) {
376
- return (
377
- <div>
378
- {cond(
379
- $show,
380
-
381
- // Visible when truthy
382
- <ul>
383
- <ListItemView label="Squirrel" />
384
- <ListItemView label="Chipmunk" />
385
- <ListItemView label="Groundhog" />
386
- </ul>,
387
-
388
- // Visible when falsy
389
- <span>List is hidden</span>,
390
- )}
391
- </div>
392
- );
393
- }
394
- ```
395
-
396
- #### `repeat($items, keyFn, renderFn)`
397
-
398
- The `repeat` helper repeats a render function for each item in a list. The `keyFn` takes an item's value and returns a number, string or Symbol that uniquely identifies that list item. If `$items` changes or gets reordered, all rendered items with matching keys will be reused, those no longer in the list will be removed and those that didn't previously have a matching key are created.
399
-
400
- ```jsx
401
- function RepeatedListView() {
402
- const $items = Dolla.toState(["Squirrel", "Chipmunk", "Groundhog"]);
403
-
404
- return (
405
- <ul>
406
- {repeat(
407
- $items,
408
- (item) => item, // Using the string itself as the key
409
- ($item, $index, ctx) => {
410
- return <ListItemView label={$item} />;
411
- },
412
- )}
413
- </ul>
414
- );
415
- }
416
- ```
417
-
418
- #### `portal(content, parentNode)`
419
-
420
- The `portal` helper displays DOM elements from a view as children of a parent element elsewhere in the document. Portals are typically used to display modals and other content that needs to appear at the top level of a document.
421
-
422
- ```jsx
423
- function PortalView() {
424
- const content = (
425
- <div class="modal">
426
- <p>This is a modal.</p>
427
- </div>
428
- );
429
-
430
- // Content will be appended to `document.body` while this view is connected.
431
- return portal(document.body, content);
432
- }
433
- ```
434
-
435
- ### View Context
436
-
437
- A view function takes a context object as its second argument. The context provides a set of functions you can use to respond to lifecycle events, observe dynamic data, print debug messages and display child elements among other things.
438
-
439
- #### Printing Debug Messages
440
-
441
- ```jsx
442
- function ExampleView(props, ctx) {
443
- // Set the name of this view's context. Console messages are prefixed with name.
444
- ctx.name = "CustomName";
445
-
446
- // Print messages to the console. These are suppressed by default in the app's "production" mode.
447
- // You can also change which of these are printed and filter messages from certain contexts in the `createApp` options object.
448
- ctx.info("Verbose debugging info that might be useful to know");
449
- ctx.log("Standard messages");
450
- ctx.warn("Something bad might be happening");
451
- ctx.error("Uh oh!");
452
-
453
- // If you encounter a bad enough situation, you can halt and disconnect the entire app.
454
- ctx.crash(new Error("BOOM"));
455
-
456
- return <h1>Hello World!</h1>;
457
- }
458
- ```
459
-
460
- #### Lifecycle Events
461
-
462
- ```jsx
463
- function ExampleView(props, ctx) {
464
- ctx.beforeConnect(() => {
465
- // Do something before this view's DOM nodes are created.
466
- });
467
-
468
- ctx.onConnected(() => {
469
- // Do something immediately after this view is connected to the DOM.
470
- });
471
-
472
- ctx.beforeDisconnect(() => {
473
- // Do something before removing this view from the DOM.
474
- });
475
-
476
- ctx.onDisconnected(() => {
477
- // Do some cleanup after this view is disconnected from the DOM.
478
- });
479
-
480
- return <h1>Hello World!</h1>;
481
- }
482
- ```
483
-
484
- #### Displaying Children
485
-
486
- The context object has an `outlet` function that can be used to display children at a location of your choosing.
487
-
488
- ```js
489
- function LayoutView(props, ctx) {
490
- return (
491
- <div className="layout">
492
- <OtherView />
493
- <div className="content">{ctx.outlet()}</div>
494
- </div>
495
- );
496
- }
497
-
498
- function ExampleView() {
499
- // <h1> and <p> are displayed inside LayoutView's outlet.
500
- return (
501
- <LayoutView>
502
- <h1>Hello</h1>
503
- <p>This is inside the box.</p>
504
- </LayoutView>
505
- );
506
- }
507
- ```
508
-
509
- #### Observing States
510
-
511
- The `observe` function starts observing when the view is connected and stops when disconnected. This takes care of cleaning up observers so you don't have to worry about memory leaks.
512
-
513
- ```jsx
514
- function ExampleView(props, ctx) {
515
- const { $someValue } = ctx.getStore(SomeStore);
516
-
517
- ctx.observe($someValue, (value) => {
518
- ctx.log("someValue is now", value);
519
- });
520
-
521
- return <h1>Hello World!</h1>;
522
- }
523
- ```
524
-
525
- #### Routing
526
-
527
- Dolla makes heavy use of client-side routing. You can define as many routes as you have views, and the URL
528
- will determine which one the app shows at any given time. By building an app around routes, lots of things one expects
529
- from a web app will just work; back and forward buttons, sharable URLs, bookmarks, etc.
530
-
531
- Routes are matched by highest specificity regardless of the order they were registered.
532
- This avoids some confusing situations that come up with order-based routers like that of `express`.
533
- On the other hand, order-based routers can support regular expressions as patterns which Dolla's router cannot.
534
-
535
- #### Route Patterns
536
-
537
- Routes are defined with strings called patterns. A pattern defines the shape the URL path must match, with special
538
- placeholders for variables that appear within the route. Values matched by those placeholders are parsed out and exposed
539
- to your code (`router` store, `$params` readable). Below are some examples of patterns and how they work.
540
-
541
- - Static: `/this/is/static` has no params and will match only when the route is exactly `/this/is/static`.
542
- - Numeric params: `/users/{#id}/edit` has the named param `{#id}` which matches numbers only, such as `123` or `52`. The
543
- resulting value will be parsed as a number.
544
- - Generic params: `/users/{name}` has the named param `{name}` which matches anything in that position in the path. The
545
- resulting value will be a string.
546
- - Wildcard: `/users/*` will match anything beginning with `/users` and store everything after that in params
547
- as `wildcard`. `*` is valid only at the end of a route.
548
-
549
- Now, here are some route examples in the context of an app:
550
-
551
- ```js
552
- import Dolla from "@manyducks.co/dolla";
553
- import { PersonDetails, ThingIndex, ThingDetails, ThingEdit, ThingDelete } from "./views.js";
554
-
555
- Dolla.router.setup({
556
- routes: [
557
- { path: "/people/{name}", view: PersonDetails },
558
- {
559
- // A `null` component with subroutes acts as a namespace for those subroutes.
560
- // Passing a view instead of `null` results in subroutes being rendered inside that view wherever `ctx.outlet()` is called.
561
- path: "/things",
562
- view: null,
563
- routes: [
564
- { path: "/", view: ThingIndex }, // matches `/things`
565
- { path: "/{#id}", view: ThingDetails }, // matches `/things/{#id}`
566
- { path: "/{#id}/edit", view: ThingEdit }, // matches `/things/{#id}/edit`
567
- { path: "/{#id}/delete", view: ThingDelete }, // matches `/things/{#id}/delete`
568
- ],
569
- },
570
- ],
571
65
  });
572
- ```
573
-
574
- As you may have inferred from the code above, when the URL matches a pattern the corresponding view is displayed. If we
575
- visit `/people/john`, we will see the `PersonDetails` view and the params will be `{ name: "john" }`. Params can be
576
- accessed anywhere through `Dolla.router`.
577
-
578
- ```js
579
- function PersonDetails(props, ctx) {
580
- // Info about the current route is exported as a set of Readables. Query params are also Writable through $$query:
581
- const { $path, $pattern, $params, $query } = Dolla.router;
582
-
583
- Dolla.router.back(); // Step back in the history to the previous route, if any.
584
- Dolla.router.back(2); // Hit the back button twice.
585
-
586
- Dolla.router.forward(); // Step forward in the history to the next route, if any.
587
- Dolla.router.forward(4); // Hit the forward button 4 times.
588
-
589
- Dolla.router.go("/things/152"); // Navigate to another path within the same app.
590
- Dolla.router.go("https://www.example.com/another/site"); // Navigate to another domain entirely.
591
-
592
- // Three ways to confirm with the user that they wish to navigate before actually doing it.
593
- Dolla.router.go("/another/page", { prompt: true });
594
- Dolla.router.go("/another/page", { prompt: "Are you sure you want to leave and go to /another/page?" });
595
- Dolla.router.go("/another/page", { prompt: PromptView });
596
-
597
- // Get the live value of `{name}` from the current path.
598
- const $name = Dolla.derive([$params], (p) => p.name);
599
66
 
600
- // Render it into a <p> tag. The name portion will update if the URL changes.
601
- return <p>The person is: {$name}</p>;
602
- }
603
- ```
604
-
605
- ## HTTP Client
606
-
607
- ```js
608
- // Middleware!
609
- Dolla.http.use((request, next) => {
610
- // Add auth header for all requests going to the API.
611
- if (request.url.pathname.startsWith("/api")) {
612
- request.headers.set("authorization", `Bearer ${authToken}`);
613
- }
614
-
615
- const response = await next();
616
-
617
- // Could do something with the response here.
618
-
619
- return response;
620
- });
621
-
622
- const exampleResponse = await Dolla.http.get("/api/example");
623
-
624
- // Body is already parsed from JSON into an object.
625
- exampleResponse.body.someValue;
67
+ Dolla.mount(document.body, Counter);
626
68
  ```
627
69
 
628
- ## Localization
629
-
630
- ```js
631
- import Dolla, { html, t } from "@manyducks.co/dolla";
632
-
633
- function Counter(props, ctx) {
634
- const [$count, setCount] = Dolla.createState(0);
70
+ > TODO: Show small examples for routing and stores.
635
71
 
636
- function increment() {
637
- setCount((count) => count + 1);
638
- }
639
-
640
- return html`
641
- <div>
642
- <p>Clicks: ${$count}</p>
643
- <button onclick=${increment}>${t("buttonLabel")}</button>
644
- </div>
645
- `;
646
- }
647
-
648
- Dolla.i18n.setup({
649
- locale: "en",
650
- translations: [
651
- { locale: "en", strings: { buttonLabel: "Click here to increment" } },
652
- { locale: "ja", strings: { buttonLabel: "γ“γ“γ«ζŠΌγ—γ¦ε’—εŠ γ™γ‚‹" } },
653
- ],
654
- });
655
-
656
- Dolla.mount(document.body, Counter);
657
- ```
72
+ For more detail [check out the Docs](./docs/index.md).
658
73
 
659
74
  ---
660
75
 
661
- [πŸ¦†](https://www.manyducks.co)
76
+ [πŸ¦† That's a lot of ducks.](https://www.manyducks.co)