@joist/observable 2.0.0-alpha.0 → 2.0.0-alpha.12

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,21 +1,21 @@
1
1
  # Observable
2
2
 
3
3
  Observable in Joist means something slightly different then in something like RxJs.
4
- Marking a class with `@observable()` means that instances of that class will BE observable. This means you can watch for changes on select properties.s
4
+ Decorating a class with `@observable` means that instances of that class will BE observable. This means you can watch for changes on select properties.s
5
5
 
6
6
  #### Installation:
7
7
 
8
8
  ```BASH
9
- npm i @joist/observable
9
+ npm i @joist/observable@canary
10
10
  ```
11
11
 
12
12
  #### Example:
13
13
 
14
14
  ```TS
15
- import { observable, observer, OnChange, Changes } from '@joist/observable';
15
+ import { observable, observer, OnPropertyChanged, Changes } from '@joist/observable';
16
16
 
17
17
  @observable
18
- class State implements OnChange {
18
+ class State implements OnPropertyChanged {
19
19
  // Changes to these will trigger callback
20
20
  @observe todos: string[] = [];
21
21
  @observe userName?: string;
@@ -23,7 +23,7 @@ class State implements OnChange {
23
23
  // changes to this will not
24
24
  someValue: boolean = false;
25
25
 
26
- onChange(changes: Changes) {
26
+ onPropertyChanged(changes: Changes) {
27
27
  console.log(changes);
28
28
  // { todos: { value: ['Build Shit'], previousValue: [] }, userName: { value: 'Danny Blue', previousValue: undefined } }
29
29
  }
@@ -40,7 +40,7 @@ state.userName = 'Danny Blue'
40
40
  If you want to externally monitor your class for changes you can extend event target and dispatch events. (available in both node and the browser)
41
41
 
42
42
  ```TS
43
- import { observable, observer, OnChange, Changes } from '@joist/observable';
43
+ import { observable, observer, OnPropertyChanged, Changes } from '@joist/observable';
44
44
 
