Skip to content

Commit

Permalink
fix: conflict with variant-group, resolve #1
Browse files Browse the repository at this point in the history
  • Loading branch information
zguolee committed Aug 16, 2022
1 parent 29e9789 commit d3aed63
Show file tree
Hide file tree
Showing 15 changed files with 364 additions and 234 deletions.
11 changes: 11 additions & 0 deletions .vscode/settings.json
@@ -0,0 +1,11 @@
{
"files.exclude": {
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true,
"**/Thumbs.db": true,
"**/node_modules": true
}
}
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -28,6 +28,9 @@ export default defineConfig({
})
```

## Acknowledgement
- [UnoCSS](https://github.com/unocss/unocss)

## License

MIT License © 2022-PRESENT [Neil Lee](https://github.com/zguolee)
37 changes: 18 additions & 19 deletions packages/preset-applet/README.md
@@ -1,6 +1,6 @@
# @unocss-applet/preset-applet

The Applet preset for [UnoCSS](https://github.com/unocss/unocss), fork from [@unocss/preset-uno](https://github.com/unocss/unocss/tree/main/packages/preset-uno) and modified to transform some CSS selector that mini-program can't use.
The Applet preset for [UnoCSS](https://github.com/unocss/unocss), fork from [@unocss/preset-uno](https://github.com/unocss/unocss/tree/main/packages/preset-uno) and modified to transform some CSS selector.

## Install

Expand All @@ -22,31 +22,30 @@ export default defineConfig({
})
```

## Type Declarations
```ts
// PresetMiniOptions https://github.com/unocss/unocss/blob/main/packages/preset-mini/src/index.ts#L30-L55
export interface PresetAppletOptions extends PresetMiniOptions {
/**
* Enable applet, only build applet should be true
* e.g. In uniapp `enableApplet: !(process.env.UNI_PLATFORM === 'h5')` to disable rename class in h5
* @default true
*/
enableApplet?: boolean
}
```

## Change

