Skip to content

Commit 483d17b

Browse files
refactor: 🏷️ fix typescript types
1 parent 5f74927 commit 483d17b

File tree

2 files changed

+53
-249
lines changed

2 files changed

+53
-249
lines changed

src/index.ts

Lines changed: 53 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
1-
import type { IconifyJSON } from '@iconify/types'
2-
import type { UnoGenerator } from '@unocss/core'
3-
import { createGenerator } from '@unocss/core'
4-
import UnocssIcons from '@unocss/preset-icons'
1+
/* eslint-disable regexp/strict */
2+
/* eslint-disable unicorn/better-regex */
3+
import { type IconifyJSON } from '@iconify/types'
4+
import { createGenerator, type UnoGenerator } from '@unocss/core'
5+
import presetIcons from '@unocss/preset-icons'
56
import { presetTypography } from '@unocss/preset-typography'
7+
import presetAttributify from '@unocss/preset-attributify'
68
import windicssPreset from '@unocss/preset-wind'
79
import { parse as CSSParser, walk as CSSWalker } from 'css-tree'
810
import fg from 'fast-glob'
9-
import { readFileSync } from 'fs'
1011
import MagicString from 'magic-string'
12+
import { readFileSync } from 'node:fs'
1113
import { parse, preprocess } from 'svelte/compiler'
12-
import type {
13-
PreprocessorGroup,
14-
Processed,
15-
} from 'svelte/types/compiler/preprocess'
14+
import { type PreprocessorGroup, type Processed } from 'svelte/types/compiler/preprocess'
1615
import { loadConfig } from 'unconfig'
1716
import { type FullConfig } from 'windicss/types/interfaces'
1817

