A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): edit theme colors and fonts token by token
Hampus64f26de6cce7
diff --git a/fluxer_app/src/features/theme_settings/components/ColorsAndFontsSection.tsx b/fluxer_app/src/features/theme_settings/components/ColorsAndFontsSection.tsxnew file mode 100644index 000000000..43ed0b9e8--- /dev/null+++ b/fluxer_app/src/features/theme_settings/components/ColorsAndFontsSection.tsx@@ -0,0 +1,226 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {ConfirmModal} from '@app/features/app/components/dialogs/ConfirmModal';+import {SettingsSection} from '@app/features/app/components/dialogs/shared/SettingsSection';+import {CANCEL_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';+import {remFromPx} from '@app/features/theme/layout/RemFromPx';+import Theme from '@app/features/theme/state/Theme';+import ThemeEditTarget from '@app/features/theme/state/ThemeEditTarget';+import ThemeProfile from '@app/features/theme/state/ThemeProfile';+import * as ThemeSettingsCommands from '@app/features/theme_settings/commands/ThemeSettingsCommands';+import {TokenRow} from '@app/features/theme_settings/components/TokenRow';+import ThemeSettingsState from '@app/features/theme_settings/state/ThemeSettingsState';+import styles from '@app/features/theme_settings/ThemesTab.module.css';+import {getThemeBaseKind, getThemeDefaultVariables} from '@app/features/theme_settings/utils/ThemeDefaultVariables';+import {TRY_A_DIFFERENT_NAME_OR_CLEAR_THE_SEARCH_DESCRIPTOR} from '@app/features/theme_settings/utils/ThemeSettingsMessageDescriptors';+import {+ getTokenGroupLabelDescriptor,+ getTokenVariableDefinition,+ humanizeVariableName,+ TOKEN_GROUPS,+} from '@app/features/theme_settings/utils/TokenGroups';+import {Accordion} from '@app/features/ui/accordion/Accordion';+import {Button} from '@app/features/ui/button/Button';+import * as ModalCommands from '@app/features/ui/commands/ModalCommands';+import {modal} from '@app/features/ui/commands/ModalCommands';+import {Input} from '@app/features/ui/components/form/FormInput';+import {+ extractThemeVariableOverrides,+ removeThemeVariableOverrides,+ updateCssForVariable,+} from '@app/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils';+import {COLORS_AND_FONTS_SECTION_DESCRIPTOR} from '@app/features/user/components/settings_utils/section_registry/ThemesSections';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {MagnifyingGlassIcon} from '@phosphor-icons/react';+import {observer} from 'mobx-react-lite';+import type React from 'react';+import {useMemo, useState} from 'react';++const COLORS_AND_FONTS_DESCRIPTION_DESCRIPTOR = msg({+ message:+ "Change single colors and fonts of the base theme. Your changes are saved in the quick CSS of the theme you're editing.",+ comment:+ 'Description of the "Colors and fonts" section in Settings > Themes. Quick CSS is custom CSS the user writes.',+});+const CHANGED_COUNT_DESCRIPTOR = msg({+ message: '{count, plural, one {# changed} other {# changed}}',+ comment:+ 'Shown next to the "Colors and fonts" section title in Settings > Themes. How many colors and fonts the user changed.',+});+const CLEAR_ALL_CHANGES_DESCRIPTOR = msg({+ message: 'Clear all changes',+ comment: 'Button in the "Colors and fonts" section in Settings > Themes that removes every color and font change.',+});+const CLEAR_ALL_CHANGES_TITLE_DESCRIPTOR = msg({+ message: 'Clear all color and font changes?',+ comment: 'Confirmation title before clearing every color and font change in Settings > Themes.',+});+const CLEAR_ALL_CHANGES_CONFIRM_DESCRIPTOR = msg({+ message: 'This removes every color, font and size change. Saved themes and the rest of your quick CSS stay.',+ comment:+ 'Confirmation text before clearing every color and font change in Settings > Themes. Quick CSS is custom CSS the user writes.',+});+const SEARCH_COLORS_AND_FONTS_DESCRIPTOR = msg({+ message: 'Search colors and fonts…',+ comment: 'Placeholder for the search field in the "Colors and fonts" section in Settings > Themes.',+});+const NOTHING_MATCHES_DESCRIPTOR = msg({+ message: 'Nothing matches "{searchQuery}".',+ comment: 'Empty search result in the "Colors and fonts" section in Settings > Themes.',+});++function matchesSearch(variableName: string, query: string): boolean {+ const definition = getTokenVariableDefinition(variableName);+ return [variableName, humanizeVariableName(variableName), definition?.groupLabel, definition?.kind].some(+ (value) => value?.toLowerCase().includes(query) ?? false,+ );+}++export const ColorsAndFontsSection: React.FC = observer(() => {+ const {i18n} = useLingui();+ const customThemeCss = ThemeProfile.customThemeCssFor(ThemeEditTarget.target) ?? '';+ const overrides = useMemo(() => extractThemeVariableOverrides(customThemeCss), [customThemeCss]);+ const overrideCount = Object.keys(overrides).length;+ const defaultValues = getThemeDefaultVariables(getThemeBaseKind(Theme.themeFor(ThemeEditTarget.target)));+ const searchQuery = ThemeSettingsState.tokenSearch.trim().toLowerCase();+ const searching = searchQuery.length > 0;+ const [searchCollapsed, setSearchCollapsed] = useState<{query: string; groupIds: ReadonlySet<string>}>({+ query: searchQuery,+ groupIds: new Set(),+ });+ const collapsedWhileSearching = searchCollapsed.query === searchQuery ? searchCollapsed.groupIds : new Set<string>();+ const setGroupExpanded = (groupId: string, expanded: boolean) => {+ if (!searching) {+ ThemeSettingsState.setGroupExpanded(groupId, expanded);+ return;+ }+ const next = new Set(collapsedWhileSearching);+ if (expanded) {+ next.delete(groupId);+ } else {+ next.add(groupId);+ }+ setSearchCollapsed({query: searchQuery, groupIds: next});+ };+ const groups = useMemo(+ () =>+ TOKEN_GROUPS.map((group) => ({+ group,+ variables: searching+ ? group.variables.filter((variable) => matchesSearch(variable, searchQuery))+ : group.variables,+ })).filter((entry) => entry.variables.length > 0),+ [searching, searchQuery],+ );+ const writeCss = (css: string) => {+ ThemeSettingsCommands.setEditedCustomThemeCss(css.trim().length === 0 ? null : css);+ };+ const handleClearAll = () => {+ ModalCommands.push(+ modal(() => (+ <ConfirmModal+ title={i18n._(CLEAR_ALL_CHANGES_TITLE_DESCRIPTOR)}+ description={i18n._(CLEAR_ALL_CHANGES_CONFIRM_DESCRIPTOR)}+ primaryText={i18n._(CLEAR_ALL_CHANGES_DESCRIPTOR)}+ primaryVariant="danger"+ secondaryText={i18n._(CANCEL_DESCRIPTOR)}+ onPrimary={() =>+ writeCss(removeThemeVariableOverrides(ThemeProfile.customThemeCssFor(ThemeEditTarget.target) ?? ''))+ }+ data-flx="theme-settings.colors-and-fonts-section.handle-clear-all.confirm-modal"+ />+ )),+ );+ };+ return (+ <SettingsSection+ id="colors-and-fonts"+ title={i18n._(COLORS_AND_FONTS_SECTION_DESCRIPTOR)}+ description={i18n._(COLORS_AND_FONTS_DESCRIPTION_DESCRIPTOR)}+ actions={+ overrideCount > 0 ? (+ <>+ <span className={styles.changedCount} data-flx="theme-settings.colors-and-fonts-section.changed-count">+ {i18n._(CHANGED_COUNT_DESCRIPTOR, {count: overrideCount})}+ </span>+ <Button+ variant="secondary"+ small+ onClick={handleClearAll}+ data-flx="theme-settings.colors-and-fonts-section.button.clear-all"+ >+ {i18n._(CLEAR_ALL_CHANGES_DESCRIPTOR)}+ </Button>+ </>+ ) : null+ }+ data-flx="theme-settings.colors-and-fonts-section.colors-and-fonts"+ >+ <Input+ className={styles.searchInput}+ value={ThemeSettingsState.tokenSearch}+ onChange={(event) => ThemeSettingsState.setTokenSearch(event.target.value)}+ placeholder={i18n._(SEARCH_COLORS_AND_FONTS_DESCRIPTOR)}+ aria-label={i18n._(SEARCH_COLORS_AND_FONTS_DESCRIPTOR)}+ leftIcon={+ <MagnifyingGlassIcon+ size={remFromPx(16)}+ weight="bold"+ data-flx="theme-settings.colors-and-fonts-section.magnifying-glass-icon"+ />+ }+ data-flx="theme-settings.colors-and-fonts-section.search-input.set-token-search"+ />+ {groups.length === 0 ? (+ <div className={styles.empty} data-flx="theme-settings.colors-and-fonts-section.empty">+ <p className={styles.emptyTitle} data-flx="theme-settings.colors-and-fonts-section.empty-title">+ {i18n._(NOTHING_MATCHES_DESCRIPTOR, {searchQuery: ThemeSettingsState.tokenSearch.trim()})}+ </p>+ <p className={styles.note} data-flx="theme-settings.colors-and-fonts-section.note">+ {i18n._(TRY_A_DIFFERENT_NAME_OR_CLEAR_THE_SEARCH_DESCRIPTOR)}+ </p>+ </div>+ ) : (+ <div className={styles.list} data-flx="theme-settings.colors-and-fonts-section.list">+ {groups.map(({group, variables}) => {+ const labelDescriptor = getTokenGroupLabelDescriptor(group.id);+ return (+ <Accordion+ key={group.id}+ id={`theme-token-group-${group.id}`}+ title={+ <>+ {labelDescriptor == null ? group.fallbackLabel : i18n._(labelDescriptor)}+ <span className={styles.groupCount} data-flx="theme-settings.colors-and-fonts-section.group-count">+ {variables.length}+ </span>+ </>+ }+ expanded={+ searching ? !collapsedWhileSearching.has(group.id) : ThemeSettingsState.isGroupExpanded(group.id)+ }+ onExpandedChange={(expanded) => setGroupExpanded(group.id, expanded)}+ compact+ data-flx="theme-settings.colors-and-fonts-section.accordion"+ >+ {variables.map((variableName) => (+ <TokenRow+ key={variableName}+ variableName={variableName}+ label={humanizeVariableName(variableName)}+ kind={getTokenVariableDefinition(variableName)?.kind ?? 'other'}+ currentValue={overrides[variableName] ?? ''}+ defaultValue={defaultValues[variableName] ?? ''}+ onChange={(value) => writeCss(updateCssForVariable(customThemeCss, variableName, value))}+ data-flx="theme-settings.colors-and-fonts-section.token-row.write-css"+ />+ ))}+ </Accordion>+ );+ })}+ </div>+ )}+ </SettingsSection>+ );+});diff --git a/fluxer_app/src/features/theme_settings/components/TokenRow.module.css b/fluxer_app/src/features/theme_settings/components/TokenRow.module.cssnew file mode 100644index 000000000..1b4bf6462--- /dev/null+++ b/fluxer_app/src/features/theme_settings/components/TokenRow.module.css@@ -0,0 +1,158 @@+/* SPDX-License-Identifier: AGPL-3.0-or-later */++.row {+ display: flex;+ align-items: center;+ gap: var(--spacing-3);+ min-height: 3rem;+ padding: var(--spacing-1) 0;+}++.text {+ display: flex;+ flex: 1 1 auto;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+}++.label {+ overflow: hidden;+ font-weight: 500;+ font-size: 0.875rem;+ line-height: 1.25rem;+ color: var(--text-primary);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.label::first-letter {+ text-transform: uppercase;+}++.variableName {+ overflow: hidden;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 0.75rem;+ line-height: 1rem;+ color: var(--text-tertiary);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.controls {+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ gap: var(--spacing-1);+}++.field {+ display: flex;+ align-items: center;+ height: 2.25rem;+ overflow: hidden;+ border: 0.0625rem solid var(--background-modifier-accent);+ border-radius: 0.5rem;+ transition: border-color 150ms cubic-bezier(0.4, 0, 0.2, 1);+}++.field:focus-within {+ border-color: var(--background-modifier-accent-focus);+}++.textField {+ width: 15rem;+}++.input {+ flex: 1 1 auto;+ min-width: 0;+ height: 100%;+ padding: 0 0.75rem;+ border: none;+ outline: none;+ appearance: none;+ background: transparent;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 0.8125rem;+ color: var(--text-primary);+}++.input::placeholder {+ color: var(--text-tertiary);+}++.colorInput {+ width: 6.5rem;+}++.divider {+ align-self: stretch;+ width: 0.0625rem;+ background-color: var(--background-modifier-accent);+}++.swatch {+ align-self: stretch;+ width: 2.5rem;+ padding: 0;+ border: none;+ cursor: pointer;+}++.fontPreview {+ flex: 0 0 auto;+ padding-inline-start: 0.75rem;+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--text-primary);+}++.popover {+ z-index: 20000;+ outline: none;+}++.resetButton {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ padding: 0;+ border: none;+ border-radius: var(--radius-md);+ background: transparent;+ color: var(--text-primary-muted);+ cursor: pointer;+}++.resetButton:hover {+ color: var(--text-primary);+ background-color: var(--background-modifier-hover);+}++.resetSpacer {+ width: 2rem;+ height: 2rem;+}++@media (max-width: 720px) {+ .row {+ flex-wrap: wrap;+ }++ .text {+ flex-basis: 100%;+ }++ .controls {+ flex: 1 1 auto;+ }++ .textField {+ flex: 1 1 auto;+ width: auto;+ }+}diff --git a/fluxer_app/src/features/theme_settings/components/TokenRow.tsx b/fluxer_app/src/features/theme_settings/components/TokenRow.tsxnew file mode 100644index 000000000..f5f0c0ed6--- /dev/null+++ b/fluxer_app/src/features/theme_settings/components/TokenRow.tsx@@ -0,0 +1,233 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {ColorPickerPopover} from '@app/features/app/components/floating/ColorPickerPopover';+import {remFromPx} from '@app/features/theme/layout/RemFromPx';+import type {ThemeVariableKind} from '@app/features/theme/variables/ThemeVariableManifest';+import styles from '@app/features/theme_settings/components/TokenRow.module.css';+import surfaceStyles from '@app/features/ui/components/form/FormSurface.module.css';+import FocusRing from '@app/features/ui/focus_ring/FocusRing';+import {+ cssColorStringToHex,+ stripCssColorPriority,+} from '@app/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {ArrowCounterClockwiseIcon} from '@phosphor-icons/react';+import {clsx} from 'clsx';+import type React from 'react';+import {useCallback, useEffect, useState} from 'react';+import {Button as AriaButton, Dialog, DialogTrigger, Popover} from 'react-aria-components';++const EDIT_COLOR_FOR_DESCRIPTOR = msg({+ message: 'Edit color for {tokenLabel}',+ comment: 'Accessible label for the color swatch button of a color in Settings > Themes > "Colors and fonts".',+});+const COLOR_PICKER_FOR_DESCRIPTOR = msg({+ message: 'Color picker for {tokenLabel}',+ comment: 'Accessible label for the color picker popover of a color in Settings > Themes.',+});+const RESET_TO_DEFAULT_DESCRIPTOR = msg({+ message: 'Reset {tokenLabel} to default',+ comment: 'Accessible label for resetting a color or font in Settings > Themes to its default.',+});+const VALUE_FOR_DESCRIPTOR = msg({+ message: 'Value for {tokenLabel}',+ comment: 'Accessible label for the text field of a font or other value in Settings > Themes.',+});+const HEX_VALUE_FOR_DESCRIPTOR = msg({+ message: 'Hex value for {tokenLabel}',+ comment: 'Accessible label for the hex text field of a color in Settings > Themes.',+});++interface TokenRowProps {+ variableName: string;+ label: string;+ kind: ThemeVariableKind;+ currentValue: string;+ defaultValue: string;+ onChange: (value: string | null) => void;+}++function useDraft(value: string): [string, (next: string) => void] {+ const [draft, setDraft] = useState(value);+ useEffect(() => {+ setDraft(value);+ }, [value]);+ return [draft, setDraft];+}++function commitOnEnter(commit: () => void) {+ return (event: React.KeyboardEvent<HTMLInputElement>) => {+ if (event.key !== 'Enter') return;+ event.preventDefault();+ commit();+ event.currentTarget.blur();+ };+}++const ColorControl: React.FC<TokenRowProps> = ({label, currentValue, defaultValue, onChange}) => {+ const {i18n} = useLingui();+ const [open, setOpen] = useState(false);+ const colorValue = currentValue || defaultValue;+ const swatchCss = stripCssColorPriority(colorValue) || 'transparent';+ const [draft, setDraft] = useDraft(cssColorStringToHex(colorValue) ?? colorValue);+ const commit = useCallback(() => {+ const trimmed = draft.trim();+ if (trimmed.length === 0) {+ onChange(null);+ return;+ }+ const nextHex = cssColorStringToHex(trimmed);+ if (nextHex === null) {+ setDraft(cssColorStringToHex(colorValue) ?? colorValue);+ return;+ }+ const currentHex = cssColorStringToHex(colorValue);+ if (currentHex !== null && nextHex.toLowerCase() === currentHex.toLowerCase()) {+ setDraft(nextHex);+ return;+ }+ onChange(nextHex.toLowerCase());+ }, [colorValue, draft, onChange, setDraft]);+ return (+ <FocusRing within offset={-2} data-flx="theme-settings.token-row.color-control.focus-ring">+ <div+ className={clsx(styles.field, surfaceStyles.surface)}+ data-flx="theme-settings.token-row.color-control.field"+ >+ <input+ type="text"+ className={clsx(styles.input, styles.colorInput)}+ value={draft}+ placeholder={cssColorStringToHex(defaultValue) ?? defaultValue}+ spellCheck={false}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commit}+ onKeyDown={commitOnEnter(commit)}+ aria-label={i18n._(HEX_VALUE_FOR_DESCRIPTOR, {tokenLabel: label})}+ data-flx="theme-settings.token-row.color-control.input.set-draft.text"+ />+ <div className={styles.divider} data-flx="theme-settings.token-row.color-control.divider" />+ <DialogTrigger+ isOpen={open}+ onOpenChange={setOpen}+ data-flx="theme-settings.token-row.color-control.dialog-trigger"+ >+ <AriaButton+ className={styles.swatch}+ style={{backgroundColor: swatchCss}}+ aria-label={i18n._(EDIT_COLOR_FOR_DESCRIPTOR, {tokenLabel: label})}+ data-flx="theme-settings.token-row.color-control.swatch"+ />+ <Popover+ placement="bottom end"+ offset={8}+ className={styles.popover}+ data-flx="theme-settings.token-row.color-control.popover"+ >+ <Dialog+ aria-label={i18n._(COLOR_PICKER_FOR_DESCRIPTOR, {tokenLabel: label})}+ data-flx="theme-settings.token-row.color-control.dialog"+ >+ <ColorPickerPopover+ color={cssColorStringToHex(colorValue) ?? '#000000'}+ onChange={(hex) => onChange(hex.toLowerCase())}+ onReset={() => {+ onChange(null);+ setOpen(false);+ }}+ data-flx="theme-settings.token-row.color-control.color-picker-popover.change"+ />+ </Dialog>+ </Popover>+ </DialogTrigger>+ </div>+ </FocusRing>+ );+};++const TextControl: React.FC<TokenRowProps> = ({kind, label, currentValue, defaultValue, onChange}) => {+ const {i18n} = useLingui();+ const [draft, setDraft] = useDraft(currentValue);+ const commit = useCallback(() => {+ const trimmed = draft.trim();+ if (trimmed === currentValue) return;+ onChange(trimmed.length === 0 ? null : trimmed);+ }, [currentValue, draft, onChange]);+ const isFont = kind === 'font';+ return (+ <FocusRing within offset={-2} data-flx="theme-settings.token-row.text-control.focus-ring">+ <div+ className={clsx(styles.field, styles.textField, surfaceStyles.surface)}+ data-flx="theme-settings.token-row.text-control.field"+ >+ {isFont ? (+ <span+ className={styles.fontPreview}+ style={{fontFamily: currentValue || defaultValue || 'inherit'}}+ aria-hidden+ data-flx="theme-settings.token-row.text-control.font-preview"+ >+ Aa+ </span>+ ) : null}+ <input+ type="text"+ className={styles.input}+ value={draft}+ placeholder={defaultValue}+ spellCheck={false}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commit}+ onKeyDown={commitOnEnter(commit)}+ aria-label={i18n._(VALUE_FOR_DESCRIPTOR, {tokenLabel: label})}+ data-flx="theme-settings.token-row.text-control.input.set-draft.text"+ />+ </div>+ </FocusRing>+ );+};++export const TokenRow: React.FC<TokenRowProps> = (props) => {+ const {i18n} = useLingui();+ const {variableName, label, kind, currentValue, onChange} = props;+ const overridden = currentValue.length > 0;+ return (+ <div className={styles.row} data-flx="theme-settings.token-row.row">+ <div className={styles.text} data-flx="theme-settings.token-row.text">+ <span className={styles.label} data-flx="theme-settings.token-row.label">+ {label}+ </span>+ <span className={styles.variableName} data-flx="theme-settings.token-row.variable-name">+ {variableName}+ </span>+ </div>+ <div className={styles.controls} data-flx="theme-settings.token-row.controls">+ {kind === 'color' ? (+ <ColorControl data-flx="theme-settings.token-row.color-control" {...props} />+ ) : (+ <TextControl data-flx="theme-settings.token-row.text-control" {...props} />+ )}+ {overridden ? (+ <FocusRing offset={-2} data-flx="theme-settings.token-row.focus-ring">+ <button+ type="button"+ className={styles.resetButton}+ aria-label={i18n._(RESET_TO_DEFAULT_DESCRIPTOR, {tokenLabel: label})}+ onClick={() => onChange(null)}+ data-flx="theme-settings.token-row.reset-button.change"+ >+ <ArrowCounterClockwiseIcon+ size={remFromPx(16)}+ weight="bold"+ data-flx="theme-settings.token-row.arrow-counter-clockwise-icon"+ />+ </button>+ </FocusRing>+ ) : (+ <span className={styles.resetSpacer} data-flx="theme-settings.token-row.reset-spacer" />+ )}+ </div>+ </div>+ );+};