tailwindcss 0.0.0-insiders.7c337f2 → 0.0.0-insiders.7d8eb21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +246 -6
  2. package/README.md +13 -9
  3. package/defaultTheme.d.ts +2 -1
  4. package/lib/cli/build/deps.js +54 -0
  5. package/lib/cli/build/index.js +48 -0
  6. package/lib/cli/build/plugin.js +362 -0
  7. package/lib/cli/build/utils.js +78 -0
  8. package/lib/cli/build/watching.js +178 -0
  9. package/lib/cli/help/index.js +71 -0
  10. package/lib/cli/index.js +18 -0
  11. package/lib/cli/init/index.js +46 -0
  12. package/lib/cli/shared.js +12 -0
  13. package/lib/cli-peer-dependencies.js +18 -5
  14. package/lib/cli.js +62 -592
  15. package/lib/constants.js +19 -12
  16. package/lib/corePluginList.js +5 -3
  17. package/lib/corePlugins.js +619 -347
  18. package/lib/css/preflight.css +7 -0
  19. package/lib/featureFlags.js +34 -22
  20. package/lib/index.js +16 -9
  21. package/lib/lib/cacheInvalidation.js +42 -21
  22. package/lib/lib/collapseAdjacentRules.js +16 -14
  23. package/lib/lib/collapseDuplicateDeclarations.js +13 -10
  24. package/lib/lib/content.js +177 -0
  25. package/lib/lib/defaultExtractor.js +230 -33
  26. package/lib/lib/detectNesting.js +13 -4
  27. package/lib/lib/evaluateTailwindFunctions.js +105 -42
  28. package/lib/lib/expandApplyAtRules.js +151 -92
  29. package/lib/lib/expandTailwindAtRules.js +134 -149
  30. package/lib/lib/findAtConfigPath.js +44 -0
  31. package/lib/lib/generateRules.js +404 -185
  32. package/lib/lib/getModuleDependencies.js +21 -18
  33. package/lib/lib/normalizeTailwindDirectives.js +11 -8
  34. package/lib/lib/offsets.js +285 -0
  35. package/lib/lib/partitionApplyAtRules.js +14 -11
  36. package/lib/lib/regex.js +60 -0
  37. package/lib/lib/remap-bitfield.js +87 -0
  38. package/lib/lib/resolveDefaultsAtRules.js +97 -79
  39. package/lib/lib/setupContextUtils.js +567 -242
  40. package/lib/lib/setupTrackingContext.js +77 -106
  41. package/lib/lib/sharedState.js +18 -10
  42. package/lib/lib/substituteScreenAtRules.js +9 -7
  43. package/lib/postcss-plugins/nesting/index.js +7 -5
  44. package/lib/postcss-plugins/nesting/plugin.js +10 -8
  45. package/lib/processTailwindFeatures.js +34 -31
  46. package/lib/public/colors.js +7 -5
  47. package/lib/public/create-plugin.js +6 -4
  48. package/lib/public/default-config.js +7 -5
  49. package/lib/public/default-theme.js +7 -5
  50. package/lib/public/resolve-config.js +13 -10
  51. package/lib/util/bigSign.js +4 -1
  52. package/lib/util/buildMediaQuery.js +10 -5
  53. package/lib/util/cloneDeep.js +6 -5
  54. package/lib/util/cloneNodes.js +9 -2
  55. package/lib/util/color.js +20 -17
  56. package/lib/util/configurePlugins.js +5 -2
  57. package/lib/util/createPlugin.js +6 -5
  58. package/lib/util/createUtilityPlugin.js +15 -13
  59. package/lib/util/dataTypes.js +75 -51
  60. package/lib/util/defaults.js +8 -5
  61. package/lib/util/escapeClassName.js +13 -10
  62. package/lib/util/escapeCommas.js +4 -1
  63. package/lib/util/flattenColorPalette.js +7 -8
  64. package/lib/util/formatVariantSelector.js +270 -103
  65. package/lib/util/getAllConfigs.js +34 -15
  66. package/lib/util/hashConfig.js +10 -7
  67. package/lib/util/isKeyframeRule.js +4 -1
  68. package/lib/util/isPlainObject.js +4 -1
  69. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +34 -26
  70. package/lib/util/log.js +14 -8
  71. package/lib/util/nameClass.js +19 -8
  72. package/lib/util/negateValue.js +20 -5
  73. package/lib/util/normalizeConfig.js +94 -53
  74. package/lib/util/normalizeScreens.js +115 -4
  75. package/lib/util/parseAnimationValue.js +43 -41
  76. package/lib/util/parseBoxShadowValue.js +12 -45
  77. package/lib/util/parseDependency.js +37 -55
  78. package/lib/util/parseGlob.js +34 -0
  79. package/lib/util/parseObjectStyles.js +15 -12
  80. package/lib/util/pluginUtils.js +146 -42
  81. package/lib/util/prefixSelector.js +26 -9
  82. package/lib/util/removeAlphaVariables.js +29 -0
  83. package/lib/util/resolveConfig.js +104 -105
  84. package/lib/util/resolveConfigPath.js +20 -17
  85. package/lib/util/responsive.js +12 -9
  86. package/lib/util/splitAtTopLevelOnly.js +43 -0
  87. package/lib/util/tap.js +4 -1
  88. package/lib/util/toColorValue.js +4 -1
  89. package/lib/util/toPath.js +18 -2
  90. package/lib/util/transformThemeValue.js +23 -11
  91. package/lib/util/validateConfig.js +24 -0
  92. package/lib/util/validateFormalSyntax.js +24 -0
  93. package/lib/util/withAlphaVariable.js +32 -24
  94. package/package.json +32 -29
  95. package/peers/index.js +6693 -3036
  96. package/plugin.d.ts +10 -5
  97. package/resolveConfig.d.ts +12 -0
  98. package/scripts/generate-types.js +53 -0
  99. package/scripts/release-channel.js +18 -0
  100. package/scripts/release-notes.js +21 -0
  101. package/scripts/type-utils.js +27 -0
  102. package/src/cli/build/deps.js +56 -0
  103. package/src/cli/build/index.js +49 -0
  104. package/src/cli/build/plugin.js +434 -0
  105. package/src/cli/build/utils.js +76 -0
  106. package/src/cli/build/watching.js +227 -0
  107. package/src/cli/help/index.js +70 -0
  108. package/src/cli/index.js +3 -0
  109. package/src/cli/init/index.js +50 -0
  110. package/src/cli/shared.js +5 -0
  111. package/src/cli-peer-dependencies.js +7 -1
  112. package/src/cli.js +46 -659
  113. package/src/corePlugins.js +346 -79
  114. package/src/css/preflight.css +7 -0
  115. package/src/featureFlags.js +12 -2
  116. package/src/index.js +5 -0
  117. package/src/lib/content.js +213 -0
  118. package/src/lib/defaultExtractor.js +202 -35
  119. package/src/lib/detectNesting.js +9 -1
  120. package/src/lib/evaluateTailwindFunctions.js +78 -7
  121. package/src/lib/expandApplyAtRules.js +129 -34
  122. package/src/lib/expandTailwindAtRules.js +12 -50
  123. package/src/lib/findAtConfigPath.js +48 -0
  124. package/src/lib/generateRules.js +379 -126
  125. package/src/lib/offsets.js +351 -0
  126. package/src/lib/regex.js +74 -0
  127. package/src/lib/remap-bitfield.js +82 -0
  128. package/src/lib/resolveDefaultsAtRules.js +53 -36
  129. package/src/lib/setupContextUtils.js +510 -120
  130. package/src/lib/setupTrackingContext.js +8 -45
  131. package/src/lib/sharedState.js +2 -0
  132. package/src/util/buildMediaQuery.js +5 -3
  133. package/src/util/cloneNodes.js +5 -1
  134. package/src/util/dataTypes.js +51 -26
  135. package/src/util/formatVariantSelector.js +317 -101
  136. package/src/util/getAllConfigs.js +19 -0
  137. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  138. package/src/util/log.js +1 -1
  139. package/src/util/nameClass.js +4 -0
  140. package/src/util/negateValue.js +10 -2
  141. package/src/util/normalizeConfig.js +40 -10
  142. package/src/util/normalizeScreens.js +99 -4
  143. package/src/util/parseBoxShadowValue.js +3 -50
  144. package/src/util/parseDependency.js +37 -42
  145. package/src/util/parseGlob.js +24 -0
  146. package/src/util/pluginUtils.js +132 -10
  147. package/src/util/prefixSelector.js +28 -10
  148. package/src/util/removeAlphaVariables.js +24 -0
  149. package/src/util/resolveConfig.js +70 -62
  150. package/src/util/splitAtTopLevelOnly.js +45 -0
  151. package/src/util/toPath.js +1 -1
  152. package/src/util/transformThemeValue.js +13 -3
  153. package/src/util/validateConfig.js +13 -0
  154. package/src/util/validateFormalSyntax.js +34 -0
  155. package/src/util/withAlphaVariable.js +1 -1
  156. package/stubs/defaultConfig.stub.js +165 -164
  157. package/stubs/simpleConfig.stub.js +1 -0
  158. package/types/config.d.ts +77 -37
  159. package/types/generated/default-theme.d.ts +342 -0
  160. package/types/index.d.ts +7 -1
  161. package/types.d.ts +0 -1
