Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Make SonarCloud happier (#9545)
Browse files Browse the repository at this point in the history
* Make SonarCloud happier

* i18n

* Iterate

* Update AddExistingToSpaceDialog.tsx

* Update SlashCommands.tsx
  • Loading branch information
t3chguy committed Nov 7, 2022
1 parent 77764d8 commit 3747464
Show file tree
Hide file tree
Showing 33 changed files with 131 additions and 162 deletions.
4 changes: 2 additions & 2 deletions src/HtmlUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ function formatEmojis(message: string, isHtmlMessage: boolean): (JSX.Element | s
export function bodyToHtml(content: IContent, highlights: Optional<string[]>, opts: IOptsReturnString): string;
export function bodyToHtml(content: IContent, highlights: Optional<string[]>, opts: IOptsReturnNode): ReactNode;
export function bodyToHtml(content: IContent, highlights: Optional<string[]>, opts: IOpts = {}) {
const isFormattedBody = content.format === "org.matrix.custom.html" && content.formatted_body;
const isFormattedBody = content.format === "org.matrix.custom.html" && !!content.formatted_body;
let bodyHasEmoji = false;
let isHtmlMessage = false;

Expand Down Expand Up @@ -511,7 +511,7 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op
decodeEntities: false,
});
const isPlainText = phtml.html() === phtml.root().text();
isHtmlMessage = isFormattedBody && !isPlainText;
isHtmlMessage = !isPlainText;

if (isHtmlMessage && SettingsStore.getValue("feature_latex_maths")) {
// @ts-ignore - The types for `replaceWith` wrongly expect
Expand Down
12 changes: 7 additions & 5 deletions src/Login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,13 @@ export default class Login {
* @returns {MatrixClient}
*/
public createTemporaryClient(): MatrixClient {
if (this.tempClient) return this.tempClient; // use memoization
return this.tempClient = createClient({
baseUrl: this.hsUrl,
idBaseUrl: this.isUrl,
});
if (!this.tempClient) {
this.tempClient = createClient({
baseUrl: this.hsUrl,
idBaseUrl: this.isUrl,
});
}
return this.tempClient;
}

public async getFlows(): Promise<Array<LoginFlow>> {
Expand Down
8 changes: 0 additions & 8 deletions src/NodeAnimator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ export default class NodeAnimator extends React.Component<IProps> {

if (oldNode && (oldNode as HTMLElement).style.left !== c.props.style.left) {
this.applyStyles(oldNode as HTMLElement, { left: c.props.style.left });
// console.log("translation: "+oldNode.style.left+" -> "+c.props.style.left);
}
// clone the old element with the props (and children) of the new element
// so prop updates are still received by the children.
Expand All @@ -94,7 +93,6 @@ export default class NodeAnimator extends React.Component<IProps> {
if (startStyles.length > 0) {
const startStyle = startStyles[0];
newProps.style = startStyle;
// console.log("mounted@startstyle0: "+JSON.stringify(startStyle));
}

newProps.ref = ((n) => this.collectNode(
Expand All @@ -118,18 +116,12 @@ export default class NodeAnimator extends React.Component<IProps> {
// to start with, so now we animate 1 etc.
for (let i = 1; i < startStyles.length; ++i) {
this.applyStyles(domNode as HTMLElement, startStyles[i]);
// console.log("start:"
// JSON.stringify(startStyles[i]),
// );
}

// and then we animate to the resting state
setTimeout(() => {
this.applyStyles(domNode as HTMLElement, restingStyle);
}, 0);

// console.log("enter:",
// JSON.stringify(restingStyle));
}
this.nodes[k] = node;
}
Expand Down
3 changes: 1 addition & 2 deletions src/Notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,10 @@ import ErrorDialog from "./components/views/dialogs/ErrorDialog";
import LegacyCallHandler from "./LegacyCallHandler";
import VoipUserMapper from "./VoipUserMapper";
import { SdkContextClass } from "./contexts/SDKContext";
import { localNotificationsAreSilenced } from "./utils/notifications";
import { localNotificationsAreSilenced, createLocalNotificationSettingsIfNeeded } from "./utils/notifications";
import { getIncomingCallToastKey, IncomingCallToast } from "./toasts/IncomingCallToast";
import ToastStore from "./stores/ToastStore";
import { ElementCall } from "./models/Call";
import { createLocalNotificationSettingsIfNeeded } from './utils/notifications';

/*
* Dispatches:
Expand Down
7 changes: 3 additions & 4 deletions src/Searching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,11 +497,10 @@ interface IEncryptedSeshatEvent {
}

function restoreEncryptionInfo(searchResultSlice: SearchResult[] = []): void {
for (let i = 0; i < searchResultSlice.length; i++) {
const timeline = searchResultSlice[i].context.getTimeline();
for (const result of searchResultSlice) {
const timeline = result.context.getTimeline();

for (let j = 0; j < timeline.length; j++) {
const mxEv = timeline[j];
for (const mxEv of timeline) {
const ev = mxEv.event as IEncryptedSeshatEvent;

if (ev.curve25519Key) {
Expand Down
14 changes: 4 additions & 10 deletions src/SlashCommands.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ export const Commands = [
runFn: function(roomId, args) {
const cli = MatrixClientPeg.get();

let targetRoomId: string;
let targetRoomId: string | undefined;
if (args) {
const matches = args.match(/^(\S+)$/);
if (matches) {
Expand All @@ -729,15 +729,9 @@ export const Commands = [

// Try to find a room with this alias
const rooms = cli.getRooms();
for (let i = 0; i < rooms.length; i++) {
if (rooms[i].getCanonicalAlias() === roomAlias ||
rooms[i].getAltAliases().includes(roomAlias)
) {
targetRoomId = rooms[i].roomId;
break;
}
if (targetRoomId) break;
}
targetRoomId = rooms.find(room => {
return room.getCanonicalAlias() === roomAlias || room.getAltAliases().includes(roomAlias);
})?.roomId;
if (!targetRoomId) {
return reject(
newTranslatableError(
Expand Down
4 changes: 1 addition & 3 deletions src/WhoIsTyping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,7 @@ export function usersTyping(room: Room, exclude: string[] = []): RoomMember[] {
const whoIsTyping = [];

const memberKeys = Object.keys(room.currentState.members);
for (let i = 0; i < memberKeys.length; ++i) {
const userId = memberKeys[i];

for (const userId of memberKeys) {
if (room.currentState.members[userId].typing) {
if (exclude.indexOf(userId) === -1) {
whoIsTyping.push(room.currentState.members[userId]);
Expand Down
9 changes: 2 additions & 7 deletions src/components/structures/ContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -524,16 +524,11 @@ export const alwaysAboveLeftOf = (
const menuOptions: IPosition & { chevronFace: ChevronFace } = { chevronFace };

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.
if (buttonBottom < UIStore.instance.windowHeight / 2) {
menuOptions.top = buttonBottom + vPadding;
} else {
menuOptions.bottom = (UIStore.instance.windowHeight - buttonTop) + vPadding;
}
// Align the menu vertically above the menu
menuOptions.bottom = (UIStore.instance.windowHeight - buttonTop) + vPadding;

return menuOptions;
};
Expand Down
2 changes: 0 additions & 2 deletions src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -546,8 +546,6 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}

private onAction = (payload: ActionPayload): void => {
// console.log(`MatrixClientPeg.onAction: ${payload.action}`);

// Start the onboarding process for certain actions
if (MatrixClientPeg.get()?.isGuest() && ONBOARDING_FLOW_STARTERS.includes(payload.action)) {
// This will cause `payload` to be dispatched later, once a
Expand Down
5 changes: 3 additions & 2 deletions src/components/structures/RightPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,12 @@ export default class RightPanel extends React.Component<IProps, IState> {
if (!this.props.room || member.roomId !== this.props.room.roomId) {
return;
}

// redraw the badge on the membership list
if (this.state.phase === RightPanelPhases.RoomMemberList && member.roomId === this.props.room.roomId) {
if (this.state.phase === RightPanelPhases.RoomMemberList) {
this.delayedUpdate();
} else if (
this.state.phase === RightPanelPhases.RoomMemberInfo && member.roomId === this.props.room.roomId &&
this.state.phase === RightPanelPhases.RoomMemberInfo &&
member.userId === this.state.cardState.member.userId
) {
// refresh the member info (e.g. new power level)
Expand Down
1 change: 0 additions & 1 deletion src/components/structures/RoomView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2293,7 +2293,6 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
highlightedEventId = this.state.initialEventId;
}

// console.info("ShowUrlPreview for %s is %s", this.state.room.roomId, this.state.showUrlPreview);
const messagePanel = (
<TimelinePanel
ref={this.gatherTimelinePanelRef}
Expand Down
10 changes: 6 additions & 4 deletions src/components/structures/SpaceHierarchy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,11 @@ const ManageButtons = ({ hierarchy, selected, setSelected, setError }: IManageBu
};
}

let buttonText = _t("Saving...");
if (!saving) {
buttonText = selectionAllSuggested ? _t("Mark as not suggested") : _t("Mark as suggested");
}

return <>
<Button
{...props}
Expand Down Expand Up @@ -669,10 +674,7 @@ const ManageButtons = ({ hierarchy, selected, setSelected, setError }: IManageBu
kind="primary_outline"
disabled={disabled}
>
{ saving
? _t("Saving...")
: (selectionAllSuggested ? _t("Mark as not suggested") : _t("Mark as suggested"))
}
{ buttonText }
</Button>
</>;
};
Expand Down
3 changes: 1 addition & 2 deletions src/components/structures/SpaceRoomView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -477,8 +477,7 @@ const SpaceSetupPrivateInvite = ({ space, onFinished }) => {
ev.preventDefault();
if (busy) return;
setError("");
for (let i = 0; i < fieldRefs.length; i++) {
const fieldRef = fieldRefs[i];
for (const fieldRef of fieldRefs) {
const valid = await fieldRef.current.validate({ allowEmpty: true });

if (valid === false) { // true/null are allowed
Expand Down
2 changes: 0 additions & 2 deletions src/components/structures/TimelinePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -645,8 +645,6 @@ class TimelinePanel extends React.Component<IProps, IState> {
if (data.timeline.getTimelineSet() !== this.props.timelineSet) return;

if (!Thread.hasServerSideSupport && this.context.timelineRenderingType === TimelineRenderingType.Thread) {
// const direction = toStartOfTimeline ? Direction.Backward : Direction.Forward;
// this.timelineWindow.extend(direction, 1);
if (toStartOfTimeline && !this.state.canBackPaginate) {
this.setState({
canBackPaginate: true,
Expand Down
10 changes: 2 additions & 8 deletions src/components/views/auth/PasswordLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,14 +191,8 @@ export default class PasswordLogin extends React.PureComponent<IProps, IState> {
return false;
}

private allFieldsValid() {
const keys = Object.keys(this.state.fieldValid);
for (let i = 0; i < keys.length; ++i) {
if (!this.state.fieldValid[keys[i]]) {
return false;
}
}
return true;
private allFieldsValid(): boolean {
return Object.values(this.state.fieldValid).every(Boolean);
}

private findFirstInvalidField(fieldIDs: LoginField[]) {
Expand Down
10 changes: 2 additions & 8 deletions src/components/views/auth/RegistrationForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,8 @@ export default class RegistrationForm extends React.PureComponent<IProps, IState
/**
* @returns {boolean} true if all fields were valid last time they were validated.
*/
private allFieldsValid() {
const keys = Object.keys(this.state.fieldValid);
for (let i = 0; i < keys.length; ++i) {
if (!this.state.fieldValid[keys[i]]) {
return false;
}
}
return true;
private allFieldsValid(): boolean {
return Object.values(this.state.fieldValid).every(Boolean);
}

private findFirstInvalidField(fieldIDs: RegistrationField[]) {
Expand Down
6 changes: 2 additions & 4 deletions src/components/views/avatars/DecoratedRoomAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,8 @@ export default class DecoratedRoomAvatar extends React.PureComponent<IProps, ISt
if (otherUserId && this.props.room.getJoinedMemberCount() === 2) {
// Track presence, if available
if (isPresenceEnabled()) {
if (otherUserId) {
this.dmUser = MatrixClientPeg.get().getUser(otherUserId);
icon = this.getPresenceIcon();
}
this.dmUser = MatrixClientPeg.get().getUser(otherUserId);
icon = this.getPresenceIcon();
}
} else {
// Track publicity
Expand Down
6 changes: 4 additions & 2 deletions src/components/views/dialogs/AddExistingToSpaceDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export const AddExistingToSpace: React.FC<IAddExistingToSpaceProps> = ({
setError(null);
setProgress(0);

let error;
let error: Error | undefined;

for (const room of selectedToAdd) {
const via = calculateRoomVia(room);
Expand All @@ -197,13 +197,15 @@ export const AddExistingToSpace: React.FC<IAddExistingToSpaceProps> = ({
setProgress(i => i + 1);
} catch (e) {
logger.error("Failed to add rooms to space", e);
setError(error = e);
error = e;
break;
}
}

if (!error) {
onFinished(true);
} else {
setError(error);
}
};

Expand Down
3 changes: 0 additions & 3 deletions src/components/views/dialogs/CreateRoomDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,6 @@ export default class CreateRoomDialog extends React.Component<IProps, IState> {
this.nameField.current.focus();
}

componentWillUnmount() {
}

private onKeyDown = (event: KeyboardEvent) => {
const action = getKeyBindingsManager().getAccessibilityAction(event);
switch (action) {
Expand Down
11 changes: 6 additions & 5 deletions src/components/views/dialogs/KeySignatureUploadFailedDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,13 @@ const KeySignatureUploadFailedDialog: React.FC<IProps> = ({
/>
</div>);
} else {
let text = _t("Upload completed");
if (!success) {
text = cancelled ? _t("Cancelled signature upload") : _t("Unable to upload");
}

body = (<div>
{ success ?
<span>{ _t("Upload completed") }</span> :
cancelled ?
<span>{ _t("Cancelled signature upload") }</span> :
<span>{ _t("Unable to upload") }</span> }
<span>{ text }</span>
<DialogButtons
primaryButton={_t("OK")}
hasCancel={false}
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/elements/AccessibleButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ type DynamicElementProps<T extends keyof JSX.IntrinsicElements> =
type IProps<T extends keyof JSX.IntrinsicElements> = DynamicHtmlElementProps<T> & {
inputRef?: React.Ref<Element>;
element?: T;
children?: ReactNode | undefined;
children?: ReactNode;
// The kind of button, similar to how Bootstrap works.
// See available classes for AccessibleButton for options.
kind?: AccessibleButtonKind | string;
Expand Down
10 changes: 0 additions & 10 deletions src/components/views/elements/EditableText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,6 @@ export default class EditableText extends React.Component<IProps, IState> {
};

private onKeyDown = (ev: React.KeyboardEvent<HTMLDivElement>): void => {
// console.log("keyDown: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder);

if (this.placeholder) {
this.showPlaceholder(false);
}
Expand All @@ -130,13 +128,9 @@ export default class EditableText extends React.Component<IProps, IState> {
ev.preventDefault();
break;
}

// console.log("keyDown: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder);
};

private onKeyUp = (ev: React.KeyboardEvent<HTMLDivElement>): void => {
// console.log("keyUp: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder);

if (!(ev.target as HTMLDivElement).textContent) {
this.showPlaceholder(true);
} else if (!this.placeholder) {
Expand All @@ -152,8 +146,6 @@ export default class EditableText extends React.Component<IProps, IState> {
this.onFinish(ev);
break;
}

// console.log("keyUp: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder);
};

private onClickDiv = (): void => {
Expand All @@ -165,8 +157,6 @@ export default class EditableText extends React.Component<IProps, IState> {
};

private onFocus = (ev: React.FocusEvent<HTMLDivElement>): void => {
//ev.target.setSelectionRange(0, ev.target.textContent.length);

const node = ev.target.childNodes[0];
if (node) {
const range = document.createRange();
Expand Down
Loading

0 comments on commit 3747464

Please sign in to comment.