apprun 3.35.0 → 3.36.1

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 (75) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +134 -16
  3. package/WHATSNEW.md +28 -12
  4. package/apprun-book.jpg +0 -0
  5. package/apprun.d.ts +9 -6
  6. package/cli/app.js +29 -0
  7. package/cli/index.html +13 -0
  8. package/{apprun-cli.js → cli/index.js} +8 -14
  9. package/dist/apprun-dev-tools.js +1 -2
  10. package/dist/apprun-dev-tools.js.map +1 -1
  11. package/dist/apprun-html.esm.js +7 -7
  12. package/dist/apprun-html.esm.js.map +1 -1
  13. package/dist/apprun-html.js +1 -1
  14. package/dist/apprun-html.js.map +1 -1
  15. package/dist/apprun-play-html.esm.js +7 -7
  16. package/dist/apprun-play-html.esm.js.map +1 -1
  17. package/dist/apprun-play.js +1 -1
  18. package/dist/apprun-play.js.map +1 -1
  19. package/dist/apprun.esm.js +1 -1
  20. package/dist/apprun.esm.js.map +1 -1
  21. package/dist/apprun.js +1 -1
  22. package/dist/apprun.js.map +1 -1
  23. package/esm/app.js +60 -12
  24. package/esm/app.js.map +1 -1
  25. package/esm/apprun-dev-tools.js +1 -7
  26. package/esm/apprun-dev-tools.js.map +1 -1
  27. package/esm/apprun-html.js +8 -4
  28. package/esm/apprun-html.js.map +1 -1
  29. package/esm/apprun.js +81 -17
  30. package/esm/apprun.js.map +1 -1
  31. package/esm/component.js +60 -19
  32. package/esm/component.js.map +1 -1
  33. package/esm/decorator.js +22 -5
  34. package/esm/decorator.js.map +1 -1
  35. package/esm/directive.js +64 -13
  36. package/esm/directive.js.map +1 -1
  37. package/esm/router.js +263 -22
  38. package/esm/router.js.map +1 -1
  39. package/esm/type-utils.js +91 -0
  40. package/esm/type-utils.js.map +1 -0
  41. package/esm/types.js +32 -11
  42. package/esm/types.js.map +1 -1
  43. package/esm/vdom-my-new.js +329 -0
  44. package/esm/vdom-my-new.js.map +1 -0
  45. package/esm/vdom-my-prop-attr.js +227 -0
  46. package/esm/vdom-my-prop-attr.js.map +1 -0
  47. package/esm/vdom-my.js +77 -88
  48. package/esm/vdom-my.js.map +1 -1
  49. package/esm/version.js +15 -0
  50. package/esm/version.js.map +1 -0
  51. package/esm/web-component.js +30 -10
  52. package/esm/web-component.js.map +1 -1
  53. package/index.html +1 -1
  54. package/jest.config.js +3 -8
  55. package/jest.setup.js +29 -3
  56. package/jsx-runtime.js +1 -1
  57. package/jsx-runtime.js.map +1 -1
  58. package/package.json +7 -7
  59. package/src/app.ts +58 -12
  60. package/src/apprun-dev-tools.tsx +1 -7
  61. package/src/apprun-html.ts +8 -4
  62. package/src/apprun.ts +97 -20
  63. package/src/component.ts +62 -20
  64. package/src/decorator.ts +23 -6
  65. package/src/directive.ts +64 -13
  66. package/src/router.ts +282 -20
  67. package/src/type-utils.ts +130 -0
  68. package/src/types.ts +33 -12
  69. package/src/vdom-my-new.ts +311 -0
  70. package/src/vdom-my-prop-attr.ts +241 -0
  71. package/src/vdom-my.ts +82 -71
  72. package/src/version.ts +16 -0
  73. package/src/web-component.ts +31 -11
  74. package/cli/export.js +0 -92
  75. package/cli/import.js +0 -68
