@lightningjs/blits 2.4.1 → 2.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.
@@ -15,6 +15,8 @@
15
15
  * SPDX-License-Identifier: Apache-2.0
16
16
  */
17
17
 
18
+ import { platform } from '../../platform.js'
19
+
18
20
  // LocalStorage and Cookie storage library
19
21
  class localCookie {
20
22
  constructor(options) {
@@ -41,7 +43,8 @@ class localCookie {
41
43
 
42
44
  // Checks if local storage is available and works
43
45
  _checkIfLocalStorageWorks() {
44
- if (typeof localStorage !== 'undefined') {
46
+ const localStorage = platform.localStorage
47
+ if (localStorage !== undefined) {
45
48
  try {
46
49
  localStorage.setItem('feature_test', 'yes')
47
50
  if (localStorage.getItem('feature_test') === 'yes') {
@@ -66,23 +69,23 @@ class localCookie {
66
69
  * Local Storage APIs
67
70
  */
68
71
  _getItemLocalStorage(key) {
69
- return window.localStorage.getItem(key)
72
+ return platform.localStorage.getItem(key)
70
73
  }
71
74
 
72
75
  _setItemLocalStorage(key, value) {
73
- return window.localStorage.setItem(key, value)
76
+ return platform.localStorage.setItem(key, value)
74
77
  }
75
78
 
76
79
  _removeItemLocalStorage(key) {
77
- return window.localStorage.removeItem(key)
80
+ return platform.localStorage.removeItem(key)
78
81
  }
79
82
 
80
83
  _clearLocalStorage() {
81
- return window.localStorage.clear()
84
+ return platform.localStorage.clear()
82
85
  }
83
86
 
84
87
  _getLocalStorageKeys() {
85
- return Object.keys(window.localStorage)
88
+ return Object.keys(platform.localStorage)
86
89
  }
87
90
 
88
91
  /*
@@ -91,7 +94,7 @@ class localCookie {
91
94
  _getItemCookie(key) {
92
95
  /* eslint-disable */
93
96
  function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
94
- var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(key) + '=([^;]*)'));
97
+ var match = platform.getCookie().match(RegExp('(?:^|;\\s*)' + escape(key) + '=([^;]*)'));
95
98
 
96
99
  //if value in key of the entire cookie is empty, its deleted
97
100
  if (match && match[1] === '')
@@ -103,13 +106,13 @@ class localCookie {
103
106
  _setItemCookie(key, value) {
104
107
  var now = new Date()
105
108
  var expires = new Date(now.getTime() +1000*60*60*24*365*5) // 5 years!
106
- document.cookie = `${key}=${value}; expires=${expires.toUTCString()};`
109
+ platform.setCookie(`${key}=${value}; expires=${expires.toUTCString()};`)
107
110
  return //return undefined just like localStorage
108
111
  }
109
112
 
110
113
  _removeItemCookie(key) {
111
114
  // to delete an k/v set the key to empty
112
- document.cookie = `${key}=;Max-Age=-99999999;`
115
+ platform.setCookie(`${key}=;Max-Age=-99999999;`)
113
116
  return //return undefined just like localStorage
114
117
  }
115
118
 
@@ -117,14 +120,14 @@ class localCookie {
117
120
  // empty all key/values in cookies
118
121
  // What about cookies we got from the server? ¯\_(ツ)_/¯
119
122
  // They should have the HttpOnly flag, so we shouldn't be able to delete them
120
- document.cookie.split(";").forEach( (c) => {
121
- document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=;Max-Age=-99999999");
123
+ platform.getCookie().split(";").forEach( (c) => {
124
+ platform.setCookie(c.replace(/^ +/, "").replace(/=.*/, "=;expires=;Max-Age=-99999999"));
122
125
  });
123
126
 
124
127
  return //return undefined
125
128
  }
126
129
  _getCookieKeys() {
127
- return document.cookie.split(";").map((item)=>item.trim().split("=")[0])
130
+ return platform.getCookie().split(";").map((item)=>item.trim().split("=")[0])
128
131
  }
129
132
  }
130
133
 
@@ -24,6 +24,7 @@ import { stage } from '../launch.js'
24
24
  import Focus from '../focus/focus.js'
25
25
  import Announcer from '../announcer/announcer.js'
26
26
  import Settings from '../settings.js'
27
+ import { platform } from '../platform.js'
27
28
 
28
29
  /**
29
30
  * @typedef {import('../component.js').BlitsComponentFactory} BlitsComponentFactory - The component of the route
@@ -417,7 +418,8 @@ const executeBeforeHook = async function (
417
418
  this.currentRoute = previousRoute
418
419
  if (this.history.length > 0) {
419
420
  preventHashChangeNavigation = true
420
- window.history.back()
421
+ platform.historyBack()
422
+
421
423
  navigatingBack = false
422
424
  state.navigating = false
423
425
  }
@@ -434,7 +436,7 @@ const executeBeforeHook = async function (
434
436
  this.currentRoute = previousRoute
435
437
  if (this.history.length > 0) {
436
438
  preventHashChangeNavigation = true
437
- window.history.back()
439
+ platform.historyBack()
438
440
  navigatingBack = false
439
441
  state.navigating = false
440
442
  }
@@ -0,0 +1,58 @@
1
+ /*
2
+ * Copyright 2026 Comcast Cable Communications Management, LLC
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ *
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ *
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+
18
+ import type { ComponentFactory, Settings } from '@lightningjs/blits'
19
+
20
+ export interface SnapshotNode {
21
+ type: string
22
+ attributes: Record<string, any>
23
+ children: Array<SnapshotNode | ComponentSnapshotNode>
24
+ }
25
+
26
+ export interface ComponentSnapshotNode {
27
+ type: 'Component'
28
+ name: string
29
+ hasFocus: boolean
30
+ isHovered: boolean
31
+ attributes: Record<string, any>
32
+ props: Record<string, any>
33
+ state: Record<string, any>
34
+ tree: SnapshotNode | null
35
+ }
36
+
37
+ export interface RenderComponentOptions {
38
+ props?: Record<string, any>
39
+ settings?: Settings
40
+ }
41
+
42
+ export interface RenderComponentFixture {
43
+ component: any
44
+ root: any
45
+ snapshot(): SnapshotNode | ComponentSnapshotNode
46
+ setProps(props: Record<string, any>): void
47
+ setState(state: Record<string, any>): void
48
+ focus(event?: KeyboardEvent): Promise<any>
49
+ unfocus(): any
50
+ createKeyboardEvent(key: string, init?: KeyboardEventInit): KeyboardEvent
51
+ input(key: string, event?: KeyboardEvent): boolean
52
+ destroy(): void
53
+ }
54
+
55
+ export function renderComponent(
56
+ Component: ComponentFactory,
57
+ options?: RenderComponentOptions
58
+ ): RenderComponentFixture
@@ -0,0 +1,20 @@
1
+ /*
2
+ * Copyright 2026 Comcast Cable Communications Management, LLC
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ *
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ *
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+
18
+ import renderComponent from './renderComponent.js'
19
+
20
+ export { renderComponent }
@@ -0,0 +1,116 @@
1
+ /*
2
+ * Copyright 2026 Comcast Cable Communications Management, LLC
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ *
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ *
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+
18
+ class TestKeyboardEvent {
19
+ constructor(type, init = {}) {
20
+ this.type = type
21
+ this.key = init.key
22
+ this.code = init.code
23
+ this.keyCode = init.keyCode || 0
24
+ this.bubbles = init.bubbles === true
25
+ this.cancelable = init.cancelable === true
26
+ this.composed = init.composed === true
27
+ this.timeStamp = init.timeStamp || Date.now()
28
+ }
29
+ }
30
+
31
+ const createEventTarget = () => {
32
+ const listeners = {}
33
+
34
+ return {
35
+ addEventListener(type, handler) {
36
+ listeners[type] = listeners[type] || []
37
+ listeners[type].push(handler)
38
+ },
39
+ removeEventListener(type, handler) {
40
+ const handlers = listeners[type]
41
+ if (handlers === undefined) return
42
+ const index = handlers.indexOf(handler)
43
+ if (index > -1) handlers.splice(index, 1)
44
+ },
45
+ dispatchEvent(event) {
46
+ const handlers = listeners[event.type] || []
47
+ for (let i = 0; i < handlers.length; i++) {
48
+ handlers[i](event)
49
+ }
50
+ return true
51
+ },
52
+ }
53
+ }
54
+
55
+ const createStorage = () => {
56
+ const store = {}
57
+
58
+ return {
59
+ getItem(key) {
60
+ return store[key] !== undefined ? store[key] : null
61
+ },
62
+ setItem(key, value) {
63
+ store[key] = String(value)
64
+ },
65
+ removeItem(key) {
66
+ delete store[key]
67
+ },
68
+ clear() {
69
+ const keys = Object.keys(store)
70
+ for (let i = 0; i < keys.length; i++) {
71
+ delete store[keys[i]]
72
+ }
73
+ },
74
+ }
75
+ }
76
+
77
+ const nodePlatform = () => {
78
+ const input = createEventTarget()
79
+ const viewport = createEventTarget()
80
+ let cookie = ''
81
+
82
+ return {
83
+ input,
84
+ viewport,
85
+ dispatchEvent: input.dispatchEvent.bind(input),
86
+ localStorage: createStorage(),
87
+ getCookie: () => cookie,
88
+ setCookie: (value) => {
89
+ cookie = value
90
+ },
91
+ historyBack() {},
92
+ screenHeight: 1080,
93
+ hardwareConcurrency: 1,
94
+ userAgent: 'node',
95
+ KeyboardEvent: TestKeyboardEvent,
96
+ isKeyboardEvent: (event) => event instanceof TestKeyboardEvent,
97
+ createKeyboardEvent: (type, init = {}) => new TestKeyboardEvent(type, init),
98
+ SpeechSynthesisUtterance: class TestSpeechSynthesisUtterance {
99
+ constructor(text = '') {
100
+ this.text = text
101
+ }
102
+ },
103
+ speechSynthesis: {
104
+ cancel() {},
105
+ getVoices() {
106
+ return []
107
+ },
108
+ pause() {},
109
+ resume() {},
110
+ speak() {},
111
+ },
112
+ now: Date.now,
113
+ }
114
+ }
115
+
116
+ export default nodePlatform
@@ -0,0 +1,346 @@
1
+ /*
2
+ * Copyright 2026 Comcast Cable Communications Management, LLC
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ *
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ *
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+
18
+ import Settings from '../settings.js'
19
+ import { renderer, stage } from '../launch.js'
20
+ import symbols from '../lib/symbols.js'
21
+ import { initLog } from '../lib/log.js'
22
+ import { getRaw } from '../lib/reactivity/reactive.js'
23
+ import Focus from '../focus/focus.js'
24
+ import { initKeyMap, keyMap } from '../application.js'
25
+ import { configurePlatform, platform } from '../platform.js'
26
+ import nodePlatform from './nodePlatform.js'
27
+
28
+ let nodeId = 0
29
+
30
+ const renderComponent = (Component, options = {}) => {
31
+ const originalElement = stage.element
32
+ const originalPlatform = platform
33
+
34
+ Settings.set(options.settings || {})
35
+ configurePlatform(() => nodePlatform())
36
+ initLog()
37
+ initKeyMap()
38
+ mockRenderer()
39
+ // Generated template code calls stage.element through `this.element`
40
+ stage.element = createElement
41
+
42
+ const root = createElement()
43
+ const parent = {
44
+ $componentId: 'BlitsTestComponent::Root',
45
+ [symbols.lifecycle]: {
46
+ set state(v) {},
47
+ },
48
+ $focus() {},
49
+ $input() {
50
+ return false
51
+ },
52
+ }
53
+ const component = Component({ props: options.props || {} }, root, parent)
54
+
55
+ const snapshot = () => {
56
+ const holderMap = new WeakMap()
57
+ collectComponents(component, holderMap)
58
+ return componentSnapshot(component, holderMap)
59
+ }
60
+
61
+ const setProps = (props = {}) => {
62
+ const keys = Object.keys(props)
63
+ for (let i = 0; i < keys.length; i++) {
64
+ component[symbols.props][keys[i]] = props[keys[i]]
65
+ }
66
+ }
67
+
68
+ const setState = (state = {}) => {
69
+ const keys = Object.keys(state)
70
+ for (let i = 0; i < keys.length; i++) {
71
+ component[symbols.state][keys[i]] = state[keys[i]]
72
+ }
73
+ }
74
+
75
+ const focus = (event) => {
76
+ Focus.hold = false
77
+ component.$focus(event)
78
+ return new Promise((resolve) => {
79
+ setTimeout(() => {
80
+ setTimeout(() => resolve(component))
81
+ })
82
+ })
83
+ }
84
+
85
+ const unfocus = () => {
86
+ component.unfocus()
87
+ return component
88
+ }
89
+
90
+ const input = (key, event = createKeyboardEvent(key)) => {
91
+ const focused = Focus.get()
92
+ if (focused === null || focused.eol === true || isInComponentTree(focused, component) === false)
93
+ return false
94
+ Focus.input(key, event)
95
+ return true
96
+ }
97
+
98
+ const destroy = () => {
99
+ if (component.eol !== true) {
100
+ component.destroy()
101
+ }
102
+ stage.element = originalElement
103
+ configurePlatform(() => originalPlatform)
104
+ }
105
+
106
+ return {
107
+ component,
108
+ root,
109
+ snapshot,
110
+ setProps,
111
+ setState,
112
+ focus,
113
+ unfocus,
114
+ createKeyboardEvent,
115
+ input,
116
+ destroy,
117
+ }
118
+ }
119
+
120
+ const mockRenderer = () => {
121
+ // Lifecycle hooks register renderer events even in headless tests
122
+ if (renderer.on === undefined) renderer.on = () => {}
123
+ if (renderer.off === undefined) renderer.off = () => {}
124
+ }
125
+
126
+ const collectComponents = (component, holderMap) => {
127
+ if (component === undefined || component === null) return
128
+ // Component tags render as holder elements; keep the link for snapshots
129
+ if (component[symbols.holder] !== undefined) {
130
+ holderMap.set(component[symbols.holder], component)
131
+ }
132
+ const children = component[symbols.children] || []
133
+ for (let i = 0; i < children.length; i++) {
134
+ const child = children[i]
135
+ if (child && child.$componentId !== undefined) {
136
+ collectComponents(child, holderMap)
137
+ }
138
+ }
139
+ }
140
+
141
+ const elementSnapshot = (element, holderMap) => {
142
+ const component = holderMap.get(element)
143
+ if (component !== undefined) {
144
+ return componentSnapshot(component, holderMap)
145
+ }
146
+
147
+ const children = []
148
+ for (let i = 0; i < element.children.length; i++) {
149
+ children.push(elementSnapshot(element.children[i], holderMap))
150
+ }
151
+
152
+ return {
153
+ type: elementType(element.attributes),
154
+ attributes: attributesSnapshot(element.attributes),
155
+ children,
156
+ }
157
+ }
158
+
159
+ const componentSnapshot = (component, holderMap) => {
160
+ const holder = component[symbols.holder]
161
+ const wrapper = component[symbols.wrapper]
162
+
163
+ return {
164
+ type: 'Component',
165
+ name: componentName(component),
166
+ hasFocus: component.$hasFocus === true,
167
+ isHovered: component.$isHovered === true,
168
+ attributes: holder ? attributesSnapshot(holder.attributes) : {},
169
+ props: propsSnapshot(component),
170
+ state: stateSnapshot(component),
171
+ tree: wrapper ? elementSnapshot(wrapper, holderMap) : null,
172
+ }
173
+ }
174
+
175
+ const attributesSnapshot = (attributes) => {
176
+ const out = {}
177
+ const keys = Object.keys(attributes)
178
+ for (let i = 0; i < keys.length; i++) {
179
+ const key = keys[i]
180
+ if (
181
+ key === '___wrapper' ||
182
+ key === '__textnode' ||
183
+ key === '__layout' ||
184
+ key === 'holder' ||
185
+ key === 'parent'
186
+ ) {
187
+ continue
188
+ }
189
+ if (attributes[key] !== undefined) {
190
+ out[key] = clone(attributes[key])
191
+ }
192
+ }
193
+ return out
194
+ }
195
+
196
+ const propsSnapshot = (component) => {
197
+ const props = component[symbols.props] || {}
198
+ const propKeys = component[symbols.propKeys] || Object.keys(props)
199
+ const out = {}
200
+ for (let i = 0; i < propKeys.length; i++) {
201
+ const key = propKeys[i]
202
+ if (props[key] !== undefined) {
203
+ out[key] = clone(props[key])
204
+ }
205
+ }
206
+ return out
207
+ }
208
+
209
+ const stateSnapshot = (component) => {
210
+ const state = component[symbols.state] || {}
211
+ const originalState = component[symbols.originalState] || {}
212
+ const stateKeys = Object.keys(originalState)
213
+ const out = {}
214
+ for (let i = 0; i < stateKeys.length; i++) {
215
+ const key = stateKeys[i]
216
+ if (key === '$hasFocus' || key === '$isHovered') continue
217
+ if (state[key] !== undefined) {
218
+ out[key] = clone(state[key])
219
+ }
220
+ }
221
+ return out
222
+ }
223
+
224
+ const componentName = (component) => {
225
+ const match = component.$componentId && component.$componentId.match(/^BlitsComponent::(.+)_\d+$/)
226
+ return match ? match[1] : 'Component'
227
+ }
228
+
229
+ const elementType = (attributes) => {
230
+ if (attributes.__textnode === true) return 'Text'
231
+ if (attributes.__layout === true) return 'Layout'
232
+ if (attributes[symbols.isSlot] === true) return 'Slot'
233
+ if (attributes[symbols.isSprite] === true) return 'Sprite'
234
+ return 'Element'
235
+ }
236
+
237
+ const clone = (value) => {
238
+ value = getRaw(value)
239
+
240
+ if (Array.isArray(value) === true) {
241
+ return value.map((v) => clone(v))
242
+ }
243
+
244
+ if (
245
+ value !== null &&
246
+ typeof value === 'object' &&
247
+ Object.getPrototypeOf(value) === Object.prototype
248
+ ) {
249
+ return cleanObject(value)
250
+ }
251
+
252
+ return value
253
+ }
254
+
255
+ const cleanObject = (value) => {
256
+ const out = {}
257
+ const keys = Object.keys(value)
258
+ for (let i = 0; i < keys.length; i++) {
259
+ const key = keys[i]
260
+ if (value[key] !== undefined) {
261
+ out[key] = clone(value[key])
262
+ }
263
+ }
264
+ return out
265
+ }
266
+
267
+ const createElement = ({ parent } = {}) => {
268
+ // Minimal BlitsElement mock used by generated render/effect code
269
+ const element = {
270
+ attributes: {},
271
+ children: [],
272
+ node: {
273
+ children: [],
274
+ on() {},
275
+ off() {},
276
+ },
277
+ parent,
278
+ populate(attributes = {}) {
279
+ this.nodeId = ++nodeId
280
+ const keys = Object.keys(attributes)
281
+ for (let i = 0; i < keys.length; i++) {
282
+ this.set(keys[i], attributes[keys[i]])
283
+ }
284
+ if (attributes[symbols.isSlot] !== undefined) {
285
+ this.attributes[symbols.isSlot] = attributes[symbols.isSlot]
286
+ }
287
+ if (attributes[symbols.isSprite] !== undefined) {
288
+ this.attributes[symbols.isSprite] = attributes[symbols.isSprite]
289
+ }
290
+ },
291
+ set(key, value) {
292
+ this.attributes[key] = value
293
+ this.node[key] = value
294
+ },
295
+ setInspectorMetadata() {},
296
+ destroy() {
297
+ this.eol = true
298
+ this.children.length = 0
299
+ this.node.children.length = 0
300
+ },
301
+ }
302
+
303
+ appendToParent(element, parent)
304
+
305
+ return element
306
+ }
307
+
308
+ const appendToParent = (element, parent) => {
309
+ if (parent === undefined || parent === null || parent === 'root') return
310
+ if (parent.children === undefined) return
311
+ parent.children.push(element)
312
+ if (parent.node && parent.node.children) {
313
+ parent.node.children.push(element.node)
314
+ }
315
+ }
316
+
317
+ const createKeyboardEvent = (key, init = {}) => {
318
+ const keyCode = init.keyCode || keyCodeFromKey(key)
319
+ return platform.createKeyboardEvent('keydown', {
320
+ key,
321
+ ...init,
322
+ keyCode,
323
+ bubbles: true,
324
+ cancelable: true,
325
+ composed: true,
326
+ })
327
+ }
328
+
329
+ const keyCodeFromKey = (key) => {
330
+ const keys = Object.keys(keyMap)
331
+ for (let i = 0; i < keys.length; i++) {
332
+ if (keyMap[keys[i]] === key) return Number(keys[i])
333
+ }
334
+ return 0
335
+ }
336
+
337
+ const isInComponentTree = (child, parent) => {
338
+ let current = child
339
+ while (current !== undefined && current !== null) {
340
+ if (current === parent) return true
341
+ current = current[symbols.parent]
342
+ }
343
+ return false
344
+ }
345
+
346
+ export default renderComponent