@tylix/compiler 0.5.1 → 0.6.0

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.
@@ -1,35 +1,97 @@
1
- let activeRequests = 0
2
- let barEl = null
3
-
4
- function ensureBar() {
5
- if (barEl) return barEl
6
- barEl = document.createElement('div')
7
- barEl.id = 'tylix-loading-bar'
8
- barEl.style.cssText =
9
- 'position:fixed;top:0;left:0;height:3px;width:0%;background:#10b981;z-index:99999;transition:width 0.2s ease,opacity 0.3s ease;opacity:0;'
10
- document.body.appendChild(barEl)
11
- return barEl
1
+ // Shared state for the loading indicator. The loading page (app/loading.tyx)
2
+ // receives this object as its "loading" prop. When a project has no loading
3
+ // page, a plain top bar is drawn instead, unless the project turned it off
4
+ // with loadingBar: false in tylix.config.
5
+ //
6
+ // active number of requests in flight
7
+ // progress bar width, 0 to 100
8
+ // visible false when nothing is loading
9
+ //
10
+ // The logic below uses plain variables and only WRITES to the reactive
11
+ // object. Reading reactive state here would subscribe whichever template
12
+ // effect happens to be running when a request starts, and creating an
13
+ // effect here would make it a child of that effect, which is torn down
14
+ // the next time the parent re-runs. The built-in bar is therefore painted
15
+ // directly.
16
+ const __tylixLoading = reactive({
17
+ active: 0,
18
+ progress: 0,
19
+ visible: false,
20
+ })
21
+
22
+ let __tylixActive = 0
23
+ let __tylixProgress = 0
24
+ let __tylixVisible = false
25
+ let __tylixHideTimer = null
26
+ let __tylixResetTimer = null
27
+ let __tylixWatchdog = null
28
+ let __tylixFallbackBar = null
29
+
30
+ function __tylixGetFallbackBar() {
31
+ if (window.__TYLIX_CUSTOM_LOADING__) return null
32
+ if (!__tylixFallbackBar) {
33
+ if (!document.body) return null
34
+ const bar = document.createElement('div')
35
+ bar.id = 'tylix-loading-bar'
36
+ bar.setAttribute('aria-hidden', 'true')
37
+ bar.style.cssText =
38
+ 'position:fixed;top:0;left:0;height:3px;width:0%;background:#10b981;z-index:99999;pointer-events:none;transition:width 0.2s ease,opacity 0.3s ease;opacity:0;'
39
+ document.body.appendChild(bar)
40
+ __tylixFallbackBar = bar
41
+ }
42
+ return __tylixFallbackBar
12
43
  }
13
44
 
14
- export function __tylixRequestStart() {
15
- activeRequests++
16
- const bar = ensureBar()
17
- bar.style.opacity = '1'
18
- bar.style.width = '70%'
45
+ function __tylixApply() {
46
+ __tylixLoading.active = __tylixActive
47
+ __tylixLoading.progress = __tylixProgress
48
+ __tylixLoading.visible = __tylixVisible
49
+
50
+ const bar = __tylixGetFallbackBar()
51
+ if (bar) {
52
+ bar.style.opacity = __tylixVisible ? '1' : '0'
53
+ bar.style.width = __tylixProgress + '%'
54
+ }
19
55
  }
20
56
 
21
- export function __tylixRequestEnd() {
22
- activeRequests = Math.max(0, activeRequests - 1)
23
- if (activeRequests === 0) {
24
- const bar = ensureBar()
25
- bar.style.width = '100%'
26
- setTimeout(() => {
27
- if (activeRequests === 0) {
28
- bar.style.opacity = '0'
29
- setTimeout(() => {
30
- bar.style.width = '0%'
31
- }, 300)
57
+ function __tylixFinish() {
58
+ clearTimeout(__tylixHideTimer)
59
+ clearTimeout(__tylixResetTimer)
60
+ __tylixProgress = 100
61
+ __tylixApply()
62
+ __tylixHideTimer = setTimeout(() => {
63
+ if (__tylixActive > 0) return
64
+ __tylixVisible = false
65
+ __tylixApply()
66
+ __tylixResetTimer = setTimeout(() => {
67
+ if (__tylixActive === 0) {
68
+ __tylixProgress = 0
69
+ __tylixApply()
32
70
  }
33
- }, 150)
34
- }
71
+ }, 300)
72
+ }, 150)
35
73
  }
74
+
75
+ // Safety net: a request that never settles must not leave the bar up.
76
+ function __tylixForceFinish() {
77
+ __tylixActive = 0
78
+ __tylixFinish()
79
+ }
80
+
81
+ export function __tylixRequestStart() {
82
+ clearTimeout(__tylixHideTimer)
83
+ clearTimeout(__tylixResetTimer)
84
+ clearTimeout(__tylixWatchdog)
85
+ __tylixActive++
86
+ __tylixVisible = true
87
+ __tylixProgress = 70
88
+ __tylixWatchdog = setTimeout(__tylixForceFinish, 30000)
89
+ __tylixApply()
90
+ }
91
+
92
+ export function __tylixRequestEnd() {
93
+ __tylixActive = Math.max(0, __tylixActive - 1)
94
+ if (__tylixActive > 0) return
95
+ clearTimeout(__tylixWatchdog)
96
+ __tylixFinish()
97
+ }
@@ -6,72 +6,99 @@
6
6
  * that depend on a property when that property is written -- nothing
7
7
  * else re-renders.
8
8
  *
9
- * reactive() wraps nested objects/arrays lazily, on read: when a get
10
- * trap returns a value that is itself an object, that value is wrapped
11
- * in reactive() too (and memoized, so repeated reads of the same
12
- * nested object return the same Proxy identity rather than a fresh
13
- * wrapper each time). Without this, only the top-level keys passed to
14
- * reactive() are ever tracked -- writes to a property of an object
15
- * *assigned into* a state field (e.g. a resource object's .data) are
16
- * invisible to the dependency graph, because get() would otherwise
17
- * hand back the raw, unwrapped object.
9
+ * What is wrapped: plain objects and arrays, lazily on read and
10
+ * memoized (so repeated reads return the same Proxy identity). Date,
11
+ * Map, Set, Promise, RegExp, DOM nodes and class instances are left
12
+ * alone: their methods need the real object as `this` and break when
13
+ * called through a Proxy.
18
14
  *
19
- * Every effect also tracks (a) which dep Sets it's currently a member
20
- * of, and (b) which child effects were created while it was running
15
+ * What is tracked: property reads, `key in obj`, and key enumeration
16
+ * (Object.keys, for...in). Writes that ADD a key also notify readers
17
+ * of the array's length / the object's key list, which is what makes
18
+ * `items.push(x)` re-render a list that iterates `items`.
19
+ *
20
+ * Every effect tracks (a) which dep Sets it's currently a member of,
21
+ * and (b) which child effects were created while it was running
21
22
  * (e.g. an #if/#each block's effect re-creating its children's own
22
- * effects on every rebuild). Before an effect re-runs, it disposes
23
- * itself from every dep Set and recursively disposes every child --
24
- * without this, rebuilding a block's children on every re-render
25
- * leaks the PREVIOUS render's child effects forever: they stay
26
- * subscribed, keep firing on every future write to whatever they
27
- * read, and do so against DOM nodes that have already been removed
28
- * (whose .parentNode is now null), which throws and can abort
29
- * whatever action triggered the write mid-way through.
23
+ * effects on every rebuild). Before an effect re-runs, it detaches
24
+ * from every dep and deactivates every child, recursively. A
25
+ * deactivated effect is skipped even if it is already queued in the
26
+ * current trigger pass, so a replaced block can never fire against
27
+ * DOM nodes that were already removed.
30
28
  */
31
29
 
32
30
  let activeEffect = null
33
31
  const targetMap = new WeakMap()
34
32
 
35
- // Memoizes target -> proxy so re-reading the same nested object
36
- // (e.g. a resource object stored in state, read on every render)
37
- // returns the same Proxy instance instead of a new wrapper each time.
38
- // Without this, dependencies tracked against one wrapper would never
39
- // match the wrapper an effect reads on a later pass, and triggers
40
- // would silently miss their subscribers.
33
+ // target -> proxy, so re-reading the same nested object returns the
34
+ // same Proxy instance (dependencies tracked against one wrapper must
35
+ // match the wrapper read on later passes).
41
36
  const reactiveMap = new WeakMap()
37
+ // Every proxy we have handed out, to avoid double-wrapping.
38
+ const proxies = new WeakSet()
39
+
40
+ const ITERATE_KEY = Symbol('iterate')
42
41
 
43
- function isObject(val) {
44
- return val !== null && typeof val === 'object'
42
+ function isReactiveTarget(val) {
43
+ if (val === null || typeof val !== 'object') return false
44
+ if (proxies.has(val)) return true
45
+ if (Object.isFrozen(val)) return false
46
+ if (Array.isArray(val)) return true
47
+ const proto = Object.getPrototypeOf(val)
48
+ return proto === Object.prototype || proto === null
45
49
  }
46
50
 
47
- export function reactive(target) {
48
- if (!isObject(target)) return target
51
+ function isIndexKey(key) {
52
+ return typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key)
53
+ }
49
54
 
50
- // Already-reactive objects (including ones we've handed out before)
51
- // shouldn't get double-wrapped -- wrapping a Proxy in another Proxy
52
- // would track/trigger through two independent dep graphs for the
53
- // same logical object.
54
- if (reactiveMap.has(target)) return reactiveMap.get(target)
55
+ export function reactive(target) {
56
+ if (!isReactiveTarget(target)) return target
57
+ if (proxies.has(target)) return target
58
+ const existing = reactiveMap.get(target)
59
+ if (existing) return existing
55
60
 
56
61
  const proxy = new Proxy(target, {
57
62
  get(obj, key, receiver) {
58
- track(obj, key)
59
63
  const result = Reflect.get(obj, key, receiver)
60
- // Lazily wrap nested objects/arrays so writes to THEIR
61
- // properties are tracked too -- e.g. state.postsResource.data =
62
- // [...] needs postsResource itself to have been returned as a
63
- // reactive proxy for this assignment to hit the set trap below.
64
- return isObject(result) ? reactive(result) : result
64
+ if (typeof key !== 'symbol') track(obj, key)
65
+ // Lazily wrap nested plain objects/arrays so writes to THEIR
66
+ // properties are tracked too.
67
+ return isReactiveTarget(result) ? reactive(result) : result
68
+ },
69
+ has(obj, key) {
70
+ if (typeof key !== 'symbol') track(obj, key)
71
+ return Reflect.has(obj, key)
72
+ },
73
+ ownKeys(obj) {
74
+ track(obj, Array.isArray(obj) ? 'length' : ITERATE_KEY)
75
+ return Reflect.ownKeys(obj)
65
76
  },
66
77
  set(obj, key, value, receiver) {
67
- const changed = obj[key] !== value
78
+ const isArray = Array.isArray(obj)
79
+ const hadKey =
80
+ isArray && isIndexKey(key)
81
+ ? Number(key) < obj.length
82
+ : Object.prototype.hasOwnProperty.call(obj, key)
83
+ const oldValue = obj[key]
68
84
  const result = Reflect.set(obj, key, value, receiver)
69
- if (changed) trigger(obj, key)
85
+ if (!hadKey) {
86
+ trigger(obj, key, 'add')
87
+ } else if (!Object.is(oldValue, value)) {
88
+ trigger(obj, key, 'set', isArray && key === 'length' ? value : undefined)
89
+ }
90
+ return result
91
+ },
92
+ deleteProperty(obj, key) {
93
+ const hadKey = Object.prototype.hasOwnProperty.call(obj, key)
94
+ const result = Reflect.deleteProperty(obj, key)
95
+ if (hadKey && result) trigger(obj, key, 'delete')
70
96
  return result
71
97
  },
72
98
  })
73
99
 
74
100
  reactiveMap.set(target, proxy)
101
+ proxies.add(proxy)
75
102
  return proxy
76
103
  }
77
104
 
@@ -81,39 +108,81 @@ function track(obj, key) {
81
108
  if (!depsMap) targetMap.set(obj, (depsMap = new Map()))
82
109
  let dep = depsMap.get(key)
83
110
  if (!dep) depsMap.set(key, (dep = new Set()))
84
- dep.add(activeEffect)
85
- activeEffect.deps.push(dep)
111
+ if (!dep.has(activeEffect)) {
112
+ dep.add(activeEffect)
113
+ activeEffect.deps.push(dep)
114
+ }
86
115
  }
87
116
 
88
- function trigger(obj, key) {
117
+ function trigger(obj, key, type, newLength) {
89
118
  const depsMap = targetMap.get(obj)
90
119
  if (!depsMap) return
91
- const dep = depsMap.get(key)
92
- if (!dep)
93
- return // Copy before iterating: an effect may re-track (add/remove itself)
94
- // while running, which would corrupt the Set mid-iteration.
95
- ;[...dep].forEach((fn) => fn())
120
+
121
+ const queued = new Set()
122
+ const collect = (dep) => {
123
+ if (dep) for (const fn of dep) queued.add(fn)
124
+ }
125
+
126
+ collect(depsMap.get(key))
127
+
128
+ if (type === 'add') {
129
+ if (Array.isArray(obj)) {
130
+ if (isIndexKey(key)) collect(depsMap.get('length'))
131
+ } else {
132
+ collect(depsMap.get(ITERATE_KEY))
133
+ }
134
+ } else if (type === 'delete' && !Array.isArray(obj)) {
135
+ collect(depsMap.get(ITERATE_KEY))
136
+ }
137
+
138
+ // `arr.length = 0` / splice shrinking: readers of the removed
139
+ // indices must hear about it too.
140
+ if (Array.isArray(obj) && key === 'length' && newLength !== undefined) {
141
+ for (const [k, dep] of depsMap) {
142
+ if (isIndexKey(k) && Number(k) >= newLength) collect(dep)
143
+ }
144
+ }
145
+
146
+ // Run every queued effect even if one throws, then rethrow the
147
+ // first error so a failing effect can't starve the others.
148
+ let failed = false
149
+ let firstError
150
+ for (const fn of queued) {
151
+ if (!fn.active || fn === activeEffect) continue
152
+ try {
153
+ fn()
154
+ } catch (err) {
155
+ if (!failed) {
156
+ failed = true
157
+ firstError = err
158
+ }
159
+ }
160
+ }
161
+ if (failed) throw firstError
96
162
  }
97
163
 
98
- // Detaches an effect from every dep Set it was previously part of,
99
- // and disposes every child effect it created during its last run --
100
- // disposal recurses, so a deeply nested #if inside an #each inside
101
- // another #if tears down its whole subtree correctly.
164
+ // Detaches an effect from every dep Set it was part of and
165
+ // deactivates every child effect it created during its last run --
166
+ // recursively, so a deeply nested #if inside an #each inside another
167
+ // #if tears down its whole subtree.
102
168
  function cleanup(effectFn) {
103
169
  for (const dep of effectFn.deps) dep.delete(effectFn)
104
170
  effectFn.deps.length = 0
105
- for (const child of effectFn.children) cleanup(child)
171
+ for (const child of effectFn.children) {
172
+ child.active = false
173
+ cleanup(child)
174
+ }
106
175
  effectFn.children.length = 0
107
176
  }
108
177
 
109
178
  export function effect(fn) {
110
179
  const wrapped = () => {
180
+ if (!wrapped.active) return
111
181
  cleanup(wrapped)
112
182
  const previousEffect = activeEffect
113
183
  // Register as a child of whichever effect is currently running
114
184
  // (if any), so that when THAT effect re-runs, it disposes this
115
- // one too -- this is what makes rebuilding an #if/#each block's
116
- // children safe to do repeatedly without leaking.
185
+ // one too.
117
186
  if (previousEffect) previousEffect.children.push(wrapped)
118
187
  activeEffect = wrapped
119
188
  try {
@@ -122,8 +191,9 @@ export function effect(fn) {
122
191
  activeEffect = previousEffect
123
192
  }
124
193
  }
194
+ wrapped.active = true
125
195
  wrapped.deps = []
126
196
  wrapped.children = []
127
197
  wrapped()
128
198
  return wrapped
129
- }
199
+ }
@@ -1,20 +1,15 @@
1
1
  import { emitStatementLines } from '../codegen/emitStatementLines.js'
2
+ import { generateParams } from '../codegen/generateExpression.js'
2
3
  import { collectTemplateChecks } from './typedTemplateExpr.js'
3
4
 
4
- function paramListWithTypes(params) {
5
- return params
6
- .map(
7
- (p) => `${p.name}${p.typeAnnotation ? `: ${p.typeAnnotation}` : ': any'}`,
8
- )
9
- .join(', ')
10
- }
11
-
12
5
  // Recursively emits a check tree (see collectTemplateChecks) into
13
6
  // the virtual __render() body. `each` entries open a real
14
7
  // `for (const item of (iterable as any[]))` so the loop variable is
15
8
  // an actual TS declaration, not a bare identifier the checker has
16
9
  // never seen -- `as any[]` since state/props are typically `any`
17
10
  // here anyway, and iterating `any` never fails strict mode regardless.
11
+ // The optional index binding of `{{#each item, i in items}}` is
12
+ // declared as a number.
18
13
  function emitChecks(checks, sink, indent) {
19
14
  for (const c of checks) {
20
15
  if (c.kind === 'each') {
@@ -22,12 +17,17 @@ function emitChecks(checks, sink, indent) {
22
17
  `${indent}for (const ${c.itemName} of (${c.iterableExpr} as any[])) {`,
23
18
  c.line,
24
19
  )
20
+ if (c.indexName) {
21
+ sink.pushLine(`${indent} const ${c.indexName}: number = 0;`, null)
22
+ }
25
23
  emitChecks(c.children, sink, indent + ' ')
26
24
  sink.pushLine(`${indent}}`, null)
27
25
  } else if (c.eventType) {
26
+ const base = c.eventBase ?? 'Event'
27
+ const full = `${base} & { target: ${c.eventType} }`
28
28
  sink.pushLine(`${indent}{`, null)
29
29
  sink.pushLine(
30
- `${indent} const event: Event & { target: ${c.eventType} } = new Event("synthetic") as unknown as Event & { target: ${c.eventType} };`,
30
+ `${indent} const event: ${full} = new Event("synthetic") as unknown as ${full};`,
31
31
  null,
32
32
  )
33
33
  sink.pushLine(`${indent} const $event = event;`, null)
@@ -91,7 +91,7 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
91
91
  : ''
92
92
  sink.pushLine(``, null)
93
93
  sink.pushLine(
94
- ` ${a.isAsync ? 'async ' : ''}${a.name}(${paramListWithTypes(a.params)})${returnType ? `: ${returnType}` : ''} {`,
94
+ ` ${a.isAsync ? 'async ' : ''}${a.name}(${generateParams(a.params, true)})${returnType ? `: ${returnType}` : ''} {`,
95
95
  a.line,
96
96
  )
97
97
  for (const stmt of a.body) emitStatementLines(stmt, sink, ' ')
@@ -112,7 +112,8 @@ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
112
112
  collectTemplateChecks(templateNodes, new Set(), checks)
113
113
  if (checks.length > 0) {
114
114
  sink.pushLine(``, null)
115
- sink.pushLine(` __render() {`, null)
115
+ // async so `await` inside event handlers typechecks
116
+ sink.pushLine(` async __render() {`, null)
116
117
  emitChecks(checks, sink, ' ')
117
118
  sink.pushLine(` }`, null)
118
119
  }
@@ -130,4 +131,4 @@ export function mapVirtualLineToSource(lineMap, virtualLine) {
130
131
  else break
131
132
  }
132
133
  return best
133
- }
134
+ }