react-native-nano-icons 1.0.0-beta.1 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +124 -2
  2. package/android/build.gradle +8 -1
  3. package/android/src/main/java/com/nanoicons/NanoIconView.kt +53 -4
  4. package/android/src/main/java/com/nanoicons/NanoIconViewManager.kt +42 -18
  5. package/android/src/main/jni/CMakeLists.txt +38 -0
  6. package/android/src/main/jni/RNNanoIconsSpec.h +19 -0
  7. package/common/cpp/react/renderer/components/RNNanoIconsSpec/NanoIconViewComponentDescriptor.h +11 -0
  8. package/common/cpp/react/renderer/components/RNNanoIconsSpec/NanoIconViewShadowNode.cpp +46 -0
  9. package/common/cpp/react/renderer/components/RNNanoIconsSpec/NanoIconViewShadowNode.h +41 -0
  10. package/ios/NanoIconInlineBaseline.h +4 -0
  11. package/ios/NanoIconInlineBaseline.mm +190 -0
  12. package/ios/NanoIconView.h +1 -0
  13. package/ios/NanoIconView.mm +118 -107
  14. package/lib/commonjs/cli/build.d.ts +5 -0
  15. package/lib/commonjs/cli/build.js +37 -15
  16. package/lib/commonjs/cli/buildSymbols.d.ts +26 -0
  17. package/lib/commonjs/cli/buildSymbols.js +134 -0
  18. package/lib/commonjs/cli/config.d.ts +3 -1
  19. package/lib/commonjs/cli/config.js +3 -3
  20. package/lib/commonjs/cli/expoConfig.d.ts +3 -0
  21. package/lib/commonjs/cli/expoConfig.js +17 -6
  22. package/lib/commonjs/cli/index.d.ts +4 -2
  23. package/lib/commonjs/cli/index.js +12 -1
  24. package/lib/commonjs/cli/link.d.ts +15 -0
  25. package/lib/commonjs/cli/link.js +185 -1
  26. package/lib/commonjs/metro/fontRebuildWatcher.d.ts +62 -0
  27. package/lib/commonjs/metro/fontRebuildWatcher.js +174 -0
  28. package/lib/commonjs/metro/index.d.ts +35 -0
  29. package/lib/commonjs/metro/index.js +92 -0
  30. package/lib/commonjs/metro/symbolRebuildWatcher.d.ts +19 -0
  31. package/lib/commonjs/metro/symbolRebuildWatcher.js +76 -0
  32. package/lib/commonjs/plugin/src/buildSymbols.d.ts +3 -0
  33. package/lib/commonjs/plugin/src/buildSymbols.js +18 -0
  34. package/lib/commonjs/plugin/src/index.d.ts +1 -1
  35. package/lib/commonjs/plugin/src/index.js +9 -3
  36. package/lib/commonjs/plugin/src/types.d.ts +34 -2
  37. package/lib/commonjs/plugin/src/withNanoIconsDrawableLinking.d.ts +8 -0
  38. package/lib/commonjs/plugin/src/withNanoIconsDrawableLinking.js +29 -0
  39. package/lib/commonjs/plugin/src/withNanoIconsSymbolLinking.d.ts +8 -0
  40. package/lib/commonjs/plugin/src/withNanoIconsSymbolLinking.js +37 -0
  41. package/lib/commonjs/scripts/cli.js +27 -9
  42. package/lib/commonjs/src/core/font/compile.js +3 -5
  43. package/lib/commonjs/src/core/font/quadratic.d.ts +1 -0
  44. package/lib/commonjs/src/core/font/quadratic.js +2 -0
  45. package/lib/commonjs/src/core/glyph/merge.js +3 -1
  46. package/lib/commonjs/src/core/glyph/parse.d.ts +1 -0
  47. package/lib/commonjs/src/core/pathkit/contours.d.ts +1 -0
  48. package/lib/commonjs/src/core/pathkit/contours.js +18 -0
  49. package/lib/commonjs/src/core/pathkit/evenodd.js +1 -15
  50. package/lib/commonjs/src/core/pathkit/winding.d.ts +4 -0
  51. package/lib/commonjs/src/core/pathkit/winding.js +59 -0
  52. package/lib/commonjs/src/core/pipeline/config.d.ts +1 -0
  53. package/lib/commonjs/src/core/pipeline/config.js +6 -0
  54. package/lib/commonjs/src/core/pipeline/iconPool.d.ts +13 -2
  55. package/lib/commonjs/src/core/pipeline/iconPool.js +89 -31
  56. package/lib/commonjs/src/core/pipeline/index.d.ts +2 -0
  57. package/lib/commonjs/src/core/pipeline/index.js +3 -1
  58. package/lib/commonjs/src/core/pipeline/prepare.d.ts +1 -0
  59. package/lib/commonjs/src/core/pipeline/prepare.js +18 -0
  60. package/lib/commonjs/src/core/pipeline/prepareIcon.d.ts +3 -0
  61. package/lib/commonjs/src/core/pipeline/prepareIcon.js +11 -8
  62. package/lib/commonjs/src/core/pipeline/prepareSvg.d.ts +6 -0
  63. package/lib/commonjs/src/core/pipeline/prepareSvg.js +11 -0
  64. package/lib/commonjs/src/core/pipeline/prepareSymbol.d.ts +26 -0
  65. package/lib/commonjs/src/core/pipeline/prepareSymbol.js +79 -0
  66. package/lib/commonjs/src/core/pipeline/prepareWorker.js +3 -3
  67. package/lib/commonjs/src/core/pipeline/preparedSvgCache.d.ts +6 -0
  68. package/lib/commonjs/src/core/pipeline/preparedSvgCache.js +44 -0
  69. package/lib/commonjs/src/core/pipeline/runFontPipeline.d.ts +5 -0
  70. package/lib/commonjs/src/core/pipeline/runFontPipeline.js +10 -8
  71. package/lib/commonjs/src/core/pipeline/runSymbolPipeline.d.ts +54 -0
  72. package/lib/commonjs/src/core/pipeline/runSymbolPipeline.js +161 -0
  73. package/lib/commonjs/src/core/symbols/contents.d.ts +2 -0
  74. package/lib/commonjs/src/core/symbols/contents.js +15 -0
  75. package/lib/commonjs/src/core/symbols/knockout.d.ts +3 -0
  76. package/lib/commonjs/src/core/symbols/knockout.js +51 -0
  77. package/lib/commonjs/src/core/symbols/layers.d.ts +36 -0
  78. package/lib/commonjs/src/core/symbols/layers.js +182 -0
  79. package/lib/commonjs/src/core/symbols/template.d.ts +22 -0
  80. package/lib/commonjs/src/core/symbols/template.js +140 -0
  81. package/lib/commonjs/src/core/symbols/vectorDrawable.d.ts +11 -0
  82. package/lib/commonjs/src/core/symbols/vectorDrawable.js +66 -0
  83. package/lib/commonjs/src/utils/fingerPrint.d.ts +11 -0
  84. package/lib/commonjs/src/utils/fingerPrint.js +28 -9
  85. package/lib/commonjs/src/utils/naming.d.ts +10 -0
  86. package/lib/commonjs/src/utils/naming.js +49 -0
  87. package/lib/module/createNanoIconsSet.native.js +29 -26
  88. package/lib/module/createNanoIconsSet.shared.js +3 -2
  89. package/lib/module/createNanoIconsSet.web.js +17 -5
  90. package/lib/module/devServerFont.js +30 -0
  91. package/lib/module/devServerFont.web.js +25 -0
  92. package/lib/module/loadDynamicFont.js +6 -3
  93. package/lib/module/specs/NanoIconViewNativeComponent.ts +9 -6
  94. package/lib/module/symbols/index.android.js +42 -0
  95. package/lib/module/symbols/index.ios.js +35 -0
  96. package/lib/module/symbols/index.js +35 -0
  97. package/lib/module/symbols/index.native.js +12 -0
  98. package/lib/module/symbols/types.js +1 -0
  99. package/lib/module/utils/fingerPrint.js +18 -3
  100. package/lib/module/utils/glyphRuntime.js +36 -2
  101. package/lib/module/utils/naming.js +46 -0
  102. package/lib/module/utils/validateLayerColor.js +24 -0
  103. package/lib/typescript/src/core/glyph/parse.d.ts +1 -0
  104. package/lib/typescript/src/core/pathkit/contours.d.ts +1 -0
  105. package/lib/typescript/src/core/pathkit/winding.d.ts +5 -0
  106. package/lib/typescript/src/core/symbols/contents.d.ts +3 -0
  107. package/lib/typescript/src/core/symbols/knockout.d.ts +4 -0
  108. package/lib/typescript/src/core/symbols/layers.d.ts +37 -0
  109. package/lib/typescript/src/core/symbols/template.d.ts +23 -0
  110. package/lib/typescript/src/core/symbols/vectorDrawable.d.ts +12 -0
  111. package/lib/typescript/src/devServerFont.d.ts +4 -0
  112. package/lib/typescript/src/devServerFont.web.d.ts +4 -0
  113. package/lib/typescript/src/loadDynamicFont.d.ts +1 -0
  114. package/lib/typescript/src/specs/NanoIconViewNativeComponent.d.ts +6 -5
  115. package/lib/typescript/src/symbols/index.android.d.ts +33 -0
  116. package/lib/typescript/src/symbols/index.d.ts +31 -0
  117. package/lib/typescript/src/symbols/index.ios.d.ts +31 -0
  118. package/lib/typescript/src/symbols/index.native.d.ts +8 -0
  119. package/lib/typescript/src/symbols/types.d.ts +24 -0
  120. package/lib/typescript/src/types.d.ts +2 -0
  121. package/lib/typescript/src/utils/fingerPrint.d.ts +11 -0
  122. package/lib/typescript/src/utils/glyphRuntime.d.ts +3 -1
  123. package/lib/typescript/src/utils/naming.d.ts +11 -0
  124. package/lib/typescript/src/utils/validateLayerColor.d.ts +3 -0
  125. package/metro.js +1 -0
  126. package/package.json +26 -2
  127. package/react-native-nano-icons.podspec +4 -1
  128. package/react-native.config.js +10 -0
  129. package/src/specs/NanoIconViewNativeComponent.ts +9 -6
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.preparedSvgCacheKey = preparedSvgCacheKey;
7
+ exports.prepareIconsWithCache = prepareIconsWithCache;
8
+ const node_crypto_1 = __importDefault(require("node:crypto"));
9
+ const node_fs_1 = __importDefault(require("node:fs"));
10
+ const iconPool_1 = require("./iconPool");
11
+ function preparedSvgCacheKey(task, hash) {
12
+ const contentHash = hash ??
13
+ node_crypto_1.default
14
+ .createHash('sha256')
15
+ .update(node_fs_1.default.readFileSync(task.filePath))
16
+ .digest('hex');
17
+ if (task.kind === 'symbol') {
18
+ return `symbol:${task.setName}:${task.file}:${task.prefix}:${contentHash}`;
19
+ }
20
+ return `${task.file}:${task.upm}:${task.safeZone}:${contentHash}`;
21
+ }
22
+ async function prepareIconsWithCache(tasks, concurrency, cache, pool, svgHashByFile) {
23
+ const prepare = (batch) => pool ? pool.prepare(batch) : (0, iconPool_1.prepareIcons)(batch, concurrency);
24
+ if (!cache)
25
+ return prepare(tasks);
26
+ const results = new Array(tasks.length);
27
+ const keys = new Array(tasks.length);
28
+ const misses = [];
29
+ tasks.forEach((task, i) => {
30
+ keys[i] = preparedSvgCacheKey(task, svgHashByFile?.get(task.file));
31
+ const hit = cache.get(keys[i]);
32
+ if (hit)
33
+ results[i] = hit;
34
+ else
35
+ misses.push(i);
36
+ });
37
+ const fresh = await prepare(misses.map((i) => tasks[i]));
38
+ fresh.forEach((result, j) => {
39
+ const i = misses[j];
40
+ results[i] = result;
41
+ cache.set(keys[i], result);
42
+ });
43
+ return results;
44
+ }
@@ -1,5 +1,7 @@
1
1
  import type { NanoLogger } from '../types';
