@base-framework/base 3.9.17 → 3.9.18

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
@@ -1,763 +1,791 @@
1
- # Base Framework
2
-
3
- ## Framework Overview
4
-
5
- Our goal with Base is to solve many client-side and Server-side rendering issues. Base focuses on reusability, scalability, and performance.
6
-
7
- Base has a core that supports adding and removing events, custom events, data-tracking, element class and attribute modifying, object and type utils, etc.
8
-
9
- The framework is modular and has additional modules to help with ajax, HTML, layouts, data, data-binding, states, dates, routing, components, atoms, etc.
10
-
11
- You can learn more about how to use Base in the wiki documentation. [Base Wiki](https://github.com/chrisdurfee/base/wiki)
12
-
13
- ## AI Quickstart
14
- - For contributors using GitHub Copilot, start with `.github/copilot-instructions.md` (concise in-repo rules) and `copilot.md` (detailed guide).
15
- - Key patterns Copilot should follow here:
16
- - Author layouts as JS objects: `{ tag:'div', class:'name', children:[...] }` (`nest` is shorthand). Use `text` for text nodes; `html|innerHTML` for raw HTML.
17
- - Events on elements receive `(event, parentComponent)`: `{ click(e, parent) { parent.doThing(); } }`.
18
- - Watchers: embed `[[path]]` in strings or arrays (auto-converted to `watch` directive). Example: `{ class: 'counter-[[count]]' }` or `{ value: ['[[path]]', data] }`.
19
- - Components extend `Component`, implement `render()`, declare state in `setupStates()` and data in `setData()`; render via `Builder.render(...)`.
20
- - Directives live in `modules/layout/directives/core/default-directives.js` (e.g., `bind`, `watch`, `map`, `for`, `route`, `switch`, `useData`, `useState`, `onCreated`, `onDestroyed`).
21
- - Routing: `router.data.path` is reactive; navigate with `router.navigate(uri, data?, replace?)`; `NavLink` watches `router.data.path`.
22
-
23
- ## Base Converter
24
-
25
- There is a GPT created with ChatGPT that can convert code from other frameworks to Base. The GPT is new so it still has some issues but it is a good start. [Base Converter](https://chatgpt.com/g/g-uNL6KKeCo-base-converter/)
26
-
27
-
28
- ## Layouts
29
-
30
- Base uses components to render an application. Base creates and renders components using native JavaScript. Layouts are scaffolded using JavaScript object literals. Because the layouts are rendered client-side or server-side using native JavaScript, the framework does not require a compiling or build process.
31
-
32
- Layouts are reuable and can be used in multiple components and pages. Layouts can be nested and composed to create complex layouts.
33
-
34
- ```javascript
35
-
36
- // Layouts use normal JavaScript object literals to create the layout.
37
- { class: 'name' } === <div class="name"></div>
38
-
39
- // Input example
40
- { tag: 'input', type: 'text', value: 'name' } === <input type="text" value="name" />
41
-
42
- // Nested layout example
43
- { class: 'name', nest: [ { class: 'child' } ] } === <div class="name"><div class="child"></div></div>
44
-
45
- ```
46
-
47
- Base use atoms and components to create reusable layouts.
48
-
49
- Learn more: [Base Layouts](https://github.com/chrisdurfee/base/wiki/Layout)
50
-
51
-
52
- ## Components and Atoms
53
-
54
- Components are encapsulated layouts that contain the presentation and functionality. They are reusable and extensible, helping to reduce redundant code through abstract types.
55
-
56
- ```javascript
57
- import { Component } from '@base-framework/base';
58
-
59
- /**
60
- * Page
61
- *
62
- * This will create a page component.
63
- *
64
- * @class Page
65
- * @extends {Component}
66
- */
67
- export class Page extends Component
68
- {
69
- render()
70
- {
71
- return {
72
- class: 'page'
73
- };
74
- }
75
- }
76
- ```
77
-
78
- Components have lifecycle methods for actions during creation, setup, and destruction.
79
-
80
- learn more: [Base Components](https://github.com/chrisdurfee/base/wiki/Components)
81
-
82
- ## Atoms
83
- Atoms are the building blocks for reusable layouts, allowing common design patterns and elements to be shared between multiple components and other atoms.
84
-
85
- ## Atom Types
86
- Atoms can be instantiated using various methodologies:
87
-
88
- ### Function Atoms
89
- These atoms are instantiated with either standard functions or arrow functions, equipped with a props object to transfer properties to the atoms.
90
-
91
- ```typescript
92
- const Div = (props, children) => ({
93
- ...props,
94
- children
95
- });
96
- ```
97
-
98
- ### Atom Callbacks
99
- Atoms may be created using the Atom function, which accepts a callback function as its sole parameter. The callback function is passed a props object and children array and returns an object containing the atom's layout.
100
-
101
- ```typescript
102
- import { Atom } from '@base-framework/base';
103
-
104
- const Button = Atom((props, children) => ({
105
- tag: 'button',
106
- ...props,
107
- children
108
- }));
109
- ```
110
-
111
- #### Atom Nesting
112
- Atoms should use composition to nest other atoms. This is achieved by passing the children array to the atoms args.
113
-
114
- ```typescript
115
- import { Atom } from '@base-framework/base';
116
-
117
- const SecondaryButton = Atom((props, children) => (Button({
118
- ...props,
119
- class: 'secondary-btn',
120
- children
121
- }));
122
- ```
123
-
124
- ## Adding Event Listeners
125
- Event listener callbacks within atoms accept two parameters: the originating event object and the "parent" component object in which the atom resides.
126
-
127
- ## Utilization of Atoms
128
- To leverage an atom, invoke its function and pass the requisite values via a props and children.
129
-
130
- ```javascript
131
- const Div = (props, children) => ({
132
- ...props,
133
- children
134
- });
135
-
136
- Div({ class: 'text' }, 'text');
137
- ```
138
-
139
- Atoms created with the Base Atom callback function support passing optional params including props or children to the atom. The props object should always be first but if the atom does not require props, the children array or string can be passed as the first argument.
140
-
141
- ```javascript
142
- import { Atom } from '@base-framework/base';
143
-
144
- const Div = Atom((props, children) => ({
145
- ...props,
146
- tag: 'div',
147
- children
148
- }));
149
-
150
- // props only
151
- Div({class: 'text'});
152
-
153
- // text child only
154
- Div('test');
155
-
156
- // array child only
157
- Div([
158
- Div('test')
159
- ]);
160
-
161
- // props and text child
162
- Div({class: 'text'}, 'test');
163
-
164
- // props and array children
165
- Div({class: 'text'}, [
166
- Div('test'),
167
- Div('test')
168
- ]);
169
- ```
170
-
171
- Learn more: [Base Atoms](https://github.com/chrisdurfee/base/wiki/Atoms)
172
-
173
- Base has a package that has already created most of the HTML Atoms needed for rendering layouts. This package can be installed via npm.
174
-
175
- ```bash
176
- npm install @base-framework/atoms
177
- ```
178
-
179
- Here is the repository for the atoms package: [Base Atoms](https://github.com/chrisdurfee/atoms). Like Base, the atoms package is open-source and free to use.
180
-
181
- ## Organisms
182
-
183
- Base has a package that has some special organisms that can make building complex layouts quicker. This package can be installed via npm.
184
-
185
- ```bash
186
- npm install @base-framework/organisms
187
- ```
188
-
189
- Here is the repository for the organisms package: [Base Organisms](https://github.com/chrisdurfee/organisms). The organisms package is open-source and free to use.
190
-
191
-
192
- ## Element Directives
193
-
194
- Elements created by Base have access to custom directives, enabling more functionalities than standard HTML elements. These include caching, adding states, binding and watching data, re-rendering contents, declarative routing and switching, array mapping and binding, event listeners, and more.
195
-
196
- Learn more: [Base Element Directives](https://github.com/chrisdurfee/base/wiki/Directives)
197
-
198
-
199
- ## Data Binding, Watching, and Linking
200
-
201
- Base supports "bindables" for creating and using data, supporting both shallow and deep nested data. Bindables can be one-way or two-way bindings.
202
-
203
- Types of bindables include:
204
- - **Data**: A generic object with complex, deep nested data.
205
- - **SimpleData**: A shallow data object.
206
- - **Models**: Child of Data, with default attributes and server resource connectivity.
207
-
208
- ```javascript
209
- import { Atom } from '@base-framework/base';
210
-
211
- /**
212
- * If a parent component has a Data object with a "count" property.
213
- *
214
- * This will create an input with the value bound of the "count"
215
- * property. This bind is Bi-directional binding to the
216
- * "count" property of the parent component's Data object.
217
- */
218
- Input({ bind: 'count' })
219
-
220
- /**
221
- * Elements can watch for changes in data and re-render when the data changes.
222
- */
223
- Div({class: '[[className]]'})
224
-
225
- // Multi-attribute watching
226
- A({href: '/account/user/[[userId]]'}, '[[userName]] - [[age]]')
227
-
228
- // Multi-data watcher
229
- Div({class: ['[[propName]] [[otherPropName]]', [data, otherData]]})
230
- ```
231
-
232
- Base Data objects are bindable. There are a few types of data objects:
233
-
234
- ```javascript
235
- import { Data, SimpleData, Model } from '@base-framework/base';
236
-
237
- /**
238
- * Data object
239
- *
240
- * This can store deep nested data including arrays and objects.
241
- */
242
- const data = new Data({
243
- name: {
244
- first: 'Bruce',
245
- last: 'Wayne'
246
- },
247
- address: {
248
- street: '123 Gotham St',
249
- city: 'Gotham',
250
- state: 'NY'
251
- },
252
- phones: ['555-555-5555', '555-555-5556'],
253
- age: 21
254
- });
255
-
256
- /**
257
- * SimpleData object
258
- *
259
- * This can store shallow data.
260
- */
261
- const simpleData = new SimpleData({ name: 'batman' });
262
-
263
- /**
264
- * The data objects are proxies and can be used like objects.
265
- */
266
-
267
- // Retrieval
268
- let prop = data.name.first;
269
- // or
270
- let name = data.get('name.first');
271
-
272
- // Assignment
273
- simpleData.name = 'batman';
274
- // or
275
- data.set('name', 'batman');
276
-
277
- // Pushing to an array
278
- data.push('phones', '555-555-5557');
279
-
280
- // changing an item in an array
281
- data.set('phones[0]', '555-555-5558');
282
-
283
- // Batch updates using an object
284
- data.set({
285
- name: 'batman',
286
- age: 21
287
- });
288
-
289
- // Deletion
290
- data.delete('name');
291
-
292
- /**
293
- * Model object
294
- *
295
- * This can store default attributes and server resource
296
- * connectivity.
297
- *
298
- * The model's service already has methods for adding,
299
- * updating, deleting, and fetching data from the
300
- * server.
301
- */
302
- const UserModel = Model.extend({
303
- defaults: {
304
- name: {
305
- first: 'Bruce',
306
- last: 'Wayne'
307
- },
308
- address: {
309
- street: '123 Gotham St',
310
- city: 'Gotham',
311
- state: 'NY'
312
- },
313
- age: 21
314
- },
315
- url: '/api/user',
316
-
317
- xhr: {
318
-
319
- /**
320
- * Custom methods can be added to the model service.
321
- *
322
- * @param {object} instanceParams
323
- * @param {function} callback
324
- * @returns {object|bool} The xhr object
325
- */
326
- customMethod(instanceParams, callback)
327
- {
328
- if (!this.isValid())
329
- {
330
- return false;
331
- }
332
-
333
- let params = 'op=customParam' +
334
- '&' + this.setupObjectData();
335
-
336
- // this will be added to the base url of the model
337
- const URL = "/custom/url";
338
- return this._post(URL, params, instanceParams, callBack);
339
- }
340
- }
341
- });
342
-
343
- const model = new UserModel();
344
-
345
- /**
346
- * The model can be used to fetch data from the server.
347
- *
348
- * The response will be set to the model.
349
- */
350
- model.xhr.get({}, (response) => {
351
-
352
- });
353
-
354
- // post
355
- model.xhr.add({}, (response) => {
356
-
357
- });
358
-
359
- // put
360
- model.xhr.update({}, (response) => {
361
-
362
- });
363
-
364
- // delete
365
- model.xhr.delete({}, (response) => {
366
-
367
- });
368
-
369
- ```
370
- The component also supports the state property. This is another bindable type extended from the SimpleData object so it only supports shallow data.
371
-
372
- ```javascript
373
-
374
- /**
375
- * This will return the state propreties and values that will be
376
- * use to create the "state" object.
377
- *
378
- * @returns {object}
379
- */
380
- setupStates()
381
- {
382
- return {
383
- count: 0,
384
- loading: false
385
- };
386
- }
387
-
388
- ```
389
-
390
- Each component can have one "data" property that can be set using the "setData" method.
391
-
392
- If a component has been created using the "route" or "switch" directive, it will receive a "route" property that will contain the route data which is also bindable.
393
-
394
- The data objects push changes to the elements that are bound to the data. This allows for re-rendering of the elements when the data changes.
395
-
396
- Here is an example of how to use data binding in a component:
397
-
398
- ```javascript
399
- import { Div } from '@base-framework/atoms';
400
- import { Component } from '@base-framework/base';
401
-
402
- /**
403
- * Timer
404
- *
405
- * This will create a timer component that uses state watching.
406
- *
407
- * @class
408
- */
409
- export class Timer extends Component
410
- {
411
- /**
412
- * This will render the timer.
413
- *
414
- * @returns {object}
415
- */
416
- render()
417
- {
418
- // This will rerender the div text content when the count state changes.
419
- return Div('[[count]]');
420
- }
421
-
422
- /**
423
- * This will setup the states.
424
- *
425
- * @returns {object}
426
- */
427
- setupStates()
428
- {
429
- return { count: 0 };
430
- }
431
-
432
- afterSetup()
433
- {
434
- const ONE_SECOND = 1000;
435
- window.setInterval(() => this.state.increment('count'), ONE_SECOND);
436
- }
437
- }
438
- ```
439
-
440
- Learn more: [Base Data Binding](https://github.com/chrisdurfee/base/wiki/Directives#binding-to-data)
441
-
442
-
443
- ## Performance
444
-
445
- Components are static by default, rendering only once per instance. They become dynamic when bound to bindable data sources, allowing for content re-rendering, value changes, function calls, and class additions on data change.
446
-
447
-
448
- ## Getting Started
449
-
450
- To begin using Base framework in a client-side or server-side rendered project, follow these steps:
451
-
452
- 1. **Clone the repository**:
453
- ```bash
454
- git clone https://github.com/yourrepository/base-framework.git
455
- ```
456
-
457
- 2. Navigate to the project directory:
458
- ```bash
459
- cd base-framework
460
- ```
461
- 3. Install dependencies (ensure Node.js is installed):
462
- ```bash
463
- npm install @base-framework/base
464
- ```
465
-
466
- 4. Import the framework into your project:
467
- ```javascript
468
- import { base } from '@base-framework/base';
469
- ```
470
-
471
- ### Modular (subpath) imports
472
-
473
- The package root (`@base-framework/base`) ships the full framework as a single
474
- file. For smaller bundles, you can import only the part you need from a
475
- subpath. Each subpath is code-split and tree-shakeable, so apps only download
476
- what they use:
477
-
478
- ```javascript
479
- import { Ajax } from '@base-framework/base/ajax'; // ~8 KB
480
- import { Data, SimpleData, Model } from '@base-framework/base/data';
481
- import { DateTime } from '@base-framework/base/date'; // ~6 KB
482
- import { Html } from '@base-framework/base/html';
483
- import { Store, State } from '@base-framework/base/state';
484
- import { Component, Unit, Jot, Pod, Atom, Builder, Import } from '@base-framework/base/component';
485
- import { router, NavLink } from '@base-framework/base/router';
486
- ```
487
-
488
- The `component` and `router` subpaths register the default directives
489
- (`bind`, `watch`, `map`, `for`, `route`, `switch`, ...) automatically, exactly
490
- like the package root does, so reactive layouts work the same way.
491
-
492
- ## Usage
493
-
494
- Create a new component:
495
-
496
- ```javascript
497
- import { base, Component } from '@base-framework/base';
498
-
499
- /**
500
- * Page
501
- *
502
- * This will create a page component.
503
- *
504
- * @class Page
505
- * @extends {Component}
506
- */
507
- export class Page extends Component
508
- {
509
- render()
510
- {
511
- /**
512
- * This will render an empty div and assign a className
513
- * of "value".
514
- */
515
- return {
516
- class: this.key
517
- };
518
- }
519
- }
520
- ```
521
-
522
- Use the builder to create a new instance of the component:
523
-
524
- ```javascript
525
- import { Builder } from '@base-framework/base';
526
- import { Page } from './components/page.js';
527
-
528
- /**
529
- * This will create a new instance of the Page component.
530
- */
531
- const page = new Page(
532
- {
533
- /**
534
- * Props can be passed to the component and accessed by their key names.
535
- *
536
- * You can name the props anything you want, but it is recommended to
537
- * use camel case and avoid using reserved keywords.
538
- */
539
- key: 'value'
540
- });
541
-
542
- // The props passed can now be accessed by the component class.
543
- ```
544
-
545
- Render the component to the DOM:
546
-
547
- ```javascript
548
- import { Builder } from '@base-framework/base';
549
- import { Page } from './components/page.js';
550
-
551
- /**
552
- * This will create a new instance of the Page component.
553
- */
554
- const page = new Page();
555
-
556
- // Render the component to the DOM.
557
- const container = document.body;
558
- Builder.render(page, container);
559
- ```
560
-
561
- To allow more reusability, you create static elements as atoms and organisms. Atoms and organisms should use composition. These can be used in multiple components and layouts.
562
-
563
- ```javascript
564
- import { Atom } from '@base-framework/base';
565
-
566
- const Button = Atom((props, children) => ({
567
- tag: 'button',
568
- ...props,
569
- children
570
- }));
571
-
572
- const SecondaryButton = Atom((props, children) => (Button({
573
- ...props,
574
- class: 'secondary-btn',
575
- children
576
- }));
577
-
578
- ```
579
-
580
- Atoms can be added to components and other atoms:
581
-
582
- ```javascript
583
-
584
- import { Component } from '@base-framework/base';
585
- import { Div } from '@base-framework/atoms';
586
- import { SecondaryButton } from './atoms/button.js';
587
-
588
- export class Page extends Component
589
- {
590
- render()
591
- {
592
- return Div([
593
- SecondaryButton({
594
- /**
595
- * This will add a click event listener to the button.
596
- *
597
- * @param {Event} event The event object
598
- * @param {Component} parent The parent component object
599
- * @returns {void}
600
- */
601
- click(event, parent) =>
602
- {
603
- // Code to access the parent component
604
- }
605
- })
606
- ]);
607
- }
608
- }
609
- ```
610
-
611
- ## Code Splitting
612
-
613
- Base supports code splitting, allowing you to load components and modules on demand. This can help reduce the initial load time of your application. You can import atoms or components on demand using the Import module.
614
-
615
- ```javascript
616
- import { Import } from "@base-framework/base";
617
- import { A, Div, H1, Header } from "@base-framework/atoms";
618
-
619
- // Without using Vite
620
-
621
- /**
622
- * This will create an import buttons.
623
- *
624
- * @returns {object}
625
- */
626
- const ImportButtons = () => (
627
- Div([
628
- Header([
629
- H1('Aside')
630
- ]),
631
- Div({ class: 'card' }, [
632
-
633
- // Importing the buttons module on demand
634
- Import('../../../../../../components/atoms/import-buttons.js')
635
- ])
636
- ])
637
- );
638
-
639
- // With Vite
640
-
641
- /**
642
- * This will create an import buttons.
643
- *
644
- * @returns {object}
645
- */
646
- const ImportButtons = () => (
647
- Div([
648
- Header([
649
- H1('Aside')
650
- ]),
651
- Div({ class: 'card' }, [
652
-
653
- /**
654
- * This will import the buttons module on demand. The import function
655
- * needs to be used to add the module to the vite build.
656
- */
657
- Import({ src: () => import('../../../../../../components/atoms/import-buttons.js') })
658
- ])
659
- ])
660
- );
661
- ```
662
-
663
- ## Example Todo App
664
-
665
- Here is an example of a todo app using Base:
666
-
667
- ```javascript
668
- import { Button, Div, Form, H1, Input, Li, Ul } from "@base-framework/atoms";
669
- import { Builder, Data } from "@base-framework/base";
670
-
671
- /**
672
- * This will create a to-do app.
673
- *
674
- * @returns {object}
675
- */
676
- export function ToDoApp()
677
- {
678
- /**
679
- * This will set up the data store for the to-do app.
680
- */
681
- const data = new Data({ items: [] });
682
-
683
- /**
684
- * This will handle the form submission for adding a new to-do item.
685
- *
686
- * @param {object} event
687
- */
688
- const handleSubmit = (event) =>
689
- {
690
- event.preventDefault();
691
- const form = event.target;
692
- const input = form.querySelector('input');
693
-
694
- // add the new to-do item to the array of items
695
- data.push('items', input.value);
696
- input.value = '';
697
- };
698
-
699
- /**
700
- * This will handle removing a to-do item from the list.
701
- *
702
- * @param {number} index
703
- * @returns {boolean}
704
- */
705
- const handleRemove = (index) => data.splice('items', index);
706
-
707
- return Div([
708
- H1('To-Do App'),
709
- Form({ submit: handleSubmit }, [
710
- Input({ placeholder: 'Add a new item' }),
711
- Button({ type: 'submit' }, 'Add')
712
- ]),
713
- Ul({
714
- for: [data, 'items', (item, index) => Li([
715
- Span(item),
716
- Button({ click: () => handleRemove(index) }, 'Remove')
717
- ])]
718
- })
719
- ]);
720
- }
721
-
722
- /**
723
- * This will render the to-do app to the body of the document.
724
- */
725
- Builder.render(ToDoApp(), document.body);
726
- ```
727
-
728
-
729
- ## Example Projects Using Base
730
-
731
- [Base Platform Example](https://github.com/chrisdurfee/next-app-shell)
732
-
733
- [Base App Example](https://github.com/chrisdurfee/base-update)
734
-
735
- [Base Website Example](https://github.com/chrisdurfee/life)
736
-
737
- [Base Server Example](https://github.com/chrisdurfee/base-server)
738
-
739
- [Base Game Example](https://github.com/chrisdurfee/multisplode)
740
-
741
-
742
- ## Contributing
743
-
744
- Contributions to Base are welcome. Follow these steps to contribute:
745
-
746
- - Fork the repository.
747
- - Create a new branch for your feature or bug fix.
748
- - Commit your changes with clear, descriptive messages.
749
- - Push your branch and submit a pull request.
750
- - Before contributing, read our CONTRIBUTING.md for coding standards and community guidelines.
751
-
752
- ## License
753
-
754
- Base is licensed under the MIT License. See the LICENSE file for details.
755
-
756
- ## Contact
757
-
758
- For questions, suggestions, or issues, contact us:
759
-
760
- - Email:
761
- - GitHub Issues: github.com/chrisdurfee/base/issues
762
- - Community Chat: Discord coming soon
763
- - Follow us on Social Media:
1
+ # Base Framework
2
+
3
+ ## Framework Overview
4
+
5
+ Our goal with Base is to solve many client-side and Server-side rendering issues. Base focuses on reusability, scalability, and performance.
6
+
7
+ Base has a core that supports adding and removing events, custom events, data-tracking, element class and attribute modifying, object and type utils, etc.
8
+
9
+ The framework is modular and has additional modules to help with ajax, HTML, layouts, data, data-binding, states, dates, routing, components, atoms, etc.
10
+
11
+ You can learn more about how to use Base in the wiki documentation. [Base Wiki](https://github.com/chrisdurfee/base/wiki)
12
+
13
+ ## AI Quickstart
14
+ - For contributors using GitHub Copilot, start with `.github/copilot-instructions.md` (concise in-repo rules) and `copilot.md` (detailed guide).
15
+ - Key patterns Copilot should follow here:
16
+ - Author layouts as JS objects: `{ tag:'div', class:'name', children:[...] }` (`nest` is shorthand). Use `text` for text nodes; `html|innerHTML` for raw HTML.
17
+ - Events on elements receive `(event, parentComponent)`: `{ click(e, parent) { parent.doThing(); } }`.
18
+ - Watchers: embed `[[path]]` in strings or arrays (auto-converted to `watch` directive). Example: `{ class: 'counter-[[count]]' }` or `{ value: ['[[path]]', data] }`.
19
+ - Components extend `Component`, implement `render()`, declare state in `setupStates()` and data in `setData()`; render via `Builder.render(...)`.
20
+ - Directives live in `modules/layout/directives/core/default-directives.js` (e.g., `bind`, `watch`, `map`, `for`, `route`, `switch`, `useData`, `useState`, `onCreated`, `onDestroyed`).
21
+ - Routing: `router.data.path` is reactive; navigate with `router.navigate(uri, data?, replace?)`; `NavLink` watches `router.data.path`.
22
+
23
+ ## Base Converter
24
+
25
+ There is a GPT created with ChatGPT that can convert code from other frameworks to Base. The GPT is new so it still has some issues but it is a good start. [Base Converter](https://chatgpt.com/g/g-uNL6KKeCo-base-converter/)
26
+
27
+
28
+ ## Layouts
29
+
30
+ Base uses components to render an application. Base creates and renders components using native JavaScript. Layouts are scaffolded using JavaScript object literals. Because the layouts are rendered client-side or server-side using native JavaScript, the framework does not require a compiling or build process.
31
+
32
+ Layouts are reuable and can be used in multiple components and pages. Layouts can be nested and composed to create complex layouts.
33
+
34
+ ```javascript
35
+
36
+ // Layouts use normal JavaScript object literals to create the layout.
37
+ { class: 'name' } === <div class="name"></div>
38
+
39
+ // Input example
40
+ { tag: 'input', type: 'text', value: 'name' } === <input type="text" value="name" />
41
+
42
+ // Nested layout example
43
+ { class: 'name', nest: [ { class: 'child' } ] } === <div class="name"><div class="child"></div></div>
44
+
45
+ ```
46
+
47
+ Base use atoms and components to create reusable layouts.
48
+
49
+ Learn more: [Base Layouts](https://github.com/chrisdurfee/base/wiki/Layout)
50
+
51
+
52
+ ## Components and Atoms
53
+
54
+ Components are encapsulated layouts that contain the presentation and functionality. They are reusable and extensible, helping to reduce redundant code through abstract types.
55
+
56
+ ```javascript
57
+ import { Component } from '@base-framework/base';
58
+
59
+ /**
60
+ * Page
61
+ *
62
+ * This will create a page component.
63
+ *
64
+ * @class Page
65
+ * @extends {Component}
66
+ */
67
+ export class Page extends Component
68
+ {
69
+ render()
70
+ {
71
+ return {
72
+ class: 'page'
73
+ };
74
+ }
75
+ }
76
+ ```
77
+
78
+ Components have lifecycle methods for actions during creation, setup, and destruction.
79
+
80
+ learn more: [Base Components](https://github.com/chrisdurfee/base/wiki/Components)
81
+
82
+ ## Atoms
83
+ Atoms are the building blocks for reusable layouts, allowing common design patterns and elements to be shared between multiple components and other atoms.
84
+
85
+ ## Atom Types
86
+ Atoms can be instantiated using various methodologies:
87
+
88
+ ### Function Atoms
89
+ These atoms are instantiated with either standard functions or arrow functions, equipped with a props object to transfer properties to the atoms.
90
+
91
+ ```typescript
92
+ const Div = (props, children) => ({
93
+ ...props,
94
+ children
95
+ });
96
+ ```
97
+
98
+ ### Atom Callbacks
99
+ Atoms may be created using the Atom function, which accepts a callback function as its sole parameter. The callback function is passed a props object and children array and returns an object containing the atom's layout.
100
+
101
+ ```typescript
102
+ import { Atom } from '@base-framework/base';
103
+
104
+ const Button = Atom((props, children) => ({
105
+ tag: 'button',
106
+ ...props,
107
+ children
108
+ }));
109
+ ```
110
+
111
+ #### Atom Nesting
112
+ Atoms should use composition to nest other atoms. This is achieved by passing the children array to the atoms args.
113
+
114
+ ```typescript
115
+ import { Atom } from '@base-framework/base';
116
+
117
+ const SecondaryButton = Atom((props, children) => (Button({
118
+ ...props,
119
+ class: 'secondary-btn',
120
+ children
121
+ }));
122
+ ```
123
+
124
+ ## Adding Event Listeners
125
+ Event listener callbacks within atoms accept two parameters: the originating event object and the "parent" component object in which the atom resides.
126
+
127
+ ## Utilization of Atoms
128
+ To leverage an atom, invoke its function and pass the requisite values via a props and children.
129
+
130
+ ```javascript
131
+ const Div = (props, children) => ({
132
+ ...props,
133
+ children
134
+ });
135
+
136
+ Div({ class: 'text' }, 'text');
137
+ ```
138
+
139
+ Atoms created with the Base Atom callback function support passing optional params including props or children to the atom. The props object should always be first but if the atom does not require props, the children array or string can be passed as the first argument.
140
+
141
+ ```javascript
142
+ import { Atom } from '@base-framework/base';
143
+
144
+ const Div = Atom((props, children) => ({
145
+ ...props,
146
+ tag: 'div',
147
+ children
148
+ }));
149
+
150
+ // props only
151
+ Div({class: 'text'});
152
+
153
+ // text child only
154
+ Div('test');
155
+
156
+ // array child only
157
+ Div([
158
+ Div('test')
159
+ ]);
160
+
161
+ // props and text child
162
+ Div({class: 'text'}, 'test');
163
+
164
+ // props and array children
165
+ Div({class: 'text'}, [
166
+ Div('test'),
167
+ Div('test')
168
+ ]);
169
+ ```
170
+
171
+ Learn more: [Base Atoms](https://github.com/chrisdurfee/base/wiki/Atoms)
172
+
173
+ Base has a package that has already created most of the HTML Atoms needed for rendering layouts. This package can be installed via npm.
174
+
175
+ ```bash
176
+ npm install @base-framework/atoms
177
+ ```
178
+
179
+ Here is the repository for the atoms package: [Base Atoms](https://github.com/chrisdurfee/atoms). Like Base, the atoms package is open-source and free to use.
180
+
181
+ ## Organisms
182
+
183
+ Base has a package that has some special organisms that can make building complex layouts quicker. This package can be installed via npm.
184
+
185
+ ```bash
186
+ npm install @base-framework/organisms
187
+ ```
188
+
189
+ Here is the repository for the organisms package: [Base Organisms](https://github.com/chrisdurfee/organisms). The organisms package is open-source and free to use.
190
+
191
+
192
+ ## Element Directives
193
+
194
+ Elements created by Base have access to custom directives, enabling more functionalities than standard HTML elements. These include caching, adding states, binding and watching data, re-rendering contents, declarative routing and switching, array mapping and binding, event listeners, and more.
195
+
196
+ Learn more: [Base Element Directives](https://github.com/chrisdurfee/base/wiki/Directives)
197
+
198
+
199
+ ## Data Binding, Watching, and Linking
200
+
201
+ Base supports "bindables" for creating and using data, supporting both shallow and deep nested data. Bindables can be one-way or two-way bindings.
202
+
203
+ Types of bindables include:
204
+ - **Data**: A generic object with complex, deep nested data.
205
+ - **SimpleData**: A shallow data object.
206
+ - **Models**: Child of Data, with default attributes and server resource connectivity.
207
+
208
+ ```javascript
209
+ import { Atom } from '@base-framework/base';
210
+
211
+ /**
212
+ * If a parent component has a Data object with a "count" property.
213
+ *
214
+ * This will create an input with the value bound of the "count"
215
+ * property. This bind is Bi-directional binding to the
216
+ * "count" property of the parent component's Data object.
217
+ */
218
+ Input({ bind: 'count' })
219
+
220
+ /**
221
+ * Elements can watch for changes in data and re-render when the data changes.
222
+ */
223
+ Div({class: '[[className]]'})
224
+
225
+ // Multi-attribute watching
226
+ A({href: '/account/user/[[userId]]'}, '[[userName]] - [[age]]')
227
+
228
+ // Multi-data watcher
229
+ Div({class: ['[[propName]] [[otherPropName]]', [data, otherData]]})
230
+ ```
231
+
232
+ Base Data objects are bindable. There are a few types of data objects:
233
+
234
+ ```javascript
235
+ import { Data, SimpleData, Model } from '@base-framework/base';
236
+
237
+ /**
238
+ * Data object
239
+ *
240
+ * This can store deep nested data including arrays and objects.
241
+ */
242
+ const data = new Data({
243
+ name: {
244
+ first: 'Bruce',
245
+ last: 'Wayne'
246
+ },
247
+ address: {
248
+ street: '123 Gotham St',
249
+ city: 'Gotham',
250
+ state: 'NY'
251
+ },
252
+ phones: ['555-555-5555', '555-555-5556'],
253
+ age: 21
254
+ });
255
+
256
+ /**
257
+ * SimpleData object
258
+ *
259
+ * This can store shallow data.
260
+ */
261
+ const simpleData = new SimpleData({ name: 'batman' });
262
+
263
+ /**
264
+ * The data objects are proxies and can be used like objects.
265
+ */
266
+
267
+ // Retrieval
268
+ let prop = data.name.first;
269
+ // or
270
+ let name = data.get('name.first');
271
+
272
+ // Assignment
273
+ simpleData.name = 'batman';
274
+ // or
275
+ data.set('name', 'batman');
276
+
277
+ // Pushing to an array
278
+ data.push('phones', '555-555-5557');
279
+
280
+ // changing an item in an array
281
+ data.set('phones[0]', '555-555-5558');
282
+
283
+ // Batch updates using an object
284
+ data.set({
285
+ name: 'batman',
286
+ age: 21
287
+ });
288
+
289
+ // Deletion
290
+ data.delete('name');
291
+
292
+ /**
293
+ * Model object
294
+ *
295
+ * This can store default attributes and server resource
296
+ * connectivity.
297
+ *
298
+ * The model's service already has methods for adding,
299
+ * updating, deleting, and fetching data from the
300
+ * server.
301
+ */
302
+ const UserModel = Model.extend({
303
+ defaults: {
304
+ name: {
305
+ first: 'Bruce',
306
+ last: 'Wayne'
307
+ },
308
+ address: {
309
+ street: '123 Gotham St',
310
+ city: 'Gotham',
311
+ state: 'NY'
312
+ },
313
+ age: 21
314
+ },
315
+ url: '/api/user',
316
+
317
+ xhr: {
318
+
319
+ /**
320
+ * Custom methods can be added to the model service.
321
+ *
322
+ * @param {object} instanceParams
323
+ * @param {function} callback
324
+ * @returns {object|bool} The xhr object
325
+ */
326
+ customMethod(instanceParams, callback)
327
+ {
328
+ if (!this.isValid())
329
+ {
330
+ return false;
331
+ }
332
+
333
+ let params = 'op=customParam' +
334
+ '&' + this.setupObjectData();
335
+
336
+ // this will be added to the base url of the model
337
+ const URL = "/custom/url";
338
+ return this._post(URL, params, instanceParams, callBack);
339
+ }
340
+ }
341
+ });
342
+
343
+ const model = new UserModel();
344
+
345
+ /**
346
+ * The model can be used to fetch data from the server.
347
+ *
348
+ * The response will be set to the model.
349
+ */
350
+ model.xhr.get({}, (response) => {
351
+
352
+ });
353
+
354
+ // post
355
+ model.xhr.add({}, (response) => {
356
+
357
+ });
358
+
359
+ // put
360
+ model.xhr.update({}, (response) => {
361
+
362
+ });
363
+
364
+ // delete
365
+ model.xhr.delete({}, (response) => {
366
+
367
+ });
368
+
369
+ ```
370
+ The component also supports the state property. This is another bindable type extended from the SimpleData object so it only supports shallow data.
371
+
372
+ ```javascript
373
+
374
+ /**
375
+ * This will return the state propreties and values that will be
376
+ * use to create the "state" object.
377
+ *
378
+ * @returns {object}
379
+ */
380
+ setupStates()
381
+ {
382
+ return {
383
+ count: 0,
384
+ loading: false
385
+ };
386
+ }
387
+
388
+ ```
389
+
390
+ Each component can have one "data" property that can be set using the "setData" method.
391
+
392
+ If a component has been created using the "route" or "switch" directive, it will receive a "route" property that will contain the route data which is also bindable.
393
+
394
+ The data objects push changes to the elements that are bound to the data. This allows for re-rendering of the elements when the data changes.
395
+
396
+ Here is an example of how to use data binding in a component:
397
+
398
+ ```javascript
399
+ import { Div } from '@base-framework/atoms';
400
+ import { Component } from '@base-framework/base';
401
+
402
+ /**
403
+ * Timer
404
+ *
405
+ * This will create a timer component that uses state watching.
406
+ *
407
+ * @class
408
+ */
409
+ export class Timer extends Component
410
+ {
411
+ /**
412
+ * This will render the timer.
413
+ *
414
+ * @returns {object}
415
+ */
416
+ render()
417
+ {
418
+ // This will rerender the div text content when the count state changes.
419
+ return Div('[[count]]');
420
+ }
421
+
422
+ /**
423
+ * This will setup the states.
424
+ *
425
+ * @returns {object}
426
+ */
427
+ setupStates()
428
+ {
429
+ return { count: 0 };
430
+ }
431
+
432
+ afterSetup()
433
+ {
434
+ const ONE_SECOND = 1000;
435
+ window.setInterval(() => this.state.increment('count'), ONE_SECOND);
436
+ }
437
+ }
438
+ ```
439
+
440
+ Learn more: [Base Data Binding](https://github.com/chrisdurfee/base/wiki/Directives#binding-to-data)
441
+
442
+
443
+ ## Keep-Alive Routes, Scroll Restore, and Request Caching
444
+
445
+ These features are opt-in and off by default.
446
+
447
+ ```javascript
448
+ import { Component, ResourceCache, router } from '@base-framework/base';
449
+
450
+ // keep route pages alive instead of destroying them (LRU, default max 5)
451
+ router.setKeepAlive(true, { max: 5 });
452
+ // or per route: { uri: '/clients', component: ClientList, keepAlive: true }
453
+
454
+ class ClientList extends Component
455
+ {
456
+ afterMount() { /* panel is in the document, safe to measure */ }
457
+ onActivate(params, { restored }) { /* each visit */ }
458
+ onDeactivate() { /* pause timers and listeners */ }
459
+ }
460
+
461
+ // cache, dedupe, and revalidate model GET requests
462
+ model.xhr.withCache({ ttl: 30000, swr: true }).all('', callBack);
463
+ ResourceCache.clear(); // e.g. on logout
464
+ ```
465
+
466
+ Back / forward navigation restores the window scroll (waiting up to 1500ms for content), and elements with a `data-scroll-key` attribute keep their inner scroll.
467
+
468
+ Learn more: [afterMount](https://github.com/chrisdurfee/base/wiki/Components#aftermount), [Route Keep-Alive](https://github.com/chrisdurfee/base/wiki/Keep-Alive), [Scroll Restoration](https://github.com/chrisdurfee/base/wiki/Router#scroll-restoration), [Resource Cache](https://github.com/chrisdurfee/base/wiki/Resource-Cache)
469
+
470
+
471
+ ## Performance
472
+
473
+ Components are static by default, rendering only once per instance. They become dynamic when bound to bindable data sources, allowing for content re-rendering, value changes, function calls, and class additions on data change.
474
+
475
+
476
+ ## Getting Started
477
+
478
+ To begin using Base framework in a client-side or server-side rendered project, follow these steps:
479
+
480
+ 1. **Clone the repository**:
481
+ ```bash
482
+ git clone https://github.com/yourrepository/base-framework.git
483
+ ```
484
+
485
+ 2. Navigate to the project directory:
486
+ ```bash
487
+ cd base-framework
488
+ ```
489
+ 3. Install dependencies (ensure Node.js is installed):
490
+ ```bash
491
+ npm install @base-framework/base
492
+ ```
493
+
494
+ 4. Import the framework into your project:
495
+ ```javascript
496
+ import { base } from '@base-framework/base';
497
+ ```
498
+
499
+ ### Modular (subpath) imports
500
+
501
+ The package root (`@base-framework/base`) ships the full framework as a single
502
+ file. For smaller bundles, you can import only the part you need from a
503
+ subpath. Each subpath is code-split and tree-shakeable, so apps only download
504
+ what they use:
505
+
506
+ ```javascript
507
+ import { Ajax } from '@base-framework/base/ajax'; // ~8 KB
508
+ import { Data, SimpleData, Model } from '@base-framework/base/data';
509
+ import { DateTime } from '@base-framework/base/date'; // ~6 KB
510
+ import { Html } from '@base-framework/base/html';
511
+ import { Store, State } from '@base-framework/base/state';
512
+ import { Component, Unit, Jot, Pod, Atom, Builder, Import } from '@base-framework/base/component';
513
+ import { router, NavLink } from '@base-framework/base/router';
514
+ ```
515
+
516
+ The `component` and `router` subpaths register the default directives
517
+ (`bind`, `watch`, `map`, `for`, `route`, `switch`, ...) automatically, exactly
518
+ like the package root does, so reactive layouts work the same way.
519
+
520
+ ## Usage
521
+
522
+ Create a new component:
523
+
524
+ ```javascript
525
+ import { base, Component } from '@base-framework/base';
526
+
527
+ /**
528
+ * Page
529
+ *
530
+ * This will create a page component.
531
+ *
532
+ * @class Page
533
+ * @extends {Component}
534
+ */
535
+ export class Page extends Component
536
+ {
537
+ render()
538
+ {
539
+ /**
540
+ * This will render an empty div and assign a className
541
+ * of "value".
542
+ */
543
+ return {
544
+ class: this.key
545
+ };
546
+ }
547
+ }
548
+ ```
549
+
550
+ Use the builder to create a new instance of the component:
551
+
552
+ ```javascript
553
+ import { Builder } from '@base-framework/base';
554
+ import { Page } from './components/page.js';
555
+
556
+ /**
557
+ * This will create a new instance of the Page component.
558
+ */
559
+ const page = new Page(
560
+ {
561
+ /**
562
+ * Props can be passed to the component and accessed by their key names.
563
+ *
564
+ * You can name the props anything you want, but it is recommended to
565
+ * use camel case and avoid using reserved keywords.
566
+ */
567
+ key: 'value'
568
+ });
569
+
570
+ // The props passed can now be accessed by the component class.
571
+ ```
572
+
573
+ Render the component to the DOM:
574
+
575
+ ```javascript
576
+ import { Builder } from '@base-framework/base';
577
+ import { Page } from './components/page.js';
578
+
579
+ /**
580
+ * This will create a new instance of the Page component.
581
+ */
582
+ const page = new Page();
583
+
584
+ // Render the component to the DOM.
585
+ const container = document.body;
586
+ Builder.render(page, container);
587
+ ```
588
+
589
+ To allow more reusability, you create static elements as atoms and organisms. Atoms and organisms should use composition. These can be used in multiple components and layouts.
590
+
591
+ ```javascript
592
+ import { Atom } from '@base-framework/base';
593
+
594
+ const Button = Atom((props, children) => ({
595
+ tag: 'button',
596
+ ...props,
597
+ children
598
+ }));
599
+
600
+ const SecondaryButton = Atom((props, children) => (Button({
601
+ ...props,
602
+ class: 'secondary-btn',
603
+ children
604
+ }));
605
+
606
+ ```
607
+
608
+ Atoms can be added to components and other atoms:
609
+
610
+ ```javascript
611
+
612
+ import { Component } from '@base-framework/base';
613
+ import { Div } from '@base-framework/atoms';
614
+ import { SecondaryButton } from './atoms/button.js';
615
+
616
+ export class Page extends Component
617
+ {
618
+ render()
619
+ {
620
+ return Div([
621
+ SecondaryButton({
622
+ /**
623
+ * This will add a click event listener to the button.
624
+ *
625
+ * @param {Event} event The event object
626
+ * @param {Component} parent The parent component object
627
+ * @returns {void}
628
+ */
629
+ click(event, parent) =>
630
+ {
631
+ // Code to access the parent component
632
+ }
633
+ })
634
+ ]);
635
+ }
636
+ }
637
+ ```
638
+
639
+ ## Code Splitting
640
+
641
+ Base supports code splitting, allowing you to load components and modules on demand. This can help reduce the initial load time of your application. You can import atoms or components on demand using the Import module.
642
+
643
+ ```javascript
644
+ import { Import } from "@base-framework/base";
645
+ import { A, Div, H1, Header } from "@base-framework/atoms";
646
+
647
+ // Without using Vite
648
+
649
+ /**
650
+ * This will create an import buttons.
651
+ *
652
+ * @returns {object}
653
+ */
654
+ const ImportButtons = () => (
655
+ Div([
656
+ Header([
657
+ H1('Aside')
658
+ ]),
659
+ Div({ class: 'card' }, [
660
+
661
+ // Importing the buttons module on demand
662
+ Import('../../../../../../components/atoms/import-buttons.js')
663
+ ])
664
+ ])
665
+ );
666
+
667
+ // With Vite
668
+
669
+ /**
670
+ * This will create an import buttons.
671
+ *
672
+ * @returns {object}
673
+ */
674
+ const ImportButtons = () => (
675
+ Div([
676
+ Header([
677
+ H1('Aside')
678
+ ]),
679
+ Div({ class: 'card' }, [
680
+
681
+ /**
682
+ * This will import the buttons module on demand. The import function
683
+ * needs to be used to add the module to the vite build.
684
+ */
685
+ Import({ src: () => import('../../../../../../components/atoms/import-buttons.js') })
686
+ ])
687
+ ])
688
+ );
689
+ ```
690
+
691
+ ## Example Todo App
692
+
693
+ Here is an example of a todo app using Base:
694
+
695
+ ```javascript
696
+ import { Button, Div, Form, H1, Input, Li, Ul } from "@base-framework/atoms";
697
+ import { Builder, Data } from "@base-framework/base";
698
+
699
+ /**
700
+ * This will create a to-do app.
701
+ *
702
+ * @returns {object}
703
+ */
704
+ export function ToDoApp()
705
+ {
706
+ /**
707
+ * This will set up the data store for the to-do app.
708
+ */
709
+ const data = new Data({ items: [] });
710
+
711
+ /**
712
+ * This will handle the form submission for adding a new to-do item.
713
+ *
714
+ * @param {object} event
715
+ */
716
+ const handleSubmit = (event) =>
717
+ {
718
+ event.preventDefault();
719
+ const form = event.target;
720
+ const input = form.querySelector('input');
721
+
722
+ // add the new to-do item to the array of items
723
+ data.push('items', input.value);
724
+ input.value = '';
725
+ };
726
+
727
+ /**
728
+ * This will handle removing a to-do item from the list.
729
+ *
730
+ * @param {number} index
731
+ * @returns {boolean}
732
+ */
733
+ const handleRemove = (index) => data.splice('items', index);
734
+
735
+ return Div([
736
+ H1('To-Do App'),
737
+ Form({ submit: handleSubmit }, [
738
+ Input({ placeholder: 'Add a new item' }),
739
+ Button({ type: 'submit' }, 'Add')
740
+ ]),
741
+ Ul({
742
+ for: [data, 'items', (item, index) => Li([
743
+ Span(item),
744
+ Button({ click: () => handleRemove(index) }, 'Remove')
745
+ ])]
746
+ })
747
+ ]);
748
+ }
749
+
750
+ /**
751
+ * This will render the to-do app to the body of the document.
752
+ */
753
+ Builder.render(ToDoApp(), document.body);
754
+ ```
755
+
756
+
757
+ ## Example Projects Using Base
758
+
759
+ [Base Platform Example](https://github.com/chrisdurfee/next-app-shell)
760
+
761
+ [Base App Example](https://github.com/chrisdurfee/base-update)
762
+
763
+ [Base Website Example](https://github.com/chrisdurfee/life)
764
+
765
+ [Base Server Example](https://github.com/chrisdurfee/base-server)
766
+
767
+ [Base Game Example](https://github.com/chrisdurfee/multisplode)
768
+
769
+
770
+ ## Contributing
771
+
772
+ Contributions to Base are welcome. Follow these steps to contribute:
773
+
774
+ - Fork the repository.
775
+ - Create a new branch for your feature or bug fix.
776
+ - Commit your changes with clear, descriptive messages.
777
+ - Push your branch and submit a pull request.
778
+ - Before contributing, read our CONTRIBUTING.md for coding standards and community guidelines.
779
+
780
+ ## License
781
+
782
+ Base is licensed under the MIT License. See the LICENSE file for details.
783
+
784
+ ## Contact
785
+
786
+ For questions, suggestions, or issues, contact us:
787
+
788
+ - Email:
789
+ - GitHub Issues: github.com/chrisdurfee/base/issues
790
+ - Community Chat: Discord coming soon
791
+ - Follow us on Social Media: