repo
stringclasses
15 values
pull_number
int64
147
18.3k
instance_id
stringlengths
14
31
issue_numbers
sequencelengths
1
3
base_commit
stringlengths
40
40
patch
stringlengths
289
585k
test_patch
stringlengths
355
6.82M
problem_statement
stringlengths
25
49.4k
hints_text
stringlengths
0
58.9k
created_at
unknowndate
2014-08-08 22:09:38
2024-06-28 03:13:12
version
stringclasses
110 values
PASS_TO_PASS
sequencelengths
0
4.82k
FAIL_TO_PASS
sequencelengths
1
1.06k
language
stringclasses
4 values
image_urls
sequencelengths
0
4
website links
sequencelengths
0
4
tailwindlabs/tailwindcss
10,059
tailwindlabs__tailwindcss-10059
[ "10052" ]
40c0cbe272dab4904cbe9e2aaa200ebdb44a25fd
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -733,6 +733,8 @@ function* resolveMatches(candidate, context, original = candidate) { } for (let match of matches) { + let isValid = true + match[1].raws.tailwind = { ...match[1].raws.tailwind, candidate } // Apply final format selector @@ -742,7 +744,7 @@ function* resolveMatches(candidate, context, original = candidate) { container.walkRules((rule) => { if (inKeyframes(rule)) return - rule.selector = finalizeSelector(finalFormat, { + let selectorOptions = { selector: rule.selector, candidate: original, base: candidate @@ -751,11 +753,31 @@ function* resolveMatches(candidate, context, original = candidate) { isArbitraryVariant: match[0].isArbitraryVariant, context, - }) + } + + try { + rule.selector = finalizeSelector(finalFormat, selectorOptions) + } catch { + // The selector we produced is invalid + // This could be because: + // - A bug exists + // - A plugin introduced an invalid variant selector (ex: `addVariant('foo', '&;foo')`) + // - The user used an invalid arbitrary variant (ex: `[&;foo]:underline`) + // Either way the build will fail because of this + // We would rather that the build pass "silently" given that this could + // happen because of picking up invalid things when scanning content + // So we'll throw out the candidate instead + isValid = false + return false + } }) match[1] = container.nodes[0] } + if (!isValid) { + continue + } + yield match } }
diff --git a/tests/arbitrary-variants.test.js b/tests/arbitrary-variants.test.js --- a/tests/arbitrary-variants.test.js +++ b/tests/arbitrary-variants.test.js @@ -1099,3 +1099,47 @@ it('Arbitrary variants are ordered alphabetically', () => { `) }) }) + +it('Arbitrary variants support multiple attribute selectors', () => { + let config = { + content: [ + { + raw: html` <div class="[[data-foo='bar'][data-baz]_&]:underline"></div> `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + [data-foo='bar'][data-baz] .\[\[data-foo\=\'bar\'\]\[data-baz\]_\&\]\:underline { + text-decoration-line: underline; + } + `) + }) +}) + +it('Invalid arbitrary variants selectors should produce nothing instead of failing', () => { + let config = { + content: [ + { + raw: html` + <div class="[&;foo]:underline"></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css``) + }) +})
Fails to compile "expected opening square bracket" with two attribute selectors <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** Latest Tailwind v3.2.4, reproducible in live playground below. **Reproduction URL** https://play.tailwindcss.com/w66a9h6SsL **Describe your issue** The Tailwind compiler fails with `Expected an opening square bracket.` when parsing a second attribute selector after one with a value. The following code attempts to style the element when one of its parents has two attributes. Checking for the presence of two attributes works flawlessly. Checking for the presence of one and the value of the second works great as well. Swapping the order of the attributes breaks the compiler. - βœ… `[data-beta][data-testid]` - βœ… `[data-beta][data-testid='test']` - ❌ `[data-testid='test'][data-beta]` ```html <ul data-testid="test" data-beta> <li class="[[data-beta][data-testid]_&]:bg-violet-500"> This works </li> <li class="[[data-beta][data-testid='test']_&]:bg-violet-500"> This works </li> <li class="[[data-testid='test'][data-beta]_&]:bg-violet-500"> This breaks </li> </ul> ```
"2022-12-12T15:55:19Z"
3.2
[]
[ "tests/arbitrary-variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/w66a9h6SsL" ]
tailwindlabs/tailwindcss
10,212
tailwindlabs__tailwindcss-10212
[ "10180" ]
5594c3bec95e1db985e49f6836b51d7046d59579
diff --git a/src/lib/defaultExtractor.js b/src/lib/defaultExtractor.js --- a/src/lib/defaultExtractor.js +++ b/src/lib/defaultExtractor.js @@ -28,8 +28,14 @@ function* buildRegExps(context) { : '' let utility = regex.any([ - // Arbitrary properties - /\[[^\s:'"`]+:[^\s]+\]/, + // Arbitrary properties (without square brackets) + /\[[^\s:'"`]+:[^\s\[\]]+\]/, + + // Arbitrary properties with balanced square brackets + // This is a targeted fix to continue to allow theme() + // with square brackets to work in arbitrary properties + // while fixing a problem with the regex matching too much + /\[[^\s:'"`]+:[^\s]+?\[[^\s]+?\][^\s]+?\]/, // Utilities regex.pattern([
diff --git a/tests/default-extractor.test.js b/tests/default-extractor.test.js --- a/tests/default-extractor.test.js +++ b/tests/default-extractor.test.js @@ -488,3 +488,11 @@ test('ruby percent string array', () => { expect(extractions).toContain(`text-[#bada55]`) }) + +test('arbitrary properties followed by square bracketed stuff', () => { + let extractions = defaultExtractor( + '<div class="h-16 items-end border border-white [display:inherit]">[foo]</div>' + ) + + expect(extractions).toContain(`[display:inherit]`) +})
Div content with brackets `[]` prevents arbitrary class from being generated ## This works: https://play.tailwindcss.com/0VLICQ8oUW <img width="810" alt="image" src="https://user-images.githubusercontent.com/111561/209682078-7e43a107-52ff-4006-8c37-ec44414abe12.png"> ## This does not work: https://play.tailwindcss.com/5KJf7xDKv6 <img width="821" alt="image" src="https://user-images.githubusercontent.com/111561/209682172-de1dcaaa-6e69-429b-907f-840691e35ceb.png">
Hey @tordans I am trying to understand the problem statement. If you elaborate about the project and the problem it will be helpful for me cause I am new in this project and I am trying to contribute in this project. I did check through your code and didnt find any issue just pust a space before ending "
"2023-01-02T14:38:18Z"
3.2
[]
[ "tests/default-extractor.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/111561/209682078-7e43a107-52ff-4006-8c37-ec44414abe12.png", "https://user-images.githubusercontent.com/111561/209682172-de1dcaaa-6e69-429b-907f-840691e35ceb.png" ]
[ "https://play.tailwindcss.com/0VLICQ8oUW", "https://play.tailwindcss.com/5KJf7xDKv6" ]
tailwindlabs/tailwindcss
10,214
tailwindlabs__tailwindcss-10214
[ "10125" ]
2b885ef2525988758761cc3535383d8d1dc260bf
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -201,6 +201,7 @@ function applyVariant(variant, matches, context) { } if (context.variantMap.has(variant)) { + let isArbitraryVariant = isArbitraryValue(variant) let variantFunctionTuples = context.variantMap.get(variant).slice() let result = [] @@ -262,7 +263,10 @@ function applyVariant(variant, matches, context) { clone.append(wrapper) }, format(selectorFormat) { - collectedFormats.push(selectorFormat) + collectedFormats.push({ + format: selectorFormat, + isArbitraryVariant, + }) }, args, }) @@ -288,7 +292,10 @@ function applyVariant(variant, matches, context) { } if (typeof ruleWithVariant === 'string') { - collectedFormats.push(ruleWithVariant) + collectedFormats.push({ + format: ruleWithVariant, + isArbitraryVariant, + }) } if (ruleWithVariant === null) { @@ -329,7 +336,10 @@ function applyVariant(variant, matches, context) { // modified (by plugin): .foo .foo\\:markdown > p // rebuiltBase (internal): .foo\\:markdown > p // format: .foo & - collectedFormats.push(modified.replace(rebuiltBase, '&')) + collectedFormats.push({ + format: modified.replace(rebuiltBase, '&'), + isArbitraryVariant, + }) rule.selector = before }) } @@ -349,7 +359,6 @@ function applyVariant(variant, matches, context) { Object.assign(args, context.variantOptions.get(variant)) ), collectedFormats: (meta.collectedFormats ?? []).concat(collectedFormats), - isArbitraryVariant: isArbitraryValue(variant), }, clone.nodes[0], ] @@ -733,48 +742,15 @@ function* resolveMatches(candidate, context, original = candidate) { } for (let match of matches) { - let isValid = true - match[1].raws.tailwind = { ...match[1].raws.tailwind, candidate } // Apply final format selector - if (match[0].collectedFormats) { - let finalFormat = formatVariantSelector('&', ...match[0].collectedFormats) - let container = postcss.root({ nodes: [match[1].clone()] }) - container.walkRules((rule) => { - if (inKeyframes(rule)) return - - let selectorOptions = { - selector: rule.selector, - candidate: original, - base: candidate - .split(new RegExp(`\\${context?.tailwindConfig?.separator ?? ':'}(?![^[]*\\])`)) - .pop(), - isArbitraryVariant: match[0].isArbitraryVariant, - - context, - } - - try { - rule.selector = finalizeSelector(finalFormat, selectorOptions) - } catch { - // The selector we produced is invalid - // This could be because: - // - A bug exists - // - A plugin introduced an invalid variant selector (ex: `addVariant('foo', '&;foo')`) - // - The user used an invalid arbitrary variant (ex: `[&;foo]:underline`) - // Either way the build will fail because of this - // We would rather that the build pass "silently" given that this could - // happen because of picking up invalid things when scanning content - // So we'll throw out the candidate instead - isValid = false - return false - } - }) - match[1] = container.nodes[0] - } + match = applyFinalFormat(match, { context, candidate, original }) - if (!isValid) { + // Skip rules with invalid selectors + // This will cause the candidate to be added to the "not class" + // cache skipping it entirely for future builds + if (match === null) { continue } @@ -783,6 +759,62 @@ function* resolveMatches(candidate, context, original = candidate) { } } +function applyFinalFormat(match, { context, candidate, original }) { + if (!match[0].collectedFormats) { + return match + } + + let isValid = true + let finalFormat + + try { + finalFormat = formatVariantSelector(match[0].collectedFormats, { + context, + candidate, + }) + } catch { + // The format selector we produced is invalid + // This could be because: + // - A bug exists + // - A plugin introduced an invalid variant selector (ex: `addVariant('foo', '&;foo')`) + // - The user used an invalid arbitrary variant (ex: `[&;foo]:underline`) + // Either way the build will fail because of this + // We would rather that the build pass "silently" given that this could + // happen because of picking up invalid things when scanning content + // So we'll throw out the candidate instead + + return null + } + + let container = postcss.root({ nodes: [match[1].clone()] }) + + container.walkRules((rule) => { + if (inKeyframes(rule)) { + return + } + + try { + rule.selector = finalizeSelector(rule.selector, finalFormat, { + candidate: original, + context, + }) + } catch { + // If this selector is invalid we also want to skip it + // But it's likely that being invalid here means there's a bug in a plugin rather than too loosely matching content + isValid = false + return false + } + }) + + if (!isValid) { + return null + } + + match[1] = container.nodes[0] + + return match +} + function inKeyframes(rule) { return rule.parent && rule.parent.type === 'atrule' && rule.parent.name === 'keyframes' } diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -1080,20 +1080,38 @@ function registerPlugins(plugins, context) { }) } - let result = formatStrings.map((formatString) => - finalizeSelector(formatVariantSelector('&', ...formatString), { - selector: `.${candidate}`, - candidate, - context, - isArbitraryVariant: !(value in (options.values ?? {})), - }) + let isArbitraryVariant = !(value in (options.values ?? {})) + + formatStrings = formatStrings.map((format) => + format.map((str) => ({ + format: str, + isArbitraryVariant, + })) + ) + + manualFormatStrings = manualFormatStrings.map((format) => ({ + format, + isArbitraryVariant, + })) + + let opts = { + candidate, + context, + } + + let result = formatStrings.map((formats) => + finalizeSelector(`.${candidate}`, formatVariantSelector(formats, opts), opts) .replace(`.${candidate}`, '&') .replace('{ & }', '') .trim() ) if (manualFormatStrings.length > 0) { - result.push(formatVariantSelector('&', ...manualFormatStrings)) + result.push( + formatVariantSelector(manualFormatStrings, opts) + .toString() + .replace(`.${candidate}`, '&') + ) } return result diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -3,30 +3,57 @@ import unescape from 'postcss-selector-parser/dist/util/unesc' import escapeClassName from '../util/escapeClassName' import prefixSelector from '../util/prefixSelector' +/** @typedef {import('postcss-selector-parser').Root} Root */ +/** @typedef {import('postcss-selector-parser').Selector} Selector */ +/** @typedef {import('postcss-selector-parser').Pseudo} Pseudo */ +/** @typedef {import('postcss-selector-parser').Node} Node */ + +/** @typedef {{format: string, isArbitraryVariant: boolean}[]} RawFormats */ +/** @typedef {import('postcss-selector-parser').Root} ParsedFormats */ +/** @typedef {RawFormats | ParsedFormats} AcceptedFormats */ + let MERGE = ':merge' -let PARENT = '&' - -export let selectorFunctions = new Set([MERGE]) - -export function formatVariantSelector(current, ...others) { - for (let other of others) { - let incomingValue = resolveFunctionArgument(other, MERGE) - if (incomingValue !== null) { - let existingValue = resolveFunctionArgument(current, MERGE, incomingValue) - if (existingValue !== null) { - let existingTarget = `${MERGE}(${incomingValue})` - let splitIdx = other.indexOf(existingTarget) - let addition = other.slice(splitIdx + existingTarget.length).split(' ')[0] - - current = current.replace(existingTarget, existingTarget + addition) - continue - } + +/** + * @param {RawFormats} formats + * @param {{context: any, candidate: string, base: string | null}} options + * @returns {ParsedFormats | null} + */ +export function formatVariantSelector(formats, { context, candidate }) { + let prefix = context?.tailwindConfig.prefix ?? '' + + // Parse the format selector into an AST + let parsedFormats = formats.map((format) => { + let ast = selectorParser().astSync(format.format) + + return { + ...format, + ast: format.isArbitraryVariant ? ast : prefixSelector(prefix, ast), } + }) - current = other.replace(PARENT, current) + // We start with the candidate selector + let formatAst = selectorParser.root({ + nodes: [ + selectorParser.selector({ + nodes: [selectorParser.className({ value: escapeClassName(candidate) })], + }), + ], + }) + + // And iteratively merge each format selector into the candidate selector + for (let { ast } of parsedFormats) { + // 1. Handle :merge() special pseudo-class + ;[formatAst, ast] = handleMergePseudo(formatAst, ast) + + // 2. Merge the format selector into the current selector AST + ast.walkNesting((nesting) => nesting.replaceWith(...formatAst.nodes[0].nodes)) + + // 3. Keep going! + formatAst = ast } - return current + return formatAst } /** @@ -35,11 +62,11 @@ export function formatVariantSelector(current, ...others) { * Technically :is(), :not(), :has(), etc… can have combinators but those are nested * inside the relevant node and won't be picked up so they're fine to ignore * - * @param {import('postcss-selector-parser').Node} node - * @returns {import('postcss-selector-parser').Node[]} + * @param {Node} node + * @returns {Node[]} **/ function simpleSelectorForNode(node) { - /** @type {import('postcss-selector-parser').Node[]} */ + /** @type {Node[]} */ let nodes = [] // Walk backwards until we hit a combinator node (or the start) @@ -60,8 +87,8 @@ function simpleSelectorForNode(node) { * Resorts the nodes in a selector to ensure they're in the correct order * Tags go before classes, and pseudo classes go after classes * - * @param {import('postcss-selector-parser').Selector} sel - * @returns {import('postcss-selector-parser').Selector} + * @param {Selector} sel + * @returns {Selector} **/ function resortSelector(sel) { sel.sort((a, b) => { @@ -81,6 +108,18 @@ function resortSelector(sel) { return sel } +/** + * Remove extraneous selectors that do not include the base class/candidate + * + * Example: + * Given the utility `.a, .b { color: red}` + * Given the candidate `sm:b` + * + * The final selector should be `.sm\:b` and not `.a, .sm\:b` + * + * @param {Selector} ast + * @param {string} base + */ function eliminateIrrelevantSelectors(sel, base) { let hasClassesMatchingCandidate = false @@ -104,41 +143,26 @@ function eliminateIrrelevantSelectors(sel, base) { // TODO: Can we do this for :matches, :is, and :where? } -export function finalizeSelector( - format, - { - selector, - candidate, - context, - isArbitraryVariant, - - // Split by the separator, but ignore the separator inside square brackets: - // - // E.g.: dark:lg:hover:[paint-order:markers] - // ┬ ┬ ┬ ┬ - // β”‚ β”‚ β”‚ ╰── We will not split here - // ╰──┴─────┴─────────────── We will split here - // - base = candidate - .split(new RegExp(`\\${context?.tailwindConfig?.separator ?? ':'}(?![^[]*\\])`)) - .pop(), - } -) { - let ast = selectorParser().astSync(selector) - - // We explicitly DO NOT prefix classes in arbitrary variants - if (context?.tailwindConfig?.prefix && !isArbitraryVariant) { - format = prefixSelector(context.tailwindConfig.prefix, format) - } - - format = format.replace(PARENT, `.${escapeClassName(candidate)}`) - - let formatAst = selectorParser().astSync(format) +/** + * @param {string} current + * @param {AcceptedFormats} formats + * @param {{context: any, candidate: string, base: string | null}} options + * @returns {string} + */ +export function finalizeSelector(current, formats, { context, candidate, base }) { + let separator = context?.tailwindConfig?.separator ?? ':' + + // Split by the separator, but ignore the separator inside square brackets: + // + // E.g.: dark:lg:hover:[paint-order:markers] + // ┬ ┬ ┬ ┬ + // β”‚ β”‚ β”‚ ╰── We will not split here + // ╰──┴─────┴─────────────── We will split here + // + base = base ?? candidate.split(new RegExp(`\\${separator}(?![^[]*\\])`)).pop() - // Remove extraneous selectors that do not include the base class/candidate being matched against - // For example if we have a utility defined `.a, .b { color: red}` - // And the formatted variant is sm:b then we want the final selector to be `.sm\:b` and not `.a, .sm\:b` - ast.each((sel) => eliminateIrrelevantSelectors(sel, base)) + // Parse the selector into an AST + let selector = selectorParser().astSync(current) // Normalize escaped classes, e.g.: // @@ -151,18 +175,31 @@ export function finalizeSelector( // base in selector: bg-\\[rgb\\(255\\,0\\,0\\)\\] // escaped base: bg-\\[rgb\\(255\\2c 0\\2c 0\\)\\] // - ast.walkClasses((node) => { + selector.walkClasses((node) => { if (node.raws && node.value.includes(base)) { node.raws.value = escapeClassName(unescape(node.raws.value)) } }) + // Remove extraneous selectors that do not include the base candidate + selector.each((sel) => eliminateIrrelevantSelectors(sel, base)) + + // If there are no formats that means there were no variants added to the candidate + // so we can just return the selector as-is + let formatAst = Array.isArray(formats) + ? formatVariantSelector(formats, { context, candidate }) + : formats + + if (formatAst === null) { + return selector.toString() + } + let simpleStart = selectorParser.comment({ value: '/*__simple__*/' }) let simpleEnd = selectorParser.comment({ value: '/*__simple__*/' }) // We can safely replace the escaped base now, since the `base` section is // now in a normalized escaped value. - ast.walkClasses((node) => { + selector.walkClasses((node) => { if (node.value !== base) { return } @@ -200,47 +237,86 @@ export function finalizeSelector( simpleEnd.remove() }) - // This will make sure to move pseudo's to the correct spot (the end for - // pseudo elements) because otherwise the selector will never work - // anyway. - // - // E.g.: - // - `before:hover:text-center` would result in `.before\:hover\:text-center:hover::before` - // - `hover:before:text-center` would result in `.hover\:before\:text-center:hover::before` - // - // `::before:hover` doesn't work, which means that we can make it work for you by flipping the order. - function collectPseudoElements(selector) { - let nodes = [] - - for (let node of selector.nodes) { - if (isPseudoElement(node)) { - nodes.push(node) - selector.removeChild(node) - } - - if (node?.nodes) { - nodes.push(...collectPseudoElements(node)) - } + // Remove unnecessary pseudo selectors that we used as placeholders + selector.walkPseudos((p) => { + if (p.value === MERGE) { + p.replaceWith(p.nodes) } + }) - return nodes - } - - // Remove unnecessary pseudo selectors that we used as placeholders - ast.each((selector) => { - selector.walkPseudos((p) => { - if (selectorFunctions.has(p.value)) { - p.replaceWith(p.nodes) - } - }) - - let pseudoElements = collectPseudoElements(selector) + // Move pseudo elements to the end of the selector (if necessary) + selector.each((sel) => { + let pseudoElements = collectPseudoElements(sel) if (pseudoElements.length > 0) { - selector.nodes.push(pseudoElements.sort(sortSelector)) + sel.nodes.push(pseudoElements.sort(sortSelector)) + } + }) + + return selector.toString() +} + +/** + * + * @param {Selector} selector + * @param {Selector} format + */ +export function handleMergePseudo(selector, format) { + /** @type {{pseudo: Pseudo, value: string}[]} */ + let merges = [] + + // Find all :merge() pseudo-classes in `selector` + selector.walkPseudos((pseudo) => { + if (pseudo.value === MERGE) { + merges.push({ + pseudo, + value: pseudo.nodes[0].toString(), + }) } }) - return ast.toString() + // Find all :merge() "attachments" in `format` and attach them to the matching selector in `selector` + format.walkPseudos((pseudo) => { + if (pseudo.value !== MERGE) { + return + } + + let value = pseudo.nodes[0].toString() + + // Does `selector` contain a :merge() pseudo-class with the same value? + let existing = merges.find((merge) => merge.value === value) + + // Nope so there's nothing to do + if (!existing) { + return + } + + // Everything after `:merge()` up to the next combinator is what is attached to the merged selector + let attachments = [] + let next = pseudo.next() + while (next && next.type !== 'combinator') { + attachments.push(next) + next = next.next() + } + + let combinator = next + + existing.pseudo.parent.insertAfter( + existing.pseudo, + selectorParser.selector({ nodes: attachments.map((node) => node.clone()) }) + ) + + pseudo.remove() + attachments.forEach((node) => node.remove()) + + // What about this case: + // :merge(.group):focus > & + // :merge(.group):hover & + if (combinator && combinator.type === 'combinator') { + combinator.remove() + } + }) + + return [selector, format] } // Note: As a rule, double colons (::) should be used instead of a single colon @@ -263,6 +339,37 @@ let pseudoElementExceptions = [ '::-webkit-resizer', ] +/** + * This will make sure to move pseudo's to the correct spot (the end for + * pseudo elements) because otherwise the selector will never work + * anyway. + * + * E.g.: + * - `before:hover:text-center` would result in `.before\:hover\:text-center:hover::before` + * - `hover:before:text-center` would result in `.hover\:before\:text-center:hover::before` + * + * `::before:hover` doesn't work, which means that we can make it work for you by flipping the order. + * + * @param {Selector} selector + **/ +function collectPseudoElements(selector) { + /** @type {Node[]} */ + let nodes = [] + + for (let node of selector.nodes) { + if (isPseudoElement(node)) { + nodes.push(node) + selector.removeChild(node) + } + + if (node?.nodes) { + nodes.push(...collectPseudoElements(node)) + } + } + + return nodes +} + // This will make sure to move pseudo's to the correct spot (the end for // pseudo elements) because otherwise the selector will never work // anyway. @@ -303,28 +410,3 @@ function isPseudoElement(node) { return node.value.startsWith('::') || pseudoElementsBC.includes(node.value) } - -function resolveFunctionArgument(haystack, needle, arg) { - let startIdx = haystack.indexOf(arg ? `${needle}(${arg})` : needle) - if (startIdx === -1) return null - - // Start inside the `(` - startIdx += needle.length + 1 - - let target = '' - let count = 0 - - for (let char of haystack.slice(startIdx)) { - if (char !== '(' && char !== ')') { - target += char - } else if (char === '(') { - target += char - count++ - } else if (char === ')') { - if (--count < 0) break // unbalanced - target += char - } - } - - return target -} diff --git a/src/util/prefixSelector.js b/src/util/prefixSelector.js --- a/src/util/prefixSelector.js +++ b/src/util/prefixSelector.js @@ -1,14 +1,32 @@ import parser from 'postcss-selector-parser' +/** + * @template {string | import('postcss-selector-parser').Root} T + * + * Prefix all classes in the selector with the given prefix + * + * It can take either a string or a selector AST and will return the same type + * + * @param {string} prefix + * @param {T} selector + * @param {boolean} prependNegative + * @returns {T} + */ export default function (prefix, selector, prependNegative = false) { - return parser((selectors) => { - selectors.walkClasses((classSelector) => { - let baseClass = classSelector.value - let shouldPlaceNegativeBeforePrefix = prependNegative && baseClass.startsWith('-') - - classSelector.value = shouldPlaceNegativeBeforePrefix - ? `-${prefix}${baseClass.slice(1)}` - : `${prefix}${baseClass}` - }) - }).processSync(selector) + if (prefix === '') { + return selector + } + + let ast = typeof selector === 'string' ? parser().astSync(selector) : selector + + ast.walkClasses((classSelector) => { + let baseClass = classSelector.value + let shouldPlaceNegativeBeforePrefix = prependNegative && baseClass.startsWith('-') + + classSelector.value = shouldPlaceNegativeBeforePrefix + ? `-${prefix}${baseClass.slice(1)}` + : `${prefix}${baseClass}` + }) + + return typeof selector === 'string' ? ast.toString() : ast }
diff --git a/tests/arbitrary-variants.test.js b/tests/arbitrary-variants.test.js --- a/tests/arbitrary-variants.test.js +++ b/tests/arbitrary-variants.test.js @@ -542,6 +542,14 @@ test('classes in arbitrary variants should not be prefixed', () => { <div>should not be red</div> <div class="foo">should be red</div> </div> + <div class="hover:[&_.foo]:tw-text-red-400"> + <div>should not be red</div> + <div class="foo">should be red</div> + </div> + <div class="[&_.foo]:hover:tw-text-red-400"> + <div>should not be red</div> + <div class="foo">should be red</div> + </div> `, }, ], @@ -558,7 +566,14 @@ test('classes in arbitrary variants should not be prefixed', () => { --tw-text-opacity: 1; color: rgb(248 113 113 / var(--tw-text-opacity)); } - + .hover\:\[\&_\.foo\]\:tw-text-red-400 .foo:hover { + --tw-text-opacity: 1; + color: rgb(248 113 113 / var(--tw-text-opacity)); + } + .\[\&_\.foo\]\:hover\:tw-text-red-400:hover .foo { + --tw-text-opacity: 1; + color: rgb(248 113 113 / var(--tw-text-opacity)); + } .foo .\[\.foo_\&\]\:tw-text-red-400 { --tw-text-opacity: 1; color: rgb(248 113 113 / var(--tw-text-opacity)); diff --git a/tests/format-variant-selector.test.js b/tests/format-variant-selector.test.js --- a/tests/format-variant-selector.test.js +++ b/tests/format-variant-selector.test.js @@ -1,23 +1,24 @@ -import { formatVariantSelector, finalizeSelector } from '../src/util/formatVariantSelector' +import { finalizeSelector } from '../src/util/formatVariantSelector' it('should be possible to add a simple variant to a simple selector', () => { let selector = '.text-center' let candidate = 'hover:text-center' - let variants = ['&:hover'] + let formats = [{ format: '&:hover', isArbitraryVariant: false }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( - '.hover\\:text-center:hover' - ) + expect(finalizeSelector(selector, formats, { candidate })).toEqual('.hover\\:text-center:hover') }) it('should be possible to add a multiple simple variants to a simple selector', () => { let selector = '.text-center' let candidate = 'focus:hover:text-center' - let variants = ['&:hover', '&:focus'] + let formats = [ + { format: '&:hover', isArbitraryVariant: false }, + { format: '&:focus', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.focus\\:hover\\:text-center:hover:focus' ) }) @@ -26,9 +27,9 @@ it('should be possible to add a simple variant to a selector containing escaped let selector = '.bg-\\[rgba\\(0\\,0\\,0\\)\\]' let candidate = 'hover:bg-[rgba(0,0,0)]' - let variants = ['&:hover'] + let formats = [{ format: '&:hover', isArbitraryVariant: false }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:bg-\\[rgba\\(0\\2c 0\\2c 0\\)\\]:hover' ) }) @@ -37,9 +38,9 @@ it('should be possible to add a simple variant to a selector containing escaped let selector = '.bg-\\[rgba\\(0\\2c 0\\2c 0\\)\\]' let candidate = 'hover:bg-[rgba(0,0,0)]' - let variants = ['&:hover'] + let formats = [{ format: '&:hover', isArbitraryVariant: false }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:bg-\\[rgba\\(0\\2c 0\\2c 0\\)\\]:hover' ) }) @@ -48,9 +49,9 @@ it('should be possible to add a simple variant to a more complex selector', () = let selector = '.space-x-4 > :not([hidden]) ~ :not([hidden])' let candidate = 'hover:space-x-4' - let variants = ['&:hover'] + let formats = [{ format: '&:hover', isArbitraryVariant: false }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:space-x-4:hover > :not([hidden]) ~ :not([hidden])' ) }) @@ -59,9 +60,13 @@ it('should be possible to add multiple simple variants to a more complex selecto let selector = '.space-x-4 > :not([hidden]) ~ :not([hidden])' let candidate = 'disabled:focus:hover:space-x-4' - let variants = ['&:hover', '&:focus', '&:disabled'] + let formats = [ + { format: '&:hover', isArbitraryVariant: false }, + { format: '&:focus', isArbitraryVariant: false }, + { format: '&:disabled', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.disabled\\:focus\\:hover\\:space-x-4:hover:focus:disabled > :not([hidden]) ~ :not([hidden])' ) }) @@ -70,9 +75,9 @@ it('should be possible to add a single merge variant to a simple selector', () = let selector = '.text-center' let candidate = 'group-hover:text-center' - let variants = [':merge(.group):hover &'] + let formats = [{ format: ':merge(.group):hover &', isArbitraryVariant: false }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .group-hover\\:text-center' ) }) @@ -81,9 +86,12 @@ it('should be possible to add multiple merge variants to a simple selector', () let selector = '.text-center' let candidate = 'group-focus:group-hover:text-center' - let variants = [':merge(.group):hover &', ':merge(.group):focus &'] + let formats = [ + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: ':merge(.group):focus &', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:focus:hover .group-focus\\:group-hover\\:text-center' ) }) @@ -92,9 +100,9 @@ it('should be possible to add a single merge variant to a more complex selector' let selector = '.space-x-4 ~ :not([hidden]) ~ :not([hidden])' let candidate = 'group-hover:space-x-4' - let variants = [':merge(.group):hover &'] + let formats = [{ format: ':merge(.group):hover &', isArbitraryVariant: false }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .group-hover\\:space-x-4 ~ :not([hidden]) ~ :not([hidden])' ) }) @@ -103,9 +111,12 @@ it('should be possible to add multiple merge variants to a more complex selector let selector = '.space-x-4 ~ :not([hidden]) ~ :not([hidden])' let candidate = 'group-focus:group-hover:space-x-4' - let variants = [':merge(.group):hover &', ':merge(.group):focus &'] + let formats = [ + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: ':merge(.group):focus &', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:focus:hover .group-focus\\:group-hover\\:space-x-4 ~ :not([hidden]) ~ :not([hidden])' ) }) @@ -114,9 +125,12 @@ it('should be possible to add multiple unique merge variants to a simple selecto let selector = '.text-center' let candidate = 'peer-focus:group-hover:text-center' - let variants = [':merge(.group):hover &', ':merge(.peer):focus ~ &'] + let formats = [ + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: ':merge(.peer):focus ~ &' }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.peer:focus ~ .group:hover .peer-focus\\:group-hover\\:text-center' ) }) @@ -125,37 +139,41 @@ it('should be possible to add multiple unique merge variants to a simple selecto let selector = '.text-center' let candidate = 'group-hover:peer-focus:text-center' - let variants = [':merge(.peer):focus ~ &', ':merge(.group):hover &'] + let formats = [ + { format: ':merge(.peer):focus ~ &', isArbitraryVariant: false }, + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .peer:focus ~ .group-hover\\:peer-focus\\:text-center' ) }) it('should be possible to use multiple :merge() calls with different "arguments"', () => { - let result = '&' - result = formatVariantSelector(result, ':merge(.group):hover &') - expect(result).toEqual(':merge(.group):hover &') - - result = formatVariantSelector(result, ':merge(.peer):hover ~ &') - expect(result).toEqual(':merge(.peer):hover ~ :merge(.group):hover &') - - result = formatVariantSelector(result, ':merge(.group):focus &') - expect(result).toEqual(':merge(.peer):hover ~ :merge(.group):focus:hover &') + let selector = '.foo' + let candidate = 'peer-focus:group-focus:peer-hover:group-hover:foo' + + let formats = [ + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: ':merge(.peer):hover ~ &', isArbitraryVariant: false }, + { format: ':merge(.group):focus &', isArbitraryVariant: false }, + { format: ':merge(.peer):focus ~ &', isArbitraryVariant: false }, + ] - result = formatVariantSelector(result, ':merge(.peer):focus ~ &') - expect(result).toEqual(':merge(.peer):focus:hover ~ :merge(.group):focus:hover &') + expect(finalizeSelector(selector, formats, { candidate })).toEqual( + '.peer:focus:hover ~ .group:focus:hover .peer-focus\\:group-focus\\:peer-hover\\:group-hover\\:foo' + ) }) it('group hover and prose headings combination', () => { let selector = '.text-center' let candidate = 'group-hover:prose-headings:text-center' - let variants = [ - ':where(&) :is(h1, h2, h3, h4)', // Prose Headings - ':merge(.group):hover &', // Group Hover + let formats = [ + { format: ':where(&) :is(h1, h2, h3, h4)', isArbitraryVariant: false }, // Prose Headings + { format: ':merge(.group):hover &', isArbitraryVariant: false }, // Group Hover ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover :where(.group-hover\\:prose-headings\\:text-center) :is(h1, h2, h3, h4)' ) }) @@ -163,12 +181,12 @@ it('group hover and prose headings combination', () => { it('group hover and prose headings combination flipped', () => { let selector = '.text-center' let candidate = 'prose-headings:group-hover:text-center' - let variants = [ - ':merge(.group):hover &', // Group Hover - ':where(&) :is(h1, h2, h3, h4)', // Prose Headings + let formats = [ + { format: ':merge(.group):hover &', isArbitraryVariant: false }, // Group Hover + { format: ':where(&) :is(h1, h2, h3, h4)', isArbitraryVariant: false }, // Prose Headings ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( ':where(.group:hover .prose-headings\\:group-hover\\:text-center) :is(h1, h2, h3, h4)' ) }) @@ -176,28 +194,74 @@ it('group hover and prose headings combination flipped', () => { it('should be possible to handle a complex utility', () => { let selector = '.space-x-4 > :not([hidden]) ~ :not([hidden])' let candidate = 'peer-disabled:peer-first-child:group-hover:group-focus:focus:hover:space-x-4' - let variants = [ - '&:hover', // Hover - '&:focus', // Focus - ':merge(.group):focus &', // Group focus - ':merge(.group):hover &', // Group hover - ':merge(.peer):first-child ~ &', // Peer first-child - ':merge(.peer):disabled ~ &', // Peer disabled + let formats = [ + { format: '&:hover', isArbitraryVariant: false }, // Hover + { format: '&:focus', isArbitraryVariant: false }, // Focus + { format: ':merge(.group):focus &', isArbitraryVariant: false }, // Group focus + { format: ':merge(.group):hover &', isArbitraryVariant: false }, // Group hover + { format: ':merge(.peer):first-child ~ &', isArbitraryVariant: false }, // Peer first-child + { format: ':merge(.peer):disabled ~ &', isArbitraryVariant: false }, // Peer disabled ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.peer:disabled:first-child ~ .group:hover:focus .peer-disabled\\:peer-first-child\\:group-hover\\:group-focus\\:focus\\:hover\\:space-x-4:hover:focus > :not([hidden]) ~ :not([hidden])' ) }) +it('should match base utilities that are prefixed', () => { + let context = { tailwindConfig: { prefix: 'tw-' } } + let selector = '.tw-text-center' + let candidate = 'tw-text-center' + let formats = [] + + expect(finalizeSelector(selector, formats, { candidate, context })).toEqual('.tw-text-center') +}) + +it('should prefix classes from variants', () => { + let context = { tailwindConfig: { prefix: 'tw-' } } + let selector = '.tw-text-center' + let candidate = 'foo:tw-text-center' + let formats = [{ format: '.foo &', isArbitraryVariant: false }] + + expect(finalizeSelector(selector, formats, { candidate, context })).toEqual( + '.tw-foo .foo\\:tw-text-center' + ) +}) + +it('should not prefix classes from arbitrary variants', () => { + let context = { tailwindConfig: { prefix: 'tw-' } } + let selector = '.tw-text-center' + let candidate = '[.foo_&]:tw-text-center' + let formats = [{ format: '.foo &', isArbitraryVariant: true }] + + expect(finalizeSelector(selector, formats, { candidate, context })).toEqual( + '.foo .\\[\\.foo_\\&\\]\\:tw-text-center' + ) +}) + +it('Merged selectors with mixed combinators uses the first one', () => { + // This isn't explicitly specced behavior but it is how it works today + + let selector = '.text-center' + let candidate = 'text-center' + let formats = [ + { format: ':merge(.group):focus > &', isArbitraryVariant: true }, + { format: ':merge(.group):hover &', isArbitraryVariant: true }, + ] + + expect(finalizeSelector(selector, formats, { candidate })).toEqual( + '.group:hover:focus > .text-center' + ) +}) + describe('real examples', () => { it('example a', () => { let selector = '.placeholder-red-500::placeholder' let candidate = 'hover:placeholder-red-500' - let variants = ['&:hover'] + let formats = [{ format: '&:hover', isArbitraryVariant: false }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:placeholder-red-500:hover::placeholder' ) }) @@ -206,9 +270,12 @@ describe('real examples', () => { let selector = '.space-x-4 > :not([hidden]) ~ :not([hidden])' let candidate = 'group-hover:hover:space-x-4' - let variants = ['&:hover', ':merge(.group):hover &'] + let formats = [ + { format: '&:hover', isArbitraryVariant: false }, + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .group-hover\\:hover\\:space-x-4:hover > :not([hidden]) ~ :not([hidden])' ) }) @@ -217,9 +284,12 @@ describe('real examples', () => { let selector = '.text-center' let candidate = 'dark:group-hover:text-center' - let variants = [':merge(.group):hover &', '.dark &'] + let formats = [ + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: '.dark &', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.dark .group:hover .dark\\:group-hover\\:text-center' ) }) @@ -228,9 +298,12 @@ describe('real examples', () => { let selector = '.text-center' let candidate = 'group-hover:dark:text-center' - let variants = ['.dark &', ':merge(.group):hover &'] + let formats = [ + { format: '.dark &' }, + { format: ':merge(.group):hover &', isArbitraryVariant: false }, + ] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .dark .group-hover\\:dark\\:text-center' ) }) @@ -240,9 +313,9 @@ describe('real examples', () => { let selector = '.text-center' let candidate = 'hover:prose-headings:text-center' - let variants = [':where(&) :is(h1, h2, h3, h4)', '&:hover'] + let formats = [{ format: ':where(&) :is(h1, h2, h3, h4)' }, { format: '&:hover' }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( ':where(.hover\\:prose-headings\\:text-center) :is(h1, h2, h3, h4):hover' ) }) @@ -251,9 +324,9 @@ describe('real examples', () => { let selector = '.text-center' let candidate = 'prose-headings:hover:text-center' - let variants = ['&:hover', ':where(&) :is(h1, h2, h3, h4)'] + let formats = [{ format: '&:hover' }, { format: ':where(&) :is(h1, h2, h3, h4)' }] - expect(finalizeSelector(formatVariantSelector(...variants), { selector, candidate })).toEqual( + expect(finalizeSelector(selector, formats, { candidate })).toEqual( ':where(.prose-headings\\:hover\\:text-center:hover) :is(h1, h2, h3, h4)' ) }) @@ -274,8 +347,7 @@ describe('pseudo elements', () => { ${':where(&::before) :is(h1, h2, h3, h4)'} | ${':where(&) :is(h1, h2, h3, h4)::before'} ${':where(&::file-selector-button) :is(h1, h2, h3, h4)'} | ${':where(&::file-selector-button) :is(h1, h2, h3, h4)'} `('should translate "$before" into "$after"', ({ before, after }) => { - let result = finalizeSelector(formatVariantSelector('&', before), { - selector: '.a', + let result = finalizeSelector('.a', [{ format: before, isArbitraryVariant: false }], { candidate: 'a', })
`prefix` option + `modifier` + `arbitrary variant`: extra prefix is generated for classes inside variant `prefix: "tw-",` + `hover:[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000]` generates: ```CSS .hover\:\[\&\.header-is-scrolled_\.menu-list_a\]\:tw-text-\[\#FF0000\].tw-header-is-scrolled .tw-menu-list a:hover { --tw-text-opacity: 1; color: rgb(255 0 0 / var(--tw-text-opacity)); } ``` expected result: ```CSS .hover\:\[\&\.header-is-scrolled_\.menu-list_a\]\:tw-text-\[\#FF0000\].header-is-scrolled .menu-list a:hover { --tw-text-opacity: 1; color: rgb(255 0 0 / var(--tw-text-opacity)); } ``` # [Tailwind Play Link](https://play.tailwindcss.com/kuo2fGhMiZ) ![image](https://user-images.githubusercontent.com/5171262/208573193-a916f1a3-0efc-4064-99a9-f9b33fa8de3f.png) ```HTML <div class="[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] header-is-scrolled"> <div class="menu-list"> <a href="#">abc<-</a> </div> </div> <div class="[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] header-is-scrolled"> <div class="tw-menu-list"> <a href="#">abc</a> </div> </div> <div class="[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] tw-header-is-scrolled"> <div class="menu-list"> <a href="#">abc</a> </div> </div> <div class="[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] tw-header-is-scrolled"> <div class="tw-menu-list"> <a href="#">abc</a> </div> </div> <div class="hover:[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] header-is-scrolled"> <div class="menu-list"> <a href="#">abc</a> </div> </div> <div class="hover:[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] header-is-scrolled"> <div class="tw-menu-list"> <a href="#">abc</a> </div> </div> <div class="hover:[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] tw-header-is-scrolled"> <div class="menu-list"> <a href="#">abc</a> </div> </div> <div class="hover:[&.header-is-scrolled_.menu-list_a]:tw-text-[#FF0000] tw-header-is-scrolled"> <div class="tw-menu-list"> <a href="#">abc<-</a> </div> </div> ```
I think I'm having a similar issue with group This is not working: ```html <div class="tw-group is-published"> <div class="tw-hidden group-[.is-published]:block"> Published </div> </div> ``` But found this is working: ```html <div class="tw-group tw-is-published"> <div class="tw-hidden group-[.is-published]:block"> Published </div> </div> ``` Is this the same issue?
"2023-01-02T20:13:22Z"
3.2
[]
[ "tests/format-variant-selector.test.js", "tests/arbitrary-variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/kuo2fGhMiZ" ]
tailwindlabs/tailwindcss
10,276
tailwindlabs__tailwindcss-10276
[ "10266" ]
7b3de616e9c26211c605d2378b9ceb4888a8cfa1
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -150,9 +150,13 @@ export let variantPlugins = { let variants = { group: (_, { modifier }) => - modifier ? [`:merge(.group\\/${modifier})`, ' &'] : [`:merge(.group)`, ' &'], + modifier + ? [`:merge(.group\\/${escapeClassName(modifier)})`, ' &'] + : [`:merge(.group)`, ' &'], peer: (_, { modifier }) => - modifier ? [`:merge(.peer\\/${modifier})`, ' ~ &'] : [`:merge(.peer)`, ' ~ &'], + modifier + ? [`:merge(.peer\\/${escapeClassName(modifier)})`, ' ~ &'] + : [`:merge(.peer)`, ' ~ &'], } for (let [name, fn] of Object.entries(variants)) { diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -54,32 +54,50 @@ function normalizeOptionTypes({ type = 'any', ...options }) { } function parseVariantFormatString(input) { - if (input.includes('{')) { - if (!isBalanced(input)) throw new Error(`Your { and } are unbalanced.`) - - return input - .split(/{(.*)}/gim) - .flatMap((line) => parseVariantFormatString(line)) - .filter(Boolean) - } - - return [input.trim()] -} - -function isBalanced(input) { - let count = 0 - - for (let char of input) { - if (char === '{') { - count++ + /** @type {string[]} */ + let parts = [] + + // When parsing whitespace around special characters are insignificant + // However, _inside_ of a variant they could be + // Because the selector could look like this + // @media { &[data-name="foo bar"] } + // This is why we do not skip whitespace + + let current = '' + let depth = 0 + + for (let idx = 0; idx < input.length; idx++) { + let char = input[idx] + + if (char === '\\') { + // Escaped characters are not special + current += '\\' + input[++idx] + } else if (char === '{') { + // Nested rule: start + ++depth + parts.push(current.trim()) + current = '' } else if (char === '}') { - if (--count < 0) { - return false // unbalanced + // Nested rule: end + if (--depth < 0) { + throw new Error(`Your { and } are unbalanced.`) } + + parts.push(current.trim()) + current = '' + } else { + // Normal character + current += char } } - return count === 0 + if (current.length > 0) { + parts.push(current.trim()) + } + + parts = parts.filter((part) => part !== '') + + return parts } function insertInto(list, value, { before = [] } = {}) {
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -689,3 +689,27 @@ it('Ring color utilities are generated when using respectDefaultRingColorOpacity `) }) }) + +it('should not crash when group names contain special characters', () => { + let config = { + future: { respectDefaultRingColorOpacity: true }, + content: [ + { + raw: '<div class="group/${id}"><div class="group-hover/${id}:visible"></div></div>', + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .group\/\$\{id\}:hover .group-hover\/\$\{id\}\:visible { + visibility: visible; + } + `) + }) +})
Dynamic nested groups names webpack error **What version of Tailwind CSS are you using?** I'm using the latest v3.2.4 **What build tool (or framework if it abstracts the build tool) are you using?** I'm using Next.js (v13.1.1) with Webpack (v5.74.0) **What version of Node.js are you using?** v18.12.1 **What browser are you using?** Chrome **What operating system are you using?** Windows **Reproduction URL** [CodeSandbox bug repoduction](https://codesandbox.io/p/sandbox/gifted-clarke-l6ite9?file=%2Fcomponents%2FContainer.tsx&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A27%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A27%7D%5D) **Describe your issue** I tried to assign names to groups by props dynamically on runtime but it failed to compile with this message: `./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[3].oneOf[11].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[3].oneOf[11].use[2]!./styles/globals.css TypeError: Cannot read properties of undefined (reading '5') at resolveMatches.next (<anonymous>) at Function.from (<anonymous>) at runMicrotasks (<anonymous>)` When i concatenate the `id` prop to a group with `+` operator this error don't come up but nested group doesn't work. I tried every plugin out there but nothing worked naming groups dynamically by props.
Hey! You can’t use concatenation or interpolation to create class names, as Tailwind generates all of your styles at build time and needs to be able to statically extract every class you’re using from your templates: https://tailwindcss.com/docs/content-configuration#dynamic-class-names It shouldn’t cause the build to fail or crash though, so will definitely look into that. Here's a super minimal reproduction that triggers the error even in Play: https://play.tailwindcss.com/s8ydiMPxcN Hey! Thanks for that information, i do a little change and it's working now. Going to keep this open so we can diagnose the crash πŸ‘πŸ»
"2023-01-09T16:08:52Z"
3.2
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
10,288
tailwindlabs__tailwindcss-10288
[ "10267" ]
b05918ab75370bfbecb3d556fec8846cbd285f0d
diff --git a/src/lib/offsets.js b/src/lib/offsets.js --- a/src/lib/offsets.js +++ b/src/lib/offsets.js @@ -13,6 +13,7 @@ import { remapBitfield } from './remap-bitfield.js' * @property {function | undefined} sort The sort function * @property {string|null} value The value we want to compare * @property {string|null} modifier The modifier that was used (if any) + * @property {bigint} variant The variant bitmask */ /** @@ -127,6 +128,8 @@ export class Offsets { * @returns {RuleOffset} */ applyVariantOffset(rule, variant, options) { + options.variant = variant.variants + return { ...rule, layer: 'variants', @@ -211,6 +214,19 @@ export class Offsets { for (let bOptions of b.options) { if (aOptions.id !== bOptions.id) continue if (!aOptions.sort || !bOptions.sort) continue + + let maxFnVariant = max([aOptions.variant, bOptions.variant]) ?? 0n + + // Create a mask of 0s from bits 1..N where N represents the mask of the Nth bit + let mask = ~(maxFnVariant | (maxFnVariant - 1n)) + let aVariantsAfterFn = a.variants & mask + let bVariantsAfterFn = b.variants & mask + + // If the variants the same, we _can_ sort them + if (aVariantsAfterFn !== bVariantsAfterFn) { + continue + } + let result = aOptions.sort( { value: aOptions.value,
diff --git a/tests/arbitrary-variants.test.js b/tests/arbitrary-variants.test.js --- a/tests/arbitrary-variants.test.js +++ b/tests/arbitrary-variants.test.js @@ -1158,3 +1158,201 @@ it('Invalid arbitrary variants selectors should produce nothing instead of faili expect(result.css).toMatchFormattedCss(css``) }) }) + +it('should output responsive variants + stacked variants in the right order', () => { + let config = { + content: [ + { + raw: html` + <div class="xl:p-1"></div> + <div class="md:[&_ul]:flex-row"></div> + <div class="[&_ul]:flex"></div> + <div class="[&_ul]:flex-col"></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + @media (min-width: 1280px) { + .xl\:p-1 { + padding: 0.25rem; + } + } + .\[\&_ul\]\:flex ul { + display: flex; + } + .\[\&_ul\]\:flex-col ul { + flex-direction: column; + } + @media (min-width: 768px) { + .md\:\[\&_ul\]\:flex-row ul { + flex-direction: row; + } + } + `) + }) +}) + +it('should sort multiple variant fns with normal variants between them', () => { + /** @type {string[]} */ + let lines = [] + + for (let a of [1, 2]) { + for (let b of [2, 1]) { + for (let c of [1, 2]) { + for (let d of [2, 1]) { + for (let e of [1, 2]) { + lines.push(`<div class="fred${a}:qux-[${b}]:baz${c}:bar-[${d}]:foo${e}:p-1"></div>`) + } + } + } + } + } + + // Fisher-Yates shuffle + for (let i = lines.length - 1; i > 0; i--) { + let j = Math.floor(Math.random() * i) + ;[lines[i], lines[j]] = [lines[j], lines[i]] + } + + let config = { + content: [ + { + raw: lines.join('\n'), + }, + ], + corePlugins: { preflight: false }, + plugins: [ + function ({ addVariant, matchVariant }) { + addVariant('foo1', '&[data-foo=1]') + addVariant('foo2', '&[data-foo=2]') + + matchVariant('bar', (value) => `&[data-bar=${value}]`, { + sort: (a, b) => b.value - a.value, + }) + + addVariant('baz1', '&[data-baz=1]') + addVariant('baz2', '&[data-baz=2]') + + matchVariant('qux', (value) => `&[data-qux=${value}]`, { + sort: (a, b) => b.value - a.value, + }) + + addVariant('fred1', '&[data-fred=1]') + addVariant('fred2', '&[data-fred=2]') + }, + ], + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .fred1\:qux-\[2\]\:baz1\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='1'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[2\]\:baz1\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='1'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[2\]\:baz1\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='1'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[2\]\:baz1\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='1'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[2\]\:baz2\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='2'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[2\]\:baz2\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='2'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[2\]\:baz2\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='2'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[2\]\:baz2\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='2'][data-qux='2'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz1\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='1'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz1\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='1'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz1\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='1'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz1\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='1'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz2\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='2'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz2\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='2'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz2\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='2'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred1\:qux-\[1\]\:baz2\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='2'][data-qux='1'][data-fred='1'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz1\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='1'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz1\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='1'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz1\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='1'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz1\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='1'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz2\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='2'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz2\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='2'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz2\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='2'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[2\]\:baz2\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='2'][data-qux='2'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz1\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='1'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz1\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='1'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz1\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='1'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz1\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='1'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz2\:bar-\[2\]\:foo1\:p-1[data-foo='1'][data-bar='2'][data-baz='2'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz2\:bar-\[2\]\:foo2\:p-1[data-foo='2'][data-bar='2'][data-baz='2'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz2\:bar-\[1\]\:foo1\:p-1[data-foo='1'][data-bar='1'][data-baz='2'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + .fred2\:qux-\[1\]\:baz2\:bar-\[1\]\:foo2\:p-1[data-foo='2'][data-bar='1'][data-baz='2'][data-qux='1'][data-fred='2'] { + padding: 0.25rem; + } + `) + }) +})
Order of CSS selectors is not correct with v3.2.x in specific scenarios **What version of Tailwind CSS are you using?** v3.2.4 **What build tool (or framework if it abstracts the build tool) are you using?** I use Vite. But I was able to reproduce the bug with `npx tailwindcss -i ./src/style.css -o ./dist/style.css`. **What version of Node.js are you using?** v16.16.0 **What browser are you using?** Chrome **What operating system are you using?** Windows 10 **Reproduction URL** https://replit.com/@rahulv3a/Tailwind-bug. Please click on `Run` to run the instance and `Show files` to view the code. I couldn't replicate it on play.tailwindcss.com because the files are required to be in a specific folder structure to reproduce. **Describe your issue** I have a PHP project with hundreds of files. Markup of various components (like menus) is generated by a CMS. As adding classes is not an option, I need to use `[&_]` on the containers to style them. Some layouts break when I update from `v3.1.x` to `v3.2.x` because the CSS order of certain selectors in the CSS generated is wrong. It occurs only when: - `[&_]` classes are used with `v3.2.x`. Everything works flawlessly with `v3.1.x`. - specific conditions are met. I'm still trying to figure them out. But I was able to create an isolated demo for you. **Example** In the following markup, the list items should be stacked in SM, and side-by-side from MD onwards. But they stay stacked in all viewports. ```html <div class="[&_ul]:flex [&_ul]:flex-col md:[&_ul]:flex-row"> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div> ``` Generated CSS: ```css @media (min-width: 768px) { .md\:\[\&_ul\]\:flex-row ul { flex-direction: row; } } .\[\&_ul\]\:flex ul { display: flex; } .\[\&_ul\]\:flex-col ul { flex-direction: column; } ``` Expected CSS: ```css .\[\&_ul\]\:flex ul { display: flex; } .\[\&_ul\]\:flex-col ul { flex-direction: column; } @media (min-width: 768px) { .md\:\[\&_ul\]\:flex-row ul { flex-direction: row; } } ``` **Demo** I created an online demo https://replit.com/@rahulv3a/Tailwind-bug of the example mentioned above. It contains only the code required to reproduce the bug. Please click on `Run` to run the instance and `Show files` to view the code. - Tailwind setup - v3.2.4 is being used. - `yarn tailwindcss -i ./src/style.css -o ./dist/style.css` is used to generate the CSS. - `preflight` is disabled to keep things simple. - Conditions - tailwind.config.js - `content` has `["./inc/**/*.php", "./templates/**/*.php"]`. - The order of the paths is important to replicate the issue. - inc/functions.php - It contains two comments. In my project, `./inc` contains hundreds of functions that are documented in detail. The comments contain words like contents, lowercase, etc. Tailwind creates classes for them which is fine. But for some reason unknown, the comments that start with `//` interfere with the order of CSS selectors. - template/01-required.php - I don't know why but this code is required to replicate the issue. - template/component.php - This file contains the actual code mentioned in the example above. **More examples** Here are some more examples of the bug I experience in my project with `v3.2.x`: - `<br>` stays hidden in all viewports. ```html <h1 class="[&amp;_br]:hidden [&amp;_br]:xl:block"> Lorem<br /> Ipsum </h1> ``` - `<img>` stays full width in all viewports. ```html <figure class="[&_img]:w-full md:[&_img]:w-[300px] xl:[&_img]:w-[340px]"> <img src="./image.jpg" alt="some image" /> </figure> ``` I can create isolated demos for each of them if it helps you debug. Please let me know if you need any other information.
Thanks for reporting, I was able to distill the reproduction down to this minimal demo on Tailwind Play: https://play.tailwindcss.com/3ujiz5LanM Can see the sorting issue in the "Generated CSS" tab. Will look at this one next week! Thanks for the reporting...
"2023-01-10T14:50:56Z"
3.2
[]
[ "tests/arbitrary-variants.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
10,400
tailwindlabs__tailwindcss-10400
[ "10353" ]
667eac5e8845e3928055351e747606fa8864603f
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -168,7 +168,30 @@ export let variantPlugins = { if (!result.includes('&')) result = '&' + result let [a, b] = fn('', extra) - return result.replace(/&(\S+)?/g, (_, pseudo = '') => a + pseudo + b) + + let start = null + let end = null + let quotes = 0 + + for (let i = 0; i < result.length; ++i) { + let c = result[i] + if (c === '&') { + start = i + } else if (c === "'" || c === '"') { + quotes += 1 + } else if (start !== null && c === ' ' && !quotes) { + end = i + } + } + + if (start !== null && end === null) { + end = result.length + } + + // Basically this but can handle quotes: + // result.replace(/&(\S+)?/g, (_, pseudo = '') => a + pseudo + b) + + return result.slice(0, start) + a + result.slice(start + 1, end) + b + result.slice(end) }, { values: Object.fromEntries(pseudoVariants) } ) diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -152,10 +152,18 @@ function applyVariant(variant, matches, context) { // Retrieve "modifier" { - let match = /(.*)\/(.*)$/g.exec(variant) - if (match && !context.variantMap.has(variant)) { - variant = match[1] - args.modifier = match[2] + let [baseVariant, ...modifiers] = splitAtTopLevelOnly(variant, '/') + + // This is a hack to support variants with `/` in them, like `ar-1/10/20:text-red-500` + // In this case 1/10 is a value but /20 is a modifier + if (modifiers.length > 1) { + baseVariant = baseVariant + '/' + modifiers.slice(0, -1).join('/') + modifiers = modifiers.slice(-1) + } + + if (modifiers.length && !context.variantMap.has(variant)) { + variant = baseVariant + args.modifier = modifiers[0] if (!flagEnabled(context.tailwindConfig, 'generalizedModifiers')) { return []
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -949,4 +949,66 @@ crosscheck(({ stable, oxide }) => { `) }) }) + + test('detects quoted arbitrary values containing a slash', async () => { + let config = { + content: [ + { + raw: html`<div class="group-[[href^='/']]:hidden"></div>`, + }, + ], + } + + let input = css` + @tailwind utilities; + ` + + let result = await run(input, config) + + oxide.expect(result.css).toMatchFormattedCss(css` + .group[href^='/'] .group-\[\[href\^\=\'\/\'\]\]\:hidden { + display: none; + } + `) + + stable.expect(result.css).toMatchFormattedCss(css` + .hidden { + display: none; + } + .group[href^='/'] .group-\[\[href\^\=\'\/\'\]\]\:hidden { + display: none; + } + `) + }) + + test('handled quoted arbitrary values containing escaped spaces', async () => { + let config = { + content: [ + { + raw: html`<div class="group-[[href^='_bar']]:hidden"></div>`, + }, + ], + } + + let input = css` + @tailwind utilities; + ` + + let result = await run(input, config) + + oxide.expect(result.css).toMatchFormattedCss(css` + .group[href^=' bar'] .group-\[\[href\^\=\'_bar\'\]\]\:hidden { + display: none; + } + `) + + stable.expect(result.css).toMatchFormattedCss(css` + .hidden { + display: none; + } + .group[href^=' bar'] .group-\[\[href\^\=\'_bar\'\]\]\:hidden { + display: none; + } + `) + }) }) diff --git a/tests/util/run.js b/tests/util/run.js --- a/tests/util/run.js +++ b/tests/util/run.js @@ -60,6 +60,18 @@ let nullProxy = new Proxy( } ) +/** + * @typedef {object} CrossCheck + * @property {typeof import('@jest/globals')} oxide + * @property {typeof import('@jest/globals')} stable + * @property {object} engine + * @property {boolean} engine.oxide + * @property {boolean} engine.stable + */ + +/** + * @param {(data: CrossCheck) => void} fn + */ export function crosscheck(fn) { let engines = env.ENGINE === 'oxide' ? [{ engine: 'Stable' }, { engine: 'Oxide' }] : [{ engine: 'Stable' }]
double escape happening in attribute value selectors <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.2.4 **What build tool (or framework if it abstracts the build tool) are you using?** postcss 8.4.19 **What version of Node.js are you using?** v14.19.1 **What browser are you using?** Chrome **What operating system are you using?** Kubuntu Linux **Reproduction URL** https://play.tailwindcss.com/sRVqoiJfLV **Describe your issue** in the attribute value of a attribute selector the value is being double escaped and there appears to be no way to un-escape it.
"2023-01-23T16:11:12Z"
3.2
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/sRVqoiJfLV" ]
tailwindlabs/tailwindcss
10,601
tailwindlabs__tailwindcss-10601
[ "10582" ]
66c640b73599e36c6087644d3b2c231cc17b37ff
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -3,10 +3,14 @@ import selectorParser from 'postcss-selector-parser' import parseObjectStyles from '../util/parseObjectStyles' import isPlainObject from '../util/isPlainObject' import prefixSelector from '../util/prefixSelector' -import { updateAllClasses, filterSelectorsForClass, getMatchingTypes } from '../util/pluginUtils' +import { updateAllClasses, getMatchingTypes } from '../util/pluginUtils' import log from '../util/log' import * as sharedState from './sharedState' -import { formatVariantSelector, finalizeSelector } from '../util/formatVariantSelector' +import { + formatVariantSelector, + finalizeSelector, + eliminateIrrelevantSelectors, +} from '../util/formatVariantSelector' import { asClass } from '../util/nameClass' import { normalize } from '../util/dataTypes' import { isValidVariantFormatString, parseVariant } from './setupContextUtils' @@ -111,22 +115,28 @@ function applyImportant(matches, classCandidate) { if (matches.length === 0) { return matches } + let result = [] for (let [meta, rule] of matches) { let container = postcss.root({ nodes: [rule.clone()] }) + container.walkRules((r) => { - r.selector = updateAllClasses( - filterSelectorsForClass(r.selector, classCandidate), - (className) => { - if (className === classCandidate) { - return `!${className}` - } - return className - } + let ast = selectorParser().astSync(r.selector) + + // Remove extraneous selectors that do not include the base candidate + ast.each((sel) => eliminateIrrelevantSelectors(sel, classCandidate)) + + // Update all instances of the base candidate to include the important marker + updateAllClasses(ast, (className) => + className === classCandidate ? `!${className}` : className ) + + r.selector = ast.toString() + r.walkDecls((d) => (d.important = true)) }) + result.push([{ ...meta, important: true }, container.nodes[0]]) } diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -120,7 +120,7 @@ function resortSelector(sel) { * @param {Selector} ast * @param {string} base */ -function eliminateIrrelevantSelectors(sel, base) { +export function eliminateIrrelevantSelectors(sel, base) { let hasClassesMatchingCandidate = false sel.walk((child) => { diff --git a/src/util/pluginUtils.js b/src/util/pluginUtils.js --- a/src/util/pluginUtils.js +++ b/src/util/pluginUtils.js @@ -1,4 +1,3 @@ -import selectorParser from 'postcss-selector-parser' import escapeCommas from './escapeCommas' import { withAlphaValue } from './withAlphaVariable' import { @@ -21,37 +20,19 @@ import negateValue from './negateValue' import { backgroundSize } from './validateFormalSyntax' import { flagEnabled } from '../featureFlags.js' +/** + * @param {import('postcss-selector-parser').Container} selectors + * @param {(className: string) => string} updateClass + * @returns {string} + */ export function updateAllClasses(selectors, updateClass) { - let parser = selectorParser((selectors) => { - selectors.walkClasses((sel) => { - let updatedClass = updateClass(sel.value) - sel.value = updatedClass - if (sel.raws && sel.raws.value) { - sel.raws.value = escapeCommas(sel.raws.value) - } - }) - }) - - let result = parser.processSync(selectors) + selectors.walkClasses((sel) => { + sel.value = updateClass(sel.value) - return result -} - -export function filterSelectorsForClass(selectors, classCandidate) { - let parser = selectorParser((selectors) => { - selectors.each((sel) => { - const containsClass = sel.nodes.some( - (node) => node.type === 'class' && node.value === classCandidate - ) - if (!containsClass) { - sel.remove() - } - }) + if (sel.raws && sel.raws.value) { + sel.raws.value = escapeCommas(sel.raws.value) + } }) - - let result = parser.processSync(selectors) - - return result } function resolveArbitraryValue(modifier, validate) {
diff --git a/tests/important-modifier.test.js b/tests/important-modifier.test.js --- a/tests/important-modifier.test.js +++ b/tests/important-modifier.test.js @@ -108,4 +108,46 @@ crosscheck(() => { `) }) }) + + test('the important modifier works on utilities using :where()', () => { + let config = { + content: [ + { + raw: html` <div class="btn hover:btn !btn hover:focus:disabled:!btn"></div> `, + }, + ], + corePlugins: { preflight: false }, + plugins: [ + function ({ addComponents }) { + addComponents({ + ':where(.btn)': { + backgroundColor: '#00f', + }, + }) + }, + ], + } + + let input = css` + @tailwind components; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + :where(.\!btn) { + background-color: #00f !important; + } + :where(.btn) { + background-color: #00f; + } + :where(.hover\:btn:hover) { + background-color: #00f; + } + :where(.hover\:focus\:disabled\:\!btn:disabled:focus:hover) { + background-color: #00f !important; + } + `) + }) + }) })
Using `:where(.anything)` in a plugin and having `!anything` inside HTML, creates invalid CSS <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** 3.2.6 **What build tool (or framework if it abstracts the build tool) are you using?** Tailwind Play (or any tool) **Reproduction URL** https://play.tailwindcss.com/Oy7NHRkftL?file=config **Describe your issue** If there is string with `!` prefix with the same class from a plugin that has a `:where()` selector, Tailwind creates invalid CSS HTML: ``` !btn ``` tailwind.config.js: ```js const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function({ addComponents }) { addComponents({ '.btn': { backgroundColor: 'red', }, ':where(.btn)': { backgroundColor: 'blue', }, }) }) ] } ``` Generated CSS: ```css .\!btn { background-color: red !important } { background-color: blue !important } ``` As you can see it can't apply important to the `:where()` selector and it generates an empty selector.
Thanks for reporting! Here's a slightly simplified reproduction for our own reference: https://play.tailwindcss.com/4MqOxcleAv?file=config
"2023-02-16T14:48:07Z"
3.2
[]
[ "tests/important-modifier.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/Oy7NHRkftL?file=config" ]
tailwindlabs/tailwindcss
10,604
tailwindlabs__tailwindcss-10604
[ "10591" ]
17159ff6c28b2d9700fa489dddf4d6f8d8d6f376
diff --git a/stubs/defaultConfig.stub.js b/stubs/defaultConfig.stub.js --- a/stubs/defaultConfig.stub.js +++ b/stubs/defaultConfig.stub.js @@ -879,8 +879,8 @@ module.exports = { none: 'none', all: 'all', DEFAULT: - 'color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter', - colors: 'color, background-color, border-color, outline-color, text-decoration-color, fill, stroke', + 'color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter', + colors: 'color, background-color, border-color, text-decoration-color, fill, stroke', opacity: 'opacity', shadow: 'box-shadow', transform: 'transform',
diff --git a/tests/basic-usage.oxide.test.css b/tests/basic-usage.oxide.test.css --- a/tests/basic-usage.oxide.test.css +++ b/tests/basic-usage.oxide.test.css @@ -1020,8 +1020,8 @@ backdrop-filter: none; } .transition { - transition-property: color, background-color, border-color, outline-color, text-decoration-color, - fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, + opacity, box-shadow, transform, filter, backdrop-filter; transition-duration: 0.15s; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } diff --git a/tests/basic-usage.test.css b/tests/basic-usage.test.css --- a/tests/basic-usage.test.css +++ b/tests/basic-usage.test.css @@ -1020,8 +1020,8 @@ backdrop-filter: none; } .transition { - transition-property: color, background-color, border-color, outline-color, text-decoration-color, - fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, + opacity, box-shadow, transform, filter, backdrop-filter; transition-duration: 0.15s; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } diff --git a/tests/kitchen-sink.test.js b/tests/kitchen-sink.test.js --- a/tests/kitchen-sink.test.js +++ b/tests/kitchen-sink.test.js @@ -698,9 +698,8 @@ crosscheck(() => { } @media (prefers-reduced-motion: no-preference) { .motion-safe\:transition { - transition-property: color, background-color, border-color, outline-color, - text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, - backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, + stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-duration: 0.15s; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } @@ -710,9 +709,8 @@ crosscheck(() => { } @media (prefers-reduced-motion: reduce) { .motion-reduce\:transition { - transition-property: color, background-color, border-color, outline-color, - text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, - backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, + stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-duration: 0.15s; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } @@ -759,9 +757,8 @@ crosscheck(() => { } @media (prefers-reduced-motion: no-preference) { .md\:motion-safe\:hover\:transition:hover { - transition-property: color, background-color, border-color, outline-color, - text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, - backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, + fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-duration: 0.15s; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } diff --git a/tests/raw-content.oxide.test.css b/tests/raw-content.oxide.test.css --- a/tests/raw-content.oxide.test.css +++ b/tests/raw-content.oxide.test.css @@ -761,8 +761,8 @@ backdrop-filter: none; } .transition { - transition-property: color, background-color, border-color, outline-color, text-decoration-color, - fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, + opacity, box-shadow, transform, filter, backdrop-filter; transition-duration: 0.15s; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } diff --git a/tests/raw-content.test.css b/tests/raw-content.test.css --- a/tests/raw-content.test.css +++ b/tests/raw-content.test.css @@ -761,8 +761,8 @@ backdrop-filter: none; } .transition { - transition-property: color, background-color, border-color, outline-color, text-decoration-color, - fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; + transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, + opacity, box-shadow, transform, filter, backdrop-filter; transition-duration: 0.15s; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); }
Input outlines show during transition with Tailwind 3.2.6 ### What version of @tailwindcss/forms are you using? 0.5.3 ### What version of Node.js are you using? 18.13.0 ### What browser are you using? Chrome ### What operating system are you using? Windows ### Reproduction repository https://play.tailwindcss.com/irT3FCtMUB ### Describe your issue Since https://github.com/tailwindlabs/tailwindcss/issues/10385 was merged inputs that use this plugin and the `transition` class receive an outline ring in addition to the box-shadow ring during their transition animation. The way to fix this is to add `outline-none` to the input or apply that to all inputs in your style sheet. `@tailwindcss/forms` sets the input's outline style to none, but only on the `:focus` state. For this to not be included in the transition it needs to be set as a base input style. This caught me off guard when updating from Tailwind 3.2.4 to 3.2.6 and I thought it was a bug in that release. After figuring out what's going on it seems like something that should probably be fixed in this plugin since it's setting a default outline style.
This issue is also visible on Heroicons in `Search all icons...` input https://heroicons.com/ I too noticed flickering when `focus:outline-none` and `transition` are used at the same time. Laravel Jetstream uses this combination. There are two ways for a temporary fix: - remove `outline-color` from `transition-property` - use `outline-none` without `focus` Thanks for reporting β€” working on a solution to this, will have a fix out today.
"2023-02-16T17:20:27Z"
3.2
[]
[ "tests/kitchen-sink.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/irT3FCtMUB" ]
tailwindlabs/tailwindcss
10,903
tailwindlabs__tailwindcss-10903
[ "10899" ]
a785c93b54c770b65364a8c781761dd97ac684d5
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -4,6 +4,7 @@ import parser from 'postcss-selector-parser' import { resolveMatches } from './generateRules' import escapeClassName from '../util/escapeClassName' import { applyImportantSelector } from '../util/applyImportantSelector' +import { collectPseudoElements, sortSelector } from '../util/formatVariantSelector.js' /** @typedef {Map<string, [any, import('postcss').Rule[]]>} ApplyCache */ @@ -562,6 +563,17 @@ function processApply(root, context, localCache) { rule.walkDecls((d) => { d.important = meta.important || important }) + + // Move pseudo elements to the end of the selector (if necessary) + let selector = parser().astSync(rule.selector) + selector.each((sel) => { + let [pseudoElements] = collectPseudoElements(sel) + if (pseudoElements.length > 0) { + sel.nodes.push(...pseudoElements.sort(sortSelector)) + } + }) + + rule.selector = selector.toString() }) } diff --git a/src/util/applyImportantSelector.js b/src/util/applyImportantSelector.js --- a/src/util/applyImportantSelector.js +++ b/src/util/applyImportantSelector.js @@ -1,19 +1,31 @@ import { splitAtTopLevelOnly } from './splitAtTopLevelOnly' +import parser from 'postcss-selector-parser' +import { collectPseudoElements, sortSelector } from './formatVariantSelector.js' export function applyImportantSelector(selector, important) { - let matches = /^(.*?)(:before|:after|::[\w-]+)(\)*)$/g.exec(selector) - if (!matches) return `${important} ${wrapWithIs(selector)}` + let sel = parser().astSync(selector) - let [, before, pseudo, brackets] = matches - return `${important} ${wrapWithIs(before + brackets)}${pseudo}` -} + sel.each((sel) => { + // Wrap with :is if it's not already wrapped + let isWrapped = + sel.nodes[0].type === 'pseudo' && + sel.nodes[0].value === ':is' && + sel.nodes.every((node) => node.type !== 'combinator') -function wrapWithIs(selector) { - let parts = splitAtTopLevelOnly(selector, ' ') + if (!isWrapped) { + sel.nodes = [ + parser.pseudo({ + value: ':is', + nodes: [sel.clone()], + }), + ] + } - if (parts.length === 1 && parts[0].startsWith(':is(') && parts[0].endsWith(')')) { - return selector - } + let [pseudoElements] = collectPseudoElements(sel) + if (pseudoElements.length > 0) { + sel.nodes.push(...pseudoElements.sort(sortSelector)) + } + }) - return `:is(${selector})` + return `${important} ${sel.toString()}` } diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -246,9 +246,9 @@ export function finalizeSelector(current, formats, { context, candidate, base }) // Move pseudo elements to the end of the selector (if necessary) selector.each((sel) => { - let pseudoElements = collectPseudoElements(sel) + let [pseudoElements] = collectPseudoElements(sel) if (pseudoElements.length > 0) { - sel.nodes.push(pseudoElements.sort(sortSelector)) + sel.nodes.push(...pseudoElements.sort(sortSelector)) } }) @@ -351,23 +351,45 @@ let pseudoElementExceptions = [ * `::before:hover` doesn't work, which means that we can make it work for you by flipping the order. * * @param {Selector} selector + * @param {boolean} force **/ -function collectPseudoElements(selector) { +export function collectPseudoElements(selector, force = false) { /** @type {Node[]} */ let nodes = [] + let seenPseudoElement = null - for (let node of selector.nodes) { - if (isPseudoElement(node)) { + for (let node of [...selector.nodes]) { + if (isPseudoElement(node, force)) { nodes.push(node) selector.removeChild(node) + seenPseudoElement = node.value + } else if (seenPseudoElement !== null) { + if (pseudoElementExceptions.includes(seenPseudoElement) && isPseudoClass(node, force)) { + nodes.push(node) + selector.removeChild(node) + } else { + seenPseudoElement = null + } } if (node?.nodes) { - nodes.push(...collectPseudoElements(node)) + let hasPseudoElementRestrictions = + node.type === 'pseudo' && (node.value === ':is' || node.value === ':has') + + let [collected, seenPseudoElementInSelector] = collectPseudoElements( + node, + force || hasPseudoElementRestrictions + ) + + if (seenPseudoElementInSelector) { + seenPseudoElement = seenPseudoElementInSelector + } + + nodes.push(...collected) } } - return nodes + return [nodes, seenPseudoElement] } // This will make sure to move pseudo's to the correct spot (the end for @@ -380,7 +402,7 @@ function collectPseudoElements(selector) { // // `::before:hover` doesn't work, which means that we can make it work // for you by flipping the order. -function sortSelector(a, z) { +export function sortSelector(a, z) { // Both nodes are non-pseudo's so we can safely ignore them and keep // them in the same order. if (a.type !== 'pseudo' && z.type !== 'pseudo') { @@ -404,9 +426,13 @@ function sortSelector(a, z) { return isPseudoElement(a) - isPseudoElement(z) } -function isPseudoElement(node) { +function isPseudoElement(node, force = false) { if (node.type !== 'pseudo') return false - if (pseudoElementExceptions.includes(node.value)) return false + if (pseudoElementExceptions.includes(node.value) && !force) return false return node.value.startsWith('::') || pseudoElementsBC.includes(node.value) } + +function isPseudoClass(node, force) { + return node.type === 'pseudo' && !isPseudoElement(node, force) +}
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -2357,4 +2357,74 @@ crosscheck(({ stable, oxide }) => { `) }) }) + + it('pseudo elements inside apply are moved outside of :is() or :has()', () => { + let config = { + darkMode: 'class', + content: [ + { + raw: html` <div class="foo bar baz qux steve bob"></div> `, + }, + ], + } + + let input = css` + .foo::before { + @apply dark:bg-black/100; + } + + .bar::before { + @apply rtl:dark:bg-black/100; + } + + .baz::before { + @apply rtl:dark:hover:bg-black/100; + } + + .qux::file-selector-button { + @apply rtl:dark:hover:bg-black/100; + } + + .steve::before { + @apply rtl:hover:dark:bg-black/100; + } + + .bob::file-selector-button { + @apply rtl:hover:dark:bg-black/100; + } + + .foo::before { + @apply [:has([dir="rtl"]_&)]:hover:bg-black/100; + } + + .bar::file-selector-button { + @apply [:has([dir="rtl"]_&)]:hover:bg-black/100; + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + :is(.dark .foo)::before, + :is([dir='rtl'] :is(.dark .bar))::before, + :is([dir='rtl'] :is(.dark .baz:hover))::before { + background-color: #000; + } + :is([dir='rtl'] :is(.dark .qux))::file-selector-button:hover { + background-color: #000; + } + :is([dir='rtl'] :is(.dark .steve):hover):before { + background-color: #000; + } + :is([dir='rtl'] :is(.dark .bob))::file-selector-button:hover { + background-color: #000; + } + :has([dir='rtl'] .foo:hover):before { + background-color: #000; + } + :has([dir='rtl'] .bar)::file-selector-button:hover { + background-color: #000; + } + `) + }) + }) }) diff --git a/tests/important-selector.test.js b/tests/important-selector.test.js --- a/tests/important-selector.test.js +++ b/tests/important-selector.test.js @@ -21,6 +21,7 @@ crosscheck(({ stable, oxide }) => { <div class="group-hover:focus-within:text-left"></div> <div class="rtl:active:text-center"></div> <div class="dark:before:underline"></div> + <div class="hover:[&::file-selector-button]:rtl:dark:bg-black/100"></div> `, }, ], @@ -155,6 +156,12 @@ crosscheck(({ stable, oxide }) => { text-align: right; } } + #app + :is( + [dir='rtl'] :is(.dark .hover\:\[\&\:\:file-selector-button\]\:rtl\:dark\:bg-black\/100) + )::file-selector-button:hover { + background-color: #000; + } `) }) })
after update from 3.2.7 to 3.3.0 pseudo elements `after` and `before` doesn't get `dark: ...` anymore <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** 3.3.0 **What build tool (or framework if it abstracts the build tool) are you using?** astro v2.1.8 **What version of Node.js are you using?** 19.8.1 **What browser are you using?** Chrome 111 **What operating system are you using?** Zorin OS 16.2 **Describe your issue** after update every `after` and `before` pseudo element doesn't get any `dark` modifier value, for example if i write `... bg-gray-800 dark:bg-gray-100 ...` it get only `bg-gray-800` on version 3.2.7 it works as usual
Hey, thank you for this bug report! πŸ™ Can you please provide a minimal reproduction repo that shows the issue? Trying to reproduce it and seems to work as expected: https://play.tailwindcss.com/d5HtkTSI6a > Hey, thank you for this bug report! πŸ™ > > Can you please provide a minimal reproduction repo that shows the issue? > > Trying to reproduce it and seems to work as expected: https://play.tailwindcss.com/d5HtkTSI6a I have reproduced a case here: https://play.tailwindcss.com/tsNrZ1Qtm5?file=css > Hey, thank you for this bug report! pray > > Can you please provide a minimal reproduction repo that shows the issue? > > Trying to reproduce it and seems to work as expected: https://play.tailwindcss.com/d5HtkTSI6a I tried to extract and abstract part of code of my use case: https://play.tailwindcss.com/ytDMhpXmfR?file=css
"2023-03-29T14:53:21Z"
3.3
[]
[ "tests/important-selector.test.js", "tests/apply.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
10,943
tailwindlabs__tailwindcss-10943
[ "10937" ]
d7310491b5cd2c0fe96b398de8bbb6caf2bdee4d
diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -337,6 +337,9 @@ let pseudoElementExceptions = [ '::-webkit-scrollbar-track-piece', '::-webkit-scrollbar-corner', '::-webkit-resizer', + + // Old-style Angular Shadow DOM piercing pseudo element + '::ng-deep', ] /**
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -2427,4 +2427,34 @@ crosscheck(({ stable, oxide }) => { `) }) }) + + stable.test('::ng-deep pseudo element is left alone', () => { + let config = { + darkMode: 'class', + content: [ + { + raw: html` <div class="foo bar"></div> `, + }, + ], + } + + let input = css` + ::ng-deep .foo .bar { + @apply font-bold; + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ::ng-deep .foo .bar { + font-weight: 700; + } + `) + }) + }) + + // 1. `::ng-deep` is deprecated + // 2. It uses invalid selector syntax that Lightning CSS does not support + // It may be enough for Oxide to not support it at all + oxide.test.todo('::ng-deep pseudo element is left alone') })
@apply method is invalid after upgrade to 3.3.1 <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.3.1 **What build tool (or framework if it abstracts the build tool) are you using?** webpack 5.77.0 **What version of Node.js are you using?** v16.16.0 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://github.com/Postcatlab/postcat/blob/3411792892633e5c53d4e86466a0fd52f4599f4a/src/browser/src/app/pages/workspace/overview/project-list/project-list.component.scss **Describe your issue** My previous version was 3.2.4 After upgrading to the latest version of 3.3.1, @apply is invalid. * Angular 15.2.5 ```scss :host { .operate-btn-list { display: none; } .ant-card { @include hover-item; } ::ng-deep { .ant-list-items { .ant-list-item { @apply px-[10px] rounded-[3px]; @include hover-item; border: 1px solid transparent; } } } } ``` previous display ![image](https://user-images.githubusercontent.com/15225835/229733712-d9d19b15-8461-4113-b2a5-7298d8cb71c4.png) current display ![](https://user-images.githubusercontent.com/15225835/229733180-e01260c1-4772-45dd-848c-32ceb7696db1.png)
"2023-04-04T16:29:09Z"
3.3
[]
[ "tests/apply.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/15225835/229733712-d9d19b15-8461-4113-b2a5-7298d8cb71c4.png", "https://user-images.githubusercontent.com/15225835/229733180-e01260c1-4772-45dd-848c-32ceb7696db1.png" ]
[]
tailwindlabs/tailwindcss
10,962
tailwindlabs__tailwindcss-10962
[ "10960" ]
467a39e0d59a9fdc42deef3a9c7d51c44ace90e8
diff --git a/jest/global-setup.js b/jest/global-setup.js --- a/jest/global-setup.js +++ b/jest/global-setup.js @@ -1,6 +1,9 @@ let { execSync } = require('child_process') +let state = { ran: false } module.exports = function () { + if (state.ran) return execSync('npm run build:rust', { stdio: 'ignore' }) execSync('npm run generate:plugin-list', { stdio: 'ignore' }) + state.ran = true } diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -4,7 +4,7 @@ import parser from 'postcss-selector-parser' import { resolveMatches } from './generateRules' import escapeClassName from '../util/escapeClassName' import { applyImportantSelector } from '../util/applyImportantSelector' -import { collectPseudoElements, sortSelector } from '../util/formatVariantSelector.js' +import { movePseudos } from '../util/pseudoElements' /** @typedef {Map<string, [any, import('postcss').Rule[]]>} ApplyCache */ @@ -566,13 +566,7 @@ function processApply(root, context, localCache) { // Move pseudo elements to the end of the selector (if necessary) let selector = parser().astSync(rule.selector) - selector.each((sel) => { - let [pseudoElements] = collectPseudoElements(sel) - if (pseudoElements.length > 0) { - sel.nodes.push(...pseudoElements.sort(sortSelector)) - } - }) - + selector.each((sel) => movePseudos(sel)) rule.selector = selector.toString() }) } diff --git a/src/util/applyImportantSelector.js b/src/util/applyImportantSelector.js --- a/src/util/applyImportantSelector.js +++ b/src/util/applyImportantSelector.js @@ -1,5 +1,5 @@ import parser from 'postcss-selector-parser' -import { collectPseudoElements, sortSelector } from './formatVariantSelector.js' +import { movePseudos } from './pseudoElements' export function applyImportantSelector(selector, important) { let sel = parser().astSync(selector) @@ -20,10 +20,7 @@ export function applyImportantSelector(selector, important) { ] } - let [pseudoElements] = collectPseudoElements(sel) - if (pseudoElements.length > 0) { - sel.nodes.push(...pseudoElements.sort(sortSelector)) - } + movePseudos(sel) }) return `${important} ${sel.toString()}` diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -2,6 +2,7 @@ import selectorParser from 'postcss-selector-parser' import unescape from 'postcss-selector-parser/dist/util/unesc' import escapeClassName from '../util/escapeClassName' import prefixSelector from '../util/prefixSelector' +import { movePseudos } from './pseudoElements' /** @typedef {import('postcss-selector-parser').Root} Root */ /** @typedef {import('postcss-selector-parser').Selector} Selector */ @@ -245,12 +246,7 @@ export function finalizeSelector(current, formats, { context, candidate, base }) }) // Move pseudo elements to the end of the selector (if necessary) - selector.each((sel) => { - let [pseudoElements] = collectPseudoElements(sel) - if (pseudoElements.length > 0) { - sel.nodes.push(...pseudoElements.sort(sortSelector)) - } - }) + selector.each((sel) => movePseudos(sel)) return selector.toString() } @@ -318,124 +314,3 @@ export function handleMergePseudo(selector, format) { return [selector, format] } - -// Note: As a rule, double colons (::) should be used instead of a single colon -// (:). This distinguishes pseudo-classes from pseudo-elements. However, since -// this distinction was not present in older versions of the W3C spec, most -// browsers support both syntaxes for the original pseudo-elements. -let pseudoElementsBC = [':before', ':after', ':first-line', ':first-letter'] - -// These pseudo-elements _can_ be combined with other pseudo selectors AND the order does matter. -let pseudoElementExceptions = [ - '::file-selector-button', - - // Webkit scroll bar pseudo elements can be combined with user-action pseudo classes - '::-webkit-scrollbar', - '::-webkit-scrollbar-button', - '::-webkit-scrollbar-thumb', - '::-webkit-scrollbar-track', - '::-webkit-scrollbar-track-piece', - '::-webkit-scrollbar-corner', - '::-webkit-resizer', - - // Old-style Angular Shadow DOM piercing pseudo element - '::ng-deep', -] - -/** - * This will make sure to move pseudo's to the correct spot (the end for - * pseudo elements) because otherwise the selector will never work - * anyway. - * - * E.g.: - * - `before:hover:text-center` would result in `.before\:hover\:text-center:hover::before` - * - `hover:before:text-center` would result in `.hover\:before\:text-center:hover::before` - * - * `::before:hover` doesn't work, which means that we can make it work for you by flipping the order. - * - * @param {Selector} selector - * @param {boolean} force - **/ -export function collectPseudoElements(selector, force = false) { - /** @type {Node[]} */ - let nodes = [] - let seenPseudoElement = null - - for (let node of [...selector.nodes]) { - if (isPseudoElement(node, force)) { - nodes.push(node) - selector.removeChild(node) - seenPseudoElement = node.value - } else if (seenPseudoElement !== null) { - if (pseudoElementExceptions.includes(seenPseudoElement) && isPseudoClass(node, force)) { - nodes.push(node) - selector.removeChild(node) - } else { - seenPseudoElement = null - } - } - - if (node?.nodes) { - let hasPseudoElementRestrictions = - node.type === 'pseudo' && (node.value === ':is' || node.value === ':has') - - let [collected, seenPseudoElementInSelector] = collectPseudoElements( - node, - force || hasPseudoElementRestrictions - ) - - if (seenPseudoElementInSelector) { - seenPseudoElement = seenPseudoElementInSelector - } - - nodes.push(...collected) - } - } - - return [nodes, seenPseudoElement] -} - -// This will make sure to move pseudo's to the correct spot (the end for -// pseudo elements) because otherwise the selector will never work -// anyway. -// -// E.g.: -// - `before:hover:text-center` would result in `.before\:hover\:text-center:hover::before` -// - `hover:before:text-center` would result in `.hover\:before\:text-center:hover::before` -// -// `::before:hover` doesn't work, which means that we can make it work -// for you by flipping the order. -export function sortSelector(a, z) { - // Both nodes are non-pseudo's so we can safely ignore them and keep - // them in the same order. - if (a.type !== 'pseudo' && z.type !== 'pseudo') { - return 0 - } - - // If one of them is a combinator, we need to keep it in the same order - // because that means it will start a new "section" in the selector. - if ((a.type === 'combinator') ^ (z.type === 'combinator')) { - return 0 - } - - // One of the items is a pseudo and the other one isn't. Let's move - // the pseudo to the right. - if ((a.type === 'pseudo') ^ (z.type === 'pseudo')) { - return (a.type === 'pseudo') - (z.type === 'pseudo') - } - - // Both are pseudo's, move the pseudo elements (except for - // ::file-selector-button) to the right. - return isPseudoElement(a) - isPseudoElement(z) -} - -function isPseudoElement(node, force = false) { - if (node.type !== 'pseudo') return false - if (pseudoElementExceptions.includes(node.value) && !force) return false - - return node.value.startsWith('::') || pseudoElementsBC.includes(node.value) -} - -function isPseudoClass(node, force) { - return node.type === 'pseudo' && !isPseudoElement(node, force) -} diff --git a/src/util/pseudoElements.js b/src/util/pseudoElements.js new file mode 100644 --- /dev/null +++ b/src/util/pseudoElements.js @@ -0,0 +1,170 @@ +/** @typedef {import('postcss-selector-parser').Root} Root */ +/** @typedef {import('postcss-selector-parser').Selector} Selector */ +/** @typedef {import('postcss-selector-parser').Pseudo} Pseudo */ +/** @typedef {import('postcss-selector-parser').Node} Node */ + +// There are some pseudo-elements that may or may not be: + +// **Actionable** +// Zero or more user-action pseudo-classes may be attached to the pseudo-element itself +// structural-pseudo-classes are NOT allowed but we don't make +// The spec is not clear on whether this is allowed or not β€” but in practice it is. + +// **Terminal** +// It MUST be placed at the end of a selector +// +// This is the required in the spec. However, some pseudo elements are not "terminal" because +// they represent a "boundary piercing" that is compiled out by a build step. + +// **Jumpable** +// Any terminal element may "jump" over combinators when moving to the end of the selector +// +// This is a backwards-compat quirk of :before and :after variants. + +/** @typedef {'terminal' | 'actionable' | 'jumpable'} PseudoProperty */ + +/** @type {Record<string, PseudoProperty[]>} */ +let elementProperties = { + '::after': ['terminal', 'jumpable'], + '::backdrop': ['terminal'], + '::before': ['terminal', 'jumpable'], + '::cue': ['terminal'], + '::cue-region': ['terminal'], + '::first-letter': ['terminal', 'jumpable'], + '::first-line': ['terminal', 'jumpable'], + '::grammar-error': ['terminal'], + '::marker': ['terminal'], + '::part': ['terminal', 'actionable'], + '::placeholder': ['terminal'], + '::selection': ['terminal'], + '::slotted': ['terminal'], + '::spelling-error': ['terminal'], + '::target-text': ['terminal'], + + // other + '::file-selector-button': ['terminal', 'actionable'], + '::-webkit-progress-bar': ['terminal', 'actionable'], + + // Webkit scroll bar pseudo elements can be combined with user-action pseudo classes + '::-webkit-scrollbar': ['terminal', 'actionable'], + '::-webkit-scrollbar-button': ['terminal', 'actionable'], + '::-webkit-scrollbar-thumb': ['terminal', 'actionable'], + '::-webkit-scrollbar-track': ['terminal', 'actionable'], + '::-webkit-scrollbar-track-piece': ['terminal', 'actionable'], + '::-webkit-scrollbar-corner': ['terminal', 'actionable'], + '::-webkit-resizer': ['terminal', 'actionable'], + + // Note: As a rule, double colons (::) should be used instead of a single colon + // (:). This distinguishes pseudo-classes from pseudo-elements. However, since + // this distinction was not present in older versions of the W3C spec, most + // browsers support both syntaxes for the original pseudo-elements. + ':after': ['terminal', 'jumpable'], + ':before': ['terminal', 'jumpable'], + ':first-letter': ['terminal', 'jumpable'], + ':first-line': ['terminal', 'jumpable'], + + // The default value is used when the pseudo-element is not recognized + // Because it's not recognized, we don't know if it's terminal or not + // So we assume it can't be moved AND can have user-action pseudo classes attached to it + __default__: ['actionable'], +} + +/** + * @param {Selector} sel + * @returns {Selector} + */ +export function movePseudos(sel) { + let [pseudos] = movablePseudos(sel) + + // Remove all pseudo elements from their respective selectors + pseudos.forEach(([sel, pseudo]) => sel.removeChild(pseudo)) + + // Re-add them to the end of the selector in the correct order. + // This moves terminal pseudo elements to the end of the + // selector otherwise the selector will not be valid. + // + // Examples: + // - `before:hover:text-center` would result in `.before\:hover\:text-center:hover::before` + // - `hover:before:text-center` would result in `.hover\:before\:text-center:hover::before` + // + // The selector `::before:hover` does not work but we + // can make it work for you by flipping the order. + sel.nodes.push(...pseudos.map(([, pseudo]) => pseudo)) + + return sel +} + +/** @typedef {[sel: Selector, pseudo: Pseudo, attachedTo: Pseudo | null]} MovablePseudo */ +/** @typedef {[pseudos: MovablePseudo[], lastSeenElement: Pseudo | null]} MovablePseudosResult */ + +/** + * @param {Selector} sel + * @returns {MovablePseudosResult} + */ +function movablePseudos(sel) { + /** @type {MovablePseudo[]} */ + let buffer = [] + + /** @type {Pseudo | null} */ + let lastSeenElement = null + + for (let node of sel.nodes) { + if (node.type === 'combinator') { + buffer = buffer.filter(([, node]) => propertiesForPseudo(node).includes('jumpable')) + lastSeenElement = null + } else if (node.type === 'pseudo') { + if (isMovablePseudoElement(node)) { + lastSeenElement = node + buffer.push([sel, node, null]) + } else if (lastSeenElement && isAttachablePseudoClass(node, lastSeenElement)) { + buffer.push([sel, node, lastSeenElement]) + } else { + lastSeenElement = null + } + + for (let sub of node.nodes ?? []) { + let [movable, lastSeenElementInSub] = movablePseudos(sub) + lastSeenElement = lastSeenElementInSub || lastSeenElement + buffer.push(...movable) + } + } + } + + return [buffer, lastSeenElement] +} + +/** + * @param {Node} node + * @returns {boolean} + */ +function isPseudoElement(node) { + return node.value.startsWith('::') || elementProperties[node.value] !== undefined +} + +/** + * @param {Node} node + * @returns {boolean} + */ +function isMovablePseudoElement(node) { + return isPseudoElement(node) && propertiesForPseudo(node).includes('terminal') +} + +/** + * @param {Node} node + * @param {Pseudo} pseudo + * @returns {boolean} + */ +function isAttachablePseudoClass(node, pseudo) { + if (node.type !== 'pseudo') return false + if (isPseudoElement(node)) return false + + return propertiesForPseudo(pseudo).includes('actionable') +} + +/** + * @param {Pseudo} pseudo + * @returns {PseudoProperty[]} + */ +function propertiesForPseudo(pseudo) { + return elementProperties[pseudo.value] ?? elementProperties.__default__ +}
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -2428,7 +2428,7 @@ crosscheck(({ stable, oxide }) => { }) }) - stable.test('::ng-deep pseudo element is left alone', () => { + stable.test('::ng-deep, ::deep, ::v-deep pseudo elements are left alone', () => { let config = { darkMode: 'class', content: [ @@ -2442,6 +2442,12 @@ crosscheck(({ stable, oxide }) => { ::ng-deep .foo .bar { @apply font-bold; } + ::v-deep .foo .bar { + @apply font-bold; + } + ::deep .foo .bar { + @apply font-bold; + } ` return run(input, config).then((result) => { @@ -2449,12 +2455,19 @@ crosscheck(({ stable, oxide }) => { ::ng-deep .foo .bar { font-weight: 700; } + ::v-deep .foo .bar { + font-weight: 700; + } + ::deep .foo .bar { + font-weight: 700; + } `) }) }) // 1. `::ng-deep` is deprecated - // 2. It uses invalid selector syntax that Lightning CSS does not support + // 2. `::deep` and `::v-deep` are non-standard + // 3. They all use invalid selector syntax that Lightning CSS does not support // It may be enough for Oxide to not support it at all - oxide.test.todo('::ng-deep pseudo element is left alone') + oxide.test.todo('::ng-deep, ::deep, ::v-deep pseudo elements are left alone') }) diff --git a/tests/format-variant-selector.test.js b/tests/format-variant-selector.test.js --- a/tests/format-variant-selector.test.js +++ b/tests/format-variant-selector.test.js @@ -350,6 +350,8 @@ crosscheck(() => { ${':where(&::file-selector-button) :is(h1, h2, h3, h4)'} | ${':where(&::file-selector-button) :is(h1, h2, h3, h4)'} ${'#app :is(.dark &::before)'} | ${'#app :is(.dark &)::before'} ${'#app :is(:is(.dark &)::before)'} | ${'#app :is(:is(.dark &))::before'} + ${'#app :is(.foo::file-selector-button)'} | ${'#app :is(.foo)::file-selector-button'} + ${'#app :is(.foo::-webkit-progress-bar)'} | ${'#app :is(.foo)::-webkit-progress-bar'} `('should translate "$before" into "$after"', ({ before, after }) => { let result = finalizeSelector('.a', [{ format: before, isArbitraryVariant: false }], { candidate: 'a', diff --git a/tests/parallel-variants.test.js b/tests/parallel-variants.test.js --- a/tests/parallel-variants.test.js +++ b/tests/parallel-variants.test.js @@ -28,7 +28,7 @@ crosscheck(() => { .test\:font-medium ::test { font-weight: 500; } - .hover\:test\:font-black :hover::test { + .hover\:test\:font-black ::test:hover { font-weight: 900; } .test\:font-bold::test { @@ -37,7 +37,7 @@ crosscheck(() => { .test\:font-medium::test { font-weight: 500; } - .hover\:test\:font-black:hover::test { + .hover\:test\:font-black::test:hover { font-weight: 900; } `) @@ -77,10 +77,10 @@ crosscheck(() => { .test\:font-medium::test { font-weight: 500; } - .hover\:test\:font-black :hover::test { + .hover\:test\:font-black ::test:hover { font-weight: 900; } - .hover\:test\:font-black:hover::test { + .hover\:test\:font-black::test:hover { font-weight: 900; } `) @@ -126,10 +126,10 @@ crosscheck(() => { .test\:font-medium::test { font-weight: 500; } - .hover\:test\:font-black :hover::test { + .hover\:test\:font-black ::test:hover { font-weight: 900; } - .hover\:test\:font-black:hover::test { + .hover\:test\:font-black::test:hover { font-weight: 900; } `)
3.3.1 not handling pseudo-elements properly **What version of Tailwind CSS are you using?** `3.3.1` **What build tool (or framework if it abstracts the build tool) are you using?** tailwindcss **What version of Node.js are you using?** `v18.14.0` #### Steps to Repro ```bash mkdir repro cd repro yarn global add [email protected] tailwindcss init ``` Create `repro.css` with the following content: ```css @config 'tailwind.config.js'; ::deep [a] { @apply bg-white; } ``` Run `tailwindcss --input .\repro.css --output .\result.css` ```css /* result.css / Incorrect */ [a]::deep { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)) } ``` You can fix this by downgrading tailwindcss to 3.3.0: ```bash yarn global add [email protected] tailwindcss --input .\repro.css --output .\result.css ```` And the CORRECT output ```css /* Correct! */ ::deep [a] { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)) } ```
"2023-04-06T12:31:05Z"
3.3
[ "tests/format-variant-selector.test.js" ]
[ "tests/parallel-variants.test.js", "tests/apply.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
11,111
tailwindlabs__tailwindcss-11111
[ "11107" ]
18677447063f7d08252a3f34c34d7deb0bcd6995
diff --git a/src/util/pseudoElements.js b/src/util/pseudoElements.js --- a/src/util/pseudoElements.js +++ b/src/util/pseudoElements.js @@ -26,17 +26,17 @@ /** @type {Record<string, PseudoProperty[]>} */ let elementProperties = { '::after': ['terminal', 'jumpable'], - '::backdrop': ['terminal'], + '::backdrop': ['terminal', 'jumpable'], '::before': ['terminal', 'jumpable'], '::cue': ['terminal'], '::cue-region': ['terminal'], '::first-letter': ['terminal', 'jumpable'], '::first-line': ['terminal', 'jumpable'], '::grammar-error': ['terminal'], - '::marker': ['terminal'], + '::marker': ['terminal', 'jumpable'], '::part': ['terminal', 'actionable'], - '::placeholder': ['terminal'], - '::selection': ['terminal'], + '::placeholder': ['terminal', 'jumpable'], + '::selection': ['terminal', 'jumpable'], '::slotted': ['terminal'], '::spelling-error': ['terminal'], '::target-text': ['terminal'],
diff --git a/tests/format-variant-selector.test.js b/tests/format-variant-selector.test.js --- a/tests/format-variant-selector.test.js +++ b/tests/format-variant-selector.test.js @@ -352,6 +352,10 @@ crosscheck(() => { ${'#app :is(:is(.dark &)::before)'} | ${'#app :is(:is(.dark &))::before'} ${'#app :is(.foo::file-selector-button)'} | ${'#app :is(.foo)::file-selector-button'} ${'#app :is(.foo::-webkit-progress-bar)'} | ${'#app :is(.foo)::-webkit-progress-bar'} + ${'.parent::marker li'} | ${'.parent li::marker'} + ${'.parent::selection li'} | ${'.parent li::selection'} + ${'.parent::placeholder input'} | ${'.parent input::placeholder'} + ${'.parent::backdrop dialog'} | ${'.parent dialog::backdrop'} `('should translate "$before" into "$after"', ({ before, after }) => { let result = finalizeSelector('.a', [{ format: before, isArbitraryVariant: false }], { candidate: 'a',
Unexpected behavior of pseudo-elements such as marker **What version of Tailwind CSS are you using?** For example: v3.3.2 **What build tool (or framework if it abstracts the build tool) are you using?** vite 4.3.3, vue 3.2.47, postcss 8.4.23 **What version of Node.js are you using?** v20.0.0 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** As v3.3.2 is currently unavailable in Tailwind Play, this is the Insiders version. [https://play.tailwindcss.com/3SbW3c1AhG](https://play.tailwindcss.com/3SbW3c1AhG) <img width="50" src="https://user-images.githubusercontent.com/36815907/234824052-0245f5dc-5045-4a89-b241-a21edf9218e5.png"> In v3.3.1, it works as expected. [https://play.tailwindcss.com/1nJxOORQv7](https://play.tailwindcss.com/1nJxOORQv7) <img width="50" src="https://user-images.githubusercontent.com/36815907/234824207-9d53f56f-edb1-4898-816d-162b81f4fc1a.png"> **Describe your issue** In v3.3.2, some behaviors of pseudo-elements are not as expected, for example, the marker color cannot be changed correctly, while this works correctly in v3.3.1. ```html <div class="[&>li]:marker:text-red-500"> <li>A</li> <li>B</li> <li>C</li> </div> <div class="prose prose-li:marker:text-purple-500"> <li>D</li> <li>E</li> <li>F</li> </div> ```
Hey, thank you for this bug report! πŸ™ If you swap the variants around then it behaves as expected: https://play.tailwindcss.com/u1trU3XrlL however I do think we regressed on this. --- @thecrypticace Pinging you because I know you worked on this recently to fix other bugs. We can also pair on this later today to see what's going on if you want.
"2023-04-27T13:34:47Z"
3.3
[]
[ "tests/format-variant-selector.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/36815907/234824052-0245f5dc-5045-4a89-b241-a21edf9218e5.png", "https://user-images.githubusercontent.com/36815907/234824207-9d53f56f-edb1-4898-816d-162b81f4fc1a.png" ]
[ "https://play.tailwindcss.com/3SbW3c1AhG](https://play.tailwindcss.com/3SbW3c1AhG", "https://play.tailwindcss.com/1nJxOORQv7](https://play.tailwindcss.com/1nJxOORQv7" ]
tailwindlabs/tailwindcss
11,157
tailwindlabs__tailwindcss-11157
[ "11027" ]
cdca9cbcfe331b54ca4df80bc720f8cd78e303a0
diff --git a/src/lib/evaluateTailwindFunctions.js b/src/lib/evaluateTailwindFunctions.js --- a/src/lib/evaluateTailwindFunctions.js +++ b/src/lib/evaluateTailwindFunctions.js @@ -1,7 +1,7 @@ import dlv from 'dlv' import didYouMean from 'didyoumean' import transformThemeValue from '../util/transformThemeValue' -import parseValue from 'postcss-value-parser' +import parseValue from '../value-parser/index' import { normalizeScreens } from '../util/normalizeScreens' import buildMediaQuery from '../util/buildMediaQuery' import { toPath } from '../util/toPath' @@ -146,6 +146,9 @@ function resolveVNode(node, vNode, functions) { } function resolveFunctions(node, input, functions) { + let hasAnyFn = Object.keys(functions).some((fn) => input.includes(`${fn}(`)) + if (!hasAnyFn) return input + return parseValue(input) .walk((vNode) => { resolveVNode(node, vNode, functions) diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -49,10 +49,22 @@ export function normalize(value, isRoot = true) { value = value.trim() } - // Add spaces around operators inside math functions like calc() that do not follow an operator - // or '('. - value = value.replace(/(calc|min|max|clamp)\(.+\)/g, (match) => { + value = normalizeMathOperatorSpacing(value) + + return value +} + +/** + * Add spaces around operators inside math functions + * like calc() that do not follow an operator or '('. + * + * @param {string} value + * @returns {string} + */ +function normalizeMathOperatorSpacing(value) { + return value.replace(/(calc|min|max|clamp)\(.+\)/g, (match) => { let vars = [] + return match .replace(/var\((--.+?)[,)]/g, (match, g1) => { vars.push(g1) @@ -61,8 +73,6 @@ export function normalize(value, isRoot = true) { .replace(/(-?\d*\.?\d(?!\b-\d.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g, '$1 $2 ') .replace(placeholderRe, () => vars.shift()) }) - - return value } export function url(value) { diff --git a/src/value-parser/index.d.ts b/src/value-parser/index.d.ts new file mode 100644 --- /dev/null +++ b/src/value-parser/index.d.ts @@ -0,0 +1,177 @@ +declare namespace postcssValueParser { + interface BaseNode { + /** + * The offset, inclusive, inside the CSS value at which the node starts. + */ + sourceIndex: number + + /** + * The offset, exclusive, inside the CSS value at which the node ends. + */ + sourceEndIndex: number + + /** + * The node's characteristic value + */ + value: string + } + + interface ClosableNode { + /** + * Whether the parsed CSS value ended before the node was properly closed + */ + unclosed?: true + } + + interface AdjacentAwareNode { + /** + * The token at the start of the node + */ + before: string + + /** + * The token at the end of the node + */ + after: string + } + + interface CommentNode extends BaseNode, ClosableNode { + type: 'comment' + } + + interface DivNode extends BaseNode, AdjacentAwareNode { + type: 'div' + } + + interface FunctionNode extends BaseNode, ClosableNode, AdjacentAwareNode { + type: 'function' + + /** + * Nodes inside the function + */ + nodes: Node[] + } + + interface SpaceNode extends BaseNode { + type: 'space' + } + + interface StringNode extends BaseNode, ClosableNode { + type: 'string' + + /** + * The quote type delimiting the string + */ + quote: '"' | "'" + } + + interface UnicodeRangeNode extends BaseNode { + type: 'unicode-range' + } + + interface WordNode extends BaseNode { + type: 'word' + } + + /** + * Any node parsed from a CSS value + */ + type Node = + | CommentNode + | DivNode + | FunctionNode + | SpaceNode + | StringNode + | UnicodeRangeNode + | WordNode + + interface CustomStringifierCallback { + /** + * @param node The node to stringify + * @returns The serialized CSS representation of the node + */ + (nodes: Node): string | undefined + } + + interface WalkCallback { + /** + * @param node The currently visited node + * @param index The index of the node in the series of parsed nodes + * @param nodes The series of parsed nodes + * @returns Returning `false` will prevent traversal of descendant nodes (only applies if `bubble` was set to `true` in the `walk()` call) + */ + (node: Node, index: number, nodes: Node[]): void | boolean + } + + /** + * A CSS dimension, decomposed into its numeric and unit parts + */ + interface Dimension { + number: string + unit: string + } + + /** + * A wrapper around a parsed CSS value that allows for inspecting and walking nodes + */ + interface ParsedValue { + /** + * The series of parsed nodes + */ + nodes: Node[] + + /** + * Walk all parsed nodes, applying a callback + * + * @param callback A visitor callback that will be executed for each node + * @param bubble When set to `true`, walking will be done inside-out instead of outside-in + */ + walk(callback: WalkCallback, bubble?: boolean): this + } + + interface ValueParser { + /** + * Decompose a CSSΒ dimension into its numeric and unit part + * + * @param value The dimension to decompose + * @returns An object representing `number` and `unit` part of the dimension or `false` if the decomposing fails + */ + unit(value: string): Dimension | false + + /** + * Serialize a series of nodes into a CSS value + * + * @param nodes The nodes to stringify + * @param custom A custom stringifier callback + * @returns The generated CSS value + */ + stringify(nodes: Node | Node[], custom?: CustomStringifierCallback): string + + /** + * Walk a series of nodes, applying a callback + * + * @param nodes The nodes to walk + * @param callback A visitor callback that will be executed for each node + * @param bubble When set to `true`, walking will be done inside-out instead of outside-in + */ + walk(nodes: Node[], callback: WalkCallback, bubble?: boolean): void + + /** + * Parse a CSS value into a series of nodes to operate on + * + * @param value The value to parse + */ + new (value: string): ParsedValue + + /** + * Parse a CSS value into a series of nodes to operate on + * + * @param value The value to parse + */ + (value: string): ParsedValue + } +} + +declare const postcssValueParser: postcssValueParser.ValueParser + +export = postcssValueParser diff --git a/src/value-parser/index.js b/src/value-parser/index.js new file mode 100644 --- /dev/null +++ b/src/value-parser/index.js @@ -0,0 +1,28 @@ +var parse = require('./parse') +var walk = require('./walk') +var stringify = require('./stringify') + +function ValueParser(value) { + if (this instanceof ValueParser) { + this.nodes = parse(value) + return this + } + return new ValueParser(value) +} + +ValueParser.prototype.toString = function () { + return Array.isArray(this.nodes) ? stringify(this.nodes) : '' +} + +ValueParser.prototype.walk = function (cb, bubble) { + walk(this.nodes, cb, bubble) + return this +} + +ValueParser.unit = require('./unit') + +ValueParser.walk = walk + +ValueParser.stringify = stringify + +module.exports = ValueParser diff --git a/src/value-parser/parse.js b/src/value-parser/parse.js new file mode 100644 --- /dev/null +++ b/src/value-parser/parse.js @@ -0,0 +1,303 @@ +var openParentheses = '('.charCodeAt(0) +var closeParentheses = ')'.charCodeAt(0) +var singleQuote = "'".charCodeAt(0) +var doubleQuote = '"'.charCodeAt(0) +var backslash = '\\'.charCodeAt(0) +var slash = '/'.charCodeAt(0) +var comma = ','.charCodeAt(0) +var colon = ':'.charCodeAt(0) +var star = '*'.charCodeAt(0) +var uLower = 'u'.charCodeAt(0) +var uUpper = 'U'.charCodeAt(0) +var plus = '+'.charCodeAt(0) +var isUnicodeRange = /^[a-f0-9?-]+$/i + +module.exports = function (input) { + var tokens = [] + var value = input + + var next, quote, prev, token, escape, escapePos, whitespacePos, parenthesesOpenPos + var pos = 0 + var code = value.charCodeAt(pos) + var max = value.length + var stack = [{ nodes: tokens }] + var balanced = 0 + var parent + + var name = '' + var before = '' + var after = '' + + while (pos < max) { + // Whitespaces + if (code <= 32) { + next = pos + do { + next += 1 + code = value.charCodeAt(next) + } while (code <= 32) + token = value.slice(pos, next) + + prev = tokens[tokens.length - 1] + if (code === closeParentheses && balanced) { + after = token + } else if (prev && prev.type === 'div') { + prev.after = token + prev.sourceEndIndex += token.length + } else if ( + code === comma || + code === colon || + (code === slash && + value.charCodeAt(next + 1) !== star && + (!parent || (parent && parent.type === 'function' && false))) + ) { + before = token + } else { + tokens.push({ + type: 'space', + sourceIndex: pos, + sourceEndIndex: next, + value: token, + }) + } + + pos = next + + // Quotes + } else if (code === singleQuote || code === doubleQuote) { + next = pos + quote = code === singleQuote ? "'" : '"' + token = { + type: 'string', + sourceIndex: pos, + quote: quote, + } + do { + escape = false + next = value.indexOf(quote, next + 1) + if (~next) { + escapePos = next + while (value.charCodeAt(escapePos - 1) === backslash) { + escapePos -= 1 + escape = !escape + } + } else { + value += quote + next = value.length - 1 + token.unclosed = true + } + } while (escape) + token.value = value.slice(pos + 1, next) + token.sourceEndIndex = token.unclosed ? next : next + 1 + tokens.push(token) + pos = next + 1 + code = value.charCodeAt(pos) + + // Comments + } else if (code === slash && value.charCodeAt(pos + 1) === star) { + next = value.indexOf('*/', pos) + + token = { + type: 'comment', + sourceIndex: pos, + sourceEndIndex: next + 2, + } + + if (next === -1) { + token.unclosed = true + next = value.length + token.sourceEndIndex = next + } + + token.value = value.slice(pos + 2, next) + tokens.push(token) + + pos = next + 2 + code = value.charCodeAt(pos) + + // Operation within calc + } else if ((code === slash || code === star) && parent && parent.type === 'function' && true) { + token = value[pos] + tokens.push({ + type: 'word', + sourceIndex: pos - before.length, + sourceEndIndex: pos + token.length, + value: token, + }) + pos += 1 + code = value.charCodeAt(pos) + + // Dividers + } else if (code === slash || code === comma || code === colon) { + token = value[pos] + + tokens.push({ + type: 'div', + sourceIndex: pos - before.length, + sourceEndIndex: pos + token.length, + value: token, + before: before, + after: '', + }) + before = '' + + pos += 1 + code = value.charCodeAt(pos) + + // Open parentheses + } else if (openParentheses === code) { + // Whitespaces after open parentheses + next = pos + do { + next += 1 + code = value.charCodeAt(next) + } while (code <= 32) + parenthesesOpenPos = pos + token = { + type: 'function', + sourceIndex: pos - name.length, + value: name, + before: value.slice(parenthesesOpenPos + 1, next), + } + pos = next + + if (name === 'url' && code !== singleQuote && code !== doubleQuote) { + next -= 1 + do { + escape = false + next = value.indexOf(')', next + 1) + if (~next) { + escapePos = next + while (value.charCodeAt(escapePos - 1) === backslash) { + escapePos -= 1 + escape = !escape + } + } else { + value += ')' + next = value.length - 1 + token.unclosed = true + } + } while (escape) + // Whitespaces before closed + whitespacePos = next + do { + whitespacePos -= 1 + code = value.charCodeAt(whitespacePos) + } while (code <= 32) + if (parenthesesOpenPos < whitespacePos) { + if (pos !== whitespacePos + 1) { + token.nodes = [ + { + type: 'word', + sourceIndex: pos, + sourceEndIndex: whitespacePos + 1, + value: value.slice(pos, whitespacePos + 1), + }, + ] + } else { + token.nodes = [] + } + if (token.unclosed && whitespacePos + 1 !== next) { + token.after = '' + token.nodes.push({ + type: 'space', + sourceIndex: whitespacePos + 1, + sourceEndIndex: next, + value: value.slice(whitespacePos + 1, next), + }) + } else { + token.after = value.slice(whitespacePos + 1, next) + token.sourceEndIndex = next + } + } else { + token.after = '' + token.nodes = [] + } + pos = next + 1 + token.sourceEndIndex = token.unclosed ? next : pos + code = value.charCodeAt(pos) + tokens.push(token) + } else { + balanced += 1 + token.after = '' + token.sourceEndIndex = pos + 1 + tokens.push(token) + stack.push(token) + tokens = token.nodes = [] + parent = token + } + name = '' + + // Close parentheses + } else if (closeParentheses === code && balanced) { + pos += 1 + code = value.charCodeAt(pos) + + parent.after = after + parent.sourceEndIndex += after.length + after = '' + balanced -= 1 + stack[stack.length - 1].sourceEndIndex = pos + stack.pop() + parent = stack[balanced] + tokens = parent.nodes + + // Words + } else { + next = pos + do { + if (code === backslash) { + next += 1 + } + next += 1 + code = value.charCodeAt(next) + } while ( + next < max && + !( + code <= 32 || + code === singleQuote || + code === doubleQuote || + code === comma || + code === colon || + code === slash || + code === openParentheses || + (code === star && parent && parent.type === 'function' && true) || + (code === slash && parent.type === 'function' && true) || + (code === closeParentheses && balanced) + ) + ) + token = value.slice(pos, next) + + if (openParentheses === code) { + name = token + } else if ( + (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) && + plus === token.charCodeAt(1) && + isUnicodeRange.test(token.slice(2)) + ) { + tokens.push({ + type: 'unicode-range', + sourceIndex: pos, + sourceEndIndex: next, + value: token, + }) + } else { + tokens.push({ + type: 'word', + sourceIndex: pos, + sourceEndIndex: next, + value: token, + }) + } + + pos = next + } + } + + for (pos = stack.length - 1; pos; pos -= 1) { + stack[pos].unclosed = true + stack[pos].sourceEndIndex = value.length + } + + return stack[0].nodes +} diff --git a/src/value-parser/stringify.js b/src/value-parser/stringify.js new file mode 100644 --- /dev/null +++ b/src/value-parser/stringify.js @@ -0,0 +1,41 @@ +function stringifyNode(node, custom) { + var type = node.type + var value = node.value + var buf + var customResult + + if (custom && (customResult = custom(node)) !== undefined) { + return customResult + } else if (type === 'word' || type === 'space') { + return value + } else if (type === 'string') { + buf = node.quote || '' + return buf + value + (node.unclosed ? '' : buf) + } else if (type === 'comment') { + return '/*' + value + (node.unclosed ? '' : '*/') + } else if (type === 'div') { + return (node.before || '') + value + (node.after || '') + } else if (Array.isArray(node.nodes)) { + buf = stringify(node.nodes, custom) + if (type !== 'function') { + return buf + } + return value + '(' + (node.before || '') + buf + (node.after || '') + (node.unclosed ? '' : ')') + } + return value +} + +function stringify(nodes, custom) { + var result, i + + if (Array.isArray(nodes)) { + result = '' + for (i = nodes.length - 1; ~i; i -= 1) { + result = stringifyNode(nodes[i], custom) + result + } + return result + } + return stringifyNode(nodes, custom) +} + +module.exports = stringify diff --git a/src/value-parser/unit.js b/src/value-parser/unit.js new file mode 100644 --- /dev/null +++ b/src/value-parser/unit.js @@ -0,0 +1,118 @@ +var minus = '-'.charCodeAt(0) +var plus = '+'.charCodeAt(0) +var dot = '.'.charCodeAt(0) +var exp = 'e'.charCodeAt(0) +var EXP = 'E'.charCodeAt(0) + +// Check if three code points would start a number +// https://www.w3.org/TR/css-syntax-3/#starts-with-a-number +function likeNumber(value) { + var code = value.charCodeAt(0) + var nextCode + + if (code === plus || code === minus) { + nextCode = value.charCodeAt(1) + + if (nextCode >= 48 && nextCode <= 57) { + return true + } + + var nextNextCode = value.charCodeAt(2) + + if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) { + return true + } + + return false + } + + if (code === dot) { + nextCode = value.charCodeAt(1) + + if (nextCode >= 48 && nextCode <= 57) { + return true + } + + return false + } + + if (code >= 48 && code <= 57) { + return true + } + + return false +} + +// Consume a number +// https://www.w3.org/TR/css-syntax-3/#consume-number +module.exports = function (value) { + var pos = 0 + var length = value.length + var code + var nextCode + var nextNextCode + + if (length === 0 || !likeNumber(value)) { + return false + } + + code = value.charCodeAt(pos) + + if (code === plus || code === minus) { + pos++ + } + + while (pos < length) { + code = value.charCodeAt(pos) + + if (code < 48 || code > 57) { + break + } + + pos += 1 + } + + code = value.charCodeAt(pos) + nextCode = value.charCodeAt(pos + 1) + + if (code === dot && nextCode >= 48 && nextCode <= 57) { + pos += 2 + + while (pos < length) { + code = value.charCodeAt(pos) + + if (code < 48 || code > 57) { + break + } + + pos += 1 + } + } + + code = value.charCodeAt(pos) + nextCode = value.charCodeAt(pos + 1) + nextNextCode = value.charCodeAt(pos + 2) + + if ( + (code === exp || code === EXP) && + ((nextCode >= 48 && nextCode <= 57) || + ((nextCode === plus || nextCode === minus) && nextNextCode >= 48 && nextNextCode <= 57)) + ) { + pos += nextCode === plus || nextCode === minus ? 3 : 2 + + while (pos < length) { + code = value.charCodeAt(pos) + + if (code < 48 || code > 57) { + break + } + + pos += 1 + } + } + + return { + number: value.slice(0, pos), + unit: value.slice(pos), + } +} diff --git a/src/value-parser/walk.js b/src/value-parser/walk.js new file mode 100644 --- /dev/null +++ b/src/value-parser/walk.js @@ -0,0 +1,18 @@ +module.exports = function walk(nodes, cb, bubble) { + var i, max, node, result + + for (i = 0, max = nodes.length; i < max; i += 1) { + node = nodes[i] + if (!bubble) { + result = cb(node, i, nodes) + } + + if (result !== false && node.type === 'function' && Array.isArray(node.nodes)) { + walk(node.nodes, cb, bubble) + } + + if (bubble) { + cb(node, i, nodes) + } + } +}
diff --git a/tests/evaluateTailwindFunctions.test.js b/tests/evaluateTailwindFunctions.test.js --- a/tests/evaluateTailwindFunctions.test.js +++ b/tests/evaluateTailwindFunctions.test.js @@ -1383,5 +1383,36 @@ crosscheck(({ stable, oxide }) => { // 4. But we've not received any further logs about it expect().toHaveBeenWarnedWith(['invalid-theme-key-in-class']) }) + + test('it works mayhaps', async () => { + let input = css` + .test { + /* prettier-ignore */ + inset: calc(-1 * (2*theme("spacing.4"))); + /* prettier-ignore */ + padding: calc(-1 * (2* theme("spacing.4"))); + } + ` + + let output = css` + .test { + /* prettier-ignore */ + inset: calc(-1 * (2*1rem)); + /* prettier-ignore */ + padding: calc(-1 * (2* 1rem)); + } + ` + + return run(input, { + theme: { + spacing: { + 4: '1rem', + }, + }, + }).then((result) => { + expect(result.css).toMatchCss(output) + expect(result.warnings().length).toBe(0) + }) + }) }) }) diff --git a/tests/source-maps.test.js b/tests/source-maps.test.js --- a/tests/source-maps.test.js +++ b/tests/source-maps.test.js @@ -260,145 +260,143 @@ crosscheck(({ stable, oxide }) => { '2:6-20 -> 304:2-12', '2:20 -> 305:0', '2:6 -> 307:0', - '2:20 -> 309:1', - '2:6 -> 310:0', - '2:6-20 -> 311:2-12', - '2:20 -> 312:0', - '2:6 -> 314:0', - '2:20 -> 316:1', - '2:6 -> 318:0', - '2:6-20 -> 319:2-18', - '2:20 -> 320:0', - '2:6 -> 322:0', - '2:20 -> 325:1', - '2:6 -> 327:0', - '2:6-20 -> 329:2-20', - '2:6-20 -> 330:2-24', - '2:20 -> 331:0', - '2:6 -> 333:0', - '2:20 -> 335:1', - '2:6 -> 337:0', - '2:6-20 -> 339:2-17', - '2:20 -> 340:0', + '2:6-20 -> 308:2-12', + '2:20 -> 309:0', + '2:6 -> 311:0', + '2:20 -> 313:1', + '2:6 -> 315:0', + '2:6-20 -> 316:2-18', + '2:20 -> 317:0', + '2:6 -> 319:0', + '2:20 -> 322:1', + '2:6 -> 324:0', + '2:6-20 -> 326:2-20', + '2:6-20 -> 327:2-24', + '2:20 -> 328:0', + '2:6 -> 330:0', + '2:20 -> 332:1', + '2:6 -> 334:0', + '2:6-20 -> 336:2-17', + '2:20 -> 337:0', + '2:6 -> 339:0', + '2:20 -> 341:1', '2:6 -> 342:0', - '2:20 -> 344:1', - '2:6 -> 345:0', - '2:6-20 -> 346:2-17', - '2:20 -> 347:0', - '2:6 -> 349:0', - '2:20 -> 353:1', - '2:6 -> 355:0', - '2:6-20 -> 363:2-24', - '2:6-20 -> 364:2-32', - '2:20 -> 365:0', - '2:6 -> 367:0', - '2:20 -> 369:1', - '2:6 -> 371:0', - '2:6-20 -> 373:2-17', - '2:6-20 -> 374:2-14', - '2:20 -> 375:0', - '2:6-20 -> 377:0-72', - '2:6 -> 378:0', - '2:6-20 -> 379:2-15', - '2:20 -> 380:0', - '2:6 -> 382:0', - '2:6-20 -> 383:2-26', - '2:6-20 -> 384:2-26', - '2:6-20 -> 385:2-21', - '2:6-20 -> 386:2-21', - '2:6-20 -> 387:2-16', - '2:6-20 -> 388:2-16', - '2:6-20 -> 389:2-16', - '2:6-20 -> 390:2-17', - '2:6-20 -> 391:2-17', - '2:6-20 -> 392:2-15', - '2:6-20 -> 393:2-15', - '2:6-20 -> 394:2-20', - '2:6-20 -> 395:2-40', - '2:6-20 -> 396:2-32', - '2:6-20 -> 397:2-31', - '2:6-20 -> 398:2-30', - '2:6-20 -> 399:2-17', - '2:6-20 -> 400:2-22', - '2:6-20 -> 401:2-24', - '2:6-20 -> 402:2-25', - '2:6-20 -> 403:2-26', - '2:6-20 -> 404:2-20', - '2:6-20 -> 405:2-29', - '2:6-20 -> 406:2-30', - '2:6-20 -> 407:2-40', - '2:6-20 -> 408:2-36', - '2:6-20 -> 409:2-29', - '2:6-20 -> 410:2-24', - '2:6-20 -> 411:2-32', - '2:6-20 -> 412:2-14', + '2:6-20 -> 343:2-17', + '2:20 -> 344:0', + '2:6 -> 346:0', + '2:20 -> 350:1', + '2:6 -> 352:0', + '2:6-20 -> 360:2-24', + '2:6-20 -> 361:2-32', + '2:20 -> 362:0', + '2:6 -> 364:0', + '2:20 -> 366:1', + '2:6 -> 368:0', + '2:6-20 -> 370:2-17', + '2:6-20 -> 371:2-14', + '2:20 -> 372:0', + '2:6-20 -> 374:0-72', + '2:6 -> 375:0', + '2:6-20 -> 376:2-15', + '2:20 -> 377:0', + '2:6 -> 379:0', + '2:6-20 -> 380:2-26', + '2:6-20 -> 381:2-26', + '2:6-20 -> 382:2-21', + '2:6-20 -> 383:2-21', + '2:6-20 -> 384:2-16', + '2:6-20 -> 385:2-16', + '2:6-20 -> 386:2-16', + '2:6-20 -> 387:2-17', + '2:6-20 -> 388:2-17', + '2:6-20 -> 389:2-15', + '2:6-20 -> 390:2-15', + '2:6-20 -> 391:2-20', + '2:6-20 -> 392:2-40', + '2:6-20 -> 393:2-32', + '2:6-20 -> 394:2-31', + '2:6-20 -> 395:2-30', + '2:6-20 -> 396:2-17', + '2:6-20 -> 397:2-22', + '2:6-20 -> 398:2-24', + '2:6-20 -> 399:2-25', + '2:6-20 -> 400:2-26', + '2:6-20 -> 401:2-20', + '2:6-20 -> 402:2-29', + '2:6-20 -> 403:2-30', + '2:6-20 -> 404:2-40', + '2:6-20 -> 405:2-36', + '2:6-20 -> 406:2-29', + '2:6-20 -> 407:2-24', + '2:6-20 -> 408:2-32', + '2:6-20 -> 409:2-14', + '2:6-20 -> 410:2-20', + '2:6-20 -> 411:2-18', + '2:6-20 -> 412:2-19', '2:6-20 -> 413:2-20', - '2:6-20 -> 414:2-18', - '2:6-20 -> 415:2-19', - '2:6-20 -> 416:2-20', - '2:6-20 -> 417:2-16', - '2:6-20 -> 418:2-18', - '2:6-20 -> 419:2-15', - '2:6-20 -> 420:2-21', - '2:6-20 -> 421:2-23', + '2:6-20 -> 414:2-16', + '2:6-20 -> 415:2-18', + '2:6-20 -> 416:2-15', + '2:6-20 -> 417:2-21', + '2:6-20 -> 418:2-23', + '2:6-20 -> 419:2-29', + '2:6-20 -> 420:2-27', + '2:6-20 -> 421:2-28', '2:6-20 -> 422:2-29', - '2:6-20 -> 423:2-27', - '2:6-20 -> 424:2-28', - '2:6-20 -> 425:2-29', - '2:6-20 -> 426:2-25', - '2:6-20 -> 427:2-26', - '2:6-20 -> 428:2-27', - '2:6 -> 429:2', - '2:20 -> 430:0', - '2:6 -> 432:0', - '2:6-20 -> 433:2-26', - '2:6-20 -> 434:2-26', - '2:6-20 -> 435:2-21', - '2:6-20 -> 436:2-21', - '2:6-20 -> 437:2-16', - '2:6-20 -> 438:2-16', - '2:6-20 -> 439:2-16', - '2:6-20 -> 440:2-17', - '2:6-20 -> 441:2-17', - '2:6-20 -> 442:2-15', - '2:6-20 -> 443:2-15', - '2:6-20 -> 444:2-20', - '2:6-20 -> 445:2-40', - '2:6-20 -> 446:2-32', - '2:6-20 -> 447:2-31', - '2:6-20 -> 448:2-30', - '2:6-20 -> 449:2-17', - '2:6-20 -> 450:2-22', - '2:6-20 -> 451:2-24', - '2:6-20 -> 452:2-25', - '2:6-20 -> 453:2-26', - '2:6-20 -> 454:2-20', - '2:6-20 -> 455:2-29', - '2:6-20 -> 456:2-30', - '2:6-20 -> 457:2-40', - '2:6-20 -> 458:2-36', - '2:6-20 -> 459:2-29', - '2:6-20 -> 460:2-24', - '2:6-20 -> 461:2-32', - '2:6-20 -> 462:2-14', + '2:6-20 -> 423:2-25', + '2:6-20 -> 424:2-26', + '2:6-20 -> 425:2-27', + '2:6 -> 426:2', + '2:20 -> 427:0', + '2:6 -> 429:0', + '2:6-20 -> 430:2-26', + '2:6-20 -> 431:2-26', + '2:6-20 -> 432:2-21', + '2:6-20 -> 433:2-21', + '2:6-20 -> 434:2-16', + '2:6-20 -> 435:2-16', + '2:6-20 -> 436:2-16', + '2:6-20 -> 437:2-17', + '2:6-20 -> 438:2-17', + '2:6-20 -> 439:2-15', + '2:6-20 -> 440:2-15', + '2:6-20 -> 441:2-20', + '2:6-20 -> 442:2-40', + '2:6-20 -> 443:2-32', + '2:6-20 -> 444:2-31', + '2:6-20 -> 445:2-30', + '2:6-20 -> 446:2-17', + '2:6-20 -> 447:2-22', + '2:6-20 -> 448:2-24', + '2:6-20 -> 449:2-25', + '2:6-20 -> 450:2-26', + '2:6-20 -> 451:2-20', + '2:6-20 -> 452:2-29', + '2:6-20 -> 453:2-30', + '2:6-20 -> 454:2-40', + '2:6-20 -> 455:2-36', + '2:6-20 -> 456:2-29', + '2:6-20 -> 457:2-24', + '2:6-20 -> 458:2-32', + '2:6-20 -> 459:2-14', + '2:6-20 -> 460:2-20', + '2:6-20 -> 461:2-18', + '2:6-20 -> 462:2-19', '2:6-20 -> 463:2-20', - '2:6-20 -> 464:2-18', - '2:6-20 -> 465:2-19', - '2:6-20 -> 466:2-20', - '2:6-20 -> 467:2-16', - '2:6-20 -> 468:2-18', - '2:6-20 -> 469:2-15', - '2:6-20 -> 470:2-21', - '2:6-20 -> 471:2-23', + '2:6-20 -> 464:2-16', + '2:6-20 -> 465:2-18', + '2:6-20 -> 466:2-15', + '2:6-20 -> 467:2-21', + '2:6-20 -> 468:2-23', + '2:6-20 -> 469:2-29', + '2:6-20 -> 470:2-27', + '2:6-20 -> 471:2-28', '2:6-20 -> 472:2-29', - '2:6-20 -> 473:2-27', - '2:6-20 -> 474:2-28', - '2:6-20 -> 475:2-29', - '2:6-20 -> 476:2-25', - '2:6-20 -> 477:2-26', - '2:6-20 -> 478:2-27', - '2:6 -> 479:2', - '2:20 -> 480:0', + '2:6-20 -> 473:2-25', + '2:6-20 -> 474:2-26', + '2:6-20 -> 475:2-27', + '2:6 -> 476:2', + '2:20 -> 477:0', ]) })
Incorrect parsing of theme functions within calc operations without spaces <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.3.1 **What build tool (or framework if it abstracts the build tool) are you using?** [play.tailwindcss.com](https://play.tailwindcss.com/) or Webpack **What version of Node.js are you using?** N/A **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/sQrIVhIaM7?file=css **Describe your issue** Usage of the `theme` function isn’t getting replaced by the corresponding value when the function is in a `calc` expression without spaces. For example: ```css .test { /* Input: */ inset: calc(-1 * (2*theme("spacing.4"))); /* Expected: */ inset: calc(-1 * (2*1rem)); /* Actual: */ inset: calc(-1 * (2*theme("spacing.4"))); } ``` --- I believe this might be the same issue as https://github.com/TrySound/postcss-value-parser/issues/86, but thought I’d report it here as I’m not 100% sure and it definitely affects Tailwind. This happened for us because we use Sass alongside Tailwind, via Webpack. sass-loader apparently outputs Sass differently in Webpack production and development mode (https://github.com/webpack-contrib/sass-loader/issues/1129), with spaces removed in production.
"2023-05-04T13:50:14Z"
3.3
[ "tests/source-maps.test.js" ]
[ "tests/evaluateTailwindFunctions.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/", "https://play.tailwindcss.com/sQrIVhIaM7?file=css" ]
tailwindlabs/tailwindcss
11,345
tailwindlabs__tailwindcss-11345
[ "11331" ]
eb8d9294c51c05713b93eb7478993b76be9d1bab
diff --git a/src/util/pseudoElements.js b/src/util/pseudoElements.js --- a/src/util/pseudoElements.js +++ b/src/util/pseudoElements.js @@ -19,12 +19,13 @@ // **Jumpable** // Any terminal element may "jump" over combinators when moving to the end of the selector // -// This is a backwards-compat quirk of :before and :after variants. +// This is a backwards-compat quirk of pseudo element variants from earlier versions of Tailwind CSS. /** @typedef {'terminal' | 'actionable' | 'jumpable'} PseudoProperty */ /** @type {Record<string, PseudoProperty[]>} */ let elementProperties = { + // Pseudo elements from the spec '::after': ['terminal', 'jumpable'], '::backdrop': ['terminal', 'jumpable'], '::before': ['terminal', 'jumpable'], @@ -41,18 +42,14 @@ let elementProperties = { '::spelling-error': ['terminal'], '::target-text': ['terminal'], - // other + // Pseudo elements from the spec with special rules '::file-selector-button': ['terminal', 'actionable'], - '::-webkit-progress-bar': ['terminal', 'actionable'], - // Webkit scroll bar pseudo elements can be combined with user-action pseudo classes - '::-webkit-scrollbar': ['terminal', 'actionable'], - '::-webkit-scrollbar-button': ['terminal', 'actionable'], - '::-webkit-scrollbar-thumb': ['terminal', 'actionable'], - '::-webkit-scrollbar-track': ['terminal', 'actionable'], - '::-webkit-scrollbar-track-piece': ['terminal', 'actionable'], - '::-webkit-scrollbar-corner': ['terminal', 'actionable'], - '::-webkit-resizer': ['terminal', 'actionable'], + // Library-specific pseudo elements used by component libraries + // These are Shadow DOM-like + '::deep': ['actionable'], + '::v-deep': ['actionable'], + '::ng-deep': ['actionable'], // Note: As a rule, double colons (::) should be used instead of a single colon // (:). This distinguishes pseudo-classes from pseudo-elements. However, since @@ -65,8 +62,8 @@ let elementProperties = { // The default value is used when the pseudo-element is not recognized // Because it's not recognized, we don't know if it's terminal or not - // So we assume it can't be moved AND can have user-action pseudo classes attached to it - __default__: ['actionable'], + // So we assume it can be moved AND can have user-action pseudo classes attached to it + __default__: ['terminal', 'actionable'], } /**
diff --git a/tests/util/apply-important-selector.test.js b/tests/util/apply-important-selector.test.js --- a/tests/util/apply-important-selector.test.js +++ b/tests/util/apply-important-selector.test.js @@ -16,6 +16,10 @@ it.each` ${':is(.foo) :is(.bar)'} | ${'#app :is(:is(.foo) :is(.bar))'} ${':is(.foo)::before'} | ${'#app :is(.foo)::before'} ${'.foo:before'} | ${'#app :is(.foo):before'} + ${'.foo::some-uknown-pseudo'} | ${'#app :is(.foo)::some-uknown-pseudo'} + ${'.foo::some-uknown-pseudo:hover'} | ${'#app :is(.foo)::some-uknown-pseudo:hover'} + ${'.foo:focus::some-uknown-pseudo:hover'} | ${'#app :is(.foo:focus)::some-uknown-pseudo:hover'} + ${'.foo:hover::some-uknown-pseudo:focus'} | ${'#app :is(.foo:hover)::some-uknown-pseudo:focus'} `('should generate "$after" from "$before"', ({ before, after }) => { expect(applyImportantSelector(before, '#app')).toEqual(after) })
Some arbitrary pseudo-elements are moved inside `:is()` when using `important` config option, breaking the selector <blockquote><details><summary><b>Tailwind CSS/browser/device version information</b></summary></br > **What version of Tailwind CSS are you using?** v3.3.2 **What build tool (or framework if it abstracts the build tool) are you using?** Tailwind Play **What version of Node.js are you using?** N/A **What browser are you using?** Chrome v114.0.5735.90 **What operating system are you using?** macOS v13.1 (22C65) </details></blockquote> **Reproduction URL** * βœ… Works when not using `important` (w/o `:is()`): https://play.tailwindcss.com/yOqpv2N25J * ❌ Breaks when using `important` (w/ `:is()`): https://play.tailwindcss.com/gVUTg4DLNK **Describe your issue** This code: **Config** ```js module.exports = { important: 'body' } ``` **Markup** ```html <progress value="5" max="10" class=" bg-gray-300 [&::-webkit-progress-bar]:bg-gray-300 [&::-moz-progress-bar]:bg-blue-500 [&::-webkit-progress-value]:bg-blue-500" /> ``` **Generated CSS** (invalid) ```css body :is(.\[\&\:\:-webkit-progress-value\]\:bg-blue-500::-webkit-progress-value) { --tw-bg-opacity: 1; background-color: rgb(59 130 246 / var(--tw-bg-opacity)); } ``` Instead of including the pseudo-element on the inside of `:is()`, it should remain on the outside, where it is valid. For example, the rendered output of `[&::-moz-progress-bar]:[&:hover]:font-bold` should be… ```css body :is(.\[\&\:\:-moz-progress-bar\]\:\[\&\:hover\]\:font-bold:hover)::-moz-progress-bar { font-weight: 700; } ``` but is currently… ```css body :is(.\[\&\:\:-moz-progress-bar\]\:\[\&\:hover\]\:font-bold:hover::-moz-progress-bar) { font-weight: 700; } ``` This is unique to pseudo-elements and does not apply to pseudo-classes. Pseudo-classes should remain on the inside of `:is()`. This already works for most pseudo-elements in TailwindCSS, so maybe it's just keeping an index of all of them. Could TailwindCSS be set up such that any time a double `::` appears, it instructs the compiler to display it after the `:is()`? I considered maybe it's the case that it keeps them all inside unless on a specific list since some devs write `:before` vs. `::before`, and trying to determine that intelligently for some like that is fine, but could the double `::`β€”when usedβ€”be set to always indicate a pseudo-element (vs. a pseudo-class)?
I meet the same problem..Even using the @csstools/postcss-is-pseudo-class plugin can't convert successfully invalid:is()
"2023-06-02T18:11:03Z"
3.3
[]
[ "tests/util/apply-important-selector.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/gVUTg4DLNK", "https://play.tailwindcss.com/yOqpv2N25J" ]
tailwindlabs/tailwindcss
11,454
tailwindlabs__tailwindcss-11454
[ "11384" ]
6722e78b35c70ac4b1bd4060f9cda9019f326241
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -21,6 +21,7 @@ import { formatBoxShadowValue, parseBoxShadowValue } from './util/parseBoxShadow import { removeAlphaVariables } from './util/removeAlphaVariables' import { flagEnabled } from './featureFlags' import { normalize } from './util/dataTypes' +import { INTERNAL_FEATURES } from './lib/setupContextUtils' export let variantPlugins = { pseudoElementVariants: ({ addVariant }) => { @@ -79,7 +80,7 @@ export let variantPlugins = { }) }, - pseudoClassVariants: ({ addVariant, matchVariant, config }) => { + pseudoClassVariants: ({ addVariant, matchVariant, config, prefix }) => { let pseudoVariants = [ // Positional ['first', '&:first-child'], @@ -150,12 +151,12 @@ export let variantPlugins = { let variants = { group: (_, { modifier }) => modifier - ? [`:merge(.group\\/${escapeClassName(modifier)})`, ' &'] - : [`:merge(.group)`, ' &'], + ? [`:merge(${prefix('.group')}\\/${escapeClassName(modifier)})`, ' &'] + : [`:merge(${prefix('.group')})`, ' &'], peer: (_, { modifier }) => modifier - ? [`:merge(.peer\\/${escapeClassName(modifier)})`, ' ~ &'] - : [`:merge(.peer)`, ' ~ &'], + ? [`:merge(${prefix('.peer')}\\/${escapeClassName(modifier)})`, ' ~ &'] + : [`:merge(${prefix('.peer')})`, ' ~ &'], } for (let [name, fn] of Object.entries(variants)) { @@ -191,7 +192,12 @@ export let variantPlugins = { return result.slice(0, start) + a + result.slice(start + 1, end) + b + result.slice(end) }, - { values: Object.fromEntries(pseudoVariants) } + { + values: Object.fromEntries(pseudoVariants), + [INTERNAL_FEATURES]: { + respectPrefix: false, + }, + } ) } }, diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -13,7 +13,7 @@ import { } from '../util/formatVariantSelector' import { asClass } from '../util/nameClass' import { normalize } from '../util/dataTypes' -import { isValidVariantFormatString, parseVariant } from './setupContextUtils' +import { isValidVariantFormatString, parseVariant, INTERNAL_FEATURES } from './setupContextUtils' import isValidArbitraryValue from '../util/isSyntacticallyValidPropertyValue' import { splitAtTopLevelOnly } from '../util/splitAtTopLevelOnly.js' import { flagEnabled } from '../featureFlags' @@ -226,9 +226,16 @@ function applyVariant(variant, matches, context) { if (context.variantMap.has(variant)) { let isArbitraryVariant = isArbitraryValue(variant) + let internalFeatures = context.variantOptions.get(variant)?.[INTERNAL_FEATURES] ?? {} let variantFunctionTuples = context.variantMap.get(variant).slice() let result = [] + let respectPrefix = (() => { + if (isArbitraryVariant) return false + if (internalFeatures.respectPrefix === false) return false + return true + })() + for (let [meta, rule] of matches) { // Don't generate variants for user css if (meta.layer === 'user') { @@ -289,7 +296,7 @@ function applyVariant(variant, matches, context) { format(selectorFormat) { collectedFormats.push({ format: selectorFormat, - isArbitraryVariant, + respectPrefix, }) }, args, @@ -318,7 +325,7 @@ function applyVariant(variant, matches, context) { if (typeof ruleWithVariant === 'string') { collectedFormats.push({ format: ruleWithVariant, - isArbitraryVariant, + respectPrefix, }) } @@ -362,7 +369,7 @@ function applyVariant(variant, matches, context) { // format: .foo & collectedFormats.push({ format: modified.replace(rebuiltBase, '&'), - isArbitraryVariant, + respectPrefix, }) rule.selector = before }) diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -23,6 +23,8 @@ import { hasContentChanged } from './cacheInvalidation.js' import { Offsets } from './offsets.js' import { finalizeSelector, formatVariantSelector } from '../util/formatVariantSelector' +export const INTERNAL_FEATURES = Symbol() + const VARIANT_TYPES = { AddVariant: Symbol.for('ADD_VARIANT'), MatchVariant: Symbol.for('MATCH_VARIANT'), @@ -1110,17 +1112,24 @@ function registerPlugins(plugins, context) { } let isArbitraryVariant = !(value in (options.values ?? {})) + let internalFeatures = options[INTERNAL_FEATURES] ?? {} + + let respectPrefix = (() => { + if (isArbitraryVariant) return false + if (internalFeatures.respectPrefix === false) return false + return true + })() formatStrings = formatStrings.map((format) => format.map((str) => ({ format: str, - isArbitraryVariant, + respectPrefix, })) ) manualFormatStrings = manualFormatStrings.map((format) => ({ format, - isArbitraryVariant, + respectPrefix, })) let opts = { diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -9,7 +9,7 @@ import { movePseudos } from './pseudoElements' /** @typedef {import('postcss-selector-parser').Pseudo} Pseudo */ /** @typedef {import('postcss-selector-parser').Node} Node */ -/** @typedef {{format: string, isArbitraryVariant: boolean}[]} RawFormats */ +/** @typedef {{format: string, respectPrefix: boolean}[]} RawFormats */ /** @typedef {import('postcss-selector-parser').Root} ParsedFormats */ /** @typedef {RawFormats | ParsedFormats} AcceptedFormats */ @@ -29,7 +29,7 @@ export function formatVariantSelector(formats, { context, candidate }) { return { ...format, - ast: format.isArbitraryVariant ? ast : prefixSelector(prefix, ast), + ast: format.respectPrefix ? prefixSelector(prefix, ast) : ast, } }) diff --git a/src/util/prefixSelector.js b/src/util/prefixSelector.js --- a/src/util/prefixSelector.js +++ b/src/util/prefixSelector.js @@ -17,6 +17,7 @@ export default function (prefix, selector, prependNegative = false) { return selector } + /** @type {import('postcss-selector-parser').Root} */ let ast = typeof selector === 'string' ? parser().astSync(selector) : selector ast.walkClasses((classSelector) => {
diff --git a/tests/format-variant-selector.test.js b/tests/format-variant-selector.test.js --- a/tests/format-variant-selector.test.js +++ b/tests/format-variant-selector.test.js @@ -4,7 +4,7 @@ it('should be possible to add a simple variant to a simple selector', () => { let selector = '.text-center' let candidate = 'hover:text-center' - let formats = [{ format: '&:hover', isArbitraryVariant: false }] + let formats = [{ format: '&:hover', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual('.hover\\:text-center:hover') }) @@ -14,8 +14,8 @@ it('should be possible to add a multiple simple variants to a simple selector', let candidate = 'focus:hover:text-center' let formats = [ - { format: '&:hover', isArbitraryVariant: false }, - { format: '&:focus', isArbitraryVariant: false }, + { format: '&:hover', respectPrefix: true }, + { format: '&:focus', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -27,7 +27,7 @@ it('should be possible to add a simple variant to a selector containing escaped let selector = '.bg-\\[rgba\\(0\\,0\\,0\\)\\]' let candidate = 'hover:bg-[rgba(0,0,0)]' - let formats = [{ format: '&:hover', isArbitraryVariant: false }] + let formats = [{ format: '&:hover', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:bg-\\[rgba\\(0\\2c 0\\2c 0\\)\\]:hover' @@ -38,7 +38,7 @@ it('should be possible to add a simple variant to a selector containing escaped let selector = '.bg-\\[rgba\\(0\\2c 0\\2c 0\\)\\]' let candidate = 'hover:bg-[rgba(0,0,0)]' - let formats = [{ format: '&:hover', isArbitraryVariant: false }] + let formats = [{ format: '&:hover', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:bg-\\[rgba\\(0\\2c 0\\2c 0\\)\\]:hover' @@ -49,7 +49,7 @@ it('should be possible to add a simple variant to a more complex selector', () = let selector = '.space-x-4 > :not([hidden]) ~ :not([hidden])' let candidate = 'hover:space-x-4' - let formats = [{ format: '&:hover', isArbitraryVariant: false }] + let formats = [{ format: '&:hover', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:space-x-4:hover > :not([hidden]) ~ :not([hidden])' @@ -61,9 +61,9 @@ it('should be possible to add multiple simple variants to a more complex selecto let candidate = 'disabled:focus:hover:space-x-4' let formats = [ - { format: '&:hover', isArbitraryVariant: false }, - { format: '&:focus', isArbitraryVariant: false }, - { format: '&:disabled', isArbitraryVariant: false }, + { format: '&:hover', respectPrefix: true }, + { format: '&:focus', respectPrefix: true }, + { format: '&:disabled', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -75,7 +75,7 @@ it('should be possible to add a single merge variant to a simple selector', () = let selector = '.text-center' let candidate = 'group-hover:text-center' - let formats = [{ format: ':merge(.group):hover &', isArbitraryVariant: false }] + let formats = [{ format: ':merge(.group):hover &', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .group-hover\\:text-center' @@ -87,8 +87,8 @@ it('should be possible to add multiple merge variants to a simple selector', () let candidate = 'group-focus:group-hover:text-center' let formats = [ - { format: ':merge(.group):hover &', isArbitraryVariant: false }, - { format: ':merge(.group):focus &', isArbitraryVariant: false }, + { format: ':merge(.group):hover &', respectPrefix: true }, + { format: ':merge(.group):focus &', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -100,7 +100,7 @@ it('should be possible to add a single merge variant to a more complex selector' let selector = '.space-x-4 ~ :not([hidden]) ~ :not([hidden])' let candidate = 'group-hover:space-x-4' - let formats = [{ format: ':merge(.group):hover &', isArbitraryVariant: false }] + let formats = [{ format: ':merge(.group):hover &', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .group-hover\\:space-x-4 ~ :not([hidden]) ~ :not([hidden])' @@ -112,8 +112,8 @@ it('should be possible to add multiple merge variants to a more complex selector let candidate = 'group-focus:group-hover:space-x-4' let formats = [ - { format: ':merge(.group):hover &', isArbitraryVariant: false }, - { format: ':merge(.group):focus &', isArbitraryVariant: false }, + { format: ':merge(.group):hover &', respectPrefix: true }, + { format: ':merge(.group):focus &', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -126,7 +126,7 @@ it('should be possible to add multiple unique merge variants to a simple selecto let candidate = 'peer-focus:group-hover:text-center' let formats = [ - { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: ':merge(.group):hover &', respectPrefix: true }, { format: ':merge(.peer):focus ~ &' }, ] @@ -140,8 +140,8 @@ it('should be possible to add multiple unique merge variants to a simple selecto let candidate = 'group-hover:peer-focus:text-center' let formats = [ - { format: ':merge(.peer):focus ~ &', isArbitraryVariant: false }, - { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: ':merge(.peer):focus ~ &', respectPrefix: true }, + { format: ':merge(.group):hover &', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -154,10 +154,10 @@ it('should be possible to use multiple :merge() calls with different "arguments" let candidate = 'peer-focus:group-focus:peer-hover:group-hover:foo' let formats = [ - { format: ':merge(.group):hover &', isArbitraryVariant: false }, - { format: ':merge(.peer):hover ~ &', isArbitraryVariant: false }, - { format: ':merge(.group):focus &', isArbitraryVariant: false }, - { format: ':merge(.peer):focus ~ &', isArbitraryVariant: false }, + { format: ':merge(.group):hover &', respectPrefix: true }, + { format: ':merge(.peer):hover ~ &', respectPrefix: true }, + { format: ':merge(.group):focus &', respectPrefix: true }, + { format: ':merge(.peer):focus ~ &', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -169,8 +169,8 @@ it('group hover and prose headings combination', () => { let selector = '.text-center' let candidate = 'group-hover:prose-headings:text-center' let formats = [ - { format: ':where(&) :is(h1, h2, h3, h4)', isArbitraryVariant: false }, // Prose Headings - { format: ':merge(.group):hover &', isArbitraryVariant: false }, // Group Hover + { format: ':where(&) :is(h1, h2, h3, h4)', respectPrefix: true }, // Prose Headings + { format: ':merge(.group):hover &', respectPrefix: true }, // Group Hover ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -182,8 +182,8 @@ it('group hover and prose headings combination flipped', () => { let selector = '.text-center' let candidate = 'prose-headings:group-hover:text-center' let formats = [ - { format: ':merge(.group):hover &', isArbitraryVariant: false }, // Group Hover - { format: ':where(&) :is(h1, h2, h3, h4)', isArbitraryVariant: false }, // Prose Headings + { format: ':merge(.group):hover &', respectPrefix: true }, // Group Hover + { format: ':where(&) :is(h1, h2, h3, h4)', respectPrefix: true }, // Prose Headings ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -195,12 +195,12 @@ it('should be possible to handle a complex utility', () => { let selector = '.space-x-4 > :not([hidden]) ~ :not([hidden])' let candidate = 'peer-disabled:peer-first-child:group-hover:group-focus:focus:hover:space-x-4' let formats = [ - { format: '&:hover', isArbitraryVariant: false }, // Hover - { format: '&:focus', isArbitraryVariant: false }, // Focus - { format: ':merge(.group):focus &', isArbitraryVariant: false }, // Group focus - { format: ':merge(.group):hover &', isArbitraryVariant: false }, // Group hover - { format: ':merge(.peer):first-child ~ &', isArbitraryVariant: false }, // Peer first-child - { format: ':merge(.peer):disabled ~ &', isArbitraryVariant: false }, // Peer disabled + { format: '&:hover', respectPrefix: true }, // Hover + { format: '&:focus', respectPrefix: true }, // Focus + { format: ':merge(.group):focus &', respectPrefix: true }, // Group focus + { format: ':merge(.group):hover &', respectPrefix: true }, // Group hover + { format: ':merge(.peer):first-child ~ &', respectPrefix: true }, // Peer first-child + { format: ':merge(.peer):disabled ~ &', respectPrefix: true }, // Peer disabled ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -221,7 +221,7 @@ it('should prefix classes from variants', () => { let context = { tailwindConfig: { prefix: 'tw-' } } let selector = '.tw-text-center' let candidate = 'foo:tw-text-center' - let formats = [{ format: '.foo &', isArbitraryVariant: false }] + let formats = [{ format: '.foo &', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate, context })).toEqual( '.tw-foo .foo\\:tw-text-center' @@ -232,7 +232,7 @@ it('should not prefix classes from arbitrary variants', () => { let context = { tailwindConfig: { prefix: 'tw-' } } let selector = '.tw-text-center' let candidate = '[.foo_&]:tw-text-center' - let formats = [{ format: '.foo &', isArbitraryVariant: true }] + let formats = [{ format: '.foo &', respectPrefix: false }] expect(finalizeSelector(selector, formats, { candidate, context })).toEqual( '.foo .\\[\\.foo_\\&\\]\\:tw-text-center' @@ -245,8 +245,8 @@ it('Merged selectors with mixed combinators uses the first one', () => { let selector = '.text-center' let candidate = 'text-center' let formats = [ - { format: ':merge(.group):focus > &', isArbitraryVariant: true }, - { format: ':merge(.group):hover &', isArbitraryVariant: true }, + { format: ':merge(.group):focus > &', respectPrefix: false }, + { format: ':merge(.group):hover &', respectPrefix: false }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -259,7 +259,7 @@ describe('real examples', () => { let selector = '.placeholder-red-500::placeholder' let candidate = 'hover:placeholder-red-500' - let formats = [{ format: '&:hover', isArbitraryVariant: false }] + let formats = [{ format: '&:hover', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.hover\\:placeholder-red-500:hover::placeholder' @@ -271,8 +271,8 @@ describe('real examples', () => { let candidate = 'group-hover:hover:space-x-4' let formats = [ - { format: '&:hover', isArbitraryVariant: false }, - { format: ':merge(.group):hover &', isArbitraryVariant: false }, + { format: '&:hover', respectPrefix: true }, + { format: ':merge(.group):hover &', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -285,8 +285,8 @@ describe('real examples', () => { let candidate = 'dark:group-hover:text-center' let formats = [ - { format: ':merge(.group):hover &', isArbitraryVariant: false }, - { format: '.dark &', isArbitraryVariant: false }, + { format: ':merge(.group):hover &', respectPrefix: true }, + { format: '.dark &', respectPrefix: true }, ] expect(finalizeSelector(selector, formats, { candidate })).toEqual( @@ -298,10 +298,7 @@ describe('real examples', () => { let selector = '.text-center' let candidate = 'group-hover:dark:text-center' - let formats = [ - { format: '.dark &' }, - { format: ':merge(.group):hover &', isArbitraryVariant: false }, - ] + let formats = [{ format: '.dark &' }, { format: ':merge(.group):hover &', respectPrefix: true }] expect(finalizeSelector(selector, formats, { candidate })).toEqual( '.group:hover .dark .group-hover\\:dark\\:text-center' @@ -355,7 +352,7 @@ describe('pseudo elements', () => { ${'.parent::placeholder input'} | ${'.parent input::placeholder'} ${'.parent::backdrop dialog'} | ${'.parent dialog::backdrop'} `('should translate "$before" into "$after"', ({ before, after }) => { - let result = finalizeSelector('.a', [{ format: before, isArbitraryVariant: false }], { + let result = finalizeSelector('.a', [{ format: before, respectPrefix: true }], { candidate: 'a', }) diff --git a/tests/getVariants.test.js b/tests/getVariants.test.js --- a/tests/getVariants.test.js +++ b/tests/getVariants.test.js @@ -65,6 +65,25 @@ it('should provide selectors for complex matchVariant variants like `group`', () expect(variant.selectors({ modifier: 'foo', value: '.foo_&' })).toEqual(['.foo .group\\/foo &']) }) +it('should provide selectors for complex matchVariant variants like `group` (when using a prefix)', () => { + let config = { prefix: 'tw-' } + let context = createContext(resolveConfig(config)) + + let variants = context.getVariants() + + let variant = variants.find((v) => v.name === 'group') + expect(variant.selectors()).toEqual(['.tw-group &']) + expect(variant.selectors({})).toEqual(['.tw-group &']) + expect(variant.selectors({ value: 'hover' })).toEqual(['.tw-group:hover &']) + expect(variant.selectors({ value: '.foo_&' })).toEqual(['.foo .tw-group &']) + expect(variant.selectors({ modifier: 'foo', value: 'hover' })).toEqual([ + '.tw-group\\/foo:hover &', + ]) + expect(variant.selectors({ modifier: 'foo', value: '.foo_&' })).toEqual([ + '.foo .tw-group\\/foo &', + ]) +}) + it('should provide selectors for variants with atrules', () => { let config = {} let context = createContext(resolveConfig(config)) diff --git a/tests/prefix.test.js b/tests/prefix.test.js --- a/tests/prefix.test.js +++ b/tests/prefix.test.js @@ -607,3 +607,33 @@ test('supports non-word prefixes (2)', async () => { } `) }) + +test('does not prefix arbitrary group/peer classes', async () => { + let config = { + prefix: 'tw-', + content: [ + { + raw: html` + <div class="tw-group tw-peer foo"> + <div class="group-[&.foo]:tw-flex"></div> + </div> + <div class="peer-[&.foo]:tw-flex"></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .tw-group.foo .group-\[\&\.foo\]\:tw-flex, + .tw-peer.foo ~ .peer-\[\&\.foo\]\:tw-flex { + display: flex; + } + `) +})
Group Class with prefix config doesn't work **What version of Tailwind CSS are you using?** For example: v3.3.2 **What build tool (or framework if it abstracts the build tool) are you using?** For example: postcss-cli 8.3.1 **What version of Node.js are you using?** For example: v14.5.0 **What operating system are you using?** For example: Ubuntu **Reproduction URL** https://play.tailwindcss.com/cxSWYn1qBg **Describe your issue** Have issue with prefix config and group hover `prefix: 'tw-'` parent : group children: group-[.class]:tw-hidden
I'm having this issue as well, except in my case I'm using custom variants as described [here](https://tailwindcss.com/docs/plugins#adding-variants). `hocus` works just fine, but `group-hocus` does not work as described in the [docs](https://tailwindcss.com/docs/plugins#parent-and-sibling-states). [Tailwind Play](https://play.tailwindcss.com/XrDo7yGNc6) @calvinagar The 2nd argument to addVariant is a selector or list of selectors. What you want is to write this as: ``` addVariant('group-hocus', [':merge(.group):hover &', ':merge(.group):focus &']) ``` Here's a [Tailwind Play](https://play.tailwindcss.com/bqT9SUXxVW?file=config) of that working.
"2023-06-19T13:32:46Z"
3.3
[]
[ "tests/format-variant-selector.test.js", "tests/getVariants.test.js", "tests/prefix.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/cxSWYn1qBg" ]
tailwindlabs/tailwindcss
11,470
tailwindlabs__tailwindcss-11470
[ "11466" ]
eae2b7a3f4f3a2981614a580a9f5534b9ffe0586
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -933,7 +933,7 @@ export let corePlugins = { }, animation: ({ matchUtilities, theme, config }) => { - let prefixName = (name) => `${config('prefix')}${escapeClassName(name)}` + let prefixName = (name) => escapeClassName(config('prefix') + name) let keyframes = Object.fromEntries( Object.entries(theme('keyframes') ?? {}).map(([key, value]) => { return [key, { [`@keyframes ${prefixName(key)}`]: value }]
diff --git a/tests/animations.test.js b/tests/animations.test.js --- a/tests/animations.test.js +++ b/tests/animations.test.js @@ -277,3 +277,33 @@ test('with dots in the name and prefix', () => { `) }) }) + +test('special character prefixes are escaped in animation names', () => { + let config = { + prefix: '@', + content: [{ raw: `<div class="@animate-one"></div>` }], + theme: { + extend: { + keyframes: { + one: { to: { transform: 'rotate(360deg)' } }, + }, + animation: { + one: 'one 2s', + }, + }, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + @keyframes \@one { + to { + transform: rotate(360deg); + } + } + .\@animate-one { + animation: 2s \@one; + } + `) + }) +})
Animation Names Won't Be Escaped If Prefix Contains Especial Characters **What version of Tailwind CSS are you using?** v3.3.2 **What build tool (or framework if it abstracts the build tool) are you using?** Tailwind Play **What version of Node.js are you using?** N/A **What browser are you using?** Chrome, Safari **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/ojvPuQftlm **Describe your issue** Using the `@` prefix in my configuration file will allow me to create animation utilities without escaping it, therefore not producing valid animations. The link above allows you to test the same implementation with the `animate-spin` and `@animate-spin` utilities (by tweaking the prefix) to see that the output CSS does not escape the `@spin` animation.
"2023-06-21T14:08:19Z"
3.3
[]
[ "tests/animations.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/ojvPuQftlm" ]
tailwindlabs/tailwindcss
12,049
tailwindlabs__tailwindcss-12049
[ "12048" ]
5366d242c25aa5e008c38a53cdfeca1cf0a22e44
diff --git a/src/util/color.js b/src/util/color.js --- a/src/util/color.js +++ b/src/util/color.js @@ -5,7 +5,7 @@ let SHORT_HEX = /^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i let VALUE = /(?:\d+|\d*\.\d+)%?/ let SEP = /(?:\s*,\s*|\s+)/ let ALPHA_SEP = /\s*[,/]\s*/ -let CUSTOM_PROPERTY = /var\(--(?:[^ )]*?)\)/ +let CUSTOM_PROPERTY = /var\(--(?:[^ )]*?)(?:,(?:[^ )]*?|var\(--[^ )]*?\)))?\)/ let RGB = new RegExp( `^(rgba?)\\(\\s*(${VALUE.source}|${CUSTOM_PROPERTY.source})(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${ALPHA_SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?\\s*\\)$`
diff --git a/tests/opacity.test.js b/tests/opacity.test.js --- a/tests/opacity.test.js +++ b/tests/opacity.test.js @@ -1045,3 +1045,21 @@ it('can replace the potential alpha value in rgba/hsla syntax', async () => { } `) }) + +it('variables with variable fallback values can use opacity modifier', async () => { + let config = { + content: [ + { + raw: html`<div class="bg-[rgb(var(--some-var,var(--some-other-var)))]/50"></div>`, + }, + ], + } + + let result = await run(`@tailwind utilities;`, config) + + expect(result.css).toMatchFormattedCss(css` + .bg-\[rgb\(var\(--some-var\,var\(--some-other-var\)\)\)\]\/50 { + background-color: rgb(var(--some-var, var(--some-other-var)) / 0.5); + } + `) +})
Background opacity modifier does not work with CSS variable's fallback value <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** version: 3.3.3 **What build tool (or framework if it abstracts the build tool) are you using?** play.tailwindcss.com **What version of Node.js are you using?** browser **What browser are you using?** chrome **What operating system are you using?** macOs **Reproduction URL** https://play.tailwindcss.com/djB8sJngwG **Describe your issue** Full example code: ```html <div class="flex flex-col gap-4 m-10 [--color-red:255_0_0]"> <div class="h-10 w-80 bg-red-500">1. classic</div> <div class="h-10 w-80 bg-[#f00]">2. custom color</div> <div class="h-10 w-80 bg-[rgb(var(--color-red))]">3. custom color from var</div> <div class="h-10 w-80 bg-[rgb(var(--broken-var,var(--color-red)))]">4. custom color from var with fallback</div> <div class="h-10 w-80 bg-[rgb(var(--color-red))]/50">5. custom color from var with opacity</div> <div class="h-10 w-80 bg-[rgb(var(--broken-var,var(--color-red)))]/50">6. custom color from var with fallback and with opacity</div> <div class="h-10 w-80 bg-[rgb(var(--broken-var,var(--color-red))/0.5)]">7. custom color from var with fallback and with "manual" opacity</div> </div> ``` It seems tailwind is unable to properly process such syntax: `bg-[rgb(var(--broken-var,var(--color-red)))]/50`. There's no output at all. The reason for this is most likely CSS variable being nested for fallback value. For nested `var()` without opacity modifier: `bg-[rgb(var(--broken-var,var(--color-red)))]` the output is correct: ```css .bg-\[rgb\(var\(--broken-var\2c var\(--color-red\)\)\)\]{ background-color: rgb(var(--broken-var,var(--color-red))) } ``` The only reasonable workaround I found is to "manually" apply alpha value to `rgb()` function like so: `bg-[rgb(var(--broken-var,var(--color-red))/0.5)]`, which gives an output that I would expect to get for the broken example: ```css .bg-\[rgb\(var\(--broken-var\2c var\(--color-red\)\)\/0\.5\)\]{ background-color: rgb(var(--broken-var,var(--color-red))/0.5) } ``` However, I think it would be great to be able to use consistent syntax across all use-cases.
"2023-09-20T20:17:08Z"
3.3
[]
[ "tests/opacity.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/djB8sJngwG" ]
tailwindlabs/tailwindcss
12,105
tailwindlabs__tailwindcss-12105
[ "12099" ]
61dc99f4adbebdbcfeb899f3bcd64167b49d758c
diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -147,43 +147,45 @@ function getClasses(selector, mutate) { return parser.transformSync(selector) } +/** + * Ignore everything inside a :not(...). This allows you to write code like + * `div:not(.foo)`. If `.foo` is never found in your code, then we used to + * not generated it. But now we will ignore everything inside a `:not`, so + * that it still gets generated. + * + * @param {selectorParser.Root} selectors + */ +function ignoreNot(selectors) { + selectors.walkPseudos((pseudo) => { + if (pseudo.value === ':not') { + pseudo.remove() + } + }) +} + function extractCandidates(node, state = { containsNonOnDemandable: false }, depth = 0) { let classes = [] + let selectors = [] - // Handle normal rules if (node.type === 'rule') { - // Ignore everything inside a :not(...). This allows you to write code like - // `div:not(.foo)`. If `.foo` is never found in your code, then we used to - // not generated it. But now we will ignore everything inside a `:not`, so - // that it still gets generated. - function ignoreNot(selectors) { - selectors.walkPseudos((pseudo) => { - if (pseudo.value === ':not') { - pseudo.remove() - } - }) - } + // Handle normal rules + selectors.push(...node.selectors) + } else if (node.type === 'atrule') { + // Handle at-rules (which contains nested rules) + node.walkRules((rule) => selectors.push(...rule.selectors)) + } - for (let selector of node.selectors) { - let classCandidates = getClasses(selector, ignoreNot) - // At least one of the selectors contains non-"on-demandable" candidates. - if (classCandidates.length === 0) { - state.containsNonOnDemandable = true - } + for (let selector of selectors) { + let classCandidates = getClasses(selector, ignoreNot) - for (let classCandidate of classCandidates) { - classes.push(classCandidate) - } + // At least one of the selectors contains non-"on-demandable" candidates. + if (classCandidates.length === 0) { + state.containsNonOnDemandable = true } - } - // Handle at-rules (which contains nested rules) - else if (node.type === 'atrule') { - node.walkRules((rule) => { - for (let classCandidate of rule.selectors.flatMap((selector) => getClasses(selector))) { - classes.push(classCandidate) - } - }) + for (let classCandidate of classCandidates) { + classes.push(classCandidate) + } } if (depth === 0) {
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -760,3 +760,35 @@ test('handled quoted arbitrary values containing escaped spaces', async () => { ` ) }) + +test('Skips classes inside :not() when nested inside an at-rule', async () => { + let config = { + content: [ + { + raw: html` <div class="disabled !disabled"></div> `, + }, + ], + corePlugins: { preflight: false }, + plugins: [ + function ({ addUtilities }) { + addUtilities({ + '.hand:not(.disabled)': { + '@supports (cursor: pointer)': { + cursor: 'pointer', + }, + }, + }) + }, + ], + } + + let input = css` + @tailwind utilities; + ` + + // We didn't find the hand class therefore + // nothing should be generated + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css``) +})
Tailwind looks for classes inside `:not()` in utilities and components when in at-rules <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.3.3 **What build tool (or framework if it abstracts the build tool) are you using?** Next.js 13.4.13 (Tool agnostic bug) **What version of Node.js are you using?** For example: v18.16.0 **What browser are you using?** For example: Chrome **What operating system are you using?** For example: Windows **Reproduction URL** https://play.tailwindcss.com/Tg2m8Otzun **Describe your issue** Tailwind searches for importance for things like `disabled` in places that are not classnames. As shown in the example above, DaisyUI applies variants upon hover when the component is not disabled. Because Tailwind sees a string `!disabled`, the styles applied in Daisy's hover variant become important and thus overshadow things like the active style. If you hold click on the menu options in the playground, nothing happens. However, if you remove the `!disabled` span and hold click, you will see the proper `:active` styles become applied This also happens in React (checking a variable, for instance) and is documented here: https://github.com/saadeghi/daisyui/issues/2240
Hey, thanks for reporting this. > Tailwind searches for importance for things like disabled in places that are not classnames. This is by design. Not everyone uses Tailwind in HTML but in JSX, Svelte, Pug, etc… Parsing files to find class names and to do so properly would have significant limitations as we would have to understand the code, how it works at build time, and how it works at runtime. This is not feasible for Tailwind itself. Tailwind CSS scans entire source files for matches generally regardless of where that match occurs. This means you can get false positives but you can typically use the `blocklist` feature to work around this. > If you hold click on the menu options in the playground, nothing happens. However, if you remove the !disabled span and hold click, you will see the proper :active styles become applied This is definitely a bug. We do not traverse classes inside `:not()` β€” but it is still (incorrectly) traversed when inside an at rule. Minimized repro: https://play.tailwindcss.com/GMBdxJHeL9?file=config I'll look at this in the am. @thecrypticace I think the level of how tailwind scans the code is too much ![image](https://github.com/tailwindlabs/tailwindcss/assets/26060677/2c8e4e04-2aeb-4193-832f-b7ffea42fdb8)
"2023-09-28T14:26:04Z"
3.3
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/Tg2m8Otzun" ]
tailwindlabs/tailwindcss
12,112
tailwindlabs__tailwindcss-12112
[ "12110" ]
d32228628ed45941a3ca1d2ca9d946d72c0d0cfa
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -553,6 +553,13 @@ function processApply(root, context, localCache) { ? parent.selector.slice(importantSelector.length) : parent.selector + // If the selector becomes empty after replacing the important selector + // This means that it's the same as the parent selector and we don't want to replace it + // Otherwise we'll crash + if (parentSelector === '') { + parentSelector = parent.selector + } + rule.selector = replaceSelector(parentSelector, rule.selector, applyCandidate) // And then re-add it if it was removed
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -2081,3 +2081,55 @@ test('::ng-deep, ::deep, ::v-deep pseudo elements are left alone', () => { `) }) }) + +test('should not break replacing important selector when the same as the parent selector (pseudo)', async () => { + let config = { + important: ':root', + content: [], + } + + let input = css` + @tailwind components; + @layer components { + :root { + @apply flex; + } + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + :root { + display: flex; + } + `) +}) + +test('should not break replacing important selector when the same as the parent selector (class)', async () => { + let config = { + important: '.foo', + content: [ + { + raw: html` <div class="foo"></div> `, + }, + ], + } + + let input = css` + @tailwind components; + @layer components { + .foo { + @apply flex; + } + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .foo { + display: flex; + } + `) +})
Compilation error for rule reusing important selector within a layer and using @apply **What version of Tailwind CSS are you using?** v3.3.3 Reproduced on current play.tailwindcss.com version **What build tool (or framework if it abstracts the build tool) are you using?** vite v4.4.9 postcss v8.4.29 **What version of Node.js are you using?** v18.17.0 **What browser are you using?** N/A **What operating system are you using?** Ubuntu **Reproduction URL** https://play.tailwindcss.com/xsicGQjVTh **Describe your issue** When using a selector in the `important` configuration option, adding a class using that same selector within a layer and using `@apply` causes a compilation error. e.g. ```js // config { important: '.a-class', } // css @layer base { .a-class { @apply font-bold; } } ``` The crash seems to happen in [applyImportantSelector.js](https://github.com/tailwindlabs/tailwindcss/blob/d32228628ed45941a3ca1d2ca9d946d72c0d0cfa/src/util/applyImportantSelector.js#L10) because `sel.nodes` is an empty array, and it is assumed `sel.nodes[0]` is defined. Either not using `@apply` or moving out of the `@layer` block makes this work as expected.
"2023-09-29T15:54:22Z"
3.3
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/xsicGQjVTh" ]
tailwindlabs/tailwindcss
12,113
tailwindlabs__tailwindcss-12113
[ "12111" ]
457d2b1b1c5dc09b2edbc92f1dd1499a00cd4ef0
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -815,10 +815,19 @@ function applyFinalFormat(match, { context, candidate }) { } try { - rule.selector = finalizeSelector(rule.selector, finalFormat, { + let selector = finalizeSelector(rule.selector, finalFormat, { candidate, context, }) + + // Finalize Selector determined that this candidate is irrelevant + // TODO: This elimination should happen earlier so this never happens + if (selector === null) { + rule.remove() + return + } + + rule.selector = selector } catch { // If this selector is invalid we also want to skip it // But it's likely that being invalid here means there's a bug in a plugin rather than too loosely matching content diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -186,6 +186,13 @@ export function finalizeSelector(current, formats, { context, candidate, base }) // Remove extraneous selectors that do not include the base candidate selector.each((sel) => eliminateIrrelevantSelectors(sel, base)) + // If ffter eliminating irrelevant selectors, we end up with nothing + // Then the whole "rule" this is associated with does not need to exist + // We use `null` as a marker value for that case + if (selector.length === 0) { + return null + } + // If there are no formats that means there were no variants added to the candidate // so we can just return the selector as-is let formatAst = Array.isArray(formats)
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -792,3 +792,46 @@ test('Skips classes inside :not() when nested inside an at-rule', async () => { expect(result.css).toMatchFormattedCss(css``) }) + +test('Irrelevant rules are removed when applying variants', async () => { + let config = { + content: [ + { + raw: html` <div class="md:w-full"></div> `, + }, + ], + corePlugins: { preflight: false }, + plugins: [ + function ({ addUtilities }) { + addUtilities({ + '@supports (foo: bar)': { + // This doesn't contain `w-full` so it should not exist in the output + '.outer': { color: 'red' }, + '.outer:is(.w-full)': { color: 'green' }, + }, + }) + }, + ], + } + + let input = css` + @tailwind utilities; + ` + + // We didn't find the hand class therefore + // nothing should be generated + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + @media (min-width: 768px) { + .md\:w-full { + width: 100%; + } + @supports (foo: bar) { + .outer.md\:w-full { + color: green; + } + } + } + `) +})
Combination of TW JS based config and a class causes malformed CSS **What version of Tailwind CSS are you using?** v3.3.3 **What build tool (or framework if it abstracts the build tool) are you using?** Vite v4.4.9 **What version of Node.js are you using?** v20.7.0 **What browser are you using?** Any **What operating system are you using?** macOS 14.0 **Reproduction URL** https://play.tailwindcss.com/jZXL8Axggn **Describe your issue** What I have is this: **A Tailwind config file containing the following:** ```js '@media screen(md)': { '.outer-grid': { rowGap: theme('spacing.16'), paddingTop: theme('spacing.16'), paddingBottom: theme('spacing.16'), }, '.outer-grid>*:last-child:is(.w-full)': { marginBottom: `-${theme('spacing.16')}`, }, }, ``` **A class in my templates** `[&>*]:after:w-full` The combination of this JS config and this class trips up something and results in compilation warings and the following CSS in my compiled file: ```css @media (min-width: 768px) { { content: var(--tw-content); row-gap: 4rem; padding-top: 4rem; padding-bottom: 4rem } .outer-grid>*:last-child:is(.\[\&\>\*\]\:before\:w-full>*):before { content: var(--tw-content); margin-bottom: -4rem } } ``` I noticed this because of the error `npm run build` produces: ``` warnings when minifying css: β–² [WARNING] Unexpected "{" [css-syntax-error] <stdin>:2610:3: 2610 β”‚ { ``` And I can even see in VS code with the TW extension the malformed CSS when I hover over this one class: <img width="893" alt="Screenshot_2023-09-28_at_17 09 03" src="https://github.com/tailwindlabs/tailwindcss/assets/69107412/a8730642-f74d-43e7-8439-0c0903778464"> When I either: - Remove the class from my templates, or - Remove the ` '.outer-grid>*:last-child:is(.w-full)'` statement from the `@media sceen(md)` query, the warning and malformed CSS is gone. Note that the ` '.outer-grid>*:last-child:is(.w-full)'` statement _not_ in a media query compiles without issues. A workaround is to use an attribute selector instead `[class~="w-full"]`. https://play.tailwindcss.com/i6OoVDdQbc?file=config
"2023-09-29T20:14:25Z"
3.3
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/i6OoVDdQbc?file=config", "https://play.tailwindcss.com/jZXL8Axggn" ]
tailwindlabs/tailwindcss
12,324
tailwindlabs__tailwindcss-12324
[ "12318" ]
8f788e27b09d1a09a23f0e33d127145d36fe1a03
diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -78,7 +78,7 @@ export function normalize(value, context = null, isRoot = true) { /** * Add spaces around operators inside math functions - * like calc() that do not follow an operator or '('. + * like calc() that do not follow an operator, '(', or `,`. * * @param {string} value * @returns {string} @@ -165,7 +165,7 @@ function normalizeMathOperatorSpacing(value) { // Handle operators else if ( ['+', '-', '*', '/'].includes(char) && - !['(', '+', '-', '*', '/'].includes(lastChar()) + !['(', '+', '-', '*', '/', ','].includes(lastChar()) ) { result += ` ${char} ` } else {
diff --git a/tests/normalize-data-types.test.js b/tests/normalize-data-types.test.js --- a/tests/normalize-data-types.test.js +++ b/tests/normalize-data-types.test.js @@ -68,6 +68,9 @@ let table = [ ['calc(theme(spacing.foo-2))', 'calc(theme(spacing.foo-2))'], ['calc(theme(spacing.foo-bar))', 'calc(theme(spacing.foo-bar))'], + // A negative number immediately after a `,` should not have spaces inserted + ['clamp(-3px+4px,-3px+4px,-3px+4px)', 'clamp(-3px + 4px,-3px + 4px,-3px + 4px)'], + // Prevent formatting inside `var()` functions ['calc(var(--foo-bar-bar)*2)', 'calc(var(--foo-bar-bar) * 2)'],
Arbituray Value using Clamp() doesn't work if there is a negative value <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.3.3 **What build tool (or framework if it abstracts the build tool) are you using?** postcss 8.4.31, postcss-cli 10.1.0, webpack 5.89.0 **What version of Node.js are you using?** v16.14.0 **What browser are you using?** Chrome 118.0.5993.118 **What operating system are you using?** Windows 10 **Reproduction URL** Can't provide URL of the project. But it can be replicated on TailwindPlay https://play.tailwindcss.com/BuKHeMD2uv on Line 18 mt-[clamp(0.25rem,-0.6731rem+4.1026vw,4.25rem)] I'm Using this [Font-size Clamp Generator](https://clamp.font-size.app/?config=eyJyb290IjoiMTYiLCJtaW5XaWR0aCI6IjM2MHB4IiwibWF4V2lkdGgiOiIxOTIwcHgiLCJtaW5Gb250U2l6ZSI6IjRweCIsIm1heEZvbnRTaXplIjoiNjhweCJ9). Screenshot of Configuration: https://snipboard.io/zXFA3o.jpg **Describe your issue** mt-[clamp(0.25rem,-0.6731rem+4.1026vw,4.25rem)] It add space to "-" Screenshot: https://snipboard.io/SEMTQZ.jpg
Hey @rexsoi! I noticed that the example you shared contains incorrect CSS. If you want to perform computations within the `clamp` function, wrap it with `calc`: `mt-[clamp(0.25rem,-0.6731rem+4.1026vw,4.25rem)]` => `mt-[clamp(0.25rem,calc(-0.6731rem+4.1026vw),4.25rem)]` @alex-krasikau Nah, that's not true (it may have been in the past though? β€” I don't recall). Any math function in CSS supports expressions. Though, you _can_ use `calc()` as a workaround for the errant space. Ex: https://play.tailwindcss.com/zohf7KMMmg
"2023-10-30T14:32:58Z"
3.3
[]
[ "tests/normalize-data-types.test.js" ]
TypeScript
[ "https://snipboard.io/zXFA3o.jpg", "https://snipboard.io/SEMTQZ.jpg" ]
[ "https://play.tailwindcss.com/BuKHeMD2uv" ]
tailwindlabs/tailwindcss
12,515
tailwindlabs__tailwindcss-12515
[ "12362" ]
b2b37e04e4d861901bb76781d34faa638a251a35
diff --git a/src/util/pluginUtils.js b/src/util/pluginUtils.js --- a/src/util/pluginUtils.js +++ b/src/util/pluginUtils.js @@ -87,6 +87,22 @@ function isArbitraryValue(input) { function splitUtilityModifier(modifier) { let slashIdx = modifier.lastIndexOf('/') + // If the `/` is inside an arbitrary, we want to find the previous one if any + // This logic probably isn't perfect but it should work for most cases + let arbitraryStartIdx = modifier.lastIndexOf('[', slashIdx) + let arbitraryEndIdx = modifier.indexOf(']', slashIdx) + + let isNextToArbitrary = modifier[slashIdx - 1] === ']' || modifier[slashIdx + 1] === '[' + + // Backtrack to the previous `/` if the one we found was inside an arbitrary + if (!isNextToArbitrary) { + if (arbitraryStartIdx !== -1 && arbitraryEndIdx !== -1) { + if (arbitraryStartIdx < slashIdx && slashIdx < arbitraryEndIdx) { + slashIdx = modifier.lastIndexOf('/', arbitraryStartIdx) + } + } + } + if (slashIdx === -1 || slashIdx === modifier.length - 1) { return [modifier, undefined] }
diff --git a/tests/arbitrary-values.test.js b/tests/arbitrary-values.test.js --- a/tests/arbitrary-values.test.js +++ b/tests/arbitrary-values.test.js @@ -639,6 +639,21 @@ it('should support underscores in arbitrary modifiers', () => { }) }) +it('should support slashes in arbitrary modifiers', () => { + let config = { + content: [{ raw: html`<div class="text-lg/[calc(50px/1rem)]"></div>` }], + } + + return run('@tailwind utilities', config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .text-lg\/\[calc\(50px\/1rem\)\] { + font-size: 1.125rem; + line-height: calc(50px / 1rem); + } + `) + }) +}) + it('should not insert spaces around operators inside `env()`', () => { let config = { content: [{ raw: html`<div class="grid-cols-[calc(env(safe-area-inset-bottom)+1px)]"></div>` }],
`/` is not allowed in arbitrary modifier Version: 3.3.5 Repro: https://play.tailwindcss.com/yLjHBexR1d Not really something I wrote in real life, just something I though of when testing edge cases of my own implementation. So could be considered as not supported, this is issue is just to let you know. Feel free to close!
"2023-11-30T16:14:02Z"
3.3
[]
[ "tests/arbitrary-values.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/yLjHBexR1d" ]
tailwindlabs/tailwindcss
12,639
tailwindlabs__tailwindcss-12639
[ "12623" ]
a091db5df4651fde85fcf917b11fdaa210b79623
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -118,10 +118,20 @@ function applyImportant(matches, classCandidate) { let result = [] + function isInKeyframes(rule) { + return rule.parent && rule.parent.type === 'atrule' && rule.parent.name === 'keyframes' + } + for (let [meta, rule] of matches) { let container = postcss.root({ nodes: [rule.clone()] }) container.walkRules((r) => { + // Declarations inside keyframes cannot be marked as important + // They will be ignored by the browser + if (isInKeyframes(r)) { + return + } + let ast = selectorParser().astSync(r.selector) // Remove extraneous selectors that do not include the base candidate
diff --git a/tests/important-modifier.test.js b/tests/important-modifier.test.js --- a/tests/important-modifier.test.js +++ b/tests/important-modifier.test.js @@ -147,3 +147,32 @@ test('the important modifier works on utilities using :where()', () => { `) }) }) + +test('the important modifier does not break keyframes', () => { + let config = { + content: [ + { + raw: html` <div class="!animate-pulse"></div> `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + @keyframes pulse { + 50% { + opacity: 0.5; + } + } + + .\!animate-pulse { + animation: 2s cubic-bezier(0.4, 0, 0.6, 1) infinite pulse !important; + } + `) + }) +})
important modifier on animation breaks keyframes <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.4.0 **What build tool (or framework if it abstracts the build tool) are you using?** postcss 8.4.32 **What version of Node.js are you using?** v21.4.0 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/4mir5NtQdV **Describe your issue** If you use the !important modifier for animations, the keyframe steps of the animation are removed (and the animation breaks). You can also see this in tailwind intellisense. ![CleanShot 2023-12-19 at 23 02 29@2x](https://github.com/tailwindlabs/tailwindcss/assets/2500670/f2079572-00a0-4825-a79f-2e4d7015eeed)
"2023-12-21T16:36:36Z"
3.3
[]
[ "tests/important-modifier.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/4mir5NtQdV" ]
tailwindlabs/tailwindcss
12,704
tailwindlabs__tailwindcss-12704
[ "12665" ]
b52a78b56f329af8714bf2664a673bd2f2b2e336
diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -107,6 +107,13 @@ function normalizeMathOperatorSpacing(value) { 'keyboard-inset-left', 'keyboard-inset-width', 'keyboard-inset-height', + + 'radial-gradient', + 'linear-gradient', + 'conic-gradient', + 'repeating-radial-gradient', + 'repeating-linear-gradient', + 'repeating-conic-gradient', ] return value.replace(/(calc|min|max|clamp)\(.+\)/g, (match) => { @@ -162,6 +169,11 @@ function normalizeMathOperatorSpacing(value) { result += consumeUntil([')']) } + // Don't break CSS grid track names + else if (peek('[')) { + result += consumeUntil([']']) + } + // Handle operators else if ( ['+', '-', '*', '/'].includes(char) &&
diff --git a/tests/normalize-data-types.test.js b/tests/normalize-data-types.test.js --- a/tests/normalize-data-types.test.js +++ b/tests/normalize-data-types.test.js @@ -86,6 +86,16 @@ let table = [ // Prevent formatting keywords ['minmax(min-content,25%)', 'minmax(min-content,25%)'], + // Prevent formatting keywords + [ + 'radial-gradient(calc(1+2)),radial-gradient(calc(1+2))', + 'radial-gradient(calc(1 + 2)),radial-gradient(calc(1 + 2))', + ], + [ + '[content-start]_calc(100%-1px)_[content-end]_minmax(1rem,1fr)', + '[content-start] calc(100% - 1px) [content-end] minmax(1rem,1fr)', + ], + // Misc ['color(0_0_0/1.0)', 'color(0 0 0/1.0)'], ['color(0_0_0_/_1.0)', 'color(0 0 0 / 1.0)'],
Arbitrary values for 'radial-gradient' generate incorrect CSS <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** 3.4.0 **What build tool (or framework if it abstracts the build tool) are you using?** Next.js 14.0.4 **What version of Node.js are you using?** 18.15.0 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/wORjugi1Xl **Describe your issue** This is similar to #12654 and #12281 using arbitrary background values with multiple radial gradients. Here is the input ```html <div class="w-screen h-screen bg-[radial-gradient(ellipse_539px_673px_at_calc(50vw_-_539px)_0px,red_0px,transparent_70dvh),radial-gradient(circle_at_calc(50vw_+_539px)_100dvh,blue_0%,transparent_75dvh)]"> Test </div> ``` Here is the generated output CSS ```css .bg-\[radial-gradient\(ellipse_539px_673px_at_calc\(50vw_-_539px\)_0px\2c red_0px\2c transparent_70dvh\)\2c radial-gradient\(circle_at_calc\(50vw_\+_539px\)_100dvh\2c blue_0\%\2c transparent_75dvh\)\] { background-image: radial-gradient(ellipse 539px 673px at calc(50vw - 539px) 0px,red 0px,transparent 70dvh), radial - gradient(circle at calc(50vw + 539px) 100dvh,blue 0%,transparent 75dvh); } ``` Notice the second radial-gradient is generated as `radial - gradient` with spaces. The correct CSS should be ```css .bg-\[radial-gradient\(ellipse_539px_673px_at_calc\(50vw_-_539px\)_0px\2c red_0px\2c transparent_70dvh\)\2c radial-gradient\(circle_at_calc\(50vw_\+_539px\)_100dvh\2c blue_0\%\2c transparent_75dvh\)\] { background-image: radial-gradient(ellipse 539px 673px at calc(50vw - 539px) 0px,red 0px,transparent 70dvh), radial-gradient(circle at calc(50vw + 539px) 100dvh,blue 0%,transparent 75dvh); } ```
Here's an even more minimal reproduction for when we get a chance to look at this properly: https://play.tailwindcss.com/WgsZXMdp0Y Culprit seems to be the presence of `calc` in the first gradient β€” without that the second `radial-gradient` has no spaces like expected.
"2024-01-03T17:51:46Z"
3.3
[]
[ "tests/normalize-data-types.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/wORjugi1Xl" ]
tailwindlabs/tailwindcss
13,379
tailwindlabs__tailwindcss-13379
[ "13037" ]
97607f1cfb30103db96747c9b9e50fefa117fbb4
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -270,7 +270,7 @@ export let variantPlugins = { addVariant('dark', selector) } else if (mode === 'class') { // Old behavior - addVariant('dark', `:is(${selector} &)`) + addVariant('dark', `&:is(${selector} *)`) } },
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -2212,3 +2212,40 @@ test('applying user defined classes with nested CSS should result in an error', `) }) }) + +test('applying classes with class-based dark variant to pseudo elements', async () => { + let config = { + darkMode: 'class', + content: [], + } + + let input = css` + ::-webkit-scrollbar-track { + @apply bg-white dark:bg-black; + } + ::-webkit-scrollbar-track:hover { + @apply bg-blue-600 dark:bg-blue-500; + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + ::-webkit-scrollbar-track { + --tw-bg-opacity: 1; + background-color: rgb(255 255 255 / var(--tw-bg-opacity)); + } + :is(.dark *)::-webkit-scrollbar-track { + --tw-bg-opacity: 1; + background-color: rgb(0 0 0 / var(--tw-bg-opacity)); + } + ::-webkit-scrollbar-track:hover { + --tw-bg-opacity: 1; + background-color: rgb(37 99 235 / var(--tw-bg-opacity)); + } + :is(.dark *)::-webkit-scrollbar-track:hover { + --tw-bg-opacity: 1; + background-color: rgb(59 130 246 / var(--tw-bg-opacity)); + } + `) +}) diff --git a/tests/dark-mode.test.js b/tests/dark-mode.test.js --- a/tests/dark-mode.test.js +++ b/tests/dark-mode.test.js @@ -16,7 +16,7 @@ it('should be possible to use the darkMode "class" mode', () => { return run(input, config).then((result) => { expect(result.css).toMatchFormattedCss(css` ${defaults} - :is(.dark .dark\:font-bold) { + .dark\:font-bold:is(.dark *) { font-weight: 700; } `) @@ -39,7 +39,7 @@ it('should be possible to change the class name', () => { return run(input, config).then((result) => { expect(result.css).toMatchFormattedCss(css` ${defaults} - :is(.test-dark .dark\:font-bold) { + .dark\:font-bold:is(.test-dark *) { font-weight: 700; } `) @@ -133,7 +133,7 @@ it('should support the deprecated `class` dark mode behavior', () => { return run(input, config).then((result) => { expect(result.css).toMatchFormattedCss(css` - :is(.dark .dark\:font-bold) { + .dark\:font-bold:is(.dark *) { font-weight: 700; } `) @@ -153,7 +153,7 @@ it('should support custom classes with deprecated `class` dark mode', () => { return run(input, config).then((result) => { expect(result.css).toMatchFormattedCss(css` - :is(.my-dark .dark\:font-bold) { + .dark\:font-bold:is(.my-dark *) { font-weight: 700; } `) @@ -181,7 +181,7 @@ it('should use legacy sorting when using `darkMode: class`', () => { --tw-text-opacity: 1; color: rgb(187 247 208 / var(--tw-text-opacity)); } - :is(.dark .dark\:text-green-100) { + .dark\:text-green-100:is(.dark *) { --tw-text-opacity: 1; color: rgb(220 252 231 / var(--tw-text-opacity)); }
dark selector does not work correctly in @apply starting from version 3.3.0 <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?**: v3.3.0 **What build tool (or framework if it abstracts the build tool) are you using?**: postcss-cli 8.4.32, Next.js 13.4.19, webpack **What version of Node.js are you using?**: v20 **What browser are you using?**: Chrome **What operating system are you using?**: Windows **Reproduction URL**: https://play.tailwindcss.com/8lfHYybqfC **Describe your issue** In the repro you can see that in the latest version of tw v3 the scrollbar does not turn green in dark mode, while it does in v2. There is a workaround if you use the .dark class: ```css /* THIS DOES NOT WORK */ ::-webkit-scrollbar-track { @apply bg-yellow-800 dark:bg-green-800; } ::-webkit-scrollbar-thumb { @apply bg-yellow-500 dark:bg-green-500; } ::-webkit-scrollbar-thumb:hover { @apply bg-yellow-600 dark:bg-green-600; } /* THIS DOES WORK */ ::-webkit-scrollbar-track { @apply bg-yellow-800 } ::-webkit-scrollbar-thumb { @apply bg-yellow-500 } ::-webkit-scrollbar-thumb:hover { @apply bg-yellow-600 } .dark ::-webkit-scrollbar-track { @apply bg-green-800; } .dark ::-webkit-scrollbar-thumb { @apply bg-green-500; } .dark ::-webkit-scrollbar-thumb:hover { @apply bg-green-600; } ``` This should work with the first option as well. This issue has already been reported in different discussions without a repro, or in similar issues that were linked to a specific framework. - I got the workaround from this similar discussion: https://github.com/tailwindlabs/tailwindcss/discussions/2917#discussioncomment-6435337 - description of this issue without repro https://github.com/tailwindlabs/tailwindcss/discussions/11497 - description of this issue without repro https://github.com/tailwindlabs/tailwindcss/discussions/11665 - Not sure, but I think it's related https://github.com/tailwindlabs/tailwindcss/discussions/11077 - Linked to Angular: https://github.com/tailwindlabs/tailwindcss/issues/12352 - Linked to Vue: https://github.com/tailwindlabs/tailwindcss/issues/11024 According to [the release article of v3.3](https://tailwindcss.com/blog/tailwindcss-v3-3#new-caption-side-utilities) there should be no breaking changes. This is one though.
Definitely a real bug, thanks for reporting! My gut is we can fix this by updating the `class` strategy implementation to work like the `selector` strategy implementation, where we put the `&` at the front: ```diff } else if (mode === 'class') { - addVariant('dark', `:is(${selector} &)`) + addVariant('dark', `&:is(${selector}, ${selector} *)`) } ``` By the looks of it, our internals will properly hoist out the pseudo-elements automatically if we move things around this way. Will try to get this patched up this week πŸ‘ @adamwathan i am interested can you assign it me I came across the same issue with my next project. I solved it by making these changes in tailwind.config.js: from `darkMode: ["class", "[data-theme='dark']"],` into `darkMode: ["selector", "[data-theme='dark']"],` ["The selector strategy replaced the class strategy in Tailwind CSS v3.4.1."](https://tailwindcss.com/docs/dark-mode)
"2024-03-27T14:14:41Z"
3.4
[]
[ "tests/dark-mode.test.js", "tests/apply.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/8lfHYybqfC" ]
tailwindlabs/tailwindcss
13,740
tailwindlabs__tailwindcss-13740
[ "13716" ]
f1f419a9ecfcd00a2001ee96ab252739fca47564
diff --git a/src/util/pluginUtils.js b/src/util/pluginUtils.js --- a/src/util/pluginUtils.js +++ b/src/util/pluginUtils.js @@ -124,7 +124,7 @@ export function parseColorFormat(value) { if (typeof value === 'string' && value.includes('<alpha-value>')) { let oldValue = value - return ({ opacityValue = 1 }) => oldValue.replace('<alpha-value>', opacityValue) + return ({ opacityValue = 1 }) => oldValue.replace(/<alpha-value>/g, opacityValue) } return value
diff --git a/tests/opacity.test.js b/tests/opacity.test.js --- a/tests/opacity.test.js +++ b/tests/opacity.test.js @@ -673,6 +673,30 @@ it('should be possible to use an <alpha-value> as part of the color definition w }) }) +it('should be possible to use multiple <alpha-value>s as part of the color definition with an opacity modifiers', () => { + let config = { + content: [ + { + raw: html` <div class="bg-primary/50"></div> `, + }, + ], + corePlugins: ['backgroundColor'], + theme: { + colors: { + primary: 'light-dark(rgb(0 0 0 / <alpha-value>), rgb(255 255 255 / <alpha-value>))', + }, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .bg-primary\/50 { + background-color: light-dark(rgb(0 0 0 / 0.5), rgb(255 255 255 / 0.5)); + } + `) + }) +}) + it('should be possible to use an <alpha-value> as part of the color definition with an opacity modifiers', () => { let config = { content: [
`<alpha-value>` is not recognized on reuse **What version of Tailwind CSS are you using?** v3.4.3 (last) **Reproduction URL** https://play.tailwindcss.com/iK3QZJynRz?file=config **Describe your issue** <img width="800" alt="image" src="https://github.com/tailwindlabs/tailwindcss/assets/625005/d43b6f8d-47a8-4994-8568-3767c0ce76cb"> Tailwind config ``` /** @type {import('tailwindcss').Config} */ export default { theme: { extend: { colors: { ⬇⬇⬇⬇⬇⬇⬇⬇ ⬇⬇⬇⬇⬇⬇⬇⬇ primary: 'light-dark(rgb(0 0 0 / <alpha-value>), rgb(255 255 255 / <alpha-value>))', } }, }, } ``` CSS ``` ⬇⬇ ⬇⬇⬇⬇⬇⬇⬇⬇ color: light-dark(rgb(0 0 0 / 0.5), rgb(255 255 255 / <alpha-value>)); ``` When adding a color to a Tailwind setting with more than one use of `<alpha-value>` in a single value, only the first occurrence of `<alpha-value>` is recognized. More information is available [here](https://github.com/tailwindlabs/tailwindcss/discussions/12172#discussioncomment-9236533) (сс @olyckne).
"2024-05-24T23:31:51Z"
3.4
[]
[ "tests/opacity.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/iK3QZJynRz?file=config" ]
tailwindlabs/tailwindcss
13,770
tailwindlabs__tailwindcss-13770
[ "13769" ]
9fda4616eb5706223374c921c9ee4d90903f6fee
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -434,23 +434,40 @@ export let variantPlugins = { ) }, - hasVariants: ({ matchVariant }) => { - matchVariant('has', (value) => `&:has(${normalize(value)})`, { values: {} }) + hasVariants: ({ matchVariant, prefix }) => { + matchVariant('has', (value) => `&:has(${normalize(value)})`, { + values: {}, + [INTERNAL_FEATURES]: { + respectPrefix: false, + }, + }) + matchVariant( 'group-has', (value, { modifier }) => modifier - ? `:merge(.group\\/${modifier}):has(${normalize(value)}) &` - : `:merge(.group):has(${normalize(value)}) &`, - { values: {} } + ? `:merge(${prefix('.group')}\\/${modifier}):has(${normalize(value)}) &` + : `:merge(${prefix('.group')}):has(${normalize(value)}) &`, + { + values: {}, + [INTERNAL_FEATURES]: { + respectPrefix: false, + }, + } ) + matchVariant( 'peer-has', (value, { modifier }) => modifier - ? `:merge(.peer\\/${modifier}):has(${normalize(value)}) ~ &` - : `:merge(.peer):has(${normalize(value)}) ~ &`, - { values: {} } + ? `:merge(${prefix('.peer')}\\/${modifier}):has(${normalize(value)}) ~ &` + : `:merge(${prefix('.peer')}):has(${normalize(value)}) ~ &`, + { + values: {}, + [INTERNAL_FEATURES]: { + respectPrefix: false, + }, + } ) },
diff --git a/tests/prefix.test.js b/tests/prefix.test.js --- a/tests/prefix.test.js +++ b/tests/prefix.test.js @@ -637,3 +637,132 @@ test('does not prefix arbitrary group/peer classes', async () => { } `) }) + +test('does not prefix has-* variants with arbitrary values', async () => { + let config = { + prefix: 'tw-', + content: [ + { + raw: html` + <div class="has-[.active]:tw-flex foo"> + <figure class="has-[figcaption]:tw-inline-block"></figure> + <div class="has-[.foo]:tw-flex"></div> + <div class="has-[.foo:hover]:tw-block"></div> + <div class="has-[[data-active]]:tw-inline"></div> + <div class="has-[>_.potato]:tw-table"></div> + <div class="has-[+_h2]:tw-grid"></div> + <div class="has-[>_h1_+_h2]:tw-contents"></div> + <div class="has-[h2]:has-[.banana]:tw-hidden"></div> + </div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .has-\[\.foo\:hover\]\:tw-block:has(.foo:hover) { + display: block; + } + .has-\[figcaption\]\:tw-inline-block:has(figcaption) { + display: inline-block; + } + .has-\[\[data-active\]\]\:tw-inline:has([data-active]) { + display: inline; + } + .has-\[\.active\]\:tw-flex:has(.active), + .has-\[\.foo\]\:tw-flex:has(.foo) { + display: flex; + } + .has-\[\>_\.potato\]\:tw-table:has(> .potato) { + display: table; + } + .has-\[\+_h2\]\:tw-grid:has(+ h2) { + display: grid; + } + .has-\[\>_h1_\+_h2\]\:tw-contents:has(> h1 + h2) { + display: contents; + } + .has-\[h2\]\:has-\[\.banana\]\:tw-hidden:has(.banana):has(h2) { + display: none; + } + `) +}) + +test('does not prefix group-has-* variants with arbitrary values', () => { + let config = { + prefix: 'tw-', + theme: {}, + content: [ + { + raw: html` + <div class="tw-group"> + <div class="group-has-[>_h1_+_.foo]:tw-block"></div> + </div> + <div class="tw-group/two"> + <div class="group-has-[>_h1_+_.foo]/two:tw-flex"></div> + </div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .tw-group:has(> h1 + .foo) .group-has-\[\>_h1_\+_\.foo\]\:tw-block { + display: block; + } + .tw-group\/two:has(> h1 + .foo) .group-has-\[\>_h1_\+_\.foo\]\/two\:tw-flex { + display: flex; + } + `) + }) +}) + +test('does not prefix peer-has-* variants with arbitrary values', () => { + let config = { + prefix: 'tw-', + theme: {}, + content: [ + { + raw: html` + <div> + <div className="tw-peer"></div> + <div class="peer-has-[>_h1_+_.foo]:tw-block"></div> + </div> + <div> + <div className="tw-peer"></div> + <div class="peer-has-[>_h1_+_.foo]/two:tw-flex"></div> + </div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .tw-peer:has(> h1 + .foo) ~ .peer-has-\[\>_h1_\+_\.foo\]\:tw-block { + display: block; + } + .tw-peer\/two:has(> h1 + .foo) ~ .peer-has-\[\>_h1_\+_\.foo\]\/two\:tw-flex { + display: flex; + } + `) + }) +})
Classes are prefixed when using `has-*` variants with arbitrary values **What version of Tailwind CSS are you using?** v3.4.3 **What build tool (or framework if it abstracts the build tool) are you using?** Tested using `play.tailwindcss.com` and added some test to `tailwindcss` repo. **What version of Node.js are you using?** v20.9.0 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/TJ9YW9YcGi https://play.tailwindcss.com/abhsA5hh21 ![shot2024-05-31 at 08 58 17@2x](https://github.com/tailwindlabs/tailwindcss/assets/3856862/7101deb8-559c-4f7d-b5a7-706714bf6040) **Describe your issue** Classes are prefixed when using `has-*` variants with arbitrary values
"2024-05-31T06:59:16Z"
3.4
[]
[ "tests/prefix.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/abhsA5hh21", "https://play.tailwindcss.com/TJ9YW9YcGi" ]
tailwindlabs/tailwindcss
13,781
tailwindlabs__tailwindcss-13781
[ "13754" ]
669109efdd8f89c6949ae496eb1e95b528603976
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -741,11 +741,19 @@ export let corePlugins = { zIndex: createUtilityPlugin('zIndex', [['z', ['zIndex']]], { supportsNegativeValues: true }), order: createUtilityPlugin('order', undefined, { supportsNegativeValues: true }), gridColumn: createUtilityPlugin('gridColumn', [['col', ['gridColumn']]]), - gridColumnStart: createUtilityPlugin('gridColumnStart', [['col-start', ['gridColumnStart']]]), - gridColumnEnd: createUtilityPlugin('gridColumnEnd', [['col-end', ['gridColumnEnd']]]), + gridColumnStart: createUtilityPlugin('gridColumnStart', [['col-start', ['gridColumnStart']]], { + supportsNegativeValues: true, + }), + gridColumnEnd: createUtilityPlugin('gridColumnEnd', [['col-end', ['gridColumnEnd']]], { + supportsNegativeValues: true, + }), gridRow: createUtilityPlugin('gridRow', [['row', ['gridRow']]]), - gridRowStart: createUtilityPlugin('gridRowStart', [['row-start', ['gridRowStart']]]), - gridRowEnd: createUtilityPlugin('gridRowEnd', [['row-end', ['gridRowEnd']]]), + gridRowStart: createUtilityPlugin('gridRowStart', [['row-start', ['gridRowStart']]], { + supportsNegativeValues: true, + }), + gridRowEnd: createUtilityPlugin('gridRowEnd', [['row-end', ['gridRowEnd']]], { + supportsNegativeValues: true, + }), float: ({ addUtilities }) => { addUtilities({
diff --git a/tests/negative-prefix.test.js b/tests/negative-prefix.test.js --- a/tests/negative-prefix.test.js +++ b/tests/negative-prefix.test.js @@ -360,3 +360,27 @@ test('addUtilities without negative prefix + variant + negative prefix in conten expect(result.css).toMatchCss(css``) }) + +test('negative col/row-start/end utilities', () => { + let config = { + content: [{ raw: html`<div class="-col-start-4 -col-end-4 -row-start-4 -row-end-4"></div>` }], + corePlugins: { preflight: false }, + } + + return run('@tailwind utilities;', config).then((result) => { + expect(result.css).toMatchCss(css` + .-col-start-4 { + grid-column-start: -4; + } + .-col-end-4 { + grid-column-end: -4; + } + .-row-start-4 { + grid-row-start: -4; + } + .-row-end-4 { + grid-row-end: -4; + } + `) + }) +})
Col-end does not support negative values This is a very small issue, col-end does not support negative values out of the box, but negative values makes a lot of sense there. This happens on **v3.4.3**. https://play.tailwindcss.com/8L8o0VhDfr The code is here: ~~~ html <div class="grid grid-cols-3"> <div class="-col-end-1">BROKEN</div> <div class="col-end-[-1]">WORKS</div> </div> ~~~ I'm not sure if this is exactly a bug, because it is not explicitly described in the documentation, but it is a broken expectation (I've expected that to work for consistency).
"2024-06-03T15:22:42Z"
3.4
[]
[ "tests/negative-prefix.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/8L8o0VhDfr" ]
tailwindlabs/tailwindcss
13,826
tailwindlabs__tailwindcss-13826
[ "13818" ]
ff6f085da2afe4149ab2791b8b6b74836dbbba9f
diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -19,6 +19,7 @@ function isCSSFunction(value) { // More info: // - https://drafts.csswg.org/scroll-animations/#propdef-timeline-scope // - https://developer.mozilla.org/en-US/docs/Web/CSS/timeline-scope#dashed-ident +// - https://www.w3.org/TR/css-anchor-position-1 // const AUTO_VAR_INJECTION_EXCEPTIONS = new Set([ // Concrete properties @@ -26,11 +27,16 @@ const AUTO_VAR_INJECTION_EXCEPTIONS = new Set([ 'timeline-scope', 'view-timeline-name', 'font-palette', + 'anchor-name', + 'anchor-scope', + 'position-anchor', + 'position-try-options', // Shorthand properties 'scroll-timeline', 'animation-timeline', 'view-timeline', + 'position-try', ]) // This is not a data type, but rather a function that can normalize the
diff --git a/tests/normalize-data-types.test.js b/tests/normalize-data-types.test.js --- a/tests/normalize-data-types.test.js +++ b/tests/normalize-data-types.test.js @@ -112,7 +112,18 @@ it('should not automatically inject the `var()` for properties that accept `<das { raw: '[color:--foo]' }, // Automatic var injection is skipped + { raw: '[scroll-timeline-name:--foo]' }, { raw: '[timeline-scope:--foo]' }, + { raw: '[view-timeline-name:--foo]' }, + { raw: '[font-palette:--foo]' }, + { raw: '[anchor-name:--foo]' }, + { raw: '[anchor-scope:--foo]' }, + { raw: '[position-anchor:--foo]' }, + { raw: '[position-try-options:--foo]' }, + { raw: '[scroll-timeline:--foo]' }, + { raw: '[animation-timeline:--foo]' }, + { raw: '[view-timeline:--foo]' }, + { raw: '[position-try:--foo]' }, ], } @@ -122,13 +133,45 @@ it('should not automatically inject the `var()` for properties that accept `<das return run(input, config).then((result) => { expect(result.css).toMatchFormattedCss(css` + .\[anchor-name\:--foo\] { + anchor-name: --foo; + } + .\[anchor-scope\:--foo\] { + anchor-scope: --foo; + } + .\[animation-timeline\:--foo\] { + animation-timeline: --foo; + } .\[color\:--foo\] { color: var(--foo); } - + .\[font-palette\:--foo\] { + font-palette: --foo; + } + .\[position-anchor\:--foo\] { + position-anchor: --foo; + } + .\[position-try-options\:--foo\] { + position-try-options: --foo; + } + .\[position-try\:--foo\] { + position-try: --foo; + } + .\[scroll-timeline-name\:--foo\] { + scroll-timeline-name: --foo; + } + .\[scroll-timeline\:--foo\] { + scroll-timeline: --foo; + } .\[timeline-scope\:--foo\] { timeline-scope: --foo; } + .\[view-timeline-name\:--foo\] { + view-timeline-name: --foo; + } + .\[view-timeline\:--foo\] { + view-timeline: --foo; + } `) }) })
Arbitrary value for `anchor-name` outputs as custom variable instead of identifier value <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** `v3.4.4` **What build tool (or framework if it abstracts the build tool) are you using?** `"next": "^14.2.3"` **What version of Node.js are you using?** `v18.15.0` **What browser are you using?** N/A **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/fagqAhZl3j ```html <div class="[anchor-name:--foo]"></div> <div class="hover:[anchor-name:--foo]"></div> ``` **Describe your issue** Arbitrary value for `anchor-name` outputs as custom variable (`var(--foo)`) instead of the desired identifier value (`--foo`). Per specs by Chrome: https://developer.chrome.com/blog/anchor-positioning-api [Current issue] the above outputs as: ```css .\[anchor-name\:--foo\] { anchor-name: var(--foo); } .hover\:\[anchor-name\:--foo\]:hover { anchor-name: var(--foo); } ``` [Desired] `--foo` instead of `var(--foo)` ```css .\[anchor-name\:--foo\] { anchor-name: --foo; } .hover\:\[anchor-name\:--foo\]:hover { anchor-name: --foo; } ```
MOhammadreza Xeradm@nd 🧠 Original MOhammadreza 🧠 Original
"2024-06-12T14:05:58Z"
3.4
[]
[ "tests/normalize-data-types.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/fagqAhZl3j" ]
tailwindlabs/tailwindcss
3,850
tailwindlabs__tailwindcss-3850
[ "3834" ]
23b71a9a36b9327683d4548d654434ee4c2482f5
diff --git a/src/plugins/gradientColorStops.js b/src/plugins/gradientColorStops.js --- a/src/plugins/gradientColorStops.js +++ b/src/plugins/gradientColorStops.js @@ -2,7 +2,7 @@ import _ from 'lodash' import flattenColorPalette from '../util/flattenColorPalette' import nameClass from '../util/nameClass' import toColorValue from '../util/toColorValue' -import { toRgba } from '../util/withAlphaVariable' +import { toRgba, toHsla } from '../util/withAlphaVariable' export default function () { return function ({ addUtilities, theme, variants }) { @@ -16,8 +16,9 @@ export default function () { } try { - const [r, g, b] = toRgba(value) - return `rgba(${r}, ${g}, ${b}, 0)` + const isHSL = value.startsWith('hsl') + const [i, j, k] = isHSL ? toHsla(value) : toRgba(value) + return `${isHSL ? 'hsla' : 'rgba'}(${i}, ${j}, ${k}, 0)` } catch (_error) { return `rgba(255, 255, 255, 0)` } diff --git a/src/plugins/ringWidth.js b/src/plugins/ringWidth.js --- a/src/plugins/ringWidth.js +++ b/src/plugins/ringWidth.js @@ -1,20 +1,21 @@ import _ from 'lodash' import nameClass from '../util/nameClass' -import { toRgba } from '../util/withAlphaVariable' +import { toHsla, toRgba } from '../util/withAlphaVariable' export default function () { return function ({ addUtilities, theme, variants }) { - function safeCall(callback, defaultValue) { + const ringColorDefault = (() => { + const isHSL = (theme('ringColor.DEFAULT') || '').startsWith('hsl') + const opacity = theme('ringOpacity.DEFAULT', '0.5') try { - return callback() + const [i, j, k] = isHSL + ? toHsla(theme('ringColor.DEFAULT')) + : toRgba(theme('ringColor.DEFAULT')) + return `${isHSL ? 'hsla' : 'rgba'}(${i}, ${j}, ${k}, ${opacity})` } catch (_error) { - return defaultValue + return `rgba(147, 197, 253, ${opacity})` } - } - - const ringColorDefault = (([r, g, b]) => { - return `rgba(${r}, ${g}, ${b}, ${theme('ringOpacity.DEFAULT', '0.5')})` - })(safeCall(() => toRgba(theme('ringColor.DEFAULT')), ['147', '197', '253'])) + })() addUtilities( { diff --git a/src/util/withAlphaVariable.js b/src/util/withAlphaVariable.js --- a/src/util/withAlphaVariable.js +++ b/src/util/withAlphaVariable.js @@ -16,6 +16,12 @@ export function toRgba(color) { return [r, g, b, a === undefined && hasAlpha(color) ? 1 : a] } +export function toHsla(color) { + const [h, s, l, a] = createColor(color).hsl().array() + + return [h, `${s}%`, `${l}%`, a === undefined && hasAlpha(color) ? 1 : a] +} + export default function withAlphaVariable({ color, property, variable }) { if (_.isFunction(color)) { return { @@ -25,7 +31,9 @@ export default function withAlphaVariable({ color, property, variable }) { } try { - const [r, g, b, a] = toRgba(color) + const isHSL = color.startsWith('hsl') + + const [i, j, k, a] = isHSL ? toHsla(color) : toRgba(color) if (a !== undefined) { return { @@ -35,7 +43,7 @@ export default function withAlphaVariable({ color, property, variable }) { return { [variable]: '1', - [property]: `rgba(${r}, ${g}, ${b}, var(${variable}))`, + [property]: `${isHSL ? 'hsla' : 'rgba'}(${i}, ${j}, ${k}, var(${variable}))`, } } catch (error) { return {
diff --git a/__tests__/plugins/gradientColorStops.test.js b/__tests__/plugins/gradientColorStops.test.js --- a/__tests__/plugins/gradientColorStops.test.js +++ b/__tests__/plugins/gradientColorStops.test.js @@ -17,6 +17,7 @@ test('opacity variables are given to colors defined as closures', () => { return `rgb(31,31,31)` }, + secondary: 'hsl(10, 50%, 50%)', }, opacity: { 50: '0.5', @@ -33,23 +34,47 @@ test('opacity variables are given to colors defined as closures', () => { .process('@tailwind utilities', { from: undefined }) .then((result) => { const expected = ` - .text-primary { - --tw-text-opacity: 1; - color: rgba(31,31,31,var(--tw-text-opacity)) - } - .text-opacity-50 { - --tw-text-opacity: 0.5 - } - .from-primary { - --tw-gradient-from: rgb(31,31,31); - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(31, 31, 31, 0)) - } - .via-primary { - --tw-gradient-stops: var(--tw-gradient-from), rgb(31,31,31), var(--tw-gradient-to, rgba(31, 31, 31, 0)) - } - .to-primary { - --tw-gradient-to: rgb(31,31,31) - } + .text-primary { + --tw-text-opacity: 1; + color: rgba(31, 31, 31, var(--tw-text-opacity)); + } + + .text-secondary { + --tw-text-opacity: 1; + color: hsla(10, 50%, 50%, var(--tw-text-opacity)); + } + + .text-opacity-50 { + --tw-text-opacity: 0.5; + } + + .from-primary { + --tw-gradient-from: rgb(31, 31, 31); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(31, 31, 31, 0)); + } + + .from-secondary { + --tw-gradient-from: hsl(10, 50%, 50%); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, hsla(10, 50%, 50%, 0)); + } + + .via-primary { + --tw-gradient-stops: var(--tw-gradient-from), rgb(31, 31, 31), + var(--tw-gradient-to, rgba(31, 31, 31, 0)); + } + + .via-secondary { + --tw-gradient-stops: var(--tw-gradient-from), hsl(10, 50%, 50%), + var(--tw-gradient-to, hsla(10, 50%, 50%, 0)); + } + + .to-primary { + --tw-gradient-to: rgb(31, 31, 31); + } + + .to-secondary { + --tw-gradient-to: hsl(10, 50%, 50%); + } ` expect(result.css).toMatchCss(expected) diff --git a/__tests__/plugins/ringWidth.test.js b/__tests__/plugins/ringWidth.test.js --- a/__tests__/plugins/ringWidth.test.js +++ b/__tests__/plugins/ringWidth.test.js @@ -61,6 +61,51 @@ test('ring widths', () => { ]) }) +test('ring widths with defaults and hsl value for ringColor', () => { + const config = { + theme: { + ringWidth: {}, + ringOffsetWidth: { + DEFAULT: '2px', + }, + ringOffsetColor: { + DEFAULT: 'pink', + }, + ringColor: { + DEFAULT: 'hsl(10, 50%, 50%)', + }, + }, + variants: { + ringColor: [], + }, + } + + const { utilities } = invokePlugin(plugin(), config) + expect(utilities).toEqual([ + [ + { + '*': { + '--tw-ring-color': 'hsla(10, 50%, 50%, 0.5)', + '--tw-ring-inset': 'var(--tw-empty,/*!*/ /*!*/)', + '--tw-ring-offset-color': 'pink', + '--tw-ring-offset-shadow': '0 0 #0000', + '--tw-ring-offset-width': '2px', + '--tw-ring-shadow': '0 0 #0000', + }, + }, + { respectImportant: false }, + ], + [ + { + '.ring-inset': { + '--tw-ring-inset': 'inset', + }, + }, + undefined, + ], + ]) +}) + test('ring widths with defaults', () => { const config = { theme: { diff --git a/__tests__/withAlphaVariable.test.js b/__tests__/withAlphaVariable.test.js --- a/__tests__/withAlphaVariable.test.js +++ b/__tests__/withAlphaVariable.test.js @@ -118,3 +118,26 @@ test('it allows a closure to be passed', () => { 'background-color': 'rgba(0, 0, 0, var(--tw-bg-opacity))', }) }) + +test('it transforms rgb and hsl to rgba and hsla', () => { + expect( + withAlphaVariable({ + color: 'rgb(50, 50, 50)', + property: 'background-color', + variable: '--tw-bg-opacity', + }) + ).toEqual({ + '--tw-bg-opacity': '1', + 'background-color': 'rgba(50, 50, 50, var(--tw-bg-opacity))', + }) + expect( + withAlphaVariable({ + color: 'hsl(50, 50%, 50%)', + property: 'background-color', + variable: '--tw-bg-opacity', + }) + ).toEqual({ + '--tw-bg-opacity': '1', + 'background-color': 'hsla(50, 50%, 50%, var(--tw-bg-opacity))', + }) +})
Preserve HSL colors instead of converting to RGBA (keeps colors on older browsers) ### What version of Tailwind CSS are you using? v2.0.4 ### What version of Node.js are you using? v14.16.0 ### What browser are you using? N/A ### What operating system are you using? macOS ### Reproduction repository see body I'm using HSL color definitions in a project instead of RGB/hex. With Tailwind 2.0, the `hsl()` values in my tailwind.config.js get converted to `rgba()` rules (so the opacity classes can [work their dark magic](https://adamwathan.me/composing-the-uncomposable-with-css-variables/)). However, because HSL -> RGB isn't a simple add/subtract swap, the resulting CSS uses floats for each color channel: ```js // tailwind.config.js module.exports = { theme: { colors: { offblack: 'hsl(205,95%,2%)' } } } ``` ```css /* resulting CSS */ .text-offblack { --tw-text-opacity: 1; color: rgba(.2550000000000002,5.907499999999999,9.945,var(--tw-text-opacity)); } ``` The trouble with this is that [browser support for floats in rgba](https://caniuse.com/mdn-css_types_color_floats_in_rgb_rgba) wasn't good until the last couple years. That means people with older browsers (something like 5% of traffic) **will see NO COLORS AT ALL** on my site with Tailwind 2.0 β€” everything is black and white. Can we make Tailwind keep HSL values and output `hsla()` colors instead of `rgba()`? _Originally posted by @andronocean in https://github.com/tailwindlabs/tailwindcss/discussions/3833_
I don't really see how this would matter considering the stats of people using old browsers are a very small minority ![image](https://nbb.rocks/i/Fl4dB.png) Safari is actually the biggest problem for browser support, vis a vis current usage. It didn't support floats until late 2018/early 2019 (somewhere in v12.1.x) And since iOS safari versions are pegged to iOS upgrades, a lot of older iPhones and iPads cannot get support now. So depending on the geography and device trends of your visitors, you could be saying 3% - 10% of visitors get no colors ([caniuse data](https://caniuse.com/mdn-css_types_color_floats_in_rgb_rgba)): <img width="655" alt="Screen Shot 2021-03-24 at 8 01 33 PM" src="https://user-images.githubusercontent.com/26490481/112399011-ce315c80-8cdb-11eb-9f80-204adea55ab4.png"> Personally, I think colors are pretty dang fundamental to the web, and need to work everywhere they reasonably can. But furthermore, I think the developer experience is important. If I define HSL colors, I'm doing so for a reason, and there's no good reason for Tailwind to change them. Admittedly, a good chunk of the browsers that this breaks on also lack custom properties support, so the colors still wouldn't work out of the box for them, due to the opacity variable. Tailwind is upfront about its use of custom properties, however, so if that matters to a developer they are likely to address it with some sort of fallback. It's not going to be an undocumented surprise like the HSL > RGBA behavior in question. Just note that `hsl()` could also be converted to `hsla()`. I can raise a PR if needed. ---- edit: @andronocean have you tried to use `hsla()` instead of `hsl()? Because it should not transform it. @fedeci it's indeed not transforming it to `rgba` if you use `hsla`, but the problem is you lose the capacity to apply opacity utilities like `text-opacity-{n}` or `bg-opacity-{n}`. It basically returns the `hsla` color only, instead of composing it with a CSS variable for the alpha transparency. I've actually just recorded a video that covers how to "bring back" the support for opacity in colors, by defining colors as functions. It doesn't cover `hsla` in particular, but this would be a possible solution - we'll release that video soon. You can see the code responsible for the "transform" here: https://github.com/tailwindlabs/tailwindcss/blob/master/src/util/withAlphaVariable.js But like Adam mentioned in the GitHub discussion, we could probably implement support for `hsla` colors, so users don't have to manually compose them with Tailwind's internal `opacityVariable` that is used to set the alpha transparency channel πŸ‘
"2021-03-26T10:28:46Z"
2.1
[]
[ "__tests__/withAlphaVariable.test.js", "__tests__/plugins/ringWidth.test.js", "__tests__/plugins/gradientColorStops.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
4,102
tailwindlabs__tailwindcss-4102
[ "3136" ]
77ef26015645dc767a1f520cf4f7772696702e5c
diff --git a/src/lib/substituteVariantsAtRules.js b/src/lib/substituteVariantsAtRules.js --- a/src/lib/substituteVariantsAtRules.js +++ b/src/lib/substituteVariantsAtRules.js @@ -124,6 +124,7 @@ const defaultVariantGenerators = (config) => ({ hover: generatePseudoClassVariant('hover'), 'focus-within': generatePseudoClassVariant('focus-within'), 'focus-visible': generatePseudoClassVariant('focus-visible'), + 'read-only': generatePseudoClassVariant('read-only'), focus: generatePseudoClassVariant('focus'), active: generatePseudoClassVariant('active'), visited: generatePseudoClassVariant('visited'), diff --git a/stubs/defaultConfig.stub.js b/stubs/defaultConfig.stub.js --- a/stubs/defaultConfig.stub.js +++ b/stubs/defaultConfig.stub.js @@ -807,6 +807,7 @@ module.exports = { 'visited', 'checked', 'empty', + 'read-only', 'group-hover', 'group-focus', 'focus-within',
diff --git a/tests/variantsAtRule.test.js b/tests/variantsAtRule.test.js --- a/tests/variantsAtRule.test.js +++ b/tests/variantsAtRule.test.js @@ -569,6 +569,27 @@ test('it can generate hover, active and focus variants', () => { }) }) +test('it can generate read-only variants', () => { + const input = ` + @variants read-only { + .banana { color: yellow; } + .chocolate { color: brown; } + } + ` + + const output = ` + .banana { color: yellow; } + .chocolate { color: brown; } + .read-only\\:banana:read-only { color: yellow; } + .read-only\\:chocolate:read-only { color: brown; } + ` + + return run(input).then((result) => { + expect(result.css).toMatchCss(output) + expect(result.warnings().length).toBe(0) + }) +}) + test('it can generate hover, active and focus variants for multiple classes in one rule', () => { const input = ` @variants hover, focus, active { @@ -648,7 +669,7 @@ test('variants are generated in the order specified', () => { test('the built-in variant pseudo-selectors are appended before any pseudo-elements', () => { const input = ` - @variants hover, focus-within, focus-visible, focus, active, group-hover { + @variants hover, focus-within, focus-visible, focus, active, group-hover, read-only { .placeholder-yellow::placeholder { color: yellow; } } ` @@ -661,6 +682,7 @@ test('the built-in variant pseudo-selectors are appended before any pseudo-eleme .focus\\:placeholder-yellow:focus::placeholder { color: yellow; } .active\\:placeholder-yellow:active::placeholder { color: yellow; } .group:hover .group-hover\\:placeholder-yellow::placeholder { color: yellow; } + .read-only\\:placeholder-yellow:read-only::placeholder { color: yellow; } ` return run(input).then((result) => {
Read only variant There's currently no variant for `<input>` elements with the `readonly` attribute. I added this myself today following the [variant plugin documentation](https://tailwindcss.com/docs/plugins#adding-variants), but wanted to check whether this would be a good inclusion to the framework as a variant users can turn on. Thoughts? If it's a good fit, I can probably do a PR relatively quickly.
Hey! No concrete plans to add this but since we already have `disabled` I suppose there's no reason to close a PR for it, especially since it would be disabled by default. Feel free to open a PR for it if you like πŸ‘πŸ» Closing this though as we only use issues for bug reports. @weaversam8 Are you still willing to submit a PR to add the `readonly` variant? I would personally love to see this! @TheCatLady @skyporter @mendz - I actually no longer have the bandwidth to do this PR right now, sorry 😒 If anyone else wants to tackle this, it probably isn't too hard. Some reference PRs you can take a look at are #3298, #2385, and #1824.
"2021-04-18T11:57:39Z"
2.1
[]
[ "tests/variantsAtRule.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
4,214
tailwindlabs__tailwindcss-4214
[ "3948" ]
e764df5055b7e4a1f2edb72d38b76b338d0e2f13
diff --git a/src/index.js b/src/index.js --- a/src/index.js +++ b/src/index.js @@ -97,7 +97,7 @@ module.exports = function (config) { return { postcssPlugin: 'tailwindcss', - plugins: [...plugins, processTailwindFeatures(getConfig), formatCSS], + plugins: [...plugins, processTailwindFeatures(getConfig, resolvedConfigPath), formatCSS], } } diff --git a/src/jit/lib/setupContext.js b/src/jit/lib/setupContext.js --- a/src/jit/lib/setupContext.js +++ b/src/jit/lib/setupContext.js @@ -787,7 +787,14 @@ export default function setupContext(configOrPath) { configDependencies: new Set(), candidateFiles: purgeContent .filter((item) => typeof item === 'string') - .map((path) => normalizePath(path)), + .map((purgePath) => + normalizePath( + path.resolve( + userConfigPath === null ? process.cwd() : path.dirname(userConfigPath), + purgePath + ) + ) + ), rawContent: purgeContent .filter((item) => typeof item.raw === 'string') .map(({ raw, extension }) => ({ content: raw, extension })), diff --git a/src/lib/purgeUnusedStyles.js b/src/lib/purgeUnusedStyles.js --- a/src/lib/purgeUnusedStyles.js +++ b/src/lib/purgeUnusedStyles.js @@ -3,6 +3,7 @@ import postcss from 'postcss' import purgecss from '@fullhuman/postcss-purgecss' import log from '../util/log' import htmlTags from 'html-tags' +import path from 'path' function removeTailwindMarkers(css) { css.walkAtRules('tailwind', (rule) => rule.remove()) @@ -33,7 +34,7 @@ export function tailwindExtractor(content) { return broadMatches.concat(broadMatchesWithoutTrailingSlash).concat(innerMatches) } -export default function purgeUnusedUtilities(config, configChanged) { +export default function purgeUnusedUtilities(config, configChanged, resolvedConfigPath) { const purgeEnabled = _.get( config, 'purge.enabled', @@ -104,7 +105,6 @@ export default function purgeUnusedUtilities(config, configChanged) { }, removeTailwindMarkers, purgecss({ - content: Array.isArray(config.purge) ? config.purge : config.purge.content, defaultExtractor: (content) => { const extractor = defaultExtractor || tailwindExtractor const preserved = [...extractor(content)] @@ -116,6 +116,18 @@ export default function purgeUnusedUtilities(config, configChanged) { return preserved }, ...purgeOptions, + content: (Array.isArray(config.purge) + ? config.purge + : config.purge.content || purgeOptions.content || [] + ).map((item) => { + if (typeof item === 'string') { + return path.resolve( + resolvedConfigPath ? path.dirname(resolvedConfigPath) : process.cwd(), + item + ) + } + return item + }), }), ]) } diff --git a/src/processTailwindFeatures.js b/src/processTailwindFeatures.js --- a/src/processTailwindFeatures.js +++ b/src/processTailwindFeatures.js @@ -24,7 +24,7 @@ let previousConfig = null let processedPlugins = null let getProcessedPlugins = null -export default function (getConfig) { +export default function (getConfig, resolvedConfigPath) { return function (css) { const config = getConfig() const configChanged = hash(previousConfig) !== hash(config) @@ -65,7 +65,7 @@ export default function (getConfig) { substituteScreenAtRules(config), substituteClassApplyAtRules(config, getProcessedPlugins, configChanged), applyImportantConfiguration(config), - purgeUnusedStyles(config, configChanged), + purgeUnusedStyles(config, configChanged, resolvedConfigPath), ]).process(css, { from: _.get(css, 'source.input.file') }) } }
diff --git a/tests/fixtures/custom-purge-config.js b/tests/fixtures/custom-purge-config.js new file mode 100644 --- /dev/null +++ b/tests/fixtures/custom-purge-config.js @@ -0,0 +1,20 @@ +module.exports = { + purge: ['./*.html'], + theme: { + extend: { + colors: { + 'black!': '#000', + }, + spacing: { + 1.5: '0.375rem', + '(1/2+8)': 'calc(50% + 2rem)', + }, + minHeight: { + '(screen-4)': 'calc(100vh - 1rem)', + }, + fontFamily: { + '%#$@': 'Comic Sans', + }, + }, + }, +} diff --git a/tests/jit/relative-purge-paths.config.js b/tests/jit/relative-purge-paths.config.js new file mode 100644 --- /dev/null +++ b/tests/jit/relative-purge-paths.config.js @@ -0,0 +1,7 @@ +module.exports = { + mode: 'jit', + purge: ['./relative-purge-paths.test.html'], + corePlugins: { preflight: false }, + theme: {}, + plugins: [], +} diff --git a/tests/jit/relative-purge-paths.test.css b/tests/jit/relative-purge-paths.test.css new file mode 100644 --- /dev/null +++ b/tests/jit/relative-purge-paths.test.css @@ -0,0 +1,757 @@ +* { + --tw-shadow: 0 0 #0000; + --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgba(59, 130, 246, 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; +} +.container { + width: 100%; +} +@media (min-width: 640px) { + .container { + max-width: 640px; + } +} +@media (min-width: 768px) { + .container { + max-width: 768px; + } +} +@media (min-width: 1024px) { + .container { + max-width: 1024px; + } +} +@media (min-width: 1280px) { + .container { + max-width: 1280px; + } +} +@media (min-width: 1536px) { + .container { + max-width: 1536px; + } +} +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border-width: 0; +} +.pointer-events-none { + pointer-events: none; +} +.invisible { + visibility: hidden; +} +.absolute { + position: absolute; +} +.inset-0 { + top: 0px; + right: 0px; + bottom: 0px; + left: 0px; +} +.inset-y-4 { + top: 1rem; + bottom: 1rem; +} +.inset-x-2 { + left: 0.5rem; + right: 0.5rem; +} +.top-6 { + top: 1.5rem; +} +.right-8 { + right: 2rem; +} +.bottom-12 { + bottom: 3rem; +} +.left-16 { + left: 4rem; +} +.isolate { + isolation: isolate; +} +.isolation-auto { + isolation: auto; +} +.z-30 { + z-index: 30; +} +.order-last { + order: 9999; +} +.order-2 { + order: 2; +} +.col-span-3 { + grid-column: span 3 / span 3; +} +.col-start-1 { + grid-column-start: 1; +} +.col-end-4 { + grid-column-end: 4; +} +.row-span-2 { + grid-row: span 2 / span 2; +} +.row-start-3 { + grid-row-start: 3; +} +.row-end-5 { + grid-row-end: 5; +} +.float-right { + float: right; +} +.clear-left { + clear: left; +} +.m-4 { + margin: 1rem; +} +.my-2 { + margin-top: 0.5rem; + margin-bottom: 0.5rem; +} +.mx-auto { + margin-left: auto; + margin-right: auto; +} +.mt-0 { + margin-top: 0px; +} +.mr-1 { + margin-right: 0.25rem; +} +.mb-3 { + margin-bottom: 0.75rem; +} +.ml-4 { + margin-left: 1rem; +} +.box-border { + box-sizing: border-box; +} +.inline-grid { + display: inline-grid; +} +.hidden { + display: none; +} +.h-16 { + height: 4rem; +} +.max-h-screen { + max-height: 100vh; +} +.min-h-0 { + min-height: 0px; +} +.w-12 { + width: 3rem; +} +.min-w-min { + min-width: min-content; +} +.max-w-full { + max-width: 100%; +} +.flex-1 { + flex: 1 1 0%; +} +.flex-shrink { + flex-shrink: 1; +} +.flex-shrink-0 { + flex-shrink: 0; +} +.flex-grow { + flex-grow: 1; +} +.flex-grow-0 { + flex-grow: 0; +} +.table-fixed { + table-layout: fixed; +} +.border-collapse { + border-collapse: collapse; +} +.transform { + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + transform: translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} +.transform-gpu { + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + transform: translate3d(var(--tw-translate-x), var(--tw-translate-y), 0) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); +} +.origin-top-right { + transform-origin: top right; +} +.translate-x-5 { + --tw-translate-x: 1.25rem; +} +.-translate-x-4 { + --tw-translate-x: -1rem; +} +.translate-y-6 { + --tw-translate-y: 1.5rem; +} +.-translate-x-3 { + --tw-translate-x: -0.75rem; +} +.rotate-3 { + --tw-rotate: 3deg; +} +.skew-y-12 { + --tw-skew-y: 12deg; +} +.skew-x-12 { + --tw-skew-x: 12deg; +} +.scale-95 { + --tw-scale-x: 0.95; + --tw-scale-y: 0.95; +} +.animate-none { + animation: none; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} +.animate-spin { + animation: spin 1s linear infinite; +} +.cursor-pointer { + cursor: pointer; +} +.select-none { + user-select: none; +} +.resize-none { + resize: none; +} +.list-inside { + list-style-position: inside; +} +.list-disc { + list-style-type: disc; +} +.appearance-none { + appearance: none; +} +.auto-cols-min { + grid-auto-columns: min-content; +} +.grid-flow-row { + grid-auto-flow: row; +} +.auto-rows-max { + grid-auto-rows: max-content; +} +.grid-cols-4 { + grid-template-columns: repeat(4, minmax(0, 1fr)); +} +.grid-rows-3 { + grid-template-rows: repeat(3, minmax(0, 1fr)); +} +.flex-row-reverse { + flex-direction: row-reverse; +} +.flex-wrap { + flex-wrap: wrap; +} +.place-content-start { + place-content: start; +} +.place-items-end { + place-items: end; +} +.content-center { + align-content: center; +} +.items-start { + align-items: flex-start; +} +.justify-center { + justify-content: center; +} +.justify-items-end { + justify-items: end; +} +.gap-4 { + gap: 1rem; +} +.gap-x-2 { + column-gap: 0.5rem; +} +.gap-y-3 { + row-gap: 0.75rem; +} +.space-x-4 > :not([hidden]) ~ :not([hidden]) { + --tw-space-x-reverse: 0; + margin-right: calc(1rem * var(--tw-space-x-reverse)); + margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse))); +} +.space-y-3 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(0.75rem * calc(1 - var(--tw-space-y-reverse))); + margin-bottom: calc(0.75rem * var(--tw-space-y-reverse)); +} +.space-y-reverse > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 1; +} +.space-x-reverse > :not([hidden]) ~ :not([hidden]) { + --tw-space-x-reverse: 1; +} +.divide-x-2 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-x-reverse: 0; + border-right-width: calc(2px * var(--tw-divide-x-reverse)); + border-left-width: calc(2px * calc(1 - var(--tw-divide-x-reverse))); +} +.divide-y-4 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-y-reverse: 0; + border-top-width: calc(4px * calc(1 - var(--tw-divide-y-reverse))); + border-bottom-width: calc(4px * var(--tw-divide-y-reverse)); +} +.divide-x-0 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-x-reverse: 0; + border-right-width: calc(0px * var(--tw-divide-x-reverse)); + border-left-width: calc(0px * calc(1 - var(--tw-divide-x-reverse))); +} +.divide-y-0 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-y-reverse: 0; + border-top-width: calc(0px * calc(1 - var(--tw-divide-y-reverse))); + border-bottom-width: calc(0px * var(--tw-divide-y-reverse)); +} +.divide-dotted > :not([hidden]) ~ :not([hidden]) { + border-style: dotted; +} +.divide-gray-200 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-divide-opacity)); +} +.divide-opacity-50 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 0.5; +} +.place-self-center { + place-self: center; +} +.self-end { + align-self: flex-end; +} +.justify-self-start { + justify-self: start; +} +.overflow-hidden { + overflow: hidden; +} +.overscroll-contain { + overscroll-behavior: contain; +} +.truncate { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.overflow-ellipsis { + text-overflow: ellipsis; +} +.whitespace-nowrap { + white-space: nowrap; +} +.break-words { + overflow-wrap: break-word; +} +.rounded-md { + border-radius: 0.375rem; +} +.border { + border-width: 1px; +} +.border-2 { + border-width: 2px; +} +.border-solid { + border-style: solid; +} +.border-black { + --tw-border-opacity: 1; + border-color: rgba(0, 0, 0, var(--tw-border-opacity)); +} +.border-opacity-10 { + --tw-border-opacity: 0.1; +} +.bg-green-500 { + --tw-bg-opacity: 1; + background-color: rgba(16, 185, 129, var(--tw-bg-opacity)); +} +.bg-opacity-20 { + --tw-bg-opacity: 0.2; +} +.bg-gradient-to-r { + background-image: linear-gradient(to right, var(--tw-gradient-stops)); +} +.from-red-300 { + --tw-gradient-from: #fca5a5; + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(252, 165, 165, 0)); +} +.via-purple-200 { + --tw-gradient-stops: var(--tw-gradient-from), #ddd6fe, + var(--tw-gradient-to, rgba(221, 214, 254, 0)); +} +.to-blue-400 { + --tw-gradient-to: #60a5fa; +} +.decoration-slice { + box-decoration-break: slice; +} +.decoration-clone { + box-decoration-break: clone; +} +.bg-cover { + background-size: cover; +} +.bg-local { + background-attachment: local; +} +.bg-clip-border { + background-clip: border-box; +} +.bg-top { + background-position: top; +} +.bg-no-repeat { + background-repeat: no-repeat; +} +.bg-origin-border { + background-origin: border-box; +} +.bg-origin-padding { + background-origin: padding-box; +} +.bg-origin-content { + background-origin: content-box; +} +.fill-current { + fill: currentColor; +} +.stroke-current { + stroke: currentColor; +} +.stroke-2 { + stroke-width: 2; +} +.object-cover { + object-fit: cover; +} +.object-bottom { + object-position: bottom; +} +.p-4 { + padding: 1rem; +} +.py-2 { + padding-top: 0.5rem; + padding-bottom: 0.5rem; +} +.px-3 { + padding-left: 0.75rem; + padding-right: 0.75rem; +} +.pt-1 { + padding-top: 0.25rem; +} +.pr-2 { + padding-right: 0.5rem; +} +.pb-3 { + padding-bottom: 0.75rem; +} +.pl-4 { + padding-left: 1rem; +} +.text-center { + text-align: center; +} +.align-middle { + vertical-align: middle; +} +.font-sans { + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, + 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', + 'Segoe UI Symbol', 'Noto Color Emoji'; +} +.text-2xl { + font-size: 1.5rem; + line-height: 2rem; +} +.font-medium { + font-weight: 500; +} +.uppercase { + text-transform: uppercase; +} +.not-italic { + font-style: normal; +} +.ordinal, +.slashed-zero, +.lining-nums, +.oldstyle-nums, +.proportional-nums, +.tabular-nums, +.diagonal-fractions, +.stacked-fractions { + --tw-ordinal: var(--tw-empty, /*!*/ /*!*/); + --tw-slashed-zero: var(--tw-empty, /*!*/ /*!*/); + --tw-numeric-figure: var(--tw-empty, /*!*/ /*!*/); + --tw-numeric-spacing: var(--tw-empty, /*!*/ /*!*/); + --tw-numeric-fraction: var(--tw-empty, /*!*/ /*!*/); + font-variant-numeric: var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) + var(--tw-numeric-spacing) var(--tw-numeric-fraction); +} +.ordinal { + --tw-ordinal: ordinal; +} +.tabular-nums { + --tw-numeric-spacing: tabular-nums; +} +.diagonal-fractions { + --tw-numeric-fraction: diagonal-fractions; +} +.leading-relaxed { + line-height: 1.625; +} +.leading-5 { + line-height: 1.25rem; +} +.tracking-tight { + letter-spacing: -0.025em; +} +.text-indigo-500 { + --tw-text-opacity: 1; + color: rgba(99, 102, 241, var(--tw-text-opacity)); +} +.text-opacity-10 { + --tw-text-opacity: 0.1; +} +.underline { + text-decoration: underline; +} +.antialiased { + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +.placeholder-green-300::placeholder { + --tw-placeholder-opacity: 1; + color: rgba(110, 231, 183, var(--tw-placeholder-opacity)); +} +.placeholder-opacity-60::placeholder { + --tw-placeholder-opacity: 0.6; +} +.opacity-90 { + opacity: 0.9; +} +.bg-blend-darken { + background-blend-mode: darken; +} +.bg-blend-difference { + background-blend-mode: difference; +} +.mix-blend-multiply { + mix-blend-mode: multiply; +} +.mix-blend-saturation { + mix-blend-mode: saturation; +} +.shadow { + --tw-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-md { + --tw-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-lg { + --tw-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.outline-none { + outline: 2px solid transparent; + outline-offset: 2px; +} +.outline-black { + outline: 2px dotted black; + outline-offset: 2px; +} +.ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); +} +.ring-4 { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); +} +.ring-white { + --tw-ring-opacity: 1; + --tw-ring-color: rgba(255, 255, 255, var(--tw-ring-opacity)); +} +.ring-opacity-40 { + --tw-ring-opacity: 0.4; +} +.ring-offset-2 { + --tw-ring-offset-width: 2px; +} +.ring-offset-blue-300 { + --tw-ring-offset-color: #93c5fd; +} +.filter { + --tw-blur: var(--tw-empty, /*!*/ /*!*/); + --tw-brightness: var(--tw-empty, /*!*/ /*!*/); + --tw-contrast: var(--tw-empty, /*!*/ /*!*/); + --tw-grayscale: var(--tw-empty, /*!*/ /*!*/); + --tw-hue-rotate: var(--tw-empty, /*!*/ /*!*/); + --tw-invert: var(--tw-empty, /*!*/ /*!*/); + --tw-saturate: var(--tw-empty, /*!*/ /*!*/); + --tw-sepia: var(--tw-empty, /*!*/ /*!*/); + --tw-drop-shadow: var(--tw-empty, /*!*/ /*!*/); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); +} +.filter-none { + filter: none; +} +.blur-md { + --tw-blur: blur(12px); +} +.brightness-150 { + --tw-brightness: brightness(1.5); +} +.contrast-50 { + --tw-contrast: contrast(0.5); +} +.drop-shadow-md { + --tw-drop-shadow: drop-shadow(0 4px 3px rgba(0, 0, 0, 0.07)) + drop-shadow(0 2px 2px rgba(0, 0, 0, 0.06)); +} +.grayscale { + --tw-grayscale: grayscale(100%); +} +.hue-rotate-60 { + --tw-hue-rotate: hue-rotate(60deg); +} +.invert { + --tw-invert: invert(100%); +} +.saturate-200 { + --tw-saturate: saturate(2); +} +.sepia { + --tw-sepia: sepia(100%); +} +.backdrop-filter { + --tw-backdrop-blur: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-brightness: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-contrast: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-grayscale: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-hue-rotate: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-invert: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-opacity: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-saturate: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-sepia: var(--tw-empty, /*!*/ /*!*/); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); +} +.backdrop-filter-none { + backdrop-filter: none; +} +.backdrop-blur-lg { + --tw-backdrop-blur: blur(16px); +} +.backdrop-brightness-50 { + --tw-backdrop-brightness: brightness(0.5); +} +.backdrop-contrast-0 { + --tw-backdrop-contrast: contrast(0); +} +.backdrop-grayscale { + --tw-backdrop-grayscale: grayscale(100%); +} +.backdrop-hue-rotate-90 { + --tw-backdrop-hue-rotate: hue-rotate(90deg); +} +.backdrop-invert { + --tw-backdrop-invert: invert(100%); +} +.backdrop-opacity-75 { + --tw-backdrop-opacity: opacity(0.75); +} +.backdrop-saturate-150 { + --tw-backdrop-saturate: saturate(1.5); +} +.backdrop-sepia { + --tw-backdrop-sepia: sepia(100%); +} +.transition { + transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, + transform, filter, backdrop-filter; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} +.transition-all { + transition-property: all; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} +.delay-300 { + transition-delay: 300ms; +} +.duration-200 { + transition-duration: 200ms; +} +.ease-in-out { + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); +} diff --git a/tests/jit/relative-purge-paths.test.html b/tests/jit/relative-purge-paths.test.html new file mode 100644 --- /dev/null +++ b/tests/jit/relative-purge-paths.test.html @@ -0,0 +1,147 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <link rel="icon" href="/favicon.ico" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Title</title> + <link rel="stylesheet" href="./tailwind.css" /> + </head> + <body> + <div class="sr-only"></div> + <div class="content-center"></div> + <div class="items-start"></div> + <div class="self-end"></div> + <div class="animate-none"></div> + <div class="animate-spin"></div> + <div class="appearance-none"></div> + <div class="bg-local"></div> + <div class="bg-clip-border"></div> + <div class="bg-green-500"></div> + <div class="bg-gradient-to-r"></div> + <div class="bg-opacity-20"></div> + <div class="bg-top"></div> + <div class="bg-no-repeat"></div> + <div class="bg-cover"></div> + <div class="bg-origin-border bg-origin-padding bg-origin-content"></div> + <div class="border-collapse"></div> + <div class="border-black"></div> + <div class="border-opacity-10"></div> + <div class="rounded-md"></div> + <div class="border-solid"></div> + <div class="border"></div> + <div class="border-2"></div> + <div class="shadow"></div> + <div class="shadow-md"></div> + <div class="shadow-lg"></div> + <div class="decoration-clone decoration-slice"></div> + <div class="box-border"></div> + <div class="clear-left"></div> + <div class="container"></div> + <div class="cursor-pointer"></div> + <div class="hidden inline-grid"></div> + <div class="divide-gray-200"></div> + <div class="divide-opacity-50"></div> + <div class="divide-dotted"></div> + <div class="divide-x-2 divide-y-4 divide-x-0 divide-y-0"></div> + <div class="fill-current"></div> + <div class="flex-1"></div> + <div class="flex-row-reverse"></div> + <div class="flex-grow"></div> + <div class="flex-grow-0"></div> + <div class="flex-shrink"></div> + <div class="flex-shrink-0"></div> + <div class="flex-wrap"></div> + <div class="float-right"></div> + <div class="font-sans"></div> + <div class="text-2xl"></div> + <div class="antialiased"></div> + <div class="not-italic"></div> + <div class="tabular-nums ordinal diagonal-fractions"></div> + <div class="font-medium"></div> + <div class="gap-x-2 gap-y-3 gap-4"></div> + <div class="from-red-300 via-purple-200 to-blue-400"></div> + <div class="auto-cols-min"></div> + <div class="grid-flow-row"></div> + <div class="auto-rows-max"></div> + <div class="col-span-3"></div> + <div class="col-start-1"></div> + <div class="col-end-4"></div> + <div class="row-span-2"></div> + <div class="row-start-3"></div> + <div class="row-end-5"></div> + <div class="grid-cols-4"></div> + <div class="grid-rows-3"></div> + <div class="h-16"></div> + <div class="inset-0 inset-y-4 inset-x-2 top-6 right-8 bottom-12 left-16"></div> + <div class="isolate isolation-auto"></div> + <div class="justify-center"></div> + <div class="justify-items-end"></div> + <div class="justify-self-start"></div> + <div class="tracking-tight"></div> + <div class="leading-relaxed leading-5"></div> + <div class="list-inside"></div> + <div class="list-disc"></div> + <div class="m-4 my-2 mx-auto mt-0 mr-1 mb-3 ml-4"></div> + <div class="max-h-screen"></div> + <div class="max-w-full"></div> + <div class="min-h-0"></div> + <div class="min-w-min"></div> + <div class="object-cover"></div> + <div class="object-bottom"></div> + <div class="opacity-90"></div> + <div class="bg-blend-darken bg-blend-difference"></div> + <div class="mix-blend-multiply mix-blend-saturation"></div> + <div class="order-last order-2"></div> + <div class="outline-none outline-black"></div> + <div class="overflow-hidden"></div> + <div class="overscroll-contain"></div> + <div class="p-4 py-2 px-3 pt-1 pr-2 pb-3 pl-4"></div> + <div class="place-content-start"></div> + <div class="placeholder-green-300"></div> + <div class="placeholder-opacity-60"></div> + <div class="place-items-end"></div> + <div class="place-self-center"></div> + <div class="pointer-events-none"></div> + <div class="absolute"></div> + <div class="resize-none"></div> + <div class="ring-white"></div> + <div class="ring-offset-blue-300"></div> + <div class="ring-offset-2"></div> + <div class="ring-opacity-40"></div> + <div class="ring ring-4"></div> + <div + class="filter filter-none blur-md brightness-150 contrast-50 drop-shadow-md grayscale hue-rotate-60 invert saturate-200 sepia" + ></div> + <div + class="backdrop-filter backdrop-filter-none backdrop-blur-lg backdrop-brightness-50 backdrop-contrast-0 backdrop-grayscale backdrop-hue-rotate-90 backdrop-invert backdrop-opacity-75 backdrop-saturate-150 backdrop-sepia" + ></div> + <div class="rotate-3"></div> + <div class="scale-95"></div> + <div class="skew-y-12 skew-x-12"></div> + <div class="space-x-4 space-y-3 space-x-reverse space-y-reverse"></div> + <div class="stroke-current"></div> + <div class="stroke-2"></div> + <div class="table-fixed"></div> + <div class="text-center"></div> + <div class="text-indigo-500"></div> + <div class="underline"></div> + <div class="text-opacity-10"></div> + <div class="overflow-ellipsis truncate"></div> + <div class="uppercase"></div> + <div class="transform transform-gpu"></div> + <div class="origin-top-right"></div> + <div class="delay-300"></div> + <div class="duration-200"></div> + <div class="transition transition-all"></div> + <div class="ease-in-out"></div> + <div class="translate-x-5 -translate-x-4 translate-y-6 -translate-x-3"></div> + <div class="select-none"></div> + <div class="align-middle"></div> + <div class="invisible"></div> + <div class="whitespace-nowrap"></div> + <div class="w-12"></div> + <div class="break-words"></div> + <div class="z-30"></div> + </body> +</html> diff --git a/tests/jit/relative-purge-paths.test.js b/tests/jit/relative-purge-paths.test.js new file mode 100644 --- /dev/null +++ b/tests/jit/relative-purge-paths.test.js @@ -0,0 +1,25 @@ +import postcss from 'postcss' +import fs from 'fs' +import path from 'path' +import tailwind from '../../src/jit/index.js' + +function run(input, config = {}) { + return postcss(tailwind(config)).process(input, { + from: path.resolve(__filename), + }) +} + +test('relative purge paths', () => { + let css = ` + @tailwind base; + @tailwind components; + @tailwind utilities; + ` + + return run(css, path.resolve(__dirname, './relative-purge-paths.config.js')).then((result) => { + let expectedPath = path.resolve(__dirname, './relative-purge-paths.test.css') + let expected = fs.readFileSync(expectedPath, 'utf8') + + expect(result.css).toMatchFormattedCss(expected) + }) +}) diff --git a/tests/purgeUnusedStyles.test.js b/tests/purgeUnusedStyles.test.js --- a/tests/purgeUnusedStyles.test.js +++ b/tests/purgeUnusedStyles.test.js @@ -4,6 +4,7 @@ import postcss from 'postcss' import tailwind from '../src/index' import { tailwindExtractor } from '../src/lib/purgeUnusedStyles' import defaultConfig from '../stubs/defaultConfig.stub.js' +import customConfig from './fixtures/custom-purge-config.js' function suppressConsoleLogs(cb, type = 'warn') { return () => { @@ -38,25 +39,13 @@ async function inProduction(callback) { return result } +function withTestName(path) { + return `${path}?test=${expect.getState().currentTestName}` +} + const config = { ...defaultConfig, - theme: { - extend: { - colors: { - 'black!': '#000', - }, - spacing: { - 1.5: '0.375rem', - '(1/2+8)': 'calc(50% + 2rem)', - }, - minHeight: { - '(screen-4)': 'calc(100vh - 1rem)', - }, - fontFamily: { - '%#$@': 'Comic Sans', - }, - }, - }, + ...customConfig, } delete config.presets @@ -108,7 +97,22 @@ test('purges unused classes', () => { purge: [path.resolve(`${__dirname}/fixtures/**/*.html`)], }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) + .then((result) => { + assertPurged(result) + }) + }) + ) +}) + +test('purge patterns are resolved relative to the config file', () => { + return inProduction( + suppressConsoleLogs(() => { + const inputPath = path.resolve(`${__dirname}/fixtures/tailwind-input.css`) + const input = fs.readFileSync(inputPath, 'utf8') + + return postcss([tailwind(path.resolve(`${__dirname}/fixtures/custom-purge-config.js`))]) + .process(input, { from: withTestName(inputPath) }) .then((result) => { assertPurged(result) }) @@ -275,7 +279,7 @@ test('purges unused classes with important string', () => { purge: [path.resolve(`${__dirname}/fixtures/**/*.html`)], }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { assertPurged(result) }) @@ -298,7 +302,7 @@ test('mode must be a valid value', () => { content: [path.resolve(`${__dirname}/fixtures/**/*.html`)], }, }), - ]).process(input, { from: inputPath }) + ]).process(input, { from: withTestName(inputPath) }) ).rejects.toThrow() }) ) @@ -319,7 +323,7 @@ test('components are purged by default in layers mode', () => { purge: [path.resolve(`${__dirname}/fixtures/**/*.html`)], }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { expect(result.css).not.toContain('.container') assertPurged(result) @@ -347,7 +351,7 @@ test('you can specify which layers to purge', () => { }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const rules = extractRules(result.root) expect(rules).toContain('optgroup') @@ -377,7 +381,7 @@ test('you can purge just base and component layers (but why)', () => { }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const rules = extractRules(result.root) expect(rules).not.toContain('[type="checkbox"]') @@ -439,7 +443,7 @@ test( purge: [path.resolve(`${__dirname}/fixtures/**/*.html`)], }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const expected = fs.readFileSync( path.resolve(`${__dirname}/fixtures/tailwind-output.css`), @@ -465,7 +469,7 @@ test('does not purge if the array is empty', () => { purge: [], }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { process.env.NODE_ENV = OLD_NODE_ENV const expected = fs.readFileSync( @@ -491,7 +495,7 @@ test('does not purge if explicitly disabled', () => { purge: { enabled: false }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const expected = fs.readFileSync( path.resolve(`${__dirname}/fixtures/tailwind-output.css`), @@ -516,7 +520,7 @@ test('does not purge if purge is simply false', () => { purge: false, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const expected = fs.readFileSync( path.resolve(`${__dirname}/fixtures/tailwind-output.css`), @@ -541,7 +545,7 @@ test('purges outside of production if explicitly enabled', () => { purge: { enabled: true, content: [path.resolve(`${__dirname}/fixtures/**/*.html`)] }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { assertPurged(result) }) @@ -567,7 +571,7 @@ test( }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { expect(result.css).toContain('.md\\:bg-green-500') assertPurged(result) @@ -596,7 +600,7 @@ test( css.walkComments((c) => c.remove()) }, ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { expect(result.css).toContain('html') expect(result.css).toContain('body') @@ -624,7 +628,7 @@ test('element selectors are preserved by default', () => { }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const rules = extractRules(result.root) ;[ @@ -678,7 +682,7 @@ test('element selectors are preserved even when defaultExtractor is overridden', }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const rules = extractRules(result.root) ;[ @@ -729,7 +733,7 @@ test('preserving element selectors can be disabled', () => { }, }), ]) - .process(input, { from: inputPath }) + .process(input, { from: withTestName(inputPath) }) .then((result) => { const rules = extractRules(result.root)
Not all classes are being pulled in from Blade files, some only after re-saving the files. ### What version of @tailwindcss/jit are you using? 0.1.3 ### What version of Node.js are you using? v14.16.0 ### What browser are you using? Chrome ### What operating system are you using? macOS ### Reproduction repository https://github.com/foof/tailwind-jit-test The linked repo is a fresh Laravel install but where all the build configs are located in `resources/myfolder/` instead of the root folder. Reproduction steps: 1. Clone repo 2. `cd resources/myfolder` 3. `npm install` 4. `npm run watch` The purge option is configured to look at blade files in the `resources/views/myfolder` directory. Classes from `resources/views/myfolder/welcome.blade.php` are not being put into the generated CSS file. If I simply re-save the blade file while watch is running, then some of the classes gets added, but not all. For example `sm:p-6` is never included in the generated css.
> You don't have package.json or package-lock.json in your repo. `npm install` won't work. Perhaps it was unclear, but those files are also located in the subfolder `resources/myfolder`. In our project we have multiple frontends which means we have multiple package.json etc that are located in other subfolders like `resources/myfolder`, `resources/myfolder2`, `resources/myfolder3` etc. Hey! Thank you for your bug report! Much appreciated! πŸ™ The reason `sm:p-6` never gets included is because you removed all the screens in your config, which results in the fact that you can't use `responsive` utilities: ```js module.exports = { purge: [ "./**/*.{js,vue}", "./../views/myfolder/**/*.php", // Classes from these files are only included after re-saving the files when watcher is running ], theme: { screens: {}, extend: {}, }, plugins: [], }; ``` You can fix that by dropping that reset: ```diff module.exports = { purge: [ "./**/*.{js,vue}", "./../views/myfolder/**/*.php", // Classes from these files are only included after re-saving the files when watcher is running ], theme: { - screens: {}, extend: {}, }, plugins: [], }; ``` In addition, the classes for `dark` mode are not included either, this is because you didn't enable dark mode. You can do so by choosing the `class` or `media` option. https://tailwindcss.com/docs/dark-mode ```diff module.exports = { + darkMode: "class", purge: [ "./**/*.{js,vue}", "./../views/myfolder/**/*.php", // Classes from these files are only included after re-saving the files when watcher is running ], theme: { - screens: {}, extend: {}, }, plugins: [], }; ``` The last class that is missing is the `items-top` one, this is because it doesn't exist in default Tailwind: https://tailwindcss.com/docs/align-items Class | Properties -- | -- items-start | align-items: flex-start; items-end | align-items: flex-end; items-center | align-items: center; items-baseline | align-items: baseline; items-stretch | align-items: stretch; @RobinMalfait That explains some of the classes :) However `w-96` is not included when I first start `npm run watch` after making your suggested changes. But if I simply go into the blade file and hit Cmd+S without changing anything it then recompiles and `w-96` is included Very odd, I am going to re-open this issue. It seems that when you drop the `"./**/*.{js,vue}"` line it does create the `w-96` consistently on the first run. I do have to mention that I see multiple "runs" in the webpack output. When you include that line, initially the `w-96` does not get created. The good part is that I can reproduce it consistently. Once I find the solution / actual issue I'll update this issue! Thanks for opening the issue! I also get multiple runs which I forgot to mention and I wasn't sure if it was intended or not. Normally we also build JS but I removed all non-CSS stuff from the repo for simplicity's sake. If it helps, an interesting thing I found is that if I copy the entire `views` directory into `resources/myfolder` and change the purge config to `'./views/myfolder/**/*.php'`, then it works as expected. (Although still with multiple runs) I'll open another issue but I just want to add that I'm running into the same thing, specifically multiple compilations and classes from Blade files missing after the first save. I'm using a pretty standard Laravel Mix setup, and with JIT _every_ Webpack compilation runs twice now. It may be because both Mix and JIT are watching a bunch of the same files, but I need them to since I have Tailwind classes in my Vue components. With some Blade files I'm now noticing the above issue too, with dynamic classes like `hover:text-[#3b5998]`. After saving, Webpack recompiles (twice) and the generated class isn't present in my CSS, then after saving again, and Webpack recompiling twice again, it is. Okay, inexplicably, it's now working fine. I set `DEBUG=true` to see the JIT output, everything suddenly worked normally, and I removed it again and it now works as expected, even the double builds are gone. Gonna leave my comment in case it helps someone else, but sorry to muddy the waters! I was having this problem after I added the `TAILWIND_MODE=watch` variable, not sure why but after I removed it the classes get generated normally. I'm not having exactly this problem, but related. I have a `purge` config that looks at changes to certain markdown files and yaml files that are outside of the directory structure (found using `../../`) and this worked up until recently: ```js module.exports = { mode: 'jit', purge: [ '../../config/**/*.yaml', '../../pages/**/*.md', './blueprints/**/*.yaml', './js/**/*.js', './templates/**/*.twig', './typhoon.yaml', './typhoon.php', './available-classes.md', ], ... ``` However, now with JIT, the `../../` paths are not being picked up and recognized. This means that all the classes defined in those files are not being found, so not included in the CSS. Makes no difference if i save the file, restart the `--watch` command, those first two paths are never included. This worked prior to JIT. Having the same issue as above, doesn't seem to be able to pick up folders above the tailwind config. Same level folders or deeper work fine but going above no longer seems to work.
"2021-04-30T17:33:03Z"
2.1
[]
[ "tests/jit/relative-purge-paths.test.js", "tests/purgeUnusedStyles.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
4,260
tailwindlabs__tailwindcss-4260
[ "4202" ]
2d9e2d9318b371e49e904fd67b00d48f707a2ebe
diff --git a/src/jit/lib/expandApplyAtRules.js b/src/jit/lib/expandApplyAtRules.js --- a/src/jit/lib/expandApplyAtRules.js +++ b/src/jit/lib/expandApplyAtRules.js @@ -30,7 +30,6 @@ function buildApplyCache(applyCandidates, context) { return context.applyClassCache } -// TODO: Apply `!important` stuff correctly instead of just skipping it function extractApplyCandidates(params) { let candidates = params.split(/[\s\t\n]+/g) @@ -143,7 +142,6 @@ function processApply(root, context) { .join(', ') } - /** @type {Map<import('postcss').Node, [string, boolean, import('postcss').Node[]][]>} */ let perParentApplies = new Map() // Collect all apply candidates and their rules @@ -197,7 +195,7 @@ function processApply(root, context) { rule.selector = replaceSelector(parent.selector, rule.selector, applyCandidate) rule.walkDecls((d) => { - d.important = important + d.important = meta.important || important }) }) } diff --git a/src/jit/lib/generateRules.js b/src/jit/lib/generateRules.js --- a/src/jit/lib/generateRules.js +++ b/src/jit/lib/generateRules.js @@ -79,7 +79,7 @@ function applyImportant(matches) { }) r.walkDecls((d) => (d.important = true)) }) - result.push([meta, container.nodes[0]]) + result.push([{ ...meta, important: true }, container.nodes[0]]) } return result
diff --git a/tests/jit/apply.test.css b/tests/jit/apply.test.css --- a/tests/jit/apply.test.css +++ b/tests/jit/apply.test.css @@ -323,6 +323,11 @@ h2 { line-height: 2rem; } } +.important-modifier { + border-radius: 0.375rem !important; + padding-left: 1rem; + padding-right: 1rem; +} @keyframes spin { to { transform: rotate(360deg); diff --git a/tests/jit/apply.test.html b/tests/jit/apply.test.html --- a/tests/jit/apply.test.html +++ b/tests/jit/apply.test.html @@ -32,6 +32,7 @@ <div class="recursive-apply-c"></div> <div class="use-with-other-properties-base use-with-other-properties-component"></div> <div class="add-sibling-properties"></div> + <div class="important-modifier"></div> <div class="a b"></div> <div class="foo"></div> <div class="bar"></div> diff --git a/tests/jit/apply.test.js b/tests/jit/apply.test.js --- a/tests/jit/apply.test.js +++ b/tests/jit/apply.test.js @@ -119,6 +119,10 @@ test('@apply', () => { @apply lg:text-2xl; @apply sm:text-2xl; } + + .important-modifier { + @apply px-4 !rounded-md; + } } @layer utilities {
[Bug]: Important modifier not working ### What version of Tailwind CSS are you using? 2.1.2 ### What build tool (or framework if it abstracts the build tool) are you using? vue-tailwind 2.2.1, webpack 5.21.2 ### What version of Node.js are you using? v15.11.0 ### What browser are you using? Chrome ### What operating system are you using? macOS ### Reproduction repository https://play.tailwindcss.com/qVS5lsqxMS ### Describe your issue The important modifier does not work as announced here: https://tailwindcss.com/docs/just-in-time-mode The attached reproduction link should have a blue background but it is still gray: ![image](https://user-images.githubusercontent.com/5358638/116396493-c2c6d900-a825-11eb-8988-a407b536fbb0.png)
Have you enabled JIT mode [as described in the documentation](https://tailwindcss.com/docs/just-in-time-mode#enabling-jit-mode)? JIT mode is not currently supported in Tailwind Play, and you are using `jit: true` there instead of `mode: 'jit'`. If you have enabled JIT mode correctly and it's still not working please provide a repository which reproduces the issue, thanks! We're running into this with `mode: "jit"` and `@tailwindcss/postcss7-compat`: Input: ```css .ui-state-active { @apply !bg-none !whitespace-normal; } ``` Output: ```css .ui-state-active { white-space: normal; background-image: none; } ``` However, if I inline `!whitespace-normal`, it works as expected: ![image](https://user-images.githubusercontent.com/2636763/116698252-24a45180-a992-11eb-99f5-b7e94045f8bc.png) To make utilities important with `@apply` you need to add the `!important` keyword to the end of the list: ```css .ui-state-active { @apply bg-none whitespace-normal !important; } ``` This is something we could probably improve now that there's a dedicated important modifier though.
"2021-05-06T17:46:18Z"
2.1
[]
[ "tests/jit/apply.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/5358638/116396493-c2c6d900-a825-11eb-8988-a407b536fbb0.png" ]
[ "https://play.tailwindcss.com/qVS5lsqxMS" ]
tailwindlabs/tailwindcss
4,272
tailwindlabs__tailwindcss-4272
[ "4094" ]
76c670fc2913eb03a340a015d30d3db53cca9c22
diff --git a/src/jit/lib/expandTailwindAtRules.js b/src/jit/lib/expandTailwindAtRules.js --- a/src/jit/lib/expandTailwindAtRules.js +++ b/src/jit/lib/expandTailwindAtRules.js @@ -25,9 +25,12 @@ function getDefaultExtractor(fileExtension) { } } -function getExtractor(fileName, tailwindConfig) { +function getExtractor(tailwindConfig, fileExtension) { const purgeOptions = tailwindConfig && tailwindConfig.purge && tailwindConfig.purge.options - const fileExtension = path.extname(fileName).slice(1) + + if (!fileExtension) { + return (purgeOptions && purgeOptions.defaultExtractor) || getDefaultExtractor() + } if (!purgeOptions) { return getDefaultExtractor(fileExtension) @@ -208,11 +211,16 @@ export default function expandTailwindAtRules(context, registerDependency) { env.DEBUG && console.time('Reading changed files') for (let file of context.changedFiles) { let content = fs.readFileSync(file, 'utf8') - let extractor = getExtractor(file, context.tailwindConfig) + let extractor = getExtractor(context.tailwindConfig, path.extname(file).slice(1)) getClassCandidates(content, extractor, contentMatchCache, candidates, seen) } env.DEBUG && console.timeEnd('Reading changed files') + for (let { content, extension } of context.rawContent) { + let extractor = getExtractor(context.tailwindConfig, extension) + getClassCandidates(content, extractor, contentMatchCache, candidates, seen) + } + // --- // Generate the actual CSS diff --git a/src/jit/lib/setupContext.js b/src/jit/lib/setupContext.js --- a/src/jit/lib/setupContext.js +++ b/src/jit/lib/setupContext.js @@ -767,6 +767,10 @@ export default function setupContext(configOrPath) { process.env.DEBUG && console.log('Setting up new context...') + let purgeContent = Array.isArray(tailwindConfig.purge) + ? tailwindConfig.purge + : tailwindConfig.purge.content + let context = { changedFiles: new Set(), ruleCache: new Set(), @@ -781,10 +785,12 @@ export default function setupContext(configOrPath) { configPath: userConfigPath, tailwindConfig: tailwindConfig, configDependencies: new Set(), - candidateFiles: (Array.isArray(tailwindConfig.purge) - ? tailwindConfig.purge - : tailwindConfig.purge.content - ).map((path) => normalizePath(path)), + candidateFiles: purgeContent + .filter((item) => typeof item === 'string') + .map((path) => normalizePath(path)), + rawContent: purgeContent + .filter((item) => typeof item.raw === 'string') + .map(({ raw, extension }) => ({ content: raw, extension })), variantMap: new Map(), stylesheetCache: null, fileModifiedMap: new Map(),
diff --git a/tests/jit/raw-content.test.css b/tests/jit/raw-content.test.css new file mode 100644 --- /dev/null +++ b/tests/jit/raw-content.test.css @@ -0,0 +1,757 @@ +* { + --tw-shadow: 0 0 #0000; + --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgba(59, 130, 246, 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; +} +.container { + width: 100%; +} +@media (min-width: 640px) { + .container { + max-width: 640px; + } +} +@media (min-width: 768px) { + .container { + max-width: 768px; + } +} +@media (min-width: 1024px) { + .container { + max-width: 1024px; + } +} +@media (min-width: 1280px) { + .container { + max-width: 1280px; + } +} +@media (min-width: 1536px) { + .container { + max-width: 1536px; + } +} +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border-width: 0; +} +.pointer-events-none { + pointer-events: none; +} +.invisible { + visibility: hidden; +} +.absolute { + position: absolute; +} +.inset-0 { + top: 0px; + right: 0px; + bottom: 0px; + left: 0px; +} +.inset-y-4 { + top: 1rem; + bottom: 1rem; +} +.inset-x-2 { + left: 0.5rem; + right: 0.5rem; +} +.top-6 { + top: 1.5rem; +} +.right-8 { + right: 2rem; +} +.bottom-12 { + bottom: 3rem; +} +.left-16 { + left: 4rem; +} +.isolate { + isolation: isolate; +} +.isolation-auto { + isolation: auto; +} +.z-30 { + z-index: 30; +} +.order-last { + order: 9999; +} +.order-2 { + order: 2; +} +.col-span-3 { + grid-column: span 3 / span 3; +} +.col-start-1 { + grid-column-start: 1; +} +.col-end-4 { + grid-column-end: 4; +} +.row-span-2 { + grid-row: span 2 / span 2; +} +.row-start-3 { + grid-row-start: 3; +} +.row-end-5 { + grid-row-end: 5; +} +.float-right { + float: right; +} +.clear-left { + clear: left; +} +.m-4 { + margin: 1rem; +} +.my-2 { + margin-top: 0.5rem; + margin-bottom: 0.5rem; +} +.mx-auto { + margin-left: auto; + margin-right: auto; +} +.mt-0 { + margin-top: 0px; +} +.mr-1 { + margin-right: 0.25rem; +} +.mb-3 { + margin-bottom: 0.75rem; +} +.ml-4 { + margin-left: 1rem; +} +.box-border { + box-sizing: border-box; +} +.inline-grid { + display: inline-grid; +} +.hidden { + display: none; +} +.h-16 { + height: 4rem; +} +.max-h-screen { + max-height: 100vh; +} +.min-h-0 { + min-height: 0px; +} +.w-12 { + width: 3rem; +} +.min-w-min { + min-width: min-content; +} +.max-w-full { + max-width: 100%; +} +.flex-1 { + flex: 1 1 0%; +} +.flex-shrink { + flex-shrink: 1; +} +.flex-shrink-0 { + flex-shrink: 0; +} +.flex-grow { + flex-grow: 1; +} +.flex-grow-0 { + flex-grow: 0; +} +.table-fixed { + table-layout: fixed; +} +.border-collapse { + border-collapse: collapse; +} +.transform { + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + transform: translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); +} +.transform-gpu { + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + transform: translate3d(var(--tw-translate-x), var(--tw-translate-y), 0) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); +} +.origin-top-right { + transform-origin: top right; +} +.translate-x-5 { + --tw-translate-x: 1.25rem; +} +.-translate-x-4 { + --tw-translate-x: -1rem; +} +.translate-y-6 { + --tw-translate-y: 1.5rem; +} +.-translate-x-3 { + --tw-translate-x: -0.75rem; +} +.rotate-3 { + --tw-rotate: 3deg; +} +.skew-y-12 { + --tw-skew-y: 12deg; +} +.skew-x-12 { + --tw-skew-x: 12deg; +} +.scale-95 { + --tw-scale-x: 0.95; + --tw-scale-y: 0.95; +} +.animate-none { + animation: none; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} +.animate-spin { + animation: spin 1s linear infinite; +} +.cursor-pointer { + cursor: pointer; +} +.select-none { + user-select: none; +} +.resize-none { + resize: none; +} +.list-inside { + list-style-position: inside; +} +.list-disc { + list-style-type: disc; +} +.appearance-none { + appearance: none; +} +.auto-cols-min { + grid-auto-columns: min-content; +} +.grid-flow-row { + grid-auto-flow: row; +} +.auto-rows-max { + grid-auto-rows: max-content; +} +.grid-cols-4 { + grid-template-columns: repeat(4, minmax(0, 1fr)); +} +.grid-rows-3 { + grid-template-rows: repeat(3, minmax(0, 1fr)); +} +.flex-row-reverse { + flex-direction: row-reverse; +} +.flex-wrap { + flex-wrap: wrap; +} +.place-content-start { + place-content: start; +} +.place-items-end { + place-items: end; +} +.content-center { + align-content: center; +} +.items-start { + align-items: flex-start; +} +.justify-center { + justify-content: center; +} +.justify-items-end { + justify-items: end; +} +.gap-4 { + gap: 1rem; +} +.gap-x-2 { + column-gap: 0.5rem; +} +.gap-y-3 { + row-gap: 0.75rem; +} +.space-x-4 > :not([hidden]) ~ :not([hidden]) { + --tw-space-x-reverse: 0; + margin-right: calc(1rem * var(--tw-space-x-reverse)); + margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse))); +} +.space-y-3 > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(0.75rem * calc(1 - var(--tw-space-y-reverse))); + margin-bottom: calc(0.75rem * var(--tw-space-y-reverse)); +} +.space-y-reverse > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 1; +} +.space-x-reverse > :not([hidden]) ~ :not([hidden]) { + --tw-space-x-reverse: 1; +} +.divide-x-2 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-x-reverse: 0; + border-right-width: calc(2px * var(--tw-divide-x-reverse)); + border-left-width: calc(2px * calc(1 - var(--tw-divide-x-reverse))); +} +.divide-y-4 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-y-reverse: 0; + border-top-width: calc(4px * calc(1 - var(--tw-divide-y-reverse))); + border-bottom-width: calc(4px * var(--tw-divide-y-reverse)); +} +.divide-x-0 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-x-reverse: 0; + border-right-width: calc(0px * var(--tw-divide-x-reverse)); + border-left-width: calc(0px * calc(1 - var(--tw-divide-x-reverse))); +} +.divide-y-0 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-y-reverse: 0; + border-top-width: calc(0px * calc(1 - var(--tw-divide-y-reverse))); + border-bottom-width: calc(0px * var(--tw-divide-y-reverse)); +} +.divide-dotted > :not([hidden]) ~ :not([hidden]) { + border-style: dotted; +} +.divide-gray-200 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-divide-opacity)); +} +.divide-opacity-50 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 0.5; +} +.place-self-center { + place-self: center; +} +.self-end { + align-self: flex-end; +} +.justify-self-start { + justify-self: start; +} +.overflow-hidden { + overflow: hidden; +} +.overscroll-contain { + overscroll-behavior: contain; +} +.truncate { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.overflow-ellipsis { + text-overflow: ellipsis; +} +.whitespace-nowrap { + white-space: nowrap; +} +.break-words { + overflow-wrap: break-word; +} +.rounded-md { + border-radius: 0.375rem; +} +.border { + border-width: 1px; +} +.border-2 { + border-width: 2px; +} +.border-solid { + border-style: solid; +} +.border-black { + --tw-border-opacity: 1; + border-color: rgba(0, 0, 0, var(--tw-border-opacity)); +} +.border-opacity-10 { + --tw-border-opacity: 0.1; +} +.bg-green-500 { + --tw-bg-opacity: 1; + background-color: rgba(16, 185, 129, var(--tw-bg-opacity)); +} +.bg-opacity-20 { + --tw-bg-opacity: 0.2; +} +.bg-gradient-to-r { + background-image: linear-gradient(to right, var(--tw-gradient-stops)); +} +.from-red-300 { + --tw-gradient-from: #fca5a5; + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(252, 165, 165, 0)); +} +.via-purple-200 { + --tw-gradient-stops: var(--tw-gradient-from), #ddd6fe, + var(--tw-gradient-to, rgba(221, 214, 254, 0)); +} +.to-blue-400 { + --tw-gradient-to: #60a5fa; +} +.decoration-slice { + box-decoration-break: slice; +} +.decoration-clone { + box-decoration-break: clone; +} +.bg-cover { + background-size: cover; +} +.bg-local { + background-attachment: local; +} +.bg-clip-border { + background-clip: border-box; +} +.bg-top { + background-position: top; +} +.bg-no-repeat { + background-repeat: no-repeat; +} +.bg-origin-border { + background-origin: border-box; +} +.bg-origin-padding { + background-origin: padding-box; +} +.bg-origin-content { + background-origin: content-box; +} +.fill-current { + fill: currentColor; +} +.stroke-current { + stroke: currentColor; +} +.stroke-2 { + stroke-width: 2; +} +.object-cover { + object-fit: cover; +} +.object-bottom { + object-position: bottom; +} +.p-4 { + padding: 1rem; +} +.py-2 { + padding-top: 0.5rem; + padding-bottom: 0.5rem; +} +.px-3 { + padding-left: 0.75rem; + padding-right: 0.75rem; +} +.pt-1 { + padding-top: 0.25rem; +} +.pr-2 { + padding-right: 0.5rem; +} +.pb-3 { + padding-bottom: 0.75rem; +} +.pl-4 { + padding-left: 1rem; +} +.text-center { + text-align: center; +} +.align-middle { + vertical-align: middle; +} +.font-sans { + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, + 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', + 'Segoe UI Symbol', 'Noto Color Emoji'; +} +.text-2xl { + font-size: 1.5rem; + line-height: 2rem; +} +.font-medium { + font-weight: 500; +} +.uppercase { + text-transform: uppercase; +} +.not-italic { + font-style: normal; +} +.ordinal, +.slashed-zero, +.lining-nums, +.oldstyle-nums, +.proportional-nums, +.tabular-nums, +.diagonal-fractions, +.stacked-fractions { + --tw-ordinal: var(--tw-empty, /*!*/ /*!*/); + --tw-slashed-zero: var(--tw-empty, /*!*/ /*!*/); + --tw-numeric-figure: var(--tw-empty, /*!*/ /*!*/); + --tw-numeric-spacing: var(--tw-empty, /*!*/ /*!*/); + --tw-numeric-fraction: var(--tw-empty, /*!*/ /*!*/); + font-variant-numeric: var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) + var(--tw-numeric-spacing) var(--tw-numeric-fraction); +} +.ordinal { + --tw-ordinal: ordinal; +} +.tabular-nums { + --tw-numeric-spacing: tabular-nums; +} +.diagonal-fractions { + --tw-numeric-fraction: diagonal-fractions; +} +.leading-relaxed { + line-height: 1.625; +} +.leading-5 { + line-height: 1.25rem; +} +.tracking-tight { + letter-spacing: -0.025em; +} +.text-indigo-500 { + --tw-text-opacity: 1; + color: rgba(99, 102, 241, var(--tw-text-opacity)); +} +.text-opacity-10 { + --tw-text-opacity: 0.1; +} +.underline { + text-decoration: underline; +} +.antialiased { + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +.placeholder-green-300::placeholder { + --tw-placeholder-opacity: 1; + color: rgba(110, 231, 183, var(--tw-placeholder-opacity)); +} +.placeholder-opacity-60::placeholder { + --tw-placeholder-opacity: 0.6; +} +.opacity-90 { + opacity: 0.9; +} +.bg-blend-darken { + background-blend-mode: darken; +} +.bg-blend-difference { + background-blend-mode: difference; +} +.mix-blend-multiply { + mix-blend-mode: multiply; +} +.mix-blend-saturation { + mix-blend-mode: saturation; +} +.shadow { + --tw-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-md { + --tw-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.shadow-lg { + --tw-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); +} +.outline-none { + outline: 2px solid transparent; + outline-offset: 2px; +} +.outline-black { + outline: 2px dotted black; + outline-offset: 2px; +} +.ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); +} +.ring-4 { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); +} +.ring-white { + --tw-ring-opacity: 1; + --tw-ring-color: rgba(255, 255, 255, var(--tw-ring-opacity)); +} +.ring-opacity-40 { + --tw-ring-opacity: 0.4; +} +.ring-offset-2 { + --tw-ring-offset-width: 2px; +} +.ring-offset-blue-300 { + --tw-ring-offset-color: #93c5fd; +} +.filter { + --tw-blur: var(--tw-empty, /*!*/ /*!*/); + --tw-brightness: var(--tw-empty, /*!*/ /*!*/); + --tw-contrast: var(--tw-empty, /*!*/ /*!*/); + --tw-grayscale: var(--tw-empty, /*!*/ /*!*/); + --tw-hue-rotate: var(--tw-empty, /*!*/ /*!*/); + --tw-invert: var(--tw-empty, /*!*/ /*!*/); + --tw-saturate: var(--tw-empty, /*!*/ /*!*/); + --tw-sepia: var(--tw-empty, /*!*/ /*!*/); + --tw-drop-shadow: var(--tw-empty, /*!*/ /*!*/); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); +} +.filter-none { + filter: none; +} +.blur-md { + --tw-blur: blur(12px); +} +.brightness-150 { + --tw-brightness: brightness(1.5); +} +.contrast-50 { + --tw-contrast: contrast(0.5); +} +.drop-shadow-md { + --tw-drop-shadow: drop-shadow(0 4px 3px rgba(0, 0, 0, 0.07)) + drop-shadow(0 2px 2px rgba(0, 0, 0, 0.06)); +} +.grayscale { + --tw-grayscale: grayscale(100%); +} +.hue-rotate-60 { + --tw-hue-rotate: hue-rotate(60deg); +} +.invert { + --tw-invert: invert(100%); +} +.saturate-200 { + --tw-saturate: saturate(2); +} +.sepia { + --tw-sepia: sepia(100%); +} +.backdrop-filter { + --tw-backdrop-blur: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-brightness: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-contrast: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-grayscale: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-hue-rotate: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-invert: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-opacity: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-saturate: var(--tw-empty, /*!*/ /*!*/); + --tw-backdrop-sepia: var(--tw-empty, /*!*/ /*!*/); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); +} +.backdrop-filter-none { + backdrop-filter: none; +} +.backdrop-blur-lg { + --tw-backdrop-blur: blur(16px); +} +.backdrop-brightness-50 { + --tw-backdrop-brightness: brightness(0.5); +} +.backdrop-contrast-0 { + --tw-backdrop-contrast: contrast(0); +} +.backdrop-grayscale { + --tw-backdrop-grayscale: grayscale(100%); +} +.backdrop-hue-rotate-90 { + --tw-backdrop-hue-rotate: hue-rotate(90deg); +} +.backdrop-invert { + --tw-backdrop-invert: invert(100%); +} +.backdrop-opacity-75 { + --tw-backdrop-opacity: opacity(0.75); +} +.backdrop-saturate-150 { + --tw-backdrop-saturate: saturate(1.5); +} +.backdrop-sepia { + --tw-backdrop-sepia: sepia(100%); +} +.transition { + transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, + transform, filter, backdrop-filter; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} +.transition-all { + transition-property: all; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} +.delay-300 { + transition-delay: 300ms; +} +.duration-200 { + transition-duration: 200ms; +} +.ease-in-out { + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); +} diff --git a/tests/jit/raw-content.test.html b/tests/jit/raw-content.test.html new file mode 100644 --- /dev/null +++ b/tests/jit/raw-content.test.html @@ -0,0 +1,147 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <link rel="icon" href="/favicon.ico" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Title</title> + <link rel="stylesheet" href="./tailwind.css" /> + </head> + <body> + <div class="sr-only"></div> + <div class="content-center"></div> + <div class="items-start"></div> + <div class="self-end"></div> + <div class="animate-none"></div> + <div class="animate-spin"></div> + <div class="appearance-none"></div> + <div class="bg-local"></div> + <div class="bg-clip-border"></div> + <div class="bg-green-500"></div> + <div class="bg-gradient-to-r"></div> + <div class="bg-opacity-20"></div> + <div class="bg-top"></div> + <div class="bg-no-repeat"></div> + <div class="bg-cover"></div> + <div class="bg-origin-border bg-origin-padding bg-origin-content"></div> + <div class="border-collapse"></div> + <div class="border-black"></div> + <div class="border-opacity-10"></div> + <div class="rounded-md"></div> + <div class="border-solid"></div> + <div class="border"></div> + <div class="border-2"></div> + <div class="shadow"></div> + <div class="shadow-md"></div> + <div class="shadow-lg"></div> + <div class="decoration-clone decoration-slice"></div> + <div class="box-border"></div> + <div class="clear-left"></div> + <div class="container"></div> + <div class="cursor-pointer"></div> + <div class="hidden inline-grid"></div> + <div class="divide-gray-200"></div> + <div class="divide-opacity-50"></div> + <div class="divide-dotted"></div> + <div class="divide-x-2 divide-y-4 divide-x-0 divide-y-0"></div> + <div class="fill-current"></div> + <div class="flex-1"></div> + <div class="flex-row-reverse"></div> + <div class="flex-grow"></div> + <div class="flex-grow-0"></div> + <div class="flex-shrink"></div> + <div class="flex-shrink-0"></div> + <div class="flex-wrap"></div> + <div class="float-right"></div> + <div class="font-sans"></div> + <div class="text-2xl"></div> + <div class="antialiased"></div> + <div class="not-italic"></div> + <div class="tabular-nums ordinal diagonal-fractions"></div> + <div class="font-medium"></div> + <div class="gap-x-2 gap-y-3 gap-4"></div> + <div class="from-red-300 via-purple-200 to-blue-400"></div> + <div class="auto-cols-min"></div> + <div class="grid-flow-row"></div> + <div class="auto-rows-max"></div> + <div class="col-span-3"></div> + <div class="col-start-1"></div> + <div class="col-end-4"></div> + <div class="row-span-2"></div> + <div class="row-start-3"></div> + <div class="row-end-5"></div> + <div class="grid-cols-4"></div> + <div class="grid-rows-3"></div> + <div class="h-16"></div> + <div class="inset-0 inset-y-4 inset-x-2 top-6 right-8 bottom-12 left-16"></div> + <div class="isolate isolation-auto"></div> + <div class="justify-center"></div> + <div class="justify-items-end"></div> + <div class="justify-self-start"></div> + <div class="tracking-tight"></div> + <div class="leading-relaxed leading-5"></div> + <div class="list-inside"></div> + <div class="list-disc"></div> + <div class="m-4 my-2 mx-auto mt-0 mr-1 mb-3 ml-4"></div> + <div class="max-h-screen"></div> + <div class="max-w-full"></div> + <div class="min-h-0"></div> + <div class="min-w-min"></div> + <div class="object-cover"></div> + <div class="object-bottom"></div> + <div class="opacity-90"></div> + <div class="bg-blend-darken bg-blend-difference"></div> + <div class="mix-blend-multiply mix-blend-saturation"></div> + <div class="order-last order-2"></div> + <div class="outline-none outline-black"></div> + <div class="overflow-hidden"></div> + <div class="overscroll-contain"></div> + <div class="p-4 py-2 px-3 pt-1 pr-2 pb-3 pl-4"></div> + <div class="place-content-start"></div> + <div class="placeholder-green-300"></div> + <div class="placeholder-opacity-60"></div> + <div class="place-items-end"></div> + <div class="place-self-center"></div> + <div class="pointer-events-none"></div> + <div class="absolute"></div> + <div class="resize-none"></div> + <div class="ring-white"></div> + <div class="ring-offset-blue-300"></div> + <div class="ring-offset-2"></div> + <div class="ring-opacity-40"></div> + <div class="ring ring-4"></div> + <div + class="filter filter-none blur-md brightness-150 contrast-50 drop-shadow-md grayscale hue-rotate-60 invert saturate-200 sepia" + ></div> + <div + class="backdrop-filter backdrop-filter-none backdrop-blur-lg backdrop-brightness-50 backdrop-contrast-0 backdrop-grayscale backdrop-hue-rotate-90 backdrop-invert backdrop-opacity-75 backdrop-saturate-150 backdrop-sepia" + ></div> + <div class="rotate-3"></div> + <div class="scale-95"></div> + <div class="skew-y-12 skew-x-12"></div> + <div class="space-x-4 space-y-3 space-x-reverse space-y-reverse"></div> + <div class="stroke-current"></div> + <div class="stroke-2"></div> + <div class="table-fixed"></div> + <div class="text-center"></div> + <div class="text-indigo-500"></div> + <div class="underline"></div> + <div class="text-opacity-10"></div> + <div class="overflow-ellipsis truncate"></div> + <div class="uppercase"></div> + <div class="transform transform-gpu"></div> + <div class="origin-top-right"></div> + <div class="delay-300"></div> + <div class="duration-200"></div> + <div class="transition transition-all"></div> + <div class="ease-in-out"></div> + <div class="translate-x-5 -translate-x-4 translate-y-6 -translate-x-3"></div> + <div class="select-none"></div> + <div class="align-middle"></div> + <div class="invisible"></div> + <div class="whitespace-nowrap"></div> + <div class="w-12"></div> + <div class="break-words"></div> + <div class="z-30"></div> + </body> +</html> diff --git a/tests/jit/raw-content.test.js b/tests/jit/raw-content.test.js new file mode 100644 --- /dev/null +++ b/tests/jit/raw-content.test.js @@ -0,0 +1,85 @@ +import postcss from 'postcss' +import fs from 'fs' +import path from 'path' + +beforeEach(() => { + jest.resetModules() +}) + +function run(tailwind, input, config = {}) { + return postcss(tailwind(config)).process(input, { + from: path.resolve(__filename), + }) +} + +test('raw content', () => { + let tailwind = require('../../src/jit/index.js').default + + let config = { + mode: 'jit', + purge: [{ raw: fs.readFileSync(path.resolve(__dirname, './raw-content.test.html'), 'utf8') }], + corePlugins: { preflight: false }, + theme: {}, + plugins: [], + } + + let css = ` + @tailwind base; + @tailwind components; + @tailwind utilities; + ` + + return run(tailwind, css, config).then((result) => { + let expectedPath = path.resolve(__dirname, './raw-content.test.css') + let expected = fs.readFileSync(expectedPath, 'utf8') + + expect(result.css).toMatchFormattedCss(expected) + }) +}) + +test('raw content with extension', () => { + let tailwind = require('../../src/jit/index.js').default + + let config = { + mode: 'jit', + purge: { + content: [ + { + raw: fs.readFileSync(path.resolve(__dirname, './raw-content.test.html'), 'utf8'), + extension: 'html', + }, + ], + options: { + extractors: [ + { + extractor: () => [], + extensions: ['html'], + }, + ], + }, + }, + corePlugins: { preflight: false }, + theme: {}, + plugins: [], + } + + let css = ` + @tailwind base; + @tailwind components; + @tailwind utilities; + ` + + return run(tailwind, css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + * { + --tw-shadow: 0 0 #0000; + --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgba(59, 130, 246, 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + } + `) + }) +})
[JIT] Add support for "raw" purge content ### What version of Tailwind CSS are you using? v2.1.1 ### What build tool (or framework if it abstracts the build tool) are you using? Maizzle v3.3.1 ### What version of Node.js are you using? v14.15.1 ### What browser are you using? Chrome ### What operating system are you using? Windows 10 ### Reproduction repository https://github.com/maizzle/maizzle ### Describe your issue Configuring the `purge` option in your build chain instead of `tailwind.config.js` results in: ``` TypeError: expected path to be a string ``` Sounds like it expects it to be in the `tailwind.config.js` file. What I'm doing is definining a base config in the file where I compile Tailwind, like this: ```js const coreConfig = { purge: { enabled: true, content: [ 'src/**/*.*', ], }, } ``` I then merge that with the config read from my `tailwind.config.js` and use it to compile Tailwind with PostCSS: ```js // merge() is from lodash // `tailwindConfigObject` is the contents of `tailwind.config.js` return postcss([ tailwindcss(merge(coreConfig, tailwindConfigObject)), ]) .process(css, {from: undefined}) .then(result => result.css) ``` The resulting config is correct, and it works fine without JIT. When I add `mode: 'jit'` in `tailwind.config.js`, it throws the error. As soon as I also add `purge: ['src/**/*.*']` in `tailwind.config.js`, JIT works as expected.
Just tried to use an object config right in `tailwind.config.js` for `purge`: ```js module.exports = { mode: 'jit', // purge: [ // 'src/**/*.*', // ], purge: { enabled: true, content: [ 'src/**/*.*', ], }, } ``` ... and the same error is thrown. I suppose object syntax just isn't supported yet here, that also being one of the reasons purgecss options like `safelist` aren't supported? Apologies if this has been covered somewhere, I couldn't find any issue/docs about it except the `safelist` thing. > I suppose object syntax just isn't supported yet here Providing an object with a `content` property is supported, and your example should work fine. Is there any chance you could provide a minimal reproduction? I can't see a purge config anywhere in the maizzle repo. Thanks! The purge config is in the framework repo - my bad! https://github.com/maizzle/framework/blob/0dabece8b036739a0bdd8ed83c31cf8b452a3e1f/src/generators/tailwindcss.js#L22-L29 I just [merge](https://github.com/maizzle/framework/blob/0dabece8b036739a0bdd8ed83c31cf8b452a3e1f/src/generators/tailwindcss.js#L62) whatever you have in tailwind.config.js on top of that. So just adding `mode: 'jit'` in `tailwind.config.js`, without including a `purge` key with simplified array syntax (thus relying on the object syntax defined in the framework linked above), will hang πŸ€” Created a repo that reproduces the issue, I've added instructions in the readme: https://github.com/maizzle/jit-object-config Thanks! It's because [you are using "raw" content](https://github.com/maizzle/framework/blob/0dabece8b036739a0bdd8ed83c31cf8b452a3e1f/src/generators/tailwindcss.js#L26), which isn't currently supported by JIT mode. We will probably add support for this at some point for consistency with PurgeCSS, but for now that's why it isn't working, sorry about that! Ah, OK. Yeah I need `raw` when rendering templates programmatically so that Tailwind can purge based on the HTML string that I want to compile, since there are no file paths in that context. Feel free to close the issue if you prefer, and thanks for looking into it! :)
"2021-05-07T11:36:33Z"
2.1
[]
[ "tests/jit/raw-content.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
4,277
tailwindlabs__tailwindcss-4277
[ "4261" ]
2f100efbab89776366ab9e71fdbd6b0357b3af92
diff --git a/src/plugins/borderColor.js b/src/plugins/borderColor.js --- a/src/plugins/borderColor.js +++ b/src/plugins/borderColor.js @@ -2,7 +2,23 @@ import flattenColorPalette from '../util/flattenColorPalette' import withAlphaVariable from '../util/withAlphaVariable' export default function () { - return function ({ matchUtilities, theme, variants, corePlugins }) { + return function ({ addBase, matchUtilities, theme, variants, corePlugins }) { + if (!corePlugins('borderOpacity')) { + addBase({ + '*, ::before, ::after': { + 'border-color': theme('borderColor.DEFAULT', 'currentColor'), + }, + }) + } else { + addBase({ + '*, ::before, ::after': withAlphaVariable({ + color: theme('borderColor.DEFAULT', 'currentColor'), + property: 'border-color', + variable: '--tw-border-opacity', + }), + }) + } + matchUtilities( { border: (value) => {
diff --git a/tests/fixtures/tailwind-output-flagged.css b/tests/fixtures/tailwind-output-flagged.css --- a/tests/fixtures/tailwind-output-flagged.css +++ b/tests/fixtures/tailwind-output-flagged.css @@ -410,7 +410,7 @@ body { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ - border-color: #e5e7eb; /* 2 */ + border-color: currentColor; /* 2 */ } /* @@ -539,6 +539,11 @@ video { height: auto; } +*, ::before, ::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} + .container { width: 100%; } diff --git a/tests/fixtures/tailwind-output-important.css b/tests/fixtures/tailwind-output-important.css --- a/tests/fixtures/tailwind-output-important.css +++ b/tests/fixtures/tailwind-output-important.css @@ -410,7 +410,7 @@ body { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ - border-color: #e5e7eb; /* 2 */ + border-color: currentColor; /* 2 */ } /* @@ -539,6 +539,11 @@ video { height: auto; } +*, ::before, ::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} + .container { width: 100%; } diff --git a/tests/fixtures/tailwind-output-no-color-opacity.css b/tests/fixtures/tailwind-output-no-color-opacity.css --- a/tests/fixtures/tailwind-output-no-color-opacity.css +++ b/tests/fixtures/tailwind-output-no-color-opacity.css @@ -410,7 +410,7 @@ body { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ - border-color: #e5e7eb; /* 2 */ + border-color: currentColor; /* 2 */ } /* @@ -539,6 +539,10 @@ video { height: auto; } +*, ::before, ::after { + border-color: #e5e7eb; +} + .container { width: 100%; } diff --git a/tests/fixtures/tailwind-output.css b/tests/fixtures/tailwind-output.css --- a/tests/fixtures/tailwind-output.css +++ b/tests/fixtures/tailwind-output.css @@ -410,7 +410,7 @@ body { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ - border-color: #e5e7eb; /* 2 */ + border-color: currentColor; /* 2 */ } /* @@ -539,6 +539,11 @@ video { height: auto; } +*, ::before, ::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} + .container { width: 100%; } diff --git a/tests/jit/apply.test.css b/tests/jit/apply.test.css --- a/tests/jit/apply.test.css +++ b/tests/jit/apply.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/arbitrary-values.test.css b/tests/jit/arbitrary-values.test.css --- a/tests/jit/arbitrary-values.test.css +++ b/tests/jit/arbitrary-values.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/basic-usage.test.css b/tests/jit/basic-usage.test.css --- a/tests/jit/basic-usage.test.css +++ b/tests/jit/basic-usage.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/collapse-adjacent-rules.test.css b/tests/jit/collapse-adjacent-rules.test.css --- a/tests/jit/collapse-adjacent-rules.test.css +++ b/tests/jit/collapse-adjacent-rules.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/custom-extractors.test.css b/tests/jit/custom-extractors.test.css --- a/tests/jit/custom-extractors.test.css +++ b/tests/jit/custom-extractors.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/import-syntax.test.css b/tests/jit/import-syntax.test.css --- a/tests/jit/import-syntax.test.css +++ b/tests/jit/import-syntax.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/important-boolean.test.css b/tests/jit/important-boolean.test.css --- a/tests/jit/important-boolean.test.css +++ b/tests/jit/important-boolean.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/important-modifier-prefix.test.css b/tests/jit/important-modifier-prefix.test.css --- a/tests/jit/important-modifier-prefix.test.css +++ b/tests/jit/important-modifier-prefix.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/important-modifier.test.css b/tests/jit/important-modifier.test.css --- a/tests/jit/important-modifier.test.css +++ b/tests/jit/important-modifier.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/important-selector.test.css b/tests/jit/important-selector.test.css --- a/tests/jit/important-selector.test.css +++ b/tests/jit/important-selector.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/kitchen-sink.test.css b/tests/jit/kitchen-sink.test.css --- a/tests/jit/kitchen-sink.test.css +++ b/tests/jit/kitchen-sink.test.css @@ -126,6 +126,12 @@ } } } +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/opacity.test.css b/tests/jit/opacity.test.css --- a/tests/jit/opacity.test.css +++ b/tests/jit/opacity.test.css @@ -1,3 +1,8 @@ +*, +::before, +::after { + border-color: #e5e7eb; +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/prefix.test.css b/tests/jit/prefix.test.css --- a/tests/jit/prefix.test.css +++ b/tests/jit/prefix.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); @@ -73,7 +79,7 @@ .tw-group:hover .group-hover\:focus-within\:tw-text-left:focus-within { text-align: left; } -[dir="rtl"] .rtl\:active\:tw-text-center:active { +[dir='rtl'] .rtl\:active\:tw-text-center:active { text-align: center; } @media (prefers-reduced-motion: no-preference) { diff --git a/tests/jit/raw-content.test.css b/tests/jit/raw-content.test.css --- a/tests/jit/raw-content.test.css +++ b/tests/jit/raw-content.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/raw-content.test.js b/tests/jit/raw-content.test.js --- a/tests/jit/raw-content.test.js +++ b/tests/jit/raw-content.test.js @@ -71,6 +71,12 @@ test('raw content with extension', () => { return run(tailwind, css, config).then((result) => { expect(result.css).toMatchFormattedCss(` + *, + ::before, + ::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); + } * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/relative-purge-paths.test.css b/tests/jit/relative-purge-paths.test.css --- a/tests/jit/relative-purge-paths.test.css +++ b/tests/jit/relative-purge-paths.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/responsive-and-variants-atrules.test.css b/tests/jit/responsive-and-variants-atrules.test.css --- a/tests/jit/responsive-and-variants-atrules.test.css +++ b/tests/jit/responsive-and-variants-atrules.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/svelte-syntax.test.css b/tests/jit/svelte-syntax.test.css --- a/tests/jit/svelte-syntax.test.css +++ b/tests/jit/svelte-syntax.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/); diff --git a/tests/jit/variants.test.css b/tests/jit/variants.test.css --- a/tests/jit/variants.test.css +++ b/tests/jit/variants.test.css @@ -1,3 +1,9 @@ +*, +::before, +::after { + --tw-border-opacity: 1; + border-color: rgba(229, 231, 235, var(--tw-border-opacity)); +} * { --tw-shadow: 0 0 #0000; --tw-ring-inset: var(--tw-empty, /*!*/ /*!*/);
[Bug]: border-opacity doesn't work with default border color ### What version of Tailwind CSS are you using? 2.1.1 ### What build tool (or framework if it abstracts the build tool) are you using? play.tailwind.com ### What version of Node.js are you using? play.tailwind.com ### What browser are you using? Safari 14.1 and Brave 1.23.75 using Chromium: 90.0.4430.93 ### What operating system are you using? macOS 11.3.1 ### Reproduction repository https://play.tailwindcss.com/8qs2AKmp9g ### Describe your issue Border opacity doesn't work with the default border color. For instance, I'd expect to not see a border on this div since the `border-opacity` is 0. However, can still see a border. ```html <main class='w-screen h-screen p-8'> <div class='w-full h-full border border-opacity-0'></div> </main> ``` However, adding a border color (e.g., `border-red-500`) lets the opacity work correctly. If for some reason the playground link doesn't work, just start with a new playground and replace the HTML with the HTML above.
> However, adding a border color (e.g., border-red-500) lets the opacity work correctly. I have the exact same issue but with custom colors as well.
"2021-05-07T23:45:57Z"
2.1
[]
[ "tests/jit/raw-content.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/8qs2AKmp9g" ]
tailwindlabs/tailwindcss
4,335
tailwindlabs__tailwindcss-4335
[ "4008" ]
87a4516871fbe8eb5a188fa9774a99a5d43e38b6
diff --git a/src/jit/index.js b/src/jit/index.js --- a/src/jit/index.js +++ b/src/jit/index.js @@ -30,9 +30,9 @@ export default function (configOrPath = {}) { }) } - rewriteTailwindImports(root) + let tailwindDirectives = rewriteTailwindImports(root) - let context = setupContext(configOrPath)(result, root) + let context = setupContext(configOrPath, tailwindDirectives)(result, root) if (!env.TAILWIND_DISABLE_TOUCH) { if (context.configPath !== null) { @@ -41,8 +41,8 @@ export default function (configOrPath = {}) { } return postcss([ - removeLayerAtRules(context), - expandTailwindAtRules(context, registerDependency), + removeLayerAtRules(context, tailwindDirectives), + expandTailwindAtRules(context, registerDependency, tailwindDirectives), expandApplyAtRules(context), evaluateTailwindFunctions(context.tailwindConfig), substituteScreenAtRules(context.tailwindConfig), diff --git a/src/jit/lib/expandTailwindAtRules.js b/src/jit/lib/expandTailwindAtRules.js --- a/src/jit/lib/expandTailwindAtRules.js +++ b/src/jit/lib/expandTailwindAtRules.js @@ -111,9 +111,12 @@ function buildStylesheet(rules, context) { return returnValue } -export default function expandTailwindAtRules(context, registerDependency) { +export default function expandTailwindAtRules(context, registerDependency, tailwindDirectives) { return (root) => { - let foundTailwind = false + if (tailwindDirectives.size === 0) { + return root + } + let layerNodes = { base: null, components: null, @@ -126,8 +129,6 @@ export default function expandTailwindAtRules(context, registerDependency) { // file as a dependency since the output of this CSS does not depend on // the source of any templates. Think Vue <style> blocks for example. root.walkAtRules('tailwind', (rule) => { - foundTailwind = true - if (rule.params === 'base') { layerNodes.base = rule } @@ -145,10 +146,6 @@ export default function expandTailwindAtRules(context, registerDependency) { } }) - if (!foundTailwind) { - return root - } - // --- if (sharedState.env.TAILWIND_DISABLE_TOUCH) { diff --git a/src/jit/lib/removeLayerAtRules.js b/src/jit/lib/removeLayerAtRules.js --- a/src/jit/lib/removeLayerAtRules.js +++ b/src/jit/lib/removeLayerAtRules.js @@ -1,7 +1,22 @@ -export default function removeLayerAtRules() { +export default function removeLayerAtRules(_context, tailwindDirectives) { return (root) => { root.walkAtRules((rule) => { - if (['layer', 'responsive', 'variants'].includes(rule.name)) { + if (rule.name === 'layer' && ['base', 'components', 'utilities'].includes(rule.params)) { + if (!tailwindDirectives.has(rule.params)) { + throw rule.error( + `\`@layer ${rule.params}\` is used but no matching \`@tailwind ${rule.params}\` directive is present.` + ) + } + rule.remove() + } else if (rule.name === 'responsive') { + if (!tailwindDirectives.has('utilities')) { + throw rule.error('`@responsive` is used but `@tailwind utilities` is missing.') + } + rule.remove() + } else if (rule.name === 'variants') { + if (!tailwindDirectives.has('utilities')) { + throw rule.error('`@variants` is used but `@tailwind utilities` is missing.') + } rule.remove() } }) diff --git a/src/jit/lib/rewriteTailwindImports.js b/src/jit/lib/rewriteTailwindImports.js --- a/src/jit/lib/rewriteTailwindImports.js +++ b/src/jit/lib/rewriteTailwindImports.js @@ -23,4 +23,12 @@ export default function rewriteTailwindImports(root) { atRule.params = 'screens' } }) + + let tailwindDirectives = new Set() + + root.walkAtRules('tailwind', (rule) => { + tailwindDirectives.add(rule.params) + }) + + return tailwindDirectives } diff --git a/src/jit/lib/setupContext.js b/src/jit/lib/setupContext.js --- a/src/jit/lib/setupContext.js +++ b/src/jit/lib/setupContext.js @@ -314,6 +314,7 @@ function rebootWatcher(context) { touch(context.configPath) } else { context.changedFiles.add(path.resolve('.', file)) + console.log(context.touchFile) touch(context.touchFile) } }) @@ -686,14 +687,8 @@ function cleanupContext(context) { // Retrieve an existing context from cache if possible (since contexts are unique per // source path), or set up a new one (including setting up watchers and registering // plugins) then return it -export default function setupContext(configOrPath) { +export default function setupContext(configOrPath, tailwindDirectives) { return (result, root) => { - let foundTailwind = false - - root.walkAtRules('tailwind', () => { - foundTailwind = true - }) - let sourcePath = result.opts.from let [ tailwindConfig, @@ -712,7 +707,7 @@ export default function setupContext(configOrPath) { // We may want to think about `@layer` being part of this trigger too, but it's tough // because it's impossible for a layer in one file to end up in the actual @tailwind rule // in another file since independent sources are effectively isolated. - if (foundTailwind) { + if (tailwindDirectives.size > 0) { contextDependencies.add(sourcePath) for (let message of result.messages) { if (message.type === 'dependency') {
diff --git a/tests/jit/layer-without-tailwind.test.css b/tests/jit/layer-without-tailwind.test.css new file mode 100644 --- /dev/null +++ b/tests/jit/layer-without-tailwind.test.css @@ -0,0 +1,5 @@ +@layer components { + .foo { + color: black; + } +} diff --git a/tests/jit/layer-without-tailwind.test.html b/tests/jit/layer-without-tailwind.test.html new file mode 100644 --- /dev/null +++ b/tests/jit/layer-without-tailwind.test.html @@ -0,0 +1 @@ +<div class="foo"></div> diff --git a/tests/jit/layer-without-tailwind.test.js b/tests/jit/layer-without-tailwind.test.js new file mode 100644 --- /dev/null +++ b/tests/jit/layer-without-tailwind.test.js @@ -0,0 +1,101 @@ +import postcss from 'postcss' +import path from 'path' +import tailwind from '../../src/jit/index.js' + +function run(input, config = {}) { + const { currentTestName } = expect.getState() + + return postcss(tailwind(config)).process(input, { + from: `${path.resolve(__filename)}?test=${currentTestName}`, + }) +} + +test('using @layer without @tailwind', async () => { + let config = { + purge: [path.resolve(__dirname, './layer-without-tailwind.test.html')], + mode: 'jit', + theme: {}, + plugins: [], + } + + let css = ` + @layer components { + .foo { + color: black; + } + } + ` + + await expect(run(css, config)).rejects.toThrowError( + '`@layer components` is used but no matching `@tailwind components` directive is present.' + ) +}) + +test('using @responsive without @tailwind', async () => { + let config = { + purge: [path.resolve(__dirname, './layer-without-tailwind.test.html')], + mode: 'jit', + theme: {}, + plugins: [], + } + + let css = ` + @responsive { + .foo { + color: black; + } + } + ` + + await expect(run(css, config)).rejects.toThrowError( + '`@responsive` is used but `@tailwind utilities` is missing.' + ) +}) + +test('using @variants without @tailwind', async () => { + let config = { + purge: [path.resolve(__dirname, './layer-without-tailwind.test.html')], + mode: 'jit', + theme: {}, + plugins: [], + } + + let css = ` + @variants hover { + .foo { + color: black; + } + } + ` + + await expect(run(css, config)).rejects.toThrowError( + '`@variants` is used but `@tailwind utilities` is missing.' + ) +}) + +test('non-Tailwind @layer rules are okay', async () => { + let config = { + purge: [path.resolve(__dirname, './layer-without-tailwind.test.html')], + mode: 'jit', + theme: {}, + plugins: [], + } + + let css = ` + @layer custom { + .foo { + color: black; + } + } + ` + + return run(css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + @layer custom { + .foo { + color: black; + } + } + `) + }) +}) diff --git a/tests/jit/prefix.test.js b/tests/jit/prefix.test.js --- a/tests/jit/prefix.test.js +++ b/tests/jit/prefix.test.js @@ -66,7 +66,7 @@ test('prefix', () => { } } @tailwind utilities; - @layer utilites { + @layer utilities { .custom-utility { foo: bar; }
JIT x CSS Modules x `@layer` directive results in no CSS module class emitted ### What version of Tailwind CSS are you using? v2.1.1 ### What version of Node.js are you using? v12.14.1 ### What browser are you using? Chrome ### What operating system are you using? macOS ### Reproduction repository repro steps below # The Bug HTML elements aren't being assigned classnames when the Tailwind JIT engine is used with CSS modules and `@layer components`. This happens in both dev and prod I think most people can remove `@layer` but I'm reporting this anyway because this seems like a regression # Reproduction 1. `yarn create next-app --example with-tailwindcss`, then `cd` into the project dir 2. apply this patch: ```patch diff --git a/package.json b/package.json index 46f0c5d..8132319 100644 --- a/package.json +++ b/package.json @@ -13,9 +13,8 @@ "react-dom": "^17.0.1" }, "devDependencies": { - "@tailwindcss/jit": "0.1.3", "autoprefixer": "^10.0.4", "postcss": "^8.1.10", - "tailwindcss": "^2.0.2" + "tailwindcss": "^2.1.1" } } diff --git a/pages/index.js b/pages/index.js index 5cb31bc..5084680 100644 --- a/pages/index.js +++ b/pages/index.js @@ -1,8 +1,10 @@ import Head from 'next/head' +import styles from "./index.module.css"; + export default function Home() { return ( - <div className="flex flex-col items-center justify-center min-h-screen py-2"> + <div className={styles.wrapper}> <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> diff --git a/pages/index.module.css b/pages/index.module.css new file mode 100644 index 0000000..a062ca2 --- /dev/null +++ b/pages/index.module.css @@ -0,0 +1,5 @@ +@layer components { + .wrapper { + @apply flex flex-col items-center justify-center min-h-screen py-2; + } +} \ No newline at end of file diff --git a/postcss.config.js b/postcss.config.js index fc58cf3..2d5c5c0 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -2,7 +2,7 @@ // https://tailwindcss.com/docs/using-with-preprocessors module.exports = { plugins: { - '@tailwindcss/jit': {}, + 'tailwindcss': {}, autoprefixer: {}, }, } diff --git a/tailwind.config.js b/tailwind.config.js index d7f0874..32f0b66 100644 --- a/tailwind.config.js +++ b/tailwind.config.js @@ -1,4 +1,5 @@ module.exports = { + mode: "jit", purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'], darkMode: false, // or 'media' or 'class' theme: { diff --git a/yarn.lock b/yarn.lock index 4088c52..267ddf3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -131,19 +131,6 @@ resolved "https://registry.yarnpkg.com/@opentelemetry/context-base/-/context-base-0.14.0.tgz#c67fc20a4d891447ca1a855d7d70fa79a3533001" integrity sha512-sDOAZcYwynHFTbLo6n8kIbLiVF3a3BLkrmehJUyEbT9F+Smbi47kLGS2gG2g0fjBLR/Lr1InPD7kXL7FaTqEkw== -"@tailwindcss/[email protected]": - version "0.1.3" - resolved "https://registry.yarnpkg.com/@tailwindcss/jit/-/jit-0.1.3.tgz#50390d9ac95fee78ed23a7e2320ef20bd4a35354" - integrity sha512-7VAvHKNLJxbGWRKxo2Z+beiodag7vWPx8b/+Egd5fve4zFihsngeNt6RwQFnll+almjppRYefRC5Py5v5K+6vg== - dependencies: - chokidar "^3.5.1" - dlv "^1.1.3" - fast-glob "^3.2.5" - lodash.topath "^4.5.2" - object-hash "^2.1.1" - postcss-selector-parser "^6.0.4" - quick-lru "^5.1.1" - "@types/node@*": version "14.14.37" resolved "https://registry.yarnpkg.com/@types/node/-/node-14.14.37.tgz#a3dd8da4eb84a996c36e331df98d82abd76b516e" @@ -2213,7 +2200,7 @@ supports-color@^8.0.0: dependencies: has-flag "^4.0.0" -tailwindcss@^2.0.2: +tailwindcss@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/tailwindcss/-/tailwindcss-2.1.1.tgz#642f6038c9283a8e1454da34585b8b7c1a1e8877" integrity sha512-zZ6axGqpSZOCBS7wITm/WNHkBzDt5CIZlDlx0eCVldwTxFPELCVGbgh7Xpb3/kZp3cUxOmK7bZUjqhuMrbN6xQ== ``` 3. `yarn run dev`, notice that the root div has no class This issue occurs: - if you switch to webpack 5 This issue does not occur: - if you disable JIT - if you remove `@layer components` - if you use `@apply` in a `@layer` directive in a global stylesheet, not in a CSS module (I think) - if you use `@tailwindcss/jit` (I think)
I am seeing the same symptoms in a similar setup (but using just `css-loader` and `mini-css-extract-plugin`). I think this is probably expected if I understand it right β€” CSS modules are processed in total isolation and it's not possible for a `@layer` rule there to be hoisted out into Tailwind's main `@tailwind components` layer, those two trees of CSS are just totally unable to communicate or manipulate each other. What's the desired behavior here exactly? So looking into it more, the reason this works without JIT is that the layer stuff is just ignored completely. So it's exactly the same as not using `@layer` at all. We should probably throw an explicit error or something if a layer is detected in a file where it's not possible for it to work. > I think this is probably expected if I understand it right β€” CSS modules are processed in total isolation and it's not possible for a `@layer` rule there to be hoisted out into Tailwind's main `@tailwind components` layer, those two trees of CSS are just totally unable to communicate or manipulate each other. This makes sense, but I still don't think I understand why JIT behaves differently than "traditional" compiling. I would expect that the traditional compiler and the JIT compiler would receive the same CSS input, so I think the difference is that in traditional mode, Tailwind simply removes `@layer`, while JIT completely skips `@layer` blocksβ€”is this true? I don't think I really need `@layer` if I'm using CSS modules, but I still feel like traditional mode and JIT mode should return identical outputs in all cases. The difference is just that they are completely different chunks of code so there are just differences in how they work. In the JIT engine, anything in a `layer` is read and converted into an in-memory Tailwind plugin so it can be used to generate styles on demand, and this happens only when the build server first starts. Then, all `layer` rules are deleted from the source file, including all the CSS within them, since instead those rules are inserted on demand when detected in the HTML. In the traditional engine, layers are just blocks of CSS, and there's a step that gathers them all up and colocates code for the same layers together, and then late in the build stage the layer rules are converted to purgecss control comments which we use to make sure we only purge layers, and not regular custom CSS that lives outside of a layer. So it's just totally different code that needs to do totally different things for each engine β€” just bound to be differences in the failure modes like you've detected here. So in the traditional engine, what's happening with your CSS module is that the layer statements are being converted to comments, which means they end up just doing nothing. In the JIT engine, the layers are deleted since they are captured into memory as plugins, and now even though the HTML contains rules that are coming from those layer plugins, the code is never output because there is no `@tailwind components` block in the CSS module for the layer code to be inserted into. I agree that the output should be the same, this is just one of those cases where an error situation I didn't really think much about ends with different output in each engine because of the design of the separate engines. Both engines should probably error, but it's a little tricky because there's a real `@layer` rule coming to CSS and it might not be wise for us to assume all use of `layer` is Tailwind related. Can probably safely make assumptions about the `base`, `components`, and `utilities` layer names I suppose though.
"2021-05-12T20:48:45Z"
2.1
[ "tests/jit/prefix.test.js" ]
[ "tests/jit/layer-without-tailwind.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
4,795
tailwindlabs__tailwindcss-4795
[ "4791" ]
b3d5b4e00041392f85a860bcd7758edcfa7612f0
diff --git a/src/util/parseAnimationValue.js b/src/util/parseAnimationValue.js --- a/src/util/parseAnimationValue.js +++ b/src/util/parseAnimationValue.js @@ -2,7 +2,15 @@ const DIRECTIONS = new Set(['normal', 'reverse', 'alternate', 'alternate-reverse const PLAY_STATES = new Set(['running', 'paused']) const FILL_MODES = new Set(['none', 'forwards', 'backwards', 'both']) const ITERATION_COUNTS = new Set(['infinite']) -const TIMINGS = new Set(['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out']) +const TIMINGS = new Set([ + 'linear', + 'ease', + 'ease-in', + 'ease-out', + 'ease-in-out', + 'step-start', + 'step-end', +]) const TIMING_FNS = ['cubic-bezier', 'steps'] const COMMA = /\,(?![^(]*\))/g // Comma separator that is not located between brackets. E.g.: `cubiz-bezier(a, b, c)` these don't count.
diff --git a/tests/plugins/animation.test.js b/tests/plugins/animation.test.js --- a/tests/plugins/animation.test.js +++ b/tests/plugins/animation.test.js @@ -13,10 +13,12 @@ test('defining animation and keyframes', () => { none: 'none', spin: 'spin 1s linear infinite', ping: 'ping 1s cubic-bezier(0, 0, 0.2, 1) infinite', + blink: 'blink 1s step-end infinite', }, keyframes: { spin: { to: { transform: 'rotate(360deg)' } }, ping: { '75%, 100%': { transform: 'scale(2)', opacity: '0' } }, + blink: { '50%': { transform: 'scale(2)' } }, }, }, variants: { @@ -43,11 +45,20 @@ test('defining animation and keyframes', () => { } } + @layer utilities { + @variants { + @keyframes blink { + 50% { transform: scale(2); } + } + } + } + @layer utilities { @variants { .animate-none { animation: none; } .animate-spin { animation: spin 1s linear infinite; } .animate-ping { animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; } + .animate-blink { animation: blink 1s step-end infinite; } } } `)
Animations get purged if using step-start or step-end timing function ### What version of Tailwind CSS are you using? v2.2.2 ### What build tool (or framework if it abstracts the build tool) are you using? @symfony/webpack-encore": ^1.3.0 ### What version of Node.js are you using? v12.0.0 ### What browser are you using? N/A ### What operating system are you using? macOS ### Reproduction repository https://play.tailwindcss.com/P8QHN8mDNy?file=config ### Describe your issue When using `step-start` or `step-end` as animation-timing-function ([see MDN for possible built in values](https://developer.mozilla.org/de/docs/Web/CSS/animation-timing-function)) the animation won't work because `parseAnimationValue` won't return anything. I'd be happy to provide a PR to fix this πŸ‘πŸ»
Seems to be same issue as https://github.com/tailwindlabs/tailwindcss/issues/4737 @hug963 I saw your issue and I think it's kinda related. In case of `step-start` / `step-end` it should be as easy as updating the `timings` constant and add those values: https://github.com/tailwindlabs/tailwindcss/blob/master/src/util/parseAnimationValue.js#L5 Your case needs to be handled a little different, I'd expect a new regex needs to be added to the function.
"2021-06-24T11:38:52Z"
2.2
[]
[ "tests/plugins/animation.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/P8QHN8mDNy?file=config" ]
tailwindlabs/tailwindcss
4,817
tailwindlabs__tailwindcss-4817
[ "4801" ]
fdfecf3b9c50342210c280b20327726b7ff53324
diff --git a/src/jit/lib/expandTailwindAtRules.js b/src/jit/lib/expandTailwindAtRules.js --- a/src/jit/lib/expandTailwindAtRules.js +++ b/src/jit/lib/expandTailwindAtRules.js @@ -6,7 +6,13 @@ import cloneNodes from '../../util/cloneNodes' let env = sharedState.env let contentMatchCache = sharedState.contentMatchCache -const BROAD_MATCH_GLOBAL_REGEXP = /([^<>"'`\s]*\[[^<>\s]+\])|([^<>"'`\s]*[^<>"'`\s:])/g +const PATTERNS = [ + "([^<>\"'`\\s]*\\['[^<>\"'`\\s]*'\\])", // `content-['hello']` but not `content-['hello']']` + '([^<>"\'`\\s]*\\["[^<>"\'`\\s]*"\\])', // `content-["hello"]` but not `content-["hello"]"]` + '([^<>"\'`\\s]*\\[[^<>"\'`\\s]+\\])', // `fill-[#bada55]` + '([^<>"\'`\\s]*[^<>"\'`\\s:])', // `px-1.5`, `uppercase` but not `uppercase:` +].join('|') +const BROAD_MATCH_GLOBAL_REGEXP = new RegExp(PATTERNS, 'g') const INNER_MATCH_GLOBAL_REGEXP = /[^<>"'`\s.(){}[\]#=%]*[^<>"'`\s.(){}[\]#=%:]/g const builtInExtractors = {
diff --git a/tests/jit/extractor-edge-cases.test.js b/tests/jit/extractor-edge-cases.test.js new file mode 100644 --- /dev/null +++ b/tests/jit/extractor-edge-cases.test.js @@ -0,0 +1,57 @@ +import postcss from 'postcss' +import path from 'path' +import tailwind from '../../src/jit/index.js' + +function run(input, config = {}) { + const { currentTestName } = expect.getState() + + return postcss(tailwind(config)).process(input, { + from: `${path.resolve(__filename)}?test=${currentTestName}`, + }) +} + +test('PHP arrays', async () => { + let config = { + mode: 'jit', + purge: [ + { + raw: `<h1 class="<?php echo wrap(['class' => "max-w-[16rem]"]); ?>">Hello world</h1>`, + }, + ], + theme: {}, + plugins: [], + } + + let css = `@tailwind utilities` + + return run(css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + .max-w-\\[16rem\\] { + max-width: 16rem; + } + `) + }) +}) + +test('arbitrary values with quotes', async () => { + let config = { + mode: 'jit', + purge: [ + { + raw: `<div class="content-['hello]']"></div>`, + }, + ], + theme: {}, + plugins: [], + } + + let css = `@tailwind utilities` + + return run(css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + .content-\\[\\'hello\\]\\'\\] { + content: 'hello]'; + } + `) + }) +})
JIT includes quotes in class names when classes are followed by `'` and `]` characters ### What version of Tailwind CSS are you using? v2.2.4 ### What build tool (or framework if it abstracts the build tool) are you using? Tailwind CLI ### What version of Node.js are you using? v16.2.0 ### What browser are you using? Firefox (v89.0.2) ### What operating system are you using? macOS (11.4) ### Reproduction repository https://github.com/bakerkretzmar/tailwindcss-jit-quotes-repro ### Describe your issue If an arbitrary value in a class name is immediately followed by a single quote mark and another closing bracket, the quote and bracket are included in the generated class name. For example, this markup: ```html <h1 class="<?php echo wrap(['class' => 'max-w-[16rem]']); ?>">Hello world</h1> ``` generates this CSS: ```css .max-w-\[16rem\]\'\] { max-width: 16rem]' } ``` The string `['class' => 'max-w-[16rem]']` seems to be the issue, specifically the fact that it ends with `]']`. It looks like the JIT engine stops at the **second** `]`, interpreting the arbitrary value for the CSS property to be `16rem]'`. Adding a space before those characters (`['class' => 'max-w-[16rem] ']`) 'fixes' the issue and produces valid CSS.
Hey! This is a tough one β€” what you are seeing there is how we support classes like this: ```html <div class="content-[']']"> ``` https://play.tailwindcss.com/8zudTG6Nal Not sure what the right trade off to make here in ambiguous situations, especially given the constraint that this has to be achievable with a regex to be as universal and simple as possible. Any suggestions on heuristics we can use to determine when yo keep the quote/square bracket and when not to? πŸ€” Oh cool, that makes a lot of sense. I didn't realize `'` was even valid as part of a class name. Are quote characters inside the brackets valid/useful for any utilities _other_ than `content-`? My only suggestion really would be if `content-` is the only thing that needs it, stop at the first matching bracket _except_ right after a `content-`, so that `content-[']']` would work but something like `w-[']']` would just match `w-[']`. Adding that to an existing regex would likely be messy though, and adding an additional separate regex probably isn't a trade off that makes sense (if that's even possible). What are the regexes the JIT engine uses to match class names with dynamic values like this? I looked around and found a couple but none seemed to actually work against `content-[']']`, they stopped at the quotes. I'm curious to see what they're like in case I think of something else. Adding a trailing space for now feels like a more than fair workaround. I'll keep thinking about it but feel free to close this if it's not a priority πŸ‘πŸ» thanks!
"2021-06-26T13:53:19Z"
2.2
[]
[ "tests/jit/extractor-edge-cases.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
5,223
tailwindlabs__tailwindcss-5223
[ "4705" ]
ca6900dc35cedc6410226b4b2e8901852c6f44be
diff --git a/src/plugins/animation.js b/src/plugins/animation.js --- a/src/plugins/animation.js +++ b/src/plugins/animation.js @@ -11,7 +11,6 @@ export default function () { { [`@keyframes ${prefixName(key)}`]: value, }, - { respectVariants: false }, ], ] }) diff --git a/src/util/isKeyframeRule.js b/src/util/isKeyframeRule.js new file mode 100644 --- /dev/null +++ b/src/util/isKeyframeRule.js @@ -0,0 +1,3 @@ +export default function isKeyframeRule(rule) { + return rule.parent && rule.parent.type === 'atrule' && /keyframes$/.test(rule.parent.name) +} diff --git a/src/util/pluginUtils.js b/src/util/pluginUtils.js --- a/src/util/pluginUtils.js +++ b/src/util/pluginUtils.js @@ -3,6 +3,7 @@ import postcss from 'postcss' import createColor from 'color' import escapeCommas from './escapeCommas' import { withAlphaValue } from './withAlphaVariable' +import isKeyframeRule from './isKeyframeRule' export function applyPseudoToMarker(selector, marker, state, join) { let states = [state] @@ -72,6 +73,9 @@ export function updateLastClasses(selectors, updateClass) { export function transformAllSelectors(transformSelector, { wrap, withRule } = {}) { return ({ container }) => { container.walkRules((rule) => { + if (isKeyframeRule(rule)) { + return rule + } let transformed = rule.selector.split(',').map(transformSelector).join(',') rule.selector = transformed if (withRule) { diff --git a/src/util/processPlugins.js b/src/util/processPlugins.js --- a/src/util/processPlugins.js +++ b/src/util/processPlugins.js @@ -10,6 +10,7 @@ import wrapWithVariants from '../util/wrapWithVariants' import cloneNodes from '../util/cloneNodes' import transformThemeValue from './transformThemeValue' import nameClass from '../util/nameClass' +import isKeyframeRule from '../util/isKeyframeRule' function parseStyles(styles) { if (!Array.isArray(styles)) { @@ -28,10 +29,6 @@ function wrapWithLayer(rules, layer) { .append(cloneNodes(Array.isArray(rules) ? rules : [rules])) } -function isKeyframeRule(rule) { - return rule.parent && rule.parent.type === 'atrule' && /keyframes$/.test(rule.parent.name) -} - export default function (plugins, config) { const pluginBaseStyles = [] const pluginComponents = []
diff --git a/tests/jit/animations.test.css b/tests/jit/animations.test.css new file mode 100644 --- /dev/null +++ b/tests/jit/animations.test.css @@ -0,0 +1,32 @@ +@keyframes spin { + to { + transform: rotate(360deg); + } +} +.animate-spin { + animation: spin 1s linear infinite; +} +@keyframes ping { + 75%, + 100% { + transform: scale(2); + opacity: 0; + } +} +.hover\:animate-ping:hover { + animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; +} +@keyframes bounce { + 0%, + 100% { + transform: translateY(-25%); + animation-timing-function: cubic-bezier(0.8, 0, 1, 1); + } + 50% { + transform: none; + animation-timing-function: cubic-bezier(0, 0, 0.2, 1); + } +} +.group:hover .group-hover\:animate-bounce { + animation: bounce 1s infinite; +} diff --git a/tests/jit/animations.test.html b/tests/jit/animations.test.html new file mode 100644 --- /dev/null +++ b/tests/jit/animations.test.html @@ -0,0 +1,3 @@ +<div class="animate-spin"></div> +<div class="hover:animate-ping"></div> +<div class="group-hover:animate-bounce"></div> diff --git a/tests/jit/animations.test.js b/tests/jit/animations.test.js new file mode 100644 --- /dev/null +++ b/tests/jit/animations.test.js @@ -0,0 +1,30 @@ +import postcss from 'postcss' +import fs from 'fs' +import path from 'path' +import tailwind from '../../src/jit/index.js' + +function run(input, config = {}) { + return postcss(tailwind(config)).process(input, { + from: path.resolve(__filename), + }) +} + +test('animations', () => { + let config = { + darkMode: 'class', + mode: 'jit', + purge: [path.resolve(__dirname, './animations.test.html')], + corePlugins: {}, + theme: {}, + plugins: [], + } + + let css = `@tailwind utilities` + + return run(css, config).then((result) => { + let expectedPath = path.resolve(__dirname, './animations.test.css') + let expected = fs.readFileSync(expectedPath, 'utf8') + + expect(result.css).toMatchFormattedCss(expected) + }) +})
group-*:animate-* generates invalid keyframe definition ### What version of Tailwind CSS are you using? v2.2.0 ### What build tool (or framework if it abstracts the build tool) are you using? [email protected], [email protected] ### What version of Node.js are you using? v15.10.0 ### What browser are you using? Chrome ### What operating system are you using? macOS ### Reproduction repository https://play.tailwindcss.com/DrsR2rdrZO ### Describe your issue Adding an animation that should only be applied to group children (e.g. group-focus group-hover) generates invalid keyframes (offsets are missing): ```css @keyframes bounce { , { -webkit-transform: translateY(-25%); transform: translateY(-25%); -webkit-animation-timing-function: cubic-bezier(0.8,0,1,1); animation-timing-function: cubic-bezier(0.8,0,1,1); } { -webkit-transform: none; transform: none; -webkit-animation-timing-function: cubic-bezier(0,0,0.2,1); animation-timing-function: cubic-bezier(0,0,0.2,1); } } .group:focus .group-focus\:animate-bounce { -webkit-animation: bounce 1s infinite; animation: bounce 1s infinite; } ``` expected (taken from non-group animate-* classes): ```css @keyframes bounce { 0%, 100% { -webkit-transform: translateY(-25%); transform: translateY(-25%); -webkit-animation-timing-function: cubic-bezier(0.8,0,1,1); animation-timing-function: cubic-bezier(0.8,0,1,1); } 50% { -webkit-transform: none; transform: none; -webkit-animation-timing-function: cubic-bezier(0,0,0.2,1); animation-timing-function: cubic-bezier(0,0,0.2,1); } } .animate-bounce { -webkit-animation: bounce 1s infinite; animation: bounce 1s infinite; } ```
Found this in my search, I hope it helps: https://github.com/tailwindlabs/play.tailwindcss.com/issues/54 If you downgrade to 2.1.4 it should work again. Yeah it worked before, so definitely a regression. I stepped trough the code a little and it looks like the `{ respectVariants: false }` config gets lost somewhere and is not set in https://github.com/tailwindlabs/tailwindcss/blob/0d47ffd2d38552f3a1ba702f5ff2818da0fb7418/src/jit/lib/generateRules.js#L97 so the value gets handled as if it was a css selector. Also experiencing the same issue, and since downgrading currently isn't an option for me I'd like to see this fixed. My team is currently running into this issue as well. Looking forward to the fix in the next version Also running into this issue, currently downgraded to version `2.1.4` Same problem for me. Same problem for me.
"2021-08-16T14:53:27Z"
2.2
[]
[ "tests/jit/animations.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/DrsR2rdrZO" ]
tailwindlabs/tailwindcss
5,252
tailwindlabs__tailwindcss-5252
[ "5015" ]
d13b0e1085f2e526b8c5b49371b9e1b11d29b472
diff --git a/src/plugins/animation.js b/src/plugins/animation.js --- a/src/plugins/animation.js +++ b/src/plugins/animation.js @@ -19,18 +19,23 @@ export default function () { matchUtilities( { animate: (value, { includeRules }) => { - let { name: animationName } = parseAnimationValue(value) + let animations = parseAnimationValue(value) - if (keyframes[animationName] !== undefined) { - includeRules(keyframes[animationName], { respectImportant: false }) - } - - if (animationName === undefined || keyframes[animationName] === undefined) { - return { animation: value } + for (let { name } of animations) { + if (keyframes[name] !== undefined) { + includeRules(keyframes[name], { respectImportant: false }) + } } return { - animation: value.replace(animationName, prefixName(animationName)), + animation: animations + .map(({ name, value }) => { + if (name === undefined || keyframes[name] === undefined) { + return value + } + return value.replace(name, prefixName(name)) + }) + .join(', '), } }, }, diff --git a/src/util/parseAnimationValue.js b/src/util/parseAnimationValue.js --- a/src/util/parseAnimationValue.js +++ b/src/util/parseAnimationValue.js @@ -20,9 +20,10 @@ const DIGIT = /^(\d+)$/ export default function parseAnimationValue(input) { let animations = input.split(COMMA) - let result = animations.map((animation) => { - let result = {} - let parts = animation.trim().split(SPACE) + return animations.map((animation) => { + let value = animation.trim() + let result = { value } + let parts = value.split(SPACE) let seen = new Set() for (let part of parts) { @@ -58,6 +59,4 @@ export default function parseAnimationValue(input) { return result }) - - return animations.length > 1 ? result : result[0] }
diff --git a/tests/jit/animations.test.css b/tests/jit/animations.test.css deleted file mode 100644 --- a/tests/jit/animations.test.css +++ /dev/null @@ -1,32 +0,0 @@ -@keyframes spin { - to { - transform: rotate(360deg); - } -} -.animate-spin { - animation: spin 1s linear infinite; -} -@keyframes ping { - 75%, - 100% { - transform: scale(2); - opacity: 0; - } -} -.hover\:animate-ping:hover { - animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; -} -@keyframes bounce { - 0%, - 100% { - transform: translateY(-25%); - animation-timing-function: cubic-bezier(0.8, 0, 1, 1); - } - 50% { - transform: none; - animation-timing-function: cubic-bezier(0, 0, 0.2, 1); - } -} -.group:hover .group-hover\:animate-bounce { - animation: bounce 1s infinite; -} diff --git a/tests/jit/animations.test.html b/tests/jit/animations.test.html deleted file mode 100644 --- a/tests/jit/animations.test.html +++ /dev/null @@ -1,3 +0,0 @@ -<div class="animate-spin"></div> -<div class="hover:animate-ping"></div> -<div class="group-hover:animate-bounce"></div> diff --git a/tests/jit/animations.test.js b/tests/jit/animations.test.js --- a/tests/jit/animations.test.js +++ b/tests/jit/animations.test.js @@ -1,5 +1,4 @@ import postcss from 'postcss' -import fs from 'fs' import path from 'path' import tailwind from '../../src/jit/index.js' @@ -9,22 +8,199 @@ function run(input, config = {}) { }) } -test('animations', () => { +test('basic', () => { let config = { - darkMode: 'class', mode: 'jit', - purge: [path.resolve(__dirname, './animations.test.html')], - corePlugins: {}, - theme: {}, - plugins: [], + purge: [ + { + raw: ` + <div class="animate-spin"></div> + <div class="hover:animate-ping"></div> + <div class="group-hover:animate-bounce"></div> + `, + }, + ], } let css = `@tailwind utilities` return run(css, config).then((result) => { - let expectedPath = path.resolve(__dirname, './animations.test.css') - let expected = fs.readFileSync(expectedPath, 'utf8') + expect(result.css).toMatchFormattedCss(` + @keyframes spin { + to { + transform: rotate(360deg); + } + } + .animate-spin { + animation: spin 1s linear infinite; + } + @keyframes ping { + 75%, + 100% { + transform: scale(2); + opacity: 0; + } + } + .hover\\:animate-ping:hover { + animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; + } + @keyframes bounce { + 0%, + 100% { + transform: translateY(-25%); + animation-timing-function: cubic-bezier(0.8, 0, 1, 1); + } + 50% { + transform: none; + animation-timing-function: cubic-bezier(0, 0, 0.2, 1); + } + } + .group:hover .group-hover\\:animate-bounce { + animation: bounce 1s infinite; + } + `) + }) +}) + +test('custom', () => { + let config = { + mode: 'jit', + purge: [{ raw: `<div class="animate-one"></div>` }], + theme: { + extend: { + keyframes: { + one: { to: { transform: 'rotate(360deg)' } }, + }, + animation: { + one: 'one 2s', + }, + }, + }, + } + + let css = `@tailwind utilities` + + return run(css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + @keyframes one { + to { + transform: rotate(360deg); + } + } + .animate-one { + animation: one 2s; + } + `) + }) +}) + +test('custom prefixed', () => { + let config = { + mode: 'jit', + prefix: 'tw-', + purge: [{ raw: `<div class="tw-animate-one"></div>` }], + theme: { + extend: { + keyframes: { + one: { to: { transform: 'rotate(360deg)' } }, + }, + animation: { + one: 'one 2s', + }, + }, + }, + } + + let css = `@tailwind utilities` - expect(result.css).toMatchFormattedCss(expected) + return run(css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + @keyframes tw-one { + to { + transform: rotate(360deg); + } + } + .tw-animate-one { + animation: tw-one 2s; + } + `) + }) +}) + +test('multiple', () => { + let config = { + mode: 'jit', + purge: [{ raw: `<div class="animate-multiple"></div>` }], + theme: { + extend: { + animation: { + multiple: 'bounce 2s linear, pulse 3s ease-in', + }, + }, + }, + } + + let css = `@tailwind utilities` + + return run(css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + @keyframes bounce { + 0%, + 100% { + transform: translateY(-25%); + animation-timing-function: cubic-bezier(0.8, 0, 1, 1); + } + 50% { + transform: none; + animation-timing-function: cubic-bezier(0, 0, 0.2, 1); + } + } + @keyframes pulse { + 50% { + opacity: 0.5; + } + } + .animate-multiple { + animation: bounce 2s linear, pulse 3s ease-in; + } + `) + }) +}) + +test('multiple custom', () => { + let config = { + mode: 'jit', + purge: [{ raw: `<div class="animate-multiple"></div>` }], + theme: { + extend: { + keyframes: { + one: { to: { transform: 'rotate(360deg)' } }, + two: { to: { transform: 'scale(1.23)' } }, + }, + animation: { + multiple: 'one 2s, two 3s', + }, + }, + }, + } + + let css = `@tailwind utilities` + + return run(css, config).then((result) => { + expect(result.css).toMatchFormattedCss(` + @keyframes one { + to { + transform: rotate(360deg); + } + } + @keyframes two { + to { + transform: scale(1.23); + } + } + .animate-multiple { + animation: one 2s, two 3s; + } + `) }) }) diff --git a/tests/parseAnimationValue.test.js b/tests/parseAnimationValue.test.js --- a/tests/parseAnimationValue.test.js +++ b/tests/parseAnimationValue.test.js @@ -5,6 +5,7 @@ describe('Tailwind Defaults', () => { [ 'spin 1s linear infinite', { + value: 'spin 1s linear infinite', name: 'spin', duration: '1s', timingFunction: 'linear', @@ -14,15 +15,26 @@ describe('Tailwind Defaults', () => { [ 'ping 1s cubic-bezier(0, 0, 0.2, 1) infinite', { + value: 'ping 1s cubic-bezier(0, 0, 0.2, 1) infinite', name: 'ping', duration: '1s', timingFunction: 'cubic-bezier(0, 0, 0.2, 1)', iterationCount: 'infinite', }, ], - ['bounce 1s infinite', { name: 'bounce', duration: '1s', iterationCount: 'infinite' }], + [ + 'bounce 1s infinite', + { + value: 'bounce 1s infinite', + name: 'bounce', + duration: '1s', + iterationCount: 'infinite', + }, + ], ])('should be possible to parse: "%s"', (input, expected) => { - expect(parseAnimationValue(input)).toEqual(expected) + const parsed = parseAnimationValue(input) + expect(parsed).toHaveLength(1) + expect(parsed[0]).toEqual(expected) }) }) @@ -31,6 +43,7 @@ describe('MDN Examples', () => { [ '3s ease-in 1s 2 reverse both paused slidein', { + value: '3s ease-in 1s 2 reverse both paused slidein', delay: '1s', direction: 'reverse', duration: '3s', @@ -44,15 +57,18 @@ describe('MDN Examples', () => { [ 'slidein 3s linear 1s', { + value: 'slidein 3s linear 1s', delay: '1s', duration: '3s', name: 'slidein', timingFunction: 'linear', }, ], - ['slidein 3s', { duration: '3s', name: 'slidein' }], + ['slidein 3s', { value: 'slidein 3s', duration: '3s', name: 'slidein' }], ])('should be possible to parse: "%s"', (input, expected) => { - expect(parseAnimationValue(input)).toEqual(expected) + const parsed = parseAnimationValue(input) + expect(parsed).toHaveLength(1) + expect(parsed[0]).toEqual(expected) }) }) @@ -83,8 +99,9 @@ describe('duration & delay', () => { ['spin -200.321ms -100.321ms linear', { duration: '-200.321ms', delay: '-100.321ms' }], ])('should be possible to parse "%s" into %o', (input, { duration, delay }) => { const parsed = parseAnimationValue(input) - expect(parsed.duration).toEqual(duration) - expect(parsed.delay).toEqual(delay) + expect(parsed).toHaveLength(1) + expect(parsed[0].duration).toEqual(duration) + expect(parsed[0].delay).toEqual(delay) }) }) @@ -106,7 +123,9 @@ describe('iteration count', () => { ])( 'should be possible to parse "%s" with an iteraction count of "%s"', (input, iterationCount) => { - expect(parseAnimationValue(input).iterationCount).toEqual(iterationCount) + const parsed = parseAnimationValue(input) + expect(parsed).toHaveLength(1) + expect(parsed[0].iterationCount).toEqual(iterationCount) } ) }) @@ -123,18 +142,21 @@ describe('multiple animations', () => { expect(parsed).toHaveLength(3) expect(parsed).toEqual([ { + value: 'spin 1s linear infinite', name: 'spin', duration: '1s', timingFunction: 'linear', iterationCount: 'infinite', }, { + value: 'ping 1s cubic-bezier(0, 0, 0.2, 1) infinite', name: 'ping', duration: '1s', timingFunction: 'cubic-bezier(0, 0, 0.2, 1)', iterationCount: 'infinite', }, { + value: 'pulse 2s cubic-bezier(0.4, 0, 0.6) infinite', name: 'pulse', duration: '2s', timingFunction: 'cubic-bezier(0.4, 0, 0.6)', @@ -145,20 +167,21 @@ describe('multiple animations', () => { }) it.each` - input | direction | playState | fillMode | iterationCount | timingFunction | duration | delay | name - ${'1s spin 1s infinite'} | ${undefined} | ${undefined} | ${undefined} | ${'infinite'} | ${undefined} | ${'1s'} | ${'1s'} | ${'spin'} - ${'infinite infinite 1s 1s'} | ${undefined} | ${undefined} | ${undefined} | ${'infinite'} | ${undefined} | ${'1s'} | ${'1s'} | ${'infinite'} - ${'ease 1s ease 1s'} | ${undefined} | ${undefined} | ${undefined} | ${undefined} | ${'ease'} | ${'1s'} | ${'1s'} | ${'ease'} - ${'normal paused backwards infinite ease-in 1s 2s name'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} - ${'paused backwards infinite ease-in 1s 2s name normal'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} - ${'backwards infinite ease-in 1s 2s name normal paused'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} - ${'infinite ease-in 1s 2s name normal paused backwards'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} - ${'ease-in 1s 2s name normal paused backwards infinite'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} - ${'1s 2s name normal paused backwards infinite ease-in'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} - ${'2s name normal paused backwards infinite ease-in 1s'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'2s'} | ${'1s'} | ${'name'} - ${'name normal paused backwards infinite ease-in 1s 2s'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} - ${' name normal paused backwards infinite ease-in 1s 2s '} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + input | value | direction | playState | fillMode | iterationCount | timingFunction | duration | delay | name + ${'1s spin 1s infinite'} | ${'1s spin 1s infinite'} | ${undefined} | ${undefined} | ${undefined} | ${'infinite'} | ${undefined} | ${'1s'} | ${'1s'} | ${'spin'} + ${'infinite infinite 1s 1s'} | ${'infinite infinite 1s 1s'} | ${undefined} | ${undefined} | ${undefined} | ${'infinite'} | ${undefined} | ${'1s'} | ${'1s'} | ${'infinite'} + ${'ease 1s ease 1s'} | ${'ease 1s ease 1s'} | ${undefined} | ${undefined} | ${undefined} | ${undefined} | ${'ease'} | ${'1s'} | ${'1s'} | ${'ease'} + ${'normal paused backwards infinite ease-in 1s 2s name'} | ${'normal paused backwards infinite ease-in 1s 2s name'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + ${'paused backwards infinite ease-in 1s 2s name normal'} | ${'paused backwards infinite ease-in 1s 2s name normal'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + ${'backwards infinite ease-in 1s 2s name normal paused'} | ${'backwards infinite ease-in 1s 2s name normal paused'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + ${'infinite ease-in 1s 2s name normal paused backwards'} | ${'infinite ease-in 1s 2s name normal paused backwards'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + ${'ease-in 1s 2s name normal paused backwards infinite'} | ${'ease-in 1s 2s name normal paused backwards infinite'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + ${'1s 2s name normal paused backwards infinite ease-in'} | ${'1s 2s name normal paused backwards infinite ease-in'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + ${'2s name normal paused backwards infinite ease-in 1s'} | ${'2s name normal paused backwards infinite ease-in 1s'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'2s'} | ${'1s'} | ${'name'} + ${'name normal paused backwards infinite ease-in 1s 2s'} | ${'name normal paused backwards infinite ease-in 1s 2s'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} + ${' name normal paused backwards infinite ease-in 1s 2s '} | ${'name normal paused backwards infinite ease-in 1s 2s'} | ${'normal'} | ${'paused'} | ${'backwards'} | ${'infinite'} | ${'ease-in'} | ${'1s'} | ${'2s'} | ${'name'} `('should parse "$input" correctly', ({ input, ...expected }) => { let parsed = parseAnimationValue(input) - expect(parsed).toEqual(expected) + expect(parsed).toHaveLength(1) + expect(parsed[0]).toEqual(expected) })
Custom animations with more than 1 animation separeted by commas dont work ### What version of Tailwind CSS are you using? v2.2.4 ### What build tool (or framework if it abstracts the build tool) are you using? Next.js 11.0.1 ### What version of Node.js are you using? v16.4.2 ### What browser are you using? Chrome ### What operating system are you using? Windows ### Reproduction repository https://play.tailwindcss.com/si3enE3TvA ### Describe your issue On `tailwind.config.js` ```js theme: { extend: { animation: { issue: 'animation1, animation2', } } } ``` adding multiple animations makes the keyframes disappear from the styled component which makes the animation not work
Relevant codepen with expected result https://codepen.io/timber1900/pen/rNmwEvq?editors=1100 @Timber1900 Sounds like same problem as mine #4711. Combined animations are not being processed ( intentionally ? ) due to which keyframes are ignored. I tried #4802 but closed due to inaction. Defining animation along with keyframes in CSS should work for now. I had a mistake in my reproduction repository and while I could have sworn it wasn't working when I created the issue as I was testing in another Tailwind Play it appears to now be working https://play.tailwindcss.com/5t0tNwzics I'll be closing this issue as the problem appears to have fixed itself. I'm reopening this issue because I found managed to reproduce the issue, - Removing the animations of the other divs com the `tailwind.config.js` removes the keyframes from the css causing the animation to not work https://play.tailwindcss.com/mFR8PkYYKO?file=config - But if we include them it now works https://play.tailwindcss.com/gso8V7sBOc?file=config Therefore the issue is with tailwind not including the keyframes in the compiled css when the only animation using said keyframes includes multiple animations I'm seeing this issue too, keyframes are ignored when a `,` is used in the animation. Temporary workaround is to create `animation-1` and `animation-2` for `keyframes-1` and `keyframes-2` respectively (as opposed to `animation: keyframes-1, keyframes-2`), and then add those animation classes to the safelist.
"2021-08-18T17:19:07Z"
2.2
[]
[ "tests/parseAnimationValue.test.js", "tests/jit/animations.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/si3enE3TvA" ]
tailwindlabs/tailwindcss
5,470
tailwindlabs__tailwindcss-5470
[ "5458" ]
30badadd211594ccc83c686e3f4c1f06a7e107c9
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -1014,7 +1014,11 @@ export let divideColor = ({ matchUtilities, theme, corePlugins }) => { { divide: (value) => { if (!corePlugins('divideOpacity')) { - return { ['& > :not([hidden]) ~ :not([hidden])']: { 'border-color': value } } + return { + ['& > :not([hidden]) ~ :not([hidden])']: { + 'border-color': toColorValue(value), + }, + } } return { @@ -1174,9 +1178,10 @@ export let borderStyle = ({ addUtilities }) => { export let borderColor = ({ addBase, matchUtilities, theme, corePlugins }) => { if (!corePlugins('borderOpacity')) { + let value = theme('borderColor.DEFAULT', 'currentColor') addBase({ '@defaults border-width': { - 'border-color': theme('borderColor.DEFAULT', 'currentColor'), + 'border-color': toColorValue(value), }, }) } else { @@ -1193,7 +1198,9 @@ export let borderColor = ({ addBase, matchUtilities, theme, corePlugins }) => { { border: (value) => { if (!corePlugins('borderOpacity')) { - return { 'border-color': value } + return { + 'border-color': toColorValue(value), + } } return withAlphaVariable({ @@ -1213,7 +1220,9 @@ export let borderColor = ({ addBase, matchUtilities, theme, corePlugins }) => { { 'border-t': (value) => { if (!corePlugins('borderOpacity')) { - return { 'border-top-color': value } + return { + 'border-top-color': toColorValue(value), + } } return withAlphaVariable({ @@ -1224,7 +1233,9 @@ export let borderColor = ({ addBase, matchUtilities, theme, corePlugins }) => { }, 'border-r': (value) => { if (!corePlugins('borderOpacity')) { - return { 'border-right-color': value } + return { + 'border-right-color': toColorValue(value), + } } return withAlphaVariable({ @@ -1235,7 +1246,9 @@ export let borderColor = ({ addBase, matchUtilities, theme, corePlugins }) => { }, 'border-b': (value) => { if (!corePlugins('borderOpacity')) { - return { 'border-bottom-color': value } + return { + 'border-bottom-color': toColorValue(value), + } } return withAlphaVariable({ @@ -1246,7 +1259,9 @@ export let borderColor = ({ addBase, matchUtilities, theme, corePlugins }) => { }, 'border-l': (value) => { if (!corePlugins('borderOpacity')) { - return { 'border-left-color': value } + return { + 'border-left-color': toColorValue(value), + } } return withAlphaVariable({ @@ -1272,7 +1287,9 @@ export let backgroundColor = ({ matchUtilities, theme, corePlugins }) => { { bg: (value) => { if (!corePlugins('backgroundOpacity')) { - return { 'background-color': value } + return { + 'background-color': toColorValue(value), + } } return withAlphaVariable({ @@ -1539,7 +1556,7 @@ export let textColor = ({ matchUtilities, theme, corePlugins }) => { { text: (value) => { if (!corePlugins('textOpacity')) { - return { color: value } + return { color: toColorValue(value) } } return withAlphaVariable({ @@ -1583,7 +1600,11 @@ export let placeholderColor = ({ matchUtilities, theme, corePlugins }) => { { placeholder: (value) => { if (!corePlugins('placeholderOpacity')) { - return { '&::placeholder': { color: value } } + return { + '&::placeholder': { + color: toColorValue(value), + }, + } } return {
diff --git a/tests/opacity.test.css b/tests/opacity.test.css deleted file mode 100644 --- a/tests/opacity.test.css +++ /dev/null @@ -1,15 +0,0 @@ -.divide-black > :not([hidden]) ~ :not([hidden]) { - border-color: #000; -} -.border-black { - border-color: #000; -} -.bg-black { - background-color: #000; -} -.text-black { - color: #000; -} -.placeholder-black::placeholder { - color: #000; -} diff --git a/tests/opacity.test.html b/tests/opacity.test.html deleted file mode 100644 --- a/tests/opacity.test.html +++ /dev/null @@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="UTF-8" /> - <link rel="icon" href="/favicon.ico" /> - <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <title>Title</title> - <link rel="stylesheet" href="./tailwind.css" /> - </head> - <body> - <div class="divide-black"></div> - <div class="border-black"></div> - <div class="bg-black"></div> - <div class="text-black"></div> - <div class="placeholder-black"></div> - </body> -</html> diff --git a/tests/opacity.test.js b/tests/opacity.test.js --- a/tests/opacity.test.js +++ b/tests/opacity.test.js @@ -1,12 +1,19 @@ -import fs from 'fs' -import path from 'path' - -import { run } from './util/run' +import { run, html, css } from './util/run' test('opacity', () => { let config = { darkMode: 'class', - content: [path.resolve(__dirname, './opacity.test.html')], + content: [ + { + raw: html` + <div class="divide-black"></div> + <div class="border-black"></div> + <div class="bg-black"></div> + <div class="text-black"></div> + <div class="placeholder-black"></div> + `, + }, + ], corePlugins: { backgroundOpacity: false, borderOpacity: false, @@ -17,9 +24,74 @@ test('opacity', () => { } return run('@tailwind utilities', config).then((result) => { - let expectedPath = path.resolve(__dirname, './opacity.test.css') - let expected = fs.readFileSync(expectedPath, 'utf8') + expect(result.css).toMatchCss(css` + .divide-black > :not([hidden]) ~ :not([hidden]) { + border-color: #000; + } + .border-black { + border-color: #000; + } + .bg-black { + background-color: #000; + } + .text-black { + color: #000; + } + .placeholder-black::placeholder { + color: #000; + } + `) + }) +}) + +test('colors defined as functions work when opacity plugins are disabled', () => { + let config = { + darkMode: 'class', + content: [ + { + raw: html` + <div class="divide-primary"></div> + <div class="border-primary"></div> + <div class="bg-primary"></div> + <div class="text-primary"></div> + <div class="placeholder-primary"></div> + `, + }, + ], + theme: { + colors: { + primary: ({ opacityValue }) => + opacityValue === undefined + ? 'rgb(var(--color-primary))' + : `rgb(var(--color-primary) / ${opacityValue})`, + }, + }, + corePlugins: { + backgroundOpacity: false, + borderOpacity: false, + divideOpacity: false, + placeholderOpacity: false, + textOpacity: false, + }, + } - expect(result.css).toMatchCss(expected) + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchCss(css` + .divide-primary > :not([hidden]) ~ :not([hidden]) { + border-color: rgb(var(--color-primary)); + } + .border-primary { + border-color: rgb(var(--color-primary)); + } + .bg-primary { + background-color: rgb(var(--color-primary)); + } + .text-primary { + color: rgb(var(--color-primary)); + } + .placeholder-primary::placeholder { + color: rgb(var(--color-primary)); + } + `) }) })
Disabling an opacity plugin breaks support for custom property colors ### What version of Tailwind CSS are you using? 2.2.7 ### What build tool (or framework if it abstracts the build tool) are you using? Tailwind Play ### What version of Node.js are you using? n/a ### What browser are you using? n/a ### What operating system are you using? n/a ### Reproduction repository https://play.tailwindcss.com/YVjDQE13bj ### Describe your issue Colors defined by a function as described in https://github.com/adamwathan/tailwind-css-variable-text-opacity-demo break for plugins where the associated opacity plugin is disabled. This is caused by the plugins not calling `withAlphaVariable()` when opacity plugins are disabled: https://github.com/tailwindlabs/tailwindcss/blob/691ed02f6352da17048dd14f742f7c82919e1455/src/plugins/backgroundColor.js#L11. Since the function This behaviour makes it impossible to selectively disable opacity plugins when using colors defined via functions. Since the example repo shows how the function is expected to support the case where neither `opacityVariable` nor `opacityValue` are provided, I would expect it to work.
A workaround is to provide an empty theme instead of disabling the opacity plugin, for example `backgroundOpacity: {}`.
"2021-09-10T13:28:31Z"
2.2
[]
[ "tests/opacity.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/YVjDQE13bj" ]
tailwindlabs/tailwindcss
5,830
tailwindlabs__tailwindcss-5830
[ "5806" ]
0c2f1a64727d8f2c5fbc8425001aaf47940cf5a2
diff --git a/src/lib/collapseDuplicateDeclarations.js b/src/lib/collapseDuplicateDeclarations.js new file mode 100644 --- /dev/null +++ b/src/lib/collapseDuplicateDeclarations.js @@ -0,0 +1,28 @@ +export default function collapseDuplicateDeclarations() { + return (root) => { + root.walkRules((node) => { + let seen = new Map() + let droppable = new Set([]) + + node.walkDecls((decl) => { + // This could happen if we have nested selectors. In that case the + // parent will loop over all its declarations but also the declarations + // of nested rules. With this we ensure that we are shallowly checking + // declarations. + if (decl.parent !== node) { + return + } + + if (seen.has(decl.prop)) { + droppable.add(seen.get(decl.prop)) + } + + seen.set(decl.prop, decl) + }) + + for (let decl of droppable) { + decl.remove() + } + }) + } +} diff --git a/src/processTailwindFeatures.js b/src/processTailwindFeatures.js --- a/src/processTailwindFeatures.js +++ b/src/processTailwindFeatures.js @@ -5,6 +5,7 @@ import evaluateTailwindFunctions from './lib/evaluateTailwindFunctions' import substituteScreenAtRules from './lib/substituteScreenAtRules' import resolveDefaultsAtRules from './lib/resolveDefaultsAtRules' import collapseAdjacentRules from './lib/collapseAdjacentRules' +import collapseDuplicateDeclarations from './lib/collapseDuplicateDeclarations' import detectNesting from './lib/detectNesting' import { createContext } from './lib/setupContextUtils' import { issueFlagNotices } from './featureFlags' @@ -42,5 +43,6 @@ export default function processTailwindFeatures(setupContext) { substituteScreenAtRules(context)(root, result) resolveDefaultsAtRules(context)(root, result) collapseAdjacentRules(context)(root, result) + collapseDuplicateDeclarations(context)(root, result) } }
diff --git a/tests/apply.test.css b/tests/apply.test.css --- a/tests/apply.test.css +++ b/tests/apply.test.css @@ -10,8 +10,6 @@ .class-order { padding: 2rem; padding-left: 0.75rem; - padding-right: 0.75rem; - padding-top: 1.75rem; padding-bottom: 1.75rem; padding-top: 1rem; padding-right: 0.25rem; @@ -127,7 +125,6 @@ /* TODO: This works but the generated CSS is unnecessarily verbose. */ .complex-utilities { --tw-ordinal: ordinal; - font-variant-numeric: var(--tw-font-variant-numeric); --tw-numeric-spacing: tabular-nums; font-variant-numeric: var(--tw-font-variant-numeric); --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -2px rgb(0 0 0 / 0.05); @@ -155,7 +152,6 @@ font-weight: 700; } .use-dependant-only-b { - font-weight: 700; font-weight: 400; } .btn { diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -351,7 +351,6 @@ test('@applying classes from outside a @layer respects the source order', async await run(input, config).then((result) => { return expect(result.css).toMatchFormattedCss(css` .baz { - text-decoration: underline; text-decoration: none; } @@ -402,3 +401,30 @@ test('@applying classes from outside a @layer respects the source order', async `) }) }) + +it('should remove duplicate properties when using apply with similar properties', () => { + let config = { + content: [{ raw: 'foo' }], + } + + let input = css` + @tailwind utilities; + + .foo { + @apply absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2; + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .foo { + position: absolute; + top: 50%; + left: 50%; + --tw-translate-x: -50%; + --tw-translate-y: -50%; + transform: var(--tw-transform); + } + `) + }) +}) diff --git a/tests/custom-plugins.test.js b/tests/custom-plugins.test.js --- a/tests/custom-plugins.test.js +++ b/tests/custom-plugins.test.js @@ -868,7 +868,6 @@ test('when important is a selector it scopes all selectors in a rule, even thoug #app .custom-rotate-90, #app .custom-rotate-1\/4 { transform: rotate(90deg); - transform: rotate(90deg); } `) }) @@ -952,7 +951,6 @@ test('all selectors in a rule are prefixed', () => { .tw-btn-blue, .tw-btn-red { padding: 10px; - padding: 10px; } `) }) diff --git a/tests/kitchen-sink.test.css b/tests/kitchen-sink.test.css --- a/tests/kitchen-sink.test.css +++ b/tests/kitchen-sink.test.css @@ -199,7 +199,6 @@ div { } .test-apply-font-variant { --tw-ordinal: ordinal; - font-variant-numeric: var(--tw-font-variant-numeric); --tw-numeric-spacing: tabular-nums; font-variant-numeric: var(--tw-font-variant-numeric); }
[JIT] apply: duplicate transform properties **What version of Tailwind CSS are you using?** 2.2.15 (also tested with 3.0.0-alpha.1 and 2.2.17) **Reproduction URL** https://play.tailwindcss.com/KkuBVniu30?file=css **Describe your issue** Using multiple transform-based properties (like translate-x and translate-y) results in duplicated `transform` property, eg ```css .absolute-center { @apply absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2; } ``` Generates: ```css .absolute-center { position: absolute; top: 50%; left: 50%; --tw-translate-x: -50%; transform: var(--tw-transform); --tw-translate-y: -50%; transform: var(--tw-transform); transform: var(--tw-transform); } ```
"2021-10-19T14:52:47Z"
3.0
[]
[ "tests/apply.test.js", "tests/custom-plugins.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/KkuBVniu30?file=css" ]
tailwindlabs/tailwindcss
5,854
tailwindlabs__tailwindcss-5854
[ "5851" ]
0ab39c312ab789d9a7ac47262b2829c08497ee1f
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -448,28 +448,42 @@ function generateRules(candidates, context) { allRules.push(matches) } - return allRules.flat(1).map(([{ sort, layer, options }, rule]) => { - if (options.respectImportant) { - if (context.tailwindConfig.important === true) { + // Strategy based on `tailwindConfig.important` + let strategy = ((important) => { + if (important === true) { + return (rule) => { rule.walkDecls((d) => { if (d.parent.type === 'rule' && !inKeyframes(d.parent)) { d.important = true } }) - } else if (typeof context.tailwindConfig.important === 'string') { + } + } + + if (typeof important === 'string') { + return (rule) => { + rule.selectors = rule.selectors.map((selector) => { + return `${important} ${selector}` + }) + } + } + })(context.tailwindConfig.important) + + return allRules.flat(1).map(([{ sort, layer, options }, rule]) => { + if (options.respectImportant) { + if (strategy) { let container = postcss.root({ nodes: [rule.clone()] }) container.walkRules((r) => { if (inKeyframes(r)) { return } - r.selectors = r.selectors.map((selector) => { - return `${context.tailwindConfig.important} ${selector}` - }) + strategy(r) }) rule = container.nodes[0] } } + return [sort | context.layerOrder[layer], rule] }) }
diff --git a/tests/layer-at-rules.test.js b/tests/layer-at-rules.test.js --- a/tests/layer-at-rules.test.js +++ b/tests/layer-at-rules.test.js @@ -50,6 +50,125 @@ test('custom user-land utilities', () => { }) }) +test('comments can be used inside layers without crashing', () => { + let config = { + content: [ + { + raw: html`<div class="important-utility important-component"></div>`, + }, + ], + corePlugins: { preflight: false }, + theme: {}, + plugins: [], + } + + let input = css` + @tailwind base; + @tailwind components; + @tailwind utilities; + + @layer base { + /* Important base */ + div { + background-color: #bada55; + } + } + + @layer utilities { + /* Important utility */ + .important-utility { + text-align: banana; + } + } + + @layer components { + /* Important component */ + .important-component { + text-align: banana; + } + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + /* Important base */ + div { + background-color: #bada55; + } + + /* Important component */ + .important-component { + text-align: banana; + } + + /* Important utility */ + .important-utility { + text-align: banana; + } + `) + }) +}) + +test('comments can be used inside layers (with important) without crashing', () => { + let config = { + important: true, + content: [ + { + raw: html`<div class="important-utility important-component"></div>`, + }, + ], + corePlugins: { preflight: false }, + theme: {}, + plugins: [], + } + + let input = css` + @tailwind base; + @tailwind components; + @tailwind utilities; + + @layer base { + /* Important base */ + div { + background-color: #bada55; + } + } + + @layer utilities { + /* Important utility */ + .important-utility { + text-align: banana; + } + } + + @layer components { + /* Important component */ + .important-component { + text-align: banana; + } + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + /* Important base */ + div { + background-color: #bada55; + } + + /* Important component */ + .important-component { + text-align: banana; + } + + /* Important utility */ + .important-utility { + text-align: banana !important; + } + `) + }) +}) + test('layers are grouped and inserted at the matching @tailwind rule', () => { let config = { content: [
Jit crash with comment in `@layer utilities` **What version of Tailwind CSS are you using?** v2.2.17 **What build tool (or framework if it abstracts the build tool) are you using?** Vite 2.6.7 **What version of Node.js are you using?** For example: v16.11.0 **What browser are you using?** N/A **What operating system are you using?** macOS **Reproduction URL** N/A **Describe your issue** With the following `tailwind.css` file, Jit mode crashes because of the "hello" comment: ```css @tailwind base; @tailwind components; @tailwind utilities; @layer utilities { /* hello */ .test { color: red; } } ``` It is important to reproduce the crash that the comment be inside the `@layer utilities` block, just before a selector. Stack trace: ``` rule.walkDecls is not a function at /Users/targos/test/node_modules/tailwindcss/lib/jit/lib/generateRules.js:338:14 at Array.map (<anonymous>) at generateRules (/Users/targos/test/node_modules/tailwindcss/lib/jit/lib/generateRules.js:330:27) at /Users/targos/test/node_modules/tailwindcss/lib/jit/lib/expandTailwindAtRules.js:186:50 at /Users/targos/test/node_modules/tailwindcss/lib/jit/processTailwindFeatures.js:60:49 at /Users/targos/test/node_modules/tailwindcss/lib/jit/index.js:25:56 at LazyResult.runOnRoot (/Users/targos/test/node_modules/postcss/lib/lazy-result.js:339:16) at LazyResult.runAsync (/Users/targos/test/node_modules/postcss/lib/lazy-result.js:391:26) at LazyResult.async (/Users/targos/test/node_modules/postcss/lib/lazy-result.js:221:30) at LazyResult.then (/Users/targos/test/node_modules/postcss/lib/lazy-result.js:206:17) (x3) ```
Hey! Thank you for your bug report! Much appreciated! πŸ™ I can't reproduce it with this setup, but can you share your full tailwind.config.js? I can reproduce it when I have `important: true`, but I want to verify that you have this as well. Oh, sorry I forgot to put the config I used. Indeed, we have `important: true`: It can be reproduced with: ```js module.exports = { mode: 'jit', important: true, purge: ['./src/**/*.{js,ts,jsx,tsx}', './index.html'], darkMode: false, }; ```
"2021-10-22T13:13:27Z"
3.0
[]
[ "tests/layer-at-rules.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
6,369
tailwindlabs__tailwindcss-6369
[ "6360" ]
08241c3f7547e5e5c86e2de312add172fb9d5da8
diff --git a/src/lib/resolveDefaultsAtRules.js b/src/lib/resolveDefaultsAtRules.js --- a/src/lib/resolveDefaultsAtRules.js +++ b/src/lib/resolveDefaultsAtRules.js @@ -71,6 +71,8 @@ function extractElementSelector(selector) { export default function resolveDefaultsAtRules({ tailwindConfig }) { return (root) => { let variableNodeMap = new Map() + + /** @type {Set<import('postcss').AtRule>} */ let universals = new Set() root.walkAtRules('defaults', (rule) => { @@ -90,31 +92,50 @@ export default function resolveDefaultsAtRules({ tailwindConfig }) { }) for (let universal of universals) { - let selectors = new Set() + /** @type {Map<string, Set<string>>} */ + let selectorGroups = new Map() let rules = variableNodeMap.get(universal.params) ?? [] for (let rule of rules) { for (let selector of extractElementSelector(rule.selector)) { + // If selector contains a vendor prefix after a pseudo element or class, + // we consider them separately because merging the declarations into + // a single rule will cause browsers that do not understand the + // vendor prefix to throw out the whole rule + let selectorGroupName = + selector.includes(':-') || selector.includes('::-') ? selector : '__DEFAULT__' + + let selectors = selectorGroups.get(selectorGroupName) ?? new Set() + selectorGroups.set(selectorGroupName, selectors) + selectors.add(selector) } } - if (selectors.size === 0) { + if (selectorGroups.size === 0) { universal.remove() continue } - let universalRule = postcss.rule() - if (flagEnabled(tailwindConfig, 'optimizeUniversalDefaults')) { - universalRule.selectors = [...selectors] + for (let [, selectors] of selectorGroups) { + let universalRule = postcss.rule() + + universalRule.selectors = [...selectors] + + universalRule.append(universal.nodes.map((node) => node.clone())) + universal.before(universalRule) + } } else { + let universalRule = postcss.rule() + universalRule.selectors = ['*', '::before', '::after'] + + universalRule.append(universal.nodes) + universal.before(universalRule) } - universalRule.append(universal.nodes) - universal.before(universalRule) universal.remove() } }
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -577,3 +577,42 @@ it('should throw when trying to apply an indirect circular dependency with a mod expect(err.reason).toBe('Circular dependency detected when using: `@apply a`') }) }) + +it('rules with vendor prefixes are still separate when optimizing defaults rules', () => { + let config = { + experimental: { optimizeUniversalDefaults: true }, + content: [{ raw: html`<div class="border"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind base; + @tailwind components; + @tailwind utilities; + + @layer components { + input[type='range']::-moz-range-thumb { + @apply border; + } + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + [type='range']::-moz-range-thumb { + --tw-border-opacity: 1; + border-color: rgb(229 231 235 / var(--tw-border-opacity)); + } + .border { + --tw-border-opacity: 1; + border-color: rgb(229 231 235 / var(--tw-border-opacity)); + } + input[type='range']::-moz-range-thumb { + border-width: 1px; + } + .border { + border-width: 1px; + } + `) + }) +})
Vendor prefix can break the generated css <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.0.0 **What build tool (or framework if it abstracts the build tool) are you using?** webpack 5.60.0 and play.tailwind.com **What version of Node.js are you using?** v16.13.0 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** Try this in any browser except firefox: https://play.tailwindcss.com/YkD75GMXHs?file=css **Describe your issue** If I @apply border class inside my custom CSS, and it just happens to be a vendor-prefixed, and the current browser doesn't support it then that invalidates all the CSS after that vendor-prefix. Any vendor-prefixed classes will need to be separated into their own blocks and not merged in the comma-separated list. This does happen in my webpack setup as well but I suspect that's not relevant.
Ah great catch, this is an important one and will prioritize, thank you πŸ‘πŸ»
"2021-12-10T15:30:47Z"
3.0
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/YkD75GMXHs?file=css" ]
tailwindlabs/tailwindcss
6,469
tailwindlabs__tailwindcss-6469
[ "6395" ]
4b2482ff3550ec7ca74561f8ae84d4d826cca762
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -248,6 +248,21 @@ function parseRules(rule, cache, options = {}) { return [cache.get(rule), options] } +const IS_VALID_PROPERTY_NAME = /^[a-z_-]/ + +function isValidPropName(name) { + return IS_VALID_PROPERTY_NAME.test(name) +} + +function isParsableCssValue(property, value) { + try { + postcss.parse(`a{${property}:${value}}`).toResult() + return true + } catch (err) { + return false + } +} + function extractArbitraryProperty(classCandidate, context) { let [, property, value] = classCandidate.match(/^\[([a-zA-Z0-9-_]+):(\S+)\]$/) ?? [] @@ -255,9 +270,17 @@ function extractArbitraryProperty(classCandidate, context) { return null } + if (!isValidPropName(property)) { + return null + } + + if (!isValidArbitraryValue(value)) { + return null + } + let normalized = normalize(value) - if (!isValidArbitraryValue(normalized)) { + if (!isParsableCssValue(property, normalized)) { return null }
diff --git a/tests/arbitrary-properties.test.js b/tests/arbitrary-properties.test.js --- a/tests/arbitrary-properties.test.js +++ b/tests/arbitrary-properties.test.js @@ -231,3 +231,45 @@ test('invalid class', () => { expect(result.css).toMatchFormattedCss(css``) }) }) + +test('invalid arbitrary property', () => { + let config = { + content: [ + { + raw: html`<div class="[autoplay:\${autoplay}]"></div>`, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind base; + @tailwind components; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css``) + }) +}) + +test('invalid arbitrary property 2', () => { + let config = { + content: [ + { + raw: html`[0:02]`, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind base; + @tailwind components; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css``) + }) +})
Abnormal css ouput when some string in the code is wrapped in square brackets **What version of Tailwind CSS are you using?** v3.0.1 **What build tool (or framework if it abstracts the build tool) are you using?** Next.js 12.0.4, postcss 8.4.4 **What version of Node.js are you using?** v14.18.1 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://github.com/DrShpongle/tailwindcss-3-issue-demo **Describe your issue** In case we use some text wrapped with square brackets we get abnormal css output: **Example 1:** Just an object with string field: https://github.com/DrShpongle/tailwindcss-3-issue-demo/blob/main/components/problem-01.js#L4-L5 ![problem-01 js β€” with-tailwindcss-app 2021-12-11 at 1 36 31 PM](https://user-images.githubusercontent.com/1519448/145675038-5633e78e-79ad-493a-b3ab-8d0245fa0831.jpg) and related output: https://github.com/DrShpongle/tailwindcss-3-issue-demo/blob/main/dist/output.css#L579-L581 ![output css β€” with-tailwindcss-app 2021-12-11 at 1 38 58 PM](https://user-images.githubusercontent.com/1519448/145675095-66ae8a3c-3e50-49f7-9948-2f3fa8802b86.jpg) **Example 2:** Just regular dumb component: https://github.com/DrShpongle/tailwindcss-3-issue-demo/blob/main/components/problem-02.tsx#L10 ![problem-02 tsx β€” with-tailwindcss-app 2021-12-11 at 1 42 50 PM](https://user-images.githubusercontent.com/1519448/145675212-7f46ff3e-6877-474f-9f70-3848f2140dc5.jpg) and related output: https://github.com/DrShpongle/tailwindcss-3-issue-demo/blob/main/dist/output.css#L583-L585 ![output css β€” with-tailwindcss-app 2021-12-11 at 1 44 09 PM](https://user-images.githubusercontent.com/1519448/145675245-51b3dea5-f9ce-43b4-8a2c-ba6e230d1ec6.jpg)
This is probably because of [arbitrary properties](https://tailwindcss.com/docs/adding-custom-styles#arbitrary-properties). you can just add an unnecessary escape: ```ts const ProblemComponent = () => { return ( <button nCanPlay={(event: any) => { console.debug(`player ready: [autoplay\:${autoplay}]`); }} ></button> ); }; ``` you can also use a function like this: ```ts const addBrackets = (str: string) => `[${str}]`; const ProblemComponent = () => { return ( <button nCanPlay={(event: any) => { console.debug(`player ready: ${addBrackets(`autoplay:${autoplay}`)}]`); }} ></button> ); }; ```
"2021-12-13T17:36:20Z"
3.0
[]
[ "tests/arbitrary-properties.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/1519448/145675038-5633e78e-79ad-493a-b3ab-8d0245fa0831.jpg", "https://user-images.githubusercontent.com/1519448/145675095-66ae8a3c-3e50-49f7-9948-2f3fa8802b86.jpg", "https://user-images.githubusercontent.com/1519448/145675212-7f46ff3e-6877-474f-9f70-3848f2140dc5.jpg", "https://user-images.githubusercontent.com/1519448/145675245-51b3dea5-f9ce-43b4-8a2c-ba6e230d1ec6.jpg" ]
[]
tailwindlabs/tailwindcss
6,519
tailwindlabs__tailwindcss-6519
[ "6436" ]
fb545bc94de9e8baf33990b71d87df0c269dce22
diff --git a/src/lib/evaluateTailwindFunctions.js b/src/lib/evaluateTailwindFunctions.js --- a/src/lib/evaluateTailwindFunctions.js +++ b/src/lib/evaluateTailwindFunctions.js @@ -42,7 +42,7 @@ function validatePath(config, path, defaultValue) { ? pathToString(path) : path.replace(/^['"]+/g, '').replace(/['"]+$/g, '') const pathSegments = Array.isArray(path) ? path : toPath(pathString) - const value = dlv(config.theme, pathString, defaultValue) + const value = dlv(config.theme, pathSegments, defaultValue) if (value === undefined) { let error = `'${pathString}' does not exist in your theme config.` diff --git a/src/util/toPath.js b/src/util/toPath.js --- a/src/util/toPath.js +++ b/src/util/toPath.js @@ -1,4 +1,26 @@ +/** + * Parse a path string into an array of path segments. + * + * Square bracket notation `a[b]` may be used to "escape" dots that would otherwise be interpreted as path separators. + * + * Example: + * a -> ['a] + * a.b.c -> ['a', 'b', 'c'] + * a[b].c -> ['a', 'b', 'c'] + * a[b.c].e.f -> ['a', 'b.c', 'e', 'f'] + * a[b][c][d] -> ['a', 'b', 'c', 'd'] + * + * @param {string|string[]} path + **/ export function toPath(path) { if (Array.isArray(path)) return path - return path.split(/[\.\]\[]+/g) + + let openBrackets = path.split('[').length - 1 + let closedBrackets = path.split(']').length - 1 + + if (openBrackets !== closedBrackets) { + throw new Error(`Path is invalid. Has unbalanced brackets: ${path}`) + } + + return path.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean) }
diff --git a/tests/evaluateTailwindFunctions.test.js b/tests/evaluateTailwindFunctions.test.js --- a/tests/evaluateTailwindFunctions.test.js +++ b/tests/evaluateTailwindFunctions.test.js @@ -31,6 +31,111 @@ test('it looks up values in the theme using dot notation', () => { }) }) +test('it looks up values in the theme using bracket notation', () => { + let input = css` + .banana { + color: theme('colors[yellow]'); + } + ` + + let output = css` + .banana { + color: #f7cc50; + } + ` + + return run(input, { + theme: { + colors: { + yellow: '#f7cc50', + }, + }, + }).then((result) => { + expect(result.css).toEqual(output) + expect(result.warnings().length).toBe(0) + }) +}) + +test('it looks up values in the theme using consecutive bracket notation', () => { + let input = css` + .banana { + color: theme('colors[yellow][100]'); + } + ` + + let output = css` + .banana { + color: #f7cc50; + } + ` + + return run(input, { + theme: { + colors: { + yellow: { + 100: '#f7cc50', + }, + }, + }, + }).then((result) => { + expect(result.css).toEqual(output) + expect(result.warnings().length).toBe(0) + }) +}) + +test('it looks up values in the theme using bracket notation that have dots in them', () => { + let input = css` + .banana { + padding-top: theme('spacing[1.5]'); + } + ` + + let output = css` + .banana { + padding-top: 0.375rem; + } + ` + + return run(input, { + theme: { + spacing: { + '1.5': '0.375rem', + }, + }, + }).then((result) => { + expect(result.css).toEqual(output) + expect(result.warnings().length).toBe(0) + }) +}) + +test('theme with mismatched brackets throws an error ', async () => { + let config = { + theme: { + spacing: { + '1.5': '0.375rem', + }, + }, + } + + let input = (path) => css` + .banana { + padding-top: theme('${path}'); + } + ` + + await expect(run(input('spacing[1.5]]'), config)).rejects.toThrowError( + `Path is invalid. Has unbalanced brackets: spacing[1.5]]` + ) + + await expect(run(input('spacing[[1.5]'), config)).rejects.toThrowError( + `Path is invalid. Has unbalanced brackets: spacing[[1.5]` + ) + + await expect(run(input('spacing[a['), config)).rejects.toThrowError( + `Path is invalid. Has unbalanced brackets: spacing[a[` + ) +}) + test('color can be a function', () => { let input = css` .backgroundColor { diff --git a/tests/to-path.test.js b/tests/to-path.test.js --- a/tests/to-path.test.js +++ b/tests/to-path.test.js @@ -7,11 +7,12 @@ it('should keep an array as an array', () => { }) it.each` - input | output - ${'a.b.c'} | ${['a', 'b', 'c']} - ${'a[0].b.c'} | ${['a', '0', 'b', 'c']} - ${'.a'} | ${['', 'a']} - ${'[].a'} | ${['', 'a']} + input | output + ${'a.b.c'} | ${['a', 'b', 'c']} + ${'a[0].b.c'} | ${['a', '0', 'b', 'c']} + ${'.a'} | ${['a']} + ${'[].a'} | ${['a']} + ${'a[1.5][b][c]'} | ${['a', '1.5', 'b', 'c']} `('should convert "$input" to "$output"', ({ input, output }) => { expect(toPath(input)).toEqual(output) })
v2 to v3 theme() keys bug? **What version of Tailwind CSS are you using?** v3.0.1 **What build tool (or framework if it abstracts the build tool) are you using?** vue cli v5.x webpack v5.x **What version of Node.js are you using?** v16.5.0 **What browser are you using?** N/A **What operating system are you using?** macOS **Describe your issue** Develop or compile. This message always appears ``` does not exist in your theme config. 'spacing' has the following keys: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14', '16', '18', '20', '24', '28', '32', '36', '40', '44', '48', '52', '56', '60', '64', '72', '80', '96', 'px', '0.5', '1.5', '2.5', '3.5', '4.5', '7.5' 17 | } 18 | .dialog.iOS .title { > 19 | font-size: theme("spacing['4.5']"); | ^ 20 | color: theme("colors.black"); 21 | } ``` But the following keys message contains the index There is no such error message in v2 tailwind.config.js ``` module.exports = { theme: { spacing: { ["4.5"]: "1.125rem" }, } } ```
I think it's wrong to use array in object definition, try with this. ``` module.exports = { theme: { spacing: { "4.5": "1.125rem" }, } } ``` By the way why are you using space in font size? and if you want to not override default spacing values you need to extend the theme this way ``` theme: { extend: { ``` @jheng-jie was just here to create a ticket for the same problem. we experience this as well, and it is a blocker for migration. @minimit it is not an [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) so it won't make a difference. Hey! Can you please provide a reproduction? @adamwathan [here is one](https://github.com/ardaerzin/tailwind3-spacing) in the `Test.module.css` file if you enable the commented out lines, you'll start seeing the errors. this was working fine in tailwind v2. also the regular classnames still work as you can see in the index page @adamwathan Sorry my project so big But it can be easily reappear ```shell # vite yarn create vite test && cd test # tailwindcss yarn add -D tailwindcss postcss autoprefixer npx tailwindcss init -p ``` tailwind.config.js ```javascript module.exports = { content: [ "./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}", ], theme: { extend: { spacing: { ["4.5"]: "0.125rem", ["4d5"]: "0.125rem", } }, }, plugins: [], } ``` src/App.vue ```vue <template> <div class="test">Test</div> <!-- is working --> <div class="p-4.5">Test</div> </template> <style> @tailwind base; @tailwind components; @tailwind utilities; .test { /* working */ padding: theme("spacing.4d5"); /* has the following keys: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14', '16', '20', '24', '28', '32', '36', '40', '44', '48', '52', '56', '60', '64', '72', '80', '96', 'px', '0.5', '1.5', '2.5', '3.5', '4.5', '4d5' */ padding: theme("spacing['4.5']"); /* 'spacing[4.5]' does not exist in your theme config. 'spacing.4' is not an object. */ padding: theme("spacing[4.5]"); } </style> ``` The problem may occur in the "dot" naming I don't think it's related to the dot naming, looks like the `[]` don't work anymore. Smallest repro possible: https://play.tailwindcss.com/SvPNpftcow?file=config Switching to `v2.2.19` makes it work, switching to `v3.0.1` doesn't. I can confirm this. It happend with height[1.5] or a custom transitionProperty
"2021-12-14T22:26:30Z"
3.0
[]
[ "tests/to-path.test.js", "tests/evaluateTailwindFunctions.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
6,546
tailwindlabs__tailwindcss-6546
[ "6503" ]
4a5ba3779e9bb4ce726488e9b624bd73521e79e9
diff --git a/src/util/resolveConfig.js b/src/util/resolveConfig.js --- a/src/util/resolveConfig.js +++ b/src/util/resolveConfig.js @@ -6,6 +6,8 @@ import colors from '../public/colors' import { defaults } from './defaults' import { toPath } from './toPath' import { normalizeConfig } from './normalizeConfig' +import isPlainObject from './isPlainObject' +import { cloneDeep } from './cloneDeep' function isFunction(input) { return typeof input === 'function' @@ -144,7 +146,15 @@ function resolveFunctionKeys(object) { val = isFunction(val) ? val(resolvePath, configUtils) : val } - return val === undefined ? defaultValue : val + if (val === undefined) { + return defaultValue + } + + if (isPlainObject(val)) { + return cloneDeep(val) + } + + return val } resolvePath.theme = resolvePath
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -57,3 +57,55 @@ test('all plugins are executed that match a candidate', () => { `) }) }) + +test('per-plugin colors with the same key can differ when using a custom colors object', () => { + let config = { + content: [ + { + raw: html` + <div class="bg-theme text-theme">This should be green text on red background.</div> + `, + }, + ], + theme: { + // colors & theme MUST be plain objects + // If they're functions here the test passes regardless + colors: { + theme: { + bg: 'red', + text: 'green', + }, + }, + extend: { + textColor: { + theme: { + DEFAULT: 'green', + }, + }, + backgroundColor: { + theme: { + DEFAULT: 'red', + }, + }, + }, + }, + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .bg-theme { + --tw-bg-opacity: 1; + background-color: rgb(255 0 0 / var(--tw-bg-opacity)); + } + .text-theme { + --tw-text-opacity: 1; + color: rgb(0 128 0 / var(--tw-text-opacity)); + } + `) + }) +})
Extending multiple color plugins using the same color name causes incorrect colors. <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** 3.0.2 **What build tool (or framework if it abstracts the build tool) are you using?** Playground **What version of Node.js are you using?** n/a **What browser are you using?** n/a **What operating system are you using?** n/a **Reproduction URL** https://play.tailwindcss.com/v7qgUeljBK?file=config **Describe your issue** Extending multiple color plugins using the same color name causes incorrect colors. See https://play.tailwindcss.com/v7qgUeljBK?file=config for a failing case. It works when using the same name multiple times directly https://play.tailwindcss.com/qaS9VP8AHE?file=config
I would like to work on this, can you assign to me?
"2021-12-15T19:02:38Z"
3.0
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/v7qgUeljBK?file=config", "https://play.tailwindcss.com/qaS9VP8AHE?file=config" ]
tailwindlabs/tailwindcss
6,726
tailwindlabs__tailwindcss-6726
[ "6709" ]
da7396cf7759dc68f4c2a4c1b03d46e5718cf915
diff --git a/src/util/color.js b/src/util/color.js --- a/src/util/color.js +++ b/src/util/color.js @@ -5,8 +5,11 @@ let SHORT_HEX = /^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i let VALUE = `(?:\\d+|\\d*\\.\\d+)%?` let SEP = `(?:\\s*,\\s*|\\s+)` let ALPHA_SEP = `\\s*[,/]\\s*` -let RGB_HSL = new RegExp( - `^(rgb|hsl)a?\\(\\s*(${VALUE})${SEP}(${VALUE})${SEP}(${VALUE})(?:${ALPHA_SEP}(${VALUE}))?\\s*\\)$` +let RGB = new RegExp( + `^rgba?\\(\\s*(${VALUE})${SEP}(${VALUE})${SEP}(${VALUE})(?:${ALPHA_SEP}(${VALUE}))?\\s*\\)$` +) +let HSL = new RegExp( + `^hsla?\\(\\s*((?:${VALUE})(?:deg|rad|grad|turn)?)${SEP}(${VALUE})${SEP}(${VALUE})(?:${ALPHA_SEP}(${VALUE}))?\\s*\\)$` ) export function parseColor(value) { @@ -37,13 +40,23 @@ export function parseColor(value) { } } - let match = value.match(RGB_HSL) + let rgbMatch = value.match(RGB) + + if (rgbMatch !== null) { + return { + mode: 'rgb', + color: [rgbMatch[1], rgbMatch[2], rgbMatch[3]].map((v) => v.toString()), + alpha: rgbMatch[4]?.toString?.(), + } + } + + let hslMatch = value.match(HSL) - if (match !== null) { + if (hslMatch !== null) { return { - mode: match[1], - color: [match[2], match[3], match[4]].map((v) => v.toString()), - alpha: match[5]?.toString?.(), + mode: 'hsl', + color: [hslMatch[1], hslMatch[2], hslMatch[3]].map((v) => v.toString()), + alpha: hslMatch[4]?.toString?.(), } }
diff --git a/tests/arbitrary-values.test.css b/tests/arbitrary-values.test.css --- a/tests/arbitrary-values.test.css +++ b/tests/arbitrary-values.test.css @@ -603,6 +603,13 @@ .bg-\[hsla\(0\2c 100\%\2c 50\%\2c 0\.3\)\] { background-color: hsla(0, 100%, 50%, 0.3); } +.bg-\[hsl\(0rad\2c 100\%\2c 50\%\)\] { + --tw-bg-opacity: 1; + background-color: hsl(0rad 100% 50% / var(--tw-bg-opacity)); +} +.bg-\[hsla\(0turn\2c 100\%\2c 50\%\2c 0\.3\)\] { + background-color: hsla(0turn, 100%, 50%, 0.3); +} .bg-\[\#0f0_var\(--value\)\] { background-color: #0f0 var(--value); } diff --git a/tests/arbitrary-values.test.html b/tests/arbitrary-values.test.html --- a/tests/arbitrary-values.test.html +++ b/tests/arbitrary-values.test.html @@ -216,6 +216,7 @@ <div class="bg-[rgb(123,_456,_123)_black]"></div> <div class="bg-[rgb(123_456_789)]"></div> <div class="bg-[hsl(0,100%,50%)] bg-[hsla(0,100%,50%,0.3)]"></div> + <div class="bg-[hsl(0rad,100%,50%)] bg-[hsla(0turn,100%,50%,0.3)]"></div> <div class="bg-[#0f0_var(--value)]"></div> <div class="bg-[var(--value1)_var(--value2)]"></div> <div class="bg-[color:var(--value1)_var(--value2)]"></div> diff --git a/tests/color.test.js b/tests/color.test.js --- a/tests/color.test.js +++ b/tests/color.test.js @@ -2,21 +2,37 @@ import { parseColor, formatColor } from '../src/util/color' describe('parseColor', () => { it.each` - color | output - ${'black'} | ${{ mode: 'rgb', color: ['0', '0', '0'], alpha: undefined }} - ${'#0088cc'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: undefined }} - ${'#08c'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: undefined }} - ${'#0088cc99'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: '0.6' }} - ${'#08c9'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: '0.6' }} - ${'rgb(0, 30, 60)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: undefined }} - ${'rgba(0, 30, 60, 0.5)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: '0.5' }} - ${'rgb(0 30 60)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: undefined }} - ${'rgb(0 30 60 / 0.5)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: '0.5' }} - ${'hsl(0, 30%, 60%)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: undefined }} - ${'hsla(0, 30%, 60%, 0.5)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: '0.5' }} - ${'hsl(0 30% 60%)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: undefined }} - ${'hsl(0 30% 60% / 0.5)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: '0.5' }} - ${'transparent'} | ${{ mode: 'rgb', color: ['0', '0', '0'], alpha: '0' }} + color | output + ${'black'} | ${{ mode: 'rgb', color: ['0', '0', '0'], alpha: undefined }} + ${'#0088cc'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: undefined }} + ${'#08c'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: undefined }} + ${'#0088cc99'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: '0.6' }} + ${'#08c9'} | ${{ mode: 'rgb', color: ['0', '136', '204'], alpha: '0.6' }} + ${'rgb(0, 30, 60)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: undefined }} + ${'rgba(0, 30, 60, 0.5)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: '0.5' }} + ${'rgb(0 30 60)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: undefined }} + ${'rgb(0 30 60 / 0.5)'} | ${{ mode: 'rgb', color: ['0', '30', '60'], alpha: '0.5' }} + ${'hsl(0, 30%, 60%)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: undefined }} + ${'hsl(0deg, 30%, 60%)'} | ${{ mode: 'hsl', color: ['0deg', '30%', '60%'], alpha: undefined }} + ${'hsl(0rad, 30%, 60%)'} | ${{ mode: 'hsl', color: ['0rad', '30%', '60%'], alpha: undefined }} + ${'hsl(0grad, 30%, 60%)'} | ${{ mode: 'hsl', color: ['0grad', '30%', '60%'], alpha: undefined }} + ${'hsl(0turn, 30%, 60%)'} | ${{ mode: 'hsl', color: ['0turn', '30%', '60%'], alpha: undefined }} + ${'hsla(0, 30%, 60%, 0.5)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: '0.5' }} + ${'hsla(0deg, 30%, 60%, 0.5)'} | ${{ mode: 'hsl', color: ['0deg', '30%', '60%'], alpha: '0.5' }} + ${'hsla(0rad, 30%, 60%, 0.5)'} | ${{ mode: 'hsl', color: ['0rad', '30%', '60%'], alpha: '0.5' }} + ${'hsla(0grad, 30%, 60%, 0.5)'} | ${{ mode: 'hsl', color: ['0grad', '30%', '60%'], alpha: '0.5' }} + ${'hsla(0turn, 30%, 60%, 0.5)'} | ${{ mode: 'hsl', color: ['0turn', '30%', '60%'], alpha: '0.5' }} + ${'hsl(0 30% 60%)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: undefined }} + ${'hsl(0deg 30% 60%)'} | ${{ mode: 'hsl', color: ['0deg', '30%', '60%'], alpha: undefined }} + ${'hsl(0rad 30% 60%)'} | ${{ mode: 'hsl', color: ['0rad', '30%', '60%'], alpha: undefined }} + ${'hsl(0grad 30% 60%)'} | ${{ mode: 'hsl', color: ['0grad', '30%', '60%'], alpha: undefined }} + ${'hsl(0turn 30% 60%)'} | ${{ mode: 'hsl', color: ['0turn', '30%', '60%'], alpha: undefined }} + ${'hsl(0 30% 60% / 0.5)'} | ${{ mode: 'hsl', color: ['0', '30%', '60%'], alpha: '0.5' }} + ${'hsl(0deg 30% 60% / 0.5)'} | ${{ mode: 'hsl', color: ['0deg', '30%', '60%'], alpha: '0.5' }} + ${'hsl(0rad 30% 60% / 0.5)'} | ${{ mode: 'hsl', color: ['0rad', '30%', '60%'], alpha: '0.5' }} + ${'hsl(0grad 30% 60% / 0.5)'} | ${{ mode: 'hsl', color: ['0grad', '30%', '60%'], alpha: '0.5' }} + ${'hsl(0turn 30% 60% / 0.5)'} | ${{ mode: 'hsl', color: ['0turn', '30%', '60%'], alpha: '0.5' }} + ${'transparent'} | ${{ mode: 'rgb', color: ['0', '0', '0'], alpha: '0' }} `('should parse "$color" to the correct value', ({ color, output }) => { expect(parseColor(color)).toEqual(output) })
HSL no longer works in JIT **What version of Tailwind CSS are you using?** v3.0.7 **What build tool (or framework if it abstracts the build tool) are you using?** Next 12.0.7, VSCode 1.63.2, latest version of Tailwind IntelliSense plugin **What version of Node.js are you using?** v16.13.0 **What browser are you using?** N/A **What operating system are you using?** macOS **Reproduction URL** The `bg-[hsl(202deg,96%,16%)]` class name. **Describe your issue** This used to work in previous Tailwind 2.x versions but `bg-[hsl(202deg,96%,16%)]` but no longer works.
Thanks! Looks like we need to account for the unit on the first value in our parser, because using `rad`, `grad`, or `turn` also doesn't work. One temporary workaround is to add a type hint: ``` bg-[color:hsl(202deg,96%,16%)] ``` ...or remove the `deg`: ``` bg-[hsl(202,96%,16%)] ``` Will leave this open until we get a chance to fix though πŸ‘πŸ»
"2021-12-24T18:14:01Z"
3.0
[]
[ "tests/color.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
6,875
tailwindlabs__tailwindcss-6875
[ "6194" ]
41e32bd9a726e5df686681d08f0429ae55897e67
diff --git a/src/lib/expandTailwindAtRules.js b/src/lib/expandTailwindAtRules.js --- a/src/lib/expandTailwindAtRules.js +++ b/src/lib/expandTailwindAtRules.js @@ -140,17 +140,28 @@ export default function expandTailwindAtRules(context) { variants: null, } - // Make sure this file contains Tailwind directives. If not, we can save - // a lot of work and bail early. Also we don't have to register our touch - // file as a dependency since the output of this CSS does not depend on - // the source of any templates. Think Vue <style> blocks for example. - root.walkAtRules('tailwind', (rule) => { - if (Object.keys(layerNodes).includes(rule.params)) { - layerNodes[rule.params] = rule + let hasApply = false + + root.walkAtRules((rule) => { + // Make sure this file contains Tailwind directives. If not, we can save + // a lot of work and bail early. Also we don't have to register our touch + // file as a dependency since the output of this CSS does not depend on + // the source of any templates. Think Vue <style> blocks for example. + if (rule.name === 'tailwind') { + if (Object.keys(layerNodes).includes(rule.params)) { + layerNodes[rule.params] = rule + } + } + + // We also want to check for @apply because the user can + // apply classes in an isolated environment like CSS + // modules and we still need to inject defaults + if (rule.name === 'apply') { + hasApply = true } }) - if (Object.values(layerNodes).every((n) => n === null)) { + if (Object.values(layerNodes).every((n) => n === null) && !hasApply) { return root }
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -1,5 +1,6 @@ import fs from 'fs' import path from 'path' +import { DEFAULTS_LAYER } from '../src/lib/expandTailwindAtRules.js' import { run, html, css } from './util/run' @@ -810,3 +811,39 @@ it('should be possible to apply user css without tailwind directives', () => { `) }) }) + +fit('apply can emit defaults in isolated environments without @tailwind directives', () => { + let config = { + [DEFAULTS_LAYER]: true, + experimental: { optimizeUniversalDefaults: true }, + + content: [{ raw: html`<div class="foo"></div>` }], + } + + let input = css` + .foo { + @apply focus:rotate-90; + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .foo { + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-transform: translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y)) + rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) + scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + } + .foo:focus { + --tw-rotate: 90deg; + transform: var(--tw-transform); + } + `) + }) +})
Focus visible doesn't work with @apply in CSS module **What version of Tailwind CSS are you using?** 3.0.0-alpha.2 **What build tool (or framework if it abstracts the build tool) are you using?** Next 12.0.4 **What version of Node.js are you using?** v16.13.0 **What browser are you using?** Chrome **What operating system are you using?** MacOS **Reproduction URL** Test.module.css ``` .testClass { @apply focus-visible:ring-4 focus-visible:ring-teal-300; } ``` **Describe your issue** Focus visible doesn't work using @apply with CSS modules as of 3.0 alpha 2. It works fine if I revert back to alpha 1.
Hey! Can you please provide a proper reproduction (a repo we can clone that replicates your particular setup)? Yes, will do tomorrow morning Same issue with `focus` and tailwindcss 2.2.19. The issue comes with @apply in CSS module and without using the same utilities in the global css file or in className. ![image](https://user-images.githubusercontent.com/4593089/143284250-132e8a5c-3f5a-46ad-8e97-81aa23882e1f.png) reproduction: https://codesandbox.io/s/youthful-sky-9ktgf?file=/src/pages/index.tsx edit: updated example with tailwindcss 3.0.0 -> https://codesandbox.io/s/patient-platform-pm5qx?file=/src/pages/index.tsx > Same issue with `focus` and tailwindcss 2.2.19. > > The issue comes with @apply in CSS module and without using the same utilities in the global css file or in className. ![image](https://user-images.githubusercontent.com/4593089/143284250-132e8a5c-3f5a-46ad-8e97-81aa23882e1f.png) > > reproduction: https://codesandbox.io/s/youthful-sky-9ktgf?file=/src/pages/index.tsx Thank you. I was about to do it, I promise πŸ˜€ Can confirm that when just using normal utility classes focus visible rings work fine (--tw-ring-inset and --tr-ring-offset are set to /* */ if I don't explicitly use them) whereas when using @apply inside a CSS module I get these errors and the ring doesn't work <img width="572" alt="Screen Shot 2021-11-26 at 3 47 35 PM" src="https://user-images.githubusercontent.com/10248395/143636780-426c2116-4862-4f46-92a6-a44db490bcf0.png"> <img width="610" alt="Screen Shot 2021-11-26 at 3 47 41 PM" src="https://user-images.githubusercontent.com/10248395/143636785-b817e8e1-1e8d-46be-a6b1-3bb3aff84f12.png"> In some scenarios this seems to be broken in 3.0 alpha 1 as well (not just alpha 2) Same issue with :focus, I tried 2.1.2, 2.2.19, 3.0.0-alpha.2 and this problem is encountered everywhere with the transform and ring properties. Next.js 12 + CSS Modules <img width="580" alt="Screenshot 2021-12-07 at 21 50 42" src="https://user-images.githubusercontent.com/24757335/145088947-5949be0d-7991-41c7-97d9-a36fb04f3fc6.png"> <img width="460" alt="Screenshot 2021-12-08 at 22 14 52" src="https://user-images.githubusercontent.com/24757335/145269835-ced115c7-0800-41c7-ad55-ee8703685ce8.png"> got the same issues, working with transform and ring using @apply. I have same issues in v3 ![image](https://user-images.githubusercontent.com/22712590/145550271-3a88bc34-e0ab-42ce-9077-b0729373f51f.png) Same issue with backdrop filters. No --tw-backdrop-filter is defined, so it does not work. This issue appears to be resolved in Chrome but not Safari
"2022-01-04T15:49:31Z"
3.0
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
6,938
tailwindlabs__tailwindcss-6938
[ "6321" ]
9c72add3b717d7f540f63579d0a934bfd40f0491
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -72,47 +72,6 @@ function extractApplyCandidates(params) { return [candidates, false] } -function partitionApplyParents(root) { - let applyParents = new Set() - - root.walkAtRules('apply', (rule) => { - applyParents.add(rule.parent) - }) - - for (let rule of applyParents) { - let nodeGroups = [] - let lastGroup = [] - - for (let node of rule.nodes) { - if (node.type === 'atrule' && node.name === 'apply') { - if (lastGroup.length > 0) { - nodeGroups.push(lastGroup) - lastGroup = [] - } - nodeGroups.push([node]) - } else { - lastGroup.push(node) - } - } - - if (lastGroup.length > 0) { - nodeGroups.push(lastGroup) - } - - if (nodeGroups.length === 1) { - continue - } - - for (let group of [...nodeGroups].reverse()) { - let newParent = rule.clone({ nodes: [] }) - newParent.append(group) - rule.after(newParent) - } - - rule.remove() - } -} - function processApply(root, context) { let applyCandidates = new Set() @@ -343,7 +302,6 @@ function processApply(root, context) { export default function expandApplyAtRules(context) { return (root) => { - partitionApplyParents(root) processApply(root, context) } } diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -20,6 +20,58 @@ import log from '../util/log' import negateValue from '../util/negateValue' import isValidArbitraryValue from '../util/isValidArbitraryValue' +function partitionRules(root) { + if (!root.walkAtRules) return [root] + + let applyParents = new Set() + let rules = [] + + root.walkAtRules('apply', (rule) => { + applyParents.add(rule.parent) + }) + + if (applyParents.size === 0) { + rules.push(root) + } + + for (let rule of applyParents) { + let nodeGroups = [] + let lastGroup = [] + + for (let node of rule.nodes) { + if (node.type === 'atrule' && node.name === 'apply') { + if (lastGroup.length > 0) { + nodeGroups.push(lastGroup) + lastGroup = [] + } + nodeGroups.push([node]) + } else { + lastGroup.push(node) + } + } + + if (lastGroup.length > 0) { + nodeGroups.push(lastGroup) + } + + if (nodeGroups.length === 1) { + rules.push(rule) + continue + } + + for (let group of [...nodeGroups].reverse()) { + let clone = rule.clone({ nodes: [] }) + clone.append(group) + rules.unshift(clone) + rule.after(clone) + } + + rule.remove() + } + + return rules +} + function parseVariantFormatString(input) { if (input.includes('{')) { if (!isBalanced(input)) throw new Error(`Your { and } are unbalanced.`) @@ -232,7 +284,9 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs context.candidateRuleMap.set(identifier, []) } - context.candidateRuleMap.get(identifier).push([{ sort: offset, layer: 'user' }, rule]) + context.candidateRuleMap + .get(identifier) + .push(...partitionRules(rule).map((rule) => [{ sort: offset, layer: 'user' }, rule])) } }, addBase(base) { @@ -246,7 +300,7 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs context.candidateRuleMap .get(prefixedIdentifier) - .push([{ sort: offset, layer: 'base' }, rule]) + .push(...partitionRules(rule).map((rule) => [{ sort: offset, layer: 'base' }, rule])) } }, /** @@ -260,7 +314,6 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs for (let [identifier, rule] of withIdentifiers(groups)) { let prefixedIdentifier = prefixIdentifier(identifier, {}) - let offset = offsets.base++ if (!context.candidateRuleMap.has(prefixedIdentifier)) { context.candidateRuleMap.set(prefixedIdentifier, []) @@ -268,7 +321,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs context.candidateRuleMap .get(prefixedIdentifier) - .push([{ sort: offset, layer: 'defaults' }, rule]) + .push( + ...partitionRules(rule).map((rule) => [ + { sort: offsets.base++, layer: 'defaults' }, + rule, + ]) + ) } }, addComponents(components, options) { @@ -281,7 +339,6 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs for (let [identifier, rule] of withIdentifiers(components)) { let prefixedIdentifier = prefixIdentifier(identifier, options) - let offset = offsets.components++ classList.add(prefixedIdentifier) @@ -291,7 +348,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs context.candidateRuleMap .get(prefixedIdentifier) - .push([{ sort: offset, layer: 'components', options }, rule]) + .push( + ...partitionRules(rule).map((rule) => [ + { sort: offsets.components++, layer: 'components', options }, + rule, + ]) + ) } }, addUtilities(utilities, options) { @@ -304,7 +366,6 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs for (let [identifier, rule] of withIdentifiers(utilities)) { let prefixedIdentifier = prefixIdentifier(identifier, options) - let offset = offsets.utilities++ classList.add(prefixedIdentifier) @@ -314,7 +375,12 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs context.candidateRuleMap .get(prefixedIdentifier) - .push([{ sort: offset, layer: 'utilities', options }, rule]) + .push( + ...partitionRules(rule).map((rule) => [ + { sort: offsets.utilities++, layer: 'utilities', options }, + rule, + ]) + ) } }, matchUtilities: function (utilities, options) { diff --git a/src/processTailwindFeatures.js b/src/processTailwindFeatures.js --- a/src/processTailwindFeatures.js +++ b/src/processTailwindFeatures.js @@ -14,6 +14,8 @@ export default function processTailwindFeatures(setupContext) { return function (root, result) { let { tailwindDirectives, applyDirectives } = normalizeTailwindDirectives(root) + detectNesting()(root, result) + let context = setupContext({ tailwindDirectives, applyDirectives, @@ -37,7 +39,6 @@ export default function processTailwindFeatures(setupContext) { issueFlagNotices(context.tailwindConfig) - detectNesting(context)(root, result) expandTailwindAtRules(context)(root, result) expandApplyAtRules(context)(root, result) evaluateTailwindFunctions(context)(root, result)
diff --git a/tests/apply.test.css b/tests/apply.test.css --- a/tests/apply.test.css +++ b/tests/apply.test.css @@ -122,7 +122,6 @@ text-align: left; } } -/* TODO: This works but the generated CSS is unnecessarily verbose. */ .complex-utilities { --tw-ordinal: ordinal; --tw-numeric-spacing: tabular-nums; @@ -144,14 +143,6 @@ --tw-numeric-fraction: diagonal-fractions; font-variant-numeric: var(--tw-font-variant-numeric); } -.basic-nesting-parent { - .basic-nesting-child { - font-weight: 700; - } - .basic-nesting-child:hover { - font-weight: 400; - } -} .use-base-only-a { font-weight: 700; } diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -52,15 +52,9 @@ test('@apply', () => { .selectors-group { @apply group-hover:text-center lg:group-hover:text-left; } - /* TODO: This works but the generated CSS is unnecessarily verbose. */ .complex-utilities { @apply ordinal tabular-nums focus:diagonal-fractions shadow-lg hover:shadow-xl; } - .basic-nesting-parent { - .basic-nesting-child { - @apply font-bold hover:font-normal; - } - } .use-base-only-a { @apply font-bold; } @@ -910,6 +904,196 @@ it('should be possible to apply a class from another rule with multiple selector }) }) +describe('multiple instances', () => { + it('should be possible to apply multiple "instances" of the same class', () => { + let config = { + content: [{ raw: html`` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + .a { + @apply b; + } + + .b { + @apply uppercase; + } + + .b { + color: red; + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .a { + text-transform: uppercase; + color: red; + } + + .b { + text-transform: uppercase; + color: red; + } + `) + }) + }) + + it('should be possible to apply a combination of multiple "instances" of the same class', () => { + let config = { + content: [{ raw: html`` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + .a { + @apply b; + } + + .b { + @apply uppercase; + color: red; + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .a { + text-transform: uppercase; + color: red; + } + + .b { + text-transform: uppercase; + color: red; + } + `) + }) + }) + + it('should generate the same output, even if it was used in a @layer', () => { + let config = { + content: [{ raw: html`<div class="a b"></div>` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind components; + + @layer components { + .a { + @apply b; + } + + .b { + @apply uppercase; + color: red; + } + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .a { + text-transform: uppercase; + color: red; + } + + .b { + text-transform: uppercase; + color: red; + } + `) + }) + }) + + it('should be possible to apply a combination of multiple "instances" of the same class (defined in a layer)', () => { + let config = { + content: [{ raw: html`<div class="a b"></div>` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind components; + + @layer components { + .a { + color: red; + @apply b; + color: blue; + } + + .b { + @apply text-green-500; + text-decoration: underline; + } + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .a { + color: red; + --tw-text-opacity: 1; + color: rgb(34 197 94 / var(--tw-text-opacity)); + text-decoration: underline; + color: blue; + } + + .b { + --tw-text-opacity: 1; + color: rgb(34 197 94 / var(--tw-text-opacity)); + text-decoration: underline; + } + `) + }) + }) + + it('should properly maintain the order', () => { + let config = { + content: [{ raw: html`` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + h2 { + @apply text-xl; + @apply lg:text-3xl; + @apply sm:text-2xl; + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + h2 { + font-size: 1.25rem; + line-height: 1.75rem; + } + + @media (min-width: 1024px) { + h2 { + font-size: 1.875rem; + line-height: 2.25rem; + } + } + + @media (min-width: 640px) { + h2 { + font-size: 1.5rem; + line-height: 2rem; + } + } + `) + }) + }) +}) + /* it('apply can emit defaults in isolated environments without @tailwind directives', () => { let config = {
Utility classes can't be built with @apply and custom props <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.0.0 **What build tool (or framework if it abstracts the build tool) are you using?** PostCSS **What version of Node.js are you using?** v14.13.0 **What browser are you using?** Chrome **What operating system are you using?** Windows **Reproduction URL** https://play.tailwindcss.com/qm3e5FDSEr **Describe your issue** I've made utility classes that have both Tailwind tokens and custom css. But these classes could no longer be used with `@apply` after upgrading to v3. This seems to be a [regression from v2->v3](https://play.tailwindcss.com/CwBZvIVuPx?file=css). I can mitigate the issue for now by [duplicating some classes](https://play.tailwindcss.com/7FFOWiZ88S?file=css), but that's not a great solution.
same for me =( Hey! So we're going to dig into this a little deeper, but as a workaround you can wrap these classes in an `@layer utilities` directive to get this working: ```css @layer utilities { .a { @apply b; } .b { @apply uppercase; color: red; } } ``` Here's an updated Play illustrating this: https://play.tailwindcss.com/ksUrE9fW01?file=css Hi, I have a lot of custom css classes that I reuse via `@apply my-css-class`. Recently I upgraded to v3 and things stopped working. I'd like to ask if there is any workaround apart from putting those classes into an `@layer utilities` as above? Since I took for granted that I can reuse those classes with `@apply`, they are over all places and it's not easy to find them all. @Tony2 with `3.0.7` you don't need to use `@layer`, but each css that uses `@apply` will need to include a reference to `@tailwind`. I have a PR that resolves this to `2.X.X` behaviour #6580 thank you @garymathews for the hint! I rely heavily on twcss for my work (an in-house component framework). This bug made me somewhat worried if my bet on twcss is the correct decision. Till v2 it has appeared rock-solid and very well-maintained. I understand that v3 is still relatively new, however being able to use `@apply my-class` is IMO a vital feature to keep css maintainable.
"2022-01-06T20:11:03Z"
3.0
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/7FFOWiZ88S?file=css", "https://play.tailwindcss.com/CwBZvIVuPx?file=css", "https://play.tailwindcss.com/qm3e5FDSEr" ]
tailwindlabs/tailwindcss
7,102
tailwindlabs__tailwindcss-7102
[ "380" ]
deee3b1995a7726ecb95ae144dd6647dd6b4ce72
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -529,6 +529,41 @@ export let corePlugins = { }) }, + borderSpacing: ({ addDefaults, matchUtilities, theme }) => { + addDefaults('border-spacing', { + '--tw-border-spacing-x': 0, + '--tw-border-spacing-y': 0, + }) + + matchUtilities( + { + 'border-spacing': (value) => { + return { + '--tw-border-spacing-x': value, + '--tw-border-spacing-y': value, + '@defaults border-spacing': {}, + 'border-spacing': 'var(--tw-border-spacing-x) var(--tw-border-spacing-y)', + } + }, + 'border-spacing-x': (value) => { + return { + '--tw-border-spacing-x': value, + '@defaults border-spacing': {}, + 'border-spacing': 'var(--tw-border-spacing-x) var(--tw-border-spacing-y)', + } + }, + 'border-spacing-y': (value) => { + return { + '--tw-border-spacing-y': value, + '@defaults border-spacing': {}, + 'border-spacing': 'var(--tw-border-spacing-x) var(--tw-border-spacing-y)', + } + }, + }, + { values: theme('borderSpacing') } + ) + }, + transformOrigin: createUtilityPlugin('transformOrigin', [['origin', ['transformOrigin']]]), translate: createUtilityPlugin( 'translate', diff --git a/stubs/defaultConfig.stub.js b/stubs/defaultConfig.stub.js --- a/stubs/defaultConfig.stub.js +++ b/stubs/defaultConfig.stub.js @@ -194,6 +194,9 @@ module.exports = { '3xl': '1.5rem', full: '9999px', }, + borderSpacing: ({ theme }) => ({ + ...theme('spacing'), + }), borderWidth: { DEFAULT: '1px', 0: '0px',
diff --git a/tests/__snapshots__/source-maps.test.js.snap b/tests/__snapshots__/source-maps.test.js.snap new file mode 100644 --- /dev/null +++ b/tests/__snapshots__/source-maps.test.js.snap @@ -0,0 +1,317 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`apply generates source maps 1`] = ` +Array [ + "2:4 -> 2:4", + "3:6-27 -> 3:6-27", + "4:6-33 -> 4:6-18", + "4:6-33 -> 5:6-17", + "4:6-33 -> 6:6-24", + "4:6-33 -> 7:6-61", + "5:4 -> 8:4", + "7:4 -> 10:4", + "8:6-39 -> 11:6-39", + "9:6-31 -> 12:6-18", + "9:6-31 -> 13:6-17", + "9:6-31 -> 14:6-24", + "9:6-31 -> 15:6-61", + "10:4 -> 16:4", + "13:6 -> 18:4", + "13:6-29 -> 19:6-18", + "13:6-29 -> 20:6-17", + "13:6-29 -> 21:6-24", + "13:6 -> 22:6", + "13:29 -> 23:0", +] +`; + +exports[`components have source maps 1`] = ` +Array [ + "2:4 -> 1:0", + "2:4 -> 2:4", + "2:24 -> 3:0", + "2:4 -> 4:0", + "2:4 -> 5:4", + "2:4 -> 6:8", + "2:24 -> 7:4", + "2:24 -> 8:0", + "2:4 -> 9:0", + "2:4 -> 10:4", + "2:4 -> 11:8", + "2:24 -> 12:4", + "2:24 -> 13:0", + "2:4 -> 14:0", + "2:4 -> 15:4", + "2:4 -> 16:8", + "2:24 -> 17:4", + "2:24 -> 18:0", + "2:4 -> 19:0", + "2:4 -> 20:4", + "2:4 -> 21:8", + "2:24 -> 22:4", + "2:24 -> 23:0", + "2:4 -> 24:0", + "2:4 -> 25:4", + "2:4 -> 26:8", + "2:24 -> 27:4", + "2:24 -> 28:0", +] +`; + +exports[`preflight + base have source maps 1`] = ` +Array [ + "2:4 -> 1:0", + "2:18-4 -> 3:1-2", + "2:18 -> 6:1", + "2:4 -> 8:0", + "2:4-18 -> 11:2-32", + "2:4-18 -> 12:2-25", + "2:4-18 -> 13:2-29", + "2:4-18 -> 14:2-31", + "2:18 -> 15:0", + "2:4 -> 17:0", + "2:4-18 -> 19:2-18", + "2:18 -> 20:0", + "2:4 -> 22:0", + "2:18 -> 27:1", + "2:4 -> 29:0", + "2:4-18 -> 30:2-26", + "2:4-18 -> 31:2-40", + "2:4-18 -> 32:2-26", + "2:4-18 -> 33:2-21", + "2:4-18 -> 34:2-230", + "2:18 -> 35:0", + "2:4 -> 37:0", + "2:18 -> 40:1", + "2:4 -> 42:0", + "2:4-18 -> 43:2-19", + "2:4-18 -> 44:2-30", + "2:18 -> 45:0", + "2:4 -> 47:0", + "2:18 -> 51:1", + "2:4 -> 53:0", + "2:4-18 -> 54:2-19", + "2:4-18 -> 55:2-24", + "2:4-18 -> 56:2-31", + "2:18 -> 57:0", + "2:4 -> 59:0", + "2:18 -> 61:1", + "2:4 -> 63:0", + "2:4-18 -> 64:2-35", + "2:18 -> 65:0", + "2:4 -> 67:0", + "2:18 -> 69:1", + "2:4 -> 71:0", + "2:4-18 -> 77:2-20", + "2:4-18 -> 78:2-22", + "2:18 -> 79:0", + "2:4 -> 81:0", + "2:18 -> 83:1", + "2:4 -> 85:0", + "2:4-18 -> 86:2-16", + "2:4-18 -> 87:2-26", + "2:18 -> 88:0", + "2:4 -> 90:0", + "2:18 -> 92:1", + "2:4 -> 94:0", + "2:4-18 -> 96:2-21", + "2:18 -> 97:0", + "2:4 -> 99:0", + "2:18 -> 102:1", + "2:4 -> 104:0", + "2:4-18 -> 108:2-121", + "2:4-18 -> 109:2-24", + "2:18 -> 110:0", + "2:4 -> 112:0", + "2:18 -> 114:1", + "2:4 -> 116:0", + "2:4-18 -> 117:2-16", + "2:18 -> 118:0", + "2:4 -> 120:0", + "2:18 -> 122:1", + "2:4 -> 124:0", + "2:4-18 -> 126:2-16", + "2:4-18 -> 127:2-16", + "2:4-18 -> 128:2-20", + "2:4-18 -> 129:2-26", + "2:18 -> 130:0", + "2:4 -> 132:0", + "2:4-18 -> 133:2-17", + "2:18 -> 134:0", + "2:4 -> 136:0", + "2:4-18 -> 137:2-13", + "2:18 -> 138:0", + "2:4 -> 140:0", + "2:18 -> 144:1", + "2:4 -> 146:0", + "2:4-18 -> 147:2-24", + "2:4-18 -> 148:2-31", + "2:4-18 -> 149:2-35", + "2:18 -> 150:0", + "2:4 -> 152:0", + "2:18 -> 156:1", + "2:4 -> 158:0", + "2:4-18 -> 163:2-30", + "2:4-18 -> 164:2-25", + "2:4-18 -> 165:2-30", + "2:4-18 -> 166:2-24", + "2:4-18 -> 167:2-19", + "2:4-18 -> 168:2-20", + "2:18 -> 169:0", + "2:4 -> 171:0", + "2:18 -> 173:1", + "2:4 -> 175:0", + "2:4-18 -> 177:2-22", + "2:18 -> 178:0", + "2:4 -> 180:0", + "2:18 -> 183:1", + "2:4 -> 185:0", + "2:4-18 -> 189:2-36", + "2:4-18 -> 190:2-39", + "2:4-18 -> 191:2-32", + "2:18 -> 192:0", + "2:4 -> 194:0", + "2:18 -> 196:1", + "2:4 -> 198:0", + "2:4-18 -> 199:2-15", + "2:18 -> 200:0", + "2:4 -> 202:0", + "2:18 -> 204:1", + "2:4 -> 206:0", + "2:4-18 -> 207:2-18", + "2:18 -> 208:0", + "2:4 -> 210:0", + "2:18 -> 212:1", + "2:4 -> 214:0", + "2:4-18 -> 215:2-26", + "2:18 -> 216:0", + "2:4 -> 218:0", + "2:18 -> 220:1", + "2:4 -> 222:0", + "2:4-18 -> 224:2-14", + "2:18 -> 225:0", + "2:4 -> 227:0", + "2:18 -> 230:1", + "2:4 -> 232:0", + "2:4-18 -> 233:2-39", + "2:4-18 -> 234:2-30", + "2:18 -> 235:0", + "2:4 -> 237:0", + "2:18 -> 239:1", + "2:4 -> 241:0", + "2:4-18 -> 242:2-26", + "2:18 -> 243:0", + "2:4 -> 245:0", + "2:18 -> 248:1", + "2:4 -> 250:0", + "2:4-18 -> 251:2-36", + "2:4-18 -> 252:2-23", + "2:18 -> 253:0", + "2:4 -> 255:0", + "2:18 -> 257:1", + "2:4 -> 259:0", + "2:4-18 -> 260:2-20", + "2:18 -> 261:0", + "2:4 -> 263:0", + "2:18 -> 265:1", + "2:4 -> 267:0", + "2:4-18 -> 280:2-11", + "2:18 -> 281:0", + "2:4 -> 283:0", + "2:4-18 -> 284:2-11", + "2:4-18 -> 285:2-12", + "2:18 -> 286:0", + "2:4 -> 288:0", + "2:4-18 -> 289:2-12", + "2:18 -> 290:0", + "2:4 -> 292:0", + "2:4-18 -> 295:2-18", + "2:4-18 -> 296:2-11", + "2:4-18 -> 297:2-12", + "2:18 -> 298:0", + "2:4 -> 300:0", + "2:18 -> 302:1", + "2:4 -> 304:0", + "2:4-18 -> 305:2-18", + "2:18 -> 306:0", + "2:4 -> 308:0", + "2:18 -> 311:1", + "2:4 -> 313:0", + "2:4-18 -> 315:2-20", + "2:4-18 -> 316:2-24", + "2:18 -> 317:0", + "2:4 -> 319:0", + "2:18 -> 321:1", + "2:4 -> 323:0", + "2:4-18 -> 325:2-17", + "2:18 -> 326:0", + "2:4 -> 328:0", + "2:18 -> 330:1", + "2:4 -> 331:0", + "2:4-18 -> 332:2-17", + "2:18 -> 333:0", + "2:4 -> 335:0", + "2:18 -> 339:1", + "2:4 -> 341:0", + "2:4-18 -> 349:2-24", + "2:4-18 -> 350:2-32", + "2:18 -> 351:0", + "2:4 -> 353:0", + "2:18 -> 355:1", + "2:4 -> 357:0", + "2:4-18 -> 359:2-17", + "2:4-18 -> 360:2-14", + "2:18 -> 361:0", + "2:4 -> 363:0", + "2:18 -> 365:1", + "2:4 -> 367:0", + "2:4-18 -> 368:2-15", + "2:18 -> 369:0", + "2:4 -> 371:0", + "2:4-18 -> 372:2-26", + "2:4-18 -> 373:2-26", + "2:4-18 -> 374:2-21", + "2:4-18 -> 375:2-21", + "2:4-18 -> 376:2-16", + "2:4-18 -> 377:2-16", + "2:4-18 -> 378:2-16", + "2:4-18 -> 379:2-17", + "2:4-18 -> 380:2-17", + "2:4-18 -> 381:2-15", + "2:4-18 -> 382:2-15", + "2:4-18 -> 383:2-20", + "2:4-18 -> 384:2-40", + "2:4-18 -> 385:2-17", + "2:4-18 -> 386:2-22", + "2:4-18 -> 387:2-24", + "2:4-18 -> 388:2-25", + "2:4-18 -> 389:2-26", + "2:4-18 -> 390:2-20", + "2:4-18 -> 391:2-29", + "2:4-18 -> 392:2-30", + "2:4-18 -> 393:2-40", + "2:4-18 -> 394:2-36", + "2:4-18 -> 395:2-29", + "2:4-18 -> 396:2-24", + "2:4-18 -> 397:2-32", + "2:4-18 -> 398:2-14", + "2:4-18 -> 399:2-20", + "2:4-18 -> 400:2-18", + "2:4-18 -> 401:2-19", + "2:4-18 -> 402:2-20", + "2:4-18 -> 403:2-16", + "2:4-18 -> 404:2-18", + "2:4-18 -> 405:2-15", + "2:4-18 -> 406:2-21", + "2:4-18 -> 407:2-23", + "2:4-18 -> 408:2-29", + "2:4-18 -> 409:2-27", + "2:4-18 -> 410:2-28", + "2:4-18 -> 411:2-29", + "2:4-18 -> 412:2-25", + "2:4-18 -> 413:2-26", + "2:4-18 -> 414:2-27", + "2:4 -> 415:2", + "2:18 -> 416:0", +] +`; diff --git a/tests/basic-usage.test.css b/tests/basic-usage.test.css --- a/tests/basic-usage.test.css +++ b/tests/basic-usage.test.css @@ -1,6 +1,8 @@ *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; @@ -252,6 +254,19 @@ .border-collapse { border-collapse: collapse; } +.border-spacing-4 { + --tw-border-spacing-x: 1rem; + --tw-border-spacing-y: 1rem; + border-spacing: var(--tw-border-spacing-x) var(--tw-border-spacing-y); +} +.border-spacing-x-6 { + --tw-border-spacing-x: 1.5rem; + border-spacing: var(--tw-border-spacing-x) var(--tw-border-spacing-y); +} +.border-spacing-y-8 { + --tw-border-spacing-y: 2rem; + border-spacing: var(--tw-border-spacing-x) var(--tw-border-spacing-y); +} .origin-top-right { transform-origin: top right; } diff --git a/tests/basic-usage.test.html b/tests/basic-usage.test.html --- a/tests/basic-usage.test.html +++ b/tests/basic-usage.test.html @@ -25,6 +25,7 @@ <div class="bg-cover"></div> <div class="bg-origin-border bg-origin-padding bg-origin-content"></div> <div class="border-collapse"></div> + <div class="border-spacing-4 border-spacing-x-6 border-spacing-y-8"></div> <div class="border-black border-t-black border-r-black border-b-black border-l-black border-x-black border-y-black"></div> <div class="border-opacity-10"></div> <div class="rounded-md"></div> diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -152,6 +152,8 @@ test('default ring color can be a function', () => { *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/collapse-adjacent-rules.test.css b/tests/collapse-adjacent-rules.test.css --- a/tests/collapse-adjacent-rules.test.css +++ b/tests/collapse-adjacent-rules.test.css @@ -10,6 +10,8 @@ *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/import-syntax.test.css b/tests/import-syntax.test.css --- a/tests/import-syntax.test.css +++ b/tests/import-syntax.test.css @@ -4,6 +4,8 @@ h1 { *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/important-boolean.test.css b/tests/important-boolean.test.css --- a/tests/important-boolean.test.css +++ b/tests/important-boolean.test.css @@ -1,6 +1,8 @@ *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/important-modifier-prefix.test.css b/tests/important-modifier-prefix.test.css --- a/tests/important-modifier-prefix.test.css +++ b/tests/important-modifier-prefix.test.css @@ -1,6 +1,8 @@ *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/important-selector.test.css b/tests/important-selector.test.css --- a/tests/important-selector.test.css +++ b/tests/important-selector.test.css @@ -1,6 +1,8 @@ *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/kitchen-sink.test.css b/tests/kitchen-sink.test.css --- a/tests/kitchen-sink.test.css +++ b/tests/kitchen-sink.test.css @@ -139,6 +139,8 @@ div { *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/plugins/divide.test.js b/tests/plugins/divide.test.js --- a/tests/plugins/divide.test.js +++ b/tests/plugins/divide.test.js @@ -11,6 +11,8 @@ it('should add the divide styles for divide-y and a default border color', () => *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; @@ -75,6 +77,8 @@ it('should add the divide styles for divide-x and a default border color', () => *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; @@ -139,6 +143,8 @@ it('should add the divide styles for divide-y-reverse and a default border color *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; @@ -201,6 +207,8 @@ it('should add the divide styles for divide-x-reverse and a default border color *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; @@ -263,6 +271,8 @@ it('should only inject the base styles once if we use divide and border at the s *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/prefix.test.css b/tests/prefix.test.css --- a/tests/prefix.test.css +++ b/tests/prefix.test.css @@ -1,6 +1,8 @@ *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/source-maps.test.js b/tests/source-maps.test.js --- a/tests/source-maps.test.js +++ b/tests/source-maps.test.js @@ -40,28 +40,7 @@ it('apply generates source maps', async () => { expect(sources.length).toBe(1) // It would make the tests nicer to read and write - expect(annotations).toStrictEqual([ - '2:4 -> 2:4', - '3:6-27 -> 3:6-27', - '4:6-33 -> 4:6-18', - '4:6-33 -> 5:6-17', - '4:6-33 -> 6:6-24', - '4:6-33 -> 7:6-61', - '5:4 -> 8:4', - '7:4 -> 10:4', - '8:6-39 -> 11:6-39', - '9:6-31 -> 12:6-18', - '9:6-31 -> 13:6-17', - '9:6-31 -> 14:6-24', - '9:6-31 -> 15:6-61', - '10:4 -> 16:4', - '13:6 -> 18:4', - '13:6-29 -> 19:6-18', - '13:6-29 -> 20:6-17', - '13:6-29 -> 21:6-24', - '13:6 -> 22:6', - '13:29 -> 23:0', - ]) + expect(annotations).toMatchSnapshot() }) it('preflight + base have source maps', async () => { @@ -82,259 +61,7 @@ it('preflight + base have source maps', async () => { expect(sources.length).toBe(1) // It would make the tests nicer to read and write - expect(annotations).toStrictEqual([ - '2:4 -> 1:0', - '2:18-4 -> 3:1-2', - '2:18 -> 6:1', - '2:4 -> 8:0', - '2:4-18 -> 11:2-32', - '2:4-18 -> 12:2-25', - '2:4-18 -> 13:2-29', - '2:4-18 -> 14:2-31', - '2:18 -> 15:0', - '2:4 -> 17:0', - '2:4-18 -> 19:2-18', - '2:18 -> 20:0', - '2:4 -> 22:0', - '2:18 -> 27:1', - '2:4 -> 29:0', - '2:4-18 -> 30:2-26', - '2:4-18 -> 31:2-40', - '2:4-18 -> 32:2-26', - '2:4-18 -> 33:2-21', - '2:4-18 -> 34:2-230', - '2:18 -> 35:0', - '2:4 -> 37:0', - '2:18 -> 40:1', - '2:4 -> 42:0', - '2:4-18 -> 43:2-19', - '2:4-18 -> 44:2-30', - '2:18 -> 45:0', - '2:4 -> 47:0', - '2:18 -> 51:1', - '2:4 -> 53:0', - '2:4-18 -> 54:2-19', - '2:4-18 -> 55:2-24', - '2:4-18 -> 56:2-31', - '2:18 -> 57:0', - '2:4 -> 59:0', - '2:18 -> 61:1', - '2:4 -> 63:0', - '2:4-18 -> 64:2-35', - '2:18 -> 65:0', - '2:4 -> 67:0', - '2:18 -> 69:1', - '2:4 -> 71:0', - '2:4-18 -> 77:2-20', - '2:4-18 -> 78:2-22', - '2:18 -> 79:0', - '2:4 -> 81:0', - '2:18 -> 83:1', - '2:4 -> 85:0', - '2:4-18 -> 86:2-16', - '2:4-18 -> 87:2-26', - '2:18 -> 88:0', - '2:4 -> 90:0', - '2:18 -> 92:1', - '2:4 -> 94:0', - '2:4-18 -> 96:2-21', - '2:18 -> 97:0', - '2:4 -> 99:0', - '2:18 -> 102:1', - '2:4 -> 104:0', - '2:4-18 -> 108:2-121', - '2:4-18 -> 109:2-24', - '2:18 -> 110:0', - '2:4 -> 112:0', - '2:18 -> 114:1', - '2:4 -> 116:0', - '2:4-18 -> 117:2-16', - '2:18 -> 118:0', - '2:4 -> 120:0', - '2:18 -> 122:1', - '2:4 -> 124:0', - '2:4-18 -> 126:2-16', - '2:4-18 -> 127:2-16', - '2:4-18 -> 128:2-20', - '2:4-18 -> 129:2-26', - '2:18 -> 130:0', - '2:4 -> 132:0', - '2:4-18 -> 133:2-17', - '2:18 -> 134:0', - '2:4 -> 136:0', - '2:4-18 -> 137:2-13', - '2:18 -> 138:0', - '2:4 -> 140:0', - '2:18 -> 144:1', - '2:4 -> 146:0', - '2:4-18 -> 147:2-24', - '2:4-18 -> 148:2-31', - '2:4-18 -> 149:2-35', - '2:18 -> 150:0', - '2:4 -> 152:0', - '2:18 -> 156:1', - '2:4 -> 158:0', - '2:4-18 -> 163:2-30', - '2:4-18 -> 164:2-25', - '2:4-18 -> 165:2-30', - '2:4-18 -> 166:2-24', - '2:4-18 -> 167:2-19', - '2:4-18 -> 168:2-20', - '2:18 -> 169:0', - '2:4 -> 171:0', - '2:18 -> 173:1', - '2:4 -> 175:0', - '2:4-18 -> 177:2-22', - '2:18 -> 178:0', - '2:4 -> 180:0', - '2:18 -> 183:1', - '2:4 -> 185:0', - '2:4-18 -> 189:2-36', - '2:4-18 -> 190:2-39', - '2:4-18 -> 191:2-32', - '2:18 -> 192:0', - '2:4 -> 194:0', - '2:18 -> 196:1', - '2:4 -> 198:0', - '2:4-18 -> 199:2-15', - '2:18 -> 200:0', - '2:4 -> 202:0', - '2:18 -> 204:1', - '2:4 -> 206:0', - '2:4-18 -> 207:2-18', - '2:18 -> 208:0', - '2:4 -> 210:0', - '2:18 -> 212:1', - '2:4 -> 214:0', - '2:4-18 -> 215:2-26', - '2:18 -> 216:0', - '2:4 -> 218:0', - '2:18 -> 220:1', - '2:4 -> 222:0', - '2:4-18 -> 224:2-14', - '2:18 -> 225:0', - '2:4 -> 227:0', - '2:18 -> 230:1', - '2:4 -> 232:0', - '2:4-18 -> 233:2-39', - '2:4-18 -> 234:2-30', - '2:18 -> 235:0', - '2:4 -> 237:0', - '2:18 -> 239:1', - '2:4 -> 241:0', - '2:4-18 -> 242:2-26', - '2:18 -> 243:0', - '2:4 -> 245:0', - '2:18 -> 248:1', - '2:4 -> 250:0', - '2:4-18 -> 251:2-36', - '2:4-18 -> 252:2-23', - '2:18 -> 253:0', - '2:4 -> 255:0', - '2:18 -> 257:1', - '2:4 -> 259:0', - '2:4-18 -> 260:2-20', - '2:18 -> 261:0', - '2:4 -> 263:0', - '2:18 -> 265:1', - '2:4 -> 267:0', - '2:4-18 -> 280:2-11', - '2:18 -> 281:0', - '2:4 -> 283:0', - '2:4-18 -> 284:2-11', - '2:4-18 -> 285:2-12', - '2:18 -> 286:0', - '2:4 -> 288:0', - '2:4-18 -> 289:2-12', - '2:18 -> 290:0', - '2:4 -> 292:0', - '2:4-18 -> 295:2-18', - '2:4-18 -> 296:2-11', - '2:4-18 -> 297:2-12', - '2:18 -> 298:0', - '2:4 -> 300:0', - '2:18 -> 302:1', - '2:4 -> 304:0', - '2:4-18 -> 305:2-18', - '2:18 -> 306:0', - '2:4 -> 308:0', - '2:18 -> 311:1', - '2:4 -> 313:0', - '2:4-18 -> 315:2-20', - '2:4-18 -> 316:2-24', - '2:18 -> 317:0', - '2:4 -> 319:0', - '2:18 -> 321:1', - '2:4 -> 323:0', - '2:4-18 -> 325:2-17', - '2:18 -> 326:0', - '2:4 -> 328:0', - '2:18 -> 330:1', - '2:4 -> 331:0', - '2:4-18 -> 332:2-17', - '2:18 -> 333:0', - '2:4 -> 335:0', - '2:18 -> 339:1', - '2:4 -> 341:0', - '2:4-18 -> 349:2-24', - '2:4-18 -> 350:2-32', - '2:18 -> 351:0', - '2:4 -> 353:0', - '2:18 -> 355:1', - '2:4 -> 357:0', - '2:4-18 -> 359:2-17', - '2:4-18 -> 360:2-14', - '2:18 -> 361:0', - '2:4 -> 363:0', - '2:18 -> 365:1', - '2:4 -> 367:0', - '2:4-18 -> 368:2-15', - '2:18 -> 369:0', - '2:4 -> 371:0', - '2:4-18 -> 372:2-21', - '2:4-18 -> 373:2-21', - '2:4-18 -> 374:2-16', - '2:4-18 -> 375:2-16', - '2:4-18 -> 376:2-16', - '2:4-18 -> 377:2-17', - '2:4-18 -> 378:2-17', - '2:4-18 -> 379:2-15', - '2:4-18 -> 380:2-15', - '2:4-18 -> 381:2-20', - '2:4-18 -> 382:2-40', - '2:4-18 -> 383:2-17', - '2:4-18 -> 384:2-22', - '2:4-18 -> 385:2-24', - '2:4-18 -> 386:2-25', - '2:4-18 -> 387:2-26', - '2:4-18 -> 388:2-20', - '2:4-18 -> 389:2-29', - '2:4-18 -> 390:2-30', - '2:4-18 -> 391:2-40', - '2:4-18 -> 392:2-36', - '2:4-18 -> 393:2-29', - '2:4-18 -> 394:2-24', - '2:4-18 -> 395:2-32', - '2:4-18 -> 396:2-14', - '2:4-18 -> 397:2-20', - '2:4-18 -> 398:2-18', - '2:4-18 -> 399:2-19', - '2:4-18 -> 400:2-20', - '2:4-18 -> 401:2-16', - '2:4-18 -> 402:2-18', - '2:4-18 -> 403:2-15', - '2:4-18 -> 404:2-21', - '2:4-18 -> 405:2-23', - '2:4-18 -> 406:2-29', - '2:4-18 -> 407:2-27', - '2:4-18 -> 408:2-28', - '2:4-18 -> 409:2-29', - '2:4-18 -> 410:2-25', - '2:4-18 -> 411:2-26', - '2:4-18 -> 412:2-27', - '2:4 -> 413:2', - '2:18 -> 414:0', - ]) + expect(annotations).toMatchSnapshot() }) it('utilities have source maps', async () => { @@ -376,34 +103,5 @@ it('components have source maps', async () => { expect(sources.length).toBe(1) // It would make the tests nicer to read and write - expect(annotations).toStrictEqual([ - '2:4 -> 1:0', - '2:4 -> 2:4', - '2:24 -> 3:0', - '2:4 -> 4:0', - '2:4 -> 5:4', - '2:4 -> 6:8', - '2:24 -> 7:4', - '2:24 -> 8:0', - '2:4 -> 9:0', - '2:4 -> 10:4', - '2:4 -> 11:8', - '2:24 -> 12:4', - '2:24 -> 13:0', - '2:4 -> 14:0', - '2:4 -> 15:4', - '2:4 -> 16:8', - '2:24 -> 17:4', - '2:24 -> 18:0', - '2:4 -> 19:0', - '2:4 -> 20:4', - '2:4 -> 21:8', - '2:24 -> 22:4', - '2:24 -> 23:0', - '2:4 -> 24:0', - '2:4 -> 25:4', - '2:4 -> 26:8', - '2:24 -> 27:4', - '2:24 -> 28:0', - ]) + expect(annotations).toMatchSnapshot() }) diff --git a/tests/util/defaults.js b/tests/util/defaults.js --- a/tests/util/defaults.js +++ b/tests/util/defaults.js @@ -10,6 +10,8 @@ export function defaults({ defaultRingColor = `rgb(59 130 246 / 0.5)` } = {}) { *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; diff --git a/tests/variants.test.css b/tests/variants.test.css --- a/tests/variants.test.css +++ b/tests/variants.test.css @@ -1,6 +1,8 @@ *, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0;
Border Spacing Hey, I just wanted to ask if something related to "border-spacing" is planed? The default table layout does include `border-spacing: 2px` which is kind of annoying since I wanted to add a bottom border after the table head. With border-spacing 2: ![bildschirmfoto 2018-02-09 um 23 37 21](https://user-images.githubusercontent.com/15618191/36053507-34513eb6-0df2-11e8-9f3a-3c17e96d8c89.png) With border-spacing 0: ![bildschirmfoto 2018-02-09 um 23 37 51](https://user-images.githubusercontent.com/15618191/36053530-46238176-0df2-11e8-8101-390743bca782.png) See also: https://www.w3schools.com/cssref/pr_border-spacing.asp Have a nice day, Jordan
+1 Default Border Spacing is a problem. You cannot add a continuous background color to tables because of this. See http://jsbin.com/soxeqat/edit?html,output We're planning to add some table related utilities in the near future but in the mean time you can easily add your own utilities: https://tailwindcss.com/docs/adding-new-utilities Looking at getting some of this stuff added soon but quick question, do you actually want `border-spacing: 0` or do you just need `border-collapse: collapse`? It would be nice to avoid adding another scale to the config file for border spacing if people really just care about removing border spacing altogether. For the continuous background color problem, `border-collapse: collapse` would be enough of a solution. See: http://jsbin.com/culebiluca/2 @adamwathan Yeah `border-collapse: collapse` should be enough. I didn't knew about this css "command". We have border collapse utilities now as of v0.6.0 πŸ‘ There is an edge case where `border-collapse` does not work: it does not allow you to apply a continuous _rounded_ border to a table element. - One option as detailed in [this Stack Overflow](https://stackoverflow.com/questions/628301/css3s-border-radius-property-and-border-collapsecollapse-dont-mix-how-can-i) is to use `border-collapse` and apply styles to the last and first `td` child of the last and first `tr` children. - The other options is to apply `border-spacing: 0;` and use `border-separate`. **Are there any plans to add support for changing `border-spacing` to tailwind?** I have a table, with: - a right border of the first column - and a border of the table head (first row or th tag) These borders are supposed to be sticky when scrolling on the x- and y-axis. This case just works with `border-separate` but here the default is `border-spacing: 2px`. For a cleaner look I would need a `border-spacing: 0px`... So, any progress regarding the question above? **"Are there any plans to add support for changing border-spacing"** Seem like adding your own utility is your best bet for now. With JIT enabled, it'll be nice to see this added to the core library @adamwathan ``` @layer utilities { .border-spacing-0 { border-spacing: 0; } } ``` I'm also in need of this. I think this should be included in Tailwind's stock utilities.
"2022-01-17T18:43:53Z"
3.0
[]
[ "tests/source-maps.test.js", "tests/plugins/divide.test.js", "tests/basic-usage.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/15618191/36053507-34513eb6-0df2-11e8-9f3a-3c17e96d8c89.png", "https://user-images.githubusercontent.com/15618191/36053530-46238176-0df2-11e8-8101-390743bca782.png" ]
[]
tailwindlabs/tailwindcss
7,163
tailwindlabs__tailwindcss-7163
[ "7149" ]
10103d8bafdb401da417fd13b19dd426f612340f
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -3,6 +3,7 @@ import * as path from 'path' import postcss from 'postcss' import createUtilityPlugin from './util/createUtilityPlugin' import buildMediaQuery from './util/buildMediaQuery' +import escapeClassName from './util/escapeClassName' import parseAnimationValue from './util/parseAnimationValue' import flattenColorPalette from './util/flattenColorPalette' import withAlphaVariable, { withAlphaValue } from './util/withAlphaVariable' @@ -612,8 +613,8 @@ export let corePlugins = { }) }, - animation: ({ matchUtilities, theme, prefix }) => { - let prefixName = (name) => prefix(`.${name}`).slice(1) + animation: ({ matchUtilities, theme, config }) => { + let prefixName = (name) => `${config('prefix')}${escapeClassName(name)}` let keyframes = Object.fromEntries( Object.entries(theme('keyframes') ?? {}).map(([key, value]) => { return [key, { [`@keyframes ${prefixName(key)}`]: value }]
diff --git a/tests/animations.test.js b/tests/animations.test.js --- a/tests/animations.test.js +++ b/tests/animations.test.js @@ -181,3 +181,96 @@ test('multiple custom', () => { `) }) }) + +test('with dots in the name', () => { + let config = { + content: [ + { + raw: html` + <div class="animate-zoom-.5"></div> + <div class="animate-zoom-1.5"></div> + `, + }, + ], + theme: { + extend: { + keyframes: { + 'zoom-.5': { to: { transform: 'scale(0.5)' } }, + 'zoom-1.5': { to: { transform: 'scale(1.5)' } }, + }, + animation: { + 'zoom-.5': 'zoom-.5 2s', + 'zoom-1.5': 'zoom-1.5 2s', + }, + }, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + @keyframes zoom-\.5 { + to { + transform: scale(0.5); + } + } + .animate-zoom-\.5 { + animation: zoom-\.5 2s; + } + @keyframes zoom-1\.5 { + to { + transform: scale(1.5); + } + } + .animate-zoom-1\.5 { + animation: zoom-1\.5 2s; + } + `) + }) +}) + +test('with dots in the name and prefix', () => { + let config = { + prefix: 'tw-', + content: [ + { + raw: html` + <div class="tw-animate-zoom-.5"></div> + <div class="tw-animate-zoom-1.5"></div> + `, + }, + ], + theme: { + extend: { + keyframes: { + 'zoom-.5': { to: { transform: 'scale(0.5)' } }, + 'zoom-1.5': { to: { transform: 'scale(1.5)' } }, + }, + animation: { + 'zoom-.5': 'zoom-.5 2s', + 'zoom-1.5': 'zoom-1.5 2s', + }, + }, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + @keyframes tw-zoom-\.5 { + to { + transform: scale(0.5); + } + } + .tw-animate-zoom-\.5 { + animation: tw-zoom-\.5 2s; + } + @keyframes tw-zoom-1\.5 { + to { + transform: scale(1.5); + } + } + .tw-animate-zoom-1\.5 { + animation: tw-zoom-1\.5 2s; + } + `) + }) +})
Wrong keyframe keys when generationg CSS classes with JS <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** For example: v3.0.15 **What build tool (or framework if it abstracts the build tool) are you using?** postcss-cli 9.1.0, vite 2.7.13 **What version of Node.js are you using?** 16.13.2 **What browser are you using?** Firefox **What operating system are you using?** Ubuntu 20.04 **Reproduction URL** https://github.com/Mastercuber/tailwindcss-minimal-example **Describe your issue** In the config file `tailwind.config.js` I'm generating some animations with floating point numbers in the class name like [this](https://github.com/Mastercuber/tailwindcss-minimal-example/blob/a7c9450525434893077c03cb91754295f4cbea83/tailwind.config.js#L14). The generated animation classes looks good, but the `@keyframe` directives have a different value than the animation classes itself, though the exact same key is used for both. The used class in the App is `animate-zoom-2.5` to actually see it in the output and the generated css is [here](https://github.com/Mastercuber/tailwindcss-minimal-example/blob/a7c9450525434893077c03cb91754295f4cbea83/test.css#L427) Now I just use another key for the keyframe name.
Hey, @Mastercuber. What you're seeing there isn't the "wrong key" per se. Tailwind is mistakenly trying to prefix the "." in your animation value and keyframe name when it should instead be escaping them and then prefixing. I will send the Tailwind team a PR to address this.
"2022-01-22T01:00:18Z"
3.0
[]
[ "tests/animations.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
7,289
tailwindlabs__tailwindcss-7289
[ "7178" ]
dab8b046ea862a54ba3f646bfcbd059ef1335e74
diff --git a/src/util/parseBoxShadowValue.js b/src/util/parseBoxShadowValue.js --- a/src/util/parseBoxShadowValue.js +++ b/src/util/parseBoxShadowValue.js @@ -1,7 +1,7 @@ let KEYWORDS = new Set(['inset', 'inherit', 'initial', 'revert', 'unset']) let COMMA = /\,(?![^(]*\))/g // Comma separator that is not located between brackets. E.g.: `cubiz-bezier(a, b, c)` these don't count. let SPACE = /\ +(?![^(]*\))/g // Similar to the one above, but with spaces instead. -let LENGTH = /^-?(\d+)(.*?)$/g +let LENGTH = /^-?(\d+|\.\d+)(.*?)$/g export function parseBoxShadowValue(input) { let shadows = input.split(COMMA)
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -137,3 +137,38 @@ it('fasly config values still work', () => { `) }) }) + +it('shadows support values without a leading zero', () => { + let config = { + content: [{ raw: html`<div class="shadow-one shadow-two"></div>` }], + theme: { + boxShadow: { + one: '0.5rem 0.5rem 0.5rem #0005', + two: '.5rem .5rem .5rem #0005', + }, + }, + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .shadow-one { + --tw-shadow: 0.5rem 0.5rem 0.5rem #0005; + --tw-shadow-colored: 0.5rem 0.5rem 0.5rem var(--tw-shadow-color); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); + } + .shadow-two { + --tw-shadow: 0.5rem 0.5rem 0.5rem #0005; + --tw-shadow-colored: 0.5rem 0.5rem 0.5rem var(--tw-shadow-color); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); + } + `) + }) +})
Units without leading 0s causes shadow color to not work. **What version of Tailwind CSS are you using?** 3.0.14 **What build tool (or framework if it abstracts the build tool) are you using?** Play **What version of Node.js are you using?** N/A **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/sgiL9df2gw?file=config **Describe your issue** When using a value without a leading 0 for a box shadow the color won't be changed. I took a shot at rewriting `parseBoxShadowValue` to get it to work because it seemed like a fun one to play around with. Ran the tests and it all passed. Didn't want to create a PR incase you had quicker, better fixes. ```js let KEYWORDS = ['inset', 'inherit', 'initial', 'revert', 'unset'] let COMMA = /\,(?![^(]*\))/g // Comma separator that is not located between brackets. E.g.: `cubiz-bezier(a, b, c)` these don't count. let SPACE = /\ +(?![^(]*\))/g // Similar to the one above, but with spaces instead. function parseBoxShadowValue (input) { let shadows = input.split(COMMA) return shadows.map(shadow => { let value = shadow.trim() let parts = value.split(SPACE) let output = { raw: value, valid: true } // A box-shadow requires at least 3 parts. if (parts.length < 3) { output.valid = false return output } // The color is always at the end, also a color can't start with a number or a . if (/^[\d.]/.test(parts[parts.length - 1])) { output.valid = false return output } if (KEYWORDS.includes(parts[0])) { output.keyword = parts.shift() } output.color = parts.pop() output.x = parts.shift() output.y = parts.shift() output.blur = parts.shift() output.spread = parts.shift() output.unknown = parts return output }) } ```
"2022-02-01T16:47:23Z"
3.0
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/sgiL9df2gw?file=config" ]
tailwindlabs/tailwindcss
7,291
tailwindlabs__tailwindcss-7291
[ "7207" ]
cd8f109981ed64ec78fb70b3091153f45931ff27
diff --git a/src/index.js b/src/index.js --- a/src/index.js +++ b/src/index.js @@ -13,7 +13,21 @@ module.exports = function tailwindcss(configOrPath) { return root }, function (root, result) { - processTailwindFeatures(setupTrackingContext(configOrPath))(root, result) + let context = setupTrackingContext(configOrPath) + + if (root.type === 'document') { + let roots = root.nodes.filter((node) => node.type === 'root') + + for (const root of roots) { + if (root.type === 'root') { + processTailwindFeatures(context)(root, result) + } + } + + return + } + + processTailwindFeatures(context)(root, result) }, env.DEBUG && function (root) {
diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -1,5 +1,6 @@ import fs from 'fs' import path from 'path' +import postcss from 'postcss' import { run, css, html, defaults } from './util/run' @@ -568,3 +569,37 @@ test('The visited variant removes opacity support', () => { `) }) }) + +it('appends variants to the correct place when using postcss documents', () => { + let config = { + content: [{ raw: html`<div class="underline sm:underline"></div>` }], + plugins: [], + corePlugins: { preflight: false }, + } + + const doc = postcss.document() + doc.append(postcss.parse(`a {}`)) + doc.append(postcss.parse(`@tailwind base`)) + doc.append(postcss.parse(`@tailwind utilities`)) + doc.append(postcss.parse(`b {}`)) + + const result = doc.toResult() + + return run(result, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + a { + } + ${defaults} + .underline { + text-decoration-line: underline; + } + @media (min-width: 640px) { + .sm\:underline { + text-decoration-line: underline; + } + } + b { + } + `) + }) +})
Variant nodes are appended to the document rather than a root **What version of Tailwind CSS are you using?** 3.0.16 **What build tool (or framework if it abstracts the build tool) are you using?** postcss-cli 9.1.0 **What version of Node.js are you using?** 17.x **Reproduction URL** See the reproduction in 43081j/postcss-lit#26 --- postcss recently introduced the concept of a "document". This allows custom syntaxes to be written for it which represent their arbitrary AST as the `document`, containing one or more `Root` nodes which are the actual CSS from said document. For example, CSS in JS solutions would result in a `Document` representing the JS file, and one or more `Root` representing the contained stylesheets. When combined with tailwind, this works like so: - postcss executes the custom syntax against the file, resolving to a postcss-compatible AST - postcss executes tailwind on this AST (`Document { nodes: [Root, Root] }` at this point) Tailwind then executes code like this to replace the at-rules: https://github.com/tailwindlabs/tailwindcss/blob/490c9dcb29bfed72855d701c40a7e04f69b5633b/src/lib/expandTailwindAtRules.js#L206-L209 This works because `layerNode.base.parent` is one of the child `Root` nodes. So by calling `before`, we're prepending child nodes to the `Root`, _not_ the `Document` (GOOD). However, we can then reach this: https://github.com/tailwindlabs/tailwindcss/blob/490c9dcb29bfed72855d701c40a7e04f69b5633b/src/lib/expandTailwindAtRules.js#L239-L241 Which, as you see, will append explicitly to `root`: the `Document` in this case. This will result in an AST like so: ```ts Document { nodes: [ Root, Root, Rule, // BAD NODE! ] } ``` When a custom syntax then attempts to stringify the AST back to the original non-css document, this misplaced `Rule` will be thrown on the end... **causing a syntax error in the output**. ### Solution? I don't know tailwind's source well enough to suggest a solution here. Possibly, if any `layerNodes.*` exists, use its parent as the root. If none exist, fall back to what it does now? Or is there maybe an existing way to explicitly mark where those rules should exist? wherever `layerNodes.variants` comes from. Can we simply put some at-rule like `@tailwindvariants`? Until this is fixed, custom postcss syntaxes can't really work with "variant rules".
``` /** * Use this directive to control where Tailwind injects the hover, focus, * responsive, dark mode, and other variants of each class. * * If omitted, Tailwind will append these classes to the very end of * your stylesheet by default. */ @tailwind variants; ``` @ma-g-ma maybe this is it! and i've just been blind. can you give it a go? add `@tailwind variants` to your source CSS if it is, tailwind people: feel free to close this. we will just have to remember to always define the variants at-rule. i'll also update our syntax's docs @43081j Yep, it works! Both variants are correctly placed. Though it seems that they appear with an invalid pseudo selector e.g. ``` .focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)) } ``` IDE error messsage: > Unknown pseudo selector 'ring-blue-500' Of course, this might be unrelated. awesome. for tailwind maintainers: maybe its still worth warning in these situations? if someone tries to use one of your classes without specifying the at-rule, especially if they have a `Document` node, its probably not their intention to dump it on the end. In those cases it would be useful to have a warning somehow. If they don't have a `Document`, no warning would be needed. @ma-g-ma i'll track it in the other issue we have open and try look into it soon πŸ‘ > @43081j Yep, it works! Both variants are correctly placed. > > Though it seems that they appear with an invalid pseudo selector e.g. > > ``` > .focus\:ring-blue-500:focus { > --tw-ring-opacity: 1; > --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)) > } > ``` > > IDE error messsage: > > > Unknown pseudo selector 'ring-blue-500' > > Of course, this might be unrelated. Just commenting to say that the syntax you mentioned above is correct, as you can check through the W3C CSS Validator. Are you still having that issue? That was a bug in the syntax FYI, backslashes not being escaped in the stringified output (it's in a string so one backslash would be nothing). It has been fixed. I don't think there's necessarily a bug here in tailwind after all. But I do think the behaviour could be improved so the user gets warned when trying to use classes without the associated directive (only if they have a Document in their AST, implying it's a custom syntax).
"2022-02-01T20:06:03Z"
3.0
[]
[ "tests/variants.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
7,295
tailwindlabs__tailwindcss-7295
[ "6861" ]
ab9fd951dd7617442bb38f9fd52541cf1ddeceec
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -63,9 +63,23 @@ function applyPrefix(matches, context) { let [meta] = match if (meta.options.respectPrefix) { let container = postcss.root({ nodes: [match[1].clone()] }) + let classCandidate = match[1].raws.tailwind.classCandidate + container.walkRules((r) => { - r.selector = prefixSelector(context.tailwindConfig.prefix, r.selector) + // If this is a negative utility with a dash *before* the prefix we + // have to ensure that the generated selector matches the candidate + + // Not doing this will cause `-tw-top-1` to generate the class `.tw--top-1` + // The disconnect between candidate <-> class can cause @apply to hard crash. + let shouldPrependNegative = classCandidate.startsWith('-') + + r.selector = prefixSelector( + context.tailwindConfig.prefix, + r.selector, + shouldPrependNegative + ) }) + match[1] = container.nodes[0] } } @@ -371,6 +385,14 @@ function splitWithSeparator(input, separator) { return input.split(new RegExp(`\\${separator}(?![^[]*\\])`, 'g')) } +function* recordCandidates(matches, classCandidate) { + for (const match of matches) { + match[1].raws.tailwind = { classCandidate } + + yield match + } +} + function* resolveMatches(candidate, context) { let separator = context.tailwindConfig.separator let [classCandidate, ...variants] = splitWithSeparator(candidate, separator).reverse() @@ -482,7 +504,9 @@ function* resolveMatches(candidate, context) { continue } - matches = applyPrefix(matches.flat(), context) + matches = matches.flat() + matches = Array.from(recordCandidates(matches, classCandidate)) + matches = applyPrefix(matches, context) if (important) { matches = applyImportant(matches, context) diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -666,17 +666,30 @@ function registerPlugins(plugins, context) { if (checks.length > 0) { let patternMatchingCount = new Map() + let prefixLength = context.tailwindConfig.prefix.length for (let util of classList) { let utils = Array.isArray(util) ? (() => { let [utilName, options] = util - let classes = Object.keys(options?.values ?? {}).map((value) => - formatClass(utilName, value) - ) + let values = Object.keys(options?.values ?? {}) + let classes = values.map((value) => formatClass(utilName, value)) if (options?.supportsNegativeValues) { + // This is the normal negated version + // e.g. `-inset-1` or `-tw-inset-1` classes = [...classes, ...classes.map((cls) => '-' + cls)] + + // This is the negated version *after* the prefix + // e.g. `tw--inset-1` + // The prefix is already attached to util name + // So we add the negative after the prefix + classes = [ + ...classes, + ...classes.map( + (cls) => cls.slice(0, prefixLength) + '-' + cls.slice(prefixLength) + ), + ] } return classes diff --git a/src/util/prefixSelector.js b/src/util/prefixSelector.js --- a/src/util/prefixSelector.js +++ b/src/util/prefixSelector.js @@ -1,12 +1,14 @@ import parser from 'postcss-selector-parser' -import { tap } from './tap' -export default function (prefix, selector) { +export default function (prefix, selector, prependNegative = false) { return parser((selectors) => { selectors.walkClasses((classSelector) => { - tap(classSelector.value, (baseClass) => { - classSelector.value = `${prefix}${baseClass}` - }) + let baseClass = classSelector.value + let shouldPlaceNegativeBeforePrefix = prependNegative && baseClass.startsWith('-') + + classSelector.value = shouldPlaceNegativeBeforePrefix + ? `-${prefix}${baseClass.slice(1)}` + : `${prefix}${baseClass}` }) }).processSync(selector) }
diff --git a/tests/getClassList.test.js b/tests/getClassList.test.js --- a/tests/getClassList.test.js +++ b/tests/getClassList.test.js @@ -5,22 +5,57 @@ it('should generate every possible class, without variants', () => { let config = {} let context = createContext(resolveConfig(config)) - expect(context.getClassList()).toBeInstanceOf(Array) + let classes = context.getClassList() + expect(classes).toBeInstanceOf(Array) // Verify we have a `container` for the 'components' section. - expect(context.getClassList()).toContain('container') + expect(classes).toContain('container') // Verify we handle the DEFAULT case correctly - expect(context.getClassList()).toContain('border') + expect(classes).toContain('border') // Verify we handle negative values correctly - expect(context.getClassList()).toContain('-inset-1/4') - expect(context.getClassList()).toContain('-m-0') - expect(context.getClassList()).not.toContain('-uppercase') - expect(context.getClassList()).not.toContain('-opacity-50') - expect( - createContext( - resolveConfig({ theme: { extend: { margin: { DEFAULT: '5px' } } } }) - ).getClassList() - ).not.toContain('-m-DEFAULT') + expect(classes).toContain('-inset-1/4') + expect(classes).toContain('-m-0') + expect(classes).not.toContain('-uppercase') + expect(classes).not.toContain('-opacity-50') + + config = { theme: { extend: { margin: { DEFAULT: '5px' } } } } + context = createContext(resolveConfig(config)) + classes = context.getClassList() + + expect(classes).not.toContain('-m-DEFAULT') +}) + +it('should generate every possible class while handling negatives and prefixes', () => { + let config = { prefix: 'tw-' } + let context = createContext(resolveConfig(config)) + let classes = context.getClassList() + expect(classes).toBeInstanceOf(Array) + + // Verify we have a `container` for the 'components' section. + expect(classes).toContain('tw-container') + + // Verify we handle the DEFAULT case correctly + expect(classes).toContain('tw-border') + + // Verify we handle negative values correctly + expect(classes).toContain('-tw-inset-1/4') + expect(classes).toContain('-tw-m-0') + expect(classes).not.toContain('-tw-uppercase') + expect(classes).not.toContain('-tw-opacity-50') + + // These utilities do work but there's no reason to generate + // them alongside the `-{prefix}-{utility}` versions + expect(classes).not.toContain('tw--inset-1/4') + expect(classes).not.toContain('tw--m-0') + + config = { + prefix: 'tw-', + theme: { extend: { margin: { DEFAULT: '5px' } } }, + } + context = createContext(resolveConfig(config)) + classes = context.getClassList() + + expect(classes).not.toContain('-tw-m-DEFAULT') }) diff --git a/tests/prefix.test.js b/tests/prefix.test.js --- a/tests/prefix.test.js +++ b/tests/prefix.test.js @@ -1,7 +1,7 @@ import fs from 'fs' import path from 'path' -import { run, css } from './util/run' +import { run, html, css } from './util/run' test('prefix', () => { let config = { @@ -73,3 +73,288 @@ test('prefix', () => { expect(result.css).toMatchFormattedCss(expected) }) }) + +it('negative values: marker before prefix', async () => { + let config = { + prefix: 'tw-', + content: [{ raw: html`<div class="-tw-top-1"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .-tw-top-1 { + top: -0.25rem; + } + `) +}) + +it('negative values: marker after prefix', async () => { + let config = { + prefix: 'tw-', + content: [{ raw: html`<div class="tw--top-1"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .tw--top-1 { + top: -0.25rem; + } + `) +}) + +it('negative values: marker before prefix and arbitrary value', async () => { + let config = { + prefix: 'tw-', + content: [{ raw: html`<div class="-tw-top-[1px]"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .-tw-top-\[1px\] { + top: -1px; + } + `) +}) + +it('negative values: marker after prefix and arbitrary value', async () => { + let config = { + prefix: 'tw-', + content: [{ raw: html`<div class="tw--top-[1px]"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .tw--top-\[1px\] { + top: -1px; + } + `) +}) + +it('negative values: no marker and arbitrary value', async () => { + let config = { + prefix: 'tw-', + content: [{ raw: html`<div class="tw-top-[-1px]"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .tw-top-\[-1px\] { + top: -1px; + } + `) +}) + +it('negative values: variant versions', async () => { + let config = { + prefix: 'tw-', + content: [ + { + raw: html` + <div class="hover:-tw-top-1 hover:tw--top-1"></div> + <div class="hover:-tw-top-[1px] hover:tw--top-[1px]"></div> + <div class="hover:tw-top-[-1px]"></div> + + <!-- this one should not generate anything --> + <div class="-hover:tw-top-1"></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .hover\:-tw-top-1:hover { + top: -0.25rem; + } + .hover\:tw--top-1:hover { + top: -0.25rem; + } + .hover\:-tw-top-\[1px\]:hover { + top: -1px; + } + .hover\:tw--top-\[1px\]:hover { + top: -1px; + } + .hover\:tw-top-\[-1px\]:hover { + top: -1px; + } + `) +}) + +it('negative values: prefix and apply', async () => { + let config = { + prefix: 'tw-', + content: [{ raw: html`` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + + .a { + @apply hover:tw--top-1; + } + .b { + @apply hover:-tw-top-1; + } + .c { + @apply hover:-tw-top-[1px]; + } + .d { + @apply hover:tw--top-[1px]; + } + .e { + @apply hover:tw-top-[-1px]; + } + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .a:hover { + top: -0.25rem; + } + .b:hover { + top: -0.25rem; + } + .c:hover { + top: -1px; + } + .d:hover { + top: -1px; + } + .e:hover { + top: -1px; + } + `) +}) + +it('negative values: prefix in the safelist', async () => { + let config = { + prefix: 'tw-', + safelist: [{ pattern: /-tw-top-1/g }, { pattern: /tw--top-1/g }], + theme: { + inset: { + 1: '0.25rem', + }, + }, + content: [{ raw: html`` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .-tw-top-1 { + top: -0.25rem; + } + .tw--top-1 { + top: -0.25rem; + } + `) +}) + +it('prefix with negative values and variants in the safelist', async () => { + let config = { + prefix: 'tw-', + safelist: [ + { pattern: /-tw-top-1/, variants: ['hover', 'sm:hover'] }, + { pattern: /tw--top-1/, variants: ['hover', 'sm:hover'] }, + ], + theme: { + inset: { + 1: '0.25rem', + }, + }, + content: [{ raw: html`` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + await run(input, config) + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .-tw-top-1 { + top: -0.25rem; + } + .tw--top-1 { + top: -0.25rem; + } + .hover\:-tw-top-1:hover { + top: -0.25rem; + } + + .hover\:tw--top-1:hover { + top: -0.25rem; + } + @media (min-width: 640px) { + .sm\:hover\:-tw-top-1:hover { + top: -0.25rem; + } + .sm\:hover\:tw--top-1:hover { + top: -0.25rem; + } + } + `) +})
Safelisting negative values with a prefix not working <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.0.9 **What build tool (or framework if it abstracts the build tool) are you using?** postcss-cli 9.1.0 tailwindcss-cli **What version of Node.js are you using?** v14.16.1 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/lNapHkRIzf?file=config **Describe your issue** Safelisting negative values with a prefix isn't working. Reproduction URL: https://play.tailwindcss.com/lNapHkRIzf?file=config Config: ```js { prefix: 'tw-', safelist: [ { pattern: /-skew-x-2/, variants: ['hover','focus','md','sm','md:hover','sm:hover','md:focus','sm:focus'], }, ], theme: { extend: { // ... }, }, plugins: [], } ``` Generated safelisted CSS ( no negative value utilities get generated ): ```css .tw-skew-x-2, .hover\:tw-skew-x-2, .focus\:tw-skew-x-2, .sm\:tw-skew-x-2, .sm\:hover\:tw-skew-x-2, .sm\:focus\:tw-skew-x-2, .md\:tw-skew-x-2, .md\:hover\:tw-skew-x-2, .md\:focus\:tw-skew-x-2 { --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-transform: translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .tw-skew-x-2 { --tw-skew-x: 2deg; transform: var(--tw-transform); } .hover\:tw-skew-x-2:hover { --tw-skew-x: 2deg; transform: var(--tw-transform); } .focus\:tw-skew-x-2:focus { --tw-skew-x: 2deg; transform: var(--tw-transform); } @media (min-width: 640px) { .sm\:tw-skew-x-2 { --tw-skew-x: 2deg; transform: var(--tw-transform); } .sm\:hover\:tw-skew-x-2:hover { --tw-skew-x: 2deg; transform: var(--tw-transform); } .sm\:focus\:tw-skew-x-2:focus { --tw-skew-x: 2deg; transform: var(--tw-transform); } } @media (min-width: 768px) { .md\:tw-skew-x-2 { --tw-skew-x: 2deg; transform: var(--tw-transform); } .md\:hover\:tw-skew-x-2:hover { --tw-skew-x: 2deg; transform: var(--tw-transform); } .md\:focus\:tw-skew-x-2:focus { --tw-skew-x: 2deg; transform: var(--tw-transform); } } ```
+1 experiencing a similar issue on the newest update ``` "@tailwindcss/aspect-ratio": "^0.4.0", "@tailwindcss/forms": "^0.4.0", "@tailwindcss/line-clamp": "^0.3.0", "@tailwindcss/typography": "^0.5.0", "@types/tailwindcss": "^3.0.1", ```
"2022-02-01T22:12:38Z"
3.0
[ "tests/getClassList.test.js" ]
[ "tests/prefix.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/lNapHkRIzf?file=config" ]
tailwindlabs/tailwindcss
7,458
tailwindlabs__tailwindcss-7458
[ "7441" ]
0c5af6fed417d7bde2eae133687052eecf19f6f8
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -70,7 +70,28 @@ export let variantPlugins = { 'only-of-type', // State - 'visited', + [ + 'visited', + ({ container }) => { + let toRemove = ['--tw-text-opacity', '--tw-border-opacity', '--tw-bg-opacity'] + + container.walkDecls((decl) => { + if (toRemove.includes(decl.prop)) { + decl.remove() + + return + } + + for (const varName of toRemove) { + if (decl.value.includes(`/ var(${varName})`)) { + decl.value = decl.value.replace(`/ var(${varName})`, '') + } + } + }) + + return ':visited' + }, + ], 'target', ['open', '[open]'], @@ -100,15 +121,27 @@ export let variantPlugins = { ].map((variant) => (Array.isArray(variant) ? variant : [variant, `:${variant}`])) for (let [variantName, state] of pseudoVariants) { - addVariant(variantName, `&${state}`) + addVariant(variantName, (ctx) => { + let result = typeof state === 'function' ? state(ctx) : state + + return `&${result}` + }) } for (let [variantName, state] of pseudoVariants) { - addVariant(`group-${variantName}`, `:merge(.group)${state} &`) + addVariant(`group-${variantName}`, (ctx) => { + let result = typeof state === 'function' ? state(ctx) : state + + return `:merge(.group)${result} &` + }) } for (let [variantName, state] of pseudoVariants) { - addVariant(`peer-${variantName}`, `:merge(.peer)${state} ~ &`) + addVariant(`peer-${variantName}`, (ctx) => { + let result = typeof state === 'function' ? state(ctx) : state + + return `:merge(.peer)${result} ~ &` + }) } },
diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -539,3 +539,32 @@ it('variants for utilities should not be produced in a file without a utilities `) }) }) + +test('The visited variant removes opacity support', () => { + let config = { + content: [ + { + raw: html` + <a class="visited:border-red-500 visited:bg-red-500 visited:text-red-500" + >Look, it's a link!</a + > + `, + }, + ], + plugins: [], + } + + return run('@tailwind utilities', config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .visited\:border-red-500:visited { + border-color: rgb(239 68 68); + } + .visited\:bg-red-500:visited { + background-color: rgb(239 68 68); + } + .visited\:text-red-500:visited { + color: rgb(239 68 68); + } + `) + }) +})
Visited classes are not generated Visited classes are not generated [Reproduction](https://play.tailwindcss.com/Mi5NOidSAz?file=css)
"2022-02-14T17:24:18Z"
3.0
[]
[ "tests/variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/Mi5NOidSAz?file=css" ]
tailwindlabs/tailwindcss
7,462
tailwindlabs__tailwindcss-7462
[ "7309" ]
f116f9f6648af81bf22e0c28d01a8da015a53180
diff --git a/src/lib/defaultExtractor.js b/src/lib/defaultExtractor.js --- a/src/lib/defaultExtractor.js +++ b/src/lib/defaultExtractor.js @@ -8,6 +8,8 @@ const PATTERNS = [ /([^<>"'`\s]*\[\w*\("[^"'`\s]*"\)\])/.source, // bg-[url("...")] /([^<>"'`\s]*\[\w*\('[^"`\s]*'\)\])/.source, // bg-[url('...'),url('...')] /([^<>"'`\s]*\[\w*\("[^'`\s]*"\)\])/.source, // bg-[url("..."),url("...")] + /([^<>"'`\s]*\[[^<>"'`\s]*\('[^"`\s]*'\)+\])/.source, // h-[calc(100%-theme('spacing.1'))] + /([^<>"'`\s]*\[[^<>"'`\s]*\("[^'`\s]*"\)+\])/.source, // h-[calc(100%-theme("spacing.1"))] /([^<>"'`\s]*\['[^"'`\s]*'\])/.source, // `content-['hello']` but not `content-['hello']']` /([^<>"'`\s]*\["[^"'`\s]*"\])/.source, // `content-["hello"]` but not `content-["hello"]"]` /([^<>"'`\s]*\[[^<>"'`\s]*:[^\]\s]*\])/.source, // `[attr:value]`
diff --git a/tests/arbitrary-values.test.js b/tests/arbitrary-values.test.js --- a/tests/arbitrary-values.test.js +++ b/tests/arbitrary-values.test.js @@ -341,3 +341,32 @@ it('should be possible to read theme values in arbitrary values (with quotes)', `) }) }) + +it('should be possible to read theme values in arbitrary values (with quotes) when inside calc or similar functions', () => { + let config = { + content: [ + { + raw: html`<div + class="w-[calc(100%-theme('spacing.1'))] w-[calc(100%-theme('spacing[0.5]'))]" + ></div>`, + }, + ], + theme: { + spacing: { + 0.5: 'calc(.5 * .25rem)', + 1: 'calc(1 * .25rem)', + }, + }, + } + + return run('@tailwind utilities', config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .w-\[calc\(100\%-theme\(\'spacing\.1\'\)\)\] { + width: calc(100% - calc(1 * 0.25rem)); + } + .w-\[calc\(100\%-theme\(\'spacing\[0\.5\]\'\)\)\] { + width: calc(100% - calc(0.5 * 0.25rem)); + } + `) + }) +}) diff --git a/tests/default-extractor.test.js b/tests/default-extractor.test.js --- a/tests/default-extractor.test.js +++ b/tests/default-extractor.test.js @@ -26,6 +26,8 @@ const input = <div class="hover:font-bold"></div> <div class="content-['>']"></div> <div class="[--y:theme(colors.blue.500)]"> + <div class="w-[calc(100%-theme('spacing.1'))]"> + <div class='w-[calc(100%-theme("spacing.2"))]'> <script> let classes01 = ["text-[10px]"] @@ -90,6 +92,8 @@ const includes = [ `hover:test`, `overflow-scroll`, `[--y:theme(colors.blue.500)]`, + `w-[calc(100%-theme('spacing.1'))]`, + `w-[calc(100%-theme("spacing.2"))]`, ] const excludes = [
Cannot use `theme()` within `calc()` in arbitrary value **What version of Tailwind CSS are you using?** v3.0.18 **What build tool (or framework if it abstracts the build tool) are you using?** Next.js 12.0.8, Webpack ^5, PostCSS ^8.4.5 **What version of Node.js are you using?** v16.13.1 **What browser are you using?** Firefox, Chrome **What operating system are you using?** Ubuntu **Reproduction URL** https://play.tailwindcss.com/zsAHSyoNVo **Describe your issue** I posted to a closed issue, reposting here in the hopes that it doesn't get lost again: https://github.com/tailwindlabs/tailwindcss/issues/6791 > I'm facing this same issue trying to get calc() to work with theme() in an arbitrary value. According to the intellisense it's valid, but the css never actually gets generated/injected: > > `h-[calc(100%-theme('spacing.16'))]`
Hey! You can make this work by getting rid of the quotes: https://play.tailwindcss.com/mn0S0290Tm Ideally we can make it work with quotes too though, will leave this open so we at least look into it a bit more. Ah! It was my understanding that quotes were necessary in the postcss (and therefore in the arbitrary values as well). How does `theme(spacing.16)` work without the quotes, if there's a quick answer to that? (I see now doublechecking that previous closed issue that there were no quotes used within `theme()`, not sure why my brain decided to add them...) In any case thank you for the workaround!
"2022-02-14T20:07:03Z"
3.0
[]
[ "tests/default-extractor.test.js", "tests/arbitrary-values.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/zsAHSyoNVo" ]
tailwindlabs/tailwindcss
7,478
tailwindlabs__tailwindcss-7478
[ "7204" ]
db475be6ddf087ff96cc326e891ac125d4f9e4e8
diff --git a/src/lib/expandTailwindAtRules.js b/src/lib/expandTailwindAtRules.js --- a/src/lib/expandTailwindAtRules.js +++ b/src/lib/expandTailwindAtRules.js @@ -158,7 +158,7 @@ export default function expandTailwindAtRules(context) { // --- // Find potential rules in changed files - let candidates = new Set(['*']) + let candidates = new Set([sharedState.NOT_ON_DEMAND]) let seen = new Set() env.DEBUG && console.time('Reading changed files') diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -5,6 +5,7 @@ import isPlainObject from '../util/isPlainObject' import prefixSelector from '../util/prefixSelector' import { updateAllClasses } from '../util/pluginUtils' import log from '../util/log' +import * as sharedState from './sharedState' import { formatVariantSelector, finalizeSelector } from '../util/formatVariantSelector' import { asClass } from '../util/nameClass' import { normalize } from '../util/dataTypes' @@ -382,6 +383,10 @@ function* resolveMatchedPlugins(classCandidate, context) { } function splitWithSeparator(input, separator) { + if (input === sharedState.NOT_ON_DEMAND) { + return [sharedState.NOT_ON_DEMAND] + } + return input.split(new RegExp(`\\${separator}(?![^[]*\\])`, 'g')) } diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -138,7 +138,7 @@ function withIdentifiers(styles) { // If this isn't "on-demandable", assign it a universal candidate to always include it. if (containsNonOnDemandableSelectors) { - candidates.unshift('*') + candidates.unshift(sharedState.NOT_ON_DEMAND) } // However, it could be that it also contains "on-demandable" candidates. @@ -163,8 +163,8 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs } function prefixIdentifier(identifier, options) { - if (identifier === '*') { - return '*' + if (identifier === sharedState.NOT_ON_DEMAND) { + return sharedState.NOT_ON_DEMAND } if (!options.respectPrefix) { diff --git a/src/lib/sharedState.js b/src/lib/sharedState.js --- a/src/lib/sharedState.js +++ b/src/lib/sharedState.js @@ -5,6 +5,7 @@ export const env = { export const contextMap = new Map() export const configContextMap = new Map() export const contextSourcesMap = new Map() +export const NOT_ON_DEMAND = new String('*') export function resolveDebug(debug) { if (debug === undefined) {
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -1,7 +1,7 @@ import fs from 'fs' import path from 'path' -import { html, run, css } from './util/run' +import { html, run, css, defaults } from './util/run' test('basic usage', () => { let config = { @@ -188,3 +188,64 @@ it('can scan extremely long classes without crashing', () => { expect(result.css).toMatchFormattedCss(css``) }) }) + +it('does not produce duplicate output when seeing variants preceding a wildcard (*)', () => { + let config = { + content: [{ raw: html`underline focus:*` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind base; + @tailwind components; + @tailwind utilities; + + * { + color: red; + } + + .combined, + * { + text-align: center; + } + + @layer base { + * { + color: blue; + } + + .combined, + * { + color: red; + } + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + * { + color: blue; + } + + .combined, + * { + color: red; + } + + ${defaults} + + .underline { + text-decoration-line: underline; + } + + * { + color: red; + } + + .combined, + * { + text-align: center; + } + `) + }) +})
Bug: some text content can trigger multiple Tailwind builds in the same output css <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.0.16 (also saw on v3.0.15) **What build tool (or framework if it abstracts the build tool) are you using?** Just Tailwind. **What version of Node.js are you using?** v16.13.0 **What browser are you using?** N/A **What operating system are you using?** macOS **Reproduction URL** https://github.com/matthewcc/tailwind3-duplicates **Describe your issue** Modifiers (such as pseudo-classes) followed by an asterisk appear to trigger additional instances of "tailwindcss v3.x.x" being inserted into the outputted css file. In our case, we had things like `sm:*` and `focus:*` as text included in a Storybook mdx file as documentation. This mdx file also has jsx with actual Tailwind classes, so we need it added to the `content` property in the Tailwind config. This triggered some extra builds (located in the same css output file), and aside from just extra lines some of our own styles lost priority to re-inserted default Tailwind styles. There are additional notes in the Read Me in the reproduction link. We've changed the text that triggered this issue in our files in the meantime and it's possibly an edge case, but we wanted to share it. Big fans of Tailwind, thanks for your work.
"2022-02-15T16:14:45Z"
3.0
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
7,479
tailwindlabs__tailwindcss-7479
[ "7347" ]
b94d565eb6f61635babd59873cda40e845217ffb
diff --git a/src/util/parseBoxShadowValue.js b/src/util/parseBoxShadowValue.js --- a/src/util/parseBoxShadowValue.js +++ b/src/util/parseBoxShadowValue.js @@ -1,10 +1,58 @@ let KEYWORDS = new Set(['inset', 'inherit', 'initial', 'revert', 'unset']) -let COMMA = /\,(?![^(]*\))/g // Comma separator that is not located between brackets. E.g.: `cubiz-bezier(a, b, c)` these don't count. let SPACE = /\ +(?![^(]*\))/g // Similar to the one above, but with spaces instead. let LENGTH = /^-?(\d+|\.\d+)(.*?)$/g +let SPECIALS = /[(),]/g + +/** + * This splits a string on top-level commas. + * + * Regex doesn't support recursion (at least not the JS-flavored version). + * So we have to use a tiny state machine to keep track of paren vs comma + * placement. Before we'd only exclude commas from the inner-most nested + * set of parens rather than any commas that were not contained in parens + * at all which is the intended behavior here. + * + * Expected behavior: + * var(--a, 0 0 1px rgb(0, 0, 0)), 0 0 1px rgb(0, 0, 0) + * ─┬─ ┬ ┬ ┬ + * x x x ╰──────── Split because top-level + * ╰──────────────┴──┴───────────── Ignored b/c inside >= 1 levels of parens + * + * @param {string} input + */ +function* splitByTopLevelCommas(input) { + SPECIALS.lastIndex = -1 + + let depth = 0 + let lastIndex = 0 + let found = false + + // Find all parens & commas + // And only split on commas if they're top-level + for (let match of input.matchAll(SPECIALS)) { + if (match[0] === '(') depth++ + if (match[0] === ')') depth-- + if (match[0] === ',' && depth === 0) { + found = true + + yield input.substring(lastIndex, match.index) + lastIndex = match.index + match[0].length + } + } + + // Provide the last segment of the string if available + // Otherwise the whole string since no commas were found + // This mirrors the behavior of string.split() + if (found) { + yield input.substring(lastIndex) + } else { + yield input + } +} + export function parseBoxShadowValue(input) { - let shadows = input.split(COMMA) + let shadows = Array.from(splitByTopLevelCommas(input)) return shadows.map((shadow) => { let value = shadow.trim() let result = { raw: value }
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -346,3 +346,31 @@ it('does not produce duplicate output when seeing variants preceding a wildcard `) }) }) + +it('it can parse box shadows with variables', () => { + let config = { + content: [{ raw: html`<div class="shadow-lg"></div>` }], + theme: { + boxShadow: { + lg: 'var(-a, 0 35px 60px -15px rgba(0, 0, 0)), 0 0 1px rgb(0, 0, 0)', + }, + }, + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .shadow-lg { + --tw-shadow: var(-a, 0 35px 60px -15px rgba(0, 0, 0)), 0 0 1px rgb(0, 0, 0); + --tw-shadow-colored: 0 35px 60px -15px var(--tw-shadow-color), + 0 0 1px var(--tw-shadow-color); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), + var(--tw-shadow); + } + `) + }) +})
Bug: box shadow with color method can be compiled with missing parentheses **What version of Tailwind CSS are you using?** 3.0.16 **What build tool (or framework if it abstracts the build tool) are you using?** just Tailwind **What version of Node.js are you using?** For example: v16.13.0 **What browser are you using?** N/A **What operating system are you using?** macOS **Reproduction URL** minimal reproduction: https://github.com/matthewcc/tailwind3-boxshadow-error **Describe your issue** We are using a 3rd party theme switching plugin that can output the following configuration (minimal reproduction doesn't require the plugin): ``` boxShadow: { 'lg': 'var(--some-variable-name, 0 35px 60px -15px rgba(0, 0, 0))' } ``` This is valid CSS, and Tailwind 2 handled it fine. But how Tailwind compiles box-shadow has been updated in v3, and with the above configuration the new `tw-shadow-colored` attribute is created missing a closing parentheses: ` --tw-shadow-colored: var(--some-variable-name, 0 35px 60px -15px var(--tw-shadow-color);` If we do not use color functions like `rgb(...)` or `hsla(...)`, it compiles fine. It also compiles fine if we throw in random CSS functions like `calc()`. The issue seems to only happen when the config value is a CSS var that contains a CSS color method, and only with box-shadow (we tried to recreate this with other theme-able values for Tailwind, but only saw this happen with box-shadow), so it seems to specifically be about how Tailwind is transforming those color functions for box-shadow.
Yeah, this is something which has been bugging me for ages. Tailwind internally converts the formats of all colors to `color: rgba(...)` values which keeps us from being able to specify colors in other systems or use color profiles in CSS Color Module Level 4 colors. I have a discussion at #2218 which illustrates the issue in more depth. I'd really like to see this get fixed in Tailwind.
"2022-02-15T18:02:47Z"
3.0
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
7,563
tailwindlabs__tailwindcss-7563
[ "7234" ]
9effea5d283be35e67135034a7e69a34a68141d3
diff --git a/src/postcss-plugins/nesting/plugin.js b/src/postcss-plugins/nesting/plugin.js --- a/src/postcss-plugins/nesting/plugin.js +++ b/src/postcss-plugins/nesting/plugin.js @@ -39,6 +39,42 @@ export function nesting(opts = postcssNested) { decl.remove() }) + /** + * Use a private PostCSS API to remove the "clean" flag from the entire AST. + * This is done because running process() on the AST will set the "clean" + * flag on all nodes, which we don't want. + * + * This causes downstream plugins using the visitor API to be skipped. + * + * This is guarded because the PostCSS API is not public + * and may change in future versions of PostCSS. + * + * See https://github.com/postcss/postcss/issues/1712 for more details + * + * @param {import('postcss').Node} node + */ + function markDirty(node) { + if (!('markDirty' in node)) { + return + } + + // Traverse the tree down to the leaf nodes + if (node.nodes) { + node.nodes.forEach((n) => markDirty(n)) + } + + // If it's a leaf node mark it as dirty + // We do this here because marking a node as dirty + // will walk up the tree and mark all parents as dirty + // resulting in a lot of unnecessary work if we did this + // for every single node + if (!node.nodes) { + node.markDirty() + } + } + + markDirty(root) + return root } }
diff --git a/tests/postcss-plugins/nesting/index.test.js b/tests/postcss-plugins/nesting/index.test.js --- a/tests/postcss-plugins/nesting/index.test.js +++ b/tests/postcss-plugins/nesting/index.test.js @@ -1,6 +1,7 @@ import postcss from 'postcss' import postcssNested from 'postcss-nested' import plugin from '../../../src/postcss-plugins/nesting' +import { visitorSpyPlugin } from './plugins.js' it('should be possible to load a custom nesting plugin', async () => { let input = css` @@ -166,6 +167,46 @@ test('@screen rules can work with `@apply`', async () => { `) }) +test('nesting does not break downstream plugin visitors', async () => { + let input = css` + .foo { + color: black; + } + @suppoerts (color: blue) { + .foo { + color: blue; + } + } + /* Comment */ + ` + + let spyPlugin = visitorSpyPlugin() + + let plugins = [plugin(postcssNested), spyPlugin.plugin] + + let result = await run(input, plugins) + + expect(result).toMatchCss(css` + .foo { + color: black; + } + @suppoerts (color: blue) { + .foo { + color: blue; + } + } + /* Comment */ + `) + + expect(spyPlugin.spies.Once).toHaveBeenCalled() + expect(spyPlugin.spies.OnceExit).toHaveBeenCalled() + expect(spyPlugin.spies.Root).toHaveBeenCalled() + expect(spyPlugin.spies.Rule).toHaveBeenCalled() + expect(spyPlugin.spies.AtRule).toHaveBeenCalled() + expect(spyPlugin.spies.Comment).toHaveBeenCalled() + expect(spyPlugin.spies.Declaration).toHaveBeenCalled() +}) + // --- function indentRecursive(node, indent = 0) { @@ -187,11 +228,21 @@ function formatNodes(root) { } async function run(input, options) { - return ( - await postcss([options === undefined ? plugin : plugin(options), formatNodes]).process(input, { - from: undefined, - }) - ).toString() + let plugins = [] + + if (Array.isArray(options)) { + plugins = options + } else { + plugins.push(options === undefined ? plugin : plugin(options)) + } + + plugins.push(formatNodes) + + let result = await postcss(plugins).process(input, { + from: undefined, + }) + + return result.toString() } function css(templates) { diff --git a/tests/postcss-plugins/nesting/plugins.js b/tests/postcss-plugins/nesting/plugins.js new file mode 100644 --- /dev/null +++ b/tests/postcss-plugins/nesting/plugins.js @@ -0,0 +1,42 @@ +export function visitorSpyPlugin() { + let Once = jest.fn() + let OnceExit = jest.fn() + let Root = jest.fn() + let AtRule = jest.fn() + let Rule = jest.fn() + let Comment = jest.fn() + let Declaration = jest.fn() + + let plugin = Object.assign( + function () { + return { + postcssPlugin: 'visitor-test', + + // These work fine + Once, + OnceExit, + + // These break + Root, + Rule, + AtRule, + Declaration, + Comment, + } + }, + { postcss: true } + ) + + return { + plugin, + spies: { + Once, + OnceExit, + Root, + AtRule, + Rule, + Comment, + Declaration, + }, + } +}
tailwindcss/nesting used with postcss-nesting breaks some postcss plugins <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.0.17 **What build tool (or framework if it abstracts the build tool) are you using?** [email protected] **What version of Node.js are you using?** For example: v17.1.0 **What operating system are you using?** MacOS **Describe your issue** `tailwindcss/nesting` used with `postcss-nesting` breaks some postcss plugins. In this example vite config `cssHasPseudo` is not working. Also another plugin that is not working is `postcss-mixins` ```js import tailwindcss from 'tailwindcss' import tailwindcssNesting from 'tailwindcss/nesting' import autoprefixer from 'autoprefixer' import postcssImport from 'postcss-import' import postcssNesting from 'postcss-nesting' import cssHasPseudo from 'css-has-pseudo' import postcssCustomMedia from 'postcss-custom-media' export default { css: { postcss: { plugins: [postcssImport, tailwindcssNesting(postcssNesting), postcssCustomMedia, cssHasPseudo, tailwindcss, autoprefixer] } } } ```
Could you provide a reproduction? It would help to see the versions of the plugins you have installed along with the whole of the setup. Here is a repro, hope it helps (text should turn red). All plugins are latest versions with tailwind (doesn't work) - https://stackblitz.com/edit/vitejs-vite-fv2tnq?file=style.pcss&terminal=dev without tailwind (works) - https://stackblitz.com/edit/vitejs-vite-vbidlr?file=style.pcss&terminal=dev
"2022-02-21T14:58:08Z"
3.0
[]
[ "tests/postcss-plugins/nesting/index.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
7,565
tailwindlabs__tailwindcss-7565
[ "4896" ]
af64d7190c1e3b4ed765c7464f99b6aec5d5bac2
diff --git a/src/lib/collapseAdjacentRules.js b/src/lib/collapseAdjacentRules.js --- a/src/lib/collapseAdjacentRules.js +++ b/src/lib/collapseAdjacentRules.js @@ -5,7 +5,7 @@ let comparisonMap = { let types = new Set(Object.keys(comparisonMap)) export default function collapseAdjacentRules() { - return (root) => { + function collapseRulesIn(root) { let currentRule = null root.each((node) => { if (!types.has(node.type)) { @@ -35,5 +35,20 @@ export default function collapseAdjacentRules() { currentRule = node } }) + + // After we've collapsed adjacent rules & at-rules, we need to collapse + // adjacent rules & at-rules that are children of at-rules. + // We do not care about nesting rules because Tailwind CSS + // explicitly does not handle rule nesting on its own as + // the user is expected to use a nesting plugin + root.each((node) => { + if (node.type === 'atrule') { + collapseRulesIn(node) + } + }) + } + + return (root) => { + collapseRulesIn(root) } }
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -1289,9 +1289,6 @@ it('apply partitioning works with media queries', async () => { body { --tw-text-opacity: 1; color: rgb(220 38 38 / var(--tw-text-opacity)); - } - html, - body { font-size: 2rem; } } diff --git a/tests/collapse-adjacent-rules.test.css b/tests/collapse-adjacent-rules.test.css --- a/tests/collapse-adjacent-rules.test.css +++ b/tests/collapse-adjacent-rules.test.css @@ -72,6 +72,29 @@ color: black; font-weight: 700; } +@supports (foo: bar) { + .some-apply-thing { + font-weight: 700; + --tw-text-opacity: 1; + color: rgb(0 0 0 / var(--tw-text-opacity)); + } +} +@media (min-width: 768px) { + .some-apply-thing { + font-weight: 700; + --tw-text-opacity: 1; + color: rgb(0 0 0 / var(--tw-text-opacity)); + } +} +@supports (foo: bar) { + @media (min-width: 768px) { + .some-apply-thing { + font-weight: 700; + --tw-text-opacity: 1; + color: rgb(0 0 0 / var(--tw-text-opacity)); + } + } +} @media (min-width: 640px) { .sm\:text-center { text-align: center; diff --git a/tests/collapse-adjacent-rules.test.html b/tests/collapse-adjacent-rules.test.html --- a/tests/collapse-adjacent-rules.test.html +++ b/tests/collapse-adjacent-rules.test.html @@ -19,5 +19,6 @@ <div class="md:text-center"></div> <div class="lg:font-bold"></div> <div class="lg:text-center"></div> + <div class="some-apply-thing"></div> </body> </html> diff --git a/tests/collapse-adjacent-rules.test.js b/tests/collapse-adjacent-rules.test.js --- a/tests/collapse-adjacent-rules.test.js +++ b/tests/collapse-adjacent-rules.test.js @@ -8,7 +8,11 @@ test('collapse adjacent rules', () => { content: [path.resolve(__dirname, './collapse-adjacent-rules.test.html')], corePlugins: { preflight: false }, theme: {}, - plugins: [], + plugins: [ + function ({ addVariant }) { + addVariant('foo-bar', '@supports (foo: bar)') + }, + ], } let input = css` @@ -45,6 +49,9 @@ test('collapse adjacent rules', () => { .bar { font-weight: 700; } + .some-apply-thing { + @apply foo-bar:md:text-black foo-bar:md:font-bold foo-bar:text-black foo-bar:font-bold md:font-bold md:text-black; + } ` return run(input, config).then((result) => { diff --git a/tests/kitchen-sink.test.css b/tests/kitchen-sink.test.css --- a/tests/kitchen-sink.test.css +++ b/tests/kitchen-sink.test.css @@ -498,8 +498,6 @@ div { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } - } - @media (prefers-reduced-motion: no-preference) { .dark .md\:dark\:motion-safe\:foo\:active\:custom-util:active { background: #abcdef !important; }
Duplicated CSS rules in @media output ### What version of Tailwind CSS are you using? 2.2.4 ### What build tool (or framework if it abstracts the build tool) are you using? Gulp and tailwindcss-cli ### What version of Node.js are you using? v14.17.2 ### What browser are you using? N/A ### What operating system are you using? Windows 10 ### Reproduction repository https://play.tailwindcss.com/6re84tZQjw?file=css ### Describe your issue Noticed this recently and just curious if this is the intended/expected behavior. In **JIT** mode, when using `@apply`, responsive variants (e.g. `md:`) are output as separate, duplicate CSS rules rather than combined into one (as is the case with non-responsive rules). _Note: This is the case whether one uses multiple `@apply` rules or combines all styles into one._ **Input:** _CONFIG_ ``` const colors = require('tailwindcss/colors') module.exports = { mode: 'jit', theme: { extend: {}, }, variants: {}, plugins: [], } ``` _HTML_ ``` <div class="nav-main"> <a href="#" class="nav-item">nav</a> </div> ``` _CSS_ ``` @tailwind base; @tailwind components; @tailwind utilities; .nav-main { @apply bg-gray-200 w-full; @apply md:w-1/2 md:px-5 md:bg-blue-200; } .nav-item { @apply uppercase text-sm tracking-wider font-semibold flex py-2 px-4 border-b-2 border-transparent; @apply md:text-blue-600 md:font-bold md:tracking-widest; } ``` _or_ ``` .nav-main { @apply bg-gray-200 w-full md:w-1/2 md:px-5 md:bg-blue-200; } .nav-item { @apply uppercase text-sm tracking-wider font-semibold flex py-2 px-4 border-b-2 border-transparent md:text-blue-600 md:font-bold md:tracking-widest; } ``` Output: ``` .nav-main { width: 100%; --tw-bg-opacity: 1; background-color: rgba(229, 231, 235, var(--tw-bg-opacity)); } @media (min-width: 768px) { .nav-main { width: 50%; } .nav-main { --tw-bg-opacity: 1; background-color: rgba(191, 219, 254, var(--tw-bg-opacity)); } .nav-main { padding-left: 1.25rem; padding-right: 1.25rem; } } .nav-item { display: flex; border-bottom-width: 2px; border-color: transparent; padding-top: 0.5rem; padding-bottom: 0.5rem; padding-left: 1rem; padding-right: 1rem; font-size: 0.875rem; line-height: 1.25rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; } @media (min-width: 768px) { .nav-item { font-weight: 700; } .nav-item { letter-spacing: 0.1em; } .nav-item { --tw-text-opacity: 1; color: rgba(37, 99, 235, var(--tw-text-opacity)); } } ``` Output **without** `mode: 'jit'` ``` .nav-main { width: 100%; --tw-bg-opacity: 1; background-color: rgba(229, 231, 235, var(--tw-bg-opacity)); } @media (min-width: 768px) { .nav-main { width: 50%; --tw-bg-opacity: 1; background-color: rgba(191, 219, 254, var(--tw-bg-opacity)); padding-left: 1.25rem; padding-right: 1.25rem; } } .nav-item { display: flex; border-bottom-width: 2px; border-color: transparent; padding-left: 1rem; padding-right: 1rem; padding-top: 0.5rem; padding-bottom: 0.5rem; font-size: 0.875rem; line-height: 1.25rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; } @media (min-width: 768px) { .nav-item { font-weight: 700; letter-spacing: 0.1em; --tw-text-opacity: 1; color: rgba(37, 99, 235, var(--tw-text-opacity)); } } ``` https://play.tailwindcss.com/6re84tZQjw?file=css I'm a huge fan of tailwindcss and newly getting familiar with JIT so I appreciate any help or clarification that is offered!
Updating this issue with some additional observations from my local development. When running JIT watch mode (via `npx tailwindcss`), I get many duplicated CSS rules. Still trying to drilldown to what specific actions cause this, but it seems to be related to tailwind watching my content files (Blade views in this case). When a utility class is added to the Blade file, if that utility is not yet present in the base file, it is added (as expected) but many existing rules get duplicated in the process. I end up with a file that looks like this: ``` #app .pointer-events-none { pointer-events: none; pointer-events: none; pointer-events: none; pointer-events: none; pointer-events: none; pointer-events: none; } #app .absolute { position: absolute; position: absolute; position: absolute; position: absolute; position: absolute; position: absolute; } #app .relative { position: relative; position: relative; position: relative; position: relative; position: relative; position: relative; } #app .sticky { position: sticky; } #app .top-0 { top: 0px; } #app .left-0 { left: 0px; } #app .bottom-0 { bottom: 0px; } #app .top-4 { top: 1rem; } #app .top-0 { top: 0px; } #app .left-0 { left: 0px; } #app .bottom-0 { bottom: 0px; } #app .top-5 { top: 1.25rem; } #app .top-0 { top: 0px; } #app .left-0 { left: 0px; } #app .bottom-0 { bottom: 0px; } #app .top-7 { top: 1.75rem; } #app .top-0 { top: 0px; } #app .left-0 { left: 0px; } #app .bottom-0 { bottom: 0px; } #app .top-2 { top: 0.5rem; } #app .top-0 { top: 0px; } #app .left-0 { left: 0px; } #app .bottom-0 { bottom: 0px; } #app .top-2 { top: 0.5rem; } #app .top-0 { top: 0px; } #app .left-0 { left: 0px; } #app .bottom-0 { bottom: 0px; } #app .top-3 { top: 0.75rem; ``` Triggering a re-processing of the primary CSS file that contains the calls to `@tailwind base; @tailwind components; @tailwind utilities;` seems to fix the issue and remove the duplicates so the issue is avoided in final production builds. However, it can be an obstacle when developing because the flood of duplicate rules makes debugging styles via DevTools quite difficult. If I'm missing something here and inadvertently causing the issue, I'd welcome any insight! I'm a novice, but confirm your tailwind.config.js file's "purge" settings are complete and correct Just thought I'd note that I'm experiencing the same thing with duplicate CSS, and I happen to have all these things in common with the OP, though I'm not sure which of these are relevant just yet: - JIT mode enabled - templates are also Blade (with some straight PHP also included in the purge) - also happen to be using `#app` as an `important` qualifier in `tailwind.config.js` However, I'm using Laravel Mix + BrowserSync to watch files and recompile as needed. Duplicate rules seem to accumulate during a single BrowserSync session. If I restart my watch task, the duplicate rules get cleaned up. if you have already node js installed or after installing open node command prompt window by typing node( on windows machine) in start. [krogereschedule](https://www.krogereschedule.org/)
"2022-02-21T16:58:26Z"
3.0
[]
[ "tests/collapse-adjacent-rules.test.js", "tests/apply.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/6re84tZQjw?file=css" ]
tailwindlabs/tailwindcss
7,587
tailwindlabs__tailwindcss-7587
[ "6748" ]
3b8ca9d4ebcfabd39dcbcceeaa73b5b8bf57f3c2
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -1925,7 +1925,7 @@ export let corePlugins = { ringWidth: ({ matchUtilities, addDefaults, addUtilities, theme }) => { let ringOpacityDefault = theme('ringOpacity.DEFAULT', '0.5') let ringColorDefault = withAlphaValue( - theme('ringColor.DEFAULT'), + theme('ringColor')?.DEFAULT, ringOpacityDefault, `rgb(147 197 253 / ${ringOpacityDefault})` )
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -110,6 +110,103 @@ test('per-plugin colors with the same key can differ when using a custom colors }) }) +test('default ring color can be a function', () => { + function color(variable) { + return function ({ opacityVariable, opacityValue }) { + if (opacityValue !== undefined) { + return `rgba(${variable}, ${opacityValue})` + } + if (opacityVariable !== undefined) { + return `rgba(${variable}, var(${opacityVariable}, 1))` + } + return `rgb(${variable})` + } + } + + let config = { + content: [ + { + raw: html` <div class="ring"></div> `, + }, + ], + + theme: { + extend: { + ringColor: { + DEFAULT: color('var(--red)'), + }, + }, + }, + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind base; + @tailwind components; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + *, + ::before, + ::after { + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgba(var(--red), 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; + } + + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + it('fasly config values still work', () => { let config = { content: [{ raw: html`<div class="inset-0"></div>` }],
Default colour not applied to ring when using function to generate it **What version of Tailwind CSS are you using?** v3.0.5 **What build tool (or framework if it abstracts the build tool) are you using?** postcss-cli 8.4..5 **What version of Node.js are you using?** v16.13.1 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** [Repo te reproduce bug](https://github.com/villekivela/tailwind3-bug) **Describe your issue** Default colour is not applied when using a function to generate default colour for ring. Works for border. Was working v2.2.19.
@villekivela I worked in this, didn't got the solution, but will like to add something I figured out. It does work with functions with hard coded colour values, the issue lies in doing the same variably. A simple hard coded colour returning function `const col = () => {return "#FF0000";}` and calling part `ringColor: { DEFAULT: col(), }` This works perfectly > @villekivela I worked in this, didn't got the solution, but will like to add something I figured out. It does work with functions with hard coded colour values, the issue lies in doing the same variably. A simple hard coded colour returning function `const col = () => {return "#FF0000";}` and calling part `ringColor: { DEFAULT: col(), }` This works perfectly i have the same problem but it curious how with colors like bg-sky-700 work but with another no, can you check if for this color work in your proyect?
"2022-02-22T20:23:39Z"
3.0
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
7,588
tailwindlabs__tailwindcss-7588
[ "5043", "7369" ]
d72b277ba6696fc28c3bf92d84de0f451ea1e360
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -140,7 +140,7 @@ function processApply(root, context) { for (let apply of applies) { let candidates = perParentApplies.get(apply.parent) || [] - perParentApplies.set(apply.parent, candidates) + perParentApplies.set(apply.parent, [candidates, apply.source]) let [applyCandidates, important] = extractApplyCandidates(apply.params) @@ -178,7 +178,7 @@ function processApply(root, context) { } } - for (const [parent, candidates] of perParentApplies) { + for (const [parent, [candidates, atApplySource]] of perParentApplies) { let siblings = [] for (let [applyCandidate, important, rules] of candidates) { @@ -220,6 +220,12 @@ function processApply(root, context) { } let root = postcss.root({ nodes: [node.clone()] }) + + // Make sure every node in the entire tree points back at the @apply rule that generated it + root.walk((node) => { + node.source = atApplySource + }) + let canRewriteSelector = node.type !== 'atrule' || (node.type === 'atrule' && node.name !== 'keyframes') diff --git a/src/lib/resolveDefaultsAtRules.js b/src/lib/resolveDefaultsAtRules.js --- a/src/lib/resolveDefaultsAtRules.js +++ b/src/lib/resolveDefaultsAtRules.js @@ -120,7 +120,9 @@ export default function resolveDefaultsAtRules({ tailwindConfig }) { } for (let [, selectors] of selectorGroups) { - let universalRule = postcss.rule() + let universalRule = postcss.rule({ + source: universal.source, + }) universalRule.selectors = [...selectors] @@ -128,7 +130,9 @@ export default function resolveDefaultsAtRules({ tailwindConfig }) { universal.before(universalRule) } } else { - let universalRule = postcss.rule() + let universalRule = postcss.rule({ + source: universal.source, + }) universalRule.selectors = ['*', '::before', '::after'] diff --git a/src/util/cloneNodes.js b/src/util/cloneNodes.js --- a/src/util/cloneNodes.js +++ b/src/util/cloneNodes.js @@ -4,6 +4,12 @@ export default function cloneNodes(nodes, source) { if (source !== undefined) { cloned.source = source + + if ('walk' in cloned) { + cloned.walk((child) => { + child.source = source + }) + } } return cloned
diff --git a/tests/source-maps.test.js b/tests/source-maps.test.js new file mode 100644 --- /dev/null +++ b/tests/source-maps.test.js @@ -0,0 +1,409 @@ +import { runWithSourceMaps as run, html, css } from './util/run' +import { parseSourceMaps } from './util/source-maps' + +it('apply generates source maps', async () => { + let config = { + content: [ + { + raw: html` + <div class="with-declaration"></div> + <div class="with-comment"></div> + <div class="just-apply"></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + .with-declaration { + background-color: red; + @apply h-4 w-4 bg-green-500; + } + + .with-comment { + /* sourcemap will work here too */ + @apply h-4 w-4 bg-red-500; + } + + .just-apply { + @apply h-4 w-4 bg-black; + } + ` + + let result = await run(input, config) + let { sources, annotations } = parseSourceMaps(result) + + // All CSS generated by Tailwind CSS should be annotated with source maps + // And always be able to point to the original source file + expect(sources).not.toContain('<no source>') + expect(sources.length).toBe(1) + + // It would make the tests nicer to read and write + expect(annotations).toStrictEqual([ + '2:4 -> 2:4', + '3:6-27 -> 3:6-27', + '4:6-33 -> 4:6-18', + '4:6-33 -> 5:6-17', + '4:6-33 -> 6:6-24', + '4:6-33 -> 7:6-61', + '5:4 -> 8:4', + '7:4 -> 10:4', + '8:6-39 -> 11:6-39', + '9:6-31 -> 12:6-18', + '9:6-31 -> 13:6-17', + '9:6-31 -> 14:6-24', + '9:6-31 -> 15:6-61', + '10:4 -> 16:4', + '13:6 -> 18:4', + '13:6-29 -> 19:6-18', + '13:6-29 -> 20:6-17', + '13:6-29 -> 21:6-24', + '13:6 -> 22:6', + '13:29 -> 23:0', + ]) +}) + +it('preflight + base have source maps', async () => { + let config = { + content: [], + } + + let input = css` + @tailwind base; + ` + + let result = await run(input, config) + let { sources, annotations } = parseSourceMaps(result) + + // All CSS generated by Tailwind CSS should be annotated with source maps + // And always be able to point to the original source file + expect(sources).not.toContain('<no source>') + expect(sources.length).toBe(1) + + // It would make the tests nicer to read and write + expect(annotations).toStrictEqual([ + '2:4 -> 1:0', + '2:18-4 -> 3:1-2', + '2:18 -> 6:1', + '2:4 -> 8:0', + '2:4-18 -> 11:2-32', + '2:4-18 -> 12:2-25', + '2:4-18 -> 13:2-29', + '2:4-18 -> 14:2-31', + '2:18 -> 15:0', + '2:4 -> 17:0', + '2:4-18 -> 19:2-18', + '2:18 -> 20:0', + '2:4 -> 22:0', + '2:18 -> 27:1', + '2:4 -> 29:0', + '2:4-18 -> 30:2-26', + '2:4-18 -> 31:2-40', + '2:4-18 -> 32:2-26', + '2:4-18 -> 33:2-21', + '2:4-18 -> 34:2-230', + '2:18 -> 35:0', + '2:4 -> 37:0', + '2:18 -> 40:1', + '2:4 -> 42:0', + '2:4-18 -> 43:2-19', + '2:4-18 -> 44:2-30', + '2:18 -> 45:0', + '2:4 -> 47:0', + '2:18 -> 51:1', + '2:4 -> 53:0', + '2:4-18 -> 54:2-19', + '2:4-18 -> 55:2-24', + '2:4-18 -> 56:2-31', + '2:18 -> 57:0', + '2:4 -> 59:0', + '2:18 -> 61:1', + '2:4 -> 63:0', + '2:4-18 -> 64:2-35', + '2:18 -> 65:0', + '2:4 -> 67:0', + '2:18 -> 69:1', + '2:4 -> 71:0', + '2:4-18 -> 77:2-20', + '2:4-18 -> 78:2-22', + '2:18 -> 79:0', + '2:4 -> 81:0', + '2:18 -> 83:1', + '2:4 -> 85:0', + '2:4-18 -> 86:2-16', + '2:4-18 -> 87:2-26', + '2:18 -> 88:0', + '2:4 -> 90:0', + '2:18 -> 92:1', + '2:4 -> 94:0', + '2:4-18 -> 96:2-21', + '2:18 -> 97:0', + '2:4 -> 99:0', + '2:18 -> 102:1', + '2:4 -> 104:0', + '2:4-18 -> 108:2-121', + '2:4-18 -> 109:2-24', + '2:18 -> 110:0', + '2:4 -> 112:0', + '2:18 -> 114:1', + '2:4 -> 116:0', + '2:4-18 -> 117:2-16', + '2:18 -> 118:0', + '2:4 -> 120:0', + '2:18 -> 122:1', + '2:4 -> 124:0', + '2:4-18 -> 126:2-16', + '2:4-18 -> 127:2-16', + '2:4-18 -> 128:2-20', + '2:4-18 -> 129:2-26', + '2:18 -> 130:0', + '2:4 -> 132:0', + '2:4-18 -> 133:2-17', + '2:18 -> 134:0', + '2:4 -> 136:0', + '2:4-18 -> 137:2-13', + '2:18 -> 138:0', + '2:4 -> 140:0', + '2:18 -> 144:1', + '2:4 -> 146:0', + '2:4-18 -> 147:2-24', + '2:4-18 -> 148:2-31', + '2:4-18 -> 149:2-35', + '2:18 -> 150:0', + '2:4 -> 152:0', + '2:18 -> 156:1', + '2:4 -> 158:0', + '2:4-18 -> 163:2-30', + '2:4-18 -> 164:2-25', + '2:4-18 -> 165:2-30', + '2:4-18 -> 166:2-24', + '2:4-18 -> 167:2-19', + '2:4-18 -> 168:2-20', + '2:18 -> 169:0', + '2:4 -> 171:0', + '2:18 -> 173:1', + '2:4 -> 175:0', + '2:4-18 -> 177:2-22', + '2:18 -> 178:0', + '2:4 -> 180:0', + '2:18 -> 183:1', + '2:4 -> 185:0', + '2:4-18 -> 189:2-36', + '2:4-18 -> 190:2-39', + '2:4-18 -> 191:2-32', + '2:18 -> 192:0', + '2:4 -> 194:0', + '2:18 -> 196:1', + '2:4 -> 198:0', + '2:4-18 -> 199:2-15', + '2:18 -> 200:0', + '2:4 -> 202:0', + '2:18 -> 204:1', + '2:4 -> 206:0', + '2:4-18 -> 207:2-18', + '2:18 -> 208:0', + '2:4 -> 210:0', + '2:18 -> 212:1', + '2:4 -> 214:0', + '2:4-18 -> 215:2-26', + '2:18 -> 216:0', + '2:4 -> 218:0', + '2:18 -> 220:1', + '2:4 -> 222:0', + '2:4-18 -> 224:2-14', + '2:18 -> 225:0', + '2:4 -> 227:0', + '2:18 -> 230:1', + '2:4 -> 232:0', + '2:4-18 -> 233:2-39', + '2:4-18 -> 234:2-30', + '2:18 -> 235:0', + '2:4 -> 237:0', + '2:18 -> 239:1', + '2:4 -> 241:0', + '2:4-18 -> 242:2-26', + '2:18 -> 243:0', + '2:4 -> 245:0', + '2:18 -> 248:1', + '2:4 -> 250:0', + '2:4-18 -> 251:2-36', + '2:4-18 -> 252:2-23', + '2:18 -> 253:0', + '2:4 -> 255:0', + '2:18 -> 257:1', + '2:4 -> 259:0', + '2:4-18 -> 260:2-20', + '2:18 -> 261:0', + '2:4 -> 263:0', + '2:18 -> 265:1', + '2:4 -> 267:0', + '2:4-18 -> 280:2-11', + '2:18 -> 281:0', + '2:4 -> 283:0', + '2:4-18 -> 284:2-11', + '2:4-18 -> 285:2-12', + '2:18 -> 286:0', + '2:4 -> 288:0', + '2:4-18 -> 289:2-12', + '2:18 -> 290:0', + '2:4 -> 292:0', + '2:4-18 -> 295:2-18', + '2:4-18 -> 296:2-11', + '2:4-18 -> 297:2-12', + '2:18 -> 298:0', + '2:4 -> 300:0', + '2:18 -> 302:1', + '2:4 -> 304:0', + '2:4-18 -> 305:2-18', + '2:18 -> 306:0', + '2:4 -> 308:0', + '2:18 -> 311:1', + '2:4 -> 313:0', + '2:4-18 -> 315:2-20', + '2:4-18 -> 316:2-24', + '2:18 -> 317:0', + '2:4 -> 319:0', + '2:18 -> 321:1', + '2:4 -> 323:0', + '2:4-18 -> 325:2-17', + '2:18 -> 326:0', + '2:4 -> 328:0', + '2:18 -> 330:1', + '2:4 -> 331:0', + '2:4-18 -> 332:2-17', + '2:18 -> 333:0', + '2:4 -> 335:0', + '2:18 -> 339:1', + '2:4 -> 341:0', + '2:4-18 -> 349:2-24', + '2:4-18 -> 350:2-32', + '2:18 -> 351:0', + '2:4 -> 353:0', + '2:18 -> 355:1', + '2:4 -> 357:0', + '2:4-18 -> 359:2-17', + '2:4-18 -> 360:2-14', + '2:18 -> 361:0', + '2:4 -> 363:0', + '2:18 -> 365:1', + '2:4 -> 367:0', + '2:4-18 -> 368:2-15', + '2:18 -> 369:0', + '2:4 -> 371:0', + '2:4-18 -> 372:2-21', + '2:4-18 -> 373:2-21', + '2:4-18 -> 374:2-16', + '2:4-18 -> 375:2-16', + '2:4-18 -> 376:2-16', + '2:4-18 -> 377:2-17', + '2:4-18 -> 378:2-17', + '2:4-18 -> 379:2-15', + '2:4-18 -> 380:2-15', + '2:4-18 -> 381:2-20', + '2:4-18 -> 382:2-40', + '2:4-18 -> 383:2-17', + '2:4-18 -> 384:2-22', + '2:4-18 -> 385:2-24', + '2:4-18 -> 386:2-25', + '2:4-18 -> 387:2-26', + '2:4-18 -> 388:2-20', + '2:4-18 -> 389:2-29', + '2:4-18 -> 390:2-30', + '2:4-18 -> 391:2-40', + '2:4-18 -> 392:2-36', + '2:4-18 -> 393:2-29', + '2:4-18 -> 394:2-24', + '2:4-18 -> 395:2-32', + '2:4-18 -> 396:2-14', + '2:4-18 -> 397:2-20', + '2:4-18 -> 398:2-18', + '2:4-18 -> 399:2-19', + '2:4-18 -> 400:2-20', + '2:4-18 -> 401:2-16', + '2:4-18 -> 402:2-18', + '2:4-18 -> 403:2-15', + '2:4-18 -> 404:2-21', + '2:4-18 -> 405:2-23', + '2:4-18 -> 406:2-29', + '2:4-18 -> 407:2-27', + '2:4-18 -> 408:2-28', + '2:4-18 -> 409:2-29', + '2:4-18 -> 410:2-25', + '2:4-18 -> 411:2-26', + '2:4-18 -> 412:2-27', + '2:4 -> 413:2', + '2:18 -> 414:0', + ]) +}) + +it('utilities have source maps', async () => { + let config = { + content: [{ raw: `text-red-500` }], + } + + let input = css` + @tailwind utilities; + ` + + let result = await run(input, config) + let { sources, annotations } = parseSourceMaps(result) + + // All CSS generated by Tailwind CSS should be annotated with source maps + // And always be able to point to the original source file + expect(sources).not.toContain('<no source>') + expect(sources.length).toBe(1) + + // It would make the tests nicer to read and write + expect(annotations).toStrictEqual(['2:4 -> 1:0', '2:4-23 -> 2:4-24', '2:4 -> 3:4', '2:23 -> 4:0']) +}) + +it('components have source maps', async () => { + let config = { + content: [{ raw: `container` }], + } + + let input = css` + @tailwind components; + ` + + let result = await run(input, config) + let { sources, annotations } = parseSourceMaps(result) + + // All CSS generated by Tailwind CSS should be annotated with source maps + // And always be able to point to the original source file + expect(sources).not.toContain('<no source>') + expect(sources.length).toBe(1) + + // It would make the tests nicer to read and write + expect(annotations).toStrictEqual([ + '2:4 -> 1:0', + '2:4 -> 2:4', + '2:24 -> 3:0', + '2:4 -> 4:0', + '2:4 -> 5:4', + '2:4 -> 6:8', + '2:24 -> 7:4', + '2:24 -> 8:0', + '2:4 -> 9:0', + '2:4 -> 10:4', + '2:4 -> 11:8', + '2:24 -> 12:4', + '2:24 -> 13:0', + '2:4 -> 14:0', + '2:4 -> 15:4', + '2:4 -> 16:8', + '2:24 -> 17:4', + '2:24 -> 18:0', + '2:4 -> 19:0', + '2:4 -> 20:4', + '2:4 -> 21:8', + '2:24 -> 22:4', + '2:24 -> 23:0', + '2:4 -> 24:0', + '2:4 -> 25:4', + '2:4 -> 26:8', + '2:24 -> 27:4', + '2:24 -> 28:0', + ]) +}) diff --git a/tests/util/run.js b/tests/util/run.js --- a/tests/util/run.js +++ b/tests/util/run.js @@ -5,6 +5,14 @@ import tailwind from '../../src' export * from './strings' export * from './defaults' +let map = JSON.stringify({ + version: 3, + file: null, + sources: [], + names: [], + mappings: '', +}) + export function run(input, config, plugin = tailwind) { let { currentTestName } = expect.getState() @@ -12,3 +20,14 @@ export function run(input, config, plugin = tailwind) { from: `${path.resolve(__filename)}?test=${currentTestName}`, }) } + +export function runWithSourceMaps(input, config, plugin = tailwind) { + let { currentTestName } = expect.getState() + + return postcss(plugin(config)).process(input, { + from: `${path.resolve(__filename)}?test=${currentTestName}`, + map: { + prev: map, + }, + }) +} diff --git a/tests/util/source-maps.js b/tests/util/source-maps.js new file mode 100644 --- /dev/null +++ b/tests/util/source-maps.js @@ -0,0 +1,79 @@ +import { SourceMapConsumer } from 'source-map-js' + +/** + * Parse the source maps from a PostCSS result + * + * @param {import('postcss').Result} result + */ +export function parseSourceMaps(result) { + const map = result.map.toJSON() + + return { + sources: map.sources, + annotations: annotatedMappings(map), + } +} + +/** + * An string annotation that represents a source map + * + * It's not meant to be exhaustive just enough to + * verify that the source map is working and that + * lines are mapped back to the original source + * + * Including when using @apply with multiple classes + * + * @param {import('source-map-js').RawSourceMap} map + */ +function annotatedMappings(map) { + const smc = new SourceMapConsumer(map) + const annotations = {} + + smc.eachMapping((mapping) => { + let annotation = (annotations[mapping.generatedLine] = annotations[mapping.generatedLine] || { + ...mapping, + + original: { + start: [mapping.originalLine, mapping.originalColumn], + end: [mapping.originalLine, mapping.originalColumn], + }, + + generated: { + start: [mapping.generatedLine, mapping.generatedColumn], + end: [mapping.generatedLine, mapping.generatedColumn], + }, + }) + + annotation.generated.end[0] = mapping.generatedLine + annotation.generated.end[1] = mapping.generatedColumn + + annotation.original.end[0] = mapping.originalLine + annotation.original.end[1] = mapping.originalColumn + }) + + return Object.values(annotations).map((annotation) => { + return `${formatRange(annotation.original)} -> ${formatRange(annotation.generated)}` + }) +} + +/** + * @param {object} range + * @param {[number, number]} range.start + * @param {[number, number]} range.end + */ +function formatRange(range) { + if (range.start[0] === range.end[0]) { + // This range is on the same line + // and the columns are the same + if (range.start[1] === range.end[1]) { + return `${range.start[0]}:${range.start[1]}` + } + + // This range is on the same line + // but the columns are different + return `${range.start[0]}:${range.start[1]}-${range.end[1]}` + } + + // This range spans multiple lines + return `${range.start[0]}:${range.start[1]}-${range.end[0]}:${range.end[1]}` +}
Enabling JIT breaks sourcemaps in webpack + PostCSS project ### What version of Tailwind CSS are you using? 2.2.6 ### What build tool (or framework if it abstracts the build tool) are you using? webpack 5.46.0, postcss 8.3.6 ### What version of Node.js are you using? 14.17.0 ### What browser are you using? Chrome ### What operating system are you using? Ubuntu ### Reproduction repository β € ### Describe your issue When using Tailwind's JIT option for processing PostCSS in the webpack project, source maps are not being shown in the Chrome DevTools (but still generated in the output CSS file). The value of `devtool` option in the webpack config doesn't matter, the result is the same. With config like this: ``` purge: [ './src/**/*.tsx', ], mode: 'jit', ``` Source maps don't get processed: ![Screenshot from 2021-07-22 16-36-57](https://user-images.githubusercontent.com/3055750/126648794-ffeed31f-df8c-4cf5-a6b7-20c2ac834799.png) When disabling the JIT option: ``` purge: false, ``` Source maps are being processed properly, and the original file is shown in Chrome DevTools: ![Screenshot from 2021-07-22 16-30-51](https://user-images.githubusercontent.com/3055750/126649229-f6154cf6-42b1-4b5f-9d6b-35366f31de8f.png) I'll bootstrap a repro repo if a more thorough investigation is needed. Add a `from` when postcss parsing preflight <!-- πŸ‘‹ Hey, thanks for your interest in contributing to Tailwind! **Please ask first before starting work on any significant new features.** It's never a fun experience to have your pull request declined after investing a lot of time and effort into a new feature. To avoid this from happening, we request that contributors create an issue to first discuss any significant new features. This includes things like adding new utilities, creating new at-rules, or adding new component examples to the documentation. https://github.com/tailwindcss/tailwindcss/blob/master/.github/CONTRIBUTING.md --> Hi, I was tracking down today why builds for some of our apps were not deterministic. I believe it's because no `from` is provided to `postcss.parse`, so it generates a random ID every compilation. I am out of my depth with frontend tooling, so I wasn't sure how this `from` value is used and if what I've done is appropriate. Regardless, I believe it should be something stable and non-null. See https://github.com/postcss/postcss/issues/1512 and https://github.com/tailwindlabs/tailwindcss/pull/3356 for a related issue and discussion. Fixes #7583
**here is a workaround until JIT and sourcemaps work ( it is breaking as of v2.2.7) ** - need two config files (tailwind.config.js) one file with JIT enabled the other disabled. - tailwind.css < @tailwind components; @tailwind utilities; - styles.scss < @tailwind base; import xyz // and Load SCSS via globing / scss can have @apply - and run two tasks to process style sheets ` return src(${options.paths.src.css}/tailwind.css) .pipe(postcss([ require('postcss-import'), tailwindcss(options.config.tailwindjs) ]))` ` return src(${options.paths.src.css}/**styles.scss**) .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(postcss([ tailwindcss(options.config.tailwindnoJIT) ]))` and voila sourcemaps are working working with JIT and is blazing fast, styles sheets small as well :) @adamwathan FYI, sourcemaps still not working with JIT enabled in `2.2.7`. ![Screenshot from 2021-08-04 11-53-26](https://user-images.githubusercontent.com/3055750/128153175-4e19701c-9d06-4f4f-82f3-832caf38a382.png) ![Screenshot from 2021-08-04 11-55-11](https://user-images.githubusercontent.com/3055750/128153176-674af11f-e275-452f-a526-09a138269358.png) Same here. Source maps won't work in JIT mode. I just tried to make a new simple project with webpack and tailwind just to try it out. If I dont use JIT then the source maps works. If I use the mode JIT then the source maps wont work. I use Tailwind together with some CMS and some elements I cant add css classes to, so I have to use @apply to style those elements. I added some screenshots down below to show my project and how it looks in firefox dev tools. **working source maps in firefox dev tools (JIT disabled)** ![working source maps in firefox dev tools (JIT disabled)](https://user-images.githubusercontent.com/43706427/133685149-91b845ed-1da5-447d-8839-5bf691f76a86.jpg) **broken source maps in firefox dev tools (JIT enabled)** ![broken source maps in firefox dev tools (JIT enabled)](https://user-images.githubusercontent.com/43706427/133684908-94e542da-65cb-4b63-b438-b4a66faed743.jpg) **error message in firefox dev tools (JIT enabled)** ![error message in friefox dev tools (JIT enabled)](https://user-images.githubusercontent.com/43706427/133684978-95795b5b-c1b0-4f89-bdba-0325276a0ab1.jpg) **how I import tailwind files to my css** ![how I import tailwind to my css](https://user-images.githubusercontent.com/43706427/133685039-c4586cf2-b47f-42ef-8745-d454795f1857.jpg) **index.js in vscode** ![index js in vscode](https://user-images.githubusercontent.com/43706427/133685082-0343fd06-e715-4def-84b2-47f84f9374fa.jpg) **typography.css in vscode** ![typography css in vscode](https://user-images.githubusercontent.com/43706427/133685119-44ce11bf-a043-4ec9-8410-0b859f9cbfe4.jpg) Same here. Is there any prospect of fixing this problem. We would not like to do without the JIT, because we now also use arbitrary value support that only works with the JIT. But working without SourceMap is also tedious. Same here too, I tried some different configurations with different builder or method but I not found any solution and my comprehension about how jit works with sourcemaps is so limited that i cannot deep dive into code to inspect and get a solution to help :( Adding any regular css rule or even a simple comment will generate sourcemaps correctly. ```html <div class="with-sourcemap"></div> <div class="with-another-sourcemap"></div> <div class="no-sourcemap-here"></div> ``` ```pcss .with-sourcemap { background-color: red; @apply h-4 w-4 bg-green-500; } .with-another-sourcemap { /* sourcemap will work here too */ @apply h-4 w-4 bg-red-500; } .no-sourcemap-here { @apply h-4 w-4 bg-black; } ``` ![image](https://user-images.githubusercontent.com/5835044/151717106-64a76fe6-8f28-4052-95e3-2ade4f71c1d4.png) ![image](https://user-images.githubusercontent.com/5835044/151717114-b88e7e6d-0597-4624-9758-0ec267fc7752.png) ![image](https://user-images.githubusercontent.com/5835044/151717126-b132a0be-c401-43df-9543-24995b6efb9f.png) Source maps are also not working properly in 3.0.19. `src/css/app.css` ``` @tailwind base; @tailwind components; @tailwind utilities; ``` `src/js/app.js` ``` import '../css/app.css' ``` `webpack.config.js` ``` const path = require('path') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const CssMinimizerPlugin = require('css-minimizer-webpack-plugin') module.exports = (env, argv) => { process.env.NODE_ENV = argv.mode return { devtool: 'source-map', entry: { app: '/src/js/app.js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: 'babel-loader' }, { test: /\.css$/, exclude: /node_modules/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', ], } ] }, optimization: { minimize: true, minimizer: [ `...`, new CssMinimizerPlugin(), ], }, output: { chunkFilename: '[name].[contenthash].js', clean: true, filename: '[name].js', path: path.resolve(__dirname, 'public/dist') }, plugins: [ new MiniCssExtractPlugin({filename: '[name].css'}) ] } } ``` The generated `public/dist/app.css.map` includes this section: ``` "sources":["webpack://@test/test/./src/css/app.css","webpack://@test/test/./src/css/%3Cinput%20css%20doRbU6%3E","webpack://@test/test/<no source>"] ``` Using Chrome DevTools all the Tailwind CSS rules show as `<no source>:1` Thanks! Gonna take a look at this either today or tomorrow as I'll be making a few fixes to source map generation.
"2022-02-22T21:18:13Z"
3.0
[]
[ "tests/source-maps.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/3055750/126648794-ffeed31f-df8c-4cf5-a6b7-20c2ac834799.png", "https://user-images.githubusercontent.com/3055750/126649229-f6154cf6-42b1-4b5f-9d6b-35366f31de8f.png" ]
[]
tailwindlabs/tailwindcss
7,664
tailwindlabs__tailwindcss-7664
[ "7226" ]
bd167635d5ea3866ebcae2fd390393befd730558
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -88,7 +88,7 @@ function applyPrefix(matches, context) { return matches } -function applyImportant(matches) { +function applyImportant(matches, classCandidate) { if (matches.length === 0) { return matches } @@ -98,7 +98,10 @@ function applyImportant(matches) { let container = postcss.root({ nodes: [rule.clone()] }) container.walkRules((r) => { r.selector = updateAllClasses(r.selector, (className) => { - return `!${className}` + if (className === classCandidate) { + return `!${className}` + } + return className }) r.walkDecls((d) => (d.important = true)) }) @@ -514,7 +517,7 @@ function* resolveMatches(candidate, context) { matches = applyPrefix(matches, context) if (important) { - matches = applyImportant(matches, context) + matches = applyImportant(matches, classCandidate) } for (let variant of variants) {
diff --git a/tests/important-modifier.test.js b/tests/important-modifier.test.js --- a/tests/important-modifier.test.js +++ b/tests/important-modifier.test.js @@ -17,6 +17,22 @@ test('important modifier', () => { }, ], corePlugins: { preflight: false }, + plugins: [ + function ({ theme, matchUtilities }) { + matchUtilities( + { + 'custom-parent': (value) => { + return { + '.custom-child': { + margin: value, + }, + } + }, + }, + { values: theme('spacing') } + ) + }, + ], } let input = css` @@ -57,6 +73,9 @@ test('important modifier', () => { .\!font-bold { font-weight: 700 !important; } + .\!custom-parent-5 .custom-child { + margin: 1.25rem !important; + } .hover\:\!text-center:hover { text-align: center !important; }
! important not working as expected with the matchUtilities **What version of Tailwind CSS are you using?** Tailwind v3.0.14 **What build tool (or framework if it abstracts the build tool) are you using?** postcss-cli 8.3.1 **What browser are you using?** Chrome, **What operating system are you using?** Windows **Reproduction URL**. https://play.tailwindcss.com/zEL8hw6BSy **Describe your issue** Creating a match utilities that has subclasses isn't working correctly with !important. I created the following matchUtilities to enable editing the title font-size from the parent (for headless CMS scenario) `'card-title-text': (value) => ({'.card-title': {'font-size': value,}}),` Doing so worked as expected for normal classes and generated the following class: `.card-title-text-4xl .card-title { font-size: 2.25rem/* 36px */; font-size: [object Object]; }` but for !card-title-text-4xl it applied the ! to all subclasses as well generating the following css ``` .\!card-title-text-4xl .\!card-title { font-size: 2.25rem/* 36px */ !important; font-size: [object Object] !important; } ``` The \! prefix before the card-title i believe shouldn't exist
"2022-02-25T18:04:37Z"
3.0
[]
[ "tests/important-modifier.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/zEL8hw6BSy" ]
tailwindlabs/tailwindcss
7,665
tailwindlabs__tailwindcss-7665
[ "4659", "3953" ]
f7a9d370c87f0d804c8b5924e1f04eb7ad82cd33
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -1964,10 +1964,16 @@ export let corePlugins = { }) }, - ringColor: ({ matchUtilities, theme }) => { + ringColor: ({ matchUtilities, theme, corePlugins }) => { matchUtilities( { ring: (value) => { + if (!corePlugins('ringOpacity')) { + return { + '--tw-ring-color': toColorValue(value), + } + } + return withAlphaVariable({ color: value, property: '--tw-ring-color', diff --git a/src/util/resolveConfig.js b/src/util/resolveConfig.js --- a/src/util/resolveConfig.js +++ b/src/util/resolveConfig.js @@ -66,6 +66,36 @@ const configUtils = { {} ) }, + rgb(property) { + if (!property.startsWith('--')) { + throw new Error( + 'The rgb() helper requires a custom property name to be passed as the first argument.' + ) + } + + return ({ opacityValue }) => { + if (opacityValue === undefined || opacityValue === 1) { + return `rgb(var(${property}) / 1.0)` + } + + return `rgb(var(${property}) / ${opacityValue})` + } + }, + hsl(property) { + if (!property.startsWith('--')) { + throw new Error( + 'The hsl() helper requires a custom property name to be passed as the first argument.' + ) + } + + return ({ opacityValue }) => { + if (opacityValue === undefined || opacityValue === 1) { + return `hsl(var(${property}) / 1)` + } + + return `hsl(var(${property}) / ${opacityValue})` + } + }, } function value(valueToResolve, ...args) {
diff --git a/tests/opacity.test.js b/tests/opacity.test.js --- a/tests/opacity.test.js +++ b/tests/opacity.test.js @@ -95,3 +95,335 @@ test('colors defined as functions work when opacity plugins are disabled', () => `) }) }) + +it('can use rgb helper when defining custom properties for colors (opacity plugins enabled)', () => { + let config = { + content: [ + { + raw: html` + <div class="divide-primary"></div> + <div class="divide-primary divide-opacity-50"></div> + <div class="border-primary"></div> + <div class="border-primary border-opacity-50"></div> + <div class="bg-primary"></div> + <div class="bg-primary bg-opacity-50"></div> + <div class="text-primary"></div> + <div class="text-primary text-opacity-50"></div> + <div class="placeholder-primary"></div> + <div class="placeholder-primary placeholder-opacity-50"></div> + <div class="ring-primary"></div> + <div class="ring-primary ring-opacity-50"></div> + `, + }, + ], + theme: { + colors: ({ rgb }) => ({ + primary: rgb('--color-primary'), + }), + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchCss(css` + .divide-primary > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 1; + border-color: rgb(var(--color-primary) / var(--tw-divide-opacity)); + } + .divide-opacity-50 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 0.5; + } + .border-primary { + --tw-border-opacity: 1; + border-color: rgb(var(--color-primary) / var(--tw-border-opacity)); + } + .border-opacity-50 { + --tw-border-opacity: 0.5; + } + .bg-primary { + --tw-bg-opacity: 1; + background-color: rgb(var(--color-primary) / var(--tw-bg-opacity)); + } + .bg-opacity-50 { + --tw-bg-opacity: 0.5; + } + .text-primary { + --tw-text-opacity: 1; + color: rgb(var(--color-primary) / var(--tw-text-opacity)); + } + .text-opacity-50 { + --tw-text-opacity: 0.5; + } + .placeholder-primary::placeholder { + --tw-placeholder-opacity: 1; + color: rgb(var(--color-primary) / var(--tw-placeholder-opacity)); + } + .placeholder-opacity-50::placeholder { + --tw-placeholder-opacity: 0.5; + } + .ring-primary { + --tw-ring-opacity: 1; + --tw-ring-color: rgb(var(--color-primary) / var(--tw-ring-opacity)); + } + .ring-opacity-50 { + --tw-ring-opacity: 0.5; + } + `) + }) +}) + +it('can use rgb helper when defining custom properties for colors (opacity plugins disabled)', () => { + let config = { + content: [ + { + raw: html` + <div class="divide-primary"></div> + <div class="divide-primary/50"></div> + <div class="border-primary"></div> + <div class="border-primary/50"></div> + <div class="bg-primary"></div> + <div class="bg-primary/50"></div> + <div class="text-primary"></div> + <div class="text-primary/50"></div> + <div class="placeholder-primary"></div> + <div class="placeholder-primary/50"></div> + <div class="ring-primary"></div> + <div class="ring-primary/50"></div> + `, + }, + ], + theme: { + colors: ({ rgb }) => ({ + primary: rgb('--color-primary'), + }), + }, + corePlugins: { + backgroundOpacity: false, + borderOpacity: false, + divideOpacity: false, + placeholderOpacity: false, + textOpacity: false, + ringOpacity: false, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .divide-primary > :not([hidden]) ~ :not([hidden]) { + border-color: rgb(var(--color-primary) / 1); + } + .divide-primary\/50 > :not([hidden]) ~ :not([hidden]) { + border-color: rgb(var(--color-primary) / 0.5); + } + .border-primary { + border-color: rgb(var(--color-primary) / 1); + } + .border-primary\/50 { + border-color: rgb(var(--color-primary) / 0.5); + } + .bg-primary { + background-color: rgb(var(--color-primary) / 1); + } + .bg-primary\/50 { + background-color: rgb(var(--color-primary) / 0.5); + } + .text-primary { + color: rgb(var(--color-primary) / 1); + } + .text-primary\/50 { + color: rgb(var(--color-primary) / 0.5); + } + .placeholder-primary::placeholder { + color: rgb(var(--color-primary) / 1); + } + .placeholder-primary\/50::placeholder { + color: rgb(var(--color-primary) / 0.5); + } + .ring-primary { + --tw-ring-color: rgb(var(--color-primary) / 1); + } + .ring-primary\/50 { + --tw-ring-color: rgb(var(--color-primary) / 0.5); + } + `) + }) +}) + +it('can use hsl helper when defining custom properties for colors (opacity plugins enabled)', () => { + let config = { + content: [ + { + raw: html` + <div class="divide-primary"></div> + <div class="divide-primary divide-opacity-50"></div> + <div class="border-primary"></div> + <div class="border-primary border-opacity-50"></div> + <div class="bg-primary"></div> + <div class="bg-primary bg-opacity-50"></div> + <div class="text-primary"></div> + <div class="text-primary text-opacity-50"></div> + <div class="placeholder-primary"></div> + <div class="placeholder-primary placeholder-opacity-50"></div> + <div class="ring-primary"></div> + <div class="ring-primary ring-opacity-50"></div> + `, + }, + ], + theme: { + colors: ({ hsl }) => ({ + primary: hsl('--color-primary'), + }), + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchCss(css` + .divide-primary > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 1; + border-color: hsl(var(--color-primary) / var(--tw-divide-opacity)); + } + .divide-opacity-50 > :not([hidden]) ~ :not([hidden]) { + --tw-divide-opacity: 0.5; + } + .border-primary { + --tw-border-opacity: 1; + border-color: hsl(var(--color-primary) / var(--tw-border-opacity)); + } + .border-opacity-50 { + --tw-border-opacity: 0.5; + } + .bg-primary { + --tw-bg-opacity: 1; + background-color: hsl(var(--color-primary) / var(--tw-bg-opacity)); + } + .bg-opacity-50 { + --tw-bg-opacity: 0.5; + } + .text-primary { + --tw-text-opacity: 1; + color: hsl(var(--color-primary) / var(--tw-text-opacity)); + } + .text-opacity-50 { + --tw-text-opacity: 0.5; + } + .placeholder-primary::placeholder { + --tw-placeholder-opacity: 1; + color: hsl(var(--color-primary) / var(--tw-placeholder-opacity)); + } + .placeholder-opacity-50::placeholder { + --tw-placeholder-opacity: 0.5; + } + .ring-primary { + --tw-ring-opacity: 1; + --tw-ring-color: hsl(var(--color-primary) / var(--tw-ring-opacity)); + } + .ring-opacity-50 { + --tw-ring-opacity: 0.5; + } + `) + }) +}) + +it('can use hsl helper when defining custom properties for colors (opacity plugins disabled)', () => { + let config = { + content: [ + { + raw: html` + <div class="divide-primary"></div> + <div class="divide-primary/50"></div> + <div class="border-primary"></div> + <div class="border-primary/50"></div> + <div class="bg-primary"></div> + <div class="bg-primary/50"></div> + <div class="text-primary"></div> + <div class="text-primary/50"></div> + <div class="placeholder-primary"></div> + <div class="placeholder-primary/50"></div> + <div class="ring-primary"></div> + <div class="ring-primary/50"></div> + `, + }, + ], + theme: { + colors: ({ hsl }) => ({ + primary: hsl('--color-primary'), + }), + }, + corePlugins: { + backgroundOpacity: false, + borderOpacity: false, + divideOpacity: false, + placeholderOpacity: false, + textOpacity: false, + ringOpacity: false, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchCss(css` + .divide-primary > :not([hidden]) ~ :not([hidden]) { + border-color: hsl(var(--color-primary) / 1); + } + .divide-primary\/50 > :not([hidden]) ~ :not([hidden]) { + border-color: hsl(var(--color-primary) / 0.5); + } + .border-primary { + border-color: hsl(var(--color-primary) / 1); + } + .border-primary\/50 { + border-color: hsl(var(--color-primary) / 0.5); + } + .bg-primary { + background-color: hsl(var(--color-primary) / 1); + } + .bg-primary\/50 { + background-color: hsl(var(--color-primary) / 0.5); + } + .text-primary { + color: hsl(var(--color-primary) / 1); + } + .text-primary\/50 { + color: hsl(var(--color-primary) / 0.5); + } + .placeholder-primary::placeholder { + color: hsl(var(--color-primary) / 1); + } + .placeholder-primary\/50::placeholder { + color: hsl(var(--color-primary) / 0.5); + } + .ring-primary { + --tw-ring-color: hsl(var(--color-primary) / 1); + } + .ring-primary\/50 { + --tw-ring-color: hsl(var(--color-primary) / 0.5); + } + `) + }) +}) + +it('the rgb helper throws when not passing custom properties', () => { + let config = { + theme: { + colors: ({ rgb }) => ({ + primary: rgb('anything else'), + }), + }, + } + + return expect(run('@tailwind utilities', config)).rejects.toThrow( + 'The rgb() helper requires a custom property name to be passed as the first argument.' + ) +}) + +it('the hsl helper throws when not passing custom properties', () => { + let config = { + theme: { + colors: ({ hsl }) => ({ + primary: hsl('anything else'), + }), + }, + } + + return expect(run('@tailwind utilities', config)).rejects.toThrow( + 'The hsl() helper requires a custom property name to be passed as the first argument.' + ) +})
Add support for cssvar colors to `withAlphaVariable` and `withAlphaValue` As mentioned in this discussion https://github.com/tailwindlabs/tailwindcss/discussions/4205 (and can be seen in this demo https://play.tailwindcss.com/Q7aU4F9lpb) currently using css variables to define colors breaks down somewhat if the are used anywhere were an alpha channel is added. I've extended the `withAlphaVariable` and `withAlphaValue` utils to check if a css variable was defined as numeric values `--color-var: 255, 0, 255` and consequently used like this in the config `DEFAULT: 'rgb(var(--color-var))'`. My implementation will work for both `rgb` and `hsl` as long as they were valid colors to begin with and should be somewhat resistant to inconsistent whitespace use. The only downside of this implementation is that you won't be able to use variables containing hex colors directly but you need to define them as a numeric triple as shown in my example above. Since this is my first PR to this project I really hope everything is in order but feel free discuss issues of this solution with me πŸ™‚ Suggestion: improve support for color css variables ### What version of @tailwindcss/jit are you using? 0.1.6 ### What version of Node.js are you using? 14 ### What browser are you using? all ### What operating system are you using? linux ### Reproduction repository no need Today with tailwind, it is not that easy to use the colors stored in a css variable. If we do this `--color-primary: theme(colors.blue.500);`, `--color-primary: #hexcolor;`, `--color-primary: rgb (255,255,255)` or other color format, we definitely lose the ability to add color opacity. So, we are forced to store the color in an unconventional way: `--color-primary: 59, 130, 246;`. This brings some disappointment: hand conversion, no visual on colors in IDEs ![Imgur](https://i.imgur.com/Ow4tDFX.jpg) I think it will be interesting to have a function available that allows at build time to convert the most common color format to one that takes advantage of opacity. Like that ![Imgur](https://i.imgur.com/MT3T89b.jpg) ```css /* result to */ --color-primary: 59, 130, 246; ``` - After that, in the same way, we can declare the color in tailwind.config ```js // ... colors: { yellow: colors.orange, primary: varToRgba('--color-primary'), } // ... ``` - And / or, as in a recent similar library, proposing to create classes on the fly with a syntax like this: `border-$color-primary` (with opacity support of course) Thanks a lot for your work!
It took me a bit to figure out how to get a working local build with a custom config, but I was also able to verify that my demo is now working correctly. (The second square uses a non-rgb variable and therefore it's expected that it isn't semi-transparent) ![image](https://user-images.githubusercontent.com/3532342/122193527-da6d2600-ce94-11eb-9572-6b17e677e914.png) Any plans to merge this? We really need a solution for custom css variables with bg-opacity. @memic84 it's pretty hidden in the documentation but you can actually use this as a "workaround": ```JS const getColor = (colorVar, { opacityVariable, opacityValue }) => { if (opacityValue !== undefined) { return `rgba(var(${colorVar}), ${opacityValue})`; } if (opacityVariable !== undefined) { return `rgba(var(${colorVar}), var(${opacityVariable}, 1))`; } return `rgb(var(${colorVar}))`; }; module.exports = { // ... theme: { extend: { colors: { primary: (params) => getColor('--color-primary-rgb', params), } } } ``` I still would like this PR merged, because I think everyone would benefit from making this easier. > @memic84 it's pretty hidden in the documentation but you can actually use this as a "workaround": > > ```js > const getColor = (colorVar, { opacityVariable, opacityValue }) => { > if (opacityValue !== undefined) { > return `rgba(var(${colorVar}), ${opacityValue})`; > } > if (opacityVariable !== undefined) { > return `rgba(var(${colorVar}), var(${opacityVariable}, 1))`; > } > > return `rgb(var(${colorVar}))`; > }; > > module.exports = { > // ... > theme: { > extend: { > colors: { > primary: (params) => getColor('--color-primary-rgb', params), > } > } > } > ``` > > I still would like this PR merged, because I think everyone would benefit from making this easier. This doesn't seem to work in combination with `@apply`. @PeeJeeDR works for me without a problem in my angular project, even VS Code intellisense picks it up with the tailwind extension. Hey thanks for this! Any thoughts on how this could possibly work with both the old and new rgb/hsl formats? ``` --color-1: 12, 34, 56 rgb(var(--color-1)) --color-2: 12 34 56 rgb(var(--color-2) ``` Both of those are valid, and depending on the syntax used, the comma before the alpha channel needs to be omitted πŸ€” @adamwathan good catch, I think there is no good way of handling this besides convention or maybe a config option which way you intend to use. Using JIT you could try to read the value of the var, but I don't know if the overhead is worth it. We're going to make some internal changes to use the new rgb/hsl format for all colors we generate internally, then let's update this to use that as well and just assume people are using space-separated syntax. Will target v3 which will be in alpha/beta in like a month, and released in November πŸ‘πŸ» Hey we've updated Tailwind internally to use the space separated syntax for all color related work that we do. Do you mind updating this PR to work based on that assumption? πŸ™ @reinink sure I will try to look into it over the weekend πŸ˜‰ @reinink @adamwathan I've just started looking into this and I was wondering if it's ok to be very specific with the expected format. ``` // this is going to work rgb(var(--my-color-var)) // --my-color-var: 255 0 0; hsl(var(--my-color-var)) // --my-color-var: 0 100% 50%; // this is not going to work rgb(var(--my-color-var)) // --my-color-var: 255, 0, 0; hsl(var(--my-color-var)) // --my-color-var: 0, 100%, 50%; rgb(var(--my-color-var)) // --my-color-var: 255 0 0 / 0.1; hsl(var(--my-color-var)) // --my-color-var: 0 100% 50% / 0.1; rgba(var(--my-color-var)) // --my-color-var: 255 0 0 0.1; hsla(var(--my-color-var)) // --my-color-var: 0 100% 50% 0.1; ``` What do you think? Supporting the `rgba` syntax would in theory be possible, but then the set opacity level (e.g. bg-opacity-10) can still not be applied. You can take a look if you are happy with my current changes. rgba/hsla values stay as is, but for rgb/hsl values not in the described format this could be a breaking change if anyone is currently using those as color values. Just following up on this (we're doing a big GitHub clean up) β€” my only concern is this one not working: ```css :root { --my-color-var: 255 0 0 / 0.1; } ``` It feels bad that if someone wants to define colors that have the opacity baked in that everything would break. Maybe this is okay though because if someone wanted to do that they wouldn't define the color as channels but rather as a full color? ```css :root { --my-color-var: rgb(255 0 0 / 0.1); } ``` I kinda wonder though if trying to do this all automagically is just too much and instead we could just offer a helper function people could use? For example: ```js // tailwind.config.js module.exports = { theme: { colors: ({ rgb, hsl }) => ({ primary: rgb('--color-primary'), secondary: hsl('--color-secondary'), // ... }) } } ``` You'd need to know about those helpers of course but it feels a lot more mechanically simple to me, with less chances of discovering an edge case down the road that we've accidentally made impossible to solve without a breaking change. Would love to see variables get first class support Currently using https://github.com/mertasan/tailwindcss-variables which is great for generating and using variables, but overriding means writing css like `colors-primary-rgb: 255, 0, 255;` If you're revisiting the color system, please make it work with CSS Color Level 4 (see: #2218) as well. The way the colors are deconstructed internally makes it absolutely impossible to specify any color using the CSS color() function and have it work with opacity.
"2022-02-25T18:48:19Z"
3.0
[]
[ "tests/opacity.test.js" ]
TypeScript
[ "https://i.imgur.com/Ow4tDFX.jpg", "https://i.imgur.com/MT3T89b.jpg" ]
[ "https://play.tailwindcss.com/Q7aU4F9lpb" ]
tailwindlabs/tailwindcss
7,789
tailwindlabs__tailwindcss-7789
[ "7771" ]
c6097d59fcd3b4a176188327adee488c562ecb8f
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -303,6 +303,19 @@ function looksLikeUri(declaration) { } } +function isParsableNode(node) { + let isParsable = true + + node.walkDecls((decl) => { + if (!isParsableCssValue(decl.name, decl.value)) { + isParsable = false + return false + } + }) + + return isParsable +} + function isParsableCssValue(property, value) { // We don't want to to treat [https://example.com] as a custom property // Even though, according to the CSS grammar, it's a totally valid CSS declaration @@ -456,60 +469,66 @@ function* resolveMatches(candidate, context) { } } - // Only keep the result of the very first plugin if we are dealing with - // arbitrary values, to protect against ambiguity. - if (isArbitraryValue(modifier) && matches.length > 1) { - let typesPerPlugin = matches.map((match) => new Set([...(typesByMatches.get(match) ?? [])])) + if (isArbitraryValue(modifier)) { + // When generated arbitrary values are ambiguous, we can't know + // which to pick so don't generate any utilities for them + if (matches.length > 1) { + let typesPerPlugin = matches.map((match) => new Set([...(typesByMatches.get(match) ?? [])])) - // Remove duplicates, so that we can detect proper unique types for each plugin. - for (let pluginTypes of typesPerPlugin) { - for (let type of pluginTypes) { - let removeFromOwnGroup = false + // Remove duplicates, so that we can detect proper unique types for each plugin. + for (let pluginTypes of typesPerPlugin) { + for (let type of pluginTypes) { + let removeFromOwnGroup = false - for (let otherGroup of typesPerPlugin) { - if (pluginTypes === otherGroup) continue + for (let otherGroup of typesPerPlugin) { + if (pluginTypes === otherGroup) continue - if (otherGroup.has(type)) { - otherGroup.delete(type) - removeFromOwnGroup = true + if (otherGroup.has(type)) { + otherGroup.delete(type) + removeFromOwnGroup = true + } } - } - if (removeFromOwnGroup) pluginTypes.delete(type) + if (removeFromOwnGroup) pluginTypes.delete(type) + } } - } - let messages = [] - - for (let [idx, group] of typesPerPlugin.entries()) { - for (let type of group) { - let rules = matches[idx] - .map(([, rule]) => rule) - .flat() - .map((rule) => - rule - .toString() - .split('\n') - .slice(1, -1) // Remove selector and closing '}' - .map((line) => line.trim()) - .map((x) => ` ${x}`) // Re-indent - .join('\n') + let messages = [] + + for (let [idx, group] of typesPerPlugin.entries()) { + for (let type of group) { + let rules = matches[idx] + .map(([, rule]) => rule) + .flat() + .map((rule) => + rule + .toString() + .split('\n') + .slice(1, -1) // Remove selector and closing '}' + .map((line) => line.trim()) + .map((x) => ` ${x}`) // Re-indent + .join('\n') + ) + .join('\n\n') + + messages.push( + ` Use \`${candidate.replace('[', `[${type}:`)}\` for \`${rules.trim()}\`` ) - .join('\n\n') - - messages.push(` Use \`${candidate.replace('[', `[${type}:`)}\` for \`${rules.trim()}\``) - break + break + } } + + log.warn([ + `The class \`${candidate}\` is ambiguous and matches multiple utilities.`, + ...messages, + `If this is content and not a class, replace it with \`${candidate + .replace('[', '&lsqb;') + .replace(']', '&rsqb;')}\` to silence this warning.`, + ]) + continue } - log.warn([ - `The class \`${candidate}\` is ambiguous and matches multiple utilities.`, - ...messages, - `If this is content and not a class, replace it with \`${candidate - .replace('[', '&lsqb;') - .replace(']', '&rsqb;')}\` to silence this warning.`, - ]) - continue + matches = matches.map((list) => list.filter((match) => isParsableNode(match[1]))) } matches = matches.flat()
diff --git a/tests/arbitrary-values.test.js b/tests/arbitrary-values.test.js --- a/tests/arbitrary-values.test.js +++ b/tests/arbitrary-values.test.js @@ -370,3 +370,17 @@ it('should be possible to read theme values in arbitrary values (with quotes) wh `) }) }) + +it('should not output unparsable arbitrary CSS values', () => { + let config = { + content: [ + { + raw: 'let classes = `w-[${sizes.width}]`', + }, + ], + } + + return run('@tailwind utilities', config).then((result) => { + return expect(result.css).toMatchFormattedCss(``) + }) +})
JIT analysis the comments code to add that classes instead of omit it <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** For example: v3.0.17 **What build tool (or framework if it abstracts the build tool) are you using?** For example: postcss 8.4.5, Next.js 12.1.0 **What version of Node.js are you using?** For example: v17.3.1 **What browser are you using?** For example: N/A **What operating system are you using?** macOS **Describe your issue** Storybook can't start because JIT parses code from comments <img width="563" alt="imagen" src="https://user-images.githubusercontent.com/13077343/157001625-06c4caa4-b6b8-4e9d-90f9-4dcfd1daa6ee.png">
Hey, this is covered in the docs: https://tailwindcss.com/docs/content-configuration#dynamic-class-names. Tailwind CSS does not interpret your source code so dynamic class names like this won't work. Ideally, we would just _not_ generate the CSS here since it's generating values that appear to result in a syntax error. Will see what we can do about this.
"2022-03-08T17:17:23Z"
3.0
[]
[ "tests/arbitrary-values.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/13077343/157001625-06c4caa4-b6b8-4e9d-90f9-4dcfd1daa6ee.png" ]
[]
tailwindlabs/tailwindcss
8,091
tailwindlabs__tailwindcss-8091
[ "8079" ]
1d4c5c78bd7b22f11753f216649bc12ce481d5e3
diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -42,10 +42,16 @@ export function normalize(value, isRoot = true) { // Add spaces around operators inside calc() that do not follow an operator // or '('. - return value.replace( - /(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g, - '$1 $2 ' - ) + value = value.replace(/calc\(.+\)/g, (match) => { + return match.replace( + /(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g, + '$1 $2 ' + ) + }) + + // Add spaces around some operators not inside calc() that do not follow an operator + // or '('. + return value.replace(/(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([\/])/g, '$1 $2 ') } export function url(value) {
diff --git a/tests/normalize-data-types.test.js b/tests/normalize-data-types.test.js new file mode 100644 --- /dev/null +++ b/tests/normalize-data-types.test.js @@ -0,0 +1,42 @@ +import { normalize } from '../src/util/dataTypes' + +let table = [ + ['foo', 'foo'], + ['foo-bar', 'foo-bar'], + ['16/9', '16 / 9'], + + // '_'s are converted to spaces except when escaped + ['foo_bar', 'foo bar'], + ['foo__bar', 'foo bar'], + ['foo\\_bar', 'foo_bar'], + + // Urls are preserved as-is + [ + 'url("https://example.com/abc+def/some-path/2022-01-01-abc/some_underscoered_path")', + 'url("https://example.com/abc+def/some-path/2022-01-01-abc/some_underscoered_path")', + ], + + // var(…) is preserved as is + ['var(--foo)', 'var(--foo)'], + ['var(--headings-h1-size)', 'var(--headings-h1-size)'], + + // calc(…) get's spaces around operators + ['calc(1+2)', 'calc(1 + 2)'], + ['calc(100%+1rem)', 'calc(100% + 1rem)'], + ['calc(1+calc(100%-20px))', 'calc(1 + calc(100% - 20px))'], + ['calc(var(--headings-h1-size)*100)', 'calc(var(--headings-h1-size) * 100)'], + [ + 'calc(var(--headings-h1-size)*calc(100%+50%))', + 'calc(var(--headings-h1-size) * calc(100% + 50%))', + ], + ['var(--heading-h1-font-size)', 'var(--heading-h1-font-size)'], + ['var(--my-var-with-more-than-3-words)', 'var(--my-var-with-more-than-3-words)'], + ['var(--width, calc(100%+1rem))', 'var(--width, calc(100% + 1rem))'], + + // Misc + ['color(0_0_0/1.0)', 'color(0 0 0 / 1.0)'], +] + +it.each(table)('normalize data: %s', (input, output) => { + expect(normalize(input)).toBe(output) +})
Tailwind incorrect generate CSS variables as minus sign **What version of Tailwind CSS are you using?** 3.0.23 Hi, I am not sure if this issue is linked to the other problems I have reported in #7874 and #7884 as the output issue seems different. I am therefore opening a new issue. If I use the following CSS: ``` .prose h1 { @apply tw-text-[length:var(--heading-h1-font-size)]; } ``` Tailwind will generate the following code: ``` .prose h1 { font-size: var(--heading-h1 - font-size); } ``` For some reason the dash after the -h1 part is considered as a minus (maybe due to the number ?). In all cases this seems like a bug. Thanks :)
Definitely seems like a bug and I think you’re right it’s probably because of the number! Will try to look at this this week πŸ‘πŸ»
"2022-04-11T21:39:57Z"
3.0
[]
[ "tests/normalize-data-types.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,121
tailwindlabs__tailwindcss-8121
[ "8102" ]
206f1d6df536b54feea505f004ab4a626ca47caf
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -382,7 +382,11 @@ function* resolveMatchedPlugins(classCandidate, context) { const twConfigPrefix = context.tailwindConfig.prefix const twConfigPrefixLen = twConfigPrefix.length - if (candidatePrefix[twConfigPrefixLen] === '-') { + + const hasMatchingPrefix = + candidatePrefix.startsWith(twConfigPrefix) || candidatePrefix.startsWith(`-${twConfigPrefix}`) + + if (candidatePrefix[twConfigPrefixLen] === '-' && hasMatchingPrefix) { negative = true candidatePrefix = twConfigPrefix + candidatePrefix.slice(twConfigPrefixLen + 1) }
diff --git a/tests/prefix.test.js b/tests/prefix.test.js --- a/tests/prefix.test.js +++ b/tests/prefix.test.js @@ -358,3 +358,19 @@ it('prefix with negative values and variants in the safelist', async () => { } `) }) + +it('prefix does not detect and generate unnecessary classes', async () => { + let config = { + prefix: 'tw-_', + content: [{ raw: html`-aaa-filter aaaa-table aaaa-hidden` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css``) +})
πŸ› Unnecessary classes are output <details> <summary>Environments</summary> **What version of Tailwind CSS are you using?** v3.0.24 **What build tool (or framework if it abstracts the build tool) are you using?** postcss v8.4.7, webpack v5.72.0 **What version of Node.js are you using?** v16.13.2 **What browser are you using?** N/A **What operating system are you using?** macOS </details> **Reproduction URL** - https://play.tailwindcss.com/KvFiBdkhw3 To check the output of 2 characters, change `prefix:'tw_-'` to `prefix:'tw-'` in `Config` tab. - https://play.tailwindcss.com/00iNAwt2JZ **Describe your issue** As the title says. Unnecessary classes should not be output.
"2022-04-15T15:52:00Z"
3.0
[]
[ "tests/prefix.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/KvFiBdkhw3", "https://play.tailwindcss.com/00iNAwt2JZ" ]
tailwindlabs/tailwindcss
8,122
tailwindlabs__tailwindcss-8122
[ "8103" ]
5c76de72baa408d6cd32cd7ba97660617da6ff34
diff --git a/src/lib/collapseAdjacentRules.js b/src/lib/collapseAdjacentRules.js --- a/src/lib/collapseAdjacentRules.js +++ b/src/lib/collapseAdjacentRules.js @@ -29,7 +29,11 @@ export default function collapseAdjacentRules() { (currentRule[property] ?? '').replace(/\s+/g, ' ') ) ) { - currentRule.append(node.nodes) + // An AtRule may not have children (for example if we encounter duplicate @import url(…) rules) + if (node.nodes) { + currentRule.append(node.nodes) + } + node.remove() } else { currentRule = node
diff --git a/tests/collapse-adjacent-rules.test.js b/tests/collapse-adjacent-rules.test.js --- a/tests/collapse-adjacent-rules.test.js +++ b/tests/collapse-adjacent-rules.test.js @@ -1,7 +1,7 @@ import fs from 'fs' import path from 'path' -import { run, css } from './util/run' +import { run, html, css } from './util/run' test('collapse adjacent rules', () => { let config = { @@ -61,3 +61,21 @@ test('collapse adjacent rules', () => { expect(result.css).toMatchFormattedCss(expected) }) }) + +test('duplicate url imports does not break rule collapsing', () => { + let config = { + content: [{ raw: html`` }], + corePlugins: { preflight: false }, + } + + let input = css` + @import url('https://example.com'); + @import url('https://example.com'); + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + @import url('https://example.com'); + `) + }) +})
Duplicate @import CSS rules cause undefined behaviour **What version of Tailwind CSS are you using?** v3.0.24 **What build tool (or framework if it abstracts the build tool) are you using?** vite 2.9.1 **What version of Node.js are you using?** v16.11.0 **What browser are you using?** N/A **What operating system are you using?** Linux **Reproduction URL** https://github.com/jordimarimon/tailwindcss-duplicate-imports **Describe your issue** Hi! First of all, thanks for this amazing library! I am using a third party library that I can't modify and this library has duplicate `@import` CSS rules. Because of this duplicate `@import` CSS rules I get the following error from the Tailwind PostCSS plugin: ``` TypeError: Cannot read properties of undefined (reading 'type') at AtRule.normalize (<path-to-project>/tailwindcss-duplicate-imports/node_modules/postcss/lib/container.js:294:22) at AtRule.append (<path-to-project>/tailwindcss-duplicate-imports/node_modules/postcss/lib/container.js:147:24) at AtRule.append (<path-to-project>/tailwindcss-duplicate-imports/node_modules/postcss/lib/at-rule.js:13:18) at <path-to-project>/tailwindcss-duplicate-imports/node_modules/tailwindcss/lib/lib/collapseAdjacentRules.js:24:29 at Root.each (<path-to-project>/tailwindcss-duplicate-imports/node_modules/postcss/lib/container.js:41:16) at collapseRulesIn (<path-to-project>/tailwindcss-duplicate-imports/node_modules/tailwindcss/lib/lib/collapseAdjacentRules.js:9:14) at <path-to-project>/tailwindcss-duplicate-imports/node_modules/tailwindcss/lib/lib/collapseAdjacentRules.js:42:9 at <path-to-project>/tailwindcss-duplicate-imports/node_modules/tailwindcss/lib/processTailwindFeatures.js:51:53 at plugins (<path-to-project>/tailwindcss-duplicate-imports/node_modules/tailwindcss/lib/index.js:33:58) at LazyResult.runOnRoot (<path-to-project>/tailwindcss-duplicate-imports/node_modules/postcss/lib/lazy-result.js:339:16) ``` In the repository that I have shared, after running `npm install`, there are three types of builds (see the NPM scripts in the package.json): - Build with TailwindCSS CLI -> works because the `@import` rule is not being resolved - Build with PostCSS CLI -> works until I add the `postcss-import` plugin - Build with [Vite](https://vitejs.dev/) -> Fails with the error above If you look at the `src/input.css` file you will see that I import two files that have the same `@import` rule. If I remove or change one of the duplicate rules, the build works fine. The problem I have, in my real project, is that the duplicate `@import` rules are from a third party library... and I can't modify it. I have cloned the TailwindCSS repository and link it locally to debug it and the line where I have found the problem is here: https://github.com/tailwindlabs/tailwindcss/blob/master/src/lib/collapseAdjacentRules.js#L32 It seems like `node.nodes` is undefined. Also, in my real project I'm not using Vite, I'm using the Angular CLI. The error also happens there. The problem is solved if, in the TailwindCSS plugin, I check if `node.nodes` exist before calling `currentRule.append(node.nodes)`. But I'm not sure if this is the correct solution. I'm not even sure if this is a problem of the TailwindCSS plugin.
"2022-04-15T16:16:37Z"
3.0
[]
[ "tests/collapse-adjacent-rules.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,125
tailwindlabs__tailwindcss-8125
[ "7874" ]
e5ed08b5cbdd902dcbb7b25d7c32ad9b474ea1a8
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -252,222 +252,228 @@ function processApply(root, context, localCache) { }) // Start the @apply process if we have rules with @apply in them - if (applies.length > 0) { - // Fill up some caches! - let applyClassCache = combineCaches([localCache, buildApplyCache(applyCandidates, context)]) - - /** - * When we have an apply like this: - * - * .abc { - * @apply hover:font-bold; - * } - * - * What we essentially will do is resolve to this: - * - * .abc { - * @apply .hover\:font-bold:hover { - * font-weight: 500; - * } - * } - * - * Notice that the to-be-applied class is `.hover\:font-bold:hover` and that the utility candidate was `hover:font-bold`. - * What happens in this function is that we prepend a `.` and escape the candidate. - * This will result in `.hover\:font-bold` - * Which means that we can replace `.hover\:font-bold` with `.abc` in `.hover\:font-bold:hover` resulting in `.abc:hover` - */ - // TODO: Should we use postcss-selector-parser for this instead? - function replaceSelector(selector, utilitySelectors, candidate) { - let needle = `.${escapeClassName(candidate)}` - let utilitySelectorsList = utilitySelectors.split(/\s*\,(?![^(]*\))\s*/g) - - return selector - .split(/\s*\,(?![^(]*\))\s*/g) - .map((s) => { - let replaced = [] - - for (let utilitySelector of utilitySelectorsList) { - let replacedSelector = utilitySelector.replace(needle, s) - if (replacedSelector === utilitySelector) { - continue - } - replaced.push(replacedSelector) - } - return replaced.join(', ') - }) - .join(', ') - } + if (applies.length === 0) { + return + } - let perParentApplies = new Map() + // Fill up some caches! + let applyClassCache = combineCaches([localCache, buildApplyCache(applyCandidates, context)]) + + /** + * When we have an apply like this: + * + * .abc { + * @apply hover:font-bold; + * } + * + * What we essentially will do is resolve to this: + * + * .abc { + * @apply .hover\:font-bold:hover { + * font-weight: 500; + * } + * } + * + * Notice that the to-be-applied class is `.hover\:font-bold:hover` and that the utility candidate was `hover:font-bold`. + * What happens in this function is that we prepend a `.` and escape the candidate. + * This will result in `.hover\:font-bold` + * Which means that we can replace `.hover\:font-bold` with `.abc` in `.hover\:font-bold:hover` resulting in `.abc:hover` + */ + // TODO: Should we use postcss-selector-parser for this instead? + function replaceSelector(selector, utilitySelectors, candidate) { + let needle = `.${escapeClassName(candidate)}` + let needles = [...new Set([needle, needle.replace(/\\2c /g, '\\,')])] + let utilitySelectorsList = utilitySelectors.split(/\s*(?<!\\)\,(?![^(]*\))\s*/g) + + return selector + .split(/\s*(?<!\\)\,(?![^(]*\))\s*/g) + .map((s) => { + let replaced = [] + + for (let utilitySelector of utilitySelectorsList) { + let replacedSelector = utilitySelector + for (const needle of needles) { + replacedSelector = replacedSelector.replace(needle, s) + } + if (replacedSelector === utilitySelector) { + continue + } + replaced.push(replacedSelector) + } + return replaced.join(', ') + }) + .join(', ') + } - // Collect all apply candidates and their rules - for (let apply of applies) { - let candidates = perParentApplies.get(apply.parent) || [] + let perParentApplies = new Map() - perParentApplies.set(apply.parent, [candidates, apply.source]) + // Collect all apply candidates and their rules + for (let apply of applies) { + let candidates = perParentApplies.get(apply.parent) || [] - let [applyCandidates, important] = extractApplyCandidates(apply.params) + perParentApplies.set(apply.parent, [candidates, apply.source]) - if (apply.parent.type === 'atrule') { - if (apply.parent.name === 'screen') { - const screenType = apply.parent.params + let [applyCandidates, important] = extractApplyCandidates(apply.params) - throw apply.error( - `@apply is not supported within nested at-rules like @screen. We suggest you write this as @apply ${applyCandidates - .map((c) => `${screenType}:${c}`) - .join(' ')} instead.` - ) - } + if (apply.parent.type === 'atrule') { + if (apply.parent.name === 'screen') { + const screenType = apply.parent.params throw apply.error( - `@apply is not supported within nested at-rules like @${apply.parent.name}. You can fix this by un-nesting @${apply.parent.name}.` + `@apply is not supported within nested at-rules like @screen. We suggest you write this as @apply ${applyCandidates + .map((c) => `${screenType}:${c}`) + .join(' ')} instead.` ) } - for (let applyCandidate of applyCandidates) { - if ([prefix(context, 'group'), prefix(context, 'peer')].includes(applyCandidate)) { - // TODO: Link to specific documentation page with error code. - throw apply.error(`@apply should not be used with the '${applyCandidate}' utility`) - } - - if (!applyClassCache.has(applyCandidate)) { - throw apply.error( - `The \`${applyCandidate}\` class does not exist. If \`${applyCandidate}\` is a custom class, make sure it is defined within a \`@layer\` directive.` - ) - } + throw apply.error( + `@apply is not supported within nested at-rules like @${apply.parent.name}. You can fix this by un-nesting @${apply.parent.name}.` + ) + } - let rules = applyClassCache.get(applyCandidate) + for (let applyCandidate of applyCandidates) { + if ([prefix(context, 'group'), prefix(context, 'peer')].includes(applyCandidate)) { + // TODO: Link to specific documentation page with error code. + throw apply.error(`@apply should not be used with the '${applyCandidate}' utility`) + } - candidates.push([applyCandidate, important, rules]) + if (!applyClassCache.has(applyCandidate)) { + throw apply.error( + `The \`${applyCandidate}\` class does not exist. If \`${applyCandidate}\` is a custom class, make sure it is defined within a \`@layer\` directive.` + ) } + + let rules = applyClassCache.get(applyCandidate) + + candidates.push([applyCandidate, important, rules]) } + } + + for (const [parent, [candidates, atApplySource]] of perParentApplies) { + let siblings = [] + + for (let [applyCandidate, important, rules] of candidates) { + for (let [meta, node] of rules) { + let parentClasses = extractClasses(parent) + let nodeClasses = extractClasses(node) + + // Add base utility classes from the @apply node to the list of + // classes to check whether it intersects and therefore results in a + // circular dependency or not. + // + // E.g.: + // .foo { + // @apply hover:a; // This applies "a" but with a modifier + // } + // + // We only have to do that with base classes of the `node`, not of the `parent` + // E.g.: + // .hover\:foo { + // @apply bar; + // } + // .bar { + // @apply foo; + // } + // + // This should not result in a circular dependency because we are + // just applying `.foo` and the rule above is `.hover\:foo` which is + // unrelated. However, if we were to apply `hover:foo` then we _did_ + // have to include this one. + nodeClasses = nodeClasses.concat( + extractBaseCandidates(nodeClasses, context.tailwindConfig.separator) + ) - for (const [parent, [candidates, atApplySource]] of perParentApplies) { - let siblings = [] - - for (let [applyCandidate, important, rules] of candidates) { - for (let [meta, node] of rules) { - let parentClasses = extractClasses(parent) - let nodeClasses = extractClasses(node) - - // Add base utility classes from the @apply node to the list of - // classes to check whether it intersects and therefore results in a - // circular dependency or not. - // - // E.g.: - // .foo { - // @apply hover:a; // This applies "a" but with a modifier - // } - // - // We only have to do that with base classes of the `node`, not of the `parent` - // E.g.: - // .hover\:foo { - // @apply bar; - // } - // .bar { - // @apply foo; - // } - // - // This should not result in a circular dependency because we are - // just applying `.foo` and the rule above is `.hover\:foo` which is - // unrelated. However, if we were to apply `hover:foo` then we _did_ - // have to include this one. - nodeClasses = nodeClasses.concat( - extractBaseCandidates(nodeClasses, context.tailwindConfig.separator) + let intersects = parentClasses.some((selector) => nodeClasses.includes(selector)) + if (intersects) { + throw node.error( + `You cannot \`@apply\` the \`${applyCandidate}\` utility here because it creates a circular dependency.` ) + } - let intersects = parentClasses.some((selector) => nodeClasses.includes(selector)) - if (intersects) { - throw node.error( - `You cannot \`@apply\` the \`${applyCandidate}\` utility here because it creates a circular dependency.` - ) - } + let root = postcss.root({ nodes: [node.clone()] }) - let root = postcss.root({ nodes: [node.clone()] }) + // Make sure every node in the entire tree points back at the @apply rule that generated it + root.walk((node) => { + node.source = atApplySource + }) - // Make sure every node in the entire tree points back at the @apply rule that generated it - root.walk((node) => { - node.source = atApplySource - }) + let canRewriteSelector = + node.type !== 'atrule' || (node.type === 'atrule' && node.name !== 'keyframes') + + if (canRewriteSelector) { + root.walkRules((rule) => { + // Let's imagine you have the following structure: + // + // .foo { + // @apply bar; + // } + // + // @supports (a: b) { + // .bar { + // color: blue + // } + // + // .something-unrelated {} + // } + // + // In this case we want to apply `.bar` but it happens to be in + // an atrule node. We clone that node instead of the nested one + // because we still want that @supports rule to be there once we + // applied everything. + // + // However it happens to be that the `.something-unrelated` is + // also in that same shared @supports atrule. This is not good, + // and this should not be there. The good part is that this is + // a clone already and it can be safely removed. The question is + // how do we know we can remove it. Basically what we can do is + // match it against the applyCandidate that you want to apply. If + // it doesn't match the we can safely delete it. + // + // If we didn't do this, then the `replaceSelector` function + // would have replaced this with something that didn't exist and + // therefore it removed the selector altogether. In this specific + // case it would result in `{}` instead of `.something-unrelated {}` + if (!extractClasses(rule).some((candidate) => candidate === applyCandidate)) { + rule.remove() + return + } - let canRewriteSelector = - node.type !== 'atrule' || (node.type === 'atrule' && node.name !== 'keyframes') - - if (canRewriteSelector) { - root.walkRules((rule) => { - // Let's imagine you have the following structure: - // - // .foo { - // @apply bar; - // } - // - // @supports (a: b) { - // .bar { - // color: blue - // } - // - // .something-unrelated {} - // } - // - // In this case we want to apply `.bar` but it happens to be in - // an atrule node. We clone that node instead of the nested one - // because we still want that @supports rule to be there once we - // applied everything. - // - // However it happens to be that the `.something-unrelated` is - // also in that same shared @supports atrule. This is not good, - // and this should not be there. The good part is that this is - // a clone already and it can be safely removed. The question is - // how do we know we can remove it. Basically what we can do is - // match it against the applyCandidate that you want to apply. If - // it doesn't match the we can safely delete it. - // - // If we didn't do this, then the `replaceSelector` function - // would have replaced this with something that didn't exist and - // therefore it removed the selector altogether. In this specific - // case it would result in `{}` instead of `.something-unrelated {}` - if (!extractClasses(rule).some((candidate) => candidate === applyCandidate)) { - rule.remove() - return - } - - rule.selector = replaceSelector(parent.selector, rule.selector, applyCandidate) - - rule.walkDecls((d) => { - d.important = meta.important || important - }) - }) - } + rule.selector = replaceSelector(parent.selector, rule.selector, applyCandidate) - // Insert it - siblings.push([ - // Ensure that when we are sorting, that we take the layer order into account - { ...meta, sort: meta.sort | context.layerOrder[meta.layer] }, - root.nodes[0], - ]) + rule.walkDecls((d) => { + d.important = meta.important || important + }) + }) } + + // Insert it + siblings.push([ + // Ensure that when we are sorting, that we take the layer order into account + { ...meta, sort: meta.sort | context.layerOrder[meta.layer] }, + root.nodes[0], + ]) } + } - // Inject the rules, sorted, correctly - let nodes = siblings.sort(([a], [z]) => bigSign(a.sort - z.sort)).map((s) => s[1]) + // Inject the rules, sorted, correctly + let nodes = siblings.sort(([a], [z]) => bigSign(a.sort - z.sort)).map((s) => s[1]) - // `parent` refers to the node at `.abc` in: .abc { @apply mt-2 } - parent.after(nodes) - } + // `parent` refers to the node at `.abc` in: .abc { @apply mt-2 } + parent.after(nodes) + } - for (let apply of applies) { - // If there are left-over declarations, just remove the @apply - if (apply.parent.nodes.length > 1) { - apply.remove() - } else { - // The node is empty, drop the full node - apply.parent.remove() - } + for (let apply of applies) { + // If there are left-over declarations, just remove the @apply + if (apply.parent.nodes.length > 1) { + apply.remove() + } else { + // The node is empty, drop the full node + apply.parent.remove() } - - // Do it again, in case we have other `@apply` rules - processApply(root, context, localCache) } + + // Do it again, in case we have other `@apply` rules + processApply(root, context, localCache) } export default function expandApplyAtRules(context) {
diff --git a/tests/prefix.test.js b/tests/prefix.test.js --- a/tests/prefix.test.js +++ b/tests/prefix.test.js @@ -374,3 +374,29 @@ it('prefix does not detect and generate unnecessary classes', async () => { expect(result.css).toMatchFormattedCss(css``) }) + +it('supports prefixed utilities using arbitrary values', async () => { + let config = { + prefix: 'tw-', + content: [{ raw: html`foo` }], + corePlugins: { preflight: false }, + } + + let input = css` + .foo { + @apply tw-text-[color:rgb(var(--button-background,var(--primary-button-background)))]; + @apply tw-ease-[cubic-bezier(0.77,0,0.175,1)]; + @apply tw-rounded-[min(4px,var(--input-border-radius))]; + } + ` + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .foo { + color: rgb(var(--button-background, var(--primary-button-background))); + transition-timing-function: cubic-bezier(0.77, 0, 0.175, 1); + border-radius: min(4px, var(--input-border-radius)); + } + `) +})
Prefix option does not work with custom properties **What version of Tailwind CSS are you using?** v3.0.23 Hi ! I am trying to use the prefix option, but I have found a problem that prevents it to work for more complex patterns. For instance, here is a simple code _without_ any prefix: ``` .button { @apply text-[color:rgb(var(--button-background,var(--primary-button-background)))]; } ``` This properly generates the following markup: ``` .button { color: rgb(var(--button-background,var(--primary-button-background))); } ``` When using a prefix (in my example "tw-"), if I change the apply: ``` .button { @apply tw-text-[color:rgb(var(--button-background,var(--primary-button-background)))]; } ``` Then the following incorrect CSS is generated (note the lack of selector): ``` { color: rgb(var(--button-background,var(--primary-button-background))); } ```
To complement this issue, here are a few other use cases where CSS generation fails with prefix: ``` .accordion-content { @apply tw-ease-[cubic-bezier(0.77,0,0.175,1)]; } ``` Generates this incorrect markup: ``` { transition-timing-function: cubic-bezier(0.77,0,0.175,1); } ``` While the same without the prefix configured generate the correct markup. Hi, Here are a few other cases where Tailwind generate incorrect CSS with prefix: ``` .foo { @apply tw-rounded-[min(4px,var(--input-border-radius))]; } ``` It generates the following incorrect code (notice the lack of selector): ``` { border-radius: min(4px,var(--input-border-radius)); } ``` I'd be in favor to, since Bootstrap can live beside other libraries (eg. Booster v4 includes jQuery TableSorter, speaking of table styles leaking) or custom code. [GarageBand For Android ](https://www.garagebandapp.org/)
"2022-04-15T20:19:59Z"
3.0
[]
[ "tests/prefix.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,201
tailwindlabs__tailwindcss-8201
[ "8171" ]
1cc1ace14260f13ba97123c35aeb826edf8cca08
diff --git a/src/util/color.js b/src/util/color.js --- a/src/util/color.js +++ b/src/util/color.js @@ -8,13 +8,15 @@ let ALPHA_SEP = /\s*[,/]\s*/ let CUSTOM_PROPERTY = /var\(--(?:[^ )]*?)\)/ let RGB = new RegExp( - `^rgba?\\(\\s*(${VALUE.source}|${CUSTOM_PROPERTY.source})${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source})${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source})(?:${ALPHA_SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?\\s*\\)$` + `^(rgb)a?\\(\\s*(${VALUE.source}|${CUSTOM_PROPERTY.source})(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${ALPHA_SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?\\s*\\)$` ) let HSL = new RegExp( - `^hsla?\\(\\s*((?:${VALUE.source})(?:deg|rad|grad|turn)?|${CUSTOM_PROPERTY.source})${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source})${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source})(?:${ALPHA_SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?\\s*\\)$` + `^(hsl)a?\\(\\s*((?:${VALUE.source})(?:deg|rad|grad|turn)?|${CUSTOM_PROPERTY.source})(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${ALPHA_SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?\\s*\\)$` ) -export function parseColor(value) { +// In "loose" mode the color may contain fewer than 3 parts, as long as at least +// one of the parts is variable. +export function parseColor(value, { loose = false } = {}) { if (typeof value !== 'string') { return null } @@ -42,27 +44,27 @@ export function parseColor(value) { } } - let rgbMatch = value.match(RGB) + let match = value.match(RGB) ?? value.match(HSL) - if (rgbMatch !== null) { - return { - mode: 'rgb', - color: [rgbMatch[1], rgbMatch[2], rgbMatch[3]].map((v) => v.toString()), - alpha: rgbMatch[4]?.toString?.(), - } + if (match === null) { + return null } - let hslMatch = value.match(HSL) + let color = [match[2], match[3], match[4]].filter(Boolean).map((v) => v.toString()) - if (hslMatch !== null) { - return { - mode: 'hsl', - color: [hslMatch[1], hslMatch[2], hslMatch[3]].map((v) => v.toString()), - alpha: hslMatch[4]?.toString?.(), - } + if (!loose && color.length !== 3) { + return null } - return null + if (color.length < 3 && !color.some((part) => /^var\(.*?\)$/.test(part))) { + return null + } + + return { + mode: match[1], + color, + alpha: match[5]?.toString?.(), + } } export function formatColor({ mode, color, alpha }) { diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -121,7 +121,7 @@ export function color(value) { part = normalize(part) if (part.startsWith('var(')) return true - if (parseColor(part) !== null) return colors++, true + if (parseColor(part, { loose: true }) !== null) return colors++, true return false })
diff --git a/tests/arbitrary-values.test.js b/tests/arbitrary-values.test.js --- a/tests/arbitrary-values.test.js +++ b/tests/arbitrary-values.test.js @@ -68,6 +68,8 @@ it('should support arbitrary values for various background utilities', () => { <!-- By implicit type --> <div class="bg-[url('/image-1-0.png')]"></div> <div class="bg-[#ff0000]"></div> + <div class="bg-[rgb(var(--bg-color))]"></div> + <div class="bg-[hsl(var(--bg-color))]"></div> <!-- By explicit type --> <div class="bg-[url:var(--image-url)]"></div> @@ -89,6 +91,14 @@ it('should support arbitrary values for various background utilities', () => { background-color: rgb(255 0 0 / var(--tw-bg-opacity)); } + .bg-\[rgb\(var\(--bg-color\)\)\] { + background-color: rgb(var(--bg-color)); + } + + .bg-\[hsl\(var\(--bg-color\)\)\] { + background-color: hsl(var(--bg-color)); + } + .bg-\[color\:var\(--bg-color\)\] { background-color: var(--bg-color); }
Color custom properties still require hint **What version of Tailwind CSS are you using?** latest insiders (21st April 2022) This PR added the ability to use rgb/hsl custom properties: https://github.com/tailwindlabs/tailwindcss/pull/7933 This unfortunately does not work with prefixes. The following class does not generate anything: ```tw-bg-[rgb(var(--background))]``` and still requires a color: hint.
"2022-04-26T11:31:22Z"
3.0
[]
[ "tests/arbitrary-values.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,204
tailwindlabs__tailwindcss-8204
[ "8165" ]
bb0ab6744b6aaaad4d070341a03429be14975b53
diff --git a/src/lib/defaultExtractor.js b/src/lib/defaultExtractor.js --- a/src/lib/defaultExtractor.js +++ b/src/lib/defaultExtractor.js @@ -1,42 +1,160 @@ -const PATTERNS = [ - /(?:\['([^'\s]+[^<>"'`\s:\\])')/.source, // ['text-lg' -> text-lg - /(?:\["([^"\s]+[^<>"'`\s:\\])")/.source, // ["text-lg" -> text-lg - /(?:\[`([^`\s]+[^<>"'`\s:\\])`)/.source, // [`text-lg` -> text-lg - /([^${(<>"'`\s]*\[\w*'[^"`\s]*'?\])/.source, // font-['some_font',sans-serif] - /([^${(<>"'`\s]*\[\w*"[^'`\s]*"?\])/.source, // font-["some_font",sans-serif] - /([^<>"'`\s]*\[\w*\('[^"'`\s]*'\)\])/.source, // bg-[url('...')] - /([^<>"'`\s]*\[\w*\("[^"'`\s]*"\)\])/.source, // bg-[url("...")] - /([^<>"'`\s]*\[\w*\('[^"`\s]*'\)\])/.source, // bg-[url('...'),url('...')] - /([^<>"'`\s]*\[\w*\("[^'`\s]*"\)\])/.source, // bg-[url("..."),url("...")] - /([^<>"'`\s]*\[[^<>"'`\s]*\('[^"`\s]*'\)+\])/.source, // h-[calc(100%-theme('spacing.1'))] - /([^<>"'`\s]*\[[^<>"'`\s]*\("[^'`\s]*"\)+\])/.source, // h-[calc(100%-theme("spacing.1"))] - /([^${(<>"'`\s]*\['[^"'`\s]*'\])/.source, // `content-['hello']` but not `content-['hello']']` - /([^${(<>"'`\s]*\["[^"'`\s]*"\])/.source, // `content-["hello"]` but not `content-["hello"]"]` - /([^<>"'`\s]*\[[^<>"'`\s]*:[^\]\s]*\])/.source, // `[attr:value]` - /([^<>"'`\s]*\[[^<>"'`\s]*:'[^"'`\s]*'\])/.source, // `[content:'hello']` but not `[content:"hello"]` - /([^<>"'`\s]*\[[^<>"'`\s]*:"[^"'`\s]*"\])/.source, // `[content:"hello"]` but not `[content:'hello']` - /([^<>"'`\s]*\[[^"'`\s]+\][^<>"'`\s]*)/.source, // `fill-[#bada55]`, `fill-[#bada55]/50` - /([^"'`\s]*[^<>"'`\s:\\])/.source, // `<sm:underline`, `md>:font-bold` - /([^<>"'`\s]*[^"'`\s:\\])/.source, // `px-1.5`, `uppercase` but not `uppercase:` - - // Arbitrary properties - // /([^"\s]*\[[^\s]+?\][^"\s]*)/.source, - // /([^'\s]*\[[^\s]+?\][^'\s]*)/.source, - // /([^`\s]*\[[^\s]+?\][^`\s]*)/.source, -].join('|') - -const BROAD_MATCH_GLOBAL_REGEXP = new RegExp(PATTERNS, 'g') -const INNER_MATCH_GLOBAL_REGEXP = /[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g +import * as regex from './regex' + +let patterns = Array.from(buildRegExps()) /** * @param {string} content */ export function defaultExtractor(content) { - let broadMatches = content.matchAll(BROAD_MATCH_GLOBAL_REGEXP) - let innerMatches = content.match(INNER_MATCH_GLOBAL_REGEXP) || [] - let results = [...broadMatches, ...innerMatches].flat().filter((v) => v !== undefined) + /** @type {(string|string)[]} */ + let results = [] + + for (let pattern of patterns) { + results.push(...(content.match(pattern) ?? [])) + } + + return results.filter((v) => v !== undefined).map(clipAtBalancedParens) +} + +function* buildRegExps() { + yield regex.pattern([ + // Variants + /((?=([^\s"'\\\[]+:))\2)?/, + + // Important (optional) + /!?/, + + regex.any([ + // Arbitrary properties + /\[[^\s:'"]+:[^\s\]]+\]/, + + // Utilities + regex.pattern([ + // Utility Name / Group Name + /-?(?:\w+)/, + + // Normal/Arbitrary values + regex.optional( + regex.any([ + regex.pattern([ + // Arbitrary values + /-\[[^\s:]+\]/, + + // Not immediately followed by an `{[(` + /(?![{([]])/, + + // optionally followed by an opacity modifier + /(?:\/[^\s'"\\$]*)?/, + ]), + + regex.pattern([ + // Arbitrary values + /-\[[^\s]+\]/, + + // Not immediately followed by an `{[(` + /(?![{([]])/, + + // optionally followed by an opacity modifier + /(?:\/[^\s'"\\$]*)?/, + ]), + + // Normal values w/o quotes β€” may include an opacity modifier + /[-\/][^\s'"\\$={]*/, + ]) + ), + ]), + ]), + ]) + + // 5. Inner matches + // yield /[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g +} + +// We want to capture any "special" characters +// AND the characters immediately following them (if there is one) +let SPECIALS = /([\[\]'"`])([^\[\]'"`])?/g +let ALLOWED_CLASS_CHARACTERS = /[^"'`\s<>\]]+/ + +/** + * Clips a string ensuring that parentheses, quotes, etc… are balanced + * Used for arbitrary values only + * + * We will go past the end of the balanced parens until we find a non-class character + * + * Depth matching behavior: + * w-[calc(100%-theme('spacing[some_key][1.5]'))]'] + * ┬ ┬ ┬┬ ┬ ┬┬ ┬┬┬┬┬┬┬ + * 1 2 3 4 34 3 210 END + * ╰────┴──────────┴────────┴────────┴┴───┴─┴┴┴ + * + * @param {string} input + */ +function clipAtBalancedParens(input) { + // We are care about this for arbitrary values + if (!input.includes('-[')) { + return input + } + + let depth = 0 + let openStringTypes = [] + + // Find all parens, brackets, quotes, etc + // Stop when we end at a balanced pair + // This is naive and will treat mismatched parens as balanced + // This shouldn't be a problem in practice though + let matches = input.matchAll(SPECIALS) + + // We can't use lookbehind assertions because we have to support Safari + // So, instead, we've emulated it using capture groups and we'll re-work the matches to accommodate + matches = Array.from(matches).flatMap((match) => { + const [, ...groups] = match + + return groups.map((group, idx) => + Object.assign([], match, { + index: match.index + idx, + 0: group, + }) + ) + }) + + for (let match of matches) { + let char = match[0] + let inStringType = openStringTypes[openStringTypes.length - 1] + + if (char === inStringType) { + openStringTypes.pop() + } else if (char === "'" || char === '"' || char === '`') { + openStringTypes.push(char) + } + + if (inStringType) { + continue + } else if (char === '[') { + depth++ + continue + } else if (char === ']') { + depth-- + continue + } + + // We've gone one character past the point where we should stop + // This means that there was an extra closing `]` + // We'll clip to just before it + if (depth < 0) { + return input.substring(0, match.index) + } + + // We've finished balancing the brackets but there still may be characters that can be included + // For example in the class `text-[#336699]/[.35]` + // The depth goes to `0` at the closing `]` but goes up again at the `[` + + // If we're at zero and encounter a non-class character then we clip the class there + if (depth === 0 && !ALLOWED_CLASS_CHARACTERS.test(char)) { + return input.substring(0, match.index) + } + } - return results + return input } // Regular utilities diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -34,6 +34,15 @@ function extractClasses(node) { return Object.assign(classes, { groups: normalizedGroups }) } +let selectorExtractor = parser((root) => root.nodes.map((node) => node.toString())) + +/** + * @param {string} ruleSelectors + */ +function extractSelectors(ruleSelectors) { + return selectorExtractor.transformSync(ruleSelectors) +} + function extractBaseCandidates(candidates, separator) { let baseClasses = new Set() @@ -295,10 +304,9 @@ function processApply(root, context, localCache) { function replaceSelector(selector, utilitySelectors, candidate) { let needle = `.${escapeClassName(candidate)}` let needles = [...new Set([needle, needle.replace(/\\2c /g, '\\,')])] - let utilitySelectorsList = utilitySelectors.split(/\s*(?<!\\)\,(?![^(]*\))\s*/g) + let utilitySelectorsList = extractSelectors(utilitySelectors) - return selector - .split(/\s*(?<!\\)\,(?![^(]*\))\s*/g) + return extractSelectors(selector) .map((s) => { let replaced = [] diff --git a/src/lib/expandTailwindAtRules.js b/src/lib/expandTailwindAtRules.js --- a/src/lib/expandTailwindAtRules.js +++ b/src/lib/expandTailwindAtRules.js @@ -17,8 +17,8 @@ const builtInTransformers = { svelte: (content) => content.replace(/(?:^|\s)class:/g, ' '), } -function getExtractor(tailwindConfig, fileExtension) { - let extractors = tailwindConfig.content.extract +function getExtractor(context, fileExtension) { + let extractors = context.tailwindConfig.content.extract return ( extractors[fileExtension] || @@ -165,7 +165,7 @@ export default function expandTailwindAtRules(context) { for (let { content, extension } of context.changedContent) { let transformer = getTransformer(context.tailwindConfig, extension) - let extractor = getExtractor(context.tailwindConfig, extension) + let extractor = getExtractor(context, extension) getClassCandidates(transformer(content), extractor, candidates, seen) } diff --git a/src/lib/regex.js b/src/lib/regex.js new file mode 100644 --- /dev/null +++ b/src/lib/regex.js @@ -0,0 +1,74 @@ +const REGEX_SPECIAL = /[\\^$.*+?()[\]{}|]/g +const REGEX_HAS_SPECIAL = RegExp(REGEX_SPECIAL.source) + +/** + * @param {string|RegExp|Array<string|RegExp>} source + */ +function toSource(source) { + source = Array.isArray(source) ? source : [source] + + source = source.map((item) => (item instanceof RegExp ? item.source : item)) + + return source.join('') +} + +/** + * @param {string|RegExp|Array<string|RegExp>} source + */ +export function pattern(source) { + return new RegExp(toSource(source), 'g') +} + +/** + * @param {string|RegExp|Array<string|RegExp>} source + */ +export function withoutCapturing(source) { + return new RegExp(`(?:${toSource(source)})`, 'g') +} + +/** + * @param {Array<string|RegExp>} sources + */ +export function any(sources) { + return `(?:${sources.map(toSource).join('|')})` +} + +/** + * @param {string|RegExp} source + */ +export function optional(source) { + return `(?:${toSource(source)})?` +} + +/** + * @param {string|RegExp|Array<string|RegExp>} source + */ +export function zeroOrMore(source) { + return `(?:${toSource(source)})*` +} + +/** + * Generate a RegExp that matches balanced brackets for a given depth + * We have to specify a depth because JS doesn't support recursive groups using ?R + * + * Based on https://stackoverflow.com/questions/17759004/how-to-match-string-within-parentheses-nested-in-java/17759264#17759264 + * + * @param {string|RegExp|Array<string|RegExp>} source + */ +export function nestedBrackets(open, close, depth = 1) { + return withoutCapturing([ + escape(open), + /[^\s]*/, + depth === 1 + ? `[^${escape(open)}${escape(close)}\s]*` + : any([`[^${escape(open)}${escape(close)}\s]*`, nestedBrackets(open, close, depth - 1)]), + /[^\s]*/, + escape(close), + ]) +} + +export function escape(string) { + return string && REGEX_HAS_SPECIAL.test(string) + ? string.replace(REGEX_SPECIAL, '\\$&') + : string || '' +}
diff --git a/tests/arbitrary-values.test.css b/tests/arbitrary-values.test.css --- a/tests/arbitrary-values.test.css +++ b/tests/arbitrary-values.test.css @@ -316,6 +316,9 @@ .cursor-\[url\(hand\.cur\)_2_2\2c pointer\] { cursor: url(hand.cur) 2 2, pointer; } +.cursor-\[url\(\'\.\/path_to_hand\.cur\'\)_2_2\2c pointer\] { + cursor: url("./path_to_hand.cur") 2 2, pointer; +} .cursor-\[var\(--value\)\] { cursor: var(--value); } diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -401,3 +401,32 @@ it('should generate styles using :not(.unknown-class) even if `.unknown-class` d `) }) }) + +it('supports multiple backgrounds as arbitrary values even if only some are quoted', () => { + let config = { + content: [ + { + raw: html`<div + class="bg-[url('/images/one-two-three.png'),linear-gradient(to_right,_#eeeeee,_#000000)]" + ></div>`, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .bg-\[url\(\'\/images\/one-two-three\.png\'\)\2c + linear-gradient\(to_right\2c + _\#eeeeee\2c + _\#000000\)\] { + background-image: url('/images/one-two-three.png'), + linear-gradient(to right, #eeeeee, #000000); + } + `) + }) +}) diff --git a/tests/default-extractor.test.js b/tests/default-extractor.test.js --- a/tests/default-extractor.test.js +++ b/tests/default-extractor.test.js @@ -56,7 +56,11 @@ const htmlExamples = html` let classes11 = ['hover:'] let classes12 = ['hover:\'abc'] let classes13 = ["lg:text-[4px]"] - let classes14 = ["<div class='hover:test'>"] + let classes14 = ["<div class='hover:underline'>"] + let classes15 = ["<div class='hover:test'>"] // unknown so dont generate + let classes16 = ["font-[arbitrary,'arbitrary_with_space']"] + let classes17 = ["font-['arbitrary_with_space','arbitrary_2']"] + let classes18 = ["bg-[url('/images/one-two-three.png'),linear-gradient(to_right,_#eeeeee,_#000000)]"] let obj = { lowercase: true, @@ -73,6 +77,10 @@ const htmlExamples = html` "h-[109px]": true } </script> + <script type="text/twig"> + element['#border_color']|default('border-[color:var(--color,theme(colors.cyan.500))]') + {% if settings == 'foo'%}translate-x-[var(--scroll-offset)]{% endif %} + </script> ` const includes = [ @@ -133,11 +141,16 @@ const includes = [ `lg:text-[4px]`, `lg:text-[24px]`, `content-['>']`, - `hover:test`, + `hover:underline`, `overflow-scroll`, `[--y:theme(colors.blue.500)]`, `w-[calc(100%-theme('spacing.1'))]`, `w-[calc(100%-theme("spacing.2"))]`, + `border-[color:var(--color,theme(colors.cyan.500))]`, + `translate-x-[var(--scroll-offset)]`, + `font-[arbitrary,'arbitrary_with_space']`, + `font-['arbitrary_with_space','arbitrary_2']`, + `bg-[url('/images/one-two-three.png'),linear-gradient(to_right,_#eeeeee,_#000000)]`, ] const excludes = [ @@ -145,6 +158,7 @@ const excludes = [ 'hover:', "hover:'abc", `font-bold`, + `<div class='hover:underline'>`, `<div class='hover:test'>`, `test`, ] @@ -193,7 +207,7 @@ test('basic utility classes', async () => { expect(extractions).toContain('pointer-events-none') }) -test('modifiers with basic utilites', async () => { +test('modifiers with basic utilities', async () => { const extractions = defaultExtractor(` <div class="hover:text-center hover:focus:font-bold"></div> `) @@ -394,26 +408,26 @@ test('with single quotes array within template literal', async () => { const extractions = defaultExtractor(`<div class=\`\${['pr-1.5']}\`></div>`) expect(extractions).toContain('pr-1.5') - expect(extractions).toContain('pr-1') + expect(extractions).not.toContain('pr-1') }) test('with double quotes array within template literal', async () => { const extractions = defaultExtractor(`<div class=\`\${["pr-1.5"]}\`></div>`) expect(extractions).toContain('pr-1.5') - expect(extractions).toContain('pr-1') + expect(extractions).not.toContain('pr-1') }) test('with single quotes array within function', async () => { const extractions = defaultExtractor(`document.body.classList.add(['pl-1.5'].join(" "));`) expect(extractions).toContain('pl-1.5') - expect(extractions).toContain('pl-1') + expect(extractions).not.toContain('pl-1') }) test('with double quotes array within function', async () => { const extractions = defaultExtractor(`document.body.classList.add(["pl-1.5"].join(" "));`) expect(extractions).toContain('pl-1.5') - expect(extractions).toContain('pl-1') + expect(extractions).not.toContain('pl-1') })
Compound background-image JIT not working **What version of Tailwind CSS are you using?** [email protected] ``` Operating System: Platform: linux Arch: x64 Version: #44-Ubuntu SMP Thu Mar 24 15:35:05 UTC 2022 Binaries: Node: 14.18.1 npm: 8.6.0 Yarn: 1.22.18 pnpm: N/A Relevant packages: next: 12.1.5 react: 18.0.0 react-dom: 18.0.0 ``` **What browser are you using?** Firefox Doing compound bg-[] for background images is not working. e.g. ``` bg-[url('/media/left-side-bar.png'),linear-gradient(to_right,_#e2d9d4,_#f3eeeb)] ``` Either of those work by themselves works, but when it is joined it is not working. When I hover over it the CSS class it says it will create is correct. ```css .bg-\[url\(\'\/media\/left-side-bar\.png\'\)\2c _linear-gradient\(to_right\2c _\#e2d9d4\2c _\#f3eeeb\)\] { background-image: url('/media/left-side-bar.png'), linear-gradient(to right, #e2d9d4, #f3eeeb); } ``` https://play.tailwindcss.com/5sCBtDy3RZ
"2022-04-26T18:31:55Z"
3.0
[]
[ "tests/default-extractor.test.js", "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/5sCBtDy3RZ" ]
tailwindlabs/tailwindcss
8,222
tailwindlabs__tailwindcss-8222
[ "7844" ]
3989f77dd3fa5765f818e7b24bc52d95504a2e0c
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -8,18 +8,30 @@ import escapeClassName from '../util/escapeClassName' /** @typedef {Map<string, [any, import('postcss').Rule[]]>} ApplyCache */ function extractClasses(node) { - let classes = new Set() + /** @type {Map<string, Set<string>>} */ + let groups = new Map() + let container = postcss.root({ nodes: [node.clone()] }) container.walkRules((rule) => { parser((selectors) => { selectors.walkClasses((classSelector) => { + let parentSelector = classSelector.parent.toString() + + let classes = groups.get(parentSelector) + if (!classes) { + groups.set(parentSelector, (classes = new Set())) + } + classes.add(classSelector.value) }) }).processSync(rule.selector) }) - return Array.from(classes) + let normalizedGroups = Array.from(groups.values(), (classes) => Array.from(classes)) + let classes = normalizedGroups.flat() + + return Object.assign(classes, { groups: normalizedGroups }) } function extractBaseCandidates(candidates, separator) { @@ -353,10 +365,23 @@ function processApply(root, context, localCache) { let siblings = [] for (let [applyCandidate, important, rules] of candidates) { + let potentialApplyCandidates = [ + applyCandidate, + ...extractBaseCandidates([applyCandidate], context.tailwindConfig.separator), + ] + for (let [meta, node] of rules) { let parentClasses = extractClasses(parent) let nodeClasses = extractClasses(node) + // When we encounter a rule like `.dark .a, .b { … }` we only want to be left with `[.dark, .a]` if the base applyCandidate is `.a` or with `[.b]` if the base applyCandidate is `.b` + // So we've split them into groups + nodeClasses = nodeClasses.groups + .filter((classList) => + classList.some((className) => potentialApplyCandidates.includes(className)) + ) + .flat() + // Add base utility classes from the @apply node to the list of // classes to check whether it intersects and therefore results in a // circular dependency or not.
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -658,6 +658,94 @@ it('should throw when trying to apply an indirect circular dependency with a mod }) }) +it('should not throw when the circular dependency is part of a different selector (1)', () => { + let config = { + content: [{ raw: html`<div class="c"></div>` }], + plugins: [], + } + + let input = css` + @tailwind utilities; + + @layer utilities { + html.dark .a, + .b { + color: red; + } + } + + html.dark .c { + @apply b; + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + html.dark .c { + color: red; + } + `) + }) +}) + +it('should not throw when the circular dependency is part of a different selector (2)', () => { + let config = { + content: [{ raw: html`<div class="c"></div>` }], + plugins: [], + } + + let input = css` + @tailwind utilities; + + @layer utilities { + html.dark .a, + .b { + color: red; + } + } + + html.dark .c { + @apply hover:b; + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + html.dark .c:hover { + color: red; + } + `) + }) +}) + +it('should throw when the circular dependency is part of the same selector', () => { + let config = { + content: [{ raw: html`<div class="c"></div>` }], + plugins: [], + } + + let input = css` + @tailwind utilities; + + @layer utilities { + html.dark .a, + html.dark .b { + color: red; + } + } + + html.dark .c { + @apply hover:b; + } + ` + + return run(input, config).catch((err) => { + expect(err.reason).toBe( + 'You cannot `@apply` the `hover:b` utility here because it creates a circular dependency.' + ) + }) +}) + it('rules with vendor prefixes are still separate when optimizing defaults rules', () => { let config = { experimental: { optimizeUniversalDefaults: true },
@apply rule cannot pick up grouped utility css selector <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** **2.2.19** **What build tool (or framework if it abstracts the build tool) are you using?** **postcss-cli 8.3.1** **What version of Node.js are you using?** **v16.13.2** **What browser are you using?** **Chrome** **What operating system are you using?** **MacOS** **Reproduction URL** https://gist.github.com/ALexander4295502/6fef8dfb343bc94a970700715460d172 **Describe your issue** I am using a grouped css selector in my utility `colors.css` file as shown in the gist above (grouped selectors are `html.dark .dark\:v-dark-bg-backdrop-modal` and `.v-dark-bg-backdrop-modal`) ```css /* colors.css */ @layer utilities { @variants focus, hover, active, visited { /* purgecss start ignore */ html.dark .dark\:v-dark-bg-backdrop-modal, .v-dark-bg-backdrop-modal { background-color: rgba(70, 71, 101, 0.8); } /* purgecss end ignore */ } } ``` And in one of my component css file, I am applying **one** of the grouped selectors to my component ```css @import './colors.css'; html.dark my-modal { @apply v-dark-bg-backdrop-modal; } ``` And after running postcss cli command the `html.dark my-modal` is disappeared in the output CSS file, but if I separate the grouped selectos as separate selectors as below: ```css html.dark .dark\:v-dark-bg-backdrop-modal { background-color: rgba(70, 71, 101, 0.8); } .v-dark-bg-backdrop-modal { background-color: rgba(70, 71, 101, 0.8); } ``` There won't be any issues. As I didn't find any note in https://tailwindcss.com/docs/functions-and-directives#apply saying that `@apply` cannot be used for grouped selector, hence I think this is a bug needs to be fixed.
I just upgraded our version of tailwind to V3 and now compilation fails because of group classes with `@apply` <img width="797" alt="Screenshot 2022-04-13 at 19 57 46" src="https://user-images.githubusercontent.com/12516195/163252189-6d940bc8-2ffe-4fec-981c-59166b2ae12e.png"> Fulfilled to consider your to be as I would survey I have an unclear issue, I am likewise confused and requiring light on this not well characterized issue. Need help. [epayitonline](https://www.epayitonline.vip/) Hi wondering if someone can take a look at this issue? > I just upgraded our version of tailwind to V3 and now compilation fails because of group classes with `@apply` > > <img alt="Screenshot 2022-04-13 at 19 57 46" width="797" src="https://user-images.githubusercontent.com/12516195/163252189-6d940bc8-2ffe-4fec-981c-59166b2ae12e.png"> Does that mean the grouped class selector is not supported to be used in the tailwind css? I didn't find a documentation mentioning that.
"2022-04-28T15:56:42Z"
3.0
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,262
tailwindlabs__tailwindcss-8262
[ "8233" ]
7c337f24fcdedb7b8adc6d25a030dbcdd8181ca1
diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -30,6 +30,8 @@ export function formatVariantSelector(current, ...others) { } export function finalizeSelector(format, { selector, candidate, context }) { + let ast = selectorParser().astSync(selector) + let separator = context?.tailwindConfig?.separator ?? ':' // Split by the separator, but ignore the separator inside square brackets: @@ -48,6 +50,19 @@ export function finalizeSelector(format, { selector, candidate, context }) { format = format.replace(PARENT, `.${escapeClassName(candidate)}`) + let formatAst = selectorParser().astSync(format) + + // Remove extraneous selectors that do not include the base class/candidate being matched against + // For example if we have a utility defined `.a, .b { color: red}` + // And the formatted variant is sm:b then we want the final selector to be `.sm\:b` and not `.a, .sm\:b` + ast.each((node) => { + let hasClassesMatchingCandidate = node.some((n) => n.type === 'class' && n.value === base) + + if (!hasClassesMatchingCandidate) { + node.remove() + } + }) + // Normalize escaped classes, e.g.: // // The idea would be to replace the escaped `base` in the selector with the @@ -59,65 +74,61 @@ export function finalizeSelector(format, { selector, candidate, context }) { // base in selector: bg-\\[rgb\\(255\\,0\\,0\\)\\] // escaped base: bg-\\[rgb\\(255\\2c 0\\2c 0\\)\\] // - selector = selectorParser((selectors) => { - return selectors.walkClasses((node) => { - if (node.raws && node.value.includes(base)) { - node.raws.value = escapeClassName(unescape(node.raws.value)) - } - - return node - }) - }).processSync(selector) + ast.walkClasses((node) => { + if (node.raws && node.value.includes(base)) { + node.raws.value = escapeClassName(unescape(node.raws.value)) + } + }) // We can safely replace the escaped base now, since the `base` section is // now in a normalized escaped value. - selector = selector.replace(`.${escapeClassName(base)}`, format) + ast.walkClasses((node) => { + if (node.value === base) { + node.replaceWith(...formatAst.nodes) + } + }) - // Remove unnecessary pseudo selectors that we used as placeholders - return selectorParser((selectors) => { - return selectors.map((selector) => { - selector.walkPseudos((p) => { - if (selectorFunctions.has(p.value)) { - p.replaceWith(p.nodes) - } - - return p - }) - - // This will make sure to move pseudo's to the correct spot (the end for - // pseudo elements) because otherwise the selector will never work - // anyway. - // - // E.g.: - // - `before:hover:text-center` would result in `.before\:hover\:text-center:hover::before` - // - `hover:before:text-center` would result in `.hover\:before\:text-center:hover::before` - // - // `::before:hover` doesn't work, which means that we can make it work for you by flipping the order. - function collectPseudoElements(selector) { - let nodes = [] - - for (let node of selector.nodes) { - if (isPseudoElement(node)) { - nodes.push(node) - selector.removeChild(node) - } - - if (node?.nodes) { - nodes.push(...collectPseudoElements(node)) - } - } - - return nodes + // This will make sure to move pseudo's to the correct spot (the end for + // pseudo elements) because otherwise the selector will never work + // anyway. + // + // E.g.: + // - `before:hover:text-center` would result in `.before\:hover\:text-center:hover::before` + // - `hover:before:text-center` would result in `.hover\:before\:text-center:hover::before` + // + // `::before:hover` doesn't work, which means that we can make it work for you by flipping the order. + function collectPseudoElements(selector) { + let nodes = [] + + for (let node of selector.nodes) { + if (isPseudoElement(node)) { + nodes.push(node) + selector.removeChild(node) } - let pseudoElements = collectPseudoElements(selector) - if (pseudoElements.length > 0) { - selector.nodes.push(pseudoElements.sort(sortSelector)) + if (node?.nodes) { + nodes.push(...collectPseudoElements(node)) } + } + + return nodes + } - return selector + // Remove unnecessary pseudo selectors that we used as placeholders + ast.each((selector) => { + selector.walkPseudos((p) => { + if (selectorFunctions.has(p.value)) { + p.replaceWith(p.nodes) + } }) - }).processSync(selector) + + let pseudoElements = collectPseudoElements(selector) + if (pseudoElements.length > 0) { + selector.nodes.push(pseudoElements.sort(sortSelector)) + } + }) + + return ast.toString() } // Note: As a rule, double colons (::) should be used instead of a single colon
diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -603,3 +603,131 @@ it('appends variants to the correct place when using postcss documents', () => { `) }) }) + +it('variants support multiple, grouped selectors (html)', () => { + let config = { + content: [{ raw: html`<div class="sm:base1 sm:base2"></div>` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + .base1 .foo, + .base1 .bar { + color: red; + } + + .base2 .bar .base2-foo { + color: red; + } + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + @media (min-width: 640px) { + .sm\:base1 .foo, + .sm\:base1 .bar { + color: red; + } + + .sm\:base2 .bar .base2-foo { + color: red; + } + } + `) + }) +}) + +it('variants support multiple, grouped selectors (apply)', () => { + let config = { + content: [{ raw: html`<div class="baz"></div>` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + .base .foo, + .base .bar { + color: red; + } + } + .baz { + @apply sm:base; + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + @media (min-width: 640px) { + .baz .foo, + .baz .bar { + color: red; + } + } + `) + }) +}) + +it('variants only picks the used selectors in a group (html)', () => { + let config = { + content: [{ raw: html`<div class="sm:b"></div>` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + .a, + .b { + color: red; + } + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + @media (min-width: 640px) { + .sm\:b { + color: red; + } + } + `) + }) +}) + +it('variants only picks the used selectors in a group (apply)', () => { + let config = { + content: [{ raw: html`<div class="baz"></div>` }], + plugins: [], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + .a, + .b { + color: red; + } + } + .baz { + @apply sm:b; + } + ` + + return run(input, config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + @media (min-width: 640px) { + .baz { + color: red; + } + } + `) + }) +})
Nested and grouped scss selector doesn't work with responsive utility variants <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** `3.0.24` **What build tool (or framework if it abstracts the build tool) are you using?** ``` laravel-mix: 6.0.43 (abstracts webpack with:) webpack: 5.60.0 postcss-loader: 6.2.0 sass-loader: 12.6.0 postcss: 8.4.12 sass: 1.51.0 ``` **What version of Node.js are you using?** `v16.14.1` **What browser are you using?** Chrome, Firefox **What operating system are you using?** macOS **Reproduction URL** [Repro on GitHub](https://github.com/mimamuh/tailwind-issue-with-nested-scss-selectors) **Describe your issue** I have a _SCSS_ file `./src/main.scss` with a utility rule added to the `@components` layer using _Tailwind_ with _SASS_: ```scss @layer components { .base { /* NOTE: These grouped and nested rules causes the bug when the `base` utility is combined with a breakpoint like `md:base` */ .foo, .bar { @apply bg-rose-600; } } } ``` Then there is some _HTML_ `./index.html` using the new utilities together with a responsive utility variant `sm:`: ```html <!-- This div uses the md:base here --> <div class="flex gap-4 md:base"> <!-- And the foo should render something red --> <button class="p-2 border-2 border-zinc-600 foo">Should be red</button> <!-- And also bar should render something red --> <button class="p-2 border-2 border-zinc-600 bar">Should be red</button> <button class="p-2 border-2 border-zinc-600">As is</button> </div> ``` As `.foo, .bar` is grouped, the generated _CSS_ of _Tailwind_ is this: ```css @media (min-width: 768px) { .md\:base .foo, .base .bar { --tw-bg-opacity: 1; background-color: rgb(225 29 72 / var(--tw-bg-opacity)); } } ``` Instead of this: ```css @media (min-width: 768px) { .md\:base .foo, .md\:base .bar { --tw-bg-opacity: 1; background-color: rgb(225 29 72 / var(--tw-bg-opacity)); } } ``` **It basically applies the breakpoint only to the first grouped and nested utility combo `.base .foo`, but not to the second `.base .bar`.**
"2022-05-03T17:05:40Z"
3.0
[]
[ "tests/variants.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,313
tailwindlabs__tailwindcss-8313
[ "8305" ]
be51739337584f4b33d44b67baa2ad04b48d3e9d
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -471,7 +471,27 @@ function processApply(root, context, localCache) { return } - rule.selector = replaceSelector(parent.selector, rule.selector, applyCandidate) + // Strip the important selector from the parent selector if at the beginning + let importantSelector = + typeof context.tailwindConfig.important === 'string' + ? context.tailwindConfig.important + : null + + // We only want to move the "important" selector if this is a Tailwind-generated utility + // We do *not* want to do this for user CSS that happens to be structured the same + let isGenerated = parent.raws.tailwind !== undefined + + let parentSelector = + isGenerated && importantSelector && parent.selector.indexOf(importantSelector) === 0 + ? parent.selector.slice(importantSelector.length) + : parent.selector + + rule.selector = replaceSelector(parentSelector, rule.selector, applyCandidate) + + // And then re-add it if it was removed + if (importantSelector && parentSelector !== parent.selector) { + rule.selector = `${importantSelector} ${rule.selector}` + } rule.walkDecls((d) => { d.important = meta.important || important
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -1467,3 +1467,84 @@ it('should apply using the updated user CSS when the source has changed', async } `) }) + +it('apply + layer utilities + selector variants (like group) + important selector', async () => { + let config = { + important: '#myselector', + content: [{ raw: html`<div class="custom-utility"></div>` }], + plugins: [], + } + + let input = css` + @tailwind utilities; + @layer utilities { + .custom-utility { + @apply font-normal group-hover:underline; + } + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + #myselector .custom-utility { + font-weight: 400; + } + + #myselector .group:hover .custom-utility { + text-decoration-line: underline; + } + `) +}) + +it('apply + user CSS + selector variants (like group) + important selector (1)', async () => { + let config = { + important: '#myselector', + content: [{ raw: html`<div class="custom-utility"></div>` }], + plugins: [], + } + + let input = css` + .custom-utility { + @apply font-normal group-hover:underline; + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .custom-utility { + font-weight: 400; + } + + .group:hover .custom-utility { + text-decoration-line: underline; + } + `) +}) + +it('apply + user CSS + selector variants (like group) + important selector (2)', async () => { + let config = { + important: '#myselector', + content: [{ raw: html`<div class="custom-utility"></div>` }], + plugins: [], + } + + let input = css` + #myselector .custom-utility { + @apply font-normal group-hover:underline; + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + #myselector .custom-utility { + font-weight: 400; + } + + .group:hover #myselector .custom-utility { + text-decoration-line: underline; + } + `) +})
Using custom variants in utilities with important feature **What version of Tailwind CSS are you using?** 3.0.24 **What build tool (or framework if it abstracts the build tool) are you using?** postcss-cli 9.1.0 **What version of Node.js are you using?** 16 **Reproduction URL** https://play.tailwindcss.com/WxwCNZmQFX **Describe your issue** I want to setup custom variant for the webpage if it is loaded inside the iframe. When using this custom variant together with ` important: '#csc-app'` feature it produces different selectors if the classes are defined in the html or in the utilities. If the variant is used in the html then `.usage-variant_iframe` selector comes after the important selector: ``` #csc-app .usage-variant_iframe .iframe\:text-sm ``` If the variant is used in the utility then `.usage-variant_iframe` selector comes before the important selector: ``` .usage-variant_iframe #csc-app .custom-utility ``` As a work around i'm adding the `.usage-variant_iframe` twice right now. Once before the `#csc-app` div and second time after, but it would be great if this can be consistent.
Hey! What do you mean by β€œif the variant is used in the HTML” and β€œif the variant is used in the utility”? Can you give examples of each so I understand for sure? I should've been more clear πŸ˜„ By html i mean using variant like so `<p class="text-2xl iframe:text-sm">`. I define standard text size, and then override it for the iframe variant. By utility i mean first defining your custom utility so: ``` @layer utilities { .custom-utility { @apply text-red-900 iframe:text-blue-900; } } ``` And then using it like this `<p class="custom-utility">` It is also in the playground https://play.tailwindcss.com/WxwCNZmQFX If you take a look at the generated css for the example above then we get: ``` .usage-variant_iframe #csc-app .custom-utility { --tw-text-opacity: 1; color: rgb(30 58 138 / var(--tw-text-opacity)); } #csc-app .usage-variant_iframe .iframe\:text-sm { font-size: 0.875rem; line-height: 1.25rem; } ```
"2022-05-09T18:15:01Z"
3.0
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/WxwCNZmQFX" ]
tailwindlabs/tailwindcss
8,448
tailwindlabs__tailwindcss-8448
[ "7800" ]
c4e443acc093d8980bf476f14255b793c5065b9a
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -1977,13 +1977,20 @@ export let corePlugins = { ) }, - ringWidth: ({ matchUtilities, addDefaults, addUtilities, theme }) => { - let ringOpacityDefault = theme('ringOpacity.DEFAULT', '0.5') - let ringColorDefault = withAlphaValue( - theme('ringColor')?.DEFAULT, - ringOpacityDefault, - `rgb(147 197 253 / ${ringOpacityDefault})` - ) + ringWidth: ({ matchUtilities, addDefaults, addUtilities, theme, config }) => { + let ringColorDefault = (() => { + if (flagEnabled(config(), 'respectDefaultRingColorOpacity')) { + return theme('ringColor.DEFAULT') + } + + let ringOpacityDefault = theme('ringOpacity.DEFAULT', '0.5') + + return withAlphaValue( + theme('ringColor')?.DEFAULT, + ringOpacityDefault, + `rgb(147 197 253 / ${ringOpacityDefault})` + ) + })() addDefaults('ring-width', { '--tw-ring-inset': ' ', diff --git a/src/featureFlags.js b/src/featureFlags.js --- a/src/featureFlags.js +++ b/src/featureFlags.js @@ -6,7 +6,7 @@ let defaults = { } let featureFlags = { - future: ['hoverOnlyWhenSupported'], + future: ['hoverOnlyWhenSupported', 'respectDefaultRingColorOpacity'], experimental: ['optimizeUniversalDefaults', 'variantGrouping'], } diff --git a/src/util/getAllConfigs.js b/src/util/getAllConfigs.js --- a/src/util/getAllConfigs.js +++ b/src/util/getAllConfigs.js @@ -9,6 +9,13 @@ export default function getAllConfigs(config) { const features = { // Add experimental configs here... + respectDefaultRingColorOpacity: { + theme: { + ringColor: { + DEFAULT: '#3b82f67f', + }, + }, + }, } const experimentals = Object.keys(features) diff --git a/stubs/defaultConfig.stub.js b/stubs/defaultConfig.stub.js --- a/stubs/defaultConfig.stub.js +++ b/stubs/defaultConfig.stub.js @@ -720,7 +720,7 @@ module.exports = { 8: '8px', }, ringColor: ({ theme }) => ({ - DEFAULT: theme('colors.blue.500', '#3b82f6'), + DEFAULT: theme(`colors.blue.500`, '#3b82f6'), ...theme('colors'), }), ringOffsetColor: ({ theme }) => theme('colors'),
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -430,3 +430,237 @@ it('supports multiple backgrounds as arbitrary values even if only some are quot `) }) }) + +it('The "default" ring opacity is used by the default ring color when not using respectDefaultRingColorOpacity (1)', () => { + let config = { + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: 'rgb(59 130 246 / 0.5)' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + +it('The "default" ring opacity is used by the default ring color when not using respectDefaultRingColorOpacity (2)', () => { + let config = { + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + theme: { + ringOpacity: { + DEFAULT: 0.75, + }, + }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: 'rgb(59 130 246 / 0.75)' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + +it('Customizing the default ring color uses the "default" opacity when not using respectDefaultRingColorOpacity (1)', () => { + let config = { + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + theme: { + ringColor: { + DEFAULT: '#ff7f7f', + }, + }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: 'rgb(255 127 127 / 0.5)' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + +it('Customizing the default ring color uses the "default" opacity when not using respectDefaultRingColorOpacity (2)', () => { + let config = { + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + theme: { + ringColor: { + DEFAULT: '#ff7f7f00', + }, + }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: 'rgb(255 127 127 / 0.5)' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + +it('The "default" ring color ignores the default opacity when using respectDefaultRingColorOpacity (1)', () => { + let config = { + future: { respectDefaultRingColorOpacity: true }, + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: '#3b82f67f' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + +it('The "default" ring color ignores the default opacity when using respectDefaultRingColorOpacity (2)', () => { + let config = { + future: { respectDefaultRingColorOpacity: true }, + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + theme: { + ringOpacity: { + DEFAULT: 0.75, + }, + }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: '#3b82f67f' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + +it('Customizing the default ring color preserves its opacity when using respectDefaultRingColorOpacity (1)', () => { + let config = { + future: { respectDefaultRingColorOpacity: true }, + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + theme: { + ringColor: { + DEFAULT: '#ff7f7f', + }, + }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: '#ff7f7f' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +}) + +it('Customizing the default ring color preserves its opacity when using respectDefaultRingColorOpacity (2)', () => { + let config = { + future: { respectDefaultRingColorOpacity: true }, + content: [{ raw: html`<div class="ring"></div>` }], + corePlugins: { preflight: false }, + theme: { + ringColor: { + DEFAULT: '#ff7f7f00', + }, + }, + } + + let input = css` + @tailwind base; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults({ defaultRingColor: '#ff7f7f00' })} + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + `) + }) +})
Default ringColor has opacity baked into it <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.0.22 **What build tool (or framework if it abstracts the build tool) are you using?** postcss 8.4.6, webpack 5.65.0 **What version of Node.js are you using?** For example: v17.5.0 **What browser are you using?** Edge (Chromium) **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/DXtIUnfIC0 **Describe your issue** When trying to set the default color for `ringColor`, it seems like an opacity of `0.5` is being applied regardless of the defined color. In my example I wanted to set the default ring color to be `#000`, but the output ends up becoming `--tw-ring-color: rgb(0 0 0 / 0.5);`. Ideally, I'd like to be able override that default opacity with a defined opacity of my own choosing, or have the color defined for `DEFAULT` just override whatever opacity is being applied.
Hey! This is because `ringOpacity` has a `DEFAULT` of `0.5`. If you override that as well you get the result you want: https://play.tailwindcss.com/CwV0YGg3LS?file=config The whole `ringOpacity` thing isn’t really documented anymore though because we are encouraging the opacity modifier as of v3, so going to leave this open just to prompt us to figure out how to document this or what to do about it. Ah, fantastic. Thank you. > encouraging the opacity modifier I see that intellisense in play.tailwind.com has class suggestions for `<div class="ring/` but they don't have associated styles. Are there plans to support the opacity modifier on the default, maybe `ring/100` or `ring ring/100`? Or is that a separate ring feature request and a separate intellisense bug? Just revisiting this, spent like 45 minutes talking through it with @thecrypticace and I think we _would_ like to change this so that the `ringOpacity.DEFAULT` value didn't inject itself into your custom `ringColor.DEFAULT` value but it would be a breaking change, since anyone who has currently customized `ringColor.DEFAULT` would now see a different color after updating. It feels a little _too_ breaking to just call it a bug fix to me unfortunately. I think what we're going to do is feature flag this fix so that anyone who runs into this problem and finds this issue can see that there's a flag to opt-in to the breaking change early, and then in v4 we can make that the default and mention it in the upgrade guide. Not sure when we will tackle this but leaving this as a note for myself anyways for when we look at this issue again πŸ‘πŸ» In the mean time, changing your `ringOpacity.DEFAULT` as explained earlier is the right way to solve this.
"2022-05-26T23:36:32Z"
3.0
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/DXtIUnfIC0" ]
tailwindlabs/tailwindcss
8,489
tailwindlabs__tailwindcss-8489
[ "8488" ]
fca70850b2985c0c8add440522f9f2da68c13392
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -1437,7 +1437,8 @@ export let corePlugins = { return { '--tw-gradient-from': toColorValue(value, 'from'), - '--tw-gradient-stops': `var(--tw-gradient-from), var(--tw-gradient-to, ${transparentToValue})`, + '--tw-gradient-to': transparentToValue, + '--tw-gradient-stops': `var(--tw-gradient-from), var(--tw-gradient-to)`, } }, }, @@ -1449,10 +1450,11 @@ export let corePlugins = { let transparentToValue = transparentTo(value) return { + '--tw-gradient-to': transparentToValue, '--tw-gradient-stops': `var(--tw-gradient-from), ${toColorValue( value, 'via' - )}, var(--tw-gradient-to, ${transparentToValue})`, + )}, var(--tw-gradient-to)`, } }, },
diff --git a/tests/arbitrary-values.test.css b/tests/arbitrary-values.test.css --- a/tests/arbitrary-values.test.css +++ b/tests/arbitrary-values.test.css @@ -651,18 +651,22 @@ } .from-\[\#da5b66\] { --tw-gradient-from: #da5b66; - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(218 91 102 / 0)); + --tw-gradient-to: rgb(218 91 102 / 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .from-\[var\(--color\)\] { --tw-gradient-from: var(--color); - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(255 255 255 / 0)); + --tw-gradient-to: rgb(255 255 255 / 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .via-\[\#da5b66\] { - --tw-gradient-stops: var(--tw-gradient-from), #da5b66, var(--tw-gradient-to, rgb(218 91 102 / 0)); + --tw-gradient-to: rgb(218 91 102 / 0); + --tw-gradient-stops: var(--tw-gradient-from), #da5b66, var(--tw-gradient-to); } .via-\[var\(--color\)\] { + --tw-gradient-to: rgb(255 255 255 / 0); --tw-gradient-stops: var(--tw-gradient-from), var(--color), - var(--tw-gradient-to, rgb(255 255 255 / 0)); + var(--tw-gradient-to); } .to-\[\#da5b66\] { --tw-gradient-to: #da5b66; diff --git a/tests/basic-usage.test.css b/tests/basic-usage.test.css --- a/tests/basic-usage.test.css +++ b/tests/basic-usage.test.css @@ -596,10 +596,12 @@ } .from-red-300 { --tw-gradient-from: #fca5a5; - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(252 165 165 / 0)); + --tw-gradient-to: rgb(252 165 165 / 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .via-purple-200 { - --tw-gradient-stops: var(--tw-gradient-from), #e9d5ff, var(--tw-gradient-to, rgb(233 213 255 / 0)); + --tw-gradient-to: rgb(233 213 255 / 0); + --tw-gradient-stops: var(--tw-gradient-from), #e9d5ff, var(--tw-gradient-to); } .to-blue-400 { --tw-gradient-to: #60a5fa; diff --git a/tests/color-opacity-modifiers.test.js b/tests/color-opacity-modifiers.test.js --- a/tests/color-opacity-modifiers.test.js +++ b/tests/color-opacity-modifiers.test.js @@ -167,7 +167,8 @@ test('utilities that support any type are supported', async () => { expect(result.css).toMatchFormattedCss(css` .from-red-500\/50 { --tw-gradient-from: rgb(239 68 68 / 0.5); - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(239 68 68 / 0)); + --tw-gradient-to: rgb(239 68 68 / 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .fill-red-500\/25 { fill: rgb(239 68 68 / 0.25); diff --git a/tests/kitchen-sink.test.css b/tests/kitchen-sink.test.css --- a/tests/kitchen-sink.test.css +++ b/tests/kitchen-sink.test.css @@ -261,7 +261,8 @@ div { } .from-foo { --tw-gradient-from: #bada55; - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(186 218 85 / 0)); + --tw-gradient-to: rgb(186 218 85 / 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .text-center { text-align: center; diff --git a/tests/plugins/gradientColorStops.test.js b/tests/plugins/gradientColorStops.test.js --- a/tests/plugins/gradientColorStops.test.js +++ b/tests/plugins/gradientColorStops.test.js @@ -34,19 +34,21 @@ test('opacity variables are given to colors defined as closures', () => { expect(result.css).toMatchFormattedCss(css` .from-primary { --tw-gradient-from: rgb(31, 31, 31); - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(31, 31, 31, 0)); + --tw-gradient-to: rgba(31, 31, 31, 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .from-secondary { --tw-gradient-from: hsl(10, 50%, 50%); - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, hsl(10 50% 50% / 0)); + --tw-gradient-to: hsl(10 50% 50% / 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .via-primary { - --tw-gradient-stops: var(--tw-gradient-from), rgb(31, 31, 31), - var(--tw-gradient-to, rgba(31, 31, 31, 0)); + --tw-gradient-to: rgba(31, 31, 31, 0); + --tw-gradient-stops: var(--tw-gradient-from), rgb(31, 31, 31), var(--tw-gradient-to); } .via-secondary { - --tw-gradient-stops: var(--tw-gradient-from), hsl(10, 50%, 50%), - var(--tw-gradient-to, hsl(10 50% 50% / 0)); + --tw-gradient-to: hsl(10 50% 50% / 0); + --tw-gradient-stops: var(--tw-gradient-from), hsl(10, 50%, 50%), var(--tw-gradient-to); } .to-primary { --tw-gradient-to: rgb(31, 31, 31); diff --git a/tests/raw-content.test.css b/tests/raw-content.test.css --- a/tests/raw-content.test.css +++ b/tests/raw-content.test.css @@ -412,10 +412,12 @@ } .from-red-300 { --tw-gradient-from: #fca5a5; - --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgb(252 165 165 / 0)); + --tw-gradient-to: rgb(252 165 165 / 0); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); } .via-purple-200 { - --tw-gradient-stops: var(--tw-gradient-from), #e9d5ff, var(--tw-gradient-to, rgb(233 213 255 / 0)); + --tw-gradient-to: rgb(233 213 255 / 0); + --tw-gradient-stops: var(--tw-gradient-from), #e9d5ff, var(--tw-gradient-to); } .to-blue-400 { --tw-gradient-to: #60a5fa;
bg-gradient auto-transparent calculation doesn't work when parent element uses two colour gradient **What version of Tailwind CSS are you using?** v3.0.24 **What build tool (or framework if it abstracts the build tool) are you using?** [email protected] [email protected] Also through cdn package <script src="https://cdn.tailwindcss.com"></script> **What version of Node.js are you using?** v16.15.0 **What browser are you using?** Firefox, Chrome, Safari All latest **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/w4cImWRzrB **Describe your issue** When creating a transparent gradient the guidance is to not include to-transparent to let tailwind calculate the correct transparent to color to avoid a safari bug. If this happens on a child element where the parent element uses a gradient background with two colors defined then the transparent color is set to the parents to color.
"2022-06-01T19:10:34Z"
3.0
[]
[ "tests/plugins/gradientColorStops.test.js", "tests/color-opacity-modifiers.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/w4cImWRzrB" ]
tailwindlabs/tailwindcss
8,563
tailwindlabs__tailwindcss-8563
[ "8562" ]
9a5db88e54e47ec1812200f544c3e8aa317a79d5
diff --git a/src/lib/evaluateTailwindFunctions.js b/src/lib/evaluateTailwindFunctions.js --- a/src/lib/evaluateTailwindFunctions.js +++ b/src/lib/evaluateTailwindFunctions.js @@ -162,7 +162,7 @@ let nodeTypePropertyMap = { export default function ({ tailwindConfig: config }) { let functions = { theme: (node, path, ...defaultValue) => { - let matches = path.match(/^([^\/\s]+)(?:\s*\/\s*([^\/\s]+))$/) + let matches = path.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/) let alpha = undefined if (matches) {
diff --git a/tests/evaluateTailwindFunctions.test.js b/tests/evaluateTailwindFunctions.test.js --- a/tests/evaluateTailwindFunctions.test.js +++ b/tests/evaluateTailwindFunctions.test.js @@ -1024,3 +1024,34 @@ test('Theme function can extract alpha values for colors (8)', () => { expect(result.warnings().length).toBe(0) }) }) + +test('Theme functions can reference values with slashes in brackets', () => { + let input = css` + .foo1 { + color: theme(colors[a/b]); + } + .foo2 { + color: theme(colors[a/b]/50%); + } + ` + + let output = css` + .foo1 { + color: #000000; + } + .foo2 { + color: rgb(0 0 0 / 50%); + } + ` + + return runFull(input, { + theme: { + colors: { + 'a/b': '#000000', + }, + }, + }).then((result) => { + expect(result.css).toMatchCss(output) + expect(result.warnings().length).toBe(0) + }) +}) diff --git a/tests/opacity.test.js b/tests/opacity.test.js --- a/tests/opacity.test.js +++ b/tests/opacity.test.js @@ -728,3 +728,36 @@ it('should be possible to use <alpha-value> inside arbitrary values', () => { `) }) }) + +it('Theme functions can reference values with slashes in brackets', () => { + let config = { + content: [ + { + raw: html` <div class="bg-foo1 bg-foo2"></div> `, + }, + ], + theme: { + colors: { + 'a/b': '#000000', + }, + extend: { + backgroundColor: ({ theme }) => ({ + foo1: theme('colors[a/b]'), + foo2: theme('colors[a/b]/50%'), + }), + }, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchCss(css` + .bg-foo1 { + --tw-bg-opacity: 1; + background-color: rgb(0 0 0 / var(--tw-bg-opacity)); + } + .bg-foo2 { + background-color: rgb(0 0 0 / 50%); + } + `) + }) +})
3.1.0 "unbalanced brackets" error when using theme function with bracket notation **What version of Tailwind CSS are you using?** v3.1.0 **What build tool (or framework if it abstracts the build tool) are you using?** - laravel-mix 6.0.49 - play.tailwindcss.com **What version of Node.js are you using?** v18.3.0 **What browser are you using?** N/A **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/kLuW3Vrpv6?file=css **Describe your issue** In Tailwindcss `v3.1.0` this css ```css .test-width { width: theme('width[1/12]'); } ``` give this error: `Error: Path is invalid. Has unbalanced brackets: width['1` while in Tailwindcss `v3.0.24` it compiles correctly to ```css .test-width { width: 8.33333%; } ```
"2022-06-09T18:05:57Z"
3.1
[ "tests/opacity.test.js" ]
[ "tests/evaluateTailwindFunctions.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/kLuW3Vrpv6?file=css" ]
tailwindlabs/tailwindcss
8,569
tailwindlabs__tailwindcss-8569
[ "8559" ]
c44dd7b8e70e9ab633a33b4f82b6f23c914d8f3d
diff --git a/src/lib/defaultExtractor.js b/src/lib/defaultExtractor.js --- a/src/lib/defaultExtractor.js +++ b/src/lib/defaultExtractor.js @@ -25,7 +25,7 @@ function* buildRegExps(context) { let utility = regex.any([ // Arbitrary properties - /\[[^\s:'"]+:[^\s\]]+\]/, + /\[[^\s:'"`]+:[^\s\]]+\]/, // Utilities regex.pattern([ @@ -43,7 +43,7 @@ function* buildRegExps(context) { /(?![{([]])/, // optionally followed by an opacity modifier - /(?:\/[^\s'"\\><$]*)?/, + /(?:\/[^\s'"`\\><$]*)?/, ]), regex.pattern([ @@ -54,11 +54,11 @@ function* buildRegExps(context) { /(?![{([]])/, // optionally followed by an opacity modifier - /(?:\/[^\s'"\\$]*)?/, + /(?:\/[^\s'"`\\$]*)?/, ]), // Normal values w/o quotes β€” may include an opacity modifier - /[-\/][^\s'"\\$={><]*/, + /[-\/][^\s'"`\\$={><]*/, ]) ), ]), @@ -69,8 +69,8 @@ function* buildRegExps(context) { '((?=((', regex.any( [ - regex.pattern([/([^\s"'\[\\]+-)?\[[^\s"'\\]+\]/, separator]), - regex.pattern([/[^\s"'\[\\]+/, separator]), + regex.pattern([/([^\s"'`\[\\]+-)?\[[^\s"'`\\]+\]/, separator]), + regex.pattern([/[^\s"'`\[\\]+/, separator]), ], true ), @@ -91,7 +91,7 @@ function* buildRegExps(context) { ]) // 5. Inner matches - // yield /[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g + yield /[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g } // We want to capture any "special" characters
diff --git a/tests/default-extractor.test.js b/tests/default-extractor.test.js --- a/tests/default-extractor.test.js +++ b/tests/default-extractor.test.js @@ -415,28 +415,24 @@ test('with single quotes array within template literal', async () => { const extractions = defaultExtractor(`<div class=\`\${['pr-1.5']}\`></div>`) expect(extractions).toContain('pr-1.5') - expect(extractions).not.toContain('pr-1') }) test('with double quotes array within template literal', async () => { const extractions = defaultExtractor(`<div class=\`\${["pr-1.5"]}\`></div>`) expect(extractions).toContain('pr-1.5') - expect(extractions).not.toContain('pr-1') }) test('with single quotes array within function', async () => { const extractions = defaultExtractor(`document.body.classList.add(['pl-1.5'].join(" "));`) expect(extractions).toContain('pl-1.5') - expect(extractions).not.toContain('pl-1') }) test('with double quotes array within function', async () => { const extractions = defaultExtractor(`document.body.classList.add(["pl-1.5"].join(" "));`) expect(extractions).toContain('pl-1.5') - expect(extractions).not.toContain('pl-1') }) test('with angle brackets', async () => { @@ -449,3 +445,26 @@ test('with angle brackets', async () => { expect(extractions).not.toContain('>shadow-xl') expect(extractions).not.toContain('shadow-xl<') }) + +test('markdown code fences', async () => { + const extractions = defaultExtractor('<!-- this should work: `.font-bold`, `.font-normal` -->') + + expect(extractions).toContain('font-bold') + expect(extractions).toContain('font-normal') + expect(extractions).not.toContain('.font-bold') + expect(extractions).not.toContain('.font-normal') +}) + +test('classes in slim templates', async () => { + const extractions = defaultExtractor(` + p.bg-red-500.text-sm + 'This is a paragraph + small.italic.text-gray-500 + '(Look mom, no closing tag!) + `) + + expect(extractions).toContain('bg-red-500') + expect(extractions).toContain('text-sm') + expect(extractions).toContain('italic') + expect(extractions).toContain('text-gray-500') +})
Tailwind 3.1 regression: No longer keeps classes mentioned in markdown backticks **What version of Tailwind CSS are you using?** For example: v3.1.0 **What build tool (or framework if it abstracts the build tool) are you using?** - parcel - tailwindcss play **What version of Node.js are you using?** For example: v16.14.2 **What browser are you using?** For example: Firefox **What operating system are you using?** For example: OpenSUSE linux **Reproduction URL** https://play.tailwindcss.com/XRYewVE3SL **Describe your issue** Check `Generated CSS` -> `Components`. The classes `.alert-success` `.alert-info` `.alert-failure` are missing in TailwindCSS 3.1, but are rendered in TailwindCSS 3.0 and earlier. This is a 3.1.0 regression. Removing the backticks around the class names (but keeping the leading `.`) in the HTML comment makes the classes get rendered in TailwindCSS 3.1 as well. **Note** This might have the same root cause as #8557 has.
"2022-06-09T20:43:56Z"
3.1
[]
[ "tests/default-extractor.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/XRYewVE3SL" ]
tailwindlabs/tailwindcss
8,604
tailwindlabs__tailwindcss-8604
[ "8601" ]
ad98a619a446a58de24286a3d3e8f442668fd00d
diff --git a/src/lib/defaultExtractor.js b/src/lib/defaultExtractor.js --- a/src/lib/defaultExtractor.js +++ b/src/lib/defaultExtractor.js @@ -37,7 +37,7 @@ function* buildRegExps(context) { regex.any([ regex.pattern([ // Arbitrary values - /-\[[^\s:]+\]/, + /-(?:\w+-)*\[[^\s:]+\]/, // Not immediately followed by an `{[(` /(?![{([]])/, @@ -48,7 +48,7 @@ function* buildRegExps(context) { regex.pattern([ // Arbitrary values - /-\[[^\s]+\]/, + /-(?:\w+-)*\[[^\s]+\]/, // Not immediately followed by an `{[(` /(?![{([]])/,
diff --git a/tests/default-extractor.test.js b/tests/default-extractor.test.js --- a/tests/default-extractor.test.js +++ b/tests/default-extractor.test.js @@ -468,3 +468,11 @@ test('classes in slim templates', async () => { expect(extractions).toContain('italic') expect(extractions).toContain('text-gray-500') }) + +test('multi-word + arbitrary values + quotes', async () => { + const extractions = defaultExtractor(` + grid-cols-['repeat(2)'] + `) + + expect(extractions).toContain(`grid-cols-['repeat(2)']`) +})
Arbitrary `content-['hello']` utilities not recognized when using a prefix like `tw-` <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.1.2 **What browser are you using?** Chrome **Reproduction URL** https://play.tailwindcss.com/cjDwL0ojUE
Thanks for reporting! Looks like this only happens when using a prefix, will get it figured out πŸ‘
"2022-06-12T14:04:19Z"
3.1
[]
[ "tests/default-extractor.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/cjDwL0ojUE" ]
tailwindlabs/tailwindcss
8,608
tailwindlabs__tailwindcss-8608
[ "8594" ]
a9c7e52a59d9532974891a53ff0dc1fe25c5ae94
diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -465,11 +465,14 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs } if (Array.isArray(result)) { - return result.map((variant) => parseVariant(variant)) + return result + .filter((variant) => typeof variant === 'string') + .map((variant) => parseVariant(variant)) } // result may be undefined with legacy variants that use APIs like `modifySelectors` - return result && parseVariant(result)(api) + // result may also be a postcss node if someone was returning the result from `modifySelectors` + return result && typeof result === 'string' && parseVariant(result)(api) } }
diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -461,6 +461,57 @@ test('before and after variants are a bit special, and forced to the end (2)', ( }) }) +test('returning non-strings and non-selectors in addVariant', () => { + /** @type {import('../types/config').Config} */ + let config = { + content: [ + { + raw: html` + <div class="peer-aria-expanded:text-center"></div> + <div class="peer-aria-expanded-2:text-center"></div> + `, + }, + ], + plugins: [ + function ({ addVariant, e }) { + addVariant('peer-aria-expanded', ({ modifySelectors, separator }) => + // Returning anything other string | string[] | undefined here is not supported + // But we're trying to be lenient here and just throw it out + modifySelectors( + ({ className }) => + `.peer[aria-expanded="true"] ~ .${e(`peer-aria-expanded${separator}${className}`)}` + ) + ) + + addVariant('peer-aria-expanded-2', ({ modifySelectors, separator }) => { + let nodes = modifySelectors( + ({ className }) => + `.peer[aria-expanded="false"] ~ .${e(`peer-aria-expanded${separator}${className}`)}` + ) + + return [ + // Returning anything other than strings here is not supported + // But we're trying to be lenient here and just throw it out + nodes, + '.peer[aria-expanded="false"] ~ &', + ] + }) + }, + ], + } + + return run('@tailwind components;@tailwind utilities', config).then((result) => { + return expect(result.css).toMatchFormattedCss(css` + .peer[aria-expanded='true'] ~ .peer-aria-expanded\:text-center { + text-align: center; + } + .peer[aria-expanded='false'] ~ .peer-aria-expanded-2\:text-center { + text-align: center; + } + `) + }) +}) + it('should not generate variants of user css if it is not inside a layer', () => { let config = { content: [{ raw: html`<div class="hover:foo"></div>` }],
Updating from v3.0.23 to v3.1.1 & 3.1.2 getting variant.replace not a function error Hi All. I am trying to update our project from tailwinds v3.0.23 to the latest. Going to v3.0.24 I have no issues but updating to v3.1.1 or 3.1.2 I am getting this error when I try to run my project. It also comes up as an intellisense error as shown below. Not sure if it something I am doing wrong that worked in the older versions. I am using laravel mix v6.0.11 which runs on top of webpack 4.4.31 Here is the output: <img width="1204" alt="Screen Shot 2022-06-10 at 4 54 42 PM" src="https://user-images.githubusercontent.com/17321059/173164135-1ba43fe6-e938-4d49-99e6-99f6cbaf3e32.png"> Then here is what installed. I am running node v16.13.2: <img width="1462" alt="Screen Shot 2022-06-10 at 5 03 23 PM" src="https://user-images.githubusercontent.com/17321059/173164218-d91ecf25-53f3-40ec-8d9b-cc7004ba3116.png"> Here is my tailwind config: ``` javascript const plugin = require('tailwindcss/plugin') const defaultTheme = require('tailwindcss/defaultTheme') const { extend } = require('tailwindcss/defaultTheme') const customColors = { charcoal: '#2F1F21', 'charcoal-50': '#5B5757', burgandy: '#85300D', ocre: '#AB6B05', ocean: '#125759', cream: '#DEDBD9', 'cream-30': '#F5F4F4', 'cream-50': '#EEECEB', sand: '#BAAB99', 'blaze-red': '#FF5717', 'warm-yellow': '#FF5717', turquoise: '#2BBDA6', } module.exports = { content: [ 'shopify/snippets/*.liquid', 'shopify/templates/*.liquid', 'shopify/templates/customers/*.liquid', 'shopify/layout/*.liquid', 'src/sections/*.liquid', 'src/scripts/*.{js,ts}', ], theme: { screens: { xs: '475px', ...defaultTheme.screens, }, extend: { fontFamily: { sans: ['DM Sans', 'Helvetica', 'Artial', 'sans-serif'], serif: ['GT Super', 'Times', 'serif'], }, colors: customColors, animation: { 'spin-10s': 'spin 10s linear infinite', }, letterSpacing: { tight: '-0.035em', }, }, }, safelist: [ { pattern: /font-*/, }, ], plugins: [ require('tailwind-scrollbar-hide'), plugin(function ({ addVariant }) { addVariant('current', ['&[aria-current="true"]', '&.active']) }), plugin(function ({ addVariant }) { addVariant('accessible', ['body.accessible &']) }), plugin(function ({ addVariant, e }) { //add more true or false aria attributes or custom boolean attributes const ariaAttributes = ['aria-expanded', 'aria-hidden', 'aria-current', 'aria-busy', 'data-check-validity'] ariaAttributes.forEach((adj) => { const selector = adj addVariant(selector, [`&[${selector}="true"]`]) const groupSelector = `group-${adj}` addVariant(groupSelector, ({ modifySelectors, separator }) => modifySelectors(({ className }) => `.group[${adj}="true"] .${e(`${groupSelector}${separator}${className}`)}`) ) const peerSelector = `peer-${adj}` addVariant(peerSelector, ({ modifySelectors, separator }) => modifySelectors(({ className }) => `.peer[${adj}="true"] ~ .${e(`${peerSelector}${separator}${className}`)}`) ) }) }), //extra custom colors into root variables, can extra all by passing in theme, //then pass theme('colors') into the extra function plugin(function ({ addBase }) { function extractColorVars(colorObj, colorGroup = '') { return Object.keys(colorObj).reduce((vars, colorKey) => { const value = colorObj[colorKey] const newVars = typeof value === 'string' ? { [`--color${colorGroup}-${colorKey}`]: value } : extractColorVars(value, `-${colorKey}`) return { ...vars, ...newVars } }, {}) } addBase({ ':root': extractColorVars(customColors), }) }), ], } ```
Getting the same error, in my case, it's related to **tailwindcss-named-groups** plugin. A shot in the dark here, but it might be related to this change: https://github.com/tailwindlabs/tailwindcss/commit/bb4f5dab6b1f44887b0264cc558090b906715d02 You can clear the error by making your `addVariant` calls return `undefined` instead of returning the result of `modifySelectors`. So try adding some brackets here for example: ``` addVariant(peerSelector, ({ modifySelectors, separator }) => { modifySelectors(({ className }) => `.peer[${adj}="true"] ~ .${e(`${peerSelector}${separator}${className}`)}`) }) ``` I don't know if that will actually make what you're intending to happen start working again, but hopefully this helps.
"2022-06-12T14:44:15Z"
3.1
[]
[ "tests/variants.test.js" ]
TypeScript
[ "https://user-images.githubusercontent.com/17321059/173164135-1ba43fe6-e938-4d49-99e6-99f6cbaf3e32.png", "https://user-images.githubusercontent.com/17321059/173164218-d91ecf25-53f3-40ec-8d9b-cc7004ba3116.png" ]
[]
tailwindlabs/tailwindcss
8,615
tailwindlabs__tailwindcss-8615
[ "8614" ]
d1165637d341af0536e07a88858a5bef75d8cc39
diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -40,9 +40,9 @@ export function normalize(value, isRoot = true) { value = value.trim() } - // Add spaces around operators inside calc() that do not follow an operator + // Add spaces around operators inside math functions like calc() that do not follow an operator // or '('. - value = value.replace(/calc\(.+\)/g, (match) => { + value = value.replace(/(calc|min|max|clamp)\(.+\)/g, (match) => { return match.replace( /(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g, '$1 $2 '
diff --git a/tests/normalize-data-types.test.js b/tests/normalize-data-types.test.js --- a/tests/normalize-data-types.test.js +++ b/tests/normalize-data-types.test.js @@ -20,7 +20,7 @@ let table = [ ['var(--foo)', 'var(--foo)'], ['var(--headings-h1-size)', 'var(--headings-h1-size)'], - // calc(…) get's spaces around operators + // math functions like calc(…) get spaces around operators ['calc(1+2)', 'calc(1 + 2)'], ['calc(100%+1rem)', 'calc(100% + 1rem)'], ['calc(1+calc(100%-20px))', 'calc(1 + calc(100% - 20px))'], @@ -29,6 +29,9 @@ let table = [ 'calc(var(--headings-h1-size)*calc(100%+50%))', 'calc(var(--headings-h1-size) * calc(100% + 50%))', ], + ['min(1+2)', 'min(1 + 2)'], + ['max(1+2)', 'max(1 + 2)'], + ['clamp(1+2,1+3,1+4)', 'clamp(1 + 2,1 + 3,1 + 4)'], ['var(--heading-h1-font-size)', 'var(--heading-h1-font-size)'], ['var(--my-var-with-more-than-3-words)', 'var(--my-var-with-more-than-3-words)'], ['var(--width, calc(100%+1rem))', 'var(--width, calc(100% + 1rem))'],
Regression: Tailwind producing invalid CSS for arbitrary values with arithmetic operators <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.1.2 and v3.1.1 **What build tool (or framework if it abstracts the build tool) are you using?** Tailwind Play **What version of Node.js are you using?** Not applicable **What browser are you using?** Chrome 102 and Safari 15.5 **What operating system are you using?** macOS 12.4 **Reproduction URL** https://play.tailwindcss.com/Y4DN00mQfb **Describe your issue** The class `w-[min(50vw+100px)]` produces following CSS in Tailwind CSS v3.1.1 and v3.1.2: ```css .w-\[min\(50vw\+100px\)\] { width: min(50vw+100px); } ``` which is perceived as invalid in both Chrome and Safari due to the missing space around the `+` operator and therefore not applied. Same happens for `max()` and the other [math functions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Functions#math_functions), but not for `calc()`. In Tailwind CSS v3.0.24 the CSS produced was correct: ```css .w-\[min\(50vw\+100px\)\] { width: min(50vw + 100px); } ```
Current workarounds in Tailwind v3.1.1 and above: - Wrapping arithmetic operations in a `calc()` call: `w-[min(calc(50vw+100px))]` - Using `_` to insert spaces: `w-[min(50vw_+_100px)]` Both not ideal in the long term.
"2022-06-13T08:23:31Z"
3.1
[]
[ "tests/normalize-data-types.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/Y4DN00mQfb" ]
tailwindlabs/tailwindcss
8,622
tailwindlabs__tailwindcss-8622
[ "8610" ]
22eaad17c33583b841d2086a9386dd5c1770061c
diff --git a/src/corePlugins.js b/src/corePlugins.js --- a/src/corePlugins.js +++ b/src/corePlugins.js @@ -14,6 +14,7 @@ import { version as tailwindVersion } from '../package.json' import log from './util/log' import { normalizeScreens } from './util/normalizeScreens' import { formatBoxShadowValue, parseBoxShadowValue } from './util/parseBoxShadowValue' +import { removeAlphaVariables } from './util/removeAlphaVariables' import { flagEnabled } from './featureFlags' export let variantPlugins = { @@ -21,7 +22,19 @@ export let variantPlugins = { addVariant('first-letter', '&::first-letter') addVariant('first-line', '&::first-line') - addVariant('marker', ['& *::marker', '&::marker']) + addVariant('marker', [ + ({ container }) => { + removeAlphaVariables(container, ['--tw-text-opacity']) + + return '& *::marker' + }, + ({ container }) => { + removeAlphaVariables(container, ['--tw-text-opacity']) + + return '&::marker' + }, + ]) + addVariant('selection', ['& *::selection', '&::selection']) addVariant('file', '&::file-selector-button') @@ -77,21 +90,11 @@ export let variantPlugins = { [ 'visited', ({ container }) => { - let toRemove = ['--tw-text-opacity', '--tw-border-opacity', '--tw-bg-opacity'] - - container.walkDecls((decl) => { - if (toRemove.includes(decl.prop)) { - decl.remove() - - return - } - - for (const varName of toRemove) { - if (decl.value.includes(`/ var(${varName})`)) { - decl.value = decl.value.replace(`/ var(${varName})`, '') - } - } - }) + removeAlphaVariables(container, [ + '--tw-text-opacity', + '--tw-border-opacity', + '--tw-bg-opacity', + ]) return '&:visited' }, diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -163,15 +163,17 @@ function applyVariant(variant, matches, context) { let container = postcss.root({ nodes: [rule.clone()] }) - for (let [variantSort, variantFunction] of variantFunctionTuples) { - let clone = container.clone() + for (let [variantSort, variantFunction, containerFromArray] of variantFunctionTuples) { + let clone = containerFromArray ?? container.clone() let collectedFormats = [] - let originals = new Map() - function prepareBackup() { - if (originals.size > 0) return // Already prepared, chicken out - clone.walkRules((rule) => originals.set(rule, rule.selector)) + // Already prepared, chicken out + if (clone.raws.neededBackup) { + return + } + clone.raws.neededBackup = true + clone.walkRules((rule) => (rule.raws.originalSelector = rule.selector)) } function modifySelectors(modifierFunction) { @@ -231,6 +233,10 @@ function applyVariant(variant, matches, context) { // reserving additional X places for these 'unknown' variants in between. variantSort | BigInt(idx << ruleWithVariant.length), variantFunction, + + // If the clone has been modified we have to pass that back + // though so each rule can use the modified container + clone.clone(), ]) } continue @@ -244,13 +250,15 @@ function applyVariant(variant, matches, context) { continue } - // We filled the `originals`, therefore we assume that somebody touched + // We had to backup selectors, therefore we assume that somebody touched // `container` or `modifySelectors`. Let's see if they did, so that we // can restore the selectors, and collect the format strings. - if (originals.size > 0) { + if (clone.raws.neededBackup) { + delete clone.raws.neededBackup clone.walkRules((rule) => { - if (!originals.has(rule)) return - let before = originals.get(rule) + let before = rule.raws.originalSelector + if (!before) return + delete rule.raws.originalSelector if (before === rule.selector) return // No mutation happened let modified = rule.selector diff --git a/src/util/removeAlphaVariables.js b/src/util/removeAlphaVariables.js new file mode 100644 --- /dev/null +++ b/src/util/removeAlphaVariables.js @@ -0,0 +1,24 @@ +/** + * This function removes any uses of CSS variables used as an alpha channel + * + * This is required for selectors like `:visited` which do not allow + * changes in opacity or external control using CSS variables. + * + * @param {import('postcss').Container} container + * @param {string[]} toRemove + */ +export function removeAlphaVariables(container, toRemove) { + container.walkDecls((decl) => { + if (toRemove.includes(decl.prop)) { + decl.remove() + + return + } + + for (let varName of toRemove) { + if (decl.value.includes(`/ var(${varName})`)) { + decl.value = decl.value.replace(`/ var(${varName})`, '') + } + } + }) +}
diff --git a/tests/parallel-variants.test.js b/tests/parallel-variants.test.js --- a/tests/parallel-variants.test.js +++ b/tests/parallel-variants.test.js @@ -85,3 +85,52 @@ test('parallel variants can be generated using a function that returns parallel `) }) }) + +test('a function that returns parallel variants can modify the container', async () => { + let config = { + content: [ + { + raw: html`<div + class="hover:test:font-black test:font-bold test:font-medium font-normal" + ></div>`, + }, + ], + plugins: [ + function test({ addVariant }) { + addVariant('test', ({ container }) => { + container.walkDecls((decl) => { + decl.value = `calc(0 + ${decl.value})` + }) + + return ['& *::test', '&::test'] + }) + }, + ], + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .font-normal { + font-weight: 400; + } + .test\:font-bold *::test { + font-weight: calc(0 + 700); + } + .test\:font-medium *::test { + font-weight: calc(0 + 500); + } + .test\:font-bold::test { + font-weight: calc(0 + 700); + } + .test\:font-medium::test { + font-weight: calc(0 + 500); + } + .hover\:test\:font-black *:hover::test { + font-weight: calc(0 + 900); + } + .hover\:test\:font-black:hover::test { + font-weight: calc(0 + 900); + } + `) + }) +}) diff --git a/tests/variants.test.css b/tests/variants.test.css --- a/tests/variants.test.css +++ b/tests/variants.test.css @@ -112,16 +112,14 @@ line-height: 1.75rem; } .marker\:text-red-500 *::marker { - --tw-text-opacity: 1; - color: rgb(239 68 68 / var(--tw-text-opacity)); + color: rgb(239 68 68); } .marker\:text-lg::marker { font-size: 1.125rem; line-height: 1.75rem; } .marker\:text-red-500::marker { - --tw-text-opacity: 1; - color: rgb(239 68 68 / var(--tw-text-opacity)); + color: rgb(239 68 68); } .selection\:bg-blue-500 *::selection { --tw-bg-opacity: 1; diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -485,8 +485,7 @@ test('returning non-strings and non-selectors in addVariant', () => { addVariant('peer-aria-expanded-2', ({ modifySelectors, separator }) => { let nodes = modifySelectors( - ({ className }) => - `.peer[aria-expanded="false"] ~ .${e(`peer-aria-expanded${separator}${className}`)}` + ({ className }) => `.${e(`peer-aria-expanded-2${separator}${className}`)}` ) return [
Safari ignores alpha channel in colors in `::marker`, which makes styling them with Tailwind impossible <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.1.2 **What build tool (or framework if it abstracts the build tool) are you using?** <details> <summary>`postcss`</summary> ```js module.exports = { plugins: { "postcss-import": {}, "tailwindcss": {}, "autoprefixer": {}, } } ``` </details> **What version of Node.js are you using?** v12.22.9 **What browser are you using?** Safari 15.5 on macOS 12.4 **Reproduction URL** https://play.tailwindcss.com/iea3Szbz1t **Describe your issue** On Safari, all of the following examples work correctly: ```css ::marker { color: red; } ::marker { color: #f00; } ::marker { color: rgb(255 0 0); } ``` But these are completely ignored: ```css ::marker { color: rgba(255 0 0 50); } ::marker { color: rgb(255 0 0 / 50); } ``` I discovered this while playing with arbitrary variants, trying to lighten the ordinals in an ordered list. When that didn't work, I thought, "that's fine, I can just use an arbitrary value!" but turns out that `[&::marker]:text-[#ff0000]` gets translated to ```css .\[\&\:\:marker\]\:text-\[\#ff0000\]::marker { --tw-text-opacity: 1; color: rgb(255 0 0 / var(--tw-text-opacity)); } ``` Which makes it impossible to use Tailwind to style marker colors. I realize this is more of a Safari bug than a Tailwind bug, but I'm curious as to why you're translating a hardcoded `[red]` into an RGBA value, and whether that's something that could be addressed to allow styling list markers with Tailwind πŸ€”
For anyone else that stumbles into this, the workaround I've found is to add this to my CSS file: ``` css ::marker { color: theme(colors.slate.500); } ``` But ideally this should be handled from the HTML to make it easier to manage together with the other styles. Looked at this quickly, it seems like the thing that breaks it is the variable, not the fact that there's an opacity value set: https://jsfiddle.net/oyv60qhd/1/ So you can work around this by disabling all of our color opacity utilities like this: ```js // tailwind.config.js module.exports = { // ... corePlugins: { textOpacity: false, backgroundOpacity: false, divideOpacity: false, borderOpacity: false, placeholderOpacity: false, }, } ``` Those will end up being disabled by default in v4. The whole reason we generate CSS like this: ```css .\[\&\:\:marker\]\:text-\[\#ff0000\]::marker { --tw-text-opacity: 1; color: rgb(255 0 0 / var(--tw-text-opacity)); } ``` ...is so you can combine the color with the corresponding opacity utility, for example: ```html <li class="marker:text-[red] marker:text-opacity-50"> ``` ...but generally we encourage the opacity modifier now, which doesn't require the variable but we still have to output it for backwards compatibility reasons (unless those opacity plugins are disabled). Will leave this open at least for now though so I remember to discuss it with the team in case there's an easy way to just make this work that isn't a breaking change. I've submitted a WebKit bug report for this: [WebKit Bug #241576](https://bugs.webkit.org/show_bug.cgi?id=241576) hah I already did that earlier today: https://bugs.webkit.org/show_bug.cgi?id=241566 β€” in any case appreciate it! The problem is that custom properties are not supported because allowed properties in `::marker` are whitelisted in webkit (correct): https://github.com/WebKit/WebKit/blob/fdc6c5fc1872fab62106b209c8a6a5aaa00730be/Source/WebCore/style/PropertyAllowlist.cpp but they don't include custom properties (incorrect). The spec doesn't mention them though so it's also possibly a CSS spec issue.
"2022-06-13T18:13:17Z"
3.1
[]
[ "tests/parallel-variants.test.js", "tests/variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/iea3Szbz1t" ]
tailwindlabs/tailwindcss
8,625
tailwindlabs__tailwindcss-8625
[ "8619" ]
aad299cf90d8679fb9fad6d519749365d9c6da08
diff --git a/src/lib/evaluateTailwindFunctions.js b/src/lib/evaluateTailwindFunctions.js --- a/src/lib/evaluateTailwindFunctions.js +++ b/src/lib/evaluateTailwindFunctions.js @@ -40,9 +40,7 @@ function listKeys(obj) { } function validatePath(config, path, defaultValue, themeOpts = {}) { - const pathString = Array.isArray(path) - ? pathToString(path) - : path.replace(/^['"]+/g, '').replace(/['"]+$/g, '') + const pathString = Array.isArray(path) ? pathToString(path) : path.replace(/^['"]+|['"]+$/g, '') const pathSegments = Array.isArray(path) ? path : toPath(pathString) const value = dlv(config.theme, pathSegments, defaultValue) @@ -162,6 +160,10 @@ let nodeTypePropertyMap = { export default function ({ tailwindConfig: config }) { let functions = { theme: (node, path, ...defaultValue) => { + // Strip quotes from beginning and end of string + // This allows the alpha value to be present inside of quotes + path = path.replace(/^['"]+|['"]+$/g, '') + let matches = path.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/) let alpha = undefined
diff --git a/tests/evaluateTailwindFunctions.test.js b/tests/evaluateTailwindFunctions.test.js --- a/tests/evaluateTailwindFunctions.test.js +++ b/tests/evaluateTailwindFunctions.test.js @@ -1055,3 +1055,53 @@ test('Theme functions can reference values with slashes in brackets', () => { expect(result.warnings().length).toBe(0) }) }) + +test('Theme functions with alpha value inside quotes', () => { + let input = css` + .foo { + color: theme('colors.yellow / 50%'); + } + ` + + let output = css` + .foo { + color: rgb(247 204 80 / 50%); + } + ` + + return runFull(input, { + theme: { + colors: { + yellow: '#f7cc50', + }, + }, + }).then((result) => { + expect(result.css).toMatchCss(output) + expect(result.warnings().length).toBe(0) + }) +}) + +test('Theme functions with alpha with quotes value around color only', () => { + let input = css` + .foo { + color: theme('colors.yellow' / 50%); + } + ` + + let output = css` + .foo { + color: rgb(247 204 80 / 50%); + } + ` + + return runFull(input, { + theme: { + colors: { + yellow: '#f7cc50', + }, + }, + }).then((result) => { + expect(result.css).toMatchCss(output) + expect(result.warnings().length).toBe(0) + }) +})
3.1 version, theme function reports lint error <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.1.2 **What build tool (or framework if it abstracts the build tool) are you using?** **What version of Node.js are you using?** 16.14 **What browser are you using?** **What operating system are you using?** **Reproduction URL** **Describe your issue** `theme('colors[primary] / 20%')` reports `'colors[primary] / 20%' does not exist in your theme config.`. It works well , but reports a lint error. Do I need to add any config or change the code below in `tailwind.config.js` ? ```css ... primary: withOpacity('--color-primary-rgb'), ... ``` Describe the problem you're seeing, any important steps to reproduce and what behavior you expect instead.
"2022-06-13T19:28:51Z"
3.1
[]
[ "tests/evaluateTailwindFunctions.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,652
tailwindlabs__tailwindcss-8652
[ "8643" ]
3cf48bf174fe7347f848d3aa16598e7a375639fe
diff --git a/src/lib/evaluateTailwindFunctions.js b/src/lib/evaluateTailwindFunctions.js --- a/src/lib/evaluateTailwindFunctions.js +++ b/src/lib/evaluateTailwindFunctions.js @@ -183,9 +183,15 @@ export default function ({ tailwindConfig: config }) { throw node.error(error) } - if (alpha !== undefined) { - value = parseColorFormat(value) - value = withAlphaValue(value, alpha, value) + let maybeColor = parseColorFormat(value) + let isColorFunction = maybeColor !== undefined && typeof maybeColor === 'function' + + if (alpha !== undefined || isColorFunction) { + if (alpha === undefined) { + alpha = 1.0 + } + + value = withAlphaValue(maybeColor, alpha, maybeColor) } return value
diff --git a/tests/evaluateTailwindFunctions.test.js b/tests/evaluateTailwindFunctions.test.js --- a/tests/evaluateTailwindFunctions.test.js +++ b/tests/evaluateTailwindFunctions.test.js @@ -1025,6 +1025,36 @@ test('Theme function can extract alpha values for colors (8)', () => { }) }) +test('Theme functions replace the alpha value placeholder even with no alpha provided', () => { + let input = css` + .foo { + background: theme(colors.blue.400); + color: theme(colors.blue.500); + } + ` + + let output = css` + .foo { + background: rgb(0 0 255 / 1); + color: rgb(var(--foo) / 1); + } + ` + + return runFull(input, { + theme: { + colors: { + blue: { + 400: 'rgb(0 0 255 / <alpha-value>)', + 500: 'rgb(var(--foo) / <alpha-value>)', + }, + }, + }, + }).then((result) => { + expect(result.css).toMatchCss(output) + expect(result.warnings().length).toBe(0) + }) +}) + test('Theme functions can reference values with slashes in brackets', () => { let input = css` .foo1 {
theme() with css variable colors doesn't work in .css files <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.1.3 **What build tool (or framework if it abstracts the build tool) are you using?** postcss 8.4.14 **What version of Node.js are you using?** v16.13.1 **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/eoS0xJO1cm **Describe your issue** If you use css variable for colors, then `theme` doesn't work in `.css` files: ``` module.exports = { theme: { colors: { blue: 'rgb(var(--blue) / <alpha-value>)', }, }, plugins: [], } ``` ``` @tailwind base; @tailwind components; @tailwind utilities; :root { --blue: 0 0 255; } .custom-class { color: theme("colors.blue"); } ``` Generated css: ``` .custom-class { color: rgb(var(--blue) / <alpha-value>); } ```
"2022-06-15T18:57:16Z"
3.1
[]
[ "tests/evaluateTailwindFunctions.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/eoS0xJO1cm" ]
tailwindlabs/tailwindcss
8,687
tailwindlabs__tailwindcss-8687
[ "8660" ]
77c248cabb38d085df9ce9ca32e4f865f07bcd27
diff --git a/src/lib/defaultExtractor.js b/src/lib/defaultExtractor.js --- a/src/lib/defaultExtractor.js +++ b/src/lib/defaultExtractor.js @@ -64,31 +64,41 @@ function* buildRegExps(context) { ]), ]) - yield regex.pattern([ - // Variants - '((?=((', - regex.any( - [ - regex.pattern([/([^\s"'`\[\\]+-)?\[[^\s"'`]+\]/, separator]), - regex.pattern([/[^\s"'`\[\\]+/, separator]), - ], - true - ), - ')+))\\2)?', - - // Important (optional) - /!?/, - - variantGroupingEnabled - ? regex.any([ - // Or any of those things but grouped separated by commas - regex.pattern([/\(/, utility, regex.zeroOrMore([/,/, utility]), /\)/]), - - // Arbitrary properties, constrained utilities, arbitrary values, etc… - utility, - ]) - : utility, - ]) + let variantPatterns = [ + // Without quotes + regex.any([ + regex.pattern([/([^\s"'`\[\\]+-)?\[[^\s"'`]+\]/, separator]), + regex.pattern([/[^\s"'`\[\\]+/, separator]), + ]), + + // With quotes allowed + regex.any([ + regex.pattern([/([^\s"'`\[\\]+-)?\[[^\s`]+\]/, separator]), + regex.pattern([/[^\s`\[\\]+/, separator]), + ]), + ] + + for (const variantPattern of variantPatterns) { + yield regex.pattern([ + // Variants + '((?=((', + variantPattern, + ')+))\\2)?', + + // Important (optional) + /!?/, + + variantGroupingEnabled + ? regex.any([ + // Or any of those things but grouped separated by commas + regex.pattern([/\(/, utility, regex.zeroOrMore([/,/, utility]), /\)/]), + + // Arbitrary properties, constrained utilities, arbitrary values, etc… + utility, + ]) + : utility, + ]) + } // 5. Inner matches yield /[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g
diff --git a/tests/arbitrary-variants.test.js b/tests/arbitrary-variants.test.js --- a/tests/arbitrary-variants.test.js +++ b/tests/arbitrary-variants.test.js @@ -493,3 +493,37 @@ test('keeps escaped underscores in arbitrary variants mixed with normal variants `) }) }) + +test('allows attribute variants with quotes', () => { + let config = { + content: [ + { + raw: ` + <div class="[&[data-test='2']]:underline"></div> + <div class='[&[data-test="2"]]:underline'></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = ` + @tailwind base; + @tailwind components; + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + ${defaults} + + .\[\&\[data-test\=\'2\'\]\]\:underline[data-test="2"] { + text-decoration-line: underline; + } + + .\[\&\[data-test\=\"2\"\]\]\:underline[data-test='2'] { + text-decoration-line: underline; + } + `) + }) +})
no css output for inline classes which specify an attribute value in an arbitrary variant <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** 3.1.3 **What build tool (or framework if it abstracts the build tool) are you using?** https://play.tailwindcss.com **What version of Node.js are you using?** <https://play.tailwindcss.com>'s **What browser are you using?** Chrome 102.0.5005.115 **What operating system are you using?** macOS 12.4 **Reproduction URL** https://play.tailwindcss.com/zYyWNdDUB4 **Describe your issue** Arbitrary variants don't support specifying attribute values. Using the form `[&[my-attribute]]:` generates the expected CSS. Adding a value β€”`[&[my-attribute='val']]:` or `[&[my-attribute="val"]]:`β€” results in no CSS being generated for that class.
"2022-06-20T13:46:39Z"
3.1
[]
[ "tests/arbitrary-variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com>'s", "https://play.tailwindcss.com", "https://play.tailwindcss.com/zYyWNdDUB4" ]
tailwindlabs/tailwindcss
8,688
tailwindlabs__tailwindcss-8688
[ "8661" ]
c5e7857362148aaadfa294f51da7d343c87e1199
diff --git a/src/util/dataTypes.js b/src/util/dataTypes.js --- a/src/util/dataTypes.js +++ b/src/util/dataTypes.js @@ -49,9 +49,7 @@ export function normalize(value, isRoot = true) { ) }) - // Add spaces around some operators not inside calc() that do not follow an operator - // or '('. - return value.replace(/(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([\/])/g, '$1 $2 ') + return value } export function url(value) {
diff --git a/tests/arbitrary-values.test.css b/tests/arbitrary-values.test.css --- a/tests/arbitrary-values.test.css +++ b/tests/arbitrary-values.test.css @@ -107,7 +107,7 @@ margin-top: clamp(30px, 100px); } .aspect-\[16\/9\] { - aspect-ratio: 16 / 9; + aspect-ratio: 16/9; } .aspect-\[var\(--aspect\)\] { aspect-ratio: var(--aspect); @@ -232,77 +232,113 @@ } .translate-x-\[12\%\] { --tw-translate-x: 12%; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .translate-x-\[var\(--value\)\] { --tw-translate-x: var(--value); - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .translate-y-\[12\%\] { --tw-translate-y: 12%; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .translate-y-\[var\(--value\)\] { --tw-translate-y: var(--value); - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .rotate-\[23deg\] { --tw-rotate: 23deg; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .rotate-\[2\.3rad\] { --tw-rotate: 2.3rad; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .rotate-\[401grad\] { --tw-rotate: 401grad; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .rotate-\[1\.5turn\] { --tw-rotate: 1.5turn; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .skew-x-\[3px\] { --tw-skew-x: 3px; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .skew-x-\[var\(--value\)\] { --tw-skew-x: var(--value); - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .skew-y-\[3px\] { --tw-skew-y: 3px; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .skew-y-\[var\(--value\)\] { --tw-skew-y: var(--value); - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .scale-\[0\.7\] { --tw-scale-x: 0.7; --tw-scale-y: 0.7; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .scale-\[var\(--value\)\] { --tw-scale-x: var(--value); --tw-scale-y: var(--value); - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .scale-x-\[0\.7\] { --tw-scale-x: 0.7; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .scale-x-\[var\(--value\)\] { --tw-scale-x: var(--value); - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .scale-y-\[0\.7\] { --tw-scale-y: 0.7; - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .scale-y-\[var\(--value\)\] { --tw-scale-y: var(--value); - transform: translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); + transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) + skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) + scaleY(var(--tw-scale-y)); } .animate-\[pong_1s_cubic-bezier\(0\2c 0\2c 0\.2\2c 1\)_infinite\] { animation: pong 1s cubic-bezier(0, 0, 0.2, 1) infinite; @@ -317,7 +353,7 @@ cursor: url(hand.cur) 2 2, pointer; } .cursor-\[url\(\'\.\/path_to_hand\.cur\'\)_2_2\2c pointer\] { - cursor: url("./path_to_hand.cur") 2 2, pointer; + cursor: url('./path_to_hand.cur') 2 2, pointer; } .cursor-\[var\(--value\)\] { cursor: var(--value); @@ -665,8 +701,7 @@ } .via-\[var\(--color\)\] { --tw-gradient-to: rgb(255 255 255 / 0); - --tw-gradient-stops: var(--tw-gradient-from), var(--color), - var(--tw-gradient-to); + --tw-gradient-stops: var(--tw-gradient-from), var(--color), var(--tw-gradient-to); } .to-\[\#da5b66\] { --tw-gradient-to: #da5b66; @@ -946,75 +981,102 @@ } .blur-\[15px\] { --tw-blur: blur(15px); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .brightness-\[300\%\] { --tw-brightness: brightness(300%); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .contrast-\[2\.4\] { --tw-contrast: contrast(2.4); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .drop-shadow-\[0px_1px_2px_black\] { --tw-drop-shadow: drop-shadow(0px 1px 2px black); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .grayscale-\[0\.55\] { --tw-grayscale: grayscale(0.55); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .hue-rotate-\[0\.8turn\] { --tw-hue-rotate: hue-rotate(0.8turn); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .invert-\[0\.75\] { --tw-invert: invert(0.75); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .saturate-\[180\%\] { --tw-saturate: saturate(180%); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .sepia-\[0\.2\] { --tw-sepia: sepia(0.2); - filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); + filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) + var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow); } .backdrop-blur-\[11px\] { --tw-backdrop-blur: blur(11px); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-brightness-\[1\.23\] { --tw-backdrop-brightness: brightness(1.23); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-contrast-\[0\.87\] { --tw-backdrop-contrast: contrast(0.87); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-grayscale-\[0\.42\] { --tw-backdrop-grayscale: grayscale(0.42); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-hue-rotate-\[1\.57rad\] { --tw-backdrop-hue-rotate: hue-rotate(1.57rad); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-invert-\[0\.66\] { --tw-backdrop-invert: invert(0.66); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-opacity-\[22\%\] { --tw-backdrop-opacity: opacity(22%); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-saturate-\[144\%\] { --tw-backdrop-saturate: saturate(144%); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .backdrop-sepia-\[0\.38\] { --tw-backdrop-sepia: sepia(0.38); - backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); + backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) + var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) + var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia); } .transition-\[opacity\2c width\] { transition-property: opacity, width; diff --git a/tests/normalize-data-types.test.js b/tests/normalize-data-types.test.js --- a/tests/normalize-data-types.test.js +++ b/tests/normalize-data-types.test.js @@ -3,7 +3,8 @@ import { normalize } from '../src/util/dataTypes' let table = [ ['foo', 'foo'], ['foo-bar', 'foo-bar'], - ['16/9', '16 / 9'], + ['16/9', '16/9'], + ['16_/_9', '16 / 9'], // '_'s are converted to spaces except when escaped ['foo_bar', 'foo bar'], @@ -16,6 +17,10 @@ let table = [ 'url("https://example.com/abc+def/some-path/2022-01-01-abc/some_underscoered_path")', ], + // file-path-like-things without quotes are preserved as-is + ['/foo/bar/baz.png', '/foo/bar/baz.png'], + ['/foo/bar-2/baz.png', '/foo/bar-2/baz.png'], + // var(…) is preserved as is ['var(--foo)', 'var(--foo)'], ['var(--headings-h1-size)', 'var(--headings-h1-size)'], @@ -37,7 +42,8 @@ let table = [ ['var(--width, calc(100%+1rem))', 'var(--width, calc(100% + 1rem))'], // Misc - ['color(0_0_0/1.0)', 'color(0 0 0 / 1.0)'], + ['color(0_0_0/1.0)', 'color(0 0 0/1.0)'], + ['color(0_0_0_/_1.0)', 'color(0 0 0 / 1.0)'], ] it.each(table)('normalize data: %s', (input, output) => {
Automated space adding to look-like-mathematic-operators leads to multiple errors The function "normalize" with dataTypes.js leads to errors when using with some plugins like plaiceholder within 11ty for example. https://github.com/tailwindlabs/tailwindcss/blob/master/src/util/dataTypes.js Line 54 ![grafik](https://user-images.githubusercontent.com/49027330/174238693-0513b010-8da8-42d8-90b6-04de2ee2445a.png) The marked line adds spaces around look-like-mathematic-operators. We're using plaiceholder to get blurred preview images and got filePaths like "3-questions-to" or "TEXT-2/TBC" we got a the file path "3 - questions-to" or "TEXT-2 / TBC". And so this isn't a valid file path. And so this is useless for us. And there is no workaround. I wasted 8+ hours trying to fix this garbage which seems to be useless to me and is only helpful for a better look in the rendered css. But when I fix this, I got another errors with plaiceholder and fs... Is there any case we need this or is it only for a better look?
I tested this again. While doing a mathematic calculation you need the space before and after the operator. But without a css math function like calc, min, max, clamp for example the calculation won't work So this is useless or am I completely wrong If I got a "go" by any main developer I'd change or remove this line myself so that it returns the original value and open a pull request First of all I understand that it's frustrating when you run into a bug, but opening an issue that ignores the issue template, doesn't include a reproduction, complains about how we wasted your time, and goes on to talk about code in the project being "garbage" isn't the sort of behavior I'm personally willing to put up with. This is a free, MIT-licensed, open source project which means there _is_ a workaround β€” you simply fork the code and change it to do what you want. When you open an issue asking for a bug to be fixed, you're asking for a favor, and no one is obligated to fix it, as a consumer of open source you have to be okay with that. That said, I looked into this briefly and it looks like it was introduced in this PR: https://github.com/tailwindlabs/tailwindcss/pull/8091 The idea was to fix some other bug while preserving the existing behavior of adding spaces in situations like `aspect-[16/9]`. It does look like the spaces aren't actually needed by the browser though so it probably is safe to remove. Before we do that, can you provide a reproduction of the problem? I'm guessing it's in situations like `bg-[url('...')]` or something where there is a path in an arbitrary value? We have code in the framework that's intended to bypass these types of normalizations in URLs already so I want to make sure I understand why you're hitting that part of the code before we just throw something out. @adamwathan first I have to be sorry for using such a rude language. Usually this is not my style and I think I was too emotional this morning while writing this issue 2nd: Next time I'll use the issue template to help you reading this issue easier. Thank you for your detailed explanation and the given pull request. Yes, this could be case for this usage. I'll give you a short explanation of my problem. We're using 11ty for creating a full static blog, tailwindcss for the layout and plaiceholder for creating blurred images as placeholder till the original pictures are rendered/loaded completely As 11ty isn't currently able to work with async function, we're trying to use plaiceholder with tailwind as described on this page: https://plaiceholder.co/docs/plugins/tailwind So we got class names like "plaiceholder-[/3-questions-to/file.png]" or "plaiceholder-[/filepath-2/filename.png]" The described problem converts this paths to "/3 - questions-to/file.png" or "/filepath-2 / filename.png". So the files cannot be found. If I try to escape this with backslashes, so that I got "/3\-questions-to/file.png" for example, but then I got error from fs that this isn't a legal path (this message is correct) Then I tried working with "url(file://)", but I got an error with plaiceholder again that this path doesn't start with a leading slash what is required by plaiceholder. So I turned into a loop of trouble.. The next screenshot is from the plaiceholder node_modules ![grafik](https://user-images.githubusercontent.com/49027330/174301538-6ee901ea-d56e-4cc9-b35e-9a35c9a8ba2d.png) If we could talk about how to fix it, I'd try to support and writing this myself an putting it into the main code via a pr Hey! Really need an actual reproduction here I think, this would be a lot easier to troubleshoot if you would provide an actual GitHub repository I can clone that demonstrates the problem, and is why we require reproductions as part of the issue template. Trying to set up a reproduction for this myself and it's proving painful because this plugin doesn't work with Tailwind CSS v3, only v2 with JIT mode enabled. I've got it basically running and I can't reproduce the issue myself, the CSS is generated with no spaces added: <img width="1168" alt="image" src="https://user-images.githubusercontent.com/4323180/174307399-a363feb0-f87c-4810-b4e4-45e936a58fec.png"> I'm still not sure what the issue is really though since you haven't provided a reproduction, or explicitly stated what you expect the output to be. Here's my reproduction: https://github.com/adamwathan/tailwind-repro-8661 Have to use `npm i --force` to install it because the Plaiceholder plugin has a peer dependency on Tailwind CSS v2 which is no longer developed, then run `npm run build` to generate the CSS. If you can provide an actual reproduction and a very clear description of the expected output as compared to the output you're seeing it will be easier to help πŸ‘πŸ» @adamwathan perfect, thanksπŸ˜€ As I cannot send you link to our repo directly cause this is hosted on our in-House gitlab server, I'll try to rebuild a testing case here on GitHub this weekend. I'll then provide the link to it as a comment when I finished it @adamwathan I created the test repository as I proposed before. https://github.com/DanielKraemer/11ty-tailwind-plaiceholder-filepath-spaces-error When running `npm run start` you shold get an error like this: ![grafik](https://user-images.githubusercontent.com/49027330/174477424-56c5efae-2046-4ea0-816d-54ed715e0c11.png) If you got some questions don't hesitate contacting me Minimal reproduction: https://play.tailwindcss.com/IAwqejTC8S?file=config
"2022-06-20T14:42:08Z"
3.1
[]
[ "tests/normalize-data-types.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
8,772
tailwindlabs__tailwindcss-8772
[ "8702" ]
c8c4852b87f6cb9a966eba62698b74efab0abc51
diff --git a/src/lib/defaultExtractor.js b/src/lib/defaultExtractor.js --- a/src/lib/defaultExtractor.js +++ b/src/lib/defaultExtractor.js @@ -1,4 +1,4 @@ -import { flagEnabled } from '../featureFlags.js' +import { flagEnabled } from '../featureFlags' import * as regex from './regex' export function defaultExtractor(context) { @@ -22,6 +22,10 @@ export function defaultExtractor(context) { function* buildRegExps(context) { let separator = context.tailwindConfig.separator let variantGroupingEnabled = flagEnabled(context.tailwindConfig, 'variantGrouping') + let prefix = + context.tailwindConfig.prefix !== '' + ? regex.optional(regex.pattern([/-?/, regex.escape(context.tailwindConfig.prefix)])) + : '' let utility = regex.any([ // Arbitrary properties @@ -88,6 +92,8 @@ function* buildRegExps(context) { // Important (optional) /!?/, + prefix, + variantGroupingEnabled ? regex.any([ // Or any of those things but grouped separated by commas
diff --git a/tests/prefix.test.js b/tests/prefix.test.js --- a/tests/prefix.test.js +++ b/tests/prefix.test.js @@ -400,3 +400,120 @@ it('supports prefixed utilities using arbitrary values', async () => { } `) }) + +it('supports non-word prefixes (1)', async () => { + let config = { + prefix: '@', + content: [ + { + raw: html` + <div class="@underline"></div> + <div class="@bg-black"></div> + <div class="@[color:red]"></div> + <div class="hover:before:@content-['Hovering']"></div> + <div class="my-utility"></div> + <div class="foo"></div> + + <!-- these won't be detected --> + <div class="overline"></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + .my-utility { + color: orange; + } + } + .foo { + @apply @text-white; + @apply [background-color:red]; + } + ` + + const result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .\@bg-black { + --tw-bg-opacity: 1; + background-color: rgb(0 0 0 / var(--tw-bg-opacity)); + } + .\@underline { + text-decoration-line: underline; + } + .my-utility { + color: orange; + } + .foo { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity)); + background-color: red; + } + .hover\:before\:\@content-\[\'Hovering\'\]:hover::before { + --tw-content: 'Hovering'; + content: var(--tw-content); + } + `) +}) + +it('supports non-word prefixes (2)', async () => { + let config = { + prefix: '@]$', + content: [ + { + raw: html` + <div class="@]$underline"></div> + <div class="@]$bg-black"></div> + <div class="@]$[color:red]"></div> + <div class="hover:before:@]$content-['Hovering']"></div> + <div class="my-utility"></div> + <div class="foo"></div> + + <!-- these won't be detected --> + <div class="overline"></div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + .my-utility { + color: orange; + } + } + .foo { + @apply @]$text-white; + @apply [background-color:red]; + } + ` + + const result = await run(input, config) + + // TODO: The class `.hover\:before\:\@\]\$content-\[\'Hovering\'\]:hover::before` is not generated + // This happens because of the parenthesis/brace/bracket clipping performed on candidates + + expect(result.css).toMatchFormattedCss(css` + .\@\]\$bg-black { + --tw-bg-opacity: 1; + background-color: rgb(0 0 0 / var(--tw-bg-opacity)); + } + .\@\]\$underline { + text-decoration-line: underline; + } + .my-utility { + color: orange; + } + .foo { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity)); + background-color: red; + } + `) +})
Arbitrary Values Not Supported for Special-Character Prefixes (e.g., `@`) in 3.1 ## What version of Tailwind CSS are you using? 3.1.4 ## What build tool (or framework if it abstracts the build tool) are you using? `[email protected]` ## What version of Node.js are you using? v16.14.0 ## What browser are you using? Chrome ## What operating system are you using? MacOS ## Reproduction URL https://play.tailwindcss.com/0B55HN10nd ## Describe your issue Unlike in `[email protected]`, arbitrary values no longer work as of v3.1.x if a special character (e.g., `@`) is used as a prefix. One can see that the regular class names work just fine, but not the arbitrary `content` styles. Related to #8601. (I actually just augmented their example for this use case.)
"2022-07-04T18:25:49Z"
3.1
[]
[ "tests/prefix.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/0B55HN10nd" ]
tailwindlabs/tailwindcss
8,773
tailwindlabs__tailwindcss-8773
[ "8626" ]
5191ec1c006dfd6ac911e53d30f12993fe4eb586
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -129,6 +129,7 @@ function applyVariant(variant, matches, context) { } let args + let isArbitraryVariant = false // Find partial arbitrary variants if (variant.endsWith(']') && !variant.startsWith('[')) { @@ -144,6 +145,8 @@ function applyVariant(variant, matches, context) { return [] } + isArbitraryVariant = true + let fn = parseVariant(selector) let sort = Array.from(context.variantOrder.values()).pop() << 1n @@ -300,6 +303,7 @@ function applyVariant(variant, matches, context) { ...meta, sort: variantSort | meta.sort, collectedFormats: (meta.collectedFormats ?? []).concat(collectedFormats), + isArbitraryVariant, }, clone.nodes[0], ] @@ -627,6 +631,7 @@ function* resolveMatches(candidate, context, original = candidate) { base: candidate .split(new RegExp(`\\${context?.tailwindConfig?.separator ?? ':'}(?![^[]*\\])`)) .pop(), + isArbitraryVariant: match[0].isArbitraryVariant, context, }) diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -35,6 +35,7 @@ export function finalizeSelector( selector, candidate, context, + isArbitraryVariant, // Split by the separator, but ignore the separator inside square brackets: // @@ -50,7 +51,8 @@ export function finalizeSelector( ) { let ast = selectorParser().astSync(selector) - if (context?.tailwindConfig?.prefix) { + // We explicitly DO NOT prefix classes in arbitrary variants + if (context?.tailwindConfig?.prefix && !isArbitraryVariant) { format = prefixSelector(context.tailwindConfig.prefix, format) }
diff --git a/tests/arbitrary-variants.test.js b/tests/arbitrary-variants.test.js --- a/tests/arbitrary-variants.test.js +++ b/tests/arbitrary-variants.test.js @@ -527,3 +527,42 @@ test('allows attribute variants with quotes', () => { `) }) }) + +test('classes in arbitrary variants should not be prefixed', () => { + let config = { + prefix: 'tw-', + content: [ + { + raw: ` + <div class="[.foo_&]:tw-text-red-400">should not be red</div> + <div class="foo"> + <div class="[.foo_&]:tw-text-red-400">should be red</div> + </div> + <div class="[&_.foo]:tw-text-red-400"> + <div>should not be red</div> + <div class="foo">should be red</div> + </div> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = ` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .foo .\[\.foo_\&\]\:tw-text-red-400 { + --tw-text-opacity: 1; + color: rgb(248 113 113 / var(--tw-text-opacity)); + } + + .\[\&_\.foo\]\:tw-text-red-400 .foo { + --tw-text-opacity: 1; + color: rgb(248 113 113 / var(--tw-text-opacity)); + } + `) + }) +})
Classes inside arbitrary variants are incorrectly being prefixed Classes inside arbitrary variants are prefixed when they shouldn't be as they're not tailwind utilities. The utility `[.foo_&]:tw-text-red-400` incorrectly generates a selector referencing `.tw-foo` instead of `.foo` See: https://github.com/tailwindlabs/tailwindcss/pull/8299#issuecomment-1154053957 Reproduction: https://play.tailwindcss.com/GCMzAzdKNY
I put \ in front of '.foo_&' and it is some how giving selector .foo https://play.tailwindcss.com/LWujxXokrG @thecrypticace I built upon your example and created an example to test classes, IDs, and attributes. It appears IDs work as expected, but both classes and attributes experience bugs when using prefixes, and when not using prefixes, only the attributes examples break: * **With prefix:** https://play.tailwindcss.com/kKJt04VYW2 (classes and attributes break) * **Without prefix:** https://play.tailwindcss.com/PF2YRSjHnL (only attributes break)
"2022-07-04T18:43:56Z"
3.1
[]
[ "tests/arbitrary-variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/GCMzAzdKNY" ]
tailwindlabs/tailwindcss
8,831
tailwindlabs__tailwindcss-8831
[ "8824" ]
b4e637e2e096a9d6f2210efba9541f6fd4f28e56
diff --git a/src/lib/evaluateTailwindFunctions.js b/src/lib/evaluateTailwindFunctions.js --- a/src/lib/evaluateTailwindFunctions.js +++ b/src/lib/evaluateTailwindFunctions.js @@ -157,26 +157,52 @@ let nodeTypePropertyMap = { decl: 'value', } -export default function ({ tailwindConfig: config }) { - let functions = { - theme: (node, path, ...defaultValue) => { - // Strip quotes from beginning and end of string - // This allows the alpha value to be present inside of quotes - path = path.replace(/^['"]+|['"]+$/g, '') +/** + * @param {string} path + * @returns {Iterable<[path: string, alpha: string|undefined]>} + */ +function* toPaths(path) { + // Strip quotes from beginning and end of string + // This allows the alpha value to be present inside of quotes + path = path.replace(/^['"]+|['"]+$/g, '') - let matches = path.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/) - let alpha = undefined + let matches = path.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/) + let alpha = undefined - if (matches) { - path = matches[1] - alpha = matches[2] - } + yield [path, undefined] + + if (matches) { + path = matches[1] + alpha = matches[2] + + yield [path, alpha] + } +} - let { isValid, value, error } = validatePath( +/** + * + * @param {any} config + * @param {string} path + * @param {any} defaultValue + */ +function resolvePath(config, path, defaultValue) { + const results = Array.from(toPaths(path)).map(([path, alpha]) => { + return Object.assign(validatePath(config, path, defaultValue, { opacityValue: alpha }), { + resolvedPath: path, + alpha, + }) + }) + + return results.find((result) => result.isValid) ?? results[0] +} + +export default function ({ tailwindConfig: config }) { + let functions = { + theme: (node, path, ...defaultValue) => { + let { isValid, value, error, alpha } = resolvePath( config, path, - defaultValue.length ? defaultValue : undefined, - { opacityValue: alpha } + defaultValue.length ? defaultValue : undefined ) if (!isValid) {
diff --git a/tests/evaluateTailwindFunctions.test.js b/tests/evaluateTailwindFunctions.test.js --- a/tests/evaluateTailwindFunctions.test.js +++ b/tests/evaluateTailwindFunctions.test.js @@ -1135,3 +1135,51 @@ test('Theme functions with alpha with quotes value around color only', () => { expect(result.warnings().length).toBe(0) }) }) + +it('can find values with slashes in the theme key while still allowing for alpha values ', () => { + let input = css` + .foo00 { + color: theme(colors.foo-5); + } + .foo01 { + color: theme(colors.foo-5/10); + } + .foo02 { + color: theme(colors.foo-5/10/25); + } + .foo03 { + color: theme(colors.foo-5 / 10); + } + .foo04 { + color: theme(colors.foo-5/10 / 25); + } + ` + + return runFull(input, { + theme: { + colors: { + 'foo-5': '#050000', + 'foo-5/10': '#051000', + 'foo-5/10/25': '#051025', + }, + }, + }).then((result) => { + expect(result.css).toMatchCss(css` + .foo00 { + color: #050000; + } + .foo01 { + color: #051000; + } + .foo02 { + color: #051025; + } + .foo03 { + color: rgb(5 0 0 / 10); + } + .foo04 { + color: rgb(5 16 0 / 25); + } + `) + }) +})
Tailwind error when using theme() in css Adding following styles to css leads to an error: ``` .test { --shadow: theme("boxShadow.glow-8/28/20"); box-shadow: var(---shadow); } ``` error: ``` 'boxShadow.glow-8/28' does not exist in your theme config. Did you mean 'boxShadow.glow-8/28/20'? ``` **What version of Tailwind CSS are you using?** v3.1.5 **What build tool (or framework if it abstracts the build tool) are you using?** NextJS 12.1.0 **What version of Node.js are you using?** v16.2.0 **What browser are you using?** N/A **What operating system are you using?** Windows **Reproduction URL** https://play.tailwindcss.com/xlki3pMe9n?file=css **Describe your issue** Adding styles that contain more than one forward slash `/` returns an error when it's used via `theme()` function, for example: `theme("boxShadow.glow-6/30/40")`
"2022-07-11T14:41:24Z"
3.1
[]
[ "tests/evaluateTailwindFunctions.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/xlki3pMe9n?file=css" ]
tailwindlabs/tailwindcss
8,971
tailwindlabs__tailwindcss-8971
[ "8966" ]
da268f63e63d2f166950ec77fa76cc088f8d83b4
diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -471,7 +471,11 @@ function splitWithSeparator(input, separator) { function* recordCandidates(matches, classCandidate) { for (const match of matches) { - match[1].raws.tailwind = { ...match[1].raws.tailwind, classCandidate } + match[1].raws.tailwind = { + ...match[1].raws.tailwind, + classCandidate, + preserveSource: match[0].options?.preserveSource ?? false, + } yield match } diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -289,6 +289,7 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs }, addComponents(components, options) { let defaultOptions = { + preserveSource: false, respectPrefix: true, respectImportant: false, } @@ -311,6 +312,7 @@ function buildPluginApi(tailwindConfig, context, { variantList, variantMap, offs }, addUtilities(utilities, options) { let defaultOptions = { + preserveSource: false, respectPrefix: true, respectImportant: true, } @@ -579,14 +581,14 @@ function collectLayerPlugins(root) { } else if (layerRule.params === 'components') { for (let node of layerRule.nodes) { layerPlugins.push(function ({ addComponents }) { - addComponents(node, { respectPrefix: false }) + addComponents(node, { respectPrefix: false, preserveSource: true }) }) } layerRule.remove() } else if (layerRule.params === 'utilities') { for (let node of layerRule.nodes) { layerPlugins.push(function ({ addUtilities }) { - addUtilities(node, { respectPrefix: false }) + addUtilities(node, { respectPrefix: false, preserveSource: true }) }) } layerRule.remove() diff --git a/src/util/cloneNodes.js b/src/util/cloneNodes.js --- a/src/util/cloneNodes.js +++ b/src/util/cloneNodes.js @@ -2,7 +2,11 @@ export default function cloneNodes(nodes, source = undefined, raws = undefined) return nodes.map((node) => { let cloned = node.clone() - if (source !== undefined) { + // We always want override the source map + // except when explicitly told not to + let shouldOverwriteSource = node.raws.tailwind?.preserveSource !== true || !cloned.source + + if (source !== undefined && shouldOverwriteSource) { cloned.source = source if ('walk' in cloned) {
diff --git a/tests/__snapshots__/source-maps.test.js.snap b/tests/__snapshots__/source-maps.test.js.snap --- a/tests/__snapshots__/source-maps.test.js.snap +++ b/tests/__snapshots__/source-maps.test.js.snap @@ -347,3 +347,17 @@ Array [ "2:18 -> 440:0", ] `; + +exports[`source maps for layer rules are not rewritten to point to @tailwind directives 1`] = ` +Array [ + "2:6 -> 1:0", + "2:6 -> 2:10", + "2:25 -> 3:0", + "3:8 -> 4:8", + "4:10-31 -> 5:10-31", + "5:8 -> 6:8", + "3:8 -> 7:8", + "4:10-31 -> 8:10-31", + "5:8 -> 9:8", +] +`; diff --git a/tests/source-maps.test.js b/tests/source-maps.test.js --- a/tests/source-maps.test.js +++ b/tests/source-maps.test.js @@ -1,4 +1,5 @@ -import { runWithSourceMaps as run, html, css } from './util/run' +import postcss from 'postcss' +import { runWithSourceMaps as run, html, css, map } from './util/run' import { parseSourceMaps } from './util/source-maps' it('apply generates source maps', async () => { @@ -39,7 +40,6 @@ it('apply generates source maps', async () => { expect(sources).not.toContain('<no source>') expect(sources.length).toBe(1) - // It would make the tests nicer to read and write expect(annotations).toMatchSnapshot() }) @@ -60,7 +60,6 @@ it('preflight + base have source maps', async () => { expect(sources).not.toContain('<no source>') expect(sources.length).toBe(1) - // It would make the tests nicer to read and write expect(annotations).toMatchSnapshot() }) @@ -81,7 +80,6 @@ it('utilities have source maps', async () => { expect(sources).not.toContain('<no source>') expect(sources.length).toBe(1) - // It would make the tests nicer to read and write expect(annotations).toStrictEqual(['2:4 -> 1:0', '2:4-23 -> 2:4-24', '2:4 -> 3:4', '2:23 -> 4:0']) }) @@ -102,6 +100,50 @@ it('components have source maps', async () => { expect(sources).not.toContain('<no source>') expect(sources.length).toBe(1) - // It would make the tests nicer to read and write + expect(annotations).toMatchSnapshot() +}) + +it('source maps for layer rules are not rewritten to point to @tailwind directives', async () => { + let config = { + content: [{ raw: `font-normal foo hover:foo` }], + } + + let utilitiesFile = postcss.parse( + css` + @tailwind utilities; + `, + { from: 'components.css', map: { prev: map } } + ) + + let mainCssFile = postcss.parse( + css` + @layer utilities { + .foo { + background-color: red; + } + } + `, + { from: 'input.css', map: { prev: map } } + ) + + // Just pretend that there's an @import in `mainCssFile` that imports the nodes from `utilitiesFile` + let input = postcss.root({ + nodes: [...utilitiesFile.nodes, ...mainCssFile.nodes], + source: mainCssFile.source, + }) + + let result = await run(input, config) + + let { sources, annotations } = parseSourceMaps(result) + + // All CSS generated by Tailwind CSS should be annotated with source maps + // And always be able to point to the original source file + expect(sources).not.toContain('<no source>') + + // And we should see that the source map for the layer rule is not rewritten + // to point to the @tailwind directive but instead points to the original + expect(sources.length).toBe(2) + expect(sources).toEqual(['components.css', 'input.css']) + expect(annotations).toMatchSnapshot() }) diff --git a/tests/util/run.js b/tests/util/run.js --- a/tests/util/run.js +++ b/tests/util/run.js @@ -5,7 +5,7 @@ import tailwind from '../../src' export * from './strings' export * from './defaults' -let map = JSON.stringify({ +export let map = JSON.stringify({ version: 3, file: null, sources: [],
Incorrect work of url() in css file when using vite.js <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** "tailwindcss": "3.1.6" **What build tool (or framework if it abstracts the build tool) are you using?** "vite": "3.0.3" **What version of Node.js are you using?** v16.16.0 **What browser are you using?** Any **What operating system are you using?** Windows (WSL2) **Reproduction URL** https://codesandbox.io/s/vite-tailwind-bug-jm7w9h **Describe your issue** If vite.config.js entry point is a style file, for example, for a classic backend, then the url() in css files are not processed. But if I comment out the tilewindcss plugin in the postcss.config.js file, then everything works fine. Result with tailwindcss: (not processed) ``` .test{background-image:url(img.svg)} ``` Result without tailwindcss: (processed) ``` .test{background-image:url(/img-8dac5379.svg)} ```
"2022-07-27T15:45:05Z"
3.1
[]
[ "tests/source-maps.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
9,008
tailwindlabs__tailwindcss-9008
[ "8991" ]
0b5bfc8065e928caa7cf11a7bac37fda10411b6f
diff --git a/src/util/resolveConfig.js b/src/util/resolveConfig.js --- a/src/util/resolveConfig.js +++ b/src/util/resolveConfig.js @@ -180,7 +180,7 @@ function resolveFunctionKeys(object) { val = val[path[index++]] let shouldResolveAsFn = - isFunction(val) && (path.alpha === undefined || index < path.length - 1) + isFunction(val) && (path.alpha === undefined || index <= path.length - 1) val = shouldResolveAsFn ? val(resolvePath, configUtils) : val }
diff --git a/tests/opacity.test.js b/tests/opacity.test.js --- a/tests/opacity.test.js +++ b/tests/opacity.test.js @@ -761,3 +761,70 @@ it('Theme functions can reference values with slashes in brackets', () => { `) }) }) + +it('works with opacity values defined as a placeholder or a function in when colors is a function', () => { + let config = { + content: [ + { + raw: html` + <div + class="bg-foo10 bg-foo20 bg-foo30 bg-foo40 bg-foo11 bg-foo21 bg-foo31 bg-foo41" + ></div> + `, + }, + ], + theme: { + colors: () => ({ + foobar1: ({ opacityValue }) => `rgb(255 100 0 / ${opacityValue ?? '100%'})`, + foobar2: `rgb(255 100 0 / <alpha-value>)`, + foobar3: { + 100: ({ opacityValue }) => `rgb(255 100 0 / ${opacityValue ?? '100%'})`, + 200: `rgb(255 100 0 / <alpha-value>)`, + }, + }), + extend: { + backgroundColor: ({ theme }) => ({ + foo10: theme('colors.foobar1'), + foo20: theme('colors.foobar2'), + foo30: theme('colors.foobar3.100'), + foo40: theme('colors.foobar3.200'), + foo11: theme('colors.foobar1 / 50%'), + foo21: theme('colors.foobar2 / 50%'), + foo31: theme('colors.foobar3.100 / 50%'), + foo41: theme('colors.foobar3.200 / 50%'), + }), + }, + }, + } + + return run('@tailwind utilities', config).then((result) => { + expect(result.css).toMatchCss(css` + .bg-foo10 { + background-color: rgb(255 100 0 / 100%); + } + .bg-foo20 { + --tw-bg-opacity: 1; + background-color: rgb(255 100 0 / var(--tw-bg-opacity)); + } + .bg-foo30 { + background-color: rgb(255 100 0 / 100%); + } + .bg-foo40 { + --tw-bg-opacity: 1; + background-color: rgb(255 100 0 / var(--tw-bg-opacity)); + } + .bg-foo11 { + background-color: rgb(255 100 0 / 50%); + } + .bg-foo21 { + background-color: rgb(255 100 0 / 50%); + } + .bg-foo31 { + background-color: rgb(255 100 0 / 50%); + } + .bg-foo41 { + background-color: rgb(255 100 0 / 50%); + } + `) + }) +})
Custom color opacity in theme function ### Discussed in https://github.com/tailwindlabs/tailwindcss/discussions/8987 <div type='discussions-op-text'> <sup>Originally posted by **dawaltconley** July 29, 2022</sup> Hi, I'm trying to reference custom colors with variable opacity elsewhere in my theme config and cannot figure out how. From the little bit of testing I've done it could be a bug or missing feature, but I wanted to ask here in case I'm missing something obvious. Here are the relevant parts of my config: ```js module.exports = { theme: { extend: { colors: { foobar: ({ opacityValue }) => `rgb(255 100 0 / ${opacityValue})`, }, typography: ({ theme }) => ({ theme: { css: { '--tw-prose-headings': theme('colors.red[500] / 50%'), // this works '--tw-prose-bullets': theme('colors.foobar / 80%'), // this does not }, }, }), }, }, } ``` I've also tried using the new `<alpha-value>` syntax. The `text-foobar/80` etc classes _do_ work in my template files, but `opacityValue` seems to be `undefined` when referencing it in the config. i.e. the above outputs `rgb(255 100 0 / undefined)` for `--tw-prose-bullets`.</div> ### My analysis of this issue The code that resolves alpha values in `theme()` function is: https://github.com/tailwindlabs/tailwindcss/blob/14542d94f7078dc8d065ddcc6d403cd0a467f1be/src/util/resolveConfig.js#L176-L186 This code expects there to be more that 2 components in the path; let's see why. #### 3-part color ##### Initial state ```js index = 0; val = { // … colors: someResolvingFunction, // … }; path = ['colors', 'red', '500']; // also path.alpha = '50%'; ``` ##### While loop 1 ```js val = val[path[index++]]` // index = 1; val = someResolvingFunction let shouldResolveAsFn = isFunction(val) && (path.alpha === undefined || index < path.length - 1) // shouldResolveAsFn = true, since index < path.length - 1 is true as index = 1, path.length - 1 = 2. val = shouldResolveAsFn ? val(resolvePath, configUtils) : val // val = { // …, // red: { // …, // 500: '#ef4444', // … // }, // … // } ``` ##### While loop 2 ```js val = val[path[index++]]` // index = 2; val = val['red'] = { …, 500: '#ef4444', … } let shouldResolveAsFn = isFunction(val) && (path.alpha === undefined || index < path.length - 1) // shouldResolveAsFn = false, since isFunction(val) = false val = shouldResolveAsFn ? val(resolvePath, configUtils) : val // val = { …, 500: '#ef4444', … } ``` ##### While loop 3 ```js val = val[path[index++]]` // index = 3; val = val['500'] = { …, 500: '#ef4444', … }['500'] = '#ef4444' let shouldResolveAsFn = isFunction(val) && (path.alpha === undefined || index < path.length - 1) // shouldResolveAsFn = false, since isFunction(val) = false val = shouldResolveAsFn ? val(resolvePath, configUtils) : val // val = '#ef4444' ``` While loop stops since the condition `index < path.length` now evaluates to `false` and our final `val` value is `#ef4444`, all good βœ”. #### 2-part color ##### Initial state ```js index = 0; val = { // … colors: someResolvingFunction, // … }; path = ['colors', 'foobar']; // also path.alpha = '80%'; ``` ##### While loop 1 ```js val = val[path[index++]]` // index = 1; val = someResolvingFunction let shouldResolveAsFn = isFunction(val) && (path.alpha === undefined || index < path.length - 1) // shouldResolveAsFn = false, since index < path.length - 1 is false as index = 1, path.length - 1 = 1. val = shouldResolveAsFn ? val(resolvePath, configUtils) : val // val = someResolvingFunction ``` ##### While loop 2 ```js val = val[path[index++]]` // index = 2; val = someResolvingFunction['foobar'] = undefined // val is now undefined so no value is printed. ``` While loop stops since the condition `val !== undefined` now evaluates to `false` and our final `val` value is `undefined`, not good ❌. ### Summary This is because in the first while loop of 2-part color, the `index < path.length - 1` condition stops `someResolvingFunction` from being evaluated as a function and instead, the function is passed through as-is.
"2022-08-02T15:05:09Z"
3.1
[]
[ "tests/opacity.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
9,027
tailwindlabs__tailwindcss-9027
[ "9023" ]
2bfd3e7423c71bb505c97949c57a7e3ef36530eb
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -499,6 +499,12 @@ function processApply(root, context, localCache) { }) } + // It could be that the node we were inserted was removed because the class didn't match + // If that was the *only* rule in the parent, then we have nothing add so we skip it + if (!root.nodes[0]) { + continue + } + // Insert it siblings.push([ // Ensure that when we are sorting, that we take the layer order into account
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -1548,3 +1548,39 @@ it('apply + user CSS + selector variants (like group) + important selector (2)', } `) }) + +it('can apply user utilities that start with a dash', async () => { + let config = { + content: [{ raw: html`<div class="foo-1 -foo-1 new-class"></div>` }], + plugins: [], + } + + let input = css` + @tailwind utilities; + @layer utilities { + .foo-1 { + margin: 10px; + } + .-foo-1 { + margin: -15px; + } + .new-class { + @apply -foo-1; + } + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .foo-1 { + margin: 10px; + } + .-foo-1 { + margin: -15px; + } + .new-class { + margin: -15px; + } + `) +})
When defining dash-prefixed utility classes in a @layer, using them in an @apply statement throws a build error <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** Tailwind v3.1.7 **What build tool (or framework if it abstracts the build tool) are you using?** Tailwindcss CLI tool **What version of Node.js are you using?** Node v16.6.2 **What browser are you using?** N/A, CLI issue **What operating system are you using?** macOS **Reproduction URL** Repo with basic demo code: https://github.com/lform/tailwind-dash-demo **Describe your issue** We're creating some utility classes in a `@layer utilities` layer that extend each other using `@apply` statements to create a simple header font-sizing system that utilizes modular scale. The classes work fine except if you try to use a dash-prefixed class thats been defined in the utilites layer in one of the `@apply` statements. There are workarounds but they would break the consistency of using the dash-prefix for negative values that tailwind employs uniformly. We're building out some re-usable components and want to utilize those font-sizing classes in them so this is a bit of a hindrence. We've temporarily changed the syntax to `h-ms--1` to work around this but its not ideal as it doesnt obey the consistency. The above repo has the full code demo but basically the following is the problem: ``` @layer utilities { .h-ms { /* Works fine */ @apply font-header leading-tight; } .h-ms-1 { /* Works fine */ @apply h-ms text-ms-1 font-bold; } .-h-ms-1 { /* Works fine, `-text-ms-1` is defined in the tailwind config */ @apply h-ms -text-ms-1 font-bold; } .new-class { /* This throws the below error */ @apply -h-ms-1 italic; } } ``` Which then throws the following error (the error goes away if you remove the offending dash-prefixed item in question from the apply statement): ``` TypeError: Cannot read property 'parent' of undefined at Root.normalize (/Users/bmf/sites/tailwind-dash-test/node_modules/postcss/lib/container.js:292:15) at Root.normalize (/Users/bmf/sites/tailwind-dash-test/node_modules/postcss/lib/root.js:25:23) at Root.insertAfter (/Users/bmf/sites/tailwind-dash-test/node_modules/postcss/lib/container.js:201:22) at Rule.after (/Users/bmf/sites/tailwind-dash-test/node_modules/postcss/lib/node.js:161:17) at processApply (/Users/bmf/sites/tailwind-dash-test/node_modules/tailwindcss/lib/lib/expandApplyAtRules.js:453:16) at /Users/bmf/sites/tailwind-dash-test/node_modules/tailwindcss/lib/lib/expandApplyAtRules.js:471:9 at /Users/bmf/sites/tailwind-dash-test/node_modules/tailwindcss/lib/processTailwindFeatures.js:55:50 at Object.Once (/Users/bmf/sites/tailwind-dash-test/node_modules/tailwindcss/lib/cli.js:682:27) at LazyResult.runOnRoot (/Users/bmf/sites/tailwind-dash-test/node_modules/postcss/lib/lazy-result.js:337:23) at LazyResult.runAsync (/Users/bmf/sites/tailwind-dash-test/node_modules/postcss/lib/lazy-result.js:393:26) ``` Is there another way to approach this that would work? Not sure if this is a bug, expected or the wrong way to create these utility classes. Open to suggestions if there's a more correct approach, was unable to find any help when searching this issue online.
"2022-08-04T18:19:30Z"
3.1
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
9,070
tailwindlabs__tailwindcss-9070
[ "9066" ]
21849031bd673de84f58a8fa3170162640e2ac2c
diff --git a/src/util/getAllConfigs.js b/src/util/getAllConfigs.js --- a/src/util/getAllConfigs.js +++ b/src/util/getAllConfigs.js @@ -11,9 +11,10 @@ export default function getAllConfigs(config) { // Add experimental configs here... respectDefaultRingColorOpacity: { theme: { - ringColor: { + ringColor: ({ theme }) => ({ DEFAULT: '#3b82f67f', - }, + ...theme('colors'), + }), }, }, }
diff --git a/tests/basic-usage.test.js b/tests/basic-usage.test.js --- a/tests/basic-usage.test.js +++ b/tests/basic-usage.test.js @@ -661,3 +661,31 @@ it('A bare ring-opacity utility is supported when using respectDefaultRingColorO `) }) }) + +it('Ring color utilities are generated when using respectDefaultRingColorOpacity', () => { + let config = { + future: { respectDefaultRingColorOpacity: true }, + content: [{ raw: html`<div class="ring ring-blue-500"></div>` }], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .ring { + --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) + var(--tw-ring-offset-color); + --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) + var(--tw-ring-color); + box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); + } + .ring-blue-500 { + --tw-ring-opacity: 1; + --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity)); + } + `) + }) +})
Not possible to set ring color with `future.respectDefaultRingColorOpacity` enabled <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.1.7 **What build tool (or framework if it abstracts the build tool) are you using?** n/a **What version of Node.js are you using?** n/a **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/N1ko1lZjzn?file=config **Describe your issue** When `future.respectDefaultRingColorOpacity` is set to `true` in Tailwind config, I can't set ring colors like `ring-gray-500` anymore. The respective class is not created by the Tailwind compiler. Related: https://github.com/tailwindlabs/tailwindcss/issues/9016#issuecomment-1210378693
"2022-08-10T14:28:51Z"
3.1
[]
[ "tests/basic-usage.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/N1ko1lZjzn?file=config" ]
tailwindlabs/tailwindcss
9,107
tailwindlabs__tailwindcss-9107
[ "9093" ]
b0018e20bf250a2e4df1f39f73e763662538e524
diff --git a/src/lib/expandApplyAtRules.js b/src/lib/expandApplyAtRules.js --- a/src/lib/expandApplyAtRules.js +++ b/src/lib/expandApplyAtRules.js @@ -34,13 +34,13 @@ function extractClasses(node) { return Object.assign(classes, { groups: normalizedGroups }) } -let selectorExtractor = parser((root) => root.nodes.map((node) => node.toString())) +let selectorExtractor = parser() /** * @param {string} ruleSelectors */ function extractSelectors(ruleSelectors) { - return selectorExtractor.transformSync(ruleSelectors) + return selectorExtractor.astSync(ruleSelectors) } function extractBaseCandidates(candidates, separator) { @@ -299,30 +299,61 @@ function processApply(root, context, localCache) { * What happens in this function is that we prepend a `.` and escape the candidate. * This will result in `.hover\:font-bold` * Which means that we can replace `.hover\:font-bold` with `.abc` in `.hover\:font-bold:hover` resulting in `.abc:hover` + * + * @param {string} selector + * @param {string} utilitySelectors + * @param {string} candidate */ - // TODO: Should we use postcss-selector-parser for this instead? function replaceSelector(selector, utilitySelectors, candidate) { - let needle = `.${escapeClassName(candidate)}` - let needles = [...new Set([needle, needle.replace(/\\2c /g, '\\,')])] + let selectorList = extractSelectors(selector) let utilitySelectorsList = extractSelectors(utilitySelectors) + let candidateList = extractSelectors(`.${escapeClassName(candidate)}`) + let candidateClass = candidateList.nodes[0].nodes[0] - return extractSelectors(selector) - .map((s) => { - let replaced = [] + selectorList.each((sel) => { + /** @type {Set<import('postcss-selector-parser').Selector>} */ + let replaced = new Set() - for (let utilitySelector of utilitySelectorsList) { - let replacedSelector = utilitySelector - for (const needle of needles) { - replacedSelector = replacedSelector.replace(needle, s) - } - if (replacedSelector === utilitySelector) { - continue + utilitySelectorsList.each((utilitySelector) => { + utilitySelector = utilitySelector.clone() + + utilitySelector.walkClasses((node) => { + if (node.value !== candidateClass.value) { + return } - replaced.push(replacedSelector) - } - return replaced.join(', ') + + // Since you can only `@apply` class names this is sufficient + // We want to replace the matched class name with the selector the user is using + // Ex: Replace `.text-blue-500` with `.foo.bar:is(.something-cool)` + node.replaceWith(...sel.nodes.map((node) => node.clone())) + + // Record that we did something and we want to use this new selector + replaced.add(utilitySelector) + }) }) - .join(', ') + + // Sort tag names before class names + // This happens when replacing `.bar` in `.foo.bar` with a tag like `section` + for (const sel of replaced) { + sel.sort((a, b) => { + if (a.type === 'tag' && b.type === 'class') { + return -1 + } else if (a.type === 'class' && b.type === 'tag') { + return 1 + } else if (a.type === 'class' && b.type === 'pseudo') { + return -1 + } else if (a.type === 'pseudo' && b.type === 'class') { + return 1 + } + + return sel.index(a) - sel.index(b) + }) + } + + sel.replaceWith(...replaced) + }) + + return selectorList.toString() } let perParentApplies = new Map()
diff --git a/tests/apply.test.js b/tests/apply.test.js --- a/tests/apply.test.js +++ b/tests/apply.test.js @@ -1584,3 +1584,105 @@ it('can apply user utilities that start with a dash', async () => { } `) }) + +it('can apply joined classes when using elements', async () => { + let config = { + content: [{ raw: html`<div class="foo-1 -foo-1 new-class"></div>` }], + plugins: [], + } + + let input = css` + .foo.bar { + color: red; + } + .bar.foo { + color: green; + } + header:nth-of-type(odd) { + @apply foo; + } + main { + @apply foo bar; + } + footer { + @apply bar; + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .foo.bar { + color: red; + } + .bar.foo { + color: green; + } + header.bar:nth-of-type(odd) { + color: red; + color: green; + } + main.bar { + color: red; + } + main.foo { + color: red; + } + main.bar { + color: green; + } + main.foo { + color: green; + } + footer.foo { + color: red; + color: green; + } + `) +}) + +it('can produce selectors that replace multiple instances of the same class', async () => { + let config = { + content: [{ raw: html`<div class="foo-1 -foo-1 new-class"></div>` }], + plugins: [], + } + + let input = css` + .foo + .foo { + color: blue; + } + .bar + .bar { + color: fuchsia; + } + header { + @apply foo; + } + main { + @apply foo bar; + } + footer { + @apply bar; + } + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .foo + .foo { + color: blue; + } + .bar + .bar { + color: fuchsia; + } + header + header { + color: blue; + } + main + main { + color: blue; + color: fuchsia; + } + footer + footer { + color: fuchsia; + } + `) +})
Sibling selectors of components don't work on classes applying them **What version of Tailwind CSS are you using?** For example: v3.1.8 **What build tool (or framework if it abstracts the build tool) are you using?** Tailwind Play **What browser are you using?** Chrome **What operating system are you using?** macOS **Reproduction URL** https://play.tailwindcss.com/Gd9jsdpkCi?file=css **Describe your issue** When applying custom components to selectors with a sibling operator, the output CSS does not apply to them properly. For example, with the following code ```css @layer components { .row.row-odd { @apply bg-green-400; } .row.row-even { @apply bg-red-400; } .row-odd + .row-even { @apply bg-blue-400; } .row-even + .row-odd { @apply bg-yellow-400; } } section:nth-of-type(odd) { @apply row row-odd; } section:nth-of-type(even) { @apply row row-even; } ``` ...should output something similar to: ```css section:nth-of-type(odd) + section:nth-of-type(even) { background: blue; } section:nth-of-type(even) + section:nth-of-type(odd) { background: yellow; } ``` ...and yet it only outputs: ```css section:nth-of-type(odd) + .row-even { background: blue; } .row-odd + .section:nth-of-type(even) { background: blue; } section:nth-of-type(even) + .row-odd { background: yellow; } .row-even + section:nth-of-type(odd) { background: yellow; } ``` It also seems that when declaring composite rules (multiple classes, such as `.row.row-odd`) this breaks during compilation when applying it to a tag instead of a class, resulting in rules such as `.rowsection` (with no separator, which makes no sense) as a result of the following code: ```css @layer components { .row.row-odd { @apply bg-green-400; } } section { @apply row-odd; } ``` Both behaviors are observable in the output of the Tailwind Play document I linked
"2022-08-15T15:51:54Z"
3.1
[]
[ "tests/apply.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/Gd9jsdpkCi?file=css" ]
tailwindlabs/tailwindcss
9,208
tailwindlabs__tailwindcss-9208
[ "9205" ]
da850424dcdf011acda795b52c87cbd28628c943
diff --git a/src/lib/expandTailwindAtRules.js b/src/lib/expandTailwindAtRules.js --- a/src/lib/expandTailwindAtRules.js +++ b/src/lib/expandTailwindAtRules.js @@ -177,16 +177,12 @@ export default function expandTailwindAtRules(context) { let classCacheCount = context.classCache.size env.DEBUG && console.time('Generate rules') - let rules = generateRules(candidates, context) + generateRules(candidates, context) env.DEBUG && console.timeEnd('Generate rules') // We only ever add to the classCache, so if it didn't grow, there is nothing new. env.DEBUG && console.time('Build stylesheet') if (context.stylesheetCache === null || context.classCache.size !== classCacheCount) { - for (let rule of rules) { - context.ruleCache.add(rule) - } - context.stylesheetCache = buildStylesheet([...context.ruleCache], context) } env.DEBUG && console.timeEnd('Build stylesheet') diff --git a/src/lib/generateRules.js b/src/lib/generateRules.js --- a/src/lib/generateRules.js +++ b/src/lib/generateRules.js @@ -649,8 +649,37 @@ function inKeyframes(rule) { return rule.parent && rule.parent.type === 'atrule' && rule.parent.name === 'keyframes' } +function getImportantStrategy(important) { + if (important === true) { + return (rule) => { + if (inKeyframes(rule)) { + return + } + + rule.walkDecls((d) => { + if (d.parent.type === 'rule' && !inKeyframes(d.parent)) { + d.important = true + } + }) + } + } + + if (typeof important === 'string') { + return (rule) => { + if (inKeyframes(rule)) { + return + } + + rule.selectors = rule.selectors.map((selector) => { + return `${important} ${selector}` + }) + } + } +} + function generateRules(candidates, context) { let allRules = [] + let strategy = getImportantStrategy(context.tailwindConfig.important) for (let candidate of candidates) { if (context.notClassCache.has(candidate)) { @@ -658,7 +687,11 @@ function generateRules(candidates, context) { } if (context.classCache.has(candidate)) { - allRules.push(context.classCache.get(candidate)) + continue + } + + if (context.candidateRuleCache.has(candidate)) { + allRules = allRules.concat(Array.from(context.candidateRuleCache.get(candidate))) continue } @@ -670,47 +703,27 @@ function generateRules(candidates, context) { } context.classCache.set(candidate, matches) - allRules.push(matches) - } - // Strategy based on `tailwindConfig.important` - let strategy = ((important) => { - if (important === true) { - return (rule) => { - rule.walkDecls((d) => { - if (d.parent.type === 'rule' && !inKeyframes(d.parent)) { - d.important = true - } - }) - } - } + let rules = context.candidateRuleCache.get(candidate) ?? new Set() + context.candidateRuleCache.set(candidate, rules) - if (typeof important === 'string') { - return (rule) => { - rule.selectors = rule.selectors.map((selector) => { - return `${important} ${selector}` - }) - } - } - })(context.tailwindConfig.important) + for (const match of matches) { + let [{ sort, layer, options }, rule] = match - return allRules.flat(1).map(([{ sort, layer, options }, rule]) => { - if (options.respectImportant) { - if (strategy) { + if (options.respectImportant && strategy) { let container = postcss.root({ nodes: [rule.clone()] }) - container.walkRules((r) => { - if (inKeyframes(r)) { - return - } - - strategy(r) - }) + container.walkRules(strategy) rule = container.nodes[0] } + + let newEntry = [sort | context.layerOrder[layer], rule] + rules.add(newEntry) + context.ruleCache.add(newEntry) + allRules.push(newEntry) } + } - return [sort | context.layerOrder[layer], rule] - }) + return allRules } function isArbitraryValue(input) { diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -873,6 +873,7 @@ export function createContext(tailwindConfig, changedContent = [], root = postcs let context = { disposables: [], ruleCache: new Set(), + candidateRuleCache: new Map(), classCache: new Map(), applyClassCache: new Map(), notClassCache: new Set(),
diff --git a/tests/important-boolean.test.js b/tests/important-boolean.test.js --- a/tests/important-boolean.test.js +++ b/tests/important-boolean.test.js @@ -1,7 +1,8 @@ import fs from 'fs' import path from 'path' +import * as sharedState from '../src/lib/sharedState' -import { run, css } from './util/run' +import { run, css, html } from './util/run' test('important boolean', () => { let config = { @@ -63,3 +64,74 @@ test('important boolean', () => { expect(result.css).toMatchFormattedCss(expected) }) }) + +// This is in a describe block so we can use `afterEach` :) +describe('duplicate elision', () => { + let filePath = path.resolve(__dirname, './important-boolean-duplicates.test.html') + + afterEach(async () => await fs.promises.unlink(filePath)) + + test('important rules are not duplicated when rebuilding', async () => { + let config = { + important: true, + content: [filePath], + } + + await fs.promises.writeFile( + config.content[0], + html` + <div class="ml-2"></div> + <div class="ml-4"></div> + ` + ) + + let input = css` + @tailwind utilities; + ` + + let result = await run(input, config) + let allContexts = Array.from(sharedState.contextMap.values()) + + let context = allContexts[allContexts.length - 1] + + let ruleCacheSize1 = context.ruleCache.size + + expect(result.css).toMatchFormattedCss(css` + .ml-2 { + margin-left: 0.5rem !important; + } + .ml-4 { + margin-left: 1rem !important; + } + `) + + await fs.promises.writeFile( + config.content[0], + html` + <div class="ml-2"></div> + <div class="ml-6"></div> + ` + ) + + result = await run(input, config) + + let ruleCacheSize2 = context.ruleCache.size + + expect(result.css).toMatchFormattedCss(css` + .ml-2 { + margin-left: 0.5rem !important; + } + .ml-4 { + margin-left: 1rem !important; + } + .ml-6 { + margin-left: 1.5rem !important; + } + `) + + // The rule cache was effectively doubling in size previously + // because the rule cache was never de-duped + // This ensures this behavior doesn't return + expect(ruleCacheSize2 - ruleCacheSize1).toBeLessThan(10) + }) +})
Using important: true leads to duplicate rules in output This issue supersedes #9203 which was a bit of a false start. V3.1.18 Tailwind CLI Node v14.18.1 Chrome Window 10 (No Docker or WSL) Command line : npx tailwindcss --output twout.css --watch -i twbase.css Reproduction URL: https://github.com/willdean/TwRepro1 **Describe your issue** When the important option is set to true, modifications to the source file cause TW to emit duplicate rules into the output for each update. Repro steps: 1. Start the CLI, using the command line above (or tw.bat on Windows) 2. Observe that the output file `twout.css` contains just two rules (after the boilerplate): ``` .ml-2 { margin-left: 0.5rem !important } .ml-4 { margin-left: 1rem !important } ``` 3. Modify the index.html file so that the `ml-4` selector on the second div becomes `ml-6` and save the file 4. Verify that the CLI regenerates the output file `twout.css` The output file now contains ``` .ml-2 { margin-left: 0.5rem !important } .ml-4 { margin-left: 1rem !important } .ml-2 { margin-left: 0.5rem !important } .ml-6 { margin-left: 1.5rem !important } ``` i.e. the `.ml-2` rule has been duplicated. This will happen each time a modification to the source file is made - there will be an additional `.ml-2` rule generated. **Some commentary:** I have spent some time trying to understand this, and I think there may be two separate problems, though I'm not a JS developer by trade, and I don't really understand TW's architecture, so please forgive me if I'm completely wrong here. **Possible Issue 1** - Each time a file is modified, TW adds duplicates of all the rules related to that specific file to `context.stylesheetCache`. This is nothing to do with whether the `important` configuration option is set or not. However, this does not normally cause duplication in the output, because the code which later converts the list of rules into css code elides all the duplicates. This may however be a part of the slow-down/leak problem in #7449. **Possible Issue 2**- The code which converts the rules list into CSS (is this Postcss?) is apparently able to elide duplicate rules, and that normally deals with the duplicates which build-up in the cache. However, this elision features partly breaks (not completely - some rules get repeated 'n' times, whereas some only see one duplicate) when the `important` option is set. If issue 1 is dealt with then issue 2 possibly wouldn't matter. In #9203 I posted some very crude work-around code which stops the duplicates in the cache. Edit: This issue doesn't seem to repro in https://play.tailwindcss.com/
In case this raises questions about PostCSS: ``` >npm -g list postcss C:\Users\will\AppData\Roaming\npm `-- [email protected] +-- [email protected] | `-- [email protected] deduped +-- [email protected] | `-- [email protected] deduped +-- [email protected] | `-- [email protected] deduped +-- [email protected] | `-- [email protected] deduped `-- [email protected] ``` I don't think this is likely to be related to PostCSS. We do some internal cache clearing stuff on Tailwind Play. Since there's only a single content input source we have it set up to act essentially as if it were a fresh build. Thanks Jordan - I don't properly comprehend the flow of: `(List-Of-Rules-with-lots-of-duplicates) => [A miracle happens here] => (CSS file with fewer duplicates)` and thought that the miracle might be PostCSS. Anyway, the duplicates have been annoying us for months and months, so it was nice to get to *some* level of understanding. Yeah I'm not sure why the duplicates some time disappear and sometimes don't but I can absolutely reproduce it in the CLI so I'm taking a look. I've also been able to create a script that makes the rule cache grow significantly which reproduces the slowdown issue. That's a small but significantly helpful data point as well! The point at which the duplicate is created in the cache is `returnValue.utilities.add(rule);` in `buildStylesheet`. I wondered if there had originally been the intent that, being made from a `Set` object, the cache would inherently not hold duplicates. Of course, from the PoV of a `Set`, the duplicates are not the same, so that doesn't work. I wouldn’t be surprised if it did used to be the same rule instance but in fixing another bug we’ve introduced a regression (probably by cloning the rule somewhere) that is causing duplicates to appear. Candidates (like `ml-4`) should be pulling their corresponding rule from a cache if they have been generated already, so should have been the same rule instance originally I think.
"2022-08-29T17:47:47Z"
3.1
[]
[ "tests/important-boolean.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/" ]
tailwindlabs/tailwindcss
9,262
tailwindlabs__tailwindcss-9262
[ "9056" ]
09f38d296434a9b73ccfbdba6c7ebf1438727832
diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -29,6 +29,58 @@ export function formatVariantSelector(current, ...others) { return current } +/** + * Given any node in a selector this gets the "simple" selector it's a part of + * A simple selector is just a list of nodes without any combinators + * Technically :is(), :not(), :has(), etc… can have combinators but those are nested + * inside the relevant node and won't be picked up so they're fine to ignore + * + * @param {import('postcss-selector-parser').Node} node + * @returns {import('postcss-selector-parser').Node[]} + **/ +function simpleSelectorForNode(node) { + /** @type {import('postcss-selector-parser').Node[]} */ + let nodes = [] + + // Walk backwards until we hit a combinator node (or the start) + while (node.prev() && node.prev().type !== 'combinator') { + node = node.prev() + } + + // Now record all non-combinator nodes until we hit one (or the end) + while (node && node.type !== 'combinator') { + nodes.push(node) + node = node.next() + } + + return nodes +} + +/** + * Resorts the nodes in a selector to ensure they're in the correct order + * Tags go before classes, and pseudo classes go after classes + * + * @param {import('postcss-selector-parser').Selector} sel + * @returns {import('postcss-selector-parser').Selector} + **/ +function resortSelector(sel) { + sel.sort((a, b) => { + if (a.type === 'tag' && b.type === 'class') { + return -1 + } else if (a.type === 'class' && b.type === 'tag') { + return 1 + } else if (a.type === 'class' && b.type === 'pseudo' && b.value !== ':merge') { + return -1 + } else if (a.type === 'pseudo' && a.value !== ':merge' && b.type === 'class') { + return 1 + } + + return sel.index(a) - sel.index(b) + }) + + return sel +} + export function finalizeSelector( format, { @@ -88,12 +140,47 @@ export function finalizeSelector( } }) + let simpleStart = selectorParser.comment({ value: '/*__simple__*/' }) + let simpleEnd = selectorParser.comment({ value: '/*__simple__*/' }) + // We can safely replace the escaped base now, since the `base` section is // now in a normalized escaped value. ast.walkClasses((node) => { - if (node.value === base) { - node.replaceWith(...formatAst.nodes) + if (node.value !== base) { + return + } + + let parent = node.parent + let formatNodes = formatAst.nodes[0].nodes + + // Perf optimization: if the parent is a single class we can just replace it and be done + if (parent.nodes.length === 1) { + node.replaceWith(...formatNodes) + return } + + let simpleSelector = simpleSelectorForNode(node) + parent.insertBefore(simpleSelector[0], simpleStart) + parent.insertAfter(simpleSelector[simpleSelector.length - 1], simpleEnd) + + for (let child of formatNodes) { + parent.insertBefore(simpleSelector[0], child) + } + + node.remove() + + // Re-sort the simple selector to ensure it's in the correct order + simpleSelector = simpleSelectorForNode(simpleStart) + let firstNode = parent.index(simpleStart) + + parent.nodes.splice( + firstNode, + simpleSelector.length, + ...resortSelector(selectorParser.selector({ nodes: simpleSelector })).nodes + ) + + simpleStart.remove() + simpleEnd.remove() }) // This will make sure to move pseudo's to the correct spot (the end for
diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -855,3 +855,92 @@ test('hoverOnlyWhenSupported adds hover and pointer media features by default', `) }) }) + +test('multi-class utilities handle selector-mutating variants correctly', () => { + let config = { + content: [ + { + raw: html`<div + class="hover:foo hover:bar hover:baz group-hover:foo group-hover:bar group-hover:baz peer-checked:foo peer-checked:bar peer-checked:baz" + ></div>`, + }, + { + raw: html`<div + class="hover:foo1 hover:bar1 hover:baz1 group-hover:foo1 group-hover:bar1 group-hover:baz1 peer-checked:foo1 peer-checked:bar1 peer-checked:baz1" + ></div>`, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + .foo.bar.baz { + color: red; + } + .foo1 .bar1 .baz1 { + color: red; + } + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + .hover\:foo.bar.baz:hover { + color: red; + } + .hover\:bar.foo.baz:hover { + color: red; + } + .hover\:baz.foo.bar:hover { + color: red; + } + .hover\:foo1:hover .bar1 .baz1 { + color: red; + } + .foo1 .hover\:bar1:hover .baz1 { + color: red; + } + .foo1 .bar1 .hover\:baz1:hover { + color: red; + } + .group:hover .group-hover\:foo.bar.baz { + color: red; + } + .group:hover .group-hover\:bar.foo.baz { + color: red; + } + .group:hover .group-hover\:baz.foo.bar { + color: red; + } + .group:hover .group-hover\:foo1 .bar1 .baz1 { + color: red; + } + .foo1 .group:hover .group-hover\:bar1 .baz1 { + color: red; + } + .foo1 .bar1 .group:hover .group-hover\:baz1 { + color: red; + } + .peer:checked ~ .peer-checked\:foo.bar.baz { + color: red; + } + .peer:checked ~ .peer-checked\:bar.foo.baz { + color: red; + } + .peer:checked ~ .peer-checked\:baz.foo.bar { + color: red; + } + .peer:checked ~ .peer-checked\:foo1 .bar1 .baz1 { + color: red; + } + .foo1 .peer:checked ~ .peer-checked\:bar1 .baz1 { + color: red; + } + .foo1 .bar1 .peer:checked ~ .peer-checked\:baz1 { + color: red; + } + `) + }) +})
CSS rules of the form `.foo.bar` don't behave as expected with `peer-checked:bar` **What version of Tailwind CSS are you using?** v3.1.8 **What build tool (or framework if it abstracts the build tool) are you using?** postcss-cli 10.0.0 **What version of Node.js are you using?** v16.14.0 **What browser are you using?** N/A **What operating system are you using?** Linux **Reproduction URL** https://play.tailwindcss.com/4zvuUG5xci Seems Tailwind Play is still on v3.1.5, but I see the issue in v3.1.8 **Describe your issue** If I have a standard CSS rule defined like this: ```css @layer components { .foo.bar { background-color: green; } } ``` Then I would expect `peer-checked:bar` to define the following: ```css .peer:checked ~ .foo.peer-checked\:bar { background-color: green; } ``` Instead it generates: ```css .foo.peer:checked ~ .peer-checked\:bar { background-color: green; } ``` `.foo` is applied to the `.peer` instead of the `.peer-checked\:bar`. Changing the original rule to `.bar.foo` fixes the issue (i.e. it works as expected with the first class in the list).
Hey! Can you share a more real-world example of why you would even be doing this? I agree the behavior doesn't feel right here but the usage looks really bizarre to me (`.bar` is not a utility in your example, it's part of a complex selector), and I'm honestly more inclined to throw an exception here than to change the behavior. I also have this same question and I cannot find any proper answers on the internet and also need a solution. Works like a charm! It there already an Solution to this problem? I have the same problem. [cuims](https://www.cuims.net/) Sorry for the delay, I've been on holiday for the last couple of weeks. Our use case is admittedly a bit weird and complicated so I'm not surprised it hasn't really been an issue. We have a "visual check box" component where we control how it appears using CSS classes, e.g. adding the `checkbox--checked` class makes it appear checked and `checkbox--disabled` makes it appear disabled. This enables us to build more complex components using Tailwind, for example we can use `<input type="checkbox" class="sr-only peer">` to control one of these visual check boxes by adding classes like `peer-checked:checkbox--checked peer-disabled:checkbox--disabled`. This works really well and allows us to create custom components that are controlled entirely by CSS, no JS involved. However, if we want to render a checked and disabled checkbox ideally we would define the style using a `.checkbox--checked.checkbox--disabled` rule, but due to the bug above that doesn't work with `peer-checked:checkbox--checked peer-disabled:checkbox--disabled`. Instead we've had to create a `checkbox--checked-and-disabled` class and use that with the appropriate Tailwind modifiers. Note that we use this in various different situations not just with `peer`. There are obviously other ways we could implement this that might result in simpler CSS, but the flexibility was important for our use cases.
"2022-09-05T15:43:26Z"
3.1
[]
[ "tests/variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/4zvuUG5xci" ]
tailwindlabs/tailwindcss
9,309
tailwindlabs__tailwindcss-9309
[ "9303" ]
cc1be47a4fa2de74bc63b0b123f335271ec1bc68
diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -81,6 +81,29 @@ function resortSelector(sel) { return sel } +function eliminateIrrelevantSelectors(sel, base) { + let hasClassesMatchingCandidate = false + + sel.walk((child) => { + if (child.type === 'class' && child.value === base) { + hasClassesMatchingCandidate = true + return false // Stop walking + } + }) + + if (!hasClassesMatchingCandidate) { + sel.remove() + } + + // We do NOT recursively eliminate sub selectors that don't have the base class + // as this is NOT a safe operation. For example, if we have: + // `.space-x-2 > :not([hidden]) ~ :not([hidden])` + // We cannot remove the [hidden] from the :not() because it would change the + // meaning of the selector. + + // TODO: Can we do this for :matches, :is, and :where? +} + export function finalizeSelector( format, { @@ -115,13 +138,7 @@ export function finalizeSelector( // Remove extraneous selectors that do not include the base class/candidate being matched against // For example if we have a utility defined `.a, .b { color: red}` // And the formatted variant is sm:b then we want the final selector to be `.sm\:b` and not `.a, .sm\:b` - ast.each((node) => { - let hasClassesMatchingCandidate = node.some((n) => n.type === 'class' && n.value === base) - - if (!hasClassesMatchingCandidate) { - node.remove() - } - }) + ast.each((sel) => eliminateIrrelevantSelectors(sel, base)) // Normalize escaped classes, e.g.: //
diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -944,3 +944,88 @@ test('multi-class utilities handle selector-mutating variants correctly', () => `) }) }) + +test('class inside pseudo-class function :has', () => { + let config = { + content: [ + { raw: html`<div class="foo hover:foo sm:foo"></div>` }, + { raw: html`<div class="bar hover:bar sm:bar"></div>` }, + { raw: html`<div class="baz hover:baz sm:baz"></div>` }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + @layer utilities { + :where(.foo) { + color: red; + } + :matches(.foo, .bar, .baz) { + color: orange; + } + :is(.foo) { + color: yellow; + } + html:has(.foo) { + color: green; + } + } + ` + + return run(input, config).then((result) => { + expect(result.css).toMatchFormattedCss(css` + :where(.foo) { + color: red; + } + :matches(.foo, .bar, .baz) { + color: orange; + } + :is(.foo) { + color: yellow; + } + html:has(.foo) { + color: green; + } + + :where(.hover\:foo:hover) { + color: red; + } + :matches(.hover\:foo:hover, .bar, .baz) { + color: orange; + } + :matches(.foo, .hover\:bar:hover, .baz) { + color: orange; + } + :matches(.foo, .bar, .hover\:baz:hover) { + color: orange; + } + :is(.hover\:foo:hover) { + color: yellow; + } + html:has(.hover\:foo:hover) { + color: green; + } + @media (min-width: 640px) { + :where(.sm\:foo) { + color: red; + } + :matches(.sm\:foo, .bar, .baz) { + color: orange; + } + :matches(.foo, .sm\:bar, .baz) { + color: orange; + } + :matches(.foo, .bar, .sm\:baz) { + color: orange; + } + :is(.sm\:foo) { + color: yellow; + } + html:has(.sm\:foo) { + color: green; + } + } + `) + }) +})
Adding custom utilities that use `:where()` selector, generates empty CSS selector when used with a responsive prefix <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** 3.1.8 **Reproduction URL** https://play.tailwindcss.com/6lUxA2zYzo?file=config **Describe your issue** This works: ```html <div class="sm:make-it-red"> ``` ```js addUtilities({ '.make-it-red': { backgroundColor: 'red', }, }),{ variants: ["responsive"], } ``` But this doesn't work: ```html <div class="sm:make-it-pink"> ``` ```js addUtilities({ ':where(.make-it-pink)': { backgroundColor: 'hotpink', }, }),{ variants: ["responsive"], } ``` Expected CSS: ```css @media (min-width: 640px) { .sm\:make-it-red { background-color: red } :where(.sm\:make-it-pink){ background-color: hotpink } } ``` Generated CSS: ```css @media (min-width: 640px) { .sm\:make-it-red { background-color: red } { background-color: hotpink } } ``` As you can see [here](https://play.tailwindcss.com/6lUxA2zYzo?file=config) it generates empty selector name. I wonder if there's a way to make it work to have `:where()` selectors with responsive prefixes.
"2022-09-11T21:56:32Z"
3.1
[]
[ "tests/variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/6lUxA2zYzo?file=config" ]
tailwindlabs/tailwindcss
9,319
tailwindlabs__tailwindcss-9319
[ "9318" ]
527031d5f679a958a7d0de045a057a1e32db2985
diff --git a/src/lib/evaluateTailwindFunctions.js b/src/lib/evaluateTailwindFunctions.js --- a/src/lib/evaluateTailwindFunctions.js +++ b/src/lib/evaluateTailwindFunctions.js @@ -7,6 +7,7 @@ import buildMediaQuery from '../util/buildMediaQuery' import { toPath } from '../util/toPath' import { withAlphaValue } from '../util/withAlphaVariable' import { parseColorFormat } from '../util/pluginUtils' +import log from '../util/log' function isObject(input) { return typeof input === 'object' && input !== null @@ -196,7 +197,9 @@ function resolvePath(config, path, defaultValue) { return results.find((result) => result.isValid) ?? results[0] } -export default function ({ tailwindConfig: config }) { +export default function (context) { + let config = context.tailwindConfig + let functions = { theme: (node, path, ...defaultValue) => { let { isValid, value, error, alpha } = resolvePath( @@ -206,6 +209,24 @@ export default function ({ tailwindConfig: config }) { ) if (!isValid) { + let parentNode = node.parent + let candidate = parentNode?.raws.tailwind?.candidate + + if (parentNode && candidate !== undefined) { + // Remove this utility from any caches + context.markInvalidUtilityNode(parentNode) + + // Remove the CSS node from the markup + parentNode.remove() + + // Show a warning + log.warn('invalid-theme-key-in-class', [ + `The utility \`${candidate}\` contains an invalid theme value and was not generated.`, + ]) + + return + } + throw node.error(error) } diff --git a/src/lib/setupContextUtils.js b/src/lib/setupContextUtils.js --- a/src/lib/setupContextUtils.js +++ b/src/lib/setupContextUtils.js @@ -856,6 +856,52 @@ function registerPlugins(plugins, context) { } } +/** + * Mark as class as retroactively invalid + * + * + * @param {string} candidate + */ +function markInvalidUtilityCandidate(context, candidate) { + if (!context.classCache.has(candidate)) { + return + } + + // Mark this as not being a real utility + context.notClassCache.add(candidate) + + // Remove it from any candidate-specific caches + context.classCache.delete(candidate) + context.applyClassCache.delete(candidate) + context.candidateRuleMap.delete(candidate) + context.candidateRuleCache.delete(candidate) + + // Ensure the stylesheet gets rebuilt + context.stylesheetCache = null +} + +/** + * Mark as class as retroactively invalid + * + * @param {import('postcss').Node} node + */ +function markInvalidUtilityNode(context, node) { + let candidate = node.raws.tailwind.candidate + + if (!candidate) { + return + } + + for (const entry of context.ruleCache) { + if (entry[1].raws.tailwind.candidate === candidate) { + context.ruleCache.delete(entry) + // context.postCssNodeCache.delete(node) + } + } + + markInvalidUtilityCandidate(context, candidate) +} + export function createContext(tailwindConfig, changedContent = [], root = postcss.root()) { let context = { disposables: [], @@ -870,6 +916,9 @@ export function createContext(tailwindConfig, changedContent = [], root = postcs changedContent: changedContent, variantMap: new Map(), stylesheetCache: null, + + markInvalidUtilityCandidate: (candidate) => markInvalidUtilityCandidate(context, candidate), + markInvalidUtilityNode: (node) => markInvalidUtilityNode(context, node), } let resolvedPlugins = resolvePlugins(context, root)
diff --git a/tests/evaluateTailwindFunctions.test.js b/tests/evaluateTailwindFunctions.test.js --- a/tests/evaluateTailwindFunctions.test.js +++ b/tests/evaluateTailwindFunctions.test.js @@ -1,14 +1,18 @@ +import fs from 'fs' +import path from 'path' import postcss from 'postcss' import plugin from '../src/lib/evaluateTailwindFunctions' -import tailwind from '../src/index' -import { css } from './util/run' +import { run as runFull, css, html } from './util/run' function run(input, opts = {}) { - return postcss([plugin({ tailwindConfig: opts })]).process(input, { from: undefined }) -} - -function runFull(input, config) { - return postcss([tailwind(config)]).process(input, { from: undefined }) + return postcss([ + plugin({ + tailwindConfig: opts, + markInvalidUtilityNode() { + // no op + }, + }), + ]).process(input, { from: undefined }) } test('it looks up values in the theme using dot notation', () => { @@ -1222,3 +1226,62 @@ it('can find values with slashes in the theme key while still allowing for alpha `) }) }) + +describe('context dependent', () => { + let configPath = path.resolve(__dirname, './evaluate-tailwind-functions.tailwind.config.js') + let filePath = path.resolve(__dirname, './evaluate-tailwind-functions.test.html') + let config = { + content: [filePath], + corePlugins: { preflight: false }, + } + + // Rebuild the config file for each test + beforeEach(() => fs.promises.writeFile(configPath, `module.exports = ${JSON.stringify(config)};`)) + afterEach(() => fs.promises.unlink(configPath)) + + let warn + + beforeEach(() => { + warn = jest.spyOn(require('../src/util/log').default, 'warn') + }) + + afterEach(() => warn.mockClear()) + + it('should not generate when theme fn doesnt resolve', async () => { + await fs.promises.writeFile( + filePath, + html` + <div class="underline [--box-shadow:theme('boxShadow.doesnotexist')]"></div> + <div class="bg-[theme('boxShadow.doesnotexist')]"></div> + ` + ) + + // TODO: We need a way to reuse the context in our test suite without requiring writing to files + // It should be an explicit thing tho β€” like we create a context and pass it in or something + let result = await runFull('@tailwind utilities', configPath) + + // 1. On first run it should work because it's been removed from the class cache + expect(result.css).toMatchCss(css` + .underline { + text-decoration-line: underline; + } + `) + + // 2. But we get a warning in the console + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls.map((x) => x[0])).toEqual(['invalid-theme-key-in-class']) + + // 3. The second run should work fine because it's been removed from the class cache + result = await runFull('@tailwind utilities', configPath) + + expect(result.css).toMatchCss(css` + .underline { + text-decoration-line: underline; + } + `) + + // 4. But we've not received any further logs about it + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls.map((x) => x[0])).toEqual(['invalid-theme-key-in-class']) + }) +})
Tailwind compiler crashes when you try to `[--box-shadow:theme('boxShadow.doesNotExist')]` **What version of Tailwind CSS are you using?** v3.1.8 **What build tool (or framework if it abstracts the build tool) are you using?** vite 3.0.9, postcss 8.4.14 postcss-cli 8.3.1 **What version of Node.js are you using?** v16.0.0 **What browser are you using?** Chrome **What operating system are you using?** PopOS, Ubuntu **Reproduction URL** https://stackblitz.com/edit/vitejs-vite-zy2efk?file=src/App.jsx **Describe your issue** I was thinkering with tailwind to find ways of modifying css variables with classes. Came up with something like ```javascript <button className="[--box-shadow:theme('boxShadow.sm')] bg-white p-5"> Button </button> ``` But if I change the `theme` to something that will throw a runtime error: ```javascript <button className="[--box-shadow:theme('boxShadow.doesNotExist')] bg-white p-5"> Button </button> ``` Still crashes if I change it back to: ```javascript <button className="[--box-shadow:theme('boxShadow.sm')] bg-white p-5"> Button </button> ``` Well, maybe the Tailwind compiler crashes and can't recover? It's a bug, I think!?
"2022-09-13T18:05:38Z"
3.1
[]
[ "tests/evaluateTailwindFunctions.test.js" ]
TypeScript
[]
[]
tailwindlabs/tailwindcss
9,991
tailwindlabs__tailwindcss-9991
[ "9977" ]
a1249779ec74693023c26f852a3f9c6edfa7ba7c
diff --git a/src/util/formatVariantSelector.js b/src/util/formatVariantSelector.js --- a/src/util/formatVariantSelector.js +++ b/src/util/formatVariantSelector.js @@ -250,7 +250,18 @@ export function finalizeSelector( let pseudoElementsBC = [':before', ':after', ':first-line', ':first-letter'] // These pseudo-elements _can_ be combined with other pseudo selectors AND the order does matter. -let pseudoElementExceptions = ['::file-selector-button'] +let pseudoElementExceptions = [ + '::file-selector-button', + + // Webkit scroll bar pseudo elements can be combined with user-action pseudo classes + '::-webkit-scrollbar', + '::-webkit-scrollbar-button', + '::-webkit-scrollbar-thumb', + '::-webkit-scrollbar-track', + '::-webkit-scrollbar-track-piece', + '::-webkit-scrollbar-corner', + '::-webkit-resizer', +] // This will make sure to move pseudo's to the correct spot (the end for // pseudo elements) because otherwise the selector will never work
diff --git a/tests/variants.test.js b/tests/variants.test.js --- a/tests/variants.test.js +++ b/tests/variants.test.js @@ -1096,3 +1096,52 @@ test('variant functions returning arrays should output correct results when nest } `) }) + +test.only('arbitrary variant selectors should not re-order scrollbar pseudo classes', async () => { + let config = { + content: [ + { + raw: html` + <div class="[&::-webkit-scrollbar:hover]:underline" /> + <div class="[&::-webkit-scrollbar-button:hover]:underline" /> + <div class="[&::-webkit-scrollbar-thumb:hover]:underline" /> + <div class="[&::-webkit-scrollbar-track:hover]:underline" /> + <div class="[&::-webkit-scrollbar-track-piece:hover]:underline" /> + <div class="[&::-webkit-scrollbar-corner:hover]:underline" /> + <div class="[&::-webkit-resizer:hover]:underline" /> + `, + }, + ], + corePlugins: { preflight: false }, + } + + let input = css` + @tailwind utilities; + ` + + let result = await run(input, config) + + expect(result.css).toMatchFormattedCss(css` + .\[\&\:\:-webkit-scrollbar\:hover\]\:underline::-webkit-scrollbar:hover { + text-decoration-line: underline; + } + .\[\&\:\:-webkit-scrollbar-button\:hover\]\:underline::-webkit-scrollbar-button:hover { + text-decoration-line: underline; + } + .\[\&\:\:-webkit-scrollbar-thumb\:hover\]\:underline::-webkit-scrollbar-thumb:hover { + text-decoration-line: underline; + } + .\[\&\:\:-webkit-scrollbar-track\:hover\]\:underline::-webkit-scrollbar-track:hover { + text-decoration-line: underline; + } + .\[\&\:\:-webkit-scrollbar-track-piece\:hover\]\:underline::-webkit-scrollbar-track-piece:hover { + text-decoration-line: underline; + } + .\[\&\:\:-webkit-scrollbar-corner\:hover\]\:underline::-webkit-scrollbar-corner:hover { + text-decoration-line: underline; + } + .\[\&\:\:-webkit-resizer\:hover\]\:underline::-webkit-resizer:hover { + text-decoration-line: underline; + } + `) +})
arbitrary variants with modifiers inside the selector are generated in the wrong order <!-- Please provide all of the information requested below. We're a small team and without all of this information it's not possible for us to help and your bug report will be closed. --> **What version of Tailwind CSS are you using?** v3.2.4 **What build tool (or framework if it abstracts the build tool) are you using?** playground **Reproduction URL** https://play.tailwindcss.com/RWATzeVv1a **Describe your issue** This arbitrary variant `[&::-webkit-scrollbar-thumb:hover]:bg-green-500` is generated in the wrong order as `&:hover::-webkit-scrollbar-thumb` but should be `&::-webkit-scrollbar-thumb:hover`. When replacing the `::` with just one `:`, the generated order is correct (but the result obviously does not work anymore)
"2022-12-02T17:06:59Z"
3.2
[]
[ "tests/variants.test.js" ]
TypeScript
[]
[ "https://play.tailwindcss.com/RWATzeVv1a" ]