import React, {useContext, useEffect, useState, forwardRef, HTMLAttributes, CSSProperties} from 'react'; import {ThemeContext} from "../contexts/contexts"; import { Accordion as SAccordion, AccordionContent as SAccordionContent, AccordionTitle as SAccordionTitle, Breadcrumb as SBreadcrumb, Button as SButton, ButtonGroup as SButtonGroup, Card as SCard, Divider as SDivider, Form as SForm, FormField as SFormField, FormGroup as SFormGroup, FormInput as SFormInput, Header as SHeader, Icon as SIcon, List as SList, ListContent as SListContent, ListDescription as SListDescription, ListHeader as SListHeader, ListIcon as SListIcon, ListItem as SListItem, Loader as SLoader, Menu as SMenu, MenuItem as SMenuItem, MenuHeader as SMenuHeader, MenuMenu as SMenuMenu, Modal as SModal, ModalActions as SModalActions, ModalContent as SModalContent, ModalDescription as SModalDescription, ModalHeader as SModalHeader, Placeholder as SPlaceholder, Popup as SPopup, Progress as SProgress, Ref as SRef, Segment as SSegment, Statistic as SStatistic, StatisticGroup as SStatisticGroup, Tab as STab, Table as STable, TableBody as STableBody, TableCell as STableCell, TableFooter as STableFooter, TableHeader as STableHeader, TableHeaderCell as STableHeaderCell, TableRow as STableRow, TabPane as STabPane, TextArea as STextArea, AccordionContentProps, AccordionProps, AccordionTitleProps, BreadcrumbProps, ButtonProps, ButtonGroupProps, CardProps as SCardProps, DividerProps, FormProps, FormFieldProps, FormGroupProps, FormInputProps, HeaderProps, IconProps, ListProps, ListItemProps, ListIconProps, ListContentProps, ListHeaderProps, ListDescriptionProps, LoaderProps, MenuProps, MenuItemProps, MenuMenuProps, ModalProps, ModalActionsProps, ModalContentProps, ModalDescriptionProps, ModalHeaderProps, PlaceholderProps, PopupProps, ProgressProps, SegmentProps, StatisticProps, StatisticGroupProps, TabProps, TableProps, TableBodyProps, TableCellProps, TableFooterProps, TableHeaderProps, TableHeaderCellProps, TableRowProps, TabPaneProps, TextAreaProps, } from "semantic-ui-react"; import {MantineProvider} from "@mantine/core"; import {Notifications} from "@mantine/notifications"; import {cssVariablesResolver, mantineTheme} from "../themes/mantine"; import {ColorToSemanticHexColor} from "./Vars"; import _ from "lodash"; import {ThemeContextValue, ThemeName, SavedThemeName} from "../types/theme"; export const darkTheme = 'dark'; export const lightTheme = 'light'; export const nightTheme = 'night'; export const amberTheme = 'amber'; export const defaultTheme = lightTheme; export const systemTheme = 'system'; export const themeSessionKey = 'color-scheme'; // Every theme a user can apply, in the order the theme picker offers them. export const themeNames: ThemeName[] = [lightTheme, darkTheme, nightTheme, amberTheme]; // Themes built on a dark background. Semantic components are `inverted` in these. const darkThemes: ThemeName[] = [darkTheme, nightTheme, amberTheme]; // Themes a user must choose deliberately; `prefers-color-scheme` never picks them. const explicitOnlyThemes: ThemeName[] = [nightTheme, amberTheme]; export const isDarkTheme = (theme: ThemeName): boolean => darkThemes.includes(theme); const isThemeName = (value: unknown): value is ThemeName => themeNames.includes(value as ThemeName); /** Resolve the saved preference to the theme that should be applied right now. */ export const resolveTheme = (saved: SavedThemeName): ThemeName => { if (isThemeName(saved)) { return saved; } // `system`, null, or a value written by an older version. const prefersDark = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-color-scheme: dark)').matches; return prefersDark ? darkTheme : lightTheme; } const readSavedTheme = (): SavedThemeName => { try { const value = localStorage.getItem(themeSessionKey); if (isThemeName(value) || value === systemTheme) { return value; } } catch (e) { // localStorage can throw when cookies/storage are blocked. console.error('Unable to read the saved theme', e); } return null; } interface ThemeProviderProps { children: React.ReactNode; } export function ThemeProvider({children, ...props}: ThemeProviderProps) { if (!_.isEmpty(props)) { console.log(props); console.error('ThemeWrapper does not support props!'); } // savedTheme is the user's preference: a theme name, `system`, or null (never chosen). const [savedTheme, setSavedTheme] = useState(readSavedTheme); // theme is what is currently applied. const [theme, setThemeName] = useState(() => resolveTheme(readSavedTheme())); // `data-theme` on is what the token CSS keys off of. index.html stamps it before // first paint from the same localStorage value, so the first render already matches. useEffect(() => { document.documentElement.setAttribute('data-theme', theme); }, [theme]); // Follow the OS preference only while the user has not chosen a specific theme. useEffect(() => { if (isThemeName(savedTheme) || typeof window.matchMedia !== 'function') { return; } const query = window.matchMedia('(prefers-color-scheme: dark)'); const onChange = () => setThemeName(resolveTheme(savedTheme)); query.addEventListener('change', onChange); return () => query.removeEventListener('change', onChange); }, [savedTheme]); const saveTheme = (value: SavedThemeName) => { setSavedTheme(value); try { if (value === null) { localStorage.removeItem(themeSessionKey); } else { localStorage.setItem(themeSessionKey, value); } } catch (e) { console.error('Unable to save the theme', e); } } /** Apply and persist a theme. Pass `system` to follow the OS preference. */ const setTheme = (value: SavedThemeName) => { if (value !== systemTheme && value !== null && !isThemeName(value)) { console.error(`Unknown theme! ${value}`); return; } saveTheme(value); setThemeName(resolveTheme(value)); } // Retained for callers written against the old two-theme API. const setDarkTheme = (save = false) => { setThemeName(darkTheme); if (save) saveTheme(darkTheme); } const setLightTheme = (save = false) => { setThemeName(lightTheme); if (save) saveTheme(lightTheme); } const cycleSavedTheme = (e?: React.MouseEvent) => { // Cycle: System -> Light -> Dark -> Night -> Amber -> System if (e) { e.preventDefault(); } const order: SavedThemeName[] = [systemTheme, ...themeNames]; const current = order.indexOf(isThemeName(savedTheme) ? savedTheme : systemTheme); setTheme(order[(current + 1) % order.length]); } const dark = isDarkTheme(theme); // Compatibility layer for components which have not been migrated to tokens yet. Semantic // has no concept of the night/amber themes, so they reuse its dark treatment while pulling // their colors from the tokens. These values disappear with the last Semantic component. const i = dark ? {inverted: true} : {inverted: undefined}; const inverted = dark ? 'inverted' : ''; let s: {style?: CSSProperties} = {}; let t: {style?: CSSProperties} = {}; if (theme === darkTheme) { s = {style: {backgroundColor: '#1B1C1D', color: '#dddddd'}}; t = {style: {color: '#eeeeee'}}; } else if (explicitOnlyThemes.includes(theme)) { s = {style: {backgroundColor: 'var(--panel)', color: 'var(--text)'}}; t = {style: {color: 'var(--text)'}}; } const themeValue: ThemeContextValue = { i, // Used for Semantic elements which support "inverted". s, // Used to invert the style some elements. t, // Used to invert text. inverted, // Used to add "invert" to className. theme, savedTheme, isDark: dark, setTheme, setDarkTheme, setLightTheme, cycleSavedTheme, }; // Mantine's own scheme decides the surfaces its internals use (overlays, scrollbars, // focus rings). Night and amber are neither of its two schemes, so they ride on dark // and take their actual colors from our tokens. This is the theme `base` flag. return {children} } // Simple wrappers for Semantic UI elements to use the current theme. const invertedNull = (props: T): T => { if (props['inverted'] === true) { return {...props, inverted: null}; } return props; } const defaultGrey = (props: T, inverted: boolean): T => { // Some elements look softer when grey, use grey only if another color is not provided. if (inverted) { return {color: 'grey', ...props} as T; } return props; } // ---------------------------------------------------------------------------- // Accordion Compound Component // ---------------------------------------------------------------------------- type AccordionTitleComponent = React.FC; type AccordionContentComponent = React.FC; interface AccordionComponent extends React.FC { Title: AccordionTitleComponent; Content: AccordionContentComponent; } const AccordionTitle: AccordionTitleComponent = (props) => { return }; const AccordionContent: AccordionContentComponent = (props) => { return }; const AccordionBase: React.FC = (props) => { const {i, inverted} = useContext(ThemeContext); const mergedProps = defaultGrey({...i, ...props}, !!inverted); return }; export const Accordion: AccordionComponent = Object.assign(AccordionBase, { Title: AccordionTitle, Content: AccordionContent, }); // ---------------------------------------------------------------------------- // Button Compound Component // ---------------------------------------------------------------------------- type ButtonGroupComponent = React.FC; interface ButtonComponent extends React.ForwardRefExoticComponent> { Group: ButtonGroupComponent; } const ButtonGroup: ButtonGroupComponent = (props) => { return }; const ButtonBase = forwardRef((props, ref) => { const {i, inverted} = useContext(ThemeContext); const mergedProps = defaultGrey({...i, ...props}, !!inverted); // SButton is a class component, so a forwarded `ref` would resolve to the class instance rather than the DOM // node. Semantic UI's Modal/Popup use the trigger's ref with `node.contains(...)`, which throws on a non-DOM // value. Wrap in Ref (findDOMNode) so the forwarded ref always resolves to the underlying ); }; // ---------------------------------------------------------------------------- // Form Compound Component // ---------------------------------------------------------------------------- type FormFieldComponent = React.FC; type FormGroupComponent = React.FC; type FormInputComponent = React.FC; interface FormComponent extends React.FC { Field: FormFieldComponent; Group: FormGroupComponent; Input: FormInputComponent; } const FormField: FormFieldComponent = (props) => { const {i} = useContext(ThemeContext); const mergedProps = invertedNull({...i, ...props}); return }; const FormGroup: FormGroupComponent = (props) => { const {i} = useContext(ThemeContext); const mergedProps = invertedNull({...i, ...props}); return }; const FormInput: FormInputComponent = (props) => { const {i} = useContext(ThemeContext); return }; const FormBase: React.FC = (props) => { const {i} = useContext(ThemeContext); return }; export const Form: FormComponent = Object.assign(FormBase, { Field: FormField, Group: FormGroup, Input: FormInput, }); // ---------------------------------------------------------------------------- // Card Compound Component // ---------------------------------------------------------------------------- interface CardIconProps extends HTMLAttributes { onClick?: () => void; children?: React.ReactNode; } type CardIconComponent = React.FC; interface CardProps extends Omit { color?: string; } interface CardComponent extends React.FC { Icon: CardIconComponent; } const CardIcon: CardIconComponent = ({onClick, children, ...props}) => { const {inverted} = useContext(ThemeContext); const cardIcon =
{children}
; if (onClick) { return
{cardIcon}
} else { return cardIcon; } }; const CardBase: React.FC = ({color, ...props}) => { const {inverted} = useContext(ThemeContext); const style: CSSProperties = props.style || {}; const emphasisColor = ColorToSemanticHexColor(color); if (emphasisColor) { // Increase drop shadow to emphasize color. const borderColor = inverted ? '#888' : '#ddd'; style.boxShadow = `0 0 0 2px ${borderColor}, 0 5px 0 0 ${emphasisColor}, 0 0px 3px 0 #d4d4d5`; } return }; export const Card: CardComponent = Object.assign(CardBase, { Icon: CardIcon, }); // ---------------------------------------------------------------------------- // Tab Compound Component // ---------------------------------------------------------------------------- type TabPaneComponent = React.FC; interface TabComponent extends React.FC { Pane: TabPaneComponent; } const TabPane: TabPaneComponent = (props) => { const {i} = useContext(ThemeContext); return }; const TabBase: React.FC = (props) => { const {i} = useContext(ThemeContext); const mergedProps = invertedNull({...i, ...props}); return }; export const Tab: TabComponent = Object.assign(TabBase, { Pane: TabPane, }); // ---------------------------------------------------------------------------- // Statistic Compound Component // ---------------------------------------------------------------------------- type StatisticGroupComponent = React.FC; interface StatisticComponent extends React.FC { Group: StatisticGroupComponent; } const StatisticGroup: StatisticGroupComponent = (props) => { const {i} = useContext(ThemeContext); const style: CSSProperties = {...props.style, marginLeft: 0, marginRight: 0}; return }; const StatisticBase: React.FC = (props) => { const {i, inverted} = useContext(ThemeContext); const mergedProps = defaultGrey({...i, ...props}, !!inverted); return }; export const Statistic: StatisticComponent = Object.assign(StatisticBase, { Group: StatisticGroup, }); // ---------------------------------------------------------------------------- // Breadcrumb Compound Component // ---------------------------------------------------------------------------- interface BreadcrumbDividerProps { icon?: string; } type BreadcrumbDividerComponent = React.FC; interface BreadcrumbComponent extends React.FC { Divider: BreadcrumbDividerComponent; } const BreadcrumbDivider: BreadcrumbDividerComponent = ({icon, ...props}) => { const {inverted} = useContext(ThemeContext); // TODO this only handles icons for now. const className = `divider icon ${inverted} ${icon || ''}`; return }; const BreadcrumbBase: React.FC = (props) => { const {t} = useContext(ThemeContext); return }; export const Breadcrumb: BreadcrumbComponent = Object.assign(BreadcrumbBase, { Divider: BreadcrumbDivider, }); // ---------------------------------------------------------------------------- // Table Compound Component // ---------------------------------------------------------------------------- type TableBodyComponent = React.FC; type TableCellComponent = React.FC; type TableFooterComponent = React.FC; type TableHeaderComponent = React.FC; type TableHeaderCellComponent = React.FC; type TableRowComponent = React.FC; interface TableComponent extends React.FC { Body: TableBodyComponent; Cell: TableCellComponent; Footer: TableFooterComponent; Header: TableHeaderComponent; HeaderCell: TableHeaderCellComponent; Row: TableRowComponent; } const TableBody: TableBodyComponent = (props) => { return }; const TableCell: TableCellComponent = (props) => { return }; const TableFooter: TableFooterComponent = (props) => { return }; const TableHeader: TableHeaderComponent = (props) => { return }; const TableHeaderCell: TableHeaderCellComponent = (props) => { return }; const TableRow: TableRowComponent = (props) => { return }; const TableBase: React.FC = (props) => { const {i} = useContext(ThemeContext); return }; export const Table: TableComponent = Object.assign(TableBase, { Body: TableBody, Cell: TableCell, Footer: TableFooter, Header: TableHeader, HeaderCell: TableHeaderCell, Row: TableRow, });