background.ts/conversation_view.ts modules, Whisper.View/ToastView in TS

This commit is contained in:
Scott Nonnenberg 2021-02-26 13:06:37 -08:00 committed by Josh Perez
parent 2aa2aca9f2
commit d0e3a2ce29
34 changed files with 957 additions and 887 deletions

View file

@ -0,0 +1,35 @@
// Copyright 2015-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
window.Whisper = window.Whisper || {};
window.Whisper.ToastView = window.Whisper.View.extend({
className: 'toast',
template: () => $('#toast').html(),
initialize() {
this.$el.hide();
this.timeout = 2000;
},
close() {
this.$el.fadeOut(this.remove.bind(this));
},
render() {
this.$el.html(
window.Mustache.render(
window._.result(this, 'template', ''),
window._.result(this, 'render_attributes', '')
)
);
this.$el.attr('tabIndex', 0);
this.$el.show();
setTimeout(this.close.bind(this), this.timeout);
},
});
window.Whisper.ToastView.show = (View, el) => {
const toast = new View();
toast.$el.appendTo(el);
toast.render();
};

View file

@ -0,0 +1,32 @@
// Copyright 2015-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/*
* Defines a default definition for render() which allows sub-classes
* to simply specify a template property and renderAttributes which are plugged
* into Mustache.render
*/
// eslint-disable-next-line func-names
(function () {
window.Whisper = window.Whisper || {};
window.Whisper.View = Backbone.View.extend({
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
constructor(...params: Array<any>) {
window.Backbone.View.call(this, ...params);
// Checks for syntax errors
window.Mustache.parse(_.result(this, 'template'));
},
render_attributes() {
return _.result(this.model, 'attributes', {});
},
render() {
const attrs = window._.result(this, 'render_attributes', {});
const template = window._.result(this, 'template', '');
this.$el.html(window.Mustache.render(template, attrs));
return this;
},
});
})();

View file

