All files / packages/sds-metadata/src/processors/decl-processors styling-hooks-processor.ts

0% Statements 0/20
0% Branches 0/4
0% Functions 0/2
0% Lines 0/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                                                                                                                                           
import { Declaration } from "postcss";
import { DeclarationProcessor } from "../../types.js";
import valueParser from "postcss-value-parser";
 
export type StylingHooksProcessorResults = Record<string, string[]>;
 
export class StylingHooksProcessor
  implements DeclarationProcessor<StylingHooksProcessorResults>
{
  private readonly stylingHooksMap = {
    global: new Set<string>(),
    component: new Set<string>(),
    shared: new Set<string>(),
    kinetics: new Set<string>(),
  };
 
  private readonly TOKEN_REGEX =
    /--(?:c|slds|sds|lwc)-(?<type>g|s|c|kx)-[-\w]*/;
 
  private resolveTokenType(token: string) {
    const match = token.match(this.TOKEN_REGEX);
    return match?.groups?.type;
  }
 
  resolveTokenName(token: string) {
    const tokenType = this.resolveTokenType(token);
    if (tokenType) {
      this.addTokenToMap(tokenType, token);
    }
  }
 
  processDeclaration(declaration: Declaration) {
    // Parse the prop of the tokens
    this.resolveTokenName(declaration.prop);
    // Parse the value of the tokens
    const value = valueParser(declaration.value);
    value.walk((node) => {
      if (node.type === "word") {
        this.resolveTokenName(node.value);
      }
    });
  }
 
  private addTokenToMap(type: string, token: string) {
    switch (type) {
      case "g":
        this.stylingHooksMap.global.add(token);
        break;
      case "s":
        this.stylingHooksMap.shared.add(token);
        break;
      case "c":
        this.stylingHooksMap.component.add(token);
        break;
      case "kx":
        this.stylingHooksMap.kinetics.add(token);
        break;
    }
  }
 
  getResults(): StylingHooksProcessorResults {
    return Object.fromEntries(
      Object.entries(this.stylingHooksMap).map(([key, value]) => [
        key,
        Array.from(value),
      ])
    );
  }
}