Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,16 +69,18 @@ export function useRemoteFieldBinding<Value extends RemoteFormValue>({

useLayoutEffect(
() =>
formId === undefined ? undefined : forms.registerField(formId, entry.id, name, rule),
[entry.id, formId, forms, name, rule],
formId === undefined
? undefined
: forms.registerField(formId, entry.id, name, rule, !readOnly && !disabled),
[disabled, entry.id, formId, forms, name, readOnly, rule],
)

const setValue = useCallback(
(value: Value) => {
if (formId === undefined) setLocal(value)
else forms.setValue(formId, name, value)
else forms.setValue(formId, name, value, rule.kind)
},
[formId, forms, name],
[formId, forms, name, rule.kind],
)
const submit = useCallback(() => {
if (formId !== undefined) forms.submit(formId)
Expand Down
161 changes: 115 additions & 46 deletions web/src/lib/AppUi/remote-forms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,18 @@ export type RemoteFormState = RemoteFormProps & {
readonly canSubmit: boolean
}

type RemoteFieldKind = RemoteFieldRule['kind']
type CarriedField = { readonly value: RemoteFormValue; readonly kind: RemoteFieldKind }
type CarriedFields = Readonly<Record<string, CarriedField>>

/** Fields the user changed but did not save, per form ID, carried to a new app generation. */
export type RemoteFormDrafts = ReadonlyMap<string, RemoteFormValues>
export type RemoteFormDrafts = ReadonlyMap<string, CarriedFields>

/** What the drafts carried from the previous app generation became in this one. */
export type RemoteFormCarry = {
/** Forms whose carried changes were set again. */
readonly restored: number
/** Changed fields the new generation's forms no longer have. */
/** Changed fields without a compatible, writable field in the new form. */
readonly dropped: readonly string[]
}

Expand Down Expand Up @@ -116,9 +120,13 @@ function sameValues(left: RemoteFormValues, right: RemoteFormValues) {
type FormRecord = {
props: RemoteFormProps | undefined
draft: RemoteFormValues
draftKinds: Map<string, RemoteFieldKind>
scope: string
attachments: number
fields: Map<string, { readonly name: string; readonly rule: RemoteFieldRule }>
fields: Map<
string,
{ readonly name: string; readonly rule: RemoteFieldRule; readonly writable: boolean }
>
handlers: RemoteFormHandlers | undefined
awaiting: boolean
timer: ReturnType<typeof setTimeout> | undefined
Expand All @@ -133,8 +141,9 @@ export function createRemoteFormStore({
}: { readonly awaitingTimeoutMs?: number } = {}) {
const forms = new Map<string, FormRecord>()
const listeners = new Set<() => void>()
// Drafts of the previous app generation, waiting for their form to arrive.
let carried = new Map<string, RemoteFormValues>()
// Draft fields can wait for both their form and their own registration.
let carried = new Map<string, Map<string, CarriedField>>()
const restoredForms = new Set<string>()
let carry: RemoteFormCarry = { restored: 0, dropped: [] }

function snapshot(form: FormRecord): RemoteFormState | undefined {
Expand All @@ -161,9 +170,13 @@ export function createRemoteFormStore({
}
}

function notifyListeners() {
for (const listener of listeners) listener()
}

function changed(form: FormRecord) {
form.snapshot = snapshot(form)
for (const listener of listeners) listener()
notifyListeners()
}

function settle(form: FormRecord) {
Expand All @@ -172,13 +185,14 @@ export function createRemoteFormStore({
form.timer = undefined
}

// Fields mount before their form, so either may create the record.
// The form and its fields can mount in either order.
function ensure(id: string) {
const existing = forms.get(id)
if (existing) return existing
const form: FormRecord = {
props: undefined,
draft: {},
draftKinds: new Map(),
scope: '',
attachments: 0,
fields: new Map(),
Expand All @@ -195,14 +209,62 @@ export function createRemoteFormStore({
if (form.attachments > 0 || form.fields.size > 0 || forms.get(id) !== form) return
settle(form)
forms.delete(id)
for (const listener of listeners) listener()
notifyListeners()
}

function notifyChange(form: FormRecord) {
const state = form.snapshot
if (state) form.handlers?.change(state.draft, state.dirty, state.valid)
}

function restoreCarried(id: string, form: FormRecord) {
const { props } = form
const pending = carried.get(id)
if (!props || form.attachments === 0 || !pending) return false

// An empty set records a mounted name with no writable fields.
const writableKindsByName = new Map<string, Set<RemoteFieldKind>>()
for (const { name, rule, writable } of form.fields.values()) {
const kinds = writableKindsByName.get(name) ?? new Set<RemoteFieldKind>()
if (writable) kinds.add(rule.kind)
writableKindsByName.set(name, kinds)
}
const restored = { ...form.draft }
const dropped: string[] = []
for (const [name, { value, kind }] of pending) {
const declared = Object.hasOwn(props.values, name)
const kinds = writableKindsByName.get(name)
// A later remote mutation may draw a field for this saved value.
if (!props.readonly && declared && !kinds) continue
pending.delete(name)
if (props.readonly || !declared || !kinds?.has(kind)) {
dropped.push(name)
continue
}
restoredForms.add(id)
restored[name] = value
form.draftKinds.set(name, kind)
}
if (pending.size === 0) carried.delete(id)
if (restoredForms.size !== carry.restored || dropped.length > 0) {
carry = {
restored: restoredForms.size,
dropped: [...carry.dropped, ...dropped],
}
}
if (sameValues(form.draft, restored)) return false
form.draft = restored
return true
}

function reconcileCarried(id: string, form: FormRecord) {
const previousCarry = carry
if (restoreCarried(id, form)) {
changed(form)
notifyChange(form)
} else if (carry !== previousCarry) notifyListeners()
}

return {
subscribe(listener: () => void) {
listeners.add(listener)
Expand Down Expand Up @@ -239,68 +301,64 @@ export function createRemoteFormStore({
previous.pending === props.pending &&
previous.conflict === props.conflict &&
previous.submittable === props.submittable
)
) {
reconcileCarried(id, form)
return
}
// Any update of the form answers a submit that is still awaited.
settle(form)
const pending = previous ? undefined : carried.get(id)
if (pending) {
// The user's unsaved changes from the previous generation return on the fields
// the new one still has; the rest is reported, never sent.
carried.delete(id)
const restored: Record<string, RemoteFormValue> = { ...props.values }
const dropped: string[] = []
for (const [name, value] of Object.entries(pending)) {
if (Object.hasOwn(props.values, name)) restored[name] = value
else dropped.push(name)
}
form.draft = restored
carry = {
restored:
carry.restored + (dropped.length < Object.keys(pending).length ? 1 : 0),
dropped: [...carry.dropped, ...dropped],
}
form.props = props
changed(form)
notifyChange(form)
return
}
if (!previous || previous.version !== props.version) form.draft = props.values
else if (!sameValues(previous.values, props.values)) {
if (!previous || previous.version !== props.version) {
form.draft = props.values
form.draftKinds.clear()
} else if (!sameValues(previous.values, props.values)) {
// Fields the user left untouched follow the new saved values.
const rebased: Record<string, RemoteFormValue> = { ...props.values }
for (const [name, value] of Object.entries(form.draft))
if (!Object.is(value, previous.values[name])) rebased[name] = value
form.draft = rebased
}
form.props = props
const restored = restoreCarried(id, form)
changed(form)
if (restored) notifyChange(form)
},

registerField(id: string, node: string, name: string, rule: RemoteFieldRule) {
registerField(
id: string,
node: string,
name: string,
rule: RemoteFieldRule,
writable: boolean,
) {
const form = ensure(id)
form.fields.set(node, { name, rule })
const field = { name, rule, writable }
form.fields.set(node, field)
const restored = restoreCarried(id, form)
changed(form)
if (restored) notifyChange(form)
return () => {
if (form.fields.get(node)?.rule !== rule) return
if (form.fields.get(node) !== field) return
form.fields.delete(node)
changed(form)
release(id, form)
}
},

setValue(id: string, name: string, value: RemoteFormValue) {
setValue(id: string, name: string, value: RemoteFormValue, kind: RemoteFieldKind) {
const form = forms.get(id)
if (!form?.props || Object.is(form.draft[name], value)) return
form.draft = { ...form.draft, [name]: value }
form.draftKinds.set(name, kind)
changed(form)
notifyChange(form)
},

discard(id: string) {
const form = forms.get(id)
carried.delete(id)
if (!form?.props || form.draft === form.props.values) return
form.draft = form.props.values
form.draftKinds.clear()
changed(form)
notifyChange(form)
},
Expand All @@ -322,23 +380,34 @@ export function createRemoteFormStore({

/** The fields the user changed and did not save, per form, for the next generation. */
unsavedDrafts(): RemoteFormDrafts {
const drafts = new Map<string, RemoteFormValues>()
const drafts = new Map<string, CarriedFields>()
for (const [id, form] of forms) {
const { props } = form
if (!props) continue
const changedFields = Object.entries(form.draft).filter(
([name, value]) => !Object.is(value, props.values[name]),
)
if (changedFields.length > 0) drafts.set(id, Object.fromEntries(changedFields))
const changedFields = new Map<string, CarriedField>()
for (const [name, kind] of form.draftKinds) {
const value = form.draft[name]
if (value !== undefined && !Object.is(value, props.values[name]))
changedFields.set(name, { value, kind })
}
if (changedFields.size > 0) drafts.set(id, Object.fromEntries(changedFields))
}
// Fields still waiting to register travel on with any active edits of the same form.
for (const [id, values] of carried) {
drafts.set(id, { ...Object.fromEntries(values), ...drafts.get(id) })
}
// Drafts that never found their form in this generation travel on unchanged.
for (const [id, values] of carried) if (!drafts.has(id)) drafts.set(id, values)
return drafts
},

/** Takes the previous generation's unsaved drafts; each returns when its form arrives. */
/** Takes the previous generation's drafts for fields already drawn or arriving later. */
carry(drafts: RemoteFormDrafts) {
carried = new Map(drafts)
carried = new Map(
Array.from(drafts, ([id, fields]) => [id, new Map(Object.entries(fields))]),
)
for (const id of carried.keys()) {
const form = forms.get(id)
if (form) reconcileCarried(id, form)
}
},

/** What the carried drafts became so far. */
Expand Down
56 changes: 43 additions & 13 deletions web/src/tests/features/AppUi/remote-app-dialogs.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { afterEach, expect, mock, test } from 'bun:test'
import type { ReactElement } from 'react'
import { GlobalRegistrator } from '@happy-dom/global-registrator'
import { AppDraftHandoffContext, draftHandoff } from '@/features/AppUi/appDraftHandoffContext.ts'
import type { AppUiSummary } from '@/lib/AppUi/contract.ts'
import type { RemoteUiStore } from '@/lib/AppUi/remote-tree.ts'
import withTestLanguage from '@/tests/Helpers/withTestLanguage.tsx'
Expand Down Expand Up @@ -420,18 +421,8 @@ test('fills the host action dialog with the app dialog instead of opening a seco
})

test('an app update keeps the unsaved draft and asks the user to check it', async () => {
const { AppDraftHandoffContext } = await import('@/features/AppUi/appDraftHandoffContext.ts')
let kept: Map<string, Record<string, unknown>> | undefined
const handoff = {
take: () => {
const drafts = kept
kept = undefined
return drafts as never
},
keep: (drafts: ReadonlyMap<string, Readonly<Record<string, unknown>>>) => {
kept = drafts.size > 0 ? new Map(drafts) : undefined
},
}
const kept = { current: null }
const handoff = draftHandoff('monitoring', kept)
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
Expand All @@ -457,7 +448,7 @@ test('an app update keeps the unsaved draft and asks the user to check it', asyn
// The new generation draws the same form; the user's interval comes back, still unsaved.
const after = createRemoteUiStore()
await show(2, after)
expect(kept).toBeUndefined()
expect(kept.current).toBeNull()
await apply(after, [[0, '~', dialog, 0]])
await click(button('Settings'))
expect(input('interval').value).toBe('120')
Expand All @@ -469,3 +460,42 @@ test('an app update keeps the unsaved draft and asks the user to check it', asyn
await click(button('Dismiss notice'))
expect(document.body.textContent).not.toContain('The app was updated')
})

test('restores a carried draft into a form drawn before the view mounts', async () => {
const store = createRemoteUiStore()
const handoff = draftHandoff('monitoring', { current: null })
handoff.keep(new Map([['policy', { interval: { value: 120, kind: 'number' } }]]))

expect(
await apply(store, [
[
0,
'~',
element('1', 'ui-form', {
properties: { id: 'policy', values: { interval: 60 }, version: 'v2' },
eventListeners: { change: true },
children: [
element('2', 'ui-number-field', {
properties: { name: 'interval', label: 'Interval' },
}),
],
}),
0,
],
]),
).toBe(true)
await render(
<AppDraftHandoffContext value={handoff}>
<RemoteAppView store={store} onEvent={onEvent} />
</AppDraftHandoffContext>,
)

expect(input('interval').value).toBe('120')
expect(document.body.textContent).toContain('Your unsaved changes were kept')
expect(onEvent).toHaveBeenCalledTimes(1)
expect(onEvent).toHaveBeenCalledWith('1', 'change', {
values: { interval: 120 },
dirty: true,
valid: true,
})
})
Loading