From 7549e079eab81615d9ab0c7a9d126a5addfb8ecb Mon Sep 17 00:00:00 2001 From: Samuel Kim Date: Fri, 27 Nov 2026 15:35:50 +0900 Subject: [PATCH] =?UTF-8?q?chore:=20=EC=95=84=EC=9D=B4=EC=BD=98=20?= =?UTF-8?q?=EB=8F=99=EA=B8=B0=ED=99=94=20=EB=95=8C=20Code=20Connect=20?= =?UTF-8?q?=EC=95=84=EC=9D=B4=EC=BD=98=20batch=20=EC=9E=AC=EC=83=9D?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: WRP-4914 Co-Authored-By: Claude Opus 5.5 --- figma/README.md | 36 +++- figma/shared/icon-name.ts | 2 +- figma/swiftui/icons.figma.batch.json | 42 ++--- figma/swiftui/icons.figma.batch.ts | 3 +- scripts/icon_code_connect_batch.js | 105 +++++++++++ scripts/icon_sync.js | 24 ++- scripts/tests/icon_code_connect_batch.test.js | 178 ++++++++++++++++++ 7 files changed, 365 insertions(+), 25 deletions(-) create mode 100644 scripts/icon_code_connect_batch.js create mode 100644 scripts/tests/icon_code_connect_batch.test.js diff --git a/figma/README.md b/figma/README.md index 349b107a6..cff9999a2 100644 --- a/figma/README.md +++ b/figma/README.md @@ -10,7 +10,7 @@ Web(React)은 `wanteddev/montage-web`의 `figma/`, Android(Compose)는 `wantedde | `figma.config.json` | 라벨(`SwiftUI`), 대상 파일, Figma URL 치환표(`` 등) | | `package.json`, `tsconfig.json` | Code Connect CLI 버전 고정(`@figma/code-connect` 2.1.1)과 템플릿 타입 체크 설정 | | `swiftui/*.figma.ts` | 컴포넌트별 템플릿 (Figma variant → `Montage.*` 뷰 호출) | -| `swiftui/icons.figma.batch.*` | 아이콘 일괄 매핑 | +| `swiftui/icons.figma.batch.*` | 아이콘 일괄 매핑. `.json`은 아이콘 동기화가 만든다([아이콘 batch](#아이콘-batch) 참고) | | `shared/` | 템플릿 공통 헬퍼. Compose 템플릿과 함께 쓰던 파일을 그대로 가져와 Compose용 코드도 일부 남아 있습니다 | `.figma.ts`는 SwiftPM 빌드 대상이 아니므로 라이브러리 빌드에 영향이 없습니다. @@ -39,6 +39,40 @@ FIGMA_ACCESS_TOKEN=<개인 토큰> npx figma connect publish -c figma.config.jso - Figma main 파일 편집 권한, Dev 또는 Full seat - `Code Connect: Write` 범위의 개인 access token. 토큰은 커밋하지 않습니다. +## 아이콘 batch + +`swiftui/icons.figma.batch.json`은 아이콘 노드와 `Icon` case를 잇는 목록입니다. **손으로 고치지 않습니다.** 아이콘 동기화가 `Icon.xcassets`, `Icon` enum과 함께 다시 만듭니다. + +### 갱신 흐름 + +1. `/montage-icon-sync`(또는 Actions의 `Figma Icon Sync` 수동 실행)로 아이콘을 동기화합니다. +2. sync job(montage-web 재사용 워크플로)이 Figma API로 아이콘 SVG와 `output/result.json`을 받습니다. +3. `scripts/icon_sync.js`가 SVG로 에셋과 enum을 갱신하고, `result.json`으로 batch를 다시 만듭니다. 결과는 한 커밋에 같이 들어갑니다. +4. 동기화 PR이 머지되면 [게시](#수정--확인--게시)합니다. **게시는 자동이 아닙니다.** 게시 전에는 새 아이콘에 Dev Mode 스니펫이 나오지 않습니다. + +### 노드 ID 출처 + +`result.json`의 `id`는 0-Component 파일 `Icon` 섹션(Normal, Color/Logo, Color/Normal, Navigation)의 **컴포넌트 세트** 노드 ID입니다. 탐색 경로는 montage-web `.github/workflows/figma-icon-sync.yml`의 `ROOT_TRAVERSE_*_IDS`에 있습니다. Figma에서 컴포넌트 세트를 선택하고 링크를 복사하면 URL의 `node-id`와 같습니다. + +- 세트 하나에 아이콘이 여러 개면 노드 하나에 variant가 여러 개 붙습니다(예: `arrowDown`, `arrowDownThick`). +- 같은 아이콘이 세트 두 곳에 있으면 노드마다 항목이 생깁니다(예: `blankColor`). +- variant `name`은 Figma `Name` 속성 값이라 `Color` 접미사를 뗍니다. `component`는 `Icon` + 파스칼 케이스입니다. + +`result.json`이 없거나 SVG 목록과 어긋나면 `icon_sync.js`는 파일을 하나도 바꾸지 않고 실패합니다. + +### 검증 + +```bash +# 레포 루트에서: batch가 생성기 출력과 같은지, 이름이 Icon enum case와 1:1인지 +npm test + +# figma/에서: 템플릿 타입 체크와 parse (icons.figma.batch.json은 노드 수가 나옵니다. 아이콘 수와 다릅니다) +npm run typecheck +npm run parse +``` + +`npm test`는 CI에서 돌지 않습니다. batch나 `Icon` enum을 건드린 PR은 올리기 전에 로컬에서 직접 돌립니다. `Icon` enum에만 case를 손으로 넣으면 1:1 테스트가 실패합니다. 아이콘은 Figma에 올린 뒤 동기화로 추가합니다. + ## 주의 - **`label`(`SwiftUI`)을 바꾸지 않습니다.** 바꾸면 같은 컴포넌트에 SwiftUI 스니펫이 두 벌 게시되고, Figma MCP가 `clientFrameworks: "swiftui"`로 스니펫을 고르지 못합니다. - **내릴 때는 `--node`와 `--label`을 함께 씁니다.** 빼면 React·Compose 스니펫까지 지워질 수 있습니다. diff --git a/figma/shared/icon-name.ts b/figma/shared/icon-name.ts index 2db0e7bab..11d30f857 100644 --- a/figma/shared/icon-name.ts +++ b/figma/shared/icon-name.ts @@ -3,7 +3,7 @@ // 입력은 Web 아이콘 컴포넌트명에서 'Icon'을 뗀 이름(예: IconAgentColor → agentColor) // 또는 Figma 아이콘 인스턴스의 Name variant(예: heart). -/** iOS `Icon` enum case. 360/360 이름이 그대로 일치한다. */ +/** iOS `Icon` enum case. 이름이 그대로 일치한다(scripts/tests/icon_code_connect_batch.test.js에서 확인). */ export const iosIcon = (name: string): string => `.${name}`; const snake = (name: string): string => diff --git a/figma/swiftui/icons.figma.batch.json b/figma/swiftui/icons.figma.batch.json index 18b15b09b..e40309402 100644 --- a/figma/swiftui/icons.figma.batch.json +++ b/figma/swiftui/icons.figma.batch.json @@ -246,6 +246,16 @@ } ] }, + { + "url": "?node-id=8-731", + "component": "IconBlankColor", + "variants": [ + { + "name": "blank", + "component": "IconBlankColor" + } + ] + }, { "url": "?node-id=13090-23582", "component": "IconBold", @@ -1654,6 +1664,16 @@ } ] }, + { + "url": "?node-id=40167-141755", + "component": "IconLogoInstagramColor", + "variants": [ + { + "name": "logoInstagram", + "component": "IconLogoInstagramColor" + } + ] + }, { "url": "?node-id=9258-18856", "component": "IconLogoKakao", @@ -2805,27 +2825,7 @@ "component": "IconZepFastFill" } ] - }, - { - "url": "?node-id=40167-141755", - "component": "IconLogoInstagramColor", - "variants": [ - { - "name": "logoInstagram", - "component": "IconLogoInstagramColor" - } - ] - }, - { - "url": "?node-id=8-731", - "component": "IconBlankColor", - "variants": [ - { - "name": "blank", - "component": "IconBlankColor" - } - ] } ] } -] \ No newline at end of file +] diff --git a/figma/swiftui/icons.figma.batch.ts b/figma/swiftui/icons.figma.batch.ts index 428be33b9..f8dfa3449 100644 --- a/figma/swiftui/icons.figma.batch.ts +++ b/figma/swiftui/icons.figma.batch.ts @@ -1,4 +1,5 @@ -// [2026-11-16] 아이콘 노드 → iOS `Icon` case. 노드 목록은 montage-web figma/icons/icons.figma.batch.json과 같다. +// [2026-11-16] 아이콘 노드 → iOS `Icon` case. +// 노드 목록(icons.figma.batch.json)은 scripts/icon_sync.js가 아이콘 동기화 때 다시 만든다. 손으로 고치지 않는다. import figma from 'figma'; import { iosIcon, nameFromComponent } from '../shared/icon-name'; diff --git a/scripts/icon_code_connect_batch.js b/scripts/icon_code_connect_batch.js new file mode 100644 index 000000000..d950f3567 --- /dev/null +++ b/scripts/icon_code_connect_batch.js @@ -0,0 +1,105 @@ +// Figma 아이콘 sync 결과 → SwiftUI Code Connect 아이콘 batch(figma/swiftui/icons.figma.batch.json) +// +// figma-icon-sync 워크플로의 sync job(montage-web 재사용 워크플로)이 output/result.json에 +// 아이콘마다 { id: 컴포넌트 세트 노드 ID('40167-141864'), name: SVG 파일명('agentColor') }를 남긴다. +// icon_sync.js가 이 파일로 batch를 다시 만들어, 아이콘이 추가·삭제되면 batch도 같은 커밋에 반영된다. +// +// 출력 규칙(montage-web scripts/figma-icon.mjs와 같은 구조) +// - 노드(url) 하나에 아이콘 variant 여러 개가 묶일 수 있다(예: arrowDown, arrowDownThick). +// - 같은 아이콘이 노드 두 곳에 있으면 노드마다 항목을 둔다(예: blankColor). +// - variant name은 Figma Name variant 값이라 'Color' 접미사를 뗀다. component는 'Icon' + 파스칼 케이스. +// - 순서는 이름 → 노드 ID 순으로 정렬해 result.json 순서와 무관하게 같은 결과가 나오게 한다. +// +// montage-web과 다른 점: 웹은 중복 노드를 노드 ID로만 걸러, 아이콘 X가 노드 A·B에 있고 B에 다른 아이콘도 있으면 +// B의 X를 빠뜨린다(그 인스턴스는 템플릿 fallback으로 다른 아이콘 스니펫이 나온다). 여기서는 (노드 ID, 이름) 쌍을 +// 모두 넣는다. 웹 로직으로 되돌리지 않는다. + +const BATCH_PATH = 'figma/swiftui/icons.figma.batch.json'; +const NODE_ID_PATTERN = /^\d+-\d+$/; + +const componentName = (name) => `Icon${name.charAt(0).toUpperCase()}${name.slice(1)}`; + +const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + +/** + * @param {Array<{ id: string; name: string }>} entries output/result.json 항목 + * @returns {string} icons.figma.batch.json 내용(끝 줄바꿈 포함) + */ +const buildIconBatch = (entries) => { + if (!Array.isArray(entries) || entries.length === 0) { + throw new Error('result.json에 아이콘 항목이 없습니다.'); + } + + const seen = new Set(); + const unique = []; + for (const entry of entries) { + const { id, name } = entry ?? {}; + if (typeof name !== 'string' || !/^[a-z][A-Za-z0-9]*$/.test(name)) { + throw new Error(`아이콘 이름 형식이 아닙니다: ${JSON.stringify(entry)}`); + } + if (typeof id !== 'string' || !NODE_ID_PATTERN.test(id)) { + throw new Error(`노드 ID 형식이 아닙니다: ${JSON.stringify(entry)}`); + } + const key = `${id} ${name}`; + if (!seen.has(key)) { + seen.add(key); + unique.push({ id, name }); + } + } + + unique.sort((a, b) => compare(a.name, b.name) || compare(a.id, b.id)); + + const variantsByUrl = new Map(); + for (const { id, name } of unique) { + const url = `?node-id=${id}`; + const variants = variantsByUrl.get(url) ?? []; + variants.push({ name: name.replace(/Color$/, ''), component: componentName(name) }); + variantsByUrl.set(url, variants); + } + + const batch = [ + { + templateFile: './icons.figma.batch.ts', + components: [...variantsByUrl].map(([url, variants]) => ({ + url, + component: variants[0].component, + variants, + })), + }, + ]; + + return `${JSON.stringify(batch, null, 2)}\n`; +}; + +/** batch에 들어간 아이콘 이름(= SVG 파일명 = Icon enum case) 목록 */ +const iconNamesInBatch = (batchJson) => { + const names = new Set(); + for (const group of JSON.parse(batchJson)) { + for (const component of group.components) { + for (const { component: c } of component.variants) { + const n = c.replace(/^Icon/, ''); + names.add(n.charAt(0).toLowerCase() + n.slice(1)); + } + } + } + return [...names].sort(compare); +}; + +/** 두 이름 목록이 다르면 차이를 담아 throw */ +const assertSameNames = (expected, actual, expectedLabel, actualLabel) => { + const a = new Set(expected); + const b = new Set(actual); + const onlyExpected = [...a].filter((n) => !b.has(n)).sort(compare); + const onlyActual = [...b].filter((n) => !a.has(n)).sort(compare); + if (onlyExpected.length || onlyActual.length) { + throw new Error( + [ + `${expectedLabel}와 ${actualLabel}의 아이콘 이름이 다릅니다.`, + `${expectedLabel}에만 있음: ${onlyExpected.join(', ') || '(없음)'}`, + `${actualLabel}에만 있음: ${onlyActual.join(', ') || '(없음)'}`, + ].join('\n'), + ); + } +}; + +module.exports = { BATCH_PATH, buildIconBatch, iconNamesInBatch, assertSameNames }; diff --git a/scripts/icon_sync.js b/scripts/icon_sync.js index 73d53717a..67a149276 100644 --- a/scripts/icon_sync.js +++ b/scripts/icon_sync.js @@ -1,5 +1,6 @@ const fs = require('fs'); const path = require('path'); +const { BATCH_PATH, buildIconBatch, iconNamesInBatch, assertSameNames } = require('./icon_code_connect_batch'); const outputDir = './output'; const iconAssetsDir = './Sources/Montage/Asset/Icon.xcassets'; @@ -10,6 +11,20 @@ const main = async () => { const icons = outputs.filter((filename) => filename.endsWith('.svg')); + // Code Connect 아이콘 batch는 파일을 건드리기 전에 만들고 검증한다. + // result.json이 없거나 SVG 목록과 어긋나면 여기서 멈춰 에셋·enum만 바뀐 커밋이 생기지 않게 한다. + const resultPath = path.join(outputDir, 'result.json'); + if (!fs.existsSync(resultPath)) { + throw new Error(`${resultPath}가 없어 Code Connect 아이콘 batch를 만들 수 없습니다.`); + } + const iconBatch = buildIconBatch(JSON.parse(fs.readFileSync(resultPath, 'utf8'))); + assertSameNames( + icons.map((filename) => filename.replace(/\.svg$/, '')), + iconNamesInBatch(iconBatch), + 'SVG', + 'result.json' + ); + // clean up start const iconAssets = fs .readdirSync('./Sources/Montage/Asset/Icon.xcassets', 'utf8') @@ -106,10 +121,17 @@ const main = async () => { fs.writeFileSync(swiftFilePath, swiftFileContent, 'utf-8'); // swift file update end + // Code Connect 아이콘 batch 갱신 (figma/README.md 참고) + fs.writeFileSync(BATCH_PATH, iconBatch, 'utf-8'); + // remove output directory fs.rmSync(outputDir, { recursive: true, force: true }); console.log('DONE!'); }; -main(); +// 실패하면 exit code를 1로 남겨 워크플로가 커밋 단계로 넘어가지 않게 한다. +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/scripts/tests/icon_code_connect_batch.test.js b/scripts/tests/icon_code_connect_batch.test.js new file mode 100644 index 000000000..86c3a255b --- /dev/null +++ b/scripts/tests/icon_code_connect_batch.test.js @@ -0,0 +1,178 @@ +// Code Connect 아이콘 batch 생성(icon_code_connect_batch.js)과 icon_sync.js 연동 테스트 +// +// - 커밋된 batch가 생성기가 내는 정규화된 형태인지(순서·name/component 정합성. 노드 ID 값 자체는 확인하지 못한다) +// - batch 아이콘 이름이 Icon enum case와 1:1인지 +// - icon_sync.js가 가짜 레포에서 batch를 쓰고, result.json이 어긋나면 아무것도 바꾸지 않는지 +// +// CI에서는 돌지 않는다. 레포 루트에서 `npm test`로 실행한다. + +const test = require('node:test'); +const { after } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const { BATCH_PATH, buildIconBatch, iconNamesInBatch } = require('../icon_code_connect_batch'); + +const REPO_ROOT = path.resolve(__dirname, '../..'); +const ICON_SWIFT_REL = 'Sources/Montage/1 Components/9 Utilities/Icon.swift'; + +const readCommittedBatch = () => fs.readFileSync(path.join(REPO_ROOT, BATCH_PATH), 'utf8'); + +/** batch → result.json 항목(노드 ID, SVG 파일명)으로 되돌린다 */ +const entriesFromBatch = (batchJson) => + JSON.parse(batchJson).flatMap((group) => + group.components.flatMap(({ url, variants }) => + variants.map(({ component }) => { + const n = component.replace(/^Icon/, ''); + return { id: url.split('node-id=')[1], name: n.charAt(0).toLowerCase() + n.slice(1) }; + }) + ) + ); + +const iconEnumCases = (swift) => { + const body = swift.match(/public enum Icon: String, CaseIterable\s*\{\s*\n([\s\S]*?)\n\}/)[1]; + return body + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.startsWith('case ')) + .map((line) => line.slice('case '.length)); +}; + +test('커밋된 batch가 생성기 출력 형태와 같다', () => { + const committed = readCommittedBatch(); + assert.equal(buildIconBatch(entriesFromBatch(committed)), committed); +}); + +test('batch 아이콘 이름이 Icon enum case와 1:1이다', () => { + const cases = iconEnumCases(fs.readFileSync(path.join(REPO_ROOT, ICON_SWIFT_REL), 'utf8')); + assert.deepEqual(iconNamesInBatch(readCommittedBatch()), [...cases].sort()); +}); + +test('노드별로 묶고, 입력 순서와 무관하게 같은 결과를 낸다', () => { + const entries = [ + { id: '8-731', name: 'blankColor' }, + { id: '6362-15083', name: 'arrowDownThick' }, + { id: '40167-141716', name: 'blankColor' }, + { id: '6362-15083', name: 'arrowDown' }, + { id: '6362-15083', name: 'arrowDown' }, + ]; + const out = buildIconBatch(entries); + assert.equal(buildIconBatch([...entries].reverse()), out); + assert.deepEqual(JSON.parse(out)[0].components, [ + { + url: '?node-id=6362-15083', + component: 'IconArrowDown', + variants: [ + { name: 'arrowDown', component: 'IconArrowDown' }, + { name: 'arrowDownThick', component: 'IconArrowDownThick' }, + ], + }, + { + url: '?node-id=40167-141716', + component: 'IconBlankColor', + variants: [{ name: 'blank', component: 'IconBlankColor' }], + }, + { + url: '?node-id=8-731', + component: 'IconBlankColor', + variants: [{ name: 'blank', component: 'IconBlankColor' }], + }, + ]); +}); + +test('형식이 잘못된 항목은 거부한다', () => { + assert.throws(() => buildIconBatch([])); + assert.throws(() => buildIconBatch([{ id: '1:2', name: 'heart' }])); + assert.throws(() => buildIconBatch([{ id: '1-2', name: 'Heart' }])); +}); + +// --- icon_sync.js 연동 --- + +const ICON_SWIFT_FIXTURE = `import SwiftUI + +public enum Icon: String, CaseIterable { + case heart +} +`; + +const fakeRepos = []; +after(() => fakeRepos.forEach((root) => fs.rmSync(root, { recursive: true, force: true }))); + +const makeFakeRepo = ({ svgs, result }) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'icon-sync-')); + fakeRepos.push(root); + fs.mkdirSync(path.join(root, 'scripts')); + for (const file of ['icon_sync.js', 'icon_code_connect_batch.js']) { + fs.copyFileSync(path.join(REPO_ROOT, 'scripts', file), path.join(root, 'scripts', file)); + } + fs.mkdirSync(path.join(root, 'Sources/Montage/Asset/Icon.xcassets/heart.imageset'), { recursive: true }); + fs.mkdirSync(path.dirname(path.join(root, ICON_SWIFT_REL)), { recursive: true }); + fs.writeFileSync(path.join(root, ICON_SWIFT_REL), ICON_SWIFT_FIXTURE); + fs.mkdirSync(path.join(root, 'figma/swiftui'), { recursive: true }); + fs.writeFileSync(path.join(root, BATCH_PATH), 'OLD\n'); + fs.mkdirSync(path.join(root, 'output')); + for (const name of svgs) { + fs.writeFileSync(path.join(root, 'output', `${name}.svg`), ''); + } + if (result) { + fs.writeFileSync(path.join(root, 'output/result.json'), JSON.stringify(result)); + } + return root; +}; + +const runIconSync = (root) => + spawnSync(process.execPath, ['scripts/icon_sync.js'], { cwd: root, encoding: 'utf8' }); + +test('icon_sync.js가 에셋·enum과 함께 batch를 갱신한다', () => { + const root = makeFakeRepo({ + svgs: ['heart', 'agentColor'], + result: [ + { id: '1-2', name: 'heart', description: '' }, + { id: '3-4', name: 'agentColor', description: '' }, + ], + }); + const run = runIconSync(root); + assert.equal(run.status, 0, run.stderr); + + assert.deepEqual(iconEnumCases(fs.readFileSync(path.join(root, ICON_SWIFT_REL), 'utf8')), ['agentColor', 'heart']); + const batch = fs.readFileSync(path.join(root, BATCH_PATH), 'utf8'); + assert.deepEqual(iconNamesInBatch(batch), ['agentColor', 'heart']); + assert.equal(JSON.parse(batch)[0].components[0].url, '?node-id=3-4'); +}); + +test('result.json이 없거나 SVG와 어긋나면 아무 파일도 바꾸지 않고 실패한다', () => { + const cases = [ + { label: 'result.json 없음', result: undefined, message: /result\.json가 없어/ }, + { label: 'SVG에만 있음', result: [{ id: '1-2', name: 'heart' }], message: /SVG에만 있음: agentColor/ }, + { + label: 'result.json에만 있음', + result: [ + { id: '1-2', name: 'heart' }, + { id: '3-4', name: 'agentColor' }, + { id: '5-6', name: 'bell' }, + ], + message: /result\.json에만 있음: bell/, + }, + { + label: '노드 ID 형식 오류', + result: [ + { id: '1:2', name: 'heart' }, + { id: '3-4', name: 'agentColor' }, + ], + message: /노드 ID 형식이 아닙니다/, + }, + ]; + for (const { label, result, message } of cases) { + const root = makeFakeRepo({ svgs: ['heart', 'agentColor'], result }); + const run = runIconSync(root); + assert.notEqual(run.status, 0, label); + assert.match(run.stderr, message, label); + assert.equal(fs.readFileSync(path.join(root, BATCH_PATH), 'utf8'), 'OLD\n', label); + assert.equal(fs.readFileSync(path.join(root, ICON_SWIFT_REL), 'utf8'), ICON_SWIFT_FIXTURE, label); + assert.ok(fs.existsSync(path.join(root, 'Sources/Montage/Asset/Icon.xcassets/heart.imageset')), label); + assert.ok(fs.existsSync(path.join(root, 'output')), label); + } +});