mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
feat(dashboard): start the order form from one server dry-run
The form took its defaults from the schema in the browser, which cannot see the installation defaults the API now applies on create, so it could show values the created application would not have. The page sends one dry-run create when it opens and fills the form and the YAML editor from the spec the server returns. There are no further previews while the user edits. A preview that fails, or gets no answer within 8 seconds, opens the form without installation values and shows a notice with Retry. Deploy still works then, because the real create applies the defaults itself. After a failed preview a dropdown stays empty instead of selecting the cluster's default option: a value the user did not choose would be sent and win over the platform default the API applies to omitted fields. A cleared plain text field leaves its key out, as it did before, so clearing a field still resets it. Assisted-by: LLM Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
This commit is contained in:
14 files changed
+874
-112
No files matched your search
@@ -109,8 +109,7 @@ schema). The pipeline in `apps/console/src/components/SchemaForm.tsx`:
|
||||
- credential-shaped fields (`password`, `*token`, `*accessKey`, …) →
|
||||
`SensitiveStringWidget` — see `lib/sensitive-fields.ts` and its tests for
|
||||
the exact matching rules.
|
||||
4. Defaults are emitted to the parent once per schema via `getDefaultFormState`
|
||||
so the first submit always carries a populated spec.
|
||||
4. Application forms use server-prepared values: the order page asks `dryRunCreate` once when it opens and starts the form from the returned spec (no previews on edits), and editing starts with the saved API response. In `defaulting="server"` mode, schema defaults are stripped at every depth and RJSF cannot populate defaults, a field with a schema default is not required inside an object because the server fills it (array rows and dictionary values keep their requirements), while a dynamic option list still selects its server-marked default when the field is empty, except after a failed preview (`autoSelectDefaults` off), where the empty field stays empty and the API applies the platform's default. A cleared plain text input leaves its key out, so on create the API fills it again from the defaults, unless that empties a nested object: the form then sends `{}` for it, which stops installation defaults for that object. A dropdown's None and a sensitive field are written as `""`. Other resource forms retain their existing schema-default mode.
|
||||
|
||||
When you add a new widget binding:
|
||||
|
||||
|
||||
+7
-2
@@ -5,6 +5,7 @@ import Form from "@rjsf/core"
|
||||
import validator from "@rjsf/validator-ajv8"
|
||||
import { customTemplates, customWidgets } from "./rjsf-registry.ts"
|
||||
import { addDynamicOptionWidgets } from "../lib/dynamic-options.ts"
|
||||
import { serverFormStateBehavior } from "../lib/server-form.ts"
|
||||
|
||||
export function AdditionalPropertiesField(props: FieldProps) {
|
||||
const { schema, formData, onChange, readonly, disabled, name, required, idSchema } =
|
||||
@@ -17,6 +18,7 @@ export function AdditionalPropertiesField(props: FieldProps) {
|
||||
[schema.additionalProperties],
|
||||
)
|
||||
const keys = Object.keys(formData || {})
|
||||
const serverDefaults = props.formContext?.serverDefaults === true
|
||||
|
||||
// The nested <Form> renders its own subtree, so it needs its own uiSchema to
|
||||
// bind x-cozystack-options fields (e.g. nodeGroups.*.instanceType) to the
|
||||
@@ -41,8 +43,8 @@ export function AdditionalPropertiesField(props: FieldProps) {
|
||||
return
|
||||
}
|
||||
|
||||
// Initialize with default value from schema
|
||||
const defaultValue = itemSchema.type === "object" ? {} : itemSchema.default ?? ""
|
||||
// Server mode adds an empty entry and leaves defaults to the API on create.
|
||||
const defaultValue = itemSchema.type === "object" ? {} : serverDefaults ? "" : itemSchema.default ?? ""
|
||||
onChange({ ...formData, [newKey]: defaultValue })
|
||||
setNewKey("")
|
||||
}
|
||||
@@ -98,9 +100,12 @@ export function AdditionalPropertiesField(props: FieldProps) {
|
||||
schema={itemSchema}
|
||||
uiSchema={itemUiSchema}
|
||||
formData={formData[key]}
|
||||
formContext={props.formContext}
|
||||
experimental_defaultFormStateBehavior={serverDefaults ? serverFormStateBehavior : undefined}
|
||||
validator={validator}
|
||||
templates={templatesWithoutSubmit}
|
||||
widgets={customWidgets}
|
||||
fields={props.registry.fields}
|
||||
onChange={(e) => handleValueChange(key, e.formData)}
|
||||
disabled={isReadonly}
|
||||
liveValidate={false}
|
||||
|
||||
+51
-1
@@ -61,7 +61,7 @@ function clientWith(result: ListResult) {
|
||||
|
||||
const NEVER_RESOLVES = () => new Promise<K8sList<unknown>>(() => {})
|
||||
|
||||
function makeProps(overrides: Partial<WidgetProps> = {}, source = "storageclass"): WidgetProps {
|
||||
function makeProps(overrides: Omit<Partial<WidgetProps>, "registry"> & { registry?: Partial<WidgetProps["registry"]> } = {}, source = "storageclass"): WidgetProps {
|
||||
const base = {
|
||||
id: "field",
|
||||
name: "field",
|
||||
@@ -88,6 +88,56 @@ function makeProps(overrides: Partial<WidgetProps> = {}, source = "storageclass"
|
||||
}
|
||||
|
||||
describe("DynamicOptionsWidget", () => {
|
||||
it.each(["", null, undefined])("selects the default item in server mode when the prepared value is empty %s", async (value) => {
|
||||
const onChange = vi.fn()
|
||||
renderWithK8sProvider(
|
||||
<DynamicOptionsWidget {...makeProps({ value, onChange, registry: { formContext: { serverDefaults: true } } })} />,
|
||||
{ client: clientWith(list(option("storageclass", [{ value: "standard", default: true }]))) },
|
||||
)
|
||||
await waitFor(() => expect(onChange).toHaveBeenCalledWith("standard"))
|
||||
expect(onChange).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("keeps a value the server prepared, such as an installation default, over the default item", async () => {
|
||||
const onChange = vi.fn()
|
||||
renderWithK8sProvider(
|
||||
<DynamicOptionsWidget {...makeProps({ value: "installed", onChange, registry: { formContext: { serverDefaults: true } } })} />,
|
||||
{ client: clientWith(list(option("storageclass", [{ value: "standard", default: true }, { value: "installed" }]))) },
|
||||
)
|
||||
await screen.findByRole("option", { name: "standard" })
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("leaves the field empty when the form did not start from the server's values", async () => {
|
||||
const onChange = vi.fn()
|
||||
renderWithK8sProvider(
|
||||
<DynamicOptionsWidget {...makeProps({ onChange, registry: { formContext: { serverDefaults: true, autoSelectDefaults: false } } })} />,
|
||||
{ client: clientWith(list(option("storageclass", [{ value: "standard", default: true }, { value: "replicated" }]))) },
|
||||
)
|
||||
await screen.findByRole("option", { name: "standard" })
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole("combobox")).toHaveValue("")
|
||||
})
|
||||
|
||||
it("keeps None as an explicit empty string after clearing installation defaults", async () => {
|
||||
const onChange = vi.fn()
|
||||
function Harness() {
|
||||
const [value, setValue] = useState<unknown>("installed")
|
||||
return <DynamicOptionsWidget {...makeProps({
|
||||
value,
|
||||
onChange: (next: unknown) => { onChange(next); setValue(next) },
|
||||
registry: { formContext: { serverDefaults: true } },
|
||||
})} />
|
||||
}
|
||||
renderWithK8sProvider(<Harness />, {
|
||||
client: clientWith(list(option("storageclass", [{ value: "standard", default: true }]))),
|
||||
})
|
||||
await screen.findByRole("option", { name: "standard" })
|
||||
fireEvent.change(screen.getByRole("combobox"), { target: { value: "" } })
|
||||
expect(onChange.mock.calls).toEqual([[""]])
|
||||
expect(screen.getByRole("combobox")).toHaveValue("")
|
||||
})
|
||||
|
||||
it("auto-selects the server-marked default item exactly once when no value is set", async () => {
|
||||
const onChange = vi.fn()
|
||||
renderWithK8sProvider(
|
||||
|
||||
+10
-4
@@ -42,6 +42,8 @@ export function DynamicOptionsWidget(props: WidgetProps) {
|
||||
]?.source
|
||||
|
||||
const rootFormData = (registry?.formContext as { rootFormData?: unknown })?.rootFormData
|
||||
const serverDefaults = !!registry?.formContext?.serverDefaults
|
||||
const autoSelectDefaults = registry?.formContext?.autoSelectDefaults !== false
|
||||
const { name: source, parameterised } = resolveSource(rawSource, rootFormData)
|
||||
|
||||
// A parameterised source is deliberately absent from the Option list — it
|
||||
@@ -81,14 +83,15 @@ export function DynamicOptionsWidget(props: WidgetProps) {
|
||||
// on initial load. The ref latches after the first auto-default and is never
|
||||
// reset, so deliberately clearing an optional field sticks — re-arming it
|
||||
// here would let the effect immediately re-apply the default and make the
|
||||
// field impossible to clear.
|
||||
// field impossible to clear. A form that did not start from the server's
|
||||
// values leaves an empty field alone, so the API applies its own default.
|
||||
const hasAutoDefaulted = useRef(false)
|
||||
useEffect(() => {
|
||||
if (!hasAutoDefaulted.current && !value && defaultItem && !isLoading) {
|
||||
if (autoSelectDefaults && !hasAutoDefaulted.current && !value && defaultItem && !isLoading) {
|
||||
hasAutoDefaulted.current = true
|
||||
onChange(defaultItem.value)
|
||||
}
|
||||
}, [value, defaultItem, isLoading, onChange])
|
||||
}, [autoSelectDefaults, value, defaultItem, isLoading, onChange])
|
||||
|
||||
const placeholder = isLoading
|
||||
? "Loading..."
|
||||
@@ -106,7 +109,10 @@ export function DynamicOptionsWidget(props: WidgetProps) {
|
||||
<select
|
||||
id={id}
|
||||
value={currentValue}
|
||||
onChange={(e) => onChange(e.target.value || undefined)}
|
||||
onChange={(e) => {
|
||||
hasAutoDefaulted.current = true
|
||||
onChange(serverDefaults ? e.target.value : e.target.value || undefined)
|
||||
}}
|
||||
disabled={disabled || readonly}
|
||||
required={required}
|
||||
className="w-full rounded-lg border border-slate-300 bg-white pl-3 pr-8 py-2 text-sm text-slate-900 outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-400 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { useState } from "react"
|
||||
import { describe, it, expect, vi } from "vitest"
|
||||
import { screen, waitFor } from "@testing-library/react"
|
||||
import type { K8sList } from "@cozystack/k8s-client"
|
||||
import { SchemaForm } from "./SchemaForm.tsx"
|
||||
import { createMockK8sClient } from "../test-utils/mock-k8s-client.ts"
|
||||
import { renderWithK8sProvider } from "../test-utils/render.tsx"
|
||||
|
||||
vi.mock("../lib/tenant-context.tsx", () => ({
|
||||
useTenantContext: () => ({
|
||||
tenants: [],
|
||||
selectedTenant: "root",
|
||||
selectTenant: () => {},
|
||||
tenantNamespace: "tenant-root",
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
}))
|
||||
|
||||
const storageClass = { type: "string", "x-cozystack-options": { source: "storageclass" } }
|
||||
|
||||
const schemas = {
|
||||
field: JSON.stringify({ type: "object", properties: { storageClass } }),
|
||||
dictionaryValue: JSON.stringify({
|
||||
type: "object",
|
||||
properties: { nodeGroups: { type: "object", additionalProperties: { type: "object", properties: { storageClass } } } },
|
||||
}),
|
||||
arrayRow: JSON.stringify({
|
||||
type: "object",
|
||||
properties: { rows: { type: "array", items: { type: "object", properties: { storageClass } } } },
|
||||
}),
|
||||
}
|
||||
|
||||
const options: K8sList<unknown> = {
|
||||
apiVersion: "core.cozystack.io/v1alpha1",
|
||||
kind: "OptionList",
|
||||
metadata: { resourceVersion: "1" },
|
||||
items: [{
|
||||
apiVersion: "core.cozystack.io/v1alpha1",
|
||||
kind: "Option",
|
||||
metadata: { name: "storageclass" },
|
||||
spec: { items: [{ value: "local", default: true }, { value: "replicated" }] },
|
||||
}],
|
||||
}
|
||||
|
||||
function Harness({ schema, initial, autoSelectDefaults }: { schema: string; initial: unknown; autoSelectDefaults?: boolean }) {
|
||||
const [spec, setSpec] = useState<unknown>(initial)
|
||||
return <SchemaForm openAPISchema={schema} formData={spec} onChange={setSpec} defaulting="server" autoSelectDefaults={autoSelectDefaults} />
|
||||
}
|
||||
|
||||
const client = () => createMockK8sClient({
|
||||
lists: [{ apiGroup: "core.cozystack.io", apiVersion: "v1alpha1", plural: "options", namespace: "tenant-root", result: options }],
|
||||
})
|
||||
|
||||
describe("dynamic options in a server-prepared form", () => {
|
||||
it.each([
|
||||
["a field", schemas.field, {}],
|
||||
["a dictionary value", schemas.dictionaryValue, { nodeGroups: { md0: {} } }],
|
||||
["an array row", schemas.arrayRow, { rows: [{}] }],
|
||||
])("selects the default option of an empty value in %s", async (_where, schema, initial) => {
|
||||
renderWithK8sProvider(<Harness schema={schema} initial={initial} />, { client: client() })
|
||||
await waitFor(() => expect(screen.getByRole("combobox")).toHaveValue("local"))
|
||||
})
|
||||
|
||||
it.each([
|
||||
["a field", schemas.field, {}],
|
||||
["a dictionary value", schemas.dictionaryValue, { nodeGroups: { md0: {} } }],
|
||||
["an array row", schemas.arrayRow, { rows: [{}] }],
|
||||
])("leaves an empty value in %s alone when told the form did not start from the server's values", async (_where, schema, initial) => {
|
||||
renderWithK8sProvider(<Harness schema={schema} initial={initial} autoSelectDefaults={false} />, { client: client() })
|
||||
await screen.findByRole("option", { name: "local" })
|
||||
expect(screen.getByRole("combobox")).toHaveValue("")
|
||||
})
|
||||
})
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import { createRef, useState } from "react"
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react"
|
||||
import { SchemaForm, type SchemaFormHandle } from "./SchemaForm.tsx"
|
||||
|
||||
function Harness({ schema, initial }: { schema: unknown; initial: unknown }) {
|
||||
const [spec, setSpec] = useState(initial)
|
||||
return <>
|
||||
<SchemaForm openAPISchema={JSON.stringify(schema)} formData={spec} onChange={setSpec} defaulting="server" />
|
||||
<output data-testid="spec">{JSON.stringify(spec)}</output>
|
||||
</>
|
||||
}
|
||||
const value = () => JSON.parse(screen.getByTestId("spec").textContent ?? "")
|
||||
|
||||
describe("server-prepared form values", () => {
|
||||
it("renders server values without filling schema defaults on mount or edits", () => {
|
||||
render(<Harness schema={{ type: "object", properties: {
|
||||
default: { type: "string", default: "client" },
|
||||
nested: { type: "object", default: {}, properties: { child: { type: "string", default: "client-child" } } },
|
||||
rows: { type: "array", minItems: 1, items: { type: "string", default: "client-row" } },
|
||||
flag: { type: "boolean", default: true },
|
||||
count: { type: "integer", default: 3 },
|
||||
text: { type: "string", default: "client" },
|
||||
nullable: { type: "string", nullable: true, default: "client" },
|
||||
} }} initial={{ default: "server", nested: {}, rows: [], flag: false, count: 0, text: "", nullable: null }} />)
|
||||
expect(screen.getByLabelText("default")).toHaveValue("server")
|
||||
expect(screen.getByLabelText("child")).toHaveValue("")
|
||||
fireEvent.change(screen.getByLabelText("default"), { target: { value: "user" } })
|
||||
expect(value()).toEqual({ default: "user", nested: {}, rows: [], flag: false, count: 0, text: "", nullable: null })
|
||||
})
|
||||
|
||||
it("leaves out a plain string field the user clears, wherever it sits", () => {
|
||||
render(<Harness schema={{ type: "object", properties: {
|
||||
name: { type: "string" },
|
||||
rows: { type: "array", items: { type: "object", properties: { label: { type: "string" } } } },
|
||||
entries: { type: "object", additionalProperties: { type: "object", properties: { note: { type: "string" } } } },
|
||||
} }} initial={{ name: "server", rows: [{ label: "x" }], entries: { a: { note: "y" } } }} />)
|
||||
fireEvent.change(screen.getByLabelText("name"), { target: { value: "" } })
|
||||
fireEvent.change(screen.getByLabelText("label"), { target: { value: "" } })
|
||||
fireEvent.change(screen.getByLabelText("note"), { target: { value: "" } })
|
||||
expect(value()).toEqual({ rows: [{}], entries: { a: {} } })
|
||||
})
|
||||
|
||||
it("does not write a const field or an empty array the schema asks for", () => {
|
||||
render(<Harness schema={{ type: "object", properties: {
|
||||
kind: { type: "string", const: "fixed" },
|
||||
top: { type: "string" },
|
||||
rows: { type: "array", minItems: 1, items: { type: "string" } },
|
||||
} }} initial={{}} />)
|
||||
fireEvent.change(screen.getByLabelText("top"), { target: { value: "user" } })
|
||||
expect(value()).toEqual({ top: "user" })
|
||||
})
|
||||
|
||||
it("writes no const field or empty array into a dictionary value either", () => {
|
||||
render(<Harness schema={{ type: "object", properties: { entries: { type: "object", additionalProperties: {
|
||||
type: "object", properties: {
|
||||
kind: { type: "string", const: "fixed" },
|
||||
list: { type: "array", minItems: 1, items: { type: "string" } },
|
||||
label: { type: "string" },
|
||||
},
|
||||
} } } }} initial={{ entries: { a: {} } }} />)
|
||||
fireEvent.change(screen.getByLabelText("label"), { target: { value: "z" } })
|
||||
expect(value()).toEqual({ entries: { a: { label: "z" } } })
|
||||
})
|
||||
|
||||
it("keeps an emptied sensitive field as an empty string", () => {
|
||||
render(<Harness schema={{ type: "object", properties: { password: { type: "string" } } }} initial={{ password: "secret" }} />)
|
||||
fireEvent.change(screen.getByLabelText("password"), { target: { value: "" } })
|
||||
expect(value()).toEqual({ password: "" })
|
||||
})
|
||||
|
||||
it("lets a nested object be enabled without its defaulted fields, and still requires the others", () => {
|
||||
const schema = JSON.stringify({ type: "object", properties: { autoscaling: {
|
||||
type: "object", default: {}, required: ["enabled", "min", "name"],
|
||||
properties: { enabled: { type: "boolean", default: false }, min: { type: "integer", default: 1 }, name: { type: "string" } },
|
||||
} } })
|
||||
function validate(spec: unknown) {
|
||||
const ref = createRef<SchemaFormHandle>()
|
||||
const view = render(<SchemaForm ref={ref} openAPISchema={schema} formData={spec} onChange={() => {}} defaulting="server" />)
|
||||
let valid: boolean | undefined
|
||||
act(() => { valid = ref.current?.validate() })
|
||||
view.unmount()
|
||||
return valid
|
||||
}
|
||||
expect(validate({ autoscaling: { enabled: true, name: "x" } })).toBe(true)
|
||||
expect(validate({ autoscaling: { enabled: true } })).toBe(false)
|
||||
})
|
||||
|
||||
it("still requires the fields of an array row, because the server does not complete rows", () => {
|
||||
const schema = JSON.stringify({ type: "object", properties: { rows: { type: "array", items: {
|
||||
type: "object", required: ["storage", "name"],
|
||||
properties: { storage: { type: "string", default: "10Gi" }, name: { type: "string" } },
|
||||
} } } })
|
||||
function validate(spec: unknown) {
|
||||
const ref = createRef<SchemaFormHandle>()
|
||||
const view = render(<SchemaForm ref={ref} openAPISchema={schema} formData={spec} onChange={() => {}} defaulting="server" />)
|
||||
let valid: boolean | undefined
|
||||
act(() => { valid = ref.current?.validate() })
|
||||
view.unmount()
|
||||
return valid
|
||||
}
|
||||
expect(validate({ rows: [{ name: "x", storage: "1Gi" }] })).toBe(true)
|
||||
expect(validate({ rows: [{ name: "x" }] })).toBe(false)
|
||||
})
|
||||
|
||||
it("adds an array row without calculating its developer defaults", () => {
|
||||
render(<Harness schema={{ type: "object", properties: { rows: { type: "array", items: {
|
||||
type: "object", properties: { setting: { type: "string", default: "client" } },
|
||||
} } } }} initial={{ rows: [] }} />)
|
||||
fireEvent.click(screen.getByRole("button", { name: /add/i }))
|
||||
expect(screen.getByLabelText("setting")).toHaveValue("")
|
||||
expect(value()).toEqual({ rows: [{}] })
|
||||
})
|
||||
|
||||
it("adds a dictionary entry without calculating its developer defaults", () => {
|
||||
render(<Harness schema={{ type: "object", properties: { entries: { type: "object", additionalProperties: {
|
||||
type: "object", properties: { setting: { type: "string", default: "client" } },
|
||||
} } } }} initial={{ entries: {} }} />)
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter key name..."), { target: { value: "new" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: /add/i }))
|
||||
expect(screen.getByLabelText("setting")).toHaveValue("")
|
||||
expect(value()).toEqual({ entries: { new: {} } })
|
||||
})
|
||||
})
|
||||
+16
-4
@@ -18,6 +18,7 @@ import { AdditionalPropertiesField } from "./AdditionalPropertiesField.tsx"
|
||||
import { FreeformObjectField } from "./FreeformObjectField.tsx"
|
||||
import { ResourceQuotasField } from "./ResourceQuotasField.tsx"
|
||||
import { SourceField } from "./SourceField.tsx"
|
||||
import { serverFormStateBehavior, withoutSchemaDefaults } from "../lib/server-form.ts"
|
||||
import "./schema-form.css"
|
||||
|
||||
/**
|
||||
@@ -215,6 +216,13 @@ interface SchemaFormProps {
|
||||
* flows.
|
||||
*/
|
||||
immutableMode?: "enforce" | "off"
|
||||
defaulting?: "schema" | "server"
|
||||
/**
|
||||
* Whether a dropdown selects its server-marked default when its field is
|
||||
* empty. Turned off when the form could not start from the server's values,
|
||||
* where the API fills an omitted field with the platform's default instead.
|
||||
*/
|
||||
autoSelectDefaults?: boolean
|
||||
}
|
||||
|
||||
export interface SchemaFormHandle {
|
||||
@@ -234,6 +242,8 @@ export const SchemaForm = forwardRef<SchemaFormHandle, SchemaFormProps>(function
|
||||
onChange,
|
||||
children,
|
||||
immutableMode,
|
||||
defaulting = "schema",
|
||||
autoSelectDefaults = true,
|
||||
}: SchemaFormProps, ref) {
|
||||
const formRef = useRef<Form>(null)
|
||||
useImperativeHandle(
|
||||
@@ -256,8 +266,8 @@ export const SchemaForm = forwardRef<SchemaFormHandle, SchemaFormProps>(function
|
||||
}, [openAPISchema])
|
||||
|
||||
const schema = useMemo<RJSFSchema>(
|
||||
() => sanitizeSchema(parsedSchema) as RJSFSchema,
|
||||
[parsedSchema],
|
||||
() => sanitizeSchema(defaulting === "server" ? withoutSchemaDefaults(parsedSchema) : parsedSchema) as RJSFSchema,
|
||||
[parsedSchema, defaulting],
|
||||
)
|
||||
|
||||
const onChangeRef = useRef(onChange)
|
||||
@@ -273,12 +283,13 @@ export const SchemaForm = forwardRef<SchemaFormHandle, SchemaFormProps>(function
|
||||
// getDefaultFormState would re-emit defaults computed from the stale initial
|
||||
// formData and wipe whatever the user already typed.
|
||||
useEffect(() => {
|
||||
if (defaulting === "server") return
|
||||
if (!schema || Object.keys(schema).length === 0) return
|
||||
if (emittedSchemaRef.current === schema) return
|
||||
emittedSchemaRef.current = schema
|
||||
const defaults = getDefaultFormState(validator, schema, formDataRef.current ?? {}, schema)
|
||||
onChangeRef.current(defaults)
|
||||
}, [schema])
|
||||
}, [schema, defaulting])
|
||||
|
||||
const immutablePaths = useMemo<ImmutablePath[]>(
|
||||
() => (immutableMode === "enforce" ? findImmutablePaths(parsedSchema) : []),
|
||||
@@ -352,6 +363,7 @@ export const SchemaForm = forwardRef<SchemaFormHandle, SchemaFormProps>(function
|
||||
schema={schema}
|
||||
uiSchema={uiSchema}
|
||||
formData={formData}
|
||||
experimental_defaultFormStateBehavior={defaulting === "server" ? serverFormStateBehavior : undefined}
|
||||
validator={validator}
|
||||
templates={templatesWithoutSubmit}
|
||||
widgets={customWidgets}
|
||||
@@ -360,7 +372,7 @@ export const SchemaForm = forwardRef<SchemaFormHandle, SchemaFormProps>(function
|
||||
// choice made elsewhere in the form — the VMs of the import source the
|
||||
// user just picked. Handing the whole object down is what lets an
|
||||
// option source name reference a sibling field.
|
||||
formContext={{ rootFormData: formData }}
|
||||
formContext={{ rootFormData: formData, serverDefaults: defaulting === "server", autoSelectDefaults }}
|
||||
onChange={(e) => onChange(e.formData)}
|
||||
liveValidate={false}
|
||||
showErrorList={false}
|
||||
|
||||
+13
@@ -43,6 +43,19 @@ function renderWithLabel(props: WidgetProps) {
|
||||
const TOGGLE_NAME = /toggle credential visibility/i
|
||||
|
||||
describe("SensitiveStringWidget", () => {
|
||||
it("keeps an emptied value as an empty string when the server owns defaults, and drops the key otherwise", async () => {
|
||||
const user = userEvent.setup()
|
||||
const server = vi.fn()
|
||||
const view = renderWithLabel(makeProps({ value: "abc", onChange: server, registry: { formContext: { serverDefaults: true } } as unknown as WidgetProps["registry"] }))
|
||||
await user.clear(screen.getByLabelText("access key"))
|
||||
expect(server).toHaveBeenLastCalledWith("")
|
||||
view.unmount()
|
||||
const schema = vi.fn()
|
||||
renderWithLabel(makeProps({ value: "abc", onChange: schema }))
|
||||
await user.clear(screen.getByLabelText("access key"))
|
||||
expect(schema).toHaveBeenLastCalledWith(undefined)
|
||||
})
|
||||
|
||||
it("renders a real <input> control associated with its label, regardless of state", () => {
|
||||
renderWithLabel(makeProps({ value: "super-secret" }))
|
||||
|
||||
|
||||
+5
-2
@@ -14,6 +14,7 @@ const TOGGLE_CLASS =
|
||||
|
||||
export function SensitiveStringWidget(props: WidgetProps) {
|
||||
const { id, value, onChange, required, disabled, readonly, autofocus, placeholder } = props
|
||||
const serverDefaults = !!props.registry?.formContext?.serverDefaults
|
||||
const [revealed, setRevealed] = useState(false)
|
||||
|
||||
const stringValue = typeof value === "string" ? value : ""
|
||||
@@ -36,9 +37,11 @@ export function SensitiveStringWidget(props: WidgetProps) {
|
||||
onChange={(event) => {
|
||||
// Empty string is coerced to undefined so the surrounding form
|
||||
// drops the key from the spec entirely on clear, matching the
|
||||
// convention used by the other custom widgets in this folder.
|
||||
// convention used by the other custom widgets in this folder. When
|
||||
// the server owns defaults an omitted key gets its default back, so
|
||||
// the empty string is kept as the user's explicit value.
|
||||
const next = event.target.value
|
||||
onChange(next === "" ? undefined : next)
|
||||
onChange(next === "" && !serverDefaults ? undefined : next)
|
||||
}}
|
||||
className={INPUT_CLASS}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect } from "vitest"
|
||||
import { withoutSchemaDefaults } from "./server-form.ts"
|
||||
|
||||
describe("server form schema", () => {
|
||||
it("removes defaults at every form depth while preserving properties and the original schema", () => {
|
||||
const leaf = { type: "string", default: "client" }
|
||||
const original = { type: "object", default: {}, properties: {
|
||||
default: leaf,
|
||||
rows: { type: "array", items: leaf },
|
||||
map: { type: "object", additionalProperties: leaf },
|
||||
} }
|
||||
expect(withoutSchemaDefaults(original)).toEqual({ type: "object", properties: {
|
||||
default: { type: "string" },
|
||||
rows: { type: "array", items: { type: "string" } },
|
||||
map: { type: "object", additionalProperties: { type: "string" } },
|
||||
} })
|
||||
expect(leaf.default).toBe("client")
|
||||
expect(original.default).toEqual({})
|
||||
})
|
||||
|
||||
it("does not require a field that has a default, because the server fills it", () => {
|
||||
const original = { type: "object", required: ["enabled", "name"], properties: {
|
||||
enabled: { type: "boolean", default: false },
|
||||
name: { type: "string" },
|
||||
nested: { type: "object", required: ["size"], properties: { size: { type: "integer", default: 1 } } },
|
||||
} }
|
||||
expect(withoutSchemaDefaults(original)).toEqual({ type: "object", required: ["name"], properties: {
|
||||
enabled: { type: "boolean" },
|
||||
name: { type: "string" },
|
||||
nested: { type: "object", properties: { size: { type: "integer" } } },
|
||||
} })
|
||||
expect(original.required).toEqual(["enabled", "name"])
|
||||
})
|
||||
|
||||
it("keeps the requirements of array rows and dictionary values, which the server does not complete", () => {
|
||||
const row = { type: "object", required: ["storage", "name"], properties: {
|
||||
storage: { type: "string", default: "10Gi" },
|
||||
name: { type: "string" },
|
||||
} }
|
||||
const kept = { type: "object", required: ["storage", "name"], properties: {
|
||||
storage: { type: "string" },
|
||||
name: { type: "string" },
|
||||
} }
|
||||
expect(withoutSchemaDefaults({ type: "object", properties: {
|
||||
rows: { type: "array", items: row },
|
||||
map: { type: "object", additionalProperties: row },
|
||||
nested: { type: "object", properties: { rows: { type: "array", items: row } } },
|
||||
} })).toEqual({ type: "object", properties: {
|
||||
rows: { type: "array", items: kept },
|
||||
map: { type: "object", additionalProperties: kept },
|
||||
nested: { type: "object", properties: { rows: { type: "array", items: kept } } },
|
||||
} })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Experimental_DefaultFormStateBehavior } from "@rjsf/utils"
|
||||
|
||||
export function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function withoutSchemaDefaults(schema: unknown, inReplaced = false): unknown {
|
||||
if (!isObject(schema)) return schema
|
||||
const result = { ...schema }
|
||||
delete result.default
|
||||
// Inside an object the server fills a field that has a default, so the form need
|
||||
// not require it. An array row or a dictionary value is stored as typed, with no
|
||||
// defaults added, so its requirements stay.
|
||||
if (!inReplaced && isObject(result.properties) && Array.isArray(result.required)) {
|
||||
const properties = result.properties
|
||||
const required = result.required.filter((name) => !(isObject(properties[name]) && "default" in properties[name]))
|
||||
if (required.length > 0) result.required = required
|
||||
else delete result.required
|
||||
}
|
||||
for (const key of ["properties", "patternProperties", "definitions", "$defs", "dependentSchemas"]) {
|
||||
if (isObject(result[key])) {
|
||||
result[key] = Object.fromEntries(Object.entries(result[key]).map(
|
||||
([name, child]) => [name, withoutSchemaDefaults(child, inReplaced)],
|
||||
))
|
||||
}
|
||||
}
|
||||
for (const key of ["items", "additionalProperties", "additionalItems"]) {
|
||||
if (isObject(result[key])) result[key] = withoutSchemaDefaults(result[key], true)
|
||||
else if (Array.isArray(result[key])) result[key] = result[key].map((child) => withoutSchemaDefaults(child, true))
|
||||
}
|
||||
if (Array.isArray(result.prefixItems)) result.prefixItems = result.prefixItems.map((child) => withoutSchemaDefaults(child, true))
|
||||
for (const key of ["not", "if", "then", "else"]) {
|
||||
if (isObject(result[key])) result[key] = withoutSchemaDefaults(result[key], inReplaced)
|
||||
}
|
||||
for (const key of ["oneOf", "anyOf", "allOf"]) {
|
||||
if (Array.isArray(result[key])) result[key] = result[key].map((child) => withoutSchemaDefaults(child, inReplaced))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export const serverFormStateBehavior: Experimental_DefaultFormStateBehavior = {
|
||||
emptyObjectFields: "skipDefaults",
|
||||
arrayMinItems: { populate: "never" },
|
||||
constAsDefaults: "never",
|
||||
}
|
||||
+7
-2
@@ -6,6 +6,7 @@ import { MemoryRouter } from "react-router"
|
||||
const h = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
client: { dryRunCreate: vi.fn() },
|
||||
ad: {
|
||||
spec: {
|
||||
application: {
|
||||
@@ -38,6 +39,7 @@ vi.mock("../lib/app-definitions.ts", () => ({
|
||||
vi.mock("@cozystack/k8s-client", () => ({
|
||||
useK8sCreate: () => ({ mutateAsync: h.create, isPending: false }),
|
||||
useK8sUpdate: () => ({ mutateAsync: h.update, isPending: false }),
|
||||
useK8sClient: () => h.client,
|
||||
K8sApiError: class extends Error {},
|
||||
}))
|
||||
vi.mock("../components/YamlEditor.tsx", () => ({
|
||||
@@ -51,12 +53,13 @@ describe("ApplicationOrderPage free-form objects", () => {
|
||||
beforeEach(() => {
|
||||
h.create.mockReset().mockResolvedValue({})
|
||||
h.update.mockReset().mockResolvedValue({})
|
||||
h.client.dryRunCreate.mockReset().mockImplementation(async (_g, _v, _p, body: unknown) => body)
|
||||
})
|
||||
|
||||
it("sends nested objects on create after a form/YAML round trip", async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<MemoryRouter><ApplicationOrderPage appNameOverride="nats" /></MemoryRouter>)
|
||||
await user.type(screen.getByPlaceholderText("nats"), "demo")
|
||||
await user.type(await screen.findByPlaceholderText("nats"), "demo")
|
||||
fireEvent.change(screen.getByLabelText("merge"), { target: { value: JSON.stringify(merge) } })
|
||||
fireEvent.change(screen.getByLabelText("resolver"), { target: { value: '{"type":"full"}' } })
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
@@ -81,7 +84,9 @@ describe("ApplicationOrderPage free-form objects", () => {
|
||||
it.each([false, true])("blocks invalid JSON from the API in edit mode %s", async (edit) => {
|
||||
const user = userEvent.setup()
|
||||
render(<MemoryRouter><ApplicationOrderPage appNameOverride="nats" editMode={edit ? { name: "demo", initialSpec: { config: { merge } } } : undefined} /></MemoryRouter>)
|
||||
if (!edit) await user.type(screen.getByPlaceholderText("nats"), "demo")
|
||||
if (!edit) {
|
||||
await user.type(await screen.findByPlaceholderText("nats"), "demo")
|
||||
}
|
||||
fireEvent.change(screen.getByLabelText("merge"), { target: { value: "{" } })
|
||||
await user.click(screen.getByRole("button", { name: edit ? /^save$/i : /^deploy$/i }))
|
||||
expect(h.create).not.toHaveBeenCalled()
|
||||
|
||||
+347
-70
@@ -1,105 +1,382 @@
|
||||
import { forwardRef, useImperativeHandle } from "react"
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest"
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react"
|
||||
import userEvent from "@testing-library/user-event"
|
||||
import { MemoryRouter } from "react-router"
|
||||
import yaml from "js-yaml"
|
||||
import type { ApplicationInstance } from "@cozystack/types"
|
||||
|
||||
// The Deploy button bypasses RJSF; in form mode the gate calls
|
||||
// SchemaForm.validate(), in YAML mode it is skipped. Mock SchemaForm so the
|
||||
// test drives that boolean directly, and YamlEditor so Monaco stays out.
|
||||
const h = vi.hoisted(() => ({
|
||||
validateReturn: true,
|
||||
createMutateAsync: vi.fn(),
|
||||
updateMutateAsync: vi.fn(),
|
||||
ad: {
|
||||
spec: {
|
||||
application: {
|
||||
kind: "VirtualMachine",
|
||||
plural: "virtualmachines",
|
||||
singular: "virtualmachine",
|
||||
openAPISchema: JSON.stringify({ type: "object", properties: {} }),
|
||||
},
|
||||
dashboard: {},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("../lib/tenant-context.tsx", () => ({
|
||||
useTenantContext: () => ({ tenantNamespace: "tenant-test" }),
|
||||
validate: true, create: vi.fn(), update: vi.fn(), client: { dryRunCreate: vi.fn() },
|
||||
tenant: { ns: "tenant-test" as string | null, loading: false },
|
||||
ad: { spec: { application: { kind: "Widget", plural: "widgets", singular: "widget",
|
||||
openAPISchema: JSON.stringify({ type: "object", properties: { setting: { type: "string", default: "client-schema" } } }),
|
||||
}, dashboard: {} } },
|
||||
}))
|
||||
vi.mock("../lib/tenant-context.tsx", () => ({ useTenantContext: () => ({ tenantNamespace: h.tenant.ns, isLoading: h.tenant.loading }) }))
|
||||
vi.mock("../lib/app-definitions.ts", () => ({
|
||||
useApplicationDefinition: () => ({ data: h.ad, isLoading: false, error: null }),
|
||||
appDisplayName: () => "Virtual Machine",
|
||||
iconDataUrl: () => null,
|
||||
appDisplayName: () => "Widget", iconDataUrl: () => null,
|
||||
}))
|
||||
vi.mock("@cozystack/k8s-client", () => ({
|
||||
useK8sCreate: () => ({ mutateAsync: h.createMutateAsync, isPending: false }),
|
||||
useK8sUpdate: () => ({ mutateAsync: h.updateMutateAsync, isPending: false }),
|
||||
K8sApiError: class K8sApiError extends Error {},
|
||||
useK8sClient: () => h.client,
|
||||
useK8sCreate: () => ({ mutateAsync: h.create, isPending: false }),
|
||||
useK8sUpdate: () => ({ mutateAsync: h.update, isPending: false }),
|
||||
K8sApiError: class extends Error {},
|
||||
}))
|
||||
vi.mock("../components/SchemaForm.tsx", () => ({
|
||||
SchemaForm: forwardRef<{ validate: () => boolean }, Record<string, unknown>>(
|
||||
function MockSchemaForm(_props, ref) {
|
||||
useImperativeHandle(ref, () => ({ validate: () => h.validateReturn }))
|
||||
return null
|
||||
SchemaForm: forwardRef<{ validate: () => boolean }, { formData: unknown; onChange: (value: unknown) => void; defaulting: string; autoSelectDefaults?: boolean }>(
|
||||
function MockSchemaForm(props, ref) {
|
||||
useImperativeHandle(ref, () => ({ validate: () => h.validate }))
|
||||
return <textarea aria-label="Spec" data-defaulting={props.defaulting} data-auto-select={String(props.autoSelectDefaults)} value={JSON.stringify(props.formData)} onChange={(e) => props.onChange(JSON.parse(e.target.value))} />
|
||||
},
|
||||
),
|
||||
}))
|
||||
vi.mock("../components/YamlEditor.tsx", () => ({
|
||||
YamlEditor: ({ value }: { value: string }) => <textarea data-testid="yaml" readOnly value={value} />,
|
||||
YamlEditor: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => <textarea data-testid="yaml" value={value} onChange={(e) => onChange(e.target.value)} />,
|
||||
}))
|
||||
|
||||
const { ApplicationOrderPage } = await import("./ApplicationOrderPage.tsx")
|
||||
|
||||
function renderPage() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<ApplicationOrderPage appNameOverride="virtualmachine" />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
function pageElement(route = "/") { return <MemoryRouter initialEntries={[route]}><ApplicationOrderPage appNameOverride="widget" /></MemoryRouter> }
|
||||
function renderPage(route = "/") { return render(pageElement(route)) }
|
||||
function editSpec(value: unknown) { fireEvent.change(screen.getByLabelText("Spec"), { target: { value: JSON.stringify(value) } }) }
|
||||
const deploy = () => screen.getByRole("button", { name: /^deploy$/i })
|
||||
function deferred() {
|
||||
let resolve!: (value: ApplicationInstance) => void
|
||||
let reject!: (reason: Error) => void
|
||||
const promise = new Promise<ApplicationInstance>((done, fail) => { resolve = done; reject = fail })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
function previewBody(call = 0): ApplicationInstance { return h.client.dryRunCreate.mock.calls[call][3] as ApplicationInstance }
|
||||
|
||||
describe("ApplicationOrderPage submit validation gate", () => {
|
||||
describe("ApplicationOrderPage server preview", () => {
|
||||
beforeEach(() => {
|
||||
h.createMutateAsync.mockReset()
|
||||
h.createMutateAsync.mockResolvedValue({})
|
||||
h.updateMutateAsync.mockReset()
|
||||
h.updateMutateAsync.mockResolvedValue({})
|
||||
h.validateReturn = true
|
||||
h.create.mockReset().mockResolvedValue({})
|
||||
h.update.mockReset().mockResolvedValue({})
|
||||
h.client.dryRunCreate.mockReset().mockImplementation(async (_g, _v, _p, body: ApplicationInstance) => body)
|
||||
h.validate = true
|
||||
h.tenant.ns = "tenant-test"
|
||||
h.tenant.loading = false
|
||||
})
|
||||
|
||||
it("does not POST in form mode when the form fails RJSF validation", async () => {
|
||||
h.validateReturn = false
|
||||
const user = userEvent.setup()
|
||||
it("asks the server once when the page opens and starts the form from the answer", async () => {
|
||||
const pending = deferred()
|
||||
h.client.dryRunCreate.mockReturnValue(pending.promise)
|
||||
renderPage()
|
||||
|
||||
await user.type(screen.getByRole("textbox"), "demo-vm")
|
||||
await user.click(screen.getByRole("button", { name: /^deploy$/i }))
|
||||
|
||||
expect(h.createMutateAsync).not.toHaveBeenCalled()
|
||||
expect(h.client.dryRunCreate).toHaveBeenCalledOnce()
|
||||
expect(h.client.dryRunCreate.mock.calls[0].slice(0, 3)).toEqual(["apps.cozystack.io", "v1alpha1", "widgets"])
|
||||
expect(previewBody()).toMatchObject({ metadata: { name: "preview", namespace: "tenant-test" }, spec: {} })
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Loading initial settings")
|
||||
expect(screen.queryByLabelText("Spec")).not.toBeInTheDocument()
|
||||
expect(deploy()).toBeDisabled()
|
||||
expect(screen.getByRole("button", { name: /^form$/i })).toBeDisabled()
|
||||
expect(screen.getByRole("button", { name: /^yaml$/i })).toBeDisabled()
|
||||
await act(async () => pending.resolve({ ...previewBody(), spec: { setting: "from-server" } }))
|
||||
expect(await screen.findByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "from-server" }))
|
||||
expect(deploy()).toBeEnabled()
|
||||
expect(h.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("POSTs in form mode when the form passes validation", async () => {
|
||||
h.validateReturn = true
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
|
||||
await user.type(screen.getByRole("textbox"), "demo-vm")
|
||||
await user.click(screen.getByRole("button", { name: /^deploy$/i }))
|
||||
|
||||
expect(h.createMutateAsync).toHaveBeenCalledTimes(1)
|
||||
it("previews under the name the user came in with", async () => {
|
||||
renderPage("/?name=demo")
|
||||
await screen.findByLabelText("Spec")
|
||||
expect(previewBody().metadata.name).toBe("demo")
|
||||
})
|
||||
|
||||
it("skips the gate in YAML mode even when validation would fail", async () => {
|
||||
// In YAML mode the spec is hand-authored, so the gate must not block it.
|
||||
h.validateReturn = false
|
||||
it("sends no further previews while the user edits", async () => {
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await user.type(await screen.findByPlaceholderText("widget"), "demo")
|
||||
editSpec({ setting: "user" })
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
await user.click(screen.getByRole("button", { name: /^form$/i }))
|
||||
expect(h.client.dryRunCreate).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
await user.type(screen.getByRole("textbox"), "demo-vm")
|
||||
await user.click(screen.getByRole("button", { name: /yaml/i }))
|
||||
await user.click(screen.getByRole("button", { name: /^deploy$/i }))
|
||||
it("submits the displayed spec unchanged through form and YAML", async () => {
|
||||
const prepared = { setting: "from-server", nested: {}, list: [], enabled: false, count: 0, text: "", nullable: null }
|
||||
h.client.dryRunCreate.mockImplementation(async (_g, _v, _p, body: ApplicationInstance) => ({ ...body, spec: prepared }))
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await user.type(await screen.findByPlaceholderText("widget"), "demo")
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
const editor = await screen.findByTestId("yaml")
|
||||
expect((yaml.load((editor as HTMLTextAreaElement).value) as { spec: unknown }).spec).toEqual(prepared)
|
||||
await user.click(screen.getByRole("button", { name: /^form$/i }))
|
||||
await user.click(deploy())
|
||||
expect(h.create).toHaveBeenCalledOnce()
|
||||
expect(h.create.mock.calls[0][0]).toMatchObject({ metadata: { name: "demo" }, spec: prepared })
|
||||
})
|
||||
|
||||
expect(h.createMutateAsync).toHaveBeenCalledTimes(1)
|
||||
it("opens the form with a notice when the preview fails, and deploy still works", async () => {
|
||||
h.client.dryRunCreate.mockRejectedValueOnce(new Error("webhook does not support dry run"))
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("webhook does not support dry run")
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue("{}")
|
||||
await user.type(screen.getByPlaceholderText("widget"), "demo")
|
||||
editSpec({ setting: "user" })
|
||||
await user.click(deploy())
|
||||
expect(h.create.mock.calls[0][0]).toMatchObject({ metadata: { name: "demo" }, spec: { setting: "user" } })
|
||||
})
|
||||
|
||||
it("lets the form pick option defaults only when it started from the server's values", async () => {
|
||||
h.client.dryRunCreate.mockRejectedValueOnce(new Error("rejected"))
|
||||
const user = userEvent.setup()
|
||||
const view = renderPage()
|
||||
await screen.findByRole("alert")
|
||||
expect(screen.getByLabelText("Spec")).toHaveAttribute("data-auto-select", "false")
|
||||
await user.click(screen.getByRole("button", { name: /retry/i }))
|
||||
expect(await screen.findByLabelText("Spec")).toHaveAttribute("data-auto-select", "true")
|
||||
view.unmount()
|
||||
renderPage()
|
||||
expect(await screen.findByLabelText("Spec")).toHaveAttribute("data-auto-select", "true")
|
||||
})
|
||||
|
||||
it("gives up on a preview that hangs and opens the form", async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
h.client.dryRunCreate.mockReturnValue(new Promise(() => {}))
|
||||
renderPage()
|
||||
expect(screen.queryByLabelText("Spec")).not.toBeInTheDocument()
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(8000) })
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("timed out")
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue("{}")
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it("treats a non-object answer as a failed preview", async () => {
|
||||
h.client.dryRunCreate.mockImplementation(async (_g, _v, _p, body: ApplicationInstance) => ({ ...body, spec: [] }))
|
||||
renderPage()
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("non-object")
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue("{}")
|
||||
})
|
||||
|
||||
it("shows the form without a preview when there is no tenant", () => {
|
||||
h.tenant.ns = null
|
||||
renderPage()
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue("{}")
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument()
|
||||
expect(deploy()).toBeDisabled()
|
||||
expect(h.client.dryRunCreate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("waits for the tenant list, then sends one preview", async () => {
|
||||
h.tenant.ns = null
|
||||
h.tenant.loading = true
|
||||
const view = renderPage()
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Loading initial settings")
|
||||
expect(h.client.dryRunCreate).not.toHaveBeenCalled()
|
||||
h.tenant.ns = "tenant-test"
|
||||
h.tenant.loading = false
|
||||
view.rerender(pageElement())
|
||||
expect(await screen.findByLabelText("Spec")).toBeInTheDocument()
|
||||
expect(h.client.dryRunCreate).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it("keeps what the user typed when the tenant is switched", async () => {
|
||||
const view = renderPage()
|
||||
await screen.findByLabelText("Spec")
|
||||
editSpec({ setting: "user" })
|
||||
h.tenant.ns = "tenant-other"
|
||||
view.rerender(pageElement())
|
||||
await act(async () => {})
|
||||
expect(h.client.dryRunCreate).toHaveBeenCalledOnce()
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "user" }))
|
||||
})
|
||||
|
||||
it("drops a preview answer that arrives after the tenant changed", async () => {
|
||||
const first = deferred()
|
||||
const second = deferred()
|
||||
h.client.dryRunCreate.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
|
||||
const view = renderPage()
|
||||
h.tenant.ns = "tenant-other"
|
||||
view.rerender(pageElement())
|
||||
expect(h.client.dryRunCreate).toHaveBeenCalledTimes(2)
|
||||
await act(async () => first.resolve({ ...previewBody(0), spec: { setting: "stale" } }))
|
||||
expect(screen.queryByLabelText("Spec")).not.toBeInTheDocument()
|
||||
await act(async () => second.resolve({ ...previewBody(1), spec: { setting: "current" } }))
|
||||
expect(await screen.findByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "current" }))
|
||||
})
|
||||
|
||||
it("drops a failure that arrives after the tenant changed", async () => {
|
||||
const first = deferred()
|
||||
const second = deferred()
|
||||
h.client.dryRunCreate.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
|
||||
const view = renderPage()
|
||||
h.tenant.ns = "tenant-other"
|
||||
view.rerender(pageElement())
|
||||
await act(async () => first.reject(new Error("stale failure")))
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument()
|
||||
expect(screen.getByRole("status")).toBeInTheDocument()
|
||||
await act(async () => second.resolve({ ...previewBody(1), spec: { setting: "current" } }))
|
||||
expect(await screen.findByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "current" }))
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("starts a new preview when the application kind changes back while another is pending", async () => {
|
||||
const widgets = h.ad
|
||||
const view = renderPage()
|
||||
await screen.findByLabelText("Spec")
|
||||
h.client.dryRunCreate.mockReturnValueOnce(deferred().promise)
|
||||
try {
|
||||
h.ad = { spec: { ...widgets.spec, application: { ...widgets.spec.application, plural: "gadgets" } } }
|
||||
view.rerender(pageElement())
|
||||
expect(screen.getByRole("status")).toBeInTheDocument()
|
||||
h.ad = widgets
|
||||
view.rerender(pageElement())
|
||||
expect(await screen.findByLabelText("Spec")).toBeInTheDocument()
|
||||
expect(h.client.dryRunCreate).toHaveBeenCalledTimes(3)
|
||||
expect(h.client.dryRunCreate.mock.calls[2][2]).toBe("widgets")
|
||||
} finally {
|
||||
h.ad = widgets
|
||||
}
|
||||
})
|
||||
|
||||
it("retries with the edits made after the failure", async () => {
|
||||
h.client.dryRunCreate.mockRejectedValueOnce(new Error("rejected"))
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await screen.findByRole("alert")
|
||||
editSpec({ setting: "user", extra: "keep" })
|
||||
h.client.dryRunCreate.mockImplementationOnce(async (_g, _v, _p, body: ApplicationInstance) => ({ ...body, spec: { platform: "set", ...(body.spec as object) } }))
|
||||
await user.click(screen.getByRole("button", { name: /retry/i }))
|
||||
expect(await screen.findByLabelText("Spec")).toHaveValue(JSON.stringify({ platform: "set", setting: "user", extra: "keep" }))
|
||||
expect(previewBody(1).spec).toEqual({ setting: "user", extra: "keep" })
|
||||
})
|
||||
|
||||
it("does not carry a retry draft into another application kind", async () => {
|
||||
const widgets = h.ad
|
||||
h.client.dryRunCreate.mockRejectedValueOnce(new Error("rejected"))
|
||||
const user = userEvent.setup()
|
||||
const view = renderPage()
|
||||
await screen.findByRole("alert")
|
||||
editSpec({ setting: "user" })
|
||||
await user.click(screen.getByRole("button", { name: /retry/i }))
|
||||
await screen.findByLabelText("Spec")
|
||||
try {
|
||||
h.ad = { spec: { ...widgets.spec, application: { ...widgets.spec.application, plural: "gadgets" } } }
|
||||
view.rerender(pageElement())
|
||||
await screen.findByLabelText("Spec")
|
||||
expect(h.client.dryRunCreate.mock.calls[2][2]).toBe("gadgets")
|
||||
expect(previewBody(2).spec).toEqual({})
|
||||
} finally {
|
||||
h.ad = widgets
|
||||
}
|
||||
})
|
||||
|
||||
it("offers Retry in the form only, where the draft is the form's", async () => {
|
||||
h.client.dryRunCreate.mockRejectedValueOnce(new Error("rejected"))
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await screen.findByRole("alert")
|
||||
expect(screen.getByRole("button", { name: /retry/i })).toBeInTheDocument()
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
expect(screen.getByRole("alert")).toBeInTheDocument()
|
||||
expect(screen.queryByRole("button", { name: /retry/i })).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole("button", { name: /^form$/i }))
|
||||
expect(screen.getByRole("button", { name: /retry/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("retries on request under the name typed meanwhile", async () => {
|
||||
h.client.dryRunCreate.mockRejectedValueOnce(new Error("name rejected"))
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await screen.findByRole("alert")
|
||||
await user.type(screen.getByPlaceholderText("widget"), "demo")
|
||||
h.client.dryRunCreate.mockImplementationOnce(async (_g, _v, _p, body: ApplicationInstance) => ({ ...body, spec: { setting: "from-server" } }))
|
||||
await user.click(screen.getByRole("button", { name: /retry/i }))
|
||||
expect(await screen.findByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "from-server" }))
|
||||
expect(previewBody(1).metadata.name).toBe("demo")
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument()
|
||||
expect(h.client.dryRunCreate).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it("leaves malformed YAML editable and does not send it", async () => {
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await screen.findByLabelText("Spec")
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
fireEvent.change(await screen.findByTestId("yaml"), { target: { value: "spec: [" } })
|
||||
await user.click(deploy())
|
||||
expect(h.create).not.toHaveBeenCalled()
|
||||
expect(document.querySelector(".bg-red-50")).not.toBeNull()
|
||||
fireEvent.change(screen.getByTestId("yaml"), { target: { value: yaml.dump({ metadata: { name: "demo" }, spec: { setting: "user" } }) } })
|
||||
expect(document.querySelector(".bg-red-50")).toBeNull()
|
||||
await user.click(deploy())
|
||||
expect(h.create.mock.calls[0][0]).toMatchObject({ metadata: { name: "demo" }, spec: { setting: "user" } })
|
||||
})
|
||||
|
||||
it("adopts the name and spec edited in YAML when going back to the form", async () => {
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await screen.findByLabelText("Spec")
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
fireEvent.change(await screen.findByTestId("yaml"), { target: { value: yaml.dump({ metadata: { name: "renamed" }, spec: { setting: "edited-in-yaml" } }) } })
|
||||
await user.click(screen.getByRole("button", { name: /^form$/i }))
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "edited-in-yaml" }))
|
||||
expect(screen.getByPlaceholderText("widget")).toHaveValue("renamed")
|
||||
await user.click(deploy())
|
||||
expect(h.create.mock.calls[0][0]).toMatchObject({ metadata: { name: "renamed" }, spec: { setting: "edited-in-yaml" } })
|
||||
})
|
||||
|
||||
it("returns to the form with the new kind's values when the application kind changes in YAML", async () => {
|
||||
const widgets = h.ad
|
||||
const user = userEvent.setup()
|
||||
const view = renderPage()
|
||||
await screen.findByLabelText("Spec")
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
try {
|
||||
h.client.dryRunCreate.mockImplementationOnce(async (_g, _v, _p, body: ApplicationInstance) => ({ ...body, spec: { setting: "gadget" } }))
|
||||
h.ad = { spec: { ...widgets.spec, application: { ...widgets.spec.application, plural: "gadgets" } } }
|
||||
view.rerender(pageElement())
|
||||
expect(await screen.findByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "gadget" }))
|
||||
expect(screen.queryByTestId("yaml")).not.toBeInTheDocument()
|
||||
await user.type(screen.getByPlaceholderText("widget"), "demo")
|
||||
await user.click(deploy())
|
||||
expect(h.create.mock.calls[0][0]).toMatchObject({ metadata: { name: "demo" }, spec: { setting: "gadget" } })
|
||||
} finally {
|
||||
h.ad = widgets
|
||||
}
|
||||
})
|
||||
|
||||
it("opens the new kind with an empty form when its preview fails", async () => {
|
||||
const widgets = h.ad
|
||||
const view = renderPage()
|
||||
await screen.findByLabelText("Spec")
|
||||
editSpec({ setting: "typed for the first kind" })
|
||||
try {
|
||||
h.client.dryRunCreate.mockRejectedValueOnce(new Error("rejected"))
|
||||
h.ad = { spec: { ...widgets.spec, application: { ...widgets.spec.application, plural: "gadgets" } } }
|
||||
view.rerender(pageElement())
|
||||
expect(await screen.findByRole("alert")).toBeInTheDocument()
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue("{}")
|
||||
} finally {
|
||||
h.ad = widgets
|
||||
}
|
||||
})
|
||||
|
||||
it("keeps form validation after a successful preview", async () => {
|
||||
h.validate = false
|
||||
const user = userEvent.setup()
|
||||
renderPage()
|
||||
await user.type(await screen.findByPlaceholderText("widget"), "demo")
|
||||
await user.click(deploy())
|
||||
expect(h.create).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole("button", { name: /^yaml$/i }))
|
||||
await user.click(deploy())
|
||||
expect(h.create).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it("edits saved values without a creation preview", async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<MemoryRouter><ApplicationOrderPage appNameOverride="widget" editMode={{ name: "existing", initialSpec: { setting: "saved" } }} /></MemoryRouter>)
|
||||
expect(screen.getByLabelText("Spec")).toHaveValue(JSON.stringify({ setting: "saved" }))
|
||||
expect(screen.getByLabelText("Spec")).toHaveAttribute("data-defaulting", "server")
|
||||
expect(screen.getByLabelText("Spec")).toHaveAttribute("data-auto-select", "true")
|
||||
await user.click(screen.getByRole("button", { name: /^save$/i }))
|
||||
expect(h.update).toHaveBeenCalledOnce()
|
||||
expect(h.client.dryRunCreate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+120
-25
@@ -3,7 +3,7 @@ import { useNavigate, useParams, useSearchParams } from "react-router"
|
||||
import { ChevronLeft, FileCode, FormInput } from "lucide-react"
|
||||
import yaml from "js-yaml"
|
||||
import { Button, Spinner, cn } from "@cozystack/ui"
|
||||
import { useK8sCreate, useK8sUpdate, K8sApiError } from "@cozystack/k8s-client"
|
||||
import { useK8sClient, useK8sCreate, useK8sUpdate, K8sApiError } from "@cozystack/k8s-client"
|
||||
import { APPS_GROUP, APPS_VERSION } from "@cozystack/types"
|
||||
import {
|
||||
useApplicationDefinition,
|
||||
@@ -14,6 +14,7 @@ import { useTenantContext } from "../lib/tenant-context.tsx"
|
||||
import { useResourceBasePath } from "../lib/portal.ts"
|
||||
import { composeResource } from "../lib/app-resource.ts"
|
||||
import { prepareUpdateSpec } from "../lib/prepare-update.ts"
|
||||
import { isObject } from "../lib/server-form.ts"
|
||||
import { SchemaForm, type SchemaFormHandle } from "../components/SchemaForm.tsx"
|
||||
|
||||
// Lazy-load the YAML editor so monaco and its workers are code-split into their
|
||||
@@ -24,6 +25,15 @@ const YamlEditor = lazy(() =>
|
||||
|
||||
type Mode = "form" | "yaml"
|
||||
|
||||
type Preview = { status: "loading" } | { status: "ready" } | { status: "failed"; error: string }
|
||||
|
||||
// The preview only has to pass the API's name checks, so it uses a short plain
|
||||
// name unless the user came in with one.
|
||||
const PREVIEW_NAME = "preview"
|
||||
// Cap for a preview that gets no answer at all, such as a hanging admission
|
||||
// webhook. An error response opens the form at once and does not wait for it.
|
||||
const PREVIEW_TIMEOUT_MS = 8000
|
||||
|
||||
interface ApplicationOrderPageProps {
|
||||
/** When provided, the page pre-fills the form with this spec and PUTs on save. */
|
||||
editMode?: { name: string; initialSpec: unknown }
|
||||
@@ -38,10 +48,11 @@ export function ApplicationOrderPage({
|
||||
const routeParams = useParams<{ appName: string }>()
|
||||
const appName = appNameOverride ?? routeParams.appName
|
||||
const { data: ad, isLoading, error } = useApplicationDefinition(appName)
|
||||
const { tenantNamespace } = useTenantContext()
|
||||
const { tenantNamespace, isLoading: tenantLoading } = useTenantContext()
|
||||
const [searchParams] = useSearchParams()
|
||||
const navigate = useNavigate()
|
||||
const basePath = useResourceBasePath()
|
||||
const client = useK8sClient()
|
||||
|
||||
const [name, setName] = useState(editMode?.name ?? searchParams.get("name") ?? "")
|
||||
const [spec, setSpec] = useState<unknown>(editMode?.initialSpec ?? {})
|
||||
@@ -65,6 +76,85 @@ export function ApplicationOrderPage({
|
||||
}, [editMode])
|
||||
|
||||
const plural = ad?.spec?.application.plural ?? ""
|
||||
const isEditing = !!editMode
|
||||
const [preview, setPreview] = useState<Preview>({ status: "loading" })
|
||||
const [previewName, setPreviewName] = useState(searchParams.get("name") ?? "")
|
||||
const [previewSpec, setPreviewSpec] = useState<Record<string, unknown>>({})
|
||||
const [previewRun, setPreviewRun] = useState(0)
|
||||
const [loadedPlural, setLoadedPlural] = useState(plural)
|
||||
if (!isEditing && plural && loadedPlural !== plural) {
|
||||
setLoadedPlural(plural)
|
||||
setSpec({})
|
||||
setPreviewSpec({})
|
||||
setPreview({ status: "loading" })
|
||||
setMode("form")
|
||||
setYamlText("")
|
||||
}
|
||||
// Without a tenant the preview cannot start, so only a tenant list that is still
|
||||
// loading keeps the form waiting.
|
||||
const previewPending = !isEditing && preview.status === "loading" && (!!tenantNamespace || tenantLoading)
|
||||
|
||||
const draft = useMemo(() => {
|
||||
try {
|
||||
let draftName = name
|
||||
let draftSpec = spec
|
||||
let document: Record<string, unknown> | null = null
|
||||
if (mode === "yaml") {
|
||||
const parsed = yaml.load(yamlText)
|
||||
if (!isObject(parsed)) throw new Error("Application YAML must be an object")
|
||||
document = parsed
|
||||
if (isObject(parsed.metadata) && typeof parsed.metadata.name === "string") draftName = parsed.metadata.name
|
||||
draftSpec = parsed.spec ?? {}
|
||||
}
|
||||
if (!isObject(draftSpec)) throw new Error("Application spec must be an object")
|
||||
const body = ad && tenantNamespace ? composeResource(ad, tenantNamespace, draftName, draftSpec) : null
|
||||
return { body, document, error: null }
|
||||
} catch (err) {
|
||||
return { body: null, document: null, error: (err as Error).message }
|
||||
}
|
||||
}, [ad, tenantNamespace, name, spec, mode, yamlText])
|
||||
// One dry-run create when the page opens: the server returns the spec with
|
||||
// installation and developer defaults, and the form starts from it. Edits do
|
||||
// not trigger more previews, the real create validates and applies defaults.
|
||||
useEffect(() => {
|
||||
if (isEditing || !ad || !tenantNamespace || !plural) return
|
||||
// Only a pending preview runs: a settled one must survive a tenant switch
|
||||
// without replacing what the user typed. Retry and a new kind set it pending.
|
||||
if (preview.status !== "loading") return
|
||||
let active = true
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const body = composeResource(ad, tenantNamespace, previewName || PREVIEW_NAME, previewSpec)
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error("the request timed out")), PREVIEW_TIMEOUT_MS)
|
||||
})
|
||||
Promise.race([client.dryRunCreate(APPS_GROUP, APPS_VERSION, plural, body, tenantNamespace), timeout])
|
||||
.then((result) => {
|
||||
const prepared = result.spec ?? {}
|
||||
if (!isObject(prepared)) throw new Error("the server returned a non-object application spec")
|
||||
if (!active) return
|
||||
setSpec(prepared)
|
||||
setPreview({ status: "ready" })
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
if (!active) return
|
||||
setPreview({ status: "failed", error: err.message })
|
||||
})
|
||||
.finally(() => clearTimeout(timer))
|
||||
return () => {
|
||||
active = false
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [client, ad, tenantNamespace, plural, isEditing, previewName, previewSpec, previewRun, preview.status])
|
||||
|
||||
const retryPreview = () => {
|
||||
// The preview carries the current draft, so the answer completes it and keeps
|
||||
// what the user typed since the failure.
|
||||
const current = draft.body?.spec
|
||||
setPreviewSpec(isObject(current) ? current : {})
|
||||
setPreviewName(name)
|
||||
setPreview({ status: "loading" })
|
||||
setPreviewRun((run) => run + 1)
|
||||
}
|
||||
|
||||
const create = useK8sCreate({
|
||||
apiGroup: APPS_GROUP,
|
||||
@@ -94,12 +184,9 @@ export function ApplicationOrderPage({
|
||||
/** Switch into form mode: parse YAML back to name/spec. */
|
||||
const enterForm = () => {
|
||||
try {
|
||||
const parsed = yaml.load(yamlText) as {
|
||||
metadata?: { name?: string }
|
||||
spec?: unknown
|
||||
}
|
||||
if (parsed?.metadata?.name) setName(parsed.metadata.name)
|
||||
if (parsed?.spec !== undefined) setSpec(parsed.spec)
|
||||
if (draft.error || !draft.body) throw new Error(draft.error ?? "Application is unavailable")
|
||||
setName(draft.body.metadata.name)
|
||||
setSpec(draft.body.spec ?? {})
|
||||
setYamlError(null)
|
||||
setMode("form")
|
||||
} catch (err) {
|
||||
@@ -109,22 +196,15 @@ export function ApplicationOrderPage({
|
||||
|
||||
/** Build resource from whichever editor is currently active. */
|
||||
const snapshot = () => {
|
||||
if (mode === "yaml") {
|
||||
const parsed = yaml.load(yamlText) as {
|
||||
metadata?: { name?: string }
|
||||
spec?: unknown
|
||||
}
|
||||
return {
|
||||
name: parsed?.metadata?.name ?? name,
|
||||
spec: parsed?.spec ?? spec,
|
||||
}
|
||||
}
|
||||
return { name, spec }
|
||||
if (draft.error || !draft.body) throw new Error(draft.error ?? "Application is unavailable")
|
||||
return { name: draft.body.metadata.name, spec: draft.body.spec ?? {} }
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
if (!ad || !tenantNamespace) return
|
||||
const snap = snapshot()
|
||||
let snap: ReturnType<typeof snapshot>
|
||||
try { snap = snapshot() }
|
||||
catch (err) { setYamlError((err as Error).message); return }
|
||||
if (!snap.name) {
|
||||
alert("Please set a resource name.")
|
||||
return
|
||||
@@ -214,6 +294,7 @@ export function ApplicationOrderPage({
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={mode === "form"}
|
||||
disabled={previewPending}
|
||||
onClick={() => (mode === "yaml" ? enterForm() : undefined)}
|
||||
className={cn(
|
||||
"flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-all",
|
||||
@@ -227,6 +308,7 @@ export function ApplicationOrderPage({
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={mode === "yaml"}
|
||||
disabled={previewPending}
|
||||
onClick={() => (mode === "form" ? enterYaml() : undefined)}
|
||||
className={cn(
|
||||
"flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-all",
|
||||
@@ -250,7 +332,7 @@ export function ApplicationOrderPage({
|
||||
variant="primary"
|
||||
size="sm"
|
||||
onClick={submit}
|
||||
disabled={create.isPending || update.isPending || !tenantNamespace}
|
||||
disabled={create.isPending || update.isPending || !tenantNamespace || previewPending}
|
||||
>
|
||||
{(create.isPending || update.isPending) && <Spinner className="text-white" />}
|
||||
{editMode ? "Save" : "Deploy"}
|
||||
@@ -259,7 +341,18 @@ export function ApplicationOrderPage({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mode === "form" ? (
|
||||
{!isEditing && preview.status === "failed" && (
|
||||
<div role="alert" className="border-b border-amber-200 bg-amber-50 px-6 py-2 text-xs text-amber-800">
|
||||
Could not load the platform's initial settings ({preview.error}). The form starts empty, and the API still fills omitted fields when you deploy.
|
||||
{mode === "form" && <button type="button" onClick={retryPreview} className="ml-2 underline">Retry</button>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{previewPending ? (
|
||||
<div role="status" className="flex items-center gap-2 p-8 text-slate-500">
|
||||
<Spinner /> Loading initial settings…
|
||||
</div>
|
||||
) : mode === "form" ? (
|
||||
<div className="flex-1 overflow-auto bg-slate-50 p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border border-slate-200 bg-white p-4">
|
||||
@@ -289,6 +382,8 @@ export function ApplicationOrderPage({
|
||||
formData={spec}
|
||||
onChange={setSpec}
|
||||
immutableMode={editMode ? "enforce" : "off"}
|
||||
defaulting="server"
|
||||
autoSelectDefaults={preview.status !== "failed"}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -296,9 +391,9 @@ export function ApplicationOrderPage({
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-1 flex-col bg-white">
|
||||
{yamlError && (
|
||||
{(draft.error || yamlError) && (
|
||||
<div className="border-b border-red-200 bg-red-50 px-6 py-2 text-xs text-red-700">
|
||||
{yamlError}
|
||||
{draft.error ?? yamlError}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1">
|
||||
@@ -309,7 +404,7 @@ export function ApplicationOrderPage({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<YamlEditor value={yamlText} onChange={setYamlText} />
|
||||
<YamlEditor value={yamlText} onChange={(value) => { setYamlError(null); setYamlText(value) }} />
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user