progressively-enhance-web-components 1.0.4 → 2.1.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/CHANGELOG.md CHANGED
@@ -1,8 +1,48 @@
1
- # Changelog
1
+ ## 2.1.0
2
2
 
3
- ## Next version
3
+ - Breaking: Changed attribute values to be escaped when they are written into a component's markup. Previously a value was pasted into the markup as it was, so one holding a quote or an angle bracket broke the attribute or element it landed in, and an entity such as `&lt;b&gt;` came out as a real `<b>` element. Pass markup as slotted children rather than through an attribute.
4
+ - Related: Fixed a value holding `$&`, `$1` or similar being expanded as a replacement pattern, and an attribute name holding a character such as `.` filling in other template literals as well as its own (`${a.b}` matched `${axb}`). The browser example in USAGE.md and the sample app had the same problems and have been fixed the same way.
5
+ - Breaking: Changed component definitions to only be recognized on a `<template>` whose `id` is a valid custom element name. Previously a `<template id="header">` used for something else caused every `<header>` element to be "enhanced" with its contents.
6
+ - Changed jsdom's CSS parsing complaints to be silenced through a jsdom virtual console rather than by temporarily replacing `console.error`, which could also throw when something logged `null` or `undefined`.
7
+ - Changed files to be read in alphabetical order on every platform. When the same template `id` is defined more than once, which one is used no longer depends on the filesystem, and a warning is now logged.
8
+ - Changed hidden directories, such as `.git`, to be skipped like hidden files. Symbolic links are now followed, with protection against loops.
9
+ - Changed the module to throw a clear error when `templatesDir` is not given, rather than throwing an unhelpful `TypeError` when called with no params at all, or silently doing nothing when called without it.
10
+ - Fixed every file holding a non-ASCII character, such as an accented letter, a curly quote or an emoji, being treated as binary and silently skipped. A file is now treated as binary only when it has a null byte near its start or is not valid UTF-8.
11
+ - Fixed invocations inside HTML comments, inside `<script>`, `<style>`, `<textarea>` and `<title>` elements, and inside plain `<template>` elements being enhanced. Expanding one inside a `<script>` string broke the script.
12
+ - Fixed a component whose template invokes another component only having the inner one enhanced when it happened to be defined first. Nested components are now always enhanced. A component that invokes itself, directly or through another, is expanded one level and then left for its JavaScript to render, with a warning, rather than expanding forever.
13
+ - Fixed an invocation nested inside another of the same kind never being enhanced in `shadow` and `both` modes, the search for invocations stepping over everything the outer one held.
14
+ - Fixed one invocation that is never closed stopping every invocation after it in the same file from being enhanced.
15
+ - Fixed an element whose name only begins the same way as the one being enhanced, such as `</my-thing-two>` inside `<my-thing>`, being taken as its closing tag.
16
+ - Fixed a self-closing invocation nested inside another of the same kind leaving the outer one unclosed.
17
+ - Fixed an apostrophe in an unquoted attribute, such as `<my-thing don't>`, being read as the start of a quoted value.
18
+ - Fixed a character that becomes longer when lowercased, such as `İ`, shifting every position after it and corrupting the output.
19
+ - Fixed `light` mode moving a slotted child that belongs to a nested custom element, or that sits inside another slotted child, to the top level of the component.
20
+ - Fixed the `data-enhanced=""` cleanup also rewriting matching text anywhere inside the enhanced element, not just on the element itself.
21
+ - Improved performance: each file is now scanned once for all components rather than once per component, one jsdom document is reused for every invocation, and a file is parsed as a document only if it contains a `<template>`.
22
+ - Updated dependencies.
4
23
 