2
2
  import { type PipelineConfig, type PipelinePaths } from './config';
3
+ import { type SvgWorkerPool } from './iconPool';
4
+ import { type PreparedSvgCache } from './preparedSvgCache';
3
5
  export type PipelineResult = {
4
6
  ttfPath: string;
5
7
  glyphmapPath: string;
@@ -14,4 +16,7 @@ export declare function runFontPipeline(config: PipelineConfig, paths: PipelineP
14
16
  logger?: NanoLogger;
15
17
  inputHash?: string;
16
18
  concurrency?: number;
19
+ preparedSvgCache?: PreparedSvgCache;
20
+ svgWorkerPool?: SvgWorkerPool;
21
+ svgHashByFile?: Map<string, string>;
17
22
  }): Promise<PipelineResult>;
@@ -10,6 +10,7 @@ const compile_1 = require("../font/compile");
10
10
  const fontIdentity_1 = require("../../utils/fontIdentity");
11
11
  const config_1 = require("./config");
12
12
  const iconPool_1 = require("./iconPool");
13
+ const preparedSvgCache_1 = require("./preparedSvgCache");
13
14
  /**
14
15
  * Run the font pipeline with given config and paths.
15
16
  * Uses the cached PathKit instance (initialized on first call).
@@ -39,13 +40,14 @@ async function runFontPipeline(config, paths, options) {
39
40
  const codepointToIcon = new Map();
40
41
  const allGlyphs = [];
41
42
  const failed = [];
42
- const results = await (0, iconPool_1.prepareIcons)(files.map((file) => ({
43
+ const results = await (0, preparedSvgCache_1.prepareIconsWithCache)(files.map((file) => ({
44
+ kind: 'font',
43
45
  file,
44
46
  filePath: node_path_1.default.join(paths.inputDir, file),
45
47
  fontFamily: config.fontFamily,
46
48
  upm: config.upm,
47
49
  safeZone: config.safeZone,
48
- })), options?.concurrency ?? (0, iconPool_1.defaultConcurrency)());
50
+ })), options?.concurrency ?? (0, iconPool_1.defaultConcurrency)(), options?.preparedSvgCache, options?.svgWorkerPool, options?.svgHashByFile);
49
51
  for (const result of results) {
50
52
  for (const [level, msg] of result.logs)
51
53
  logger?.[level](msg);
@@ -72,11 +74,6 @@ async function runFontPipeline(config, paths, options) {
72
74
  if (failed.length) {
73
75
  throw new Error(`${failed.length} of ${files.length} icons in [${config.fontFamily}] could not be converted: ${failed.join(', ')}`);
74
76
  }
75
- const glyphmapPath = node_path_1.default.join(paths.outputDir, `${config.fontFamily}.glyphmap.json`);
76
- if (inputHash) {
77
- glyphMap.m.h = inputHash;
78
- }
79
- await promises_1.default.writeFile(glyphmapPath, JSON.stringify(glyphMap), 'utf8');
80
77
  logger?.info(`Compiling TTF…`);
81
78
  const ttfPath = node_path_1.default.join(paths.outputDir, `${config.fontFamily}.ttf`);
82
79
  let ttfBuffer;
@@ -97,8 +94,13 @@ async function runFontPipeline(config, paths, options) {
97
94
  if (config.web && ttfBuffer) {
98
95
  logger?.info(`Compiling WOFF2…`);
99
96
  woff2Path = node_path_1.default.join(paths.outputDir, `${config.fontFamily}.woff2`);
100
- await promises_1.default.writeFile(woff2Path, await (0, compile_1.compileWoff2FromTtf)(ttfBuffer));
97
+ (0, config_1.writeFileAtomic)(woff2Path, await (0, compile_1.compileWoff2FromTtf)(ttfBuffer));
98
+ }
99
+ const glyphmapPath = node_path_1.default.join(paths.outputDir, `${config.fontFamily}.glyphmap.json`);
100
+ if (inputHash) {
101
+ glyphMap.m.h = inputHash;
101
102
  }
103
+ (0, config_1.writeFileAtomic)(glyphmapPath, JSON.stringify(glyphMap));
102
104
  const iconCount = Object.keys(glyphMap.i).length;
103
105
  const elapsed = Date.now() - startTime;
104
106
  const products = woff2Path
@@ -0,0 +1,54 @@
1
+ import { type SvgWorkerPool } from './iconPool';
2
+ import type { SymbolTask } from './prepareSymbol';
3
+ import { type PreparedSvgCache } from './preparedSvgCache';
4
+ import type { NanoLogger } from '../types';
5
+ export type SymbolsPipelineConfig = {
6
+ /** Set name (used for output filenames and the manifest export name). */
7
+ name: string;
8
+ /** Symbol name prefix, e.g. "nano" → "nano.home". */
9
+ prefix: string;
10
+ };
11
+ export type SymbolsPipelinePaths = {
12
+ inputDir: string;
13
+ outputDir: string;
14
+ };
15
+ export type NanoSymbolMap = {
16
+ m: {
17
+ p: string;
18
+ h?: string;
19
+ };
20
+ s: Record<string, string>;
21
+ d: Record<string, string>;
22
+ };
23
+ export type SymbolsPipelineResult = {
24
+ name: string;
25
+ prefix: string;
26
+ /** Directory containing the generated `.symbolset` folders. */
27
+ symbolsDir: string;
28
+ /** The generated `.symbolset` folders. */
29
+ assetDirs: string[];
30
+ /** Directory containing the generated Android VectorDrawable `.xml` files. */
31
+ drawablesDir: string;
32
+ /** The generated VectorDrawable `.xml` file paths. */
33
+ drawableFiles: string[];
34
+ /** The generated types-only `.d.ts` (icon-name + iOS-symbol-name unions). */
35
+ dtsPath: string;
36
+ symbolmapPath: string;
37
+ symbols: Record<string, string>;
38
+ /** Icon → Android drawable resource name (e.g. "home" → "nano_home"). */
39
+ drawables: Record<string, string>;
40
+ };
41
+ /**
42
+ * Run the symbol pipeline: prep each SVG, then emit one `.symbolset` per icon
43
+ * carrying both the monochrome and the multicolor rendering mode, plus its
44
+ * monochrome and original Android VectorDrawables. Also writes a typed manifest and a symbolmap JSON
45
+ * (for build fingerprinting).
46
+ */
47
+ export declare function runSymbolPipeline(config: SymbolsPipelineConfig, paths: SymbolsPipelinePaths, options?: {
48
+ logger?: NanoLogger;
49
+ inputHash?: string;
50
+ concurrency?: number;
51
+ preparedSvgCache?: PreparedSvgCache<SymbolTask>;
52
+ svgWorkerPool?: SvgWorkerPool;
53
+ svgHashByFile?: Map<string, string>;
54
+ }): Promise<SymbolsPipelineResult>;
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runSymbolPipeline = runSymbolPipeline;
7
+ const promises_1 = __importDefault(require("node:fs/promises"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const config_1 = require("./config");
10
+ const iconPool_1 = require("./iconPool");
11
+ const preparedSvgCache_1 = require("./preparedSvgCache");
12
+ const naming_1 = require("../../utils/naming");
13
+ function union(values) {
14
+ if (values.length === 0)
15
+ return 'never';
16
+ return values.map((v) => ` | ${JSON.stringify(v)}`).join('\n');
17
+ }
18
+ /**
19
+ * Types-only manifest (`.d.ts`) — erased by the bundler, so nothing ships in the
20
+ * JS bundle. It augments `NanoSymbolNames` so `nativeNanoSymbol()` accepts this
21
+ * set's filenames with no generic, augments react-navigation's `SFSymbolNames` so
22
+ * the descriptor it returns is accepted as an icon, and exports `${base}Symbol`
23
+ * (iOS asset-catalog names) plus `${base}Name` (SVG filenames).
24
+ *
25
+ * Both augmentations merge across sets, so every set emits its own block.
26
+ */
27
+ function symbolsDts(base, symbols) {
28
+ const iconNames = Object.keys(symbols);
29
+ const symbolNames = Object.values(symbols);
30
+ return `// Generated by react-native-nano-icons — do not edit.
31
+ /** SVG filenames in this set. */
32
+ export type ${base}Name =
33
+ ${union(iconNames)};
34
+
35
+ /** iOS asset-catalog symbol names. */
36
+ export type ${base}Symbol =
37
+ ${union(symbolNames)};
38
+
39
+ /** Lets nativeNanoSymbol() accept this set's icon names (no generic needed). */
40
+ declare module 'react-native-nano-icons/symbols' {
41
+ interface NanoSymbolNames extends Record<${base}Name, true> {}
42
+ }
43
+
44
+ /** Lets react-navigation accept this set's symbols as a tab-bar/header icon. */
45
+ declare module '@react-navigation/native' {
46
+ interface SFSymbolNames extends Record<${base}Symbol, true> {}
47
+ }
48
+ `;
49
+ }
50
+ /**
51
+ * Run the symbol pipeline: prep each SVG, then emit one `.symbolset` per icon
52
+ * carrying both the monochrome and the multicolor rendering mode, plus its
53
+ * monochrome and original Android VectorDrawables. Also writes a typed manifest and a symbolmap JSON
54
+ * (for build fingerprinting).
55
+ */
56
+ async function runSymbolPipeline(config, paths, options) {
57
+ const startTime = Date.now();
58
+ const logger = options?.logger;
59
+ const kind = 'symbol';
60
+ logger?.update(`Building ${kind}s "${config.name}"…`);
61
+ const symbolsDir = node_path_1.default.join(paths.outputDir, `${config.name}.symbols`);
62
+ const drawablesDir = node_path_1.default.join(paths.outputDir, `${config.name}.drawables`);
63
+ const files = (await promises_1.default.readdir(paths.inputDir))
64
+ .filter((f) => f.toLowerCase().endsWith('.svg'))
65
+ .sort();
66
+ const failed = [];
67
+ const results = await (0, preparedSvgCache_1.prepareIconsWithCache)(files.map((file) => ({
68
+ kind: 'symbol',
69
+ file,
70
+ filePath: node_path_1.default.join(paths.inputDir, file),
71
+ setName: config.name,
72
+ prefix: config.prefix,
73
+ })), options?.concurrency ?? (0, iconPool_1.defaultConcurrency)(), options?.preparedSvgCache, options?.svgWorkerPool, options?.svgHashByFile);
74
+ const resourceNameToFile = new Map();
75
+ const assets = [];
76
+ for (const result of results) {
77
+ for (const [level, msg] of result.logs)
78
+ logger?.[level](msg);
79
+ if (result.error !== null) {
80
+ logger?.fail(result.error);
81
+ failed.push(result.file);
82
+ continue;
83
+ }
84
+ if (!result.asset)
85
+ continue;
86
+ // Android resource names are lowercased with every non-[a-z0-9_] run collapsed
87
+ // to "_", so distinct filenames can map to the same name. They must be unique
88
+ // within the set — fail loudly rather than silently renaming, so the runtime
89
+ // helper can derive the name purely from the filename.
90
+ const resourceName = (0, naming_1.toDrawableResourceName)(result.asset.assetName);
91
+ for (const name of [
92
+ resourceName,
93
+ (0, naming_1.toOriginalDrawableResourceName)(resourceName),
94
+ ]) {
95
+ const clashingFile = resourceNameToFile.get(name);
96
+ if (clashingFile) {
97
+ throw new Error(`[react-native-nano-icons] "${config.name}": "${result.file}" and "${clashingFile}" ` +
98
+ `both map to the Android drawable name "${name}". Rename one of the ` +
99
+ `SVGs so they differ by more than case or non-alphanumeric characters.`);
100
+ }
101
+ resourceNameToFile.set(name, result.file);
102
+ }
103
+ assets.push({
104
+ iconName: result.iconName,
105
+ asset: result.asset,
106
+ resourceName,
107
+ });
108
+ }
109
+ if (failed.length) {
110
+ throw new Error(`${failed.length} of ${files.length} icons in [${config.name}] could not be converted: ${failed.join(', ')}`);
111
+ }
112
+ (0, config_1.ensureDir)(paths.outputDir);
113
+ (0, config_1.ensureEmptyDir)(symbolsDir);
114
+ (0, config_1.ensureEmptyDir)(drawablesDir);
115
+ const symbols = {};
116
+ const drawables = {};
117
+ const assetDirs = [];
118
+ const drawableFiles = [];
119
+ for (const { iconName, asset, resourceName } of assets) {
120
+ const assetDir = node_path_1.default.join(symbolsDir, asset.assetDirName);
121
+ await promises_1.default.mkdir(assetDir, { recursive: true });
122
+ await promises_1.default.writeFile(node_path_1.default.join(assetDir, asset.svgFilename), asset.svg, 'utf8');
123
+ await promises_1.default.writeFile(node_path_1.default.join(assetDir, 'Contents.json'), asset.contents, 'utf8');
124
+ const drawableFile = node_path_1.default.join(drawablesDir, `${resourceName}.xml`);
125
+ await promises_1.default.writeFile(drawableFile, asset.vdXml, 'utf8');
126
+ const originalDrawableFile = node_path_1.default.join(drawablesDir, `${(0, naming_1.toOriginalDrawableResourceName)(resourceName)}.xml`);
127
+ await promises_1.default.writeFile(originalDrawableFile, asset.vdOriginalXml, 'utf8');
128
+ symbols[iconName] = asset.assetName;
129
+ drawables[iconName] = resourceName;
130
+ assetDirs.push(assetDir);
131
+ drawableFiles.push(drawableFile, originalDrawableFile);
132
+ }
133
+ const symbolmapPath = node_path_1.default.join(paths.outputDir, `${config.name}.symbolmap.json`);
134
+ const symbolmap = {
135
+ m: {
136
+ p: config.prefix,
137
+ ...(options?.inputHash ? { h: options.inputHash } : {}),
138
+ },
139
+ s: symbols,
140
+ d: drawables,
141
+ };
142
+ (0, config_1.writeFileAtomic)(symbolmapPath, JSON.stringify(symbolmap));
143
+ const base = (0, naming_1.manifestBaseName)(config.name);
144
+ const dtsPath = node_path_1.default.join(paths.outputDir, `${config.name}.symbols.d.ts`);
145
+ (0, config_1.writeFileAtomic)(dtsPath, symbolsDts(base, symbols));
146
+ const count = assetDirs.length;
147
+ const elapsed = Date.now() - startTime;
148
+ logger?.succeed(`Built ${config.name} ${kind}s [${count} ${kind}${count === 1 ? '' : 's'} in ${elapsed}ms]`);
149
+ return {
150
+ name: config.name,
151
+ prefix: config.prefix,
152
+ symbolsDir,
153
+ assetDirs,
154
+ drawablesDir,
155
+ drawableFiles,
156
+ dtsPath,
157
+ symbolmapPath,
158
+ symbols,
159
+ drawables,
160
+ };
161
+ }
@@ -0,0 +1,2 @@
1
+ export declare function symbolsetContentsJson(svgFilename: string): string;
2
+ export declare function catalogRootContentsJson(): string;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ // Asset-catalog Contents.json emitters for custom SF Symbol sets.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.symbolsetContentsJson = symbolsetContentsJson;
5
+ exports.catalogRootContentsJson = catalogRootContentsJson;
6
+ function symbolsetContentsJson(svgFilename) {
7
+ return JSON.stringify({
8
+ info: { author: 'xcode', version: 1 },
9
+ properties: { 'symbol-rendering-intent': 'template' },
10
+ symbols: [{ filename: svgFilename, idiom: 'universal' }],
11
+ }, null, 2);
12
+ }
13
+ function catalogRootContentsJson() {
14
+ return JSON.stringify({ info: { author: 'xcode', version: 1 } }, null, 2);
15
+ }
@@ -0,0 +1,3 @@
1
+ export declare const KNOCKOUT_ATTRIBUTE = "data-nano-knockout";
2
+ export declare const KNOCKOUT_MARKER_FILL = "#fe01fe";
3
+ export declare function markKnockoutFills(svg: string): string | null;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KNOCKOUT_MARKER_FILL = exports.KNOCKOUT_ATTRIBUTE = void 0;
4
+ exports.markKnockoutFills = markKnockoutFills;
5
+ const xmldom_1 = require("@xmldom/xmldom");
6
+ exports.KNOCKOUT_ATTRIBUTE = 'data-nano-knockout';
7
+ exports.KNOCKOUT_MARKER_FILL = '#fe01fe';
8
+ const ELEMENT_NODE = 1;
9
+ const PAINT_PROPERTIES = ['fill', 'stroke'];
10
+ function styleDeclaration(property) {
11
+ return new RegExp(`(^|;)\\s*${property}\\s*:([^;]*)`);
12
+ }
13
+ function explicitPaint(el, property) {
14
+ const fromStyle = el.getAttribute('style')?.match(styleDeclaration(property));
15
+ if (fromStyle)
16
+ return fromStyle[2].trim();
17
+ return el.getAttribute(property);
18
+ }
19
+ function setPaint(el, property, value) {
20
+ const style = el.getAttribute('style');
21
+ if (style !== null) {
22
+ el.setAttribute('style', style.replace(styleDeclaration(property), '$1'));
23
+ }
24
+ el.setAttribute(property, value);
25
+ }
26
+ function markElement(el, isAnnotatedRoot) {
27
+ for (const property of PAINT_PROPERTIES) {
28
+ const paint = explicitPaint(el, property);
29
+ if (paint !== null && paint !== 'none') {
30
+ setPaint(el, property, exports.KNOCKOUT_MARKER_FILL);
31
+ }
32
+ else if (paint === null && isAnnotatedRoot && property === 'fill') {
33
+ setPaint(el, property, exports.KNOCKOUT_MARKER_FILL);
34
+ }
35
+ }
36
+ for (const child of Array.from(el.childNodes)) {
37
+ if (child.nodeType === ELEMENT_NODE)
38
+ markElement(child, false);
39
+ }
40
+ }
41
+ function markKnockoutFills(svg) {
42
+ if (!svg.includes(exports.KNOCKOUT_ATTRIBUTE))
43
+ return null;
44
+ const doc = new xmldom_1.DOMParser().parseFromString(svg, 'image/svg+xml');
45
+ const annotated = Array.from(doc.getElementsByTagName('*')).filter((el) => el.hasAttribute(exports.KNOCKOUT_ATTRIBUTE));
46
+ if (annotated.length === 0)
47
+ return null;
48
+ for (const el of annotated)
49
+ markElement(el, true);
50
+ return new xmldom_1.XMLSerializer().serializeToString(doc);
51
+ }
@@ -0,0 +1,36 @@
1
+ import type { PathKitModule } from '../pathkit/types';
2
+ /**
3
+ * Resolve stacked layers into SF Symbol template layers. Monochrome joins every
4
+ * layer into one nonzero-filled path, multicolor paints each layer on its own:
5
+ * 1. Knockouts: layers annotated with `data-nano-knockout`, or (when nothing is
6
+ * annotated) near-white layers over ink. Their part over ink is emitted with
7
+ * reversed winding, so it cancels the ink beneath it in monochrome while
8
+ * multicolor still paints it in its own fill. Their part over nothing is
9
+ * drawn in both modes.
10
+ * 2. Occlusion: subtract layers above from each layer; ink is never cut by a
11
+ * knockout, so the winding under every knockout is exactly one.
12
+ * In: back→front layers with fills. Out: visible layers in z-order plus the
13
+ * monochrome silhouette.
14
+ */
15
+ export type SymbolLayerInput = {
16
+ d: string;
17
+ fill: string | null;
18
+ knockout?: boolean;
19
+ };
20
+ export type SymbolLayer = {
21
+ d: string;
22
+ fill: string | null;
23
+ };
24
+ export type ResolvedSymbolLayers = {
25
+ layers: SymbolLayer[];
26
+ monochrome: string;
27
+ };
28
+ export declare function isKnockoutFill(fill: string | null): boolean;
29
+ export declare function resolveSymbolLayers(PathKit: PathKitModule, layers: SymbolLayerInput[], options?: {
30
+ onKnockoutLayer?: (index: number) => void;
31
+ }): ResolvedSymbolLayers;
32
+ /**
33
+ * Tight bounding box [x, y, w, h] of path `d` strings in source coords, or null.
34
+ * Used to fit icon content (not the padded viewBox) to the cap band.
35
+ */
36
+ export declare function contentBounds(PathKit: PathKitModule, ds: string[]): [number, number, number, number] | null;
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isKnockoutFill = isKnockoutFill;
4
+ exports.resolveSymbolLayers = resolveSymbolLayers;
5
+ exports.contentBounds = contentBounds;
6
+ const parse_1 = require("../../utils/parse");
7
+ const winding_1 = require("../pathkit/winding");
8
+ function isKnockoutFill(fill) {
9
+ if (fill === null)
10
+ return false;
11
+ const [r, g, b, a] = (0, parse_1.parseColor)(fill);
12
+ return a >= 0.9 && r >= 240 && g >= 240 && b >= 240;
13
+ }
14
+ function knockoutFlags(layers) {
15
+ if (layers.some((l) => l.knockout))
16
+ return layers.map((l) => !!l.knockout);
17
+ const whiteFlags = layers.map((l) => isKnockoutFill(l.fill));
18
+ return whiteFlags.some((w) => !w) ? whiteFlags : layers.map(() => false);
19
+ }
20
+ function pathOps(PathKit) {
21
+ const Ops = PathKit.PathOp ?? {};
22
+ const run = (a, b, op) => {
23
+ if (a.trim() === '')
24
+ return op === (Ops.UNION ?? 1) ? b : '';
25
+ if (b.trim() === '')
26
+ return op === (Ops.INTERSECT ?? 2) ? '' : a;
27
+ const pa = PathKit.FromSVGString(a);
28
+ const pb = PathKit.FromSVGString(b);
29
+ const out = pa && pb ? PathKit.MakeFromOp(pa, pb, op) : null;
30
+ pa?.delete?.();
31
+ pb?.delete?.();
32
+ if (!out)
33
+ return a;
34
+ const d = (0, winding_1.orientedPathData)(PathKit, out);
35
+ out.delete?.();
36
+ return d;
37
+ };
38
+ return {
39
+ difference: (a, b) => run(a, b, Ops.DIFFERENCE ?? 0),
40
+ union: (a, b) => run(a, b, Ops.UNION ?? 1),
41
+ intersect: (a, b) => run(a, b, Ops.INTERSECT ?? 2),
42
+ };
43
+ }
44
+ function resolveWithKnockouts(PathKit, layers, flags, onKnockoutLayer) {
45
+ const ops = pathOps(PathKit);
46
+ const visible = new Array(layers.length).fill('');
47
+ let aboveAll = '';
48
+ let aboveInk = '';
49
+ for (let i = layers.length - 1; i >= 0; i--) {
50
+ const d = layers[i].d;
51
+ visible[i] = ops.difference(d, flags[i] ? aboveAll : aboveInk);
52
+ aboveAll = ops.union(aboveAll, d);
53
+ if (!flags[i])
54
+ aboveInk = ops.union(aboveInk, d);
55
+ }
56
+ const emitted = [];
57
+ let monochrome = '';
58
+ layers.forEach((layer, i) => {
59
+ const region = visible[i];
60
+ if (region.trim() === '')
61
+ return;
62
+ if (!flags[i]) {
63
+ emitted.push({ d: (0, winding_1.canonicalWinding)(PathKit, region), fill: layer.fill });
64
+ monochrome = ops.union(monochrome, region);
65
+ return;
66
+ }
67
+ const inside = ops.intersect(region, monochrome);
68
+ const outside = ops.difference(region, monochrome);
69
+ const parts = [
70
+ inside.trim() === '' ? '' : (0, winding_1.reversedWinding)(PathKit, inside),
71
+ outside.trim() === '' ? '' : (0, winding_1.canonicalWinding)(PathKit, outside),
72
+ ].filter((part) => part !== '');
73
+ if (inside.trim() !== '')
74
+ onKnockoutLayer?.(i);
75
+ emitted.push({ d: parts.join(' '), fill: layer.fill });
76
+ monochrome = ops.union(ops.difference(monochrome, inside), outside);
77
+ });
78
+ return { layers: emitted, monochrome: (0, winding_1.canonicalWinding)(PathKit, monochrome) };
79
+ }
80
+ function resolveOccluded(PathKit, layers) {
81
+ const Ops = PathKit.PathOp ?? {};
82
+ const DIFFERENCE = Ops.DIFFERENCE ?? 0;
83
+ const UNION = Ops.UNION ?? 1;
84
+ const isEmptyD = (d) => d.trim() === '';
85
+ const emitted = [];
86
+ // Walk top → bottom, tracking the union of everything above.
87
+ let above = null;
88
+ for (let i = layers.length - 1; i >= 0; i--) {
89
+ const p = PathKit.FromSVGString(layers[i].d);
90
+ if (!p) {
91
+ emitted.push({ index: i, d: layers[i].d, fill: layers[i].fill });
92
+ continue;
93
+ }
94
+ p.simplify();
95
+ // visible region = path minus everything above
96
+ let visibleD;
97
+ if (above === null) {
98
+ visibleD = p.toSVGString();
99
+ }
100
+ else {
101
+ const visible = PathKit.MakeFromOp(p, above, DIFFERENCE);
102
+ if (visible) {
103
+ visible.simplify();
104
+ visibleD = visible.toSVGString();
105
+ visible.delete?.();
106
+ }
107
+ else {
108
+ visibleD = p.toSVGString();
109
+ }
110
+ }
111
+ if (!isEmptyD(visibleD)) {
112
+ emitted.push({ index: i, d: visibleD, fill: layers[i].fill });
113
+ }
114
+ if (above === null) {
115
+ above = p;
116
+ }
117
+ else {
118
+ const newAbove = PathKit.MakeFromOp(above, p, UNION);
119
+ p.delete?.();
120
+ if (newAbove) {
121
+ newAbove.simplify();
122
+ above.delete?.();
123
+ above = newAbove;
124
+ }
125
+ }
126
+ }
127
+ const monochrome = above?.toSVGString() ?? '';
128
+ above?.delete?.();
129
+ return {
130
+ layers: emitted
131
+ .sort((a, b) => a.index - b.index)
132
+ .map((r) => ({ d: r.d, fill: r.fill })),
133
+ monochrome,
134
+ };
135
+ }
136
+ function resolveSymbolLayers(PathKit, layers, options) {
137
+ const flags = knockoutFlags(layers);
138
+ if (flags.some(Boolean)) {
139
+ return resolveWithKnockouts(PathKit, layers, flags, options?.onKnockoutLayer);
140
+ }
141
+ if (layers.length <= 1) {
142
+ return {
143
+ layers: layers.map((l) => ({ d: l.d, fill: l.fill })),
144
+ monochrome: layers[0]?.d ?? '',
145
+ };
146
+ }
147
+ return resolveOccluded(PathKit, layers);
148
+ }
149
+ /**
150
+ * Tight bounding box [x, y, w, h] of path `d` strings in source coords, or null.
151
+ * Used to fit icon content (not the padded viewBox) to the cap band.
152
+ */
153
+ function contentBounds(PathKit, ds) {
154
+ let minX = Infinity;
155
+ let minY = Infinity;
156
+ let maxX = -Infinity;
157
+ let maxY = -Infinity;
158
+ for (const d of ds) {
159
+ const p = PathKit.FromSVGString(d);
160
+ if (!p)
161
+ continue;
162
+ const b = p.getBounds();
163
+ p.delete?.();
164
+ if (!Number.isFinite(b.fLeft) ||
165
+ !Number.isFinite(b.fTop) ||
166
+ !Number.isFinite(b.fRight) ||
167
+ !Number.isFinite(b.fBottom)) {
168
+ continue;
169
+ }
170
+ if (b.fLeft < minX)
171
+ minX = b.fLeft;
172
+ if (b.fTop < minY)
173
+ minY = b.fTop;
174
+ if (b.fRight > maxX)
175
+ maxX = b.fRight;
176
+ if (b.fBottom > maxY)
177
+ maxY = b.fBottom;
178
+ }
179
+ if (!Number.isFinite(minX) || maxX <= minX || maxY <= minY)
180
+ return null;
181
+ return [minX, minY, maxX - minX, maxY - minY];
182
+ }
@@ -0,0 +1,22 @@
1
+ import type { NanoLogger } from '../types';
2
+ export type SymbolTemplateLayer = {
3
+ /** Path data in source viewBox coordinates (nonzero winding). */
4
+ d: string;
5
+ fill: string | null;
6
+ };
7
+ export declare function layerHexColor(fill: string | null): string;
8
+ export declare function layerClass(layerIndex: number): string;
9
+ /**
10
+ * Build the template SVG for one symbol. Layers are back→front; every layer
11
+ * gets `monochrome-N multicolor-N:custom` classes, with the layer fills
12
+ * declared in a `<style>` block.
13
+ */
14
+ export declare function buildSymbolTemplate(opts: {
15
+ layers: SymbolTemplateLayer[];
16
+ viewBox: [number, number, number, number];
17
+ /** Tight content box `[x, y, w, h]`; used instead of the viewBox when given. */
18
+ contentBounds?: [number, number, number, number];
19
+ /** Shown in the template's Notes group. */
20
+ descriptiveName?: string;
21
+ logger?: NanoLogger;
22
+ }): string;