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(transformer-attributify-jsx): matchedRule #3791

Merged
merged 7 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 25 additions & 6 deletions packages/transformer-attributify-jsx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ export interface TransformerAttributifyJsxOptions {
exclude?: FilterPattern
}

const elementRE = /(<\w[\w:\.$-]*\s)([\s\S]*?)(?=>[\s\S]?<\/[\s\w:\.$-]*>|\/>)/g
const elementRE = /<([^\/?<>0-9$_!][^\s>]*)\s+((?:"[^"]*"|'[^"]*'|({[^}]*})|[^{>])+)>/g
const attributeRE = /(?<![~`!$%^&*()_+\-=[{;':"|,.<>/?]\s*)([a-zA-Z()#][\[?a-zA-Z0-9-_:()#%\]?]*)(?:\s*=\s*((?:'[^']*')|(?:"[^"]*")|\S+))?/g
const valuedAttributeRE = /((?!\d|-{2}|-\d)[a-zA-Z0-9\u00A0-\uFFFF-_:!%-.~<]+)=(?:["]([^"]*)["]|[']([^']*)[']|[{]((?:[`(](?:[^`)]*)[`)]|[^}])+)[}])/gms
const valuedAttributeRE = /((?!\d|-{2}|-\d)[a-zA-Z0-9\u00A0-\uFFFF-_:!%-.~<]+)=(?:["](?:[^"]*)["]|['](?:[^']*)[']|([{])((?:[`(](?:[^`)]*)[`)]|[^}])+)([}]))/gms

export default function transformerAttributifyJsx(options: TransformerAttributifyJsxOptions = {}): SourceCodeTransformer {
const {
Expand Down Expand Up @@ -75,17 +75,36 @@ export default function transformerAttributifyJsx(options: TransformerAttributif
for (const item of Array.from(code.original.matchAll(elementRE))) {
// Get the length of the className part, and replace it with the equal length of empty string
let attributifyPart = item[2]
if (valuedAttributeRE.test(attributifyPart))
attributifyPart = attributifyPart.replace(valuedAttributeRE, match => ' '.repeat(match.length))
if (valuedAttributeRE.test(attributifyPart)) {
attributifyPart = attributifyPart.replace(valuedAttributeRE, (match, _, dynamicFlagStart) => {
if (!dynamicFlagStart)
return ' '.repeat(match.length)
let preLastModifierIndex = 0
let temp = match
// No more recursively processing the more complex situations of jsx in attributes.
for (const _item of match.matchAll(elementRE)) {
const attrAttributePart = _item[2]
if (valuedAttributeRE.test(attrAttributePart))
attrAttributePart.replace(valuedAttributeRE, (m: string) => ' '.repeat(m.length))

const pre = temp.slice(0, preLastModifierIndex) + ' '.repeat(_item.index + _item[0].indexOf(_item[2]) - preLastModifierIndex) + attrAttributePart
temp = pre + ' '.repeat(_item.input.length - pre.length)
preLastModifierIndex = pre.length
}
if (preLastModifierIndex !== 0)
return temp

return ' '.repeat(match.length)
})
}
for (const attr of attributifyPart.matchAll(attributeRE)) {
const matchedRule = attr[0].replace(/\:/i, '-')
if (matchedRule.includes('=') || isBlocked(matchedRule))
continue

tasks.push(uno.parseToken(matchedRule).then((matched) => {
if (matched) {
const tag = item[1]
const startIdx = (item.index || 0) + (attr.index || 0) + tag.length
const startIdx = (item.index || 0) + (attr.index || 0) + item[0].indexOf(item[2])
const endIdx = startIdx + matchedRule.length
code.overwrite(startIdx, endIdx, `${matchedRule}=""`)
}
Expand Down
154 changes: 99 additions & 55 deletions test/transformer-attributify-jsx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ const originalCode = `
on-demand · instant · fully customizable
</div>
<div components={<div absolute bottom-5></div>}></div>
<div components={() => <div left-0 bottom-5>
<div text-center> flex </div>
</div>}></div>
<h1 flex>h1</h1>
<div {...{ flex }} />
<div {...{ onClick: () => { grid(); flex } }} flex />
Expand Down Expand Up @@ -68,7 +71,7 @@ describe('transformerAttributifyJsx', () => {
],
})

it('transform', async () => {
it('transform test1', async () => {
const code = new MagicString(originalCode)
await transformerAttributifyJsx().transform(code, 'app.tsx', { uno, tokens: new Set() } as any)

Expand Down Expand Up @@ -106,6 +109,9 @@ describe('transformerAttributifyJsx', () => {
on-demand · instant · fully customizable
</div>
<div components={<div absolute="" bottom-5=""></div>}></div>
<div components={() => <div left-0="" bottom-5="">
<div text-center=""> flex </div>
</div>}></div>
<h1 flex="">h1</h1>
<div {...{ flex }} />
<div {...{ onClick: () => { grid(); flex } }} flex="" />
Expand All @@ -114,66 +120,98 @@ describe('transformerAttributifyJsx', () => {
</div>"
`)
})

it('blocklist', async () => {
const code = new MagicString(originalCode)
const blocklist: (string | RegExp)[] = ['flex', 'absolute']

await transformerAttributifyJsx({
blocklist,
}).transform(code, 'app.jsx', { uno, tokens: new Set() } as any)
// #3754
it('transform test2', async () => {
const code = new MagicString(`
const App: React.FC = () => {
return (
<div w-full h-full bg-gray-300
>
<div>123</div>
</div>
)
}
export default App
`)
await transformerAttributifyJsx().transform(code, 'app.tsx', { uno, tokens: new Set() } as any)

expect(code.toString()).toMatchInlineSnapshot(`
"<div h-full="" text-center="" flex select-none="" className={red ? 'text-red': 'text-green'}>
<input value={ target ? '10px' : '20px'} style={{ height: '100px' }} />
<div ma="">
<div text-5xl="" fw100="" animate-bounce-alt="" animate-count-infinite="" animate-duration-1s="" key={index}>
unocss
</div>
<div op30="" text-lg="" fw300="" m1="" className={hidden && 'op0'}>
The instant on-demand Atomic CSS engine.
</div>
<div m2="" flex justify-center="" text-2xl="" op30="" hover-op80="" hover-text-2xl="">
<a
i-carbon-logo-github
text-inherit=""
href="https://github.com/unocss/unocss"
target="_blank"
></a>
<router-link to={\`/path/\${1}\`}/>
</div>
</div>
<section
className={cn({ 'c-red': variable > 0 }, 'mr-10')}
mr-10=""
className={cn({ 'c-red': variable > 0 }, 'mr-10')}
></section>
<div
label={
<b>1</b>
"
const App: React.FC = () => {
return (
<div w-full="" h-full="" bg-gray-300=""
>
<div>123</div>
</div>
)
}
></div>
<div absolute bottom-5="" right-0="" left-0="" text-center="" op30="" fw300="">
on-demand · instant · fully customizable
</div>
<div components={<div absolute bottom-5=""></div>}></div>
<h1 flex>h1</h1>
<div {...{ flex }} />
<div {...{ onClick: () => { grid(); flex } }} flex />
<div {...true ? flex : props.grid } {...grid || ( block ) && $flex } />
<div {...[, flex, [flex], !flex, -flex, +flex, ~flex, "flex", \`flex\` ] } />
</div>"
export default App
"
`)

const codeToString = code.toString()
blocklist.forEach((rule) => {
if (rule instanceof RegExp)
expect(new RegExp(`${rule.source}=""`).test(codeToString)).not.true
else
expect(codeToString).not.toMatch(`${rule}=""`)
})
})

// it('blocklist', async () => {
Simon-He95 marked this conversation as resolved.
Show resolved Hide resolved
// const code = new MagicString(originalCode)
// const blocklist: (string | RegExp)[] = ['flex', 'absolute']

// await transformerAttributifyJsx({
// blocklist,
// }).transform(code, 'app.jsx', { uno, tokens: new Set() } as any)

// expect(code.toString()).toMatchInlineSnapshot(`
// "<div h-full="" text-center="" flex select-none="" className={red ? 'text-red': 'text-green'}>
// <input value={ target ? '10px' : '20px'} style={{ height: '100px' }} />
// <div ma="">
// <div text-5xl="" fw100="" animate-bounce-alt="" animate-count-infinite="" animate-duration-1s="" key={index}>
// unocss
// </div>
// <div op30="" text-lg="" fw300="" m1="" className={hidden && 'op0'}>
// The instant on-demand Atomic CSS engine.
// </div>
// <div m2="" flex justify-center="" text-2xl="" op30="" hover-op80="" hover-text-2xl="">
// <a
// i-carbon-logo-github
// text-inherit=""
// href="https://github.com/unocss/unocss"
// target="_blank"
// ></a>
// <router-link to={\`/path/\${1}\`}/>
// </div>
// </div>
// <section
// className={cn({ 'c-red': variable > 0 }, 'mr-10')}
// mr-10=""
// className={cn({ 'c-red': variable > 0 }, 'mr-10')}
// ></section>
// <div
// label={
// <b>1</b>
// }
// ></div>
// <div absolute bottom-5="" right-0="" left-0="" text-center="" op30="" fw300="">
// on-demand · instant · fully customizable
// </div>
// <div components={<div absolute bottom-5=""></div>}></div>
// <div components={() => <div left-0="" bottom-5="">
// <div text-center=""> flex </div>
// </div>}></div>
// <h1 flex>h1</h1>
// <div {...{ flex }} />
// <div {...{ onClick: () => { grid(); flex } }} flex />
// <div {...true ? flex : props.grid } {...grid || ( block ) && $flex } />
// <div {...[, flex, [flex], !flex, -flex, +flex, ~flex, "flex", \`flex\` ] } />
// </div>"
// `)

// const codeToString = code.toString()
// blocklist.forEach((rule) => {
// if (rule instanceof RegExp)
// expect(new RegExp(`${rule.source}=""`).test(codeToString)).not.true
// else
// expect(codeToString).not.toMatch(`${rule}=""`)
// })
// })

it('if class-like tag do not cause error', async () => {
const code = new MagicString(tagCouldBeAttrCode)
await transformerAttributifyJsx().transform(code, 'app.tsx', { uno, tokens: new Set() } as any)
Expand Down Expand Up @@ -231,6 +269,9 @@ describe('transformerAttributifyJsxBabel', () => {
on-demand · instant · fully customizable
</div>
<div components={<div absolute="" bottom-5=""></div>}></div>
<div components={() => <div left-0="" bottom-5="">
<div text-center=""> flex </div>
</div>}></div>
<h1 flex="">h1</h1>
<div {...{
flex
Expand Down Expand Up @@ -282,6 +323,9 @@ describe('transformerAttributifyJsxBabel', () => {
on-demand · instant · fully customizable
</div>
<div components={<div absolute bottom-5=""></div>}></div>
<div components={() => <div left-0="" bottom-5="">
<div text-center=""> flex </div>
</div>}></div>
<h1 flex>h1</h1>
<div {...{
flex
Expand Down