/* ************************************************************************ */ /* */ /* This file is part of Frama-C. */ /* */ /* Copyright (C) 2007-2022 */ /* CEA (Commissariat à l'énergie atomique et aux énergies */ /* alternatives) */ /* */ /* you can redistribute it and/or modify it under the terms of the GNU */ /* Lesser General Public License as published by the Free Software */ /* Foundation, version 2.1. */ /* */ /* It is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Lesser General Public License for more details. */ /* */ /* See the GNU Lesser General Public License version 2.1 */ /* for more details (enclosed in the file licenses/LGPLv2.1). */ /* */ /* ************************************************************************ */ /* eslint-disable @typescript-eslint/explicit-function-return-type */ /* --------------------------------------------------------------------------*/ /* --- Form Fields ---*/ /* --------------------------------------------------------------------------*/ /** Form Fields are made of states and fields, arranged into a form page. Field states are typically build with [[useState]] and [[useProperty]] hooks, also you can also build them manually. All the provided hooks can be used and composed with each other to build full feature states. Form fields shall be arranged into sections and form pages to obtain a wellformed layout. @packageDocumentation @module dome/layout/form */ import { debounce } from 'lodash'; import React from 'react'; import * as Dome from 'dome'; import * as Utils from 'dome/misc/utils'; import { SVG } from 'dome/controls/icons'; import { Checkbox, Radio, Select as SelectMenu } from 'dome/controls/buttons'; export type FieldError = | undefined | boolean | string | { [key: string]: FieldError } | FieldError[]; export type Checker = (value: A) => boolean | FieldError; export type Callback = (value: A, error: FieldError) => void; export type FieldState = [A, FieldError, Callback]; /* --------------------------------------------------------------------------*/ /* --- State Errors Utilities ---*/ /* --------------------------------------------------------------------------*/ export function inRange( a: number, b: number, ): Checker { return (v: number) => (a <= v && v <= b); } export function validate( value: A, checker: undefined | Checker, ): FieldError { if (checker) { try { const r = checker(value); if (r === undefined || r === true) return undefined; return r; } catch (err) { return `${err}`; } } return undefined; } export function isValid(err: FieldError): boolean { return !err; } type ObjectError = { [key: string]: FieldError }; function isObjectError(err: FieldError): err is ObjectError { return typeof err === 'object' && !Array.isArray(err); } function isArrayError(err: FieldError): err is FieldError[] { return Array.isArray(err); } function isValidObject(err: ObjectError): boolean { const ks = Object.keys(err); for (let k = 0; k < ks.length; k++) { if (!isValid(err[ks[k]])) return false; } return true; } function isValidArray(err: FieldError[]): boolean { for (let k = 0; k < err.length; k++) { if (!isValid(err[k])) return false; } return true; } /* --------------------------------------------------------------------------*/ /* --- State Hooks ---*/ /* --------------------------------------------------------------------------*/ /** Create a local field state, like `React.useState()` does. */ export function useState( defaultValue: A, checker?: Checker, onChange?: Callback, ): FieldState { const [value, setValue] = React.useState(defaultValue); const [error, setError] = React.useState(undefined); const setState = React.useCallback((newValue: A, newError: FieldError) => { const localError = validate(newValue, checker) || newError; setValue(newValue); setError(localError); if (onChange) onChange(newValue, localError); }, [checker, setValue, setError, onChange]); return [value, error, setState]; } /** Introduces a local state and propagates only non-errors. */ export function useValid( state: [A, (newValue: A) => void], ): FieldState { const [value, setValue] = state; const [local, setLocal] = React.useState(value); const [error, setError] = React.useState(undefined); const update = React.useCallback( (newValue: A, newError: FieldError) => { setLocal(newValue); setError(newError); if (!newError) setValue(newValue); }, [setValue], ); return [error ? local : value, error, update]; } /** Provides a new state with a default value. */ export function useDefault( state: FieldState, defaultValue: A, ): FieldState { const [value, error, setState] = state; return [value ?? defaultValue, error, setState]; } /** Coerces a state with defined value into some with possibly undefined one. */ export function useDefined( state: FieldState, ): FieldState { const [value, error, setState] = state; const update = React.useCallback( (newValue: A | undefined, newError: FieldError) => { if (newValue !== undefined) { setState(newValue, newError); } }, [setState], ); return [value, error, update]; } /** Undefined value leads to an error. @param onError - error message in case of undefined or invalid updates. */ export function useRequired( state: FieldState, onError?: string, ): FieldState { const [value, error, setState] = state; const cache = React.useRef(value); const update = React.useCallback( (newValue: A | undefined, newError: FieldError) => { if (newValue === undefined) { setState(cache.current, onError || 'Required field'); } else { setState(newValue, newError); } }, [cache, onError, setState], ); return [value, error, update]; } /** Enrich the state with a local checker. The local error, if any, has precedence over any error from updates. */ export function useChecker( state: FieldState, checker?: Checker, ): FieldState { const [value, error, setState] = state; const update = React.useCallback((newValue: A, newError: FieldError) => { const localError = validate(newValue, checker) || newError; setState(newValue, localError); }, [checker, setState]); return [value, error, update]; } /** Transform a state `A` into a state `B` through converting functions. Input and output functions shall be the inverse with each others. In case an exception is raised during input conversion, state `B` retains its previous value (or default value) but forwards the translation error. In case an exception is raised during output conversion, a local state is maintained with the invalid `B` value until it is transformed into a valid one. @param input - converting function from `A` to `B` @param output - converting function from `B` to `A` */ export function useFilter( state: FieldState, input: (value: A) => B, output: (value: B) => A, defaultValue: B, ): FieldState { const [value, error, setState] = state; const [localValue, setLocalValue] = React.useState(defaultValue); const [localError, setLocalError] = React.useState(undefined); const [dangling, setDangling] = React.useState(false); const update = React.useCallback( (newValue: B, newError: FieldError) => { try { const outValue = output(newValue); setLocalValue(newValue); setLocalError(newError); if (isValid(newError)) { setDangling(false); setState(outValue, undefined); } } catch (err) { setLocalValue(newValue); setLocalError(newError || err ? `${err}` : 'Invalid value'); setDangling(true); } }, [output, setState, setLocalValue, setLocalError], ); if (dangling) { return [localValue, localError, update]; } try { return [input(value), error, update]; } catch (err) { return [localValue, err ? `${err}` : 'Invalid input', update]; } } /** Introduces a latency between local changes and propagated ones. A transient local state is maintained during debounced updates, until the last update is finally flushed. */ export function useLatency( state: FieldState, latency?: number, ): FieldState { const [value, error, setState] = state; const period = latency ?? 0; const [localValue, setLocalValue] = React.useState(value); const [localError, setLocalError] = React.useState(error); const [dangling, setDangling] = React.useState(false); const update = React.useMemo(() => { if (period > 0) { const propagate = debounce( (lateValue: A, lateError: FieldError) => { setState(lateValue, lateError); setDangling(false); }, period, ); return (newValue: A, newError: FieldError) => { setLocalValue(newValue); setLocalError(newError); setDangling(true); propagate(newValue, newError); }; } setDangling(false); return setState; }, [period, setDangling, setState, setLocalValue, setLocalError]); return [ dangling ? localValue : value, dangling ? localError : error, update, ]; } /** Returns the state associated to a property of the input state. */ export function useProperty( state: FieldState, property: K, checker?: Checker, ): FieldState { const [value, error, setState] = state; const update = React.useCallback((newProp: A[K], newError: FieldError) => { const newValue = { ...value, [property]: newProp }; const objError = isObjectError(error) ? error : {}; const propError = validate(newProp, checker) || newError; const localError = { ...objError, [property]: propError }; setState(newValue, isValidObject(localError) ? undefined : localError); }, [value, error, setState, property, checker]); return [value[property], error, update]; } /** Returns the state associated to an index element of the input state. */ export function useIndex( state: FieldState, index: number, checker?: Checker, ): FieldState { const [array, error, setState] = state; const update = React.useCallback((newValue: A, newError: FieldError) => { const newArray = array.slice(); newArray[index] = newValue; const localError = isArrayError(error) ? error.slice() : []; const valueError = validate(newValue, checker) || newError; localError[index] = valueError; setState(newArray, isValidArray(localError) ? undefined : localError); }, [array, error, setState, index, checker]); const itemError = isArrayError(error) ? error[index] : undefined; return [array[index], itemError, update]; } /* --------------------------------------------------------------------------*/ /* --- Form Filter Context ---*/ /* --------------------------------------------------------------------------*/ export interface FilterProps { /** default is false. */ hidden?: boolean; /** default is true. */ visible?: boolean; /** default is true. */ enabled?: boolean; /** default is false. */ disabled?: boolean; } export interface Children { children?: React.ReactNode } interface FormContext { disabled: boolean; hidden: boolean; } const CONTEXT = React.createContext(undefined); const HIDDEN = ({ hidden = false, visible = true }: FilterProps) => hidden || !visible; const DISABLED = ({ disabled = false, enabled = true }: FilterProps) => disabled || !enabled; function useContext(props?: FilterProps): FormContext { const Parent = React.useContext(CONTEXT); return { hidden: (props && HIDDEN(props)) || (Parent?.hidden ?? false), disabled: (props && DISABLED(props)) || (Parent?.disabled ?? false), }; } /** Allow to locally disable or hide all its children fields. @category Form Containers */ export function FormFilter(props: FilterProps & Children) { const context = useContext(props); if (context.hidden) return null; return ( {props.children} ); } /* --------------------------------------------------------------------------*/ /* --- Main Form Container ---*/ /* --------------------------------------------------------------------------*/ /** @category Form Containers */ export interface PageProps extends FilterProps, Children { /** Additional container class. */ className?: string; /** Additional container style. */ style?: React.CSSProperties; } /** Main Form Container. @category Form Containers */ export function Page(props: PageProps) { const { className, style, children, ...filter } = props; const { hidden, disabled } = useContext(filter); const css = Utils.classes(className ?? 'dome-xForm-grid'); if (hidden) return null; return (
{children}
); } // -------------------------------------------------------------------------- // --- Warning Badge // -------------------------------------------------------------------------- export interface WarningProps { /** Short warning message (displayed on hover). */ warning?: string; /** Error details (if a string is provided, in tooltip). */ error?: FieldError; /** Label offset. */ offset?: number; } /** Warning Badge. */ export function Warning(props: WarningProps) { const { warning, error, offset = 0 } = props; const DETAILS = typeof error === 'string' ? error : undefined; const WARNING = warning && ( {warning} ); return (
{WARNING}
); } // -------------------------------------------------------------------------- // --- Block Container // -------------------------------------------------------------------------- /** Layout its contents inside a full-width container. @category Form Containers */ export function FormBlock(props: FilterProps & Children) { const { children, ...filter } = props; return (
{children}
); } // -------------------------------------------------------------------------- // --- Section Container // -------------------------------------------------------------------------- /** @category Form Fields */ export interface SectionProps extends FilterProps, Children { /** Section name. */ label: string; /** Tooltip text. */ title?: string; /** Warning Error (when unfolded). */ warning?: string; /** Associated Error. */ error?: FieldError; /** Fold/Unfold settings. */ settings?: string; /** Fold/Unfold state (defaults to false). */ unfold?: boolean; } /** @category Form Fields */ export function Section(props: SectionProps) { const { label, title, children, warning, error, ...filter } = props; const { disabled, hidden } = useContext(filter); const [unfold, flip] = Dome.useFlipSettings(props.settings, props.unfold); if (hidden) return null; const hasWarning = unfold && !disabled && error; const cssTitle = Utils.classes( 'dome-text-title', disabled && 'dome-disabled', ); return (
{hasWarning && }
{unfold && children} {unfold &&
} ); } /* --------------------------------------------------------------------------*/ /* --- Generic Field --- */ /* --------------------------------------------------------------------------*/ /** @category Form Fields */ export interface GenericFieldProps extends FilterProps, Children { /** Field label. */ label: string; /** Field tooltip text. */ title?: string; /** Field offset. */ offset?: number; /** Html tag `` element. */ htmlFor?: string; /** Warning message (in case of error). */ onError?: string; /** Error (if any). */ error?: FieldError; } let FIELDID = 0; /** Generates a unique, stable identifier. */ export function useHtmlFor() { return React.useMemo(() => `dome-field ${FIELDID++}`, []); } /** Generic Field. Layout its content in a top-left aligned box on the right of the label. @category Form Fields */ export function Field(props: GenericFieldProps) { const { hidden, disabled } = useContext(props); if (hidden) return null; const { label, title, offset, htmlFor, children } = props; const cssLabel = Utils.classes( 'dome-xForm-label dome-text-label', disabled && 'dome-disabled', ); const cssField = Utils.classes( 'dome-xForm-field dome-text-label', disabled && 'dome-disabled', ); const { onError, error } = props; const WARNING = error ? ( ) : null; return ( <>
{children} {WARNING}
); } /* --------------------------------------------------------------------------*/ /* --- Input Fields ---*/ /* --------------------------------------------------------------------------*/ /** @category Form Fields */ export interface FieldProps
extends FilterProps { /** Field label. */ label: string; /** Field tooltip text. */ title?: string; /** Field state. */ state: FieldState; /** Checker. */ checker?: Checker; /** Alternative error message (in case of error). */ onError?: string; } type InputEvent = { target: { value: string } }; type InputState = [string, FieldError, (evt: InputEvent) => void]; function useChangeEvent(setState: Callback) { return React.useCallback( (evt: InputEvent) => { setState(evt.target.value, undefined); }, [setState], ); } /* --------------------------------------------------------------------------*/ /* --- Text Fields ---*/ /* --------------------------------------------------------------------------*/ /** @category Text Fields */ export interface TextFieldProps extends FieldProps { placeholder?: string; className?: string; style?: React.CSSProperties; latency?: number; } function useTextInputField( props: TextFieldProps, defaultLatency: number, ): InputState { const checked = useChecker(props.state, props.checker); const period = props.latency ?? defaultLatency; const [value, error, setState] = useLatency(checked, period); const onChange = useChangeEvent(setState); return [value || '', error, onChange]; } /** Text Field. @category Text Fields */ export function TextField(props: TextFieldProps) { const { disabled } = useContext(props); const id = useHtmlFor(); const css = Utils.classes('dome-xForm-text-field', props.className); const [value, error, onChange] = useTextInputField(props, 600); return ( ); } /** Monospaced Text Field. @category Text Fields */ export function TextCodeField(props: TextFieldProps) { const { disabled } = useContext(props); const id = useHtmlFor(); const [value, error, onChange] = useTextInputField(props, 600); const css = Utils.classes( 'dome-xForm-text-field', 'dome-text-code', props.className, ); return ( ); } /* --------------------------------------------------------------------------*/ /* --- Text Area Fields ---*/ /* --------------------------------------------------------------------------*/ /** @category Text Fields */ export interface TextFieldAreaProps extends TextFieldProps { /** Number of columns (default 35, min 5). */ cols?: number; /** Number of rows (default 5, min 2). */ rows?: number; } /** Text Field Area. @category Text Fields */ export function TextFieldArea(props: TextFieldAreaProps) { const { disabled } = useContext(props); const id = useHtmlFor(); const [value, error, onChange] = useTextInputField(props, 900); const cols = Math.max(5, props.cols ?? 35); const rows = Math.max(2, props.rows ?? 5); const css = Utils.classes( 'dome-xForm-textarea-field', props.className, ); return (