progressively-enhance-web-components 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ on: [push, pull_request]
2
+ name: CI
3
+ jobs:
4
+ test:
5
+ runs-on: ${{ matrix.os }}
6
+ strategy:
7
+ matrix:
8
+ node-version: [18.x, 20.x, 22.x]
9
+ os: [ubuntu-latest, macos-latest, windows-latest]
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - name: Use Node.js ${{ matrix.node-version }}
13
+ uses: actions/setup-node@v4
14
+ with:
15
+ node-version: ${{ matrix.node-version }}
16
+ - run: npm ci
17
+ - run: npm run lint
18
+ - run: npm run coverage
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## Next version
4
+
5
+ - Put your changes here...
6
+
7
+ ## 1.0.0
8
+
9
+ - Initial commit.
package/LICENSE.md ADDED
@@ -0,0 +1,4 @@
1
+ License
2
+ ===
3
+
4
+ All original code in this module is licensed under the [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/). Commercial and noncommercial use is permitted with attribution.
package/README.md ADDED
@@ -0,0 +1,198 @@
1
+ progressively-enhance-web-components
2
+ ===
3
+
4
+ [![npm](https://img.shields.io/npm/v/progressively-enhance-web-components.svg)](https://www.npmjs.com/package/progressively-enhance-web-components)
5
+
6
+ A template file preprocessor for [progressively enhancing](https://en.wikipedia.org/wiki/Progressive_enhancement) web components in Node.js.
7
+
8
+ It works by reading a directory of HTML templates for your web application, identifying any web components, and replacing custom element invocations with fallback markup that will work if JavaScript is disabled which will then be progressively enhanced into the desired web component when the JavaScript loads.
9
+
10
+ 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 server-side template renders and without having to write two different templates for each context.
11
+
12
+ 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.
13
+
14
+ ## Technique
15
+
16
+ To leverage this module's progressive enhancement technique, you will need to follow some simple rules when authoring your web component:
17
+
18
+ 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.
19
+ 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.
20
+ 3. Use `${templateLiteral}` values for values in your `<template>` markup. See how that works in the example below.
21
+
22
+ ## Usage
23
+
24
+ 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>`.
25
+
26
+ Suppose the intended use of the `<word-count>` component looks like this:
27
+
28
+ ```html
29
+ <word-count text="Once upon a time... " id="story">
30
+ <p slot="description">Type your story in the box above!</p>
31
+ </word-count>
32
+ ```
33
+
34
+ And suppose also that you have an Express application with templates loaded into `mvc/views`.
35
+
36
+ So 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:
37
+
38
+ ```html
39
+ <template id="word-count">
40
+ <style>
41
+ div {
42
+ position: relative;
43
+ }
44
+ textarea {
45
+ margin-top: 35px;
46
+ width: 100%;
47
+ box-sizing: border-box;
48
+ }
49
+ span {
50
+ display: block;
51
+ position: absolute;
52
+ top: 0;
53
+ right: 0;
54
+ margin-top: 10px;
55
+ font-weight: bold;
56
+ }
57
+ </style>
58
+ <div>
59
+ <textarea rows="10" cols="50" name="${id}" id="${id}">${text}</textarea>
60
+ <slot name="description"></slot>
61
+ <span></span>
62
+ </div>
63
+ </template>
64
+ ```
65
+
66
+ *Note: Any `${templateLiterals}` present in the template markup will be replaced with attribute values from the custom element invocation. More on that below.*
67
+
68
+ Then, in your Express application:
69
+
70
+ ```javascript
71
+ const fs = require('fs-extra')
72
+
73
+ // load progressively-enhance-web-components.js
74
+ const editedFiles = require('progressively-enhance-web-components')({
75
+ templatesDir: './mvc/views'
76
+ })
77
+
78
+ // copy unmodified templates to a modified templates directory
79
+ fs.copySync('mvc/views', 'mvc/.preprocessed_views')
80
+
81
+ // update the relevant templates
82
+ for (const file in editedFiles) {
83
+ fs.writeFileSync(file.replace('mvc/views', 'mvc/.preprocessed_views'), editedFiles[file])
84
+ }
85
+
86
+ // configure express
87
+ const express = require('express')
88
+ const app = express()
89
+ app.engine('html', require('teddy').__express) // set teddy as view engine that will load html files
90
+ app.set('views', 'mvc/.preprocessed_views') // set template dir
91
+ app.set('view engine', 'html') // set teddy as default view engine
92
+
93
+ // start the server
94
+ const port = 3000
95
+ app.listen(port, () => {
96
+ console.log(`🎧 express sample app server is running on http://localhost:${port}`)
97
+ })
98
+ ```
99
+
100
+ *Note: The above example uses the [Teddy](https://github.com/rooseveltframework/teddy) templating system, but you can use any templating system you like, so long as your templates can survive being preprocessed by [jsdom](https://github.com/jsdom/jsdom), which is a core part of how this module does its progressive enhancement work.*
101
+
102
+ 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.
103
+
104
+ So, for example, any web component in your templates that looks like this:
105
+
106
+ ```html
107
+ <word-count text="Once upon a time... " id="story">
108
+ <p slot="description">Type your story in the box above!</p>
109
+ </word-count>
110
+ ```
111
+
112
+ Will be replaced with this:
113
+
114
+ ```html
115
+ <word-count text="Once upon a time... " id="story">
116
+ <div>
117
+ <textarea rows="10" cols="50" name="story" id="story">Once upon a time... </textarea>
118
+ <span></span>
119
+ </div>
120
+ <p slot="description">Type your story in the box above!</p>
121
+ </word-count>
122
+ ```
123
+
124
+ 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.
125
+
126
+ 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.
127
+
128
+ 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.
129
+
130
+ Then, once the frontend JavaScript takes over, the web component can be progressively enhanced into the JS-driven version.
131
+
132
+ Here's an example implementation for the frontend JS side:
133
+
134
+ ```javascript
135
+ class WordCount extends window.HTMLElement {
136
+ connectedCallback () { // called whenever a new instance of this element is inserted into the dom
137
+ this.shadow = this.attachShadow({ mode: 'open' }) // create and attach a shadow dom to the custom element
138
+ this.shadow.appendChild(document.getElementById('word-count').content.cloneNode(true)) // create the elements in the shadow dom from the template element
139
+
140
+ // set textarea attributes
141
+ const textarea = this.shadow.querySelector('textarea')
142
+ textarea.value = this.getAttribute('text') || ''
143
+ textarea.id = this.getAttribute('id') || ''
144
+ textarea.name = this.getAttribute('id') || ''
145
+
146
+ // function for updating the word count
147
+ const updateWordCount = () => {
148
+ this.shadow.querySelector('span').textContent = `Words: ${textarea.value.trim().split(/\s+/g).filter(a => a.trim().length > 0).length}`
149
+ }
150
+
151
+ // update count when textarea content changes
152
+ textarea.addEventListener('input', updateWordCount)
153
+ updateWordCount() // update it on load as well
154
+ }
155
+ }
156
+
157
+ window.customElements.define('word-count', WordCount) // define the new element
158
+ ```
159
+
160
+ 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.
161
+
162
+ ### Available options
163
+
164
+ When you call:
165
+
166
+ ```javascript
167
+ const editedFiles = require('progressively-enhance-web-components')({
168
+ templatesDir: './mvc/views'
169
+ })
170
+ ```
171
+
172
+ There are other params you can pass to it besides `templatesDir`.
173
+
174
+ The full list of params available is:
175
+
176
+ - `templatesDir`: What folder to examine. This is required.
177
+ - `disableBeautify`: If set to true, this module will not beautify the HTML in the outputted markup. Default: `false`.
178
+ - `beautifyOptions`: Options to pass to [js-beautify](https://github.com/beautifier/js-beautify). Default: `{ indent_size: 2 }`.
179
+
180
+ ### Sample app
181
+
182
+ Here's how to run the sample app:
183
+
184
+ - `cd sampleApps/express`
185
+
186
+ - `npm ci`
187
+
188
+ - `cd ../../`
189
+
190
+ - `npm run express-sample`
191
+
192
+ - Or `npm run sample`
193
+
194
+ - Or `cd` into `sampleApps/express` and run `npm ci` and `npm start`
195
+
196
+ - Go to [http://localhost:3000](http://localhost:3000)
197
+
198
+ - The page with the web component is located at http://localhost:3000/pageWithForm
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "progressively-enhance-web-components",
3
+ "description": "🕸️ Template file preprocessor for progressively enhancing web components.",
4
+ "author": "Roosevelt Framework Team <rooseveltframework@gmail.com>",
5
+ "contributors": [
6
+ {
7
+ "name": "Contributors",
8
+ "url": "https://github.com/rooseveltframework/progressively-enhance-web-components/graphs/contributors"
9
+ }
10
+ ],
11
+ "version": "1.0.0",
12
+ "homepage": "https://github.com/rooseveltframework/progressively-enhance-web-components",
13
+ "license": "CC-BY-4.0",
14
+ "main": "progressively-enhance-web-components.js",
15
+ "engines": {
16
+ "node": ">=18.0.0"
17
+ },
18
+ "dependencies": {
19
+ "js-beautify": "1.15.3",
20
+ "jsdom": "26.0.0"
21
+ },
22
+ "devDependencies": {
23
+ "c8": "10.1.3",
24
+ "mocha": "11.1.0",
25
+ "standard": "17.1.2"
26
+ },
27
+ "mocha": {
28
+ "timeout": "700000ms"
29
+ },
30
+ "standard": {
31
+ "ignore": [
32
+ "dist/",
33
+ "sampleApps/express/public"
34
+ ]
35
+ },
36
+ "scripts": {
37
+ "lint": "standard",
38
+ "lint-fix": "standard --fix",
39
+ "test": "mocha test/*.js",
40
+ "coverage": "c8 --reporter=text --reporter=lcov mocha test/*.js --test",
41
+ "express-sample": "node -e \"process.chdir('sampleApps/express'); require('./sampleApps/express/server.js')\"",
42
+ "sample": "npm run express-sample"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git://github.com/rooseveltframework/progressively-enhance-web-components.git"
47
+ },
48
+ "keywords": [
49
+ "progressively enhance",
50
+ "progressively",
51
+ "enhance",
52
+ "progressive enhancement",
53
+ "progressive",
54
+ "enhancement",
55
+ "web components",
56
+ "web",
57
+ "components",
58
+ "custom elements",
59
+ "custom",
60
+ "elements"
61
+ ],
62
+ "funding": "https://www.paypal.com/donate/?hosted_button_id=2L2X8GRXZCGJ6"
63
+ }
@@ -0,0 +1,99 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const { JSDOM } = require('jsdom')
4
+ const beautify = require('js-beautify').html
5
+
6
+ function loopThroughFilesSync (dir) {
7
+ let fileList = []
8
+ const files = fs.readdirSync(dir, { withFileTypes: true })
9
+ files.forEach(file => {
10
+ const filePath = path.join(dir, file.name)
11
+ if (file.isDirectory()) fileList = fileList.concat(loopThroughFilesSync(filePath)) // recurse dirs
12
+ else if (file.isFile() && !file.name.startsWith('.')) fileList.push(filePath) // exclude hidden files
13
+ })
14
+ return fileList
15
+ }
16
+
17
+ function isBinaryFile (filePath, bytesToCheck = 512) {
18
+ const buffer = Buffer.alloc(bytesToCheck)
19
+ const fd = fs.openSync(filePath, 'r')
20
+ const bytesRead = fs.readSync(fd, buffer, 0, bytesToCheck, 0)
21
+ fs.closeSync(fd)
22
+ for (let i = 0; i < bytesRead; i++) {
23
+ const byte = buffer[i]
24
+ if (byte === 0) return true // null byte found, likely a binary file
25
+ else if ((byte < 32 || byte > 126) && byte !== 10 && byte !== 13 && byte !== 9) return true // non-printable ascii character found, likely a binary file; allow common control characters: \n (10), \r (13), \t (9)
26
+ }
27
+ return false
28
+ }
29
+
30
+ module.exports = (params) => {
31
+ const beautifyOptions = params?.beautifyOptions || {
32
+ indent_size: 2
33
+ }
34
+
35
+ // find all <template> elements with ids that are defined in any of the html templates
36
+ const templateFiles = loopThroughFilesSync(params.templatesDir)
37
+ const allTemplateElements = {}
38
+ for (const templateFile of templateFiles) {
39
+ if (!isBinaryFile(templateFile)) {
40
+ const dom = new JSDOM(fs.readFileSync(templateFile, 'utf8'))
41
+ const document = dom.window.document
42
+ const allElements = document.querySelectorAll('*')
43
+ const templateElements = Array.from(allElements).filter(element => element.tagName === 'TEMPLATE')
44
+ for (const templateElement of templateElements) {
45
+ if (templateElement.id) allTemplateElements[templateElement.id] = templateElement
46
+ }
47
+ }
48
+ }
49
+
50
+ // replace web components in all template files with a progressive enhancement-friendly version of the element
51
+ const editedFiles = {}
52
+ for (const templateFile of templateFiles) {
53
+ const templateCode = fs.readFileSync(templateFile, 'utf8')
54
+ if (!isBinaryFile(templateFile)) {
55
+ let dom
56
+ let document
57
+ let partial = false
58
+ if (templateCode.trimStart().startsWith('<!DOCTYPE') || templateCode.trimStart().startsWith('<!doctype')) {
59
+ dom = new JSDOM(templateCode)
60
+ document = dom.window.document
61
+ } else {
62
+ dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')
63
+ document = dom.window.document
64
+ const fragment = JSDOM.fragment(templateCode)
65
+ document.body.appendChild(fragment)
66
+ partial = true
67
+ }
68
+ const customElements = Array.from(document.querySelectorAll('*')).filter(element => element.tagName.includes('-')) // if there is a hyphen in the element name, it is a custom element
69
+ for (const element of customElements) {
70
+ if (!allTemplateElements[element.tagName.toLowerCase()]) continue // no <template> element found for this custom element, so do not convert it into a progressive enhancement-friendly version of the element
71
+
72
+ // clone the <template> markup so we can construct a more verbose, progressive enhancement-compatible version of the web component
73
+ const template = allTemplateElements[element.tagName.toLowerCase()].content.cloneNode(true)
74
+
75
+ // remove elements that are not needed in the progressive enhancement context from the <template> markup
76
+ template.querySelectorAll('style, script, slot').forEach(el => el.remove())
77
+
78
+ // replace template literals with attribute values in the <template> markup
79
+ const container = document.createElement('div')
80
+ container.appendChild(template)
81
+ for (const attrib of element.attributes) container.innerHTML = container.innerHTML.replaceAll('${' + attrib.name + '}', attrib.value)
82
+ const componentBeautifyOptions = { ...beautifyOptions }
83
+ componentBeautifyOptions.preserve_newlines = false // remove newlines from components in case any style, script, or slot elements have been removed
84
+ container.innerHTML = beautify(container.innerHTML, componentBeautifyOptions)
85
+
86
+ // move any component child elements with slot attributs to the root of the component's light dom because such elements always need to be at the root to be accepted by the web component JS
87
+ element.querySelectorAll('[slot]').forEach(slot => container.appendChild(slot.cloneNode(true)))
88
+
89
+ // replace the original custom element with the new progressive enhancement-friendly version of the element
90
+ element.innerHTML = params?.disableBeautify ? container.innerHTML : beautify(container.innerHTML, beautifyOptions)
91
+ let newFile = partial ? document.body.innerHTML : dom.serialize()
92
+ newFile = params?.disableBeautify ? newFile : beautify(newFile, beautifyOptions)
93
+ editedFiles[templateFile] = newFile
94
+ }
95
+ }
96
+ }
97
+
98
+ return editedFiles
99
+ }
package/renovate.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": [
3
+ "config:base",
4
+ ":preserveSemverRanges",
5
+ ":ignoreUnstable",
6
+ ":respectLatest",
7
+ ":disableDependencyDashboard"
8
+ ]
9
+ }
@@ -0,0 +1,23 @@
1
+ class WordCount extends window.HTMLElement {
2
+ connectedCallback () { // called whenever a new instance of this element is inserted into the dom
3
+ this.shadow = this.attachShadow({ mode: 'open' }) // create and attach a shadow dom to the custom element
4
+ this.shadow.appendChild(document.getElementById('word-count').content.cloneNode(true)) // create the elements in the shadow dom from the template element
5
+
6
+ // set textarea attributes
7
+ const textarea = this.shadow.querySelector('textarea')
8
+ textarea.value = this.getAttribute('text') || ''
9
+ textarea.id = this.getAttribute('id') || ''
10
+ textarea.name = this.getAttribute('id') || ''
11
+
12
+ // function for updating the word count
13
+ const updateWordCount = () => {
14
+ this.shadow.querySelector('span').textContent = `Words: ${textarea.value.trim().split(/\s+/g).filter(a => a.trim().length > 0).length}`
15
+ }
16
+
17
+ // update count when textarea content changes
18
+ textarea.addEventListener('input', updateWordCount)
19
+ updateWordCount() // update it on load as well
20
+ }
21
+ }
22
+
23
+ window.customElements.define('word-count', WordCount) // define the new element
@@ -0,0 +1,17 @@
1
+ module.exports = function (app) {
2
+ app.get('/', (req, res) => {
3
+ res.render('index', {})
4
+ })
5
+
6
+ app.get('/secondPage', (req, res) => {
7
+ res.render('secondPage', { variable: 'variable with contents: "hi there!"' })
8
+ })
9
+
10
+ app.get('/pageWithForm', (req, res) => {
11
+ res.render('pageWithForm', {})
12
+ })
13
+
14
+ app.post('/pageWithForm', (req, res) => {
15
+ res.render('pageWithForm', {})
16
+ })
17
+ }
@@ -0,0 +1,5 @@
1
+ <include src="layouts/main">
2
+ <arg pageContent>
3
+ <p>hello world</p>
4
+ </arg>
5
+ </include>
@@ -0,0 +1,49 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <meta name="format-detection" content="telephone=no">
7
+ <title>Sample app for progressively enhanced web components</title>
8
+ <script src="/bundle.js" defer></script>
9
+ </head>
10
+ <body>
11
+ <nav>
12
+ <ul>
13
+ <li><a href="/">Homepage</a></li>
14
+ <li><a href="/secondPage">Second page</a></li>
15
+ <li><a href="/pageWithForm">Page with form</a></li>
16
+ </ul>
17
+ </nav>
18
+ <article id="page-contents">
19
+ {pageContent|s}
20
+ </article>
21
+ <noparse> {! the noparse tag prevents the teddy templating system from parsing any children of this block which is necessary to prevent teddy from trying to parse the template literals below !}
22
+ <template id="word-count">
23
+ <style>
24
+ div {
25
+ position: relative;
26
+ }
27
+ textarea {
28
+ margin-top: 35px;
29
+ width: 100%;
30
+ box-sizing: border-box;
31
+ }
32
+ span {
33
+ display: block;
34
+ position: absolute;
35
+ top: 0;
36
+ right: 0;
37
+ margin-top: 10px;
38
+ font-weight: bold;
39
+ }
40
+ </style>
41
+ <div>
42
+ <textarea rows="10" cols="50" name="${id}" id="${id}">${text}</textarea>
43
+ <slot name="description"></slot>
44
+ <span></span>
45
+ </div>
46
+ </template>
47
+ </noparse>
48
+ </body>
49
+ </html>
@@ -0,0 +1,21 @@
1
+ <include src="layouts/main">
2
+ <arg pageContent>
3
+ <p>page with a form</p>
4
+ <form action="/pageWithForm" method="post">
5
+ <dl>
6
+ <dt><label for="your_name">Your name:</label></dt>
7
+ <dd><input type="text" name="your_name" id="your_name" value=""></dd>
8
+ <dt><label for="story">Tell me a story:</label></dt>
9
+ <dd>
10
+ <word-count text="Once upon a time... " id="story">
11
+ <p slot="description">Type your story in the box above!</p>
12
+ </word-count>
13
+ </dd>
14
+ </dl>
15
+ <menu>
16
+ <li><button type="submit" name="button1">Button 1</button></li>
17
+ <li><button type="submit" name="button2">Button 2</button></li>
18
+ </menu>
19
+ </form>
20
+ </arg>
21
+ </include>
@@ -0,0 +1,5 @@
1
+ <include src="layouts/main">
2
+ <arg pageContent>
3
+ <p>this is a second page and prints a {variable}</p>
4
+ </arg>
5
+ </include>