Skip to content

Commit

Permalink
feat(headless-ui): add focus-visible
Browse files Browse the repository at this point in the history
GH-14

Co-authored-by: zqianem <zqianem@users.noreply.github.com>
  • Loading branch information
zirbest and zqianem committed Dec 10, 2023
1 parent a383c38 commit 07afde7
Showing 1 changed file with 49 additions and 21 deletions.
70 changes: 49 additions & 21 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Preset } from '@unocss/core'
import type { Preset, Variant } from '@unocss/core'

/**
* @public
Expand All @@ -23,35 +23,41 @@ export interface PrimitivesOptions {
isAttrBoolean?: boolean
}

function presetPrimitives(options: PrimitivesOptions = {}): Preset {
function presetVariants(options: PrimitivesOptions = {}): Variant {
const {
prefix = 'ui',
variants = 'open|checked|selected|active|disabled',
selector = 'data-headlessui-state',
isAttrBoolean = false,
} = options

return {
name: 'unocss-variant-primitives',
match: (matcher: string) => {
const regex = new RegExp(`^${prefix}(-not)?-(${variants})[:-]`)
const match = matcher.match(regex)

if (!match)
return matcher

const attrGen = !isAttrBoolean
? `[${selector}~='${match[2]}']`
: `[${selector}-${match[2]}]`
return {
matcher: matcher.slice(match[0].length),
selector: (s: any) => (match[1] === '-not')
? `${s}[${selector}]:not(${attrGen}),:where([${selector}]:not(${attrGen})) ${s}:not(${selector})`
: `${s}${attrGen},:where(${attrGen}) ${s}`,
}
},
}
}

function presetPrimitives(options: PrimitivesOptions = {}): Preset {
return {
name: 'unocss-preset-primitives',
variants: [
(matcher: string) => {
const regex = new RegExp(`^${prefix}(-not)?-(${variants})[:-]`)
const match = matcher.match(regex)
if (match) {
const attrGen = !isAttrBoolean
? `[${selector}~='${match[2]}']`
: `[${selector}-${match[2]}]`
return {
matcher: matcher.slice(match[0].length),
selector: (s: any) => (match[1] === '-not')
? `${s}[${selector}]:not(${attrGen}),:where([${selector}]:not(${attrGen})) ${s}:not(${selector})`
: `${s}${attrGen},:where(${attrGen}) ${s}`,
}
}
else {
return matcher
}
},
presetVariants(options),
],
}
}
Expand All @@ -70,7 +76,29 @@ function presetHeadlessUi(options: HeadlessUiOptions = {}): Preset {
const {
prefix = 'ui',
} = options
return presetPrimitives({ prefix })

return {
name: 'unocss-preset-primitives',
variants: [
presetVariants({ prefix }),
(matcher) => {
const regex = new RegExp(`${prefix}(-not)?-focus-visible[:-]`)
const match = matcher.match(regex)

if (!match)
return matcher

return {
matcher: matcher.slice(match[0].length),
selector: (s) => {
return (match[1] === '-not')
? `${s}:focus:where(:not([data-headlessui-focus-visible] ${s}))`
: `:where([data-headlessui-focus-visible]) ${s}:focus`
},
}
},
],
}
}

/**
Expand Down

0 comments on commit 07afde7

Please sign in to comment.