diff --git a/package-lock.json b/package-lock.json index 4fc0f9b..164c218 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@kri/common": "^0.19.5", + "@kri/common": "^0.20.0", "@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", @@ -41,13 +41,14 @@ "@tiptap/starter-kit": "^3.12.0", "class-variance-authority": "^0.7.1", "cmdk": "^1.1.1", + "cn": "0.5.2", "date-fns": "^4.4.0", "dompurify": "^3.4.10", "echarts": "^6.1.0", "echarts-for-react": "^3.0.6", "jotai": "^2.15.1", "lucide-react": "^0.553.0", - "next": "^16.0.7", + "next": "^16.4.6", "next-themes": "^0.4.6", "prettier": "^3.9.6", "qrcode": "^1.5.4", @@ -60,13 +61,13 @@ }, "devDependencies": { "@tailwindcss/postcss": "^4", - "@types/node": "^20", + "@types/node": "^24.19.2", "@types/qrcode": "^1.5.6", "@types/react": "^19", "@types/react-dom": "^19", "babel-plugin-react-compiler": "1.0.0", "eslint": "^9", - "eslint-config-next": "^16.0.7", + "eslint-config-next": "^16.4.6", "tailwindcss": "^4", "tw-animate-css": "^1.4.0", "typescript": "^5" @@ -1194,14 +1195,13 @@ } }, "node_modules/@kri/common": { - "version": "0.19.5", - "resolved": "https://gitea.kric.com/api/packages/KRi/npm/%40kri%2Fcommon/-/0.19.5/common-0.19.5.tgz", - "integrity": "sha512-Ib+fO3cak17pcRbmxME7m9XwmiWYN8LM4gA8ZhCmRvEv4dopCTY0b2qO80CJXqUybFV4jRRh50+OajANIRyw4w==", + "version": "0.20.0", + "resolved": "https://gitea.kric.com/api/packages/KRi/npm/%40kri%2Fcommon/-/0.20.0/common-0.20.0.tgz", + "integrity": "sha512-v6pLvFxePWmdSqG5cK63XwFNrmu4aiZQ1WprKktKVz9CQLpKAKPauQ2mvlQkSn70HXRaJmdwQXUpZHQBFZoE0Q==", "license": "UNLICENSED", "dependencies": { - "clsx": "^2.1.1", - "crypto-js": "^4.2.0", - "tailwind-merge": "^3.4.0" + "cn": "0.5.2", + "crypto-js": "^4.2.0" }, "peerDependencies": { "@tanstack/react-query": ">=5 <6", @@ -1233,15 +1233,15 @@ } }, "node_modules/@next/env": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.2.tgz", - "integrity": "sha512-nTUTFH7G5/J/fmpkjVLegOkqyKOP0CEsJcMsyO4UCYeN1su+YMW/MfaSErnJskL7XM+UDK6aTvslxsRCyya/sA==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.6.tgz", + "integrity": "sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==", "license": "MIT" }, "node_modules/@next/eslint-plugin-next": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.2.tgz", - "integrity": "sha512-gCTWlw0e+Y6kajpFyKKgA195jUJCRhlzJE0lV7ufe8a+ghIsANWZ0/FiJwg6DuOG1+OvRbcZDcFBoRh3mNJx0g==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.6.tgz", + "integrity": "sha512-HdqERVOafOD8JaUSAkwf9aSu/1rsHlkN8C5GcXYBH3C/z1MxBhZFxB5rz/xqMMRiIj7r9tIv8OCLQ9JWUxCvWA==", "dev": true, "license": "MIT", "dependencies": { @@ -1250,9 +1250,9 @@ } }, "node_modules/@next/swc-darwin-arm64": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.2.tgz", - "integrity": "sha512-ONkhFvZNFWlsEHOM/81AtxdyuJP2KRYKYR0JxPwvcu1AuPMMMgcL+wW2luldJvMtZwKtUxoSkCychW5wIeoYSw==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.6.tgz", + "integrity": "sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg==", "cpu": [ "arm64" ], @@ -1266,9 +1266,9 @@ } }, "node_modules/@next/swc-darwin-x64": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.2.tgz", - "integrity": "sha512-luPCMbOsCoaF+kXJEUjmjmOZg1lC3BflhmUu+ZmW4tBu2vW/4AXak8JBFvePizGkxVmNiAw/r9ra+6UviCWtWQ==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.6.tgz", + "integrity": "sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA==", "cpu": [ "x64" ], @@ -1282,12 +1282,15 @@ } }, "node_modules/@next/swc-linux-arm64-gnu": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.2.tgz", - "integrity": "sha512-xhwFTAncJyaCNy5KqKKuKaIIdCy1/1ZV1s5S1G0hhT7wGMkDTlfJ6aQbfRFnIG/s3/kDrxQ8aycVe+c5QnP8ow==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.6.tgz", + "integrity": "sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA==", "cpu": [ "arm64" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -1298,12 +1301,15 @@ } }, "node_modules/@next/swc-linux-arm64-musl": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.2.tgz", - "integrity": "sha512-T1PNmfbPcxr5ndtWUL/3wQtLXsz808lq6sc2GrNT5k2oquF7UyqZddHSuAewHVsWsGXe6nsl9HoN1YNriVjuSg==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.6.tgz", + "integrity": "sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA==", "cpu": [ "arm64" ], + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -1314,12 +1320,15 @@ } }, "node_modules/@next/swc-linux-x64-gnu": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.2.tgz", - "integrity": "sha512-N9cDUOCGtkJG5PNKDFZUF3xXndrJJcpLp121uAGjIGvO/U2p9tfdNOM9htj7+5f72l0m8rMw/cvYacUJBQoudg==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.6.tgz", + "integrity": "sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ==", "cpu": [ "x64" ], + "libc": [ + "glibc" + ], "license": "MIT", "optional": true, "os": [ @@ -1330,12 +1339,15 @@ } }, "node_modules/@next/swc-linux-x64-musl": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.2.tgz", - "integrity": "sha512-yY2uh1YhX6ufuYy2FCbw1dqblbhI57GLYAJfCkqD9auTv6pLrH67Uccjc3QMKBeCYAG6lkgu08ExmX1bbjejjQ==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.6.tgz", + "integrity": "sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA==", "cpu": [ "x64" ], + "libc": [ + "musl" + ], "license": "MIT", "optional": true, "os": [ @@ -1346,9 +1358,9 @@ } }, "node_modules/@next/swc-win32-arm64-msvc": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.2.tgz", - "integrity": "sha512-j/ArWRIHpMMB6wYLMhr2puTguBt70lNU/Cmjl9p6dTDE8DGknYJMP9PdwPk2dqpCNL/KIX9yfngDvIesxJPmsg==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.6.tgz", + "integrity": "sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ==", "cpu": [ "arm64" ], @@ -1362,9 +1374,9 @@ } }, "node_modules/@next/swc-win32-x64-msvc": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.2.tgz", - "integrity": "sha512-AA4edyWHDko3NCSo0x6GomsdgFb0oR1J3MXU1b5xt6FRFg4AucrMPW3S0hCe/9onU0O1BbpGQBsqo1r0Gneu1g==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.6.tgz", + "integrity": "sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g==", "cpu": [ "x64" ], @@ -3811,12 +3823,13 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.19.25", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.25.tgz", - "integrity": "sha512-ZsJzA5thDQMSQO788d7IocwwQbI8B5OPzmqNvpf3NY/+MHDAS759Wo0gd2WQeXYt5AAAQjzcrTVC6SKCuYgoCQ==", + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", "dev": true, + "license": "MIT", "dependencies": { - "undici-types": "~6.21.0" + "undici-types": ">=7.24.0 <7.24.7" } }, "node_modules/@types/qrcode": { @@ -4947,6 +4960,18 @@ "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, + "node_modules/cn": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.5.2.tgz", + "integrity": "sha512-wm10E6iuJ37rALOw3D+3cfaXXZSLNMh2uxpQn3dNICqfJM59yXqgbA9/9Iiz155j5kYNLdK6WreNdW3NQtx3OQ==", + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/codepage": { "version": "1.15.0", "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", @@ -5516,13 +5541,13 @@ } }, "node_modules/eslint-config-next": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.2.tgz", - "integrity": "sha512-P33vjcETMXc+qBjpF77TeJHZLzk6cPcTy8KjpxLucYB3mCIFIORMcZ+cBXcAiIYjE5RM7jyknEEOwMNdnx/ADQ==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.6.tgz", + "integrity": "sha512-IBGGrVf9E6pL0NGL0hmeicVGeSyv1VEzIWq6IecDqkw+YFByhEtDJS9u1r6s6a1VxK6rssh69KyNFQUgfaacqw==", "dev": true, "license": "MIT", "dependencies": { - "@next/eslint-plugin-next": "16.4.2", + "@next/eslint-plugin-next": "16.4.6", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", @@ -7367,12 +7392,12 @@ "dev": true }, "node_modules/next": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/next/-/next-16.4.2.tgz", - "integrity": "sha512-r+oBJojfefUjOiWkBhXgLS+igxX/7BWyK59uHnyOyplMSLtBZ+QLP3okrdYTbrfrbrmNTVWLBPaHDX9KRaIt3w==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/next/-/next-16.4.6.tgz", + "integrity": "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA==", "license": "MIT", "dependencies": { - "@next/env": "16.4.2", + "@next/env": "16.4.6", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -7386,14 +7411,14 @@ "node": ">=20.9.0" }, "optionalDependencies": { - "@next/swc-darwin-arm64": "16.4.2", - "@next/swc-darwin-x64": "16.4.2", - "@next/swc-linux-arm64-gnu": "16.4.2", - "@next/swc-linux-arm64-musl": "16.4.2", - "@next/swc-linux-x64-gnu": "16.4.2", - "@next/swc-linux-x64-musl": "16.4.2", - "@next/swc-win32-arm64-msvc": "16.4.2", - "@next/swc-win32-x64-msvc": "16.4.2", + "@next/swc-darwin-arm64": "16.4.6", + "@next/swc-darwin-x64": "16.4.6", + "@next/swc-linux-arm64-gnu": "16.4.6", + "@next/swc-linux-arm64-musl": "16.4.6", + "@next/swc-linux-x64-gnu": "16.4.6", + "@next/swc-linux-x64-musl": "16.4.6", + "@next/swc-win32-arm64-msvc": "16.4.6", + "@next/swc-win32-x64-msvc": "16.4.6", "sharp": "^0.35.5" }, "peerDependencies": { @@ -8816,15 +8841,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/tailwind-merge": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz", - "integrity": "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/dcastil" - } - }, "node_modules/tailwindcss": { "version": "4.1.17", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.17.tgz", @@ -9096,10 +9112,11 @@ } }, "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" }, "node_modules/unrs-resolver": { "version": "1.11.1", diff --git a/package.json b/package.json index 13fc3a9..5fff0b5 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@kri/common": "^0.19.5", + "@kri/common": "^0.20.0", "@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", @@ -42,13 +42,14 @@ "@tiptap/starter-kit": "^3.12.0", "class-variance-authority": "^0.7.1", "cmdk": "^1.1.1", + "cn": "0.5.2", "date-fns": "^4.4.0", "dompurify": "^3.4.10", "echarts": "^6.1.0", "echarts-for-react": "^3.0.6", "jotai": "^2.15.1", "lucide-react": "^0.553.0", - "next": "^16.0.7", + "next": "^16.4.6", "next-themes": "^0.4.6", "prettier": "^3.9.6", "qrcode": "^1.5.4", @@ -61,13 +62,13 @@ }, "devDependencies": { "@tailwindcss/postcss": "^4", - "@types/node": "^20", + "@types/node": "^24.19.2", "@types/qrcode": "^1.5.6", "@types/react": "^19", "@types/react-dom": "^19", "babel-plugin-react-compiler": "1.0.0", "eslint": "^9", - "eslint-config-next": "^16.0.7", + "eslint-config-next": "^16.4.6", "tailwindcss": "^4", "tw-animate-css": "^1.4.0", "typescript": "^5" diff --git a/src/components/common/KriColorPalette.tsx b/src/components/common/KriColorPalette.tsx new file mode 100644 index 0000000..8cced0e --- /dev/null +++ b/src/components/common/KriColorPalette.tsx @@ -0,0 +1,247 @@ +'use client' + +import { useState, type CSSProperties, type KeyboardEvent } from 'react' +import { Check } from 'lucide-react' +import { Slider as SliderPrimitive } from 'radix-ui' +import { Button } from '@/components/ui/button' +import { ColorPicker, ColorPickerArea, ColorPickerHueSlider } from '@/components/common/color-palette/color-picker' +import { Input } from '@/components/ui/input' +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' +import { cn } from '@/lib/utils' +import { formatHexColor, isLightHexColor, normalizeHexColor, parseHexColor } from '@/components/common/color-palette/color' + +export const KRI_COLOR_PALETTE_DEFAULT_COLORS = [ + '#111827', '#4B5563', '#9CA3AF', '#E5E7EB', '#EF4444', '#F97316', '#F59E0B', '#EAB308', + '#84CC16', '#22C55E', '#14B8A6', '#06B6D4', '#3B82F6', '#6366F1', '#A855F7', '#EC4899', +] as const + +const CUSTOM_PICKER_FALLBACK = '#3B82F6' +const CHECKERBOARD = 'repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0% 50% / 8px 8px' + +export type KriColorPaletteProps = { + /** `#RRGGBB` 또는 `#RRGGBBAA` 형식의 색상. 지정되지 않았으면 null */ + value: string | null + onChange: (value: string | null) => void + colors?: readonly string[] + /** 색상 영역·색조 슬라이더·HEX 입력 노출 여부 */ + allowCustom?: boolean + /** + * 투명도 슬라이더 노출 및 `#RRGGBBAA` 입력 허용 여부. + * false여도 전달받은 값의 투명도는 표시·보존하며, 사용자가 색을 바꾸면 불투명(`#RRGGBB`)으로 바뀐다. + */ + allowAlpha?: boolean + allowClear?: boolean + disabled?: boolean + placeholder?: string + className?: string + 'aria-label'?: string +} + +const swatchStyle = (color: string): CSSProperties => ({ + background: `linear-gradient(${color}, ${color}), ${CHECKERBOARD}`, +}) + +export function KriColorPalette({ + value, + onChange, + colors = KRI_COLOR_PALETTE_DEFAULT_COLORS, + allowCustom = true, + allowAlpha = false, + allowClear = true, + disabled = false, + placeholder = '색상 없음', + className, + 'aria-label': ariaLabel = '색상 선택', +}: KriColorPaletteProps) { + const normalizedValue = normalizeHexColor(value) + const parsedValue = parseHexColor(normalizedValue) + const currentAlpha = parsedValue?.alpha ?? 255 + const [open, setOpen] = useState(false) + // 프리셋·HEX 입력·제거로 값이 바뀌면 색상 영역을 새 값으로 다시 초기화한다. + const [pickerKey, setPickerKey] = useState(0) + const [hexDraft, setHexDraft] = useState(normalizedValue ?? '') + const [hexDraftSource, setHexDraftSource] = useState(normalizedValue) + const [hexInvalid, setHexInvalid] = useState(false) + + if (hexDraftSource !== normalizedValue) { + setHexDraftSource(normalizedValue) + setHexDraft(normalizedValue ?? '') + setHexInvalid(false) + } + + const withAlpha = (rgb: string) => formatHexColor(rgb, allowAlpha ? currentAlpha : 255) + + const selectDiscrete = (next: string | null) => { + onChange(next) + setPickerKey((key) => key + 1) + } + + const handlePickerChange = (next: string) => { + const parsed = parseHexColor(next) + if (!parsed) return + const nextValue = withAlpha(parsed.rgb) + if (nextValue === normalizedValue) return + onChange(nextValue) + } + + const handleAlphaChange = (values: number[]) => { + const percent = values[0] ?? 100 + const nextValue = formatHexColor(parsedValue?.rgb ?? CUSTOM_PICKER_FALLBACK, (percent / 100) * 255) + if (nextValue === normalizedValue) return + onChange(nextValue) + } + + const commitHexDraft = () => { + if (hexDraft.trim() === '') { + setHexDraft(normalizedValue ?? '') + setHexInvalid(false) + return + } + // 전달받은 값을 그대로 두고 포커스만 이동한 경우(투명도 포함 값 포함)는 변경으로 보지 않는다. + if (normalizeHexColor(hexDraft) === normalizedValue) { + setHexDraft(normalizedValue ?? '') + setHexInvalid(false) + return + } + const parsed = parseHexColor(hexDraft) + if (!parsed || (!allowAlpha && parsed.alpha !== 255)) { + setHexInvalid(true) + return + } + const nextValue = formatHexColor(parsed.rgb, parsed.alpha) + setHexInvalid(false) + setHexDraft(nextValue) + if (nextValue !== normalizedValue) selectDiscrete(nextValue) + } + + const handleHexKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Enter') return + event.preventDefault() + commitHexDraft() + } + + const hexFormatLabel = allowAlpha ? '#RRGGBB 또는 #RRGGBBAA' : '#RRGGBB' + const alphaPercent = Math.round((currentAlpha / 255) * 100) + + // disabled이면 트리거 상태와 무관하게 팝오버가 열리지 않도록 한다(이미 열린 상태에서 disabled로 바뀐 경우 포함). + const resolvedOpen = open && !disabled + + return ( + setOpen(nextOpen && !disabled)}> + + + + +
+ {colors.map((color) => { + const parsedColor = parseHexColor(color) + if (!parsedColor) return null + const selected = parsedColor.rgb === parsedValue?.rgb + const checkColorClass = isLightHexColor(parsedColor.rgb) ? 'text-black' : 'text-white' + return ( + + ) + })} +
+ + {allowCustom ? ( +
+ + + + + {allowAlpha ? ( +
+ + +
+ + + + {alphaPercent}% +
+ ) : null} +
+ { + setHexDraft(event.target.value) + setHexInvalid(false) + }} + onBlur={commitHexDraft} + onKeyDown={handleHexKeyDown} + placeholder={allowAlpha ? '#RRGGBBAA' : '#RRGGBB'} + maxLength={allowAlpha ? 9 : 7} + aria-label="HEX 색상 코드" + aria-invalid={hexInvalid} + className="h-8 font-mono text-sm" + /> + {hexInvalid ?

{hexFormatLabel} 형식으로 입력해 주세요.

: null} +
+
+ ) : null} + + {allowClear ? ( +
+ +
+ ) : null} + + + ) +} diff --git a/src/components/common/color-palette/color-picker.tsx b/src/components/common/color-palette/color-picker.tsx new file mode 100644 index 0000000..0df5d1c --- /dev/null +++ b/src/components/common/color-palette/color-picker.tsx @@ -0,0 +1,1687 @@ +"use client"; + +// Adapted from Dice UI color-picker (Radix variant), https://www.diceui.com/docs/components/radix/color-picker (MIT License). +// 로컬 변경: import 경로, 아이콘(lucide PipetteIcon), 빈 interface lint 수정. + +import { cva, type VariantProps } from "class-variance-authority"; +import { cn } from "@/lib/utils"; +import { + Direction as DirectionPrimitive, + Slider as SliderPrimitive, + Slot as SlotPrimitive, +} from "radix-ui"; +import { useComposedRefs, useLayoutEffect } from "radix-ui/internal"; +import * as React from "react"; + +import { VisuallyHiddenInput } from "./visually-hidden-input"; +import { useRefWithInit } from "./use-ref-with-init"; +import { useValueAsRef } from "./use-value-as-ref"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { PipetteIcon } from "lucide-react"; + +const ROOT_NAME = "ColorPicker"; +const ROOT_IMPL_NAME = "ColorPickerImpl"; +const TRIGGER_NAME = "ColorPickerTrigger"; +const CONTENT_NAME = "ColorPickerContent"; +const AREA_NAME = "ColorPickerArea"; +const HUE_SLIDER_NAME = "ColorPickerHueSlider"; +const ALPHA_SLIDER_NAME = "ColorPickerAlphaSlider"; +const SWATCH_NAME = "ColorPickerSwatch"; +const EYE_DROPPER_NAME = "ColorPickerEyeDropper"; +const FORMAT_SELECT_NAME = "ColorPickerFormatSelect"; +const INPUT_NAME = "ColorPickerInput"; + +const colorFormats = ["hex", "rgb", "hsl", "hsb"] as const; + +interface DivProps extends React.ComponentProps<"div"> { + asChild?: boolean; +} + +type RootElement = React.ComponentRef; +type AreaElement = React.ComponentRef; +type InputElement = React.ComponentRef; + +type ColorFormat = (typeof colorFormats)[number]; + +/** + * @see https://gist.github.com/bkrmendy/f4582173f50fab209ddfef1377ab31e3 + */ +interface EyeDropper { + open: (options?: { signal?: AbortSignal }) => Promise<{ sRGBHex: string }>; +} + +declare global { + interface Window { + EyeDropper?: { + new (): EyeDropper; + }; + } +} + +interface ColorValue { + r: number; + g: number; + b: number; + a: number; +} + +interface HSVColorValue { + h: number; + s: number; + v: number; + a: number; +} + +function hexToRgb(hex: string, alpha?: number): ColorValue { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result + ? { + r: Number.parseInt(result[1] ?? "0", 16), + g: Number.parseInt(result[2] ?? "0", 16), + b: Number.parseInt(result[3] ?? "0", 16), + a: alpha ?? 1, + } + : { r: 0, g: 0, b: 0, a: alpha ?? 1 }; +} + +function toHex(n: number) { + const hex = Math.round(n).toString(16); + return hex.length === 1 ? `0${hex}` : hex; +} + +function rgbToHex(color: ColorValue): string { + return `#${toHex(color.r)}${toHex(color.g)}${toHex(color.b)}`; +} + +function rgbToHsv(color: ColorValue): HSVColorValue { + const r = color.r / 255; + const g = color.g / 255; + const b = color.b / 255; + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const diff = max - min; + + let h = 0; + if (diff !== 0) { + switch (max) { + case r: + h = ((g - b) / diff) % 6; + break; + case g: + h = (b - r) / diff + 2; + break; + case b: + h = (r - g) / diff + 4; + break; + } + } + h = Math.round(h * 60); + if (h < 0) h += 360; + + const s = max === 0 ? 0 : diff / max; + const v = max; + + return { + h, + s: Math.round(s * 100), + v: Math.round(v * 100), + a: color.a, + }; +} + +function hsvToRgb(hsv: HSVColorValue): ColorValue { + const h = hsv.h / 360; + const s = hsv.s / 100; + const v = hsv.v / 100; + + const i = Math.floor(h * 6); + const f = h * 6 - i; + const p = v * (1 - s); + const q = v * (1 - f * s); + const t = v * (1 - (1 - f) * s); + + let r: number; + let g: number; + let b: number; + + switch (i % 6) { + case 0: { + r = v; + g = t; + b = p; + break; + } + case 1: { + r = q; + g = v; + b = p; + break; + } + case 2: { + r = p; + g = v; + b = t; + break; + } + case 3: { + r = p; + g = q; + b = v; + break; + } + case 4: { + r = t; + g = p; + b = v; + break; + } + case 5: { + r = v; + g = p; + b = q; + break; + } + default: { + r = 0; + g = 0; + b = 0; + } + } + + return { + r: Math.round(r * 255), + g: Math.round(g * 255), + b: Math.round(b * 255), + a: hsv.a, + }; +} + +function colorToString(color: ColorValue, format: ColorFormat = "hex"): string { + switch (format) { + case "hex": + return rgbToHex(color); + case "rgb": + return color.a < 1 + ? `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})` + : `rgb(${color.r}, ${color.g}, ${color.b})`; + case "hsl": { + const hsl = rgbToHsl(color); + return color.a < 1 + ? `hsla(${hsl.h}, ${hsl.s}%, ${hsl.l}%, ${color.a})` + : `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`; + } + case "hsb": { + const hsv = rgbToHsv(color); + return color.a < 1 + ? `hsba(${hsv.h}, ${hsv.s}%, ${hsv.v}%, ${color.a})` + : `hsb(${hsv.h}, ${hsv.s}%, ${hsv.v}%)`; + } + default: + return rgbToHex(color); + } +} + +function rgbToHsl(color: ColorValue) { + const r = color.r / 255; + const g = color.g / 255; + const b = color.b / 255; + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const diff = max - min; + const sum = max + min; + + const l = sum / 2; + + let h = 0; + let s = 0; + + if (diff !== 0) { + s = l > 0.5 ? diff / (2 - sum) : diff / sum; + + if (max === r) { + h = (g - b) / diff + (g < b ? 6 : 0); + } else if (max === g) { + h = (b - r) / diff + 2; + } else if (max === b) { + h = (r - g) / diff + 4; + } + h /= 6; + } + + return { + h: Math.round(h * 360), + s: Math.round(s * 100), + l: Math.round(l * 100), + }; +} + +function hslToRgb( + hsl: { h: number; s: number; l: number }, + alpha = 1, +): ColorValue { + const h = hsl.h / 360; + const s = hsl.s / 100; + const l = hsl.l / 100; + + const c = (1 - Math.abs(2 * l - 1)) * s; + const x = c * (1 - Math.abs(((h * 6) % 2) - 1)); + const m = l - c / 2; + + let r = 0; + let g = 0; + let b = 0; + + if (h >= 0 && h < 1 / 6) { + r = c; + g = x; + b = 0; + } else if (h >= 1 / 6 && h < 2 / 6) { + r = x; + g = c; + b = 0; + } else if (h >= 2 / 6 && h < 3 / 6) { + r = 0; + g = c; + b = x; + } else if (h >= 3 / 6 && h < 4 / 6) { + r = 0; + g = x; + b = c; + } else if (h >= 4 / 6 && h < 5 / 6) { + r = x; + g = 0; + b = c; + } else if (h >= 5 / 6 && h < 1) { + r = c; + g = 0; + b = x; + } + + return { + r: Math.round((r + m) * 255), + g: Math.round((g + m) * 255), + b: Math.round((b + m) * 255), + a: alpha, + }; +} + +function parseColorString(value: string): ColorValue | null { + const trimmed = value.trim(); + + if (trimmed.startsWith("#")) { + const hexMatch = trimmed.match(/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/); + if (hexMatch) { + return hexToRgb(trimmed); + } + } + + const rgbMatch = trimmed.match( + /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)$/, + ); + if (rgbMatch) { + return { + r: Number.parseInt(rgbMatch[1] ?? "0", 10), + g: Number.parseInt(rgbMatch[2] ?? "0", 10), + b: Number.parseInt(rgbMatch[3] ?? "0", 10), + a: rgbMatch[4] ? Number.parseFloat(rgbMatch[4]) : 1, + }; + } + + const hslMatch = trimmed.match( + /^hsla?\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(?:,\s*([\d.]+))?\s*\)$/, + ); + if (hslMatch) { + const h = Number.parseInt(hslMatch[1] ?? "0", 10); + const s = Number.parseInt(hslMatch[2] ?? "0", 10) / 100; + const l = Number.parseInt(hslMatch[3] ?? "0", 10) / 100; + const a = hslMatch[4] ? Number.parseFloat(hslMatch[4]) : 1; + + const c = (1 - Math.abs(2 * l - 1)) * s; + const x = c * (1 - Math.abs(((h / 60) % 2) - 1)); + const m = l - c / 2; + + let r = 0; + let g = 0; + let b = 0; + + if (h >= 0 && h < 60) { + r = c; + g = x; + b = 0; + } else if (h >= 60 && h < 120) { + r = x; + g = c; + b = 0; + } else if (h >= 120 && h < 180) { + r = 0; + g = c; + b = x; + } else if (h >= 180 && h < 240) { + r = 0; + g = x; + b = c; + } else if (h >= 240 && h < 300) { + r = x; + g = 0; + b = c; + } else if (h >= 300 && h < 360) { + r = c; + g = 0; + b = x; + } + + return { + r: Math.round((r + m) * 255), + g: Math.round((g + m) * 255), + b: Math.round((b + m) * 255), + a, + }; + } + + const hsbMatch = trimmed.match( + /^hsba?\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(?:,\s*([\d.]+))?\s*\)$/, + ); + if (hsbMatch) { + const h = Number.parseInt(hsbMatch[1] ?? "0", 10); + const s = Number.parseInt(hsbMatch[2] ?? "0", 10); + const v = Number.parseInt(hsbMatch[3] ?? "0", 10); + const a = hsbMatch[4] ? Number.parseFloat(hsbMatch[4]) : 1; + + return hsvToRgb({ h, s, v, a }); + } + + return null; +} + +type Direction = "ltr" | "rtl"; + +interface StoreState { + color: ColorValue; + hsv: HSVColorValue; + open: boolean; + format: ColorFormat; +} + +interface Store { + subscribe: (cb: () => void) => () => void; + getState: () => StoreState; + setColor: (value: ColorValue) => void; + setHsv: (value: HSVColorValue) => void; + setOpen: (value: boolean) => void; + setFormat: (value: ColorFormat) => void; + notify: () => void; +} + +const StoreContext = React.createContext(null); + +function useStoreContext(consumerName: string) { + const context = React.useContext(StoreContext); + if (!context) { + throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``); + } + return context; +} + +function useStore(selector: (state: StoreState) => U): U { + const store = useStoreContext("useStore"); + + const getSnapshot = React.useCallback( + () => selector(store.getState()), + [store, selector], + ); + + return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot); +} + +interface ColorPickerContextValue { + dir: Direction; + disabled?: boolean; + inline?: boolean; + readOnly?: boolean; + required?: boolean; +} + +const ColorPickerContext = React.createContext( + null, +); + +function useColorPickerContext(consumerName: string) { + const context = React.useContext(ColorPickerContext); + if (!context) { + throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``); + } + return context; +} + +interface ColorPickerProps + extends + Omit, + Pick< + React.ComponentProps, + "defaultOpen" | "open" | "onOpenChange" | "modal" + > { + value?: string; + defaultValue?: string; + onValueChange?: (value: string) => void; + dir?: Direction; + format?: ColorFormat; + defaultFormat?: ColorFormat; + onFormatChange?: (format: ColorFormat) => void; + name?: string; + asChild?: boolean; + disabled?: boolean; + inline?: boolean; + readOnly?: boolean; + required?: boolean; +} + +function ColorPicker(props: ColorPickerProps) { + const { + value: valueProp, + defaultValue = "#000000", + onValueChange, + format: formatProp, + defaultFormat = "hex", + onFormatChange, + defaultOpen, + open: openProp, + onOpenChange, + name, + disabled, + inline, + readOnly, + required, + ...rootProps + } = props; + + const listenersRef = useRefWithInit(() => new Set<() => void>()); + const stateRef = useRefWithInit(() => { + const colorString = valueProp ?? defaultValue; + const color = hexToRgb(colorString); + + return { + color, + hsv: rgbToHsv(color), + open: openProp ?? defaultOpen ?? false, + format: formatProp ?? defaultFormat, + }; + }); + + const propsRef = useValueAsRef({ + onValueChange, + onOpenChange, + onFormatChange, + }); + + const store = React.useMemo(() => { + function notify() { + for (const cb of listenersRef.current) { + cb(); + } + } + + return { + subscribe: (cb) => { + listenersRef.current.add(cb); + return () => listenersRef.current.delete(cb); + }, + getState: () => stateRef.current, + setColor: (value: ColorValue) => { + if (Object.is(stateRef.current.color, value)) return; + + const prevState = { ...stateRef.current }; + stateRef.current.color = value; + + if (propsRef.current.onValueChange) { + const colorString = colorToString(value, prevState.format); + propsRef.current.onValueChange(colorString); + } + + notify(); + }, + setHsv: (value: HSVColorValue) => { + if (Object.is(stateRef.current.hsv, value)) return; + + const prevState = { ...stateRef.current }; + stateRef.current.hsv = value; + + if (propsRef.current.onValueChange) { + const colorValue = hsvToRgb(value); + const colorString = colorToString(colorValue, prevState.format); + propsRef.current.onValueChange(colorString); + } + + notify(); + }, + setOpen: (value: boolean) => { + if (Object.is(stateRef.current.open, value)) return; + + stateRef.current.open = value; + + if (propsRef.current.onOpenChange) { + propsRef.current.onOpenChange(value); + } + + notify(); + }, + setFormat: (value: ColorFormat) => { + if (Object.is(stateRef.current.format, value)) return; + + stateRef.current.format = value; + + if (propsRef.current.onFormatChange) { + propsRef.current.onFormatChange(value); + } + + notify(); + }, + notify, + }; + }, [listenersRef, stateRef, propsRef]); + + return ( + + + + ); +} + +type ColorPickerImplProps = Omit< + ColorPickerProps, + | "defaultValue" + | "onValueChange" + | "onOpenChange" + | "format" + | "defaultFormat" + | "onFormatChange" +>; + +function ColorPickerImpl(props: ColorPickerImplProps) { + const { + value: valueProp, + dir: dirProp, + defaultOpen, + open: openProp, + name, + ref, + asChild, + disabled, + inline, + modal, + readOnly, + required, + ...rootProps + } = props; + + const store = useStoreContext(ROOT_IMPL_NAME); + + const dir = DirectionPrimitive.useDirection(dirProp); + + const [formTrigger, setFormTrigger] = React.useState( + null, + ); + const composedRef = useComposedRefs(ref, (node) => setFormTrigger(node)); + const isFormControl = formTrigger ? !!formTrigger.closest("form") : true; + + useLayoutEffect(() => { + if (valueProp !== undefined) { + const currentState = store.getState(); + const color = hexToRgb(valueProp, currentState.color.a); + const hsv = rgbToHsv(color); + store.setColor(color); + store.setHsv(hsv); + } + }, [valueProp, store]); + + useLayoutEffect(() => { + if (openProp !== undefined) { + store.setOpen(openProp); + } + }, [openProp, store]); + + const contextValue = React.useMemo( + () => ({ + dir, + disabled, + inline, + readOnly, + required, + }), + [dir, disabled, inline, readOnly, required], + ); + + const value = useStore((state) => rgbToHex(state.color)); + const open = useStore((state) => state.open); + + const RootPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + if (inline) { + return ( + + + {isFormControl && ( + + )} + + ); + } + + return ( + + + + {isFormControl && ( + + )} + + + ); +} + +function ColorPickerTrigger( + props: React.ComponentProps, +) { + const { asChild, disabled, ...triggerProps } = props; + + const context = useColorPickerContext(TRIGGER_NAME); + + const isDisabled = disabled || context.disabled; + + const TriggerPrimitive = asChild ? SlotPrimitive.Slot : Button; + + return ( + + + + ); +} + +function ColorPickerContent( + props: React.ComponentProps, +) { + const { asChild, className, children, ...popoverContentProps } = props; + + const context = useColorPickerContext(CONTENT_NAME); + + if (context.inline) { + const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + return ( + + {children} + + ); + } + + return ( + + {children} + + ); +} + +function ColorPickerArea(props: DivProps) { + const { + asChild, + onPointerDown: onPointerDownProp, + onPointerMove: onPointerMoveProp, + onPointerUp: onPointerUpProp, + className, + ref, + ...areaProps + } = props; + + const propsRef = useValueAsRef({ + onPointerDown: onPointerDownProp, + onPointerMove: onPointerMoveProp, + onPointerUp: onPointerUpProp, + }); + + const context = useColorPickerContext(AREA_NAME); + const store = useStoreContext(AREA_NAME); + + const hsv = useStore((state) => state.hsv); + + const isDraggingRef = React.useRef(false); + const areaRef = React.useRef(null); + const composedRef = useComposedRefs(ref, areaRef); + + const updateColorFromPosition = React.useCallback( + (clientX: number, clientY: number) => { + if (!areaRef.current) return; + + const rect = areaRef.current.getBoundingClientRect(); + const x = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)); + const y = Math.max( + 0, + Math.min(1, 1 - (clientY - rect.top) / rect.height), + ); + + const newHsv: HSVColorValue = { + h: hsv?.h ?? 0, + s: Math.round(x * 100), + v: Math.round(y * 100), + a: hsv?.a ?? 1, + }; + + store.setHsv(newHsv); + store.setColor(hsvToRgb(newHsv)); + }, + [hsv, store], + ); + + const onPointerDown = React.useCallback( + (event: React.PointerEvent) => { + if (context.disabled) return; + propsRef.current.onPointerDown?.(event); + if (event.defaultPrevented) return; + + isDraggingRef.current = true; + areaRef.current?.setPointerCapture(event.pointerId); + updateColorFromPosition(event.clientX, event.clientY); + }, + [context.disabled, updateColorFromPosition, propsRef], + ); + + const onPointerMove = React.useCallback( + (event: React.PointerEvent) => { + propsRef.current.onPointerMove?.(event); + if (event.defaultPrevented) return; + + if (isDraggingRef.current) { + updateColorFromPosition(event.clientX, event.clientY); + } + }, + [updateColorFromPosition, propsRef], + ); + + const onPointerUp = React.useCallback( + (event: React.PointerEvent) => { + propsRef.current.onPointerUp?.(event); + if (event.defaultPrevented) return; + + isDraggingRef.current = false; + areaRef.current?.releasePointerCapture(event.pointerId); + }, + [propsRef], + ); + + const hue = hsv?.h ?? 0; + const backgroundHue = hsvToRgb({ h: hue, s: 100, v: 100, a: 1 }); + + const AreaPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + return ( + +
+
+
+
+
+
+ + ); +} + +function ColorPickerHueSlider( + props: React.ComponentProps, +) { + const { className, ...sliderProps } = props; + + const context = useColorPickerContext(HUE_SLIDER_NAME); + const store = useStoreContext(HUE_SLIDER_NAME); + + const hsv = useStore((state) => state.hsv); + + const onValueChange = React.useCallback( + (values: number[]) => { + const newHsv: HSVColorValue = { + h: values[0] ?? 0, + s: hsv?.s ?? 0, + v: hsv?.v ?? 0, + a: hsv?.a ?? 1, + }; + store.setHsv(newHsv); + store.setColor(hsvToRgb(newHsv)); + }, + [hsv, store], + ); + + return ( + + + + + + + ); +} + +function ColorPickerAlphaSlider( + props: React.ComponentProps, +) { + const { className, ...sliderProps } = props; + + const context = useColorPickerContext(ALPHA_SLIDER_NAME); + const store = useStoreContext(ALPHA_SLIDER_NAME); + + const color = useStore((state) => state.color); + const hsv = useStore((state) => state.hsv); + + const onValueChange = React.useCallback( + (values: number[]) => { + const alpha = (values[0] ?? 0) / 100; + const newColor = { ...color, a: alpha }; + const newHsv = { ...hsv, a: alpha }; + store.setColor(newColor); + store.setHsv(newHsv); + }, + [color, hsv, store], + ); + + const gradientColor = `rgb(${color?.r ?? 0}, ${color?.g ?? 0}, ${color?.b ?? 0})`; + + return ( + + +
+ + + + + ); +} + +function ColorPickerSwatch(props: DivProps) { + const { asChild, className, ...swatchProps } = props; + + const context = useColorPickerContext(SWATCH_NAME); + + const color = useStore((state) => state.color); + const format = useStore((state) => state.format); + + const backgroundStyle = React.useMemo(() => { + if (!color) { + return { + background: + "linear-gradient(to bottom right, transparent calc(50% - 1px), hsl(var(--destructive)) calc(50% - 1px) calc(50% + 1px), transparent calc(50% + 1px)) no-repeat", + }; + } + + const colorString = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`; + + if (color.a < 1) { + return { + background: `linear-gradient(${colorString}, ${colorString}), repeating-conic-gradient(#ccc 0% 25%, #fff 0% 50%) 0% 50% / 8px 8px`, + }; + } + + return { + backgroundColor: colorString, + }; + }, [color]); + + const ariaLabel = !color + ? "No color selected" + : `Current color: ${colorToString(color, format)}`; + + const SwatchPrimitive = asChild ? SlotPrimitive.Slot : "div"; + + return ( + + ); +} + +function subscribeToEyeDropper() { + return () => {}; +} + +function getEyeDropperSnapshot() { + return !!window.EyeDropper; +} + +function getEyeDropperServerSnapshot() { + return false; +} + +function ColorPickerEyeDropper(props: React.ComponentProps) { + const { size: sizeProp, children, disabled, ...buttonProps } = props; + + const context = useColorPickerContext(EYE_DROPPER_NAME); + const store = useStoreContext(EYE_DROPPER_NAME); + + const color = useStore((state) => state.color); + + const isDisabled = disabled || context.disabled; + + const onEyeDropper = React.useCallback(async () => { + if (!window.EyeDropper) return; + + try { + const eyeDropper = new window.EyeDropper(); + const result = await eyeDropper.open(); + + if (result.sRGBHex) { + const currentAlpha = color?.a ?? 1; + const newColor = hexToRgb(result.sRGBHex, currentAlpha); + const newHsv = rgbToHsv(newColor); + store.setColor(newColor); + store.setHsv(newHsv); + } + } catch (error) { + console.warn("EyeDropper error:", error); + } + }, [color, store]); + + const hasEyeDropper = React.useSyncExternalStore( + subscribeToEyeDropper, + getEyeDropperSnapshot, + getEyeDropperServerSnapshot, + ); + + if (!hasEyeDropper) return null; + + const size = sizeProp ?? (children ? "default" : "icon"); + + return ( + + ); +} + +interface ColorPickerFormatSelectProps + extends + Omit, "value" | "onValueChange">, + Pick, "size" | "className"> {} + +function ColorPickerFormatSelect(props: ColorPickerFormatSelectProps) { + const { size, disabled, className, ...selectProps } = props; + + const context = useColorPickerContext(FORMAT_SELECT_NAME); + const store = useStoreContext(FORMAT_SELECT_NAME); + const isDisabled = disabled || context.disabled; + + const format = useStore((state) => state.format); + + const onFormatChange = React.useCallback( + (value: ColorFormat) => { + store.setFormat(value); + }, + [store], + ); + + return ( + + ); +} + +interface ColorPickerInputProps extends Omit< + React.ComponentProps, + "value" | "onChange" | "color" +> { + withoutAlpha?: boolean; +} + +function ColorPickerInput(props: ColorPickerInputProps) { + const store = useStoreContext(INPUT_NAME); + const context = useColorPickerContext(INPUT_NAME); + + const color = useStore((state) => state.color); + const format = useStore((state) => state.format); + const hsv = useStore((state) => state.hsv); + + const onColorChange = React.useCallback( + (newColor: ColorValue) => { + const newHsv = rgbToHsv(newColor); + store.setColor(newColor); + store.setHsv(newHsv); + }, + [store], + ); + + if (format === "hex") { + return ( + + ); + } + + if (format === "rgb") { + return ( + + ); + } + + if (format === "hsl") { + return ( + + ); + } + + if (format === "hsb") { + return ( + + ); + } +} + +const inputGroupItemVariants = cva("h-8 [-moz-appearance:textfield] focus-visible:z-10 focus-visible:ring-1 [&::-webkit-inner-spin-button]:m-0 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:m-0 [&::-webkit-outer-spin-button]:appearance-none", { + variants: { + position: { + first: "rounded-r-none", + middle: "-ml-px rounded-none border-l-0", + last: "-ml-px rounded-l-none border-l-0", + isolated: "", + }, + }, + defaultVariants: { + position: "isolated", + }, +}); + +interface InputGroupItemProps + extends + React.ComponentProps, + VariantProps {} + +function InputGroupItem({ + className, + position, + ...props +}: InputGroupItemProps) { + return ( + + ); +} + +interface FormatInputProps extends ColorPickerInputProps { + color: ColorValue; + onColorChange: (color: ColorValue) => void; + context: ColorPickerContextValue; +} + +function HexInput(props: FormatInputProps) { + const { + color, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const hexValue = rgbToHex(color); + const alphaValue = Math.round((color?.a ?? 1) * 100); + + const onHexChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = event.target.value; + const parsedColor = parseColorString(value); + if (parsedColor) { + onColorChange({ ...parsedColor, a: color?.a ?? 1 }); + } + }, + [color, onColorChange], + ); + + const onAlphaChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= 100) { + onColorChange({ ...color, a: value / 100 }); + } + }, + [color, onColorChange], + ); + + if (withoutAlpha) { + return ( + + ); + } + + return ( +
+ + +
+ ); +} + +function RgbInput(props: FormatInputProps) { + const { + color, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const rValue = Math.round(color?.r ?? 0); + const gValue = Math.round(color?.g ?? 0); + const bValue = Math.round(color?.b ?? 0); + const alphaValue = Math.round((color?.a ?? 1) * 100); + + const onChannelChange = React.useCallback( + (channel: "r" | "g" | "b" | "a", max: number, isAlpha = false) => + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= max) { + const newValue = isAlpha ? value / 100 : value; + onColorChange({ ...color, [channel]: newValue }); + } + }, + [color, onColorChange], + ); + + return ( +
+ + + + {!withoutAlpha && ( + + )} +
+ ); +} + +function HslInput(props: FormatInputProps) { + const { + color, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const hsl = React.useMemo(() => rgbToHsl(color), [color]); + const alphaValue = Math.round((color?.a ?? 1) * 100); + + const onHslChannelChange = React.useCallback( + (channel: "h" | "s" | "l", max: number) => + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= max) { + const newHsl = { ...hsl, [channel]: value }; + const newColor = hslToRgb(newHsl, color?.a ?? 1); + onColorChange(newColor); + } + }, + [hsl, color, onColorChange], + ); + + const onAlphaChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= 100) { + onColorChange({ ...color, a: value / 100 }); + } + }, + [color, onColorChange], + ); + + return ( +
+ + + + {!withoutAlpha && ( + + )} +
+ ); +} + +interface HsbInputProps extends Omit { + hsv: HSVColorValue; +} + +function HsbInput(props: HsbInputProps) { + const { + hsv, + onColorChange, + context, + withoutAlpha, + className, + ...inputProps + } = props; + + const alphaValue = Math.round((hsv?.a ?? 1) * 100); + + const onHsvChannelChange = React.useCallback( + (channel: "h" | "s" | "v", max: number) => + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= max) { + const newHsv = { ...hsv, [channel]: value }; + const newColor = hsvToRgb(newHsv); + onColorChange(newColor); + } + }, + [hsv, onColorChange], + ); + + const onAlphaChange = React.useCallback( + (event: React.ChangeEvent) => { + const value = Number.parseInt(event.target.value, 10); + if (!Number.isNaN(value) && value >= 0 && value <= 100) { + const currentColor = hsvToRgb(hsv); + onColorChange({ ...currentColor, a: value / 100 }); + } + }, + [hsv, onColorChange], + ); + + return ( +
+ + + + {!withoutAlpha && ( + + )} +
+ ); +} + +export { + ColorPicker, + ColorPickerAlphaSlider, + ColorPickerArea, + ColorPickerContent, + ColorPickerEyeDropper, + ColorPickerFormatSelect, + ColorPickerHueSlider, + ColorPickerInput, + type ColorPickerProps, + ColorPickerSwatch, + ColorPickerTrigger, + useStore as useColorPicker, +}; diff --git a/src/components/common/color-palette/color.ts b/src/components/common/color-palette/color.ts new file mode 100644 index 0000000..2d3c133 --- /dev/null +++ b/src/components/common/color-palette/color.ts @@ -0,0 +1,42 @@ +export type ParsedHexColor = { + /** `#RRGGBB` (대문자) */ + rgb: string + /** 0~255. 투명도가 없는 값은 255 */ + alpha: number +} + +const HEX_COLOR_PATTERN = /^#?([0-9A-F]{6})([0-9A-F]{2})?$/ + +/** `#RRGGBB` 또는 `#RRGGBBAA`(대소문자 무관, `#` 생략 가능)를 해석한다. 형식이 다르면 null. */ +export const parseHexColor = (value: string | null | undefined): ParsedHexColor | null => { + if (!value) return null + const match = HEX_COLOR_PATTERN.exec(value.trim().toUpperCase()) + if (!match) return null + return { + rgb: `#${match[1]}`, + alpha: match[2] ? Number.parseInt(match[2], 16) : 255, + } +} + +/** 투명도가 255이면 `#RRGGBB`, 아니면 `#RRGGBBAA`로 만든다. */ +export const formatHexColor = (rgb: string, alpha = 255): string => { + const clamped = Math.max(0, Math.min(255, Math.round(alpha))) + if (clamped === 255) return rgb.toUpperCase() + return `${rgb.toUpperCase()}${clamped.toString(16).padStart(2, '0').toUpperCase()}` +} + +/** 정규화된 hex 문자열. 형식이 다르면 null. */ +export const normalizeHexColor = (value: string | null | undefined): string | null => { + const parsed = parseHexColor(value) + return parsed ? formatHexColor(parsed.rgb, parsed.alpha) : null +} + +/** 흰 배경 위에 그렸을 때 밝은 색인지 판단한다(투명도 반영). 글자색 대비 결정에 쓴다. */ +export const isLightHexColor = (value: string): boolean => { + const parsed = parseHexColor(value) + if (!parsed) return true + const ratio = parsed.alpha / 255 + const channel = (offset: number) => Number.parseInt(parsed.rgb.slice(offset, offset + 2), 16) * ratio + 255 * (1 - ratio) + const luminance = (channel(1) * 299 + channel(3) * 587 + channel(5) * 114) / 1000 + return luminance > 150 +} diff --git a/src/components/common/color-palette/use-ref-with-init.ts b/src/components/common/color-palette/use-ref-with-init.ts new file mode 100644 index 0000000..01d2bcd --- /dev/null +++ b/src/components/common/color-palette/use-ref-with-init.ts @@ -0,0 +1,8 @@ +import * as React from "react"; + +function useRefWithInit(init: () => T): React.RefObject { + const [ref] = React.useState(() => ({ current: init() })); + return ref; +} + +export { useRefWithInit }; diff --git a/src/components/common/color-palette/use-value-as-ref.ts b/src/components/common/color-palette/use-value-as-ref.ts new file mode 100644 index 0000000..9a0d10a --- /dev/null +++ b/src/components/common/color-palette/use-value-as-ref.ts @@ -0,0 +1,14 @@ +import { useLayoutEffect } from "radix-ui/internal"; +import * as React from "react"; + +function useValueAsRef(value: T) { + const ref = React.useRef(value); + + useLayoutEffect(() => { + ref.current = value; + }); + + return ref; +} + +export { useValueAsRef }; diff --git a/src/components/common/color-palette/visually-hidden-input.tsx b/src/components/common/color-palette/visually-hidden-input.tsx new file mode 100644 index 0000000..cadd4fb --- /dev/null +++ b/src/components/common/color-palette/visually-hidden-input.tsx @@ -0,0 +1,154 @@ +"use client"; + +import * as React from "react"; + +type InputValue = string[] | string; + +interface VisuallyHiddenInputProps extends Omit< + React.InputHTMLAttributes, + "value" | "checked" | "onReset" +> { + value?: T; + checked?: boolean; + control: HTMLElement | null; + bubbles?: boolean; +} + +function VisuallyHiddenInput( + props: VisuallyHiddenInputProps, +) { + const { + control, + value, + checked, + bubbles = true, + type = "hidden", + style, + ...inputProps + } = props; + + const isCheckInput = React.useMemo( + () => type === "checkbox" || type === "radio" || type === "switch", + [type], + ); + const inputRef = React.useRef(null); + + const prevValueRef = React.useRef( + isCheckInput ? checked : value, + ); + + const [measuredSize, setMeasuredSize] = React.useState<{ + control: HTMLElement; + width: number; + height: number; + } | null>(null); + + const controlSize = React.useMemo<{ + width?: number; + height?: number; + }>( + () => + control && measuredSize?.control === control + ? { width: measuredSize.width, height: measuredSize.height } + : {}, + [control, measuredSize], + ); + + React.useLayoutEffect(() => { + if (!control) return; + + if (typeof window === "undefined") return; + + const resizeObserver = new ResizeObserver((entries) => { + if (!Array.isArray(entries) || !entries.length) return; + + const entry = entries[0]; + if (!entry) return; + + let width: number; + let height: number; + + if ("borderBoxSize" in entry) { + const borderSizeEntry = entry.borderBoxSize; + const borderSize = Array.isArray(borderSizeEntry) + ? borderSizeEntry[0] + : borderSizeEntry; + width = borderSize.inlineSize; + height = borderSize.blockSize; + } else { + width = control.offsetWidth; + height = control.offsetHeight; + } + + setMeasuredSize({ control, width, height }); + }); + + resizeObserver.observe(control, { box: "border-box" }); + return () => { + resizeObserver.disconnect(); + }; + }, [control]); + + React.useEffect(() => { + const currentValue = isCheckInput ? checked : value; + const prevValue = prevValueRef.current; + prevValueRef.current = currentValue; + + const input = inputRef.current; + if (!input) return; + + const inputProto = window.HTMLInputElement.prototype; + const propertyKey = isCheckInput ? "checked" : "value"; + const eventType = isCheckInput ? "click" : "input"; + + let serializedCurrentValue: unknown = value; + if (isCheckInput) { + serializedCurrentValue = checked; + } else if (typeof value === "object" && value !== null) { + serializedCurrentValue = JSON.stringify(value); + } + + const descriptor = Object.getOwnPropertyDescriptor(inputProto, propertyKey); + + const setter = descriptor?.set; + + if (prevValue !== currentValue && setter) { + const event = new Event(eventType, { bubbles }); + setter.call(input, serializedCurrentValue); + input.dispatchEvent(event); + } + }, [value, checked, bubbles, isCheckInput]); + + const composedStyle = React.useMemo(() => { + return { + ...style, + ...(controlSize.width !== undefined && controlSize.height !== undefined + ? controlSize + : {}), + border: 0, + clip: "rect(0 0 0 0)", + clipPath: "inset(50%)", + height: "1px", + margin: "-1px", + overflow: "hidden", + padding: 0, + position: "absolute", + whiteSpace: "nowrap", + width: "1px", + }; + }, [style, controlSize]); + + return ( + + ); +} + +export { VisuallyHiddenInput }; diff --git a/src/components/dialog/ListHeaderManageDialog.tsx b/src/components/dialog/ListHeaderManageDialog.tsx index 54e1efc..549e768 100644 --- a/src/components/dialog/ListHeaderManageDialog.tsx +++ b/src/components/dialog/ListHeaderManageDialog.tsx @@ -20,6 +20,7 @@ import { } from '@dnd-kit/sortable' import { CSS } from '@dnd-kit/utilities' import { GripVertical, Plus, Trash2 } from 'lucide-react' +import { KriColorPalette } from '@/components/common/KriColorPalette' import { KriDialog } from '@/components/common/KriDialog' import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' @@ -44,6 +45,7 @@ export type ListHeaderManageDialogProps = { type ListHeaderRowProps = { row: listHeader activeId: number | null + onHeaderColorChange: (id: number, color: string | null) => void onHeaderNameChange: (id: number, listHderNm: string) => void onHeaderTypeChange: (id: number, listHderTy: ListHeaderType) => void onFlagChange: (id: number, field: 'useColView' | 'useFilter' | 'useIntrvwerView' | 'useIntrvwerEdit', checked: boolean) => void @@ -62,13 +64,23 @@ const isInterviewerEditDisabled = (row: listHeader) => row.listHderTy === ListHeaderConst.CONTACT_INTERVIEWER || row.listHderTy === ListHeaderConst.FIELD_INTERVIEWER -const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange, onFlagChange, onDelete }: ListHeaderRowProps) => { +const ListHeaderRow = ({ + row, + activeId, + onHeaderColorChange, + onHeaderNameChange, + onHeaderTypeChange, + onFlagChange, + onDelete, +}: ListHeaderRowProps) => { const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: row.listHderId }) const canEditName = isCommonGrade(row.listHderGrad) const canEditType = isCommonGrade(row.listHderGrad) const canDelete = isCommonGrade(row.listHderGrad) const canEditFlags = !isImmutableGrade(row.listHderGrad) const canSort = isCommonGrade(row.listHderGrad) + // IMMUTABLE 헤더의 색상은 서버가 저장하지 않으므로 선택을 막는다. + const canEditColor = !isImmutableGrade(row.listHderGrad) const style: CSSProperties = { transform: CSS.Transform.toString(transform), @@ -86,7 +98,7 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange, ref={setNodeRef} style={style} className={cn( - 'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_96px_96px_110px_110px_88px] items-center gap-2', + 'h-12 px-4 border-b last:border-b-0 grid grid-cols-[56px_1fr_150px_120px_96px_96px_110px_110px_88px] items-center gap-2', (activeId === row.listHderId || isDragging) && 'bg-muted', )} > @@ -131,6 +143,12 @@ const ListHeaderRow = ({ row, activeId, onHeaderNameChange, onHeaderTypeChange, ))} + onHeaderColorChange(row.listHderId, color)} + disabled={!canEditColor} + aria-label={`${row.listHderNm} 헤더 색상`} + />
{ + setLocalRows((prev) => + prev.map((row) => { + if (row.listHderId !== id) return row + if (isImmutableGrade(row.listHderGrad)) return row + return { ...row, listHderColor } + }), + ) + } + const handleHeaderNameChange = (id: number, listHderNm: string) => { setLocalRows((prev) => prev.map((row) => { @@ -302,6 +330,7 @@ const ListHeaderManageDialog = ({ useColView: true, useIntrvwerView: false, useIntrvwerEdit: false, + listHderColor: null, } return [...prev, nextRow] @@ -388,10 +417,11 @@ const ListHeaderManageDialog = ({
-
+
순서 헤더명 헤더 타입 + 헤더 색상 헤더 노출 필터 사용 면접원 노출 @@ -413,6 +443,7 @@ const ListHeaderManageDialog = ({ key={row.listHderId} row={row} activeId={activeId} + onHeaderColorChange={handleHeaderColorChange} onHeaderNameChange={handleHeaderNameChange} onHeaderTypeChange={handleHeaderTypeChange} onFlagChange={handleFlagChange} diff --git a/src/components/kri-editor/KriEditorSms.tsx b/src/components/kri-editor/KriEditorSms.tsx index be0ced7..6688e4a 100644 --- a/src/components/kri-editor/KriEditorSms.tsx +++ b/src/components/kri-editor/KriEditorSms.tsx @@ -8,10 +8,25 @@ import { useTextareaInsert } from './hooks/useTextareaInsert' type SmsEditorProps = Omit & { mode: 'sms' } +type SmsMessageType = 'SMS' | 'LMS' | 'MMS' + function calculateBytes(value: string): number { return new TextEncoder().encode(value).byteLength } +// 첨부파일이 있으면 MMS, 제목이 있거나 smsMaxBytes 이상이면 LMS, 나머지는 SMS로 미리보기 판정한다. +function getSmsMessageType(hasAttachment: boolean, byteSize: number, smsMaxBytes: number, title: string): SmsMessageType { + if (hasAttachment) return 'MMS' + if (byteSize >= smsMaxBytes || Boolean(title)) return 'LMS' + return 'SMS' +} + +function getTextareaMinHeight(hasImages: boolean, hasTitle: boolean): string { + if (hasImages) return '160px' + if (hasTitle) return '320px' + return '360px' +} + export function KriEditorSms({ label, value, @@ -34,12 +49,12 @@ export function KriEditorSms({ const [text, setText] = React.useState(value || '') const textareaRef = React.useRef(null) const latestTextRef = React.useRef(text) - const lastTypeRef = React.useRef<'SMS' | 'LMS' | 'MMS' | null>(null) + const lastTypeRef = React.useRef(null) const { scheduleChange, flushChange } = useDebouncedChange(onChange, debounceMs) const textareaInsert = useTextareaInsert(textareaRef) const previewText = smsPreviewSuffix ? `${text}\n${smsPreviewSuffix}` : text const byteSize = React.useMemo(() => calculateBytes(previewText), [previewText]) - const messageType: 'SMS' | 'LMS' | 'MMS' = smsHasAttachment ? 'MMS' : byteSize >= smsMaxBytes || Boolean(smsTitle) ? 'LMS' : 'SMS' + const messageType = getSmsMessageType(smsHasAttachment, byteSize, smsMaxBytes, smsTitle) const maxBytes = messageType === 'SMS' ? smsMaxBytes : lmsMaxBytes function getBadgeColor(): string { @@ -127,7 +142,7 @@ export function KriEditorSms({ onBlur={() => flushChange(latestTextRef.current)} placeholder={placeholder} readOnly={isSmsReadOnly} - style={{ minHeight: smsImages.length > 0 ? '160px' : smsTitle ? '320px' : '360px' }} + style={{ minHeight: getTextareaMinHeight(smsImages.length > 0, Boolean(smsTitle)) }} {...textareaInsert.bindSelectionHandlers} /> {smsPreviewSuffix ? ( diff --git a/src/components/kri-editor/KriEditorWysiwyg.tsx b/src/components/kri-editor/KriEditorWysiwyg.tsx index 80034ce..33a70a6 100644 --- a/src/components/kri-editor/KriEditorWysiwyg.tsx +++ b/src/components/kri-editor/KriEditorWysiwyg.tsx @@ -39,6 +39,58 @@ import { useImageMapOverlay } from "./hooks/useImageMapOverlay"; type ViewMode = "wysiwyg" | "html"; +type ToolbarEndSlotProps = Pick & { + editor: Editor; + command: KriEditorCommand; + view: ViewMode; +}; + +// command는 ref를 사용하는 함수 묶음이라, 렌더 중 외부 함수에 직접 넘기면 React Compiler가 +// ref 접근으로 판단한다. 별도 컴포넌트의 props로 전달해 렌더 범위를 분리한다(동작 동일). +function ToolbarEndSlot({ renderToolbarEnd, editor, command, view }: Readonly) { + return <>{renderToolbarEnd?.({ editor, command, view })}; +} + +// 주입된 정제 함수가 우선이고, 없으면 sanitizeHtml 옵션에 따라 기본 정제기를 사용한다. +function sanitizeEditorHtml( + html: string, + htmlSanitizer: KriEditorProps["htmlSanitizer"], + sanitizeEnabled: boolean, + allowedCustomHtml: KriEditorProps["allowedCustomHtml"], +): string { + if (htmlSanitizer) return htmlSanitizer(html); + if (sanitizeEnabled) return sanitizeHtml(html, allowedCustomHtml); + return html; +} + +function writeHtmlDraft( + draftRef: { current: string }, + textareaRef: { current: HTMLTextAreaElement | null }, + html: string, +): void { + draftRef.current = html; + if (textareaRef.current) textareaRef.current.value = html; +} + +// 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다. +function syncEditorContent(editor: Editor, value: string, optimisticHtml: string): void { + // 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해 + // 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정. + const normalizedValue = value || "

"; + if (normalizedValue === editor.getHTML() || normalizedValue === optimisticHtml) return; + + editor.commands.setContent(normalizedValue, { + emitUpdate: false, + parseOptions: { preserveWhitespace: "full" }, + }); + + // resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다. + // editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다. + if (normalizedValue.includes(") { const { label, @@ -134,6 +186,9 @@ export function KriEditorWysiwyg(props: KriEditorProps) { }, [view]); const htmlDraftRef = useRef(value ?? ""); + // HTML textarea는 비제어 컴포넌트다. 렌더 중 ref를 읽지 않도록, HTML 보기로 전환하는 시점의 + // 초안을 state로 보관해 textarea가 마운트될 때의 초기값(defaultValue)으로만 사용한다. + const [htmlTextareaSeed, setHtmlTextareaSeed] = useState(value ?? ""); const canImageUpload = Boolean(onImageUpload); const selectionRef = useRef<{ from: number; to: number } | null>(null); @@ -471,6 +526,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) { if (viewRef.current === "wysiwyg") { const raw = editor.getHTML(); htmlDraftRef.current = raw; + setHtmlTextareaSeed(raw); setView("html"); // WYSIWYG에서 막 넘어온, 사용자가 직접 타이핑하지 않은 HTML이므로 @@ -492,14 +548,12 @@ export function KriEditorWysiwyg(props: KriEditorProps) { toast.message(compatibility.reason ?? "현재 HTML은 WYSIWYG로 전환할 수 없습니다."); return; } - const safe = htmlSanitizer - ? htmlSanitizer(raw) - : sanitizeHtmlOpt ? sanitizeHtml(raw, allowedCustomHtml) : raw; + const safe = sanitizeEditorHtml(raw, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml); editor.commands.setContent(safe, { emitUpdate: false, parseOptions: { preserveWhitespace: "full" } }); flushChange(preserveEmptyParagraphs(editor.getHTML())); setView("wysiwyg"); - }, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt]); + }, [allowedCustomHtml, editor, flushChange, getCompatibility, htmlSanitizer, sanitizeHtmlOpt, setView, setPreviewSource, setHtmlTextareaSeed]); const formatHtmlView = useCallback(async () => { try { @@ -512,7 +566,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) { toast.error("HTML 정렬에 실패했습니다."); console.error(err); } - }, [scheduleChange]); + }, [scheduleChange, setPreviewSource]); useEffect(() => { if (!editor) return; @@ -544,46 +598,28 @@ export function KriEditorWysiwyg(props: KriEditorProps) { useEffect(() => { setPreviewSource(value ?? ""); - if (!editor) return; - if (value == null) return; + if (!editor || value == null) return; - const compatibility = getCompatibility(value); - if (showHtmlToggle && !compatibility.compatible) { - htmlDraftRef.current = value; - if (htmlTextareaRef.current) htmlTextareaRef.current.value = value; + // WYSIWYG로 손실 없이 편집할 수 없는 값은 HTML 보기로 전환해 원문을 유지한다. + if (showHtmlToggle && !getCompatibility(value).compatible) { + writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value); if (viewRef.current !== "html") { viewRef.current = "html"; + setHtmlTextareaSeed(value); setView("html"); } return; } if (viewRef.current === "html") { - if (getWysiwygCompatibility && value !== optimisticHtmlRef.current && value !== htmlDraftRef.current) { - htmlDraftRef.current = value; - if (htmlTextareaRef.current) htmlTextareaRef.current.value = value; + const isExternalChange = value !== optimisticHtmlRef.current && value !== htmlDraftRef.current; + if (getWysiwygCompatibility && isExternalChange) { + writeHtmlDraft(htmlDraftRef, htmlTextareaRef, value); } return; } - // 빈 문자열("")은 ProseMirror 스키마상 유효한 문서가 아니라 setContent가 조용히 실패해 - // 이전 템플릿 본문이 그대로 남는 문제가 있었음 -> 빈 값은 빈 문단으로 정규화해서 비교/설정. - const normalizedValue = value || "

"; - const current = editor.getHTML(); - - if (normalizedValue !== current && normalizedValue !== optimisticHtmlRef.current) { - // 외부에서 본문이 변경된 경우에만 기존 editor 문서를 갱신한다. - editor.commands.setContent(normalizedValue, { - emitUpdate: false, - parseOptions: {preserveWhitespace: "full"}, - }); - - // resize가 활성화된 TipTap 이미지 NodeView는 노드의 src 변경을 기존 DOM에 반영하지 않는다. - // editor 전체 대신 NodeView만 다시 생성해 이미지를 갱신하고 편집 포커스는 유지한다. - if (normalizedValue.includes(" { @@ -648,14 +684,13 @@ export function KriEditorWysiwyg(props: KriEditorProps) { const previewHtml = useMemo(() => { const preserved = preserveEmptyParagraphs(previewSource); - const sanitized = htmlSanitizer - ? htmlSanitizer(preserved) - : sanitizeHtmlOpt ? sanitizeHtml(preserved, allowedCustomHtml) : preserved; + const sanitized = sanitizeEditorHtml(preserved, htmlSanitizer, sanitizeHtmlOpt, allowedCustomHtml); const withLinkStyle = applyLinkPreviewClass(sanitized); return transformPreviewHtml ? transformPreviewHtml(withLinkStyle) : withLinkStyle; }, [allowedCustomHtml, htmlSanitizer, previewSource, sanitizeHtmlOpt, transformPreviewHtml]); - const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml); + // 이미지맵을 사용할 때만 미리보기에 영역을 표시한다. + const imageMapOverlayBoxes = useImageMapOverlay(previewContainerRef, previewHtml, enableImageMap && showPreview); const wysiwygCompatibility = useMemo( () => getCompatibility(view === "html" ? previewSource : (editor?.getHTML() ?? previewSource)), @@ -704,7 +739,11 @@ export function KriEditorWysiwyg(props: KriEditorProps) { onAddRow={addRow} onAddColumn={addColumn} onDeleteTable={deleteTable} - customContent={props.renderToolbarEnd?.({ editor, command, view })} + customContent={ + props.renderToolbarEnd ? ( + + ) : undefined + } />
) : null} @@ -718,7 +757,7 @@ export function KriEditorWysiwyg(props: KriEditorProps) {