All files / src/utils spaceTheme.ts

100% Statements 50/50
100% Branches 31/31
100% Functions 20/20
100% Lines 46/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233                                                                                                11x                             11x     11x             11x                 11x 11x     11x   11x   11x 11x     9528x 9528x         3176x 3176x 3176x 3176x         1588x       1588x         769x             47x         536x 1608x 536x                     228x 38x     114x 114x           182x               125x 125x         22x                 184x 184x 146x   38x                       179x 179x 179x                     90x               42x 42x               48x 48x 48x 48x       1x      
/**
 * A flow's public space (`/space/{slug}`): its theme, turned into CSS
 * variables, and the contrast checks behind the settings form's warnings.
 * Mirrors flows-api's utils/validateSpace.js. See docs/architecture/FLOW_SPACE.md.
 */
 
export type SpaceFont = 'sans' | 'serif' | 'rounded' | 'mono'
 
/** Whether the space follows the reader's dark mode ('auto') or always shows its colors */
export type SpaceDarkMode = 'auto' | 'off'
 
/** The light or dark mode a page is drawn in */
export type ColorScheme = 'light' | 'dark'
 
export interface SpaceTheme {
  primaryColor?: string
  secondaryColor?: string
  backgroundColor?: string
  font?: SpaceFont
  darkMode?: SpaceDarkMode
}
 
/** Membership requests from the public space (flows-api utils/spaceJoin.js) */
/**
 * Membership requests (UC-SPACE-003.1): open with a default role. The
 * membership entity is optional; with one, its member field is required and
 * the former member state (UC-SPACE-006.1) optional.
 */
export interface FlowSpaceJoin {
  defaultRoleId: string
  entityId?: string
  userFieldId?: string
  formerMemberFieldId?: string
  formerMemberStateId?: string
  privacyContact?: string
}
 
export interface FlowSpace {
  enabled: boolean
  theme?: SpaceTheme
  join?: FlowSpaceJoin
}
 
/**
 * Field types the join form shows — mirrors JOIN_FIELD_TYPES in flows-api
 * utils/spaceJoin.js. A mandatory field of another type (the member field
 * aside) keeps an entity from being the membership entity.
 */
export const JOIN_FIELD_TYPES = [
  'text',
  'textarea',
  'email',
  'number',
  'date',
  'select',
  'multiselect',
  'boolean',
  'image',
  'image_set',
  'file',
  'file_set'
] as const
 
export const SPACE_FONTS: SpaceFont[] = ['sans', 'serif', 'rounded', 'mono']
 
/** Generic families only: a public page never loads a font chosen by a member */
const FONT_STACKS: Record<SpaceFont, string> = {
  sans: "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
  serif: "Georgia, Cambria, 'Times New Roman', Times, serif",
  rounded: "ui-rounded, 'SF Pro Rounded', 'Arial Rounded MT Bold', system-ui, sans-serif",
  mono: "ui-monospace, 'SFMono-Regular', Menlo, Consolas, 'Liberation Mono', monospace"
}
 
export const DEFAULT_SPACE_THEME: Required<SpaceTheme> = {
  primaryColor: '#689909',
  secondaryColor: '#bee476',
  backgroundColor: '#ffffff',
  font: 'sans',
  darkMode: 'auto'
}
 
/** The dark mode's base background, tinted by the main color (UC-SPACE-017.1 AC-4) */
const DARK_BACKGROUND_BASE = '#16191d'
const DARK_BACKGROUND_TINT = 0.1
 
/** WCAG AA minimum contrast for normal text */
export const MIN_TEXT_CONTRAST = 4.5
 
const COLOR_PATTERN = /^#[0-9a-f]{6}$/i
 
const DARK_TEXT = '#212529'
const LIGHT_TEXT = '#ffffff'
 
function channel(value: number): number {
  const c = value / 255
  return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
}
 
/** WCAG relative luminance of a #rrggbb color */
export function relativeLuminance(hex: string): number {
  const r = Number.parseInt(hex.slice(1, 3), 16)
  const g = Number.parseInt(hex.slice(3, 5), 16)
  const b = Number.parseInt(hex.slice(5, 7), 16)
  return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b)
}
 
/** WCAG contrast ratio between two #rrggbb colors, from 1 to 21 */
export function contrastRatio(a: string, b: string): number {
  const [light, dark] = [relativeLuminance(a), relativeLuminance(b)].sort((x, y) => y - x) as [
    number,
    number
  ]
  return (light + 0.05) / (dark + 0.05)
}
 
/** The text color (dark or white) that reads best on a background */
export function readableTextColor(background: string): string {
  return contrastRatio(background, DARK_TEXT) >= contrastRatio(background, LIGHT_TEXT)
    ? DARK_TEXT
    : LIGHT_TEXT
}
 
