progressively-enhance-web-components 1.0.3 → 2.0.1

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.
@@ -5,7 +5,12 @@ const beautify = require('js-beautify').html
5
5
 
6
6
  function loopThroughFilesSync (dir) {
7
7
  let fileList = []
8
- const files = fs.readdirSync(dir, { withFileTypes: true })
8
+ let files
9
+ try {
10
+ files = fs.readdirSync(dir, { withFileTypes: true })
11
+ } catch (err) {
12
+ return fileList
13
+ }
9
14
  files.forEach(file => {
10
15
  const filePath = path.join(dir, file.name)
11
16
  if (file.isDirectory()) fileList = fileList.concat(loopThroughFilesSync(filePath)) // recurse dirs
@@ -27,12 +32,123 @@ function isBinaryFile (filePath, bytesToCheck = 512) {
27
32
  return false
28
33
  }
29
34
 
30
- // hack to get jsdom to shut up about invalid css
31
- const originalConsoleError = console.error
35
+ // jsdom complains about css it cannot parse, which is not something the caller can do anything about
36
+ //
37
+ // silencing it is done around the parse and undone afterwards, rather than once when this module is loaded: console.error belongs to whatever application is calling this, and it should not lose an error of its own for as long as the process lives because a stylesheet somewhere is unparseable
32
38
  const jsDomCssError = 'Error: Could not parse CSS stylesheet'
33
- console.error = (...params) => {
34
- if (!params.find(p => p.toString().includes(jsDomCssError))) {
35
- originalConsoleError(...params)
39
+ function withoutJsdomCssComplaints (work) {
40
+ const originalConsoleError = console.error
41
+ console.error = (...params) => {
42
+ if (!params.find(p => p.toString().includes(jsDomCssError))) originalConsoleError(...params)
43
+ }
44
+ try {
45
+ return work()
46
+ } finally {
47
+ console.error = originalConsoleError
48
+ }
49
+ }
50
+
51
+ // where the opening tag that begins at `from` ends
52
+ //
53
+ // the quotes are followed so that a greater than sign inside an attribute value does not look like the end of the tag
54
+ function endOfOpeningTag (markup, from) {
55
+ let quote = null
56
+ for (let i = from; i < markup.length; i++) {
57
+ const character = markup[i]
58
+ if (quote) {
59
+ if (character === quote) quote = null
60
+ } else if (character === '"' || character === "'") quote = character
61
+ else if (character === '>') return i
62
+ }
63
+ return -1
64
+ }
65
+
66
+ // the span of markup an element occupies, from the < that opens it to the > that closes it
67
+ //
68
+ // a regular expression cannot answer this. it has no way to pair an opening tag with the closing tag that belongs to it, so an element holding another of the same name ended at the inner closing tag and left the outer one behind as stray text
69
+ function elementSpan (markup, name, start) {
70
+ const openingTagEnd = endOfOpeningTag(markup, start)
71
+ if (openingTagEnd === -1) return null
72
+ if (markup[openingTagEnd - 1] === '/') return { start, end: openingTagEnd + 1 } // closed itself, so there is no closing tag to pair it with
73
+ const lowerMarkup = markup.toLowerCase()
74
+ const opening = `<${name.toLowerCase()}`
75
+ const closing = `</${name.toLowerCase()}`
76
+ let depth = 1
77
+ let at = openingTagEnd + 1
78
+ while (at < markup.length) {
79
+ const nextOpening = lowerMarkup.indexOf(opening, at)
80
+ const nextClosing = lowerMarkup.indexOf(closing, at)
81
+ if (nextClosing === -1) return null // never closed
82
+ if (nextOpening !== -1 && nextOpening < nextClosing) {
83
+ // a longer name beginning the same way is a different element: <my-thing> is not <my-thing-two>
84
+ if (/[\s/>]/.test(markup[nextOpening + opening.length] || '')) depth++
85
+ at = nextOpening + opening.length
86
+ continue
87
+ }
88
+ const closingTagEnd = markup.indexOf('>', nextClosing)
89
+ if (closingTagEnd === -1) return null
90
+ depth--
91
+ if (depth === 0) return { start, end: closingTagEnd + 1 }
92
+ at = closingTagEnd + 1
93
+ }
94
+ return null
95
+ }
96
+
97
+ // every place an element of this name is written, outermost first
98
+ function elementSpans (markup, name) {
99
+ const spans = []
100
+ const lowerMarkup = markup.toLowerCase()
101
+ const opening = `<${name.toLowerCase()}`
102
+ let at = 0
103
+ while (at < markup.length) {
104
+ const found = lowerMarkup.indexOf(opening, at)
105
+ if (found === -1) break
106
+ if (!/[\s/>]/.test(markup[found + opening.length] || '')) { // a different element whose name begins the same way
107
+ at = found + opening.length
108
+ continue
109
+ }
110
+ const span = elementSpan(markup, name, found)
111
+ if (!span) break
112
+ spans.push(span)
113
+ at = span.end // whatever is nested inside this element is replaced along with it
114
+ }
115
+ return spans
116
+ }
117
+
118
+ // the ways an invocation can be enhanced
119
+ //
120
+ // `light` writes the component's markup into the element as fallback content, which is what this module has always done. `shadow` writes it into a declarative shadow root instead, which keeps the styles and slots a fallback cannot use and needs nothing swapped once the component upgrades. `both` writes each of them, so that a browser which builds the shadow root renders that and one which does not renders the fallback
121
+ const MODES = new Set(['light', 'shadow', 'both'])
122
+
123
+ // what says an invocation has been enhanced already, so that running this over the same markup twice does not stack a second copy of everything onto it
124
+ //
125
+ // this module adds it to every element it touches, and a developer who has written a component's markup out for themselves can write it too, which is how such an invocation is left as it stands
126
+ const ENHANCED_ATTRIBUTE = 'data-enhanced'
127
+
128
+ // an element carrying a declarative shadow root already was written out by hand, and a second one is not something a browser will build: it refuses it and reports the refusal to the console. so that element is left alone whether or not anyone marked it
129
+ function alreadyEnhanced (element) {
130
+ if (element.hasAttribute(ENHANCED_ATTRIBUTE)) return true
131
+ for (const child of element.children) {
132
+ if (child.tagName === 'TEMPLATE' && child.hasAttribute('shadowrootmode')) return true
133
+ }
134
+ return false
135
+ }
136
+
137
+ // the name of a slot no component defines, which is what keeps the fallback markup of `both` out of the component
138
+ //
139
+ // a browser that builds the shadow root leaves a child naming a slot that does not exist unassigned, and an unassigned child is not rendered, so the fallback sits there inert. without the name a default <slot> would catch it and project the fallback back into the component beside the real content. a browser that does not build the shadow root has no slots to assign anything to, ignores the attribute, and renders the fallback, which is the whole point of it
140
+ const FALLBACK_SLOT = 'pewc-fallback'
141
+
142
+ // marks every top level node of the fallback markup as belonging to that slot
143
+ function holdOutOfSlots (container) {
144
+ for (const node of [...container.childNodes]) {
145
+ if (node.nodeType === 1) node.setAttribute('slot', FALLBACK_SLOT) // an element can carry the attribute itself
146
+ else if (node.nodeType === 3 && node.textContent.trim()) { // text cannot, so it is given something that can
147
+ const wrapper = container.ownerDocument.createElement('span')
148
+ node.replaceWith(wrapper)
149
+ wrapper.setAttribute('slot', FALLBACK_SLOT)
150
+ wrapper.appendChild(node)
151
+ }
36
152
  }
37
153
  }
38
154
 
@@ -40,71 +156,125 @@ module.exports = (params) => {
40
156
  const beautifyOptions = params?.beautifyOptions || {
41
157
  indent_size: 2
42
158
  }
159
+ const beautifyMarkup = markup => params?.disableBeautify ? markup : beautify(markup, beautifyOptions)
160
+
161
+ // the dom serializer writes an empty attribute out as data-enhanced="", which says the same thing as the bare form but is not what anyone writing it by hand would write
162
+ const bareEnhancedAttribute = markup => markup.replace(new RegExp(`\\s${ENHANCED_ATTRIBUTE}=""`, 'g'), ` ${ENHANCED_ATTRIBUTE}`)
163
+
164
+ // what to do with an invocation whose definition does not say for itself
165
+ const defaultMode = params?.mode || 'both'
166
+ if (!MODES.has(defaultMode)) throw new Error(`progressively-enhance-web-components: mode must be one of ${[...MODES].join(', ')}, not ${JSON.stringify(defaultMode)}`)
167
+
168
+ // every file that could hold a template or an invocation of one, read once
169
+ //
170
+ // reading them once is not only quicker: the enhanced markup of one custom element is what the next one is applied to, so a file invoking two of them ends up with both enhanced. re-reading the file for each custom element meant each started again from what was on disk, and only the last one survived into what this returns
171
+ const files = {}
172
+ for (const file of loopThroughFilesSync(params.templatesDir)) {
173
+ if (!isBinaryFile(file)) files[file] = fs.readFileSync(file, 'utf8')
174
+ }
43
175
 
44
176
  // find all <template> elements with ids that are defined in any of the html templates
45
- const templateFiles = loopThroughFilesSync(params.templatesDir)
46
177
  const allTemplateElements = {}
47
- for (const templateFile of templateFiles) {
48
- if (!isBinaryFile(templateFile)) {
49
- const dom = new JSDOM(fs.readFileSync(templateFile, 'utf8'))
50
- const document = dom.window.document
51
- const allElements = document.querySelectorAll('*')
52
- const templateElements = Array.from(allElements).filter(element => element.tagName === 'TEMPLATE')
53
- for (const templateElement of templateElements) {
54
- if (templateElement.id) allTemplateElements[templateElement.id] = templateElement
178
+ withoutJsdomCssComplaints(() => {
179
+ for (const contents of Object.values(files)) {
180
+ const { document } = new JSDOM(contents).window
181
+ for (const templateElement of document.querySelectorAll('template')) {
182
+ if (!templateElement.id) continue
183
+ // a definition may say how it wants to be enhanced, which is a property of the component rather than of any one place it is used
184
+ const mode = templateElement.getAttribute('mode') || defaultMode
185
+ if (!MODES.has(mode)) throw new Error(`progressively-enhance-web-components: <template id="${templateElement.id}"> asks for mode ${JSON.stringify(mode)}, which is not one of ${[...MODES].join(', ')}`)
186
+ allTemplateElements[templateElement.id] = { definition: templateElement, mode }
187
+ }
188
+ }
189
+ })
190
+
191
+ // what one invocation of a custom element becomes
192
+ function enhance (invocation, customElement) {
193
+ // make a dom just for modifying this element
194
+ const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')
195
+ const document = dom.window.document
196
+ document.body.appendChild(JSDOM.fragment(invocation))
197
+
198
+ // the element we're modifying
199
+ const element = document.body.firstChild
200
+ const { definition, mode } = allTemplateElements[customElement]
201
+
202
+ // an invocation that has been enhanced already is handed back exactly as it came in, rather than reformatted, so that nothing about it changes
203
+ if (alreadyEnhanced(element)) return invocation
204
+
205
+ // js-beautify treats <template> as an inline element and so will not break the line before one. the pieces of a component are put on lines of their own here instead, which it then indents. with beautifying turned off they are joined as they were, this module having been asked to leave the markup alone
206
+ const gap = params?.disableBeautify ? '' : '\n'
207
+
208
+ // the component's markup, with the attribute values written on this invocation put where its template literals were
209
+ //
210
+ // a shadow root renders the style, script and slot elements it is given, so it keeps them. light dom fallback markup can use none of them: a style element would leak to the rest of the page, a slot projects nothing when there is no shadow root to project it into, and a script would run a second time once the component upgrades. so they are removed from a fallback
211
+ function componentMarkup (forShadowRoot) {
212
+ // clone the <template> markup so we can construct a more verbose, progressive enhancement-compatible version of the web component
213
+ const template = definition.content.cloneNode(true)
214
+
215
+ // remove elements that are not needed in the progressive enhancement context from the <template> markup
216
+ if (!forShadowRoot) template.querySelectorAll('style, script, slot').forEach(el => el.remove())
217
+
218
+ // replace template literals with attribute values in the <template> markup
219
+ const container = document.createElement('div')
220
+ container.appendChild(template)
221
+ for (const attrib of element.attributes) container.innerHTML = container.innerHTML.replace(new RegExp(`\\$\\{${attrib.name}\\}`, 'gi'), attrib.value)
222
+ if (!params?.disableBeautify) {
223
+ const componentBeautifyOptions = { ...beautifyOptions }
224
+ componentBeautifyOptions.preserve_newlines = false // remove newlines from components in case any style, script, or slot elements have been removed
225
+ container.innerHTML = beautify(container.innerHTML, componentBeautifyOptions)
55
226
  }
227
+ return container
228
+ }
229
+
230
+ if (mode === 'light') {
231
+ const fallback = componentMarkup(false)
232
+
233
+ // 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
234
+ element.querySelectorAll('[slot]').forEach(slot => fallback.appendChild(slot.cloneNode(true)))
235
+
236
+ // replace the original custom element with the new progressive enhancement-friendly version of the element
237
+ element.innerHTML = beautifyMarkup(fallback.innerHTML)
238
+ element.setAttribute(ENHANCED_ATTRIBUTE, '')
239
+ return bareEnhancedAttribute(beautifyMarkup(document.body.innerHTML))
56
240
  }
241
+
242
+ // the other modes build a shadow root, and what the element already holds is the light dom the slots in that shadow root project, so it is kept as it was written rather than replaced
243
+ //
244
+ // nothing is hoisted out of it either: only a direct child of the element can be assigned to a slot, so moving one that is nested deeper would change which content the author had put where in order to make a slot claim it
245
+ const light = element.innerHTML
246
+ const pieces = [`<template shadowrootmode="open">${componentMarkup(true).innerHTML}</template>`]
247
+
248
+ // `both` carries the fallback as well, held out of the component's slots so that it shows only where the shadow root was not built
249
+ if (mode === 'both') {
250
+ const fallback = componentMarkup(false)
251
+ holdOutOfSlots(fallback)
252
+ pieces.push(fallback.innerHTML)
253
+ }
254
+
255
+ if (light.trim()) pieces.push(light)
256
+ element.innerHTML = gap + beautifyMarkup(pieces.join(gap))
257
+ element.setAttribute(ENHANCED_ATTRIBUTE, '')
258
+ return bareEnhancedAttribute(beautifyMarkup(document.body.innerHTML))
57
259
  }
58
260
 
59
261
  // find all invocations of each of the custom elements that are in allTemplateElements
60
- const allFiles = {}
61
262
  const editedFiles = {}
62
- for (const customElement in allTemplateElements) { // loop through list of known custom elements
63
- for (const templateFile of templateFiles) { // loop through all template files to search for invocations of this custom element
64
- const templateCode = fs.readFileSync(templateFile, 'utf8')
65
- if (!allFiles[templateFile]) allFiles[templateFile] = templateCode
66
- if (!isBinaryFile(templateFile)) {
263
+ withoutJsdomCssComplaints(() => {
264
+ for (const file in files) {
265
+ const original = files[file]
266
+ let markup = original
267
+ for (const customElement in allTemplateElements) { // loop through list of known custom elements
67
268
  // replace all invocations of this custom element with the progressive enhancement-friendly version
68
- const newTemplateCode = templateCode.replace(new RegExp(`<${customElement}\\b[^>]*>(.*?)<\\/${customElement}>`, 'gs'), (match, content) => {
69
- // make a dom just for modifying this element
70
- const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')
71
- const document = dom.window.document
72
- const fragment = JSDOM.fragment(match)
73
- document.body.appendChild(fragment)
74
-
75
- // the element we're modifying
76
- const element = document.body.firstChild
77
-
78
- // clone the <template> markup so we can construct a more verbose, progressive enhancement-compatible version of the web component
79
- const template = allTemplateElements[customElement].content.cloneNode(true)
80
-
81
- // remove elements that are not needed in the progressive enhancement context from the <template> markup
82
- template.querySelectorAll('style, script, slot').forEach(el => el.remove())
83
-
84
- // replace template literals with attribute values in the <template> markup
85
- const container = document.createElement('div')
86
- container.appendChild(template)
87
- for (const attrib of element.attributes) container.innerHTML = container.innerHTML.replace(new RegExp(`\\$\\{${attrib.name}\\}`, 'gi'), attrib.value)
88
- const componentBeautifyOptions = { ...beautifyOptions }
89
- componentBeautifyOptions.preserve_newlines = false // remove newlines from components in case any style, script, or slot elements have been removed
90
- container.innerHTML = beautify(container.innerHTML, componentBeautifyOptions)
91
-
92
- // 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
93
- element.querySelectorAll('[slot]').forEach(slot => container.appendChild(slot.cloneNode(true)))
94
-
95
- // replace the original custom element with the new progressive enhancement-friendly version of the element
96
- element.innerHTML = params?.disableBeautify ? container.innerHTML : beautify(container.innerHTML, beautifyOptions)
97
- let newCode = document.body.innerHTML
98
- newCode = params?.disableBeautify ? newCode : beautify(newCode, beautifyOptions)
99
- return newCode
100
- })
101
- if (templateCode !== newTemplateCode) {
102
- allFiles[templateFile] = newTemplateCode
103
- editedFiles[templateFile] = newTemplateCode
269
+ //
270
+ // the spans are rewritten back to front so that replacing one does not move the next
271
+ for (const span of elementSpans(markup, customElement).reverse()) {
272
+ markup = markup.slice(0, span.start) + enhance(markup.slice(span.start, span.end), customElement) + markup.slice(span.end)
104
273
  }
105
274
  }
275
+ if (markup !== original) editedFiles[file] = markup
106
276
  }
107
- }
277
+ })
108
278
 
109
279
  return editedFiles
110
280
  }
@@ -1,18 +0,0 @@
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/renovate.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": [
3
- "config:base",
4
- ":preserveSemverRanges",
5
- ":ignoreUnstable",
6
- ":respectLatest",
7
- ":disableDependencyDashboard"
8
- ]
9
- }
@@ -1,23 +0,0 @@
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
@@ -1,17 +0,0 @@
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
- }
@@ -1,5 +0,0 @@
1
- <include src="layouts/main">
2
- <arg pageContent>
3
- <p>hello world</p>
4
- </arg>
5
- </include>
@@ -1,49 +0,0 @@
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="${elId}" id="${elId}">${text}</textarea>
43
- <slot name="description"></slot>
44
- <span class="word-count"></span>
45
- </div>
46
- </template>
47
- </noparse>
48
- </body>
49
- </html>
@@ -1,21 +0,0 @@
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... " elId="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>
@@ -1,5 +0,0 @@
1
- <include src="layouts/main">
2
- <arg pageContent>
3
- <p>this is a second page and prints a {variable}</p>
4
- </arg>
5
- </include>