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

246 lines
12 KiB
TypeScript

import { useAppForm, Form } from '@/components/form';
import { type AdminNode, updateAdminNodeInput, useUpdateAdminNode } from '@/api/admin/nodes/queries';
import { useAllAdminLocations } from '@/api/admin/locations/queries';
import {
type NodeFormValues,
nodeFormValues,
nodeNumberValidators,
nodeValuesFromForm,
validateNodeName,
} from '@/components/admin/nodes/nodeForm';
import { useNodeDetail } from '@/components/admin/nodes/useNodeDetail';
import ExtensionFormFields from '@/components/admin/extensions/ExtensionFormFields';
import { initialExtensionValues, useExtensionPayload } from '@/extensions/forms';
import TitledGreyBox from '@/components/elements/TitledGreyBox';
interface Values extends NodeFormValues {
resetSecret: boolean;
}
const nodeToValues = (node: AdminNode): Values => ({ ...nodeFormValues(node), resetSecret: false });
const NodeSettingsForm = () => {
const { node } = useNodeDetail();
const updateNode = useUpdateAdminNode();
const { data: locations = [] } = useAllAdminLocations();
const { withExtensionPayload } = useExtensionPayload('admin.node');
const form = useAppForm({
defaultValues: nodeToValues(node),
onSubmit: async ({ value }) => {
const { resetSecret, ...values } = value;
try {
await updateNode.mutateAsync(
updateAdminNodeInput(
node.attributes.id,
nodeValuesFromForm(withExtensionPayload(values, node)),
resetSecret
)
);
form.setFieldValue('resetSecret', false);
form.setFieldValue('extensions', initialExtensionValues());
} catch {
// Error toast is handled by the mutation.
}
},
});
return (
<Form form={form}>
<div className='grid grid-cols-1 lg:grid-cols-2 gap-6'>
<TitledGreyBox title='Settings'>
<form.AppField
name='name'
validators={{
onChange: ({ value }) => validateNodeName(value),
}}
>
{(field) => (
<field.TextField
type='text'
id='name'
label='Node Name'
description='A short identifier used to distinguish this node from others.'
/>
)}
</form.AppField>
<div className='mt-6'>
<form.AppField name='description'>
{(field) => <field.TextField type='text' id='description' label='Description' />}
</form.AppField>
</div>
<div className='mt-6'>
<form.AppField
name='locationId'
validators={{
onChange: ({ value }) => (value >= 1 ? undefined : 'A location must be selected.'),
}}
>
{(field) => (
<field.SelectField
id='location_id'
label='Location'
options={locations.map((location) => ({
value: location.attributes.id,
label: location.attributes.long
? `${location.attributes.long} (${location.attributes.short})`
: location.attributes.short,
}))}
/>
)}
</form.AppField>
</div>
<div className='mt-6'>
<form.AppField
name='fqdn'
validators={{
onChange: ({ value }) => (value.length >= 1 ? undefined : 'An FQDN must be provided.'),
}}
>
{(field) => (
<field.TextField
type='text'
id='fqdn'
label='FQDN'
description='The domain name or IP address that points to this node.'
/>
)}
</form.AppField>
</div>
<div className='mt-6'>
<form.AppField name='scheme'>
{(field) => (
<field.SelectField
id='scheme'
label='Communicate Over SSL'
options={[
{ value: 'https', label: 'Use SSL Connection (https)' },
{ value: 'http', label: 'Use HTTP Connection (http)' },
]}
/>
)}
</form.AppField>
</div>
<div className='mt-6'>
<form.AppField name='public'>
{(field) => (
<field.SwitchField
label='Allow Automatic Allocation'
description='Public nodes are available for automatic server deployment.'
/>
)}
</form.AppField>
</div>
<div className='mt-6'>
<form.AppField name='behindProxy'>
{(field) => (
<field.SwitchField
label='Behind Proxy'
description='Enable if this node sits behind a proxy such as Cloudflare.'
/>
)}
</form.AppField>
</div>
<div className='mt-6'>
<form.AppField name='maintenanceMode'>
{(field) => (
<field.SwitchField
label='Maintenance Mode'
description='Servers on a node in maintenance mode cannot be accessed.'
/>
)}
</form.AppField>
</div>
</TitledGreyBox>
<div className='space-y-6'>
<TitledGreyBox title='Allocation Limits'>
<div className='grid grid-cols-2 gap-4'>
<form.AppField name='memory' validators={nodeNumberValidators.memory}>
{(field) => <field.NumberField id='memory' label='Total Memory (MiB)' min={1} />}
</form.AppField>
<form.AppField
name='memoryOverallocate'
validators={nodeNumberValidators.memoryOverallocate}
>
{(field) => (
<field.NumberField id='memory_overallocate' label='Overallocate (%)' min={-1} />
)}
</form.AppField>
<form.AppField name='disk' validators={nodeNumberValidators.disk}>
{(field) => <field.NumberField id='disk' label='Disk Space (MiB)' min={1} />}
</form.AppField>
<form.AppField name='diskOverallocate' validators={nodeNumberValidators.diskOverallocate}>
{(field) => (
<field.NumberField id='disk_overallocate' label='Overallocate (%)' min={-1} />
)}
</form.AppField>
</div>
</TitledGreyBox>
<TitledGreyBox title='General Configuration'>
<form.AppField name='uploadSize' validators={nodeNumberValidators.uploadSize}>
{(field) => (
<field.NumberField id='upload_size' label='Maximum Web Upload Filesize (MiB)' min={1} />
)}
</form.AppField>
<div className='mt-6 grid grid-cols-2 gap-4'>
<form.AppField name='daemonListen' validators={nodeNumberValidators.daemonListen}>
{(field) => (
<field.NumberField id='daemon_listen' label='Daemon Port' min={1} max={65535} />
)}
</form.AppField>
<form.AppField name='daemonSftp' validators={nodeNumberValidators.daemonSftp}>
{(field) => (
<field.NumberField id='daemon_sftp' label='Daemon SFTP Port' min={1} max={65535} />
)}
</form.AppField>
</div>
<div className='mt-6'>
<form.AppField name='daemonBase'>
{(field) => <field.TextField type='text' id='daemon_base' label='Daemon Base Path' />}
</form.AppField>
</div>
</TitledGreyBox>
</div>
</div>
<form.AppField name='extensions'>
{() => (
<ExtensionFormFields
form='admin.node'
mode='edit'
resource={node}
error={updateNode.error}
boxed
className='mt-6'
/>
)}
</form.AppField>
<TitledGreyBox title='Save Settings' className='mt-6'>
<form.AppField name='resetSecret'>
{(field) => (
<field.SwitchField
label='Reset Daemon Master Key'
description={
'Resetting the daemon master key voids any request using the old key. ' +
'This key is used for all sensitive daemon operations including server creation and deletion.'
}
/>
)}
</form.AppField>
<div className='mt-6 text-right'>
<form.AppForm>
<form.SubmitButton>Save Changes</form.SubmitButton>
</form.AppForm>
</div>
</TitledGreyBox>
</Form>
);
};
export default function NodeSettingsTab() {
const { node } = useNodeDetail();
return <NodeSettingsForm key={node.attributes.id} />;
}