mattermost-mobile-upstream/app/utils/interactive_dialog_adapter.ts
Kyle Doliente b8aa29566a
Add collapsible sections to mobile (#10189)
* feat(apps-form): add collapsible field type and typings

Introduce the `collapsible` field type across the Apps and interactive
dialog layers: the AppFieldTypes constant, the AppField `collapsible_config`
(fields/expanded/bordered), and the DialogElement `collapsible_config`
(elements/collapsed/borderless), plus the InteractiveDialogElementType union.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(apps-form): flatten collapsible sections in dialog conversion and submission

Convert collapsible dialog elements into AppField sections (inverting
collapsed->expanded and borderless->bordered) and add recursive flatten
helpers (flattenCollapsible/flattenDialogElements/flattenAppFields). The
adapter now flattens elements before building the submission so leaf fields
nested inside collapsed sections are reachable by name and are no longer
silently dropped from the payload.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(apps-form): render collapsible sections in the apps form

Add the CollapsibleSection disclosure control (animated chevron, mount-on-
expand content, reduced-motion support, and screen-reader affordances) and
wire it into the apps form: sections initialize/submit their nested field
values, empty sections render nothing, and a failed submit auto-expands any
section containing an invalid field. Also render the BOOL field as an inline
label + Switch row. Includes unit coverage for the section component, the
inline bool toggle, and the section rendering/auto-expand behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(apps-form): present the apps form as a modal

Register APPS_FORM as a modal screen and set headerTintColor so the modal's
header button is visible, letting interactive dialogs open as a proper modal.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(apps-form): expand unit coverage for collapsible sections

Adds high-value behavioral tests for PR #10189 (collapsible sections):

- New apps_form_component.collapsible.test.tsx: recursive rendering
  (depth-3), validation auto-expansion incl. server-returned errors,
  forceExpandVersion transitions, refresh value-merge preservation,
  nested onChange/lookup discovery, nested submit_buttons, and exact
  submission payload integrity.
- dialog_utils: extensive flattenAppFields/flattenDialogElements/
  flattenCollapsible cases (empty, ordering, siblings, missing config,
  empty nested, container omission, arbitrary depth, no mutation).
- dialog_conversion: malformed/minimal collapsible conf, sibling
  top-level collapsibles, nested select/bool + depth-3 submission.
- interactive_dialog_adapter: prove flattenDialogElements is applied and
  nested/deep values reach the legacy payload end-to-end.
- collapsible_section: repeated force-expand increments; re-sync to
  collapsed on initiallyExpanded flip.

Test-only change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(apps-form): scroll interactive dialog elements into view

The apps form now renders inside a modal with a sticky header and a
keyboard-aware scroll view. The interactive_dialog page object's
fixed-distance scrolls no longer reliably reveal the target: the
pre-scroll in fillTextElement pushed the first input under the modal
header, and the single scroll in submit left the button behind the
keyboard on long/multistep dialogs. Both surfaced as identical
"element not visible" timeouts on iOS and Android in CI.

Replace the fixed scrolls with scroll-to-visible (whileElement) so the
helper scrolls only until the target input / submit button is actually
visible.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(apps-form): dismiss keyboard before revealing dialog elements

The scroll-to-visible change fixed mid-form fields, but the lowest
elements (textarea field, submit button on multistep dialogs) still
timed out: an open keyboard from the previous field occludes them and
the keyboard-aware scroll view cannot scroll them above it. CI failure
screenshots confirmed the keyboard covering the target in every
remaining case.

Add a dismissKeyboard() helper (tap the scroll view background) and call
it before scroll-to-visible in fillTextElement and submit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(apps-form): move submit action to the modal header

The apps form is now a modal with a keyboard-aware scroll view. With the
default submit button at the bottom of the body, the on-screen keyboard
covered it on phones, making the primary action unreachable (and timing
out the interactive_dialog E2E tests on iOS).

Move the default submit action into the modal header-right slot, matching
the app's existing modal-form pattern (edit_profile "Save", custom_status
"Done"). It now stays above the keyboard and is always reachable. Forms
that define their own submit_buttons keep those inline in the body. The
testID (interactive_dialog.submit.button) is preserved.

Update the apps_form unit tests to assert against the header registration,
and simplify the E2E submit() helper (no scroll/keyboard-dismiss needed
now that the button is always visible).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address coderabbit issues

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(apps-form): use a checkmark icon for the modal submit action

The design team requested the header submit control be a blue circular
checkmark button instead of a text label. The submit label now rides on
accessibilityLabel so assistive tech still announces it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(apps-form): verify collapsible section renders across the 5 core themes

