@dinoreic/fez 0.2.0 → 0.3.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.
@@ -0,0 +1,184 @@
1
+ // Utility functions that extend Fez
2
+ export default (Fez) => {
3
+ // Script from URL
4
+ // Fez.head({ js: 'https://example.com/script.js' });
5
+ // Script with attributes
6
+ // Fez.head({ js: 'https://example.com/script.js', type: 'module', async: true });
7
+ // Script with callback
8
+ // Fez.head({ js: 'https://example.com/script.js' }, () => { console.log('loaded') });
9
+ // Module loading with auto-import to window
10
+ // Fez.head({ js: 'https://example.com/module.js', module: 'MyModule' }); // imports and sets window.MyModule
11
+ // CSS inclusion
12
+ // Fez.head({ css: 'https://example.com/styles.css' });
13
+ // CSS with additional attributes and callback
14
+ // Fez.head({ css: 'https://example.com/styles.css', media: 'print' }, () => { console.log('CSS loaded') })
15
+ // Inline script evaluation
16
+ // Fez.head({ script: 'console.log("Hello world")' })
17
+ // Extract from nodes
18
+ // Fez.head(domNode)
19
+ Fez.head = (config, callback) => {
20
+ if (config.nodeName) {
21
+ if (config.nodeName == 'SCRIPT') {
22
+ Fez.head({script: config.innerText})
23
+ config.remove()
24
+ } else {
25
+ config.querySelectorAll('script').forEach((n) => Fez.head(n) )
26
+ config.querySelectorAll('template[fez], xmp[fez], script[fez]').forEach((n) => Fez.compile(n) )
27
+ }
28
+
29
+ return
30
+ }
31
+
32
+ if (typeof config !== 'object' || config === null) {
33
+ throw new Error('head requires an object parameter');
34
+ }
35
+
36
+ let src, attributes = {}, elementType;
37
+
38
+ if (config.script) {
39
+ if (config.script.includes('import ')) {
40
+ if (callback) {
41
+ Fez.error('Fez.head callback is not supported when script with import is passed (module context).')
42
+ }
43
+
44
+ // Evaluate inline script in context in the module
45
+ const script = document.createElement('script');
46
+ script.type = 'module';
47
+ script.textContent = config.script;
48
+ document.head.appendChild(script);
49
+ setTimeout(()=>script.remove(), 100)
50
+ } else {
51
+ try {
52
+ new Function(config.script)();
53
+ if (callback) callback();
54
+ } catch (error) {
55
+ Fez.error('Error executing script:', error);
56
+ console.log(config.script);
57
+ }
58
+ }
59
+ return;
60
+ } else if (config.js) {
61
+ src = config.js;
62
+ elementType = 'script';
63
+ // Copy all properties except 'js' as attributes
64
+ for (const [key, value] of Object.entries(config)) {
65
+ if (key !== 'js' && key !== 'module') {
66
+ attributes[key] = value;
67
+ }
68
+ }
69
+ // Handle module loading
70
+ if (config.module) {
71
+ attributes.type = 'module';
72
+ }
73
+ } else if (config.css) {
74
+ src = config.css;
75
+ elementType = 'link';
76
+ attributes.rel = 'stylesheet';
77
+ // Copy all properties except 'css' as attributes
78
+ for (const [key, value] of Object.entries(config)) {
79
+ if (key !== 'css') {
80
+ attributes[key] = value;
81
+ }
82
+ }
83
+ } else {
84
+ throw new Error('head requires either "script", "js" or "css" property');
85
+ }
86
+
87
+ const existingNode = document.querySelector(`${elementType}[src="${src}"], ${elementType}[href="${src}"]`);
88
+ if (existingNode) {
89
+ if (callback) callback();
90
+ return existingNode;
91
+ }
92
+
93
+ const element = document.createElement(elementType);
94
+
95
+ if (elementType === 'link') {
96
+ element.href = src;
97
+ } else {
98
+ element.src = src;
99
+ }
100
+
101
+ for (const [key, value] of Object.entries(attributes)) {
102
+ element.setAttribute(key, value);
103
+ }
104
+
105
+ if (callback || config.module) {
106
+ element.onload = () => {
107
+ // If module name is provided, import it and assign to window
108
+ if (config.module && elementType === 'script') {
109
+ import(src).then(module => {
110
+ window[config.module] = module.default || module[config.module] || module;
111
+ }).catch(error => {
112
+ console.error(`Error importing module ${config.module}:`, error);
113
+ });
114
+ }
115
+ if (callback) callback();
116
+ };
117
+ }
118
+
119
+ document.head.appendChild(element);
120
+
121
+ return element;
122
+ }
123
+
124
+ Fez.darkenColor = (color, percent = 20) => {
125
+ // Convert hex to RGB
126
+ const num = parseInt(color.replace("#", ""), 16)
127
+ const amt = Math.round(2.55 * percent)
128
+ const R = (num >> 16) - amt
129
+ const G = (num >> 8 & 0x00FF) - amt
130
+ const B = (num & 0x0000FF) - amt
131
+ return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 + (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 + (B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1)
132
+ }
133
+
134
+ Fez.lightenColor = (color, percent = 20) => {
135
+ // Convert hex to RGB
136
+ const num = parseInt(color.replace("#", ""), 16)
137
+ const amt = Math.round(2.55 * percent)
138
+ const R = (num >> 16) + amt
139
+ const G = (num >> 8 & 0x00FF) + amt
140
+ const B = (num & 0x0000FF) + amt
141
+ return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 + (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 + (B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1)
142
+ }
143
+
144
+ Fez.htmlEscape = (text) => {
145
+ if (typeof text == 'string') {
146
+ text = text
147
+ // .replaceAll('&', "&amp;")
148
+ .replace(/font-family\s*:\s*(?:&[^;]+;|[^;])*?;/gi, '')
149
+ .replaceAll("&", '&amp;')
150
+ .replaceAll("'", '&apos;')
151
+ .replaceAll('"', '&quot;')
152
+ .replaceAll('<', '&lt;')
153
+ .replaceAll('>', '&gt;')
154
+ // .replaceAll('@', '&#64;') // needed for template escaping
155
+
156
+ return text
157
+ } else {
158
+ return text === undefined ? '' : text
159
+ }
160
+ }
161
+
162
+ // create dom root and return it
163
+ Fez.domRoot = (data, name = 'div') => {
164
+ if (data instanceof Node) {
165
+ return data
166
+ } else {
167
+ const root = document.createElement(name)
168
+ root.innerHTML = data
169
+ return root
170
+ }
171
+ }
172
+
173
+ // add class by name to node and remove it from siblings
174
+ Fez.activateNode = (node, klass = 'active') => {
175
+ Array.from(node.parentElement.children).forEach(child => {
176
+ child.classList.remove(klass)
177
+ })
178
+ node.classList.add(klass)
179
+ }
180
+
181
+ Fez.isTrue = (val) => {
182
+ return ['1', 'true', 'on'].includes(String(val).toLowerCase())
183
+ }
184
+ }
package/src/fez.js CHANGED
@@ -6,12 +6,15 @@ if (typeof window !== 'undefined') window.FezBase = FezBase
6
6
  import Fez from './fez/root.js'
7
7
  if (typeof window !== 'undefined') window.Fez = Fez
8
8
 
9
+ // Load defaults after Fez is properly initialized
10
+ import('./fez/defaults.js')
11
+
9
12
  // clear all unattached nodes
10
13
  setInterval(() => {
11
14
  for (const [key, el] of Fez.instances) {
12
15
  if (!el?.isConnected) {
13
16
  // Fez.error(`Found junk instance that is not connected ${el.fezName}`)
14
- el.fez?.fezRemoveSelf()
17
+ el.fez?.fezOnDestroy()
15
18
  Fez.instances.delete(key)
16
19
  }
17
20
  }
@@ -44,7 +47,7 @@ const observer = new MutationObserver((mutations) => {
44
47
  .forEach(el => {
45
48
  if (el.fez && el.root) {
46
49
  Fez.instances.delete(el.fez.UID)
47
- el.fez.fezRemoveSelf()
50
+ el.fez.fezOnDestroy()
48
51
  }
49
52
  });
50
53
  }
@@ -58,40 +61,5 @@ observer.observe(document.documentElement, {
58
61
  subtree: true
59
62
  });
60
63
 
61
- // fez custom tags
62
-
63
- // include fez component by name
64
- //<fez-component name="some-node" :props="fez.props"></fez-node>
65
- Fez('fez-component', class {
66
- FAST = true
67
-
68
- init(props) {
69
- const tag = document.createElement(props.name)
70
- tag.props = props.props || props['data-props'] || props
71
-
72
- while (this.root.firstChild) {
73
- this.root.parentNode.insertBefore(this.root.lastChild, tag.nextSibling);
74
- }
75
-
76
- this.root.innerHTML = ''
77
- this.root.appendChild(tag)
78
- }
79
- })
80
-
81
- // include remote data from url
82
- // <fez-include src="./demo/fez/ui-slider.html"></fez-include>
83
- Fez('fez-include', class {
84
- FAST = true
85
-
86
- init(props) {
87
- Fez.fetch(props.src, (data)=>{
88
- const dom = document.createElement('div')
89
- dom.innerHTML = data
90
- Fez.head(dom) // include scripts and load fez components
91
- this.root.innerHTML = dom.innerHTML
92
- })
93
- }
94
- })
95
-
96
64
  export default Fez
97
65
  export { Fez }
package/src/log.js ADDED
@@ -0,0 +1,154 @@
1
+ // pretty print HTML
2
+ const LOG_PP = (html) => {
3
+ const parts = html
4
+ .split(/(<\/?[^>]+>)/g)
5
+ .map(p => p.trim())
6
+ .filter(p => p);
7
+
8
+ let indent = 0;
9
+ const lines = [];
10
+
11
+ for (let i = 0; i < parts.length; i++) {
12
+ const part = parts[i];
13
+ const nextPart = parts[i + 1];
14
+ const nextNextPart = parts[i + 2];
15
+
16
+ // Check if it's a tag
17
+ if (part.startsWith('<')) {
18
+ // Check if this is an opening tag followed by text and then its closing tag
19
+ if (!part.startsWith('</') && !part.endsWith('/>') && nextPart && !nextPart.startsWith('<') && nextNextPart && nextNextPart.startsWith('</')) {
20
+ // Combine them on one line
21
+ const actualIndent = Math.max(0, indent);
22
+ lines.push(' '.repeat(actualIndent) + part + nextPart + nextNextPart);
23
+ i += 2; // Skip the next two parts
24
+ }
25
+ // Closing tag
26
+ else if (part.startsWith('</')) {
27
+ indent--;
28
+ const actualIndent = Math.max(0, indent);
29
+ lines.push(' '.repeat(actualIndent) + part);
30
+ }
31
+ // Self-closing tag
32
+ else if (part.endsWith('/>') || part.includes(' />')) {
33
+ const actualIndent = Math.max(0, indent);
34
+ lines.push(' '.repeat(actualIndent) + part);
35
+ }
36
+ // Opening tag
37
+ else {
38
+ const actualIndent = Math.max(0, indent);
39
+ lines.push(' '.repeat(actualIndent) + part);
40
+ indent++;
41
+ }
42
+ }
43
+ // Text node
44
+ else if (part) {
45
+ const actualIndent = Math.max(0, indent);
46
+ lines.push(' '.repeat(actualIndent) + part);
47
+ }
48
+ }
49
+
50
+ return lines.join('\n');
51
+ }
52
+
53
+ const LOG = (() => {
54
+ const logs = [];
55
+ const logTypes = []; // Track the original type of each log
56
+ let currentIndex = 0;
57
+
58
+ return o => {
59
+ if (!document.body) {
60
+ window.requestAnimationFrame( () => LOG(o) )
61
+ return
62
+ }
63
+
64
+ if (o instanceof Node) {
65
+ o = LOG_PP(o.outerHTML)
66
+ }
67
+
68
+ // Store the original type
69
+ let originalType = typeof o;
70
+
71
+ if (o === undefined) { o = 'undefined' }
72
+ if (o === null) { o = 'null' }
73
+
74
+ if (Array.isArray(o)) {
75
+ originalType = 'array';
76
+ } else if (typeof o === 'object' && o !== null) {
77
+ originalType = 'object';
78
+ }
79
+
80
+ if (typeof o != 'string') {
81
+ o = JSON.stringify(o, (key, value) => {
82
+ if (typeof value === 'function') {
83
+ return String(value);
84
+ }
85
+ return value;
86
+ }, 2).replaceAll('<', '&lt;')
87
+ }
88
+
89
+ o = o.trim()
90
+
91
+ logs.push(o + `\n\ntype: ${originalType}`);
92
+ logTypes.push(originalType);
93
+
94
+ let d = document.getElementById('dump-dialog');
95
+ if (!d) {
96
+ d = document.body.appendChild(document.createElement('div'));
97
+ d.id = 'dump-dialog';
98
+ d.style.cssText =
99
+ 'position:fixed;top:30px;left:30px;right:50px;bottom:50px;' +
100
+ 'background:#fff;border:1px solid#333;box-shadow:0 0 10px rgba(0,0,0,0.5);' +
101
+ 'padding:20px;overflow:auto;z-index:9999;font:13px/1.4 monospace;white-space:pre';
102
+ }
103
+
104
+ // Check if we have a saved index and it's still valid
105
+ const savedIndex = parseInt(localStorage.getItem('_LOG_INDEX'));
106
+ if (!isNaN(savedIndex) && savedIndex >= 0 && savedIndex < logs.length) {
107
+ currentIndex = savedIndex;
108
+ } else {
109
+ currentIndex = logs.length - 1;
110
+ }
111
+
112
+ const renderContent = () => {
113
+ const buttons = logs.map((_, i) => {
114
+ let bgColor = '#f0f0f0'; // default
115
+ if (i !== currentIndex) {
116
+ if (logTypes[i] === 'object') {
117
+ bgColor = '#d6e3ef'; // super light blue
118
+ } else if (logTypes[i] === 'array') {
119
+ bgColor = '#d8d5ef'; // super light indigo
120
+ }
121
+ }
122
+ return `<button style="padding:4px 8px;margin:0;cursor:pointer;background:${i === currentIndex ? '#333' : bgColor};color:${i === currentIndex ? '#fff' : '#000'}" data-index="${i}">${i + 1}</button>`
123
+ }).join('');
124
+
125
+ d.innerHTML =
126
+ '<div style="display:flex;flex-direction:column;height:100%">' +
127
+ '<div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:10px">' +
128
+ '<div style="display:flex;flex-wrap:wrap;gap:4px;flex:1;margin-right:10px">' + buttons + '</div>' +
129
+ '<button style="padding:4px 8px;cursor:pointer;flex-shrink:0">&times;</button>' +
130
+ '</div>' +
131
+ '<xmp style="flex:1;overflow:auto;margin:0;padding:0;color:#000;background:#fff;font-size:14px;line-height:22px">' + logs[currentIndex] + '</xmp>' +
132
+ '</div>';
133
+
134
+ d.querySelector('button[style*="flex-shrink:0"]').onclick = () => d.remove();
135
+
136
+ d.querySelectorAll('button[data-index]').forEach(btn => {
137
+ btn.onclick = () => {
138
+ currentIndex = parseInt(btn.dataset.index);
139
+ localStorage.setItem('_LOG_INDEX', currentIndex);
140
+ renderContent();
141
+ };
142
+ });
143
+ };
144
+
145
+ renderContent();
146
+ };
147
+ })();
148
+
149
+ if (typeof window !== 'undefined') {
150
+ window.LOG = LOG
151
+ window.LOG_PP = LOG_PP
152
+ }
153
+
154
+ export default LOG
package/src/rollup.js CHANGED
@@ -1,31 +1,82 @@
1
- function fezPlugin() {
2
- return {
3
- name: 'fez-plugin',
1
+ // import .fez files and import globing via fezImport(./foo/bar/*)
2
+ // svelte is transformed to component import, all other files are copied
3
+ //
4
+ // rollup.config.js
5
+ // import fezImport from '@dinoreic/fez/rollup';
6
+ // plugins: [fezImport(), ...]
7
+
8
+ import { glob } from 'glob';
9
+ import path from 'path';
10
+
11
+ // compile fez files
12
+ const transformFez = (code, filePath) => {
13
+ const baseName = filePath.split('/').pop().split('.');
14
+
15
+ if (baseName[1] === 'fez') {
16
+ code = code.replace(/`/g, '\\`').replace(/\$/g, '\\$');
17
+ return `Fez.compile('${baseName[0]}', \`\n${code}\`)`;
18
+ }
19
+ }
20
+
21
+ // glob import files
22
+ const transformGlob = async (code, filePath) => {
23
+ // Only process .js files containing glob statements
24
+ if (!filePath.endsWith('.js')) {
25
+ return null;
26
+ }
27
+
28
+ // Check for fezImport() function calls
29
+ const globImportMatch = code.match(/fezImport\(['"`]([^'"`]+)['"`]\)/);
30
+ if (globImportMatch) {
31
+ const globPattern = globImportMatch[1];
32
+
33
+ // Resolve relative path from the file's directory
34
+ const fileDir = path.dirname(filePath);
35
+ const resolvedPattern = path.resolve(fileDir, globPattern);
4
36
 
5
- transform(code, filePath) {
6
- const baseName = filePath.split('/').pop().split('.');
37
+ const files = await glob(resolvedPattern, { absolute: true });
38
+ const imports = [];
39
+ const bindings = [];
7
40
 
8
- if (baseName[1] === 'fez') {
9
- code = code.replace(/`/g, '\\`').replace(/\$/g, '\\$');
10
- const transformedCode = `Fez.compile('${baseName[0]}', \`\n${code}\`)`;
41
+ console.log('fezGlob(', globPattern, '), files:', files.length);
11
42
 
12
- // if (baseName[0] === 'admin-menu') {
13
- // console.log('Transformed code:', baseName, transformedCode);
14
- // }
43
+ for (const file of files.sort()) {
44
+ if (file.endsWith('.svelte')) {
45
+ // Transform Svelte files with bindings
46
+ const name = path.basename(file, '.svelte').replace(/-/g, '_');
47
+ imports.push(`import Svelte_${name} from '${file}';`);
48
+ bindings.push(`Svelte.connect('s-${name.replace(/_/g, '-')}', Svelte_${name});`);
49
+ } else {
50
+ // Regular import for all other files
51
+ const name = path.basename(file, path.extname(file)).replace(/-/g, '_');
52
+ imports.push(`import ${name} from '${file}';`);
53
+ }
54
+ }
55
+
56
+ const replacement = [...imports, '', ...bindings].join('\n');
57
+ return code.replace(globImportMatch[0], replacement);
58
+ }
15
59
 
16
- return {
17
- code: transformedCode,
18
- map: null,
19
- };
60
+ return null;
61
+ }
62
+
63
+ export default function fezImport() {
64
+ return {
65
+ name: 'fez-plugin',
66
+
67
+ async transform(code, filePath) {
68
+ for (const func of [transformFez, transformGlob]) {
69
+ const result = await func(code, filePath);
70
+ if (result) {
71
+ return {
72
+ code: result,
73
+ map: null,
74
+ };
75
+ }
20
76
  }
77
+
78
+ return null;
21
79
  },
22
80
  };
23
81
  }
24
82
 
25
- // Export for ES modules
26
- export default fezPlugin;
27
-
28
- // Export for CommonJS
29
- // if (typeof module !== 'undefined') {
30
- // module.exports = fezPlugin;
31
- // }
package/dist/rollup.js DELETED
@@ -1,3 +0,0 @@
1
- (()=>{function t(){return{name:"fez-plugin",transform(e,r){let n=r.split("/").pop().split(".");if(n[1]==="fez")return e=e.replace(/`/g,"\\`").replace(/\$/g,"\\$"),{code:`Fez.compile('${n[0]}', \`
2
- ${e}\`)`,map:null}}}}var l=t;})();
3
- //# sourceMappingURL=rollup.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/rollup.js"],
4
- "sourcesContent": ["function fezPlugin() {\n return {\n name: 'fez-plugin',\n\n transform(code, filePath) {\n const baseName = filePath.split('/').pop().split('.');\n\n if (baseName[1] === 'fez') {\n code = code.replace(/`/g, '\\\\`').replace(/\\$/g, '\\\\$');\n const transformedCode = `Fez.compile('${baseName[0]}', \\`\\n${code}\\`)`;\n\n // if (baseName[0] === 'admin-menu') {\n // console.log('Transformed code:', baseName, transformedCode);\n // }\n\n return {\n code: transformedCode,\n map: null,\n };\n }\n },\n };\n}\n\n// Export for ES modules\nexport default fezPlugin;\n\n// Export for CommonJS\n// if (typeof module !== 'undefined') {\n// module.exports = fezPlugin;\n// }\n"],
5
- "mappings": "MAAA,SAASA,GAAY,CACnB,MAAO,CACL,KAAM,aAEN,UAAUC,EAAMC,EAAU,CACxB,IAAMC,EAAWD,EAAS,MAAM,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,EAEpD,GAAIC,EAAS,CAAC,IAAM,MAClB,OAAAF,EAAOA,EAAK,QAAQ,KAAM,KAAK,EAAE,QAAQ,MAAO,KAAK,EAO9C,CACL,KAPsB,gBAAgBE,EAAS,CAAC,CAAC;AAAA,EAAUF,CAAI,MAQ/D,IAAK,IACP,CAEJ,CACF,CACF,CAGA,IAAOG,EAAQJ",
6
- "names": ["fezPlugin", "code", "filePath", "baseName", "rollup_default"]
7
- }