|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import {inject, Injectable} from '@angular/core'; |
| 10 | +import {CSS_VAR_NAMESPACE} from './dom_renderer'; |
| 11 | + |
| 12 | +/** |
| 13 | + * A service that can be used to manually namespace CSS variable names at runtime. |
| 14 | + * This is useful when reading or setting CSS variables dynamically in JavaScript that |
| 15 | + * were transformed by the compiler during the build. |
| 16 | + * |
| 17 | + * @publicApi |
| 18 | + */ |
| 19 | +@Injectable({providedIn: 'root'}) |
| 20 | +export class CssVarNamespacer { |
| 21 | + private readonly namespacePrefix = inject(CSS_VAR_NAMESPACE, {optional: true}) ?? ''; |
| 22 | + |
| 23 | + /** |
| 24 | + * Prepends the namespace prefix to a CSS variable name. |
| 25 | + * |
| 26 | + * @param name The CSS variable name to namespace, including the leading `--`. |
| 27 | + * @returns The namespaced CSS variable name, including the leading `--`. Returns the input |
| 28 | + * unchanged if no namespace is configured. |
| 29 | + */ |
| 30 | + namespace(name: string): string { |
| 31 | + // Validate that the whole `--foo` variable is passed in. |
| 32 | + if (typeof ngDevMode === 'undefined' || ngDevMode) { |
| 33 | + if (!name.startsWith('--')) { |
| 34 | + throw new Error( |
| 35 | + `CSS variable names passed to \`CssVarNamespacer\` must start with '--', got: '${name}'`, |
| 36 | + ); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // We want to support libraries which might be used by applications which do and don't |
| 41 | + // namespace variables. Therefore the library always needs to use `CssVarNamespacer`, even |
| 42 | + // though the application may not actually be namespacing anything. |
| 43 | + if (!this.namespacePrefix) return name; |
| 44 | + |
| 45 | + return `--${this.namespacePrefix}${name.substring('--'.length)}`; |
| 46 | + } |
| 47 | +} |
0 commit comments