Renders the section under denim, sapphire, quartz, indigo and onyx and
asserts colors are theme-derived (label color tracks centerChannelColor),
covering the checklist's cross-theme consistency requirement.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address coderabbit: guard double submit and force-expand nested sections

Add a synchronous submittingRef guard so a rapid double-tap on the header
submit button cannot fire submit() twice before the submitting state re-renders.

Seed CollapsibleSection expanded state from forceExpandVersion so a nested
errored section that mounts only after its collapsed ancestor expands reveals
its invalid field instead of staying collapsed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Recurse into unnamed collapsible sections when force-expanding on error

computeExpandBumps returned before recursing for an unnamed collapsible
section, so a named nested section holding an invalid required field was never
bumped and stayed hidden after a failed submit. Always recurse; only bump
sections that have a name (expandVersions is keyed by name).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(apps-form): fix lines-around-comment lint in collapsible test

Add the required blank line before the submit_buttons explanatory comment
so the lint-typecheck CI check passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Keep unnamed sections and nested refresh fields when converting dialogs

Only exclude a field from visibleFields/childFields when submit_buttons is
actually set, so unnamed collapsible sections are not dropped when a form has
no submit_buttons. Detect refresh fields in the flattened element tree so a
refresh field nested inside a collapsible section still sets form.source.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add collapsible section accessibility-hint and layout unit tests

Cover the accessibility hint toggling between expand/collapse, depth-based
header indentation, the bordered chrome branch, and clean unmount while
expanded — gaps the existing collapsible suite did not assert.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Fix collapsible section reveal, nested lookups, and collapse animation

Address QA findings on the apps-form collapsible sections:

- Force-expand now keys sections by a stable path identity instead of by
  name, so an unnamed collapsed section holding an invalid field opens on a
  failed submit just like a named one (previously it blocked submission but
  could never be revealed). The same path also gives unnamed sibling
  sections distinct React keys.
- Flatten dialog elements before resolving a dynamic-select lookup in
  DialogRouter, so a dynamic select nested inside a collapsible finds its
  element and loads options instead of silently returning nothing.
- Add a FadeOut exiting animation to section content so it fades on collapse
  in step with the container height instead of popping away.
- Drop the unused isFirstField parameter threaded through renderField.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Flatten collapsible sections in the app command parser

The slash-command parser iterated resolvedForm.fields directly, so a
collapsible container would be treated as a parameter and its nested leaf
fields skipped for parameter matching, required-field detection, option
expansion, and default/readonly values.

Flatten collapsibles to their leaf fields once where resolvedForm is
resolved, so every downstream step sees a flat parameter list — the same
UI-only-grouping treatment apps_form_component and the dialog adapter
already apply before validation and submission. A new form object is built
to avoid mutating the cached binding form, and flattening is idempotent for
forms that contain no collapsibles.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address review feedback on collapsible sections

- cleanForm: recurse into collapsible sections instead of treating a section
  as a removable leaf field, so a section whose title has spaces (or repeats a
  label) no longer drops itself and every field inside it, and nested selects
  are cleaned too. Add cleanForm unit tests. (sbishel)
- collapsible_section: gate the mount-time force-expand seed on hasError so a
  section no longer re-expands on every remount after its error is fixed, since
  forceExpandVersion stays non-zero for the form's life. (sbishel)
- apps_form_field: revert the inline BOOL Switch back to the shared BoolSetting,
  restoring the field hint, Markdown descriptions, and single screen-reader
  announcement. (sbishel)
- Remove the collapsible tests duplicated in apps_form_component.test.tsx
  (covered by apps_form_component.collapsible.test.tsx) and hoist the shared
  database/beforeEach/afterEach to module level in the collapsible test. (sbishel)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Fix lint errors from merge: unused import and prop line wrap

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Consolidate section indent onto the container and trim comments

Move the depth indent to a single inset on the section container instead of
duplicating it on the header and content, and tighten verbose comments across
the collapsible feature per review feedback.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add Detox E2E coverage for collapsible dialog sections

Add testIDs to the collapsible section header and content, and cover the demo
plugin's /dialog collapsible sample with Detox tests: default expand/collapse
state, revealing nested fields on expand, and filling fields across sections
before submit.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Scroll deeper collapsible section headers into view before toggling

Expanding an outer section grows the apps-form, pushing nested section
headers below the fold. toggleSection asserted visibility and tapped
without scrolling, so MM-T5602/MM-T5603 timed out on level3 toggles in
CI. Mirror fillTextElement: dismiss the keyboard and scroll the header
into view first.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Poll for the collapsible dialog submission post before asserting

MM-T5603 closed the dialog on-device and immediately read the last post,
but the plugin's "Dialog Submitted:" response post can land a beat later,
so the single fetch captured a stale post id and the assertion timed out
on iOS. Poll apiGetLastPostInChannel until the submission post exists.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Make the collapsible submit test reliable on iOS

