@johnhenry/respondable 0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 John Henry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # respondable
2
+
3
+ [![npm version](https://img.shields.io/npm/v/%40johnhenry%2Frespondable.svg)](https://www.npmjs.com/package/@johnhenry/respondable)
4
+ [![CI](https://github.com/johnhenry/respondable/actions/workflows/ci.yml/badge.svg)](https://github.com/johnhenry/respondable/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/%40johnhenry%2Frespondable.svg)](LICENSE)
6
+
7
+ Full documentation: [opensource.johnhenry.me/respondable](https://opensource.johnhenry.me/respondable/)
8
+
9
+ > **Provenance:** extracted from [`johnhenry/lib`](https://github.com/johnhenry/lib)'s
10
+ > `js/` directory. Briefly part of [`@johnhenry/domkit`](https://github.com/johnhenry/domkit)
11
+ > (a toolkit of ~40 independent DOM/HTML-component modules), then split out
12
+ > as its own package because these two elements are two duals of the same
13
+ > idea -- respond to a media query by swapping vs. by styling -- with a
14
+ > shared query-string grammar and a real dependency
15
+ > ([`parsel-js`](https://github.com/LeaVerou/parsel)) neither of domkit's
16
+ > other widgets needed.
17
+
18
+ Two custom elements for responding to CSS media queries declaratively,
19
+ without writing `matchMedia()`/`ResizeObserver` JavaScript by hand:
20
+
21
+ | Module | What it does |
22
+ |---|---|
23
+ | [`query-container.component`](src/query-container.component/readme.md) | `<query-component query="[(min-width:600px)] ol.wide">` -- swaps the rendered child element entirely by media query. |
24
+ | [`attribute-provider.component`](src/attribute-provider.component/readme.md) | `<attribute-provider classes="[(min-width:512px)] wide">` -- applies classes/styles/attributes to an existing child by media query, instead of swapping it. |
25
+
26
+ Both parse the same pipe (`|`)-delimited `[media query] value` grammar via
27
+ [`parsel-js`](https://github.com/LeaVerou/parsel) — a real npm dependency,
28
+ not a vendored copy.
29
+
30
+ ## Which one do I want?
31
+
32
+ | I want to... | Use |
33
+ |---|---|
34
+ | Show an entirely different element by breakpoint | `query-container.component` |
35
+ | Style/class/attribute an existing element by breakpoint, without replacing it | `attribute-provider.component` |
36
+
37
+ ## Install
38
+
39
+ ```sh
40
+ npm install @johnhenry/respondable
41
+ ```
42
+
43
+ or, in a browser with no build step, via a CDN (bootstrapped through
44
+ [`@johnhenry/definable`](https://github.com/johnhenry/definable)'s
45
+ `define-component.component`, since neither module here has its own
46
+ `global.mjs` — see each module's own readme for the full pattern):
47
+
48
+ ```html
49
+ <script
50
+ type="module"
51
+ src="https://esm.sh/@johnhenry/definable/define-component.component/global.mjs"
52
+ ></script>
53
+ <define-component
54
+ name="query-component"
55
+ src="https://esm.sh/@johnhenry/respondable/query-container.component/index.mjs"
56
+ ></define-component>
57
+ ```
58
+
59
+ ## Family
60
+
61
+ - [`@johnhenry/definable`](https://github.com/johnhenry/definable) --
62
+ both modules' own demos bootstrap themselves via its
63
+ `define-component.component` (`<define-component>`), since neither has a
64
+ self-registering `global.mjs` of its own.
65
+ - [`@johnhenry/domkit`](https://github.com/johnhenry/domkit) -- the toolkit
66
+ this package was originally part of.
67
+
68
+ ## License
69
+
70
+ MIT
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@johnhenry/respondable",
3
+ "version": "0.0.0",
4
+ "description": "Respond to CSS media queries declaratively -- swap an element entirely (query-container) or apply classes/styles/attributes to existing children (attribute-provider).",
5
+ "type": "module",
6
+ "exports": {
7
+ "./*": "./src/*"
8
+ },
9
+ "files": [
10
+ "src/"
11
+ ],
12
+ "scripts": {
13
+ "test": "node scripts/check-syntax.mjs"
14
+ },
15
+ "keywords": [
16
+ "html",
17
+ "dom",
18
+ "web-components",
19
+ "custom-elements",
20
+ "media-queries",
21
+ "responsive"
22
+ ],
23
+ "author": "",
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/johnhenry/respondable.git"
28
+ },
29
+ "homepage": "https://opensource.johnhenry.me/respondable/",
30
+ "engines": {
31
+ "node": ">=26.0.0"
32
+ },
33
+ "dependencies": {
34
+ "parsel-js": "^1.2.3"
35
+ }
36
+ }
@@ -0,0 +1,186 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <link rel="stylesheet" href="https://johnhenry.github.io/lib/css/blank-slate/0.0.0/index.css" />
5
+ <link rel="stylesheet" href="./index.css" />
6
+ <style>
7
+ .until-window-load {
8
+ visibility: hidden;
9
+ }
10
+ #height::before {
11
+ content: var(--window-height-str);
12
+ }
13
+ #width::before {
14
+ content: var(--window-width-str);
15
+ }
16
+ </style>
17
+ <script
18
+ type="module"
19
+ src="https://esm.sh/@johnhenry/definable/until-window-load/global.mjs"
20
+ ></script>
21
+ <script
22
+ type="module"
23
+ src="https://esm.sh/@johnhenry/definable/define-component.component/global.mjs"
24
+ ></script>
25
+ <script
26
+ type="module"
27
+ src="https://esm.sh/@johnhenry/definable/define-component-by-content.component/global.mjs"
28
+ ></script>
29
+ <define-component
30
+ name="attribute-provider"
31
+ src="./index.mjs"
32
+ ></define-component>
33
+ <define-component-by-content
34
+ name="h-1"
35
+ shadow
36
+ mode="open"
37
+ use-dom="true"
38
+ content="<h1><slot /></h1>"
39
+ ></define-component-by-content>
40
+ <style>
41
+ attribute-provider {
42
+ margin: 0;
43
+ padding: 0;
44
+ }
45
+
46
+ div {
47
+ display: inline-grid;
48
+ width: 64px;
49
+ height: 64px;
50
+ place-content: center;
51
+ background-color: aliceblue;
52
+ /* vertical-align: top; */
53
+ }
54
+ .red {
55
+ background-color: red;
56
+ }
57
+ .green {
58
+ background-color: green;
59
+ }
60
+ .yellow {
61
+ background-color: yellow;
62
+ }
63
+ .border {
64
+ border: 8px solid black;
65
+ }
66
+ .tall::before {
67
+ content: "T";
68
+ }
69
+
70
+ .wide::before {
71
+ content: "W";
72
+ }
73
+
74
+ </style>
75
+ </head>
76
+ <body>
77
+ <h1>Attribute Provider Class</h1>
78
+ <p>
79
+ The attribute provider web-component provides attributes
80
+ to its immediate children based on media queries.
81
+ </p>
82
+
83
+
84
+ <h2>Attributes</h2>
85
+ <p>
86
+ The attribute-provider components
87
+ provides attributes to its first child
88
+ based on media queries (screen width, orientation, etc.).
89
+ </p>
90
+ <h3>Attribute syntax</h3>
91
+ <p>
92
+ Pass the folling syntax to the 'attributes' attribute:
93
+ <pre>
94
+ &lt;attribute-provider attributes="
95
+ [{media query}]
96
+ {attribute name}={attribute value};
97
+ {2nd attribute name}={2nd attribute value}|
98
+ [{2nd media query}]
99
+ {attribute name}={attribute value};
100
+ {2nd attribute name}={2nd attribute value}|
101
+ ..."&gt;
102
+ &lt;/attribute-provider&gt;
103
+ </pre>
104
+ Note that a pipe ("|") delimits query sections while a semicolon (";") delimits individual attribute settings.
105
+ </p>
106
+ <p>
107
+ Ensure to cover all possibly query cases as attributes do not reset upon media query change
108
+ </p>
109
+ <p>
110
+ Pass 'null' (no quotes) to unset a value
111
+ </p>
112
+ <h3>Attribute example</h3>
113
+ <attribute-provider
114
+ class="until-window-load"
115
+ attributes="
116
+ [(max-width:512px)] disabled=null;hidden=null;placeholder='enabled'|
117
+ [(min-width:512px) and (max-width:768px)] disabled;hidden=null; placeholder='disabled: too wide'|
118
+ [(min-width:768px)] hidden;"
119
+ >
120
+ <input />
121
+ </attribute-provider>
122
+ <h2>Classes and Style</h2>
123
+ <p>
124
+ Unlike attributes,
125
+ classes and styles DO automatically reset (when
126
+ specified directly). No need to cover the case where the no longer apply.
127
+ </p>
128
+ <h3>Class syntax</h3>
129
+ <p>
130
+ Pass the folling syntax to the 'classes' attribute:
131
+ <pre>
132
+ &lt;attribute-provider classes="
133
+ [{media query}] {class 1} {class 2} {class 3}|
134
+ [{2nd media query}] {class 1} {class 2} {class 3}|
135
+ ..."&gt;
136
+ &lt;/attribute-provider&gt;
137
+ </pre>
138
+ Note that a pipe ("|") delimits query sections while a space (" ") delimits individual classes.
139
+ </p>
140
+ <h3>Style syntax</h3>
141
+ <p>
142
+ Pass the folling syntax to the 'styles' attribute:
143
+ <pre>
144
+ &lt;attribute-provider styles="
145
+ [{media query}]
146
+ {style property}:{style value};
147
+ {2nd style property}:{2nd style value}|
148
+ [{2nd media query}]
149
+ {style property}:{style value};
150
+ {2nd style property}:{2nd style value}|
151
+ ..."&gt;
152
+ &lt;/attribute-provider&gt;
153
+ </pre>
154
+ Note that a pipe ("|") delimits query sections while a semicolon (";") delimits individual style declarations.
155
+ </p>
156
+ <h3>Class example / Style example </h3>
157
+ <attribute-provider
158
+ class="until-window-load"
159
+ classes="
160
+ red|
161
+ [(min-width:512px) and (max-width:768px)] green border |
162
+ [(min-width:640px) and (max-width:896px)] yellow |
163
+ [(orientation:portrait)] tall |
164
+ [(orientation:landscape)] wide
165
+ "
166
+ >
167
+ <div></div>
168
+ </attribute-provider>
169
+ /
170
+ <attribute-provider
171
+ class="until-window-load"
172
+ styles="
173
+ background-color:red |
174
+ [(min-width:512px) and (max-width:768px)] background-color:green; border: 8px solid black; |
175
+ [(min-width:640px) and (max-width:896px)] background-color:yellow |
176
+ [(orientation:portrait)] --tall:block |
177
+ [(orientation:landscape)] --wide:block
178
+ "
179
+ >
180
+ <div>
181
+ <span style="display: var(--tall, none)">T</span>
182
+ <span style="display: var(--wide, none)">W</span>
183
+ </div>
184
+ </attribute-provider>
185
+ </body>
186
+ </html>
File without changes
@@ -0,0 +1,213 @@
1
+ const exp = /\[(.+)\](.+)/;
2
+
3
+ const stripQuotes = (string, quotes = ["'", '"', "`"]) => {
4
+ for (const quote of quotes) {
5
+ if (string.startsWith(quote) && string.endsWith(quote)) {
6
+ return string.slice(1, -1);
7
+ }
8
+ }
9
+ return string;
10
+ };
11
+
12
+ const parseQueries = (queries) =>
13
+ queries
14
+ .trim()
15
+ .split("|")
16
+ .map((x) => x.trim())
17
+ .filter((x) => x);
18
+
19
+ export default class extends HTMLElement {
20
+ #classes;
21
+ #styles;
22
+ #attributes;
23
+ #observer;
24
+ #mediaMatches;
25
+ constructor() {
26
+ super();
27
+ this.#observer = new globalThis.MutationObserver(this.setAll.bind(this));
28
+ this.#observer.observe(this, { childList: true });
29
+ this.#mediaMatches = {};
30
+ }
31
+ connectedCallback() {}
32
+ disconnectedCallback() {
33
+ this.#observer.disconnect();
34
+ for (const mediaMatches of Object.values(this.#mediaMatches)) {
35
+ for (const m of mediaMatches) {
36
+ m.onchange = null;
37
+ }
38
+ }
39
+ }
40
+ static get observedAttributes() {
41
+ return ["classes", "styles", "attributes"];
42
+ }
43
+ setClasses() {
44
+ const queries = this.getAttribute("classes") || "";
45
+ this.#classes = new Map();
46
+ const mediaMatches = (this.#mediaMatches["classes"] = new Set());
47
+ for (const mediaQuery of parseQueries(queries)) {
48
+ let query, selector;
49
+ if (exp.test(mediaQuery)) {
50
+ [, query, selector] = exp.exec(mediaQuery);
51
+ query = query.trim();
52
+ selector = selector.trim();
53
+ } else {
54
+ query = "";
55
+ selector = mediaQuery.trim();
56
+ }
57
+ this.#classes.set(
58
+ globalThis.matchMedia(query),
59
+ selector.trim().split(" ")
60
+ );
61
+
62
+ const m = globalThis.matchMedia(query);
63
+ m.onchange = (e) => {
64
+ this.triggerClass(e);
65
+ };
66
+ mediaMatches.add(m);
67
+ }
68
+ this.triggerClass();
69
+ }
70
+ setStyles() {
71
+ const queries = this.getAttribute("styles") || "";
72
+ this.#styles = new Map();
73
+ const mediaMatches = (this.#mediaMatches["styles"] = new Set());
74
+ for (const mediaQuery of parseQueries(queries)) {
75
+ let query, selector;
76
+ if (exp.test(mediaQuery)) {
77
+ [, query, selector] = exp.exec(mediaQuery);
78
+ query = query.trim();
79
+ selector = selector.trim();
80
+ } else {
81
+ query = "";
82
+ selector = mediaQuery.trim();
83
+ }
84
+ this.#styles.set(
85
+ globalThis.matchMedia(query),
86
+ selector
87
+ .trim()
88
+ .split(";")
89
+ .filter((x) => x)
90
+ );
91
+
92
+ const m = globalThis.matchMedia(query);
93
+ m.onchange = (e) => {
94
+ this.triggerStyle(e);
95
+ };
96
+ mediaMatches.add(m);
97
+ }
98
+ this.triggerStyle();
99
+ }
100
+ setAttributes() {
101
+ const queries = this.getAttribute("attributes") || "";
102
+ this.#attributes = new Map();
103
+ const mediaMatches = (this.#mediaMatches["attributes"] = new Set());
104
+ for (const mediaQuery of parseQueries(queries)) {
105
+ let query, selector;
106
+ if (exp.test(mediaQuery)) {
107
+ [, query, selector] = exp.exec(mediaQuery);
108
+ query = query.trim();
109
+ selector = selector.trim();
110
+ } else {
111
+ query = "";
112
+ selector = mediaQuery.trim();
113
+ }
114
+
115
+ this.#attributes.set(
116
+ globalThis.matchMedia(query),
117
+ selector
118
+ .trim()
119
+ .split(";")
120
+ .filter((x) => x)
121
+ .reduce((acc, curr) => {
122
+ let [key, value] = curr.split("=", 2);
123
+ if (!key) {
124
+ return;
125
+ }
126
+
127
+ key = key.trim();
128
+ if (value === undefined) {
129
+ value = "";
130
+ }
131
+ if (value === "null") {
132
+ value = null;
133
+ }
134
+ if (value) {
135
+ value = stripQuotes(value.trim());
136
+ }
137
+ acc.push([key.trim(), value]);
138
+ return acc;
139
+ }, [])
140
+ );
141
+
142
+ const m = globalThis.matchMedia(query);
143
+ m.onchange = (e) => {
144
+ this.triggerAttribute(e);
145
+ };
146
+ mediaMatches.add(m);
147
+ }
148
+ this.triggerAttribute();
149
+ }
150
+ triggerClass() {
151
+ const classArray = this.getByKey("classes");
152
+ for (const kid of this.kids) {
153
+ const { classList } = kid;
154
+ classList.remove(...classList);
155
+ classList.add(...classArray);
156
+ }
157
+ }
158
+ triggerStyle() {
159
+ const styleArray = this.getByKey("styles");
160
+ for (const kid of this.kids) {
161
+ kid.setAttribute("style", styleArray.join(";"));
162
+ }
163
+ }
164
+ triggerAttribute() {
165
+ const attributeArray = this.getByKey("attributes");
166
+ for (const kid of this.kids) {
167
+ for (const [key, value] of attributeArray) {
168
+ if (value === null) {
169
+ kid.removeAttribute(key);
170
+ } else {
171
+ kid.setAttribute(key, value);
172
+ }
173
+ }
174
+ }
175
+ }
176
+ setAll() {
177
+ this.setClasses();
178
+ this.setStyles();
179
+ this.setAttributes();
180
+ }
181
+ attributeChangedCallback(name, prev, current) {
182
+ this.setAll();
183
+ }
184
+ get kids() {
185
+ return Array.prototype.filter.call(
186
+ this.childNodes,
187
+ (x) => x.nodeType === 1
188
+ );
189
+ }
190
+ getByKey(key) {
191
+ let result = [];
192
+ let arr;
193
+ switch (key) {
194
+ case "classes":
195
+ arr = this.#classes;
196
+ break;
197
+ case "styles":
198
+ arr = this.#styles;
199
+ break;
200
+ case "attributes":
201
+ arr = this.#attributes;
202
+ break;
203
+ }
204
+ if (arr) {
205
+ for (const [query, items] of arr) {
206
+ if (query.matches) {
207
+ result.push(...items);
208
+ }
209
+ }
210
+ }
211
+ return result;
212
+ }
213
+ }
@@ -0,0 +1,79 @@
1
+ # Attribute Provider
2
+
3
+ Applies classes, inline styles, and/or attributes to an element's
4
+ immediate children based on media queries (screen width, orientation,
5
+ etc.) — re-evaluated on every matching query change.
6
+
7
+ Compare [query-container.component](../query-container.component/readme.md),
8
+ which swaps its rendered child element entirely by media query instead of
9
+ styling the existing one.
10
+
11
+ ## Attributes
12
+
13
+ Each of `classes`/`styles`/`attributes` accepts one or more
14
+ `[media query] value` sections, pipe (`|`)-delimited. A section with no
15
+ `[media query]` prefix always applies.
16
+
17
+ ### `classes`
18
+
19
+ Space-delimited class names per section. Classes reset automatically when
20
+ no longer matched.
21
+
22
+ ```html
23
+ <attribute-provider
24
+ classes="
25
+ red|
26
+ [(min-width:512px) and (max-width:768px)] green border|
27
+ [(orientation:portrait)] tall
28
+ "
29
+ >
30
+ <div></div>
31
+ </attribute-provider>
32
+ ```
33
+
34
+ ### `styles`
35
+
36
+ Semicolon-delimited `property:value` declarations per section. Styles
37
+ reset automatically when no longer matched.
38
+
39
+ ```html
40
+ <attribute-provider
41
+ styles="
42
+ background-color:red|
43
+ [(min-width:512px) and (max-width:768px)] background-color:green; border: 8px solid black
44
+ "
45
+ >
46
+ <div></div>
47
+ </attribute-provider>
48
+ ```
49
+
50
+ ### `attributes`
51
+
52
+ Semicolon-delimited `name=value` pairs per section. Use `null` (no quotes)
53
+ to remove an attribute. **Attributes do NOT reset automatically** —
54
+ unlike `classes`/`styles`, every query case must explicitly say what to do
55
+ with each attribute.
56
+
57
+ ```html
58
+ <attribute-provider
59
+ attributes="
60
+ [(max-width:512px)] disabled=null;hidden=null;placeholder='enabled'|
61
+ [(min-width:512px) and (max-width:768px)] disabled;hidden=null|
62
+ [(min-width:768px)] hidden
63
+ "
64
+ >
65
+ <input />
66
+ </attribute-provider>
67
+ ```
68
+
69
+ ## Usage
70
+
71
+ ```html
72
+ <script
73
+ type="module"
74
+ src="https://esm.sh/@johnhenry/definable/define-component.component/global.mjs"
75
+ ></script>
76
+ <define-component name="attribute-provider" src="./index.mjs"></define-component>
77
+ ```
78
+
79
+ See `demo.htm` for a full working example of all three attributes.
@@ -0,0 +1,89 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <style>
5
+ .until-window-load {
6
+ visibility: hidden;
7
+ }
8
+ #height::before {
9
+ content: var(--window-height-str);
10
+ }
11
+ #width::before {
12
+ content: var(--window-width-str);
13
+ }
14
+ </style>
15
+ <script
16
+ type="module"
17
+ src="https://esm.sh/@johnhenry/definable/until-window-load/global.mjs"
18
+ ></script>
19
+ <script
20
+ type="module"
21
+ src="https://esm.sh/@johnhenry/definable/define-component.component/global.mjs"
22
+ ></script>
23
+ <script
24
+ type="module"
25
+ src="https://esm.sh/@johnhenry/definable/define-component-by-content.component/global.mjs"
26
+ ></script>
27
+ <define-component
28
+ name="query-component"
29
+ src="./index.mjs"
30
+ ></define-component>
31
+ <define-component-by-content
32
+ name="h-1"
33
+ shadow
34
+ mode="open"
35
+ use-dom="true"
36
+ content="<h1><slot /></h1>"
37
+ ></define-component-by-content>
38
+ </head>
39
+ <body>
40
+ <h1>Demo: Query Container</h1>
41
+ <query-component
42
+ class="until-window-load"
43
+ default="ul"
44
+ query="[(min-width:600x) and (max-width:900px)] ol.ordered[style=color:red] | [(min-width:900px)] dl.ordered[style=color:blue;font-weight:bold]"
45
+ >
46
+ <query-component default="template" query="[(min-width:900px)] dt"
47
+ >Width</query-component
48
+ >
49
+ <query-component
50
+ default="li#width"
51
+ query="[(min-width:900px)] dd#width"
52
+ ></query-component>
53
+ <query-component default="template" query="[(min-width:900px)] dt"
54
+ >Height</query-component
55
+ >
56
+ <query-component
57
+ default="li#height"
58
+ query="[(min-width:900px)] dd#height"
59
+ ></query-component>
60
+ </query-component>
61
+
62
+ <hr />
63
+ <!-- old and working-->
64
+ <query-component
65
+ class="until-window-load"
66
+ default="ul"
67
+ query="
68
+ [(min-width:300px) and (max-width:900px)] ol.ordered[style=color:blue]|
69
+ [(min-width:400px) and (max-width:600px)] ol.ordered[style=color:red;font-weight:bold]"
70
+ >
71
+ <li>a</li>
72
+ <li>b</li>
73
+ <li>c</li>
74
+ </query-component>
75
+ <query-component
76
+ class="until-window-load"
77
+ default="ul"
78
+ query="
79
+ [(min-width:600px)] dl"
80
+ >
81
+ <query-component default="li" query="[(min-width:600px)] dt"
82
+ >Definition:</query-component
83
+ >
84
+ <query-component default="" query=" [(min-width:600px)] dd.hello"
85
+ >Term</query-component
86
+ >
87
+ </query-component>
88
+ </body>
89
+ </html>
File without changes
@@ -0,0 +1,138 @@
1
+ import { tokenize } from "parsel-js";
2
+ /*
3
+ <query-component
4
+ default="ul"
5
+ query="[(min-width:300px) and (max-width:1200px)] ol.ordered[style=color:blue];"
6
+ ></query-component>
7
+ -- see readme.md for the full example.
8
+ */
9
+ const exp = /\[(.+)\](.+)/;
10
+ const elementFromSelector = (selector = "") => {
11
+ let tag = "template";
12
+ let id = undefined;
13
+ const classes = [];
14
+ const attributes = {};
15
+ if (selector) {
16
+ for (const token of tokenize(selector)) {
17
+ switch (token.type) {
18
+ case "id":
19
+ id = token.name;
20
+ break;
21
+ case "type":
22
+ tag = token.content;
23
+ break;
24
+ case "class":
25
+ classes.push(token.name);
26
+ break;
27
+ case "attribute":
28
+ attributes[token.name] = token.value;
29
+ break;
30
+ }
31
+ }
32
+ }
33
+ const element = globalThis.document.createElement(tag); //tag
34
+ if (id) {
35
+ element.id = id;
36
+ }
37
+ element.classList.add(...classes); //classes
38
+ for (const [key, value] of Object.entries(attributes)) {
39
+ // attributes
40
+ element.setAttribute(key, value);
41
+ }
42
+ return element;
43
+ };
44
+
45
+ export default class extends HTMLElement {
46
+ #content;
47
+ #queries;
48
+ #default;
49
+ #observer;
50
+ constructor() {
51
+ super();
52
+ }
53
+ connectedCallback() {
54
+ this.#observer = new globalThis.MutationObserver(this.update.bind(this));
55
+ this.#observer.observe(this, { childList: true });
56
+ }
57
+ disconnectedCallback() {
58
+ this.#observer.disconnect();
59
+ if (this.#queries) {
60
+ for (const query of this.#queries.keys()) {
61
+ query.onchange = null;
62
+ }
63
+ }
64
+ }
65
+ static get observedAttributes() {
66
+ return ["default", "query"];
67
+ }
68
+ setInitial(selector) {
69
+ this.#default = elementFromSelector(selector);
70
+ this.#content = this.#default;
71
+ this.appendChild(this.#content);
72
+ this.triggerQuery();
73
+ }
74
+ setQueries(queries) {
75
+ this.#queries = new Map();
76
+ let firstSelector = "";
77
+ for (const mediaQuery of queries
78
+ .trim()
79
+ .split("|")
80
+ .map((x) => x.trim())
81
+ .filter((x) => x)) {
82
+ const [, query, selector] = exp.exec(mediaQuery);
83
+ firstSelector = firstSelector || selector;
84
+ this.#queries.set(
85
+ globalThis.matchMedia(query),
86
+ elementFromSelector(selector)
87
+ );
88
+ const m = globalThis.matchMedia(query);
89
+ m.onchange = (e) => {
90
+ this.triggerQuery(e);
91
+ };
92
+ }
93
+ if (this.#default) {
94
+ this.triggerQuery();
95
+ } else {
96
+ this.setInitial(firstSelector);
97
+ }
98
+ }
99
+ triggerQuery() {
100
+ let element = this.#default;
101
+ if (this.#queries) {
102
+ for (const [query, selected] of this.#queries) {
103
+ if (query.matches) {
104
+ element = selected;
105
+ }
106
+ }
107
+ }
108
+ if (this.contains(this.#content)) {
109
+ if (element !== this.#content) {
110
+ element.append(...this.#content.childNodes);
111
+ this.removeChild(this.#content);
112
+ this.#content = element;
113
+ this.appendChild(this.#content);
114
+ this.update();
115
+ }
116
+ }
117
+ }
118
+ attributeChangedCallback(name, prev, current) {
119
+ switch (name) {
120
+ case "default":
121
+ this.setInitial(current);
122
+ break;
123
+ case "query":
124
+ this.setQueries(current);
125
+ break;
126
+ }
127
+ }
128
+ update() {
129
+ for (const child of [...this.childNodes]) {
130
+ if (child === this.#content) {
131
+ continue;
132
+ }
133
+ if (this.#content) {
134
+ this.#content.appendChild(child);
135
+ }
136
+ }
137
+ }
138
+ }
@@ -0,0 +1,32 @@
1
+ # Query Container HTML Component
2
+
3
+ Containter that changes based on a given media query
4
+
5
+ Inspired by: https://github.com/tabvengers/spicy-sections
6
+
7
+ ## Example usage Usage
8
+
9
+ Single query:
10
+
11
+ This following will produce an ordered list
12
+ with class name 'ordered' and blue text
13
+ when the window's width is between 400px and 900px.
14
+
15
+ ```html
16
+ <script
17
+ type="module"
18
+ src="https://esm.sh/@johnhenry/definable/define-component.component/global.mjs"
19
+ ></script>
20
+ <define-component name="query-component" src="./index.mjs"></define-component>
21
+ <query-component
22
+ default="ul"
23
+ query="
24
+ [(min-width:300px) and (max-width:1200px)] ol.ordered[style=color:blue];
25
+ [(min-width:400px) and (max-width:600px)] ol.ordered[style=color:red];
26
+ "
27
+ >
28
+ <li>a</li>
29
+ <li>b</li>
30
+ <li>c</li>
31
+ </query-component>
32
+ ```