pluginScoped.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import {
  2. type AtRule,
  3. type Container,
  4. type Document,
  5. type PluginCreator,
  6. Rule,
  7. } from 'postcss'
  8. import selectorParser from 'postcss-selector-parser'
  9. import { warn } from '../warn'
  10. const animationNameRE = /^(-\w+-)?animation-name$/
  11. const animationRE = /^(-\w+-)?animation$/
  12. const scopedPlugin: PluginCreator<string> = (id = '') => {
  13. const keyframes = Object.create(null)
  14. const shortId = id.replace(/^data-v-/, '')
  15. return {
  16. postcssPlugin: 'vue-sfc-scoped',
  17. Rule(rule) {
  18. processRule(id, rule)
  19. },
  20. AtRule(node) {
  21. if (
  22. /-?keyframes$/.test(node.name) &&
  23. !node.params.endsWith(`-${shortId}`)
  24. ) {
  25. // register keyframes
  26. keyframes[node.params] = node.params = node.params + '-' + shortId
  27. }
  28. },
  29. OnceExit(root) {
  30. if (Object.keys(keyframes).length) {
  31. // If keyframes are found in this <style>, find and rewrite animation names
  32. // in declarations.
  33. // Caveat: this only works for keyframes and animation rules in the same
  34. // <style> element.
  35. // individual animation-name declaration
  36. root.walkDecls(decl => {
  37. if (animationNameRE.test(decl.prop)) {
  38. decl.value = decl.value
  39. .split(',')
  40. .map(v => keyframes[v.trim()] || v.trim())
  41. .join(',')
  42. }
  43. // shorthand
  44. if (animationRE.test(decl.prop)) {
  45. decl.value = decl.value
  46. .split(',')
  47. .map(v => {
  48. const vals = v.trim().split(/\s+/)
  49. const i = vals.findIndex(val => keyframes[val])
  50. if (i !== -1) {
  51. vals.splice(i, 1, keyframes[vals[i]])
  52. return vals.join(' ')
  53. } else {
  54. return v
  55. }
  56. })
  57. .join(',')
  58. }
  59. })
  60. }
  61. },
  62. }
  63. }
  64. const processedRules = new WeakSet<Rule>()
  65. function processRule(id: string, rule: Rule) {
  66. if (
  67. processedRules.has(rule) ||
  68. (rule.parent &&
  69. rule.parent.type === 'atrule' &&
  70. /-?keyframes$/.test((rule.parent as AtRule).name))
  71. ) {
  72. return
  73. }
  74. processedRules.add(rule)
  75. let deep = false
  76. let parent: Document | Container | undefined = rule.parent
  77. while (parent && parent.type !== 'root') {
  78. if ((parent as any).__deep) {
  79. deep = true
  80. break
  81. }
  82. parent = parent.parent
  83. }
  84. rule.selector = selectorParser(selectorRoot => {
  85. selectorRoot.each(selector => {
  86. rewriteSelector(id, rule, selector, selectorRoot, deep)
  87. })
  88. }).processSync(rule.selector)
  89. }
  90. function rewriteSelector(
  91. id: string,
  92. rule: Rule,
  93. selector: selectorParser.Selector,
  94. selectorRoot: selectorParser.Root,
  95. deep: boolean,
  96. slotted = false,
  97. ) {
  98. let node: selectorParser.Node | null = null
  99. let shouldInject = !deep
  100. // find the last child node to insert attribute selector
  101. selector.each(n => {
  102. // DEPRECATED ">>>" and "/deep/" combinator
  103. if (
  104. n.type === 'combinator' &&
  105. (n.value === '>>>' || n.value === '/deep/')
  106. ) {
  107. n.value = ' '
  108. n.spaces.before = n.spaces.after = ''
  109. warn(
  110. `the >>> and /deep/ combinators have been deprecated. ` +
  111. `Use :deep() instead.`,
  112. )
  113. return false
  114. }
  115. if (n.type === 'pseudo') {
  116. const { value } = n
  117. // deep: inject [id] attribute at the node before the ::v-deep
  118. // combinator.
  119. if (value === ':deep' || value === '::v-deep') {
  120. ;(rule as any).__deep = true
  121. if (n.nodes.length) {
  122. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  123. // replace the current node with ::v-deep's inner selector
  124. let last: selectorParser.Selector['nodes'][0] = n
  125. n.nodes[0].each(ss => {
  126. selector.insertAfter(last, ss)
  127. last = ss
  128. })
  129. // if css nesting is used, we need to insert a nesting selector
  130. // before the ::v-deep's inner selector.
  131. // .foo { ::v-deep(.bar) } -> .foo { &[xxxxxxx] .bar }
  132. const isNestedRule = rule.parent && rule.parent.type === 'rule'
  133. if (isNestedRule && n.parent) {
  134. const hasNestingSelector = n.parent.nodes
  135. .slice(0, n.parent.index(n))
  136. .some(node => node.type === 'nesting')
  137. if (!hasNestingSelector) {
  138. node = selectorParser.nesting()
  139. selector.insertBefore(n, node)
  140. }
  141. }
  142. // insert a space combinator before if it doesn't already have one
  143. const prev = selector.at(selector.index(n) - 1)
  144. if (!prev || !isSpaceCombinator(prev)) {
  145. selector.insertAfter(
  146. n,
  147. selectorParser.combinator({
  148. value: ' ',
  149. }),
  150. )
  151. }
  152. selector.removeChild(n)
  153. } else {
  154. // DEPRECATED usage
  155. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  156. warn(
  157. `${value} usage as a combinator has been deprecated. ` +
  158. `Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`,
  159. )
  160. const prev = selector.at(selector.index(n) - 1)
  161. if (prev && isSpaceCombinator(prev)) {
  162. selector.removeChild(prev)
  163. }
  164. selector.removeChild(n)
  165. }
  166. return false
  167. }
  168. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  169. // instead.
  170. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  171. if (value === ':slotted' || value === '::v-slotted') {
  172. rewriteSelector(
  173. id,
  174. rule,
  175. n.nodes[0],
  176. selectorRoot,
  177. deep,
  178. true /* slotted */,
  179. )
  180. let last: selectorParser.Selector['nodes'][0] = n
  181. n.nodes[0].each(ss => {
  182. selector.insertAfter(last, ss)
  183. last = ss
  184. })
  185. // selector.insertAfter(n, n.nodes[0])
  186. selector.removeChild(n)
  187. // since slotted attribute already scopes the selector there's no
  188. // need for the non-slot attribute.
  189. shouldInject = false
  190. return false
  191. }
  192. // global: replace with inner selector and do not inject [id].
  193. // ::v-global(.foo) -> .foo
  194. if (value === ':global' || value === '::v-global') {
  195. selector.replaceWith(n.nodes[0])
  196. return false
  197. }
  198. }
  199. if (n.type === 'universal') {
  200. const prev = selector.at(selector.index(n) - 1)
  201. const next = selector.at(selector.index(n) + 1)
  202. // * ... {}
  203. if (!prev) {
  204. // * .foo {} -> .foo[xxxxxxx] {}
  205. if (next) {
  206. if (next.type === 'combinator' && next.value === ' ') {
  207. selector.removeChild(next)
  208. }
  209. selector.removeChild(n)
  210. return
  211. } else {
  212. // * {} -> [xxxxxxx] {}
  213. node = selectorParser.combinator({
  214. value: '',
  215. })
  216. selector.insertBefore(n, node)
  217. selector.removeChild(n)
  218. return false
  219. }
  220. }
  221. // .foo * -> .foo[xxxxxxx] *
  222. if (node) return
  223. }
  224. if (
  225. (n.type !== 'pseudo' && n.type !== 'combinator') ||
  226. (n.type === 'pseudo' &&
  227. (n.value === ':is' || n.value === ':where') &&
  228. !node)
  229. ) {
  230. node = n
  231. }
  232. })
  233. if (rule.nodes.some(node => node.type === 'rule')) {
  234. const deep = (rule as any).__deep
  235. if (!deep) {
  236. extractAndWrapNodes(rule)
  237. const atruleNodes = rule.nodes.filter(node => node.type === 'atrule')
  238. for (const atnode of atruleNodes) {
  239. extractAndWrapNodes(atnode)
  240. }
  241. }
  242. shouldInject = deep
  243. }
  244. if (node) {
  245. const { type, value } = node as selectorParser.Node
  246. if (type === 'pseudo' && (value === ':is' || value === ':where')) {
  247. ;(node as selectorParser.Pseudo).nodes.forEach(value =>
  248. rewriteSelector(id, rule, value, selectorRoot, deep, slotted),
  249. )
  250. shouldInject = false
  251. }
  252. }
  253. if (node) {
  254. ;(node as selectorParser.Node).spaces.after = ''
  255. } else {
  256. // For deep selectors & standalone pseudo selectors,
  257. // the attribute selectors are prepended rather than appended.
  258. // So all leading spaces must be eliminated to avoid problems.
  259. selector.first.spaces.before = ''
  260. }
  261. if (shouldInject) {
  262. const idToAdd = slotted ? id + '-s' : id
  263. selector.insertAfter(
  264. // If node is null it means we need to inject [id] at the start
  265. // insertAfter can handle `null` here
  266. node as any,
  267. selectorParser.attribute({
  268. attribute: idToAdd,
  269. value: idToAdd,
  270. raws: {},
  271. quoteMark: `"`,
  272. }),
  273. )
  274. }
  275. }
  276. function isSpaceCombinator(node: selectorParser.Node) {
  277. return node.type === 'combinator' && /^\s+$/.test(node.value)
  278. }
  279. function extractAndWrapNodes(parentNode: Rule | AtRule) {
  280. if (!parentNode.nodes) return
  281. const nodes = parentNode.nodes.filter(
  282. node => node.type === 'decl' || node.type === 'comment',
  283. )
  284. if (nodes.length) {
  285. for (const node of nodes) {
  286. parentNode.removeChild(node)
  287. }
  288. const wrappedRule = new Rule({
  289. nodes: nodes,
  290. selector: '&',
  291. })
  292. parentNode.prepend(wrappedRule)
  293. }
  294. }
  295. scopedPlugin.postcss = true
  296. export default scopedPlugin