| form | to | sample |
| ---- | ------- | ---------------------- |
| [`*`](https://github.com/unocss/unocss/blob/main/packages/preset-mini/src/preflights.ts) | [`page`](./src/preflights.ts) | - |

> If you need to use a class selector that contains `[.:%!#()[\/\],]`, it needs to be used with [@unocss-applet/transformer-rename-class](../unocss-applet/)
## More

```ts
import presetApplet from '@unocss-applet/preset-applet'
import transformerRenameClass from '@unocss-applet/transformer-rename-class'

export default defineConfig({
presets: [
presetApplet(),
],
transformers: [
transformerRenameClass(),
],
})
```

## Change

> Only effect when enabled when set `presetApplet({ enableApplet: false })`.
### CSS selector transform
> Default enabled because for [issue#2](https://github.com/unocss-applet/unocss-applet/issues/2) in applet, to disable just set `enableApplet: false`
| form | to | sample |
| ---- | ------- | ---------------------- |
Expand Down
11 changes: 9 additions & 2 deletions packages/preset-applet/src/index.ts
@@ -1,13 +1,20 @@
import type { Preset } from 'unocss'
import type { PresetMiniOptions, Theme } from '@unocss/preset-mini'
import { rules, shortcuts, theme, variants } from '@unocss/preset-wind'
import { preflights } from './preflights'
import { preflights } from '@unocss/preset-mini'
import { preflights as preflightsApplet } from './preflights'
import { unoCSSToAppletProcess } from './process'
import { variantColorMix } from './variants/mix'

export type { Theme }

// PresetMiniOptions https://github.com/unocss/unocss/blob/main/packages/preset-mini/src/index.ts#L30-L55
export interface PresetAppletOptions extends PresetMiniOptions {
/**
* Enable applet, only build applet should be true
* e.g. In uniapp `enableApplet: !(process.env.UNI_PLATFORM === 'h5')` to disable rename class in h5
* @default true
*/
enableApplet?: boolean
}

Expand All @@ -26,7 +33,7 @@ const presetApplet = (options: PresetAppletOptions = {}): Preset<Theme> => {
variantColorMix,
],
options,
preflights,
preflights: options.enableApplet ? preflightsApplet : preflights,
postprocess: [
(util) => {
options.enableApplet && (util.selector = unoCSSToAppletProcess(util.selector))
Expand Down
18 changes: 17 additions & 1 deletion packages/preset-rem-to-rpx/README.md
Expand Up @@ -10,7 +10,7 @@ yarn add @unocss-applet/preset-rem-to-rpx -D # with yarn
pnpm add @unocss-applet/preset-rem-to-rpx -D # with pnpm
```

## Usage
## Usage

```ts
import { defineConfig } from 'unocss'
Expand All @@ -25,6 +25,22 @@ export default defineConfig({
})
```

## Type Declarations
```ts
export interface RemToRpxOptions {
/**
* 1rem = n px
* @default 16
*/
baseFontSize?: number
/**
* screen width in px
* @default 375
*/
screenWidth?: number
}
```

```html
<div class="m-2"></div>
```
Expand Down
45 changes: 45 additions & 0 deletions packages/transformer-rename-class/README.md
Expand Up @@ -27,6 +27,51 @@ export default defineConfig({
})
```

## Type Declarations
```ts
export interface RenameClassOptions {
/**
* Prefix for compile class name
* @default 'uno-'
*/
classPrefix?: string

/**
* Hash function
*/
hashFn?: (str: string) => string

/**
* The layer name of generated rules
* @default 'applet_shortcuts'
*/
layer?: string

/**
* Enable rename class, only build applet should be true
* e.g. In uniapp `enableRename: !(process.env.UNI_PLATFORM === 'h5')` to disable rename class in h5
* @default true
*/
enableRename?: boolean

/**
* Separators to expand.
*
* ```
* foo-(bar baz) -> foo-bar foo-baz
* ^
* separator
* ```
*
* You may set it to `[':']` for strictness.
*
* @default [':', '-']
* @see https://github.com/unocss/unocss/pull/1231
*/
separators?: (':' | '-')[]
}
```

## Example
### Using in with `class`
#### without
Expand Down
124 changes: 83 additions & 41 deletions packages/transformer-rename-class/src/index.ts
@@ -1,4 +1,5 @@
import type { SourceCodeTransformer, UnocssPluginContext } from 'unocss'
import { expandVariantGroup } from '@unocss/core'

export interface RenameClassOptions {
/**
Expand All @@ -14,15 +15,40 @@ export interface RenameClassOptions {

/**
* The layer name of generated rules
* @default 'applet_shortcuts'
*/
layer?: string

/**
* Enable rename class, only build applet should be true
* e.g. In uniapp `enableRename: !(process.env.UNI_PLATFORM === 'h5')` to disable rename class in h5
* @default true
*/
enableRename?: boolean

/**
* Separators to expand.
*
* ```
* foo-(bar baz) -> foo-bar foo-baz
* ^
* separator
* ```
*
* You may set it to `[':']` for strictness.
*
* @default [':', '-']
* @see https://github.com/unocss/unocss/pull/1231
*/
separators?: (':' | '-')[]
}

export default function transformerRenameClass(options: RenameClassOptions = {}): SourceCodeTransformer {
const {
classPrefix = 'uno-',
hashFn = hash,
layer = 'applet_shortcuts',
enableRename = true,
} = options

// Regular expression of characters to be escaped
Expand All @@ -31,6 +57,63 @@ export default function transformerRenameClass(options: RenameClassOptions = {})
const classRE = /:?(hover-)?class=\".*?\"/g
const stringRE = /(['\`]).*?(['\`])/g

return {
name: 'rename-class',
enforce: 'pre',
async transform(s, _, ctx) {
if (!enableRename) {
// https://github.com/unocss/unocss/tree/main/packages/transformer-variant-group
expandVariantGroup(s, options.separators)
}
else {
// process class
const classMatches = [...s.original.matchAll(classRE)]
for (const match of classMatches) {
// skip `... ? ... : ...`
if (/\?.*:/g.test(match[0]))
continue

// skip `... : ...`
if (/{.+:.+}/g.test(match[0]))
continue

const start = match.index!
const matchSplit = match[0].split('=')

const body = expandVariantGroup(matchSplit[1].slice(1, -1), options.separators)

if (charReg.test(body)) {
const replacements = await compileApplet(body, ctx)
s.overwrite(start, start + match[0].length, `${matchSplit[0]}="${replacements.join(' ')}"`)
}
}

// process string
const stringMatches = [...s.original.matchAll(stringRE)]
for (const match of stringMatches) {
// skip `${...}`
if (/\$\{.*\}/g.test(match[0]))
continue

// https://tailwindcss.com/docs/background-image#arbitrary-values
// skip all the image formats in HTML for bg-[url('...')]
if (/\.(png|jpg|jpeg|gif|svg)/g.test(match[0]))
continue
// skip http(s)://
if (/^http(s)?:\/\//g.test(match[0]))
continue

const start = match.index!
const body = match[0].slice(1, -1)
if (charReg.test(body)) {
const replacements = await compileApplet(body, ctx)
s.overwrite(start, start + match[0].length, `'${replacements.join(' ')}'`)
}
}
}
},
}

async function compileApplet(body: string, ctx: UnocssPluginContext): Promise<string[]> {
const { uno, tokens } = ctx
const replacements = []
Expand All @@ -48,47 +131,6 @@ export default function transformerRenameClass(options: RenameClassOptions = {})
}
return replacements
}

return {
name: 'rename-class',
enforce: 'pre',
async transform(s, _, ctx) {
const classMatches = [...s.original.matchAll(classRE)]
for (const match of classMatches) {
// skip `... ? ... : ...`
if (/\?.*:/g.test(match[0]))
continue
const start = match.index!
const matchSplit = match[0].split('=')

const body = matchSplit[1].slice(1, -1)

if (charReg.test(body)) {
const replacements = await compileApplet(body, ctx)
s.overwrite(start, start + match[0].length, `${matchSplit[0]}="${replacements.join(' ')}"`)
}
}
const stringMatches = [...s.original.matchAll(stringRE)]
for (const match of stringMatches) {
// skip `${...}`
if (/\$\{.*\}/g.test(match[0]))
continue
// skip all the image formats in HTML
if (/\.(png|jpg|jpeg|gif|svg)/g.test(match[0]))
continue
// skip http(s)://
if (/^http(s)?:\/\//g.test(match[0]))
continue

const start = match.index!
const body = match[0].slice(1, -1)
if (charReg.test(body)) {
const replacements = await compileApplet(body, ctx)
s.overwrite(start, start + match[0].length, `'${replacements.join(' ')}'`)
}
}
},
}
}

function hash(str: string) {
Expand Down
8 changes: 4 additions & 4 deletions playground/index.html
Expand Up @@ -3,11 +3,11 @@
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
const coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)')
|| CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
`<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0${
coverSupport ? ', viewport-fit=cover' : ''}" />`)
</script>
<title></title>
<!--preload-links-->
Expand Down
3 changes: 0 additions & 3 deletions playground/src/App.vue
@@ -1,13 +1,10 @@
<script setup lang="ts">
import { onHide, onLaunch, onShow } from '@dcloudio/uni-app'
onLaunch(() => {
console.log('App Launch')
})
onShow(() => {
console.log('App Show')
})
onHide(() => {
console.log('App Hide')
})
</script>

Expand Down

0 comments on commit d3aed63

Please sign in to comment.