2
0

pluginScoped.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. // insert a space combinator before if it doesn't already have one
  130. const prev = selector.at(selector.index(n) - 1)
  131. if (!prev || !isSpaceCombinator(prev)) {
  132. selector.insertAfter(
  133. n,
  134. selectorParser.combinator({
  135. value: ' ',
  136. }),
  137. )
  138. }
  139. selector.removeChild(n)
  140. } else {
  141. // DEPRECATED usage
  142. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  143. warn(
  144. `${value} usage as a combinator has been deprecated. ` +
  145. `Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`,
  146. )
  147. const prev = selector.at(selector.index(n) - 1)
  148. if (prev && isSpaceCombinator(prev)) {
  149. selector.removeChild(prev)
  150. }
  151. selector.removeChild(n)
  152. }
  153. return false
  154. }
  155. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  156. // instead.
  157. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  158. if (value === ':slotted' || value === '::v-slotted') {
  159. rewriteSelector(
  160. id,
  161. rule,
  162. n.nodes[0],
  163. selectorRoot,
  164. deep,
  165. true /* slotted */,
  166. )
  167. let last: selectorParser.Selector['nodes'][0] = n
  168. n.nodes[0].each(ss => {
  169. selector.insertAfter(last, ss)
  170. last = ss
  171. })
  172. // selector.insertAfter(n, n.nodes[0])
  173. selector.removeChild(n)
  174. // since slotted attribute already scopes the selector there's no
  175. // need for the non-slot attribute.
  176. shouldInject = false
  177. return false
  178. }
  179. // global: replace with inner selector and do not inject [id].
  180. // ::v-global(.foo) -> .foo
  181. if (value === ':global' || value === '::v-global') {
  182. selector.replaceWith(n.nodes[0])
  183. return false
  184. }
  185. }
  186. if (n.type === 'universal') {
  187. const prev = selector.at(selector.index(n) - 1)
  188. const next = selector.at(selector.index(n) + 1)
  189. // * ... {}
  190. if (!prev) {
  191. // * .foo {} -> .foo[xxxxxxx] {}
  192. if (next) {
  193. if (next.type === 'combinator' && next.value === ' ') {
  194. selector.removeChild(next)
  195. }
  196. selector.removeChild(n)
  197. return
  198. } else {
  199. // * {} -> [xxxxxxx] {}
  200. node = selectorParser.combinator({
  201. value: '',
  202. })
  203. selector.insertBefore(n, node)
  204. selector.removeChild(n)
  205. return false
  206. }
  207. }
  208. // .foo * -> .foo[xxxxxxx] *
  209. if (node) return
  210. }
  211. if (
  212. (n.type !== 'pseudo' && n.type !== 'combinator') ||
  213. (n.type === 'pseudo' &&
  214. (n.value === ':is' || n.value === ':where') &&
  215. !node)
  216. ) {
  217. node = n
  218. }
  219. })
  220. if (rule.nodes.some(node => node.type === 'rule')) {
  221. const deep = (rule as any).__deep
  222. if (!deep) {
  223. extractAndWrapNodes(rule)
  224. const atruleNodes = rule.nodes.filter(node => node.type === 'atrule')
  225. for (const atnode of atruleNodes) {
  226. extractAndWrapNodes(atnode)
  227. }
  228. }
  229. shouldInject = deep
  230. }
  231. if (node) {
  232. const { type, value } = node as selectorParser.Node
  233. if (type === 'pseudo' && (value === ':is' || value === ':where')) {
  234. ;(node as selectorParser.Pseudo).nodes.forEach(value =>
  235. rewriteSelector(id, rule, value, selectorRoot, deep, slotted),
  236. )
  237. shouldInject = false
  238. }
  239. }
  240. if (node) {
  241. ;(node as selectorParser.Node).spaces.after = ''
  242. } else {
  243. // For deep selectors & standalone pseudo selectors,
  244. // the attribute selectors are prepended rather than appended.
  245. // So all leading spaces must be eliminated to avoid problems.
  246. selector.first.spaces.before = ''
  247. }
  248. if (shouldInject) {
  249. const idToAdd = slotted ? id + '-s' : id
  250. selector.insertAfter(
  251. // If node is null it means we need to inject [id] at the start
  252. // insertAfter can handle `null` here
  253. node as any,
  254. selectorParser.attribute({
  255. attribute: idToAdd,
  256. value: idToAdd,
  257. raws: {},
  258. quoteMark: `"`,
  259. }),
  260. )
  261. }
  262. }
  263. function isSpaceCombinator(node: selectorParser.Node) {
  264. return node.type === 'combinator' && /^\s+$/.test(node.value)
  265. }
  266. function extractAndWrapNodes(parentNode: Rule | AtRule) {
  267. if (!parentNode.nodes) return
  268. const nodes = parentNode.nodes.filter(
  269. node => node.type === 'decl' || node.type === 'comment',
  270. )
  271. if (nodes.length) {
  272. for (const node of nodes) {
  273. parentNode.removeChild(node)
  274. }
  275. const wrappedRule = new Rule({
  276. nodes: nodes,
  277. selector: '&',
  278. })
  279. parentNode.prepend(wrappedRule)
  280. }
  281. }
  282. scopedPlugin.postcss = true
  283. export default scopedPlugin