structured-fw 0.8.3 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +165 -29
  2. package/build/system/EventEmitter.d.ts +7 -0
  3. package/{system/client/EventEmitter.ts → build/system/EventEmitter.js} +10 -17
  4. package/build/system/Types.d.ts +2 -2
  5. package/build/system/client/ClientComponent.d.ts +1 -1
  6. package/build/system/client/ClientComponent.js +1 -1
  7. package/build/system/server/Application.d.ts +3 -1
  8. package/build/system/server/Application.js +11 -0
  9. package/build/system/server/Component.d.ts +6 -3
  10. package/build/system/server/Component.js +8 -6
  11. package/build/system/server/Components.d.ts +1 -1
  12. package/build/system/server/Document.d.ts +3 -1
  13. package/build/system/server/DocumentHead.d.ts +1 -1
  14. package/build/system/server/FormValidation.d.ts +1 -1
  15. package/index.ts +8 -2
  16. package/package.json +9 -1
  17. package/app/models/README.md +0 -9
  18. package/app/routes/README.md +0 -19
  19. package/app/views/README.md +0 -1
  20. package/app/views/layout.html +0 -1
  21. package/build/Config.d.ts +0 -2
  22. package/build/Config.js +0 -30
  23. package/build/app/Types.d.ts +0 -5
  24. package/build/app/Types.js +0 -1
  25. package/build/app/global.d.ts +0 -3
  26. package/build/app/global.js +0 -1
  27. package/build/app/models/Users.d.ts +0 -0
  28. package/build/app/models/Users.js +0 -1
  29. package/build/app/routes/Auth.d.ts +0 -0
  30. package/build/app/routes/Auth.js +0 -1
  31. package/build/app/routes/Test.d.ts +0 -2
  32. package/build/app/routes/Test.js +0 -101
  33. package/build/app/routes/Todo.d.ts +0 -0
  34. package/build/app/routes/Todo.js +0 -1
  35. package/build/app/routes/Upload.d.ts +0 -0
  36. package/build/app/routes/Upload.js +0 -1
  37. package/build/app/routes/Validation.d.ts +0 -2
  38. package/build/app/routes/Validation.js +0 -34
  39. package/build/app/routess/Auth.d.ts +0 -0
  40. package/build/app/routess/Auth.js +0 -1
  41. package/build/app/routess/Test.d.ts +0 -2
  42. package/build/app/routess/Test.js +0 -101
  43. package/build/app/routess/Todo.d.ts +0 -0
  44. package/build/app/routess/Todo.js +0 -1
  45. package/build/app/routess/Upload.d.ts +0 -0
  46. package/build/app/routess/Upload.js +0 -1
  47. package/build/app/routess/Validation.d.ts +0 -2
  48. package/build/app/routess/Validation.js +0 -34
  49. package/build/app/views/components/ClientImport/ClientImport.client.d.ts +0 -2
  50. package/build/app/views/components/ClientImport/ClientImport.client.js +0 -4
  51. package/build/app/views/components/ClientImport/Export.d.ts +0 -1
  52. package/build/app/views/components/ClientImport/Export.js +0 -1
  53. package/build/app/views/components/Conditionals/Conditionals.client.d.ts +0 -2
  54. package/build/app/views/components/Conditionals/Conditionals.client.js +0 -43
  55. package/build/app/views/components/FormTest/FormTestNested/FormTestNested.d.ts +0 -8
  56. package/build/app/views/components/FormTest/FormTestNested/FormTestNested.js +0 -7
  57. package/build/app/views/components/ModelsTest/ModelsTest.client.d.ts +0 -2
  58. package/build/app/views/components/ModelsTest/ModelsTest.client.js +0 -5
  59. package/build/app/views/components/MultipartForm/MultipartForm.client.d.ts +0 -0
  60. package/build/app/views/components/MultipartForm/MultipartForm.client.js +0 -1
  61. package/build/app/views/components/PassObject/PassObject.d.ts +0 -10
  62. package/build/app/views/components/PassObject/PassObject.js +0 -10
  63. package/build/app/views/components/PassObject/ReceiveObj/ReceiveObj.d.ts +0 -6
  64. package/build/app/views/components/PassObject/ReceiveObj/ReceiveObj.js +0 -6
  65. package/build/app/views/components/RedrawAbort/RedrawAbort.client.d.ts +0 -2
  66. package/build/app/views/components/RedrawAbort/RedrawAbort.client.js +0 -6
  67. package/build/app/views/components/RedrawAbort/RedrawAbort.d.ts +0 -8
  68. package/build/app/views/components/RedrawAbort/RedrawAbort.js +0 -8
  69. package/build/app/views/components/ServerSideContext/ServerSideContext.d.ts +0 -7
  70. package/build/app/views/components/ServerSideContext/ServerSideContext.js +0 -10
  71. package/build/assets/ts/Export.d.ts +0 -1
  72. package/build/assets/ts/Export.js +0 -1
  73. package/build/index.d.ts +0 -1
  74. package/build/index.js +0 -3
  75. package/build/tsconfig.tsbuildinfo +0 -1
  76. package/jsr.json +0 -35
  77. package/system/Helpers.ts +0 -97
  78. package/system/Symbols.ts +0 -6
  79. package/system/Types.ts +0 -232
  80. package/system/Util.ts +0 -488
  81. package/system/bin/structured.ts +0 -115
  82. package/system/client/App.ts +0 -11
  83. package/system/client/Client.ts +0 -9
  84. package/system/client/ClientComponent.ts +0 -1107
  85. package/system/client/DataStore.ts +0 -101
  86. package/system/client/DataStoreView.ts +0 -82
  87. package/system/client/Net.ts +0 -58
  88. package/system/client/NetRequest.ts +0 -64
  89. package/system/global.d.ts +0 -12
  90. package/system/server/Application.ts +0 -239
  91. package/system/server/Component.ts +0 -407
  92. package/system/server/Components.ts +0 -114
  93. package/system/server/Cookies.ts +0 -29
  94. package/system/server/Document.ts +0 -163
  95. package/system/server/DocumentHead.ts +0 -150
  96. package/system/server/FormValidation.ts +0 -231
  97. package/system/server/Handlebars.ts +0 -51
  98. package/system/server/Request.ts +0 -502
  99. package/system/server/Session.ts +0 -151
  100. package/system/server/dom/DOMFragment.ts +0 -7
  101. package/system/server/dom/DOMNode.ts +0 -140
  102. package/system/server/dom/HTMLParser.ts +0 -238
  103. package/tsconfig.json +0 -31
