Skip to content

Instantly share code, notes, and snippets.

@DRFR0ST
Created May 14, 2021 23:13
Show Gist options
  • Save DRFR0ST/02bc6e51054ba5b0246dff6354f25d72 to your computer and use it in GitHub Desktop.
Save DRFR0ST/02bc6e51054ba5b0246dff6354f25d72 to your computer and use it in GitHub Desktop.
import React, { useContext, useRef } from 'react';
import { ImageStyle, TextStyle, useColorScheme, ViewStyle } from 'react-native';
import { Theme } from 'tint-n-tinge';
import { useSignal } from './hooks';
type PaletteRaw = {
primary: string;
background: string;
text: string;
};
const LIGHT_PALETTE: PaletteRaw = {
primary: '#9C6',
background: '#FFF',
text: '#000',
};
const DARK_PALETTE: PaletteRaw = {
primary: '#9C6',
background: '#000',
text: '#FFF',
};
export const LIGHT_THEME = new Theme(LIGHT_PALETTE);
export const DARK_THEME = new Theme(DARK_PALETTE);
const THEME_MAP = {
light: LIGHT_THEME,
dark: DARK_THEME,
};
type ThemeAPI = {
palette: Theme<PaletteRaw>['palette'];
setMode: (mode: 'light' | 'dark') => void;
};
const ThemeContext = React.createContext(null as unknown as ThemeAPI);
export const ThemeProvider = (props: {
children: JSX.Element | JSX.Element[];
}) => {
const colorScheme = useColorScheme();
const themeRef = useRef(THEME_MAP[colorScheme ?? 'light']);
const signal = useSignal();
const setMode = (mode: 'light' | 'dark') => {
themeRef.current = THEME_MAP[mode];
signal();
};
return (
<ThemeContext.Provider
value={{
palette: themeRef.current.palette,
setMode,
}}
>
{props.children}
</ThemeContext.Provider>
);
};
export const makeStyles = (
styles: (theme: ThemeAPI) => {
[key: string]: ViewStyle | TextStyle | ImageStyle | Object;
},
) => {
return () => {
const context = useContext(ThemeContext);
return styles(context);
};
};
export const useTheme = () => {
const context = useContext(ThemeContext);
return context;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment