import type { DesignSystem } from '../design-system'
import type { Theme, ThemeKey } from '../theme'
import { withAlpha } from '../utilities'
import { DefaultMap } from '../utils/default-map'
import { toKeyPath } from '../utils/to-key-path'
import { deepMerge } from './config/deep-merge'
import type { UserConfig } from './config/types'
export function createThemeFn(
designSystem: DesignSystem,
configTheme: () => UserConfig['theme'],
resolveValue: (value: any) => any,
) {
return function theme(path: string, defaultValue?: any) {
let lastSlash = path.lastIndexOf('/')
let modifier: string | null = null
if (lastSlash !== -1) {
modifier = path.slice(lastSlash + 1).trim()
path = path.slice(0, lastSlash).trim()
}
let resolvedValue = (() => {
let keypath = toKeyPath(path)
let cssValue = readFromCss(designSystem.theme, keypath)
if (typeof cssValue !== 'object') {
return cssValue
}
let configValue = resolveValue(get(configTheme() ?? {}, keypath) ?? null)
if (configValue !== null && typeof configValue === 'object' && !Array.isArray(configValue)) {
return deepMerge({}, [configValue, cssValue], (_, b) => b)
}
return cssValue ?? configValue
})()
if (modifier && typeof resolvedValue === 'string') {
resolvedValue = withAlpha(resolvedValue, modifier)
}
return resolvedValue ?? defaultValue
}
}
function readFromCss(theme: Theme, path: string[]) {
if (path.length === 1 && path[0].startsWith('--')) {
return theme.get([path[0] as ThemeKey])
}
type ThemeValue =
| string
| [main: string, extra: Record<string, string>]
let themeKey = path
.map((path) => (path === '1' ? '' : path))
.map((part) =>
part.replaceAll('.', '_').replace(/([a-z])([A-Z])/g, (_, a, b) => `${a}-${b.toLowerCase()}`),
)
.filter((part, index) => part !== 'DEFAULT' || index !== path.length - 1)
.join('-')
let map = new Map<string | null, ThemeValue>()
let nested = new DefaultMap<string | null, Map<string, string>>(() => new Map())
let ns = theme.namespace(`--${themeKey}` as any)
if (ns.size === 0) {
return null
}
for (let [key, value] of ns) {
if (!key || !key.includes('--')) {
map.set(key, value)
continue
}
let nestedIndex = key.indexOf('--')
let mainKey = key.slice(0, nestedIndex)
let nestedKey = key.slice(nestedIndex + 2)
nestedKey = nestedKey.replace(/-([a-z])/g, (_, a) => a.toUpperCase())
nested.get(mainKey === '' ? null : mainKey).set(nestedKey, value)
}
for (let [key, extra] of nested) {
let value = map.get(key)
if (typeof value !== 'string') continue
map.set(key, [value, Object.fromEntries(extra)])
}
let obj = {}
let useNestedObjects = false
for (let [key, value] of map) {
key = key ?? 'DEFAULT'
let path: string[] = []
let splitIndex = key.indexOf('-')
if (useNestedObjects && splitIndex !== -1) {
path.push(key.slice(0, splitIndex))
path.push(key.slice(splitIndex + 1))
} else {
path.push(key)
}
set(obj, path, value)
}
if ('DEFAULT' in obj) {
if (path[path.length - 1] === 'DEFAULT') {
return obj.DEFAULT
}
if (Object.keys(obj).length === 1) {
return obj.DEFAULT
}
}
return obj
}
function get(obj: any, path: string[]) {
for (let i = 0; i < path.length; ++i) {
let key = path[i]
if (obj[key] === undefined) {
if (path[i + 1] === undefined) {
return undefined
}
path[i + 1] = `${key}-${path[i + 1]}`
continue
}
obj = obj[key]
}
return obj
}
function set(obj: any, path: string[], value: any) {
for (let key of path.slice(0, -1)) {
if (obj[key] === undefined) {
obj[key] = {}
}
obj = obj[key]
}
obj[path[path.length - 1]] = value
}