Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: translate channel log #32612

Merged
merged 3 commits into from
Dec 12, 2023
Merged
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
13 changes: 9 additions & 4 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {CONST as COMMON_CONST} from 'expensify-common/lib/CONST';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import CONST from '@src/CONST';
import type {
AddressLineParams,
Expand Down Expand Up @@ -428,9 +427,9 @@ export default {
copyEmailToClipboard: 'Copy email to clipboard',
markAsUnread: 'Mark as unread',
markAsRead: 'Mark as read',
editAction: ({action}: EditActionParams) => `Edit ${ReportActionsUtils.isMoneyRequestAction(action) ? 'request' : 'comment'}`,
deleteAction: ({action}: DeleteActionParams) => `Delete ${ReportActionsUtils.isMoneyRequestAction(action) ? 'request' : 'comment'}`,
deleteConfirmation: ({action}: DeleteConfirmationParams) => `Are you sure you want to delete this ${ReportActionsUtils.isMoneyRequestAction(action) ? 'request' : 'comment'}?`,
editAction: ({action}: EditActionParams) => `Edit ${action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? 'request' : 'comment'}`,
deleteAction: ({action}: DeleteActionParams) => `Delete ${action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? 'request' : 'comment'}`,
deleteConfirmation: ({action}: DeleteConfirmationParams) => `Are you sure you want to delete this ${action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? 'request' : 'comment'}?`,
Comment on lines +430 to +432
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this related?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, Currently the error happen because required cycle. In en.ts import ReportActionsUtils and ReportActionsUtils.ts we import Localize.ts.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onlyVisible: 'Only visible to',
replyInThread: 'Reply in thread',
subscribeToThread: 'Subscribe to thread',
Expand Down Expand Up @@ -1557,6 +1556,12 @@ export default {
invitePeople: 'Invite new members',
genericFailureMessage: 'An error occurred inviting the user to the workspace, please try again.',
pleaseEnterValidLogin: `Please ensure the email or phone number is valid (e.g. ${CONST.EXAMPLE_PHONE_NUMBER}).`,
user: 'user',
users: 'users',
invited: 'invited',
removed: 'removed',
to: 'to',
from: 'from',
},
inviteMessage: {
inviteMessageTitle: 'Add message',
Expand Down
14 changes: 10 additions & 4 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import CONST from '@src/CONST';
import type {
AddressLineParams,
Expand Down Expand Up @@ -419,9 +418,10 @@ export default {
copyEmailToClipboard: 'Copiar email al portapapeles',
markAsUnread: 'Marcar como no leído',
markAsRead: 'Marcar como leído',
editAction: ({action}: EditActionParams) => `Edit ${ReportActionsUtils.isMoneyRequestAction(action) ? 'pedido' : 'comentario'}`,
deleteAction: ({action}: DeleteActionParams) => `Eliminar ${ReportActionsUtils.isMoneyRequestAction(action) ? 'pedido' : 'comentario'}`,
deleteConfirmation: ({action}: DeleteConfirmationParams) => `¿Estás seguro de que quieres eliminar este ${ReportActionsUtils.isMoneyRequestAction(action) ? 'pedido' : 'comentario'}`,
editAction: ({action}: EditActionParams) => `Edit ${action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? 'pedido' : 'comentario'}`,
deleteAction: ({action}: DeleteActionParams) => `Eliminar ${action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? 'pedido' : 'comentario'}`,
deleteConfirmation: ({action}: DeleteConfirmationParams) =>
`¿Estás seguro de que quieres eliminar este ${action?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU ? 'pedido' : 'comentario'}`,
onlyVisible: 'Visible sólo para',
replyInThread: 'Responder en el hilo',
subscribeToThread: 'Suscribirse al hilo',
Expand Down Expand Up @@ -1579,6 +1579,12 @@ export default {
invitePeople: 'Invitar nuevos miembros',
genericFailureMessage: 'Se produjo un error al invitar al usuario al espacio de trabajo. Vuelva a intentarlo..',
pleaseEnterValidLogin: `Asegúrese de que el correo electrónico o el número de teléfono sean válidos (p. ej. ${CONST.EXAMPLE_PHONE_NUMBER}).`,
user: 'usuario',
users: 'usuarios',
invited: 'invitó',
removed: 'eliminó',
to: 'a',
from: 'de',
},
inviteMessage: {
inviteMessageTitle: 'Añadir un mensaje',
Expand Down
46 changes: 40 additions & 6 deletions src/libs/Localize/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as RNLocalize from 'react-native-localize';
import Onyx from 'react-native-onyx';
import Log from '@libs/Log';
import {MessageElementBase, MessageTextElement} from '@libs/MessageElement';
import Config from '@src/CONFIG';
import CONST from '@src/CONST';
import translations from '@src/languages/translations';
Expand Down Expand Up @@ -121,15 +122,48 @@ function translateIfPhraseKey(message: MaybePhraseKey): string {
}
}

function getPreferredListFormat(): Intl.ListFormat {
if (!CONJUNCTION_LIST_FORMATS_FOR_LOCALES) {
init();
}

return CONJUNCTION_LIST_FORMATS_FOR_LOCALES[BaseLocaleListener.getPreferredLocale()];
}

/**
* Format an array into a string with comma and "and" ("a dog, a cat and a chicken")
*/
function arrayToString(anArray: string[]) {
if (!CONJUNCTION_LIST_FORMATS_FOR_LOCALES) {
init();
function formatList(components: string[]) {
const listFormat = getPreferredListFormat();
return listFormat.format(components);
}

function formatMessageElementList<E extends MessageElementBase>(elements: readonly E[]): ReadonlyArray<E | MessageTextElement> {
const listFormat = getPreferredListFormat();
const parts = listFormat.formatToParts(elements.map((e) => e.content));
const resultElements: Array<E | MessageTextElement> = [];

let nextElementIndex = 0;
for (const part of parts) {
if (part.type === 'element') {
/**
* The standard guarantees that all input elements will be present in the constructed parts, each exactly
* once, and without any modifications: https://tc39.es/ecma402/#sec-createpartsfromlist
*/
const element = elements[nextElementIndex++];

resultElements.push(element);
} else {
const literalElement: MessageTextElement = {
kind: 'text',
content: part.value,
};

resultElements.push(literalElement);
}
}
const listFormat = CONJUNCTION_LIST_FORMATS_FOR_LOCALES[BaseLocaleListener.getPreferredLocale()];
return listFormat.format(anArray);

return resultElements;
}

/**
Expand All @@ -139,5 +173,5 @@ function getDevicePreferredLocale(): string {
return RNLocalize.findBestAvailableLanguage([CONST.LOCALES.EN, CONST.LOCALES.ES])?.languageTag ?? CONST.LOCALES.DEFAULT;
}

export {translate, translateLocal, translateIfPhraseKey, arrayToString, getDevicePreferredLocale};
export {translate, translateLocal, translateIfPhraseKey, formatList, formatMessageElementList, getDevicePreferredLocale};
export type {PhraseParameters, Phrase, MaybePhraseKey};
11 changes: 11 additions & 0 deletions src/libs/MessageElement.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
type MessageElementBase = {
readonly kind: string;
readonly content: string;
};

type MessageTextElement = {
readonly kind: 'text';
readonly content: string;
} & MessageElementBase;

export type {MessageElementBase, MessageTextElement};
13 changes: 13 additions & 0 deletions src/libs/PersonalDetailsUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,18 @@ function getFormattedAddress(privatePersonalDetails) {
return formattedAddress.trim().replace(/,$/, '');
}

/**
* @param {Object} personalDetail - details object
* @returns {String | undefined} - The effective display name
*/
function getEffectiveDisplayName(personalDetail) {
if (personalDetail) {
return LocalePhoneNumber.formatPhoneNumber(personalDetail.login) || personalDetail.displayName;
}

return undefined;
}

export {
getDisplayNameOrDefault,
getPersonalDetailsByIDs,
Expand All @@ -206,4 +218,5 @@ export {
getFormattedAddress,
getFormattedStreet,
getStreetLines,
getEffectiveDisplayName,
};
113 changes: 109 additions & 4 deletions src/libs/ReportActionsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,37 @@ import OnyxUtils from 'react-native-onyx/lib/utils';
import {ValueOf} from 'type-fest';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {ActionName} from '@src/types/onyx/OriginalMessage';
import {ActionName, ChangeLog} from '@src/types/onyx/OriginalMessage';
import Report from '@src/types/onyx/Report';
import ReportAction, {ReportActions} from '@src/types/onyx/ReportAction';
import ReportAction, {Message, ReportActions} from '@src/types/onyx/ReportAction';
import {EmptyObject, isEmptyObject} from '@src/types/utils/EmptyObject';
import * as CollectionUtils from './CollectionUtils';
import * as Environment from './Environment/Environment';
import isReportMessageAttachment from './isReportMessageAttachment';
import * as Localize from './Localize';
import Log from './Log';
import {MessageElementBase, MessageTextElement} from './MessageElement';
import * as PersonalDetailsUtils from './PersonalDetailsUtils';

type LastVisibleMessage = {
lastMessageTranslationKey?: string;
lastMessageText: string;
lastMessageHtml?: string;
};

type MemberChangeMessageUserMentionElement = {
readonly kind: 'userMention';
readonly accountID: number;
} & MessageElementBase;

type MemberChangeMessageRoomReferenceElement = {
readonly kind: 'roomReference';
readonly roomName: string;
readonly roomID: number;
} & MessageElementBase;

type MemberChangeMessageElement = MessageTextElement | MemberChangeMessageUserMentionElement | MemberChangeMessageRoomReferenceElement;

const allReports: OnyxCollection<Report> = {};
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
Expand Down Expand Up @@ -104,7 +120,7 @@ function isReimbursementQueuedAction(reportAction: OnyxEntry<ReportAction>) {
return reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENTQUEUED;
}

function isChannelLogMemberAction(reportAction: OnyxEntry<ReportAction>) {
function isMemberChangeAction(reportAction: OnyxEntry<ReportAction>) {
return (
reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ROOMCHANGELOG.INVITE_TO_ROOM ||
reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ROOMCHANGELOG.REMOVE_FROM_ROOM ||
Expand All @@ -113,6 +129,10 @@ function isChannelLogMemberAction(reportAction: OnyxEntry<ReportAction>) {
);
}

function isInviteMemberAction(reportAction: OnyxEntry<ReportAction>) {
return reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ROOMCHANGELOG.INVITE_TO_ROOM || reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.POLICYCHANGELOG.INVITE_TO_ROOM;
}

function isReimbursementDeQueuedAction(reportAction: OnyxEntry<ReportAction>): boolean {
return reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.REIMBURSEMENTDEQUEUED;
}
Expand Down Expand Up @@ -653,6 +673,89 @@ function isNotifiableReportAction(reportAction: OnyxEntry<ReportAction>): boolea
return actions.includes(reportAction.actionName);
}

function getMemberChangeMessageElements(reportAction: OnyxEntry<ReportAction>): readonly MemberChangeMessageElement[] {
const isInviteAction = isInviteMemberAction(reportAction);

// Currently, we only render messages when members are invited
const verb = isInviteAction ? Localize.translateLocal('workspace.invite.invited') : Localize.translateLocal('workspace.invite.removed');

const originalMessage = reportAction?.originalMessage as ChangeLog;
const targetAccountIDs: number[] = originalMessage?.targetAccountIDs ?? [];
const personalDetails = PersonalDetailsUtils.getPersonalDetailsByIDs(targetAccountIDs, 0);

const mentionElements = targetAccountIDs.map((accountID): MemberChangeMessageUserMentionElement => {
const personalDetail = personalDetails.find((personal) => personal.accountID === accountID);
const handleText = PersonalDetailsUtils.getEffectiveDisplayName(personalDetail) ?? Localize.translateLocal('common.hidden');

return {
kind: 'userMention',
content: `@${handleText}`,
accountID,
};
});

const buildRoomElements = (): readonly MemberChangeMessageElement[] => {
const roomName = originalMessage?.roomName;

if (roomName) {
const preposition = isInviteAction ? ` ${Localize.translateLocal('workspace.invite.to')} ` : ` ${Localize.translateLocal('workspace.invite.from')} `;

if (originalMessage.reportID) {
return [
{
kind: 'text',
content: preposition,
},
{
kind: 'roomReference',
roomName,
roomID: originalMessage.reportID,
content: roomName,
},
];
}
}

return [];
};

return [
{
kind: 'text',
content: `${verb} `,
},
...Localize.formatMessageElementList(mentionElements),
...buildRoomElements(),
];
}

function getMemberChangeMessageFragment(reportAction: OnyxEntry<ReportAction>): Message {
const messageElements: readonly MemberChangeMessageElement[] = getMemberChangeMessageElements(reportAction);
const html = messageElements
.map((messageElement) => {
switch (messageElement.kind) {
case 'userMention':
return `<mention-user accountID=${messageElement.accountID}></mention-user>`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@namhihi237 Why didn't we include the mentioned display name here? Did it cause any regression? For example:

`<mention-user accountID=${messageElement.accountID}>${messageElement.content}</mention-user>`

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tienifr As I know currently mention-user use MentionUserRenderer to display, in here the display name will get by accountID if we pass accountID

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if we use like you mention i think the ${messageElement.content} does not effect because we pass the accountID

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah thanks! I just want to make sure adding ${messageElement.content} does not cause any issue.

case 'roomReference':
return `<a href="${environmentURL}/r/${messageElement.roomID}" target="_blank">${messageElement.roomName}</a>`;
default:
return messageElement.content;
}
})
.join('');

return {
html: `<muted-text>${html}</muted-text>`,
text: reportAction?.message ? reportAction?.message[0].text : '',
type: CONST.REPORT.MESSAGE.TYPE.COMMENT,
};
}

function getMemberChangeMessagePlainText(reportAction: OnyxEntry<ReportAction>): string {
const messageElements = getMemberChangeMessageElements(reportAction);
return messageElements.map((element) => element.content).join('');
}

/**
* Helper method to determine if the provided accountID has made a request on the specified report.
*
Expand Down Expand Up @@ -716,7 +819,9 @@ export {
shouldReportActionBeVisibleAsLastAction,
hasRequestFromCurrentAccount,
getFirstVisibleReportActionID,
isChannelLogMemberAction,
isMemberChangeAction,
getMemberChangeMessageFragment,
getMemberChangeMessagePlainText,
isReimbursementDeQueuedAction,
};

Expand Down
41 changes: 1 addition & 40 deletions src/libs/ReportUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import {Beta, Login, PersonalDetails, PersonalDetailsList, Policy, PolicyTags, Report, ReportAction, Session, Transaction} from '@src/types/onyx';
import {Errors, Icon, PendingAction} from '@src/types/onyx/OnyxCommon';
import {ChangeLog, IOUMessage, OriginalMessageActionName, OriginalMessageCreated} from '@src/types/onyx/OriginalMessage';
import {IOUMessage, OriginalMessageActionName, OriginalMessageCreated} from '@src/types/onyx/OriginalMessage';
import {NotificationPreference} from '@src/types/onyx/Report';
import {Message, ReportActionBase, ReportActions} from '@src/types/onyx/ReportAction';
import {Receipt, WaypointCollection} from '@src/types/onyx/Transaction';
Expand Down Expand Up @@ -4226,44 +4226,6 @@ function getIOUReportActionDisplayMessage(reportAction: OnyxEntry<ReportAction>)
});
}

/**
* Return room channel log display message
*/
function getChannelLogMemberMessage(reportAction: OnyxEntry<ReportAction>): string {
const verb =
reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ROOMCHANGELOG.INVITE_TO_ROOM || reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.POLICYCHANGELOG.INVITE_TO_ROOM
? 'invited'
: 'removed';

const mentions = (reportAction?.originalMessage as ChangeLog)?.targetAccountIDs?.map(() => {
const personalDetail = allPersonalDetails?.accountID;
const displayNameOrLogin = LocalePhoneNumber.formatPhoneNumber(personalDetail?.login ?? '') || (personalDetail?.displayName ?? '') || Localize.translateLocal('common.hidden');
return `@${displayNameOrLogin}`;
});

const lastMention = mentions?.pop();
let message = '';

if (mentions?.length === 0) {
message = `${verb} ${lastMention}`;
} else if (mentions?.length === 1) {
message = `${verb} ${mentions?.[0]} and ${lastMention}`;
} else {
message = `${verb} ${mentions?.join(', ')}, and ${lastMention}`;
}

const roomName = (reportAction?.originalMessage as ChangeLog)?.roomName ?? '';
if (roomName) {
const preposition =
reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ROOMCHANGELOG.INVITE_TO_ROOM || reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.POLICYCHANGELOG.INVITE_TO_ROOM
? ' to'
: ' from';
message += `${preposition} ${roomName}`;
}

return message;
}

/**
* Checks if a report is a group chat.
*
Expand Down Expand Up @@ -4517,7 +4479,6 @@ export {
getReimbursementQueuedActionMessage,
getReimbursementDeQueuedActionMessage,
getPersonalDetailsForAccountID,
getChannelLogMemberMessage,
getRoom,
shouldDisableWelcomeMessage,
navigateToPrivateNotes,
Expand Down
Loading
Loading