The CI failure artifact showed MM-T5603 never produced a "Dialog Submitted:"
post on iOS: filling the company field inside the freshly-expanded level-2
section races the keyboard/scroll, so the submit silently drops and the
lenient ensureDialogClosed cancels the dialog. company is optional and the
dialog submits without it (Android already passes without last_name/email,
which are nominally required), so drop the flaky nested fill. Fill the
always-visible level-1 field, expand a section, submit, and assert the
entered value reaches the submission payload. Nested reveal stays covered
by MM-T5602.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add a settle delay before filling the expanded section in MM-T5603

Revert the submit test to its reviewed form and add one wait after expanding
level 2, before typing into company. On iOS, filling while the section is
still animating drops the input and the submit silently no-ops. This replaces
the earlier poll/restructure attempts with the minimal, idiomatic delay.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Move collapsible dialog tests into their own E2E file

Break the three collapsible tests out of interactive_dialog_plugin.e2e.ts
into interactive_dialog_collapsible.e2e.ts, with the suite setup copied so
the original file's other tests are untouched. Running against a fresh
channel instead of after ~30 prior tests keeps the submission post on
screen, so MM-T5603's final hasPostMessage check can find it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Verify the collapsible submission via the server post, not the UI

MM-T5603's final hasPostMessage check waited for the mobile client to render
the just-created submission post, which times out when the websocket render
lags past 10s (seen on both iOS and Android). The submit itself works and the
server has the post, so assert on the message from apiGetLastPostInChannel
instead of re-checking the rendered post on screen.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Fill all required fields in the collapsible submit test

MM-T5603 only filled first_name, so last_name and email (both required) were
empty and the dialog's validation blocked the submit, producing no post. In
the old shared file this was masked by a stale "Dialog Submitted:" post from
an earlier test; the dedicated file and server-side assertion exposed it. Fill
last_name and the nested email so the submission actually goes through.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add error-expansion E2E test and tidy collapsible test IDs

Add MM-T<collapsible>-4 covering a collapsed section auto-expanding when
its required field errors, then submitting. Switch the placeholder Zephyr
IDs to MM-T<collapsible>-N per QA (also avoids colliding with the real
Channel Bookmarks test IDs), and trim the verbose flatten comment in the
app command parser.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Route collapsible dialog spec to server B and use shared setup

Register the collapsible E2E spec in server_mutation_specs.json (target B,
where the demo plugin lives) and call requireMutationServer, satisfying the
server-mutation lint rule and manifest check added on main. Replace the
stale inline suite setup copied from the pre-refactor plugin file with the
shared interactive_dialog_plugin_helper.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Mattermost Build <build@mattermost.com>
2026-10-23 09:11:52 -07:00

