/** * Repeater field — an editable list of rows a site owner builds themselves, * each with its own small set of properties (a name, a type, whether it's * required, whether it's shown at all, and — for a dropdown — its choices). * Aureon Nexus's sign-up form builder is the first (and, for now, only) * caller: each row here becomes one field on the front-end registration * form. * * Deliberately not a generic "list of arbitrary sub-fields" primitive like * `group`/`row` are for the rest of the panel — every row here has the same * fixed shape ({@see PanelRepeaterItem}), so the UI is hand-built for that * shape rather than driven by a nested field descriptor. A second caller that * needs a differently-shaped row would be its own control, not a reason to * generalize this one. * * Each row is a compact single line (drag handle, type glyph, name, a type * badge, a Required/Optional pill, an Enabled switch, edit, remove) rather * than an always-expanded card — a list of ten fields reads as a list that * way, not as ten stacked forms. Opening a row for edit is a *staged* draft: * changes inside the open card don't reach the list until Update Field * commits them, and Cancel discards them — the parent's `value` is the * source of truth right up until that commit, never live-bound to the form * inputs the way every other field type in this panel is. A brand-new row * (via "Add Field") is added to the list optimistically so its position is * visible immediately, but Cancel on that specific row removes it again * rather than leaving an unlabelled "Field" behind. */ import { useState } from '@wordpress/element'; import { Button, TextControl, ToggleControl, CheckboxControl, TextareaControl, } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; import { Plus, Trash2, Pencil, GripVertical, Info, Copy, ChevronUp, Lock, Type as TypeIcon, Home, User, Mail, Phone, Folder, Settings as SettingsIcon, Rocket, Users, } from '../icons'; import SelectField from './select-field'; import type { PanelFieldOption, PanelRepeaterItem, PanelRepeaterPinnedItem, } from '../types'; interface RepeaterFieldProps { label: string; help?: string; itemLabel: string; addLabel: string; typeOptions: PanelFieldOption[]; iconOptions: PanelFieldOption[]; pinnedItems: PanelRepeaterPinnedItem[]; value: PanelRepeaterItem[]; onChange: ( next: PanelRepeaterItem[] ) => void; } // Field types whose expanded row shows the "Options" textarea — everything // else leaves that row empty rather than asking for choices it won't use. const OPTIONS_TYPES = [ 'select' ]; // A typed placeholder means something typed into an empty box — a dropdown // and a checkbox don't have one. const PLACEHOLDER_TYPES = [ 'text', 'email', 'tel', 'textarea' ]; // Every icon a row (or a pinned Username/Email/Password row) can carry, // keyed the same way the front end's own icon set is — not a Lucide name — // since the picker's choice has to resolve on both sides. Lucide only // supplies the actual glyphs here; the keys themselves come from the PHP // descriptor's `iconOptions`. const ICON_MAP: Record< string, typeof TypeIcon > = { home: Home, profile: User, mail: Mail, phone: Phone, lock: Lock, edit: Pencil, folder: Folder, settings: SettingsIcon, rocket: Rocket, community: Users, }; // What a row draws when its own `icon` is empty — a sensible default per // type rather than a single generic glyph for everything. const TYPE_ICON_KEY: Record< string, string > = { text: 'profile', email: 'mail', tel: 'phone', textarea: 'edit', select: 'folder', checkbox: 'edit', }; /** * The glyph a row (editable or pinned) actually draws: its own `icon` when * set, else a type-based default, else the generic fallback. * * @param icon The row's own icon key, or ''. * @param type The row's field type. */ function rowIcon( icon: string, type: string ): typeof TypeIcon { return ( ICON_MAP[ icon ] ?? ICON_MAP[ TYPE_ICON_KEY[ type ] ?? '' ] ?? TypeIcon ); } /** * A row's key, derived from its label the same way `sanitize_key()` would, * and disambiguated against its siblings so two rows never collide (the * server would otherwise silently drop one on save). * * @param label The row's current label. * @param index The row's position, as a last-resort suffix when the label * is empty. * @param taken Keys already used by the row's siblings. */ function deriveKey( label: string, index: number, taken: Set< string > ): string { const base = label .toLowerCase() .replace( /[^a-z0-9_\s-]/g, '' ) .trim() .replace( /[\s-]+/g, '_' ) .slice( 0, 32 ) || `field_${ index + 1 }`; if ( ! taken.has( base ) ) { return base; } let n = 2; while ( taken.has( `${ base }_${ n }` ) ) { n++; } return `${ base }_${ n }`; } const BLANK_ITEM: PanelRepeaterItem = { key: '', label: '', type: 'text', required: false, options: [], default: false, enabled: true, placeholder: '', description: '', icon: '', }; export default function RepeaterField( { label, help, itemLabel, addLabel, typeOptions, iconOptions, pinnedItems, value, onChange, }: RepeaterFieldProps ) { const items = Array.isArray( value ) ? value : []; // One row open at a time — editing several at once reads as several forms // competing for attention, and nothing here depends on seeing two rows' // properties side by side. const [ openIndex, setOpenIndex ] = useState< number | null >( null ); // The open row's own working copy — inputs bind to this, not to `items` // directly, so Cancel has something to discard. Null whenever nothing's // open. const [ draft, setDraft ] = useState< PanelRepeaterItem | null >( null ); // True while the open row is one "Add Field" just appended and no Update // has ever landed for it — Cancel removes the row itself, not just the // edit, so a dismissed add doesn't leave an empty "Field" in the list. const [ openIsNew, setOpenIsNew ] = useState( false ); // The grip is a native HTML5 drag handle — `dragIndex` is the row picked // up, `overIndex` the row currently under the pointer (for the drop-target // highlight only; the actual move happens once, on drop). const [ dragIndex, setDragIndex ] = useState< number | null >( null ); const [ overIndex, setOverIndex ] = useState< number | null >( null ); const close = () => { setOpenIndex( null ); setDraft( null ); setOpenIsNew( false ); }; const openForEdit = ( index: number, isNew = false ) => { setOpenIndex( index ); setDraft( { ...items[ index ] } ); setOpenIsNew( isNew ); }; const updateDraft = ( patch: Partial< PanelRepeaterItem > ) => { setDraft( ( current ) => { if ( ! current ) { return current; } const merged = { ...current, ...patch }; // The key tracks the label unless someone's typed a custom one — // once a row's label and key have diverged, respect that instead // of clobbering it on every keystroke. if ( 'label' in patch && current.key === deriveKey( current.label, openIndex ?? 0, new Set() ) ) { const taken = new Set( items .filter( ( _, i ) => i !== openIndex ) .map( ( row ) => row.key ) ); merged.key = deriveKey( merged.label, openIndex ?? 0, taken ); } return merged; } ); }; const commit = () => { if ( null === openIndex || ! draft ) { return; } const next = items.slice(); next[ openIndex ] = draft; onChange( next ); close(); }; const cancel = () => { if ( openIsNew && null !== openIndex ) { onChange( items.filter( ( _, i ) => i !== openIndex ) ); } close(); }; const remove = ( index: number ) => { onChange( items.filter( ( _, i ) => i !== index ) ); if ( openIndex === index ) { close(); } }; // Inserted right after the original — a duplicate reads as "the next one // of these", not as something appended to the end of an unrelated list. const duplicate = ( index: number ) => { const source = items[ index ]; const taken = new Set( items.map( ( row ) => row.key ) ); const copiedLabel = source.label ? copyLabel( source.label ) : source.label; const copy: PanelRepeaterItem = { ...source, label: copiedLabel, key: deriveKey( copiedLabel, items.length, taken ), }; const next = items.slice(); next.splice( index + 1, 0, copy ); onChange( next ); if ( null !== openIndex && openIndex > index ) { setOpenIndex( openIndex + 1 ); } }; // Moves the picked-up row to sit just before `target`'s current position — // called once, on drop, rather than live during drag (reordering the array // mid-drag would fire a `dragend` on an element that's no longer where the // browser thinks it is). const reorder = ( from: number, target: number ) => { if ( from === target ) { return; } const next = items.slice(); const [ moved ] = next.splice( from, 1 ); next.splice( from < target ? target - 1 : target, 0, moved ); onChange( next ); if ( openIndex === from ) { setOpenIndex( from < target ? target - 1 : target ); } }; const add = () => { const next = [ ...items, { ...BLANK_ITEM, type: typeOptions[ 0 ]?.value ?? 'text' }, ]; onChange( next ); openForEdit( next.length - 1, true ); }; // A pinned row's `type` ('password', say) is never one of `typeOptions` — // those are only the choices the editable rows offer — so it falls back // to the raw value, capitalized to match every real option's own label. const typeLabel = ( type: string ): string => typeOptions.find( ( option ) => option.value === type )?.label ?? type.charAt( 0 ).toUpperCase() + type.slice( 1 ); return (
{ label }
) } { help &&{ help }
}{ __( 'No custom fields yet.', 'aureon' ) }
) } { ( items.length > 0 || pinnedItems.length > 0 ) && ({ __( 'Users must fill this field to register.', 'aureon' ) }
{ __( 'Username, Email, and Password fields are always included and cannot be removed.', 'aureon' ) }