mattermost-mobile-upstream/app/screens/integration_selector/integration_selector.tsx
Daniel Espino García 84ea188366
Mattermost Blocks (#9764)
* Mattermost Blocks

* Move block renderer to its own components folder

* Sync translation layer

* UX fixes

* Refactor button to use the button component

* Code review

* Fix CI

* Add animations to collapse blocks

* Add unit tests

* Add e2e tests and related fixes

* Address coderabbit comments

* Address UX comments

* Address feedback

* Address coderabbit comments

* Fix snapshots

* Sync with webapp translation

* Add node limit to button markdown node

* Address feedback

* i18n-extract

* Fix test

* Move image utils to the utils folder

* Remove unneeded style

* Revert build script change

---------

Co-authored-by: Mattermost Build <build@mattermost.com>
2026-06-29 18:42:16 +02:00

687 lines
24 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {useNavigation} from 'expo-router';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {defineMessages, useIntl} from 'react-intl';
import {View} from 'react-native';
import {SafeAreaView, type Edge} from 'react-native-safe-area-context';
import {getExistingUserProfilesByIdWithFallback} from '@actions/local/user';
import {fetchChannels, searchChannels} from '@actions/remote/channel';
import {fetchProfiles, searchProfiles} from '@actions/remote/user';
import FormattedText from '@components/formatted_text';
import NavigationButton from '@components/navigation_button';
import SearchBar from '@components/search';
import ServerUserList from '@components/server_user_list';
import {General, Screens, View as ViewConstants} from '@constants';
import {useServerUrl} from '@context/server';
import {useTheme} from '@context/theme';
import useAndroidHardwareBackHandler from '@hooks/android_back_handler';
import useDidMount from '@hooks/did_mount';
import {useDebounce} from '@hooks/utils';
import {navigateBack} from '@screens/navigation';
import SettingsStore from '@store/settings_store';
import {filterChannelsMatchingTerm} from '@utils/channel';
import {filterOptions} from '@utils/message_attachment';
import {changeOpacity, getKeyboardAppearanceFromTheme, makeStyleSheetFromTheme} from '@utils/theme';
import {secureGetFromRecord} from '@utils/types';
import {typography} from '@utils/typography';
import ChannelListRow from './channel_list_row';
import CustomList from './custom_list';
import OptionListRow from './option_list_row';
import SelectedOptions from './selected_options';
type DataType = DialogOption | Channel | UserProfile;
type DataTypeList = DialogOption[] | Channel[] | UserProfile[];
type Selection = DataType | DataTypeList;
type MultiselectSelectedMap = Dictionary<DialogOption> | Dictionary<Channel> | Dictionary<UserProfile>;
const VALID_DATASOURCES = [
ViewConstants.DATA_SOURCE_CHANNELS,
ViewConstants.DATA_SOURCE_USERS,
ViewConstants.DATA_SOURCE_DYNAMIC];
const close = () => {
SettingsStore.removeIntegrationsSelectCallback();
SettingsStore.removeIntegrationsDynamicOptionsCallback();
navigateBack();
};
const safeAreaEdges: Edge[] = ['bottom', 'left', 'right'];
const extractItemKey = (dataSource: string, item: DataType): string => {
switch (dataSource) {
case ViewConstants.DATA_SOURCE_USERS: {
const typedItem = item as UserProfile;
return typedItem.id;
}
case ViewConstants.DATA_SOURCE_CHANNELS: {
const typedItem = item as Channel;
return typedItem.id;
}
default: {
const typedItem = item as DialogOption;
return typedItem.value;
}
}
};
const toggleFromMap = <T extends DialogOption | Channel | UserProfile>(current: MultiselectSelectedMap, key: string, item: T): MultiselectSelectedMap => {
const newMap = {...current};
const hasValue = Boolean(secureGetFromRecord<any>(current, key));
if (hasValue) {
delete newMap[key];
} else {
newMap[key] = item;
}
return newMap;
};
const filterSearchData = (source: string, searchData: DataTypeList, searchTerm: string) => {
if (!searchData) {
return [];
}
const lowerCasedTerm = searchTerm.toLowerCase();
if (source === ViewConstants.DATA_SOURCE_CHANNELS) {
return filterChannelsMatchingTerm(searchData as Channel[], lowerCasedTerm);
} else if (source === ViewConstants.DATA_SOURCE_DYNAMIC) {
return searchData;
}
return (searchData as DialogOption[]).filter((option) => option.text && option.text.includes(lowerCasedTerm));
};
const handleIdSelection = (dataSource: string, currentIds: {[id: string]: DataType}, item: DataType) => {
const newSelectedIds = {...currentIds};
const key = extractItemKey(dataSource, item);
const wasSelected = secureGetFromRecord(currentIds, key);
if (wasSelected) {
Reflect.deleteProperty(newSelectedIds, key);
} else {
newSelectedIds[key] = item;
}
return newSelectedIds;
};
export type Props = {
options?: PostActionOption[];
currentTeamId: string;
data?: DataTypeList;
dataSource: string;
isMultiselect?: boolean;
selected: SelectedDialogValue;
}
const getStyleSheet = makeStyleSheetFromTheme((theme: Theme) => {
return {
container: {
flex: 1,
marginHorizontal: 12,
},
searchBar: {
marginVertical: 5,
height: 38,
},
loadingContainer: {
alignItems: 'center',
backgroundColor: theme.centerChannelBg,
height: 70,
justifyContent: 'center',
},
loadingText: {
color: changeOpacity(theme.centerChannelColor, 0.6),
},
noResultContainer: {
flexGrow: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
noResultText: {
color: changeOpacity(theme.centerChannelColor, 0.5),
...typography('Body', 600, 'Regular'),
},
searchBarInput: {
color: theme.centerChannelColor,
...typography('Body', 200, 'Regular'),
},
separator: {
height: 1,
flex: 0,
backgroundColor: changeOpacity(theme.centerChannelColor, 0.1),
},
};
});
const messages = defineMessages({
loadingChannels: {
id: 'mobile.integration_selector.loading_channels',
defaultMessage: 'Loading channels...',
},
loadingOptions: {
id: 'mobile.integration_selector.loading_options',
defaultMessage: 'Loading options...',
},
});
function IntegrationSelector({
dataSource, data, isMultiselect = false, selected,
currentTeamId, options,
}: Props) {
const navigation = useNavigation();
const serverUrl = useServerUrl();
const theme = useTheme();
const searchTimeoutId = useRef<NodeJS.Timeout | null>(null);
const style = getStyleSheet(theme);
const intl = useIntl();
// HOOKS
const [integrationData, setIntegrationData] = useState<DataTypeList>(data || []);
const [loading, setLoading] = useState<boolean>(false);
const [term, setTerm] = useState<string>('');
const [searchResults, setSearchResults] = useState<DataTypeList>([]);
// Channels and DialogOptions, will be removed
const [multiselectSelected, setMultiselectSelected] = useState<MultiselectSelectedMap>(() => {
const multiselectItems: MultiselectSelectedMap = {};
if (isMultiselect && Array.isArray(selected) && !([ViewConstants.DATA_SOURCE_USERS, ViewConstants.DATA_SOURCE_CHANNELS].includes(dataSource))) {
for (const value of selected) {
const option = filteredOptions?.find((opt) => opt.value === value);
if (option) {
multiselectItems[value] = option;
}
}
}
return multiselectItems;
});
// Users selection and in the future Channels and DialogOptions
const [selectedIds, setSelectedIds] = useState<{[id: string]: DataType}>({});
const [customListData, setCustomListData] = useState<DataTypeList>([]);
const page = useRef<number>(-1);
const next = useRef<boolean>(VALID_DATASOURCES.includes(dataSource));
const filteredOptions = useMemo(() => {
return filterOptions(options) || [];
}, [options]);
// Callbacks
const clearSearch = useCallback(() => {
setTerm('');
setSearchResults([]);
}, []);
const handleSelectItem = useCallback((item: Selection) => {
if (!isMultiselect) {
const selectCallback = SettingsStore.getIntegrationsSelectCallback();
selectCallback?.(item);
close();
return;
}
switch (dataSource) {
case ViewConstants.DATA_SOURCE_CHANNELS: {
const itemKey = extractItemKey(dataSource, item as Channel);
setMultiselectSelected((current) => toggleFromMap(current, itemKey, item as Channel));
return;
}
default: {
const itemKey = extractItemKey(dataSource, item as DialogOption);
setMultiselectSelected((current) => toggleFromMap(current, itemKey, item as DialogOption));
}
}
}, [isMultiselect, dataSource]);
const handleRemoveOption = useCallback((item: Channel | DialogOption | UserProfile) => {
const itemKey = extractItemKey(dataSource, item);
setSelectedIds((current) => {
const selectedIdItems = {...current};
delete selectedIdItems[itemKey];
return selectedIdItems;
});
setMultiselectSelected((current) => {
const multiselectSelectedItems = {...current};
if (secureGetFromRecord<any>(multiselectSelectedItems, itemKey) !== undefined) {
delete multiselectSelectedItems[itemKey];
}
return multiselectSelectedItems;
});
}, [dataSource]);
const getChannels = useDebounce(useCallback(async () => {
if (next.current && !loading && !term) {
setLoading(true);
page.current += 1;
const {channels: channelData} = await fetchChannels(serverUrl, currentTeamId, page.current);
setLoading(false);
if (channelData && channelData.length > 0) {
setIntegrationData([...integrationData as Channel[], ...channelData]);
} else {
next.current = false;
}
}
}, [loading, term, serverUrl, currentTeamId, integrationData]), 100);
const loadMore = useCallback(async () => {
if (dataSource === ViewConstants.DATA_SOURCE_CHANNELS) {
getChannels();
}
// dynamic options are not paged so are not reloaded on scroll
}, [getChannels, dataSource]);
const searchDynamicOptions = useCallback(async (searchTerm = '') => {
if (filteredOptions && filteredOptions !== integrationData && !searchTerm) {
setIntegrationData(filteredOptions);
}
const getDynamicOptions = SettingsStore.getIntegrationsDynamicOptionsCallback();
if (!getDynamicOptions) {
return;
}
const results: DialogOption[] = await getDynamicOptions(searchTerm.toLowerCase());
const searchData = results || [];
if (searchTerm) {
setSearchResults(searchData);
} else {
setIntegrationData(searchData);
}
}, [filteredOptions, integrationData]);
const handleSelectProfile = useCallback((user: UserProfile): void => {
if (!isMultiselect) {
const selectCallback = SettingsStore.getIntegrationsSelectCallback();
selectCallback?.(user);
close();
}
setSelectedIds((current) => handleIdSelection(dataSource, current, user));
}, [isMultiselect, dataSource]);
const onHandleMultiselectSubmit = useCallback(() => {
const selectCallback = SettingsStore.getIntegrationsSelectCallback();
if (dataSource === ViewConstants.DATA_SOURCE_USERS) {
// New multiselect
selectCallback?.(Object.values(selectedIds) as UserProfile[]);
} else if (dataSource === ViewConstants.DATA_SOURCE_CHANNELS) {
// For channels, combine both previously selected (selectedIds) and newly selected (multiselectSelected)
const allSelected = [
...Object.values(selectedIds) as Channel[],
...Object.values(multiselectSelected) as Channel[],
];
selectCallback?.(allSelected);
} else {
// Legacy multiselect for regular options
selectCallback?.(Object.values(multiselectSelected));
}
close();
}, [dataSource, selectedIds, multiselectSelected]);
const onSearch = useCallback((text: string) => {
if (!text) {
clearSearch();
return;
}
setTerm(text);
if (searchTimeoutId.current) {
clearTimeout(searchTimeoutId.current);
}
searchTimeoutId.current = setTimeout(async () => {
if (!dataSource) {
setSearchResults(filterSearchData('', integrationData, text));
return;
}
setLoading(true);
if (dataSource === ViewConstants.DATA_SOURCE_CHANNELS) {
const isSearch = true;
const {channels: receivedChannels} = await searchChannels(
serverUrl, text, currentTeamId, isSearch);
if (receivedChannels) {
setSearchResults(receivedChannels);
}
} else if (dataSource === ViewConstants.DATA_SOURCE_DYNAMIC) {
await searchDynamicOptions(text);
}
setLoading(false);
}, General.SEARCH_TIMEOUT_MILLISECONDS);
}, [clearSearch, dataSource, integrationData, serverUrl, currentTeamId, searchDynamicOptions]);
// Effects
useAndroidHardwareBackHandler(Screens.INTEGRATION_SELECTOR, close);
useEffect(() => {
return () => {
if (searchTimeoutId.current) {
clearTimeout(searchTimeoutId.current);
searchTimeoutId.current = null;
}
};
}, []);
useDidMount(() => {
if (dataSource === ViewConstants.DATA_SOURCE_CHANNELS) {
getChannels();
} else {
// Static and dynamic option search
searchDynamicOptions('');
}
});
useEffect(() => {
let listData: DataTypeList = integrationData;
if (term) {
listData = searchResults;
}
if (dataSource === ViewConstants.DATA_SOURCE_DYNAMIC) {
listData = (integrationData as DialogOption[]).filter((option) => option.text && option.text.toLowerCase().includes(term));
}
setCustomListData(listData);
// We only want to update the list data when the search results or integration data changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchResults, integrationData]);
useEffect(() => {
if (!isMultiselect) {
return;
}
navigation.setOptions({
headerRight: () => (
<NavigationButton
onPress={onHandleMultiselectSubmit}
testID='integration_selector.multiselect.submit.button'
text={intl.formatMessage({id: 'integration_selector.multiselect.submit', defaultMessage: 'Done'})}
/>
),
});
}, [onHandleMultiselectSubmit, isMultiselect, navigation, intl]);
useEffect(() => {
const multiselectItems: MultiselectSelectedMap = {};
if (isMultiselect && Array.isArray(selected) && !([ViewConstants.DATA_SOURCE_USERS, ViewConstants.DATA_SOURCE_CHANNELS].includes(dataSource))) {
for (const value of selected) {
const option = filteredOptions?.find((opt) => opt.value === value);
if (option) {
multiselectItems[value] = option;
}
}
setMultiselectSelected(multiselectItems);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // Only initialize on mount - values are from props and don't need to re-run
// Initialize selectedIds for user/channel fields
const hasInitialized = useRef(false);
useEffect(() => {
if (isMultiselect && Array.isArray(selected) && [ViewConstants.DATA_SOURCE_USERS, ViewConstants.DATA_SOURCE_CHANNELS].includes(dataSource) && !hasInitialized.current) {
if (dataSource === ViewConstants.DATA_SOURCE_CHANNELS && integrationData?.length) {
// For channels, look in integrationData
const initialSelectedIds: {[id: string]: DataType} = {};
for (const selectedId of selected) {
const item = integrationData.find((dataItem) => extractItemKey(dataSource, dataItem) === selectedId);
if (item) {
initialSelectedIds[selectedId] = item;
}
}
if (Object.keys(initialSelectedIds).length > 0) {
setSelectedIds(initialSelectedIds);
hasInitialized.current = true;
}
} else if (dataSource === ViewConstants.DATA_SOURCE_USERS) {
getExistingUserProfilesByIdWithFallback(serverUrl, selected).then((initialSelectedIds) => {
setSelectedIds(initialSelectedIds);
hasInitialized.current = true;
});
}
}
}, [isMultiselect, selected, dataSource, integrationData, serverUrl]);
// Renders
const renderLoading = useCallback(() => {
if (!loading) {
return null;
}
let text;
switch (dataSource) {
case ViewConstants.DATA_SOURCE_CHANNELS:
text = messages.loadingChannels;
break;
default:
text = messages.loadingOptions;
break;
}
return (
<View style={style.loadingContainer}>
<FormattedText
{...text}
style={style.loadingText}
/>
</View>
);
}, [style, dataSource, loading]);
const renderNoResults = useCallback((): React.ReactNode => {
if (loading || page.current === -1) {
return null;
}
return (
<View style={style.noResultContainer}>
<FormattedText
id='mobile.custom_list.no_results'
defaultMessage='No Results'
style={style.noResultText}
/>
</View>
);
}, [loading, style]);
const renderChannelItem = useCallback((itemProps: any) => {
const itemSelected = Boolean(multiselectSelected[itemProps.item.id] || selectedIds[itemProps.item.id]);
return (
<ChannelListRow
key={itemProps.id}
{...itemProps}
theme={theme}
channel={itemProps.item as Channel}
selectable={isMultiselect || false}
selected={itemSelected}
testID={'integration_selector.channel_list'}
/>
);
}, [multiselectSelected, selectedIds, theme, isMultiselect]);
const renderOptionItem = useCallback((itemProps: any) => {
const itemSelected = Boolean(secureGetFromRecord<any>(multiselectSelected, itemProps.item.value));
return (
<OptionListRow
key={itemProps.id}
{...itemProps}
theme={theme}
selectable={isMultiselect}
selected={itemSelected}
/>
);
}, [multiselectSelected, theme, isMultiselect]);
const getRenderItem = (): (itemProps: any) => React.ReactNode => {
switch (dataSource) {
case ViewConstants.DATA_SOURCE_CHANNELS:
return renderChannelItem;
default:
return renderOptionItem;
}
};
const renderSelectedOptions = useCallback((): React.ReactElement<string> | null => {
let selectedItems: Channel[] | DialogOption[] | UserProfile[] = Object.values(multiselectSelected);
if (dataSource === ViewConstants.DATA_SOURCE_USERS) {
// New multiselect
selectedItems = Object.values(selectedIds) as UserProfile[];
} else if (dataSource === ViewConstants.DATA_SOURCE_CHANNELS) {
selectedItems = Array.from(
new Set([...Object.values(multiselectSelected), ...Object.values(selectedIds)]),
) as Channel[];
}
if (!selectedItems.length) {
return null;
}
return (
<>
<SelectedOptions
theme={theme}
selectedOptions={selectedItems}
dataSource={dataSource}
onRemove={handleRemoveOption}
/>
<View style={style.separator}/>
</>
);
}, [dataSource, handleRemoveOption, multiselectSelected, selectedIds, style.separator, theme]);
const userFetchFunction = useCallback(async (userFetchPage: number) => {
const result = await fetchProfiles(serverUrl, userFetchPage, General.PROFILE_CHUNK_SIZE);
if (result.users?.length) {
return result.users;
}
return [];
}, [serverUrl]);
const userSearchFunction = useCallback(async (searchTerm: string) => {
const lowerCasedTerm = searchTerm.toLowerCase();
const results = await searchProfiles(serverUrl, lowerCasedTerm, {allow_inactive: false});
if (results.data) {
return results.data;
}
return [];
}, [serverUrl]);
const createUserFilter = useCallback((exactMatches: UserProfile[], searchTerm: string) => {
return (p: UserProfile) => {
if (p.username === searchTerm || p.username.startsWith(searchTerm)) {
exactMatches.push(p);
return false;
}
return true;
};
}, []);
const selectedUserIds = useMemo<Set<string>>(() => {
if (dataSource === ViewConstants.DATA_SOURCE_USERS) {
return new Set(Object.keys(selectedIds));
}
return new Set();
}, [dataSource, selectedIds]);
const renderDataTypeList = () => {
switch (dataSource) {
case ViewConstants.DATA_SOURCE_USERS:
return (
<ServerUserList
term={term}
tutorialWatched={true}
handleSelectProfile={handleSelectProfile}
selectedIds={selectedUserIds}
fetchFunction={userFetchFunction}
searchFunction={userSearchFunction}
createFilter={createUserFilter}
testID={'integration_selector.user_list'}
location={Screens.INTEGRATION_SELECTOR}
/>
);
default:
return (
<CustomList
data={customListData as (Channel[] | DialogOption[])}
key='custom_list'
loading={loading}
loadingComponent={renderLoading()}
noResults={renderNoResults}
onLoadMore={loadMore}
onRowPress={handleSelectItem}
renderItem={getRenderItem()}
theme={theme}
/>
);
}
};
const selectedOptionsComponent = renderSelectedOptions();
return (
<SafeAreaView
edges={safeAreaEdges}
style={style.container}
>
<View
testID='integration_selector.screen'
style={style.searchBar}
>
<SearchBar
testID='selector.search_bar'
placeholder={intl.formatMessage({id: 'search_bar.search', defaultMessage: 'Search'})}
inputStyle={style.searchBarInput}
placeholderTextColor={changeOpacity(theme.centerChannelColor, 0.5)}
onChangeText={onSearch}
autoCapitalize='none'
keyboardAppearance={getKeyboardAppearanceFromTheme(theme)}
value={term}
/>
</View>
{selectedOptionsComponent}
{renderDataTypeList()}
</SafeAreaView>
);
}
export default IntegrationSelector;