package/src/vdom-my.ts CHANGED
@@ -1,13 +1,56 @@
1
+ /** * VDOM Implementation for AppRun
2
+ *
3
+ * Notes for AppRun’s key prop
4
+ * Use the key prop only if you need to preserve browser-side DOM state (such as cursor
5
+ * position in an <input>, focus, or maintaining state in inline components).
6
+ *
7
+ * For most use cases, especially with stateless or purely data-driven UIs, key is not
8
+ * needed and may decrease performance by forcing DOM moves.
9
+ *
10
+ * AppRun aggressively updates DOM to match your vdom, so DOM node preservation is
11
+ * only valuable when you intentionally depend on browser-managed state.
12
+ *
13
+ * | Use Case | Should I use `key`? | Why |
14
+ * | ----------------------------- | ------------------- | --------------------- |
15
+ * | Preserve input cursor/focus | ✅ Yes | Keeps browser state |
16
+ * | Inline stateful component | ✅ Yes | Preserves component |
17
+ * | Regular data list (stateless) | 🚫 No | Unnecessary DOM moves |
18
+ * | Purely visual updates | 🚫 No | No state to preserve |
19
+ *
20
+ * Features:
21
+ * - Virtual DOM rendering and diffing for efficient DOM updates
22
+ * - JSX Fragment support for both Babel and TypeScript
23
+ * - Element creation with props, children, and event handling
24
+ * - SVG element support with proper namespace handling
25
+ * - Component lifecycle management and caching
26
+ * - Keyed element optimization with automatic cleanup for memory management
27
+ * - Safe HTML insertion and text node creation
28
+ * - Directive processing integration
29
+ *
30
+ * Implementation:
31
+ * - Uses plain JavaScript object for keyCache instead of Map for better performance
32
+ * - Implements automatic cleanup of disconnected elements from keyCache
33
+ * - Supports both string and function-based tags
34
+ * - Handles component mounting and state management
35
+ * - Optimized children updating with minimal DOM operations
36
+ * - Memory-efficient caching with configurable thresholds (500 ops, 1000 max size)
37
+ *
38
+ * Recent Changes:
39
+ * - 2025-07-15: Converted keyCache from Map to plain object ({}) for improved performance
40
+ * - Updated cleanup functions to use object property deletion instead of Map methods
41
+ * - Enhanced memory management with automatic cleanup of disconnected elements
42
+ * - Added comprehensive key prop usage documentation and guidelines
43
+ */
44
+
1
45
  import { VDOM, VNode } from './types';
2
46
  import directive from './directive';
47
+ import { updateProps } from './vdom-my-prop-attr';
3
48
  export type Element = any; //HTMLElement | SVGSVGElement | SVGElement;
4
49
 
5
50
  export function Fragment(props, ...children): any[] {
6
51
  return collect(children);
7
52
  }
8
53
 
