All files / blong-browser/src/design PropertyEditor.tsx

17.04% Statements 60/352
100% Branches 1/1
0% Functions 0/1
17.04% Lines 60/352

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 3531x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       1x 1x   1x 1x 1x 1x 1x 1x  
/**
 * PropertyEditor โ€” sidebar panel showing editable properties of the selected element.
 *
 * Card properties: label, collapsible, hidden, className.
 * Field properties: title, widget.type, required, readOnly (all editable).
 */
import type {ICardConfig, IEnrichedFieldSchema} from '@feasibleone/blong';
import {useState} from 'react';
import {useBlongForm} from '../components/Form/FormContext.js';
import {useDesignMode} from './useDesignMode.js';
 
const WIDGET_TYPES = [
    'input',
    'text',
    'textArea',
    'password',
    'number',
    'integer',
    'boolean',
    'checkbox',
    'switch',
    'date',
    'time',
    'dateTime',
    'dropdown',
    'multiSelect',
    'select',
    'selectTable',
    'chips',
    'file',
    'image',
    'table',
    'json',
    'code',
    'label',
    'link',
    'divider',
] as const;
 
const FIELD_TYPES = ['string', 'number', 'boolean', 'object', 'array'] as const;
 
export function PropertyEditor() {
    const {active, selected, config, updateConfig} = useDesignMode();
    const formCtx = useBlongForm();
 
    if (!active) return null;
 
    if (!selected) {
        return (
            <div className="blong-property-editor blong-property-editor--empty">
                <i className="pi pi-info-circle blong-property-editor__icon" />
                <p className="blong-property-editor__hint">Click a card or field to inspect it</p>
            </div>
        );
    }

    if (selected.type === 'card') {
        // selected.id = 'card-{cardName}'
        const cardName = selected.id.replace(/^card-/, '');
        const origCard = formCtx?.cards[cardName];
        const cardOverride = config.cards[cardName] ?? {};
        const cardConfig = {...(origCard?.config ?? {}), ...cardOverride};

        const update = (patch: Record<string, unknown>) =>
            updateConfig({
                cards: {
                    ...config.cards,
                    [cardName]: {...cardOverride, ...patch},
                },
            });

        return (
            <div className="blong-property-editor">
                <div className="blong-property-editor__title">Card</div>
                <div className="blong-property-editor__field">
                    <label htmlFor="pe-card-label">Label</label>
                    <input
                        id="pe-card-label"
                        type="text"
                        className="blong-property-editor__input"
                        value={cardConfig.label ?? origCard?.label ?? ''}
                        onChange={e => update({label: e.target.value})}
                    />
                </div>
                <div className="blong-property-editor__field">
                    <label htmlFor="pe-card-class">CSS class</label>
                    <input
                        id="pe-card-class"
                        type="text"
                        className="blong-property-editor__input"
                        value={cardConfig.className ?? ''}
                        onChange={e => update({className: e.target.value || undefined})}
                    />
                </div>
                <div className="blong-property-editor__check">
                    <input
                        id="pe-card-collapsible"
                        type="checkbox"
                        checked={cardConfig.collapsible ?? false}
                        onChange={e => update({collapsible: e.target.checked || undefined})}
                    />
                    <label htmlFor="pe-card-collapsible">Collapsible</label>
                </div>
                <div className="blong-property-editor__check">
                    <input
                        id="pe-card-hidden"
                        type="checkbox"
                        checked={cardConfig.hidden ?? false}
                        onChange={e => update({hidden: e.target.checked || undefined})}
                    />
                    <label htmlFor="pe-card-hidden">Hidden</label>
                </div>
            </div>
        );
    }

    if (selected.type === 'field') {
        // selected.id = 'field:{fieldName}:{cardName}'
        const colonIdx = selected.id.indexOf(':', 6); // skip 'field:'
        const fieldName = selected.id.substring(6, colonIdx);
        const cardName = selected.id.substring(colonIdx + 1);

        const baseSchema = formCtx?.schema?.properties?.[fieldName];
        const schemaOverride = (config.schema?.[fieldName] ?? {}) as {
            title?: string;
            type?: string;
            fieldRequired?: boolean;
            readOnly?: boolean;
            widget?: {type?: string};
        };
        const card = formCtx?.cards[cardName];

        const updateField = (patch: Record<string, unknown>) =>
            updateConfig({
                schema: {
                    ...(config.schema ?? {}),
                    [fieldName]: {...schemaOverride, ...patch} as Partial<IEnrichedFieldSchema>,
                },
            });

        const currentTitle = schemaOverride.title ?? baseSchema?.title ?? fieldName;
        const currentType = schemaOverride.type ?? baseSchema?.type ?? '';
        const currentWidgetType =
            schemaOverride.widget?.type ?? baseSchema?.widget?.type ?? 'input';
        const currentRequired = schemaOverride.fieldRequired ?? baseSchema?.fieldRequired ?? false;
        const currentReadOnly = schemaOverride.readOnly ?? baseSchema?.readOnly ?? false;

        return (
            <div className="blong-property-editor p-component m-2">
                <div className="blong-property-editor__title">Field ยท {fieldName}</div>
                <div className="blong-property-editor__row">
                    <span className="blong-property-editor__key">Card</span>
                    <span className="blong-property-editor__val">{card?.label ?? cardName}</span>
                </div>
                <div className="blong-property-editor__field">
                    <label htmlFor="pe-field-title">Label</label>
                    <input
                        id="pe-field-title"
                        type="text"
                        className="blong-property-editor__input"
                        value={currentTitle}
                        onChange={e => updateField({title: e.target.value || undefined})}
                    />
                </div>
                <div className="blong-property-editor__field">
                    <label htmlFor="pe-field-type">Type</label>
                    <select
                        id="pe-field-type"
                        className="blong-property-editor__input"
                        value={currentType}
                        onChange={e => updateField({type: e.target.value || undefined})}
                    >
                        <option value="">โ€”</option>
                        {FIELD_TYPES.map(t => (
                            <option
                                key={t}
                                value={t}
                            >
                                {t}
                            </option>
                        ))}
                    </select>
                </div>
                <div className="blong-property-editor__field">
                    <label htmlFor="pe-field-widget">Widget</label>
                    <select
                        id="pe-field-widget"
                        className="blong-property-editor__input"
                        value={currentWidgetType}
                        onChange={e =>
                            updateField({
                                widget: {...(schemaOverride.widget ?? {}), type: e.target.value},
                            })
                        }
                    >
                        {WIDGET_TYPES.map(t => (
                            <option
                                key={t}
                                value={t}
                            >
                                {t}
                            </option>
                        ))}
                    </select>
                </div>
                <div className="blong-property-editor__check">
                    <input
                        id="pe-field-required"
                        type="checkbox"
                        checked={currentRequired}
                        onChange={e => updateField({required: e.target.checked || undefined})}
                    />
                    <label htmlFor="pe-field-required">Required</label>
                </div>
                <div className="blong-property-editor__check">
                    <input
                        id="pe-field-readonly"
                        type="checkbox"
                        checked={currentReadOnly}
                        onChange={e => updateField({readOnly: e.target.checked || undefined})}
                    />
                    <label htmlFor="pe-field-readonly">Read-only</label>
                </div>
            </div>
        );
    }

    return (
        <div className="blong-property-editor">
            <div className="blong-property-editor__title">{selected.type}</div>
            <p className="blong-property-editor__hint">{selected.id}</p>
        </div>
    );
}