5
- - Put your changes here...
24
+ ## 2.0.1
25
+
26
+ - Altered the npm package to not include unnecessary files.
27
+
28
+ ## 2.0.0
29
+
30
+ - Breaking: A component is now written into a declarative shadow root, with a copy of its markup kept beside that as fallback content, rather than into the light DOM alone. This keeps the `<style>`, `<script>` and `<slot>` elements a fallback cannot use, styles the component and makes its slots work before any JavaScript runs, and leaves nothing to be swapped once the component upgrades, while a browser that does not build shadow roots still renders the fallback as it always did.
31
+ - Related: A component class that calls `attachShadow` unconditionally now throws away what the server rendered. The browser's parser has already built the shadow root, and `attachShadow` on one it built does not fail: it hands back that same root having emptied it, so the class appears to work while rebuilding in the browser everything that had already arrived rendered, which is the cost a declarative shadow root exists to avoid. Read `this.shadowRoot` instead, falling back to `attachShadow` for an element created in JavaScript rather than written into the page, and fill the shadow root from the `<template>` only when it is empty.
32
+ - Related: The children of an invocation are now left where they were written, being the light DOM that the slots of the shadow root project. Previously a child carrying a `slot` attribute was moved to the top level of the fallback and a child without one was dropped. Only a direct child of an element can be assigned to a slot, so a slotted child written deeper than that no longer reaches one.
33
+ - To keep the previous output exactly, set the new `mode` param to `light`.
34
+ - Added `both`, `shadow`, and `light` enhancement modes, set for the whole project with the `mode` param or per component with a `mode` attribute on its `<template>`. `both` is the default and is described above. `shadow` writes only the declarative shadow root, which is smaller but renders nothing at all where declarative shadow DOM is unsupported. `light` writes only the fallback markup, which is what this module did before this version.
35
+ - Added a `data-enhanced` attribute, written onto every element this module enhances. An element that already carries one is left exactly as it was, so running this over templates it has already preprocessed no longer stacks a second shadow root and a second copy of the fallback onto the same element. Write it yourself to keep an invocation whose markup you have written out by hand.
36
+ - Related: An invocation holding a `<template shadowrootmode>` of its own is left alone whether or not it carries the attribute, a browser refusing to build a second declarative shadow root on the same element.
37
+ - Added browser tests that drive the express sample app in Chromium with Playwright, covering what no preprocessor test can: that the parser builds the shadow root, that the component class upgrades the element without discarding what the server rendered into it, that slotted content is projected, that the fallback stays inert where a shadow root was built and renders where one was not, and that nothing is shown twice in either case.
38
+ - Fixed the sample app calling `body-parser`, which it never declared as a dependency and which Express has had built in for years.
39
+ - Fixed the pieces of an enhanced element running together on one line, the shadow root, the fallback and the light DOM now each starting on their own. js-beautify treats `<template>` as an inline element and would not break the line before one.
40
+ - Improved performance.
41
+ - Fixed a file invoking more than one kind of custom element only having the last one enhanced. Each custom element was applied to the file as it was on disk rather than to what the previous one had produced, so every pass but the last was thrown away.
42
+ - Fixed a custom element invoked inside another of the same kind producing malformed markup, with a stray closing tag left behind. Pairing an opening tag with the closing tag that belongs to it is not something a regular expression can do, so it is no longer asked to.
43
+ - Fixed `disableBeautify` being ignored when building a component's markup, so the option now leaves the markup alone as it says it does.
44
+ - Fixed the module silencing part of the host application's `console.error` for the life of the process. jsdom's complaints about unparseable CSS are now silenced only while the module is doing its work.
45
+ - Updated various dependencies.
6
46
 
7
47
  ## 1.0.4
8
48
 
