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 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 | 157x 157x 157x 157x 157x 157x 2x 2x 22x 22x 6x 16x 16x 16x 16x 2438x 2438x 3x 2435x 2069x 2068x 3x 3x 2x 1x 2065x 5x 2060x 2060x 2060x 2050x 10x 525x 525x 1343x 525x 1343x 1343x 525x 818x 281x 281x 281x 281x 281x 281x 678x 281x 297x 16x 397x 397x 879x 879x 2348x 879x 1469x 1469x 3256x 2x 177x 146x 6x 2x 39x 1x 516x 26x 26x 26x 26x 26x 7x 7x 11x 7x 7x 26x 10x 10x 39x 10x 10x 26x 6x 6x 1x 5x 5x 6x 6x 26x 6x 6x 51x 4x 47x 76x 76x 6x 6x 26x 8x 8x 42x 42x 42x 88x 42x 46x 46x 8x 32x 5x 8x 8x 26x 7x 7x 7x 7x 7x 26x 44x 44x 44x 1054x 1054x 44x 44x 639x 110x 529x 44x 44x 44x 639x 114x 525x 44x 44x 15x 15x 3114x 650x 114x 114x 114x 536x 11x 11x 3109x 136x 13x 13x 3112x 466x 50x 50x 50x 416x 60x 60x 60x 356x 18x 18x 3120x 18x 18x 18x 691x 691x 691x 691x 691x 65x 691x 691x 691x 691x 691x 691x 691x 691x 691x 691x 18x 18x 65x 65x 65x 65x 691x 65x 65x 65x 65x 691x 65x 18x 63x 63x 63x 63x 719x 719x 48x 48x 671x 45x 626x 93x 533x 38x 38x 63x 2x 7x 7x 7x 7x 7x 63x 63x 63x 63x 63x 7x 2x 2x 145x 145x 145x 145x 20x 13x 14x 15x 26x 15x 11x 13x 18x 2x 2x | /**
* Android Split Tokens Format for Android/Jetpack Compose
*
* Generates multiple Kotlin files with structured token output:
* - SalesforceCosmosSystemColors.kt - System color objects (Light/Dark)
* - SalesforceCosmosReferenceColors.kt - Reference color objects (Light/Dark)
* - SalesforceCosmosSemanticColors.kt - Semantic color objects (Light/Dark)
* - SalesforceCosmosPaletteColors.kt - Palette color objects (per color family, Light/Dark)
* - SalesforceCosmosFonts.kt - Font size/weight/family objects
* - SalesforceCosmosShapes.kt - Border radius object
* - SalesforceCosmosSpacing.kt - Spacing object
* - SalesforceCosmosSizing.kt - Sizing object
* - SalesforceCosmosMotionDuration.kt - Duration object
*
* Note: Deprecated tokens are excluded from this output.
*/
import Color from 'colorjs.io';
import {
convertDurationToMs,
getRawValueUnitValue,
resolveTokenReference,
isTokenReference,
parseOklch,
expandHexColor,
getTokensForCategory,
shouldSkipToken,
isSystemColorToken,
isReferenceColorToken,
isSemanticColorToken,
generateDimensionOutput,
generateDurationOutput,
groupFontTokens,
generateFontFamilyOutput,
generateFontWeightOutput,
generateFontDimensionOutput,
generateLineHeightOutput,
generateTruncationOutput,
getTokenDescription,
PATH_INDEX,
CATEGORY,
FONT_SUBCATEGORY,
} from '../utils/mobile-helpers.js';
import { MODE_EXTENSION_KEY } from '../utils/constants.js';
import { processColorTokens } from '../utils/mobile-color-helpers.js';
// ============================================================================
// FILE HEADER GENERATOR
// ============================================================================
/**
* Generate file header with conditional imports based on what the file needs
* @param {string} purpose - Description of the file's purpose
* @param {Object} options - Import options
* @param {boolean} options.needsColor - Whether Color import is needed
* @param {boolean} options.needsDp - Whether dp import is needed
* @param {boolean} options.needsSp - Whether sp import is needed
* @returns {string} - File header with appropriate imports
*/
function generateFileHeader(purpose, options = { needsColor: false, needsDp: false, needsSp: false }) {
const imports = [];
if (options.needsColor) imports.push('import androidx.compose.ui.graphics.Color');
if (options.needsDp) imports.push('import androidx.compose.ui.unit.dp');
if (options.needsSp) imports.push('import androidx.compose.ui.unit.sp');
const importSection = imports.length > 0 ? imports.join('\n') + '\n\n' : '';
return `/*
* AUTO-GENERATED FILE. DO NOT EDIT.
*
* ${purpose}
*
* This file is intended for Compose-based Android projects.
*
* Note: Deprecated tokens are excluded from this output.
*/
package com.salesforce.android.sharedui.tokens
${importSection}`;
}
// ============================================================================
// COLOR UTILITIES
// ============================================================================
// Constants for color conversions
const COMPOSE_COLOR_PREFIX = '0xFF';
const HEX_COLOR_LENGTH = 6;
/**
* Convert OKLCH color format to hexadecimal
*/
function oklchToHex(oklch) {
const components = parseOklch(oklch);
if (!components) {
throw new Error(`[Android-Split] Could not parse OKLCH color: ${JSON.stringify(oklch)}`);
}
const [L, C, H] = components;
const color = new Color('oklch', [L, C, H]);
const srgb = color.to('srgb');
return srgb.toString({ format: 'hex' }).toUpperCase().replace('#', '');
}
/**
* Convert hex color to Compose Color constructor format
*/
function toComposeColor(hex) {
const cleanHex = expandHexColor(hex);
// Validate hex length after expansion
if (cleanHex.length !== HEX_COLOR_LENGTH) {
throw new Error(`[Android-Split] Invalid hex color: "${hex}" (expected 3 or 6 character hex)`);
}
return `Color(${COMPOSE_COLOR_PREFIX}${cleanHex})`;
}
/**
* Resolve a color value to uppercase hex
*/
function resolveColorToHex(colorValue, allTokens, visited = new Set()) {
if (!colorValue) return null;
// Handle token reference
if (isTokenReference(colorValue)) {
const refValue = resolveTokenReference(colorValue, allTokens, visited);
if (refValue !== null) {
return resolveColorToHex(refValue, allTokens, visited);
}
return null;
}
// Handle OKLCH (string or object)
if (parseOklch(colorValue)) {
return oklchToHex(colorValue);
}
// Handle hex string
Eif (typeof colorValue === 'string') {
const cleanHex = expandHexColor(colorValue);
// Validate after expansion to ensure we have a 6-digit hex
if (cleanHex.length === HEX_COLOR_LENGTH && /^[0-9a-f]{6}$/i.test(cleanHex)) {
return cleanHex.toUpperCase();
}
}
return null;
}
// ============================================================================
// NAMING UTILITIES
// ============================================================================
/**
* Convert token path to short property name for objects
* Example: ['slds', 'g', 'spacing', '1'] -> 'spacing1'
*/
function pathToShortPropertyName(path) {
// Skip namespace and scope (slds.g), then take from category onwards
const relevantPath = path.slice(PATH_INDEX.CATEGORY);
// Helper to convert a segment with hyphens to camelCase
const toCamelCase = (segment) => {
return segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
};
return relevantPath
.map((segment, index) => {
const camelSegment = toCamelCase(segment);
// First segment lowercase, subsequent segments capitalize first letter
if (index === 0) {
return camelSegment.toLowerCase();
}
return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
})
.join('');
}
/**
* Convert token path to property name for scoped font objects
* Skips category and subcategory since they're already in the class name
* Example: ['slds', 'g', 'font', 'scale', '1'] -> 'scale1'
*/
function pathToScopedFontPropertyName(path) {
// For font tokens, include subcategory + name for better clarity
// Path structure: [slds, g, font, subcategory, name, ...]
// Example: ['slds', 'g', 'font', 'scale', '1'] -> 'scale1'
// Example: ['slds', 'g', 'font', 'weight', '1'] -> 'weight1'
// Example: ['slds', 'g', 'font', 'weight', 'bold'] -> 'bold' (semantic names don't get prefix)
// Example: ['slds', 'g', 'font', 'line-clamp'] -> 'lineclamp' (hyphen converted to camelCase)
const subcategory = path[PATH_INDEX.SUBCATEGORY]; // e.g., 'scale', 'weight', 'line-clamp'
const nameParts = path.slice(4); // Everything after subcategory
// Check if this is a semantic name (non-numeric) - if so, don't prefix with subcategory
// Note: 'base', 'var', 'ratio', and 'neg' tokens should always get the subcategory prefix for consistency
const firstNamePart = nameParts[0];
const isSemanticName =
firstNamePart && !/^\d/.test(firstNamePart) && !['base', 'var', 'ratio', 'neg'].includes(firstNamePart);
// For semantic names, use just the name parts. For numeric/structured names, include subcategory
const allParts = isSemanticName ? nameParts : [subcategory, ...nameParts];
return allParts
.map((segment, index) => {
// First segment lowercase, rest capitalize
if (index === 0) {
// Convert hyphens to camelCase for first segment
return segment
.split('-')
.map((word, wordIndex) => {
if (wordIndex === 0) return word.toLowerCase();
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join('');
}
// Convert hyphens to camelCase and capitalize the first letter for subsequent segments
const camelSegment = segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
})
.join('');
}
/**
* Convert token path to property name for scoped color objects
*/
function pathToScopedColorPropertyName(path) {
// For color tokens, skip namespace, scope, and category (color)
const relevantPath = path.slice(PATH_INDEX.SUBCATEGORY);
return relevantPath
.map((segment, index) => {
// First segment lowercase, rest capitalize
if (index === 0) {
return segment.toLowerCase();
}
// Convert hyphens to camelCase and capitalize the first letter for subsequent segments
const camelSegment = segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
})
.join('');
}
// ============================================================================
// ANDROID PLATFORM CONFIG
// ============================================================================
/**
* Format an inline comment for descriptions
* @param {string|null} description - Description text
* @returns {string} - Formatted inline comment or empty string
*/
function formatInlineComment(description) {
return description ? ` // ${description}` : '';
}
const ANDROID_DIMENSION_CONFIG = {
objectDeclaration: 'object {{name}} {',
objectClose: '}',
valueProperty: (propName, value, description) =>
` val ${propName} = ${value}.dp${formatInlineComment(description)}\n`,
referenceProperty: (propName, refPropName, unit, description) =>
` val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`,
percentProperty: (propName, value, description) =>
` val ${propName}Percent = ${value}${formatInlineComment(description)}\n`,
};
const ANDROID_DURATION_CONFIG = {
objectDeclaration: 'object {{name}} {',
objectClose: '}',
valueProperty: (propName, msValue, description) =>
` val ${propName} = ${msValue}L${formatInlineComment(description)}\n`,
referenceProperty: (propName, refPropName, description) =>
` val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`,
};
// Android pathToShortPropertyName ignores category parameter (simple version)
const androidPathToPropertyName = (path) => pathToShortPropertyName(path);
// ============================================================================
// FONTS OUTPUT HELPER
// ============================================================================
/**
* Generate font tokens output for Android
* @param {object} params - Parameters
* @param {object} params.dictionary - Token dictionary
* @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
* @returns {string} - Generated Kotlin code
*/
function generateFontsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
const tokens = dictionary.allTokens;
const fontTokens = getTokensForCategory(tokens, CATEGORY.FONT);
let output = generateFileHeader('Font design tokens for Android.', { needsSp: true });
// Group font tokens by sub-category using shared helper
const {
sizes: fontSizes,
weights: fontWeights,
families: fontFamilies,
lineHeights: fontLineHeights,
scales: fontScales,
truncation: fontTruncation,
} = groupFontTokens(fontTokens);
// Font Families - object with val
if (fontFamilies.length > 0) {
output += `object ${themePrefix}FontFamily {\n`;
const familyOutputs = generateFontFamilyOutput(fontFamilies, tokens, {
pathToPropertyName: pathToScopedFontPropertyName,
formatValue: (propName, fontStack, description) =>
` val ${propName} = "${fontStack}"${formatInlineComment(description)}\n`,
formatReference: (propName, refPropName, objectName, description) =>
` val ${propName} get() = ${objectName}.${refPropName}${formatInlineComment(description)}\n`,
objectName: `${themePrefix}FontFamily`,
});
output += familyOutputs.join('');
output += '}\n\n';
}
// Font Weights - object with val
if (fontWeights.length > 0) {
output += `object ${themePrefix}FontWeight {\n`;
const weightOutputs = generateFontWeightOutput(
fontWeights,
pathToScopedFontPropertyName,
(propName, value, description) => ` val ${propName} = ${value}${formatInlineComment(description)}\n`,
);
output += weightOutputs.join('');
output += '}\n\n';
}
// Font Sizes - object with val
if (fontSizes.length > 0) {
output += `object ${themePrefix}FontSize {\n`;
const sizeOutputs = generateFontDimensionOutput(fontSizes, tokens, {
pathToPropertyName: pathToScopedFontPropertyName,
formatValue: (propName, value, token, description) =>
` val ${propName} = ${value}.sp${formatInlineComment(description)}\n`,
formatReference: (propName, refToken, allTokens, description) => {
const refPropName = pathToScopedFontPropertyName(refToken.path);
return ` val ${propName} get() = ${themePrefix}FontScale.${refPropName}${formatInlineComment(description)}\n`;
},
useDimensionConversion: true,
expectedSubcategory: FONT_SUBCATEGORY.SCALE,
});
output += sizeOutputs.join('');
output += '}\n\n';
}
// Font Scales - object with val
if (fontScales.length > 0) {
output += `object ${themePrefix}FontScale {\n`;
const scaleOutputs = generateFontDimensionOutput(fontScales, tokens, {
pathToPropertyName: pathToScopedFontPropertyName,
formatValue: (propName, value, token, description) => {
// Check if this is a number type (like ratio) vs dimension type (like rem/px)
if (token.$type === 'number') {
return ` val ${propName} = ${value}f${formatInlineComment(description)}\n`;
}
return ` val ${propName} = ${value}.sp${formatInlineComment(description)}\n`;
},
formatReference: (propName, refToken, allTokens, description) => {
const refPropName = pathToScopedFontPropertyName(refToken.path);
return ` val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`;
},
useDimensionConversion: true, // Changed from false - Android scales need dimension conversion for px units
expectedSubcategory: FONT_SUBCATEGORY.SCALE,
});
output += scaleOutputs.join('');
output += '}\n\n';
}
// Font Line Heights - object with val
if (fontLineHeights.length > 0) {
output += `object ${themePrefix}FontLineHeight {\n`;
// Helper to build lineHeight property name from token path
const buildLineHeightName = (path) => {
// Path: ['slds', 'g', 'font', 'line', 'height', '1']
// Build prefix from path[3] + path[4]: 'line' + 'height' -> 'lineHeight'
const prefix = path[3] + path[4].charAt(0).toUpperCase() + path[4].slice(1); // e.g., 'lineHeight'
const nameParts = path.slice(5); // Everything after 'height'
return [prefix, ...nameParts]
.map((segment, index) => {
if (index === 0) {
return segment; // Keep prefix (e.g., 'lineHeight') as is
}
// Convert hyphens to camelCase and capitalize the first letter for subsequent segments
const camelSegment = segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
})
.join('');
};
const lineHeightOutputs = generateLineHeightOutput(fontLineHeights, tokens, {
pathToPropertyName: buildLineHeightName,
formatValue: (propName, value, description) =>
` val ${propName} = ${value}f${formatInlineComment(description)}\n`,
formatReference: (propName, refPropName, description) =>
` val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`,
});
output += lineHeightOutputs.join('');
output += '}\n\n';
}
// Font Line Clamp - object with val
if (fontTruncation.length > 0) {
output += `object ${themePrefix}FontLineClamp {\n`;
const truncationOutputs = generateTruncationOutput(
fontTruncation,
pathToScopedFontPropertyName,
(propName, value, description) =>
` val ${propName} = ${value}f${formatInlineComment(description)}\n`,
);
output += truncationOutputs.join('');
output += '}\n\n';
}
return output.trimEnd() + '\n';
}
// ============================================================================
// COLOR OUTPUT HELPERS
// ============================================================================
//
// Generic function to generate color format with light/dark objects
// Used by System, Semantic, and Reference color formats
//
// ============================================================================
/**
* Generate Android color format with light/dark mode support
* @param {object} config - Configuration object
* @param {Array} config.tokens - All tokens from dictionary
* @param {Function} config.filterFn - Function to filter tokens for this format
* @param {string} config.fileHeader - Header comment for the file
* @param {string} config.objectNameLight - Object name for light mode (e.g., 'SalesforceCosmosSystemColorsLight')
* @param {string} config.objectNameDark - Object name for dark mode (e.g., 'SalesforceCosmosSystemColorsDark')
* @param {Function} config.getRefProperty - Function to get reference property string for a token (refToken, isDark) => string | null
* @param {boolean} config.useDarkFallback - Whether to use light value as fallback when dark value is missing (default: true)
* @returns {string} - Generated Kotlin code
*/
function generateColorFormatWithModes({
tokens,
filterFn,
fileHeader,
objectNameLight,
objectNameDark,
getRefProperty,
useDarkFallback = true,
}) {
const colorTokens = tokens.filter(filterFn);
let output = generateFileHeader(fileHeader, { needsColor: true });
// Use shared helper to process color tokens
const { lightColors, darkColors } = processColorTokens({
tokens: colorTokens,
allTokens: tokens,
getPropName: pathToScopedColorPropertyName,
getRefProperty,
resolveColor: (colorValue, allTokens) => {
const hex = resolveColorToHex(colorValue, allTokens);
return hex ? toComposeColor(hex) : null;
},
useDarkFallback,
});
// Output Light object
output += `object ${objectNameLight} {\n`;
lightColors.forEach(({ name, color, description }) => {
// Use `get()` for references, direct `=` for Color values
if (color.startsWith('Salesforce')) {
output += ` val ${name} get() = ${color}${formatInlineComment(description)}\n`;
} else {
output += ` val ${name} = ${color}${formatInlineComment(description)}\n`;
}
});
output += '}\n\n';
// Output Dark object
output += `object ${objectNameDark} {\n`;
darkColors.forEach(({ name, color, description }) => {
// Use `get()` for references, direct `=` for Color values
if (color.startsWith('Salesforce')) {
output += ` val ${name} get() = ${color}${formatInlineComment(description)}\n`;
} else {
output += ` val ${name} = ${color}${formatInlineComment(description)}\n`;
}
});
output += '}\n';
return output;
}
// ============================================================================
// SYSTEM COLORS OUTPUT HELPER
// ============================================================================
/**
* Generate system color tokens output for Android
* @param {object} params - Parameters
* @param {object} params.dictionary - Token dictionary
* @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
* @returns {string} - Generated Kotlin code with Light and Dark color objects
*/
function generateSystemColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
const tokens = dictionary.allTokens;
return generateColorFormatWithModes({
tokens,
filterFn: (token) => !shouldSkipToken(token) && isSystemColorToken(token),
fileHeader: 'System color design tokens for Android.',
objectNameLight: `${themePrefix}SystemColorsLight`,
objectNameDark: `${themePrefix}SystemColorsDark`,
getRefProperty: (refToken, isDark) => {
if (isReferenceColorToken(refToken)) {
const refPropName = pathToScopedColorPropertyName(refToken.path);
const className = isDark ? `${themePrefix}ReferenceColorsDark` : `${themePrefix}ReferenceColorsLight`;
return `${className}.${refPropName}`;
}
return null;
},
useDarkFallback: true,
});
}
// ============================================================================
// REFERENCE COLORS OUTPUT HELPER
// ============================================================================
/**
* Generate reference color tokens output for Android
* @param {object} params - Parameters
* @param {object} params.dictionary - Token dictionary
* @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
* @returns {string} - Generated Kotlin code with Light and Dark color objects
*/
function generateReferenceColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
const tokens = dictionary.allTokens;
return generateColorFormatWithModes({
tokens,
filterFn: (token) => !shouldSkipToken(token) && isReferenceColorToken(token),
fileHeader: 'Reference color design tokens for Android.',
objectNameLight: `${themePrefix}ReferenceColorsLight`,
objectNameDark: `${themePrefix}ReferenceColorsDark`,
getRefProperty: () => null,
});
}
// ============================================================================
// SEMANTIC COLORS OUTPUT HELPER
// ============================================================================
/**
* Generate semantic color tokens output for Android
* @param {object} params - Parameters
* @param {object} params.dictionary - Token dictionary
* @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
* @returns {string} - Generated Kotlin code with Light and Dark color objects
*/
function generateSemanticColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
const tokens = dictionary.allTokens;
return generateColorFormatWithModes({
tokens,
filterFn: (token) => !shouldSkipToken(token) && isSemanticColorToken(token),
fileHeader: 'Semantic color design tokens for Android.',
objectNameLight: `${themePrefix}SemanticColorsLight`,
objectNameDark: `${themePrefix}SemanticColorsDark`,
getRefProperty: (refToken, isDark) => {
if (isSystemColorToken(refToken)) {
const refPropName = pathToScopedColorPropertyName(refToken.path);
const className = isDark ? `${themePrefix}SystemColorsDark` : `${themePrefix}SystemColorsLight`;
return `${className}.${refPropName}`;
}
if (isReferenceColorToken(refToken)) {
const refPropName = pathToScopedColorPropertyName(refToken.path);
const className = isDark ? `${themePrefix}ReferenceColorsDark` : `${themePrefix}ReferenceColorsLight`;
return `${className}.${refPropName}`;
}
return null;
},
useDarkFallback: true,
});
}
// ============================================================================
// PALETTE COLORS OUTPUT HELPER
// ============================================================================
/**
* Generate palette color tokens output for Android
* @param {object} params - Parameters
* @param {object} params.dictionary - Token dictionary
* @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
* @returns {string} - Generated Kotlin code with Light and Dark color objects per palette family
*/
function generatePaletteColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
const tokens = dictionary.allTokens;
// Filter for slds.g.color.palette.* tokens, not alias.palette.*
const paletteTokens = tokens.filter(
(token) =>
token.path[0] === 'slds' &&
token.path[1] === 'g' &&
token.path[2] === 'color' &&
token.path[3] === 'palette',
);
let output = generateFileHeader('Palette color design tokens for Android.', { needsColor: true });
// Group by color family
const colorFamilies = new Map();
paletteTokens.forEach((token) => {
Iif (shouldSkipToken(token)) return;
// Palette tokens have path: ['slds', 'g', 'color', 'palette', '{family}', '{scale}']
// e.g., ['slds', 'g', 'color', 'palette', 'neutral', '0']
const family = token.path[4]; // 'neutral', 'blue', 'red', etc.
const scale = token.path[5]; // '0', '10', '50', etc.
Iif (!family || !scale) return;
if (!colorFamilies.has(family)) {
colorFamilies.set(family, { light: [], dark: [] });
}
const tokenValue = getRawValueUnitValue(token);
const darkValue = token.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value;
const description = getTokenDescription(token);
// Property name is just the family + scale since they're in family-specific objects
// e.g., 'neutral50', 'blue10' within SalesforceCosmospaletteNeutralLight
const propName = `${family}${scale}`;
// Light value - pass full tokens array so references can be resolved
const lightHex = resolveColorToHex(tokenValue, tokens);
Eif (lightHex) {
colorFamilies.get(family).light.push({ name: propName, color: toComposeColor(lightHex), description });
}
// Dark value - fallback to light value if dark doesn't resolve
const darkHex = darkValue ? resolveColorToHex(darkValue, tokens) : lightHex;
Eif (darkHex) {
colorFamilies.get(family).dark.push({ name: propName, color: toComposeColor(darkHex), description });
}
});
// Output each color family as separate objects
const sortedFamilies = Array.from(colorFamilies.keys()).sort();
sortedFamilies.forEach((family) => {
const familyName = family.charAt(0).toUpperCase() + family.slice(1);
const { light, dark } = colorFamilies.get(family);
// Light object
output += `object ${themePrefix}Palette${familyName}Light {\n`;
light.forEach(({ name, color, description }) => {
output += ` val ${name} = ${color}${formatInlineComment(description)}\n`;
});
output += '}\n\n';
// Dark object - only create if there are dark colors
Eif (dark.length > 0) {
output += `object ${themePrefix}Palette${familyName}Dark {\n`;
dark.forEach(({ name, color, description }) => {
output += ` val ${name} = ${color}${formatInlineComment(description)}\n`;
});
output += '}\n\n';
}
});
return output.trimEnd() + '\n';
}
// ============================================================================
// COMBINED FORMAT (all tokens in one file)
// ============================================================================
/**
* Helper to extract the content after the package and imports from a format output
*/
function stripFileHeader(content) {
const lines = content.split('\n');
let startIndex = 0;
let foundPackage = false;
// Find everything after the header comment, package, and imports
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Skip until we find package declaration
if (line.startsWith('package ')) {
foundPackage = true;
continue;
}
// After package, skip import lines
if (foundPackage && line.startsWith('import ')) {
continue;
}
// After package and imports, skip blank lines
if (foundPackage && line === '') {
continue;
}
// Found the first real content line (not header, package, import, or blank)
if (foundPackage && line !== '') {
startIndex = i;
break;
}
}
return lines.slice(startIndex).join('\n');
}
export const androidTokensAllFormat = ({ dictionary, options }) => {
const { themePrefix = 'SalesforceCosmos' } = options || {};
let output = generateFileHeader('All design tokens combined for comparison.', {
needsColor: true,
needsDp: true,
needsSp: true,
});
const tokenTypes = [
'spacing',
'sizing',
'shapes',
'motion-duration',
'fonts',
'system-colors',
'reference-colors',
'semantic-colors',
'palette-colors',
];
const sectionLabels = [
'SPACING',
'SIZING',
'SHAPES',
'MOTION DURATION',
'FONTS',
'SYSTEM COLORS',
'REFERENCE COLORS',
'SEMANTIC COLORS',
'PALETTE COLORS',
];
tokenTypes.forEach((tokenType, index) => {
if (index > 0) output += '\n';
output += `// ============================================================================\n`;
output += `// ${sectionLabels[index]}\n`;
output += `// ============================================================================\n\n`;
output += stripFileHeader(androidFormat({ dictionary, options: { tokenType, themePrefix } }));
});
return output;
};
// Mark formats as nested to avoid collision warnings
androidTokensAllFormat.nested = true;
// ============================================================================
// UNIFIED MOBILE FORMAT
// ============================================================================
/**
* Unified Android format that routes to appropriate rendering based on tokenType option.
* Uses pre-filtered tokens from Style Dictionary file-level filters.
*
* @param {object} params - Format parameters
* @param {object} params.dictionary - Style Dictionary dictionary object
* @param {object} params.options - Options object containing tokenType
* @param {string} params.options.tokenType - Type of tokens to format (spacing, sizing, shapes, etc.)
* @returns {string} - Formatted output for the specified token type
*/
export const androidFormat = ({ dictionary, options }) => {
const tokens = dictionary.allTokens;
const { tokenType, themePrefix = 'SalesforceCosmos' } = options || {};
Iif (!tokenType) {
throw new Error('[androidFormat] options.tokenType is required');
}
switch (tokenType) {
case 'spacing':
return generateDimensionOutput({
tokens,
category: CATEGORY.SPACING,
fileHeader: generateFileHeader('Spacing tokens for Android.', { needsDp: true }),
objectName: `${themePrefix}Spacing`,
config: ANDROID_DIMENSION_CONFIG,
pathToPropertyName: androidPathToPropertyName,
});
case 'sizing':
return generateDimensionOutput({
tokens,
category: CATEGORY.SIZING,
fileHeader: generateFileHeader('Sizing tokens for Android.', { needsDp: true }),
objectName: `${themePrefix}Sizing`,
config: ANDROID_DIMENSION_CONFIG,
pathToPropertyName: androidPathToPropertyName,
});
case 'shapes':
return generateDimensionOutput({
tokens,
category: CATEGORY.RADIUS,
fileHeader: generateFileHeader('Shape tokens (border radius) for Android.', { needsDp: true }),
objectName: `${themePrefix}Shapes`,
config: ANDROID_DIMENSION_CONFIG,
pathToPropertyName: androidPathToPropertyName,
});
case 'motion-duration':
return generateDurationOutput({
tokens,
fileHeader: generateFileHeader('Motion duration tokens for Android.'),
objectName: `${themePrefix}MotionDuration`,
config: ANDROID_DURATION_CONFIG,
pathToPropertyName: androidPathToPropertyName,
convertDuration: convertDurationToMs,
});
case 'fonts':
return generateFontsOutput({ dictionary, themePrefix });
case 'system-colors':
return generateSystemColorsOutput({ dictionary, themePrefix });
case 'reference-colors':
return generateReferenceColorsOutput({ dictionary, themePrefix });
case 'semantic-colors':
return generateSemanticColorsOutput({ dictionary, themePrefix });
case 'palette-colors':
return generatePaletteColorsOutput({ dictionary, themePrefix });
default:
throw new Error(`[androidFormat] Unknown tokenType: ${tokenType}`);
}
};
androidFormat.nested = true;
// ============================================================================
// TEST EXPORTS
// ============================================================================
/**
* Export internal functions for testing purposes only.
* These are not part of the public API.
*/
export const _testExports = {
oklchToHex,
toComposeColor,
resolveColorToHex,
pathToShortPropertyName,
pathToScopedFontPropertyName,
pathToScopedColorPropertyName,
generateColorFormatWithModes,
COMPOSE_COLOR_PREFIX,
HEX_COLOR_LENGTH,
};
|