Files
Sky Mulleyandrobert dennis 71dd1911a5 Implement native support for hooking into forms with extensions (#7256)
## Problem

Extensions can render content before and after most admin pages, but not
inside the forms on them. The only exception was
`panel.users.detail.form`, and it could only re-render or validate the
user's existing fields. An extension had no way to add a field of its
own, because the Panel's save requests had nowhere to carry the value
and nothing loaded it back.

## Changes

### Slots inside every admin form

The create and edit forms for users, nodes, servers, eggs, locations,
mounts and database hosts each render a slot inside the form, such as
`panel.servers.create.form` and `panel.servers.detail.details.form`. The
slot receives the native `form`, the form's `kind` (`admin.server`), and
`mode` (`'create'` or `'edit'`). Edit slots also receive the saved
`resource`. Contributed `form.AppField` controls share the form's
validation, pending state and submit action.

### Extension-owned fields

An extension registers fields in its provider:

```php
$this->registerFormFields('admin.user', ['plan' => ['required', 'in:free,pro']]);

$this->registerFormFields(
    'admin.node',
    ['region' => ['required', 'string', 'max:32']],
    fn (Node $node): array => ['region' => NodeRegion::for($node)],
    fn (Node $node, array $values) => NodeRegion::store($node, $values['region']),
);
```

The 14 create and update endpoints accept an optional `extensions: {
[extensionId]: { [field]: value } }` body field. Each extension's rules
are applied as `extensions.{id}.{field}`, and only when the request
includes that extension's values. The extension's `save` callback runs
in the same database transaction as the core change, so a failure rolls
both back.

Server creation is the exception. Wings reads the new server while
provisioning it, so extension values are saved after provisioning
succeeds, outside the transaction.

For Node updates when Wings is unreachable. `UpdateNode` saves the node
and then throws `ConfigurationNotPersistedException` as a warning. The
node controller defers that exception until the extension values are
saved, so the node update is no longer rolled back.

`GET /api/admin/extensions/forms/{form}/{id}` returns every extension's
current values. It requires the resource's read permission. Edit pages
fetch it before rendering the form, but only when an extension has
registered fields for that form; the bootstrap payload now lists them
per extension in `forms`.

For users and servers the callbacks are optional, and values are stored
in the extension's scoped settings (`settings()->forUser($user)`,
`forServer($server)`). Values are limited to strings, numbers, booleans,
`null`, or lists of strings and numbers, which keeps the OpenAPI schema
and generated types concrete.

A `load` callback that throws, or returns an invalid value, is recorded
against the extension in the `form` phase. The frontend then hides that
extension's slot contributions on the edit page, so a save cannot
overwrite its stored values with defaults. Fields of a disabled or
failed extension are neither validated, saved nor loaded.

---------

Co-authored-by: robert dennis <31261583+robertdrakedennis@users.noreply.github.com>
2026-10-09 01:26:45 -04:00

128 lines
5.2 KiB
TypeScript

import { useState } from 'react';
import { useStore } from '@tanstack/react-form';
import { httpValidationErrors } from '@/api/http';
import Button from '@/components/elements/Button';
import TitledGreyBox from '@/components/elements/TitledGreyBox';
import { useFieldContext } from '@/components/form';
import ExtensionMount from '@/extensions/ExtensionMount';
import {
shownFormExtensions,
useExtensionForms,
useFormExtensions,
type ExtensionFormValues,
} from '@/extensions/forms';
import type {
ExtensionField,
ExtensionFieldValue,
ExtensionFieldValues,
ExtensionFormName,
ExtensionFormResources,
} from '@/extensions/formTypes';
import { cn } from '@/lib/cn';
interface Props<TName extends ExtensionFormName> {
form: TName;
mode: 'create' | 'edit';
/** The saved resource, when editing. */
resource?: ExtensionFormResources[TName];
/** The error of the last save: the panel's messages for extension fields show on them. */
error?: unknown;
/** Draws each extension in its own card, for pages laid out in cards. */
boxed?: boolean;
/** Adds a submit button to each card, for pages whose cards each have one. */
submitLabel?: string;
className?: string;
}
/**
* The fields extensions draw in an admin form with `forms.extend()`. Render it inside
* `<form.AppField name={'extensions'}>` and submit the form's values through
* `useExtensionPayload()`, so every extension shown here is validated and saved with the
* form. When editing, an extension whose values the panel did not return (it failed to read
* them, or the signed-in admin may not see them) is left out, so a save cannot write over them.
*/
export default function ExtensionFormFields<TName extends ExtensionFormName>({
form,
mode,
resource,
error,
boxed = false,
submitLabel,
className,
}: Props<TName>) {
const field = useFieldContext<ExtensionFormValues>();
const isSubmitting = useStore(field.form.store, (state) => state.isSubmitting);
const registrations = useFormExtensions(form);
// Nothing shows until the panel's list of the form's extensions arrives.
const forms = useExtensionForms(form);
// Fields changed since `error` arrived no longer show its message.
const [edited, setEdited] = useState<{ error: unknown; paths: readonly string[] }>({ error: undefined, paths: [] });
const editedPaths = edited.error === error ? edited.paths : [];
const saved = resource?.attributes.extensions ?? {};
const extensions = shownFormExtensions(form, forms, registrations, mode === 'create' ? undefined : saved);
if (extensions.length === 0) {
return null;
}
const messages = httpValidationErrors(error);
const pending = field.state.value ?? {};
const valuesOf = (extension: string): ExtensionFieldValues => ({ ...saved[extension], ...pending[extension] });
const bind =
(extension: string) =>
(name: string): ExtensionField<ExtensionFieldValue> => {
const path = `extensions.${extension}.${name}`;
return {
id: `${form}-${extension}-${name}`.replaceAll(/[^\w-]/g, '-'),
name: path,
value: valuesOf(extension)[name],
setValue: (value) => {
setEdited((current) => ({
error,
paths: [...(current.error === error ? current.paths : []), path],
}));
// An extension's values are sent whole once any of them changes.
field.handleChange((current = {}) => ({
...current,
[extension]: { ...saved[extension], ...current[extension], [name]: value },
}));
},
error: editedPaths.includes(path) ? undefined : messages[path],
};
};
return (
<div className={cn('space-y-4', className)}>
{extensions.map(({ id, name, component: Component }) => {
const fields = (
<ExtensionMount extensionId={id} context={`form "${form}"`} resetKey={form} isSlot>
<Component form={form} mode={mode} resource={resource} values={valuesOf(id)} field={bind(id)} />
</ExtensionMount>
);
return boxed ? (
<TitledGreyBox key={id} title={name}>
{fields}
{submitLabel && (
<div className='mt-6 flex justify-end'>
<Button type='submit' isLoading={isSubmitting}>
{submitLabel}
</Button>
</div>
)}
</TitledGreyBox>
) : (
<section key={id} aria-label={name} className='border-t border-border pt-4'>
<h3 className='mb-3 text-xs font-medium uppercase tracking-wide text-muted-foreground'>
{name}
</h3>
{fields}
</section>
);
})}
</div>
);
}