@@ -22,6 +22,7 @@
22
22
  2. Prevent adjustments of font size after orientation changes in iOS.
23
23
  3. Use a more readable tab size.
24
24
  4. Use the user's configured `sans` font-family by default.
25
+ 5. Use the user's configured `sans` font-feature-settings by default.
25
26
  */
26
27
 
27
28
  html {
@@ -30,6 +31,7 @@ html {
30
31
  -moz-tab-size: 4; /* 3 */
31
32
  tab-size: 4; /* 3 */
32
33
  font-family: theme('fontFamily.sans', 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"); /* 4 */
34
+ font-feature-settings: theme('fontFamily.sans[1].fontFeatureSettings', normal); /* 5 */
33
35
  }
34
36
 
35
37
  /*
@@ -358,3 +360,8 @@ video {
358
360
  max-width: 100%;
359
361
  height: auto;
360
362
  }
363
+
364
+ /* Make elements with the HTML hidden attribute stay hidden by default */
365
+ [hidden] {
366
+ display: none;
367
+ }
@@ -3,11 +3,21 @@ import log from './util/log'
3
3
 
4
4
  let defaults = {
5
5
  optimizeUniversalDefaults: false,
6
+ generalizedModifiers: true,
6
7
  }
7
8
 
8
9
  let featureFlags = {
9
- future: [],
10
- experimental: ['optimizeUniversalDefaults'],
10
+ future: [
11
+ 'hoverOnlyWhenSupported',
12
+ 'respectDefaultRingColorOpacity',
13
+ 'disableColorOpacityUtilitiesByDefault',
14
+ 'relativeContentPathsByDefault',
15
+ ],
16
+ experimental: [
17
+ 'optimizeUniversalDefaults',
18
+ 'generalizedModifiers',
19
+ // 'variantGrouping',
20
+ ],
11
21
  }
12
22
 
13
23
  export function flagEnabled(config, flag) {
package/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import setupTrackingContext from './lib/setupTrackingContext'
2
2
  import processTailwindFeatures from './processTailwindFeatures'
3
3
  import { env } from './lib/sharedState'
4
+ import { findAtConfigPath } from './lib/findAtConfigPath'
4
5
 
5
6
  module.exports = function tailwindcss(configOrPath) {
6
7
  return {
@@ -13,6 +14,10 @@ module.exports = function tailwindcss(configOrPath) {
13
14
  return root
14
15
  },
15
16
  function (root, result) {
17
+ // Use the path for the `@config` directive if it exists, otherwise use the
18
+ // path for the file being processed
19
+ configOrPath = findAtConfigPath(root, result) ?? configOrPath
20
+
16
21
  let context = setupTrackingContext(configOrPath)
17
22
 
18
23
  if (root.type === 'document') {
@@ -0,0 +1,213 @@
1
+ // @ts-check
2
+
3
+ import fs from 'fs'
4
+ import path from 'path'
5
+ import isGlob from 'is-glob'
6
+ import fastGlob from 'fast-glob'
7
+ import normalizePath from 'normalize-path'
8
+ import { parseGlob } from '../util/parseGlob'
9
+ import { env } from './sharedState'
10
+
11
+ /** @typedef {import('../../types/config.js').RawFile} RawFile */
12
+ /** @typedef {import('../../types/config.js').FilePath} FilePath */
13
+
14
+ /**
15
+ * @typedef {object} ContentPath
16
+ * @property {string} original
17
+ * @property {string} base
18
+ * @property {string | null} glob
19
+ * @property {boolean} ignore
20
+ * @property {string} pattern
21
+ */
22
+
23
+ /**
24
+ * Turn a list of content paths (absolute or not; glob or not) into a list of
25
+ * absolute file paths that exist on the filesystem
26
+ *
27
+ * If there are symlinks in the path then multiple paths will be returned
28
+ * one for the symlink and one for the actual file
29
+ *
30
+ * @param {*} context
31
+ * @param {import('tailwindcss').Config} tailwindConfig
32
+ * @returns {ContentPath[]}
33
+ */
34
+ export function parseCandidateFiles(context, tailwindConfig) {
35
+ let files = tailwindConfig.content.files
36
+
37
+ // Normalize the file globs
38
+ files = files.filter((filePath) => typeof filePath === 'string')
39
+ files = files.map(normalizePath)
40
+
41
+ // Split into included and excluded globs
42
+ let tasks = fastGlob.generateTasks(files)
43
+
44
+ /** @type {ContentPath[]} */
45
+ let included = []
46
+
47
+ /** @type {ContentPath[]} */
48
+ let excluded = []
49
+
50
+ for (const task of tasks) {
51
+ included.push(...task.positive.map((filePath) => parseFilePath(filePath, false)))
52
+ excluded.push(...task.negative.map((filePath) => parseFilePath(filePath, true)))
53
+ }
54
+
55
+ let paths = [...included, ...excluded]
56
+
57
+ // Resolve paths relative to the config file or cwd
58
+ paths = resolveRelativePaths(context, paths)
59
+
60
+ // Resolve symlinks if possible
61
+ paths = paths.flatMap(resolvePathSymlinks)
62
+
63
+ // Update cached patterns
64
+ paths = paths.map(resolveGlobPattern)
65
+
66
+ return paths
67
+ }
68
+
69
+ /**
70
+ *
71
+ * @param {string} filePath
72
+ * @param {boolean} ignore
73
+ * @returns {ContentPath}
74
+ */
75
+ function parseFilePath(filePath, ignore) {
76
+ let contentPath = {
77
+ original: filePath,
78
+ base: filePath,
79
+ ignore,
80
+ pattern: filePath,
81
+ glob: null,
82
+ }
83
+
84
+ if (isGlob(filePath)) {
85
+ Object.assign(contentPath, parseGlob(filePath))
86
+ }
87
+
88
+ return contentPath
89
+ }
90
+
91
+ /**
92
+ *
93
+ * @param {ContentPath} contentPath
94
+ * @returns {ContentPath}
95
+ */
96
+ function resolveGlobPattern(contentPath) {
97
+ // This is required for Windows support to properly pick up Glob paths.
98
+ // Afaik, this technically shouldn't be needed but there's probably
99
+ // some internal, direct path matching with a normalized path in
100
+ // a package which can't handle mixed directory separators
101
+ let base = normalizePath(contentPath.base)
102
+
103
+ // If the user's file path contains any special characters (like parens) for instance fast-glob
104
+ // is like "OOOH SHINY" and treats them as such. So we have to escape the base path to fix this
105
+ base = fastGlob.escapePath(base)
106
+
107
+ contentPath.pattern = contentPath.glob ? `${base}/${contentPath.glob}` : base
108
+ contentPath.pattern = contentPath.ignore ? `!${contentPath.pattern}` : contentPath.pattern
109
+
110
+ return contentPath
111
+ }
112
+
113
+ /**
114
+ * Resolve each path relative to the config file (when possible) if the experimental flag is enabled
115
+ * Otherwise, resolve relative to the current working directory
116
+ *
117
+ * @param {any} context
118
+ * @param {ContentPath[]} contentPaths
119
+ * @returns {ContentPath[]}
120
+ */
121
+ function resolveRelativePaths(context, contentPaths) {
122
+ let resolveFrom = []
123
+
124
+ // Resolve base paths relative to the config file (when possible) if the experimental flag is enabled
125
+ if (context.userConfigPath && context.tailwindConfig.content.relative) {
126
+ resolveFrom = [path.dirname(context.userConfigPath)]
127
+ }
128
+
129
+ return contentPaths.map((contentPath) => {
130
+ contentPath.base = path.resolve(...resolveFrom, contentPath.base)
131
+
132
+ return contentPath
133
+ })
134
+ }
135
+
136
+ /**
137
+ * Resolve the symlink for the base directory / file in each path
138
+ * These are added as additional dependencies to watch for changes because
139
+ * some tools (like webpack) will only watch the actual file or directory
140
+ * but not the symlink itself even in projects that use monorepos.
141
+ *
142
+ * @param {ContentPath} contentPath
143
+ * @returns {ContentPath[]}
144
+ */
145
+ function resolvePathSymlinks(contentPath) {
146
+ let paths = [contentPath]
147
+
148
+ try {
149
+ let resolvedPath = fs.realpathSync(contentPath.base)
150
+ if (resolvedPath !== contentPath.base) {
151
+ paths.push({
152
+ ...contentPath,
153
+ base: resolvedPath,
154
+ })
155
+ }
156
+ } catch {
157
+ // TODO: log this?
158
+ }
159
+
160
+ return paths
161
+ }
162
+
163
+ /**
164
+ * @param {any} context
165
+ * @param {ContentPath[]} candidateFiles
166
+ * @param {Map<string, number>} fileModifiedMap
167
+ * @returns {{ content: string, extension: string }[]}
168
+ */
169
+ export function resolvedChangedContent(context, candidateFiles, fileModifiedMap) {
170
+ let changedContent = context.tailwindConfig.content.files
171
+ .filter((item) => typeof item.raw === 'string')
172
+ .map(({ raw, extension = 'html' }) => ({ content: raw, extension }))
173
+
174
+ for (let changedFile of resolveChangedFiles(candidateFiles, fileModifiedMap)) {
175
+ let content = fs.readFileSync(changedFile, 'utf8')
176
+ let extension = path.extname(changedFile).slice(1)
177
+ changedContent.push({ content, extension })
178
+ }
179
+
180
+ return changedContent
181
+ }
182
+
183
+ /**
184
+ *
185
+ * @param {ContentPath[]} candidateFiles
186
+ * @param {Map<string, number>} fileModifiedMap
187
+ * @returns {Set<string>}
188
+ */
189
+ function resolveChangedFiles(candidateFiles, fileModifiedMap) {
190
+ let paths = candidateFiles.map((contentPath) => contentPath.pattern)
191
+
192
+ let changedFiles = new Set()
193
+ env.DEBUG && console.time('Finding changed files')
194
+ let files = fastGlob.sync(paths, { absolute: true })
195
+ for (let file of files) {
196
+ let prevModified = fileModifiedMap.has(file) ? fileModifiedMap.get(file) : -Infinity
197
+ let modified = fs.statSync(file).mtimeMs
198
+
199
+ // This check is intentionally >= because we track the last modified time of context dependencies
200
+ // earier in the process and we want to make sure we don't miss any changes that happen
201
+ // when a context dependency is also a content dependency
202
+ // Ideally, we'd do all this tracking at one time but that is a larger refactor
203
+ // than we want to commit to right now, so this is a decent compromise.
204
+ // This should be sufficient because file modification times will be off by at least
205
+ // 1ms (the precision of fstat in Node) in most cases if they exist and were changed.
206
+ if (modified >= prevModified) {
207
+ changedFiles.add(file)
208
+ fileModifiedMap.set(file, modified)
209
+ }
210
+ }
211
+ env.DEBUG && console.timeEnd('Finding changed files')
212
+ return changedFiles
213
+ }
@@ -1,42 +1,209 @@
1
- const PATTERNS = [
2
- /(?:\['([^'\s]+[^<>"'`\s:\\])')/.source, // ['text-lg' -> text-lg
3
- /(?:\["([^"\s]+[^<>"'`\s:\\])")/.source, // ["text-lg" -> text-lg
4
- /(?:\[`([^`\s]+[^<>"'`\s:\\])`)/.source, // [`text-lg` -> text-lg
5
- /([^${(<>"'`\s]*\[\w*'[^"`\s]*'?\])/.source, // font-['some_font',sans-serif]
6
- /([^${(<>"'`\s]*\[\w*"[^'`\s]*"?\])/.source, // font-["some_font",sans-serif]
7
- /([^<>"'`\s]*\[\w*\('[^"'`\s]*'\)\])/.source, // bg-[url('...')]
8
- /([^<>"'`\s]*\[\w*\("[^"'`\s]*"\)\])/.source, // bg-[url("...")]
9
- /([^<>"'`\s]*\[\w*\('[^"`\s]*'\)\])/.source, // bg-[url('...'),url('...')]
10
- /([^<>"'`\s]*\[\w*\("[^'`\s]*"\)\])/.source, // bg-[url("..."),url("...")]
11
- /([^<>"'`\s]*\[[^<>"'`\s]*\('[^"`\s]*'\)+\])/.source, // h-[calc(100%-theme('spacing.1'))]
12
- /([^<>"'`\s]*\[[^<>"'`\s]*\("[^'`\s]*"\)+\])/.source, // h-[calc(100%-theme("spacing.1"))]
13
- /([^${(<>"'`\s]*\['[^"'`\s]*'\])/.source, // `content-['hello']` but not `content-['hello']']`
14
- /([^${(<>"'`\s]*\["[^"'`\s]*"\])/.source, // `content-["hello"]` but not `content-["hello"]"]`
15
- /([^<>"'`\s]*\[[^<>"'`\s]*:[^\]\s]*\])/.source, // `[attr:value]`
16
- /([^<>"'`\s]*\[[^<>"'`\s]*:'[^"'`\s]*'\])/.source, // `[content:'hello']` but not `[content:"hello"]`
17
- /([^<>"'`\s]*\[[^<>"'`\s]*:"[^"'`\s]*"\])/.source, // `[content:"hello"]` but not `[content:'hello']`
18
- /([^<>"'`\s]*\[[^"'`\s]+\][^<>"'`\s]*)/.source, // `fill-[#bada55]`, `fill-[#bada55]/50`
19
- /([^"'`\s]*[^<>"'`\s:\\])/.source, // `<sm:underline`, `md>:font-bold`
20
- /([^<>"'`\s]*[^"'`\s:\\])/.source, // `px-1.5`, `uppercase` but not `uppercase:`
21
-
22
- // Arbitrary properties
23
- // /([^"\s]*\[[^\s]+?\][^"\s]*)/.source,
24
- // /([^'\s]*\[[^\s]+?\][^'\s]*)/.source,
25
- // /([^`\s]*\[[^\s]+?\][^`\s]*)/.source,
26
- ].join('|')
27
-
28
- const BROAD_MATCH_GLOBAL_REGEXP = new RegExp(PATTERNS, 'g')
29
- const INNER_MATCH_GLOBAL_REGEXP = /[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g
1
+ import { flagEnabled } from '../featureFlags'
2
+ import * as regex from './regex'
3
+
4
+ export function defaultExtractor(context) {
5
+ let patterns = Array.from(buildRegExps(context))
6
+
7
+ /**
8
+ * @param {string} content
9
+ */
10
+ return (content) => {
11
+ /** @type {(string|string)[]} */
12
+ let results = []
13
+
14
+ for (let pattern of patterns) {
15
+ results = [...results, ...(content.match(pattern) ?? [])]
16
+ }
17
+
18
+ return results.filter((v) => v !== undefined).map(clipAtBalancedParens)
19
+ }
20
+ }
21
+
22
+ function* buildRegExps(context) {
23
+ let separator = context.tailwindConfig.separator
24
+ let variantGroupingEnabled = flagEnabled(context.tailwindConfig, 'variantGrouping')
25
+ let prefix =
26
+ context.tailwindConfig.prefix !== ''
27
+ ? regex.optional(regex.pattern([/-?/, regex.escape(context.tailwindConfig.prefix)]))
28
+ : ''
29
+
30
+ let utility = regex.any([
31
+ // Arbitrary properties (without square brackets)
32
+ /\[[^\s:'"`]+:[^\s\[\]]+\]/,
33
+
34
+ // Arbitrary properties with balanced square brackets
35
+ // This is a targeted fix to continue to allow theme()
36
+ // with square brackets to work in arbitrary properties
37
+ // while fixing a problem with the regex matching too much
38
+ /\[[^\s:'"`]+:[^\s]+?\[[^\s]+?\][^\s]+?\]/,
39
+
40
+ // Utilities
41
+ regex.pattern([
42
+ // Utility Name / Group Name
43
+ /-?(?:\w+)/,
44
+
45
+ // Normal/Arbitrary values
46
+ regex.optional(
47
+ regex.any([
48
+ regex.pattern([
49
+ // Arbitrary values
50
+ /-(?:\w+-)*\[[^\s:]+\]/,
51
+
52
+ // Not immediately followed by an `{[(`
53
+ /(?![{([]])/,
54
+
55
+ // optionally followed by an opacity modifier
56
+ /(?:\/[^\s'"`\\><$]*)?/,
57
+ ]),
58
+
59
+ regex.pattern([
60
+ // Arbitrary values
61
+ /-(?:\w+-)*\[[^\s]+\]/,
62
+
63
+ // Not immediately followed by an `{[(`
64
+ /(?![{([]])/,
65
+
66
+ // optionally followed by an opacity modifier
67
+ /(?:\/[^\s'"`\\$]*)?/,
68
+ ]),
69
+
70
+ // Normal values w/o quotes — may include an opacity modifier
71
+ /[-\/][^\s'"`\\$={><]*/,
72
+ ])
73
+ ),
74
+ ]),
75
+ ])
76
+
77
+ let variantPatterns = [
78
+ // Without quotes
79
+ regex.any([
80
+ // This is here to provide special support for the `@` variant
81
+ regex.pattern([/@\[[^\s"'`]+\](\/[^\s"'`]+)?/, separator]),
82
+
83
+ regex.pattern([/([^\s"'`\[\\]+-)?\[[^\s"'`]+\]/, separator]),
84
+ regex.pattern([/[^\s"'`\[\\]+/, separator]),
85
+ ]),
86
+
87
+ // With quotes allowed
88
+ regex.any([
89
+ regex.pattern([/([^\s"'`\[\\]+-)?\[[^\s`]+\]/, separator]),
90
+ regex.pattern([/[^\s`\[\\]+/, separator]),
91
+ ]),
92
+ ]
93
+
94
+ for (const variantPattern of variantPatterns) {
95
+ yield regex.pattern([
96
+ // Variants
97
+ '((?=((',
98
+ variantPattern,
99
+ ')+))\\2)?',
100
+
101
+ // Important (optional)
102
+ /!?/,
103
+
104
+ prefix,
105
+
106
+ variantGroupingEnabled
107
+ ? regex.any([
108
+ // Or any of those things but grouped separated by commas
109
+ regex.pattern([/\(/, utility, regex.zeroOrMore([/,/, utility]), /\)/]),
110
+
111
+ // Arbitrary properties, constrained utilities, arbitrary values, etc…
112
+ utility,
113
+ ])
114
+ : utility,
115
+ ])
116
+ }
117
+
118
+ // 5. Inner matches
119
+ yield /[^<>"'`\s.(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g
120
+ }
121
+
122
+ // We want to capture any "special" characters
123
+ // AND the characters immediately following them (if there is one)
124
+ let SPECIALS = /([\[\]'"`])([^\[\]'"`])?/g
125
+ let ALLOWED_CLASS_CHARACTERS = /[^"'`\s<>\]]+/
30
126
 
31
127
  /**
32
- * @param {string} content
128
+ * Clips a string ensuring that parentheses, quotes, etc… are balanced
129
+ * Used for arbitrary values only
130
+ *
131
+ * We will go past the end of the balanced parens until we find a non-class character
132
+ *
133
+ * Depth matching behavior:
134
+ * w-[calc(100%-theme('spacing[some_key][1.5]'))]']
135
+ * ┬ ┬ ┬┬ ┬ ┬┬ ┬┬┬┬┬┬┬
136
+ * 1 2 3 4 34 3 210 END
137
+ * ╰────┴──────────┴────────┴────────┴┴───┴─┴┴┴
138
+ *
139
+ * @param {string} input
33
140
  */
34
- export function defaultExtractor(content) {
35
- let broadMatches = content.matchAll(BROAD_MATCH_GLOBAL_REGEXP)
36
- let innerMatches = content.match(INNER_MATCH_GLOBAL_REGEXP) || []
37
- let results = [...broadMatches, ...innerMatches].flat().filter((v) => v !== undefined)
141
+ function clipAtBalancedParens(input) {
142
+ // We are care about this for arbitrary values
143
+ if (!input.includes('-[')) {
144
+ return input
145
+ }
146
+
147
+ let depth = 0
148
+ let openStringTypes = []
149
+
150
+ // Find all parens, brackets, quotes, etc
151
+ // Stop when we end at a balanced pair
152
+ // This is naive and will treat mismatched parens as balanced
153
+ // This shouldn't be a problem in practice though
154
+ let matches = input.matchAll(SPECIALS)
155
+
156
+ // We can't use lookbehind assertions because we have to support Safari
157
+ // So, instead, we've emulated it using capture groups and we'll re-work the matches to accommodate
158
+ matches = Array.from(matches).flatMap((match) => {
159
+ const [, ...groups] = match
160
+
161
+ return groups.map((group, idx) =>
162
+ Object.assign([], match, {
163
+ index: match.index + idx,
164
+ 0: group,
165
+ })
166
+ )
167
+ })
168
+
169
+ for (let match of matches) {
170
+ let char = match[0]
171
+ let inStringType = openStringTypes[openStringTypes.length - 1]
172
+
173
+ if (char === inStringType) {
174
+ openStringTypes.pop()
175
+ } else if (char === "'" || char === '"' || char === '`') {
176
+ openStringTypes.push(char)
177
+ }
178
+
179
+ if (inStringType) {
180
+ continue
181
+ } else if (char === '[') {
182
+ depth++
183
+ continue
184
+ } else if (char === ']') {
185
+ depth--
186
+ continue
187
+ }
188
+
189
+ // We've gone one character past the point where we should stop
190
+ // This means that there was an extra closing `]`
191
+ // We'll clip to just before it
192
+ if (depth < 0) {
193
+ return input.substring(0, match.index - 1)
194
+ }
195
+
196
+ // We've finished balancing the brackets but there still may be characters that can be included
197
+ // For example in the class `text-[#336699]/[.35]`
198
+ // The depth goes to `0` at the closing `]` but goes up again at the `[`
199
+
200
+ // If we're at zero and encounter a non-class character then we clip the class there
201
+ if (depth === 0 && !ALLOWED_CLASS_CHARACTERS.test(char)) {
202
+ return input.substring(0, match.index)
203
+ }
204
+ }
38
205
 
39
- return results
206
+ return input
40
207
  }
41
208
 
42
209
  // Regular utilities
@@ -1,3 +1,11 @@
1
+ function isRoot(node) {
2
+ return node.type === 'root'
3
+ }
4
+
5
+ function isAtLayer(node) {
6
+ return node.type === 'atrule' && node.name === 'layer'
7
+ }
8
+
1
9
  export default function (_context) {
2
10
  return (root, result) => {
3
11
  let found = false
@@ -5,7 +13,7 @@ export default function (_context) {
5
13
  root.walkAtRules('tailwind', (node) => {
6
14
  if (found) return false
7
15
 
8
- if (node.parent && node.parent.type !== 'root') {
16
+ if (node.parent && !(isRoot(node.parent) || isAtLayer(node.parent))) {
9
17
  found = true
10
18
  node.warn(
11
19
  result,
@@ -5,6 +5,9 @@ import parseValue from 'postcss-value-parser'
5
5
  import { normalizeScreens } from '../util/normalizeScreens'
6
6
  import buildMediaQuery from '../util/buildMediaQuery'
7
7
  import { toPath } from '../util/toPath'
8
+ import { withAlphaValue } from '../util/withAlphaVariable'
9
+ import { parseColorFormat } from '../util/pluginUtils'
10
+ import log from '../util/log'
8
11
 
9
12
  function isObject(input) {
10
13
  return typeof input === 'object' && input !== null
@@ -37,10 +40,8 @@ function listKeys(obj) {
37
40
  return list(Object.keys(obj))
38
41
  }
39
42
 
40
- function validatePath(config, path, defaultValue) {
41
- const pathString = Array.isArray(path)
42
- ? pathToString(path)
43
- : path.replace(/^['"]+/g, '').replace(/['"]+$/g, '')
43
+ function validatePath(config, path, defaultValue, themeOpts = {}) {
44
+ const pathString = Array.isArray(path) ? pathToString(path) : path.replace(/^['"]+|['"]+$/g, '')
44
45
  const pathSegments = Array.isArray(path) ? path : toPath(pathString)
45
46
  const value = dlv(config.theme, pathSegments, defaultValue)
46
47
 
@@ -114,7 +115,7 @@ function validatePath(config, path, defaultValue) {
114
115
 
115
116
  return {
116
117
  isValid: true,
117
- value: transformThemeValue(themeSection)(value),
118
+ value: transformThemeValue(themeSection)(value, themeOpts),
118
119
  }
119
120
  }
120
121
 
@@ -157,19 +158,89 @@ let nodeTypePropertyMap = {
157
158
  decl: 'value',
158
159
  }
159
160
 
160
- export default function ({ tailwindConfig: config }) {
161
+ /**
162
+ * @param {string} path
163
+ * @returns {Iterable<[path: string, alpha: string|undefined]>}
164
+ */
165
+ function* toPaths(path) {
166
+ // Strip quotes from beginning and end of string
167
+ // This allows the alpha value to be present inside of quotes
168
+ path = path.replace(/^['"]+|['"]+$/g, '')
169
+
170
+ let matches = path.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/)
171
+ let alpha = undefined
172
+
173
+ yield [path, undefined]
174
+
175
+ if (matches) {
176
+ path = matches[1]
177
+ alpha = matches[2]
178
+
179
+ yield [path, alpha]
180
+ }
181
+ }
182
+
183
+ /**
184
+ *
185
+ * @param {any} config
186
+ * @param {string} path
187
+ * @param {any} defaultValue
188
+ */
189
+ function resolvePath(config, path, defaultValue) {
190
+ const results = Array.from(toPaths(path)).map(([path, alpha]) => {
191
+ return Object.assign(validatePath(config, path, defaultValue, { opacityValue: alpha }), {
192
+ resolvedPath: path,
193
+ alpha,
194
+ })
195
+ })
196
+
197
+ return results.find((result) => result.isValid) ?? results[0]
198
+ }
199
+
200
+ export default function (context) {
201
+ let config = context.tailwindConfig
202
+
161
203
  let functions = {
162
204
  theme: (node, path, ...defaultValue) => {
163
- const { isValid, value, error } = validatePath(
205
+ let { isValid, value, error, alpha } = resolvePath(
164
206
  config,
165
207
  path,
166
208
  defaultValue.length ? defaultValue : undefined
167
209
  )
168
210
 
169
211
  if (!isValid) {
212
+ let parentNode = node.parent
213
+ let candidate = parentNode?.raws.tailwind?.candidate
214
+
215
+ if (parentNode && candidate !== undefined) {
216
+ // Remove this utility from any caches
217
+ context.markInvalidUtilityNode(parentNode)
218
+
219
+ // Remove the CSS node from the markup
220
+ parentNode.remove()
221
+
222
+ // Show a warning
223
+ log.warn('invalid-theme-key-in-class', [
224
+ `The utility \`${candidate}\` contains an invalid theme value and was not generated.`,
225
+ ])
226
+
227
+ return
228
+ }
229
+
170
230
  throw node.error(error)
171
231
  }
172
232
 
233
+ let maybeColor = parseColorFormat(value)
234
+ let isColorFunction = maybeColor !== undefined && typeof maybeColor === 'function'
235
+
236
+ if (alpha !== undefined || isColorFunction) {
237
+ if (alpha === undefined) {
238
+ alpha = 1.0
239
+ }
240
+
241
+ value = withAlphaValue(maybeColor, alpha, maybeColor)
242
+ }
243
+
173
244
  return value
174
245
  },
175
246
  screen: (node, screen) => {