๐Ÿ“ฆ situ2001 / scoped-rem

๐Ÿ“„ index.ts ยท 178 lines
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178import postcss from 'postcss';
import valueParser from 'postcss-value-parser';
import { z } from 'zod';

/**
 * Core idea of scoped-rem:
 * 1. Transform rem values `x rem` to `calc(x * var(--varname))`
 *    1. `x` is the original rem value
 *    2. `varname` is a CSS variable name without `--` prefix, default `rem-relative-base`
 *    3. `x` will be rounded to a specified `precision` if provided
 * 2. (Skipped if `rootval` is not provided) Declare the CSS variable `--varname` in a specified scope `varselector` with a relative root value `rootval`
 */
export interface ScopedRemOptions {
  /** 
   * CSS variable name used for rem conversion, default '--rem-relative-base' 
   * 
   * e.g., 'my-base', then rem value will be converted to 'calc(x * var(--my-base))'
   */
  varname?: string;

  /** 
   * Relative root value of rem, e.g., '26.6667vw'
   *
   * If not provided, the loader will skip variable declaration generation,
   * but rem values will still be transformed to calc() with CSS variables.
   * This is useful when developers want to declare the CSS variable manually elsewhere (e.g., in a global stylesheet).
   */
  rootval?: string;

  /**
   * Scope selector for the CSS variable, default ':root'
   * 
   * e.g., '.my-component' will generate:
   * ```
   * .my-component { --rem-relative-base: 26.6667vw; }
   * ```
   * instead of
   * ```
   * :root { --rem-relative-base: 26.6667vw; }
   * ```
   * which limits the variable to the specified scope.
   */
  varselector?: string;

  /**
   * Number of decimal places to round the converted rem values, default is no rounding.
   */
  precision?: number;
}

export const VARNAME_DEFAULT = 'rem-relative-base';
export const VARSELECTOR_DEFAULT = ':root';

const ScopedRemOptionsSchema: z.ZodType<ScopedRemOptions> = z.object({
  varname: z.string().optional().default(VARNAME_DEFAULT),
  rootval: z.string().optional(),
  varselector: z.string().optional().default(VARSELECTOR_DEFAULT),
  precision: z.coerce.number().int().min(0).max(100).optional(),
});

export function parseQueryOptions(query: string): ScopedRemOptions | null {
  const params = new URLSearchParams(query);
  if (!params.has('rem-scoped')) {
    return null;
  }

  const rawOptions: Record<string, string | undefined> = {
    varname: params.get('varname') || undefined,
    rootval: params.get('rootval') || undefined,
    varselector: params.get('varselector') || undefined,
    precision: params.get('precision') || undefined,
  };

  try {
    const options = ScopedRemOptionsSchema.parse(rawOptions);
    return options as ScopedRemOptions;
  } catch (error) {
    if (error instanceof z.ZodError) {
      throw new Error(
        `[scoped-rem] Invalid query options: ${error.issues.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ')}`
      );
    }
    throw error;
  }
}

function generateCssVarDeclaration(options: ScopedRemOptions): string {
  const { rootval } = options;

  if (!rootval) {
    return '';
  }

  // TODO detect var conflicts?
  const varname = options.varname || VARNAME_DEFAULT;
  const scope = options.varselector || VARSELECTOR_DEFAULT;

  return `${scope} { --${varname}: ${rootval}; }`;
}

// https://github.com/cuth/postcss-pxtorem/blob/239fc3a1ab3ecbc63d1b9f98dd380abd49c03309/lib/pixel-unit-regex.js#L9-L13
const remRegex = /"[^"]+"|'[^']+'|url\([^)]+\)|--[\w-]+|(-?\d*\.?\d+)rem/gi;

/**
 * @param css CSS source code
 * @param filename will be passed to PostCSS
 * @returns The transformed CSS
 */
function transformRemWithPostCSS(
  css: string,
  filename: string,
  options: ScopedRemOptions
): string {
  const varname = options.varname || VARNAME_DEFAULT;

  const result = postcss([
    {
      postcssPlugin: 'scoped-rem-transform',
      Declaration(decl) {
        const parsed = valueParser(decl.value);

        let modified = false;
        parsed.walk((node) => {
          if (node.type === 'word' && node.value.endsWith('rem')) {
            const numStr = node.value.match(remRegex)?.[0];
            if (!numStr) {
              return;
            }

            const numValue: number = (() => {
              if (options.precision !== undefined) {
                if (options.precision < 0 || options.precision > 100) {
                  throw new Error(
                    `[scoped-rem] Invalid precision value: ${options.precision}. It should be between 0 and 100.`
                  );
                }

                return parseFloat(
                  (parseFloat(numStr) || 0).toFixed(options.precision)
                );
              } else {
                return parseFloat(numStr) || 0;
              }
            })();

            if (numValue === 0) {
              node.value = '0';
              modified = true;
              return;
            }

            node.value = `calc(${numValue} * var(--${varname}))`;
            modified = true;
          }
        });

        if (modified) {
          decl.value = parsed.toString();
        }
      },
    },
  ]).process(css, { from: filename }).css;

  return result;
}

export function transformCss(
  css: string,
  filename: string,
  options: ScopedRemOptions
): string {
  const varDeclaration = generateCssVarDeclaration(options);
  const transformedCss = transformRemWithPostCSS(css, filename, options);

  if (!varDeclaration) return transformedCss;
  return `${varDeclaration}\n${transformedCss}`;
}