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.
@@ -1,113 +1,476 @@
1
1
  const fs = require('fs')
2
2
  const path = require('path')
3
- const { JSDOM } = require('jsdom')
3
+ const { JSDOM, VirtualConsole } = require('jsdom')
4
4
  const beautify = require('js-beautify').html
5
5
 
6
- function loopThroughFilesSync (dir) {
7
- let fileList = []
8
- let files
6
+ const MODULE_NAME = 'progressively-enhance-web-components'
7
+
8
+ // every file under a directory, in an order that is the same on every platform
9
+ //
10
+ // the order matters: when two templates share an id the later one wins, and readdir hands entries back in whatever order the filesystem keeps them. hidden files and hidden directories are both skipped, so a .git or a .preprocessed_views folder kept inside the templates directory is not read as templates. symbolic links are followed, and a directory reached a second time through one is not walked again, so a link pointing back up the tree cannot loop forever
11
+ function loopThroughFilesSync (dir, visited = new Set()) {
12
+ let realDir
13
+ let entries
9
14
  try {
10
- files = fs.readdirSync(dir, { withFileTypes: true })
11
- } catch (err) {
12
- return fileList
13
- }
14
- files.forEach(file => {
15
- const filePath = path.join(dir, file.name)
16
- if (file.isDirectory()) fileList = fileList.concat(loopThroughFilesSync(filePath)) // recurse dirs
17
- else if (file.isFile() && !file.name.startsWith('.')) fileList.push(filePath) // exclude hidden files
18
- })
15
+ realDir = fs.realpathSync(dir)
16
+ entries = fs.readdirSync(dir, { withFileTypes: true })
17
+ } catch {
18
+ return []
19
+ }
20
+ if (visited.has(realDir)) return []
21
+ visited.add(realDir)
22
+ const fileList = []
23
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
24
+ for (const entry of entries) {
25
+ if (entry.name.startsWith('.')) continue
26
+ const entryPath = path.join(dir, entry.name)
27
+ let kind = entry
28
+ if (entry.isSymbolicLink()) {
29
+ try {
30
+ kind = fs.statSync(entryPath)
31
+ } catch {
32
+ continue // a link to nothing
33
+ }
34
+ }
35
+ if (kind.isDirectory()) fileList.push(...loopThroughFilesSync(entryPath, visited))
36
+ else if (kind.isFile()) fileList.push(entryPath)
37
+ }
19
38
  return fileList
20
39
  }
21
40
 
22
- function isBinaryFile (filePath, bytesToCheck = 512) {
23
- const buffer = Buffer.alloc(bytesToCheck)
24
- const fd = fs.openSync(filePath, 'r')
25
- const bytesRead = fs.readSync(fd, buffer, 0, bytesToCheck, 0)
26
- fs.closeSync(fd)
27
- for (let i = 0; i < bytesRead; i++) {
28
- const byte = buffer[i]
29
- if (byte === 0) return true // null byte found, likely a binary file
30
- 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)
41
+ // the contents of a file, or null when it is not text this module should read
42
+ //
43
+ // a null byte near the start is the usual sign of a binary file, and checking only the start means a large image or video is not read in full just to be thrown away. anything else is read as utf-8 and rejected if it is not valid utf-8. testing each byte for printable ascii, as this once did, rejected every template holding an accented letter, a curly quote or an emoji, and so silently enhanced nothing in them
44
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
45
+ function readTextFile (filePath, bytesToCheck = 8000) {
46
+ try {
47
+ const fd = fs.openSync(filePath, 'r')
48
+ try {
49
+ const head = Buffer.alloc(bytesToCheck)
50
+ const bytesRead = fs.readSync(fd, head, 0, bytesToCheck, 0)
51
+ if (head.subarray(0, bytesRead).includes(0)) return null
52
+ } finally {
53
+ fs.closeSync(fd)
54
+ }
55
+ return utf8.decode(fs.readFileSync(filePath))
56
+ } catch {
57
+ return null
58
+ }
59
+ }
60
+
61
+ // lower case the ascii letters and nothing else
62
+ //
63
+ // tag names are matched case insensitively by searching a lower cased copy of the markup and using the positions found in it on the original. String.prototype.toLowerCase cannot be used for that: a few characters lower case to more than one code unit, İ becoming i̇ for one, and every position after such a character would then point at the wrong place in the original
64
+ const asciiLowerCase = text => text.replace(/[A-Z]+/g, letters => letters.toLowerCase())
65
+
66
+ // whether the character after a tag name ends it, so that <my-thing> is not mistaken for <my-thing-two>
67
+ const endsTagName = character => /[\s/>]/.test(character || '')
68
+
69
+ // where the opening tag that begins at `from` ends
70
+ //
71
+ // quotes are followed so that a greater than sign inside an attribute value does not look like the end of the tag. a quote only opens a value straight after an equals sign, as it does for the html parser, so an apostrophe in a bare attribute such as <my-thing don't> does not swallow the rest of the file
72
+ function endOfOpeningTag (markup, from) {
73
+ let quote = null
74
+ let valueMayStart = false
75
+ for (let i = from + 1; i < markup.length; i++) {
76
+ const character = markup[i]
77
+ if (quote) {
78
+ if (character === quote) quote = null
79
+ } else if (valueMayStart && (character === '"' || character === "'")) {
80
+ quote = character
81
+ valueMayStart = false
82
+ } else if (character === '>') return i
83
+ else if (character === '=') valueMayStart = true
84
+ else if (!/\s/.test(character)) valueMayStart = false
85
+ }
86
+ return -1
87
+ }
88
+
89
+ // elements whose contents the html parser reads as text rather than as markup, so that a tag written inside one is not a tag at all
90
+ const RAW_TEXT_ELEMENTS = new Set(['script', 'style', 'textarea', 'title', 'xmp', 'iframe', 'noembed', 'noframes'])
91
+
92
+ // the stretches of markup in which a custom element written there is not one this module should enhance
93
+ //
94
+ // those are comments, the contents of the raw text elements above, and <template> elements other than declarative shadow roots. a comment and a raw text element do not render what is written in them as elements at all: expanding an invocation written inside a <script> string broke the script by writing double quotes into it. a plain <template> is not rendered either, and one that defines a component is cloned by the component's own javascript, so it has to stay as it was written. a declarative shadow root is rendered by the parser, so a custom element inside one is enhanced like any other
95
+ //
96
+ // each range is [start, end), sorted and not overlapping
97
+ function ignoredRanges (markup, lowerMarkup) {
98
+ const ranges = []
99
+ let templateDepth = 0
100
+ let templateStart = -1
101
+ let at = 0
102
+ while (true) {
103
+ const lessThan = lowerMarkup.indexOf('<', at)
104
+ if (lessThan === -1) break
105
+ if (lowerMarkup.startsWith('<!--', lessThan)) {
106
+ const commentEnd = lowerMarkup.indexOf('-->', lessThan + 4)
107
+ const end = commentEnd === -1 ? markup.length : commentEnd + 3
108
+ if (!templateDepth) ranges.push([lessThan, end])
109
+ at = end
110
+ continue
111
+ }
112
+ const tag = /^<(\/?)([a-z][^\s/>]*)/.exec(lowerMarkup.slice(lessThan, lessThan + 256))
113
+ if (!tag) {
114
+ at = lessThan + 1
115
+ continue
116
+ }
117
+ const [, closing, name] = tag
118
+ if (closing) {
119
+ const end = lowerMarkup.indexOf('>', lessThan)
120
+ at = end === -1 ? markup.length : end + 1
121
+ if (name === 'template' && templateDepth && !--templateDepth) ranges.push([templateStart, at])
122
+ continue
123
+ }
124
+ const openingTagEnd = endOfOpeningTag(markup, lessThan)
125
+ if (openingTagEnd === -1) break
126
+ if (name === 'plaintext') { // nothing after it is markup, not even a closing tag
127
+ if (!templateDepth) ranges.push([lessThan, markup.length])
128
+ at = markup.length
129
+ } else if (RAW_TEXT_ELEMENTS.has(name)) {
130
+ let close = lowerMarkup.indexOf(`</${name}`, openingTagEnd)
131
+ while (close !== -1 && !endsTagName(lowerMarkup[close + name.length + 2])) close = lowerMarkup.indexOf(`</${name}`, close + 1)
132
+ const closeEnd = close === -1 ? -1 : lowerMarkup.indexOf('>', close)
133
+ const end = closeEnd === -1 ? markup.length : closeEnd + 1
134
+ if (!templateDepth) ranges.push([lessThan, end])
135
+ at = end
136
+ } else {
137
+ if (name === 'template') {
138
+ // inside a plain template every nested template is counted, a shadow root or not, so that the closing tags pair up
139
+ const isShadowRoot = /\sshadowrootmode\s*=/.test(lowerMarkup.slice(lessThan, openingTagEnd))
140
+ if (templateDepth) templateDepth++
141
+ else if (!isShadowRoot) {
142
+ templateDepth = 1
143
+ templateStart = lessThan
144
+ }
145
+ }
146
+ at = openingTagEnd + 1
147
+ }
148
+ }
149
+ if (templateDepth) ranges.push([templateStart, markup.length]) // a template never closed takes the rest of the file with it
150
+ return ranges
151
+ }
152
+
153
+ // the end of the ignored range holding `position`, or -1 when it is not in one
154
+ function endOfIgnoredRange (ranges, position) {
155
+ let low = 0
156
+ let high = ranges.length - 1
157
+ while (low <= high) {
158
+ const middle = (low + high) >> 1
159
+ const [start, end] = ranges[middle]
160
+ if (position < start) high = middle - 1
161
+ else if (position >= end) low = middle + 1
162
+ else return end
163
+ }
164
+ return -1
165
+ }
166
+
167
+ // where the next tag beginning with `opening` (such as `<my-thing` or `</my-thing`) is, skipping the ignored ranges and any longer name that only begins the same way
168
+ function findTag (lowerMarkup, ranges, opening, from) {
169
+ let at = from
170
+ while (true) {
171
+ const found = lowerMarkup.indexOf(opening, at)
172
+ if (found === -1) return -1
173
+ const ignoredUntil = endOfIgnoredRange(ranges, found)
174
+ if (ignoredUntil !== -1) at = ignoredUntil
175
+ else if (!endsTagName(lowerMarkup[found + opening.length])) at = found + opening.length
176
+ else return found
177
+ }
178
+ }
179
+
180
+ // the span of markup an element occupies, from the < that opens it to the > that closes it
181
+ //
182
+ // 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
183
+ function elementSpan (markup, lowerMarkup, ranges, name, start) {
184
+ const openingTagEnd = endOfOpeningTag(markup, start)
185
+ if (openingTagEnd === -1) return null
186
+ if (markup[openingTagEnd - 1] === '/') return { start, end: openingTagEnd + 1 } // closed itself, so there is no closing tag to pair it with
187
+ let depth = 1
188
+ let at = openingTagEnd + 1
189
+ while (true) {
190
+ const nextClosing = findTag(lowerMarkup, ranges, `</${name}`, at)
191
+ if (nextClosing === -1) return null // never closed
192
+ const nextOpening = findTag(lowerMarkup, ranges, `<${name}`, at)
193
+ if (nextOpening !== -1 && nextOpening < nextClosing) {
194
+ const nestedOpeningTagEnd = endOfOpeningTag(markup, nextOpening)
195
+ if (nestedOpeningTagEnd === -1) return null
196
+ if (markup[nestedOpeningTagEnd - 1] !== '/') depth++ // one that closed itself has no closing tag of its own to wait for
197
+ at = nestedOpeningTagEnd + 1
198
+ continue
199
+ }
200
+ const closingTagEnd = markup.indexOf('>', nextClosing)
201
+ if (closingTagEnd === -1) return null
202
+ if (--depth === 0) return { start, end: closingTagEnd + 1 }
203
+ at = closingTagEnd + 1
204
+ }
205
+ }
206
+
207
+ // where the next opening tag of any of these custom elements is, and which of them it opens
208
+ function nextInvocation (lowerMarkup, ranges, names, from) {
209
+ let at = from
210
+ while (true) {
211
+ const lessThan = lowerMarkup.indexOf('<', at)
212
+ if (lessThan === -1) return null
213
+ const ignoredUntil = endOfIgnoredRange(ranges, lessThan)
214
+ if (ignoredUntil !== -1) {
215
+ at = ignoredUntil
216
+ continue
217
+ }
218
+ const tag = /^<([a-z][^\s/>]*)/.exec(lowerMarkup.slice(lessThan, lessThan + 256))
219
+ if (tag && names.has(tag[1])) return { start: lessThan, name: tag[1] }
220
+ at = lessThan + 1
221
+ }
222
+ }
223
+
224
+ // whether a template id names a custom element, which is what makes it a component definition rather than any other use of a <template>
225
+ //
226
+ // without this a page holding <template id="header"> for some other script had every <header> on the site treated as an invocation of it. the rule is the one customElements.define enforces: it starts with a lower case ascii letter, holds a hyphen and no ascii upper case letters, and is not one of the hyphenated names svg and mathml already use
227
+ const POTENTIAL_CUSTOM_ELEMENT_NAME = /^[a-z][-.0-9_a-z·À-ÖØ-öø-ͽͿ-῿‌-‍‿-⁀⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\u{10000}-\u{EFFFF}]*$/u
228
+ const RESERVED_NAMES = new Set(['annotation-xml', 'color-profile', 'font-face', 'font-face-src', 'font-face-uri', 'font-face-format', 'font-face-name', 'missing-glyph'])
229
+ const isCustomElementName = name => name.includes('-') && POTENTIAL_CUSTOM_ELEMENT_NAME.test(name) && !RESERVED_NAMES.has(name)
230
+
231
+ // the ways an invocation can be enhanced
232
+ //
233
+ // `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
234
+ const MODES = new Set(['light', 'shadow', 'both'])
235
+
236
+ // 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
237
+ //
238
+ // 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
239
+ const ENHANCED_ATTRIBUTE = 'data-enhanced'
240
+
241
+ // 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
242
+ function alreadyEnhanced (element) {
243
+ if (element.hasAttribute(ENHANCED_ATTRIBUTE)) return true
244
+ for (const child of element.children) {
245
+ if (child.tagName === 'TEMPLATE' && child.hasAttribute('shadowrootmode')) return true
31
246
  }
32
247
  return false
33
248
  }
34
249
 
35
- // hack to get jsdom to shut up about invalid css
36
- const originalConsoleError = console.error
37
- const jsDomCssError = 'Error: Could not parse CSS stylesheet'
38
- console.error = (...params) => {
39
- if (!params.find(p => p.toString().includes(jsDomCssError))) {
40
- originalConsoleError(...params)
250
+ // the name of a slot no component defines, which is what keeps the fallback markup of `both` out of the component
251
+ //
252
+ // 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
253
+ const FALLBACK_SLOT = 'pewc-fallback'
254
+
255
+ // marks every top level node of the fallback markup as belonging to that slot
256
+ function holdOutOfSlots (container) {
257
+ for (const node of [...container.childNodes]) {
258
+ if (node.nodeType === 1) node.setAttribute('slot', FALLBACK_SLOT) // an element can carry the attribute itself
259
+ else if (node.nodeType === 3 && node.textContent.trim()) { // text cannot, so it is given something that can
260
+ const wrapper = container.ownerDocument.createElement('span')
261
+ node.replaceWith(wrapper)
262
+ wrapper.setAttribute('slot', FALLBACK_SLOT)
263
+ wrapper.appendChild(node)
264
+ }
265
+ }
266
+ }
267
+
268
+ // puts the attribute values of an invocation where the ${templateLiterals} of its definition are
269
+ //
270
+ // this works on the dom rather than on serialized markup. replacing text in serialized markup wrote each value in exactly as it was, so a value holding a quote or an angle bracket broke the attribute or the element it landed in, and the value having been decoded from its entities on the way in meant &lt;b&gt; arrived as a real <b>. setting the text of a node lets the serializer escape it for wherever it ended up. it also means each literal is looked up once by name, rather than every attribute name being made into a regular expression, which a name such as a.b or :value is not safe to be, and rather than every value being a replacement pattern, in which $& and $1 mean something
271
+ const TEMPLATE_LITERAL = /\$\{([^}]+)\}/g
272
+ function fillTemplateLiterals (node, values) {
273
+ const fill = text => text.replace(TEMPLATE_LITERAL, (literal, name) => values.get(name.toLowerCase()) ?? literal)
274
+ for (const child of node.childNodes) {
275
+ if (child.nodeType === 1) {
276
+ for (const attribute of child.attributes) attribute.value = fill(attribute.value)
277
+ if (child.tagName === 'TEMPLATE') fillTemplateLiterals(child.content, values)
278
+ fillTemplateLiterals(child, values)
279
+ } else if (child.nodeType === 3 || child.nodeType === 8) child.data = fill(child.data) // text and comments
41
280
  }
42
281
  }
43
282
 
44
283
  module.exports = (params) => {
45
- const beautifyOptions = params?.beautifyOptions || {
284
+ if (!params || typeof params.templatesDir !== 'string') throw new TypeError(`${MODULE_NAME}: the templatesDir param is required, and must be the path to the folder holding your templates`)
285
+
286
+ const beautifyOptions = params.beautifyOptions || {
46
287
  indent_size: 2
47
288
  }
289
+ const beautifyMarkup = markup => params.disableBeautify ? markup : beautify(markup, beautifyOptions)
290
+
291
+ // 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
292
+ //
293
+ // only the opening tag of the element just enhanced is touched, so that an attribute written that way somewhere inside it, or text that happens to read the same, is left as it was
294
+ const bareEnhancedAttribute = markup => {
295
+ const start = markup.indexOf('<')
296
+ const end = start === -1 ? -1 : endOfOpeningTag(markup, start)
297
+ if (end === -1) return markup
298
+ return markup.slice(0, start) + markup.slice(start, end + 1).replace(new RegExp(`(\\s)${ENHANCED_ATTRIBUTE}=""`), `$1${ENHANCED_ATTRIBUTE}`) + markup.slice(end + 1)
299
+ }
300
+
301
+ // what to do with an invocation whose definition does not say for itself
302
+ const defaultMode = params.mode || 'both'
303
+ if (!MODES.has(defaultMode)) throw new Error(`${MODULE_NAME}: mode must be one of ${[...MODES].join(', ')}, not ${JSON.stringify(defaultMode)}`)
304
+
305
+ // jsdom complains about css it cannot parse, which is not something the caller can do anything about
306
+ //
307
+ // the complaints are dropped by giving jsdom a console of its own rather than by replacing console.error, which belongs to whatever application is calling this. anything else jsdom has to say is still passed on
308
+ const virtualConsole = new VirtualConsole()
309
+ virtualConsole.on('jsdomError', error => {
310
+ if (error.type !== 'css-parsing') console.error(error.message)
311
+ })
48
312
 
49
- // find all <template> elements with ids that are defined in any of the html templates
50
- const templateFiles = loopThroughFilesSync(params.templatesDir)
313
+ // every file that could hold a template or an invocation of one, read once
314
+ //
315
+ // 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
316
+ const files = {}
317
+ for (const file of loopThroughFilesSync(params.templatesDir)) {
318
+ const contents = readTextFile(file)
319
+ if (contents !== null) files[file] = contents
320
+ }
321
+
322
+ // find all <template> elements whose ids name a custom element in any of the html templates
323
+ //
324
+ // a file without the word <template in it cannot define anything, so it is not handed to jsdom at all, which spares parsing every stylesheet, script and partial in the folder as a document
51
325
  const allTemplateElements = {}
52
- for (const templateFile of templateFiles) {
53
- if (!isBinaryFile(templateFile)) {
54
- const dom = new JSDOM(fs.readFileSync(templateFile, 'utf8'))
55
- const document = dom.window.document
56
- const allElements = document.querySelectorAll('*')
57
- const templateElements = Array.from(allElements).filter(element => element.tagName === 'TEMPLATE')
58
- for (const templateElement of templateElements) {
59
- if (templateElement.id) allTemplateElements[templateElement.id] = templateElement
326
+ for (const [file, contents] of Object.entries(files)) {
327
+ if (!asciiLowerCase(contents).includes('<template')) continue
328
+ const { document } = new JSDOM(contents, { virtualConsole }).window
329
+ for (const templateElement of document.querySelectorAll('template')) {
330
+ const id = templateElement.id
331
+ if (!isCustomElementName(id)) continue
332
+ // 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
333
+ const mode = templateElement.getAttribute('mode') || defaultMode
334
+ if (!MODES.has(mode)) throw new Error(`${MODULE_NAME}: <template id="${id}"> asks for mode ${JSON.stringify(mode)}, which is not one of ${[...MODES].join(', ')}`)
335
+ const previous = allTemplateElements[id]
336
+ if (previous) console.warn(`${MODULE_NAME}: <template id="${id}"> is defined more than once, in ${previous.file} and in ${file}. the one in ${file} is used`)
337
+ allTemplateElements[id] = { definition: templateElement, mode, file }
338
+ }
339
+ }
340
+ const customElementNames = new Set(Object.keys(allTemplateElements))
341
+
342
+ // one document to parse every invocation in, rather than a new one for each
343
+ //
344
+ // it is only used to parse: an element is taken out of it straight away and serialized from where it is, so that enhancing the invocations nested inside one, which parses each of them here in turn, does not disturb it
345
+ const workspace = new JSDOM('<!DOCTYPE html><html><body></body></html>', { virtualConsole }).window.document
346
+
347
+ // every invocation of a known custom element in a stretch of markup, enhanced, with everything around them left as it was
348
+ //
349
+ // `expanding` is the chain of components whose markup this is part of. a component that invokes itself, directly or through another, would expand forever, so an invocation of one already in the chain is left for its javascript to render, marked so that a later pass over the output leaves it alone too
350
+ const warnedAboutRecursion = new Set()
351
+ function enhanceMarkup (markup, expanding) {
352
+ const lowerMarkup = asciiLowerCase(markup)
353
+ const ranges = ignoredRanges(markup, lowerMarkup)
354
+ let output = ''
355
+ let at = 0
356
+ while (true) {
357
+ const found = nextInvocation(lowerMarkup, ranges, customElementNames, at)
358
+ if (!found) break
359
+ const span = elementSpan(markup, lowerMarkup, ranges, found.name, found.start)
360
+ if (!span) { // never closed, which leaves that one alone but not every invocation after it
361
+ output += markup.slice(at, found.start + 1)
362
+ at = found.start + 1
363
+ continue
60
364
  }
365
+ output += markup.slice(at, span.start) + enhance(markup.slice(span.start, span.end), found.name, expanding)
366
+ at = span.end // whatever is nested inside this element is dealt with by enhancing it
61
367
  }
368
+ return output + markup.slice(at)
62
369
  }
63
370
 
64
- // find all invocations of each of the custom elements that are in allTemplateElements
65
- const allFiles = {}
66
- const editedFiles = {}
67
- for (const customElement in allTemplateElements) { // loop through list of known custom elements
68
- for (const templateFile of templateFiles) { // loop through all template files to search for invocations of this custom element
69
- const templateCode = fs.readFileSync(templateFile, 'utf8')
70
- if (!allFiles[templateFile]) allFiles[templateFile] = templateCode
71
- if (!isBinaryFile(templateFile)) {
72
- // replace all invocations of this custom element with the progressive enhancement-friendly version
73
- const newTemplateCode = templateCode.replace(new RegExp(`<${customElement}\\b[^>]*>(.*?)<\\/${customElement}>`, 'gs'), (match, content) => {
74
- // make a dom just for modifying this element
75
- const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')
76
- const document = dom.window.document
77
- const fragment = JSDOM.fragment(match)
78
- document.body.appendChild(fragment)
79
-
80
- // the element we're modifying
81
- const element = document.body.firstChild
82
-
83
- // clone the <template> markup so we can construct a more verbose, progressive enhancement-compatible version of the web component
84
- const template = allTemplateElements[customElement].content.cloneNode(true)
85
-
86
- // remove elements that are not needed in the progressive enhancement context from the <template> markup
87
- template.querySelectorAll('style, script, slot').forEach(el => el.remove())
88
-
89
- // replace template literals with attribute values in the <template> markup
90
- const container = document.createElement('div')
91
- container.appendChild(template)
92
- for (const attrib of element.attributes) container.innerHTML = container.innerHTML.replace(new RegExp(`\\$\\{${attrib.name}\\}`, 'gi'), attrib.value)
93
- const componentBeautifyOptions = { ...beautifyOptions }
94
- componentBeautifyOptions.preserve_newlines = false // remove newlines from components in case any style, script, or slot elements have been removed
95
- container.innerHTML = beautify(container.innerHTML, componentBeautifyOptions)
96
-
97
- // 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
98
- element.querySelectorAll('[slot]').forEach(slot => container.appendChild(slot.cloneNode(true)))
99
-
100
- // replace the original custom element with the new progressive enhancement-friendly version of the element
101
- element.innerHTML = params?.disableBeautify ? container.innerHTML : beautify(container.innerHTML, beautifyOptions)
102
- let newCode = document.body.innerHTML
103
- newCode = params?.disableBeautify ? newCode : beautify(newCode, beautifyOptions)
104
- return newCode
105
- })
106
- if (templateCode !== newTemplateCode) {
107
- allFiles[templateFile] = newTemplateCode
108
- editedFiles[templateFile] = newTemplateCode
371
+ // what one invocation of a custom element becomes
372
+ function enhance (invocation, customElement, expanding) {
373
+ if (expanding.includes(customElement)) {
374
+ if (!warnedAboutRecursion.has(customElement)) {
375
+ warnedAboutRecursion.add(customElement)
376
+ console.warn(`${MODULE_NAME}: <${customElement}> invokes itself (${[...expanding.slice(expanding.indexOf(customElement)), customElement].join(' > ')}). the inner one is left for its javascript to render`)
377
+ }
378
+ const nameEnd = customElement.length + 1
379
+ return invocation.slice(0, nameEnd) + ` ${ENHANCED_ATTRIBUTE}` + invocation.slice(nameEnd)
380
+ }
381
+
382
+ workspace.body.innerHTML = invocation
383
+ const element = workspace.body.firstElementChild
384
+ if (!element) return invocation
385
+ element.remove()
386
+
387
+ // an invocation that has been enhanced already is kept exactly as it came in, rather than reformatted, so that nothing about it changes. it can still hold invocations that have not been, in its light dom or in a shadow root written into it, and only those are enhanced
388
+ if (alreadyEnhanced(element)) {
389
+ const openingTagEnd = endOfOpeningTag(invocation, 0)
390
+ if (invocation[openingTagEnd - 1] === '/') return invocation
391
+ const closingTagStart = invocation.lastIndexOf('</')
392
+ return invocation.slice(0, openingTagEnd + 1) + enhanceMarkup(invocation.slice(openingTagEnd + 1, closingTagStart), expanding) + invocation.slice(closingTagStart)
393
+ }
394
+
395
+ const { definition, mode } = allTemplateElements[customElement]
396
+
397
+ // 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
398
+ const gap = params.disableBeautify ? '' : '\n'
399
+
400
+ const values = new Map()
401
+ for (const attribute of element.attributes) values.set(attribute.name.toLowerCase(), attribute.value)
402
+
403
+ // the component's markup, with the attribute values written on this invocation put where its template literals were, and any component it invokes enhanced in turn
404
+ //
405
+ // 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
406
+ //
407
+ // what comes back is markup rather than a dom. the enhanced invocations nested in it are serialized already, and parsing them again only to serialize them a second time would undo details such as the bare data-enhanced attribute
408
+ function componentMarkup (forShadowRoot) {
409
+ // clone the <template> markup so we can construct a more verbose, progressive enhancement-compatible version of the web component
410
+ const template = definition.content.cloneNode(true)
411
+
412
+ // remove elements that are not needed in the progressive enhancement context from the <template> markup
413
+ if (!forShadowRoot) template.querySelectorAll('style, script, slot').forEach(el => el.remove())
414
+
415
+ const container = workspace.createElement('div')
416
+ container.appendChild(template)
417
+ fillTemplateLiterals(container, values)
418
+
419
+ // `both` carries the fallback beside the shadow root, held out of the component's slots so that it shows only where the shadow root was not built
420
+ if (!forShadowRoot && mode === 'both') holdOutOfSlots(container)
421
+
422
+ const markup = enhanceMarkup(container.innerHTML, [...expanding, customElement])
423
+ if (params.disableBeautify) return markup
424
+ const componentBeautifyOptions = { ...beautifyOptions }
425
+ componentBeautifyOptions.preserve_newlines = false // remove newlines from components in case any style, script, or slot elements have been removed
426
+ return beautify(markup, componentBeautifyOptions)
427
+ }
428
+
429
+ // the element with what it now holds, written out around that markup rather than by setting it as the element's contents and serializing the lot, for the same reason
430
+ element.setAttribute(ENHANCED_ATTRIBUTE, '')
431
+ const shell = element.cloneNode(false).outerHTML
432
+ const closingTag = `</${element.localName}>`
433
+ const openingTag = shell.slice(0, shell.length - closingTag.length)
434
+ const wrap = contents => bareEnhancedAttribute(beautifyMarkup(openingTag + contents + closingTag))
435
+
436
+ if (mode === 'light') {
437
+ let fallback = componentMarkup(false)
438
+
439
+ // move any component child elements with slot attributes 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
440
+ //
441
+ // one that belongs to something else is left where it is: a child of an element already being moved goes along with it rather than being moved a second time beside it, and one inside another custom element is that element's slotted content, not this one's
442
+ const belongsToThisElement = slotted => {
443
+ for (let ancestor = slotted.parentElement; ancestor !== element; ancestor = ancestor.parentElement) {
444
+ if (ancestor.hasAttribute('slot') || ancestor.localName.includes('-')) return false
109
445
  }
446
+ return true
110
447
  }
448
+ for (const slotted of element.querySelectorAll('[slot]')) {
449
+ if (belongsToThisElement(slotted)) fallback += enhanceMarkup(slotted.outerHTML, expanding)
450
+ }
451
+
452
+ // replace the original custom element with the new progressive enhancement-friendly version of the element
453
+ return wrap(beautifyMarkup(fallback))
454
+ }
455
+
456
+ // 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
457
+ //
458
+ // 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. any component invoked in it is enhanced, that being written by the author rather than by this component, so it is not part of the chain being expanded
459
+ const light = enhanceMarkup(element.innerHTML, expanding)
460
+ const pieces = [`<template shadowrootmode="open">${componentMarkup(true)}</template>`]
461
+ if (mode === 'both') pieces.push(componentMarkup(false))
462
+ if (light.trim()) pieces.push(light)
463
+ return wrap(gap + beautifyMarkup(pieces.join(gap)))
464
+ }
465
+
466
+ // enhance every invocation in every file, each file being gone over once for all of the custom elements together
467
+ //
468
+ // a component whose markup invokes another component has that one enhanced as part of it, whichever of the two was defined first. going over a file once for each custom element in turn, as this once did, only reached the inner one when its turn happened to come after the outer one's
469
+ const editedFiles = {}
470
+ if (customElementNames.size) {
471
+ for (const file in files) {
472
+ const markup = enhanceMarkup(files[file], [])
473
+ if (markup !== files[file]) editedFiles[file] = markup
111
474
  }
112
475
  }
113
476
 
@@ -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
- }