Skip to content

Instantly share code, notes, and snippets.

@tsuki-lab
Last active May 11, 2022 02:02
Show Gist options
  • Save tsuki-lab/ec39b07987b622c80ce24c8fe55a870f to your computer and use it in GitHub Desktop.
Save tsuki-lab/ec39b07987b622c80ce24c8fe55a870f to your computer and use it in GitHub Desktop.
カラーコードを管理するための手法切り取り
import { constColorsToColorObject } from './utils'
export const colors = constColorsToColorObject({
/* 本文テキスト */
body: '#333333',
/* プライマリー */
primary: '#529fff',
/* セカンダリー */
secondary: '#3d3dff',
/* エラー */
error: '#ea6161',
white: '#ffffff',
black: '#000000'
} as const)
colors.body.hex // #333333
colors.body.rgb // 51,51,51
/**
* カラーコードをHexからRgb文字列に変換する
* @param hex string for color hex
* @returns hex to `00, 00, 00`
*/
export const hexToRgb = (hex: string): string => {
const result = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
if (result) {
const r = parseInt(result[1], 16)
const g = parseInt(result[2], 16)
const b = parseInt(result[3], 16)
return `${r},${g},${b}`
}
throw new Error(`the result of the run was null. the argument is "${hex}".`)
}
type ConstColorsToColorObject = <Colors>(colors: Colors) => {
[K in keyof Colors]: {
hex: typeof colors[K]
rgb: string
}
}
/**
* カラーコードを呼び出すためのカラーオブジェクトを生成する。
* @param colors color定数
* @returns rgbとhexを呼び出すことのできるカラーオブジェクト
*/
export const constColorsToColorObject: ConstColorsToColorObject = (colors) => {
return Object.assign(
{},
...Object.entries(colors).map(([key, hex]) => {
return {
[key]: {
hex: hex,
rgb: hexToRgb(hex)
}
}
})
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment