sanity-io / color-input

Color input and schema for Sanity Studio
MIT License
17 stars 10 forks source link

How to set initialValue on v3 studio? #12

Open lotarbo opened 2 years ago

lotarbo commented 2 years ago

Hello, I try different values to do this

initialValue: '#000000'
initialValue: {hex: '#000000'},
initialValue: {color: {hex: '#000000'}}

end i got error

image
jawnirock commented 1 year ago

Same problem, is there a way to set this initialvalue?

lotarbo commented 1 year ago

@jawnirock i do it with this trick

import {defineField} from 'sanity'

function hex2rgb(hex: string, a: number) {
  const bigint = parseInt(hex.split('#')[1], 16)

  return {
    _type: 'rgbaColor',
    r: (bigint >> 16) & 255,
    g: (bigint >> 8) & 255,
    b: bigint & 255,
    a: a,
  }
}

function rgb2Hsl(rgb: {_type: string; r: number; g: number; b: number; a: number}) {
  let r = rgb.r / 255
  let g = rgb.g / 255
  let b = rgb.b / 255

  let max = Math.max(r, g, b)
  let min = Math.min(r, g, b)
  let d = max - min
  let h = 0
  if (d === 0) h = 0
  else if (max === r) h = ((g - b) / d) % 6
  else if (max === g) h = (b - r) / d + 2
  else if (max === b) h = (r - g) / d + 4
  let l = (min + max) / 2
  let s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1))
  return {
    _type: 'hslaColor',
    h: h * 60,
    s: s,
    l: l,
    a: rgb.a,
  }
}

function rgb2Hsv(rgb: {_type: string; r: number; g: number; b: number; a: number}) {
  let r = rgb.r
  let g = rgb.g
  let b = rgb.b
  let v = Math.max(r, g, b),
    c = v - Math.min(r, g, b)
  let h = c && (v == r ? (g - b) / c : v == g ? 2 + (b - r) / c : 4 + (r - g) / c)
  return {
    _type: 'hsvaColor',
    h: 60 * (h < 0 ? h + 6 : h),
    s: v && c / v,
    v: v,
    a: rgb.a,
  }
}

function createColorInputFromHex(hex: string, a: number) {
  const rgba = hex2rgb(hex, a)
  return {
    _type: 'color',
    hex: hex,
    alpha: a,
    hsl: rgb2Hsl(rgba),
    hsv: rgb2Hsv(rgba),
    rgb: rgba,
  }
}

export const projectShadowColorField = (hex?: string, a: number = 1) => {
  return defineField({
    name: 'shadowColor',
    type: 'color',
    title: 'Shadow Color',
    initialValue: hex ? createColorInputFromHex(hex, a) : {},
  })
}

and after that use this field

projectShadowColorField('#113F45', 1),
vin-ni commented 1 year ago

@lotarbo How do you import it?

Mtillmann commented 1 year ago

@lotarbo thanks for the effort! However, I think the devs should address this issue