Skip to content

Commit

Permalink
Merge pull request #996 from GSA/984-modal-styles-build
Browse files Browse the repository at this point in the history
PXBF-984-modal-styles-build: build modal styles as custom group
  • Loading branch information
scottqueen-bixal authored Mar 5, 2024
2 parents a547b76 + 06b433b commit 922504c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
28 changes: 25 additions & 3 deletions benefit-finder/vite-config/transformers/wrapStyles/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { writeFileSync } from 'fs'

export default function wrapStyles(options) {
const { id } = options
const { id, customGroup } = options
let trimmedCSS

return {
name: 'wrap-css',
Expand All @@ -13,10 +14,31 @@ export default function wrapStyles(options) {
const cssContent = bundle[fileName].source

// Remove charset
const trimmedCSS = cssContent.replace(/^@charset "UTF-8";/, '')
trimmedCSS = cssContent.replace(/^@charset "UTF-8";/, '')
// Capture modal ID selectors
// because our modal appends to the DOM outside of our #ID,
// we need to ensure it doesn't get wrapped during the build
// regex patterns
const customGroupIDPattern = `(${customGroup})`
const customGroupPattern = `${customGroupIDPattern}.*?(})`
const customGroupRegExp = new RegExp(customGroupPattern, 'g')
const customGroupIDRegExp = new RegExp(customGroupIDPattern, 'g')
// find matches for selectors
const customGroupMatch = trimmedCSS.match(customGroupRegExp)
// remove matches from bundle
trimmedCSS = trimmedCSS.replace(customGroupMatch.join(''), '')

// trim custom group styles so we can wrap later
const customGroupStyles =
customGroupMatch &&
customGroupMatch
.map(selector => {
return selector.replace(customGroupIDRegExp, '')
})
.join('')

// Wrap the CSS content with the provided ID and charset
const wrappedCssContent = `@charset "UTF-8"; #${id} { ${trimmedCSS} }`
const wrappedCssContent = `@charset "UTF-8"; #${id} {${trimmedCSS}} ${customGroup} {${customGroupStyles}}`

// Write the wrapped CSS content back to the file
try {
Expand Down
1 change: 1 addition & 0 deletions benefit-finder/vite.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export default defineConfig({
plugins: [
transformers.wrapStyles({
id: 'benefit-finder',
customGroup: '#benefit-finder-modal',
}),
],
},
Expand Down

0 comments on commit 922504c

Please sign in to comment.