A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): split setup branding into name and branding steps
Hampuscfec484de7ce
diff --git a/fluxer_app/src/features/app/components/setup/SetupBrandingAssetField.tsx b/fluxer_app/src/features/app/components/setup/SetupBrandingAssetField.tsxnew file mode 100644index 000000000..9d3b58551--- /dev/null+++ b/fluxer_app/src/features/app/components/setup/SetupBrandingAssetField.tsx@@ -0,0 +1,607 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {type BrandingAssetState, brandingAssetPolicyKind} from '@app/features/app/components/setup/SetupBrandingDraft';+import styles from '@app/features/app/components/setup/SetupBrandingStep.module.css';+import type {SetupBrandingAssetKind} from '@app/features/app/components/setup/SetupWizardClient';+import {formatFileSize} from '@app/features/messaging/utils/FileUtils';+import {contrastRatio} from '@app/features/theme/utils/InstanceBrandColors';+import {Button} from '@app/features/ui/button/Button';+import {formatAssetUploadExtensions, getPolicy} from '@fluxer/constants/src/AssetFormatPolicy';+import type {MessageDescriptor} from '@lingui/core';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {+ ArrowsClockwiseIcon,+ CaretDownIcon,+ ImageIcon,+ TrashIcon,+ UploadSimpleIcon,+ WarningCircleIcon,+} from '@phosphor-icons/react';+import {clsx} from 'clsx';+import {observer} from 'mobx-react-lite';+import type React from 'react';+import {useEffect, useRef, useState} from 'react';++const CHOOSE_IMAGE_DESCRIPTOR = msg({+ message: 'Choose an image or drop one here',+ comment: 'Text on the empty drop area of a branding image field in the setup wizard.',+});+const CHOOSE_ASSET_DESCRIPTOR = msg({+ message: 'Choose',+ comment: 'Button that opens the file picker for an empty branding image field in the setup wizard.',+});+const READING_IMAGE_DESCRIPTOR = msg({+ message: 'Loading image',+ comment: 'Status shown while a chosen branding image is being loaded in the setup wizard.',+});+const REPLACE_ASSET_DESCRIPTOR = msg({+ message: 'Replace',+ comment: 'Button that replaces an already uploaded branding image.',+});+const REMOVE_ASSET_DESCRIPTOR = msg({+ message: 'Remove',+ comment: 'Button that removes a branding image in the setup wizard.',+});+const ASSET_SIZE_DESCRIPTOR = msg({+ message: '{width} by {height} pixels',+ comment: 'Size of the chosen branding image in the setup wizard. Width and height are numbers.',+});+const ASSET_SMALL_DESCRIPTOR = msg({+ message: 'This image is smaller than recommended and may look blurry.',+ comment: 'Warning when a branding image is smaller than the recommended size in the setup wizard.',+});+const WORDMARK_LOW_ON_LIGHT_DESCRIPTOR = msg({+ message: 'This wordmark is hard to see on the light title bar.',+ comment:+ 'Warning in the setup wizard when the uploaded wordmark is too light to read on the light desktop app title bar.',+});+const WORDMARK_LOW_ON_DARK_DESCRIPTOR = msg({+ message: 'This wordmark is hard to see on the dark title bar.',+ comment:+ 'Warning in the setup wizard when the uploaded wordmark is too dark to read on the dark desktop app title bar.',+});+const ERROR_TOO_LARGE_DESCRIPTOR = msg({+ message: 'This file is larger than {size}. Choose a smaller one.',+ comment: 'Error when a branding image file is too large in the setup wizard. size is a file size such as 4 MB.',+});+const ERROR_UNSUPPORTED_DESCRIPTOR = msg({+ message: 'This file type is not supported. Supported types are {formats}.',+ comment:+ 'Error when a branding image has an unsupported file type in the setup wizard. formats is a list such as PNG, JPEG, WebP.',+});+const ERROR_UNREADABLE_DESCRIPTOR = msg({+ message: 'That image could not be used. Try a different file.',+ comment: 'Error shown when a chosen branding image cannot be loaded in the setup wizard.',+});+const ERROR_NOT_SAVED_DESCRIPTOR = msg({+ message: 'This image was not saved. Press "Continue" to try again.',+ comment:+ 'Error on a branding image field in the setup wizard when saving the image failed. "Continue" is the label of the button that saves the step.',+});+const MORE_ABOUT_IMAGE_DESCRIPTOR = msg({+ message: 'More about this image',+ comment:+ 'Button on a branding image field in the setup wizard on narrow screens that shows where the image appears and what shows when it is empty.',+});++interface AssetCopy {+ label: MessageDescriptor;+ hint: MessageDescriptor;+ help: MessageDescriptor;+ empty: MessageDescriptor;+ minWidth: number;+ minHeight: number;+}++export const ASSET_COPY: Record<SetupBrandingAssetKind, AssetCopy> = {+ logo: {+ label: msg({message: 'Logo', comment: 'Label for the logo branding image in the setup wizard.'}),+ hint: msg({+ message: 'Square or wide, in light colors on a transparent background. At least 256 pixels tall.',+ comment: 'Short hint under the logo field in the setup wizard branding step.',+ }),+ help: msg({+ message:+ 'The large image next to the sign-in form, which is always dark. On a phone it only shows next to the name, when there is no wordmark and the product name is not Fluxer. Use a square or wide PNG or SVG in light colors with a transparent background, at least 256 pixels tall and up to {size}.',+ comment:+ 'Where the logo branding image appears and the recommended format, in the setup wizard. size is a file size such as 10 MB.',+ }),+ empty: msg({+ message:+ 'If you leave it empty, the sign-in page uses your app icon or symbol. Without those, it shows the Fluxer logo while the product name is Fluxer, and no image for any other name.',+ comment: 'What the app shows when no logo is set, in the setup wizard.',+ }),+ minWidth: 0,+ minHeight: 256,+ },+ wordmark: {+ label: msg({message: 'Wordmark', comment: 'Label for the wordmark branding image in the setup wizard.'}),+ hint: msg({+ message: 'Your name in your own lettering, on a transparent background. At least 64 pixels tall.',+ comment: 'Short hint under the wordmark field in the setup wizard branding step.',+ }),+ help: msg({+ message:+ 'Your name in your own lettering. It shows under the logo on the sign-in page, at the top of the sign-in page on phones and in the desktop app title bar. Use a wide PNG or SVG with a transparent background, at least 64 pixels tall and up to {size}, in a color that works on both light and dark title bars.',+ comment:+ 'Where the wordmark branding image appears and the recommended format, in the setup wizard. size is a file size such as 10 MB.',+ }),+ empty: msg({+ message:+ 'If you leave it empty, the product name shows as plain text, or as the Fluxer wordmark while the product name is Fluxer.',+ comment: 'What the app shows when no wordmark is set, in the setup wizard.',+ }),+ minWidth: 0,+ minHeight: 64,+ },+ sign_in_backdrop: {+ label: msg({+ message: 'Sign-in background',+ comment: 'Label for the sign-in page background image in the setup wizard.',+ }),+ hint: msg({+ message: 'A landscape image, at least 1920 by 1080 pixels.',+ comment: 'Short hint under the sign-in background field in the setup wizard branding step.',+ }),+ help: msg({+ message:+ 'Fills the sign-in page behind the form, darkened so the form stays easy to read. Use a landscape JPEG, PNG, WebP or AVIF, at least 1920 by 1080 pixels and up to {size}.',+ comment:+ 'Where the sign-in background image appears and the recommended format, in the setup wizard. size is a file size such as 4 MB.',+ }),+ empty: msg({+ message: 'If you leave it empty, the sign-in page has the dark starry background.',+ comment: 'What the app shows when no sign-in background is set, in the setup wizard.',+ }),+ minWidth: 1920,+ minHeight: 1080,+ },+ icon: {+ label: msg({message: 'App icon', comment: 'Label for the icon branding image in the setup wizard.'}),+ hint: msg({+ message: 'Square, at least 512 by 512 pixels.',+ comment: 'Short hint under the app icon field in the setup wizard branding step.',+ }),+ help: msg({+ message:+ 'Shows when someone adds the web app to their home screen and next to the join date on profiles. It also fills in for the logo, symbol and favicon when those are empty. Use a square PNG, at least 512 by 512 pixels and up to {size}.',+ comment:+ 'Where the app icon branding image appears and the recommended format, in the setup wizard. size is a file size such as 10 MB.',+ }),+ empty: msg({+ message: 'If you leave it empty, those places show the Fluxer icon.',+ comment: 'What the app shows when no app icon is set, in the setup wizard.',+ }),+ minWidth: 512,+ minHeight: 512,+ },+ symbol: {+ label: msg({message: 'Symbol', comment: 'Label for the symbol branding image in the setup wizard.'}),+ hint: msg({+ message: 'Square on a transparent background, still clear at 16 pixels.',+ comment: 'Short hint under the symbol field in the setup wizard branding step.',+ }),+ help: msg({+ message:+ "A small mark next to your instance's name in the account switcher and the instance list. Use a square PNG or SVG with a transparent background that is still clear at 16 pixels, up to {size}.",+ comment:+ 'Where the symbol branding image appears and the recommended format, in the setup wizard. size is a file size such as 10 MB.',+ }),+ empty: msg({+ message: 'If you leave it empty, the lists use your app icon or logo, and a globe if both are empty.',+ comment: 'What the app shows when no symbol is set, in the setup wizard.',+ }),+ minWidth: 64,+ minHeight: 64,+ },+ favicon: {+ label: msg({message: 'Favicon', comment: 'Label for the favicon branding image in the setup wizard.'}),+ hint: msg({+ message: 'Square, at least 64 by 64 pixels.',+ comment: 'Short hint under the favicon field in the setup wizard branding step.',+ }),+ help: msg({+ message: 'The small image in the browser tab. Use a square PNG, at least 64 by 64 pixels and up to {size}.',+ comment:+ 'Where the favicon appears and the recommended format, in the setup wizard. size is a file size such as 10 MB.',+ }),+ empty: msg({+ message: 'If you leave it empty, the tab uses your app icon, or the Fluxer icon if that is empty too.',+ comment: 'What the app shows when no favicon is set, in the setup wizard.',+ }),+ minWidth: 64,+ minHeight: 64,+ },+ favicon_dark: {+ label: msg({+ message: 'Dark mode favicon',+ comment: 'Label for the favicon that browsers show while they use a dark theme, in the setup wizard.',+ }),+ hint: msg({+ message: 'Square, at least 64 by 64 pixels, for dark browser tabs.',+ comment: 'Short hint under the dark mode favicon field in the setup wizard branding step.',+ }),+ help: msg({+ message:+ 'Browsers set to a dark theme show this instead of the favicon. Add one when your favicon is too dark to see on a dark tab. Use a square PNG, at least 64 by 64 pixels and up to {size}.',+ comment:+ 'Where the dark mode favicon appears and the recommended format, in the setup wizard. size is a file size such as 10 MB.',+ }),+ empty: msg({+ message: 'If you leave it empty, the tab shows the same favicon in light and dark themes.',+ comment: 'What the app shows when no dark mode favicon is set, in the setup wizard.',+ }),+ minWidth: 64,+ minHeight: 64,+ },+};++const LIGHT_TITLEBAR = [0xe3, 0xe5, 0xe8] as const;+const DARK_TITLEBAR = [0x12, 0x12, 0x14] as const;+const LOW_CONTRAST = 1.6;+const LOW_CONTRAST_SHARE = 0.85;++interface WordmarkReadability {+ light: boolean;+ dark: boolean;+}++function measureWordmarkReadability(image: HTMLImageElement): WordmarkReadability | null {+ const scale = Math.min(1, 256 / Math.max(image.naturalWidth, 1));+ const width = Math.max(1, Math.round(image.naturalWidth * scale));+ const height = Math.max(1, Math.round(image.naturalHeight * scale));+ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ const context = canvas.getContext('2d', {willReadFrequently: true});+ if (!context) return null;+ let pixels: Uint8ClampedArray;+ try {+ context.drawImage(image, 0, 0, width, height);+ pixels = context.getImageData(0, 0, width, height).data;+ } catch {+ return null;+ }+ let opaque = 0;+ let lowOnLight = 0;+ let lowOnDark = 0;+ for (let index = 0; index < pixels.length; index += 4) {+ if (pixels[index + 3] < 128) continue;+ const rgb = [pixels[index], pixels[index + 1], pixels[index + 2]] as const;+ opaque += 1;+ if (contrastRatio(rgb, LIGHT_TITLEBAR) < LOW_CONTRAST) lowOnLight += 1;+ if (contrastRatio(rgb, DARK_TITLEBAR) < LOW_CONTRAST) lowOnDark += 1;+ }+ if (opaque === 0) return null;+ return {light: lowOnLight / opaque >= LOW_CONTRAST_SHARE, dark: lowOnDark / opaque >= LOW_CONTRAST_SHARE};+}++function hasFiles(event: React.DragEvent<HTMLElement>): boolean {+ return Array.from(event.dataTransfer.types).includes('Files');+}++export interface TargetHandlers {+ onFocusCapture: () => void;+ onBlurCapture: (event: React.FocusEvent<HTMLElement>) => void;+ onPointerEnter: () => void;+ onPointerLeave: () => void;+}++interface BrandingAssetFieldProps {+ asset: BrandingAssetState;+ labelledBy: string | null;+ disabled: boolean;+ onUpload: (kind: SetupBrandingAssetKind, file?: File) => void;+ onClear: (kind: SetupBrandingAssetKind) => void;+ onImageError: (kind: SetupBrandingAssetKind) => void;+ targetHandlers: TargetHandlers;+}++export const BrandingAssetField = observer(+ ({asset, labelledBy, disabled, onUpload, onClear, onImageError, targetHandlers}: BrandingAssetFieldProps) => {+ const {i18n} = useLingui();+ const copy = ASSET_COPY[asset.kind];+ const policy = getPolicy(brandingAssetPolicyKind(asset.kind));+ const size = formatFileSize(i18n.locale, policy.maxBytes);+ const source = asset.preview ?? asset.url;+ const [dimensions, setDimensions] = useState<{source: string; width: number; height: number} | null>(null);+ const [readability, setReadability] = useState<{source: string; result: WordmarkReadability} | null>(null);+ const [dragging, setDragging] = useState(false);+ const dragDepth = useRef(0);+ const rowRef = useRef<HTMLDivElement>(null);+ const previousSource = useRef(source);+ const shownDimensions = dimensions != null && dimensions.source === source ? dimensions : null;+ const shownReadability = readability != null && readability.source === source ? readability.result : null;+ const isVector = source?.startsWith('data:image/svg') ?? false;+ const tooSmall =+ shownDimensions != null &&+ !isVector &&+ (shownDimensions.width < copy.minWidth || shownDimensions.height < copy.minHeight);+ const labelId = labelledBy ?? `setup-branding-${asset.kind}-label`;+ const hintId = `setup-branding-${asset.kind}-hint`;+ const statusId = `setup-branding-${asset.kind}-status`;+ const helpId = `setup-branding-${asset.kind}-help`;+ const [helpOpen, setHelpOpen] = useState(false);+ const busy = disabled || asset.reading;+ let errorText: string | null = null;+ switch (asset.error) {+ case 'too_large':+ errorText = i18n._(ERROR_TOO_LARGE_DESCRIPTOR, {size});+ break;+ case 'unsupported':+ errorText = i18n._(ERROR_UNSUPPORTED_DESCRIPTOR, {+ formats: formatAssetUploadExtensions(brandingAssetPolicyKind(asset.kind)),+ });+ break;+ case 'unreadable':+ errorText = i18n._(ERROR_UNREADABLE_DESCRIPTOR);+ break;+ case 'not_saved':+ errorText = i18n._(ERROR_NOT_SAVED_DESCRIPTOR);+ break;+ }+ const warnings: Array<string> = [];+ if (tooSmall) warnings.push(i18n._(ASSET_SMALL_DESCRIPTOR));+ if (shownReadability?.light) warnings.push(i18n._(WORDMARK_LOW_ON_LIGHT_DESCRIPTOR));+ if (shownReadability?.dark) warnings.push(i18n._(WORDMARK_LOW_ON_DARK_DESCRIPTOR));+ useEffect(() => {+ const was = previousSource.current;+ previousSource.current = source;+ if ((was == null) === (source == null)) return;+ const active = document.activeElement;+ const focusLost = active == null || active === document.body || rowRef.current?.contains(active) === true;+ if (!focusLost) return;+ rowRef.current+ ?.querySelector<HTMLButtonElement>(+ source != null+ ? '[data-flx="app.self-hosted-setup-wizard-gate.asset-replace-button"]'+ : '[data-flx="app.self-hosted-setup-wizard-gate.asset-upload-button"]',+ )+ ?.focus();+ }, [source]);+ const resetDrag = () => {+ dragDepth.current = 0;+ setDragging(false);+ };+ const handleDragEnter = (event: React.DragEvent<HTMLElement>) => {+ if (busy || !hasFiles(event)) return;+ event.preventDefault();+ dragDepth.current += 1;+ setDragging(true);+ };+ const handleDragOver = (event: React.DragEvent<HTMLElement>) => {+ if (busy || !hasFiles(event)) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ };+ const handleDragLeave = () => {+ dragDepth.current = Math.max(0, dragDepth.current - 1);+ if (dragDepth.current === 0) setDragging(false);+ };+ const handleDrop = (event: React.DragEvent<HTMLElement>) => {+ event.preventDefault();+ resetDrag();+ if (busy) return;+ const file = event.dataTransfer.files[0];+ if (file) onUpload(asset.kind, file);+ };+ const describedBy = clsx(hintId, helpId, (errorText || warnings.length > 0) && statusId);+ return (+ <div+ ref={rowRef}+ className={clsx(+ styles.assetRow,+ source == null && styles.assetRowEmpty,+ dragging && styles.assetRowDragging,+ asset.error && styles.assetRowError,+ )}+ role="group"+ aria-labelledby={labelId}+ onDragEnter={handleDragEnter}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ data-branding-kind={asset.kind}+ data-branding-error={asset.error ?? undefined}+ data-flx="app.setup.setup-branding-step.branding-asset-field.asset-row"+ {...targetHandlers}+ >+ <div+ className={clsx(+ styles.thumbnail,+ asset.kind === 'sign_in_backdrop' && styles.thumbnailCover,+ source == null && styles.thumbnailEmpty,+ )}+ data-flx="app.setup.setup-branding-step.branding-asset-field.thumbnail"+ >+ {source != null ? (+ <img+ src={source}+ alt=""+ draggable={false}+ onLoad={(event) => {+ const image = event.currentTarget;+ setDimensions({source, width: image.naturalWidth, height: image.naturalHeight});+ if (asset.kind === 'wordmark') {+ const result = measureWordmarkReadability(image);+ setReadability(result ? {source, result} : null);+ }+ }}+ onError={() => onImageError(asset.kind)}+ data-flx="app.setup.setup-branding-step.branding-asset-field.img"+ />+ ) : (+ <ImageIcon+ size={20}+ weight="bold"+ aria-hidden="true"+ data-flx="app.setup.setup-branding-step.branding-asset-field.image-icon"+ />+ )}+ </div>+ <div className={styles.assetBody} data-flx="app.setup.setup-branding-step.branding-asset-field.asset-body">+ {labelledBy == null && (+ <h3+ id={labelId}+ className={styles.assetLabel}+ data-flx="app.setup.setup-branding-step.branding-asset-field.asset-label"+ >+ {i18n._(copy.label)}+ </h3>+ )}+ <p+ id={hintId}+ className={styles.assetHint}+ data-flx="app.setup.setup-branding-step.branding-asset-field.asset-hint"+ >+ {i18n._(copy.hint)}+ </p>+ <div className={styles.helpToggle} data-flx="app.setup.setup-branding-step.branding-asset-field.help-toggle">+ <Button+ variant="ghost"+ small+ compact+ aria-expanded={helpOpen}+ aria-controls={helpId}+ rightIcon={+ <CaretDownIcon+ size={12}+ weight="bold"+ aria-hidden="true"+ className={styles.helpToggleIcon}+ data-flx="app.setup.setup-branding-step.branding-asset-field.help-toggle-icon"+ />+ }+ onClick={() => setHelpOpen((open) => !open)}+ data-flx="app.setup.setup-branding-step.branding-asset-field.help-toggle-button"+ >+ {i18n._(MORE_ABOUT_IMAGE_DESCRIPTOR)}+ </Button>+ </div>+ <div+ id={helpId}+ className={clsx(styles.help, helpOpen && styles.helpOpen)}+ data-flx="app.setup.setup-branding-step.branding-asset-field.help"+ >+ <p data-flx="app.setup.setup-branding-step.branding-asset-field.help-where">{i18n._(copy.help, {size})}</p>+ {source == null && (+ <p data-flx="app.setup.setup-branding-step.branding-asset-field.help-empty">{i18n._(copy.empty)}</p>+ )}+ </div>+ {source == null && !errorText && (+ <p className={styles.assetMeta} data-flx="app.setup.setup-branding-step.branding-asset-field.asset-empty">+ {i18n._(asset.reading ? READING_IMAGE_DESCRIPTOR : CHOOSE_IMAGE_DESCRIPTOR)}+ </p>+ )}+ {shownDimensions != null && !isVector && (+ <p className={styles.assetMeta} data-flx="app.setup.setup-branding-step.branding-asset-field.asset-size">+ {i18n._(ASSET_SIZE_DESCRIPTOR, {width: shownDimensions.width, height: shownDimensions.height})}+ </p>+ )}+ {(errorText || warnings.length > 0) && (+ <div+ id={statusId}+ className={styles.assetStatus}+ data-flx="app.setup.setup-branding-step.branding-asset-field.asset-status"+ >+ {errorText && (+ <p+ className={styles.assetError}+ role="alert"+ data-flx="app.setup.setup-branding-step.branding-asset-field.asset-error"+ >+ <WarningCircleIcon+ size={16}+ weight="bold"+ aria-hidden="true"+ data-flx="app.setup.setup-branding-step.branding-asset-field.warning-circle-icon"+ />+ {errorText}+ </p>+ )}+ {warnings.map((warning) => (+ <p+ key={warning}+ className={styles.assetWarning}+ data-flx="app.setup.setup-branding-step.branding-asset-field.asset-warning"+ >+ <WarningCircleIcon+ size={16}+ weight="bold"+ aria-hidden="true"+ data-flx="app.setup.setup-branding-step.branding-asset-field.warning-circle-icon--2"+ />+ {warning}+ </p>+ ))}+ </div>+ )}+ <div+ className={styles.assetActions}+ data-flx="app.setup.setup-branding-step.branding-asset-field.asset-actions"+ >+ {source == null ? (+ <Button+ variant="secondary"+ small+ disabled={busy}+ submitting={asset.reading}+ leftIcon={+ <UploadSimpleIcon+ size={16}+ weight="bold"+ data-flx="app.setup.setup-branding-step.branding-asset-field.upload-simple-icon"+ />+ }+ onClick={() => onUpload(asset.kind)}+ aria-describedby={describedBy}+ data-flx="app.self-hosted-setup-wizard-gate.asset-upload-button"+ >+ {i18n._(CHOOSE_ASSET_DESCRIPTOR)}+ </Button>+ ) : (+ <>+ <Button+ variant="secondary"+ small+ disabled={busy}+ submitting={asset.reading}+ leftIcon={+ <ArrowsClockwiseIcon+ size={16}+ weight="bold"+ data-flx="app.setup.setup-branding-step.branding-asset-field.arrows-clockwise-icon"+ />+ }+ onClick={() => onUpload(asset.kind)}+ aria-describedby={describedBy}+ data-flx="app.self-hosted-setup-wizard-gate.asset-replace-button"+ >+ {i18n._(REPLACE_ASSET_DESCRIPTOR)}+ </Button>+ <Button+ variant="secondary"+ small+ disabled={busy}+ leftIcon={+ <TrashIcon+ size={16}+ weight="bold"+ data-flx="app.setup.setup-branding-step.branding-asset-field.trash-icon"+ />+ }+ onClick={() => onClear(asset.kind)}+ aria-describedby={labelId}+ data-flx="app.self-hosted-setup-wizard-gate.asset-clear-button"+ >+ {i18n._(REMOVE_ASSET_DESCRIPTOR)}+ </Button>+ </>+ )}+ </div>+ </div>+ </div>+ );+ },+);diff --git a/fluxer_app/src/features/app/components/setup/SetupBrandingDraft.tsx b/fluxer_app/src/features/app/components/setup/SetupBrandingDraft.tsxnew file mode 100644index 000000000..ffdab9a8c--- /dev/null+++ b/fluxer_app/src/features/app/components/setup/SetupBrandingDraft.tsx@@ -0,0 +1,119 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {SetupBrandingAssetKind} from '@app/features/app/components/setup/SetupWizardClient';+import {type AssetKind, getPolicy, isExtensionAllowed} from '@fluxer/constants/src/AssetFormatPolicy';+import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';+import {createContext, type ReactNode, useCallback, useContext, useMemo, useState} from 'react';++const BRANDING_ASSET_KINDS: ReadonlyArray<SetupBrandingAssetKind> = [+ 'logo',+ 'wordmark',+ 'sign_in_backdrop',+ 'icon',+ 'symbol',+ 'favicon',+ 'favicon_dark',+];++export type BrandingAssetError = 'too_large' | 'unsupported' | 'unreadable' | 'not_saved';++export interface BrandingAssetState {+ kind: SetupBrandingAssetKind;+ url: string | null;+ preview: string | null;+ reading: boolean;+ error: BrandingAssetError | null;+}++export function brandingAssetPolicyKind(kind: SetupBrandingAssetKind): AssetKind {+ return kind === 'sign_in_backdrop' ? 'sign_in_backdrop' : 'guild_icon';+}++export function validateBrandingFile(kind: SetupBrandingAssetKind, file: File): BrandingAssetError | null {+ const policyKind = brandingAssetPolicyKind(kind);+ const policy = getPolicy(policyKind);+ const extension = file.name.includes('.') ? (file.name.split('.').pop() ?? '') : '';+ if (!Object.values(policy.mimes).includes(file.type) && !isExtensionAllowed(policyKind, extension)) {+ return 'unsupported';+ }+ if (file.size > policy.maxBytes) {+ return 'too_large';+ }+ return null;+}++function hexToNumber(value: string | null): number | null {+ if (!value) return null;+ const match = /^#?([0-9a-fA-F]{6})$/.exec(value.trim());+ return match ? parseInt(match[1], 16) >>> 0 : null;+}++export function brandingAssetUrl(config: InstanceConfigResponse, kind: SetupBrandingAssetKind): string | null {+ const branding = config.app_public.branding;+ switch (kind) {+ case 'icon':+ return branding.icon_url;+ case 'symbol':+ return branding.symbol_url;+ case 'logo':+ return branding.logo_url;+ case 'wordmark':+ return branding.wordmark_url;+ case 'favicon':+ return branding.favicon_url;+ case 'favicon_dark':+ return branding.favicon_dark_url;+ case 'sign_in_backdrop':+ return branding.sign_in_backdrop_url;+ }+}++function assetsFromConfig(config: InstanceConfigResponse): ReadonlyArray<BrandingAssetState> {+ return BRANDING_ASSET_KINDS.map((kind) => ({+ kind,+ url: brandingAssetUrl(config, kind),+ preview: null,+ reading: false,+ error: null,+ }));+}++interface BrandingDraftState {+ productName: string;+ setProductName: (name: string) => void;+ themeColor: number | null;+ setThemeColor: (color: number | null) => void;+ assets: ReadonlyArray<BrandingAssetState>;+ updateAsset: (kind: SetupBrandingAssetKind, patch: Partial<BrandingAssetState>) => void;+ hydrate: (config: InstanceConfigResponse) => void;+}++const BrandingDraftContext = createContext<BrandingDraftState | null>(null);++export function SetupBrandingDraftProvider({children}: {children: ReactNode}) {+ const [productName, setProductName] = useState('');+ const [themeColor, setThemeColor] = useState<number | null>(null);+ const [assets, setAssets] = useState<ReadonlyArray<BrandingAssetState>>(() =>+ BRANDING_ASSET_KINDS.map((kind) => ({kind, url: null, preview: null, reading: false, error: null})),+ );+ const updateAsset = useCallback((kind: SetupBrandingAssetKind, patch: Partial<BrandingAssetState>) => {+ setAssets((current) => current.map((asset) => (asset.kind === kind ? {...asset, ...patch} : asset)));+ }, []);++ const hydrate = useCallback((next: InstanceConfigResponse) => {+ setProductName(next.app_public.branding.product_name);+ setThemeColor(hexToNumber(next.app_public.branding.theme_color));+ setAssets(assetsFromConfig(next));+ }, []);+ const value = useMemo(+ () => ({productName, setProductName, themeColor, setThemeColor, assets, updateAsset, hydrate}),+ [productName, themeColor, assets, updateAsset, hydrate],+ );+ return <BrandingDraftContext.Provider value={value}>{children}</BrandingDraftContext.Provider>;+}++export function useSetupBrandingDraft(): BrandingDraftState {+ const draft = useContext(BrandingDraftContext);+ if (draft === null) throw new Error('Setup branding draft provider is missing');+ return draft;+}diff --git a/fluxer_app/src/features/app/components/setup/SetupBrandingFields.tsx b/fluxer_app/src/features/app/components/setup/SetupBrandingFields.tsxnew file mode 100644index 000000000..40ec6ff08--- /dev/null+++ b/fluxer_app/src/features/app/components/setup/SetupBrandingFields.tsx@@ -0,0 +1,570 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ ASSET_COPY,+ BrandingAssetField,+ type TargetHandlers,+} from '@app/features/app/components/setup/SetupBrandingAssetField';+import {type BrandingAssetState, brandingAssetPolicyKind} from '@app/features/app/components/setup/SetupBrandingDraft';+import {+ type BrandingPreviewTab,+ type BrandingPreviewTarget,+ brandingPreviewTabsFor,+ SetupBrandingPreview,+} from '@app/features/app/components/setup/SetupBrandingPreview';+import styles from '@app/features/app/components/setup/SetupBrandingStep.module.css';+import type {SetupBrandingAssetKind} from '@app/features/app/components/setup/SetupWizardClient';+import {useMergeRefs} from '@app/features/app/hooks/useMergeRefs';+import {getLocaleDirection} from '@app/features/i18n/utils/LocaleDirection';+import {formatFileSize} from '@app/features/messaging/utils/FileUtils';+import {int2hex} from '@app/features/theme/utils/ColorUtils';+import {contrastRatio, resolveThemeSurface} from '@app/features/theme/utils/InstanceBrandColors';+import {Button} from '@app/features/ui/button/Button';+import {ColorPickerField} from '@app/features/ui/components/form/ColorPickerField';+import {Scroller} from '@app/features/ui/components/Scroller';+import FocusRing from '@app/features/ui/focus_ring/FocusRing';+import {getNextTabIndex, getTabNavigationDirection} from '@app/features/ui/tabs/TabKeyboardNavigation';+import {getPolicy} from '@fluxer/constants/src/AssetFormatPolicy';+import {ThemeTypes} from '@fluxer/constants/src/UserConstants';+import type {MessageDescriptor} from '@lingui/core';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {CheckIcon, InfoIcon, WarningCircleIcon} from '@phosphor-icons/react';+import {clsx} from 'clsx';+import {observer} from 'mobx-react-lite';+import type React from 'react';+import {useCallback, useEffect, useMemo, useRef, useState} from 'react';++export const DEFAULT_THEME_COLOR = 0x4641d9;++const THEME_COLOR_PRESETS: ReadonlyArray<{value: number; name: MessageDescriptor}> = [+ {+ value: DEFAULT_THEME_COLOR,+ name: msg({+ message: 'Indigo',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0x7c3aed,+ name: msg({+ message: 'Violet',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0xc026d3,+ name: msg({+ message: 'Fuchsia',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0xe11d48,+ name: msg({+ message: 'Rose',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0xea580c,+ name: msg({+ message: 'Orange',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0xca8a04,+ name: msg({+ message: 'Amber',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0x16a34a,+ name: msg({+ message: 'Green',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0x0d9488,+ name: msg({+ message: 'Teal',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0x0284c7,+ name: msg({+ message: 'Sky blue',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+ {+ value: 0x475569,+ name: msg({+ message: 'Slate gray',+ comment:+ 'Color name. Names a suggested theme color in the setup wizard branding step and is read out by screen readers.',+ }),+ },+];++const TITLE_DESCRIPTOR = msg({+ message: 'Make it look like yours',+ comment: 'Setup wizard title for the theme color and images.',+});+const BODY_DESCRIPTOR = msg({+ message: 'Everything here is optional.',+ comment: 'Setup wizard body for the theme color and images.',+});+const THEME_COLOR_LABEL_DESCRIPTOR = msg({+ message: 'Theme color',+ comment: 'Label for the theme color picker in the setup wizard.',+});+const THEME_COLOR_HELP_DESCRIPTOR = msg({+ message:+ "Buttons, links and highlights across the app use this color, and phone browsers use it for their toolbar. Reset it to keep Fluxer's indigo.",+ comment: 'Help text under the theme color picker in the setup wizard branding step.',+});+const THEME_COLOR_PRESETS_DESCRIPTOR = msg({+ message: 'Suggested colors',+ comment: 'Accessible label for the row of suggested theme colors in the setup wizard branding step.',+});+const RESET_COLOR_DESCRIPTOR = msg({+ message: 'Reset',+ comment: 'Button that resets the theme color to the default indigo in the setup wizard branding step.',+});+const COLOR_DARK_TEXT_DESCRIPTOR = msg({+ message: 'Buttons in this color get dark text so the text stays readable.',+ comment:+ 'Note under the theme color picker in the setup wizard when the chosen color is light enough that button text switches from white to dark.',+});+const COLOR_LOW_ON_DARK_DESCRIPTOR = msg({+ message: 'This color is close to the dark theme background, so buttons may be hard to see there.',+ comment: 'Warning under the theme color picker in the setup wizard when the chosen color is very dark.',+});+const COLOR_LOW_ON_LIGHT_DESCRIPTOR = msg({+ message: 'This color is close to the light theme background, so buttons may be hard to see there.',+ comment: 'Warning under the theme color picker in the setup wizard when the chosen color is very light.',+});+const LOGOS_HEADING_DESCRIPTOR = msg({+ message: 'Logos',+ comment: 'Heading above the logo and wordmark fields in the setup wizard branding step.',+});+const APP_ICONS_HEADING_DESCRIPTOR = msg({+ message: 'App icons',+ comment: 'Heading above the app icon, symbol and both favicon fields in the setup wizard branding step.',+});+function colorChannels(value: number): readonly [number, number, number] {+ return [(value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff];+}++function themeColorNotes(value: number): Array<{tone: 'info' | 'warning'; text: MessageDescriptor}> {+ const rgb = colorChannels(value);+ const notes: Array<{tone: 'info' | 'warning'; text: MessageDescriptor}> = [];+ if (contrastRatio(rgb, resolveThemeSurface(ThemeTypes.DARK, '--background-primary', 1)) < 1.5) {+ notes.push({tone: 'warning', text: COLOR_LOW_ON_DARK_DESCRIPTOR});+ }+ if (contrastRatio(rgb, resolveThemeSurface(ThemeTypes.LIGHT, '--background-primary', 1)) < 1.5) {+ notes.push({tone: 'warning', text: COLOR_LOW_ON_LIGHT_DESCRIPTOR});+ }+ if (contrastRatio(rgb, [20, 20, 20]) > contrastRatio(rgb, [250, 250, 250])) {+ notes.push({tone: 'info', text: COLOR_DARK_TEXT_DESCRIPTOR});+ }+ return notes;+}++interface ThemeColorSectionProps {+ themeColor: number | null;+ disabled: boolean;+ onChange: (value: number | null) => void;+ targetHandlers: TargetHandlers;+}++const ThemeColorSection = observer(({themeColor, disabled, onChange, targetHandlers}: ThemeColorSectionProps) => {+ const {i18n} = useLingui();+ const value = themeColor ?? DEFAULT_THEME_COLOR;+ const notes = useMemo(() => themeColorNotes(value), [value]);+ const presetsRef = useRef<HTMLDivElement>(null);+ const selectedIndex = THEME_COLOR_PRESETS.findIndex((preset) => preset.value === value);+ const focusIndex = selectedIndex >= 0 ? selectedIndex : 0;+ const rtl = getLocaleDirection(i18n.locale) === 'rtl';+ const selectPreset = (index: number) => {+ const preset = THEME_COLOR_PRESETS[index].value;+ onChange(preset === DEFAULT_THEME_COLOR ? null : preset);+ };+ const handlePresetKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>, index: number) => {+ let direction = getTabNavigationDirection(event.key, 'both');+ if (direction == null) return;+ if (rtl && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {+ direction = direction === 'next' ? 'previous' : 'next';+ }+ const next = getNextTabIndex(index, THEME_COLOR_PRESETS.length, direction);+ if (next == null) return;+ event.preventDefault();+ selectPreset(next);+ presetsRef.current?.querySelectorAll<HTMLButtonElement>('[role="radio"]')[next]?.focus();+ };+ return (+ <section+ className={styles.group}+ aria-labelledby="setup-branding-theme-color"+ data-flx="app.setup.setup-branding-step.theme-color-section.group"+ {...targetHandlers}+ >+ <div className={styles.groupHeader} data-flx="app.setup.setup-branding-step.theme-color-section.group-header">+ <h2+ id="setup-branding-theme-color"+ className={styles.groupHeading}+ data-flx="app.setup.setup-branding-step.theme-color-section.heading"+ >+ {i18n._(THEME_COLOR_LABEL_DESCRIPTOR)}+ </h2>+ <Button+ variant="ghost"+ small+ compact+ disabled={disabled || themeColor === null}+ className={clsx(themeColor === null && styles.resetHidden)}+ onClick={(event: React.MouseEvent<HTMLButtonElement>) => {+ onChange(null);+ event.currentTarget+ .closest('section')+ ?.querySelector<HTMLInputElement>('[data-flx="ui.form.color-picker-field.input.text"]')+ ?.focus();+ }}+ data-flx="app.setup.setup-branding-step.theme-color-section.reset-button"+ >+ {i18n._(RESET_COLOR_DESCRIPTOR)}+ </Button>+ </div>+ <div+ ref={presetsRef}+ className={styles.presets}+ role="radiogroup"+ aria-label={i18n._(THEME_COLOR_PRESETS_DESCRIPTOR)}+ data-flx="app.setup.setup-branding-step.theme-color-section.presets"+ >+ {THEME_COLOR_PRESETS.map(({value: preset, name}, index) => {+ const selected = preset === value;+ const hex = int2hex(preset).toUpperCase();+ return (+ <FocusRing key={preset} offset={2} data-flx="app.setup.setup-branding-step.theme-color-section.focus-ring">+ <button+ type="button"+ role="radio"+ className={clsx(styles.preset, selected && styles.presetSelected)}+ style={{backgroundColor: hex}}+ aria-label={i18n._(name)}+ title={hex}+ aria-checked={selected}+ tabIndex={index === focusIndex ? 0 : -1}+ disabled={disabled}+ onClick={() => selectPreset(index)}+ onKeyDown={(event) => handlePresetKeyDown(event, index)}+ data-flx="app.setup.setup-branding-step.theme-color-section.preset"+ >+ {selected && (+ <CheckIcon+ size={14}+ weight="bold"+ aria-hidden="true"+ color={contrastRatio(colorChannels(preset), [255, 255, 255]) >= 3 ? '#fff' : '#000'}+ data-flx="app.setup.setup-branding-step.theme-color-section.check-icon"+ />+ )}+ </button>+ </FocusRing>+ );+ })}+ </div>+ <ColorPickerField+ value={value}+ onChange={onChange}+ defaultValue={DEFAULT_THEME_COLOR}+ isDefaultValue={themeColor === null}+ onReset={() => onChange(null)}+ description={i18n._(THEME_COLOR_HELP_DESCRIPTOR)}+ descriptionClassName={styles.colorHelp}+ disabled={disabled}+ data-flx="app.self-hosted-setup-wizard-gate.theme-color-field"+ />+ {notes.map((note) => (+ <p+ key={note.text.id}+ className={clsx(styles.note, note.tone === 'warning' && styles.noteWarning)}+ role={note.tone === 'warning' ? 'status' : undefined}+ data-flx="app.setup.setup-branding-step.theme-color-section.note"+ >+ {note.tone === 'warning' ? (+ <WarningCircleIcon+ size={16}+ weight="bold"+ aria-hidden="true"+ data-flx="app.setup.setup-branding-step.theme-color-section.warning-circle-icon"+ />+ ) : (+ <InfoIcon+ size={16}+ weight="bold"+ aria-hidden="true"+ data-flx="app.setup.setup-branding-step.theme-color-section.info-icon"+ />+ )}+ <span data-flx="app.setup.setup-branding-step.theme-color-section.note-text">{i18n._(note.text)}</span>+ </p>+ ))}+ </section>+ );+});++const ASSET_GROUPS: ReadonlyArray<{+ id: string;+ heading: MessageDescriptor;+ kinds: ReadonlyArray<SetupBrandingAssetKind>;+}> = [+ {id: 'logos', heading: LOGOS_HEADING_DESCRIPTOR, kinds: ['logo', 'wordmark']},+ {id: 'backdrop', heading: ASSET_COPY.sign_in_backdrop.label, kinds: ['sign_in_backdrop']},+ {id: 'app-icons', heading: APP_ICONS_HEADING_DESCRIPTOR, kinds: ['icon', 'symbol', 'favicon', 'favicon_dark']},+];++interface BrandingFieldsProps {+ formRef: React.RefObject<HTMLFormElement | null>;+ onSubmit: (event: React.FormEvent<HTMLFormElement>) => void;+ productName: string;+ themeColor: number | null;+ assets: ReadonlyArray<BrandingAssetState>;+ disabled: boolean;+ error: string | null;+ onThemeColorChange: (value: number | null) => void;+ onUploadAsset: (kind: SetupBrandingAssetKind, file?: File) => void;+ onClearAsset: (kind: SetupBrandingAssetKind) => void;+ onAssetImageError: (kind: SetupBrandingAssetKind) => void;+}++const COLOR_POPOVER_SELECTOR = '[data-flx="ui.form.color-picker-field.popover"]';++export const BrandingFields = observer(+ ({+ formRef,+ onSubmit,+ productName,+ themeColor,+ assets,+ disabled,+ error,+ onThemeColorChange,+ onUploadAsset,+ onClearAsset,+ onAssetImageError,+ }: BrandingFieldsProps) => {+ const {i18n} = useLingui();+ const [tab, setTab] = useState<BrandingPreviewTab>('sign_in');+ const [focusTarget, setFocusTarget] = useState<BrandingPreviewTarget | null>(null);+ const [hoverTarget, setHoverTarget] = useState<BrandingPreviewTarget | null>(null);+ const stepRef = useRef<HTMLFormElement>(null);+ const mergedFormRef = useMergeRefs([stepRef, formRef]);+ const errorRef = useRef<HTMLParagraphElement>(null);+ const handledError = useRef<string | null>(null);+ const draft = useMemo(() => {+ const sources = Object.fromEntries(assets.map((asset) => [asset.kind, asset.preview ?? asset.url])) as Record<+ SetupBrandingAssetKind,+ string | null+ >;+ return {+ productName,+ themeColor: themeColor === null ? null : int2hex(themeColor),+ sources,+ };+ }, [assets, productName, themeColor]);+ const focusField = useCallback(+ (target: BrandingPreviewTarget) => {+ setFocusTarget(target);+ if (target === 'theme_color') return;+ setTab((current) => {+ const tabs = brandingPreviewTabsFor(target, draft);+ return tabs.includes(current) ? current : tabs[0];+ });+ },+ [draft],+ );+ const targetHandlers = useCallback(+ (target: BrandingPreviewTarget): TargetHandlers => ({+ onFocusCapture: () => focusField(target),+ onBlurCapture: (event) => {+ const next = event.relatedTarget;+ if (next instanceof Node && event.currentTarget.contains(next)) return;+ if (next instanceof Element && next.closest(COLOR_POPOVER_SELECTOR)) return;+ setFocusTarget(null);+ },+ onPointerEnter: () => setHoverTarget(target),+ onPointerLeave: () => setHoverTarget(null),+ }),+ [focusField],+ );+ const selectTarget = useCallback((target: BrandingPreviewTarget) => {+ const root = stepRef.current;+ if (!root) return;+ const control =+ target === 'theme_color'+ ? root.querySelector<HTMLElement>('[data-flx="ui.form.color-picker-field.input.text"]')+ : root.querySelector<HTMLElement>(+ `[data-branding-kind="${target}"] :is([data-flx="app.self-hosted-setup-wizard-gate.asset-upload-button"], [data-flx="app.self-hosted-setup-wizard-gate.asset-replace-button"]):not(:disabled)`,+ );+ if (!control) return;+ control.focus({preventScroll: true});+ control.scrollIntoView({block: 'center', behavior: 'smooth'});+ }, []);+ useEffect(() => {+ const guard = (event: DragEvent) => {+ if (event.dataTransfer && Array.from(event.dataTransfer.types).includes('Files')) event.preventDefault();+ };+ window.addEventListener('dragover', guard);+ window.addEventListener('drop', guard);+ return () => {+ window.removeEventListener('dragover', guard);+ window.removeEventListener('drop', guard);+ };+ }, []);+ useEffect(() => {+ if (error == null) {+ handledError.current = null;+ return;+ }+ if (disabled || handledError.current === error) return;+ handledError.current = error;+ const failed = stepRef.current?.querySelector<HTMLElement>(+ '[data-branding-error="not_saved"] button[data-flx^="app.self-hosted-setup-wizard-gate.asset-"]:not(:disabled)',+ );+ if (failed) {+ failed.focus();+ return;+ }+ errorRef.current?.scrollIntoView({block: 'nearest'});+ }, [error, disabled]);+ const highlight = focusTarget ?? hoverTarget;+ let caption: React.ReactNode = null;+ if (highlight != null && highlight !== 'theme_color') {+ const copy = ASSET_COPY[highlight];+ const size = formatFileSize(i18n.locale, getPolicy(brandingAssetPolicyKind(highlight)).maxBytes);+ caption = (+ <>+ <p data-flx="app.setup.setup-branding-step.caption.p">{i18n._(copy.help, {size})}</p>+ {draft.sources[highlight] == null && (+ <p data-flx="app.setup.setup-branding-step.caption.p--2">{i18n._(copy.empty)}</p>+ )}+ </>+ );+ }+ const assetByKind = new Map(assets.map((asset) => [asset.kind, asset]));+ return (+ <form+ ref={mergedFormRef}+ noValidate+ onSubmit={onSubmit}+ className={styles.step}+ data-flx="app.self-hosted-setup-wizard-gate.branding-step"+ >+ <div className={styles.header} data-flx="app.setup.setup-branding-step.branding-step.header">+ <h1+ className={styles.title}+ tabIndex={-1}+ data-step-focus="true"+ data-flx="app.setup.setup-branding-step.branding-step.title"+ >+ {i18n._(TITLE_DESCRIPTOR)}+ </h1>+ <p className={styles.body} data-flx="app.setup.setup-branding-step.branding-step.body">+ {i18n._(BODY_DESCRIPTOR)}+ </p>+ {error && (+ <p+ ref={errorRef}+ className={styles.stepError}+ role="alert"+ data-flx="app.setup.setup-branding-step.branding-step.step-error"+ >+ <WarningCircleIcon+ size={16}+ weight="bold"+ aria-hidden="true"+ data-flx="app.setup.setup-branding-step.branding-step.step-error-icon"+ />+ {error}+ </p>+ )}+ </div>+ <div className={styles.fieldsPane} data-flx="app.setup.setup-branding-step.branding-step.fields-pane">+ <Scroller contentClassName={styles.fields} data-flx="app.setup.setup-branding-step.branding-step.scroller">+ <ThemeColorSection+ themeColor={themeColor}+ disabled={disabled}+ onChange={onThemeColorChange}+ targetHandlers={targetHandlers('theme_color')}+ data-flx="app.setup.setup-branding-step.branding-step.theme-color-section"+ />+ {ASSET_GROUPS.map((group) => {+ const headingId = `setup-branding-group-${group.id}`;+ const solo = group.kinds.length === 1;+ return (+ <section+ key={group.id}+ className={styles.group}+ aria-labelledby={headingId}+ data-flx="app.setup.setup-branding-step.branding-step.group"+ >+ <h2+ id={headingId}+ className={styles.groupHeading}+ data-flx="app.setup.setup-branding-step.branding-step.group-heading"+ >+ {i18n._(group.heading)}+ </h2>+ {group.kinds.map((kind) => {+ const asset = assetByKind.get(kind);+ if (!asset) return null;+ return (+ <BrandingAssetField+ key={kind}+ asset={asset}+ labelledBy={solo ? headingId : null}+ disabled={disabled}+ onUpload={onUploadAsset}+ onClear={onClearAsset}+ onImageError={onAssetImageError}+ targetHandlers={targetHandlers(kind)}+ data-flx="app.setup.setup-branding-step.branding-step.branding-asset-field"+ />+ );+ })}+ </section>+ );+ })}+ </Scroller>+ </div>+ <div className={styles.previewPane} data-flx="app.setup.setup-branding-step.branding-step.preview-pane">+ <SetupBrandingPreview+ draft={draft}+ tab={tab}+ highlight={highlight}+ caption={caption}+ onTabChange={setTab}+ onTargetSelect={selectTarget}+ data-flx="app.setup.setup-branding-step.branding-step.setup-branding-preview"+ />+ </div>+ </form>+ );+ },+);diff --git a/fluxer_app/src/features/app/components/setup/SetupBrandingStep.module.css b/fluxer_app/src/features/app/components/setup/SetupBrandingStep.module.cssnew file mode 100644index 000000000..9306f197a--- /dev/null+++ b/fluxer_app/src/features/app/components/setup/SetupBrandingStep.module.css@@ -0,0 +1,393 @@+/* SPDX-License-Identifier: AGPL-3.0-or-later */++.step {+ --preview-stage-height: clamp(9rem, 24svh, 13rem);+ display: grid;+ grid-template-areas:+ 'header'+ 'preview'+ 'fields';+ grid-template-columns: minmax(0, 1fr);+ gap: 1.25rem;+ width: 100%;+}++.header {+ display: flex;+ grid-area: header;+ flex-direction: column;+ gap: 0.375rem;+}++.title {+ margin: 0;+ outline: none;+ color: var(--text-primary);+ font-size: 1.5rem;+ font-weight: 800;+ line-height: 1.2;+}++.body {+ margin: 0;+ color: var(--text-secondary);+ font-size: 0.9375rem;+ line-height: 1.55;+}++.previewPane {+ --preview-caption-display: none;+ position: sticky;+ top: 0;+ z-index: 2;+ grid-area: preview;+ min-width: 0;+ padding-block: 0.5rem;+ background: var(--background-secondary);+}++:global(html.mobile-layout) .previewPane {+ top: -2rem;+ background: rgb(8 6 22);+}++.fieldsPane {+ display: flex;+ grid-area: fields;+ min-width: 0;+ margin-inline: -0.5rem;+}++.fields {+ flex: 1 0 auto;+ gap: 1.75rem;+ padding-block: 0.25rem 1rem;+ padding-inline: 0.5rem 1rem;+}++.fields :is(button, input) {+ scroll-margin-block: calc(var(--preview-stage-height) + 5rem) 1rem;+}++:global(html.mobile-layout) .fields :is(button, input) {+ scroll-margin-block-end: 8.5rem;+}++@container setup-wide (min-width: 46rem) {+ .step {+ grid-template-areas:+ 'header preview'+ 'fields preview';+ grid-template-rows: auto minmax(0, 1fr);+ grid-template-columns: clamp(20rem, 30cqw, 27rem) minmax(0, 1fr);+ column-gap: clamp(1.5rem, 3cqw, 3rem);+ height: 100cqh;+ margin-block: -0.5rem;+ }++ .previewPane {+ --preview-stage-height: auto;+ --preview-caption-display: block;+ position: static;+ min-height: 0;+ padding-block: 0 1.25rem;+ background: none;+ }++ .fieldsPane {+ min-height: 0;+ }++ .fields {+ padding-block-end: 1.75rem;+ }++ .fields :is(button, input) {+ scroll-margin-block: 0.5rem;+ }+}++.group {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.groupHeader {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ min-height: 1.75rem;+}++.groupHeading {+ margin: 0;+ color: var(--text-primary);+ font-size: 1rem;+ font-weight: 700;+ line-height: 1.3;+}++.presets {+ display: grid;+ grid-template-columns: repeat(10, minmax(0, 1.75rem));+ gap: 0.375rem;+}++.preset {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 100%;+ aspect-ratio: 1;+ padding: 0;+ border: 0.0625rem solid rgb(255 255 255 / 0.14);+ border-radius: 0.5rem;+ cursor: pointer;+ transition: transform 120ms ease;+}++.preset:hover:not(:disabled) {+ transform: scale(1.08);+}++.preset:disabled {+ cursor: not-allowed;+ opacity: 0.5;+}++.presetSelected {+ box-shadow:+ 0 0 0 0.125rem var(--background-secondary),+ 0 0 0 0.25rem var(--text-primary);+}++.colorHelp {+ color: var(--text-secondary);+ font-size: 0.8125rem;+ line-height: 1.45;+}++.note {+ display: flex;+ gap: 0.375rem;+ align-items: flex-start;+ margin: 0;+ color: var(--text-secondary);+ font-size: 0.8125rem;+ line-height: 1.4;+}++.noteWarning {+ color: var(--text-warning);+}++.note svg,+.assetError svg,+.assetWarning svg,+.stepError svg {+ flex: 0 0 auto;+ margin-top: 0.0625rem;+}++.assetRow {+ position: relative;+ display: flex;+ gap: 0.875rem;+ align-items: flex-start;+ padding: 0.75rem;+ border: 0.0625rem solid var(--background-modifier-accent);+ border-radius: 0.625rem;+ background: color-mix(in srgb, var(--background-tertiary) 40%, transparent);+ transition:+ border-color 120ms ease,+ background-color 120ms ease;+}++.assetRowEmpty {+ border-style: dashed;+}++.assetRow.assetRowError {+ border-color: var(--status-danger);+}++.assetRow.assetRowDragging {+ border-style: dashed;+ border-color: var(--brand-primary-light, #a5a2ff);+ background: color-mix(in srgb, var(--brand-primary, #4641d9) 14%, var(--background-tertiary));+}++.thumbnail {+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;+ width: 5rem;+ height: 3.5rem;+ overflow: hidden;+ border-radius: 0.5rem;+ background-color: #2a2a31;+ background-image:+ linear-gradient(45deg, #34343c 25%, transparent 25%), linear-gradient(-45deg, #34343c 25%, transparent 25%),+ linear-gradient(45deg, transparent 75%, #34343c 75%), linear-gradient(-45deg, transparent 75%, #34343c 75%);+ background-position:+ 0 0,+ 0 0.375rem,+ 0.375rem -0.375rem,+ -0.375rem 0;+ background-size: 0.75rem 0.75rem;+}++.resetHidden {+ visibility: hidden;+}++.thumbnail img {+ max-width: 100%;+ max-height: 100%;+ object-fit: contain;+}++.thumbnailCover img {+ width: 100%;+ height: 100%;+ object-fit: cover;+}++.thumbnailEmpty {+ border: 0.0625rem solid var(--background-modifier-accent);+ background: var(--background-secondary);+ color: var(--text-tertiary);+}++.assetBody {+ display: flex;+ flex: 1 1 auto;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.assetLabel {+ margin: 0;+ color: var(--text-primary);+ font-size: 0.875rem;+ font-weight: 700;+ line-height: 1.3;+}++.assetHint {+ margin: 0;+ color: var(--text-secondary);+ font-size: 0.8125rem;+ line-height: 1.4;+}++.helpToggle {+ display: flex;+ margin-inline-start: -0.5rem;+}++.helpToggleIcon {+ transition: transform 120ms ease;+}++[aria-expanded='true'] .helpToggleIcon {+ transform: rotate(180deg);+}++.help {+ display: none;+ flex-direction: column;+ gap: 0.25rem;+ color: var(--text-secondary);+ font-size: 0.8125rem;+ line-height: 1.45;+}++.help p {+ margin: 0;+}++.help p + p {+ color: var(--text-tertiary);+}++.help.helpOpen {+ display: flex;+}++@container setup-wide (min-width: 46rem) {+ .helpToggle {+ display: none;+ }++ .help,+ .help.helpOpen {+ position: absolute;+ display: block;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip-path: inset(50%);+ white-space: nowrap;+ }+}++.assetMeta {+ margin: 0;+ color: var(--text-tertiary);+ font-size: 0.75rem;+ line-height: 1.4;+}++.assetStatus {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}++.assetError,+.assetWarning {+ display: flex;+ gap: 0.375rem;+ align-items: flex-start;+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.4;+}++.assetError {+ color: color-mix(in srgb, var(--status-danger) 70%, var(--text-primary));+}++.assetWarning {+ color: var(--text-warning);+}++.assetActions {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ margin-top: 0.25rem;+}++.stepError {+ display: flex;+ gap: 0.375rem;+ align-items: flex-start;+ margin: 0;+ color: color-mix(in srgb, var(--status-danger) 70%, var(--text-primary));+ font-size: 0.875rem;+ line-height: 1.45;+}++@media (prefers-reduced-motion: reduce) {+ .assetRow,+ .preset,+ .helpToggleIcon {+ transition: none;+ }+}diff --git a/fluxer_app/src/features/app/components/setup/SetupBrandingStep.tsx b/fluxer_app/src/features/app/components/setup/SetupBrandingStep.tsxnew file mode 100644index 000000000..514c99d02--- /dev/null+++ b/fluxer_app/src/features/app/components/setup/SetupBrandingStep.tsx@@ -0,0 +1,110 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ brandingAssetPolicyKind,+ brandingAssetUrl,+ useSetupBrandingDraft,+ validateBrandingFile,+} from '@app/features/app/components/setup/SetupBrandingDraft';+import {BrandingFields} from '@app/features/app/components/setup/SetupBrandingFields';+import {+ type SetupBrandingAssetKind,+ type updateInstanceConfig,+ uploadBrandingAsset,+} from '@app/features/app/components/setup/SetupWizardClient';+import {openFilePicker} from '@app/features/messaging/utils/FilePickerUtils';+import {Logger} from '@app/features/platform/utils/AppLogger';+import {readBlobAsDataUrl as fileToBase64} from '@app/features/platform/utils/BlobDataUrl';+import {int2hex} from '@app/features/theme/utils/ColorUtils';+import * as FormUtils from '@app/lib/forms';+import {getAcceptString} from '@fluxer/constants/src/AssetFormatPolicy';+import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';+import {useLingui} from '@lingui/react/macro';+import {observer} from 'mobx-react-lite';+import {type RefObject, useCallback} from 'react';++const logger = new Logger('SelfHostedSetupWizardGate');++interface BrandingStepProps {+ config: InstanceConfigResponse | null;+ formRef: RefObject<HTMLFormElement | null>;+ disabled: boolean;+ error: string | null;+ onSubmit: (submit: () => Promise<void>) => Promise<void>;+ onSave: (patch: Parameters<typeof updateInstanceConfig>[0]) => Promise<boolean>;+ onConfigUpdate: (config: InstanceConfigResponse) => void;+ onAdvance: () => void;+ onError: (error: string) => void;+}++export const BrandingStep = observer(+ ({config, formRef, disabled, error, onSubmit, onSave, onConfigUpdate, onAdvance, onError}: BrandingStepProps) => {+ const {i18n} = useLingui();+ const {productName, themeColor, setThemeColor, assets, updateAsset} = useSetupBrandingDraft();+ const saveLook = async () => {+ if (!config) return;+ for (const asset of assets) {+ const original = brandingAssetUrl(config, asset.kind);+ const image = asset.preview ?? (asset.url === null && original !== null ? null : undefined);+ if (image === undefined) continue;+ try {+ const next = await uploadBrandingAsset(asset.kind, image);+ updateAsset(asset.kind, {url: brandingAssetUrl(next, asset.kind), preview: null, error: null});+ onConfigUpdate(next);+ } catch (error) {+ logger.error('Failed to upload a branding image', error);+ updateAsset(asset.kind, {error: 'not_saved'});+ onError(FormUtils.extractErrorMessage(i18n, error));+ return;+ }+ }+ const saved = await onSave({+ app_public: {branding: {theme_color: themeColor === null ? null : int2hex(themeColor)}},+ });+ if (saved) onAdvance();+ };+ const handleUploadAsset = useCallback(+ async (kind: SetupBrandingAssetKind, droppedFile?: File) => {+ let file = droppedFile;+ if (!file) {+ [file] = await openFilePicker({accept: getAcceptString(brandingAssetPolicyKind(kind))});+ }+ if (!file) return;+ const error = validateBrandingFile(kind, file);+ if (error) {+ updateAsset(kind, {error});+ return;+ }+ updateAsset(kind, {reading: true, error: null});+ try {+ const dataUrl = await fileToBase64(file);+ updateAsset(kind, {preview: dataUrl, reading: false});+ } catch (readError) {+ logger.error('Failed to read branding asset file', readError);+ updateAsset(kind, {reading: false, error: 'unreadable'});+ }+ },+ [updateAsset],+ );++ return (+ <BrandingFields+ productName={productName}+ themeColor={themeColor}+ assets={assets}+ formRef={formRef}+ disabled={disabled}+ error={error}+ onSubmit={(event) => {+ event.preventDefault();+ void onSubmit(saveLook);+ }}+ onThemeColorChange={setThemeColor}+ onUploadAsset={handleUploadAsset}+ onClearAsset={(kind) => updateAsset(kind, {preview: null, url: null, error: null})}+ onAssetImageError={(kind) => updateAsset(kind, {preview: null, error: 'unreadable'})}+ data-flx="app.setup.setup-branding-step.branding-step.branding-fields.prevent-default"+ />+ );+ },+);diff --git a/fluxer_app/src/features/app/components/setup/SetupNameStep.tsx b/fluxer_app/src/features/app/components/setup/SetupNameStep.tsxnew file mode 100644index 000000000..1f9f11d6b--- /dev/null+++ b/fluxer_app/src/features/app/components/setup/SetupNameStep.tsx@@ -0,0 +1,101 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import styles from '@app/features/app/components/setup/SelfHostedSetupWizardGate.module.css';+import {useSetupBrandingDraft} from '@app/features/app/components/setup/SetupBrandingDraft';+import {useSetupPolicyDraft} from '@app/features/app/components/setup/SetupPolicySteps';+import type {updateInstanceConfig} from '@app/features/app/components/setup/SetupWizardClient';+import {StepError, StepHeader} from '@app/features/app/components/setup/SetupWizardSteps';+import {Input} from '@app/features/ui/components/form/FormInput';+import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {observer} from 'mobx-react-lite';+import type {RefObject} from 'react';++const MIN_INSTANCE_NAME_LENGTH = 1;+const MAX_INSTANCE_NAME_LENGTH = 80;++const NAME_TITLE_DESCRIPTOR = msg({+ message: 'Name your instance',+ comment: 'Setup wizard title for choosing the instance name.',+});+const NAME_BODY_DESCRIPTOR = msg({+ message: 'People see this name on the sign-in page and in the app.',+ comment: 'Setup wizard body for choosing the instance name.',+});+const NAME_LABEL_DESCRIPTOR = msg({+ message: 'Name',+ comment: 'Label for the instance name field in the setup wizard.',+});+const NAME_ERROR_DESCRIPTOR = msg({+ message: 'Enter a name between 1 and 80 characters.',+ comment: 'Error under the instance name field in the setup wizard.',+});++function isValidInstanceName(value: string): boolean {+ const length = value.trim().length;+ return length >= MIN_INSTANCE_NAME_LENGTH && length <= MAX_INSTANCE_NAME_LENGTH;+}++interface NameStepProps {+ config: InstanceConfigResponse | null;+ formRef: RefObject<HTMLFormElement | null>;+ showErrors: boolean;+ disabled: boolean;+ error: string | null;+ onSubmit: (submit: () => Promise<void>) => Promise<void>;+ onSave: (patch: Parameters<typeof updateInstanceConfig>[0]) => Promise<boolean>;+ onAdvance: () => void;+ onShowErrors: (showErrors: boolean) => void;+}++export const NameStep = observer(+ ({config, formRef, showErrors, disabled, error, onSubmit, onSave, onAdvance, onShowErrors}: NameStepProps) => {+ const {i18n} = useLingui();+ const {productName, setProductName} = useSetupBrandingDraft();+ const {setDraft: setFinishDraft} = useSetupPolicyDraft();+ const saveName = async () => {+ onShowErrors(true);+ if (!isValidInstanceName(productName)) return;+ const saved = await onSave({app_public: {branding: {product_name: productName.trim()}}});+ if (saved) {+ setFinishDraft((current) =>+ current.singleCommunityName.trim() && current.singleCommunityName !== config?.app_public.branding.product_name+ ? current+ : {...current, singleCommunityName: productName.trim()},+ );+ onAdvance();+ }+ };++ return (+ <form+ ref={formRef}+ noValidate+ onSubmit={(event) => {+ event.preventDefault();+ void onSubmit(saveName);+ }}+ className={styles.step}+ data-flx="app.self-hosted-setup-wizard-gate.name-step"+ >+ <StepHeader+ title={i18n._(NAME_TITLE_DESCRIPTOR)}+ body={i18n._(NAME_BODY_DESCRIPTOR)}+ data-flx="app.setup.setup-wizard-steps.name-step.step-header"+ />+ <Input+ label={i18n._(NAME_LABEL_DESCRIPTOR)}+ value={productName}+ maxLength={MAX_INSTANCE_NAME_LENGTH}+ autoComplete="off"+ disabled={disabled}+ error={showErrors && !isValidInstanceName(productName) ? i18n._(NAME_ERROR_DESCRIPTOR) : undefined}+ onChange={(event) => setProductName(event.target.value)}+ data-flx="app.self-hosted-setup-wizard-gate.name-input"+ />+ <StepError error={error} data-flx="app.setup.setup-wizard-steps.name-step.step-error" />+ </form>+ );+ },+);