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 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 8x 8x 8x 9x 9x 9x 9x 23x 23x 8x 8x 8x 8x 8x 8x 23x 8x 8x 8x 8x 6x 8x 6x 8x 7x 23x 23x 23x 23x 23x 23x 23x 2x 2x 1x 1x 1x 1x 1x 23x 23x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 2x 1x | import theo from 'theo';
import fs from 'fs-extra';
import path from 'node:path';
import { globSync } from 'glob';
import chalk from 'chalk';
import arg from 'arg';
import { validateDefaultConfig, validateThemeConfig } from './utils/validations.js';
// Register custom formats
import '../src/formats/config.js';
import '../src/formats/defaults.js';
import '../src/formats/theme.js';
import '../src/formats/shared.js';
import '../src/formats/component.js';
import '../src/formats/deprecated.js';
import '../src/formats/zeroheight.js';
// Register custom transformers
import '../src/transformers/font-scale.js';
import '../src/transformers/color.js';
import '../src/transformers/inherits.js';
import '../src/transformers/deprecated.js';
// Override the default "raw" transform
theo.registerTransform('raw', ['fontscale/web', 'color/web', 'inherits', 'deprecated']);
const args = arg({
'--ns': String,
});
// Support namespace from CLI flag or environment variable
const rawNamespace = args['--ns'] || process.env.HOOKS_NS;
/**
* Validates that a namespace value is valid.
* Namespaces must be non-empty strings containing only alphanumeric characters, hyphens, and underscores.
* @param {string} ns - The namespace value to validate
* @returns {boolean} - True if valid, false otherwise
*/
const isValidNamespace = (ns) => {
Iif (!ns || typeof ns !== 'string') {
return false;
}
// Allow alphanumeric characters, hyphens, and underscores
// Must be at least 1 character and not start/end with hyphen or underscore
return /^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(ns);
};
// Validate namespace if provided
let namespace = null;
Eif (rawNamespace && isValidNamespace(rawNamespace)) {
namespace = rawNamespace;
}
Iif (rawNamespace && !namespace) {
console.error(
`Error: Invalid namespace value "${rawNamespace}". Namespace must be a non-empty string containing only alphanumeric characters, hyphens, and underscores.`,
);
process.exit(1);
}
export default class StylingHooks {
theme;
path;
/**
* @param {object} config
* @param {string} config.rootDir - The root directory where the styling hooks are located.
* @param {string} config.themesDir - The root directory where the themes are located.
* @param {string} config.outputDir - The root directory where the styling hooks will be generated.
* @param {string} config.themes - The theme namespace to generate.
* @param {boolean} config.default - Generate the default styling hooks.
* @param {boolean} config.shared - Generate the shared styling hooks.
* @example
* new StylingHooks({
* rootDir: path.resolve(root, 'src/props/'),
* themesDir: path.resolve(root, 'src/themes/'),
* outputDir: path.resolve(root, 'dist/'),
* themes: 'slds',
* shared: true,
* });
*/
constructor(config) {
this.config = {
rootDir: config.rootDir,
themesDir: config.themesDir,
outputDir: config.outputDir,
themes: config.themes,
default: config.default,
shared: config.shared,
component: config.component,
deprecated: config.deprecated,
};
}
/**
* @param {string} value - The format type to generate.
* @returns {object} - An array of objects containing the format and transform types.
* @private
*/
formats(value) {
const options = ['default', 'shared', 'theme', 'component', 'deprecated'];
if (!options.includes(value)) {
throw new Error(`Invalid value: ${value}. Valid options are: ${options.join(', ')}`);
}
const formats = [
{
format: `custom-props-${value}.css`,
transform: 'raw',
},
{
format: 'raw.json',
transform: 'raw',
},
];
// Only generate the zeroheight format for theme tokens.
// We exclude shared, component, and deprecated tokens later in this file because we are not currently documented them.
Iif (value === 'theme') {
formats.push({
format: 'zh-light.json',
transform: 'raw',
});
}
return formats;
}
/**
* Before anything runs, we validate the correct configurations are set when invoking generateDefaults()
* @private
*/
validateDefaultConfig() {
validateDefaultConfig(this.config, () => this.defaultsExists());
}
/**
* @param {string} ns - The theme namespace to generate.
* @returns {boolean} - Returns true if the theme exists.
* @private
*/
themeExists(ns) {
// Checking for the existence of a theme requires an array of themes
// The theme can be passed in as a string or an array
// If the theme is a string, it will be converted to an array
const themeArray = this.config.themes instanceof Array ? this.config.themes : [this.config.themes];
// Get the theme directories based on the themesDir found in the config property
const getThemeDirs = globSync(path.resolve(this.config.themesDir, `@(${themeArray.join('|')})`));
// Check if the theme exists in the array of themes
Eif (Array.from(themeArray, (t) => t === ns)) {
const dir = getThemeDirs.filter((t) => t.includes(ns));
// If the theme exists on file based on rootDir, set the path and theme properties
Iif (dir.length === 0) return false;
fs.ensureDirSync(dir[0]);
this.path = dir[0];
this.theme = ns;
return true;
}
}
/**
* @returns {boolean} - Returns true if the shared directory exists.
* @private
*/
sharedExists() {
const files = globSync(path.resolve(this.config.themesDir, `${this.theme}/shared/*.json`));
Iif (files.length === 0) return false;
return true;
}
componentsExists() {
const files = globSync(path.resolve(this.config.themesDir, `${this.theme}/component/*.json`));
Iif (files.length === 0) return false;
return true;
}
deprecatedExists() {
const files = globSync(path.resolve(this.config.themesDir, `${this.theme}/deprecated/*.json`));
Iif (files.length === 0) return false;
return true;
}
/**
* @returns {boolean} - Returns true if the defaults directory exists.
* @private
*/
defaultsExists() {
fs.ensureDirSync(this.config.rootDir);
const files = globSync(path.resolve(this.config.rootDir, '*.json'));
Iif (files.length === 0) return false;
return true;
}
/**
* @param {string} path - The path to the directory to clean.
* @private
*/
cleanTemp = (path) => {
fs.emptyDirSync(path);
};
/**
* Set the namespace for the global props. This needs to happen for transforming the props so
* we set the namespace in the temp directory to use for transformation.
*
* Special handling:
* - For defaults (props.ns === 'sds'): Always use 'sds' namespace (not 'slds')
* - For themes: Uses CLI flag (--ns) or falls back to the theme folder name (props.ns)
*
* @param {string} file - The file to set the namespace.
* @param {object} props - The props object that contains information about the namespace we are setting.
* @param {string} props.ns - The namespace identifier ('sds' for defaults, theme name for themes)
* @param {string} props.tempDir - The temporary directory path for transformation
* @private
*/
setNamespace = (file, props) => {
const name = path.parse(file).name;
const jsonFile = fs.readJsonSync(file);
Eif (jsonFile.global) {
Iif (props.ns === 'sds') {
jsonFile.global.namespace = 'sds';
} else {
jsonFile.global.namespace = namespace || props.ns;
}
fs.outputJSONSync(path.resolve(props.tempDir, `${name}.json`), jsonFile);
}
};
/**
* @param {object} props - The props object that contains information about the namespace we are setting.
* @private
* @returns {string} - The path to the hooks file.
*/
cloneProps = (props) => {
Eif (this.defaultsExists()) {
globSync(path.resolve(this.config.rootDir, '*.json')).forEach((file) => {
this.setNamespace(file, props);
});
}
if (this.config.themes && this.sharedExists()) {
fs.copySync(
path.resolve(this.config.themesDir, `${this.theme}/shared`),
path.resolve(props.tempDir, 'shared'),
);
}
if (this.config.themes && this.componentsExists()) {
fs.copySync(
path.resolve(this.config.themesDir, `${this.theme}/component`),
path.resolve(props.tempDir, 'component'),
);
}
if (this.config.deprecated && this.deprecatedExists()) {
fs.copySync(
path.resolve(this.config.themesDir, `${this.theme}/deprecated`),
path.resolve(props.tempDir, 'deprecated'),
);
}
};
/**
* Build the hooks file that will be used for transforming the props.
* @param {object} props - The props object that contains information about the namespace we are setting.
* @private
* @returns {string} - The path to the hooks file.
*/
buildHooksFile = (props) => {
const hooksFile = path.resolve(props.tempDir, `${props.ns}.hooks.json`);
const imports = {
imports: [],
};
// Get the files from the themes temp directory and push to a new imports array
globSync(path.resolve(props.tempDir, '*.json')).map((file) => {
if (file.includes(props.dir)) {
imports.imports.push(file);
}
});
// Since we want to have a single API for using styling hooks,
// we need to import the files from the default directory
// which contain the default SDS props
if (this.config.themes) {
globSync(path.resolve(props.dir, '*.json')).map((file) => {
if (file.includes(props.dir)) {
imports.imports.push(file);
}
});
}
// Write to disk so we can use the file for transforming the props
fs.outputJSONSync(hooksFile, imports);
// Theo requires a path to the hooks file so we return it for use in the transformProps method
return hooksFile;
};
/**
* Build the shared hooks file that will be used for transforming the props.
* This method is different from the buildHooksFile method because we need to
* treat the shared props differently due to the folder structure
* @param {object} props - The props object that contains information about the namespace we are setting.
* @private
*/
buildSharedFile = (props) => {
const hooksFile = path.resolve(props.tempDir, `${props.ns}.shared.hooks.json`);
const imports = {
imports: [],
};
if (this.config.shared) {
globSync(path.resolve(props.tempDir, 'shared/*.json')).map((file) => {
if (file.includes(props.dir)) {
imports.imports.push(file);
}
});
fs.outputJSONSync(hooksFile, imports);
return hooksFile;
}
};
buildComponentFile = (props) => {
const hooksFile = path.resolve(props.tempDir, `${props.ns}.component.hooks.json`);
const imports = {
imports: [],
};
if (this.config.shared) {
globSync(path.resolve(props.tempDir, 'component/*.json')).map((file) => {
if (file.includes(props.dir)) {
imports.imports.push(file);
}
});
fs.outputJSONSync(hooksFile, imports);
return hooksFile;
}
};
buildDeprecatedFile = (props) => {
const hooksFile = path.resolve(props.tempDir, `${props.ns}.deprecated.hooks.json`);
const imports = {
imports: [],
};
if (this.config.deprecated) {
globSync(path.resolve(props.tempDir, 'deprecated/*.json')).map((file) => {
if (file.includes(props.dir)) {
imports.imports.push(file);
}
});
fs.outputJSONSync(hooksFile, imports);
return hooksFile;
}
};
// Transform using the config.css format
transformHooksConfig = (hooks) => {
theo
.convert({
transform: {
type: 'raw',
file: hooks,
},
format: {
type: 'config.css',
},
})
.then((data) => {
const distDir = path.resolve(this.config.outputDir, 'config');
fs.ensureDir(distDir, (err) => {
if (err) return console.error(err);
fs.outputFile(path.resolve(distDir, 'config.css'), data);
console.log(`${chalk.green.bold('Success')} config.css has been generated under ${distDir}`);
});
})
.catch((error) => console.error(`Something went wrong: ${error}`));
};
/**
* Transform the props and write to disk.
* @param {object} config - The config object that contains information about the namespace we are setting.
* @param {string} files - The path to the hooks file.
* @private
*/
transformProps = (config, files) => {
let distDir;
const filesArray = files instanceof Array ? files : [files];
filesArray.map((file) => {
const name = path.parse(file).name;
const isShared = name.includes('shared');
const isComponent = name.includes('component');
const isDeprecated = name.includes('deprecated');
const isTheme = path.parse(file).dir.split('/').includes('themes');
let fileFormats;
switch (true) {
case isShared:
fileFormats = 'shared';
break;
case isComponent:
fileFormats = 'component';
break;
case isDeprecated:
fileFormats = 'deprecated';
break;
case isTheme:
fileFormats = 'theme';
break;
default:
fileFormats = 'default';
break;
}
const formats = this.formats(fileFormats);
formats.map((type) => {
switch (true) {
case fileFormats === 'default':
distDir = path.resolve(this.config.outputDir, 'defaults');
break;
default:
distDir = path.resolve(this.config.outputDir, `themes/${config.ns}`);
break;
}
// Skip deprecated, component, and shared files only for zh-light.json format
if (
type.format === 'zh-light.json' &&
(file.includes('deprecated') || file.includes('component') || file.includes('shared'))
) {
return;
}
theo
.convert({
transform: {
type: type.transform,
file: file,
},
format: {
type: type.format,
},
})
.then((data) => {
fs.ensureDir(distDir, (err) => {
if (err) return console.error(err);
// If generating zeroheight format, output to `dist/themes/{theme}/zh-light.json`.
// Otherwise, all other file formats output using the file's base name and format type.
const outputPath =
type.format === 'zh-light.json'
? path.resolve(distDir, 'zh-light.json')
: path.resolve(
distDir,
`${name}.${type.format.replace(
/(-default)|(-theme)|(-shared)|(-component)|(-deprecated)/,
'',
)}`,
);
fs.outputFile(outputPath, data);
console.log(
`${chalk.green.bold('Success')} ${path.basename(
outputPath,
)} has been generated under ${distDir}`,
);
});
})
.catch((error) => console.error(`Something went wrong: ${error}`));
});
});
};
/**
* Generate the default styling hooks.
*/
generateDefaults = () => {
this.validateDefaultConfig();
if (this.defaultsExists()) {
const config = {
ns: 'sds',
dir: this.config.rootDir,
tempDir: path.resolve(this.config.rootDir, '.temp'),
};
this.cleanTemp(config.tempDir);
this.cloneProps(config);
const hooks = this.buildHooksFile(config);
this.transformProps(config, hooks);
}
};
/**
* Generate the config of the design system
*/
generateHooksConfig = () => {
if (this.defaultsExists()) {
const config = {
ns: 'slds',
dir: this.config.rootDir,
tempDir: path.resolve(this.config.rootDir, '.temp'),
};
this.cleanTemp(config.tempDir);
this.cloneProps(config);
// Generate single config file
const hooks = this.buildHooksFile(config);
this.transformHooksConfig(hooks);
}
};
/**
* Generate the theme styling hooks and shared if defined in a shared directory.
* @param {string} ns - The theme namespace to generate.
*/
generateTheme = (ns) => {
validateThemeConfig(
this.config,
() => this.themeExists(ns),
() => this.sharedExists(),
);
if (!this.themeExists(ns)) {
throw new Error(`Theme "${ns}" does not exist`);
}
const config = {
ns,
dir: this.path,
tempDir: path.resolve(this.path, '.temp'),
};
this.cleanTemp(config.tempDir);
this.cloneProps(config);
const hooks = this.buildHooksFile(config);
if (this.config.shared && this.sharedExists()) {
const sharedHooks = this.buildSharedFile(config);
this.transformProps(config, [hooks, sharedHooks]);
} else E{
this.transformProps(config, hooks);
}
Eif (this.config.component && this.componentsExists()) {
const componentHooks = this.buildComponentFile(config);
this.transformProps(config, componentHooks);
}
Eif (this.config.deprecated && this.deprecatedExists()) {
const deprecatedHooks = this.buildDeprecatedFile(config);
this.transformProps(config, deprecatedHooks);
}
};
/**
* Add a custom theme handler. Used to extend behavior if needed.
* @param {string} ns - The theme namespace to generate.
* @param {function} cb - The callback function to execute.
* @example
* addThemeHandler('sds', (theme) => {
* console.log(theme);
* });
* @returns {object} - An object containing the theme name and directory.
*/
addThemeHandler = (ns, cb) => {
if (this.themeExists(ns)) {
return cb({
name: this.theme,
dir: this.path,
});
}
};
}
|