index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const { isVElement } = require('..')
  2. class StyleVariablesContext {
  3. /**
  4. * @param {RuleContext} context
  5. * @param {VElement[]} styles
  6. */
  7. constructor(context, styles) {
  8. this.context = context
  9. this.styles = styles
  10. /** @type {VReference[]} */
  11. this.references = []
  12. /** @type {VExpressionContainer[]} */
  13. this.vBinds = []
  14. for (const style of styles) {
  15. for (const node of style.children) {
  16. if (node.type === 'VExpressionContainer') {
  17. this.vBinds.push(node)
  18. for (const ref of node.references.filter(
  19. (ref) => ref.variable == null
  20. )) {
  21. this.references.push(ref)
  22. }
  23. }
  24. }
  25. }
  26. }
  27. }
  28. module.exports = {
  29. getStyleVariablesContext,
  30. StyleVariablesContext
  31. }
  32. /** @type {WeakMap<VElement, StyleVariablesContext>} */
  33. const cache = new WeakMap()
  34. /**
  35. * Get the style vars context
  36. * @param {RuleContext} context
  37. * @returns {StyleVariablesContext | null}
  38. */
  39. function getStyleVariablesContext(context) {
  40. const df =
  41. context.parserServices.getDocumentFragment &&
  42. context.parserServices.getDocumentFragment()
  43. if (!df) {
  44. return null
  45. }
  46. const styles = df.children
  47. .filter(isVElement)
  48. .filter((e) => e.name === 'style')
  49. if (!styles.length) {
  50. return null
  51. }
  52. let ctx = cache.get(styles[0])
  53. if (ctx) {
  54. return ctx
  55. }
  56. ctx = new StyleVariablesContext(context, styles)
  57. cache.set(styles[0], ctx)
  58. return ctx
  59. }