@@ -0,0 +1,16 @@
1
+ When you call:
2
+
3
+ ```javascript
4
+ const editedFiles = require('progressively-enhance-web-components')({
5
+ templatesDir: './mvc/views'
6
+ })
7
+ ```
8
+
9
+ There are other params you can pass to it besides `templatesDir`.
10
+
11
+ The full list of params available is:
12
+
13
+ - `templatesDir` *[String]*: What folder to examine. This is required.
14
+ - `disableBeautify` *[Boolean]*: If set to true, this module will not beautify the HTML in the outputted markup. Default: `false`.
15
+ - `beautifyOptions` *[Object]*: Options to pass to [js-beautify](https://github.com/beautifier/js-beautify). Default: `{ indent_size: 2 }`.
16
+ - `mode` *[String]*: How to enhance an invocation whose definition does not ask for a mode of its own. One of `both`, `shadow`, or `light`. Default: `'both'`. See usage section for details.
package/README.md CHANGED
@@ -1,8 +1,4 @@
1
- progressively-enhance-web-components
2
- ===
3
-
4
- [![Build Status](https://github.com/rooseveltframework/progressively-enhance-web-components/workflows/CI/badge.svg
5
- )](https://github.com/rooseveltframework/progressively-enhance-web-components/actions?query=workflow%3ACI) [![npm](https://img.shields.io/npm/v/progressively-enhance-web-components.svg)](https://www.npmjs.com/package/progressively-enhance-web-components)
1
+ 🕸️ **progressively-enhance-web-components** [![npm](https://img.shields.io/npm/v/progressively-enhance-web-components.svg)](https://www.npmjs.com/package/progressively-enhance-web-components)
6
2
 
7
3
  A template file preprocessor for [progressively enhancing](https://en.wikipedia.org/wiki/Progressive_enhancement) web components in Node.js.
8
4
 
@@ -10,7 +6,15 @@ It works by reading a directory of HTML templates for your web application, iden
10
6
 
11
7
  This allows you to use web components in server-side templating the same way you would with client-side templating without creating a hard dependency on JavaScript for rendering templates with web components and without having to write two different templates for each context.
12
8
 
13
- This module was built and is maintained by the [Roosevelt web framework](https://github.com/rooseveltframework/roosevelt) [team](https://github.com/orgs/rooseveltframework/people), but it can be used independently of Roosevelt as well.
9
+ This module was built and is maintained by the [Roosevelt web framework](https://rooseveltframework.org) [team](https://rooseveltframework.org/contributors), but it can be used independently of Roosevelt as well.
10
+
11
+ <details open>
12
+ <summary>Documentation</summary>
13
+ <ul>
14
+ <li><a href="./USAGE.md">Usage</a></li>
15
+ <li><a href="./CONFIGURATION.md">Configuration</a></li>
16
+ </ul>
17
+ </details>
14
18
 
15
19
  ## Technique
16
20
 
@@ -18,182 +22,4 @@ To leverage this module's progressive enhancement technique, you will need to fo
18
22
 
19
23
  1. Always define the markup structure using a `<template>` element. The definition can exist anywhere in any of your templates, but the definition must exist.
20
24
  2. The template element you create to define your web component must have an `id` matching the name of the web component. So `<my-component>` must have a corresponding `<template id="my-component">` somewhere in your templates.
21
- 3. Use `${templateLiteral}` values for values in your `<template>` markup. See how that works in the example below.
22
-
23
- ## Usage
24
-
25
- We will demo this technique end-to-end using a `<word-count>` component that counts the number of words a user types into a `<textarea>`.
26
-
27
- Suppose the intended use of the `<word-count>` component looks like this:
28
-
29
- ```html
30
- <word-count text="Once upon a time... " id="story">
31
- <p slot="description">Type your story in the box above!</p>
32
- </word-count>
33
- ```
34
-
35
- And suppose also that you have an Express application with templates loaded into `mvc/views`.
36
-
37
- To leverage this module's progressive enhancement technique, you will need to define this component using a `<template>` element in any one of your templates as follows:
38
-
39
- ```html
40
- <template id="word-count">
41
- <style>
42
- div {
43
- position: relative;
44
- }
45
- textarea {
46
- margin-top: 35px;
47
- width: 100%;
48
- box-sizing: border-box;
49
- }
50
- span {
51
- display: block;
52
- position: absolute;
53
- top: 0;
54
- right: 0;
55
- margin-top: 10px;
56
- font-weight: bold;
57
- }
58
- </style>
59
- <div>
60
- <textarea rows="10" cols="50" name="${id}" id="${id}">${text}</textarea>
61
- <slot name="description"></slot>
62
- <span class="word-count"></span>
63
- </div>
64
- </template>
65
- ```
66
-
67
- *Note: Any `${templateLiterals}` present in the template markup will be replaced with attribute values from the custom element invocation. More on that below.*
68
-
69
- Then, in your Express application:
70
-
71
- ```javascript
72
- const fs = require('fs-extra')
73
-
74
- // load progressively-enhance-web-components.js
75
- const editedFiles = require('progressively-enhance-web-components')({
76
- templatesDir: './mvc/views'
77
- })
78
-
79
- // copy unmodified templates to a modified templates directory
80
- fs.copySync('mvc/views', 'mvc/.preprocessed_views')
81
-
82
- // update the relevant templates
83
- for (const file in editedFiles) {
84
- fs.writeFileSync(file.replace('mvc/views', 'mvc/.preprocessed_views'), editedFiles[file])
85
- }
86
-
87
- // configure express
88
- const express = require('express')
89
- const app = express()
90
- app.engine('html', require('teddy').__express) // set teddy as view engine that will load html files
91
- app.set('views', 'mvc/.preprocessed_views') // set template dir
92
- app.set('view engine', 'html') // set teddy as default view engine
93
-
94
- // start the server
95
- const port = 3000
96
- app.listen(port, () => {
97
- console.log(`🎧 express sample app server is running on http://localhost:${port}`)
98
- })
99
- ```
100
-
101
- *Note: The above example uses the [Teddy](https://github.com/rooseveltframework/teddy) templating system, but you can use any templating system you like.*
102
-
103
- In the above sample Express application, the `mvc/views` folder is copied to `mvc/.preprocessed_views`, then any template files in there will be updated to replace any uses of `<word-count>` with a more progressive enhancement-friendly version of `<word-count>` instead.
104
-
105
- So, for example, any web component in your templates that looks like this:
106
-
107
- ```html
108
- <word-count text="Once upon a time... " id="story">
109
- <p slot="description">Type your story in the box above!</p>
110
- </word-count>
111
- ```
112
-
113
- Will be replaced with this:
114
-
115
- ```html
116
- <word-count text="Once upon a time... " id="story">
117
- <div>
118
- <textarea rows="10" cols="50" name="story" id="story">Once upon a time... </textarea>
119
- <span class="word-count"></span>
120
- </div>
121
- <p slot="description">Type your story in the box above!</p>
122
- </word-count>
123
- ```
124
-
125
- The fallback markup is derived from the `<template>` element and is inserted into the "light DOM" of the web component, so it will display to users with JavaScript disabled.
126
-
127
- Because the `<template>` element has `${templateLiteral}` values for the `name` attribute, the `id` attribute, and the contents of the `<textarea>`, those values are prefilled properly on the fallback markup.
128
-
129
- Any tag in the `<template>` element that has a `slot` attribute will be moved to the top level of the fallback markup DOM because that is a requirement for the web component to work when JavaScript is enabled. That's why the `<p>` tag is not a child of the `<div>` in the replacement example like it is in the `<template>`. That is done intentionally by this module's preprocessing.
130
-
131
- Then, once the frontend JavaScript takes over, the web component can be progressively enhanced into the JS-driven version.
132
-
133
- Here's an example implementation for the frontend JS side:
134
-
135
- ```javascript
136
- class WordCount extends window.HTMLElement {
137
- connectedCallback () { // called whenever a new instance of this element is inserted into the dom
138
- this.shadow = this.attachShadow({ mode: 'open' }) // create and attach a shadow dom to the custom element
139
- this.shadow.appendChild(document.getElementById('word-count').content.cloneNode(true)) // create the elements in the shadow dom from the template element
140
-
141
- // set textarea attributes
142
- const textarea = this.shadow.querySelector('textarea')
143
- textarea.value = this.getAttribute('text') || ''
144
- textarea.id = this.getAttribute('id') || ''
145
- textarea.name = this.getAttribute('id') || ''
146
-
147
- // function for updating the word count
148
- const updateWordCount = () => {
149
- this.shadow.querySelector('span').textContent = `Words: ${textarea.value.trim().split(/\s+/g).filter(a => a.trim().length > 0).length}`
150
- }
151
-
152
- // update count when textarea content changes
153
- textarea.addEventListener('input', updateWordCount)
154
- updateWordCount() // update it on load as well
155
- }
156
- }
157
-
158
- window.customElements.define('word-count', WordCount) // define the new element
159
- ```
160
-
161
- Once that JS executes, the "light DOM" fallback markup will be hidden and the JS-enabled version of the web component will take over and behave as normal.
162
-
163
- ### Available options
164
-
165
- When you call:
166
-
167
- ```javascript
168
- const editedFiles = require('progressively-enhance-web-components')({
169
- templatesDir: './mvc/views'
170
- })
171
- ```
172
-
173
- There are other params you can pass to it besides `templatesDir`.
174
-
175
- The full list of params available is:
176
-
177
- - `templatesDir`: What folder to examine. This is required.
178
- - `disableBeautify`: If set to true, this module will not beautify the HTML in the outputted markup. Default: `false`.
179
- - `beautifyOptions`: Options to pass to [js-beautify](https://github.com/beautifier/js-beautify). Default: `{ indent_size: 2 }`.
180
-
181
- ### Sample app
182
-
183
- Here's how to run the sample app:
184
-
185
- - `cd sampleApps/express`
186
-
187
- - `npm ci`
188
-
189
- - `cd ../../`
190
-
191
- - `npm run express-sample`
192
-
193
- - Or `npm run sample`
194
-
195
- - Or `cd` into `sampleApps/express` and run `npm ci` and `npm start`
196
-
197
- - Go to [http://localhost:3000](http://localhost:3000)
198
-
199
- - The page with the web component is located at http://localhost:3000/pageWithForm
25
+ 3. Use `${templateLiteral}` values for values in your `<template>` markup. See "Usage" for more details.
package/USAGE.md ADDED
@@ -0,0 +1,300 @@
1
+ We will demo this technique end-to-end using a `<word-count>` component that counts the number of words a user types into a `<textarea>`.
2
+
3
+ Suppose the intended use of the `<word-count>` component looks like this:
4
+
5
+ ```html
6
+ <word-count text="Once upon a time... " id="story">
7
+ <p slot="description">Type your story in the box above!</p>
8
+ </word-count>
9
+ ```
10
+
11
+ And suppose also that you have an Express application with templates loaded into `mvc/views`.
12
+
13
+ To leverage this module's progressive enhancement technique, you will need to define this component using a `<template>` element in any one of your templates as follows:
14
+
15
+ ```html
16
+ <template id="word-count">
17
+ <style>
18
+ div {
19
+ position: relative;
20
+ }
21
+ textarea {
22
+ margin-top: 35px;
23
+ width: 100%;
24
+ box-sizing: border-box;
25
+ }
26
+ span {
27
+ display: block;
28
+ position: absolute;
29
+ top: 0;
30
+ right: 0;
31
+ margin-top: 10px;
32
+ font-weight: bold;
33
+ }
34
+ </style>
35
+ <div>
36
+ <textarea rows="10" cols="50" name="${id}" id="${id}">${text}</textarea>
37
+ <slot name="description"></slot>
38
+ <span class="word-count"></span>
39
+ </div>
40
+ </template>
41
+ ```
42
+
43
+ *Note: Any `${templateLiterals}` present in the template markup will be replaced with attribute values from the custom element invocation. More on that below.*
44
+
45
+ Then, in your Express application:
46
+
47
+ ```javascript
48
+ const fs = require('fs-extra')
49
+ const path = require('path')
50
+
51
+ const viewsDir = path.join('mvc', 'views')
52
+ const preprocessedViewsDir = path.join('mvc', '.preprocessed_views')
53
+
54
+ // load progressively-enhance-web-components.js
55
+ const editedFiles = require('progressively-enhance-web-components')({
56
+ templatesDir: viewsDir
57
+ })
58
+
59
+ // copy unmodified templates to a modified templates directory
60
+ fs.copySync(viewsDir, preprocessedViewsDir)
61
+
62
+ // update the relevant templates
63
+ for (const file in editedFiles) {
64
+ fs.writeFileSync(path.join(preprocessedViewsDir, path.relative(viewsDir, file)), editedFiles[file])
65
+ }
66
+
67
+ // configure express
68
+ const express = require('express')
69
+ const app = express()
70
+ app.engine('html', require('teddy').__express) // set teddy as view engine that will load html files
71
+ app.set('views', preprocessedViewsDir) // set template dir
72
+ app.set('view engine', 'html') // set teddy as default view engine
73
+
74
+ // start the server
75
+ const port = 3000
76
+ app.listen(port, () => {
77
+ console.log(`🎧 express sample app server is running on http://localhost:${port}`)
78
+ })
79
+ ```
80
+
81
+ *Note: The above example uses the [Teddy](https://rooseveltframework.org/docs/teddy) templating system, but you can use any templating system you like.*
82
+
83
+ In the above sample Express application, the `mvc/views` folder is copied to `mvc/.preprocessed_views`, then any template files in there will be updated to replace any uses of `<word-count>` with a more progressive enhancement-friendly version of `<word-count>` instead.
84
+
85
+ What that version looks like depends on the mode. There are three modes: `light`, `shadow`, and `both`. You can declare a mode with the `mode` attribute in your template element:
86
+
87
+ ```html
88
+ <template id="word-count" mode="shadow">
89
+ ```
90
+
91
+ Or set `mode` as a param instead to change the default for every component at once.
92
+
93
+ Whichever mode is used, the `${templateLiterals}` in the definition are replaced with the attribute values of the invocation, which is how the `name` attribute, the `id` attribute and the contents of the `<textarea>` come to be filled in below. The `<template>` element defining the component is also left in the page in every mode, so a component created in JavaScript still has something to render from.
94
+
95
+ ### Modes
96
+
97
+ #### `both`
98
+
99
+ The default. The component's markup is written into a [declarative shadow root](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/template#shadowrootmode), and a copy of it is kept beside that as fallback content. So a web component in your templates that looks like this:
100
+
101
+ ```html
102
+ <word-count text="Once upon a time... " id="story">
103
+ <p slot="description">Type your story in the box above!</p>
104
+ </word-count>
105
+ ```
106
+
107
+ Will be replaced with this:
108
+
109
+ ```html
110
+ <word-count text="Once upon a time... " id="story" data-enhanced>
111
+ <template shadowrootmode="open">
112
+ <style>
113
+ div {
114
+ position: relative;
115
+ }
116
+
117
+ textarea {
118
+ margin-top: 35px;
119
+ width: 100%;
120
+ box-sizing: border-box;
121
+ }
122
+
123
+ span {
124
+ display: block;
125
+ position: absolute;
126
+ top: 0;
127
+ right: 0;
128
+ margin-top: 10px;
129
+ font-weight: bold;
130
+ }
131
+ </style>
132
+ <div>
133
+ <textarea rows="10" cols="50" name="story" id="story">Once upon a time... </textarea>
134
+ <slot name="description"></slot>
135
+ <span class="word-count"></span>
136
+ </div>
137
+ </template>
138
+ <div slot="pewc-fallback">
139
+ <textarea rows="10" cols="50" name="story" id="story">Once upon a time... </textarea>
140
+ <span class="word-count"></span>
141
+ </div>
142
+
143
+ <p slot="description">Type your story in the box above!</p>
144
+ </word-count>
145
+ ```
146
+
147
+ This mode is the default because it is the most progressive enhancement-friendly: it is the only one that renders the component before any JavaScript loads whatever the browser supports, and where declarative shadow DOM is supported what it renders is the finished component, styled and with its slots filled, rather than a stand-in that appears unstyled and is then replaced. The tradeoff is it serves the most verbose amount of markup to the page, but that cost is trivial, especially when taking compression into consideration.
148
+
149
+ #### `shadow`
150
+
151
+ The declarative shadow root alone, with no fallback copy:
152
+
153
+ ```html
154
+ <word-count text="Once upon a time... " id="story" data-enhanced>
155
+ <template shadowrootmode="open">
156
+ <style>
157
+ div {
158
+ position: relative;
159
+ }
160
+
161
+ textarea {
162
+ margin-top: 35px;
163
+ width: 100%;
164
+ box-sizing: border-box;
165
+ }
166
+
167
+ span {
168
+ display: block;
169
+ position: absolute;
170
+ top: 0;
171
+ right: 0;
172
+ margin-top: 10px;
173
+ font-weight: bold;
174
+ }
175
+ </style>
176
+ <div>
177
+ <textarea rows="10" cols="50" name="story" id="story">Once upon a time... </textarea>
178
+ <slot name="description"></slot>
179
+ <span class="word-count"></span>
180
+ </div>
181
+ </template>
182
+
183
+ <p slot="description">Type your story in the box above!</p>
184
+ </word-count>
185
+ ```
186
+
187
+ Smaller, and worth choosing for a component whose content nobody would miss before the JavaScript loads, such as a tab bar or a toggle. The cost is that a browser which does not support declarative shadow DOM renders nothing at all, an unsupported `<template>` being inert. The same is true of anything that parses HTML without building shadow roots, such as a crawler that does not run a browser engine.
188
+
189
+ #### `light`
190
+
191
+ The fallback markup alone, written into the light DOM:
192
+
193
+ ```html
194
+ <word-count text="Once upon a time... " id="story" data-enhanced>
195
+ <div>
196
+ <textarea rows="10" cols="50" name="story" id="story">Once upon a time... </textarea>
197
+ <span class="word-count"></span>
198
+ </div>
199
+ <p slot="description">Type your story in the box above!</p>
200
+ </word-count>
201
+ ```
202
+
203
+ This displays to users with JavaScript disabled in every browser, but it is unstyled, the content given to a slot is not projected into it, and once the component upgrades the markup is shadowed and stays in the DOM unused.
204
+
205
+ ### How to ensure a custom element you want left untouched by this library is ignored
206
+
207
+ Apply a `data-enhanced` attribute:
208
+
209
+ ```html
210
+ <word-count text="Once upon a time... " id="story" data-enhanced>
211
+ <!-- whatever you wrote here is what stays here -->
212
+ </word-count>
213
+ ```
214
+
215
+ Alternatively, if a `<template shadowrootmode>` exists in your custom element invocation, that will also cause this library to ignore it.
216
+
217
+ This library will also apply the `data-enhanced` attribute to any custom element it enhances to prevent re-enhancing on a second pass.
218
+
219
+ The element itself is left exactly as written, but other invocations nested inside it that are not marked are still enhanced.
220
+
221
+ An invocation is also left alone wherever a browser would not render it as an element: inside an HTML comment, inside a `<script>`, `<style>`, `<textarea>` or `<title>`, and inside a plain `<template>` (including the `<template>` that defines a component, which your component's JavaScript clones as it was written). An invocation inside a `<template shadowrootmode>` is rendered by the browser, so it is enhanced.
222
+
223
+ ### What counts as a component definition
224
+
225
+ Only a `<template>` whose `id` is a valid custom element name is treated as a component: it must start with a lowercase letter, contain a hyphen, and contain no uppercase letters, the same rules `customElements.define` enforces. So `<template id="word-count">` defines `<word-count>`, while a `<template id="header">` or `<template id="row">` used for some other purpose is ignored rather than being applied to every `<header>` or `<row>`.
226
+
227
+ If the same `id` is defined in more than one file, the one in the file that comes last alphabetically by path is used, and a warning is logged.
228
+
229
+ A component's template can invoke other components, and each of those is enhanced as part of it. A component that invokes itself, directly or through another component, would expand forever, so the inner invocation is left for the component's JavaScript to render (and marked `data-enhanced`), and a warning is logged.
230
+
231
+ ### Attribute values are escaped
232
+
233
+ The value of an attribute is written into the component's markup as text, so `label="Tom &amp; Jerry"` or `label="say &quot;hi&quot;"` comes out as that text rather than as broken markup. If you need markup inside a component, pass it as slotted child content instead of through an attribute.
234
+
235
+ Values are not escaped for CSS or JavaScript, so avoid putting a `${templateLiteral}` inside a `<style>` or `<script>` element unless you control the attribute's value.
236
+
237
+ ### Template language syntax inside an invocation's opening tag
238
+
239
+ Each invocation is read by an HTML parser, so template language syntax written *between the attributes* of an invocation's opening tag will not survive. For example, `<word-count {if hidden}hidden{/if}>` is read as attributes named `{if`, `hidden}hidden{` and `if}`. Template syntax inside an attribute value (`text="{story}"`) or in the element's children is fine. If you need a conditional attribute, put the condition around the whole element instead.
240
+
241
+ ### Writing the frontend JavaScript
242
+
243
+ Then, once the frontend JavaScript takes over, the web component can be progressively enhanced into the JS-driven version.
244
+
245
+ Here's an example implementation for the frontend JS side:
246
+
247
+ ```javascript
248
+ class WordCount extends window.HTMLElement {
249
+ connectedCallback () { // called whenever a new instance of this element is inserted into the dom
250
+ // this.shadowRoot will exist already, except in light mode or for an element created in javascript
251
+ this.shadow = this.shadowRoot || this.attachShadow({ mode: 'open' })
252
+
253
+ // add the markup of the component if it is not already populated
254
+ if (!this.shadow.childElementCount) {
255
+ const markup = document.getElementById('word-count').content.cloneNode(true)
256
+
257
+ // fill in its ${templateLiterals} from this element's attributes
258
+ //
259
+ // the text and attribute values are set directly rather than by editing markup, so that a value holding a quote or an angle bracket is written as text instead of being parsed as html
260
+ const fill = text => text.replace(/\$\{([^}]+)\}/g, (literal, name) => this.getAttribute(name) ?? literal)
261
+ const walker = document.createTreeWalker(markup, window.NodeFilter.SHOW_ELEMENT | window.NodeFilter.SHOW_TEXT)
262
+ while (walker.nextNode()) {
263
+ const node = walker.currentNode
264
+ if (node.nodeType === window.Node.TEXT_NODE) node.data = fill(node.data)
265
+ else for (const attrib of node.attributes) attrib.value = fill(attrib.value)
266
+ }
267
+
268
+ this.shadow.append(markup)
269
+ }
270
+
271
+ const textarea = this.shadow.querySelector('textarea')
272
+
273
+ // function for updating the word count
274
+ const updateWordCount = () => {
275
+ this.shadow.querySelector('span').textContent = `Words: ${textarea.value.trim().split(/\s+/g).filter(a => a.trim().length > 0).length}`
276
+ }
277
+
278
+ // update count when textarea content changes
279
+ textarea.addEventListener('input', updateWordCount)
280
+ updateWordCount() // update it on load as well
281
+ }
282
+ }
283
+
284
+ window.customElements.define('word-count', WordCount) // define the new element
285
+ ```
286
+
287
+ ### Sample app
288
+
289
+ The sample app takes the default mode, so you can see each half of it working. See an end-to-end demo by running it:
290
+
291
+ - `cd sampleApps/express`
292
+ - `npm ci`
293
+ - `cd ../../`
294
+ - `npm run express-sample`
295
+ - Or `npm run sample`
296
+ - Or `cd` into `sampleApps/express` and run `npm ci` and `npm start`
297
+ - Go to [http://localhost:3000](http://localhost:3000)
298
+ - The page with the web component is located at [http://localhost:3000/pageWithForm](http://localhost:3000/pageWithForm)
299
+
300
+ Look at `mvc/.preprocessed_views/pageWithForm.html` to see what the invocation was turned into. Then turn JavaScript off and load the page again: the component still renders, still has its styles, and still shows the content given to its slot, because the browser's parser built the shadow root without being asked to run anything. Only the word counter is missing, that being the part JavaScript is there for.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "progressively-enhance-web-components",
3
- "description": "🕸️ Template file preprocessor for progressively enhancing web components.",
3
+ "description": "\ud83d\udd78\ufe0f Template file preprocessor for progressively enhancing web components.",
4
4
  "author": "Roosevelt Framework Team <rooseveltframework@gmail.com>",
5
5
  "contributors": [
6
6
  {
@@ -8,36 +8,42 @@
8
8
  "url": "https://github.com/rooseveltframework/progressively-enhance-web-components/graphs/contributors"
9
9
  }
10
10
  ],
11
- "version": "1.0.4",
12
- "homepage": "https://github.com/rooseveltframework/progressively-enhance-web-components",
11
+ "version": "2.1.0",
12
+ "homepage": "https://rooseveltframework.org/docs/progressively-enhance-web-components/latest",
13
13
  "license": "CC-BY-4.0",
14
14
  "main": "progressively-enhance-web-components.js",
15
+ "files": [
16
+ "progressively-enhance-web-components.js",
17
+ "CHANGELOG.md",
18
+ "CONFIGURATION.md",
19
+ "USAGE.md"
20
+ ],
15
21
  "engines": {
16
- "node": ">=18.0.0"
22
+ "node": ">=22.0.0"
17
23
  },
18
24
  "dependencies": {
19
- "js-beautify": "1.15.4",
20
- "jsdom": "26.0.0"
25
+ "js-beautify": "2.0.3",
26
+ "jsdom": "31.0.1"
21
27
  },
22
28
  "devDependencies": {
23
- "c8": "10.1.3",
24
- "mocha": "11.1.0",
29
+ "@playwright/test": "1.65.1",
25
30
  "standard": "17.1.2"
26
31
  },
27
- "mocha": {
28
- "timeout": "700000ms"
29
- },
30
32
  "standard": {
31
33
  "ignore": [
32
34
  "dist/",
33
- "sampleApps/express/public"
35
+ "playwright-report/",
36
+ "sampleApps/express/public",
37
+ "test-results/"
34
38
  ]
35
39
  },
36
40
  "scripts": {
37
41
  "lint": "standard",
38
42
  "lint-fix": "standard --fix",
39
- "test": "mocha test/*.js",
40
- "coverage": "c8 --reporter=text --reporter=lcov mocha test/*.js --test",
43
+ "test": "npm run test-node && npm run test-browser",
44
+ "test-node": "node --test test/test.js",
45
+ "test-browser": "playwright test",
46
+ "coverage": "node --test --experimental-test-coverage test/test.js",
41
47
  "express-sample": "node -e \"process.chdir('sampleApps/express'); require('./sampleApps/express/server.js')\"",
42
48
  "sample": "npm run express-sample"
43
49
  },