mattermost-mobile/app/utils/draft/index.ts
Mattermost Build 0f55d7e702
Mobile drafts (#8280) (#8473)
* refactor: started with draft, done until new tabs for draft

* refactor: change the query and added the screen for draft

* added condition for fetching draft for channel delete or not

* refactor: added draft screen

* linter fixes

* Added draft post component

* added avatar and header display name for the draft post list

* added channel info component

* channel info completed

* proper naming

* added image file markdown acknowledgement support

* draft actions

* Fix the draft receiver in drafts

* separated send message handler

* Done with send drafts

* done with delete drafts

* change save to send draft

* handle lengthy message with show more button

* done with persistent message edit, send and delete drafts

* added alert for sending message

* added update at time for the drafts

* en.json extract fix

* Updated dependencies for useCallback

* refactor: added drafts list to animated list

* added swipeable component and delete conformation for drafts

* done with rendering of images in markdown for drafts

* en.json issue fixed

* fix en.json issue

* refactor: en.json fix

* addressed review comments

* updated image metadata handling code

* linter fixes

* added the empty draft screen

* linter fix

* style fix

* back button an android takes to the channel list page

* en.json fix

* draft actions theme compatible

* CSS fix for draft channel_info and avatar component

* removed the badge icon and change font style drafts

* fix send alert sender name for GMs

* updated snapshot

* added testId to the drafts components

* updated send draft test id

* clicking on draft takes to the channel

* Added toptip for draft tours

* intl extract

* Rebase to main and reverted local testing changes

* Added tooltip for drafts

* addressed review comments

* reset navigation when click on a draft in draft tabs

* fix the theme issue and navigation issue

* reverted back the draft click navigation changes

* observing draft when hitting back button

* removed the unwanted animiation

* updated regex for parsing markdown

* removed unnecessary checks and change folder name

* removed react memo and merge unwanted observes function

* removed unnecessary comments

* changed the name for observing and querying draft function

* removed memo from component level

* Text to FormattedText component

* Text to formatted text, change image name

* added confirmation modal for deleting draft from bottomsheet

* using common send_handler for both draft and post

* removed magic number for tooltip and bottomsheet

* renamed channel_info to draft_post_header

* text to formattedText for Edit drafts

* removed unnecessary changes

* minor fixes

* mounting draft only when there is draft

* map to reduce

* renamed SwipeableDraft to DraftSwipeAction

* name fixes

* isValidUrl to isParsableUrl and added test

* added test and addressed minor review comments

* added inline component for the duplicate code

* inlt fixes

* clearDraft is not optional

* optimised categories_list.tsx component

* Swipeable to ReanimatedSwipeable, TouchableWithoutFeedback to Pressable and folder name changes

* Added comment and disabled eslint rule for showing warning

* fixed component file name

* minor'

* Removed deprecated Animated createAnimatedComponent flatlist

* added test for missing protocol check

* import change for SwipeableMethod

* active tab for tablet view

* Updated the drafts icons

* Updated compass-icon version to v0.1.48

---------

Co-authored-by: Mattermost Build <build@mattermost.com>
(cherry picked from commit 84eded1bde)

Co-authored-by: Rajat Dabade <rajatdabade1997@gmail.com>
2025-01-13 15:15:42 +02:00

240 lines
8.8 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Alert, type AlertButton} from 'react-native';
import {type SwipeableMethods} from 'react-native-gesture-handler/ReanimatedSwipeable';
import {parseMarkdownImages, removeDraft, updateDraftMarkdownImageMetadata, updateDraftMessage} from '@actions/local/draft';
import {General} from '@constants';
import {CODE_REGEX} from '@constants/autocomplete';
import {t} from '@i18n';
import type {IntlShape, MessageDescriptor} from 'react-intl';
type AlertCallback = (value?: string) => void;
export function errorBadChannel(intl: IntlShape) {
const message = {
id: t('mobile.server_link.unreachable_channel.error'),
defaultMessage: 'This link belongs to a deleted channel or to a channel to which you do not have access.',
};
return alertErrorWithFallback(intl, {}, message);
}
export function errorUnkownUser(intl: IntlShape) {
const message = {
id: t('mobile.server_link.unreachable_user.error'),
defaultMessage: 'We can\'t redirect you to the DM. The user specified is unknown.',
};
alertErrorWithFallback(intl, {}, message);
}
export function permalinkBadTeam(intl: IntlShape) {
const message = {
id: t('mobile.server_link.unreachable_team.error'),
defaultMessage: 'This link belongs to a deleted team or to a team to which you do not have access.',
};
alertErrorWithFallback(intl, {}, message);
}
export function alertErrorWithFallback(intl: IntlShape, error: any, fallback: MessageDescriptor, values?: Record<string, string>, buttons?: AlertButton[]) {
let msg = error?.message;
if (!msg || msg === 'Network request failed') {
msg = intl.formatMessage(fallback, values);
}
Alert.alert('', msg, buttons);
}
export function alertAttachmentFail(intl: IntlShape, accept: AlertCallback, cancel: AlertCallback) {
Alert.alert(
intl.formatMessage({
id: 'mobile.post_textbox.uploadFailedTitle',
defaultMessage: 'Attachment failure',
}),
intl.formatMessage({
id: 'mobile.post_textbox.uploadFailedDesc',
defaultMessage: 'Some attachments failed to upload to the server. Are you sure you want to post the message?',
}),
[{
text: intl.formatMessage({id: 'mobile.channel_info.alertNo', defaultMessage: 'No'}),
onPress: cancel,
}, {
text: intl.formatMessage({id: 'mobile.channel_info.alertYes', defaultMessage: 'Yes'}),
onPress: accept,
}],
);
}
export const textContainsAtAllAtChannel = (text: string) => {
const textWithoutCode = text.replace(CODE_REGEX, '');
return (/(?:\B|\b_+)@(channel|all)(?!(\.|-|_)*[^\W_])/i).test(textWithoutCode);
};
export const textContainsAtHere = (text: string) => {
const textWithoutCode = text.replace(CODE_REGEX, '');
return (/(?:\B|\b_+)@(here)(?!(\.|-|_)*[^\W_])/i).test(textWithoutCode);
};
export function buildChannelWideMentionMessage(intl: IntlShape, membersCount: number, channelTimezoneCount: number, atHere: boolean) {
let notifyAllMessage = '';
if (channelTimezoneCount) {
const msgID = atHere ? t('mobile.post_textbox.entire_channel_here.message.with_timezones') : t('mobile.post_textbox.entire_channel.message.with_timezones');
const atHereMsg = 'By using @here you are about to send notifications up to {totalMembers, number} {totalMembers, plural, one {person} other {people}} in {timezones, number} {timezones, plural, one {timezone} other {timezones}}. Are you sure you want to do this?';
const atAllOrChannelMsg = 'By using @all or @channel you are about to send notifications to {totalMembers, number} {totalMembers, plural, one {person} other {people}} in {timezones, number} {timezones, plural, one {timezone} other {timezones}}. Are you sure you want to do this?';
notifyAllMessage = (
intl.formatMessage(
{
id: msgID,
defaultMessage: atHere ? atHereMsg : atAllOrChannelMsg,
},
{
totalMembers: membersCount - 1,
timezones: channelTimezoneCount,
},
)
);
} else {
const msgID = atHere ? t('mobile.post_textbox.entire_channel_here.message') : t('mobile.post_textbox.entire_channel.message');
const atHereMsg = 'By using @here you are about to send notifications to up to {totalMembers, number} {totalMembers, plural, one {person} other {people}}. Are you sure you want to do this?';
const atAllOrChannelMsg = 'By using @all or @channel you are about to send notifications to {totalMembers, number} {totalMembers, plural, one {person} other {people}}. Are you sure you want to do this?';
notifyAllMessage = (
intl.formatMessage(
{
id: msgID,
defaultMessage: atHere ? atHereMsg : atAllOrChannelMsg,
},
{
totalMembers: membersCount - 1,
},
)
);
}
return notifyAllMessage;
}
export function alertChannelWideMention(intl: IntlShape, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
const message = intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.title',
defaultMessage: 'Confirm sending notifications to entire channel',
});
alertMessage(intl, message, notifyAllMessage, accept, cancel);
}
export function alertSendToGroups(intl: IntlShape, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
const message = intl.formatMessage({
id: 'mobile.post_textbox.groups.title',
defaultMessage: 'Confirm sending notifications to groups',
});
alertMessage(intl, message, notifyAllMessage, accept, cancel);
}
function alertMessage(intl: IntlShape, message: string, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
Alert.alert(
message,
notifyAllMessage,
[
{
text: intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.cancel',
defaultMessage: 'Cancel',
}),
onPress: cancel,
},
{
text: intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.confirm',
defaultMessage: 'Confirm',
}),
onPress: accept,
},
],
);
}
export const getStatusFromSlashCommand = (message: string) => {
const tokens = message.split(' ');
const command = tokens[0]?.substring(1);
return General.STATUS_COMMANDS.includes(command) ? command : '';
};
export function alertSlashCommandFailed(intl: IntlShape, error: string) {
Alert.alert(
intl.formatMessage({
id: 'mobile.commands.error_title',
defaultMessage: 'Error Executing Command',
}),
error,
);
}
export const handleDraftUpdate = async ({
serverUrl,
channelId,
rootId,
value,
}: {
serverUrl: string;
channelId: string;
rootId: string;
value: string;
}) => {
await updateDraftMessage(serverUrl, channelId, rootId, value);
const imageMetadata: Dictionary<PostImage | undefined> = {};
await parseMarkdownImages(value, imageMetadata);
if (Object.keys(imageMetadata).length !== 0) {
updateDraftMarkdownImageMetadata({serverUrl, channelId, rootId, imageMetadata});
}
};
export function deleteDraftConfirmation({intl, serverUrl, channelId, rootId, swipeable}: {
intl: IntlShape;
serverUrl: string;
channelId: string;
rootId: string;
swipeable?: React.RefObject<SwipeableMethods>;
}) {
const deleteDraft = async () => {
removeDraft(serverUrl, channelId, rootId);
};
const onDismiss = () => {
if (swipeable?.current) {
swipeable.current.close();
}
};
Alert.alert(
intl.formatMessage({
id: 'draft.options.delete.title',
defaultMessage: 'Delete draft',
}),
intl.formatMessage({
id: 'draft.options.delete.confirmation',
defaultMessage: 'Are you sure you want to delete this draft?',
}),
[
{
text: intl.formatMessage({
id: 'draft.options.delete.cancel',
defaultMessage: 'Cancel',
}),
style: 'cancel',
onPress: onDismiss,
},
{
text: intl.formatMessage({
id: 'draft.options.delete.confirm',
defaultMessage: 'Delete',
}),
onPress: deleteDraft,
},
],
);
}