/** Whether even the best text color stays below WCAG AA on this background */
export function isHardToRead(background: string): boolean {
  return contrastRatio(background, readableTextColor(background)) < MIN_TEXT_CONTRAST
}
 
/** The theme with every missing or malformed value replaced by the default */
export function resolveSpaceTheme(theme: SpaceTheme | undefined): Required<SpaceTheme> {
  const pick = (value: string | undefined, fallback: string) =>
    value && COLOR_PATTERN.test(value) ? value.toLowerCase() : fallback
  return {
    primaryColor: pick(theme?.primaryColor, DEFAULT_SPACE_THEME.primaryColor),
    secondaryColor: pick(theme?.secondaryColor, DEFAULT_SPACE_THEME.secondaryColor),
    backgroundColor: pick(theme?.backgroundColor, DEFAULT_SPACE_THEME.backgroundColor),
    font: theme?.font && SPACE_FONTS.includes(theme.font) ? theme.font : DEFAULT_SPACE_THEME.font,
    darkMode: theme?.darkMode === 'off' ? 'off' : 'auto'
  }
}
 
/** `weight` of `b` mixed into `a`, both #rrggbb */
function mixColors(a: string, b: string, weight: number): string {
  const channelAt = (hex: string, i: number) => Number.parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16)
  return (
    '#' +
    [0, 1, 2]
      .map((i) => Math.round(channelAt(a, i) * (1 - weight) + channelAt(b, i) * weight))
      .map((value) => value.toString(16).padStart(2, '0'))
      .join('')
  )
}
 
/** Whether a background takes light text, i.e. is already dark */
const isDark = (background: string) => readableTextColor(background) === LIGHT_TEXT
 
/**
 * Whether the space changes with the reader's dark mode, so its mode button is
 * shown: it follows the reader's mode and its background is light. A dark
 * background is kept in both modes, which then look the same.
 */
export function followsDarkMode(theme: SpaceTheme | undefined): boolean {
  const resolved = resolveSpaceTheme(theme)
  return resolved.darkMode === 'auto' && !isDark(resolved.backgroundColor)
}
 
/** Whether the space follows the reader's mode but has nothing to change: its background is dark */
export function hasDarkBackground(theme: SpaceTheme | undefined): boolean {
  return isDark(resolveSpaceTheme(theme).backgroundColor)
}
 
/**
 * The background a space is drawn on: its own, or in dark mode (unless the
 * flow turned that off) a dark gray tinted by its main color; a background
 * that is already dark is kept.
 */
export function spaceBackground(theme: SpaceTheme | undefined, scheme: ColorScheme): string {
  const resolved = resolveSpaceTheme(theme)
  if (scheme === 'light' || resolved.darkMode === 'off' || isDark(resolved.backgroundColor)) {
    return resolved.backgroundColor
  }
  return mixColors(DARK_BACKGROUND_BASE, resolved.primaryColor, DARK_BACKGROUND_TINT)
}
 
/**
 * CSS variables for a space page's root element, in the reader's mode. The
 * main and accent colors never change; the cards and boxes derive from the
 * background and text colors, so they follow.
 */
export function spaceThemeStyle(
  theme: SpaceTheme | undefined,
  scheme: ColorScheme = 'light'
): Record<string, string> {
  const resolved = resolveSpaceTheme(theme)
  const background = spaceBackground(theme, scheme)
  return {
    '--space-primary': resolved.primaryColor,
    '--space-on-primary': readableTextColor(resolved.primaryColor),
    '--space-secondary': resolved.secondaryColor,
    '--space-on-secondary': readableTextColor(resolved.secondaryColor),
    '--space-background': background,
    '--space-text': readableTextColor(background),
    '--space-font': FONT_STACKS[resolved.font]
  }
}
 
const themeStorageKey = (slug: string) => `spaceTheme:${slug}`
 
/**
 * Keeps a space's theme in the browser, to draw it while the space loads next
 * time instead of a white page (UC-SPACE-017.1 AC-6). Storage may be blocked
 * (private window): then nothing is kept.
 */
export function rememberSpaceTheme(slug: string, theme: SpaceTheme | undefined): void {
  try {
    localStorage.setItem(themeStorageKey(slug), JSON.stringify(theme ?? {}))
  } catch {
    // Storage unavailable: the next load starts from the default look
  }
}
 
/** The theme last shown for this space in this browser, if any */
export function rememberedSpaceTheme(slug: string): SpaceTheme | undefined {
  try {
    const stored = localStorage.getItem(themeStorageKey(slug))
    const parsed: unknown = stored ? JSON.parse(stored) : undefined
    return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
      ? (parsed as SpaceTheme)
      : undefined
  } catch {
    return undefined
  }
}