A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(app): replace nested ternaries in composer and modals
Hampus486f0736ee35
diff --git a/fluxer_app/src/features/devtools/utils/CommandUtils.ts b/fluxer_app/src/features/devtools/utils/CommandUtils.tsindex 4a81cca29..01884ac22 100644--- a/fluxer_app/src/features/devtools/utils/CommandUtils.ts+++ b/fluxer_app/src/features/devtools/utils/CommandUtils.ts@@ -239,11 +239,14 @@ function getCurrentUserNicknameLabels(guildId: string, i18n: I18n): {previous: sconst currentUserId = Authentication.currentUserId;const currentMember = GuildMembers.getMember(guildId, currentUserId);const currentUser = Users.getCurrentUser();- const fallback = currentUser- ? NicknameUtils.getDisplayName(currentUser)- : currentMember- ? NicknameUtils.getDisplayName(currentMember.user)- : i18n._(UNKNOWN_USER_DESCRIPTOR);+ let fallback: string;+ if (currentUser) {+ fallback = NicknameUtils.getDisplayName(currentUser);+ } else if (currentMember) {+ fallback = NicknameUtils.getDisplayName(currentMember.user);+ } else {+ fallback = i18n._(UNKNOWN_USER_DESCRIPTOR);+ }const memberNickname = currentMember?.nick?.trim();if (!currentMember && localCurrentUserNicknames.has(guildId)) {const localNickname = localCurrentUserNicknames.get(guildId)?.trim();diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation.tsindex 9ae21b912..91a629946 100644--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation.ts+++ b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation.ts@@ -619,13 +619,12 @@ export function presentMemberRoleUpdate(entry: GuildAuditLogEntryResponse): Audi}const role = rolePlaceholder(single.roleId, readString(readOption(entry, 'role_name')));const {target} = subject;- const summary =- subject.actor.kind !== 'system'- ? roleChangeSummary(subject, single, role)- : single.kind === 'added'- ? sentence(MEMBER_ROLE_ADDED_BY_SYSTEM_SUMMARY, {target, role})- : sentence(MEMBER_ROLE_REMOVED_BY_SYSTEM_SUMMARY, {target, role});- return {summary, rows: temporary, blocks: []};+ if (subject.actor.kind !== 'system') {+ return {summary: roleChangeSummary(subject, single, role), rows: temporary, blocks: []};+ }+ const systemSummary =+ single.kind === 'added' ? MEMBER_ROLE_ADDED_BY_SYSTEM_SUMMARY : MEMBER_ROLE_REMOVED_BY_SYSTEM_SUMMARY;+ return {summary: sentence(systemSummary, {target, role}), rows: temporary, blocks: []};}export function presentMemberMove(entry: GuildAuditLogEntryResponse): AuditLogDomainResult {diff --git a/fluxer_app/src/features/input/components/KeybindRecorder.tsx b/fluxer_app/src/features/input/components/KeybindRecorder.tsxindex 6890e4ae8..f21b0c3e2 100644--- a/fluxer_app/src/features/input/components/KeybindRecorder.tsx+++ b/fluxer_app/src/features/input/components/KeybindRecorder.tsx@@ -344,11 +344,12 @@ const KeybindEditorPopout: React.FC<KeybindEditorPopoutProps> = ({};rafId = requestAnimationFrame(pollGamepads);const globalShortcutsApi = getGlobalShortcutsApi();- const cancelGlobalCapture = globalShortcutsApi- ? canCaptureFromHook(globalShortcutsApi)- ? beginShortcutCapture(globalShortcutsApi, handleCaptureEvent)- : null- : beginGlobalKeyCapture(getElectronAPI(), handleGlobalKeyEvent);+ let cancelGlobalCapture: (() => void) | null = null;+ if (!globalShortcutsApi) {+ cancelGlobalCapture = beginGlobalKeyCapture(getElectronAPI(), handleGlobalKeyEvent);+ } else if (canCaptureFromHook(globalShortcutsApi)) {+ cancelGlobalCapture = beginShortcutCapture(globalShortcutsApi, handleCaptureEvent);+ }window.addEventListener('keydown', handleKeyDown, true);window.addEventListener('keyup', handleKeyUp, true);window.addEventListener('mousedown', handleMouseDown, true);@@ -370,6 +371,14 @@ const KeybindEditorPopout: React.FC<KeybindEditorPopoutProps> = ({setPreviewCombo(null);onReset?.();};+ let recorderText: React.ReactNode;+ if (recording) {+ recorderText = <Trans>Press a shortcut…</Trans>;+ } else if (currentHasValue) {+ recorderText = displayValue;+ } else {+ recorderText = <Trans>Click to record</Trans>;+ }return (<div className={styles.popout} data-flx="input.keybind-recorder.keybind-editor-popout.popout"><div className={styles.popoutHeader} data-flx="input.keybind-recorder.keybind-editor-popout.popout-header">@@ -402,13 +411,7 @@ const KeybindEditorPopout: React.FC<KeybindEditorPopoutProps> = ({data-flx="input.keybind-recorder.keybind-editor-popout.recorder-icon"/><span className={styles.recorderText} data-flx="input.keybind-recorder.keybind-editor-popout.recorder-text">- {recording ? (- <Trans>Press a shortcut…</Trans>- ) : currentHasValue ? (- displayValue- ) : (- <Trans>Click to record</Trans>- )}+ {recorderText}</span></div></FocusRing>diff --git a/fluxer_app/src/features/lexical/composer/LexicalComposerInput.tsx b/fluxer_app/src/features/lexical/composer/LexicalComposerInput.tsxindex a7aa5e0b3..96dbd434d 100644--- a/fluxer_app/src/features/lexical/composer/LexicalComposerInput.tsx+++ b/fluxer_app/src/features/lexical/composer/LexicalComposerInput.tsx@@ -768,7 +768,7 @@ const ComposerInner = ({onContextMenu={handleEditableContextMenu}onFocus={onFocus}onBlur={onBlur}- aria-label={ariaLabelledBy == null ? (ariaLabel == null ? placeholder : ariaLabel) : undefined}+ aria-label={ariaLabelledBy == null ? (ariaLabel ?? placeholder) : undefined}aria-labelledby={ariaLabelledBy}aria-describedby={ariaDescribedBy}aria-errormessage={ariaErrorMessage}diff --git a/fluxer_app/src/features/lexical/composer/markdownSpans.ts b/fluxer_app/src/features/lexical/composer/markdownSpans.tsindex f6f2ddba2..74f83e518 100644--- a/fluxer_app/src/features/lexical/composer/markdownSpans.ts+++ b/fluxer_app/src/features/lexical/composer/markdownSpans.ts@@ -284,12 +284,12 @@ function alignNode(node: Node, format: MarkdownHlFormat, ctx: AlignContext): voireturn;}case 'Strong': {- const delimiter = ctx.source.startsWith('**', ctx.pos)- ? '**'- : ctx.source.startsWith('__', ctx.pos)- ? '__'- : null;- if (delimiter == null) {+ let delimiter: '**' | '__';+ if (ctx.source.startsWith('**', ctx.pos)) {+ delimiter = '**';+ } else if (ctx.source.startsWith('__', ctx.pos)) {+ delimiter = '__';+ } else {ctx.failed = true;return;}diff --git a/fluxer_app/src/features/lexical/composer/nodes/ComposerMentionNode.tsx b/fluxer_app/src/features/lexical/composer/nodes/ComposerMentionNode.tsxindex 5f479deed..0ab0bf18f 100644--- a/fluxer_app/src/features/lexical/composer/nodes/ComposerMentionNode.tsx+++ b/fluxer_app/src/features/lexical/composer/nodes/ComposerMentionNode.tsx@@ -173,10 +173,16 @@ function mentionPresentationStyle(presentation: ComposerMentionPresentationForma}const underline = (presentation & ComposerMentionPresentation.underline) !== 0;const strike = (presentation & ComposerMentionPresentation.strike) !== 0;+ const textDecorations: Array<string> = [];+ if (underline) {+ textDecorations.push('underline');+ }+ if (strike) {+ textDecorations.push('line-through');+ }return {fontStyle: (presentation & ComposerMentionPresentation.italic) !== 0 ? 'italic' : undefined,- textDecorationLine:- underline && strike ? 'underline line-through' : underline ? 'underline' : strike ? 'line-through' : undefined,+ textDecorationLine: textDecorations.length > 0 ? textDecorations.join(' ') : undefined,fontSize: (presentation & ComposerMentionPresentation.subtext) !== 0 ? '0.85em' : undefined,color:(presentation & ComposerMentionPresentation.subtext) !== 0diff --git a/fluxer_app/src/features/lexical/composer/nodes/SlashSlotNode.ts b/fluxer_app/src/features/lexical/composer/nodes/SlashSlotNode.tsindex 4582030f9..1830ddfa2 100644--- a/fluxer_app/src/features/lexical/composer/nodes/SlashSlotNode.ts+++ b/fluxer_app/src/features/lexical/composer/nodes/SlashSlotNode.ts@@ -414,8 +414,7 @@ export class SlashSlotNode extends ElementNode {setResolvedWire(resolvedWire: string | null, resolvedDisplay?: string | null): this {const writable = this.getWritable();writable.__resolvedWire = resolvedWire;- writable.__resolvedDisplay =- resolvedWire == null ? null : resolvedDisplay == null ? this.getTextContent() : resolvedDisplay;+ writable.__resolvedDisplay = resolvedWire == null ? null : (resolvedDisplay ?? this.getTextContent());if (resolvedWire != null) {writable.__validity = 'valid';writable.__validationError = null;diff --git a/fluxer_app/src/features/lexical/composer/slashSlots.ts b/fluxer_app/src/features/lexical/composer/slashSlots.tsindex fc0f40998..9cc6cd35f 100644--- a/fluxer_app/src/features/lexical/composer/slashSlots.ts+++ b/fluxer_app/src/features/lexical/composer/slashSlots.ts@@ -25,6 +25,7 @@ import {$createSlashSlotNode,$isSlashSlotNode,SlashSlotNode,+ type SlashSlotValidity,} from '@app/features/lexical/composer/nodes/SlashSlotNode';import {$createSlashSlotPlaceholderNode,@@ -128,17 +129,6 @@ function $collectSlots(): Array<SlashSlotNode> {return slots;}-function $enclosingSlot(node: LexicalNode): SlashSlotNode | null {- let current: LexicalNode | null = node;- while (current != null) {- if ($isSlashSlotNode(current)) {- return current;- }- current = current.getParent();- }- return null;-}-function $isPointAtSlotBoundary(slot: SlashSlotNode, point: PointType, boundary: 'start' | 'end'): boolean {const node = point.getNode();if (point.type === 'element') {@@ -508,11 +498,10 @@ function $handleSlashStructuralDelete(event: KeyboardEvent, isBackward: boolean)if (adjacent == null) {return false;}- const adjacentSlot = $isSlashSeparatorNode(adjacent)- ? isBackward- ? adjacent.getPreviousSibling()- : adjacent.getNextSibling()- : adjacent;+ let adjacentSlot: LexicalNode | null = adjacent;+ if ($isSlashSeparatorNode(adjacent)) {+ adjacentSlot = isBackward ? adjacent.getPreviousSibling() : adjacent.getNextSibling();+ }if ($isSlashSlotNode(adjacentSlot)) {event.preventDefault();if (adjacentSlot.isRequired()) {@@ -573,14 +562,12 @@ export function registerSlashSlotPlugin(const text = node.getTextContent();const resolvedDisplay = node.getResolvedDisplay();const nextTouched = node.isTouched() || text.length > 0 || (resolvedDisplay != null && resolvedDisplay !== text);- const nextValidity =- text.length === 0- ? node.isSubmitRequired() && nextTouched- ? 'invalid'- : 'neutral'- : result.valid- ? 'valid'- : 'invalid';+ let nextValidity: SlashSlotValidity;+ if (text.length > 0) {+ nextValidity = result.valid ? 'valid' : 'invalid';+ } else {+ nextValidity = node.isSubmitRequired() && nextTouched ? 'invalid' : 'neutral';+ }const nextWire = result.resolvedWire == null ? null : result.resolvedWire;if (node.isTouched() !== nextTouched) {node.setTouched(nextTouched);diff --git a/fluxer_app/src/features/lexical/composer/useLexicalAutocomplete.ts b/fluxer_app/src/features/lexical/composer/useLexicalAutocomplete.tsindex eb2d7c087..2e4f9de33 100644--- a/fluxer_app/src/features/lexical/composer/useLexicalAutocomplete.ts+++ b/fluxer_app/src/features/lexical/composer/useLexicalAutocomplete.ts@@ -286,11 +286,7 @@ export function useLexicalAutocomplete({});const autocompleteTriggerGifQuery =- autocompleteTriggerType === 'gif'- ? autocompleteTrigger == null || autocompleteTrigger.match[3] == null- ? ''- : autocompleteTrigger.match[3].trim()- : '';+ autocompleteTriggerType === 'gif' ? (autocompleteTrigger?.match[3]?.trim() ?? '') : '';useAutocompleteGifSearch({triggerType: autocompleteTriggerType,query: autocompleteTriggerGifQuery,@@ -641,20 +637,21 @@ export function useLexicalAutocomplete({return 'mention';}}, [slotAutocompleteContext == null ? undefined : slotAutocompleteContext.optionType]);- const activeSlotMenu =- slotAutocompleteContext != null- ? {- type: slotAutocompleteType,- options: slotAutocompleteOptions,- query: normalizeSlotQuery(slotAutocompleteContext),- }- : slotOptionalContext != null- ? {type: 'commandOptionalAdd' as const, options: slotOptionalOptions, query: slotOptionalContext.query}- : null;+ let activeSlotMenu: AutocompleteMenuState | null = null;+ if (slotAutocompleteContext != null) {+ activeSlotMenu = {+ type: slotAutocompleteType,+ options: slotAutocompleteOptions,+ query: normalizeSlotQuery(slotAutocompleteContext),+ };+ } else if (slotOptionalContext != null) {+ activeSlotMenu = {type: 'commandOptionalAdd', options: slotOptionalOptions, query: slotOptionalContext.query};+ }const isSlotMenu = activeSlotMenu != null;- const autocompleteOptions = isSlotMenu ? activeSlotMenu.options : baseAutocompleteMenu.options;- const autocompleteType = isSlotMenu ? activeSlotMenu.type : baseAutocompleteMenu.type;- const resolvedAutocompleteQuery = isSlotMenu ? activeSlotMenu.query : baseAutocompleteMenu.query;+ const autocompleteMenu = activeSlotMenu ?? baseAutocompleteMenu;+ const autocompleteOptions = autocompleteMenu.options;+ const autocompleteType = autocompleteMenu.type;+ const resolvedAutocompleteQuery = autocompleteMenu.query;const isAutocompleteAttached = autocompleteOptions.length > 0;const handleSelect = useCallback(diff --git a/fluxer_app/src/features/messaging/components/alerts/AttachmentPermissionDeniedModal.tsx b/fluxer_app/src/features/messaging/components/alerts/AttachmentPermissionDeniedModal.tsxindex d503422b0..596b00db0 100644--- a/fluxer_app/src/features/messaging/components/alerts/AttachmentPermissionDeniedModal.tsx+++ b/fluxer_app/src/features/messaging/components/alerts/AttachmentPermissionDeniedModal.tsx@@ -8,6 +8,7 @@ import {modal} from '@app/features/ui/commands/ModalCommands';import {msg} from '@lingui/core/macro';import {Trans, useLingui} from '@lingui/react/macro';import {observer} from 'mobx-react-lite';+import type React from 'react';const CAN_T_PASTE_IMAGE_HERE_DESCRIPTOR = msg({message: "Can't paste image here",@@ -33,18 +34,19 @@ export const AttachmentPermissionDeniedModal = observer(const title = hasOnlyImages? i18n._(CAN_T_PASTE_IMAGE_HERE_DESCRIPTOR): i18n._(CAN_T_UPLOAD_FILES_HERE_DESCRIPTOR);- const description = canSendMessages ? (- hasOnlyImages ? (+ let description: React.ReactNode;+ if (!canSendMessages) {+ description = i18n._(CANNOT_SEND_MESSAGES_IN_CHANNEL_DESCRIPTOR);+ } else if (hasOnlyImages) {+ description = (<Trans>Images pasted from your clipboard are sent as attachments, and you don't have permission to attach files inthis channel.</Trans>- ) : (- i18n._(YOU_DON_T_HAVE_PERMISSION_TO_ATTACH_FILES_DESCRIPTOR)- )- ) : (- i18n._(CANNOT_SEND_MESSAGES_IN_CHANNEL_DESCRIPTOR)- );+ );+ } else {+ description = i18n._(YOU_DON_T_HAVE_PERMISSION_TO_ATTACH_FILES_DESCRIPTOR);+ }return (<GenericErrorModaltitle={title}diff --git a/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsx b/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsxindex d8a019bc2..cb103ff6a 100644--- a/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsx+++ b/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsx@@ -717,7 +717,7 @@ const MediaViewerModalComponent: FC = observer(() => {providerName={currentItem.providerName}videoSrc={currentItem.type === 'video' ? currentItem.src : undefined}initialTime={currentItem.initialTime}- mediaType={currentItem.type === 'audio' ? 'audio' : currentItem.type === 'video' ? 'video' : 'image'}+ mediaType={currentItem.type === 'audio' || currentItem.type === 'video' ? currentItem.type : 'image'}onMenuOpen={handleMenuOpen}data-flx="messaging.media-viewer-modal.media-viewer-modal-component.media-modal">diff --git a/fluxer_app/src/features/messaging/components/modals/UploadDropModal.tsx b/fluxer_app/src/features/messaging/components/modals/UploadDropModal.tsxindex 08636a2e0..890feb8ad 100644--- a/fluxer_app/src/features/messaging/components/modals/UploadDropModal.tsx+++ b/fluxer_app/src/features/messaging/components/modals/UploadDropModal.tsx@@ -4,6 +4,7 @@ import type {Channel} from '@app/features/channel/models/Channel';import {UNKNOWN_CHANNEL_DESCRIPTOR} from '@app/features/channel/utils/ChannelMessageDescriptors';import * as ChannelUtils from '@app/features/channel/utils/ChannelUtils';import styles from '@app/features/messaging/components/modals/UploadDropModal.module.css';+import type {MessageDescriptor} from '@lingui/core';import {msg} from '@lingui/core/macro';import {useLingui} from '@lingui/react/macro';import {ArrowFatUpIcon, FileIcon} from '@phosphor-icons/react';@@ -46,11 +47,22 @@ interface UploadDropModalProps {export const UploadDropModal = ({channel, isShiftHeld, isSlowmodeActive}: UploadDropModalProps) => {const {i18n} = useLingui();- const displayName = channel.isPrivate()- ? ChannelUtils.getDMDisplayName(channel)- : channel.name- ? `#${channel.name}`- : i18n._(UNKNOWN_CHANNEL_DESCRIPTOR);+ let displayName: string;+ if (channel.isPrivate()) {+ displayName = ChannelUtils.getDMDisplayName(channel);+ } else if (channel.name) {+ displayName = `#${channel.name}`;+ } else {+ displayName = i18n._(UNKNOWN_CHANNEL_DESCRIPTOR);+ }+ let descriptionDescriptor: MessageDescriptor;+ if (isShiftHeld) {+ descriptionDescriptor = FILES_WILL_BE_SENT_IMMEDIATELY_WITHOUT_PREVIEW_DESCRIPTOR;+ } else if (isSlowmodeActive) {+ descriptionDescriptor = YOU_CAN_ADD_COMMENTS_BEFORE_UPLOADING_DIRECT_UPLOAD_DESCRIPTOR;+ } else {+ descriptionDescriptor = YOU_CAN_ADD_COMMENTS_BEFORE_UPLOADING_HOLD_SHIFT_DESCRIPTOR;+ }return (<div className={styles.overlay} data-flx="messaging.upload-drop-modal.overlay"><div className={styles.dialog} data-flx="messaging.upload-drop-modal.dialog">@@ -64,11 +76,7 @@ export const UploadDropModal = ({channel, isShiftHeld, isSlowmodeActive}: Upload: i18n._(UPLOAD_TO_DESCRIPTOR, {displayName})}</h2><p className={styles.dialogDescription} data-flx="messaging.upload-drop-modal.dialog-description">- {isShiftHeld- ? i18n._(FILES_WILL_BE_SENT_IMMEDIATELY_WITHOUT_PREVIEW_DESCRIPTOR)- : isSlowmodeActive- ? i18n._(YOU_CAN_ADD_COMMENTS_BEFORE_UPLOADING_DIRECT_UPLOAD_DESCRIPTOR)- : i18n._(YOU_CAN_ADD_COMMENTS_BEFORE_UPLOADING_HOLD_SHIFT_DESCRIPTOR)}+ {i18n._(descriptionDescriptor)}</p></div><div