/** * The simple settings, drawn from the schema (`GET mailpuff/v1/module-settings`, * `Mailpuff_Admin_Data::fields()`), in the Settings layout * (./settings-layout.jsx): one `SettingsSection` per schema section, inputs * in a grid with labels above them, on/off settings as `ToggleRow`s. A * field's `help` is its `?` tip and its `placeholder` shows the default; a * field with a `parent` (a boolean's key) shows under that switch while it is * on, and one with `when` only while another field has that value. A field * with `enum` is a select (its `labels` name the values); an `array` field is * a list of boxes to tick (across the row, as is a `wide` one); a `secret` one is a password box. A page can add * its own lines under a switch (`extras`) or at the end of a section * (`footers`). Every field shows; nothing hides behind "More settings". * Changes stay on the screen until Save, in the bottom pill, and survive * switching Settings pages; Discard puts back what is saved. */ import { useQuery, useQueryClient } from '@tanstack/react-query'; import { Fragment, useEffect, useMemo, useState } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { apiGet, apiPost } from '../api/client'; import { ui } from '../kit'; import { FieldGrid, SettingsSection, ToggleList, ToggleRow, } from './settings-layout'; export const KEY = [ 'module-settings' ]; /** * The schema's fields as a list, each with its key. A WooCommerce field * (`woo`) is left out while WooCommerce is not active. * * @param {Object|Array} fields The schema's fields. * @return {Array} Fields. */ export function fieldList( fields ) { const list = Array.isArray( fields ) ? fields : Object.entries( fields || {} ).map( ( [ key, field ] ) => ( { key, ...field, } ) ); const woo = Boolean( window.mailpuffData?.woocommerce ); return list.filter( ( field ) => woo || ! field.woo ); } const isNumeric = ( field ) => 'integer' === field.type || 'number' === field.type; // A `secret` field (a key) is typed blind and never read back. const inputType = ( field ) => { if ( isNumeric( field ) ) { return 'number'; } return field.secret ? 'password' : 'text'; }; /** * Why a draft value cannot be saved, or ''. * * @param {Object} field The field. * @param {*} value Its draft value. * @return {string} The problem. */ export function problem( field, value ) { if ( ! isNumeric( field ) ) { return ''; } const text = String( value ?? '' ).trim(); if ( ! /^-?\d+$/.test( text ) ) { return __( 'Enter a whole number.', 'mailpuff' ); } const n = Number( text ); if ( undefined !== field.minimum && n < field.minimum ) { return sprintf( /* translators: %s: the smallest allowed number. */ __( 'Must be %s or more.', 'mailpuff' ), field.minimum ); } if ( undefined !== field.maximum && n > field.maximum ) { return sprintf( /* translators: %s: the largest allowed number. */ __( 'Must be %s or less.', 'mailpuff' ), field.maximum ); } return ''; } const same = ( a, b ) => String( a ?? '' ) === String( b ?? '' ); const isOn = ( value ) => !! value && ! [ '0', 'false' ].includes( String( value ) ); /** * Whether a field shows now: one with `when` only while each named field * has that value, one with `any` only while one of those switches is on. * * @param {Object} field The field. * @param {Function} valueOf Current value of a field key. * @return {boolean} Shown. */ export function visible( field, valueOf ) { const any = field.any || []; return ( Object.entries( field.when || {} ).every( ( [ key, value ] ) => String( valueOf( key ) ?? '' ) === String( value ) ) && ( ! any.length || any.some( ( key ) => isOn( valueOf( key ) ) ) ) ); } /** * A list field's value with one choice ticked or unticked, in the order the * choices are listed. * * @param {Object} field The field, with `enum`. * @param {Array} value Ticked values. * @param {*} item The value to flip. * @return {Array} The new value. */ export function toggleChoice( field, value, item ) { const ticked = ( Array.isArray( value ) ? value : [] ).map( String ); const flip = String( item ); const next = ticked.includes( flip ) ? ticked.filter( ( v ) => v !== flip ) : [ ...ticked, flip ]; return ( field.enum || [] ).filter( ( v ) => next.includes( String( v ) ) ); } /** * The name of one of a field's values. * * @param {Object} field The field. * @param {*} value A value from its `enum`. * @return {string} Its label. */ const choiceLabel = ( field, value ) => String( field.labels?.[ value ] ?? value ); /** * A text, number or choice field, its label above it. * * @param {Object} props * @param {Object} props.field The schema's field. * @param {*} props.value Its value. * @param {string} props.error Why it cannot be saved. * @param {boolean} props.busy Saving. * @param {Function} props.onChange Called with the new value. * @return {Element} The field. */ function InputField( { field, value, error, busy, onChange } ) { if ( 'array' === field.type ) { const ticked = ( Array.isArray( value ) ? value : [] ).map( String ); return ( { () => ( field.enum || [] ).length ? (
{ field.enum.map( ( v ) => ( onChange( toggleChoice( field, value, v ) ) } /> ) ) }
) : (

{ __( 'Nothing to pick yet.', 'mailpuff' ) }

) }
); } return ( { ( a11y ) => Array.isArray( field.enum ) ? ( onChange( e.target.value ) } > { field.enum.map( ( v ) => ( ) ) } ) : ( onChange( e.target.value ) } /> ) } ); } /** * The schema's fields in runs: inputs side by side, switches one per row, * each switch with the fields that belong to it. * * @param {Array} fields A section's fields, in order. * @return {Array} `{ kind: 'inputs'|'toggles', fields, children? }`. */ export function runs( fields ) { const out = []; const children = ( key ) => fields.filter( ( f ) => f.parent === key ); fields .filter( ( f ) => ! f.parent || ! fields.some( ( p ) => p.key === f.parent ) ) .forEach( ( f ) => { const kind = 'boolean' === f.type ? 'toggles' : 'inputs'; const last = out[ out.length - 1 ]; const item = { field: f, children: children( f.key ) }; if ( last && last.kind === kind ) { last.items.push( item ); } else { out.push( { kind, items: [ item ] } ); } } ); return out; } /* * Unsaved changes by form (its keys), kept while the page is open: each * Settings page remounts when the side menu switches pages, and an edit * should still be there, unsaved, on the way back. */ const DRAFTS = new Map(); /** * @param {Object} props * @param {string[]} props.keys Optional: only these fields, in this order, * when the page draws the rest itself. * @param {Object} props.titles Optional: a section title for each schema * section, to rename it on this page. * @param {number} props.columns 2 (default) or 3 inputs side by side. * @param {Object} props.extras Optional: a switch's key => what shows under * it while it is on, after its fields. * @param {Object} props.footers Optional: a field's key => what shows at * the end of that field's section. */ export default function SettingsForm( { keys, titles = {}, columns = 2, extras = {}, footers = {}, } ) { const qc = useQueryClient(); const { data, isLoading, error: loadError, refetch, } = useQuery( { queryKey: KEY, queryFn: () => apiGet( 'module-settings' ), } ); const id = keys ? keys.join( ',' ) : '*'; const [ draft, setDraft ] = useState( () => DRAFTS.get( id ) || {} ); const [ errors, setErrors ] = useState( {} ); const [ saving, setSaving ] = useState( false ); useEffect( () => { if ( Object.keys( draft ).length ) { DRAFTS.set( id, draft ); } else { DRAFTS.delete( id ); } }, [ id, draft ] ); const saved = data?.values || {}; const shown = useMemo( () => { const all = fieldList( data?.fields ); if ( ! keys ) { return all; } return keys .map( ( key ) => all.find( ( f ) => f.key === key ) ) .filter( Boolean ); }, [ data, keys ] ); const valueOf = ( f ) => f.key in draft ? draft[ f.key ] : saved[ f.key ] ?? f.default; const changed = shown.filter( ( f ) => f.key in draft && ! same( draft[ f.key ], saved[ f.key ] ) ); const dirty = changed.length > 0; const discard = () => { setDraft( {} ); setErrors( {} ); }; const save = () => { const problems = {}; changed.forEach( ( f ) => { const text = problem( f, draft[ f.key ] ); if ( text ) { problems[ f.key ] = text; } } ); if ( Object.keys( problems ).length ) { setErrors( problems ); return; } const values = {}; changed.forEach( ( f ) => { values[ f.key ] = isNumeric( f ) ? Number( draft[ f.key ] ) : draft[ f.key ]; } ); setSaving( true ); apiPost( 'module-settings', { values } ) .then( ( res ) => { qc.setQueryData( KEY, ( old ) => ( { ...( old || {} ), values: res?.values || { ...saved, ...values }, } ) ); // Fields can depend on what is saved (a key's last four // characters in its placeholder); setup tasks and other // screens read these settings too. qc.invalidateQueries( { queryKey: KEY } ); qc.invalidateQueries( { queryKey: [ 'overview' ] } ); qc.invalidateQueries( { queryKey: [ 'settings' ] } ); setDraft( {} ); setErrors( {} ); ui.toast.success( __( 'Saved.', 'mailpuff' ) ); } ) .catch( ( e ) => { const fields = e?.data?.fields; if ( fields && typeof fields === 'object' ) { setErrors( fields ); } else { ui.toast.error( e?.message || __( 'Could not save that setting.', 'mailpuff' ) ); } } ) .finally( () => setSaving( false ) ); }; if ( isLoading ) { return ( ); } if ( loadError ) { return ( { loadError.message || __( 'Could not load these settings.', 'mailpuff' ) }{ ' ' } { __( 'Try again', 'mailpuff' ) } ); } if ( ! shown.length ) { return null; } const groups = []; shown.forEach( ( f ) => { const section = f.section || ''; let group = groups.find( ( g ) => g.section === section ); if ( ! group ) { group = { section, fields: [] }; groups.push( group ); } group.fields.push( f ); } ); const change = ( f ) => ( v ) => { setDraft( ( d ) => ( { ...d, [ f.key ]: v } ) ); setErrors( ( e ) => { const next = { ...e }; delete next[ f.key ]; return next; } ); }; const input = ( f ) => ( ); const all = fieldList( data?.fields ); const valueOfKey = ( key ) => { const f = all.find( ( item ) => item.key === key ); return f ? valueOf( f ) : undefined; }; // A switch's fields: side by side, a list of boxes across the row. const childFields = ( children ) => ( { children .filter( ( f ) => visible( f, valueOfKey ) ) .map( ( f ) => 'array' === f.type || f.wide ? (
{ input( f ) }
) : ( input( f ) ) ) }
); return ( <> { groups.map( ( group ) => (
{ runs( group.fields ).map( ( run, i ) => { if ( run.kind === 'inputs' ) { const items = run.items.filter( ( item ) => visible( item.field, valueOfKey ) ); return items.length ? ( { items.map( ( item ) => input( item.field ) ) } ) : null; } return ( { run.items.map( ( { field: f, children } ) => ( { children.length > 0 || extras[ f.key ] ? ( <> { children.length > 0 && childFields( children ) } { extras[ f.key ] } ) : null } ) ) } ); } ) } { group.fields.map( ( f ) => ( { footers[ f.key ] } ) ) }
) ) } ); }