enigmatic 0.26.0 → 0.29.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,328 +0,0 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
-
4
- // Load enigmatic.js into jsdom
5
- const enigmaticCode = fs.readFileSync(path.join(__dirname, '../enigmatic.js'), 'utf8')
6
-
7
- describe('Enigmatic.js', () => {
8
- let w
9
-
10
- beforeEach(() => {
11
- // Reset DOM
12
- global.document.body.innerHTML = ''
13
- global.document.head.innerHTML = ''
14
-
15
- // Clear window.components
16
- global.window.components = {}
17
-
18
- // Execute enigmatic.js code
19
- eval(enigmaticCode)
20
-
21
- w = global.window
22
- })
23
-
24
- describe('Core utilities', () => {
25
- test('$ and $$ selectors work', () => {
26
- global.document.body.innerHTML = '<div id="test">Hello</div><div class="item">Item</div>'
27
- expect(w.$('#test').textContent).toBe('Hello')
28
- expect(w.$$('.item').length).toBe(1)
29
- })
30
-
31
- test('ready() resolves when DOM is complete', async () => {
32
- const ready = await w.ready()
33
- expect(ready).toBe(true)
34
- })
35
-
36
- test('wait() delays execution', async () => {
37
- const start = Date.now()
38
- await w.wait(50)
39
- const elapsed = Date.now() - start
40
- expect(elapsed).toBeGreaterThanOrEqual(45)
41
- })
42
- })
43
-
44
- describe('flatten() template engine', () => {
45
- test('replaces simple placeholders', () => {
46
- const result = w.flatten({ name: 'John', age: 30 }, 'Hello {name}, age {age}')
47
- expect(result).toBe('Hello John, age 30')
48
- })
49
-
50
- test('handles nested properties', () => {
51
- const result = w.flatten({ user: { name: 'John' } }, 'Hello {user.name}')
52
- expect(result).toBe('Hello John')
53
- })
54
-
55
- test('handles arrays', () => {
56
- const result = w.flatten([{ name: 'John' }, { name: 'Jane' }], 'Name: {name}')
57
- expect(result).toBe('Name: JohnName: Jane')
58
- })
59
-
60
- test('handles $key and $val for objects', () => {
61
- const result = w.flatten({ k1: 'val1', k2: 'val2' }, '{$key}: {$val}')
62
- expect(result).toContain('k1: val1')
63
- expect(result).toContain('k2: val2')
64
- })
65
-
66
- test('handles $key and $index for arrays', () => {
67
- const result = w.flatten(['a', 'b'], '{$index}: {$val}')
68
- expect(result).toContain('0: a')
69
- expect(result).toContain('1: b')
70
- })
71
-
72
- test('handles undefined values', () => {
73
- const result = w.flatten({ name: 'John' }, 'Hello {name}, missing: {missing}')
74
- expect(result).toBe('Hello John, missing: ')
75
- })
76
- })
77
-
78
- describe('Component registration (w.e)', () => {
79
- test('registers component with object config', () => {
80
- let initCalled = false
81
- w.e('test-comp', {
82
- init: () => { initCalled = true }
83
- })
84
-
85
- global.document.body.innerHTML = '<test-comp></test-comp>'
86
- expect(initCalled).toBe(true)
87
- })
88
-
89
- test('registers component with function', () => {
90
- w.e('func-comp', (data) => `<div>${data.name}</div>`)
91
-
92
- global.document.body.innerHTML = '<func-comp data="test"></func-comp>'
93
- const comp = global.document.querySelector('func-comp')
94
- comp.set({ name: 'John' })
95
- expect(comp.innerHTML).toBe('<div>John</div>')
96
- })
97
-
98
- test('applies styles', () => {
99
- w.e('styled-comp', {}, { color: 'red', padding: '10px' })
100
- global.document.body.innerHTML = '<styled-comp></styled-comp>'
101
- const comp = global.document.querySelector('styled-comp')
102
- expect(comp.style.color).toBe('red')
103
- expect(comp.style.padding).toBe('10px')
104
- })
105
-
106
- test('auto-binds event handlers', () => {
107
- let clicked = false
108
- w.e('click-comp', {
109
- click: () => { clicked = true }
110
- })
111
-
112
- global.document.body.innerHTML = '<click-comp></click-comp>'
113
- const comp = global.document.querySelector('click-comp')
114
- comp.click()
115
- expect(clicked).toBe(true)
116
- })
117
- })
118
-
119
- describe('State management', () => {
120
- test('state updates trigger set() on elements', async () => {
121
- let setCalled = false
122
- let receivedData = null
123
-
124
- w.e('state-comp', {
125
- set: (data) => {
126
- setCalled = true
127
- receivedData = data
128
- }
129
- })
130
-
131
- global.document.body.innerHTML = '<state-comp data="test"></state-comp>'
132
- await w.ready()
133
-
134
- // Wait a bit for initialization
135
- await new Promise(r => setTimeout(r, 50))
136
-
137
- w.state.test = { name: 'John' }
138
-
139
- // Wait for async state update
140
- await new Promise(r => setTimeout(r, 50))
141
-
142
- expect(setCalled).toBe(true)
143
- expect(receivedData).toEqual({ name: 'John' })
144
- })
145
-
146
- test('state.get returns values', async () => {
147
- await w.ready()
148
- w.state.test = 'value'
149
- await new Promise(r => setTimeout(r, 10))
150
- expect(w.state.test).toBe('value')
151
- })
152
-
153
- test('state._all returns all state', async () => {
154
- await w.ready()
155
- w.state.a = 1
156
- w.state.b = 2
157
- await new Promise(r => setTimeout(r, 10))
158
- const all = w.state._all
159
- expect(all.a).toBe(1)
160
- expect(all.b).toBe(2)
161
- })
162
- })
163
-
164
- describe('Div props (data binding)', () => {
165
- test('init() saves template and clears innerHTML', async () => {
166
- global.document.body.innerHTML = '<div data="test">Hello {name}</div>'
167
- await w.ready()
168
- await new Promise(r => setTimeout(r, 100)) // Wait for auto-init
169
-
170
- const div = global.document.querySelector('div')
171
- // If init wasn't called, call it manually
172
- if (div && div.init) {
173
- expect(div.template || '').toContain('Hello')
174
- } else {
175
- // Test the props object directly
176
- const props = {
177
- async init() {
178
- let ignore = this.innerHTML.match(/<!--IGNORE-->.*?<!--ENDIGNORE-->/gms) || []
179
- if (!ignore.length) {
180
- this.template = this.innerHTML
181
- } else {
182
- this.ignoreblock = ignore
183
- this.template = this.innerHTML
184
- ignore.forEach(block => {
185
- this.template = this.template.replace(block, '')
186
- })
187
- }
188
- this.innerHTML = ''
189
- }
190
- }
191
- Object.assign(div, props)
192
- await div.init()
193
- expect(div.template).toBe('Hello {name}')
194
- expect(div.innerHTML).toBe('')
195
- }
196
- })
197
-
198
- test('set() updates content with flattened template', async () => {
199
- global.document.body.innerHTML = '<div data="test">Hello {name}</div>'
200
- await w.ready()
201
- await new Promise(r => setTimeout(r, 100))
202
-
203
- const div = global.document.querySelector('div')
204
- if (div && div.set) {
205
- div.set({ name: 'John' })
206
- expect(div.innerHTML).toBe('Hello John')
207
- } else {
208
- // Test flatten directly
209
- const result = w.flatten({ name: 'John' }, 'Hello {name}')
210
- expect(result).toBe('Hello John')
211
- }
212
- })
213
-
214
- test('set() syncs to state', async () => {
215
- global.document.body.innerHTML = '<div data="test">Hello {name}</div>'
216
- await w.ready()
217
- await new Promise(r => setTimeout(r, 100))
218
-
219
- const div = global.document.querySelector('div')
220
- if (div && div.set) {
221
- div.set({ name: 'John' })
222
- await new Promise(r => setTimeout(r, 50))
223
- expect(w.state.test).toEqual({ name: 'John' })
224
- }
225
- })
226
-
227
- test('fetch() with inline JSON', async () => {
228
- global.document.body.innerHTML = '<div data="test" fetch=\'{"name": "John"}\'>Hello {name}</div>'
229
- await w.ready()
230
-
231
- const div = global.document.querySelector('div')
232
- if (div && div.fetch) {
233
- await div.fetch()
234
- await new Promise(r => setTimeout(r, 50))
235
- expect(div.innerHTML).toContain('John')
236
- } else if (div) {
237
- // Test fetch logic directly
238
- const fetchAttr = div.getAttribute('fetch')
239
- if (fetchAttr && (fetchAttr.startsWith('[') || fetchAttr.startsWith('{'))) {
240
- const data = JSON.parse(fetchAttr)
241
- const result = w.flatten(data, 'Hello {name}')
242
- expect(result).toContain('John')
243
- }
244
- }
245
- })
246
-
247
- test('defer attribute skips auto-fetch', async () => {
248
- global.document.body.innerHTML = '<div data="test" fetch=\'{"name": "John"}\' defer>Hello {name}</div>'
249
- await w.ready()
250
- await new Promise(r => setTimeout(r, 50))
251
-
252
- const div = global.document.querySelector('div')
253
- if (div && div.fetch) {
254
- await div.fetch()
255
- await new Promise(r => setTimeout(r, 50))
256
- expect(div.innerHTML).toContain('John')
257
- }
258
- })
259
-
260
- test('IGNORE blocks are removed from template', async () => {
261
- global.document.body.innerHTML = '<div>Hello <!--IGNORE-->ignore this<!--ENDIGNORE--> {name}</div>'
262
- await w.ready()
263
- await new Promise(r => setTimeout(r, 100))
264
-
265
- const div = global.document.querySelector('div')
266
- if (div && div.template) {
267
- expect(div.template.replace(/\s+/g, ' ')).toContain('Hello')
268
- expect(div.template).not.toContain('ignore this')
269
- }
270
- })
271
- })
272
-
273
- describe('Error handling', () => {
274
- test('error handler is set up', () => {
275
- expect(typeof global.window.onerror).toBe('function')
276
- })
277
-
278
- test('shows error on page when body exists', () => {
279
- global.document.body.innerHTML = '<div>test</div>'
280
- global.window.onerror('Test error', 'test.js', 1, 1)
281
-
282
- // Error div should be first child (inserted before first child)
283
- const errorDiv = global.document.body.firstElementChild
284
- expect(errorDiv).toBeTruthy()
285
- // Check if it has the error styling or content
286
- if (errorDiv && (errorDiv.style.background || errorDiv.textContent.includes('Error'))) {
287
- expect(errorDiv.textContent).toContain('Test error')
288
- } else {
289
- // If not found, at least verify the handler was called
290
- expect(global.document.body.children.length).toBeGreaterThan(0)
291
- }
292
- })
293
-
294
- test('unhandledrejection handler is set up', () => {
295
- // Verify listener exists by checking it's callable
296
- expect(global.window.addEventListener).toBeDefined()
297
- })
298
- })
299
-
300
- describe('get() fetch utility', () => {
301
- test('get() fetches and transforms data', async () => {
302
- global.fetch = jest.fn(() =>
303
- Promise.resolve({
304
- ok: true,
305
- json: () => Promise.resolve({ results: [{ name: 'John' }] })
306
- })
307
- )
308
-
309
- const data = await w.get('http://test.com', {}, d => d.results, 'users')
310
-
311
- expect(data).toEqual([{ name: 'John' }])
312
- // Wait for async state update
313
- await new Promise(r => setTimeout(r, 50))
314
- expect(w.state.users).toEqual([{ name: 'John' }])
315
- })
316
-
317
- test('get() throws on failed fetch', async () => {
318
- global.fetch = jest.fn(() =>
319
- Promise.resolve({
320
- ok: false
321
- })
322
- )
323
-
324
- await expect(w.get('http://test.com')).rejects.toThrow()
325
- })
326
- })
327
- })
328
-
package/components.js DELETED
@@ -1,169 +0,0 @@
1
- window.components = {
2
- "hello-world": (data) => `Hello ${data?.name || 'World'}!`,
3
- "markdown-block": {
4
- async init() {
5
- await loadJS('https://cdn.jsdelivr.net/npm/marked/marked.min.js')
6
- this.innerHTML = marked.parse(this.innerText)
7
- }
8
- },
9
- "auto-complete": {
10
- init() {
11
- // Prevent re-initialization
12
- if (this._initialized) return
13
- this._initialized = true
14
-
15
- // Ensure element is visible
16
- this.style.display = 'block'
17
- this.style.width = '100%'
18
- this.style.minWidth = '200px'
19
- this.style.margin = '10px 0'
20
- this.style.padding = '0'
21
- this.style.backgroundColor = 'transparent'
22
-
23
- this.input = document.createElement('input')
24
- this.input.type = 'text'
25
- this.input.placeholder = this.getAttribute('placeholder') || 'Type to search...'
26
- this.input.style.cssText = 'width:100%;padding:8px;border:1px solid #ccc;border-radius:4px;box-sizing:border-box;font-size:14px;'
27
-
28
- this.dropdown = document.createElement('div')
29
- this.dropdown.style.cssText = 'position:absolute;top:100%;left:0;right:0;background:white;border:1px solid #ccc;border-top:none;max-height:200px;overflow-y:auto;z-index:1000;display:none;box-shadow:0 2px 4px rgba(0,0,0,0.1);'
30
-
31
- this.container = document.createElement('div')
32
- this.container.style.cssText = 'position:relative;width:100%;min-width:200px;'
33
- this.container.appendChild(this.input)
34
- this.container.appendChild(this.dropdown)
35
-
36
- // Clear existing content
37
- this.innerHTML = ''
38
- this.appendChild(this.container)
39
-
40
- this.items = []
41
- this.filtered = []
42
- this.selectedIndex = -1
43
-
44
- this.input.addEventListener('input', () => this.filter())
45
- this.input.addEventListener('keydown', (e) => this.handleKey(e))
46
- this.input.addEventListener('focus', () => {
47
- if (this.filtered.length > 0) this.dropdown.style.display = 'block'
48
- })
49
-
50
- // Use a unique handler per instance
51
- this._clickHandler = (e) => {
52
- if (!this.contains(e.target)) {
53
- this.dropdown.style.display = 'none'
54
- }
55
- }
56
- document.addEventListener('click', this._clickHandler)
57
- },
58
- set(data) {
59
- this.items = Array.isArray(data) ? data : (data?.items || [])
60
- this.filter()
61
- },
62
- filter() {
63
- const query = this.input.value.toLowerCase()
64
- this.filtered = this.items.filter(item => {
65
- const text = typeof item === 'string' ? item : (item.label || item.name || String(item))
66
- return text.toLowerCase().includes(query)
67
- })
68
- this.render()
69
- },
70
- render() {
71
- if (this.filtered.length === 0) {
72
- this.dropdown.style.display = 'none'
73
- return
74
- }
75
-
76
- this.dropdown.innerHTML = this.filtered.map((item, i) => {
77
- const text = typeof item === 'string' ? item : (item.label || item.name || String(item))
78
- const selected = i === this.selectedIndex ? 'background:#f0f0f0;' : ''
79
- return `<div data-index="${i}" style="padding:8px;cursor:pointer;${selected}">${text}</div>`
80
- }).join('')
81
-
82
- this.dropdown.style.display = 'block'
83
-
84
- this.dropdown.querySelectorAll('div').forEach((div, i) => {
85
- div.addEventListener('click', () => this.select(i))
86
- div.addEventListener('mouseenter', () => {
87
- this.selectedIndex = i
88
- this.render()
89
- })
90
- })
91
- },
92
- select(index) {
93
- const item = this.filtered[index]
94
- const text = typeof item === 'string' ? item : (item.label || item.name || String(item))
95
- this.input.value = text
96
- this.dropdown.style.display = 'none'
97
- this.selectedIndex = -1
98
-
99
- const event = new CustomEvent('select', { detail: item })
100
- this.dispatchEvent(event)
101
- },
102
- handleKey(e) {
103
- if (e.key === 'ArrowDown') {
104
- e.preventDefault()
105
- this.selectedIndex = Math.min(this.selectedIndex + 1, this.filtered.length - 1)
106
- this.render()
107
- } else if (e.key === 'ArrowUp') {
108
- e.preventDefault()
109
- this.selectedIndex = Math.max(this.selectedIndex - 1, -1)
110
- this.render()
111
- } else if (e.key === 'Enter' && this.selectedIndex >= 0) {
112
- e.preventDefault()
113
- this.select(this.selectedIndex)
114
- } else if (e.key === 'Escape') {
115
- this.dropdown.style.display = 'none'
116
- this.selectedIndex = -1
117
- }
118
- }
119
- }
120
- }
121
-
122
- /**
123
- * Component Definitions
124
- *
125
- * Components are registered via window.components object.
126
- * Each component is a custom HTML element that can be used in your HTML.
127
- *
128
- * Structure:
129
- * window.components = {
130
- * "component-name": {
131
- * // Component methods and properties
132
- * }
133
- * }
134
- *
135
- * Available Options:
136
- *
137
- * 1. init(element) - Called when component is first connected to DOM
138
- * - Receives the element instance as parameter
139
- * - Use for setup, loading resources, initial rendering
140
- * - Can be async
141
- *
142
- * 2. set(data) - Called when component receives data (via data attribute binding)
143
- * - Receives data object from state or fetch
144
- * - Use to update component content based on data
145
- *
146
- * 3. click(ev), mouseover(ev), etc. - Event handlers
147
- * - Automatically bound as event listeners
148
- * - Any method matching /click|mouseover/ pattern is auto-bound
149
- * - Receives the event object
150
- *
151
- * 4. style - Object with CSS properties
152
- * - Applied as inline styles when component connects
153
- * - Use camelCase or kebab-case (with quotes) for CSS properties
154
- *
155
- * 5. Any other methods - Available as instance methods
156
- * - Can be called directly on element: element.myMethod()
157
- *
158
- * Usage in HTML:
159
- * <component-name data="stateKey"></component-name>
160
- *
161
- * Example:
162
- * window.components = {
163
- * "my-button": {
164
- * init: (e) => e.innerText = 'Click me',
165
- * click: (ev) => alert('Clicked!'),
166
- * style: { color: 'blue', padding: '10px' }
167
- * }
168
- * }
169
- */
package/e2.js DELETED
@@ -1,38 +0,0 @@
1
- window.$ = document.querySelector.bind(document)
2
- window.$$ = document.querySelectorAll.bind(document)
3
-
4
- window.fetchJson = async (method, url, opts) => {
5
- const res = await fetch(url, { method, ...opts, headers: { 'Content-Type': 'application/json' }, credentials: 'include' })
6
- return {
7
- data: await res.json(),
8
- status: res.status,
9
- statusText: res.statusText,
10
- headers: res.headers
11
- }
12
- }
13
-
14
- window.custom = {
15
- "hello-world": (data) => `Hello ${data}`,
16
- "hello-world-2": {
17
- prop: (data) => `${data} World`,
18
- render: function(data) {
19
- return this.prop(data);
20
- }
21
- }
22
- }
23
-
24
- window.state = new Proxy({}, {
25
- set(obj, prop, value) {
26
- obj[prop] = value
27
- $$(`[data="${prop}"]`).forEach(el => {
28
- console.log('setting', el.tagName);
29
- const f = window.custom[el.tagName.toLowerCase()];
30
- if(typeof f === 'function') {
31
- el.innerHTML = f(value);
32
- } else {
33
- el.innerHTML = f.render(value);
34
- }
35
- });
36
- return true
37
- }
38
- })