mattermost-mobile-upstream/app/utils/dialog_conversion.ts
2026-08-10 15:20:08 +02:00

211 lines
8.0 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
// Dialog conversion utilities for Interactive Dialog to AppsForm migration
// Based on webapp dialog_conversion.ts from PR #31821
import {isAppSelectOption, mapDialogTypeToAppFieldType, DialogElementTypes, DialogTextSubtypes} from './dialog_utils';
export interface ConversionContext {
elements: DialogElement[];
}
export interface ConversionResult {
submission: {[key: string]: string | number | boolean};
errors: string[];
}
/**
* Converts AppForm values back to legacy DialogSubmission format
* Used when submitting converted dialogs through legacy endpoints
*/
export function convertAppFormValuesToDialogSubmission(
values: AppFormValues,
elements: DialogElement[],
): ConversionResult {
const submission: {[key: string]: string | number | boolean} = {};
const errors: string[] = [];
// Early return if no values to process
const valueKeys = Object.keys(values);
if (valueKeys.length === 0) {
return {submission, errors};
}
// Convert each form value back to dialog submission format
valueKeys.forEach((fieldName) => {
const value = values[fieldName];
const element = elements.find((e) => e.name === fieldName);
if (!element) {
errors.push(`Field ${fieldName} not found in dialog elements`);
return;
}
// Convert based on field type
switch (element.type) {
case DialogElementTypes.TEXT:
case DialogElementTypes.TEXTAREA:
if (element.subtype === DialogTextSubtypes.NUMBER) {
// Handle empty number fields like legacy dialog - omit from submission
if (value === '' || value === null || value === undefined) {
break; // Don't include in submission
}
const numValue = Number(value);
submission[fieldName] = isNaN(numValue) ? String(value) : numValue;
} else {
submission[fieldName] = String(value || '');
}
break;
case DialogElementTypes.RADIO:
case DialogElementTypes.SELECT:
// Handle multiselect arrays for SELECT fields only
if (element.type === DialogElementTypes.SELECT && element.multiselect && Array.isArray(value)) {
// For multiselect, extract values from AppSelectOption array and join with commas
const extractedValues = value.map((option) => (
isAppSelectOption(option) ? (option.value || '') : String(option || '')
)).filter((v) => v !== '');
submission[fieldName] = extractedValues.join(',');
} else if (isAppSelectOption(value)) {
// Single AppSelectOption object
submission[fieldName] = String(value.value || '');
} else {
// Single string value
submission[fieldName] = String(value || '');
}
break;
case DialogElementTypes.BOOL:
if (typeof value === 'boolean') {
submission[fieldName] = value;
} else if (typeof value === 'string') {
const lower = value.toLowerCase().trim();
if (lower === 'true' || lower === '1' || lower === 'yes') {
submission[fieldName] = true;
} else if (lower === 'false' || lower === '0' || lower === 'no' || lower === 'off') {
submission[fieldName] = false;
} else {
// Noncanonical truthy strings (e.g. "on") keep Boolean() coercion.
submission[fieldName] = Boolean(value);
}
} else {
submission[fieldName] = Boolean(value);
}
break;
default:
submission[fieldName] = String(value || '');
}
});
return {submission, errors};
}
/**
* Converts DialogElement to AppField format
* Used when converting dialog config to AppForm
*/
export function convertDialogElementToAppField(element: DialogElement): AppField {
const appField: AppField = {
name: element.name,
type: mapDialogTypeToAppFieldType(element.type, element.data_source),
is_required: !element.optional,
label: element.display_name,
description: element.help_text,
position: 0, // Will be set by caller based on order
};
// Add type-specific properties
if (element.type === DialogElementTypes.TEXT || element.type === DialogElementTypes.TEXTAREA) {
appField.max_length = element.max_length;
appField.min_length = element.min_length;
if (element.type !== DialogElementTypes.TEXTAREA && element.subtype) {
appField.subtype = element.subtype;
}
}
if (element.type === DialogElementTypes.RADIO || element.type === DialogElementTypes.SELECT) {
appField.options = element.options?.map((option) => ({
label: option.text,
value: option.value,
}));
// Add multiselect support for select fields
if (element.type === DialogElementTypes.SELECT && element.multiselect) {
appField.multiselect = element.multiselect;
}
}
if (element.default) {
appField.value = element.default;
}
if (element.placeholder) {
appField.hint = element.placeholder;
}
// Preserve datetime configuration
if (element.type === DialogElementTypes.DATE || element.type === DialogElementTypes.DATETIME) {
appField.min_date = element.min_date;
appField.max_date = element.max_date;
appField.time_interval = element.time_interval;
appField.datetime_config = element.datetime_config;
}
// Field refresh should be controlled by the server-side dialog configuration
// The server should specify which fields trigger form refresh
appField.refresh = element.refresh;
return appField;
}
/**
* Converts InteractiveDialogConfig to AppForm. Requires the legacy `dialog` field
* (native `block_dialog` configs are handled by BlocksDialogRouter when block actions are enabled).
*/
export function convertDialogToAppForm(config: InteractiveDialogConfig): AppForm {
const {dialog} = config;
if (!dialog) {
throw new Error('convertDialogToAppForm requires config.dialog');
}
// FILE and ACTION_BUTTON are not representable as AppField types; skip rather than
// falling through mapDialogTypeToAppFieldType's default → 'text'.
const convertedFields = dialog.elements?.
filter((element) => (
element.type !== DialogElementTypes.FILE &&
element.type !== DialogElementTypes.ACTION_BUTTON
)).
map((element, index) => ({
...convertDialogElementToAppField(element),
position: index,
})) || [];
// Set source only if source_url is provided or if any fields have refresh enabled (matching webapp behavior)
const hasRefreshFields = convertedFields.some((field) => field.refresh === true);
const sourceUrl = dialog.source_url;
const form: AppForm = {
title: dialog.title,
header: dialog.introduction_text || undefined,
fields: convertedFields,
submit_buttons: undefined,
// Pass through submit label from dialog config
submit_label: dialog.submit_label || undefined,
// Set source if sourceUrl is provided or if any fields have refresh enabled (matching webapp behavior)
source: ((sourceUrl && sourceUrl.trim()) || hasRefreshFields) ? {
path: sourceUrl || '/dialog/refresh',
expand: {},
} : undefined,
submit: {
path: '/dialog/submit',
expand: {},
},
};
return form;
}