/** * 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 && (

{ label }

) } { help &&

{ help }

}
{ 0 === items.length && 0 === pinnedItems.length && (

{ __( 'No custom fields yet.', 'aureon' ) }

) } { ( items.length > 0 || pinnedItems.length > 0 ) && (
{ pinnedItems.map( ( pinned, index ) => { const PinnedIcon = rowIcon( pinned.icon, pinned.type ); return (
{ pinned.label }
{ __( 'Required', 'aureon' ) }
); } ) } { items.map( ( item, index ) => { const open = index === openIndex; const row = open && draft ? draft : item; const RowIcon = rowIcon( row.icon, row.type ); return (
{ if ( null === dragIndex ) { return; } e.preventDefault(); setOverIndex( index ); } } onDrop={ ( e ) => { e.preventDefault(); if ( null !== dragIndex ) { reorder( dragIndex, index ); } setDragIndex( null ); setOverIndex( null ); } } >
{ e.dataTransfer.effectAllowed = 'move'; setDragIndex( index ); } } onDragEnd={ () => { setDragIndex( null ); setOverIndex( null ); } } > { row.label || itemLabel }
{ row.required ? __( 'Required', 'aureon' ) : __( 'Optional', 'aureon' ) } { /* A hand-rolled switch, not `ToggleControl` — that component's track/thumb sizing lives in its own CSS-in-JS, injected after this stylesheet and winning any tie on plain specificity, so the only way to actually get the pill size and gold "on" fill this row calls for is to own the markup outright. */ }
{ open ? ( <>
{ open && draft && (
updateDraft( { label: next, } ) } /> updateDraft( { type: next, } ) } /> updateDraft( { icon: next, } ) } /> { PLACEHOLDER_TYPES.includes( draft.type ) && ( updateDraft( { placeholder: next, } ) } /> ) } { OPTIONS_TYPES.includes( draft.type ) && ( updateDraft( { options: next .split( '\n' ) .map( ( line ) => line.trim() ) .filter( Boolean ), } ) } /> ) } updateDraft( { description: next, } ) } />
updateDraft( { required: next, } ) } />

{ __( 'Users must fill this field to register.', 'aureon' ) }

{ /* A checkbox's own "Required" means it must be ticked to submit — a Terms agreement. "Checked by default" is the separate, unrelated question of what state it starts in — a newsletter opt-in starts ticked without being required. */ } { 'checkbox' === draft.type && ( updateDraft( { default: next, } ) } /> ) }
) }
); } ) }
) }

); } // Tiny local helpers rather than pulling in `sprintf` from `@wordpress/i18n` // for a couple of call sites. function removeLabel( itemLabel: string ): string { return __( 'Remove', 'aureon' ) + ' ' + itemLabel.toLowerCase(); } function duplicateLabel( itemLabel: string ): string { return __( 'Duplicate', 'aureon' ) + ' ' + itemLabel.toLowerCase(); } function copyLabel( label: string ): string { return label + ' ' + __( '(Copy)', 'aureon' ); }