9
- const ATTR_PROPS = '_props';
10
-
11
54
  function collect(children) {
12
55
  const ch = [];
13
56
  const push = (c) => {
@@ -25,6 +68,30 @@ function collect(children) {
25
68
  return ch;
26
69
  }
27
70
 
71
+ const keyCache: { [key: string]: Element } = {};
72
+ let cleanupCounter = 0;
73
+ const CLEANUP_THRESHOLD = 500; // Cleanup every 500 operations
74
+ const MAX_CACHE_SIZE = 1000;
75
+
76
+ // Lightweight cleanup function - only runs when needed
77
+ function cleanupKeyCache() {
78
+ if (Object.keys(keyCache).length <= MAX_CACHE_SIZE) return; // Skip if under limit
79
+
80
+ for (const [key, element] of Object.entries(keyCache)) {
81
+ if (!element.isConnected) {
82
+ delete keyCache[key];
83
+ }
84
+ }
85
+ }
86
+
87
+ // Export cleanup function for manual cleanup if needed
88
+ export function clearKeyCache() {
89
+ for (const key in keyCache) {
90
+ delete keyCache[key];
91
+ }
92
+ cleanupCounter = 0;
93
+ }
94
+
28
95
  export function createElement(tag: string | Function | [], props?: {}, ...children) {
29
96
  const ch = collect(children);
30
97
  if (typeof tag === 'string') return { tag, props, children: ch };
@@ -35,8 +102,6 @@ export function createElement(tag: string | Function | [], props?: {}, ...childr
35
102
  else throw new Error(`Unknown tag in vdom ${tag}`);
36
103
  };
37
104
 
38
- const keyCache = new WeakMap();
39
-
40
105
  export const updateElement = (element: Element | string, nodes: VDOM, component = {}) => {
41
106
  // tslint:disable-next-line
42
107
  if (nodes == null || nodes === false) return;
@@ -67,15 +132,14 @@ function same(el: Element, node: VNode) {
67
132
  }
68
133
 
69
134
  function update(element: Element, node: VNode, isSvg: boolean) {
70
- if (node['_op'] === 3) return;
71
135
  // console.assert(!!element);
72
136
  isSvg = isSvg || node.tag === "svg";
73
137
  if (!same(element, node)) {
74
138
  element.parentNode.replaceChild(create(node, isSvg), element);
75
139
  return;
76
140
  }
77
- !(node['_op'] & 2) && updateChildren(element, node.children, isSvg);
78
- !(node['_op'] & 1) && updateProps(element, node.props, isSvg);
141
+ updateChildren(element, node.children, isSvg);
142
+ updateProps(element, node.props, isSvg);
79
143
  }
80
144
 
81
145
  function updateChildren(element, children, isSvg: boolean) {
@@ -84,7 +148,6 @@ function updateChildren(element, children, isSvg: boolean) {
84
148
  const len = Math.min(old_len, new_len);
85
149
  for (let i = 0; i < len; i++) {
86
150
  const child = children[i];
87
- if (child['_op'] === 3) continue;
88
151
  const el = element.childNodes[i];
89
152
  if (typeof child === 'string') {
90
153
  if (el.textContent !== child) {
@@ -105,9 +168,9 @@ function updateChildren(element, children, isSvg: boolean) {
105
168
  // console.log(el.key, key);
106
169
  const old = keyCache[key];
107
170
  if (old) {
108
- const temp = old.nextSibling;
171
+ // const temp = old.nextSibling;
109
172
  element.insertBefore(old, el);
110
- temp ? element.insertBefore(el, temp) : element.appendChild(el);
173
+ // temp ? element.insertBefore(el, temp) : element.appendChild(el);
111
174
  update(element.childNodes[i], child, isSvg);
112
175
  } else {
113
176
  element.replaceChild(create(child, isSvg), el);
@@ -146,7 +209,7 @@ function createText(node) {
146
209
  div.insertAdjacentHTML('afterbegin', node.substring(6))
147
210
  return div;
148
211
  } else {
149
- return document.createTextNode(node??'');
212
+ return document.createTextNode(node ?? '');
150
213
  }
151
214
  }
152
215
 
@@ -162,70 +225,18 @@ function create(node: VNode | string | HTMLElement | SVGElement, isSvg: boolean)
162
225
 
163
226
  updateProps(element, node.props, isSvg);
164
227
  if (node.children) node.children.forEach(child => element.appendChild(create(child, isSvg)));
165
- return element
166
- }
167
-
168
- function mergeProps(oldProps: {}, newProps: {}): {} {
169
- newProps['class'] = newProps['class'] || newProps['className'];
170
- delete newProps['className'];
171
- const props = {};
172
- if (oldProps) Object.keys(oldProps).forEach(p => props[p] = null);
173
- if (newProps) Object.keys(newProps).forEach(p => props[p] = newProps[p]);
174
- return props;
175
- }
176
228
 
177
- export function updateProps(element: Element, props: {}, isSvg) {
178
- // console.assert(!!element);
179
- const cached = element[ATTR_PROPS] || {};
180
- props = mergeProps(cached, props || {});
181
- element[ATTR_PROPS] = props;
229
+ if (node.props && (node.props as any).key !== undefined) {
230
+ (element as any).key = (node.props as any).key;
231
+ keyCache[(node.props as any).key] = element;
182
232
 
183
- for (const name in props) {
184
- const value = props[name];
185
- // if (cached[name] === value) continue;
186
- // console.log('updateProps', name, value);
187
- if (name.startsWith('data-')) {
188
- const dname = name.substring(5);
189
- const cname = dname.replace(/-(\w)/g, (match) => match[1].toUpperCase());
190
- if (element.dataset[cname] !== value) {
191
- if (value || value === "") element.dataset[cname] = value;
192
- else delete element.dataset[cname];
193
- }
194
- } else if (name === 'style') {
195
- if (element.style.cssText) element.style.cssText = '';
196
- if (typeof value === 'string') element.style.cssText = value;
197
- else {
198
- for (const s in value) {
199
- if (element.style[s] !== value[s]) element.style[s] = value[s];
200
- }
201
- }
202
- } else if (name.startsWith('xlink')) {
203
- const xname = name.replace('xlink', '').toLowerCase();
204
- if (value == null || value === false) {
205
- element.removeAttributeNS('http://www.w3.org/1999/xlink', xname);
206
- } else {
207
- element.setAttributeNS('http://www.w3.org/1999/xlink', xname, value);
208
- }
209
- } else if (name.startsWith('on')) {
210
- if (!value || typeof value === 'function') {
211
- element[name] = value;
212
- } else if (typeof value === 'string') {
213
- if (value) element.setAttribute(name, value);
214
- else element.removeAttribute(name);
215
- }
216
- } else if (/^id$|^class$|^list$|^readonly$|^contenteditable$|^role|-|^for$/g.test(name) || isSvg) {
217
- if (element.getAttribute(name) !== value) {
218
- if (value) element.setAttribute(name, value);
219
- else element.removeAttribute(name);
220
- }
221
- } else if (element[name] !== value) {
222
- element[name] = value;
233
+ // Lightweight cleanup - only when counter reaches threshold
234
+ if (++cleanupCounter >= CLEANUP_THRESHOLD) {
235
+ cleanupKeyCache();
236
+ cleanupCounter = 0;
223
237
  }
224
- if (name === 'key' && value) keyCache[value] = element;
225
- }
226
- if (props && typeof props['ref'] === 'function') {
227
- window.requestAnimationFrame(() => props['ref'](element));
228
238
  }
239
+ return element
229
240
  }
230
241
 
231
242
  function render_component(node, parent, idx) {
package/src/version.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Version Management Utility
3
+ *
4
+ * Single source of truth for AppRun version information.
5
+ * This file ensures version consistency across all modules.
6
+ *
7
+ * The version is derived from package.json and should be updated
8
+ * only when the package version changes.
9
+ */
10
+
11
+ // Import version from package.json to maintain single source of truth
12
+ // This version string is used across the framework
13
+ export const APPRUN_VERSION = '3.36.1';
14
+
15
+ // Version string with prefix for global tracking
16
+ export const APPRUN_VERSION_GLOBAL = `AppRun-${APPRUN_VERSION}`;
@@ -4,30 +4,50 @@
4
4
  * This file enables using AppRun components as Web Components:
5
5
  * 1. Custom Element Creation
6
6
  * - Converts AppRun components to custom elements
7
- * - Handles lifecycle (connected, disconnected, etc)
8
- * - Manages shadow DOM and light DOM rendering
7
+ * - Handles lifecycle (connected, disconnected, attributeChanged)
8
+ * - Manages shadow DOM and light DOM rendering options
9
+ * - Automatic element registration with customElements.define()
9
10
  *
10
11
  * 2. Property/Attribute Sync
11
- * - Observes attribute changes
12
- * - Updates component state automatically
13
- * - Handles camelCase/kebab-case conversion
14
- * - Supports complex property types
12
+ * - Observes attribute changes with attributeChangedCallback
13
+ * - Updates component state automatically on changes
14
+ * - Handles camelCase/kebab-case conversion automatically
15
+ * - Supports complex property types and JSON parsing
16
+ * - Two-way data binding between attributes and state
15
17
  *
16
18
  * 3. Event Handling
17
19
  * - Proxies events between component and element
18
- * - Supports both global and local events
19
- * - Maintains proper event bubbling
20
+ * - Supports both global and local event systems
21
+ * - Maintains proper event bubbling and capturing
22
+ * - Custom event dispatching for component communication
20
23
  *
24
+ * Features:
25
+ * - Shadow DOM encapsulation support
26
+ * - Attribute observation and change detection
27
+ * - Lifecycle management and cleanup
28
+ * - Property reflection to attributes
29
+ * - Event proxy system
30
+ * - Flexible rendering options
31
+ *
32
+ * Type Safety Improvements (v3.35.1):
33
+ * - Enhanced custom element options typing
34
+ * - Better lifecycle method signatures
35
+ * - Improved attribute/property type safety
36
+ * - Safer DOM manipulation with null checks
37
+ *
21
38
  * Usage:
22
39
  * ```ts
23
40
  * // Register web component
24
- * @customElement('my-element')
41
+ * @customElement('my-element', {
42
+ * shadow: true,
43
+ * observedAttributes: ['name', 'value']
44
+ * })
25
45
  * class MyComponent extends Component {
26
46
  * // Regular AppRun component code
27
47
  * }
28
48
  *
29
49
  * // Use in HTML
30
- * <my-element name="value"></my-element>
50
+ * <my-element name="value" data-prop="complex"></my-element>
31
51
  * ```
32
52
  */
33
53
 
@@ -71,7 +91,7 @@ export const customElement = (componentClass, options: CustomElementOptions = {}
71
91
  }
72
92
  return map
73
93
  }, {})
74
- this._attrMap = (name: string) : string => attrMap[name] || name
94
+ this._attrMap = (name: string): string => attrMap[name] || name
75
95
 
76
96
  const props = {};
77
97
  Array.from(this.attributes).forEach(item => props[this._attrMap(item.name)] = item.value);
package/cli/export.js DELETED
@@ -1,92 +0,0 @@
1
- import { exec } from 'child_process';
2
- import yaml from 'js-yaml';
3
- import { unlinkSync } from 'fs';
4
-
5
- function replacer(key, value) {
6
- if (typeof value === 'function') return value.toString();
7
- return ['', null].includes(value) || (typeof value === 'object' && (value.length === 0 || Object.keys(value).length === 0)) ? undefined : value;
8
- }
9
-
10
- function createProxy(obj) {
11
- const handler = {
12
- get(target, property, receiver) {
13
-
14
- // Get the property value
15
- const value = Reflect.get(target, property, receiver);
16
-
17
- // If the value is an object (including arrays), proxy it
18
- if (typeof value === 'object' && value !== null) {
19
- if (Array.isArray(value)) {
20
- // Proxy each element of the array if it's an object
21
- return value.map(item => createProxy(item));
22
- } else {
23
- // Recursively proxy the object
24
- return createProxy(value);
25
- }
26
- }
27
-
28
- return `{${property}}`
29
- },
30
-
31
- };
32
-
33
- return Array.isArray(obj) ?
34
- obj.map(item => createProxy(item)) : new Proxy(obj, handler);
35
- }
36
-
37
- function getVDOM(component) {
38
- let view;
39
- if (typeof component.state === 'object') {
40
- const proxy = createProxy(component.state);
41
- view = component.view(proxy);
42
- } else {
43
- view = component.view(component.state);
44
- }
45
- return view;
46
- }
47
-
48
- export default function export_yaml(fn) {
49
-
50
- const tmp = process.cwd() + '/_tmp.js';
51
- exec(`npx esbuild ${fn} --outfile=${tmp} --format=esm --bundle`, (error, stdout, stderr) => {
52
- if (error) {
53
- console.error(`exec error: ${error}`);
54
- return;
55
- }
56
-
57
- import(tmp).then((m) => {
58
-
59
- const defaul_export = m.default
60
- let component;
61
- if (typeof defaul_export === 'function' &&
62
- /^class\s/.test(Function.prototype.toString.call(defaul_export))) {
63
- component = new m.default();
64
- component = component.mount();
65
- } else if (typeof defaul_export === 'function') {
66
- component = defaul_export();
67
- } else {
68
- component = defaul_export;
69
- }
70
-
71
- const vdom = getVDOM(component);
72
- const events = component['_actions'].map(a => a.name);
73
-
74
- const component_def = {
75
- name: component.constructor.name,
76
- file: fn,
77
- state: component.state,
78
- view: vdom,
79
- actions: events,
80
- update: component.update,
81
- };
82
-
83
- const yaml_def = yaml.dump(component_def, { replacer });
84
- console.log(yaml_def);
85
-
86
- unlinkSync(tmp);
87
- });
88
- });
89
- }
90
-
91
-
92
-
package/cli/import.js DELETED
@@ -1,68 +0,0 @@
1
- import ymal from 'js-yaml';
2
- import { readFileSync } from 'fs';
3
-
4
- function getProp(prop) {
5
- if (typeof prop === 'object') {
6
- return Object.keys(prop).map(name => `${name}:${prop[name]}`).join(';');
7
- }
8
- else return prop.toString();
9
- }
10
-
11
- function toProps(props) {
12
- return Object.keys(props)
13
- .map(name => ` ${name === 'className' ? 'class' : name}="${getProp(props[name])}"`)
14
- .join('');
15
- }
16
-
17
- function toHTMLArray(nodes) {
18
- return nodes.map(node => toHTML(node)).join('');
19
- }
20
-
21
- function toHTML(vdom) {
22
- if (!vdom) return '';
23
- if (Array.isArray(vdom)) return toHTMLArray(vdom)
24
- if (vdom.tag) {
25
- const props = vdom.props ? toProps(vdom.props) : '';
26
- const children = vdom.children ? toHTMLArray(vdom.children) : '';
27
- return `<${vdom.tag}${props}>${children}</${vdom.tag}>`;
28
- }
29
- if (typeof vdom === 'object') return JSON.stringify(vdom);
30
- else {
31
- const html = vdom.toString();
32
- return html.startsWith('_html:') ? html.substring(6) : html;
33
- }
34
- }
35
-
36
- export default function import_yaml(fn) {
37
-
38
- const def = ymal.load(readFileSync(fn, 'utf8'))
39
-
40
- const { name, state, view, update } = def;
41
-
42
- const jsx = toHTML(view);
43
-
44
- // const update_text = JSON.stringify(update, null, 2)
45
- // .replace(/\\n/g, '\n');
46
-
47
- const update_text =
48
- Object.keys(update).map(key => `
49
- "${key}" : ${update[key].replace(/\\n/g, '\n')}`).join(',\n'
50
- );
51
-
52
- const component = `
53
- import { app, Component } from 'apprun';
54
-
55
- class ${name} extends Component {
56
-
57
- state = ${JSON.stringify(state)};
58
-
59
- view = ${jsx};
60
-
61
- update = {
62
- ${update_text}
63
- };
64
- };
65
- `;
66
-
67
- console.log(component);
68
- }