Define icon transformations on withState

(Closes #148)
This commit is contained in:
uwap 2020-10-08 17:40:42 +02:00
parent 9a5557db03
commit 1c1de6356c

View file

@ -4,15 +4,6 @@ import ReactIcon from "@mdi/react";
import { type Color } from "./colors"; import { type Color } from "./colors";
import * as mdiIcons from "@mdi/js"; import * as mdiIcons from "@mdi/js";
export type Icon = {
render: (s: State) => React.Node,
size: (n: number) => Icon,
rotate: (n: number) => Icon,
flip: () => Icon,
flipV: () => Icon,
color: (c: Color | (State) => Color) => Icon
};
type IconPropHelper = { type IconPropHelper = {
size?: number, size?: number,
rotate?: number, rotate?: number,
@ -21,6 +12,27 @@ type IconPropHelper = {
color?: Color color?: Color
}; };
export type Icon = {
render: (s: State) => React.Node,
size: (n: number) => Icon,
rotate: (n: number) => Icon,
flip: () => Icon,
flipV: () => Icon,
color: (c: Color | (State) => Color) => Icon,
applyProps: (props: IconPropHelper) => Icon
};
const iconChainUtils = <T> (cb: (x: T, p?: IconPropHelper) => Icon,
p1: T, p?: IconPropHelper) => ({
size: (n: number) => cb(p1, {...p, size: n}),
rotate: (n: number) => cb(p1, {...p, rotate: n}),
flip: () => cb(p1, {...p, horizontal: !p?.horizontal ?? true}),
flipV: () => cb(p1, {...p, vertical: !p?.vertical ?? true}),
color: (c: Color | (State) => Color) => cb(p1, {...p, color: c}),
applyProps: (props: IconPropHelper) => cb(p1, {...p, ...props})
}
);
export const svg = (data: string, props?: IconPropHelper): Icon => { export const svg = (data: string, props?: IconPropHelper): Icon => {
const propColor = ((c: Color | (State) => Color) => (state: State) => { const propColor = ((c: Color | (State) => Color) => (state: State) => {
if (typeof c === "function") { if (typeof c === "function") {
@ -37,24 +49,16 @@ export const svg = (data: string, props?: IconPropHelper): Icon => {
color={propColor(state)} color={propColor(state)}
/> />
), ),
size: (n: number) => svg(data, {...props, size: n}), ...iconChainUtils(svg, data, props)
rotate: (n: number) => svg(data, {...props, rotate: n}),
flip: () => svg(data, {...props, horizontal: !props?.horizontal ?? true}),
flipV: () => svg(data, {...props, vertical: !props?.vertical ?? true}),
color: (c: Color | (State) => Color) => svg(data, {...props, color: c})
}; };
}; };
export const withState = (f: (s: State) => Icon): Icon => { export const withState = (f: (s: State) => Icon,
return { props?: IconPropHelper): Icon => ({
render: (state) => f(state).render(state), render: (state) => f(state).applyProps(props).render(state),
size: () => withState(f), ...iconChainUtils(withState, f, props)
rotate: () => withState(f), }
flip: () => withState(f), );
flipV: () => withState(f),
color: () => withState(f)
};
};
export const mdiBattery = (topic: string): Icon => withState((state) => { export const mdiBattery = (topic: string): Icon => withState((state) => {
const rawval = state[topic]; const rawval = state[topic];