Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(build): added source maps generation for css v-bind fix plugin #3302

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 118 additions & 1 deletion packages/ui/build/plugins/component-v-bind-fix.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { describe, test, expect } from 'vitest'
import { transformVueComponent } from './component-v-bind-fix'
import { transformVueComponent as o } from './component-v-bind-fix'

const transformVueComponent = (code: string) => {
if (!code) { return undefined }
return o(code)?.code
}

describe('component-v-bind-fix', () => {
describe('transformVueComponent', () => {
Expand Down Expand Up @@ -229,4 +234,116 @@ const background = 'yellow'

expect(transformVueComponent(componentCode())).toBe(expectedComponentCode())
})

test('transform multiple nodes', () => {
const componentCode = (attrs = '', nestedAttrs = '') => `
<template>
<button>
<span>
Hello
</span>
world!
</button>
<div>
Label
</div>
</template>

<script setup>
const theme = {
color: 'blue',
background: 'yellow',
}
</script>

<style>
button {
color: v-bind('theme.color');
background: v-bind("theme.background");
}
</style>
`

const expectedComponentCode = () => `
<template>
<button :style="\`--va-0-theme-color: \${String(theme.color)};--va-1-theme-background: \${String(theme.background)}\`">
<span>
Hello
</span>
world!
</button>
<div :style="\`--va-0-theme-color: \${String(theme.color)};--va-1-theme-background: \${String(theme.background)}\`">
Label
</div>
</template>

<script setup>
const theme = {
color: 'blue',
background: 'yellow',
}
</script>

<style>
button {
color: var(--va-0-theme-color);
background: var(--va-1-theme-background);
}
</style>
`

expect(transformVueComponent(componentCode())).toBe(expectedComponentCode())
})

test('transform multiple v-bind the same variable', () => {
const componentCode = (attrs = '', nestedAttrs = '') => `
<template>
<button>
<span>
Hello
</span>
world!
</button>
</template>

<script setup>
const theme = {
color: 'blue',
}
</script>

<style>
button {
color: v-bind('theme.color');
fill: v-bind("theme.color");
}
</style>
`

const expectedComponentCode = () => `
<template>
<button :style="\`--va-0-theme-color: \${String(theme.color)}\`">
<span>
Hello
</span>
world!
</button>
</template>

<script setup>
const theme = {
color: 'blue',
}
</script>

<style>
button {
color: var(--va-0-theme-color);
fill: var(--va-0-theme-color);
}
</style>
`

expect(transformVueComponent(componentCode())).toBe(expectedComponentCode())
})
})
92 changes: 62 additions & 30 deletions packages/ui/build/plugins/component-v-bind-fix.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Plugin } from 'vite'
import kebabCase from 'lodash/kebabCase'
import { parse } from 'vue/compiler-sfc'
import { type SFCParseResult, parse } from 'vue/compiler-sfc'
import MagicString from 'magic-string'

