a tool for shared writing and social publishing
at main 1.6 kB view raw
1import { useMemo } from "react"; 2import { Color, parseColor } from "react-aria-components"; 3import { useEntity, useReplicache } from "src/replicache"; 4import { FilterAttributes } from "src/replicache/attributes"; 5import { ThemeDefaults } from "./themeUtils"; 6 7export function useColorAttribute( 8 entity: string | null, 9 attribute: keyof FilterAttributes<{ type: "color"; cardinality: "one" }>, 10) { 11 // takes a color string and turns it into a react-aria Color type 12 // we need it to interact with Color Pickers for themeing 13 let { rootEntity } = useReplicache(); 14 let color = useEntity(entity, attribute); 15 let fallbackColor = useEntity(color ? null : rootEntity, attribute); 16 return useMemo(() => { 17 let c = color || fallbackColor; 18 return parseColor(c ? `hsba(${c.data.value})` : ThemeDefaults[attribute]); 19 }, [color, fallbackColor, attribute]); 20} 21export function useColorAttributeNullable( 22 entity: string | null, 23 attribute: keyof FilterAttributes<{ type: "color"; cardinality: "one" }>, 24) { 25 // takes a color string and turns it into a react-aria Color type 26 // we need it to interact with Color Pickers for themeing 27 let color = useEntity(entity, attribute); 28 return useMemo(() => { 29 let c = color; 30 return c ? parseColor(`hsba(${c.data.value})`) : null; 31 }, [color, attribute]); 32} 33 34export function colorToString(value: Color, space: "rgb" | "hsba") { 35 // takes a react-aria Color type and turns it into an rgb or hsba color string. 36 // we need it to set the color in our database when we can the color back from the Color Pickers 37 return value.toString(space).slice(space.length + 1, -1); 38}