@ -1,15 +1,10 @@
// Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
// This allows us to pull in types despite the fact that this is not a module. We can't
// use normal import syntax, nor can we use 'import type' syntax, or this will be turned
// into a module, and we'll get the dreaded 'exports is not defined' error.
// see https://github.com/microsoft/TypeScript/issues/41562
type DataMessageClass = import('./textsecure.d').DataMessageClass;
type WhatIsThis = import('./window.d').WhatIsThis;
import { DataMessageClass } from './textsecure.d';
import { WhatIsThis } from './window.d';
// eslint-disable-next-line func-names
(async function () {
export async function startApp(): Promise<void> {
const eventHandlerQueue = new window.PQueue({
concurrency: 1,
timeout: 1000 * 60 * 2,
@ -23,7 +18,7 @@ type WhatIsThis = import('./window.d').WhatIsThis;
wait: 500,
maxSize: 500,
processBatch: async (items: WhatIsThis) => {
const byConversationId = _.groupBy(items, item =>
const byConversationId = window._.groupBy(items, item =>
window.ConversationController.ensureContactIds({
e164: item.source,
uuid: item.sourceUuid,
@ -205,12 +200,12 @@ type WhatIsThis = import('./window.d').WhatIsThis;
if (messageReceiver) {
return messageReceiver.getStatus();
}
if (_.isNumber(preMessageReceiverStatus)) {
if (window._.isNumber(preMessageReceiverStatus)) {
return preMessageReceiverStatus;
}
return WebSocket.CLOSED;
};
window.Whisper.events = _.clone(window.Backbone.Events);
window.Whisper.events = window._.clone(window.Backbone.Events);
let accountManager: typeof window.textsecure.AccountManager;
window.getAccountManager = () => {
if (!accountManager) {
@ -2632,7 +2627,7 @@ type WhatIsThis = import('./window.d').WhatIsThis;
sentTo = data.unidentifiedStatus.map(
(item: WhatIsThis) => item.destinationUuid || item.destination
);
const unidentified = _.filter(data.unidentifiedStatus, item =>
const unidentified = window._.filter(data.unidentifiedStatus, item =>
Boolean(item.unidentified)
);
// eslint-disable-next-line no-param-reassign
@ -3284,4 +3279,6 @@ type WhatIsThis = import('./window.d').WhatIsThis;
// Note: We don't wait for completion here
window.Whisper.DeliveryReceipts.onReceipt(receipt);
}
})();
}
window.startApp = startApp;

View file

@ -61,7 +61,7 @@ export async function joinViaLink(hash: string): Promise<void> {
window.reduxActions.conversations.openConversationInternal({
conversationId: existingConversation.id,
});
window.window.Whisper.ToastView.show(
window.Whisper.ToastView.show(
window.Whisper.AlreadyGroupMemberToast,
document.getElementsByClassName('conversation-stack')[0]
);
@ -333,7 +333,7 @@ export async function joinViaLink(hash: string): Promise<void> {
window.log.info(`joinViaLink/${logId}: Showing modal`);
let groupV2InfoDialog = new Whisper.ReactWrapperView({
let groupV2InfoDialog = new window.Whisper.ReactWrapperView({
className: 'group-v2-join-dialog-wrapper',
JSX: window.Signal.State.Roots.createGroupV2JoinModal(window.reduxStore, {
join,

View file

@ -4052,7 +4052,7 @@ export class ConversationModel extends window.Backbone.Model<
this.set({ left: true });
window.Signal.Data.updateConversation(this.attributes);
const model = new Whisper.Message(({
const model = new window.Whisper.Message(({
group_update: { left: 'You' },
conversationId: this.id,
type: 'outgoing',
@ -4062,7 +4062,7 @@ export class ConversationModel extends window.Backbone.Model<
} as unknown) as MessageAttributesType);
const id = await window.Signal.Data.saveMessage(model.attributes, {
Message: Whisper.Message,
Message: window.Whisper.Message,
});
model.set({ id });
@ -5128,13 +5128,13 @@ window.Whisper.ConversationCollection = window.Backbone.Collection.extend({
// We create a new model if it's not already a model
if (!item.get) {
hydratedData.push(new Whisper.Conversation(item));
hydratedData.push(new window.Whisper.Conversation(item));
} else {
hydratedData.push(item);
}
}
} else if (!data.get) {
hydratedData = new Whisper.Conversation(data);
hydratedData = new window.Whisper.Conversation(data);
} else {
hydratedData = data;
}

View file

@ -13,7 +13,7 @@ type ConfirmationDialogViewProps = {
confirmStyle?: 'affirmative' | 'negative';
message: string;
okText: string;
reject?: () => void;
reject?: (error: Error) => void;
resolve: () => void;
};
@ -65,7 +65,7 @@ function showConfirmationDialog(options: ConfirmationDialogViewProps) {
onClose={() => {
removeConfirmationDialog();
if (options.reject) {
options.reject();
options.reject(new Error('showConfirmationDialog: onClose called'));
}
}}
title={options.message}

View file

@ -22,7 +22,7 @@ describe('Message', () => {
const ourUuid = window.getGuid();
function createMessage(attrs: { [key: string]: unknown }) {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
return messages.add(attrs);
}
@ -136,13 +136,13 @@ describe('Message', () => {
describe('getContact', () => {
it('gets outgoing contact', () => {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
const message = messages.add(attributes);
message.getContact();
});
it('gets incoming contact', () => {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
const message = messages.add({
type: 'incoming',
source,
@ -153,7 +153,7 @@ describe('Message', () => {
describe('isIncoming', () => {
it('checks if is incoming message', () => {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
let message = messages.add(attributes);
assert.notOk(message.isIncoming());
message = messages.add({ type: 'incoming' });
@ -163,7 +163,7 @@ describe('Message', () => {
describe('isOutgoing', () => {
it('checks if is outgoing message', () => {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
let message = messages.add(attributes);
assert.ok(message.isOutgoing());
message = messages.add({ type: 'incoming' });
@ -173,7 +173,7 @@ describe('Message', () => {
describe('isGroupUpdate', () => {
it('checks if is group update', () => {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
let message = messages.add(attributes);
assert.notOk(message.isGroupUpdate());
@ -584,7 +584,7 @@ describe('Message', () => {
describe('isEndSession', () => {
it('checks if it is end of the session', () => {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
let message = messages.add(attributes);
assert.notOk(message.isEndSession());
@ -596,7 +596,7 @@ describe('Message', () => {
describe('MessageCollection', () => {
it('should be ordered oldest to newest', () => {
const messages = new Whisper.MessageCollection();
const messages = new window.Whisper.MessageCollection();
// Timestamps
const today = Date.now();
const tomorrow = today + 12345;

File diff suppressed because it is too large Load diff

View file

@ -16,14 +16,14 @@ export async function longRunningTaskWrapper<T>({
const ONE_SECOND = 1000;
const TWO_SECONDS = 2000;
let progressView: typeof Whisper.ReactWrapperView | undefined;
let progressView: typeof window.Whisper.ReactWrapperView | undefined;
let spinnerStart;
let progressTimeout: NodeJS.Timeout | undefined = setTimeout(() => {
window.log.info(`longRunningTaskWrapper/${idLog}: Creating spinner`);
// Note: this component uses a portal to render itself into the top-level DOM. No
// need to attach it to the DOM here.
progressView = new Whisper.ReactWrapperView({
progressView = new window.Whisper.ReactWrapperView({
className: 'progress-modal-wrapper',
Component: window.Signal.Components.ProgressModal,
});
@ -76,7 +76,7 @@ export async function longRunningTaskWrapper<T>({
// Note: this component uses a portal to render itself into the top-level DOM. No
// need to attach it to the DOM here.
const errorView = new Whisper.ReactWrapperView({
const errorView = new window.Whisper.ReactWrapperView({
className: 'error-modal-wrapper',
Component: window.Signal.Components.ErrorModal,
props: {

View file

@ -3,14 +3,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// This allows us to pull in types despite the fact that this is not a module. We can't
// use normal import syntax, nor can we use 'import type' syntax, or this will be turned
// into a module, and we'll get the dreaded 'exports is not defined' error.
// see https://github.com/microsoft/TypeScript/issues/41562
type AttachmentType = import('../types/Attachment').AttachmentType;
type GroupV2PendingMemberType = import('../model-types.d').GroupV2PendingMemberType;
type MediaItemType = import('../components/LightboxGallery').MediaItemType;
type MessageType = import('../state/ducks/conversations').MessageType;
import { AttachmentType } from '../types/Attachment';
import { GroupV2PendingMemberType } from '../model-types.d';
import { MediaItemType } from '../components/LightboxGallery';
import { MessageType } from '../state/ducks/conversations';
type GetLinkPreviewImageResult = {
data: ArrayBuffer;
@ -250,7 +246,7 @@ Whisper.MessageBodyTooLongToast = Whisper.ToastView.extend({
});
Whisper.FileSizeToast = Whisper.ToastView.extend({
templateName: 'file-size-modal',
template: () => $('#file-size-modal').html(),
render_attributes() {
return {
'file-size-warning': window.i18n('fileSizeWarning'),
@ -267,31 +263,31 @@ Whisper.UnableToLoadToast = Whisper.ToastView.extend({
});
Whisper.DangerousFileTypeToast = Whisper.ToastView.extend({
template: window.i18n('dangerousFileType'),
template: () => window.i18n('dangerousFileType'),
});
Whisper.OneNonImageAtATimeToast = Whisper.ToastView.extend({
template: window.i18n('oneNonImageAtATimeToast'),
template: () => window.i18n('oneNonImageAtATimeToast'),
});
Whisper.CannotMixImageAndNonImageAttachmentsToast = Whisper.ToastView.extend({
template: window.i18n('cannotMixImageAndNonImageAttachments'),
template: () => window.i18n('cannotMixImageAndNonImageAttachments'),
});
Whisper.MaxAttachmentsToast = Whisper.ToastView.extend({
template: window.i18n('maximumAttachments'),
template: () => window.i18n('maximumAttachments'),
});
Whisper.AlreadyGroupMemberToast = Whisper.ToastView.extend({
template: window.i18n('GroupV2--join--already-in-group'),
template: () => window.i18n('GroupV2--join--already-in-group'),
});
Whisper.AlreadyRequestedToJoinToast = Whisper.ToastView.extend({
template: window.i18n('GroupV2--join--already-awaiting-approval'),
template: () => window.i18n('GroupV2--join--already-awaiting-approval'),
});
Whisper.ConversationLoadingScreen = Whisper.View.extend({
templateName: 'conversation-loading-screen',
template: () => $('#conversation-loading-screen').html(),
className: 'conversation-loading-screen',
});
@ -302,7 +298,7 @@ Whisper.ConversationView = Whisper.View.extend({
id() {
return `conversation-${this.model.cid}`;
},
template: $('#conversation').html(),
template: () => $('#conversation').html(),
render_attributes() {
return {
'send-message': window.i18n('sendMessage'),
@ -374,31 +370,37 @@ Whisper.ConversationView = Whisper.View.extend({
this.downloadNewVersion
);
this.lazyUpdateVerified = _.debounce(
this.lazyUpdateVerified = window._.debounce(
this.model.updateVerified.bind(this.model),
1000 // one second
);
this.model.throttledGetProfiles =
this.model.throttledGetProfiles ||
_.throttle(this.model.getProfiles.bind(this.model), FIVE_MINUTES);
window._.throttle(this.model.getProfiles.bind(this.model), FIVE_MINUTES);
this.model.throttledUpdateSharedGroups =
this.model.throttledUpdateSharedGroups ||
_.throttle(this.model.updateSharedGroups.bind(this.model), FIVE_MINUTES);
window._.throttle(
this.model.updateSharedGroups.bind(this.model),
FIVE_MINUTES
);
this.model.throttledFetchLatestGroupV2Data =
this.model.throttledFetchLatestGroupV2Data ||
_.throttle(
window._.throttle(
this.model.fetchLatestGroupV2Data.bind(this.model),
FIVE_MINUTES
);
this.model.throttledMaybeMigrateV1Group =
this.model.throttledMaybeMigrateV1Group ||
_.throttle(this.model.maybeMigrateV1Group.bind(this.model), FIVE_MINUTES);
window._.throttle(
this.model.maybeMigrateV1Group.bind(this.model),
FIVE_MINUTES
);
this.debouncedMaybeGrabLinkPreview = _.debounce(
this.debouncedMaybeGrabLinkPreview = window._.debounce(
this.maybeGrabLinkPreview.bind(this),
200
);
this.debouncedSaveDraft = _.debounce(this.saveDraft.bind(this), 200);
this.debouncedSaveDraft = window._.debounce(this.saveDraft.bind(this), 200);
this.render();
@ -1506,7 +1508,7 @@ Whisper.ConversationView = Whisper.View.extend({
const draftAttachments = this.model.get('draftAttachments') || [];
this.model.set({
draftAttachments: _.reject(
draftAttachments: window._.reject(
draftAttachments,
item => item.path === attachment.path
),
@ -1553,7 +1555,7 @@ Whisper.ConversationView = Whisper.View.extend({
}
const draftAttachments = this.model.get('draftAttachments') || [];
const files = _.compact(
const files = window._.compact(
await Promise.all(
draftAttachments.map((attachment: any) => this.getFile(attachment))
)
@ -1575,7 +1577,7 @@ Whisper.ConversationView = Whisper.View.extend({
}
return {
..._.pick(attachment, [
...window._.pick(attachment, [
'contentType',
'fileName',
'size',
@ -1620,14 +1622,14 @@ Whisper.ConversationView = Whisper.View.extend({
if (toWrite.data) {
const path = await writeNewDraftData(toWrite.data);
toWrite = {
..._.omit(toWrite, ['data']),
...window._.omit(toWrite, ['data']),
path,
};
}
if (toWrite.screenshotData) {
const screenshotPath = await writeNewDraftData(toWrite.screenshotData);
toWrite = {
..._.omit(toWrite, ['screenshotData']),
...window._.omit(toWrite, ['screenshotData']),
screenshotPath,
};
}
@ -3168,19 +3170,23 @@ Whisper.ConversationView = Whisper.View.extend({
},
async destroyMessages() {
try {
await this.confirm(window.i18n('deleteConversationConfirmation'));
this.longRunningTaskWrapper({
name: 'destroymessages',
task: async () => {
this.model.trigger('unload', 'delete messages');
await this.model.destroyMessages();
this.model.updateLastMessage();
},
});
} catch (error) {
// nothing to see here, user canceled out of dialog
}
window.showConfirmationDialog({
message: window.i18n('deleteConversationConfirmation'),
okText: window.i18n('delete'),
resolve: () => {
this.longRunningTaskWrapper({
name: 'destroymessages',
task: async () => {
this.model.trigger('unload', 'delete messages');
await this.model.destroyMessages();
this.model.updateLastMessage();
},
});
},
reject: () => {
window.log.info('destroyMessages: User canceled delete');
},
});
},
async isCallSafe() {
@ -3981,7 +3987,7 @@ Whisper.ConversationView = Whisper.View.extend({
// We eliminate the ObjectURL here, unneeded for send or save
return {
...item,
image: _.omit(item.image, 'url'),
image: window._.omit(item.image, 'url'),
};
}

66
ts/window.d.ts vendored
View file

@ -107,7 +107,7 @@ type ConfirmationDialogViewProps = {
confirmStyle?: 'affirmative' | 'negative';
message: string;
okText: string;
reject?: () => void;
reject?: (error: Error) => void;
resolve: () => void;
};
@ -115,6 +115,8 @@ declare global {
// We want to extend `window`'s properties, so we need an interface.
// eslint-disable-next-line no-restricted-syntax
interface Window {
startApp: () => void;
_: typeof Underscore;
$: typeof jQuery;
@ -127,6 +129,10 @@ declare global {
PQueue: typeof PQueue;
PQueueType: PQueue;
Mustache: {
render: (template: string, data: any, partials?: any) => string;
parse: (template: string) => void;
};
WhatIsThis: WhatIsThis;
@ -655,7 +661,7 @@ export type WhisperType = {
ClearDataView: WhatIsThis;
ReactWrapperView: WhatIsThis;
activeConfirmationView: WhatIsThis;
ToastView: typeof Whisper.View & {
ToastView: typeof window.Whisper.View & {
show: (view: typeof Backbone.View, el: Element) => void;
};
ConversationArchivedToast: WhatIsThis;
@ -731,33 +737,35 @@ export type WhisperType = {
deliveryReceiptBatcher: BatcherType<WhatIsThis>;
RotateSignedPreKeyListener: WhatIsThis;
AlreadyGroupMemberToast: typeof Whisper.ToastView;
AlreadyRequestedToJoinToast: typeof Whisper.ToastView;
BlockedGroupToast: typeof Whisper.ToastView;
BlockedToast: typeof Whisper.ToastView;
CannotMixImageAndNonImageAttachmentsToast: typeof Whisper.ToastView;
DangerousFileTypeToast: typeof Whisper.ToastView;
ExpiredToast: typeof Whisper.ToastView;
FileSavedToast: typeof Whisper.ToastView;
AlreadyGroupMemberToast: typeof window.Whisper.ToastView;
AlreadyRequestedToJoinToast: typeof window.Whisper.ToastView;
BlockedGroupToast: typeof window.Whisper.ToastView;
BlockedToast: typeof window.Whisper.ToastView;
CannotMixImageAndNonImageAttachmentsToast: typeof window.Whisper.ToastView;
DangerousFileTypeToast: typeof window.Whisper.ToastView;
ExpiredToast: typeof window.Whisper.ToastView;
FileSavedToast: typeof window.Whisper.ToastView;
FileSizeToast: any;
FoundButNotLoadedToast: typeof Whisper.ToastView;
InvalidConversationToast: typeof Whisper.ToastView;
LeftGroupToast: typeof Whisper.ToastView;
MaxAttachmentsToast: typeof Whisper.ToastView;
MessageBodyTooLongToast: typeof Whisper.ToastView;
OneNonImageAtATimeToast: typeof Whisper.ToastView;
OriginalNoLongerAvailableToast: typeof Whisper.ToastView;
OriginalNotFoundToast: typeof Whisper.ToastView;
PinnedConversationsFullToast: typeof Whisper.ToastView;
ReactionFailedToast: typeof Whisper.ToastView;
TapToViewExpiredIncomingToast: typeof Whisper.ToastView;
TapToViewExpiredOutgoingToast: typeof Whisper.ToastView;
TimerConflictToast: typeof Whisper.ToastView;
UnableToLoadToast: typeof Whisper.ToastView;
VoiceNoteLimit: typeof Whisper.ToastView;
VoiceNoteMustBeOnlyAttachmentToast: typeof Whisper.ToastView;
FoundButNotLoadedToast: typeof window.Whisper.ToastView;
InvalidConversationToast: typeof window.Whisper.ToastView;
LeftGroupToast: typeof window.Whisper.ToastView;
MaxAttachmentsToast: typeof window.Whisper.ToastView;
MessageBodyTooLongToast: typeof window.Whisper.ToastView;
OneNonImageAtATimeToast: typeof window.Whisper.ToastView;
OriginalNoLongerAvailableToast: typeof window.Whisper.ToastView;
OriginalNotFoundToast: typeof window.Whisper.ToastView;
PinnedConversationsFullToast: typeof window.Whisper.ToastView;
ReactionFailedToast: typeof window.Whisper.ToastView;
TapToViewExpiredIncomingToast: typeof window.Whisper.ToastView;
TapToViewExpiredOutgoingToast: typeof window.Whisper.ToastView;
TimerConflictToast: typeof window.Whisper.ToastView;
UnableToLoadToast: typeof window.Whisper.ToastView;
VoiceNoteLimit: typeof window.Whisper.ToastView;
VoiceNoteMustBeOnlyAttachmentToast: typeof window.Whisper.ToastView;
ConversationLoadingScreen: typeof Whisper.View;
ConversationView: typeof Whisper.View;
View: typeof Backbone.View;
ConversationLoadingScreen: typeof window.Whisper.View;
ConversationView: typeof window.Whisper.View;
View: typeof Backbone.View & {
Templates: Record<string, string>;
};
};