import CSS from "csstype" import { entries, isObject, mapValues } from "lodash-es" import React, { DependencyList, createContext, useInsertionEffect, useLayoutEffect, useMemo, } from "react" import { clsx } from "./clsx" import { attachVariableGroups } from "./cssVar" import { Destructor, joinDestructors } from "./destructors" import { hashObject } from "./hashObject" import { hyphenateStyleName } from "./hyphenateStyleName" import { useRequiredContext } from "./useRequiredContext" const UNITLESS_NUMBER_PROPS = [ "animation-iteration-count", "border-image-outset", "border-image-slice", "border-image-width", "box-flex", "box-flex-group", "box-ordinal-group", "column-count", "columns", "flex", "flex-grow", "flex-positive", "flex-shrink", "flex-negative", "flex-order", "grid-row", "grid-row-end", "grid-row-span", "grid-row-start", "grid-column", "grid-column-end", "grid-column-span", "grid-column-start", "font-weight", "line-clamp", "line-height", "opacity", "order", "orphans", "tabSize", "widows", "z-index", "zoom", // SVG-related properties "fill-opacity", "flood-opacity", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-miterlimit", "stroke-opacity", "stroke-width", ] const VENDOR_PREFIXES = ["-webkit-", "-moz-", "-ms-", "-o-"] as const /** True when a numeric value should compile without an implicit `px` suffix. */ function isUnitlessNumberProperty(kebabProperty: string): boolean { if (UNITLESS_NUMBER_PROPS.includes(kebabProperty)) { return true } for (const prefix of VENDOR_PREFIXES) { if (!kebabProperty.startsWith(prefix)) continue const unprefixed = kebabProperty.slice(prefix.length) if (UNITLESS_NUMBER_PROPS.includes(unprefixed)) { return true } } return false } type BaseCSSProperties = CSS.Properties type CustomProperties = { [name: `--${string}`]: string | number | undefined } type Declarations = BaseCSSProperties & CustomProperties type NestedRuleKey = | `&${CSS.SimplePseudos}` | `${CSS.AtRules}${string}` | `.${string}` | `&${string}` /** * Value under a pattern key (`--*` custom property or nested rule). Both share * one value type because TypeScript widens computed keys such as * `` [`&[data-selected] ${part}`] `` to `string`, and a `string` key must fit * every pattern signature at once. */ type PatternValue = Declarations | string | number | undefined export type CSSProperties = { [Key in keyof BaseCSSProperties]?: BaseCSSProperties[Key] } & { [Key in `--${string}` | NestedRuleKey]?: PatternValue } const PurseContext = createContext(undefined) export type StyleApi = { addStyleElement: (styleElement: StyleElement) => Destructor addGlobalStyle: (styleRule: string) => Destructor } const __style__ = Symbol("style-element") type StyleRule = string export type StyleElement = { __style__: typeof __style__ composed: StyleElement[] /** This style's own class. Present even when it only composes other styles. */ owned: { styleRules: StyleRule[] className: string } className: string /** * The own class as a selector, so a style interpolates into nested rules: * `` [`&[data-selected] ${part}`]: { … } ``. */ toString(): string } function isStyleElement(o: unknown): o is StyleElement { return ( o != null && typeof o === "object" && "__style__" in o && o["__style__"] === __style__ ) } const DEV = process.env.NODE_ENV === "development" export type InMemoryStyleApi = { styleRulesRef: { current: string[] } addStyleElement: StyleApi["addStyleElement"] addGlobalStyle: StyleApi["addGlobalStyle"] detachVariableGroups: Destructor } export function createInMemoryStyleApi(): InMemoryStyleApi { let styleRules: string[] = [] type InsertedStyleElement = { refCount: number destructor: Destructor } const insertedStyleElementClassNames = new Map() function addStyleRule(rule: StyleRule): Destructor { styleRules.push(rule) return () => { const ruleToRemove = rule styleRules = styleRules.filter((rule) => rule !== ruleToRemove) } } function removeStyleElement(styleElement: StyleElement) { for (const composed of styleElement.composed) { removeStyleElement(composed) } if (styleElement.owned) { const { className } = styleElement.owned const maybeInsertedStyleElement = insertedStyleElementClassNames.get(className) if (!maybeInsertedStyleElement) return const { refCount, destructor } = maybeInsertedStyleElement const newRefCount = refCount - 1 if (newRefCount <= 0) { insertedStyleElementClassNames.delete(className) destructor() } else { insertedStyleElementClassNames.set(className, { refCount: newRefCount, destructor, }) } } } function addStyleElement(styleElement: StyleElement): Destructor { for (const composed of styleElement.composed) { addStyleElement(composed) } if (styleElement.owned) { const { className, styleRules } = styleElement.owned const maybeInsertedStyleElement = insertedStyleElementClassNames.get(className) if (maybeInsertedStyleElement) { const { destructor, refCount } = maybeInsertedStyleElement insertedStyleElementClassNames.set(className, { destructor, refCount: refCount + 1, }) } else { const destructors: Destructor[] = styleRules.map(addStyleRule) const destructor = joinDestructors(destructors) insertedStyleElementClassNames.set(className, { destructor, refCount: 1, }) } } return () => removeStyleElement(styleElement) } const styleApi = { addStyleElement, addGlobalStyle: addStyleRule, } return { ...styleApi, detachVariableGroups: attachVariableGroups(styleApi), styleRulesRef: { get current() { return styleRules }, }, } } export function PurseProvider(props: { children?: React.ReactNode }) { const htmlStyleElement = useMemo(() => document.createElement("style"), []) const atRuleHtmlStyleElement = useMemo( () => document.createElement("style"), [], ) useInsertionEffect(() => { document.head.appendChild(htmlStyleElement) document.head.appendChild(atRuleHtmlStyleElement) return () => { document.head.removeChild(htmlStyleElement) document.head.removeChild(atRuleHtmlStyleElement) } }, [htmlStyleElement, atRuleHtmlStyleElement]) const styleApi: StyleApi = useMemo(() => { type InsertedStyleElement = { refCount: number destructor: Destructor } const insertedStyleElementClassNames = new Map< string, InsertedStyleElement >() // Rules go through the CSSOM rather than as Text children: changing a //