// ---------------------------------------------------------------------------
// DesignAddCardButton / DesignAddFieldButton โ€” rendered inside DesignModeProvider
// so they can call useDesignMode(). Used by Editor toolbar.
// ---------------------------------------------------------------------------

export function DesignAddCardButton({onCardAdded}: {onCardAdded: (name: string) => void}) {
    const {updateConfig, config} = useDesignMode();

    const handleAdd = () => {
        const name = `card_${Date.now()}`;
        updateConfig({
            cards: {
                ...config.cards,
                [name]: {label: 'New Card', widgets: []} as ICardConfig,
            },
        });
        onCardAdded(name);
    };

    return (
        <button
            type="button"
            className="p-button p-component p-button-icon-only ml-1"
            aria-label="Add card"
            title="Add card"
            onClick={handleAdd}
        >
            <span className="p-button-icon p-c pi pi-id-card" />
            <span className="p-button-label p-c">&nbsp;</span>
        </button>
    );
}

export function DesignAddFieldButton({
    schema: schemaProp,
    // cards: cardsProp,
}: {
    schema?: Record<string, unknown>;
    cards?: Record<string, unknown>;
}) {
    const {updateConfig, config, selected} = useDesignMode();
    const formCtx = useBlongForm();
    const [open, setOpen] = useState(false);

    // All schema field names
    const allFields = Object.keys(
        (formCtx?.schema?.properties ?? schemaProp ?? {}) as Record<string, unknown>,
    );

    // Fields currently used in any card (base + design overrides)
    const usedFields = new Set<string>([
        ...Object.values(formCtx?.cards ?? {}).flatMap(c => c.fields),
        ...Object.values(config.cards).flatMap(c => {
            const w = c.widgets ?? (Array.isArray(c.fields) ? c.fields : []);
            return w as string[];
        }),
    ]);

    const availableFields = allFields.filter(f => !usedFields.has(f));

    const handleAddField = (fieldName: string) => {
        // Target card: currently selected card, or the first one
        const cardName =
            selected?.type === 'card'
                ? selected.id.replace(/^card-/, '')
                : (Object.keys(formCtx?.cards ?? {})[0] ?? Object.keys(config.cards)[0]);
        if (!cardName) return;

        const baseCard = formCtx?.cards[cardName];
        const designCard = config.cards[cardName];
        const existing: string[] =
            (designCard?.widgets as string[] | undefined) ?? baseCard?.fields ?? [];

        updateConfig({
            cards: {
                ...config.cards,
                [cardName]: {
                    ...(designCard ?? {}),
                    widgets: [...existing, fieldName],
                    fields: undefined,
                } as ICardConfig,
            },
        });
        setOpen(false);
    };

    if (!open && availableFields.length === 0) return null;

    return (
        <span style={{position: 'relative', display: 'inline-block'}}>
            <button
                type="button"
                className="p-button p-component p-button-icon-only ml-1"
                aria-label="Add field"
                title="Add field"
                disabled={availableFields.length === 0}
                onClick={() => setOpen(o => !o)}
            >
                <span className="p-button-icon p-c pi pi-plus-circle" />
                <span className="p-button-label p-c">&nbsp;</span>
            </button>
            {open && (
                <div className="blong-design-field-picker">
                    {availableFields.map(f => (
                        <div
                            key={f}
                            className="blong-design-field-picker__item"
                            onClick={() => handleAddField(f)}
                        >
                            {formCtx?.schema?.properties?.[f]?.title ?? f}
                        </div>
                    ))}
                </div>
            )}
        </span>
    );
}