From d239eff9dc211a517a7da64a126a2fc9c2b9e637 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Sun, 1 May 2022 10:14:28 +0100 Subject: [PATCH 1/6] Apply corrections identified by SonarQube --- .../views/settings/tabs/user/HelpUserSettingsTab.tsx | 2 +- src/stores/spaces/SpaceStore.ts | 2 +- src/utils/beacon/useOwnLiveBeacons.ts | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/components/views/settings/tabs/user/HelpUserSettingsTab.tsx b/src/components/views/settings/tabs/user/HelpUserSettingsTab.tsx index 346c0c5bb1a..45ffa3e8ba4 100644 --- a/src/components/views/settings/tabs/user/HelpUserSettingsTab.tsx +++ b/src/components/views/settings/tabs/user/HelpUserSettingsTab.tsx @@ -148,7 +148,7 @@ export default class HelpUserSettingsTab extends React.Component Mozilla Foundation used under the terms of  - Apache 2.0. + Apache 2.0.
  • The diff --git a/src/stores/spaces/SpaceStore.ts b/src/stores/spaces/SpaceStore.ts index 42e1bf01bf1..fa0f662ffba 100644 --- a/src/stores/spaces/SpaceStore.ts +++ b/src/stores/spaces/SpaceStore.ts @@ -732,7 +732,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient { const newPath = new Set(parentPath).add(spaceId); childSpaces.forEach(childSpace => { - traverseSpace(childSpace.roomId, newPath) ?? []; + traverseSpace(childSpace.roomId, newPath); }); hiddenChildren.get(spaceId)?.forEach(roomId => { roomIds.add(roomId); diff --git a/src/utils/beacon/useOwnLiveBeacons.ts b/src/utils/beacon/useOwnLiveBeacons.ts index 1eb892f0c33..d83a66a1d4f 100644 --- a/src/utils/beacon/useOwnLiveBeacons.ts +++ b/src/utils/beacon/useOwnLiveBeacons.ts @@ -80,7 +80,9 @@ export const useOwnLiveBeacons = (liveBeaconIds: BeaconIdentifier[]): LiveBeacon }; const onResetLocationPublishError = () => { - liveBeaconIds.map(beaconId => OwnBeaconStore.instance.resetLocationPublishError(beaconId)); + liveBeaconIds.forEach(beaconId => { + OwnBeaconStore.instance.resetLocationPublishError(beaconId); + }); }; return { From f12cd6b60041f2a96f8f097d54795f272e4e3bba Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Sun, 1 May 2022 10:58:19 +0100 Subject: [PATCH 2/6] Apply corrections identified by SonarQube --- src/ContentMessages.ts | 16 +++++----------- src/HtmlUtils.tsx | 12 ++++++++---- src/KeyBindingsDefaults.ts | 17 +++++------------ src/Lifecycle.ts | 2 +- src/Markdown.ts | 1 - src/RoomInvite.tsx | 6 +----- src/SecurityManager.ts | 8 +++++--- src/TextForEvent.tsx | 16 ++++++++++------ .../security/CreateSecretStorageDialog.tsx | 2 +- src/autocomplete/Autocompleter.ts | 2 +- src/boundThreepids.ts | 2 +- src/components/structures/RoomDirectory.tsx | 3 +-- src/components/structures/SpaceHierarchy.tsx | 11 +++++------ src/components/structures/SpaceRoomView.tsx | 3 +-- src/components/structures/UserMenu.tsx | 7 +++---- .../views/context_menus/MessageContextMenu.tsx | 3 +-- src/components/views/dialogs/ExportDialog.tsx | 4 ++-- .../views/dialogs/MessageEditHistoryDialog.tsx | 3 ++- .../views/dialogs/SpotlightDialog.tsx | 14 +++++++------- .../security/CreateCrossSigningDialog.tsx | 4 ++-- .../views/directory/NetworkDropdown.tsx | 3 +-- .../elements/IRCTimelineProfileResizer.tsx | 2 +- src/components/views/emojipicker/Category.tsx | 4 ++-- .../views/emojipicker/EmojiPicker.tsx | 4 ++-- .../views/emojipicker/QuickReactions.tsx | 4 ++-- .../views/location/LocationShareMenu.tsx | 3 +-- src/components/views/rooms/NewRoomIntro.tsx | 9 ++++----- src/components/views/rooms/RoomList.tsx | 3 +-- src/components/views/rooms/RoomSublist.tsx | 3 +-- src/components/views/rooms/RoomTile.tsx | 15 +++++++-------- .../views/rooms/VoiceRecordComposerTile.tsx | 2 +- .../views/settings/DevicesPanelEntry.tsx | 3 +-- .../views/settings/EventIndexPanel.tsx | 2 +- src/customisations/Media.ts | 3 ++- src/editor/autocomplete.ts | 4 ++-- src/indexing/EventIndex.ts | 2 -- src/performance/index.ts | 3 ++- src/rageshake/rageshake.ts | 2 +- src/rageshake/submit-rageshake.ts | 2 +- src/resizer/item.ts | 2 +- src/resizer/resizer.ts | 4 ++-- src/settings/watchers/FontWatcher.ts | 2 +- src/stores/OwnBeaconStore.ts | 5 +---- src/stores/local-echo/RoomEchoChamber.ts | 4 ++-- src/stores/right-panel/RightPanelStore.ts | 1 - src/stores/spaces/SpaceStore.ts | 11 +++++------ src/utils/DMRoomMap.ts | 3 ++- src/utils/MegolmExportEncryption.ts | 2 +- src/utils/beacon/geolocation.ts | 3 ++- src/utils/drawable.ts | 2 +- src/utils/exportUtils/HtmlExport.tsx | 5 ++--- src/utils/image-media.ts | 4 ++-- src/utils/permalinks/Permalinks.ts | 4 +++- src/utils/rooms.ts | 3 +-- src/utils/space.tsx | 10 ++++------ 55 files changed, 125 insertions(+), 149 deletions(-) diff --git a/src/ContentMessages.ts b/src/ContentMessages.ts index 1d54b1adc3a..7cb0ad1db9c 100644 --- a/src/ContentMessages.ts +++ b/src/ContentMessages.ts @@ -380,11 +380,11 @@ export default class ContentMessages { const tooBigFiles = []; const okFiles = []; - for (let i = 0; i < files.length; ++i) { - if (this.isFileSizeAcceptable(files[i])) { - okFiles.push(files[i]); + for (const file of files) { + if (this.isFileSizeAcceptable(file)) { + okFiles.push(file); } else { - tooBigFiles.push(files[i]); + tooBigFiles.push(file); } } @@ -450,13 +450,7 @@ export default class ContentMessages { } public cancelUpload(promise: Promise, matrixClient: MatrixClient): void { - let upload: IUpload; - for (let i = 0; i < this.inprogress.length; ++i) { - if (this.inprogress[i].promise === promise) { - upload = this.inprogress[i]; - break; - } - } + const upload = this.inprogress.find(item => item.promise === promise); if (upload) { upload.canceled = true; matrixClient.cancelUpload(upload.promise); diff --git a/src/HtmlUtils.tsx b/src/HtmlUtils.tsx index ac26eccc718..7f92653c30b 100644 --- a/src/HtmlUtils.tsx +++ b/src/HtmlUtils.tsx @@ -27,13 +27,17 @@ import katex from 'katex'; import { AllHtmlEntities } from 'html-entities'; import { IContent } from 'matrix-js-sdk/src/models/event'; -import { _linkifyElement, _linkifyString } from './linkify-matrix'; +import { + _linkifyElement, + _linkifyString, + ELEMENT_URL_PATTERN, + options as linkifyMatrixOptions, +} from './linkify-matrix'; import { IExtendedSanitizeOptions } from './@types/sanitize-html'; import SettingsStore from './settings/SettingsStore'; import { tryTransformPermalinkToLocalHref } from "./utils/permalinks/Permalinks"; import { getEmojiFromUnicode } from "./emoji"; import { mediaFromMxc } from "./customisations/Media"; -import { ELEMENT_URL_PATTERN, options as linkifyMatrixOptions } from './linkify-matrix'; import { stripHTMLReply, stripPlainReply } from './utils/Reply'; // Anything outside the basic multilingual plane will be a surrogate pair @@ -45,10 +49,10 @@ const SURROGATE_PAIR_PATTERN = /([\ud800-\udbff])([\udc00-\udfff])/; const SYMBOL_PATTERN = /([\u2100-\u2bff])/; // Regex pattern for Zero-Width joiner unicode characters -const ZWJ_REGEX = new RegExp("\u200D|\u2003", "g"); +const ZWJ_REGEX = /[\u200D\u2003]/g; // Regex pattern for whitespace characters -const WHITESPACE_REGEX = new RegExp("\\s", "g"); +const WHITESPACE_REGEX = /\s/g; const BIGEMOJI_REGEX = new RegExp(`^(${EMOJIBASE_REGEX.source})+$`, 'i'); diff --git a/src/KeyBindingsDefaults.ts b/src/KeyBindingsDefaults.ts index d4f4ffc6811..083b31b87cb 100644 --- a/src/KeyBindingsDefaults.ts +++ b/src/KeyBindingsDefaults.ts @@ -18,11 +18,7 @@ limitations under the License. import { isMac, Key } from "./Keyboard"; import SettingsStore from "./settings/SettingsStore"; import SdkConfig from "./SdkConfig"; -import { - IKeyBindingsProvider, - KeyBinding, - KeyCombo, -} from "./KeyBindingsManager"; +import { IKeyBindingsProvider, KeyBinding } from "./KeyBindingsManager"; import { CATEGORIES, CategoryName, @@ -31,13 +27,10 @@ import { import { getKeyboardShortcuts } from "./accessibility/KeyboardShortcutUtils"; export const getBindingsByCategory = (category: CategoryName): KeyBinding[] => { - return CATEGORIES[category].settingNames.reduce((bindings, name) => { - const value = getKeyboardShortcuts()[name]?.default; - if (value) { - bindings.push({ - action: name as KeyBindingAction, - keyCombo: value as KeyCombo, - }); + return CATEGORIES[category].settingNames.reduce((bindings, action) => { + const keyCombo = getKeyboardShortcuts()[action]?.default; + if (keyCombo) { + bindings.push({ action, keyCombo }); } return bindings; }, []); diff --git a/src/Lifecycle.ts b/src/Lifecycle.ts index f91158c38aa..c521677b812 100644 --- a/src/Lifecycle.ts +++ b/src/Lifecycle.ts @@ -832,7 +832,7 @@ async function startMatrixClient(startSyncing = true): Promise { } // Now that we have a MatrixClientPeg, update the Jitsi info - await Jitsi.getInstance().start(); + Jitsi.getInstance().start(); // dispatch that we finished starting up to wire up any other bits // of the matrix client that cannot be set prior to starting up. diff --git a/src/Markdown.ts b/src/Markdown.ts index 9f88fbe41f1..a4cf1681aff 100644 --- a/src/Markdown.ts +++ b/src/Markdown.ts @@ -305,7 +305,6 @@ export default class Markdown { renderer.html_inline = function(node: commonmark.Node) { if (isAllowedHtmlTag(node)) { this.lit(node.literal); - return; } else { this.lit(escape(node.literal)); } diff --git a/src/RoomInvite.tsx b/src/RoomInvite.tsx index 200da2f7cf8..188bd33b2d3 100644 --- a/src/RoomInvite.tsx +++ b/src/RoomInvite.tsx @@ -88,12 +88,8 @@ export function isValid3pidInvite(event: MatrixEvent): boolean { // any events without these keys are not valid 3pid invites, so we ignore them const requiredKeys = ['key_validity_url', 'public_key', 'display_name']; - for (let i = 0; i < requiredKeys.length; ++i) { - if (!event.getContent()[requiredKeys[i]]) return false; - } - // Valid enough by our standards - return true; + return requiredKeys.every(key => !!event.getContent()[key]); } export function inviteUsersToRoom( diff --git a/src/SecurityManager.ts b/src/SecurityManager.ts index f3d254d0590..9bc23f580de 100644 --- a/src/SecurityManager.ts +++ b/src/SecurityManager.ts @@ -83,9 +83,11 @@ async function confirmToDismiss(): Promise { return !sure; } +type KeyParams = { passphrase: string, recoveryKey: string }; + function makeInputToKey( keyInfo: ISecretStorageKeyInfo, -): (keyParams: { passphrase: string, recoveryKey: string }) => Promise { +): (keyParams: KeyParams) => Promise { return async ({ passphrase, recoveryKey }) => { if (passphrase) { return deriveKey( @@ -154,9 +156,9 @@ async function getSecretStorageKey( /* props= */ { keyInfo, - checkPrivateKey: async (input) => { + checkPrivateKey: async (input: KeyParams) => { const key = await inputToKey(input); - return await MatrixClientPeg.get().checkSecretStorageKey(key, keyInfo); + return MatrixClientPeg.get().checkSecretStorageKey(key, keyInfo); }, }, /* className= */ null, diff --git a/src/TextForEvent.tsx b/src/TextForEvent.tsx index bb6d9eab3c7..04d1726f3d5 100644 --- a/src/TextForEvent.tsx +++ b/src/TextForEvent.tsx @@ -224,7 +224,7 @@ const onViewJoinRuleSettingsClick = () => { }); }; -function textForJoinRulesEvent(ev: MatrixEvent, allowJSX: boolean): () => string | JSX.Element | null { +function textForJoinRulesEvent(ev: MatrixEvent, allowJSX: boolean): () => Renderable { const senderDisplayName = ev.sender && ev.sender.name ? ev.sender.name : ev.getSender(); switch (ev.getContent().join_rule) { case JoinRule.Public: @@ -281,7 +281,7 @@ function textForServerACLEvent(ev: MatrixEvent): () => string | null { const prev = { deny: Array.isArray(prevContent.deny) ? prevContent.deny : [], allow: Array.isArray(prevContent.allow) ? prevContent.allow : [], - allow_ip_literals: !(prevContent.allow_ip_literals === false), + allow_ip_literals: prevContent.allow_ip_literals !== false, }; let getText = null; @@ -372,13 +372,15 @@ function textForCanonicalAliasEvent(ev: MatrixEvent): () => string | null { addresses: addedAltAliases.join(", "), count: addedAltAliases.length, }); - } if (removedAltAliases.length && !addedAltAliases.length) { + } + if (removedAltAliases.length && !addedAltAliases.length) { return () => _t('%(senderName)s removed the alternative addresses %(addresses)s for this room.', { senderName, addresses: removedAltAliases.join(", "), count: removedAltAliases.length, }); - } if (removedAltAliases.length && addedAltAliases.length) { + } + if (removedAltAliases.length && addedAltAliases.length) { return () => _t('%(senderName)s changed the alternative addresses for this room.', { senderName, }); @@ -504,7 +506,7 @@ const onPinnedMessagesClick = (): void => { RightPanelStore.instance.setCard({ phase: RightPanelPhases.PinnedMessages }, false); }; -function textForPinnedEvent(event: MatrixEvent, allowJSX: boolean): () => string | JSX.Element | null { +function textForPinnedEvent(event: MatrixEvent, allowJSX: boolean): () => Renderable { if (!SettingsStore.getValue("feature_pinning")) return null; const senderName = getSenderName(event); const roomId = event.getRoomId(); @@ -758,10 +760,12 @@ function textForPollEndEvent(event: MatrixEvent): () => string | null { }); } +type Renderable = string | JSX.Element | null; + interface IHandlers { [type: string]: (ev: MatrixEvent, allowJSX: boolean, showHiddenEvents?: boolean) => - (() => string | JSX.Element | null); + (() => Renderable); } const handlers: IHandlers = { diff --git a/src/async-components/views/dialogs/security/CreateSecretStorageDialog.tsx b/src/async-components/views/dialogs/security/CreateSecretStorageDialog.tsx index 53df137f6d6..190e683cf2b 100644 --- a/src/async-components/views/dialogs/security/CreateSecretStorageDialog.tsx +++ b/src/async-components/views/dialogs/security/CreateSecretStorageDialog.tsx @@ -276,7 +276,7 @@ export default class CreateSecretStorageDialog extends React.PureComponent void): Promise => { if (this.state.canUploadKeysWithPasswordOnly && this.state.accountPassword) { - await makeRequest({ + makeRequest({ type: 'm.login.password', identifier: { type: 'm.id.user', diff --git a/src/autocomplete/Autocompleter.ts b/src/autocomplete/Autocompleter.ts index 880f4e68732..0c7ef1afb2e 100644 --- a/src/autocomplete/Autocompleter.ts +++ b/src/autocomplete/Autocompleter.ts @@ -95,7 +95,7 @@ export default class Autocompleter { */ // list of results from each provider, each being a list of completions or null if it times out const completionsList: ICompletion[][] = await Promise.all(this.providers.map(async provider => { - return await timeout( + return timeout( provider.getCompletions(query, selection, force, limit), null, PROVIDER_COMPLETION_TIMEOUT, diff --git a/src/boundThreepids.ts b/src/boundThreepids.ts index a703d10fd78..6421c1309aa 100644 --- a/src/boundThreepids.ts +++ b/src/boundThreepids.ts @@ -53,7 +53,7 @@ export async function getThreepidsWithBindStatus( } } catch (e) { // Ignore terms errors here and assume other flows handle this - if (!(e.errcode === "M_TERMS_NOT_SIGNED")) { + if (e.errcode !== "M_TERMS_NOT_SIGNED") { throw e; } } diff --git a/src/components/structures/RoomDirectory.tsx b/src/components/structures/RoomDirectory.tsx index 99aeb6f5478..aa8f38556a7 100644 --- a/src/components/structures/RoomDirectory.tsx +++ b/src/components/structures/RoomDirectory.tsx @@ -26,7 +26,7 @@ import dis from "../../dispatcher/dispatcher"; import Modal from "../../Modal"; import { _t } from '../../languageHandler'; import SdkConfig from '../../SdkConfig'; -import { instanceForInstanceId, protocolNameForInstanceId } from '../../utils/DirectoryUtils'; +import { instanceForInstanceId, protocolNameForInstanceId, ALL_ROOMS, Protocols } from '../../utils/DirectoryUtils'; import Analytics from '../../Analytics'; import NetworkDropdown from "../views/directory/NetworkDropdown"; import SettingsStore from "../../settings/SettingsStore"; @@ -43,7 +43,6 @@ import PosthogTrackers from "../../PosthogTrackers"; import { PublicRoomTile } from "../views/rooms/PublicRoomTile"; import { getFieldsForThirdPartyLocation, joinRoomByAlias, showRoom } from "../../utils/rooms"; import { GenericError } from "../../utils/error"; -import { ALL_ROOMS, Protocols } from "../../utils/DirectoryUtils"; const LAST_SERVER_KEY = "mx_last_room_directory_server"; const LAST_INSTANCE_KEY = "mx_last_room_directory_instance"; diff --git a/src/components/structures/SpaceHierarchy.tsx b/src/components/structures/SpaceHierarchy.tsx index 756cacab1fe..89790e46746 100644 --- a/src/components/structures/SpaceHierarchy.tsx +++ b/src/components/structures/SpaceHierarchy.tsx @@ -36,7 +36,6 @@ import classNames from "classnames"; import { sortBy, uniqBy } from "lodash"; import { GuestAccess, HistoryVisibility } from "matrix-js-sdk/src/@types/partials"; -import dis from "../../dispatcher/dispatcher"; import defaultDispatcher from "../../dispatcher/dispatcher"; import { _t } from "../../languageHandler"; import AccessibleButton, { ButtonEvent } from "../views/elements/AccessibleButton"; @@ -330,13 +329,13 @@ export const showRoom = (cli: MatrixClient, hierarchy: RoomHierarchy, roomId: st // fail earlier so they don't have to click back to the directory. if (cli.isGuest()) { if (!room.world_readable && !room.guest_can_join) { - dis.dispatch({ action: "require_registration" }); + defaultDispatcher.dispatch({ action: "require_registration" }); return; } } const roomAlias = getDisplayAliasForRoom(room) || undefined; - dis.dispatch({ + defaultDispatcher.dispatch({ action: Action.ViewRoom, should_peek: true, room_alias: roomAlias, @@ -356,7 +355,7 @@ export const joinRoom = (cli: MatrixClient, hierarchy: RoomHierarchy, roomId: st // Don't let the user view a room they won't be able to either peek or join: // fail earlier so they don't have to click back to the directory. if (cli.isGuest()) { - dis.dispatch({ action: "require_registration" }); + defaultDispatcher.dispatch({ action: "require_registration" }); return; } @@ -365,7 +364,7 @@ export const joinRoom = (cli: MatrixClient, hierarchy: RoomHierarchy, roomId: st }); prom.then(() => { - dis.dispatch({ + defaultDispatcher.dispatch({ action: Action.JoinRoomReady, roomId, metricsTrigger: "SpaceHierarchy", @@ -569,7 +568,7 @@ const ManageButtons = ({ hierarchy, selected, setSelected, setError }: IManageBu const selectedRelations = Array.from(selected.keys()).flatMap(parentId => { return [ ...selected.get(parentId).values(), - ].map(childId => [parentId, childId]) as [string, string][]; + ].map(childId => [parentId, childId]); }); const selectionAllSuggested = selectedRelations.every(([parentId, childId]) => { diff --git a/src/components/structures/SpaceRoomView.tsx b/src/components/structures/SpaceRoomView.tsx index 1e9d5caa0cf..189800229b6 100644 --- a/src/components/structures/SpaceRoomView.tsx +++ b/src/components/structures/SpaceRoomView.tsx @@ -36,7 +36,6 @@ import { useTypedEventEmitter } from "../../hooks/useEventEmitter"; import withValidation from "../views/elements/Validation"; import * as Email from "../../email"; import defaultDispatcher from "../../dispatcher/dispatcher"; -import dis from "../../dispatcher/dispatcher"; import { Action } from "../../dispatcher/actions"; import ResizeNotifier from "../../utils/ResizeNotifier"; import MainSplit from './MainSplit'; @@ -204,7 +203,7 @@ const SpacePreview = ({ space, onJoinButtonClicked, onRejectButtonClicked }: ISp { - dis.dispatch({ + defaultDispatcher.dispatch({ action: "leave_room", room_id: space.roomId, }); diff --git a/src/components/structures/UserMenu.tsx b/src/components/structures/UserMenu.tsx index 27cc08f0bcc..78f1e29d003 100644 --- a/src/components/structures/UserMenu.tsx +++ b/src/components/structures/UserMenu.tsx @@ -20,7 +20,6 @@ import classNames from "classnames"; import { MatrixClientPeg } from "../../MatrixClientPeg"; import defaultDispatcher from "../../dispatcher/dispatcher"; -import dis from "../../dispatcher/dispatcher"; import { ActionPayload } from "../../dispatcher/payloads"; import { Action } from "../../dispatcher/actions"; import { _t } from "../../languageHandler"; @@ -323,7 +322,7 @@ export default class UserMenu extends React.Component { const cli = MatrixClientPeg.get(); if (!cli || !cli.isCryptoEnabled() || !(await cli.exportRoomKeys())?.length) { // log out without user prompt if they have no local megolm sessions - dis.dispatch({ action: 'logout' }); + defaultDispatcher.dispatch({ action: 'logout' }); } else { Modal.createTrackedDialog('Logout from LeftPanel', '', LogoutDialog); } @@ -332,12 +331,12 @@ export default class UserMenu extends React.Component { }; private onSignInClick = () => { - dis.dispatch({ action: 'start_login' }); + defaultDispatcher.dispatch({ action: 'start_login' }); this.setState({ contextMenuPosition: null }); // also close the menu }; private onRegisterClick = () => { - dis.dispatch({ action: 'start_registration' }); + defaultDispatcher.dispatch({ action: 'start_registration' }); this.setState({ contextMenuPosition: null }); // also close the menu }; diff --git a/src/components/views/context_menus/MessageContextMenu.tsx b/src/components/views/context_menus/MessageContextMenu.tsx index 917091ece83..cf61ee5bfdd 100644 --- a/src/components/views/context_menus/MessageContextMenu.tsx +++ b/src/components/views/context_menus/MessageContextMenu.tsx @@ -37,12 +37,11 @@ import { Action } from "../../../dispatcher/actions"; import { RoomPermalinkCreator } from '../../../utils/permalinks/Permalinks'; import { ButtonEvent } from '../elements/AccessibleButton'; import { copyPlaintext, getSelectedText } from '../../../utils/strings'; -import ContextMenu, { toRightOf } from '../../structures/ContextMenu'; +import ContextMenu, { toRightOf, IPosition, ChevronFace } from '../../structures/ContextMenu'; import ReactionPicker from '../emojipicker/ReactionPicker'; import ViewSource from '../../structures/ViewSource'; import { createRedactEventDialog } from '../dialogs/ConfirmRedactDialog'; import ShareDialog from '../dialogs/ShareDialog'; -import { IPosition, ChevronFace } from '../../structures/ContextMenu'; import RoomContext, { TimelineRenderingType } from '../../../contexts/RoomContext'; import { ComposerInsertPayload } from "../../../dispatcher/payloads/ComposerInsertPayload"; import EndPollDialog from '../dialogs/EndPollDialog'; diff --git a/src/components/views/dialogs/ExportDialog.tsx b/src/components/views/dialogs/ExportDialog.tsx index 6881c1c52d8..5c1bf48cac2 100644 --- a/src/components/views/dialogs/ExportDialog.tsx +++ b/src/components/views/dialogs/ExportDialog.tsx @@ -200,7 +200,7 @@ const ExportDialog: React.FC = ({ room, onFinished }) => { }, { key: "number", test: ({ value }) => { - const parsedSize = parseInt(value as string, 10); + const parsedSize = parseInt(value, 10); return validateNumberInRange(1, 2000)(parsedSize); }, invalid: () => { @@ -238,7 +238,7 @@ const ExportDialog: React.FC = ({ room, onFinished }) => { }, { key: "number", test: ({ value }) => { - const parsedSize = parseInt(value as string, 10); + const parsedSize = parseInt(value, 10); return validateNumberInRange(1, 10 ** 8)(parsedSize); }, invalid: () => { diff --git a/src/components/views/dialogs/MessageEditHistoryDialog.tsx b/src/components/views/dialogs/MessageEditHistoryDialog.tsx index 2dedfb52937..0f51530a128 100644 --- a/src/components/views/dialogs/MessageEditHistoryDialog.tsx +++ b/src/components/views/dialogs/MessageEditHistoryDialog.tsx @@ -138,7 +138,8 @@ export default class MessageEditHistoryDialog extends React.PureComponent)); + /> + )); lastEvent = e; }); return nodes; diff --git a/src/components/views/dialogs/SpotlightDialog.tsx b/src/components/views/dialogs/SpotlightDialog.tsx index f579e262875..1d6078fa10c 100644 --- a/src/components/views/dialogs/SpotlightDialog.tsx +++ b/src/components/views/dialogs/SpotlightDialog.tsx @@ -367,16 +367,16 @@ const SpotlightDialog: React.FC = ({ initialText = "", onFinished }) => ); } - const otherResult = (result as IResult); + // IResult case return ( ); }; diff --git a/src/components/views/dialogs/security/CreateCrossSigningDialog.tsx b/src/components/views/dialogs/security/CreateCrossSigningDialog.tsx index ca5b1db9fbc..4b1928c3a73 100644 --- a/src/components/views/dialogs/security/CreateCrossSigningDialog.tsx +++ b/src/components/views/dialogs/security/CreateCrossSigningDialog.tsx @@ -93,7 +93,7 @@ export default class CreateCrossSigningDialog extends React.PureComponent void): Promise => { if (this.state.canUploadKeysWithPasswordOnly && this.state.accountPassword) { - await makeRequest({ + makeRequest({ type: 'm.login.password', identifier: { type: 'm.id.user', @@ -106,7 +106,7 @@ export default class CreateCrossSigningDialog extends React.PureComponent this.updateCSSWidth(this.state.width)); } diff --git a/src/components/views/emojipicker/Category.tsx b/src/components/views/emojipicker/Category.tsx index 7cd5b96bee8..d4ea4e89ffb 100644 --- a/src/components/views/emojipicker/Category.tsx +++ b/src/components/views/emojipicker/Category.tsx @@ -52,7 +52,7 @@ class Category extends React.PureComponent { const { onClick, onMouseEnter, onMouseLeave, selectedEmojis, emojis } = this.props; const emojisForRow = emojis.slice(rowIndex * 8, (rowIndex + 1) * 8); return (
    { - emojisForRow.map(emoji => (( + emojisForRow.map(emoji => ( { onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} /> - ))) + )) }
    ); }; diff --git a/src/components/views/emojipicker/EmojiPicker.tsx b/src/components/views/emojipicker/EmojiPicker.tsx index e064df405a4..461ef4f079a 100644 --- a/src/components/views/emojipicker/EmojiPicker.tsx +++ b/src/components/views/emojipicker/EmojiPicker.tsx @@ -249,7 +249,7 @@ class EmojiPicker extends React.Component { > { this.categories.map(category => { const emojis = this.memoizedDataByCategory[category.id]; - const categoryElement = (( + const categoryElement = ( { onMouseLeave={this.onHoverEmojiEnd} selectedEmojis={this.props.selectedEmojis} /> - )); + ); const height = EmojiPicker.categoryHeightForEmojiCount(emojis.length); heightBefore += height; return categoryElement; diff --git a/src/components/views/emojipicker/QuickReactions.tsx b/src/components/views/emojipicker/QuickReactions.tsx index c0336a759de..f53b30f565d 100644 --- a/src/components/views/emojipicker/QuickReactions.tsx +++ b/src/components/views/emojipicker/QuickReactions.tsx @@ -72,7 +72,7 @@ class QuickReactions extends React.Component { }
      - { QUICK_REACTIONS.map(emoji => (( + { QUICK_REACTIONS.map(emoji => ( { onMouseLeave={this.onMouseLeave} selectedEmojis={this.props.selectedEmojis} /> - ))) } + )) }
    ); diff --git a/src/components/views/location/LocationShareMenu.tsx b/src/components/views/location/LocationShareMenu.tsx index 8be6c070db2..795a7802375 100644 --- a/src/components/views/location/LocationShareMenu.tsx +++ b/src/components/views/location/LocationShareMenu.tsx @@ -21,11 +21,10 @@ import { IEventRelation } from 'matrix-js-sdk/src/models/event'; import MatrixClientContext from '../../../contexts/MatrixClientContext'; import ContextMenu, { AboveLeftOf } from '../../structures/ContextMenu'; import LocationPicker, { ILocationPickerProps } from "./LocationPicker"; -import { shareLiveLocation, shareLocation } from './shareLocation'; +import { shareLiveLocation, shareLocation, LocationShareType } from './shareLocation'; import SettingsStore from '../../../settings/SettingsStore'; import ShareDialogButtons from './ShareDialogButtons'; import ShareType from './ShareType'; -import { LocationShareType } from './shareLocation'; import { OwnProfileStore } from '../../../stores/OwnProfileStore'; import { EnableLiveShare } from './EnableLiveShare'; import { useFeatureEnabled } from '../../../hooks/useSettings'; diff --git a/src/components/views/rooms/NewRoomIntro.tsx b/src/components/views/rooms/NewRoomIntro.tsx index 363e687c9f9..9c9f190210d 100644 --- a/src/components/views/rooms/NewRoomIntro.tsx +++ b/src/components/views/rooms/NewRoomIntro.tsx @@ -28,7 +28,6 @@ import AccessibleButton from "../elements/AccessibleButton"; import MiniAvatarUploader, { AVATAR_SIZE } from "../elements/MiniAvatarUploader"; import RoomAvatar from "../avatars/RoomAvatar"; import defaultDispatcher from "../../../dispatcher/dispatcher"; -import dis from "../../../dispatcher/dispatcher"; import { ViewUserPayload } from "../../../dispatcher/payloads/ViewUserPayload"; import { Action } from "../../../dispatcher/actions"; import SpaceStore from "../../../stores/spaces/SpaceStore"; @@ -87,7 +86,7 @@ const NewRoomIntro = () => { const canAddTopic = inRoom && room.currentState.maySendStateEvent(EventType.RoomTopic, cli.getUserId()); const onTopicClick = () => { - dis.dispatch({ + defaultDispatcher.dispatch({ action: "open_room_settings", room_id: roomId, }, true); @@ -150,7 +149,7 @@ const NewRoomIntro = () => { className="mx_NewRoomIntro_inviteButton" kind="primary_outline" onClick={() => { - dis.dispatch({ action: "view_invite", roomId }); + defaultDispatcher.dispatch({ action: "view_invite", roomId }); }} > { _t("Invite to just this room") } @@ -162,7 +161,7 @@ const NewRoomIntro = () => { className="mx_NewRoomIntro_inviteButton" kind="primary" onClick={() => { - dis.dispatch({ action: "view_invite", roomId }); + defaultDispatcher.dispatch({ action: "view_invite", roomId }); }} > { _t("Invite to this room") } @@ -192,7 +191,7 @@ const NewRoomIntro = () => { function openRoomSettings(event) { event.preventDefault(); - dis.dispatch({ + defaultDispatcher.dispatch({ action: "open_room_settings", initial_tab_id: ROOM_SECURITY_TAB, }); diff --git a/src/components/views/rooms/RoomList.tsx b/src/components/views/rooms/RoomList.tsx index a7bc539a304..a0632d763e1 100644 --- a/src/components/views/rooms/RoomList.tsx +++ b/src/components/views/rooms/RoomList.tsx @@ -16,9 +16,8 @@ limitations under the License. import React, { ComponentType, createRef, ReactComponentElement, RefObject } from "react"; import { Room } from "matrix-js-sdk/src/models/room"; -import { RoomType } from "matrix-js-sdk/src/@types/event"; +import { RoomType, EventType } from "matrix-js-sdk/src/@types/event"; import * as fbEmitter from "fbemitter"; -import { EventType } from "matrix-js-sdk/src/@types/event"; import { _t, _td } from "../../../languageHandler"; import { IState as IRovingTabIndexState, RovingTabIndexProvider } from "../../../accessibility/RovingTabIndex"; diff --git a/src/components/views/rooms/RoomSublist.tsx b/src/components/views/rooms/RoomSublist.tsx index f0a66167145..df43341bf73 100644 --- a/src/components/views/rooms/RoomSublist.tsx +++ b/src/components/views/rooms/RoomSublist.tsx @@ -39,7 +39,6 @@ import ContextMenu, { import RoomListStore, { LISTS_UPDATE_EVENT } from "../../../stores/room-list/RoomListStore"; import { ListAlgorithm, SortAlgorithm } from "../../../stores/room-list/algorithms/models"; import { DefaultTagID, TagID } from "../../../stores/room-list/models"; -import dis from "../../../dispatcher/dispatcher"; import defaultDispatcher from "../../../dispatcher/dispatcher"; import { Action } from "../../../dispatcher/actions"; import NotificationBadge from "./NotificationBadge"; @@ -426,7 +425,7 @@ export default class RoomSublist extends React.Component { } if (room) { - dis.dispatch({ + defaultDispatcher.dispatch({ action: Action.ViewRoom, room_id: room.roomId, show_room_tile: true, // to make sure the room gets scrolled into view diff --git a/src/components/views/rooms/RoomTile.tsx b/src/components/views/rooms/RoomTile.tsx index 7b0a8e95de9..070f999c2fb 100644 --- a/src/components/views/rooms/RoomTile.tsx +++ b/src/components/views/rooms/RoomTile.tsx @@ -24,7 +24,6 @@ import { RoomStateEvent } from "matrix-js-sdk/src/models/room-state"; import { RovingTabIndexWrapper } from "../../../accessibility/RovingTabIndex"; import AccessibleButton, { ButtonEvent } from "../../views/elements/AccessibleButton"; -import dis from '../../../dispatcher/dispatcher'; import defaultDispatcher from '../../../dispatcher/dispatcher'; import { Action } from "../../../dispatcher/actions"; import SettingsStore from "../../../settings/SettingsStore"; @@ -260,7 +259,7 @@ export default class RoomTile extends React.PureComponent { const action = getKeyBindingsManager().getAccessibilityAction(ev); - dis.dispatch({ + defaultDispatcher.dispatch({ action: Action.ViewRoom, show_room_tile: true, // make sure the room is visible in the list room_id: this.props.room.roomId, @@ -321,7 +320,7 @@ export default class RoomTile extends React.PureComponent { const isApplied = RoomListStore.instance.getTagsForRoom(this.props.room).includes(tagId); const removeTag = isApplied ? tagId : inverseTag; const addTag = isApplied ? null : tagId; - dis.dispatch(RoomListActions.tagRoom( + defaultDispatcher.dispatch(RoomListActions.tagRoom( MatrixClientPeg.get(), this.props.room, removeTag, @@ -346,7 +345,7 @@ export default class RoomTile extends React.PureComponent { ev.preventDefault(); ev.stopPropagation(); - dis.dispatch({ + defaultDispatcher.dispatch({ action: 'leave_room', room_id: this.props.room.roomId, }); @@ -359,7 +358,7 @@ export default class RoomTile extends React.PureComponent { ev.preventDefault(); ev.stopPropagation(); - dis.dispatch({ + defaultDispatcher.dispatch({ action: 'forget_room', room_id: this.props.room.roomId, }); @@ -370,7 +369,7 @@ export default class RoomTile extends React.PureComponent { ev.preventDefault(); ev.stopPropagation(); - dis.dispatch({ + defaultDispatcher.dispatch({ action: 'open_room_settings', room_id: this.props.room.roomId, }); @@ -383,7 +382,7 @@ export default class RoomTile extends React.PureComponent { ev.preventDefault(); ev.stopPropagation(); - dis.dispatch({ + defaultDispatcher.dispatch({ action: 'copy_room', room_id: this.props.room.roomId, }); @@ -394,7 +393,7 @@ export default class RoomTile extends React.PureComponent { ev.preventDefault(); ev.stopPropagation(); - dis.dispatch({ + defaultDispatcher.dispatch({ action: 'view_invite', roomId: this.props.room.roomId, }); diff --git a/src/components/views/rooms/VoiceRecordComposerTile.tsx b/src/components/views/rooms/VoiceRecordComposerTile.tsx index 84898c8d086..27201bedbab 100644 --- a/src/components/views/rooms/VoiceRecordComposerTile.tsx +++ b/src/components/views/rooms/VoiceRecordComposerTile.tsx @@ -196,7 +196,7 @@ export default class VoiceRecordComposerTile extends React.PureComponent { await EventIndexPeg.initEventIndex(); await EventIndexPeg.get().addInitialCheckpoints(); - await EventIndexPeg.get().startCrawler(); + EventIndexPeg.get().startCrawler(); await SettingsStore.setValue('enableEventIndexing', null, SettingLevel.DEVICE, true); await this.updateState(); }; diff --git a/src/customisations/Media.ts b/src/customisations/Media.ts index ce8f88f6f12..6d9e9a8b62c 100644 --- a/src/customisations/Media.ts +++ b/src/customisations/Media.ts @@ -16,6 +16,7 @@ import { MatrixClient } from "matrix-js-sdk/src/client"; import { ResizeMethod } from "matrix-js-sdk/src/@types/partials"; +import { Optional } from "matrix-events-sdk"; import { MatrixClientPeg } from "../MatrixClientPeg"; import { IMediaEventContent, IPreparedMedia, prepEventContentAsMedia } from "./models/IMediaEventContent"; @@ -60,7 +61,7 @@ export class Media { * The MXC URI of the thumbnail media, if a thumbnail is recorded. Null/undefined * otherwise. */ - public get thumbnailMxc(): string | undefined | null { + public get thumbnailMxc(): Optional { return this.prepared.thumbnail?.mxc; } diff --git a/src/editor/autocomplete.ts b/src/editor/autocomplete.ts index 7a6cda9d44d..90dac75bce2 100644 --- a/src/editor/autocomplete.ts +++ b/src/editor/autocomplete.ts @@ -59,8 +59,8 @@ export default class AutocompleteWrapperModel { return ac && ac.countCompletions() > 0; } - public async confirmCompletion(): Promise { - await this.getAutocompleterComponent().onConfirmCompletion(); + public confirmCompletion(): void { + this.getAutocompleterComponent().onConfirmCompletion(); this.updateCallback({ close: true }); } diff --git a/src/indexing/EventIndex.ts b/src/indexing/EventIndex.ts index 85ff7038de0..cf199b25008 100644 --- a/src/indexing/EventIndex.ts +++ b/src/indexing/EventIndex.ts @@ -173,7 +173,6 @@ export default class EventIndex extends EventEmitter { // A sync was done, presumably we queued up some live events, // commit them now. await indexManager.commitLiveEvents(); - return; } }; @@ -650,7 +649,6 @@ export default class EventIndex extends EventEmitter { this.removeListeners(); this.stopCrawler(); await indexManager.closeEventIndex(); - return; } /** diff --git a/src/performance/index.ts b/src/performance/index.ts index ad523f0c649..35319c23f05 100644 --- a/src/performance/index.ts +++ b/src/performance/index.ts @@ -165,7 +165,8 @@ export default class PerformanceMonitor { * @returns {string} a compound of the name and identifier if present */ private buildKey(name: string, id?: string): string { - return `${name}${id ? `:${id}` : ''}`; + const suffix = id ? `:${id}` : ''; + return `${name}${suffix}`; } } diff --git a/src/rageshake/rageshake.ts b/src/rageshake/rageshake.ts index acffa254af0..44a60acd08c 100644 --- a/src/rageshake/rageshake.ts +++ b/src/rageshake/rageshake.ts @@ -524,7 +524,7 @@ export async function getLogsForReport() { if (global.mx_rage_store) { // flush most recent logs await global.mx_rage_store.flush(); - return await global.mx_rage_store.consume(); + return global.mx_rage_store.consume(); } else { return [{ lines: global.mx_rage_logger.flush(true), diff --git a/src/rageshake/submit-rageshake.ts b/src/rageshake/submit-rageshake.ts index 4822a9039c4..53b8f78c984 100644 --- a/src/rageshake/submit-rageshake.ts +++ b/src/rageshake/submit-rageshake.ts @@ -212,7 +212,7 @@ export default async function sendBugReport(bugReportEndpoint: string, opts: IOp const body = await collectBugReport(opts); progressCallback(_t("Uploading logs")); - return await submitReport(bugReportEndpoint, body, progressCallback); + return submitReport(bugReportEndpoint, body, progressCallback); } /** diff --git a/src/resizer/item.ts b/src/resizer/item.ts index 868cd8230f2..5d5c95a2573 100644 --- a/src/resizer/item.ts +++ b/src/resizer/item.ts @@ -30,7 +30,7 @@ export default class ResizeItem { ) { this.reverse = resizer.isReverseResizeHandle(handle); if (container) { - this.domNode = (container); + this.domNode = container; } else { this.domNode = (this.reverse ? handle.nextElementSibling : handle.previousElementSibling); } diff --git a/src/resizer/resizer.ts b/src/resizer/resizer.ts index f9e762aeaac..39bb3db20ae 100644 --- a/src/resizer/resizer.ts +++ b/src/resizer/resizer.ts @@ -195,11 +195,11 @@ export default class Resizer { return { sizer, distributor }; } - private getResizeHandles() { + private getResizeHandles(): HTMLElement[] { if (this?.config?.handler) { return [this.config.handler]; } if (!this.container?.children) return []; - return Array.from(this.container.querySelectorAll(`.${this.classNames.handle}`)) as HTMLElement[]; + return Array.from(this.container.querySelectorAll(`.${this.classNames.handle}`)); } } diff --git a/src/settings/watchers/FontWatcher.ts b/src/settings/watchers/FontWatcher.ts index 952a2eb9f3f..c70dd78349f 100644 --- a/src/settings/watchers/FontWatcher.ts +++ b/src/settings/watchers/FontWatcher.ts @@ -60,7 +60,7 @@ export class FontWatcher implements IWatcher { if (fontSize !== size) { SettingsStore.setValue("baseFontSize", null, SettingLevel.DEVICE, fontSize); } - (document.querySelector(":root")).style.fontSize = toPx(fontSize); + document.querySelector(":root").style.fontSize = toPx(fontSize); }; private setSystemFont = ({ useSystemFont, font }) => { diff --git a/src/stores/OwnBeaconStore.ts b/src/stores/OwnBeaconStore.ts index 609b85fae25..885c15b69dc 100644 --- a/src/stores/OwnBeaconStore.ts +++ b/src/stores/OwnBeaconStore.ts @@ -418,10 +418,7 @@ export class OwnBeaconStore extends AsyncStoreWithClient { this.stopPollingLocation(); try { - this.clearPositionWatch = await watchPosition( - this.onWatchedPosition, - this.onGeolocationError, - ); + this.clearPositionWatch = watchPosition(this.onWatchedPosition, this.onGeolocationError); } catch (error) { this.onGeolocationError(error?.message); // don't set locationInterval if geolocation failed to setup diff --git a/src/stores/local-echo/RoomEchoChamber.ts b/src/stores/local-echo/RoomEchoChamber.ts index f1e1fd6a4da..284aada23ea 100644 --- a/src/stores/local-echo/RoomEchoChamber.ts +++ b/src/stores/local-echo/RoomEchoChamber.ts @@ -49,8 +49,8 @@ export class RoomEchoChamber extends GenericEchoChamber { if (event.getType() === EventType.PushRules) { - const currentVolume = this.properties.get(CachedRoomKey.NotificationVolume) as RoomNotifState; - const newVolume = getRoomNotifsState(this.context.room.roomId) as RoomNotifState; + const currentVolume = this.properties.get(CachedRoomKey.NotificationVolume); + const newVolume = getRoomNotifsState(this.context.room.roomId); if (currentVolume !== newVolume) { this.updateNotificationVolume(); } diff --git a/src/stores/right-panel/RightPanelStore.ts b/src/stores/right-panel/RightPanelStore.ts index bb4ddc4fcbf..341474293ec 100644 --- a/src/stores/right-panel/RightPanelStore.ts +++ b/src/stores/right-panel/RightPanelStore.ts @@ -141,7 +141,6 @@ export default class RightPanelStore extends ReadyWatchingStore { const hist = this.byRoom[rId]?.history ?? []; hist[hist.length - 1].state = cardState; this.emitAndUpdateSettings(); - return; } else if (targetPhase !== this.currentCard?.phase) { // Set right panel and erase history. this.show(); diff --git a/src/stores/spaces/SpaceStore.ts b/src/stores/spaces/SpaceStore.ts index fa0f662ffba..e56d4854d76 100644 --- a/src/stores/spaces/SpaceStore.ts +++ b/src/stores/spaces/SpaceStore.ts @@ -1076,7 +1076,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient { }); const enabledMetaSpaces = SettingsStore.getValue("Spaces.enabledMetaSpaces"); - this._enabledMetaSpaces = metaSpaceOrder.filter(k => enabledMetaSpaces[k]) as MetaSpace[]; + this._enabledMetaSpaces = metaSpaceOrder.filter(k => enabledMetaSpaces[k]); this._allRoomsInHome = SettingsStore.getValue("Spaces.allRoomsInHome"); this.sendUserProperties(); @@ -1169,8 +1169,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient { } case Action.SettingUpdated: { - const settingUpdatedPayload = payload as SettingUpdatedPayload; - switch (settingUpdatedPayload.settingName) { + switch (payload.settingName) { case "Spaces.allRoomsInHome": { const newValue = SettingsStore.getValue("Spaces.allRoomsInHome"); if (this.allRoomsInHome !== newValue) { @@ -1186,7 +1185,7 @@ export class SpaceStoreClass extends AsyncStoreWithClient { case "Spaces.enabledMetaSpaces": { const newValue = SettingsStore.getValue("Spaces.enabledMetaSpaces"); - const enabledMetaSpaces = metaSpaceOrder.filter(k => newValue[k]) as MetaSpace[]; + const enabledMetaSpaces = metaSpaceOrder.filter(k => newValue[k]); if (arrayHasDiff(this._enabledMetaSpaces, enabledMetaSpaces)) { const hadPeopleOrHomeEnabled = this.enabledMetaSpaces.some(s => { return s === MetaSpace.Home || s === MetaSpace.People; @@ -1217,9 +1216,9 @@ export class SpaceStoreClass extends AsyncStoreWithClient { case "Spaces.showPeopleInSpace": // getSpaceFilteredUserIds will return the appropriate value - this.emit(settingUpdatedPayload.roomId); + this.emit(payload.roomId); if (!this.enabledMetaSpaces.some(s => s === MetaSpace.Home || s === MetaSpace.People)) { - this.updateNotificationStates([settingUpdatedPayload.roomId]); + this.updateNotificationStates([payload.roomId]); } break; } diff --git a/src/utils/DMRoomMap.ts b/src/utils/DMRoomMap.ts index 69ab4e192bb..ee4837cfb69 100644 --- a/src/utils/DMRoomMap.ts +++ b/src/utils/DMRoomMap.ts @@ -20,6 +20,7 @@ import { ClientEvent, MatrixClient } from "matrix-js-sdk/src/client"; import { logger } from "matrix-js-sdk/src/logger"; import { EventType } from "matrix-js-sdk/src/@types/event"; import { MatrixEvent } from "matrix-js-sdk/src/models/event"; +import { Optional } from "matrix-events-sdk"; import { MatrixClientPeg } from '../MatrixClientPeg'; @@ -159,7 +160,7 @@ export default class DMRoomMap { return joinedRooms[0]; } - public getUserIdForRoomId(roomId: string) { + public getUserIdForRoomId(roomId: string): Optional { if (this.roomToUser == null) { // we lazily populate roomToUser so you can use // this class just to call getDMRoomsForUserId diff --git a/src/utils/MegolmExportEncryption.ts b/src/utils/MegolmExportEncryption.ts index b88b21132ab..8d7f0a00ad3 100644 --- a/src/utils/MegolmExportEncryption.ts +++ b/src/utils/MegolmExportEncryption.ts @@ -261,7 +261,7 @@ async function deriveKeys(salt: Uint8Array, iterations: number, password: string throw friendlyError('subtleCrypto.importKey failed for HMAC key: ' + e, cryptoFailMsg()); }); - return await Promise.all([aesProm, hmacProm]); + return Promise.all([aesProm, hmacProm]); } const HEADER_LINE = '-----BEGIN MEGOLM SESSION DATA-----'; diff --git a/src/utils/beacon/geolocation.ts b/src/utils/beacon/geolocation.ts index efc3a9b44c3..6925ca73b58 100644 --- a/src/utils/beacon/geolocation.ts +++ b/src/utils/beacon/geolocation.ts @@ -136,7 +136,8 @@ export const getCurrentPosition = async (): Promise => { export type ClearWatchCallback = () => void; export const watchPosition = ( onWatchPosition: PositionCallback, - onWatchPositionError: (error: GeolocationError) => void): ClearWatchCallback => { + onWatchPositionError: (error: GeolocationError) => void, +): ClearWatchCallback => { try { const onError = (error) => onWatchPositionError(mapGeolocationError(error)); const watchId = getGeolocation().watchPosition(onWatchPosition, onError, GeolocationOptions); diff --git a/src/utils/drawable.ts b/src/utils/drawable.ts index 31f7bc8cec7..5c95fb3889c 100644 --- a/src/utils/drawable.ts +++ b/src/utils/drawable.ts @@ -23,7 +23,7 @@ export async function getDrawable(url: string): Promise { if ('createImageBitmap' in window) { const response = await fetch(url); const blob = await response.blob(); - return await createImageBitmap(blob); + return createImageBitmap(blob); } else { return new Promise((resolve, reject) => { const img = document.createElement("img"); diff --git a/src/utils/exportUtils/HtmlExport.tsx b/src/utils/exportUtils/HtmlExport.tsx index 59d864b6c72..7d308a91a50 100644 --- a/src/utils/exportUtils/HtmlExport.tsx +++ b/src/utils/exportUtils/HtmlExport.tsx @@ -34,8 +34,7 @@ import * as Avatar from "../../Avatar"; import EventTile from "../../components/views/rooms/EventTile"; import DateSeparator from "../../components/views/messages/DateSeparator"; import BaseAvatar from "../../components/views/avatars/BaseAvatar"; -import { ExportType } from "./exportUtils"; -import { IExportOptions } from "./exportUtils"; +import { ExportType, IExportOptions } from "./exportUtils"; import MatrixClientContext from "../../contexts/MatrixClientContext"; import getExportCSS from "./exportCSS"; import { textForEvent } from "../../TextForEvent"; @@ -417,7 +416,7 @@ export default class HTMLExporter extends Exporter { content += body; prevEvent = event; } - return await this.wrapHTML(content); + return this.wrapHTML(content); } public async export() { diff --git a/src/utils/image-media.ts b/src/utils/image-media.ts index a57e4b841ab..b7681333821 100644 --- a/src/utils/image-media.ts +++ b/src/utils/image-media.ts @@ -84,8 +84,8 @@ export async function createThumbnail( } catch (e) { // Fallback support for other browsers (Safari and Firefox for now) canvas = document.createElement("canvas"); - (canvas as HTMLCanvasElement).width = targetWidth; - (canvas as HTMLCanvasElement).height = targetHeight; + canvas.width = targetWidth; + canvas.height = targetHeight; context = canvas.getContext("2d"); } diff --git a/src/utils/permalinks/Permalinks.ts b/src/utils/permalinks/Permalinks.ts index 8c213a8cffc..4ab355fe788 100644 --- a/src/utils/permalinks/Permalinks.ts +++ b/src/utils/permalinks/Permalinks.ts @@ -32,6 +32,8 @@ import MatrixSchemePermalinkConstructor from "./MatrixSchemePermalinkConstructor // to add to permalinks. The servers are appended as ?via=example.org const MAX_SERVER_CANDIDATES = 3; +const ANY_REGEX = /.*/; + // Permalinks can have servers appended to them so that the user // receiving them can have a fighting chance at joining the room. // These servers are called "candidates" at this point because @@ -207,7 +209,7 @@ export class RoomPermalinkCreator { private updateAllowedServers() { const bannedHostsRegexps = []; - let allowedHostsRegexps = [new RegExp(".*")]; // default allow everyone + let allowedHostsRegexps = [ANY_REGEX]; // default allow everyone if (this.room.currentState) { const aclEvent = this.room.currentState.getStateEvents("m.room.server_acl", ""); if (aclEvent && aclEvent.getContent()) { diff --git a/src/utils/rooms.ts b/src/utils/rooms.ts index d9aa310ea4d..805135be271 100644 --- a/src/utils/rooms.ts +++ b/src/utils/rooms.ts @@ -23,10 +23,9 @@ import { getE2EEWellKnown } from "./WellKnownUtils"; import dis from "../dispatcher/dispatcher"; import { getDisplayAliasForAliasSet } from "../Rooms"; import { _t } from "../languageHandler"; -import { instanceForInstanceId, protocolNameForInstanceId } from "./DirectoryUtils"; +import { instanceForInstanceId, protocolNameForInstanceId, ALL_ROOMS, Protocols } from "./DirectoryUtils"; import SdkConfig from "../SdkConfig"; import { GenericError } from "./error"; -import { ALL_ROOMS, Protocols } from "./DirectoryUtils"; export function privateShouldBeEncrypted(): boolean { const e2eeWellKnown = getE2EEWellKnown(); diff --git a/src/utils/space.tsx b/src/utils/space.tsx index 33071c4811a..6b341767062 100644 --- a/src/utils/space.tsx +++ b/src/utils/space.tsx @@ -16,8 +16,7 @@ limitations under the License. import React from "react"; import { Room } from "matrix-js-sdk/src/models/room"; -import { RoomType } from "matrix-js-sdk/src/@types/event"; -import { EventType } from "matrix-js-sdk/src/@types/event"; +import { RoomType, EventType } from "matrix-js-sdk/src/@types/event"; import { JoinRule } from "matrix-js-sdk/src/@types/partials"; import { calculateRoomVia } from "./permalinks/Permalinks"; @@ -38,7 +37,6 @@ import { shouldShowComponent } from "../customisations/helpers/UIComponents"; import { UIComponent } from "../settings/UIFeature"; import { OpenSpacePreferencesPayload, SpacePreferenceTab } from "../dispatcher/payloads/OpenSpacePreferencesPayload"; import { OpenSpaceSettingsPayload } from "../dispatcher/payloads/OpenSpaceSettingsPayload"; -import dis from "../dispatcher/dispatcher"; import { OpenAddExistingToSpaceDialogPayload } from "../dispatcher/payloads/OpenAddExistingToSpaceDialogPayload"; export const shouldShowSpaceSettings = (space: Room) => { @@ -60,14 +58,14 @@ export const makeSpaceParentEvent = (room: Room, canonical = false) => ({ }); export function showSpaceSettings(space: Room) { - dis.dispatch({ + defaultDispatcher.dispatch({ action: Action.OpenSpaceSettings, space, }); } export const showAddExistingRooms = (space: Room): void => { - dis.dispatch({ + defaultDispatcher.dispatch({ action: Action.OpenAddToExistingSpaceDialog, space, }); @@ -168,7 +166,7 @@ export const bulkSpaceBehaviour = async ( }; export const showSpacePreferences = (space: Room, initialTabId?: SpacePreferenceTab) => { - dis.dispatch({ + defaultDispatcher.dispatch({ action: Action.OpenSpacePreferences, space, initialTabId, From 8077e9126fb40d4f3b9a036ab4c8e342d424dbb6 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Sun, 1 May 2022 11:13:02 +0100 Subject: [PATCH 3/6] Apply corrections identified by SonarQube --- src/KeyBindingsDefaults.ts | 4 +- src/KeyBindingsManager.ts | 4 +- src/Keyboard.ts | 6 +-- src/MatrixClientPeg.ts | 3 -- src/accessibility/KeyboardShortcutUtils.ts | 4 +- src/accessibility/KeyboardShortcuts.ts | 24 +++++------ src/components/structures/ContextMenu.tsx | 40 ++++++++++--------- src/components/structures/RoomSearch.tsx | 4 +- src/components/structures/SpaceRoomView.tsx | 4 +- .../context_menus/ThreadListContextMenu.tsx | 4 +- .../views/elements/InteractiveTooltip.tsx | 16 ++++---- src/components/views/elements/Tooltip.tsx | 10 ++--- .../views/rooms/BasicMessageComposer.tsx | 4 +- src/components/views/rooms/RoomListHeader.tsx | 4 +- src/components/views/rooms/RoomTile.tsx | 4 +- .../views/settings/KeyboardShortcut.tsx | 4 +- src/components/views/spaces/SpacePanel.tsx | 4 +- src/settings/Settings.tsx | 6 +-- src/utils/strings.ts | 2 +- 19 files changed, 74 insertions(+), 77 deletions(-) diff --git a/src/KeyBindingsDefaults.ts b/src/KeyBindingsDefaults.ts index 083b31b87cb..8ce30252f92 100644 --- a/src/KeyBindingsDefaults.ts +++ b/src/KeyBindingsDefaults.ts @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -import { isMac, Key } from "./Keyboard"; +import { IS_MAC, Key } from "./Keyboard"; import SettingsStore from "./settings/SettingsStore"; import SdkConfig from "./SdkConfig"; import { IKeyBindingsProvider, KeyBinding } from "./KeyBindingsManager"; @@ -74,7 +74,7 @@ const messageComposerBindings = (): KeyBinding[] => { shiftKey: true, }, }); - if (isMac) { + if (IS_MAC) { bindings.push({ action: KeyBindingAction.NewLine, keyCombo: { diff --git a/src/KeyBindingsManager.ts b/src/KeyBindingsManager.ts index 7a79a69ce87..aee403e31d1 100644 --- a/src/KeyBindingsManager.ts +++ b/src/KeyBindingsManager.ts @@ -17,7 +17,7 @@ limitations under the License. import { KeyBindingAction } from "./accessibility/KeyboardShortcuts"; import { defaultBindingsProvider } from './KeyBindingsDefaults'; -import { isMac } from './Keyboard'; +import { IS_MAC } from './Keyboard'; /** * Represent a key combination. @@ -127,7 +127,7 @@ export class KeyBindingsManager { ): KeyBindingAction | undefined { for (const getter of getters) { const bindings = getter(); - const binding = bindings.find(it => isKeyComboMatch(ev, it.keyCombo, isMac)); + const binding = bindings.find(it => isKeyComboMatch(ev, it.keyCombo, IS_MAC)); if (binding) { return binding.action; } diff --git a/src/Keyboard.ts b/src/Keyboard.ts index 8d7d39fc190..efecd791fd8 100644 --- a/src/Keyboard.ts +++ b/src/Keyboard.ts @@ -74,10 +74,10 @@ export const Key = { Z: "z", }; -export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0; +export const IS_MAC = navigator.platform.toUpperCase().includes('MAC'); export function isOnlyCtrlOrCmdKeyEvent(ev) { - if (isMac) { + if (IS_MAC) { return ev.metaKey && !ev.altKey && !ev.ctrlKey && !ev.shiftKey; } else { return ev.ctrlKey && !ev.altKey && !ev.metaKey && !ev.shiftKey; @@ -85,7 +85,7 @@ export function isOnlyCtrlOrCmdKeyEvent(ev) { } export function isOnlyCtrlOrCmdIgnoreShiftKeyEvent(ev) { - if (isMac) { + if (IS_MAC) { return ev.metaKey && !ev.altKey && !ev.ctrlKey; } else { return ev.ctrlKey && !ev.altKey && !ev.metaKey; diff --git a/src/MatrixClientPeg.ts b/src/MatrixClientPeg.ts index 46d599b156d..86570090167 100644 --- a/src/MatrixClientPeg.ts +++ b/src/MatrixClientPeg.ts @@ -123,9 +123,6 @@ class MatrixClientPegClass implements IMatrixClientPeg { // used if we tear it down & recreate it with a different store private currentClientCreds: IMatrixClientCreds; - constructor() { - } - public get(): MatrixClient { return this.matrixClient; } diff --git a/src/accessibility/KeyboardShortcutUtils.ts b/src/accessibility/KeyboardShortcutUtils.ts index 434116d4303..1dff38cde34 100644 --- a/src/accessibility/KeyboardShortcutUtils.ts +++ b/src/accessibility/KeyboardShortcutUtils.ts @@ -15,7 +15,7 @@ limitations under the License. */ import { KeyCombo } from "../KeyBindingsManager"; -import { isMac, Key } from "../Keyboard"; +import { IS_MAC, Key } from "../Keyboard"; import { _t, _td } from "../languageHandler"; import PlatformPeg from "../PlatformPeg"; import SettingsStore from "../settings/SettingsStore"; @@ -96,7 +96,7 @@ export const getKeyboardShortcuts = (): IKeyboardShortcuts => { return Object.keys(KEYBOARD_SHORTCUTS).filter((k: KeyBindingAction) => { if (KEYBOARD_SHORTCUTS[k]?.controller?.settingDisabled) return false; - if (MAC_ONLY_SHORTCUTS.includes(k) && !isMac) return false; + if (MAC_ONLY_SHORTCUTS.includes(k) && !IS_MAC) return false; if (DESKTOP_SHORTCUTS.includes(k) && !overrideBrowserShortcuts) return false; return true; diff --git a/src/accessibility/KeyboardShortcuts.ts b/src/accessibility/KeyboardShortcuts.ts index 97e428d2a0f..50992eb299a 100644 --- a/src/accessibility/KeyboardShortcuts.ts +++ b/src/accessibility/KeyboardShortcuts.ts @@ -16,7 +16,7 @@ limitations under the License. */ import { _td } from "../languageHandler"; -import { isMac, Key } from "../Keyboard"; +import { IS_MAC, Key } from "../Keyboard"; import { IBaseSetting } from "../settings/Settings"; import IncompatibleController from "../settings/controllers/IncompatibleController"; import { KeyCombo } from "../KeyBindingsManager"; @@ -200,7 +200,7 @@ export const KEY_ICON: Record = { [Key.ARROW_LEFT]: "←", [Key.ARROW_RIGHT]: "→", }; -if (isMac) { +if (IS_MAC) { KEY_ICON[Key.META] = "⌘"; KEY_ICON[Key.ALT] = "⌥"; } @@ -528,8 +528,8 @@ export const KEYBOARD_SHORTCUTS: IKeyboardShortcuts = { [KeyBindingAction.GoToHome]: { default: { ctrlOrCmdKey: true, - altKey: !isMac, - shiftKey: isMac, + altKey: !IS_MAC, + shiftKey: IS_MAC, key: Key.H, }, displayName: _td("Go to Home View"), @@ -621,25 +621,25 @@ export const KEYBOARD_SHORTCUTS: IKeyboardShortcuts = { }, [KeyBindingAction.EditRedo]: { default: { - key: isMac ? Key.Z : Key.Y, + key: IS_MAC ? Key.Z : Key.Y, ctrlOrCmdKey: true, - shiftKey: isMac, + shiftKey: IS_MAC, }, displayName: _td("Redo edit"), }, [KeyBindingAction.PreviousVisitedRoomOrSpace]: { default: { - metaKey: isMac, - altKey: !isMac, - key: isMac ? Key.SQUARE_BRACKET_LEFT : Key.ARROW_LEFT, + metaKey: IS_MAC, + altKey: !IS_MAC, + key: IS_MAC ? Key.SQUARE_BRACKET_LEFT : Key.ARROW_LEFT, }, displayName: _td("Previous recently visited room or space"), }, [KeyBindingAction.NextVisitedRoomOrSpace]: { default: { - metaKey: isMac, - altKey: !isMac, - key: isMac ? Key.SQUARE_BRACKET_RIGHT : Key.ARROW_RIGHT, + metaKey: IS_MAC, + altKey: !IS_MAC, + key: IS_MAC ? Key.SQUARE_BRACKET_RIGHT : Key.ARROW_RIGHT, }, displayName: _td("Next recently visited room or space"), }, diff --git a/src/components/structures/ContextMenu.tsx b/src/components/structures/ContextMenu.tsx index 187e55cc392..695d6ec2a7b 100644 --- a/src/components/structures/ContextMenu.tsx +++ b/src/components/structures/ContextMenu.tsx @@ -157,12 +157,14 @@ export default class ContextMenu extends React.PureComponent { // XXX: This isn't pretty but the only way to allow opening a different context menu on right click whilst // a context menu and its click-guard are up without completely rewriting how the context menus work. setImmediate(() => { - const clickEvent = document.createEvent('MouseEvents'); - clickEvent.initMouseEvent( - 'contextmenu', true, true, window, 0, - 0, 0, x, y, false, false, - false, false, 0, null, - ); + const clickEvent = new MouseEvent("contextmenu", { + clientX: x, + clientY: y, + screenX: 0, + screenY: 0, + button: 0, // Left + relatedTarget: null, + }); document.elementFromPoint(x, y).dispatchEvent(clickEvent); }); } @@ -417,8 +419,8 @@ export type ToRightOf = { // Placement method for to position context menu to right of elementRect with chevronOffset export const toRightOf = (elementRect: Pick, chevronOffset = 12): ToRightOf => { - const left = elementRect.right + window.pageXOffset + 3; - let top = elementRect.top + (elementRect.height / 2) + window.pageYOffset; + const left = elementRect.right + window.scrollX + 3; + let top = elementRect.top + (elementRect.height / 2) + window.scrollY; top -= chevronOffset + 8; // where 8 is half the height of the chevron return { left, top, chevronOffset }; }; @@ -436,9 +438,9 @@ export const aboveLeftOf = ( ): AboveLeftOf => { const menuOptions: IPosition & { chevronFace: ChevronFace } = { chevronFace }; - const buttonRight = elementRect.right + window.pageXOffset; - const buttonBottom = elementRect.bottom + window.pageYOffset; - const buttonTop = elementRect.top + window.pageYOffset; + const buttonRight = elementRect.right + window.scrollX; + const buttonBottom = elementRect.bottom + window.scrollY; + const buttonTop = elementRect.top + window.scrollY; // Align the right edge of the menu to the right edge of the button menuOptions.right = UIStore.instance.windowWidth - buttonRight; // Align the menu vertically on whichever side of the button has more space available. @@ -460,9 +462,9 @@ export const aboveRightOf = ( ): AboveLeftOf => { const menuOptions: IPosition & { chevronFace: ChevronFace } = { chevronFace }; - const buttonLeft = elementRect.left + window.pageXOffset; - const buttonBottom = elementRect.bottom + window.pageYOffset; - const buttonTop = elementRect.top + window.pageYOffset; + const buttonLeft = elementRect.left + window.scrollX; + const buttonBottom = elementRect.bottom + window.scrollY; + const buttonTop = elementRect.top + window.scrollY; // Align the left edge of the menu to the left edge of the button menuOptions.left = buttonLeft; // Align the menu vertically on whichever side of the button has more space available. @@ -484,9 +486,9 @@ export const alwaysAboveLeftOf = ( ) => { const menuOptions: IPosition & { chevronFace: ChevronFace } = { chevronFace }; - const buttonRight = elementRect.right + window.pageXOffset; - const buttonBottom = elementRect.bottom + window.pageYOffset; - const buttonTop = elementRect.top + window.pageYOffset; + const buttonRight = elementRect.right + window.scrollX; + const buttonBottom = elementRect.bottom + window.scrollY; + const buttonTop = elementRect.top + window.scrollY; // Align the right edge of the menu to the right edge of the button menuOptions.right = UIStore.instance.windowWidth - buttonRight; // Align the menu vertically on whichever side of the button has more space available. @@ -508,8 +510,8 @@ export const alwaysAboveRightOf = ( ) => { const menuOptions: IPosition & { chevronFace: ChevronFace } = { chevronFace }; - const buttonLeft = elementRect.left + window.pageXOffset; - const buttonTop = elementRect.top + window.pageYOffset; + const buttonLeft = elementRect.left + window.scrollX; + const buttonTop = elementRect.top + window.scrollY; // Align the left edge of the menu to the left edge of the button menuOptions.left = buttonLeft; // Align the menu vertically above the menu diff --git a/src/components/structures/RoomSearch.tsx b/src/components/structures/RoomSearch.tsx index 94212927641..77faf0f9298 100644 --- a/src/components/structures/RoomSearch.tsx +++ b/src/components/structures/RoomSearch.tsx @@ -28,7 +28,7 @@ import { NameFilterCondition } from "../../stores/room-list/filters/NameFilterCo import { getKeyBindingsManager } from "../../KeyBindingsManager"; import SpaceStore from "../../stores/spaces/SpaceStore"; import { UPDATE_SELECTED_SPACE } from "../../stores/spaces"; -import { isMac, Key } from "../../Keyboard"; +import { IS_MAC, Key } from "../../Keyboard"; import SettingsStore from "../../settings/SettingsStore"; import Modal from "../../Modal"; import SpotlightDialog from "../views/dialogs/SpotlightDialog"; @@ -206,7 +206,7 @@ export default class RoomSearch extends React.PureComponent { ); let shortcutPrompt =
    - { isMac ? "⌘ K" : _t(ALTERNATE_KEY_NAME[Key.CONTROL]) + " K" } + { IS_MAC ? "⌘ K" : _t(ALTERNATE_KEY_NAME[Key.CONTROL]) + " K" }
    ; if (this.props.isMinimized) { diff --git a/src/components/structures/SpaceRoomView.tsx b/src/components/structures/SpaceRoomView.tsx index 189800229b6..4e258f5258b 100644 --- a/src/components/structures/SpaceRoomView.tsx +++ b/src/components/structures/SpaceRoomView.tsx @@ -315,8 +315,8 @@ const SpaceLandingAddButton = ({ space }) => { if (menuDisplayed) { const rect = handle.current.getBoundingClientRect(); contextMenu = { // align the context menu's icons with the icon which opened the context menu - const left = elementRect.left + window.pageXOffset + elementRect.width; - const top = elementRect.bottom + window.pageYOffset; + const left = elementRect.left + window.scrollX + elementRect.width; + const top = elementRect.bottom + window.scrollY; const chevronFace = ChevronFace.None; return { left, top, chevronFace }; }; diff --git a/src/components/views/elements/InteractiveTooltip.tsx b/src/components/views/elements/InteractiveTooltip.tsx index 62d0c43d06a..ca8ae4c8fd5 100644 --- a/src/components/views/elements/InteractiveTooltip.tsx +++ b/src/components/views/elements/InteractiveTooltip.tsx @@ -352,10 +352,10 @@ export default class InteractiveTooltip extends React.Component const targetRect = this.target.getBoundingClientRect(); if (this.props.direction === Direction.Left) { - const targetLeft = targetRect.left + window.pageXOffset; + const targetLeft = targetRect.left + window.scrollX; return !contentRect || (targetLeft - contentRect.width > MIN_SAFE_DISTANCE_TO_WINDOW_EDGE); } else { - const targetRight = targetRect.right + window.pageXOffset; + const targetRight = targetRect.right + window.scrollX; const spaceOnRight = UIStore.instance.windowWidth - targetRight; return contentRect && (spaceOnRight - contentRect.width < MIN_SAFE_DISTANCE_TO_WINDOW_EDGE); } @@ -366,10 +366,10 @@ export default class InteractiveTooltip extends React.Component const targetRect = this.target.getBoundingClientRect(); if (this.props.direction === Direction.Top) { - const targetTop = targetRect.top + window.pageYOffset; + const targetTop = targetRect.top + window.scrollY; return !contentRect || (targetTop - contentRect.height > MIN_SAFE_DISTANCE_TO_WINDOW_EDGE); } else { - const targetBottom = targetRect.bottom + window.pageYOffset; + const targetBottom = targetRect.bottom + window.scrollY; const spaceBelow = UIStore.instance.windowHeight - targetBottom; return contentRect && (spaceBelow - contentRect.height < MIN_SAFE_DISTANCE_TO_WINDOW_EDGE); } @@ -429,10 +429,10 @@ export default class InteractiveTooltip extends React.Component const targetRect = this.target.getBoundingClientRect(); // The window X and Y offsets are to adjust position when zoomed in to page - const targetLeft = targetRect.left + window.pageXOffset; - const targetRight = targetRect.right + window.pageXOffset; - const targetBottom = targetRect.bottom + window.pageYOffset; - const targetTop = targetRect.top + window.pageYOffset; + const targetLeft = targetRect.left + window.scrollX; + const targetRight = targetRect.right + window.scrollX; + const targetBottom = targetRect.bottom + window.scrollY; + const targetTop = targetRect.top + window.scrollY; // Place the tooltip above the target by default. If we find that the // tooltip content would extend past the safe area towards the window diff --git a/src/components/views/elements/Tooltip.tsx b/src/components/views/elements/Tooltip.tsx index f32b7c35f42..8d817551d0e 100644 --- a/src/components/views/elements/Tooltip.tsx +++ b/src/components/views/elements/Tooltip.tsx @@ -116,12 +116,12 @@ export default class Tooltip extends React.Component { ? Math.min(parentBox.width, this.props.maxParentWidth) : parentBox.width ); - const baseTop = (parentBox.top - 2 + this.props.yOffset) + window.pageYOffset; + const baseTop = (parentBox.top - 2 + this.props.yOffset) + window.scrollY; const top = baseTop + offset; - const right = width - parentBox.left - window.pageXOffset; - const left = parentBox.right + window.pageXOffset; + const right = width - parentBox.left - window.scrollX; + const left = parentBox.right + window.scrollX; const horizontalCenter = ( - parentBox.left - window.pageXOffset + (parentWidth / 2) + parentBox.left - window.scrollX + (parentWidth / 2) ); switch (this.props.alignment) { case Alignment.Natural: @@ -154,7 +154,7 @@ export default class Tooltip extends React.Component { break; case Alignment.TopRight: style.top = baseTop - 5; - style.right = width - parentBox.right - window.pageXOffset; + style.right = width - parentBox.right - window.scrollX; style.transform = "translate(5px, -100%)"; break; case Alignment.TopCenter: diff --git a/src/components/views/rooms/BasicMessageComposer.tsx b/src/components/views/rooms/BasicMessageComposer.tsx index e93119643fb..068d096624f 100644 --- a/src/components/views/rooms/BasicMessageComposer.tsx +++ b/src/components/views/rooms/BasicMessageComposer.tsx @@ -32,7 +32,7 @@ import { parseEvent, parsePlainTextMessage } from '../../../editor/deserialize'; import { renderModel } from '../../../editor/render'; import TypingStore from "../../../stores/TypingStore"; import SettingsStore from "../../../settings/SettingsStore"; -import { Key } from "../../../Keyboard"; +import { IS_MAC, Key } from "../../../Keyboard"; import { EMOTICON_TO_EMOJI } from "../../../emoji"; import { CommandCategories, CommandMap, parseCommandString } from "../../../SlashCommands"; import Range from "../../../editor/range"; @@ -50,8 +50,6 @@ import { _t } from "../../../languageHandler"; const REGEX_EMOTICON_WHITESPACE = new RegExp('(?:^|\\s)(' + EMOTICON_REGEX.source + ')\\s|:^$'); export const REGEX_EMOTICON = new RegExp('(?:^|\\s)(' + EMOTICON_REGEX.source + ')$'); -const IS_MAC = navigator.platform.indexOf("Mac") !== -1; - const SURROUND_WITH_CHARACTERS = ["\"", "_", "`", "'", "*", "~", "$"]; const SURROUND_WITH_DOUBLE_CHARACTERS = new Map([ ["(", ")"], diff --git a/src/components/views/rooms/RoomListHeader.tsx b/src/components/views/rooms/RoomListHeader.tsx index b8ac024b918..b9a33e1f44e 100644 --- a/src/components/views/rooms/RoomListHeader.tsx +++ b/src/components/views/rooms/RoomListHeader.tsx @@ -60,8 +60,8 @@ import { UIComponent } from "../../../settings/UIFeature"; const contextMenuBelow = (elementRect: DOMRect) => { // align the context menu's icons with the icon which opened the context menu - const left = elementRect.left + window.pageXOffset; - const top = elementRect.bottom + window.pageYOffset + 12; + const left = elementRect.left + window.scrollX; + const top = elementRect.bottom + window.scrollY + 12; const chevronFace = ChevronFace.None; return { left, top, chevronFace }; }; diff --git a/src/components/views/rooms/RoomTile.tsx b/src/components/views/rooms/RoomTile.tsx index 070f999c2fb..bd772401ede 100644 --- a/src/components/views/rooms/RoomTile.tsx +++ b/src/components/views/rooms/RoomTile.tsx @@ -89,8 +89,8 @@ const messagePreviewId = (roomId: string) => `mx_RoomTile_messagePreview_${roomI export const contextMenuBelow = (elementRect: PartialDOMRect) => { // align the context menu's icons with the icon which opened the context menu - const left = elementRect.left + window.pageXOffset - 9; - const top = elementRect.bottom + window.pageYOffset + 17; + const left = elementRect.left + window.scrollX - 9; + const top = elementRect.bottom + window.scrollY + 17; const chevronFace = ChevronFace.None; return { left, top, chevronFace }; }; diff --git a/src/components/views/settings/KeyboardShortcut.tsx b/src/components/views/settings/KeyboardShortcut.tsx index 14dcf77d241..3e4f65b8c58 100644 --- a/src/components/views/settings/KeyboardShortcut.tsx +++ b/src/components/views/settings/KeyboardShortcut.tsx @@ -18,7 +18,7 @@ import React from "react"; import { ALTERNATE_KEY_NAME, KEY_ICON } from "../../../accessibility/KeyboardShortcuts"; import { KeyCombo } from "../../../KeyBindingsManager"; -import { isMac, Key } from "../../../Keyboard"; +import { IS_MAC, Key } from "../../../Keyboard"; import { _t } from "../../../languageHandler"; interface IKeyboardKeyProps { @@ -45,7 +45,7 @@ export const KeyboardShortcut: React.FC = ({ value }) => const modifiersElement = []; if (value.ctrlOrCmdKey) { - modifiersElement.push(); + modifiersElement.push(); } else if (value.ctrlKey) { modifiersElement.push(); } else if (value.metaKey) { diff --git a/src/components/views/spaces/SpacePanel.tsx b/src/components/views/spaces/SpacePanel.tsx index 70e1de55cb3..f273e3c523a 100644 --- a/src/components/views/spaces/SpacePanel.tsx +++ b/src/components/views/spaces/SpacePanel.tsx @@ -63,7 +63,7 @@ import QuickSettingsButton from "./QuickSettingsButton"; import { useSettingValue } from "../../../hooks/useSettings"; import UserMenu from "../../structures/UserMenu"; import IndicatorScrollbar from "../../structures/IndicatorScrollbar"; -import { isMac, Key } from "../../../Keyboard"; +import { IS_MAC, Key } from "../../../Keyboard"; import { useDispatcher } from "../../../hooks/useDispatcher"; import defaultDispatcher from "../../../dispatcher/dispatcher"; import { ActionPayload } from "../../../dispatcher/payloads"; @@ -365,7 +365,7 @@ const SpacePanel = () => { { isPanelCollapsed ? _t("Expand") : _t("Collapse") }
    - { isMac + { IS_MAC ? "⌘ + ⇧ + D" : _t(ALTERNATE_KEY_NAME[Key.CONTROL]) + " + " + _t(ALTERNATE_KEY_NAME[Key.SHIFT]) + " + D" diff --git a/src/settings/Settings.tsx b/src/settings/Settings.tsx index e4247908ddf..9768997cb0b 100644 --- a/src/settings/Settings.tsx +++ b/src/settings/Settings.tsx @@ -32,7 +32,7 @@ import SystemFontController from './controllers/SystemFontController'; import UseSystemFontController from './controllers/UseSystemFontController'; import { SettingLevel } from "./SettingLevel"; import SettingController from "./controllers/SettingController"; -import { isMac } from '../Keyboard'; +import { IS_MAC } from '../Keyboard'; import UIFeatureController from "./controllers/UIFeatureController"; import { UIFeature } from "./UIFeature"; import { OrderedMultiController } from "./controllers/OrderedMultiController"; @@ -592,12 +592,12 @@ export const SETTINGS: {[setting: string]: ISetting} = { }, "ctrlFForSearch": { supportedLevels: LEVELS_ACCOUNT_SETTINGS, - displayName: isMac ? _td("Use Command + F to search timeline") : _td("Use Ctrl + F to search timeline"), + displayName: IS_MAC ? _td("Use Command + F to search timeline") : _td("Use Ctrl + F to search timeline"), default: false, }, "MessageComposerInput.ctrlEnterToSend": { supportedLevels: LEVELS_ACCOUNT_SETTINGS, - displayName: isMac ? _td("Use Command + Enter to send a message") : _td("Use Ctrl + Enter to send a message"), + displayName: IS_MAC ? _td("Use Command + Enter to send a message") : _td("Use Ctrl + Enter to send a message"), default: false, }, "MessageComposerInput.surroundWith": { diff --git a/src/utils/strings.ts b/src/utils/strings.ts index 41f80ed1c53..8bf039656d8 100644 --- a/src/utils/strings.ts +++ b/src/utils/strings.ts @@ -24,7 +24,7 @@ import { logger } from "matrix-js-sdk/src/logger"; export async function copyPlaintext(text: string): Promise { try { - if (navigator && navigator.clipboard && navigator.clipboard.writeText) { + if (navigator?.clipboard?.writeText) { await navigator.clipboard.writeText(text); return true; } else { From 686a11368563c60db0e89c2def486f3d0db12bd8 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Sun, 1 May 2022 11:27:11 +0100 Subject: [PATCH 4/6] make things happier --- src/SecurityManager.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/SecurityManager.ts b/src/SecurityManager.ts index 9bc23f580de..aa21cf880bf 100644 --- a/src/SecurityManager.ts +++ b/src/SecurityManager.ts @@ -103,11 +103,11 @@ function makeInputToKey( async function getSecretStorageKey( { keys: keyInfos }: { keys: Record }, - ssssItemName, + ssssItemName: string, ): Promise<[string, Uint8Array]> { const cli = MatrixClientPeg.get(); let keyId = await cli.getDefaultSecretStorageKeyId(); - let keyInfo; + let keyInfo: ISecretStorageKeyInfo; if (keyId) { // use the default SSSS key if set keyInfo = keyInfos[keyId]; @@ -156,8 +156,8 @@ async function getSecretStorageKey( /* props= */ { keyInfo, - checkPrivateKey: async (input: KeyParams) => { - const key = await inputToKey(input); + checkPrivateKey: async (keyParams: KeyParams) => { + const key = await inputToKey(keyParams); return MatrixClientPeg.get().checkSecretStorageKey(key, keyInfo); }, }, From 0df3bedde6580be5d1cf14ab412b2a01bf698059 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Sun, 1 May 2022 11:47:49 +0100 Subject: [PATCH 5/6] be happy already --- src/SecurityManager.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/SecurityManager.ts b/src/SecurityManager.ts index aa21cf880bf..c67e8ec8d96 100644 --- a/src/SecurityManager.ts +++ b/src/SecurityManager.ts @@ -103,7 +103,6 @@ function makeInputToKey( async function getSecretStorageKey( { keys: keyInfos }: { keys: Record }, - ssssItemName: string, ): Promise<[string, Uint8Array]> { const cli = MatrixClientPeg.get(); let keyId = await cli.getDefaultSecretStorageKeyId(); @@ -156,8 +155,8 @@ async function getSecretStorageKey( /* props= */ { keyInfo, - checkPrivateKey: async (keyParams: KeyParams) => { - const key = await inputToKey(keyParams); + checkPrivateKey: async (input: KeyParams) => { + const key = await inputToKey(input); return MatrixClientPeg.get().checkSecretStorageKey(key, keyInfo); }, }, @@ -173,11 +172,11 @@ async function getSecretStorageKey( }, }, ); - const [input] = await finished; - if (!input) { + const [keyParams] = await finished; + if (!keyParams) { throw new AccessCancelledError(); } - const key = await inputToKey(input); + const key = await inputToKey(keyParams); // Save to cache to avoid future prompts in the current session cacheSecretStorageKey(keyId, keyInfo, key); From 336781266487017d938537c3347ef29ff1b1f3e0 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Mon, 2 May 2022 09:57:16 +0100 Subject: [PATCH 6/6] Tweak --- src/RoomInvite.tsx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/RoomInvite.tsx b/src/RoomInvite.tsx index 188bd33b2d3..e9204996ed2 100644 --- a/src/RoomInvite.tsx +++ b/src/RoomInvite.tsx @@ -19,6 +19,7 @@ import { Room } from "matrix-js-sdk/src/models/room"; import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { User } from "matrix-js-sdk/src/models/user"; import { logger } from "matrix-js-sdk/src/logger"; +import { EventType } from "matrix-js-sdk/src/@types/event"; import { MatrixClientPeg } from './MatrixClientPeg'; import MultiInviter, { CompletionStates } from './utils/MultiInviter'; @@ -84,12 +85,16 @@ export function showRoomInviteDialog(roomId: string, initialText = ""): void { * @returns {boolean} True if valid, false otherwise */ export function isValid3pidInvite(event: MatrixEvent): boolean { - if (!event || event.getType() !== "m.room.third_party_invite") return false; + if (!event || event.getType() !== EventType.RoomThirdPartyInvite) return false; // any events without these keys are not valid 3pid invites, so we ignore them const requiredKeys = ['key_validity_url', 'public_key', 'display_name']; + if (requiredKeys.some(key => !event.getContent()[key])) { + return false; + } + // Valid enough by our standards - return requiredKeys.every(key => !!event.getContent()[key]); + return true; } export function inviteUsersToRoom(