/**
* Parse css and extract all variable names used in `v-bind`
Expand All @@ -16,8 +17,24 @@ import { parse } from 'vue/compiler-sfc'
*
* Returns`['colorComputed', 'getBg()']`
*/
const parseCssVBindCode = (style: string) => {
return parse(style).descriptor.cssVars
const getVBinds = (sfc: SFCParseResult) => {
return sfc.descriptor.cssVars
}

/** Returns start and end indexes of v-bind used in style */
const getStyleVBindLocs = (source: string, vBind: string) => {
// Regex for v-bind(color), v-bind('color'), v-bind("color")
const regex = new RegExp(`v-bind\\(['|"]?${vBind}['|"]?\\)`, 'gm')
const indexes = [] as { start: number, end: number }[]
let match

// The same variable can be used multiple times vBind in css
// replace all of them until there are no more matches
while ((match = regex.exec(source)) !== null) {
indexes.push({ start: match.index, end: match.index + match[0].length })
}

return indexes
}

/**
Expand All @@ -30,12 +47,23 @@ const parseCssVBindCode = (style: string) => {
* </va-button>
* </template>
* ```
* Returns `<va-button>`
* Returns loc for `<va-button>`
*/
const getRootNodeOpenTagCode = (code: string) => {
const template = code.match(/<template[^>]*>([\s\S]*)<\/template>/)?.[1]
const rootNode = template?.match(/<[^>]*>/)?.[0]
return rootNode
const getRootNodesOpenTags = (sfc: SFCParseResult) => {
const ast = sfc.descriptor.template?.ast
const rootNodes = ast?.children.filter(node => node.type === 1 /* ELEMENT */)

return rootNodes?.map(({ loc }) => {
const openTag = loc.source.match(/<[^>]*>/)?.[0]
if (!openTag) { return undefined }

return {
...loc,
end: { ...loc.start, offset: loc.start.offset + openTag.length },

source: openTag,
}
})
}

const renderCssVariablesAsStringCode = (vBinds: string[]) => {
Expand Down Expand Up @@ -63,7 +91,7 @@ const renderObjectGuardCode = (existingContent: string, binds: string[]) => {
return `typeof ${existingContent} === 'object' ? (Array.isArray(${existingContent}) ? ${arrayStyle} : ${objectStyle}) : ${stringStyle}`
}

const addStyleToRootNode = (rootNode: string, vBinds: string[]) => {
const addStyleAttrToTag = (rootNode: string, vBinds: string[]) => {
const [vBindCode, vBindContent] = rootNode?.match(/:style="([^"]*)"/) || []
const [attrCode, attrContent] = rootNode?.match(/[^:]style="([^"]*)"/) || []
const cssVariablesString = renderCssVariablesAsStringCode(vBinds)
Expand All @@ -84,33 +112,37 @@ const addStyleToRootNode = (rootNode: string, vBinds: string[]) => {
return rootNode.replace(/(\/?>)$/, ` :style="\`${cssVariablesString}\`"$1`)
}

/** Replace each v-bind() with var(--va-index-name) */
const replaceVueVBindWithCssVariables = (code: string, vBinds: string[]) => {
vBinds.forEach((vBind, index) => {
try {
code = code.replace(new RegExp(`v-bind\\(['|"]?${vBind}['|"]?\\)`, 'gm'), `var(--va-${index}-${kebabCase(vBind)})`)
} catch (e) {
console.log(vBind)
throw e
}
})

return code
}

export const transformVueComponent = (code: string) => {
const style = code.match(/<style[^>]*>([\s\S]*)<\/style>/)
if (!style) { return }
const sfc = parse(code)

const vBinds = parseCssVBindCode(style[0])
const vBinds = getVBinds(sfc)
if (!vBinds.length) { return }

const rootNode = getRootNodeOpenTagCode(code)
if (!rootNode) { throw new Error('Root node not found in template') }
const rootNodes = getRootNodesOpenTags(sfc)
if (!rootNodes?.length) { return }

const s = new MagicString(code)

rootNodes?.forEach((nodeOpenTag) => {
if (!nodeOpenTag) { return }

const newStartTagCode = addStyleAttrToTag(nodeOpenTag.source, vBinds)

s.overwrite(nodeOpenTag.start.offset, nodeOpenTag.end.offset, newStartTagCode)
})

vBinds.forEach((vBind, index) => {
const locs = getStyleVBindLocs(s.original, vBind)

code = replaceVueVBindWithCssVariables(code, vBinds)
locs.forEach((loc) => {
s.overwrite(loc.start, loc.end, `var(--va-${index}-${kebabCase(vBind)})`)
})
})

return code.replace(rootNode, addStyleToRootNode(rootNode, vBinds))
return {
code: s.toString(),
map: s.generateMap(),
}
}

/** We need this plugin to support CSS vbind in SSR. Vue useCssVars is disabled for cjs build */
Expand Down