45
45
  class StateChangeEvent extends Event {
46
46
  consetructor(public changes: Changes) {
@@ -49,7 +49,7 @@ class StateChangeEvent extends Event {
49
49
  }
50
50
 
51
51
  @observable
52
- class State extends EventTarget implements OnChange {
52
+ class State extends EventTarget implements OnPropertyChanged {
53
53
  // Changes to these will trigger callback
54
54
  @observe todos: string[] = [];
55
55
  @observe userName?: string;
@@ -57,8 +57,8 @@ class State extends EventTarget implements OnChange {
57
57
  // changes to this will not
58
58
  someValue: boolean = false;
59
59
 
60
- onChange(changes: Changes) {
61
- this.dispatchEvent(new StateChangeEvent());
60
+ onPropertyChanged(changes: Changes) {
61
+ this.dispatchEvent(new StateChangeEvent(changes));
62
62
  }
63
63
  }
64
64
 
@@ -71,3 +71,31 @@ state.addEventListener('statechange', (e) => {
71
71
  state.todos = [...state.todos, 'Build Shit'];
72
72
  state.userName = 'Danny Blue'
73
73
  ```
74
+
75
+ #### Attributes
76
+
77
+ If you are using @observable with custom elements it is very likely that you will want to read from and write to attributes.
78
+ Joist accounts for this by giving you an `@attr` decorator.
79
+
80
+ ```TS
81
+ import { observable, observe, attr} from '@joist/observable';
82
+
83
+ @observable
84
+ class TestElement extends HTMLElement {
85
+ // reads as a string and writes directly to the name attribute
86
+ @observe @attr name = '';
87
+
88
+ // reads as a number and writes back a string
89
+ @observe
90
+ @attr({ read: Number })
91
+ count: number = 0;
92
+
93
+ // reads as a Date object and writes back a string
94
+ @observe
95
+ @attr({
96
+ read: (val: string) => new Date(val),
97
+ write: (val: Date) => val.toString()
98
+ })
99
+ count: number = 0;
100
+ }
101
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joist/observable",
3
- "version": "2.0.0-alpha.0",
3
+ "version": "2.0.0-alpha.12",
4
4
  "main": "./target/build/lib.js",
5
5
  "module": "./target/build/lib.js",
6
6
  "exports": {
@@ -12,19 +12,20 @@
12
12
  "target/build"
13
13
  ],
14
14
  "sideEffects": false,
15
- "description": "Create objects with observable properties",
15
+ "description": "Dependency Injection in ~800 bytes",
16
16
  "repository": {
17
17
  "type": "git",
18
- "url": "git+https://github.com/joist-framework/joist.git"
18
+ "url": "git+https://github.com/deebloo/joist.git"
19
19
  },
20
20
  "keywords": [
21
21
  "TypeScript",
22
- "Observable"
22
+ "DI",
23
+ "Dependency Injection"
23
24
  ],
24
25
  "author": "deebloo",
25
26
  "license": "MIT",
26
27
  "bugs": {
27
- "url": "https://github.com/joist-framework/joist/issues"
28
+ "url": "https://github.com/deebloo/joist/issues"
28
29
  },
29
30
  "publishConfig": {
30
31
  "access": "public"
@@ -33,5 +34,5 @@
33
34
  "test": "tsc -p tsconfig.test.json && wtr --config ../../wtr.config.mjs --port 8002",
34
35
  "build": "tsc -p tsconfig.build.json"
35
36
  },
36
- "gitHead": "8078ed9c1005afd279b1ccb2c7b7856dd563bec7"
37
+ "gitHead": "875d5d0c7b5e42f023567bfcbe1d7d6178ab438e"
37
38
  }
@@ -0,0 +1,8 @@
1
+ export declare function getObservableAttributes(c: typeof HTMLElement): Array<string>;
2
+ export declare function getAttributeParsers<T extends typeof HTMLElement>(c: T): Record<string, AttributeParser>;
3
+ export interface AttributeParser {
4
+ read(val: string): any;
5
+ write(val: unknown): string;
6
+ }
7
+ export declare function attr<T extends HTMLElement>(p: Partial<AttributeParser>): (t: T, key: string) => void;
8
+ export declare function attr<T extends HTMLElement>(t: T, key: string): void;
@@ -0,0 +1,47 @@
1
+ export function getObservableAttributes(c) {
2
+ return Reflect.get(c, 'observedAttributes') || [];
3
+ }
4
+ function defaultRead(val) {
5
+ // if a boolean assume such
6
+ if (val === 'true' || val === 'false') {
7
+ return val === 'true';
8
+ }
9
+ return val;
10
+ }
11
+ export function getAttributeParsers(c) {
12
+ const parsers = Reflect.get(c, 'attributeParsers') || {};
13
+ return parsers;
14
+ }
15
+ export function attr(targetOrParser, key) {
16
+ if (targetOrParser instanceof HTMLElement) {
17
+ return defineAttribute(targetOrParser, key);
18
+ }
19
+ return (target, key) => {
20
+ const parser = targetOrParser;
21
+ defineAttribute(target, key);
22
+ const attributeParsers = Reflect.get(target.constructor, 'attributeParsers');
23
+ attributeParsers[key].read = parser.read || attributeParsers[key].read;
24
+ attributeParsers[key].write = parser.write || attributeParsers[key].write;
25
+ Reflect.set(target.constructor, 'attributeParsers', attributeParsers);
26
+ return void 0;
27
+ };
28
+ }
29
+ function defineAttribute(target, key) {
30
+ const observedAttributes = Reflect.get(target.constructor, 'observedAttributes');
31
+ if (observedAttributes) {
32
+ observedAttributes.push(key);
33
+ }
34
+ else {
35
+ Reflect.set(target.constructor, 'observedAttributes', [key]);
36
+ }
37
+ const attributeParsers = Reflect.get(target.constructor, 'attributeParsers');
38
+ if (attributeParsers) {
39
+ attributeParsers[key] = { read: defaultRead, write: String };
40
+ }
41
+ else {
42
+ const attributeParsers = {};
43
+ attributeParsers[key] = { read: defaultRead, write: String };
44
+ Reflect.set(target.constructor, 'attributeParsers', attributeParsers);
45
+ }
46
+ return void 0;
47
+ }
@@ -5,23 +5,29 @@ export declare class Change<T = any> {
5
5
  constructor(value: T, previousValue: T | undefined, firstChange: boolean);
6
6
  }
7
7
  export declare type Changes = Record<string | symbol, Change>;
8
- export interface OnChange {
9
- onChange(changes: Changes): void;
8
+ export interface OnPropertyChanged {
9
+ onPropertyChanged(changes: Changes): void;
10
10
  }
11
- export declare function readPropertyDefs(c: any): Record<string | symbol, {}>;
11
+ export declare function getObservableProperties(c: any): Array<string | symbol>;
12
12
  export interface ObservableBase {
13
13
  propChanges: Changes;
14
14
  propChange: Promise<void> | null;
15
15
  initializedChanges: Set<string | symbol>;
16
16
  definePropChange(key: string | symbol, propChange: Change): Promise<void>;
17
+ onPropertyChanged?(changes: Changes): void;
17
18
  }
18
19
  export declare function observe(target: any, key: string): void;
19
- export declare function observable<T extends new (...args: any[]) => any>(CustomElement: T): {
20
+ export declare function observable<T extends new (...args: any[]) => any>(Base: T): {
20
21
  new (...args: any[]): {
21
22
  [x: string]: any;
22
23
  propChanges: Changes;
23
24
  propChange: Promise<void> | null;
24
25
  initializedChanges: Set<string | symbol>;
25
- definePropChange(key: string | symbol, propChange: Change): Promise<void>;
26
+ definePropChange: typeof definePropChange;
27
+ connectedCallback(this: HTMLElement & any): void;
28
+ attributeChangedCallback(this: HTMLElement & any, name: string, oldVal: string, newVal: string): void;
29
+ onPropertyChanged(changes: Changes): void;
26
30
  };
27
31
  } & T;
32
+ declare function definePropChange(this: ObservableBase, key: string | symbol, propChange: Change): Promise<void>;
33
+ export {};
@@ -1,79 +1,124 @@
1
+ import { getAttributeParsers, getObservableAttributes } from './attribute';
1
2
  export class Change {
2
- value;
3
- previousValue;
4
- firstChange;
5
3
  constructor(value, previousValue, firstChange) {
6
4
  this.value = value;
7
5
  this.previousValue = previousValue;
8
6
  this.firstChange = firstChange;
9
7
  }
10
8
  }
11
- export function readPropertyDefs(c) {
12
- return c.properties || c.prototype.properties || {};
9
+ const PROPERTY_KEY = 'observedProperties';
10
+ export function getObservableProperties(c) {
11
+ return c[PROPERTY_KEY] || [];
13
12
  }
14
- const PROPERTY_KEY = 'properties';
15
13
  export function observe(target, key) {
16
- target[PROPERTY_KEY] = target[PROPERTY_KEY] || {};
17
- target[PROPERTY_KEY][key] = {};
14
+ target.constructor[PROPERTY_KEY] = target.constructor[PROPERTY_KEY] || [];
15
+ target.constructor[PROPERTY_KEY].push(key);
18
16
  }
19
- export function observable(CustomElement) {
20
- const defs = readPropertyDefs(CustomElement);
21
- const props = createPropertyDescripors(defs);
22
- return class ObservableElement extends CustomElement {
23
- propChanges = {};
24
- propChange = null;
25
- initializedChanges = new Set();
17
+ export function observable(Base) {
18
+ const properties = getObservableProperties(Base);
19
+ const attributes = getObservableAttributes(Base);
20
+ const parsers = getAttributeParsers(Base);
21
+ const descriptors = createPropertyDescripors(properties);
22
+ return class Observable extends Base {
26
23
  constructor(...args) {
27
24
  super(...args);
28
- for (let def in defs) {
29
- Reflect.set(this, createPrivateKey(def), Reflect.get(this, def));
25
+ this.propChanges = {};
26
+ this.propChange = null;
27
+ this.initializedChanges = new Set();
28
+ this.definePropChange = definePropChange;
29
+ for (let prop in descriptors) {
30
+ Reflect.set(this, createPrivateKey(prop), Reflect.get(this, prop));
30
31
  }
31
- Object.defineProperties(this, props);
32
+ Object.defineProperties(this, descriptors);
32
33
  }
33
- definePropChange(key, propChange) {
34
- if (!this.propChanges[key]) {
35
- this.propChanges[key] = propChange;
36
- }
37
- this.propChanges[key].value = propChange.value;
38
- if (!this.propChange) {
39
- // If there is no previous change defined set it up
40
- this.propChange = Promise.resolve().then(() => {
41
- // run onPropChanges here. This makes sure we capture all changes
42
- // keep track of whether or not this is the first time a given property has changes
43
- for (let change in this.propChanges) {
44
- this.propChanges[change].firstChange = !this.initializedChanges.has(change);
45
- this.initializedChanges.add(change);
34
+ connectedCallback() {
35
+ attributes.forEach((key) => {
36
+ const { write } = parsers[key];
37
+ const val = this.getAttribute(key);
38
+ if (val === null) {
39
+ const propVal = Reflect.get(this, key);
40
+ const parsedVal = write(propVal);
41
+ if (propVal !== undefined &&
42
+ propVal !== null &&
43
+ propVal !== '' &&
44
+ propVal !== parsedVal) {
45
+ this.setAttribute(key, parsedVal);
46
46
  }
47
- if (this.onChange) {
48
- this.onChange(this.propChanges);
47
+ }
48
+ });
49
+ if (super.connectedCallback) {
50
+ super.connectedCallback();
51
+ }
52
+ }
53
+ attributeChangedCallback(name, oldVal, newVal) {
54
+ const { read } = parsers[name];
55
+ Reflect.set(this, name, read(newVal));
56
+ if (super.attributeChangedCallback) {
57
+ super.attributeChangedCallback(name, oldVal, newVal);
58
+ }
59
+ }
60
+ onPropertyChanged(changes) {
61
+ if (this instanceof HTMLElement) {
62
+ for (let change in changes) {
63
+ if (attributes.includes(change)) {
64
+ const { write } = parsers[change];
65
+ const value = write(changes[change].value);
66
+ if (value !== this.getAttribute(change)) {
67
+ this.setAttribute(change, write(changes[change].value));
68
+ }
49
69
  }
50
- // reset for next time
51
- this.propChanges = {};
52
- this.propChange = null;
53
- });
70
+ }
71
+ }
72
+ if (super.onPropertyChanged) {
73
+ super.onPropertyChanged(changes);
54
74
  }
55
- return this.propChange;
56
75
  }
57
76
  };
58
77
  }
59
78
  function createPrivateKey(key) {
60
- return `__${key}`;
79
+ return `__${key.toString()}`;
61
80
  }
62
- function createPropertyDescripors(defs) {
63
- const props = {};
64
- for (let def in defs) {
65
- const privateKey = createPrivateKey(def);
66
- props[def] = {
81
+ function createPropertyDescripors(props) {
82
+ const descriptors = {};
83
+ for (let i = 0; i < props.length; i++) {
84
+ const prop = props[i];
85
+ const privateKey = createPrivateKey(prop);
86
+ descriptors[prop] = {
67
87
  set(val) {
68
88
  const prevVal = Reflect.get(this, privateKey);
69
- this.definePropChange(def, new Change(val, prevVal, true));
70
- Reflect.set(this, privateKey, val);
89
+ if (prevVal !== val) {
90
+ this.definePropChange(prop, new Change(val, prevVal, true));
91
+ }
92
+ return Reflect.set(this, privateKey, val);
71
93
  },
72
94
  get() {
73
95
  return Reflect.get(this, privateKey);
74
96
  },
75
97
  };
76
98
  }
77
- return props;
99
+ return descriptors;
100
+ }
101
+ function definePropChange(key, propChange) {
102
+ if (!this.propChanges[key]) {
103
+ this.propChanges[key] = propChange;
104
+ }
105
+ this.propChanges[key].value = propChange.value;
106
+ if (!this.propChange) {
107
+ // If there is no previous change defined set it up
108
+ this.propChange = Promise.resolve().then(() => {
109
+ // run onPropChanges here. This makes sure we capture all changes
110
+ // keep track of whether or not this is the first time a given property has changes
111
+ for (let change in this.propChanges) {
112
+ this.propChanges[change].firstChange = !this.initializedChanges.has(change);
113
+ this.initializedChanges.add(change);
114
+ }
115
+ if (this.onPropertyChanged) {
116
+ this.onPropertyChanged(this.propChanges);
117
+ }
118
+ // reset for next time
119
+ this.propChanges = {};
120
+ this.propChange = null;
121
+ });
122
+ }
123
+ return this.propChange;
78
124
  }
79
- //# sourceMappingURL=observable.js.map
@@ -1 +1,2 @@
1
- export { observable, Change, OnChange, observe, Changes } from './lib/observable';
1
+ export { observable, Change, OnPropertyChanged, observe, Changes } from './lib/observable';
2
+ export { attr } from './lib/attribute';
@@ -1,2 +1,2 @@
1
1
  export { observable, Change, observe } from './lib/observable';
2
- //# sourceMappingURL=lib.js.map
2
+ export { attr } from './lib/attribute';
@@ -1 +0,0 @@
1
- {"version":3,"file":"observable.js","sourceRoot":"","s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