package/README.md CHANGED
@@ -5,6 +5,9 @@ Framework allows the developer to develop self-contained components which are re
5
5
 
6
6
  It works with Node.js and Deno runtimes. Other runtimes are not tested.
7
7
 
8
+ > [!NOTE]
9
+ > While Structured framework is in development for a couple of years and is production tested, the npm package is introduced recently and there were still issues that came up with it in the past few versions. Since version 0.8.3 all should be functional. Please update to latest version and check for updates regularly until the npm package is as stable as the framework itself. Feel free to open issues on the github page if you have any issues with the npm package or the framework. _Structured followed versioning x.y.z where z was a single digit 0-9, but since there were a couple of versions that introduced no changes to the framework and were just npm package tweaks, I decided to make an exception to the rule and allow myself to use 2 digits for such updates._
10
+
8
11
  - [Why Structured](#why-structured)
9
12
  - [Audience](#audience)
10
13
  - [Getting started](#getting-started)
@@ -38,6 +41,17 @@ npm install @types/node
38
41
  ### Create boilerplate
39
42
  `npx structured init`
40
43
 
44
+ ### Create a test route
45
+ Create a file `/app/routes/Test.ts`:
46
+ ```
47
+ import { Application } from 'structured-fw/Application';
48
+ export default function(app: Application) {
49
+ app.request.on('GET', '/test', async()=> {
50
+ return 'Hello, World!';
51
+ });
52
+ }
53
+ ```
54
+
41
55
  ### Compile
42
56
  `tsc`\
43
57
  This will create a directory `build` (or whatever you have in tsconfig.json as compilerOptions.outputDir)
@@ -54,6 +68,8 @@ cd build
54
68
  pm2 start index.js --name="[appName]"
55
69
  ```
56
70
 
71
+ If you followed the above steps, you should be able to access `http://localhost:9191/test` in your browser and see the output `Hello, World!`.
72
+
57
73
  # Key concepts
58
74
 
59
75
  ## Application
@@ -110,7 +126,7 @@ new Application(config);
110
126
 
111
127
  ### Methods
112
128
  - `init(): Promise<void>` - initializes application, you only need to run this if you set `autoInit = false` in config, otherwise this will be ran when you create the Application instance
113
- - `on(evt: ApplicationEvents, callback: RequestCallback|((payload?: any) => void))` - allows you to add event listeners for specific `ApplicationEvenets`:
129
+ - `on(evt: ApplicationEvents, callback: RequestCallback|((payload?: any) => void))` - allows you to add event listeners for specific `ApplicationEvents`:
114
130
  - `serverStarted` - executed once the built-in http server is started and running. Callback receives Server (exported from node:http) instance as the first argument
115
131
  - `beforeRequestHandler` - runs before any request handler (route) is executed. Callback receives `RequestContext` as the first argument. Useful for example to set `RequestContext.data: RequestContextData` (user defined data, to make it available to routes and components)
116
132
  - `afterRequestHandler` - runs after any request handler (route) is executed. Callback receives `RequestContext` as the first argument
@@ -173,7 +189,7 @@ app.exportContextFields('user');
173
189
  ```
174
190
 
175
191
  ### Session
176
- Session allows you to store temporary data for the users of your web application. You don't need to create an instance of Session, you will always use the instace `Application.session`.
192
+ Session allows you to store temporary data for the users of your web application. You don't need to create an instance of Session, you will always use the instance `Application.session`.
177
193
 
178
194
  Session data is tied to a visitor via sessionId, which is always available on `RequestContext`, which means you can interact with session data from routes and server side code of your components.
179
195
 
@@ -321,7 +337,7 @@ In some edge cases you may need more control of when a route is executed, in whi
321
337
  > email: string,
322
338
  > password: string,
323
339
  > age: number
324
- >}>('POST', '/users/create', asyc (ctx) => {
340
+ >}>('POST', '/users/create', async (ctx) => {
325
341
  > ctx.body.email // string
326
342
  > ctx.body.age // number
327
343
  > const doc = new Document(app, 'User', ctx);
@@ -330,7 +346,7 @@ In some edge cases you may need more control of when a route is executed, in whi
330
346
  > ```
331
347
 
332
348
  ## Document
333
- Document does not differ much from a component, in fact, it extends Component. It has a more user-firendly API than Component. Each Document represents a web page. It has a head and body. Structured intentionally does not differentiate between a page and a Component - page is just a component that loads many other components in a desired layout. DocumentHead (each document has one at Document.head) allows adding content to `<head>` section of the output HTML page.
349
+ Document does not differ much from a component, in fact, it extends Component. It has a more user-friendly API than Component. Each Document represents a web page. It has a head and body. Structured intentionally does not differentiate between a page and a Component - page is just a component that loads many other components in a desired layout. DocumentHead (each document has one at Document.head) allows adding content to `<head>` section of the output HTML page.
334
350
 
335
351
  Creating a document:
336
352
  `const doc = new Document(app, 'HelloWorld page', ctx);`
@@ -344,13 +360,25 @@ app.request.on('GET', '/home', async (ctx) => {
344
360
  });
345
361
  ```
346
362
 
363
+ > [!TIP]
364
+ > Since version 0.8.4 Document extends EventEmitter, and "componentCreated" event is emitted whenever a component instance is created within the Document.\
365
+ > This makes the following possible:
366
+ > ```
367
+ > app.on('documentCreated', (doc) => {
368
+ > doc.on('componentCreated', (component) => {
369
+ > // do something with the document or the component
370
+ > })
371
+ > })
372
+ > ```
373
+
347
374
  ## Component
348
- A component is comprised of 1-3 files. It always must include one HTML file, while server side and client side files are optional.
349
- * HTML file preobably requires no explanation
375
+ A component is comprised of [1-3 files](#component-parts). It always must include one HTML file, while server side and client side files are optional.
376
+ * HTML file probably requires no explanation
350
377
  * server side file, code that runs on the server and makes data available to HTML and client side code
351
378
  * client side file, code that runs on the client (in the browser)
352
379
 
353
- You should never need to instantiate a Component on your own. You will always load a Component representing your page into a document (using `Document.loadComponent(componentName: string)`), which will know what to do from there.
380
+ > [!TIP]
381
+ > You should never need to instantiate a Component on your own. You will always load a Component representing your page into a document (using `Document.loadComponent(componentName: string)`), which will know what to do from there.
354
382
 
355
383
  Example component files:
356
384
  - `/app/views/`
@@ -367,9 +395,15 @@ It is recommended, but not necessary, that you contain each component in it's ow
367
395
  \
368
396
  **Component rules:**
369
397
  - **Component names must be unique**
370
- - Components HTML file can have a `.hbs` extension (which allows for better Handlebars sytax highlighting)
398
+ - Components HTML file can have a `.hbs` extension (which allows for better Handlebars syntax highlighting)
371
399
  - Components can reside at any depth in the file structure
372
400
 
401
+ ### Component parts
402
+ - [Component HTML](#component-html) (_ComponentName.html_)
403
+ - [Component server-side code](#component-server-side-code) (_ComponentName.ts_)
404
+ - [Component client-side code](#component-client-side-code) (_ComponentName.client.ts_)
405
+
406
+ ### Component HTML
373
407
  Let's create a HelloWorld Component `/app/views/HelloWorld/HelloWorld.html`:\
374
408
  `Hello, World!`
375
409
 
@@ -389,10 +423,15 @@ export default function(app: Application) {
389
423
  You can now run the app and if you open /hello/world in the browser you will see:\
390
424
  `Hello, World!` - which came from your HelloWorld component.
391
425
 
392
- That was the simplest possible example, let's make it more interesting.
426
+ > [!TIP]
427
+ > It is recommended to use .hbs (Handlebars) extension as you will get better syntax highlighting in most IDEs. Other than syntax highlighting there is no difference between using html or hbs extension.
428
+
429
+ That was the simplest possible example, let's make it more interesting by adding some server-side code.
430
+
431
+ ### Component server-side code
393
432
  Create a new file `/app/views/HelloWorld/HelloWorld.ts` (server side component code):
394
433
  ```
395
- import { ComponentScaffold } from 'system/Types.js';
434
+ import { ComponentScaffold } from 'structured-fw/Types';
396
435
  export default class HelloWorld implements ComponentScaffold {
397
436
  async getData(): Promise<{
398
437
  luckyNumber: number
@@ -423,10 +462,18 @@ Your lucky number is [a number from 0-100]
423
462
  This demonstrates the use of a *server side component code* to make data available to HTML.
424
463
  We just generated a random number, but the data could be anything and will more often come from a database, session, or be provided by the parent component.
425
464
 
465
+ > [!IMPORTANT]
466
+ > Server side `getData` will receive the following arguments:
467
+ > - `data: LooseObject` any data passed in (either by attributes, ClientComponent.add or ClientComponent.redraw)
468
+ > - `ctx: RequestContext` - current `RequestContext`, you will often use this to access for example ctx.data (`RequestContextData`) or ctx.sessionId to interact with session
469
+ > - `app: Application` - your Application instance. You can use it to, for example, access the session in combination with ctx.sessionId
470
+
426
471
  Let's make it even more interesting by adding some client side code to it.
472
+
473
+ ### Component client-side code
427
474
  Create `/app/views/HelloWorld/HelloWorld.client.ts`:
428
475
  ```
429
- import { InitializerFunction } from 'system/Types.js';
476
+ import { InitializerFunction } from 'structured-fw/Types';
430
477
  export const init: InitializerFunction = async function() {
431
478
  const generateNew = this.ref<HTMLButtonElement>('newNumber');
432
479
 
@@ -475,7 +522,7 @@ Parent says your lucky number is {{number}}.
475
522
  That's it. Since `AnotherComponent` has no server side code, all data passed to it is exported to HTML, hence the `number` you passed from `HelloWorld` will be readily available for use. If AnotherComponent had a server side part, the process is a bit different, it will receive it as part of the `data`, but can choose whether to make it available to the HTML, or just make use of it and return other stuff. Let's see how that works.
476
523
  Create `/app/views/AnotherComponent/AnotherComponent.ts`:
477
524
  ```
478
- import { ComponentScaffold } from 'system/Types.js';
525
+ import { ComponentScaffold } from 'structured-fw/Types';
479
526
  export default class AnotherComponent implements ComponentScaffold {
480
527
  async getData(data: { number: number }): Promise<{
481
528
  parentSuggests: number,
@@ -499,22 +546,16 @@ What we did is, we accepted the number provided by parent component, and returne
499
546
  betterNumber: number
500
547
  }
501
548
  ```
502
- which is now avaialble in `AnotherComponent` HTML, we assigned the received number to `parentSuggests`, while `betterNumber` is `parentSuggests + 5`, we now have these 2 available and ready to use in our HTML template.
549
+ which is now available in `AnotherComponent` HTML, we assigned the received number to `parentSuggests`, while `betterNumber` is `parentSuggests + 5`, we now have these 2 available and ready to use in our HTML template.
503
550
 
504
551
  What about client side? **By default, data returned by server side code is not available in client side code** for obvious reasons, let's assume your server side code returns sensitive data such as user's password, you would not like that exposed on the client side, hence exporting data needs to be explicitly requested in the server side code. There are two ways to achieve this, setting `exportData = true` (exports all data), or `exportFields: Array<string> = [...keysToExport]` (export only given fields).
505
552
 
506
553
  > [!NOTE]
507
554
  > Whenever a component with server-side code is rendered, `getData` is automatically called and anything it returns is available in HTML. You can export all returned data to client-side code by setting `exportData = true` or you can export some of the fields by setting `exportFields = ["field1", "field2", ...]` as a direct property of the class. To access the exported data from client-side use `ClientComponent`.`getData(key: string)` which will be `this.getData(key:string)` within client side code.
508
555
 
509
- > [!IMPORTANT]
510
- > Server side `getData` will receive the following arguments:
511
- > - `data: LooseObject` any data passed in (either by attributes, ClientComponent.add or ClientComponent.redraw)
512
- > - `ctx: RequestContext` - current `RequestContext`, you will often use this to access for example ctx.data (`RequestContextData`) or ctx.sessionId to interact with session
513
- > - `app: Application` - your Application instance. You can use it to, for example, access the session in combination with ctx.sessionId
514
-
515
556
  Let's create a client side code for `AnotherComponent` and export the `betterNumber` to it, create `/app/views/AnotherComponent/AnotherComponent.client.ts`:
516
557
  ```
517
- import { InitializerFunction } from 'system/Types.js';
558
+ import { InitializerFunction } from 'structured-fw/Types';
518
559
  export const init: InitializerFunction = async function() {
519
560
  const betterNumber = this.getData<number>('betterNumber');
520
561
 
@@ -524,7 +565,7 @@ export const init: InitializerFunction = async function() {
524
565
 
525
566
  And let's update `AnotherComponent.ts` to export `betterNumber`:
526
567
  ```
527
- import { ComponentScaffold } from 'system/Types.js';
568
+ import { ComponentScaffold } from 'structured-fw/Types';
528
569
  export default class AnotherComponent implements ComponentScaffold {
529
570
  exportFields = ['betterNumber'];
530
571
  async getData(data: { number: number }): Promise<{
@@ -546,7 +587,7 @@ This concept is wrong to start with, if we want a component to be independent, i
546
587
 
547
588
  Let's say we wanted to access the `parent` Component from `AnotherComponent`:
548
589
  ```
549
- import { InitializerFunction } from 'system/Types.js';
590
+ import { InitializerFunction } from 'structured-fw/Types';
550
591
  export const init: InitializerFunction = async function() {
551
592
  const betterNumber = this.getData<number>('betterNumber');
552
593
 
@@ -555,9 +596,9 @@ export const init: InitializerFunction = async function() {
555
596
  ```
556
597
  Here we accessed the `parent` and obtained it's `name`.
557
598
 
558
- *"But we did not send any data to the parent here"* - correct, we did not, and we won't, instead we can inform them we have some data available, or that an event they might be interested in has ocurred, and if they care, so be it:
599
+ *"But we did not send any data to the parent here"* - correct, we did not, and we won't, instead we can inform them we have some data available, or that an event they might be interested in has occurred, and if they care, so be it:
559
600
  ```
560
- import { InitializerFunction } from 'system/Types.js';
601
+ import { InitializerFunction } from 'structured-fw/Types';
561
602
  export const init: InitializerFunction = async function() {
562
603
  const betterNumber = this.getData<number>('betterNumber');
563
604
 
@@ -567,7 +608,7 @@ export const init: InitializerFunction = async function() {
567
608
 
568
609
  We emitted an `event` with `eventName` = "`truth`" and a `payload`, which in this case is a string, but can be of any type. If the parent cares about it (or for that matter, not necessarily the parent, but anyone in the component tree), they can subscribe to that event. Let's subscribe to the event from `HelloWorld` (`HelloWorld.client.ts`):
569
610
  ```
570
- import { InitializerFunction } from 'system/Types.js';
611
+ import { InitializerFunction } from 'structured-fw/Types';
571
612
  export const init: InitializerFunction = async function() {
572
613
 
573
614
  const child = this.find('AnotherComponent'); // ClientComponent | null
@@ -585,7 +626,7 @@ export const init: InitializerFunction = async function() {
585
626
  }
586
627
  ```
587
628
 
588
- That's it. If there is `AnotherComponent` found within `HelloWorld` (which there is in our case) we are subscribing to "truth" event and capturing the payload. Payload is optional, sometimes we just want to inform anyone interested that a certain event has ocurred, without the need to pass any extra data with it. We used `this.find(componentName: string)`, this will recursively find the first instance of a component with `componentName`, optionally you can make it non-recursive by passing `false` as the second argument to `find` method in which case it will look for a direct child with given name.
629
+ That's it. If there is `AnotherComponent` found within `HelloWorld` (which there is in our case) we are subscribing to "truth" event and capturing the payload. Payload is optional, sometimes we just want to inform anyone interested that a certain event has occurred, without the need to pass any extra data with it. We used `this.find(componentName: string)`, this will recursively find the first instance of a component with `componentName`, optionally you can make it non-recursive by passing `false` as the second argument to `find` method in which case it will look for a direct child with given name.
589
630
 
590
631
  We have only scratched the surface of what client-side code of a component is capable of. Which brings us to `this`. In client-side code of a component, `this` is the instance of a `ClientComponent`.
591
632
 
@@ -605,15 +646,70 @@ Methods:
605
646
  - `store.set(key: string, value: any)` - set data in client side data store
606
647
  - `find(componentName: string, recursive: boolean = true): ClientComponent | null` - find a child component
607
648
  - `findParent(componentName: string): ClientComponent | null` - find the first parent with given name
608
- - `query(componentName: string, recursive: boolean = true): Array<ClientComponent>` - return all components with given name found within this component, if `recurive = false`, only direct children are considered
649
+ - `query(componentName: string, recursive: boolean = true): Array<ClientComponent>` - return all components with given name found within this component, if `recursive = false`, only direct children are considered
609
650
  - `ref<T>(refName: string): T` - get a HTMLElement or ClientComponent that has attribute `ref="[refName]"`
610
651
  - `arrayRef<T>(refName: string): Array<T>` - get an array of HTMLElement or ClientComponent that have attribute `array:ref="[refName]"`
611
- - `add(appendTo: HTMLElement, componentName: string, data?: LooseObject)` - add `componentName` component to `appendTo` element, optionally passing `data` to the component when it's being rendered
652
+ - `add(appendTo: HTMLElement, componentName: string, data?: LooseObject): Promise<ClientComponent | null>` - add `componentName` component to `appendTo` element, optionally passing `data` to the component when it's being rendered. Returns a promise that resolves with added ClientComponent or null if something went wrong
653
+ - `redraw(data?: LooseObject): Promise<void>` - redraw the component, optionally provide data which will be available server side
654
+
655
+ ### Conditionals
656
+ You can make any DOM node within your components conditionally shown/hidden using `data-if` attribute.\
657
+ For example:
658
+ ```
659
+ <div data-if="showDiv"></div>
660
+ ```
661
+ Above div will only be shown if store.showDiv = true
662
+
663
+ You can also use `!` to invert the value, `!showDiv` in which case div would be shown if showDiv is false.
664
+
665
+ You can also use comparison:
666
+ ```
667
+ <div data-if="val === 1"></div>
668
+ <div data-if="val == 1"></div>
669
+ <div data-if="val !== 1"></div>
670
+ <div data-if="val != 1"></div>
671
+ <div data-if="val > 1"></div>
672
+ <div data-if="val < 1"></div>
673
+ <div data-if="val <= 1"></div>
674
+ <div data-if="val >= 1"></div>
675
+ ```
676
+
677
+ The right hand side of the comparison does not have to be boolean or number. It can be a string or any primitive value, but the numeric comparisons don't make sense in such case.
678
+
679
+ You can also define callbacks and use them as the condition, in you ComponentName.client.ts:
680
+ ```
681
+ import { InitializerFunction } from 'structured-fw/Types';
682
+ export const init: InitializerFunction = async function() {
683
+ this.conditionalCallback('showDiv', () => {
684
+ // return a boolean here
685
+ });
686
+ }
687
+ ```
688
+
689
+ then in ComponentName.html:
690
+ ```
691
+ <div data-if="showDiv()"></div>
692
+ ```
693
+
694
+ **Basic animation/transitions**\
695
+ If you use conditionals on any DOM node, you may also enable basic animations/transitions using following attributes:
696
+ - Enable transition:
697
+ - `data-transition-show-slide="durationMilliseconds"` - when DOM node is shown, slide it in
698
+ - `data-transition-hide-slide="durationMilliseconds"` - when DOM node is hidden, slide it out
699
+ - `data-transition-show-fade="durationMilliseconds"` - fade DOM node in
700
+ - `data-transition-hide-fade="durationMilliseconds"` - fade DOM node out
701
+ - Modify transition (slide only)
702
+ - `data-transform-origin-show="CSS transform origin"` - from where does the component slide in for example `0% 50%` to slide it in from mid-left
703
+ - `data-transform-origin-hide="CSS transform origin"` - where does the component slide out to for example `100% 100%` to slide it out to bottom-right
704
+ - `data-transition-axis-show="X | Y"` - slide animation axis
705
+ - `data-transition-axis-hide="X | Y"` - slide animation axis
612
706
 
613
707
  ## Good to know
614
- - [Uing CSS frameworks](#css-frameworks)
708
+ - [Using CSS frameworks](#css-frameworks)
615
709
  - [Using JS runtimes other than Node.js](#runtimes)
616
710
  - [Why not JSR](#jsr)
711
+ - [Best practices](#best-practices)
712
+ - [Having an issue?](#issues-and-feedback)
617
713
 
618
714
  ### CSS frameworks
619
715
  We rarely write all CSS from scratch, usually we use a CSS framework to speed us up. Structured allows you to work with any CSS frameworks such as Tailwind, PostCSS or Bootstrap.
@@ -721,6 +817,46 @@ Run application using `deno main.ts`
721
817
  It would make a lot of sense to have Structured hosted on JSR (JavaScript Registry) given Structured is a TypeScript framework, and JSR is a TypeScript-first registry, however, the issue is that Deno imposes [limitations with dynamic imports](https://docs.deno.com/deploy/api/dynamic-import/) with JSR-imported dependencies, which are required for the framework (to dynamically import your routes and components).\
722
818
  This does not stop the framework from working with Deno, but for the time being, we have to stick with good old npm.
723
819
 
820
+ ### Best practices
821
+
822
+ **Entry point:**\
823
+ I suggest the following setup for your entry point:
824
+ 1) Set `autoInit = false` in your `/Config.ts`
825
+ 2) If you are using ENV variables, define a type `EnvConf` in `/app/Types.ts`
826
+ 3) In `/index.ts`, only create the Application instance and import ENV using `importEnv`, exporting both, as follows:
827
+ ```
828
+ import { EnvConf } from './app/Types.js';
829
+ import { Application } from 'structured-fw/Application';
830
+ import { config } from './Config.js';
831
+
832
+ export const app = new Application(config);
833
+ export const env = app.importEnv<EnvConf>();
834
+ ```
835
+ 4) Create `/main.ts` and import `app` and `env` from `/index.ts`, add `main.ts` to tsconfig.json include array, add any event listeners, and load helpers from within `/main.ts`. This makes sure you can use env in any imported modules in main.ts without having to use dynamic imports. You can later import `env` and `app` from `index.ts` wherever you want to use them.
836
+
837
+ \
838
+ **Component directories**\
839
+ You should always place your components in a directory named same as your component. While this is not required, it will keep things organized. You might think your component will only have a HTML part, but at some point you may decide you want to add client/server code to it, so it's better to start out with a directory.\
840
+ Feel free to group your components in directories and subdirectories. Structured loads all components recursively when Application is initialized, and allows you to load any existing component from any component/Document. You can even move your components to other directory later without having to worry about updating the imports.
841
+
842
+ **Type definitions**\
843
+ I suggest keeping your general type definitions in /app/Types.ts, but for more specific types you should probably create /app/types/[entity].types.ts to keep things clean easy to maintain.\
844
+ For example:\
845
+ `export type BooleanInt = 0 | 1;` - this is fine
846
+ in /app/Types.ts\
847
+ `export type User = {email: string, password: string}` - you should probably create /app/types/users.types.ts for this one
848
+
849
+ **Models**\
850
+ If you ran `npx structured init`, it has created /app/models for you. Structured does not use this directory, but I suggest keeping your models interfacing the DB/APIs there. While Structured framework is not an MVC in a traditional sense, it's a good idea to keep your models in one place, as you will want to import the same model from many routes and components.
851
+
852
+ > [!IMPORTANT]
853
+ > while it's true that with Structured, components take care of their own data, it does not mean that they need to contain the code to fetch said data, instead you are encouraged to keep data logic in your models, and use those models in components/routes.
854
+
855
+ You can create additional code separation, for example, it would make sense to have /app/lib for code that interfaces an API, or have /app/Util.ts where you export utility functions. Structured boilerplate does not include these as not all applications will need them.
856
+
857
+ ### Issues and feedback
858
+ If you have any issues with the framework or the npm package, please don't hesitate to open an issue on [github](https://github.com/julijan/structured). Feedback is also welcome!
859
+
724
860
  ## Why Structured
725
861
  Framework was developed by someone who has been a web developer for almost 20 years (me), and did not like the path web development has taken.
726
862
  \
@@ -0,0 +1,7 @@
1
+ import { EventEmitterCallback } from "./Types.js";
2
+ export declare class EventEmitter<T extends Record<string, any> = Record<string, any>> {
3
+ protected listeners: Partial<Record<keyof T, Array<EventEmitterCallback<any>>>>;
4
+ on<K extends keyof T>(eventName: K, callback: EventEmitterCallback<T[K]>): void;
5
+ emit(eventName: keyof T, payload?: any): void;
6
+ unbind(eventName: keyof T, callback: EventEmitterCallback<any>): void;
7
+ }
@@ -1,38 +1,31 @@
1
- import { EventEmitterCallback } from "../Types.js";
2
-
3
1
  export class EventEmitter {
4
- protected listeners: Record<string, Array<EventEmitterCallback>> = {}
5
-
6
- // add event listener
7
- public on(eventName: string, callback: EventEmitterCallback): void {
8
- if (! Array.isArray(this.listeners[eventName])) {
2
+ constructor() {
3
+ this.listeners = {};
4
+ }
5
+ on(eventName, callback) {
6
+ if (!Array.isArray(this.listeners[eventName])) {
9
7
  this.listeners[eventName] = [];
10
8
  }
11
-
12
9
  this.listeners[eventName].push(callback);
13
10
  }
14
-
15
- // emit event with given payload
16
- public emit(eventName: string, payload?: any): void {
11
+ emit(eventName, payload) {
17
12
  if (Array.isArray(this.listeners[eventName])) {
18
13
  this.listeners[eventName].forEach((callback) => {
19
14
  callback(payload);
20
15
  });
21
16
  }
22
17
  }
23
-
24
- // remove event listener
25
- public unbind(eventName: string, callback: EventEmitterCallback): void {
18
+ unbind(eventName, callback) {
26
19
  if (Array.isArray(this.listeners[eventName])) {
27
20
  while (true) {
28
21
  const index = this.listeners[eventName].indexOf(callback);
29
22
  if (index > -1) {
30
23
  this.listeners[eventName].splice(index, 1);
31
- } else {
32
- // callback not found, all removed
24
+ }
25
+ else {
33
26
  break;
34
27
  }
35
28
  }
36
29
  }
37
30
  }
38
- }
31
+ }
@@ -127,7 +127,7 @@ export interface ComponentScaffold {
127
127
  [key: string]: any;
128
128
  }
129
129
  export type LooseObject = Record<string, any>;
130
- export type ApplicationEvents = 'serverStarted' | 'beforeRequestHandler' | 'afterRequestHandler' | 'beforeRoutes' | 'afterRoutes' | 'beforeComponentsLoad' | 'afterComponentsLoaded' | 'componentCreated' | 'documentCreated' | 'beforeAssetAccess' | 'afterAssetAccess' | 'pageNotFound';
130
+ export type ApplicationEvents = 'serverStarted' | 'beforeRequestHandler' | 'afterRequestHandler' | 'beforeRoutes' | 'afterRoutes' | 'beforeComponentsLoad' | 'afterComponentsLoaded' | 'documentCreated' | 'beforeAssetAccess' | 'afterAssetAccess' | 'pageNotFound';
131
131
  export type SessionEntry = {
132
132
  sessionId: string;
133
133
  lastRequest: number;
@@ -166,4 +166,4 @@ export type ClientComponentTransition = {
166
166
  };
167
167
  export type ClientComponentTransitionEvent = 'show' | 'hide';
168
168
  export type ClientComponentTransitions = Record<ClientComponentTransitionEvent, ClientComponentTransition>;
169
- export type EventEmitterCallback = (payload: any) => void;
169
+ export type EventEmitterCallback<T> = (payload: T) => void;
@@ -2,7 +2,7 @@ import { LooseObject } from '../Types.js';
2
2
  import { DataStoreView } from './DataStoreView.js';
3
3
  import { DataStore } from './DataStore.js';
4
4
  import { Net } from './Net.js';
5
- import { EventEmitter } from './EventEmitter.js';
5
+ import { EventEmitter } from '../EventEmitter.js';
6
6
  export declare class ClientComponent extends EventEmitter {
7
7
  readonly name: string;
8
8
  children: Array<ClientComponent>;
@@ -2,7 +2,7 @@ import { attributeValueFromString, attributeValueToString, mergeDeep, objectEach
2
2
  import { DataStoreView } from './DataStoreView.js';
3
3
  import { Net } from './Net.js';
4
4
  import { NetRequest } from './NetRequest.js';
5
- import { EventEmitter } from './EventEmitter.js';
5
+ import { EventEmitter } from '../EventEmitter.js';
6
6
  export class ClientComponent extends EventEmitter {
7
7
  constructor(parent, name, domNode, store, runInitializer = true) {
8
8
  super();
@@ -1,5 +1,5 @@
1
1
  import { Server } from 'node:http';
2
- import { ApplicationEvents, LooseObject, RequestContext, StructuredConfig } from '../Types';
2
+ import { ApplicationEvents, LooseObject, RequestContext, StructuredConfig } from '../Types.js';
3
3
  import { Document } from './Document.js';
4
4
  import { Components } from './Components.js';
5
5
  import { Session } from './Session.js';
@@ -8,6 +8,7 @@ import { Handlebars } from './Handlebars.js';
8
8
  import { Cookies } from './Cookies.js';
9
9
  export declare class Application {
10
10
  readonly config: StructuredConfig;
11
+ private initialized;
11
12
  server: null | Server;
12
13
  listening: boolean;
13
14
  private readonly eventEmitter;
@@ -25,6 +26,7 @@ export declare class Application {
25
26
  importEnv<T extends LooseObject>(smartPrimitives?: boolean): T;
26
27
  exportContextFields(...fields: Array<keyof RequestContextData>): void;
27
28
  contentType(extension: string): string | false;
29
+ registerPlugin(callback: (app: Application) => void): void;
28
30
  private respondWithComponent;
29
31
  memoryUsage(): NodeJS.MemoryUsage;
30
32
  printMemoryUsage(): void;
@@ -12,6 +12,7 @@ import { Handlebars } from './Handlebars.js';
12
12
  import { Cookies } from './Cookies.js';
13
13
  export class Application {
14
14
  constructor(config) {
15
+ this.initialized = false;
15
16
  this.server = null;
16
17
  this.listening = false;
17
18
  this.eventEmitter = new EventEmitter();
@@ -28,6 +29,9 @@ export class Application {
28
29
  }
29
30
  }
30
31
  async init() {
32
+ if (this.initialized) {
33
+ return;
34
+ }
31
35
  this.eventEmitter.setMaxListeners(10);
32
36
  try {
33
37
  await this.handlebars.loadHelpers('../Helpers.js');
@@ -63,6 +67,7 @@ export class Application {
63
67
  return '';
64
68
  }, this, true);
65
69
  await this.start();
70
+ this.initialized = true;
66
71
  }
67
72
  start() {
68
73
  return new Promise((resolve, reject) => {
@@ -136,6 +141,12 @@ export class Application {
136
141
  contentType(extension) {
137
142
  return mime.contentType(extension);
138
143
  }
144
+ registerPlugin(callback) {
145
+ if (this.initialized) {
146
+ console.warn('Plugin registered after app is initialized, some plugin features may not work.');
147
+ }
148
+ callback(this);
149
+ }
139
150
  async respondWithComponent(ctx, componentName, attributes, unwrap = true) {
140
151
  const component = this.components.getByName(componentName);
141
152
  if (component) {
@@ -1,7 +1,10 @@
1
1
  import { Document } from './Document.js';
2
2
  import { ComponentEntry, LooseObject } from '../Types.js';
3
3
  import { DOMNode } from './dom/DOMNode.js';
4
- export declare class Component {
4
+ import { EventEmitter } from '../EventEmitter.js';
5
+ export declare class Component<Events extends Record<string, any> = {
6
+ 'componentCreated': Component;
7
+ }> extends EventEmitter<Events> {
5
8
  id: string;
6
9
  name: string;
7
10
  document: Document;
@@ -20,8 +23,8 @@ export declare class Component {
20
23
  private initChildren;
21
24
  protected importedParentData(parentData: LooseObject): LooseObject;
22
25
  protected initAttributesData(domNode?: DOMNode): void;
23
- private attributePreffix;
26
+ private attributePrefix;
24
27
  private attributeDataType;
25
- private attributeUnpreffixed;
28
+ private attributeUnprefixed;
26
29
  protected fillData(data: LooseObject): void;
27
30
  }
@@ -1,8 +1,10 @@
1
1
  import { Document } from './Document.js';
2
2
  import { attributeValueFromString, attributeValueToString, objectEach, toCamelCase } from '../Util.js';
3
3
  import { DOMFragment } from './dom/DOMFragment.js';
4
- export class Component {
4
+ import { EventEmitter } from '../EventEmitter.js';
5
+ export class Component extends EventEmitter {
5
6
  constructor(name, node, parent, autoInit = true) {
7
+ super();
6
8
  this.children = [];
7
9
  this.path = [];
8
10
  this.attributesRaw = {};
@@ -44,7 +46,7 @@ export class Component {
44
46
  this.entry = null;
45
47
  }
46
48
  if (!isDocument) {
47
- this.document.application.emit('componentCreated', this);
49
+ this.document.emit('componentCreated', this);
48
50
  }
49
51
  }
50
52
  async init(html, data) {
@@ -184,7 +186,7 @@ export class Component {
184
186
  }
185
187
  for (let i = 0; i < domNode.attributes.length; i++) {
186
188
  const attrNameRaw = domNode.attributes[i].name;
187
- const attrNameUnprefixed = this.attributeUnpreffixed(attrNameRaw);
189
+ const attrNameUnprefixed = this.attributeUnprefixed(attrNameRaw);
188
190
  if (attrNameUnprefixed.indexOf('data-') === 0) {
189
191
  const attrDataType = this.attributeDataType(attrNameRaw);
190
192
  const dataDecoded = attributeValueFromString(domNode.attributes[i].value.toString());
@@ -218,7 +220,7 @@ export class Component {
218
220
  this.attributesRaw[attrNameRaw] = domNode.attributes[i].value;
219
221
  }
220
222
  }
221
- attributePreffix(attrName) {
223
+ attributePrefix(attrName) {
222
224
  const index = attrName.indexOf(':');
223
225
  if (index < 0) {
224
226
  return null;
@@ -226,7 +228,7 @@ export class Component {
226
228
  return attrName.substring(0, index);
227
229
  }
228
230
  attributeDataType(attrName) {
229
- const prefix = this.attributePreffix(attrName);
231
+ const prefix = this.attributePrefix(attrName);
230
232
  if (prefix === 'string' ||
231
233
  prefix === 'number' ||
232
234
  prefix === 'object' ||
@@ -235,7 +237,7 @@ export class Component {
235
237
  }
236
238
  return 'any';
237
239
  }
238
- attributeUnpreffixed(attrName) {
240
+ attributeUnprefixed(attrName) {
239
241
  const index = attrName.indexOf(':');
240
242
  if (index < 0) {
241
243
  return attrName;
@@ -1,4 +1,4 @@
1
- import { ComponentEntry, StructuredConfig } from '../Types';
1
+ import { ComponentEntry, StructuredConfig } from '../Types.js';
2
2
  import { Application } from './Application.js';
3
3
  export declare class Components {
4
4
  config: StructuredConfig;
@@ -3,7 +3,9 @@ import { Initializers, LooseObject, RequestContext } from '../../system/Types.js
3
3
  import { Application } from './Application.js';
4
4
  import { DocumentHead } from './DocumentHead.js';
5
5
  import { Component } from './Component.js';
6
- export declare class Document extends Component {
6
+ export declare class Document extends Component<{
7
+ 'componentCreated': Component;
8
+ }> {
7
9
  head: DocumentHead;
8
10
  language: string;
9
11
  application: Application;
@@ -1,4 +1,4 @@
1
- import { DocumentResource } from '../Types';
1
+ import { DocumentResource } from '../Types.js';
2
2
  export declare class DocumentHead {
3
3
  title: string;
4
4
  js: Array<DocumentResource>;
@@ -1,4 +1,4 @@
1
- import { FormValidationEntry, PostedDataDecoded, ValidationResult, ValidationRuleWithArguments, ValidatorErrorDecorator, ValidatorFunction } from '../Types';
1
+ import { FormValidationEntry, PostedDataDecoded, ValidationResult, ValidationRuleWithArguments, ValidatorErrorDecorator, ValidatorFunction } from '../Types.js';
2
2
  export declare class FormValidation {
3
3
  fieldRules: Array<FormValidationEntry>;
4
4
  singleError: boolean;