1918
export interface BaseConfig {
2019
silent?: boolean
2120
mode?: 'development' | 'production'
21+
attributify?: {
22+
strict?: boolean
23+
prefix?: string
24+
prefixedOnly?: boolean
25+
nonValuedAttribute?: boolean
26+
ignoreAttributes: string[]
27+
}
2228
icons?: {
2329
prefix?: string
2430
collections?: Record<string, IconifyJSON>
@@ -33,7 +39,6 @@ const defaults: DefaultConfig = {}
3339
let generatorConfiguration: BaseConfig
3440
let windiConfiguration: any
3541
let windiGenerator: UnoGenerator
36-
let iconGenerator: UnoGenerator
3742

3843
const styles: {
3944
[key: string]: Set<string>
@@ -43,11 +48,11 @@ const styles: {
4348

4449
function splitVariantGroups(content: string) {
4550
return content.replace(
46-
/([!\w][\w:_/-]*?):\(([\w\s/-]*?)\)/gm,
51+
/([\w!][\w/:-]*?):\(([\s\w/-]*)\)/g,
4752
(_, groupOne: string, groupTwo: string) =>
4853
groupTwo
4954
.split(/\s/g)
50-
.map(cssClass => `${groupOne}:${cssClass}`)
55+
.map((cssClass) => `${groupOne}:${cssClass}`)
5156
.join(' ')
5257
)
5358
}
@@ -66,25 +71,25 @@ function addStyleTag(content: string) {
6671

6772
function cleanUtilities(utilities: string) {
6873
return utilities
69-
.replace(/windi[`].+?[`]/gi, ' ') // windi`XYZ`
70-
.replace(/(?<![-])[$](?=[{])/gi, ' ') // if leading char is not -, and next char is {, then remove $
71-
.replace(/(?<=([{][\w\s]+[^{]*?))['"]/gi, ' ') // remove quotes in curly braces
72-
.replace(/(?<=([{][\w\s]+[^{]*?)\s)[:]/gi, ' ') // remove : in curly braces
73-
.replace(/([{][\w\s]+[^{]*?[?])/gi, ' ') // remove ? and condition in curly braces
74-
.replace(/[{}]/gi, ' ') // remove curly braces
75-
.replace(/\n/gi, ' ') // remove newline
76-
.replace(/ {2,}/gi, ' ') // remove multiple spaces
77-
.replace(/["'`]/gi, '') // remove quotes
74+
.replace(/windi`.+?`/gi, ' ') // windi`XYZ`
75+
.replace(/(?<!-)\$(?=\{)/g, ' ') // if leading char is not -, and next char is {, then remove $
76+
.replace(/(?<=(\{[\s\w][^{]*?))["']/g, ' ') // remove quotes in curly braces
77+
.replace(/(?<=(\{[\s\w][^{]*?)\s):/g, ' ') // remove : in curly braces
78+
.replace(/(\{[\s\w][^{]*?\?)/g, ' ') // remove ? and condition in curly braces
79+
.replace(/[{}]/g, ' ') // remove curly braces
80+
.replace(/\n/g, ' ') // remove newline
81+
.replace(/ {2,}/g, ' ') // remove multiple spaces
82+
.replace(/["'`]/g, '') // remove quotes
7883
.trim()
7984
.split(' ')
8085
}
8186

8287
function scanFile(content: string, filename: string) {
8388
//TODO@alexanderniebuhr add attributifies
8489
const MATCHES = [
85-
...content.matchAll(/class=(['"`])(?<utilities>[^\1]+?)\1/gi),
86-
...content.matchAll(/class=(?<utilities>[{][^}]+?)}/gi),
8790
...content.matchAll(/\s(class):(?<utility>[^=]+)(=)/gi),
91+
...content.matchAll(/class=(["'`])(?<utilities>[^\1]+?)\1/gi),
92+
...content.matchAll(/class=(?<utilities>\{[^}]+)\}/gi),
8893
]
8994
styles[filename] = new Set()
9095

@@ -95,21 +100,19 @@ function scanFile(content: string, filename: string) {
95100
styles[filename].add(match.groups.utility)
96101
}
97102
if (match.groups?.utilities) {
98-
cleanUtilities(match.groups?.utilities).forEach(utility => {
103+
for (const utility of cleanUtilities(match.groups?.utilities)) {
99104
if (utility.startsWith('global:')) {
100105
styles['__GLOBAL__'].add(utility.replace('global:', ''))
101106
} else {
102107
styles[filename].add(utility)
103108
}
104-
})
109+
}
105110
}
106111
}
107-
108-
return styles
109112
}
110113

111114
function extractStyles(): PreprocessorGroup {
112-
if (initialFileName.length == 0) {
115+
if (initialFileName.length === 0) {
113116
const filePaths = fg.sync(['src/**/*.svelte'], {})
114117
for (const filepath of filePaths) {
115118
const content = splitVariantGroups(readFileSync(filepath).toString())
@@ -120,7 +123,7 @@ function extractStyles(): PreprocessorGroup {
120123
return {
121124
async markup({ content, filename }): Promise<Processed> {
122125
if (!filename) return { code: content }
123-
if (initialFileName.length == 0) initialFileName = filename
126+
if (initialFileName.length === 0) initialFileName = filename
124127
content = addStyleTag(content)
125128
content = content.replace(/global:/gi, '')
126129
return {
@@ -150,7 +153,8 @@ function generateCSS(): PreprocessorGroup {
150153
node.prelude.children
151154
) {
152155
const applyUtillities: Set<string> = new Set()
153-
node.prelude.children.forEach(identifier => {
156+
// eslint-disable-next-line unicorn/no-array-for-each
157+
node.prelude.children.forEach((identifier) => {
154158
if (identifier.type === 'Identifier') {
155159
applyUtillities.add(identifier.name)
156160
}
@@ -164,19 +168,13 @@ function generateCSS(): PreprocessorGroup {
164168
parseValue: false,
165169
})
166170

167-
CSSWalker(applyStyleSheet, (node, item, list) => {
168-
if (node.type == 'Declaration') {
169-
if (node.value.type == 'Raw') {
170-
generatedApplyCss += `${node.property}:${node.value.value};`
171-
}
171+
CSSWalker(applyStyleSheet, (node) => {
172+
if (node.type == 'Declaration' && node.value.type == 'Raw') {
173+
generatedApplyCss += `${node.property}:${node.value.value};`
172174
}
173175
})
174176

175-
tagStylesCSS.overwrite(
176-
node.loc.start.offset,
177-
node.loc.end.offset,
178-
generatedApplyCss
179-
)
177+
tagStylesCSS.overwrite(node.loc.start.offset, node.loc.end.offset, generatedApplyCss)
180178
content = tagStylesCSS.toString()
181179
}
182180
})
@@ -415,12 +413,8 @@ function generateCSS(): PreprocessorGroup {
415413
parseValue: false,
416414
})
417415

418-
CSSWalker(globalStyleSheet, (node, item, list) => {
419-
if (
420-
node.type === 'Rule' &&
421-
node.prelude.type === 'SelectorList' &&
422-
node.prelude.loc
423-
) {
416+
CSSWalker(globalStyleSheet, (node) => {
417+
if (node.type === 'Rule' && node.prelude.type === 'SelectorList' && node.prelude.loc) {
424418
globalStylesCSS
425419
.appendLeft(node.prelude.loc?.start.offset, ':global(')
426420
.appendRight(node.prelude.loc?.end.offset, ')')
@@ -433,10 +427,8 @@ function generateCSS(): PreprocessorGroup {
433427
node.prelude.type === 'AtrulePrelude' &&
434428
node.prelude.loc
435429
) {
436-
globalStylesCSS.appendLeft(
437-
node.prelude.loc?.start.offset,
438-
'-global-'
439-
)
430+
globalStylesCSS.appendLeft(node.prelude.loc?.start.offset, '-global-')
431+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
440432
return (CSSWalker as any).skip
441433
}
442434
})
@@ -445,11 +437,7 @@ function generateCSS(): PreprocessorGroup {
445437
const windiStyles = await windiGenerator.generate(styles[filename])
446438
const windiStylesCSS = new MagicString(windiStyles.css)
447439
const newContent =
448-
(globalContent ? globalContent : '') +
449-
'\n' +
450-
windiStylesCSS.toString() +
451-
'\n' +
452-
content
440+
(globalContent ? globalContent : '') + '\n' + windiStylesCSS.toString() + '\n' + content
453441
// console.log(newContent)
454442
return {
455443
code: newContent,
@@ -462,10 +450,18 @@ function generateCSS(): PreprocessorGroup {
462450
export function generate(userConfig: UserConfig = {}): PreprocessorGroup {
463451
generatorConfiguration = { ...defaults, ...userConfig }
464452

465-
const presets = [windicssPreset(), presetTypography()]
453+
const presets = []
454+
if (generatorConfiguration.attributify != undefined) {
455+
presets.push(
456+
presetAttributify({
457+
...generatorConfiguration.attributify,
458+
})
459+
)
460+
}
461+
presets.push(windicssPreset(), presetTypography())
466462
if (generatorConfiguration.icons != undefined) {
467463
presets.push(
468-
UnocssIcons({
464+
presetIcons({
469465
...generatorConfiguration.icons,
470466
})
471467
)

0 commit comments

Comments
 (0)