@yhwh-script/shadow-h4x 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org>
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # shadow-h4x
2
+
3
+ This is a lifecycle implementation of CustomElements for standard-conforming WebComponents.
4
+
5
+ ## Getting started
6
+
7
+ To install shadow-h4x into your project, simply run
8
+
9
+ ```bash
10
+ npm install @yhwh-script/shadow-h4x
11
+ ```
12
+
13
+ ## How-To
14
+
15
+ Please stick to the following conventions! When working with Vite (recommended), put your components into `public/components` folder. Then add a `generate` script command to your `package.json`:
16
+
17
+ ```javascript
18
+ "scripts": {
19
+ "dev": "npm run generate && vite",
20
+ "build": "npm run generate && vite build",
21
+ "preview": "vite preview",
22
+ "generate": "node node_modules/@yhwh-script/shadow-h4x/generate.cjs"
23
+ }
24
+ ```
25
+
26
+ This will autogenerate a map of your WebComponents inside the `public/components` folder and define each WebComponents in the CustemElements registry. This is a feature! You don't have to register your elements manually. Just put them into the right folder.
27
+
28
+ Important:
29
+
30
+ Each WebComponent must be located in a subfolder under `public/components`, for instance:
31
+ `router/router-app.html`.
package/generate.cjs ADDED
@@ -0,0 +1,48 @@
1
+ const fs = require('fs')
2
+ const path = require('path');
3
+
4
+ process.chdir('.');
5
+
6
+ const constants = {
7
+ COMPONENTS_DIR: path.join(path.resolve(__dirname, '../../'), 'public/components'),
8
+ }
9
+
10
+ const elements = [];
11
+ try {
12
+ fs.readdirSync(constants.COMPONENTS_DIR, { withFileTypes: true })
13
+ .filter((dir) => dir.isDirectory())
14
+ .forEach((folder) => {
15
+ console.log(folder);
16
+ const fileNames = fs.readdirSync(
17
+ path.join(constants.COMPONENTS_DIR, folder.name)
18
+ );
19
+ fileNames.forEach((fileName) => {
20
+ if (fileName.indexOf("-") != -1) {
21
+ const dashSplit = fileName.split('-');
22
+ const prefix = dashSplit[0];
23
+ const dotSplit = dashSplit[1].split('.');
24
+ const suffix = dotSplit[0];
25
+ // elements.push(join(constants.ELEMENTS_DIR, folder.name, prefix + '-' + suffix + '.html'))
26
+
27
+ // Solution 1: Use path.posix.join for consistent forward slashes
28
+ const elementPath = path.posix.join('components', folder.name, prefix + '-' + suffix + '.html');
29
+ elements.push(elementPath);
30
+
31
+ // Alternative Solution 2: Normalize path separators
32
+ // const elementPath = join(constants.ELEMENTS_DIR, folder.name, prefix + '-' + suffix + '.html');
33
+ // elements.push(elementPath.replace(/\\/g, '/'));
34
+ }
35
+ });
36
+ });
37
+ } catch (e) {
38
+ if (e instanceof TypeError) {
39
+ console.error("WRONG GENERATION ERROR: Maybe there is a wrong filename? Use prefix/prefix-suffix.html in elements folder!")
40
+ // TODO should I ignore? maybe add a start option. Or prompt to move.
41
+ }
42
+ throw e;
43
+ }
44
+
45
+ fs.writeFileSync(
46
+ path.join('public/components', 'index.js'),
47
+ `export const htmlFiles=${JSON.stringify(elements, null, 2)};`
48
+ )
package/index.js ADDED
@@ -0,0 +1,80 @@
1
+ import { htmlFiles } from '/components';
2
+
3
+ window.getShadowDocument = function magic(hostDataIDs) {
4
+ if (typeof hostDataIDs === 'string') { hostDataIDs = hostDataIDs.split(','); }
5
+ else if (Array.isArray(hostDataIDs)) { hostDataIDs = hostDataIDs.toReversed(); }
6
+ else return undefined;
7
+ if (hostDataIDs) {
8
+ let shadowDOM = document;
9
+ for (let hostDataID of hostDataIDs) {
10
+ let found = shadowDOM.querySelector('[data-id="' + hostDataID + '"]');
11
+ if (found) { shadowDOM = found.shadowRoot; } else {
12
+ console.error({hostDataID});
13
+ return null; }
14
+ }
15
+ return shadowDOM;
16
+ }
17
+ return null;
18
+ }
19
+ for (const filePath of htmlFiles) {
20
+ const fileName = filePath.split("/").pop();
21
+ const dashSplit = fileName.split('-');
22
+ const prefix = dashSplit[0];
23
+ const dotSplit = dashSplit[1].split('.'); // TODO accept three-fold-components
24
+ const suffix = dotSplit[0];
25
+ fetch(filePath)
26
+ .then(file => file.text())
27
+ .then(html => {
28
+ const fragment = document.createRange().createContextualFragment(html);
29
+ const scriptFragment = fragment.querySelector("script");
30
+ const styleFragment = fragment.querySelector("style");
31
+ const templateFragment = fragment.querySelector("template");
32
+ customElements.define(`${prefix}-${suffix}`, class extends HTMLElement {
33
+ constructor() {
34
+ super();
35
+ const shadowRoot = this.attachShadow({ mode: "open" });
36
+ console.log({scriptFragment})
37
+ }
38
+ connectedCallback() {
39
+ this.hostDataIDs = []; // used to find the nested shadowDocument
40
+ this.dataset.id = Math.random().toString(16).substring(2, 8); // should suffice
41
+ let hostElement = this;
42
+ while (hostElement && hostElement.dataset.id) { // +3 get parent.host data-id 's
43
+ this.hostDataIDs.push(hostElement.dataset.id);
44
+ hostElement = hostElement.getRootNode().host;
45
+ }
46
+ this.#render();
47
+ }
48
+ #render() {
49
+ this.shadowRoot.replaceChildren();
50
+ this.#appendTemplate();
51
+ this.#appendStyle();
52
+ this.#appendScript();
53
+ }
54
+ #appendScript() {
55
+ if (scriptFragment) {
56
+ const scriptElement = document.createElement("script");
57
+ scriptElement.setAttribute("type", "module");
58
+ scriptElement.textContent = `
59
+ const shadowDocument = getShadowDocument('${this.hostDataIDs.toReversed().toString()}');
60
+ ${scriptFragment ? scriptFragment.textContent : ''}
61
+ `;
62
+ console.log("appending", scriptFragment.textContent)
63
+ this.shadowRoot.appendChild(scriptElement);
64
+ }
65
+ }
66
+ #appendStyle() {
67
+ if (styleFragment) {
68
+ let clonedStyle = styleFragment.cloneNode(true);
69
+ this.shadowRoot.appendChild(clonedStyle);
70
+ }
71
+ }
72
+ #appendTemplate() {
73
+ if (templateFragment) {
74
+ const clonedFragment = templateFragment.content.cloneNode(true);
75
+ this.shadowRoot.appendChild(clonedFragment);
76
+ }
77
+ }
78
+ });
79
+ });
80
+ }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "author": "Jahrome <yhwhscript@gmail.com>",
3
+ "bugs": {
4
+ "url": "https://github.com/yhwh-script/shadow-h4x/issues"
5
+ },
6
+ "description": "This is a lifecycle implementation of CustomElements for standard-conforming WebComponents.",
7
+ "homepage": "https://github.com/yhwh-script/shadow-h4x#readme",
8
+ "keywords": [
9
+ "JavaScript",
10
+ "Hack",
11
+ "CustomElements",
12
+ "WebComponents",
13
+ "Vanilla"
14
+ ],
15
+ "license": "Unlicense",
16
+ "main": "index.js",
17
+ "name": "@yhwh-script/shadow-h4x",
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/yhwh-script/shadow-h4x.git"
24
+ },
25
+ "type": "module",
26
+ "version": "1.0.0"
27
+ }