carbonium 1.3.0 → 2.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/README.md CHANGED
@@ -26,13 +26,13 @@ $("div")
26
26
  You can use carbonium to create elements:
27
27
 
28
28
  ```javascript
29
- const error = $("<div class='error'>An error has occured!</div>")[0];
29
+ const error = $("<div class='error'>An error has occurred!</div>")[0];
30
30
  ```
31
31
 
32
32
  ## Installation
33
33
 
34
34
  ```bash
35
- npm install --save-dev carbonium
35
+ npm install carbonium
36
36
  ```
37
37
 
38
38
  Now you can import carbonium:
@@ -44,11 +44,62 @@ import { $ } from "carbonium";
44
44
  If you don't want to install or use a bundler like webpack or rollup.js, you can import carbonium like this:
45
45
 
46
46
  ```javascript
47
- const { $ } = await import(
48
- "https://cdn.jsdelivr.net/npm/carbonium@1/dist/bundle.min.js"
49
- );
47
+ const { $ } =
48
+ await import("https://cdn.jsdelivr.net/npm/carbonium@2/dist/bundle.min.js");
50
49
  ```
51
50
 
51
+ ## Upgrading from version 1
52
+
53
+ ### ES module only
54
+
55
+ Since version 2, carbonium is only distributed as an ES module.
56
+ The IIFE bundle (`dist/bundle.iife.min.js`), which set a global `carbonium` variable, has been removed.
57
+
58
+ If you loaded carbonium with a classic script tag:
59
+
60
+ ```html
61
+ <script src="https://cdn.jsdelivr.net/npm/carbonium@1/dist/bundle.iife.min.js"></script>
62
+ <script>
63
+ const { $ } = carbonium;
64
+ </script>
65
+ ```
66
+
67
+ import it in a module script instead:
68
+
69
+ ```html
70
+ <script type="module">
71
+ import { $ } from "https://cdn.jsdelivr.net/npm/carbonium@2/dist/bundle.min.js";
72
+ </script>
73
+ ```
74
+
75
+ Bundlers now always use the ES module, because the `browser` field has been removed from `package.json`.
76
+ Code that imports carbonium with `import { $ } from "carbonium"` needs no changes.
77
+
78
+ ### Changed behaviour
79
+
80
+ - `$(html)` returns all created top-level elements, not only the first one.
81
+ The HTML may start with whitespace, and table parts like `<tr>` and `<td>` can be created.
82
+ The `parentNode` argument of `$(html)`, which had no effect, has been removed.
83
+ - The result is a real array: `Array.isArray($("p"))` is `true`. It is no longer a `NodeList`.
84
+ - `style`, `classList` and `relList` read from the first element and write to all elements.
85
+ In version 1, reading and setting properties like `$("p").style.color` used `document.body`.
86
+ - Methods of `style`, `classList` and `relList` return their result, so `classList.contains()` returns a boolean.
87
+ In version 1, they always returned the list.
88
+ - Element methods return the result of the first element, also when that is `null`.
89
+ For example, `getAttribute()` of a missing attribute returns `null`. In version 1, it returned the list.
90
+ - Properties with a falsy value return that value, so `$("input").disabled` can be `false`.
91
+ In version 1, it gave `undefined`.
92
+ - Array methods that return a value, like `some()` and `indexOf()`, return that value.
93
+ In version 1, they threw a `TypeError`.
94
+ - Reading a property of an empty list gives `undefined`. In version 1, it read the property of `document.body`.
95
+
96
+ ### TypeScript
97
+
98
+ - The element type can be any `Element`, not only an `HTMLElement`, so `$<SVGCircleElement>("circle")` works.
99
+ - `parentNode` can be any `ParentNode`, like a `DocumentFragment`.
100
+ - Element methods that return nothing, like `addEventListener()`, `append()` and `remove()`, are typed to return the list, so they can be chained.
101
+ - `style.removeProperty()` is typed to return a `string`.
102
+
52
103
  ## API
53
104
 
54
105
  ### Select elements
