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

feat(core): support safelist access to RuleContext #3693

Merged
merged 7 commits into from
Apr 18, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 16 additions & 9 deletions packages/core/src/generator/index.ts
@@ -1,5 +1,5 @@
import { createNanoEvents } from '../utils/events'
import type { CSSEntries, CSSObject, DynamicRule, ExtendedTokenInfo, ExtractorContext, GenerateOptions, GenerateResult, ParsedUtil, PreflightContext, PreparedRule, RawUtil, ResolvedConfig, RuleContext, RuleMeta, Shortcut, ShortcutValue, StringifiedUtil, UserConfig, UserConfigDefaults, UtilObject, Variant, VariantContext, VariantHandler, VariantHandlerContext, VariantMatchedResult } from '../types'
import type { CSSEntries, CSSObject, DynamicRule, ExtendedTokenInfo, ExtractorContext, GenerateOptions, GenerateResult, ParsedUtil, PreflightContext, PreparedRule, RawUtil, ResolvedConfig, RuleContext, RuleMeta, SafeListContext, Shortcut, ShortcutValue, StringifiedUtil, UserConfig, UserConfigDefaults, UtilObject, Variant, VariantContext, VariantHandler, VariantHandlerContext, VariantMatchedResult } from '../types'
import { resolveConfig } from '../config'
import { BetterMap, CONTROL_SHORTCUT_NO_MERGE, CountableSet, TwoKeyMap, e, entriesToCss, expandVariantGroup, isCountableSet, isRawUtil, isStaticShortcut, isString, noop, normalizeCSSEntries, normalizeCSSValues, notNull, toArray, uniq, warnOnce } from '../utils'
import { version } from '../../package.json'
Expand Down Expand Up @@ -182,11 +182,18 @@ export class UnoGenerator<Theme extends object = object> {
: input

if (safelist) {
this.config.safelist.forEach((s) => {
// We don't want to increment count if token is already in the set
if (!tokens.has(s))
tokens.add(s)
})
const safelistContext: SafeListContext<Theme> = {
generator: this,
theme: this.config.theme,
}

this.config.safelist
.flatMap(s => typeof s === 'function' ? s(safelistContext) : s)
.forEach((s) => {
// We don't want to increment count if token is already in the set
if (!tokens.has(s))
tokens.add(s)
})
}

const nl = minify ? '' : '\n'
Expand Down Expand Up @@ -284,7 +291,7 @@ export class UnoGenerator<Theme extends object = object> {
|| a[2]?.localeCompare(b[2] || '') // body
|| 0
})
.map(([, selector, body,, meta,, variantNoMerge]) => {
.map(([, selector, body, , meta, , variantNoMerge]) => {
const scopedSelector = selector ? applyScope(selector, scope) : selector
return [
[[scopedSelector ?? '', meta?.sort ?? 0]],
Expand Down Expand Up @@ -725,8 +732,8 @@ export class UnoGenerator<Theme extends object = object> {
}

const merges = [
[e.filter(([, noMerge]) => noMerge).map(([entries,, sort]) => [entries, sort]), true],
[e.filter(([, noMerge]) => !noMerge).map(([entries,, sort]) => [entries, sort]), false],
[e.filter(([, noMerge]) => noMerge).map(([entries, , sort]) => [entries, sort]), true],
[e.filter(([, noMerge]) => !noMerge).map(([entries, , sort]) => [entries, sort]), false],
] as [[CSSEntries, number][], boolean][]

return merges.map(([e, noMerge]) => [
Expand Down
16 changes: 9 additions & 7 deletions packages/core/src/types.ts
Expand Up @@ -131,6 +131,8 @@ export interface PreflightContext<Theme extends object = object> {
theme: Theme
}

export interface SafeListContext<Theme extends object = object> extends PreflightContext<Theme> { }

export interface Extractor {
name: string
order?: number
Expand Down Expand Up @@ -359,7 +361,7 @@ export interface ConfigBase<Theme extends object = object> {
/**
* Utilities that always been included
*/
safelist?: string[]
safelist?: (string | ((context: SafeListContext<Theme>) => Arrayable<string>))[]

/**
* Extractors to handle the source file and outputs possible classes/selectors
Expand Down Expand Up @@ -686,7 +688,7 @@ export interface ContentOptions {
/**
* Inline text to be extracted
*/
inline?: (string | { code: string, id?: string } | (() => Awaitable<string | { code: string, id?: string }>)) []
inline?: (string | { code: string, id?: string } | (() => Awaitable<string | { code: string, id?: string }>))[]

/**
* Filters to determine whether to extract certain modules from the build tools' transformation pipeline.
Expand Down Expand Up @@ -722,7 +724,7 @@ export interface ContentOptions {
/**
* @deprecated Renamed to `inline`
*/
plain?: (string | { code: string, id?: string }) []
plain?: (string | { code: string, id?: string })[]
}

/**
Expand Down Expand Up @@ -778,12 +780,12 @@ export interface PluginOptions {
exclude?: FilterPattern
}

export interface UserConfig<Theme extends object = object> extends ConfigBase<Theme>, UserOnlyOptions<Theme>, GeneratorOptions, PluginOptions, CliOptions {}
export interface UserConfigDefaults<Theme extends object = object> extends ConfigBase<Theme>, UserOnlyOptions<Theme> {}
export interface UserConfig<Theme extends object = object> extends ConfigBase<Theme>, UserOnlyOptions<Theme>, GeneratorOptions, PluginOptions, CliOptions { }
export interface UserConfigDefaults<Theme extends object = object> extends ConfigBase<Theme>, UserOnlyOptions<Theme> { }

export interface ResolvedConfig<Theme extends object = object> extends Omit<
RequiredByKey<UserConfig<Theme>, 'mergeSelectors' | 'theme' | 'rules' | 'variants' | 'layers' | 'extractors' | 'blocklist' | 'safelist' | 'preflights' | 'sortLayers'>,
'rules' | 'shortcuts' | 'autocomplete'
RequiredByKey<UserConfig<Theme>, 'mergeSelectors' | 'theme' | 'rules' | 'variants' | 'layers' | 'extractors' | 'blocklist' | 'safelist' | 'preflights' | 'sortLayers'>,
'rules' | 'shortcuts' | 'autocomplete'
> {
presets: Preset<Theme>[]
shortcuts: Shortcut<Theme>[]
Expand Down
4 changes: 2 additions & 2 deletions packages/postcss/src/apply.ts
Expand Up @@ -8,7 +8,7 @@ import { expandVariantGroup, notNull, regexScopePlaceholder } from '@unocss/core
type Writeable<T> = { -readonly [P in keyof T]: T[P] }

export async function parseApply(root: Root, uno: UnoGenerator, directiveName: string) {
const promises: Promise<unknown>[] = [];
const promises: Promise<unknown>[] = []
root.walkAtRules(directiveName, (rule) => {
promises.push((async () => {
if (!rule.parent)
Expand Down Expand Up @@ -88,5 +88,5 @@ export async function parseApply(root: Root, uno: UnoGenerator, directiveName: s
rule.remove()
})())
})
await Promise.all(promises);
await Promise.all(promises)
}
3 changes: 3 additions & 0 deletions test/safelist.test.ts
Expand Up @@ -10,10 +10,13 @@ describe('safelist', () => {
],
safelist: [
'm1',
() => ['m3', 'm4'],
],
})
const { css } = await uno.generate('m2')
expect(css).toContain('.m1')
expect(css).toContain('.m2')
expect(css).toContain('.m3')
expect(css).toContain('.m4')
})
})