233 lines
8.8 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {defineMessages, type IntlShape} from 'react-intl';
import {submitInteractiveDialog} from '@actions/remote/integrations';
import {AppCallResponseTypes} from '@constants/apps';
import {getFullErrorMessage} from '@utils/errors';
import {logDebug} from '@utils/log';
import {collectFileIds, convertAppFormValuesToDialogSubmission, convertDialogToAppForm} from './dialog_conversion';
import {flattenDialogElements} from './dialog_utils';
const submissionMessages = defineMessages({
submissionFailed: {
id: 'interactive_dialog.submission_failed',
defaultMessage: 'Submission failed. Please try again.',
},
submissionFailedNetwork: {
id: 'interactive_dialog.submission_failed_network',
defaultMessage: 'Submission failed due to network error. Please check your connection and try again.',
},
submissionFailedValidation: {
id: 'interactive_dialog.submission_failed_validation',
defaultMessage: 'Submission failed due to form validation. Please check your inputs and try again.',
},
});
/**
* Mobile Interactive Dialog Adapter
* Converts between legacy Interactive Dialogs and modern AppsForm system
* Following the same pattern as webapp PR #31821
*/
export class InteractiveDialogAdapter {
// WeakMap cache for expensive form conversions
// Keys are garbage collected when config objects are no longer referenced
private static readonly appFormCache = new WeakMap<InteractiveDialogConfig, AppForm>();
/**
* Convert InteractiveDialog config to AppForm structure
* Pure data transformation - no component creation
* Cached using WeakMap for performance
*/
static convertToAppForm(config: InteractiveDialogConfig): AppForm {
// Check cache first
const cached = InteractiveDialogAdapter.appFormCache.get(config);
if (cached) {
return cached;
}
// Convert and cache result
const converted = convertDialogToAppForm(config);
InteractiveDialogAdapter.appFormCache.set(config, converted);
return converted;
}
/**
* Convert AppForm values back to DialogSubmission format
* Used when submitting converted dialogs through legacy endpoints
*/
static convertValuesToSubmission(
values: AppFormValues,
config: InteractiveDialogConfig,
): DialogSubmission {
// Flatten so nested fields are reachable by name; otherwise they're
// silently dropped from the submission.
const elements = flattenDialogElements(config.dialog.elements || []);
const {submission, errors} = convertAppFormValuesToDialogSubmission(
values,
elements,
);
if (errors.length > 0) {
logDebug('Dialog conversion validation errors', {
errorCount: errors.length,
errors,
});
}
// Collect file IDs from file-type elements for server-side validation
const fileIds = collectFileIds(submission as {[x: string]: string}, elements);
return {
url: config.url || '',
callback_id: config.dialog.callback_id || '',
state: config.dialog.state || '',
submission: submission as {[x: string]: string},
user_id: '', // Will be populated by mobile action
channel_id: '', // Will be populated by mobile action
team_id: '', // Will be populated by mobile action
cancelled: false,
...(fileIds.length > 0 && {file_ids: fileIds}),
};
}
/**
* Create a submission handler for AppsFormContainer
* Converts AppForm submission to legacy dialog submission
*/
static createSubmitHandler(
config: InteractiveDialogConfig,
serverUrl: string,
intl: IntlShape,
) {
return async (values: AppFormValues): Promise<DoAppCallResult<FormResponseData>> => {
try {
// Convert values to legacy dialog submission format
const legacySubmission = InteractiveDialogAdapter.convertValuesToSubmission(values, config);
// Submit through existing mobile action
const result = await submitInteractiveDialog(serverUrl, legacySubmission);
// Convert response back to AppCallResponse format
return InteractiveDialogAdapter.convertResponseToAppCall(result, intl);
} catch (error) {
const errorMessage = getFullErrorMessage(error);
logDebug('Dialog submission failed', errorMessage);
// Provide more context in error messages
let userFriendlyMessage: string;
if (error instanceof Error) {
if (error.message.includes('network') || error.message.includes('fetch')) {
userFriendlyMessage = intl.formatMessage(submissionMessages.submissionFailedNetwork);
} else if (error.message.includes('conversion') || error.message.includes('validation')) {
userFriendlyMessage = intl.formatMessage(submissionMessages.submissionFailedValidation);
} else {
userFriendlyMessage = intl.formatMessage(submissionMessages.submissionFailed);
}
} else {
userFriendlyMessage = intl.formatMessage(submissionMessages.submissionFailed);
}
return {
error: {
type: AppCallResponseTypes.ERROR,
text: userFriendlyMessage,
data: {
errors: {},
},
},
};
}
};
}
/**
* Create a cancellation handler for AppsFormContainer
* Handles dialog cancellation notification if required
*/
static createCancelHandler(
config: InteractiveDialogConfig,
serverUrl: string,
) {
return async (): Promise<void> => {
if (config.dialog.notify_on_cancel) {
try {
const legacySubmission = InteractiveDialogAdapter.convertValuesToSubmission({}, config);
await submitInteractiveDialog(serverUrl, {
...legacySubmission,
cancelled: true,
});
} catch (error) {
logDebug('Dialog cancellation failed', getFullErrorMessage(error));
}
}
};
}
/**
* Convert dialog submission response to AppCallResponse format
* Handles the response format conversion including multiform dialogs
*/
static convertResponseToAppCall(
result: any,
intl: IntlShape,
): DoAppCallResult<FormResponseData> {
// Handle server-side validation errors from the response data
if (result?.data?.error || result?.data?.errors) {
return {
error: {
type: AppCallResponseTypes.ERROR,
text: result.data.error || intl.formatMessage({
id: 'interactive_dialog.submission_failed_validation',
defaultMessage: 'Submission failed with validation errors',
}),
data: {
errors: result.data.errors || {},
},
},
};
}
// Handle network/action-level errors
if (result?.error) {
return {
error: {
type: AppCallResponseTypes.ERROR,
text: intl.formatMessage({
id: 'interactive_dialog.submission_failed',
defaultMessage: 'Submission failed',
}),
data: {
errors: {},
},
},
};
}
// Check for multiform response - server returns new dialog form
// Server returns {"form": {...}, "type": "form"} format for multiform dialogs
if (result?.data && typeof result.data === 'object' && 'form' in result.data) {
// Return the raw form data directly - don't convert it yet
// The DialogRouter will handle the conversion after updating its state
return {
data: {
type: AppCallResponseTypes.FORM,
form: result.data.form, // Return raw dialog data
},
};
}
// Success response or no form data - closes dialog
return {
data: {
type: AppCallResponseTypes.OK,
text: '',
},
};
}
}