@@ -57,29 +108,37 @@ const { $ } = await import(
57
108
 
58
109
  #### Parameters
59
110
 
60
- | Name | Type | Description |
61
- | ---------- | ------------------------------ | -------------------------------------------------------------------------- |
62
- | selector | string | Selector to select elements |
63
- | parentNode | Document \| Element (optional) | Document or element in which to apply the selector, defaults to `document` |
111
+ | Name | Type | Description |
112
+ | ---------- | -------------------------------------------- | --------------------------------------------------------------------------------------- |
113
+ | selector | string | Selector to select elements |
114
+ | parentNode | Document \| Element \| ShadowRoot (optional) | Document, element or shadow root in which to apply the selector, defaults to `document` |
64
115
 
65
116
  #### Returns
66
117
 
67
- An array of the matched elements, which can also be accessed as a single element.
118
+ An array of the matched elements, which can also be accessed as a single element:
119
+
120
+ - Setting a property sets it on all elements.
121
+ - Reading a property reads it from the first element. On an empty list, it gives `undefined`.
122
+ - Calling a method calls it on all elements and returns the result of the first element.
123
+ When the method returns nothing, like `setAttribute()` or `remove()`, it returns the list, so you can chain calls.
124
+ - `style`, `classList` and `relList` work the same way: `$("p").classList.add("note")` adds the class to all paragraphs,
125
+ `$("p").classList.contains("note")` tells whether the first paragraph has it.
126
+ - Array methods, like `forEach()`, `filter()` and `map()`, work as usual.
127
+ The ones that return an array, like `filter()`, return a new carbonium list.
68
128
 
69
- ### Create element
129
+ ### Create elements
70
130
 
71
- ### `$(html [, parentNode])`
131
+ ### `$(html)`
72
132
 
73
133
  #### Parameters
74
134
 
75
- | Name | Type | Description |
76
- | ---------- | ------------------------------ | -------------------------------------------------------------------------- |
77
- | html | string | HTML of element to create, starting with "<" |
78
- | parentNode | Document \| Element (optional) | Document or element in which to apply the selector, defaults to `document` |
135
+ | Name | Type | Description |
136
+ | ---- | ------ | --------------------------------------------- |
137
+ | html | string | HTML of elements to create, starting with "<" |
79
138
 
80
139
  #### Returns
81
140
 
82
- An array with one created element.
141
+ An array with the created top-level elements, which can also be accessed as a single element.
83
142
 
84
143
  ## TypeScript
85
144
 
@@ -1,7 +1,7 @@
1
1
  /**
2
- Carbonium 1.3.0
2
+ Carbonium 2.0.0
3
3
  @copyright 2020 Edwin Martin
4
4
  @license MIT
5
5
  */
6
- function e(e,t){let n;return n=e.startsWith("<")?[(new DOMParser).parseFromString(e,"text/html").body.firstChild]:(t||document).querySelectorAll(e),new Proxy(n,o)}let t,n;const o={get(e,r){let l=null;if(r==Symbol.iterator)return function*(){for(const t of e)yield t};if("style"==r||"classList"==r||"relList"==r){t=e,n=r;const l=Reflect.get(document.body,r);return new Proxy(l,o)}if(e instanceof CSSStyleDeclaration||e instanceof DOMTokenList)return l=Reflect.get(document.body[n],r),"function"==typeof l?new Proxy(l,{apply:function(e,r,l){return t.forEach((t=>{Reflect.apply(e,t[n],l)})),new Proxy(t,o)}}):l;if(Array.prototype.hasOwnProperty(r)){const e=Reflect.get(Array.prototype,r);if("function"==typeof e)return new Proxy(e,{apply:function(e,t,n){const r=Reflect.apply(e,t,n);return new Proxy(void 0!==r?r:t,o)}})}return e.length>0?r in e[0]&&(l=Reflect.get(e[0],r)):r in document.body&&(l=Reflect.get(document.body,r)),l?"function"==typeof l?new Proxy(l,{apply:function(e,t,n){let o=null,r=!0;for(const l of t){const t=Reflect.apply(e,l,n);r&&(o=t,r=!1)}return null!=o?o:t}}):l:Reflect.get(e,r)},set:(e,t,n)=>(!("forEach"in e)||e instanceof CSSStyleDeclaration?Reflect.set(e,t,n):e.forEach((e=>{Reflect.set(e,t,n)})),!0),deleteProperty:(e,t)=>t in e&&delete e[t]};export{e as $};
6
+ function e(e,t=document){let n;if(e.trim().startsWith("<")){const t=document.createElement("template");t.innerHTML=e,n=[...t.content.children]}else n=[...t.querySelectorAll(e)];return new Proxy(n,c)}let t;const n=(e,t,n)=>(...c)=>{const r=e.map(e=>Reflect.apply(n,e,c));return void 0===r[0]?t:r[0]},c={get(e,r,o){if(r in e){const t=Reflect.get(e,r);return"function"==typeof t?(...n)=>{const r=Reflect.apply(t,e,n);return void 0===r?o:Array.isArray(r)?new Proxy(r,c):r}:t}const l=e[0]||t||(t=document.createElement("a"));if("style"==r||"classList"==r||"relList"==r){const t=e.map(e=>Reflect.get(e,r));return new Proxy(Reflect.get(l,r),{get(e,c){const r=Reflect.get(e,c);return"function"==typeof r?n(t,o,r):r},set:(e,n,c)=>(t.forEach(e=>Reflect.set(e,n,c)),!0)})}const s=Reflect.get(l,r);return"function"==typeof s?n(e,o,s):e.length?s:void 0},set:(e,t,n)=>(e.forEach(e=>Reflect.set(e,t,n)),!0)};export{e as $};
7
7
  //# sourceMappingURL=bundle.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.min.js","sources":["../src/carbonium.ts"],"sourcesContent":[null],"names":["$","selectors","parentNode","nodelist","startsWith","DOMParser","parseFromString","body","firstChild","document","querySelectorAll","Proxy","proxyHandler","currentListNodelist","propList","get","target","prop","propValue","Symbol","iterator","element","Reflect","CSSStyleDeclaration","DOMTokenList","apply","thisArg","argumentsList","forEach","el","Array","prototype","hasOwnProperty","ret","length","retFirst","first","set","value","deleteProperty"],"mappings":";;;;;AAMM,SAAUA,EACdC,EACAC,GAEA,IAAIC,EAeJ,OAXEA,EADEF,EAAUG,WAAW,KAEX,EACR,IAAIC,WAAYC,gBAAgBL,EAAW,aAAaM,KAAKC,aAKrDN,GAAcO,UAAUC,iBAAiBT,GAK3C,IAAIU,MAAqBR,EAAUS,EAEjD,CAIA,IAAIC,EACAC,EAEJ,MAAMF,EAAsD,CAC1D,GAAAG,CAAIC,EAAQC,GACV,IAAIC,EAAY,KAGhB,GAAID,GAAQE,OAAOC,SACjB,OAAO,YACL,IAAK,MAAMC,KAAWL,QACdK,CAEV,EAIF,GAAY,SAARJ,GAA2B,aAARA,GAA+B,WAARA,EAAmB,CAC/DJ,EAAsBG,EACtBF,EAAWG,EAGX,MAAMC,EAAYI,QAAQP,IAAIN,SAASF,KAAMU,GAC7C,OAAO,IAAIN,MAAMO,EAAWN,EAC9B,CAGA,GACEI,aAAkBO,qBAClBP,aAAkBQ,aAOlB,OAHAN,EAAYI,QAAQP,IAAKN,SAASF,KAAaO,GAAWG,GAGlC,mBAAbC,EACF,IAAIP,MAAgBO,EAAW,CACpCO,MAAO,SAAUT,EAAQU,EAASC,GAIhC,OAHAd,EAAoBe,SAASC,IAC3BP,QAAQG,MAAMT,EAASa,EAAWf,GAAWa,EAAc,IAEtD,IAAIhB,MAAME,EAAqBD,EACxC,IAGKM,EAKX,GAAIY,MAAMC,UAAUC,eAAef,GAAO,CACxC,MAAMC,EAAYI,QAAQP,IAAIe,MAAMC,UAAWd,GAC/C,GAAwB,mBAAbC,EACT,OAAO,IAAIP,MAAgBO,EAAW,CACpCO,MAAO,SAAUT,EAAQU,EAASC,GAChC,MAAMM,EAAMX,QAAQG,MAAMT,EAAQU,EAASC,GAK3C,OAAO,IAAIhB,WADqB,IAAPsB,EAAqBA,EAAMP,EACxBd,EAC9B,GAGN,CAkBA,OAfII,EAAOkB,OAAS,EAGdjB,KAAQD,EAAO,KACjBE,EAAYI,QAAQP,IAAIC,EAAO,GAAIC,IAKjCA,KAAQR,SAASF,OACnBW,EAAYI,QAAQP,IAAIN,SAASF,KAAMU,IAKvCC,EACsB,mBAAbA,EACF,IAAIP,MAAgBO,EAAW,CACpCO,MAAO,SAAUT,EAAQU,EAASC,GAChC,IAAIQ,EAAW,KACXC,GAAQ,EAEZ,IAAK,MAAMP,KAAMH,EAAS,CACxB,MAAMO,EAAMX,QAAQG,MAAMT,EAAQa,EAAIF,GAClCS,IACFD,EAAWF,EACXG,GAAQ,EAEZ,CACA,OAAOD,QAAAA,EAAYT,CACrB,IAGKR,EAKJI,QAAQP,IAAIC,EAAQC,EAC7B,EAGAoB,IAAG,CAACrB,EAAQC,EAAMqB,OACZ,YAAatB,IAAYA,aAAkBO,oBAK7CD,QAAQe,IAAIrB,EAAQC,EAAMqB,GAJ1BtB,EAAOY,SAASC,IACdP,QAAQe,IAAIR,EAAIZ,EAAMqB,EAAM,KAKzB,GAGTC,eAAc,CAACvB,EAAQC,IACjBA,KAAQD,UACKA,EAAeC"}
1
+ {"version":3,"file":"bundle.min.js","sources":["../src/carbonium.ts"],"sourcesContent":[null],"names":["$","selectors","parentNode","document","list","trim","startsWith","template","createElement","innerHTML","content","children","querySelectorAll","Proxy","proxyHandler","reference","callAll","objects","receiver","fn","args","results","map","object","Reflect","apply","undefined","get","prop","value","result","Array","isArray","first","el","key","set","_","forEach","length"],"mappings":";;;;;SAMgBA,EACdC,EACAC,EAAyBC,UAEzB,IAAIC,EAGJ,GAAIH,EAAUI,OAAOC,WAAW,KAAM,CACpC,MAAMC,EAAWJ,SAASK,cAAc,YACxCD,EAASE,UAAYR,EACrBG,EAAO,IAAIG,EAASG,QAAQC,SAC9B,MAEEP,EAAO,IAAIF,EAAWU,iBAAiBX,IAIzC,OAAmC,IAAIY,MAAM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29 +3,38 @@
3
3
  @copyright 2020 Edwin Martin
4
4
  @license MIT
5
5
  */
6
- export declare function $<T extends HTMLElement = HTMLElement>(selectors: string, parentNode?: Document | ShadowRoot | HTMLElement): CarboniumType<T>;
7
- export type CarboniumType<T extends HTMLElement = HTMLElement> = CarboniumList<T> & T;
8
- interface CarboniumList<T extends HTMLElement> extends Array<T> {
6
+ export declare function $<T extends Element = HTMLElement>(selectors: string, parentNode?: ParentNode): CarboniumType<T>;
7
+ export type CarboniumType<T extends Element = HTMLElement> = CarboniumList<T> & T;
8
+ interface CarboniumList<T extends Element> extends Array<T> {
9
9
  concat(...items: ConcatArray<T>[]): CarboniumType<T>;
10
10
  concat(...items: (T | ConcatArray<T>)[]): CarboniumType<T>;
11
11
  reverse(): CarboniumType<T>;
12
12
  slice(start?: number, end?: number): CarboniumType<T>;
13
13
  splice(start: number, deleteCount?: number): CarboniumType<T>;
14
14
  splice(start: number, deleteCount: number, ...items: T[]): CarboniumType<T>;
15
- forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): CarboniumType<T>;
16
- filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): CarboniumType<T>;
15
+ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: unknown): CarboniumType<T>;
16
+ filter(callbackfn: (value: T, index: number, array: T[]) => unknown, thisArg?: unknown): CarboniumType<T>;
17
17
  setAttribute(qualifiedName: string, value: string): CarboniumType<T>;
18
+ removeAttribute(qualifiedName: string): CarboniumType<T>;
19
+ addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: T, ev: HTMLElementEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): CarboniumType<T>;
20
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): CarboniumType<T>;
21
+ removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: T, ev: HTMLElementEventMap[K]) => unknown, options?: boolean | EventListenerOptions): CarboniumType<T>;
22
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): CarboniumType<T>;
23
+ append(...nodes: (Node | string)[]): CarboniumType<T>;
24
+ prepend(...nodes: (Node | string)[]): CarboniumType<T>;
25
+ before(...nodes: (Node | string)[]): CarboniumType<T>;
26
+ after(...nodes: (Node | string)[]): CarboniumType<T>;
27
+ remove(): CarboniumType<T>;
18
28
  classList: CarboniumClassList<T>;
