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

Feature/container max width #27

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 42 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import plugin from 'tailwindcss/plugin'

type VariantSortProps = {
value: string;
modifier: string | null;
};

export = plugin(
function containerQueries({ matchUtilities, matchVariant, theme }) {
let values: Record<string, string> = theme('containers') ?? {}
Expand All @@ -11,6 +16,31 @@ export = plugin(
return parseFloat(value)
}

function sort(aVariant: VariantSortProps, zVariant: VariantSortProps) {
const a = parseFloat(aVariant.value)
const z = parseFloat(zVariant.value)

if (a === null || z === null) return 0

// Sort values themselves regardless of unit
if (a - z !== 0) return a - z

const aLabel = aVariant.modifier ?? ''
const zLabel = zVariant.modifier ?? ''

// Explicitly move empty labels to the end
if (aLabel === '' && zLabel !== '') {
return 1;
} else if (aLabel !== '' && zLabel === '') {
return -1
}

// Sort labels alphabetically in the English locale
// We are intentionally overriding the locale because we do not want the sort to
// be affected by the machine's locale (be it a developer or CI environment)
return aLabel.localeCompare(zLabel, 'en', { numeric: true })
}

matchUtilities(
{
'@container': (value, { modifier }) => {
Expand Down Expand Up @@ -38,30 +68,20 @@ export = plugin(
},
{
values,
sort(aVariant, zVariant) {
let a = parseFloat(aVariant.value)
let z = parseFloat(zVariant.value)

if (a === null || z === null) return 0

// Sort values themselves regardless of unit
if (a - z !== 0) return a - z

let aLabel = aVariant.modifier ?? ''
let zLabel = zVariant.modifier ?? ''
sort,
}
)

// Explicitly move empty labels to the end
if (aLabel === '' && zLabel !== '') {
return 1
} else if (aLabel !== '' && zLabel === '') {
return -1
}
matchVariant(
'@max',
(value = '', { modifier }) => {
let parsed = parseValue(value)

// Sort labels alphabetically in the English locale
// We are intentionally overriding the locale because we do not want the sort to
// be affected by the machine's locale (be it a developer or CI environment)
return aLabel.localeCompare(zLabel, 'en', { numeric: true })
},
return parsed !== null ? `@container ${modifier ?? ''} (width < ${value})` : []
},
{
values,
sort,
}
)
},
Expand Down