29
+ relList: CarboniumClassList<T>;
19
30
  style: CarboniumStyleList<T>;
20
31
  }
21
- interface CarboniumClassList<T extends HTMLElement> extends DOMTokenList {
32
+ interface CarboniumClassList<T extends Element> extends DOMTokenList {
22
33
  add(...tokens: string[]): CarboniumType<T>;
23
34
  remove(...tokens: string[]): CarboniumType<T>;
24
- replace(oldToken: string, newToken: string): boolean;
25
- forEach(callbackfn: (value: string, key: number, parent: DOMTokenList) => void, thisArg?: any): CarboniumType<T>;
35
+ forEach(callbackfn: (value: string, key: number, parent: DOMTokenList) => void, thisArg?: unknown): CarboniumType<T>;
26
36
  }
27
- interface CarboniumStyleList<T extends HTMLElement> extends CSSStyleDeclaration {
28
- removeProperty(property: string): CarboniumList<T> & string;
37
+ interface CarboniumStyleList<T extends Element> extends CSSStyleDeclaration {
29
38
  setProperty(property: string, value: string | null, priority?: string): CarboniumType<T>;
30
39
  }
31
40
  export {};
package/package.json CHANGED
@@ -1,22 +1,24 @@
1
1
  {
2
2
  "name": "carbonium",
3
- "version": "1.3.0",
3
+ "version": "2.0.0",
4
4
  "description": "One kilobyte library for easy DOM manipulation",
5
5
  "type": "module",
6
- "browser": "dist/bundle.iife.min.js",
7
6
  "module": "dist/bundle.min.js",
8
7
  "types": "dist/carbonium.d.ts",
9
8
  "sideEffects": false,
10
9
  "scripts": {
11
10
  "prepare": "husky",
12
- "start": "http-server -o demo/ --silent",
11
+ "start": "node scripts/serve-demo.mjs",
13
12
  "build": "rollup --config --sourcemap",
14
13
  "dev": "rollup --config --sourcemap --watch",
15
- "release": "npm i --package-lock && npm run lint && npm test && npm publish",
14
+ "release": "npm ci --ignore-scripts && npm run lint && npm test && npm publish",
16
15
  "pretest": "npm run build",
17
16
  "test": "playwright test",
18
- "lint": "npx eslint .",
19
- "prettier": "prettier --config .prettierrc.json src/**/*.ts *.json --write"
17
+ "playwright:install": "playwright install --with-deps chromium firefox",
18
+ "lint": "eslint .",
19
+ "prettier": "prettier --config .prettierrc.json src/**/*.ts *.json --write",
20
+ "prettier:staged": "pretty-quick --staged",
21
+ "prestart": "npm run build"
20
22
  },
21
23
  "repository": {
22
24
  "type": "git",
@@ -26,9 +28,7 @@
26
28
  "src/carbonium.ts",
27
29
  "dist/carbonium.d.ts",
28
30
  "dist/bundle.min.js",
29
- "dist/bundle.min.js.map",
30
- "dist/bundle.iife.min.js",
31
- "dist/bundle.iife.min.js.map"
31
+ "dist/bundle.min.js.map"
32
32
  ],
33
33
  "keywords": [
34
34
  "front-end",
@@ -51,24 +51,23 @@
51
51
  },
52
52
  "homepage": "https://github.com/edwinm/carbonium#readme",
53
53
  "devDependencies": {
54
- "@eslint/js": "^9.39.4",
55
- "@playwright/test": "^1.59.1",
56
- "@rollup/plugin-replace": "^6.0.3",
57
- "@rollup/plugin-terser": "^1.0.0",
58
- "@rollup/plugin-typescript": "^12.3.0",
59
- "@types/node": "^22.19.17",
60
- "@typescript-eslint/eslint-plugin": "^8.58.0",
61
- "@typescript-eslint/parser": "^8.58.0",
62
- "eslint": "^9.39.4",
63
- "eslint-config-prettier": "^10.1.8",
64
- "globals": "^17.4.0",
65
- "http-server": "^14.1.1",
66
- "husky": "^9.1.7",
67
- "prettier": "^3.8.1",
68
- "pretty-quick": "^4.2.2",
69
- "rollup": "^4.60.1",
70
- "tslib": "^2.8.1",
71
- "typescript": "^6.0.2",
72
- "typescript-eslint": "^8.58.0"
54
+ "@eslint/js": "10.0.1",
55
+ "@playwright/test": "1.65.1",
56
+ "@rollup/plugin-replace": "6.0.3",
57
+ "@rollup/plugin-terser": "1.0.2",
58
+ "@rollup/plugin-typescript": "12.3.1",
59
+ "@types/node": "26.6.6",
60
+ "@typescript-eslint/eslint-plugin": "8.73.0",
61
+ "@typescript-eslint/parser": "8.73.0",
62
+ "eslint": "10.15.0",
63
+ "eslint-config-prettier": "10.1.8",
64
+ "globals": "17.14.0",
65
+ "husky": "9.1.7",
66
+ "prettier": "3.10.1",
67
+ "pretty-quick": "4.2.2",
68
+ "rollup": "4.68.8",
69
+ "tslib": "2.9.1",
70
+ "typescript": "6.0.3",
71
+ "typescript-eslint": "8.73.0"
73
72
  }
74
73
  }
package/src/carbonium.ts CHANGED
@@ -4,167 +4,103 @@
4
4
  @license MIT
5
5
  */
6
6
 
7
- export function $<T extends HTMLElement = HTMLElement>(
7
+ export function $<T extends Element = HTMLElement>(
8
8
  selectors: string,
9
- parentNode?: Document | ShadowRoot | HTMLElement
9
+ parentNode: ParentNode = document
10
10
  ): CarboniumType<T> {
11
- let nodelist: NodeListOf<T>;
12
-
13
- // If the first parameter starts with "<", create a DOM node
14
- if (selectors.startsWith("<")) {
15
- nodelist = <NodeListOf<T>>(
16
- (<unknown>[
17
- new DOMParser().parseFromString(selectors, "text/html").body.firstChild,
18
- ])
19
- );
11
+ let list: Element[];
12
+
13
+ // If the first parameter starts with "<", create DOM elements
14
+ if (selectors.trim().startsWith("<")) {
15
+ const template = document.createElement("template");
16
+ template.innerHTML = selectors;
17
+ list = [...template.content.children];
20
18
  } else {
21
19
  // Else, do querySelectorAll
22
- nodelist = (parentNode || document).querySelectorAll(selectors);
20
+ list = [...parentNode.querySelectorAll(selectors)];
23
21
  }
24
22
 
25
23
  // Wrap it in a Proxy
26
- return <CarboniumType<T>>(
27
- (<unknown>new Proxy<NodeListOf<T>>(nodelist, proxyHandler))
28
- );
24
+ return <CarboniumType<T>>(<unknown>new Proxy(list, proxyHandler));
29
25
  }
30
26
 
31
- // Used by style, classList and relList
32
- // When setting one of these, remember the elements to apply to
33
- let currentListNodelist: NodeListOf<HTMLElement>;
34
- let propList: "style" | "classList" | "relList";
35
-
36
- const proxyHandler: ProxyHandler<NodeListOf<HTMLElement>> = {
37
- get(target, prop) {
38
- let propValue = null;
39
-
40
- // Return iterator when asked for iterator, only used in ES2015+
41
- if (prop == Symbol.iterator) {
42
- return function* () {
43
- for (const element of target) {
44
- yield element;
45
- }
46
- };
47
- }
48
-
49
- // Special case for style, classList and relList
50
- if (prop == "style" || prop == "classList" || prop == "relList") {
51
- currentListNodelist = target;
52
- propList = prop;
53
- // Matched elements can be a list of any element or an empty list
54
- // Use getter of, for example, document.body.style
55
- const propValue = Reflect.get(document.body, prop);
56
- return new Proxy(propValue, proxyHandler);
57
- }
58
-
59
- // style.setProperty, getPropertyValue…, classList.add, contains, remove…, relList…
60
- if (
61
- target instanceof CSSStyleDeclaration ||
62
- target instanceof DOMTokenList
63
- ) {
64
- // Matched elements can be a list of any element or an empty list
65
- // Use getter of, for example, document.body.style.color
66
- propValue = Reflect.get((document.body as any)[propList], prop);
67
-
68
- // When getter is a function, apply it to all matched elements
69
- if (typeof propValue == "function") {
70
- return new Proxy<Function>(propValue, {
71
- apply: function (target, thisArg, argumentsList) {
72
- currentListNodelist.forEach((el) => {
73
- Reflect.apply(target, (el as any)[propList], argumentsList);
74
- });
75
- return new Proxy(currentListNodelist, proxyHandler);
76
- },
77
- });
78
- } else {
79
- return propValue;
27
+ type AnyFunction = (...args: unknown[]) => unknown;
28
+
29
+ // Stand-in for an empty list, created on first use.
30
+ // An <a>, because it has style, classList and relList.
31
+ let reference: HTMLAnchorElement | undefined;
32
+
33
+ // Call fn on all objects. Return the result of the first object,
34
+ // or, when that is undefined, the list, so calls can be chained.
35
+ const callAll =
36
+ (objects: unknown[], receiver: unknown, fn: AnyFunction) =>
37
+ (...args: unknown[]) => {
38
+ const results = objects.map((object) => Reflect.apply(fn, object, args));
39
+ return results[0] === undefined ? receiver : results[0];
40
+ };
41
+
42
+ const proxyHandler: ProxyHandler<Element[]> = {
43
+ get(list, prop, receiver) {
44
+ // Array members come first: indices, length, forEach, filter, iterator…
45
+ if (prop in list) {
46
+ const value = Reflect.get(list, prop);
47
+ if (typeof value == "function") {
48
+ return (...args: unknown[]) => {
49
+ const result = Reflect.apply(value, list, args);
50
+ // forEach returns undefined: return the list for chaining
51
+ // filter, slice… return an array: wrap it again
52
+ // some, indexOf, find… return a value: pass it on
53
+ return result === undefined
54
+ ? receiver
55
+ : Array.isArray(result)
56
+ ? new Proxy(result, proxyHandler)
57
+ : result;
58
+ };
80
59
  }
60
+ return value;
81
61
  }
82
62
 
83
- // Are we dealing with an Array function like forEach, map and filter?
84
- if (Array.prototype.hasOwnProperty(prop)) {
85
- const propValue = Reflect.get(Array.prototype, prop);
86
- if (typeof propValue == "function") {
87
- return new Proxy<Function>(propValue, {
88
- apply: function (target, thisArg, argumentsList) {
89
- const ret = Reflect.apply(target, thisArg, argumentsList);
90
- // When function returns undefined (like forEach),
91
- // return all matched elements, so calls can be chained
92
- // For example forEach(…).setAttribute(…)
93
- const newTarget = typeof ret != "undefined" ? ret : thisArg;
94
- return new Proxy(newTarget, proxyHandler);
95
- },
96
- });
97
- }
98
- }
63
+ // Read from the first element, or from the stand-in when the list is empty
64
+ const first = list[0] || (reference ||= document.createElement("a"));
99
65
 
100
- // Get property or call function on DOM elements
101
- if (target.length > 0) {
102
- // Might be DOM element specific, like input.select(),
103
- // so use first array element to get reference
104
- if (prop in target[0]) {
105
- propValue = Reflect.get(target[0], prop);
106
- }
107
- } else {
108
- // Empty list, targeted DOM element unknown,
109
- // use getter of document.body
110
- if (prop in document.body) {
111
- propValue = Reflect.get(document.body, prop);
112
- }
66
+ // style, classList and relList: read from the first, write to all
67
+ if (prop == "style" || prop == "classList" || prop == "relList") {
68
+ const objects = list.map((el) => Reflect.get(el, prop));
69
+ return new Proxy(Reflect.get(first, prop), {
70
+ get(object, key) {
71
+ const value = Reflect.get(object, key);
72
+ return typeof value == "function"
73
+ ? callAll(objects, receiver, value)
74
+ : value;
75
+ },
76
+ set(_, key, value) {
77
+ objects.forEach((object) => Reflect.set(object, key, value));
78
+ return true;
79
+ },
80
+ });
113
81
  }
114
82
 
115
- // Propagate DOM prop value
116
- if (propValue) {
117
- if (typeof propValue == "function") {
118
- return new Proxy<Function>(propValue, {
119
- apply: function (target, thisArg, argumentsList) {
120
- let retFirst = null;
121
- let first = true;
122
- // Apply on individual elements
123
- for (const el of thisArg) {
124
- const ret = Reflect.apply(target, el, argumentsList);
125
- if (first) {
126
- retFirst = ret;
127
- first = false;
128
- }
129
- }
130
- return retFirst ?? thisArg;
131
- },
132
- });
133
- } else {
134
- return propValue;
135
- }
83
+ // Methods are called on all elements, properties are read from the first
84
+ const value = Reflect.get(first, prop);
85
+ if (typeof value == "function") {
86
+ return callAll(list, receiver, value);
136
87
  }
137
-
138
- // Default
139
- return Reflect.get(target, prop);
88
+ return list.length ? value : undefined;
140
89
  },
141
90
 
142
- // DOM property is set
143
- set(target, prop, value) {
144
- if ("forEach" in target && !(target instanceof CSSStyleDeclaration)) {
145
- target.forEach((el) => {
146
- Reflect.set(el, prop, value);
147
- });
148
- } else {
149
- Reflect.set(target, prop, value);
150
- }
91
+ // Properties are set on all elements
92
+ set(list, prop, value) {
93
+ list.forEach((el) => Reflect.set(el, prop, value));
151
94
  return true;
152
95
  },
153
-
154
- deleteProperty(target, prop) {
155
- if (prop in target) {
156
- return delete (target as any)[prop];
157
- }
158
- return false;
159
- },
160
96
  };
161
97
 
162
- export type CarboniumType<T extends HTMLElement = HTMLElement> =
163
- CarboniumList<T> & T;
98
+ export type CarboniumType<T extends Element = HTMLElement> = CarboniumList<T> &
99
+ T;
164
100
 
165
101
  // Interface definitions
166
102
 
167
- interface CarboniumList<T extends HTMLElement> extends Array<T> {
103
+ interface CarboniumList<T extends Element> extends Array<T> {
168
104
  concat(...items: ConcatArray<T>[]): CarboniumType<T>;
169
105
 
170
106
  concat(...items: (T | ConcatArray<T>)[]): CarboniumType<T>;
@@ -180,38 +116,71 @@ interface CarboniumList<T extends HTMLElement> extends Array<T> {
180
116
 
181
117
  forEach(
182
118
  callbackfn: (value: T, index: number, array: T[]) => void,
183
- thisArg?: any
119
+ thisArg?: unknown
184
120
  ): CarboniumType<T>;
185
121
 
186
122
  filter(
187
- callbackfn: (value: T, index: number, array: T[]) => boolean,
188
- thisArg?: any
123
+ callbackfn: (value: T, index: number, array: T[]) => unknown,
124
+ thisArg?: unknown
189
125
  ): CarboniumType<T>;
190
126
 
127
+ // Element methods that return nothing return the list instead
128
+
191
129
  setAttribute(qualifiedName: string, value: string): CarboniumType<T>;
192
130
 
131
+ removeAttribute(qualifiedName: string): CarboniumType<T>;
132
+
133
+ addEventListener<K extends keyof HTMLElementEventMap>(
134
+ type: K,
135
+ listener: (this: T, ev: HTMLElementEventMap[K]) => unknown,
136
+ options?: boolean | AddEventListenerOptions
137
+ ): CarboniumType<T>;
138
+
139
+ addEventListener(
140
+ type: string,
141
+ listener: EventListenerOrEventListenerObject,
142
+ options?: boolean | AddEventListenerOptions
143
+ ): CarboniumType<T>;
144
+
145
+ removeEventListener<K extends keyof HTMLElementEventMap>(
146
+ type: K,
147
+ listener: (this: T, ev: HTMLElementEventMap[K]) => unknown,
148
+ options?: boolean | EventListenerOptions
149
+ ): CarboniumType<T>;
150
+
151
+ removeEventListener(
152
+ type: string,
153
+ listener: EventListenerOrEventListenerObject,
154
+ options?: boolean | EventListenerOptions
155
+ ): CarboniumType<T>;
156
+
157
+ append(...nodes: (Node | string)[]): CarboniumType<T>;
158
+
159
+ prepend(...nodes: (Node | string)[]): CarboniumType<T>;
160
+
161
+ before(...nodes: (Node | string)[]): CarboniumType<T>;
162
+
163
+ after(...nodes: (Node | string)[]): CarboniumType<T>;
164
+
165
+ remove(): CarboniumType<T>;
166
+
193
167
  classList: CarboniumClassList<T>;
168
+ relList: CarboniumClassList<T>;
194
169
  style: CarboniumStyleList<T>;
195
170
  }
196
171
 
197
- interface CarboniumClassList<T extends HTMLElement> extends DOMTokenList {
172
+ interface CarboniumClassList<T extends Element> extends DOMTokenList {
198
173
  add(...tokens: string[]): CarboniumType<T>;
199
174
 
200
175
  remove(...tokens: string[]): CarboniumType<T>;
201
176
 
202
- replace(oldToken: string, newToken: string): boolean;
203
-
204
177
  forEach(
205
178
  callbackfn: (value: string, key: number, parent: DOMTokenList) => void,
206
- thisArg?: any
179
+ thisArg?: unknown
207
180
  ): CarboniumType<T>;
208
181
  }
209
182
 
210
- interface CarboniumStyleList<
211
- T extends HTMLElement,
212
- > extends CSSStyleDeclaration {
213
- removeProperty(property: string): CarboniumList<T> & string;
214
-
183
+ interface CarboniumStyleList<T extends Element> extends CSSStyleDeclaration {
215
184
  setProperty(
216
185
  property: string,
217
186
  value: string | null,
@@ -1,7 +0,0 @@
1
- var carbonium=function(e){"use strict";
2
- /**
3
- Carbonium 1.3.0
4
- @copyright 2020 Edwin Martin
5
- @license MIT
6
- */let t,n;const o={get(e,r){let c=null;if(r==Symbol.iterator)return function*(){for(const t of e)yield t};if("style"==r||"classList"==r||"relList"==r){t=e,n=r;const c=Reflect.get(document.body,r);return new Proxy(c,o)}if(e instanceof CSSStyleDeclaration||e instanceof DOMTokenList)return c=Reflect.get(document.body[n],r),"function"==typeof c?new Proxy(c,{apply:function(e,r,c){return t.forEach((t=>{Reflect.apply(e,t[n],c)})),new Proxy(t,o)}}):c;if(Array.prototype.hasOwnProperty(r)){const e=Reflect.get(Array.prototype,r);if("function"==typeof e)return new Proxy(e,{apply:function(e,t,n){const r=Reflect.apply(e,t,n);return new Proxy(void 0!==r?r:t,o)}})}return e.length>0?r in e[0]&&(c=Reflect.get(e[0],r)):r in document.body&&(c=Reflect.get(document.body,r)),c?"function"==typeof c?new Proxy(c,{apply:function(e,t,n){let o=null,r=!0;for(const c of t){const t=Reflect.apply(e,c,n);r&&(o=t,r=!1)}return null!=o?o:t}}):c:Reflect.get(e,r)},set:(e,t,n)=>(!("forEach"in e)||e instanceof CSSStyleDeclaration?Reflect.set(e,t,n):e.forEach((e=>{Reflect.set(e,t,n)})),!0),deleteProperty:(e,t)=>t in e&&delete e[t]};return e.$=function(e,t){let n;return n=e.startsWith("<")?[(new DOMParser).parseFromString(e,"text/html").body.firstChild]:(t||document).querySelectorAll(e),new Proxy(n,o)},e}({});
7
- //# sourceMappingURL=bundle.iife.min.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bundle.iife.min.js","sources":["../src/carbonium.ts"],"sourcesContent":[null],"names":["currentListNodelist","propList","proxyHandler","get","target","prop","propValue","Symbol","iterator","element","Reflect","document","body","Proxy","CSSStyleDeclaration","DOMTokenList","apply","thisArg","argumentsList","forEach","el","Array","prototype","hasOwnProperty","ret","length","retFirst","first","set","value","deleteProperty","selectors","parentNode","nodelist","startsWith","DOMParser","parseFromString","firstChild","querySelectorAll"],"mappings":";;;;;OAgCA,IAAIA,EACAC,EAEJ,MAAMC,EAAsD,CAC1D,GAAAC,CAAIC,EAAQC,GACV,IAAIC,EAAY,KAGhB,GAAID,GAAQE,OAAOC,SACjB,OAAO,YACL,IAAK,MAAMC,KAAWL,QACdK,CAEV,EAIF,GAAY,SAARJ,GAA2B,aAARA,GAA+B,WAARA,EAAmB,CAC/DL,EAAsBI,EACtBH,EAAWI,EAGX,MAAMC,EAAYI,QAAQP,IAAIQ,SAASC,KAAMP,GAC7C,OAAO,IAAIQ,MAAMP,EAAWJ,EAC9B,CAGA,GACEE,aAAkBU,qBAClBV,aAAkBW,aAOlB,OAHAT,EAAYI,QAAQP,IAAKQ,SAASC,KAAaX,GAAWI,GAGlC,mBAAbC,EACF,IAAIO,MAAgBP,EAAW,CACpCU,MAAO,SAAUZ,EAAQa,EAASC,GAIhC,OAHAlB,EAAoBmB,SAASC,IAC3BV,QAAQM,MAAMZ,EAASgB,EAAWnB,GAAWiB,EAAc,IAEtD,IAAIL,MAAMb,EAAqBE,EACxC,IAGKI,EAKX,GAAIe,MAAMC,UAAUC,eAAelB,GAAO,CACxC,MAAMC,EAAYI,QAAQP,IAAIkB,MAAMC,UAAWjB,GAC/C,GAAwB,mBAAbC,EACT,OAAO,IA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