A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(app): merge duplicated helpers and drop dead code
Hampus59f7c7d6cce3
diff --git a/fluxer_app/src/features/accessibility/state/Accessibility.ts b/fluxer_app/src/features/accessibility/state/Accessibility.tsindex 2f0286e97..f6c29d0d2 100644--- a/fluxer_app/src/features/accessibility/state/Accessibility.ts+++ b/fluxer_app/src/features/accessibility/state/Accessibility.ts@@ -480,7 +480,7 @@ function readAccessibilityStartupSettings() {return null;}- const preserveLegacyZoomLevel = options.preserveLegacyZoomLevel ?? shouldPreserveLegacyZoomLevel();+ const preserveLegacyZoomLevel = shouldPreserveLegacyZoomLevel();return {zoomLevel: localZoomLevel ?? (preserveLegacyZoomLevel ? (legacySettings?.zoomLevel ?? 1.0) : 1.0),syncReducedMotionWithSystem:diff --git a/fluxer_app/src/features/app/components/layout/GuildsLayout.tsx b/fluxer_app/src/features/app/components/layout/GuildsLayout.tsxindex 1df530551..0b1b28cff 100644--- a/fluxer_app/src/features/app/components/layout/GuildsLayout.tsx+++ b/fluxer_app/src/features/app/components/layout/GuildsLayout.tsx@@ -45,7 +45,7 @@ import {type GuildDropPosition,type GuildDropResult,} from '@app/features/app/components/layout/types/DndTypes';-import {UserArea} from '@app/features/app/components/layout/UserArea';+import {getResizeObserverEntryBlockSize, UserArea} from '@app/features/app/components/layout/UserArea';import {getChannelUnreadState} from '@app/features/app/components/layout/utils/ChannelUnreadState';import {getRememberedSkeletonGuildRailScrollTopPx,diff --git a/fluxer_app/src/features/app/components/layout/UserArea.tsx b/fluxer_app/src/features/app/components/layout/UserArea.tsxindex 9a4ec526d..607b6d009 100644--- a/fluxer_app/src/features/app/components/layout/UserArea.tsx+++ b/fluxer_app/src/features/app/components/layout/UserArea.tsx@@ -76,7 +76,7 @@ const OPEN_USER_MENU_FOR_DESCRIPTOR = msg({});const VOICE_CONNECTION_HEIGHT_VARIABLE = '--layout-voice-connection-height';-function getResizeObserverEntryBlockSize(entry: ResizeObserverEntry): number {+export function getResizeObserverEntryBlockSize(entry: ResizeObserverEntry): number {const borderBoxSize = entry.borderBoxSize;const firstBorderBoxSize = Array.isArray(borderBoxSize) ? borderBoxSize[0] : borderBoxSize;return firstBorderBoxSize?.blockSize ?? entry.contentRect.height;diff --git a/fluxer_app/src/features/app/components/layout/app_layout/NagbarContainer.tsx b/fluxer_app/src/features/app/components/layout/app_layout/NagbarContainer.tsxindex b3ea00af3..410908bf9 100644--- a/fluxer_app/src/features/app/components/layout/app_layout/NagbarContainer.tsx+++ b/fluxer_app/src/features/app/components/layout/app_layout/NagbarContainer.tsx@@ -34,13 +34,61 @@ interface NagbarContainerProps {nagbars: Array<NagbarState>;}+interface NagbarEntry {+ Component: React.ComponentType<{isMobile: boolean}>;+ premium?: boolean;+}+class UnexpectedNagbarTypeError extends Error {- constructor(nagbarType: never) {- super(`Unexpected nagbar type: ${String(nagbarType)}`);+ constructor(nagbarType: string) {+ super(`Unexpected nagbar type: ${nagbarType}`);this.name = 'UnexpectedNagbarTypeError';}}+const PremiumGracePeriodNagbar = ({isMobile}: {isMobile: boolean}) => (+ <PremiumStatusNagbar+ variant="grace-period"+ isMobile={isMobile}+ data-flx="app.app-layout.nagbar-container.premium-grace-period-nagbar"+ />+);++const PremiumExpiredNagbar = ({isMobile}: {isMobile: boolean}) => (+ <PremiumStatusNagbar+ variant="expired"+ isMobile={isMobile}+ data-flx="app.app-layout.nagbar-container.premium-expired-nagbar"+ />+);++const NAGBARS: Record<NagbarType, NagbarEntry> = {+ [NagbarType.BUILD_ENVIRONMENT]: {Component: BuildEnvironmentNagbar},+ [NagbarType.CONNECTION]: {Component: ConnectionNagbar},+ [NagbarType.CORRUPTED_INSTALLATION]: {Component: CorruptedInstallationNagbar},+ [NagbarType.TERMS_ACCEPTANCE]: {Component: TermsAcceptanceNagbar},+ [NagbarType.SCHEDULED_MAINTENANCE]: {Component: ScheduledMaintenanceNagbar},+ [NagbarType.INSTANCE_NOTICE]: {Component: InstanceNoticeNagbar},+ [NagbarType.UNCLAIMED_ACCOUNT]: {Component: UnclaimedAccountNagbar},+ [NagbarType.EMAIL_VERIFICATION]: {Component: EmailVerificationNagbar},+ [NagbarType.ACCOUNT_LIMITED]: {Component: AccountLimitedNagbar},+ [NagbarType.DESKTOP_NOTIFICATION]: {Component: DesktopNotificationNagbar},+ [NagbarType.PREMIUM_GRACE_PERIOD]: {Component: PremiumGracePeriodNagbar, premium: true},+ [NagbarType.PREMIUM_EXPIRED]: {Component: PremiumExpiredNagbar, premium: true},+ [NagbarType.PREMIUM_ONBOARDING]: {Component: PremiumOnboardingNagbar, premium: true},+ [NagbarType.PRICE_ANNOUNCEMENT]: {Component: PriceAnnouncementNagbar, premium: true},+ [NagbarType.LEGACY_PRICE_OPT_IN]: {Component: LegacyPriceOptInNagbar, premium: true},+ [NagbarType.GIFT_INVENTORY]: {Component: GiftInventoryNagbar, premium: true},+ [NagbarType.DESKTOP_DOWNLOAD]: {Component: DesktopDownloadNagbar},+ [NagbarType.GUILD_MEMBERSHIP_CTA]: {Component: GuildMembershipCtaNagbar},+ [NagbarType.VISIONARY_MFA]: {Component: VisionaryMfaNagbar, premium: true},+ [NagbarType.VOICE_SESSION_RESTORE]: {Component: VoiceSessionRestoreNagbar},+ [NagbarType.SOFTWARE_ENCODER]: {Component: SoftwareEncoderNagbar},+ [NagbarType.STREAMER_MODE]: {Component: StreamerModeNagbar},+ [NagbarType.DOMAIN_MOVED]: {Component: DomainMovedNagbar},+ [NagbarType.WINDOWS_FONT]: {Component: WindowsFontNagbar},+};+export const NagbarContainer: React.FC<NagbarContainerProps> = observer(({nagbars}) => {const mobileLayout = MobileLayout;const showPremiumFeatures = shouldShowPremiumFeatures();@@ -48,210 +96,16 @@ export const NagbarContainer: React.FC<NagbarContainerProps> = observer(({nagbarreturn (<div className={styles.container} data-flx="app.app-layout.nagbar-container.container">{nagbars.map((nagbar) => {- switch (nagbar.type) {- case NagbarType.BUILD_ENVIRONMENT:- return (- <BuildEnvironmentNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.build-environment-nagbar"- />- );- case NagbarType.CONNECTION:- return (- <ConnectionNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.connection-nagbar"- />- );- case NagbarType.CORRUPTED_INSTALLATION:- return (- <CorruptedInstallationNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.corrupted-installation-nagbar"- />- );- case NagbarType.TERMS_ACCEPTANCE:- return (- <TermsAcceptanceNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.terms-acceptance-nagbar"- />- );- case NagbarType.SCHEDULED_MAINTENANCE:- return (- <ScheduledMaintenanceNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.scheduled-maintenance-nagbar"- />- );- case NagbarType.INSTANCE_NOTICE:- return (- <InstanceNoticeNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.instance-notice-nagbar"- />- );- case NagbarType.UNCLAIMED_ACCOUNT:- return (- <UnclaimedAccountNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.unclaimed-account-nagbar"- />- );- case NagbarType.EMAIL_VERIFICATION:- return (- <EmailVerificationNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.email-verification-nagbar"- />- );- case NagbarType.ACCOUNT_LIMITED:- return (- <AccountLimitedNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.account-limited-nagbar"- />- );- case NagbarType.DESKTOP_NOTIFICATION:- return (- <DesktopNotificationNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.desktop-notification-nagbar"- />- );- case NagbarType.PREMIUM_GRACE_PERIOD:- if (!showPremiumFeatures) return null;- return (- <PremiumStatusNagbar- variant="grace-period"- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.premium-grace-period-nagbar"- />- );- case NagbarType.PREMIUM_EXPIRED:- if (!showPremiumFeatures) return null;- return (- <PremiumStatusNagbar- variant="expired"- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.premium-expired-nagbar"- />- );- case NagbarType.PREMIUM_ONBOARDING:- if (!showPremiumFeatures) return null;- return (- <PremiumOnboardingNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.premium-onboarding-nagbar"- />- );- case NagbarType.PRICE_ANNOUNCEMENT:- if (!showPremiumFeatures) return null;- return (- <PriceAnnouncementNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.price-announcement-nagbar"- />- );- case NagbarType.LEGACY_PRICE_OPT_IN:- if (!showPremiumFeatures) return null;- return (- <LegacyPriceOptInNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.legacy-price-opt-in-nagbar"- />- );- case NagbarType.GIFT_INVENTORY:- if (!showPremiumFeatures) return null;- return (- <GiftInventoryNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.gift-inventory-nagbar"- />- );- case NagbarType.DESKTOP_DOWNLOAD:- return (- <DesktopDownloadNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.desktop-download-nagbar"- />- );- case NagbarType.GUILD_MEMBERSHIP_CTA:- return (- <GuildMembershipCtaNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.guild-membership-cta-nagbar"- />- );- case NagbarType.VISIONARY_MFA:- if (!showPremiumFeatures) return null;- return (- <VisionaryMfaNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.visionary-mfa-nagbar"- />- );- case NagbarType.VOICE_SESSION_RESTORE:- return (- <VoiceSessionRestoreNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.voice-session-restore-nagbar"- />- );- case NagbarType.SOFTWARE_ENCODER:- return (- <SoftwareEncoderNagbar- key={nagbar.type}- data-flx="app.app-layout.nagbar-container.software-encoder-nagbar"- />- );- case NagbarType.STREAMER_MODE:- return (- <StreamerModeNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.streamer-mode-nagbar"- />- );- case NagbarType.DOMAIN_MOVED:- return (- <DomainMovedNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.domain-moved-nagbar"- />- );- case NagbarType.WINDOWS_FONT:- return (- <WindowsFontNagbar- key={nagbar.type}- isMobile={mobileLayout.enabled}- data-flx="app.app-layout.nagbar-container.windows-font-nagbar"- />- );- default:- throw new UnexpectedNagbarTypeError(nagbar.type);- }+ const entry: NagbarEntry | undefined = NAGBARS[nagbar.type];+ if (!entry) throw new UnexpectedNagbarTypeError(nagbar.type);+ if (entry.premium && !showPremiumFeatures) return null;+ return (+ <entry.Component+ key={nagbar.type}+ isMobile={mobileLayout.enabled}+ data-flx="app.app-layout.nagbar-container.nagbar"+ />+ );})}</div>);diff --git a/fluxer_app/src/features/app/hooks/useTextOverflow.ts b/fluxer_app/src/features/app/hooks/useTextOverflow.tsindex 565ea82e2..78d07b4a3 100644--- a/fluxer_app/src/features/app/hooks/useTextOverflow.ts+++ b/fluxer_app/src/features/app/hooks/useTextOverflow.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {observeResize} from '@app/features/platform/utils/SharedResizeObserver';-import {type RefObject, useEffect, useState} from 'react';+import {useEffect, useState} from 'react';type OverflowAxis = 'horizontal' | 'vertical' | 'both';@@ -12,10 +12,9 @@ function getElementOverflowState(el: HTMLElement, axis: OverflowAxis): boolean {);}-function useOverflow(target: HTMLElement | RefObject<HTMLElement | null> | null, axis: OverflowAxis): boolean {+export function useElementOverflow(element: HTMLElement | null, axis: OverflowAxis = 'horizontal'): boolean {const [isOverflowing, setIsOverflowing] = useState(false);useEffect(() => {- const element = target && 'current' in target ? target.current : target;const ownerWindow = element?.ownerDocument.defaultView;if (!element || !ownerWindow) {setIsOverflowing(false);@@ -41,10 +40,6 @@ function useOverflow(target: HTMLElement | RefObject<HTMLElement | null> | null,}unobserve?.();};- }, [target, axis]);+ }, [element, axis]);return isOverflowing;}--export function useElementOverflow(element: HTMLElement | null, axis: OverflowAxis = 'horizontal'): boolean {- return useOverflow(element, axis);-}diff --git a/fluxer_app/src/features/app/keybindings/utils/RuntimeKeybinds.ts b/fluxer_app/src/features/app/keybindings/utils/RuntimeKeybinds.tsindex 91dcf65dc..8a894ba82 100644--- a/fluxer_app/src/features/app/keybindings/utils/RuntimeKeybinds.ts+++ b/fluxer_app/src/features/app/keybindings/utils/RuntimeKeybinds.ts@@ -45,12 +45,8 @@ export function gamepadSourceIdForKeybind(keybind: {id: string | null; action: Kreturn `gamepad:${keybind.id}`;}-function hasTriggerInput(combo: KeyCombo): boolean {- return keyComboHasTriggerInput(combo);-}-function isEnabledDefaultCombo(combo: KeyCombo): boolean {- return (combo.enabled ?? true) !== false && hasTriggerInput(combo);+ return (combo.enabled ?? true) !== false && keyComboHasTriggerInput(combo);}export function buildDefaultRuntimeKeybinds(diff --git a/fluxer_app/src/features/auth/flow/AuthRegisterFormCore.tsx b/fluxer_app/src/features/auth/flow/AuthRegisterFormCore.tsxindex f161f2198..eec8b3d89 100644--- a/fluxer_app/src/features/auth/flow/AuthRegisterFormCore.tsx+++ b/fluxer_app/src/features/auth/flow/AuthRegisterFormCore.tsx@@ -447,6 +447,13 @@ export const AuthRegisterFormCore = observer(function AuthRegisterFormCore({</div>);}+ const reducedMotion = Accessibility.useReducedMotion;+ const helperMotionProps = {+ initial: reducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: -5},+ animate: {opacity: 1, y: 0},+ exit: reducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: 5},+ transition: {duration: reducedMotion ? 0 : 0.2},+ };return (<form id={formId} className={styles.form} onSubmit={form.handleSubmit} data-flx={`${flx}.form.submit`}>{formError ? (@@ -511,10 +518,7 @@ export const AuthRegisterFormCore = observer(function AuthRegisterFormCore({<motion.spankey="error"className={styles.usernameError}- initial={Accessibility.useReducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: -5}}- animate={{opacity: 1, y: 0}}- exit={Accessibility.useReducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: 5}}- transition={{duration: Accessibility.useReducedMotion ? 0 : 0.2}}+ {...helperMotionProps}data-flx="auth.flow.auth-register-form-core.username-error">{helperTextState.message}@@ -524,10 +528,7 @@ export const AuthRegisterFormCore = observer(function AuthRegisterFormCore({<motion.spankey={`hint-${helperTextState.message}`}className={styles.usernameHint}- initial={Accessibility.useReducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: -5}}- animate={{opacity: 1, y: 0}}- exit={Accessibility.useReducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: 5}}- transition={{duration: Accessibility.useReducedMotion ? 0 : 0.2}}+ {...helperMotionProps}data-flx="auth.flow.auth-register-form-core.username-sign-in-hint">{helperTextState.message}@@ -537,10 +538,7 @@ export const AuthRegisterFormCore = observer(function AuthRegisterFormCore({<motion.spankey="suggestion"className={styles.usernameHint}- initial={Accessibility.useReducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: -5}}- animate={{opacity: 1, y: 0}}- exit={Accessibility.useReducedMotion ? {opacity: 1, y: 0} : {opacity: 0, y: 5}}- transition={{duration: Accessibility.useReducedMotion ? 0 : 0.2}}+ {...helperMotionProps}data-flx="auth.flow.auth-register-form-core.username-hint"><Trans>How about:</Trans>{' '}diff --git a/fluxer_app/src/features/auth/hooks/useLoginFlow.ts b/fluxer_app/src/features/auth/hooks/useLoginFlow.tsindex d34bc2c49..d67026220 100644--- a/fluxer_app/src/features/auth/hooks/useLoginFlow.ts+++ b/fluxer_app/src/features/auth/hooks/useLoginFlow.ts@@ -52,6 +52,7 @@ import * as ToastCommands from '@app/features/ui/commands/ToastCommands';import {isDesktop} from '@app/features/ui/utils/NativeUtils';import {msg} from '@lingui/core/macro';import {useLingui} from '@lingui/react/macro';+import {browserSupportsWebAuthn} from '@simplewebauthn/browser';import {useCallback, useEffect, useMemo, useRef, useState} from 'react';const logger = Logger.create('useLoginFlow');@@ -72,7 +73,7 @@ export const PasskeyLoginCapability = Object.freeze({export type PasskeyLoginCapability = (typeof PasskeyLoginCapability)[keyof typeof PasskeyLoginCapability];export function resolveInitialPasskeyLoginCapability(): PasskeyLoginCapability {- if (isDesktop() || WebAuthnUtils.isBrowserWebAuthnSupported()) {+ if (isDesktop() || browserSupportsWebAuthn()) {return PasskeyLoginCapability.AVAILABLE;}return PasskeyLoginCapability.UNAVAILABLE;diff --git a/fluxer_app/src/features/auth/state/AuthSudo.ts b/fluxer_app/src/features/auth/state/AuthSudo.tsindex 017c6e327..44c8ae696 100644--- a/fluxer_app/src/features/auth/state/AuthSudo.ts+++ b/fluxer_app/src/features/auth/state/AuthSudo.ts@@ -26,10 +26,6 @@ class Sudo {this.token = null;this.expiresAt = null;}-- hasValidToken(): boolean {- return this.getValidToken() !== null;- }}export default new Sudo();diff --git a/fluxer_app/src/features/channel/components/RecipientAddMessage.module.css b/fluxer_app/src/features/channel/components/RecipientAddMessage.module.cssdeleted file mode 100644index 8b383123e..000000000--- a/fluxer_app/src/features/channel/components/RecipientAddMessage.module.css+++ /dev/null@@ -1,5 +0,0 @@-/* SPDX-License-Identifier: AGPL-3.0-or-later */--.icon {- color: rgb(34 197 94);-}diff --git a/fluxer_app/src/features/channel/components/RecipientAddMessage.tsx b/fluxer_app/src/features/channel/components/RecipientAddMessage.tsxindex 3c41e9aaf..dda5950cc 100644--- a/fluxer_app/src/features/channel/components/RecipientAddMessage.tsx+++ b/fluxer_app/src/features/channel/components/RecipientAddMessage.tsx@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import styles from '@app/features/channel/components/RecipientAddMessage.module.css';+import styles from '@app/features/channel/components/GuildJoinMessage.module.css';import {SystemMessage} from '@app/features/channel/components/SystemMessage';import {SystemMessageUsername} from '@app/features/channel/components/SystemMessageUsername';import {useSystemMessageData} from '@app/features/messaging/hooks/useSystemMessageData';diff --git a/fluxer_app/src/features/channel/components/direct_message/DirectMessageList.tsx b/fluxer_app/src/features/channel/components/direct_message/DirectMessageList.tsxindex 8d26a05bb..4721ca928 100644--- a/fluxer_app/src/features/channel/components/direct_message/DirectMessageList.tsx+++ b/fluxer_app/src/features/channel/components/direct_message/DirectMessageList.tsx@@ -15,7 +15,7 @@ import {getDmRouteChannelId} from '@app/features/channel/components/direct_messaimport {DMListItem} from '@app/features/channel/components/direct_message/DMListItem';import {CreateDMModal} from '@app/features/channel/components/modals/CreateDMModal';import Channels from '@app/features/channel/state/Channels';-import {getCreateDMRestrictionMessage, getCreateDmRestriction} from '@app/features/channel/utils/CreateDMModalUtils';+import {getCreateDmRestriction} from '@app/features/channel/utils/CreateDMModalUtils';import {PERSONAL_NOTES_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';import {isKeyboardActivationKey} from '@app/features/input/utils/KeyboardUtils';import * as MessageCommands from '@app/features/messaging/commands/MessageCommands';@@ -47,6 +47,7 @@ import MobileLayout from '@app/features/ui/state/MobileLayout';import {Tooltip} from '@app/features/ui/tooltip/Tooltip';import * as UserCommands from '@app/features/user/commands/UserCommands';import Users from '@app/features/user/state/Users';+import {accountGateReason} from '@app/features/user/utils/AccountGatePresentation';import {ME} from '@fluxer/constants/src/AppConstants';import {RelationshipTypes} from '@fluxer/constants/src/UserConstants';import {msg} from '@lingui/core/macro';@@ -144,7 +145,7 @@ export const DMList = observer(() => {const dmPickerAvailable = RuntimeConfig.dmPickerAvailable;const currentUser = Users.currentUser;const createDmRestriction = getCreateDmRestriction(currentUser);- const createDmTooltipText = createDmRestriction ? getCreateDMRestrictionMessage(i18n, createDmRestriction) : null;+ const createDmTooltipText = createDmRestriction ? accountGateReason(i18n, createDmRestriction) : null;const isMobile = MobileLayout.isMobileLayout();const relationships = Relationships.getRelationships();const pendingCount = relationships.filter((relation) => relation.type === RelationshipTypes.INCOMING_REQUEST).length;diff --git a/fluxer_app/src/features/channel/components/pickers/shared/ComputeColumns.ts b/fluxer_app/src/features/channel/components/pickers/shared/ComputeColumns.tsindex 69103f58f..a5255b44b 100644--- a/fluxer_app/src/features/channel/components/pickers/shared/ComputeColumns.ts+++ b/fluxer_app/src/features/channel/components/pickers/shared/ComputeColumns.ts@@ -1,8 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-laterexport interface ComputeColumnsOptions {- targetTileWidth?: number;- maxLanes?: number;minColumns?: number;}@@ -11,10 +9,8 @@ export function computeMasonryColumns(tileSpacing: number,options: ComputeColumnsOptions = {},): number {- const targetTileWidth = options.targetTileWidth ?? 200;- const maxLanes = options.maxLanes ?? 8;const minColumns = options.minColumns ?? 1;if (containerWidth <= 0) return minColumns;- const columns = Math.floor((containerWidth + tileSpacing) / (targetTileWidth + tileSpacing));- return Math.max(minColumns, Math.min(columns, maxLanes));+ const columns = Math.floor((containerWidth + tileSpacing) / (200 + tileSpacing));+ return Math.max(minColumns, Math.min(columns, 8));}diff --git a/fluxer_app/src/features/channel/utils/CreateDMModalUtils.tsx b/fluxer_app/src/features/channel/utils/CreateDMModalUtils.tsxindex 05a5eb2e0..00bd829b9 100644--- a/fluxer_app/src/features/channel/utils/CreateDMModalUtils.tsx+++ b/fluxer_app/src/features/channel/utils/CreateDMModalUtils.tsx@@ -15,7 +15,7 @@ import * as ModalCommands from '@app/features/ui/commands/ModalCommands';import {modal} from '@app/features/ui/commands/ModalCommands';import type {User} from '@app/features/user/models/User';import Users from '@app/features/user/state/Users';-import {AccountGateSlate, accountGateReason} from '@app/features/user/utils/AccountGatePresentation';+import {AccountGateSlate} from '@app/features/user/utils/AccountGatePresentation';import {canPerform} from '@app/features/user/utils/AccountGates';import {blockIfAccountLimited} from '@app/features/user/utils/AccountLimitUtils';import {TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';diff --git a/fluxer_app/src/features/channel/utils/GroupDmUtils.ts b/fluxer_app/src/features/channel/utils/GroupDmUtils.tsindex ee16cfa2b..192ca35fd 100644--- a/fluxer_app/src/features/channel/utils/GroupDmUtils.ts+++ b/fluxer_app/src/features/channel/utils/GroupDmUtils.ts@@ -11,26 +11,22 @@ const canonicalizeRecipientIds = (recipientIds: ReadonlyArray<string>): string =return JSON.stringify(sortedRecipients);};-function getMaxGroupDmRecipients(): number {- return Limits.getMaxGroupDmRecipients();-}-export function getMaxGroupDmOtherRecipients(): number {- return Math.max(getMaxGroupDmRecipients() - 1, 0);+ return Math.max(Limits.getMaxGroupDmRecipients() - 1, 0);}export function getGroupDmRemainingSlots(channel?: Channel): number {if (!channel) {- return getMaxGroupDmRecipients();+ return Limits.getMaxGroupDmRecipients();}- return Math.max(getMaxGroupDmRecipients() - (channel.recipientIds.length + 1), 0);+ return Math.max(Limits.getMaxGroupDmRecipients() - (channel.recipientIds.length + 1), 0);}export function isGroupDmFull(channel?: Channel): boolean {if (!channel) {return false;}- return channel.recipientIds.length + 1 >= getMaxGroupDmRecipients();+ return channel.recipientIds.length + 1 >= Limits.getMaxGroupDmRecipients();}export function getDuplicateGroupDMChannels(diff --git a/fluxer_app/src/features/devtools/components/debug/DebugModal.tsx b/fluxer_app/src/features/devtools/components/debug/DebugModal.tsxindex 4c2873c03..358ef760e 100644--- a/fluxer_app/src/features/devtools/components/debug/DebugModal.tsx+++ b/fluxer_app/src/features/devtools/components/debug/DebugModal.tsx@@ -27,13 +27,12 @@ export interface DebugTab {interface DebugModalProps {title: string;tabs: Array<DebugTab>;- defaultTab?: string;}const logger = new Logger('DebugModal');-export const DebugModal: React.FC<DebugModalProps> = observer(({title, tabs, defaultTab}) => {+export const DebugModal: React.FC<DebugModalProps> = observer(({title, tabs}) => {const {i18n} = useLingui();- const [activeTabId, setActiveTabId] = useState<string>(defaultTab ?? tabs[0]?.id ?? '');+ const [activeTabId, setActiveTabId] = useState<string>(tabs[0]?.id ?? '');const activeTab = useMemo(() => tabs.find((tab) => tab.id === activeTabId) ?? tabs[0], [tabs, activeTabId]);const tabItems = useMemo<Array<TabItem<string>>>(() => tabs.map(({id, label}) => ({key: id, label})), [tabs]);const codeContent = useMemo(() => {diff --git a/fluxer_app/src/features/gateway/transport/GatewayGuildSubscriptionSynchronizer.ts b/fluxer_app/src/features/gateway/transport/GatewayGuildSubscriptionSynchronizer.tsindex d11482657..349c638f3 100644--- a/fluxer_app/src/features/gateway/transport/GatewayGuildSubscriptionSynchronizer.ts+++ b/fluxer_app/src/features/gateway/transport/GatewayGuildSubscriptionSynchronizer.ts@@ -118,11 +118,6 @@ export class GatewayGuildSubscriptionSynchronizer {this.resetSessionTracking();}- prepareAdoptedSession(): void {- this.resetConnectionTracking();- this.initialGuildIdAtIdentify = null;- }-clearInitialGuild(): void {this.initialGuildIdAtIdentify = null;}diff --git a/fluxer_app/src/features/gateway/transport/GatewaySessionPool.ts b/fluxer_app/src/features/gateway/transport/GatewaySessionPool.tsindex 510dc9804..85d8c5b02 100644--- a/fluxer_app/src/features/gateway/transport/GatewaySessionPool.ts+++ b/fluxer_app/src/features/gateway/transport/GatewaySessionPool.ts@@ -6,10 +6,7 @@ import {type ForegroundDemotionOutcome,} from '@app/features/account_engine/state/EngineForegroundHandoff';import Initialization from '@app/features/app/state/Initialization';-import {- captureForegroundMentionCounts,- hydrateStoresFromSnapshotScope,-} from '@app/features/gateway/snapshot/SnapshotHydration';+import {hydrateStoresFromSnapshotScope} from '@app/features/gateway/snapshot/SnapshotHydration';import SnapshotSync from '@app/features/gateway/snapshot/SnapshotSync';import {installDeferredReaction} from '@app/features/gateway/transport/DeferredReaction';import {@@ -26,6 +23,7 @@ import {AccountScopedWorkTransitionReason} from '@app/features/platform/state/Acimport SessionManager from '@app/features/platform/state/AuthSession';import {Logger} from '@app/features/platform/utils/AppLogger';import LocalPresence from '@app/features/presence/state/LocalPresence';+import ReadStates from '@app/features/read_state/state/ReadStates';import {reaction} from 'mobx';const logger = new Logger('GatewaySessionPool');@@ -76,7 +74,7 @@ class GatewaySessionPool {: {userId: account.userId, gatewayEndpoint: account.instance?.gatewayEndpoint ?? null};},isCurrentAccount: (accountKey) => SessionManager.currentAccountKey === accountKey,- captureMentionCounts: () => captureForegroundMentionCounts(),+ captureMentionCounts: () => ReadStates.captureMentionCounts(),hydrate: (accountKey, mentionCounts) => hydrateStoresFromSnapshotScope(accountKey, mentionCounts),whenForegroundLive: (accountKey) => this.whenForegroundLive(accountKey),whenEngineConfigured: () => AccountEngine.whenConfigured(),diff --git a/fluxer_app/src/features/gift/utils/GiftUtils.ts b/fluxer_app/src/features/gift/utils/GiftUtils.tsindex 35e637d20..83c24d2f5 100644--- a/fluxer_app/src/features/gift/utils/GiftUtils.ts+++ b/fluxer_app/src/features/gift/utils/GiftUtils.ts@@ -3,7 +3,7 @@import RuntimeConfig from '@app/features/app/state/RuntimeConfig';import type {Gift, GiftDurationType} from '@app/features/gift/commands/GiftCommands';import {getPremiumProductName} from '@app/features/premium/utils/PremiumUtils';-import type {I18n} from '@lingui/core';+import type {I18n, MessageDescriptor} from '@lingui/core';import {msg} from '@lingui/core/macro';const VISIONARY_LIFETIME_DESCRIPTOR = msg({@@ -76,25 +76,9 @@ function formatGiftDurationText(}}-function getPlutoniumDurationConfig(i18n: I18n): GiftDurationTextConfig {+function getDurationConfig(i18n: I18n, lifetimeDescriptor: MessageDescriptor): GiftDurationTextConfig {return {- lifetime: i18n._(RuntimeConfig.isSelfHosted() ? LIFETIME_DESCRIPTOR : VISIONARY_LIFETIME_DESCRIPTOR, {- premiumProductName: getPremiumProductName(),- }),- days: (durationQuantity: number) =>- i18n._(OTHER_OF_DESCRIPTOR, {durationQuantity, premiumProductName: getPremiumProductName()}),- weeks: (durationQuantity: number) =>- i18n._(OTHER_OF_2_DESCRIPTOR, {durationQuantity, premiumProductName: getPremiumProductName()}),- months: (durationQuantity: number) =>- i18n._(OTHER_OF_3_DESCRIPTOR, {durationQuantity, premiumProductName: getPremiumProductName()}),- years: (durationQuantity: number) =>- i18n._(OTHER_OF_4_DESCRIPTOR, {durationQuantity, premiumProductName: getPremiumProductName()}),- };-}--function getPremiumDurationConfig(i18n: I18n): GiftDurationTextConfig {- return {- lifetime: i18n._(LIFETIME_DESCRIPTOR, {premiumProductName: getPremiumProductName()}),+ lifetime: i18n._(lifetimeDescriptor, {premiumProductName: getPremiumProductName()}),days: (durationQuantity: number) =>i18n._(OTHER_OF_DESCRIPTOR, {durationQuantity, premiumProductName: getPremiumProductName()}),weeks: (durationQuantity: number) =>@@ -108,12 +92,20 @@ function getPremiumDurationConfig(i18n: I18n): GiftDurationTextConfig {export function getGiftDurationText(i18n: I18n, gift: Gift | GiftDurationPayload): string {const duration = resolveGiftDuration(gift);- return formatGiftDurationText(duration.durationType, duration.durationQuantity, getPlutoniumDurationConfig(i18n));+ return formatGiftDurationText(+ duration.durationType,+ duration.durationQuantity,+ getDurationConfig(i18n, RuntimeConfig.isSelfHosted() ? LIFETIME_DESCRIPTOR : VISIONARY_LIFETIME_DESCRIPTOR),+ );}export function getPremiumGiftDurationText(i18n: I18n, gift: Gift | GiftDurationPayload): string {const duration = resolveGiftDuration(gift);- return formatGiftDurationText(duration.durationType, duration.durationQuantity, getPremiumDurationConfig(i18n));+ return formatGiftDurationText(+ duration.durationType,+ duration.durationQuantity,+ getDurationConfig(i18n, LIFETIME_DESCRIPTOR),+ );}export function extractGiftCode(input: string): string {diff --git a/fluxer_app/src/features/input/components/KeybindRecorder.tsx b/fluxer_app/src/features/input/components/KeybindRecorder.tsxindex f21b0c3e2..cdcc123f0 100644--- a/fluxer_app/src/features/input/components/KeybindRecorder.tsx+++ b/fluxer_app/src/features/input/components/KeybindRecorder.tsx@@ -206,12 +206,7 @@ const KeybindEditorPopout: React.FC<KeybindEditorPopoutProps> = ({sawNonModifier = true;commit(combo);};- const handleKeyUp = (event: KeyboardEvent) => {- if (!isKeybindModifierKey(event.key)) return;- if (sawNonModifier) return;- heldModifierCodes.delete(event.code);- if (heldModifierCodes.size > 0) return;- const combo = lastModifierCombo ?? modifierOnlyCombo(event);+ const commitModifierRelease = (combo: KeyCombo) => {if (!combo.key && !combo.code) return;const modifierFlagCount =(combo.shift ? 1 : 0) +@@ -229,6 +224,13 @@ const KeybindEditorPopout: React.FC<KeybindEditorPopoutProps> = ({}commit(combo);};+ const handleKeyUp = (event: KeyboardEvent) => {+ if (!isKeybindModifierKey(event.key)) return;+ if (sawNonModifier) return;+ heldModifierCodes.delete(event.code);+ if (heldModifierCodes.size > 0) return;+ commitModifierRelease(lastModifierCombo ?? modifierOnlyCombo(event));+ };const handleGlobalKey = (type: 'keydown' | 'keyup', baseCombo: KeyCombo) => {if (committed) return;const comboCode = baseCombo.code ?? baseCombo.key;@@ -259,23 +261,7 @@ const KeybindEditorPopout: React.FC<KeybindEditorPopoutProps> = ({if (sawNonModifier) return;heldModifierCodes.delete(comboCode);if (heldModifierCodes.size > 0) return;- const combo = lastModifierCombo ?? {...baseCombo, modifierOnly: true};- if (!combo.key && !combo.code) return;- const modifierFlagCount =- (combo.shift ? 1 : 0) +- (combo.ctrl ? 1 : 0) +- (combo.alt ? 1 : 0) +- (combo.meta ? 1 : 0) +- (combo.ctrlOrMeta ? 1 : 0);- if (modifierFlagCount === 1) {- for (const [leftCode, rightCode] of MODIFIER_BOTH_SIDES_PAIRS) {- if (seenModifierCodes.has(leftCode) && seenModifierCodes.has(rightCode)) {- commit({...combo, code: leftCode, bothSides: true});- return;- }- }- }- commit(combo);+ commitModifierRelease(lastModifierCombo ?? {...baseCombo, modifierOnly: true});};const handleGlobalKeyEvent = (event: GlobalKeyEvent) => {const baseCombo = globalKeyEventToCombo(event);diff --git a/fluxer_app/src/features/lexical/composer/ComposerClipboard.ts b/fluxer_app/src/features/lexical/composer/ComposerClipboard.tsindex 49d711a90..fae125432 100644--- a/fluxer_app/src/features/lexical/composer/ComposerClipboard.ts+++ b/fluxer_app/src/features/lexical/composer/ComposerClipboard.ts@@ -17,7 +17,10 @@ import {$selectComposerOffset,} from '@app/features/lexical/composer/composerOffsets';import {$isSlashSlotNode, type SlashSlotNode} from '@app/features/lexical/composer/nodes/SlashSlotNode';-import {COMPOSER_SLASH_SLOT_STATE_MAX_ID_LENGTH} from '@app/features/lexical/composer/SlashSlotPersistence';+import {+ COMPOSER_SLASH_SLOT_STATE_MAX_ID_LENGTH,+ hasExactKeys,+} from '@app/features/lexical/composer/SlashSlotPersistence';import {ParserFlags} from '@app/features/messaging/utils/markdown/parser/Enums';import type {MentionSegment} from '@app/features/messaging/utils/TextareaSegmentManager';import {randomUuid} from '@app/features/platform/utils/RandomUuid';@@ -27,6 +30,7 @@ import {$addUpdateTag,$createLineBreakNode,$createTextNode,+ $findMatchingParent,$getRoot,$getSelection,$isElementNode,@@ -86,11 +90,6 @@ interface SerializedComposerClipboardPayload {segments: Array<MentionSegment>;}-function hasExactKeys<const T extends ReadonlyArray<string>>(value: Record<string, unknown>, keys: T): boolean {- const actualKeys = Object.keys(value);- return actualKeys.length === keys.length && keys.every((key) => Object.hasOwn(value, key));-}-function isBoundedString(value: unknown, minimumLength: number, maximumLength: number): value is string {return typeof value === 'string' && value.length >= minimumLength && value.length <= maximumLength;}@@ -331,17 +330,6 @@ function $createSliceNodes(slice: ComposerClipboardSlice, plainText: boolean): Areturn nodes;}-function $findEnclosingSlashSlot(node: LexicalNode): SlashSlotNode | null {- let current: LexicalNode | null = node;- while (current != null) {- if ($isSlashSlotNode(current)) {- return current;- }- current = current.getParent();- }- return null;-}-function $selectSlashSlotOffset(slot: SlashSlotNode, offset: number): void {let consumed = 0;const children = slot.getChildren();@@ -411,7 +399,7 @@ export function $insertComposerClipboardSlice(return false;}const selectedNode = selectedNodes[0]!;- const slot = $findEnclosingSlashSlot(selectedNode);+ const slot = $findMatchingParent(selectedNode, $isSlashSlotNode);if (slot != null) {const selectedRange = $getNodeDisplayRange(selectedNode);return (@@ -431,8 +419,8 @@ export function $insertComposerClipboardSlice(}const start = Math.min(offsets.anchor, offsets.focus);const end = Math.max(offsets.anchor, offsets.focus);- const anchorSlot = $findEnclosingSlashSlot(selection.anchor.getNode());- const focusSlot = $findEnclosingSlashSlot(selection.focus.getNode());+ const anchorSlot = $findMatchingParent(selection.anchor.getNode(), $isSlashSlotNode);+ const focusSlot = $findMatchingParent(selection.focus.getNode(), $isSlashSlotNode);if (anchorSlot != null && focusSlot != null && anchorSlot.is(focusSlot)) {return $replaceSlashSlotRange(anchorSlot, start, end, sliceToWire(validated));}diff --git a/fluxer_app/src/features/lexical/composer/ComposerTypeaheadModifierGuard.ts b/fluxer_app/src/features/lexical/composer/ComposerTypeaheadModifierGuard.tsindex 483f3dffd..e95b29ad7 100644--- a/fluxer_app/src/features/lexical/composer/ComposerTypeaheadModifierGuard.ts+++ b/fluxer_app/src/features/lexical/composer/ComposerTypeaheadModifierGuard.ts@@ -14,7 +14,7 @@ export interface ComposerTypeaheadActiveState {readonly current: boolean;}-function hasModifier(event: KeyboardEvent | null): boolean {+export function hasModifier(event: KeyboardEvent | null): boolean {return event != null && (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);}diff --git a/fluxer_app/src/features/lexical/composer/SlashSlotAutocompletePlugin.tsx b/fluxer_app/src/features/lexical/composer/SlashSlotAutocompletePlugin.tsxindex 0c3ca9c57..7b2a4afc6 100644--- a/fluxer_app/src/features/lexical/composer/SlashSlotAutocompletePlugin.tsx+++ b/fluxer_app/src/features/lexical/composer/SlashSlotAutocompletePlugin.tsx@@ -1,11 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {Autocomplete} from '@app/features/channel/components/Autocomplete';-import {- type AutocompleteOption,- type AutocompleteType,- getAutocompleteOptionId,-} from '@app/features/channel/components/AutocompleteTypes';+import {getAutocompleteOptionId} from '@app/features/channel/components/AutocompleteTypes';+import {hasModifier} from '@app/features/lexical/composer/ComposerTypeaheadModifierGuard';+import type {ComposerTypeaheadPluginProps} from '@app/features/lexical/composer/ComposerTypeaheadPlugin';import {isIMEComposing} from '@app/features/messaging/utils/IMECompositionUtils';import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';import {mergeRegister} from '@lexical/utils';@@ -16,26 +14,10 @@ import {KEY_ENTER_COMMAND,KEY_TAB_COMMAND,} from 'lexical';-import type React from 'react';import {useEffect, useLayoutEffect, useRef, useState} from 'react';const SLASH_SLOT_AUTOCOMPLETE_MAIN_AXIS_OFFSET = 8;-function hasModifier(event: KeyboardEvent | null): boolean {- return event != null && (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);-}--export interface SlashSlotAutocompletePluginProps {- options: Array<AutocompleteOption>;- type: AutocompleteType;- query: string;- referenceElement: HTMLElement | null;- listboxId: string;- enabled: boolean;- onSelect: (option: AutocompleteOption) => void;- activeRef: React.RefObject<boolean>;-}-export const SlashSlotAutocompletePlugin = ({options,type,@@ -45,7 +27,7 @@ export const SlashSlotAutocompletePlugin = ({enabled,onSelect,activeRef,-}: SlashSlotAutocompletePluginProps) => {+}: ComposerTypeaheadPluginProps) => {const [editor] = useLexicalComposerContext();const [selectedIndex, setSelectedIndex] = useState(0);const visible = enabled && options.length > 0;diff --git a/fluxer_app/src/features/lexical/composer/SlashSlotPersistence.ts b/fluxer_app/src/features/lexical/composer/SlashSlotPersistence.tsindex 533bd963e..6074d22a3 100644--- a/fluxer_app/src/features/lexical/composer/SlashSlotPersistence.ts+++ b/fluxer_app/src/features/lexical/composer/SlashSlotPersistence.ts@@ -77,7 +77,7 @@ const CHANNEL_WIRE_RE = /^<#\d+>$/;const INTEGER_RE = /^-?\d+$/;const NUMBER_RE = /^-?\d+(\.\d+)?$/;-function hasExactKeys(value: Record<string, unknown>, keys: ReadonlyArray<string>): boolean {+export function hasExactKeys(value: Record<string, unknown>, keys: ReadonlyArray<string>): boolean {const actualKeys = Object.keys(value);return actualKeys.length === keys.length && keys.every((key) => Object.hasOwn(value, key));}diff --git a/fluxer_app/src/features/lexical/composer/codeBlockIndent.ts b/fluxer_app/src/features/lexical/composer/codeBlockIndent.tsindex 386e61d47..ad8ebcd7d 100644--- a/fluxer_app/src/features/lexical/composer/codeBlockIndent.ts+++ b/fluxer_app/src/features/lexical/composer/codeBlockIndent.ts@@ -79,7 +79,7 @@ export function hasVisibleContent(text: string): boolean {return text.replace(INVISIBLE_RE, '') !== '';}-function hasOpenInlineCode(text: string): boolean {+export function hasOpenInlineCode(text: string): boolean {let open = 0;for (const [run] of text.matchAll(/`+/g)) {if (open === 0) {diff --git a/fluxer_app/src/features/lexical/composer/composerOffsets.ts b/fluxer_app/src/features/lexical/composer/composerOffsets.tsindex 29fca8d55..12f42a10c 100644--- a/fluxer_app/src/features/lexical/composer/composerOffsets.ts+++ b/fluxer_app/src/features/lexical/composer/composerOffsets.ts@@ -47,7 +47,7 @@ export type ComposerInsertPayload =| {kind: 'customEmoji'; emojiId: string; animated: boolean; display: string; wire: string}| {kind: 'standardEmoji'; name: string; surrogate: string; url: string | null; display: string};-function $firstParagraph(): ElementNode {+export function $firstParagraph(): ElementNode {const root = $getRoot();const first = root.getFirstChild();if (first != null && first.getType() === 'paragraph') {diff --git a/fluxer_app/src/features/lexical/composer/slashSlots.ts b/fluxer_app/src/features/lexical/composer/slashSlots.tsindex 9cc6cd35f..fbd3c9d65 100644--- a/fluxer_app/src/features/lexical/composer/slashSlots.ts+++ b/fluxer_app/src/features/lexical/composer/slashSlots.ts@@ -45,6 +45,7 @@ import {mergeRegister} from '@lexical/utils';import {$createParagraphNode,$createTextNode,+ $findMatchingParent,$getAdjacentNode,$getNodeByKey,$getRoot,@@ -134,7 +135,7 @@ function $isPointAtSlotBoundary(slot: SlashSlotNode, point: PointType, boundary:if (point.type === 'element') {return node.is(slot) && point.offset === (boundary === 'start' ? 0 : slot.getChildrenSize());}- const enclosing = $enclosingSlot(node);+ const enclosing = $findMatchingParent(node, $isSlashSlotNode);if (enclosing == null || !enclosing.is(slot)) {return false;}@@ -153,7 +154,7 @@ function $advanceToNextSlot(includeOptionalAnchor: boolean): boolean {if (slots.length === 0) {return false;}- const currentSlot = $enclosingSlot(selection.anchor.getNode());+ const currentSlot = $findMatchingParent(selection.anchor.getNode(), $isSlashSlotNode);if (currentSlot == null) {return false;}@@ -179,7 +180,7 @@ function $focusPreviousSlot(): boolean {if (slots.length === 0) {return false;}- const currentSlot = $enclosingSlot(selection.anchor.getNode());+ const currentSlot = $findMatchingParent(selection.anchor.getNode(), $isSlashSlotNode);if (currentSlot != null) {const currentIndex = slots.findIndex((slot) => slot.is(currentSlot));const previousSlot = slots[currentIndex - 1];@@ -319,7 +320,7 @@ function $findTypeTargetSlot(): SlashSlotNode | null {return null;}const {anchor} = selection;- const enclosing = $enclosingSlot(anchor.getNode());+ const enclosing = $findMatchingParent(anchor.getNode(), $isSlashSlotNode);if (enclosing != null) {return enclosing.getTextContentSize() === 0 ? enclosing : null;}@@ -432,8 +433,8 @@ function $handleSlashStructuralDelete(event: KeyboardEvent, isBackward: boolean)return false;}if (!selection.isCollapsed()) {- const anchorSlot = $enclosingSlot(selection.anchor.getNode());- const focusSlot = $enclosingSlot(selection.focus.getNode());+ const anchorSlot = $findMatchingParent(selection.anchor.getNode(), $isSlashSlotNode);+ const focusSlot = $findMatchingParent(selection.focus.getNode(), $isSlashSlotNode);if (anchorSlot != null) {if (anchorSlot.is(focusSlot)) {return false;@@ -460,7 +461,7 @@ function $handleSlashStructuralDelete(event: KeyboardEvent, isBackward: boolean)return true;}const anchorNode = selection.anchor.getNode();- const slot = $enclosingSlot(anchorNode);+ const slot = $findMatchingParent(anchorNode, $isSlashSlotNode);if (slot != null) {const hasValue = slot.getTextContentSize() > 0;const boundary = isBackward ? 'start' : 'end';@@ -527,6 +528,21 @@ function $handleSlashStructuralDelete(event: KeyboardEvent, isBackward: boolean)return false;}+function $collapsedSlotAtBoundary(event: KeyboardEvent | null, boundary: 'start' | 'end'): SlashSlotNode | null {+ if (event != null && (isIMEComposing(event) || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey)) {+ return null;+ }+ const selection = $getSelection();+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {+ return null;+ }+ const slot = $findMatchingParent(selection.anchor.getNode(), $isSlashSlotNode);+ if (slot == null || !$isPointAtSlotBoundary(slot, selection.anchor, boundary)) {+ return null;+ }+ return slot;+}+export function registerSlashSlotPlugin(editor: LexicalEditor,getResolvers: () => SlashSlotResolvers,@@ -613,21 +629,7 @@ export function registerSlashSlotPlugin(editor.registerCommand(KEY_ARROW_RIGHT_COMMAND,(event: KeyboardEvent) => {- if (- event != null &&- (isIMEComposing(event) || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey)- ) {- return false;- }- const selection = $getSelection();- if (!$isRangeSelection(selection) || !selection.isCollapsed()) {- return false;- }- const slot = $enclosingSlot(selection.anchor.getNode());- if (slot == null) {- return false;- }- if (!$isPointAtSlotBoundary(slot, selection.anchor, 'end')) {+ if ($collapsedSlotAtBoundary(event, 'end') == null) {return false;}if ($focusNextSlot()) {@@ -643,21 +645,7 @@ export function registerSlashSlotPlugin(editor.registerCommand(KEY_ARROW_LEFT_COMMAND,(event: KeyboardEvent) => {- if (- event != null &&- (isIMEComposing(event) || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey)- ) {- return false;- }- const selection = $getSelection();- if (!$isRangeSelection(selection) || !selection.isCollapsed()) {- return false;- }- const slot = $enclosingSlot(selection.anchor.getNode());- if (slot == null) {- return false;- }- if (!$isPointAtSlotBoundary(slot, selection.anchor, 'start')) {+ if ($collapsedSlotAtBoundary(event, 'start') == null) {return false;}if (event != null) {@@ -695,8 +683,8 @@ export function registerSlashSlotPlugin(if (paragraph == null) {return false;}- const anchorSlot = $enclosingSlot(selection.anchor.getNode());- const focusSlot = $enclosingSlot(selection.focus.getNode());+ const anchorSlot = $findMatchingParent(selection.anchor.getNode(), $isSlashSlotNode);+ const focusSlot = $findMatchingParent(selection.focus.getNode(), $isSlashSlotNode);if (anchorSlot != null) {if (anchorSlot.is(focusSlot)) {return false;@@ -741,7 +729,7 @@ export function registerSlashSlotPlugin(if (paragraph == null) {return;}- if ($enclosingSlot(anchorNode) != null) {+ if ($findMatchingParent(anchorNode, $isSlashSlotNode) != null) {return;}if ($activeOptionalHint() != null) {@@ -763,7 +751,11 @@ export function registerSlashSlotPlugin(}const anchorNode = selection.anchor.getNode();const paragraph = $slashCommandParagraph(anchorNode);- if (paragraph == null || $enclosingSlot(anchorNode) != null || $activeOptionalHint() != null) {+ if (+ paragraph == null ||+ $findMatchingParent(anchorNode, $isSlashSlotNode) != null ||+ $activeOptionalHint() != null+ ) {return;}const node = $nearestSlotForCaret(paragraph);@@ -799,7 +791,7 @@ function $getActiveSlot(): SlashSlotNode | null {if (!$isRangeSelection(selection)) {return null;}- const enclosing = $enclosingSlot(selection.anchor.getNode());+ const enclosing = $findMatchingParent(selection.anchor.getNode(), $isSlashSlotNode);if (enclosing != null) {return enclosing;}diff --git a/fluxer_app/src/features/lexical/composer/specialMentions.ts b/fluxer_app/src/features/lexical/composer/specialMentions.tsindex 16cf7cec1..3a29e8c6c 100644--- a/fluxer_app/src/features/lexical/composer/specialMentions.ts+++ b/fluxer_app/src/features/lexical/composer/specialMentions.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {Channel} from '@app/features/channel/models/Channel';+import {hasOpenInlineCode} from '@app/features/lexical/composer/codeBlockIndent';import type {ComposerInsertPayload} from '@app/features/lexical/composer/composerOffsets';import {isAutocompleteTriggerAllowed, type TriggerType} from '@app/features/messaging/utils/AutocompleteTriggerPolicy';import {findUrlSpans, isInsideSpan, type TextSpan} from '@app/features/messaging/utils/markdown/UrlSpanUtils';@@ -42,18 +43,6 @@ export function hasOpenCodeFence(text: string): boolean {return fences != null && fences.length % 2 === 1;}-function hasOpenInlineCode(text: string, index: number): boolean {- let openRun = 0;- for (const run of text.slice(text.lastIndexOf('\n', index - 1) + 1, index).matchAll(/`+/g)) {- if (openRun === 0) {- openRun = run[0].length;- } else if (run[0].length === openRun) {- openRun = 0;- }- }- return openRun > 0;-}-export function findTypedSpecialMention(text: string,from: number,@@ -74,7 +63,7 @@ export function findTypedSpecialMention(!WORD_CHARACTER.test(previous) &&!WORD_CHARACTER.test(text.charAt(end)) &&!hasOpenCodeFence(text.slice(0, start)) &&- !hasOpenInlineCode(text, start)+ !hasOpenInlineCode(text.slice(text.lastIndexOf('\n', start - 1) + 1, start))) {if (urlSpans === null) {urlSpans = findUrlSpans(text);diff --git a/fluxer_app/src/features/lexical/search/SearchEditorModel.ts b/fluxer_app/src/features/lexical/search/SearchEditorModel.tsindex fd1310335..073387fea 100644--- a/fluxer_app/src/features/lexical/search/SearchEditorModel.ts+++ b/fluxer_app/src/features/lexical/search/SearchEditorModel.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {$firstParagraph} from '@app/features/lexical/composer/composerOffsets';import {$createSearchTokenNode, $isSearchTokenNode} from '@app/features/lexical/search/SearchTokenNode';import {resolveSearchChipDeletion, type SearchChipRole, tokenize} from '@app/features/search/utils/SearchQueryParser';import {@@ -43,18 +44,6 @@ interface SearchSegment {readonly exclude: boolean;}-function $ensureRootParagraph(): ElementNode {- const root = $getRoot();- const first = root.getFirstChild();- if (first != null && first.getType() === 'paragraph') {- return first as ElementNode;- }- const paragraph = $createParagraphNode();- root.clear();- root.append(paragraph);- return paragraph;-}-function resolveSearchSelectionDirection(anchor: number, focus: number): SearchSelectionDirection {if (anchor === focus) {return SearchSelectionDirection.NONE;@@ -305,7 +294,7 @@ export function $getSelectionRange(): SearchSelectionRange | null {if (!$isRangeSelection(selection)) {return null;}- const paragraph = $ensureRootParagraph();+ const paragraph = $firstParagraph();const anchor = $getPointOffset(selection.anchor, paragraph);const focus = $getPointOffset(selection.focus, paragraph);if (anchor == null || focus == null) {@@ -345,7 +334,7 @@ function $selectRange(end: number,direction: SearchSelectionDirection = SearchSelectionDirection.NONE,): void {- const paragraph = $ensureRootParagraph();+ const paragraph = $firstParagraph();const queryLength = paragraph.getTextContent().length;const clampedEnd = Math.min(Math.max(0, end), queryLength);let clampedStart: number;diff --git a/fluxer_app/src/features/member/state/MemberSearch.ts b/fluxer_app/src/features/member/state/MemberSearch.tsindex fc8c9fa74..c9cb2825a 100644--- a/fluxer_app/src/features/member/state/MemberSearch.ts+++ b/fluxer_app/src/features/member/state/MemberSearch.ts@@ -352,13 +352,7 @@ class MemberSearch {}handleMemberUpdate(guildId: string, memberId: string): void {- if (!worker) return;- const member = GuildMembers.getMember(guildId, memberId);- if (!member) return;- const transformedMember = getTransformedMember(member, guildId);- if (transformedMember) {- updateMembers([transformedMember]);- }+ this.handleMemberAdd(guildId, memberId);}handleMemberRemove(guildId: string, memberId: string): void {diff --git a/fluxer_app/src/features/member/state/MemberSidebar.ts b/fluxer_app/src/features/member/state/MemberSidebar.tsindex e94d231cb..cf66606bf 100644--- a/fluxer_app/src/features/member/state/MemberSidebar.ts+++ b/fluxer_app/src/features/member/state/MemberSidebar.ts@@ -324,26 +324,7 @@ class MemberSidebar {}handleGuildCreate(guildId: string): void {- this.clearPendingListUpdateBatches(guildId);- if (this.lists[guildId]) {- const {[guildId]: _, ...remainingLists} = this.lists;- this.lists = remainingLists;- }- if (this.wireListChannelIds[guildId]) {- const {[guildId]: _, ...remainingWireMappings} = this.wireListChannelIds;- this.wireListChannelIds = remainingWireMappings;- }- if (this.listSubscribedChannelIds[guildId]) {- const {[guildId]: _, ...remainingSubscribedChannels} = this.listSubscribedChannelIds;- this.listSubscribedChannelIds = remainingSubscribedChannels;- }- this.syncedMemberListGuildIds.delete(guildId);- if (this.sentMemberListGuildId === guildId) {- this.clearSentMemberListSubscription();- }- if (this.activeMemberListSubscription?.guildId === guildId) {- this.setActiveMemberListSubscription(null);- }+ this.handleGuildDelete(guildId);}handleGuildStorageIdentityChange(guildId: string): void {diff --git a/fluxer_app/src/features/messaging/commands/MessageFetchStateMachine.ts b/fluxer_app/src/features/messaging/commands/MessageFetchStateMachine.tsindex cf0ff608f..3ce2a1d2f 100644--- a/fluxer_app/src/features/messaging/commands/MessageFetchStateMachine.ts+++ b/fluxer_app/src/features/messaging/commands/MessageFetchStateMachine.ts@@ -70,7 +70,7 @@ export function resolveMessageFetchPreflightDecision(input: MessageFetchPrefligh}export function resolveMessageFetchExecutionDecision(input: MessageFetchExecutionInput): MessageFetchExecutionDecision {- return buildExecutionDecision(input);+ return input.forceFailure ? {type: 'simulateFailure'} : {type: 'requestNetwork'};}export interface MessageFetchWindowTrustInput {diff --git a/fluxer_app/src/features/messaging/commands/ReactionCommands.tsx b/fluxer_app/src/features/messaging/commands/ReactionCommands.tsxindex d8b2bfcd0..2bf65332d 100644--- a/fluxer_app/src/features/messaging/commands/ReactionCommands.tsx+++ b/fluxer_app/src/features/messaging/commands/ReactionCommands.tsx@@ -200,20 +200,17 @@ function applyReactionFetchResult(nextAfter?: string | null,): void {const {limit, after, totalCount} = options;- if (after !== undefined) {- MessageReactions.handleFetchAppend(- messageId,- data,- emoji,- limit,- responseHasMore,- totalCount,- requestId,- nextAfter,- );- return;- }- MessageReactions.handleFetchSuccess(messageId, data, emoji, limit, responseHasMore, totalCount, requestId, nextAfter);+ MessageReactions.handleFetchSuccess(+ after !== undefined ? 'append' : 'replace',+ messageId,+ data,+ emoji,+ limit,+ responseHasMore,+ totalCount,+ requestId,+ nextAfter,+ );}function addReactionRequest(channelId: string, messageId: string, emoji: ReactionEmoji): Promise<unknown> {diff --git a/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsx b/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsxindex 1b64f4427..89a7bf85c 100644--- a/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsx+++ b/fluxer_app/src/features/messaging/components/markdown/renderers/LinkRenderer.tsx@@ -208,6 +208,23 @@ function useJumpLinkAuxClick(url: string, interactive: boolean) {);}+function useLinkContextMenu(Menu: React.FC<LinkContextMenuProps>, url: string, interactive: boolean, i18n: I18n) {+ return useCallback(+ (event: React.MouseEvent<HTMLButtonElement | HTMLSpanElement>) => {+ if (!interactive) return;+ ContextMenuCommands.openFromEvent(event, ({onClose}) => (+ <Menu+ url={url}+ i18n={i18n}+ onClose={onClose}+ data-flx="messaging.markdown.renderers.link-renderer.use-link-context-menu.menu"+ />+ ));+ },+ [Menu, interactive, i18n, url],+ );+}+type CompactGuildMentionIconStyle = React.CSSProperties & {'--jump-link-guild-icon-image'?: string;};@@ -246,13 +263,13 @@ interface JumpLinkMentionProps {interactive?: boolean;}-interface JumpLinkContextMenuProps {+interface LinkContextMenuProps {url: string;i18n: I18n;onClose: () => void;}-function JumpLinkContextMenu({url, i18n, onClose}: JumpLinkContextMenuProps) {+function JumpLinkContextMenu({url, i18n, onClose}: LinkContextMenuProps) {const handleOpenLink = useCallback(() => {void openExternalUrl(url);onClose();@@ -325,20 +342,7 @@ const JumpLinkMention = observer(function JumpLinkMention({[channel, guild?.id, interactive, navigateToJumpTarget],);const handleAuxClick = useJumpLinkAuxClick(url, interactive);- const handleContextMenu = useCallback(- (event: React.MouseEvent<HTMLButtonElement | HTMLSpanElement>) => {- if (!interactive) return;- ContextMenuCommands.openFromEvent(event, ({onClose}) => (- <JumpLinkContextMenu- url={url}- i18n={i18n}- onClose={onClose}- data-flx="messaging.markdown.renderers.link-renderer.handle-context-menu.jump-link-context-menu"- />- ));- },- [interactive, i18n, url],- );+ const handleContextMenu = useLinkContextMenu(JumpLinkContextMenu, url, interactive, i18n);const displayName = channel.isPrivate() ? getDMDisplayName(channel) : (channel.name ?? channel.id);const labelText = guild ? guild.name : displayName;const shouldShowChannelInfo = !messageId && Boolean(channel.guildId);@@ -475,20 +479,7 @@ function InaccessibleJumpLinkMention({url, i18n, interactive = true}: Inaccessib[i18n, interactive],);const handleAuxClick = useJumpLinkAuxClick(url, interactive);- const handleContextMenu = useCallback(- (event: React.MouseEvent<HTMLButtonElement | HTMLSpanElement>) => {- if (!interactive) return;- ContextMenuCommands.openFromEvent(event, ({onClose}) => (- <JumpLinkContextMenu- url={url}- i18n={i18n}- onClose={onClose}- data-flx="messaging.markdown.renderers.link-renderer.handle-context-menu.jump-link-context-menu--2"- />- ));- },- [interactive, i18n, url],- );+ const handleContextMenu = useLinkContextMenu(JumpLinkContextMenu, url, interactive, i18n);const noAccessText = i18n._(NO_ACCESS_DESCRIPTOR);const Component = interactive ? 'button' : 'span';return (@@ -552,20 +543,7 @@ const DiscoverableJumpLinkMention = observer(function DiscoverableJumpLinkMentio[channelId, guildId, interactive, joining, messageId],);const handleAuxClick = useJumpLinkAuxClick(url, interactive);- const handleContextMenu = useCallback(- (event: React.MouseEvent<HTMLButtonElement | HTMLSpanElement>) => {- if (!interactive) return;- ContextMenuCommands.openFromEvent(event, ({onClose}) => (- <JumpLinkContextMenu- url={url}- i18n={i18n}- onClose={onClose}- data-flx="messaging.markdown.renderers.link-renderer.discoverable-jump-link-mention.context-menu"- />- ));- },- [interactive, i18n, url],- );+ const handleContextMenu = useLinkContextMenu(JumpLinkContextMenu, url, interactive, i18n);const entry = DiscoveryChannelPreviews.get(guildId, channelId);if (entry?.status !== 'ready') {return (@@ -653,13 +631,7 @@ interface SettingsJumpLinkMentionProps {interactive?: boolean;}-interface SettingsLinkContextMenuProps {- url: string;- i18n: I18n;- onClose: () => void;-}--function SettingsLinkContextMenu({url, i18n, onClose}: SettingsLinkContextMenuProps) {+function SettingsLinkContextMenu({url, i18n, onClose}: LinkContextMenuProps) {const handleCopyLink = useCallback(async () => {await TextCopyCommands.copy(i18n, url);onClose();@@ -693,20 +665,7 @@ function SettingsJumpLinkMention({target, url, i18n, interactive = true}: Settin[interactive, url],);const handleAuxClick = useJumpLinkAuxClick(url, interactive);- const handleContextMenu = useCallback(- (event: React.MouseEvent<HTMLButtonElement | HTMLSpanElement>) => {- if (!interactive) return;- ContextMenuCommands.openFromEvent(event, ({onClose}) => (- <SettingsLinkContextMenu- url={url}- i18n={i18n}- onClose={onClose}- data-flx="messaging.markdown.renderers.link-renderer.handle-context-menu.settings-link-context-menu"- />- ));- },- [interactive, i18n, url],- );+ const handleContextMenu = useLinkContextMenu(SettingsLinkContextMenu, url, interactive, i18n);const tabLabel = getUserSettingsTabLabel(i18n, target.tab);const sectionLabel = target.section ? getUserSettingsSectionLabel(i18n, target.section, target.tab) : '';const tabIcon = getUserSettingsTabIconDescriptor(target.tab);@@ -787,20 +746,7 @@ function AppPageJumpLinkMention({page, url, i18n, interactive = true}: AppPageJu[interactive, page],);const handleAuxClick = useJumpLinkAuxClick(url, interactive);- const handleContextMenu = useCallback(- (event: React.MouseEvent<HTMLButtonElement | HTMLSpanElement>) => {- if (!interactive) return;- ContextMenuCommands.openFromEvent(event, ({onClose}) => (- <SettingsLinkContextMenu- url={url}- i18n={i18n}- onClose={onClose}- data-flx="messaging.markdown.renderers.link-renderer.app-page-jump-link-mention.context-menu"- />- ));- },- [interactive, i18n, url],- );+ const handleContextMenu = useLinkContextMenu(SettingsLinkContextMenu, url, interactive, i18n);const label = getAppPageLabel(i18n, page);const PageIcon = getAppPageIcon(page);const Component = interactive ? 'button' : 'span';diff --git a/fluxer_app/src/features/messaging/components/modals/MediaModal.tsx b/fluxer_app/src/features/messaging/components/modals/MediaModal.tsxindex 9f7fcb8e5..bc755dc6f 100644--- a/fluxer_app/src/features/messaging/components/modals/MediaModal.tsx+++ b/fluxer_app/src/features/messaging/components/modals/MediaModal.tsx@@ -438,10 +438,33 @@ export const MediaModal: FC<MediaModalProps> = observer(children: wrappedChildren,});}+ const actionProps = {+ isFavorited,+ onFavorite,+ onDownload,+ onOpenInBrowser,+ onCopyLink,+ onCopyMedia,+ onReset: handleResetMedia,+ onZoomIn: handleZoomIn,+ onZoomOut: handleZoomOut,+ onRotateCW: handleRotateCW,+ onRotateCCW: handleRotateCCW,+ onReply,+ onForward,+ onClose: handleClose,+ canReset: !panZoomInfo.isDefault || hasCustomRotation,+ canZoomIn: panZoomInfo.canZoomIn,+ canZoomOut: panZoomInfo.canZoomOut,+ enableZoomControls: enablePanZoom,+ onPointerEnter: handleHudPointerEnter,+ onPointerLeave: handleHudPointerLeave,+ };let mediaActions: ReactNode = null;if (isMobile && !isMobileVideo) {mediaActions = (<MobileMediaActions+ {...actionProps}rootRef={topActionBarRef}data-flx="messaging.media-modal.mobile-media-actions"/>@@ -449,6 +472,7 @@ export const MediaModal: FC<MediaModalProps> = observer(} else if (!isMobile) {mediaActions = (<MediaOverlayActions+ {...actionProps}rootRef={bottomActionBarRef}onDeleteAttachment={onDeleteAttachment}data-flx="messaging.media-modal.media-overlay-actions"diff --git a/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsx b/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsxindex cb103ff6a..06e4f47ef 100644--- a/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsx+++ b/fluxer_app/src/features/messaging/components/modals/MediaViewerModal.tsx@@ -399,56 +399,46 @@ const MediaViewerModalComponent: FC = observer(() => {},[currentIndex],);- const handleContextMenu = useCallback(- (event: MouseEvent<HTMLDivElement>) => {- if (!currentItem || !message) return;- const renderMenu = ({onClose}: {onClose: () => void}) => (+ const renderMediaMenu = useCallback(+ (item: MediaViewerItem, menuMessage: Message) =>+ ({onClose}: {onClose: () => void}) => (<MediaContextMenu- message={message}+ message={menuMessage}sourceChannel={sourceChannel}- originalSrc={currentItem.originalSrc}- proxyURL={currentItem.src}- type={currentItem.type}- contentHash={currentItem.contentHash}- attachmentId={currentItem.attachmentId}- embedIndex={currentItem.embedIndex}+ originalSrc={item.originalSrc}+ proxyURL={item.src}+ type={item.type}+ contentHash={item.contentHash}+ attachmentId={item.attachmentId}+ embedIndex={item.embedIndex}defaultName={defaultName}- naturalWidth={currentItem.naturalWidth}- naturalHeight={currentItem.naturalHeight}+ naturalWidth={item.naturalWidth}+ naturalHeight={item.naturalHeight}onClose={onClose}onDelete={handleDelete}- data-flx="messaging.media-viewer-modal.render-menu.media-context-menu"+ data-flx="messaging.media-viewer-modal.render-media-menu.media-context-menu"/>- );- ContextMenuCommands.openFromEvent(event, renderMenu);+ ),+ [defaultName, handleDelete, sourceChannel],+ );+ const handleContextMenu = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ if (!currentItem || !message) return;+ ContextMenuCommands.openFromEvent(event, renderMediaMenu(currentItem, message));},- [currentItem, defaultName, handleDelete, message, sourceChannel],+ [currentItem, message, renderMediaMenu],);const handleMenuOpen = useCallback(() => {if (!currentItem || !message) return;if (isMobile) {setIsMediaMenuOpen(true);} else {- ContextMenuCommands.openAtPoint({x: window.innerWidth / 2, y: window.innerHeight / 2}, ({onClose}) => (- <MediaContextMenu- message={message}- sourceChannel={sourceChannel}- originalSrc={currentItem.originalSrc}- proxyURL={currentItem.src}- type={currentItem.type}- contentHash={currentItem.contentHash}- attachmentId={currentItem.attachmentId}- embedIndex={currentItem.embedIndex}- defaultName={defaultName}- naturalWidth={currentItem.naturalWidth}- naturalHeight={currentItem.naturalHeight}- onClose={onClose}- onDelete={handleDelete}- data-flx="messaging.media-viewer-modal.handle-menu-open.media-context-menu"- />- ));+ ContextMenuCommands.openAtPoint(+ {x: window.innerWidth / 2, y: window.innerHeight / 2},+ renderMediaMenu(currentItem, message),+ );}- }, [currentItem, defaultName, handleDelete, message, sourceChannel, isMobile]);+ }, [currentItem, message, renderMediaMenu, isMobile]);const permissions = useMemo(() => (message ? untracked(() => getMessagePermissions(message, sourceChannel)) : null),[message, sourceChannel],diff --git a/fluxer_app/src/features/messaging/components/modals/media_modal/MediaControls.tsx b/fluxer_app/src/features/messaging/components/modals/media_modal/MediaControls.tsxindex 450c0808a..0b5f3c745 100644--- a/fluxer_app/src/features/messaging/components/modals/media_modal/MediaControls.tsx+++ b/fluxer_app/src/features/messaging/components/modals/media_modal/MediaControls.tsx@@ -113,7 +113,7 @@ const OverlayTooltipButton: FC<OverlayTooltipButtonProps> = ({</Tooltip>);-interface MediaOverlayActionsProps {+export interface MediaOverlayActionsProps {isFavorited?: boolean;onFavorite?: () => void;onDownload?: () => void;diff --git a/fluxer_app/src/features/messaging/components/modals/media_modal/MobileMediaActions.tsx b/fluxer_app/src/features/messaging/components/modals/media_modal/MobileMediaActions.tsxindex 42b7f572a..5e0d245ee 100644--- a/fluxer_app/src/features/messaging/components/modals/media_modal/MobileMediaActions.tsx+++ b/fluxer_app/src/features/messaging/components/modals/media_modal/MobileMediaActions.tsx@@ -9,7 +9,10 @@ import {ZOOM_OUT_DESCRIPTOR,} from '@app/features/i18n/utils/CommonMessageDescriptors';import styles from '@app/features/messaging/components/modals/MediaModal.module.css';-import {ControlButton} from '@app/features/messaging/components/modals/media_modal/MediaControls';+import {+ ControlButton,+ type MediaOverlayActionsProps,+} from '@app/features/messaging/components/modals/media_modal/MediaControls';import {CLOSE_MODAL_DESCRIPTOR,COPY_MEDIA_TO_CLIPBOARD_DESCRIPTOR,@@ -45,7 +48,9 @@ import {XIcon,} from '@phosphor-icons/react';import {observer} from 'mobx-react-lite';-import {type FC, type ReactNode, type Ref, useCallback, useMemo, useState} from 'react';+import {type FC, type ReactNode, useCallback, useMemo, useState} from 'react';++type MobileMediaActionsProps = Omit<MediaOverlayActionsProps, 'onDeleteAttachment'>;const iconSize = remFromPx(20);diff --git a/fluxer_app/src/features/messaging/components/modals/media_modal/pan_zoom/PanZoomSurface.tsx b/fluxer_app/src/features/messaging/components/modals/media_modal/pan_zoom/PanZoomSurface.tsxindex 63d488dd1..f067949c7 100644--- a/fluxer_app/src/features/messaging/components/modals/media_modal/pan_zoom/PanZoomSurface.tsx+++ b/fluxer_app/src/features/messaging/components/modals/media_modal/pan_zoom/PanZoomSurface.tsx@@ -2,11 +2,9 @@import styles from '@app/features/messaging/components/modals/media_modal/pan_zoom/PanZoomSurface.module.css';import {- type PanZoomTransformSnapshot,type UsePanZoomSurfaceOptions,usePanZoomSurface,} from '@app/features/messaging/components/modals/media_modal/pan_zoom/usePanZoomSurface';-import type {ZoomState} from '@app/features/messaging/components/modals/media_modal/shared';import {clsx} from 'clsx';import {motion} from 'framer-motion';import type {HTMLAttributes, ReactNode} from 'react';@@ -20,24 +18,13 @@ export interface PanZoomSurfaceHandle {interface PanZoomSurfacePropsextends Omit<- HTMLAttributes<HTMLDivElement>,- 'children' | 'onDoubleClick' | 'onPointerDown' | 'onPointerMove' | 'onPointerUp' | 'onWheel'- > {+ HTMLAttributes<HTMLDivElement>,+ 'children' | 'onDoubleClick' | 'onPointerDown' | 'onPointerMove' | 'onPointerUp' | 'onWheel'+ >,+ UsePanZoomSurfaceOptions {children: ReactNode;contentClassName?: string;contentRole?: string;- zoomState?: ZoomState;- maxScale?: number;- zoomedScale?: number;- disabled?: boolean;- panDisabled?: boolean;- doubleClickEnabled?: boolean;- tapToToggleZoom?: boolean;- resetKey?: unknown;- onZoomStateChange?: (state: ZoomState) => void;- onTransformChange?: (snapshot: PanZoomTransformSnapshot) => void;- onTap?: () => void;- onBackdropTap?: () => void;}function formatTransformLength(value: number | string): string {diff --git a/fluxer_app/src/features/messaging/events/MessageReactionAdd.ts b/fluxer_app/src/features/messaging/events/MessageReactionAdd.tsindex 58344e626..a546a428e 100644--- a/fluxer_app/src/features/messaging/events/MessageReactionAdd.ts+++ b/fluxer_app/src/features/messaging/events/MessageReactionAdd.ts@@ -31,7 +31,7 @@ export function handleMessageReactionAdd(data: MessageReactionAddPayload, _conteif (data.guild_id && data.member) {GuildMembers.hydrateIfMissing(data.guild_id, data.member);}- SavedMessages.handleMessageReactionAdd(data.message_id);+ SavedMessages.handleMessageReactionChange(data.message_id);MessageReactions.handleReactionAdd(data.message_id, data.user_id, emoji);ChannelPins.handleMessageReactionAdd(data.channel_id, data.message_id);ForumPosts.handleReaction(@@ -41,7 +41,7 @@ export function handleMessageReactionAdd(data: MessageReactionAddPayload, _contetrue,data.user_id === Authentication.currentUserId,);- MentionFeed.handleMessageReactionAdd(data.message_id);+ MentionFeed.handleMessageReactionChange(data.message_id);Messages.handleReaction({type: 'MESSAGE_REACTION_ADD',channelId: data.channel_id,diff --git a/fluxer_app/src/features/messaging/events/MessageReactionAddMany.ts b/fluxer_app/src/features/messaging/events/MessageReactionAddMany.tsindex ac0201aa8..1593d4bdb 100644--- a/fluxer_app/src/features/messaging/events/MessageReactionAddMany.ts+++ b/fluxer_app/src/features/messaging/events/MessageReactionAddMany.ts@@ -40,7 +40,7 @@ export function handleMessageReactionAddMany(if (data.guild_id && reaction.member) {GuildMembers.hydrateIfMissing(data.guild_id, reaction.member);}- SavedMessages.handleMessageReactionAdd(data.message_id);+ SavedMessages.handleMessageReactionChange(data.message_id);MessageReactions.handleReactionAdd(data.message_id, reaction.user_id, emoji);ChannelPins.handleMessageReactionAdd(data.channel_id, data.message_id);ForumPosts.handleReaction(@@ -50,7 +50,7 @@ export function handleMessageReactionAddMany(true,reaction.user_id === Authentication.currentUserId,);- MentionFeed.handleMessageReactionAdd(data.message_id);+ MentionFeed.handleMessageReactionChange(data.message_id);Messages.handleReaction({type: 'MESSAGE_REACTION_ADD',channelId: data.channel_id,diff --git a/fluxer_app/src/features/messaging/events/MessageReactionRemove.ts b/fluxer_app/src/features/messaging/events/MessageReactionRemove.tsindex 693e3c3ef..49a001ec1 100644--- a/fluxer_app/src/features/messaging/events/MessageReactionRemove.ts+++ b/fluxer_app/src/features/messaging/events/MessageReactionRemove.ts@@ -31,7 +31,7 @@ export function handleMessageReactionRemove(data: MessageReactionRemovePayload,if (data.guild_id && data.member) {GuildMembers.hydrateIfMissing(data.guild_id, data.member);}- SavedMessages.handleMessageReactionRemove(data.message_id);+ SavedMessages.handleMessageReactionChange(data.message_id);MessageReactions.handleReactionRemove(data.message_id, data.user_id, emoji);ChannelPins.handleMessageReactionRemove(data.channel_id, data.message_id);ForumPosts.handleReaction(@@ -41,7 +41,7 @@ export function handleMessageReactionRemove(data: MessageReactionRemovePayload,false,data.user_id === Authentication.currentUserId,);- MentionFeed.handleMessageReactionRemove(data.message_id);+ MentionFeed.handleMessageReactionChange(data.message_id);Messages.handleReaction({type: 'MESSAGE_REACTION_REMOVE',channelId: data.channel_id,diff --git a/fluxer_app/src/features/messaging/events/MessageReactionRemoveAll.ts b/fluxer_app/src/features/messaging/events/MessageReactionRemoveAll.tsindex c85144f53..250e6f516 100644--- a/fluxer_app/src/features/messaging/events/MessageReactionRemoveAll.ts+++ b/fluxer_app/src/features/messaging/events/MessageReactionRemoveAll.ts@@ -17,10 +17,10 @@ export function handleMessageReactionRemoveAll(data: MessageReactionRemoveAllPayload,_context: GatewayHandlerContext,): void {- SavedMessages.handleMessageReactionRemoveAll(data.message_id);+ SavedMessages.handleMessageReactionChange(data.message_id);MessageReactions.handleReactionRemoveAll(data.message_id);ChannelPins.handleMessageReactionRemoveAll(data.channel_id, data.message_id);ForumPosts.handleReactionClear(data.channel_id, data.message_id);- MentionFeed.handleMessageReactionRemoveAll(data.message_id);+ MentionFeed.handleMessageReactionChange(data.message_id);Messages.handleRemoveAllReactions({channelId: data.channel_id, messageId: data.message_id});}diff --git a/fluxer_app/src/features/messaging/events/MessageReactionRemoveEmoji.ts b/fluxer_app/src/features/messaging/events/MessageReactionRemoveEmoji.tsindex a1fcf913b..29d11139e 100644--- a/fluxer_app/src/features/messaging/events/MessageReactionRemoveEmoji.ts+++ b/fluxer_app/src/features/messaging/events/MessageReactionRemoveEmoji.ts@@ -25,11 +25,11 @@ export function handleMessageReactionRemoveEmoji(_context: GatewayHandlerContext,): void {const emoji = data.emoji as ReactionEmoji;- SavedMessages.handleMessageReactionRemoveEmoji(data.message_id);+ SavedMessages.handleMessageReactionChange(data.message_id);MessageReactions.handleReactionRemoveEmoji(data.message_id, emoji);ChannelPins.handleMessageReactionRemoveEmoji(data.channel_id, data.message_id);ForumPosts.handleReactionClear(data.channel_id, data.message_id, emoji);- MentionFeed.handleMessageReactionRemoveEmoji(data.message_id);+ MentionFeed.handleMessageReactionChange(data.message_id);Messages.handleRemoveReactionEmoji({channelId: data.channel_id,messageId: data.message_id,diff --git a/fluxer_app/src/features/messaging/hooks/useMessageSubmission.tsx b/fluxer_app/src/features/messaging/hooks/useMessageSubmission.tsxindex 35aee1866..251459ab0 100644--- a/fluxer_app/src/features/messaging/hooks/useMessageSubmission.tsx+++ b/fluxer_app/src/features/messaging/hooks/useMessageSubmission.tsx@@ -71,6 +71,24 @@ function isBlockedBySlowmode(channel: Channel): boolean {return true;}+function settlePendingSend(+ channelId: string,+ pendingSend: SlowmodeCommands.PendingMessageSend,+ send: ReturnType<typeof MessageCommands.send>,+): void {+ void send+ .then((sentMessage) => {+ if (sentMessage) {+ SlowmodeCommands.confirmMessageSend(channelId, sentMessage.timestamp, pendingSend);+ return;+ }+ SlowmodeCommands.discardPendingMessageSend(channelId, pendingSend);+ })+ .catch(() => {+ SlowmodeCommands.discardPendingMessageSend(channelId, pendingSend);+ });+}+export const useMessageSubmission = ({accountKey,channel,@@ -145,27 +163,21 @@ export const useMessageSubmission = ({});SlowmodeCommands.prepareMessageSend(channel.id);const pendingSend = SlowmodeCommands.recordPendingMessageSend(channel.id);- void MessageCommands.send(channel.id, {- content: message.content,- nonce,- hasAttachments: hasAttachmentsFinal,- allowedMentions,- messageReference,- flags: message.flags,- stickers,- favoriteMemeId,- tts,- })- .then((sentMessage) => {- if (sentMessage) {- SlowmodeCommands.confirmMessageSend(channel.id, sentMessage.timestamp, pendingSend);- return;- }- SlowmodeCommands.discardPendingMessageSend(channel.id, pendingSend);- })- .catch(() => {- SlowmodeCommands.discardPendingMessageSend(channel.id, pendingSend);- });+ settlePendingSend(+ channel.id,+ pendingSend,+ MessageCommands.send(channel.id, {+ content: message.content,+ nonce,+ hasAttachments: hasAttachmentsFinal,+ allowedMentions,+ messageReference,+ flags: message.flags,+ stickers,+ favoriteMemeId,+ tts,+ }),+ );ComponentBus.dispatch('MESSAGE_SENT', {channelId: channel.id});return true;},@@ -217,28 +229,22 @@ export const useMessageSubmission = ({SlowmodeCommands.prepareMessageSend(channel.id);const allowedMentions: AllowedMentions = {replied_user: replyingMessage?.mentioning ?? true};const pendingSend = SlowmodeCommands.recordPendingMessageSend(channel.id);- void MessageCommands.send(channel.id, {- content: messageData.content,- nonce,- hasAttachments: sendOptions.hasAttachments,- allowedMentions,- messageReference: referencedMessage- ? {channel_id: channel.id, message_id: referencedMessage.id, type: 0}- : undefined,- flags: 0,- stickers: messageData.stickers || [],- favoriteMemeId: sendOptions.favoriteMemeId,- })- .then((sentMessage) => {- if (sentMessage) {- SlowmodeCommands.confirmMessageSend(channel.id, sentMessage.timestamp, pendingSend);- return;- }- SlowmodeCommands.discardPendingMessageSend(channel.id, pendingSend);- })- .catch(() => {- SlowmodeCommands.discardPendingMessageSend(channel.id, pendingSend);- });+ settlePendingSend(+ channel.id,+ pendingSend,+ MessageCommands.send(channel.id, {+ content: messageData.content,+ nonce,+ hasAttachments: sendOptions.hasAttachments,+ allowedMentions,+ messageReference: referencedMessage+ ? {channel_id: channel.id, message_id: referencedMessage.id, type: 0}+ : undefined,+ flags: 0,+ stickers: messageData.stickers || [],+ favoriteMemeId: sendOptions.favoriteMemeId,+ }),+ );ComponentBus.dispatch('MESSAGE_SENT', {channelId: channel.id});},[accountKey, channel?.id, referencedMessage, replyingMessage],diff --git a/fluxer_app/src/features/messaging/models/MessagingMessage.ts b/fluxer_app/src/features/messaging/models/MessagingMessage.tsindex e96c50591..cb42c67fa 100644--- a/fluxer_app/src/features/messaging/models/MessagingMessage.ts+++ b/fluxer_app/src/features/messaging/models/MessagingMessage.ts@@ -304,7 +304,7 @@ export class Message {withUpdates(updates: Partial<WireMessage>): Message {if ('reactions' in updates) {- MessageReactions.replaceMessageReactions(this.id, updates.reactions ?? []);+ MessageReactions.hydrateMessageReactions(this.id, updates.reactions ?? []);}return new Message({diff --git a/fluxer_app/src/features/messaging/state/MessageEdit.ts b/fluxer_app/src/features/messaging/state/MessageEdit.tsindex 752f6644f..13fc88ba9 100644--- a/fluxer_app/src/features/messaging/state/MessageEdit.ts+++ b/fluxer_app/src/features/messaging/state/MessageEdit.ts@@ -22,8 +22,6 @@ class MessageEdit {return;}if (currentMessageId !== messageId) {- if (currentMessageId) {- }this.editingMessageIds[channelId] = messageId;}if (currentContent !== initialContent) {@@ -35,9 +33,6 @@ class MessageEdit {if (!(channelId in this.editingMessageIds)) {return;}- const messageId = this.editingMessageIds[channelId];- if (messageId) {- }delete this.editingMessageIds[channelId];}diff --git a/fluxer_app/src/features/messaging/state/MessageEditMobile.ts b/fluxer_app/src/features/messaging/state/MessageEditMobile.tsindex b7cbd4e3a..240e9ca92 100644--- a/fluxer_app/src/features/messaging/state/MessageEditMobile.ts+++ b/fluxer_app/src/features/messaging/state/MessageEditMobile.ts@@ -14,9 +14,6 @@ class MessageEditMobile {if (this.editingMessageIds[channelId] === messageId) {return;}- const currentMessageId = this.editingMessageIds[channelId];- if (currentMessageId) {- }this.editingMessageIds[channelId] = messageId;}@@ -24,9 +21,6 @@ class MessageEditMobile {if (!(channelId in this.editingMessageIds)) {return;}- const messageId = this.editingMessageIds[channelId];- if (messageId) {- }delete this.editingMessageIds[channelId];}diff --git a/fluxer_app/src/features/messaging/state/MessageReactions.ts b/fluxer_app/src/features/messaging/state/MessageReactions.tsindex 9c6a86d8d..1394e917d 100644--- a/fluxer_app/src/features/messaging/state/MessageReactions.ts+++ b/fluxer_app/src/features/messaging/state/MessageReactions.ts@@ -87,14 +87,6 @@ class MessageReactionsManager {});}- replaceMessageReactions(messageId: string, reactions: ReadonlyArray<MessageReaction> | null | undefined): void {- this.commitReactionEvent(messageId, {- type: 'reaction.hydrate',- reactions,- currentUserId: Authentication.currentUserId,- });- }-private commitReactionEvent(messageId: string, event: ReactionMachineEvent): void {const current = this.messageStates.get(messageId);if (!current && isMissingReactionStateNoop(event)) {@@ -254,6 +246,7 @@ class MessageReactionsManager {}handleFetchSuccess(+ mode: 'replace' | 'append',messageId: string,users: ReadonlyArray<UserPartial>,emoji: ReactionEmoji,@@ -271,36 +264,7 @@ class MessageReactionsManager {Users.cacheUsers(users.slice());this.commitReactorEvent(messageId, emoji, entry, {type: 'fetch.success',- mode: 'replace',- users,- requestedLimit,- responseHasMore,- totalCount,- requestId,- nextAfter,- });- this.trackReactors(messageId, emoji, users);- }-- handleFetchAppend(- messageId: string,- users: ReadonlyArray<UserPartial>,- emoji: ReactionEmoji,- requestedLimit?: number,- responseHasMore?: boolean,- totalCount?: number,- requestId?: number,- nextAfter?: string | null,- ): void {- const key = getReactionKey(messageId, emoji);- const ignored = this.shouldIgnoreFetchResult(key, requestId);- this.settleInFlightRequest(key, requestId);- if (ignored) return;- const entry = this.getOrCreateReactorEntry(messageId, emoji);- Users.cacheUsers(users.slice());- this.commitReactorEvent(messageId, emoji, entry, {- type: 'fetch.success',- mode: 'append',+ mode,users,requestedLimit,responseHasMore,diff --git a/fluxer_app/src/features/messaging/state/SavedMessages.ts b/fluxer_app/src/features/messaging/state/SavedMessages.tsindex 88a233ae3..ff5a7fa22 100644--- a/fluxer_app/src/features/messaging/state/SavedMessages.ts+++ b/fluxer_app/src/features/messaging/state/SavedMessages.ts@@ -129,7 +129,7 @@ class SavedMessages {this.savedMessages = [new Message(message, {missingReactions: 'preserve'}), ...this.savedMessages];}- private touchMessage(messageId: string): void {+ handleMessageReactionChange(messageId: string): void {const index = this.savedMessages.findIndex((m) => m.id === messageId);if (index === -1) return;this.savedMessages = [diff --git a/fluxer_app/src/features/messaging/upload/AttachmentUploadPlan.ts b/fluxer_app/src/features/messaging/upload/AttachmentUploadPlan.tsindex f99655e7e..ac5075a80 100644--- a/fluxer_app/src/features/messaging/upload/AttachmentUploadPlan.ts+++ b/fluxer_app/src/features/messaging/upload/AttachmentUploadPlan.ts@@ -2,11 +2,7 @@import {Endpoints} from '@app/features/app/constants/Endpoints';import RuntimeConfig from '@app/features/app/state/RuntimeConfig';-import {- type ChunkedUploadPart,- type ChunkedUploadPlan,- uploadFileInChunks,-} from '@app/features/messaging/upload/ChunkedAttachmentUploader';+import {type ChunkedUploadPart, uploadFileInChunks} from '@app/features/messaging/upload/ChunkedAttachmentUploader';import {CloudUpload} from '@app/features/messaging/upload/CloudUpload';import {wrapDesktopLocalUploadURL} from '@app/features/messaging/utils/DesktopResourceUrl';import type {ApiAttachmentMetadata} from '@app/features/messaging/utils/MessageRequestUtils';@@ -114,6 +110,36 @@ export async function requestPresignedAttachmentUploads(return plans;}+async function transferFileForPlan(+ file: File,+ plan: PresignedAttachmentUploadResponseAttachment,+ signal: AbortSignal,+ onBytes: (uploadedBytes: number) => void,+): Promise<void> {+ if (plan.upload_mode === 'singlepart') {+ await http.put(wrapDesktopLocalUploadURL(plan.upload_url), {+ body: file,+ auth: 'none',+ headers: {+ 'Content-Type': plan.content_type,+ },+ signal,+ onProgress: (event) => {+ onBytes(event.loaded);+ },+ });+ return;+ }+ const parts: Array<ChunkedUploadPart> = plan.parts.map((entry) => ({+ partNumber: entry.part_number,+ uploadUrl: entry.upload_url,+ }));+ await uploadFileInChunks(+ {file, contentType: plan.content_type, partSize: plan.part_size, parts},+ {signal, onProgress: onBytes},+ );+}+export async function uploadAttachmentsViaPlans(params: {nonce: string;attachments: Array<ApiAttachmentMetadata>;@@ -145,44 +171,20 @@ export async function uploadAttachmentsViaPlans(params: {throw new Error(`Missing presigned upload metadata for attachment ${attachment.id}`);}const plan = plans[planIndex];- if (plan.upload_mode === 'singlepart') {- await http.put(wrapDesktopLocalUploadURL(plan.upload_url), {- body: file,- auth: 'none',- headers: {- 'Content-Type': plan.content_type,- },- signal,- onProgress: (event) => {- const loaded = Math.min(file.size, event.loaded);- if (loaded > loadedBytesByIndex[index]) {- loadedBytesByIndex[index] = loaded;- reportProgress();- }- },- });- loadedBytesByIndex[index] = file.size;- } else {+ if (plan.upload_mode === 'multipart') {multipartUploadsToComplete.push({upload_filename: plan.upload_filename,upload_id: plan.upload_id,});- const parts: Array<ChunkedUploadPart> = plan.parts.map((entry) => ({- partNumber: entry.part_number,- uploadUrl: entry.upload_url,- }));- const uploadPlan: ChunkedUploadPlan = {file, contentType: plan.content_type, partSize: plan.part_size, parts};- await uploadFileInChunks(uploadPlan, {- signal,- onProgress: (uploaded) => {- if (uploaded > loadedBytesByIndex[index]) {- loadedBytesByIndex[index] = uploaded;- reportProgress();- }- },- });- loadedBytesByIndex[index] = file.size;}+ await transferFileForPlan(file, plan, signal, (uploaded) => {+ const loaded = Math.min(file.size, uploaded);+ if (loaded > loadedBytesByIndex[index]) {+ loadedBytesByIndex[index] = loaded;+ reportProgress();+ }+ });+ loadedBytesByIndex[index] = file.size;completedUploads += 1;reportProgress();}@@ -217,32 +219,8 @@ export async function uploadTextareaAttachmentViaPlan(params: {const uploadProgress = Math.round((Math.min(file.size, uploadedBytes) / file.size) * 100);CloudUpload.updateAttachment(channelId, attachmentId, {status: 'uploading', uploadProgress});};- if (plan.upload_mode === 'singlepart') {- await http.put(wrapDesktopLocalUploadURL(plan.upload_url), {- body: file,- auth: 'none',- headers: {- 'Content-Type': plan.content_type,- },- signal,- onProgress: (event) => {- reportProgress(event.loaded);- },- });- } else {- const parts: Array<ChunkedUploadPart> = plan.parts.map((entry) => ({- partNumber: entry.part_number,- uploadUrl: entry.upload_url,- }));- await uploadFileInChunks(- {file, contentType: plan.content_type, partSize: plan.part_size, parts},- {- signal,- onProgress: (uploadedBytes) => {- reportProgress(uploadedBytes);- },- },- );+ await transferFileForPlan(file, plan, signal, reportProgress);+ if (plan.upload_mode === 'multipart') {await completeMultipartAttachmentUploads(channelId,[{upload_filename: plan.upload_filename, upload_id: plan.upload_id}],diff --git a/fluxer_app/src/features/messaging/utils/CodeLinkUtils.ts b/fluxer_app/src/features/messaging/utils/CodeLinkUtils.tsindex 71642455c..b68854251 100644--- a/fluxer_app/src/features/messaging/utils/CodeLinkUtils.ts+++ b/fluxer_app/src/features/messaging/utils/CodeLinkUtils.ts@@ -61,7 +61,7 @@ function createPattern(config: CodeLinkConfig): RegExp {return pattern;}-function findCodeMatchesInternal(+function findCodeMatches(content: string | null,config: CodeLinkConfig,options?: {@@ -97,10 +97,6 @@ export function findCodes(content: string | null, config: CodeLinkConfig): Arrayreturn findCodeMatches(content, config).map((match) => match.code);}-function findCodeMatches(content: string | null, config: CodeLinkConfig): Array<CodeLinkMatch> {- return findCodeMatchesInternal(content, config);-}-export function findCode(content: string | null, config: CodeLinkConfig): string | null {return findCodeMatches(content, config)[0]?.code ?? null;}@@ -111,7 +107,7 @@ export function findSpoileredCodeMatches(content: string | null, config: CodeLinfor (const spoilerMatch of content.matchAll(SPOILER_REGEX)) {const spoilerBody = spoilerMatch[1];if (!spoilerBody) continue;- for (const codeMatch of findCodeMatchesInternal(spoilerBody, config, {+ for (const codeMatch of findCodeMatches(spoilerBody, config, {dedupeCodes: false,limit: Number.POSITIVE_INFINITY,})) {diff --git a/fluxer_app/src/features/messaging/utils/DesktopLocalResourceTarget.ts b/fluxer_app/src/features/messaging/utils/DesktopLocalResourceTarget.tsindex 2001cade4..16d679d84 100644--- a/fluxer_app/src/features/messaging/utils/DesktopLocalResourceTarget.ts+++ b/fluxer_app/src/features/messaging/utils/DesktopLocalResourceTarget.ts@@ -6,7 +6,7 @@ import {LOCAL_APP_REMOTE_PROXY_URL_PARAMETER,} from '@fluxer/desktop_ipc/src/LocalAppRouteContract';-export function parseDesktopLocalResourceProxyTarget(value: string): string {+export function unwrapDesktopLocalResourceURL(value: string): string {if (value.length === 0) return value;let parsedUrl: URL;try {@@ -19,7 +19,3 @@ export function parseDesktopLocalResourceProxyTarget(value: string): string {if (parsedUrl.pathname !== LOCAL_APP_REMOTE_PROXY_PATH_PREFIX && runtimeKey == null) return value;return parsedUrl.searchParams.get(LOCAL_APP_REMOTE_PROXY_URL_PARAMETER) ?? value;}--export function unwrapDesktopLocalResourceURL(value: string): string {- return parseDesktopLocalResourceProxyTarget(value);-}diff --git a/fluxer_app/src/features/messaging/utils/DesktopResourceUrl.ts b/fluxer_app/src/features/messaging/utils/DesktopResourceUrl.tsindex 58231978e..46ed8164f 100644--- a/fluxer_app/src/features/messaging/utils/DesktopResourceUrl.ts+++ b/fluxer_app/src/features/messaging/utils/DesktopResourceUrl.ts@@ -2,10 +2,7 @@import {runtimeInstanceKey} from '@app/features/app/state/InstanceSnapshotStore';import RuntimeConfig from '@app/features/app/state/RuntimeConfig';-import {- parseDesktopLocalResourceProxyTarget,- unwrapDesktopLocalResourceURL,-} from '@app/features/messaging/utils/DesktopLocalResourceTarget';+import {unwrapDesktopLocalResourceURL} from '@app/features/messaging/utils/DesktopLocalResourceTarget';import {isDesktopLocalAppDocument} from '@app/features/platform/DesktopLocalAppRuntime';import {LOCAL_APP_REMOTE_PROXY_PATH_PREFIX,@@ -37,7 +34,7 @@ class DesktopResourceRuntimeKeyError extends Error {}export function wrapDesktopLocalResourceURL(value: string): string {- return wrapResolvedDesktopLocalResourceURL(parseDesktopLocalResourceProxyTarget(value), false);+ return wrapResolvedDesktopLocalResourceURL(unwrapDesktopLocalResourceURL(value), false);}export function wrapDesktopLocalResourceURLForInstance(value: string, instanceKey: string): string {@@ -45,7 +42,7 @@ export function wrapDesktopLocalResourceURLForInstance(value: string, instanceKeif (instanceKey.trim().length === 0) {throw new DesktopResourceRuntimeKeyError();}- const targetValue = parseDesktopLocalResourceProxyTarget(value);+ const targetValue = unwrapDesktopLocalResourceURL(value);let target: URL;try {target = new URL(targetValue);@@ -78,7 +75,7 @@ export function resolveDesktopCrossOriginMediaURL(value: string | undefined): stfunction parseDisplayTarget(value: string): URL | null {try {- return new URL(parseDesktopLocalResourceProxyTarget(value));+ return new URL(unwrapDesktopLocalResourceURL(value));} catch {return null;}@@ -94,7 +91,7 @@ function isDocumentAllowedCleartextHost(hostname: string): boolean {}export function updateDesktopLocalResourceURLTarget(value: string, updateTarget: (target: URL) => boolean): string {- const targetValue = parseDesktopLocalResourceProxyTarget(value);+ const targetValue = unwrapDesktopLocalResourceURL(value);let target: URL;try {target = new URL(targetValue);@@ -107,7 +104,7 @@ export function updateDesktopLocalResourceURLTarget(value: string, updateTarget:export function wrapDesktopLocalUploadURL(value: string): string {if (!isDesktopLocalAppDocument()) return value;- const targetValue = parseDesktopLocalResourceProxyTarget(value);+ const targetValue = unwrapDesktopLocalResourceURL(value);let target: URL;try {target = new URL(targetValue);diff --git a/fluxer_app/src/features/messaging/utils/TypedEmojiShortcodeUtils.ts b/fluxer_app/src/features/messaging/utils/TypedEmojiShortcodeUtils.tsindex a2366b5f8..3a884ff76 100644--- a/fluxer_app/src/features/messaging/utils/TypedEmojiShortcodeUtils.ts+++ b/fluxer_app/src/features/messaging/utils/TypedEmojiShortcodeUtils.ts@@ -9,6 +9,7 @@ import {checkEmojiAvailabilityWithGuildFallback,} from '@app/features/expressions/utils/ExpressionPermissionUtils';import UnicodeEmojis from '@app/features/expressions/utils/UnicodeEmojis';+import {isExistingCustomEmojiMarkdown} from '@app/features/messaging/utils/markdown/TypedEmojiMatch';import {findUrlSpans, isInsideSpan, type TextSpan} from '@app/features/messaging/utils/markdown/UrlSpanUtils';import type {I18n} from '@lingui/core';@@ -40,10 +41,6 @@ interface ResolveTypedEmojiShortcodesOptions {i18n: I18n;}-function isExistingCustomEmojiMarkdown(content: string, matchIndex: number): boolean {- return content[matchIndex - 1] === '<' || (content[matchIndex - 2] === '<' && content[matchIndex - 1] === 'a');-}-function isCustomEmoji(emoji: FlatEmoji): boolean {return !!emoji.id && !!emoji.guildId;}diff --git a/fluxer_app/src/features/messaging/utils/markdown/Plaintext.ts b/fluxer_app/src/features/messaging/utils/markdown/Plaintext.tsindex 4215a8601..e3621bc18 100644--- a/fluxer_app/src/features/messaging/utils/markdown/Plaintext.ts+++ b/fluxer_app/src/features/messaging/utils/markdown/Plaintext.ts@@ -498,7 +498,7 @@ function trimTrailingWhitespaceBeforeLineBreaks(value: string, preserveMarkdown:return lines.join('\n');}-function renderToPlaintext(nodes: Array<Node>, options: PlaintextRenderOptions): string {+export function renderAstToPlaintext(nodes: Array<Node>, options: PlaintextRenderOptions): string {const result = renderNodesToPlaintext(nodes, options);return trimTrailingWhitespaceBeforeLineBreaks(result, options.preserveMarkdown).replace(/\n{3,}/g, '\n\n')@@ -513,7 +513,7 @@ export function parseAndRenderToPlaintext(try {const parser = new WasmParser(content, parserFlags);const {nodes} = parser.parse();- return renderToPlaintext(nodes, options);+ return renderAstToPlaintext(nodes, options);} catch (error) {logger.error('Error parsing content for plaintext rendering:', error);return content;diff --git a/fluxer_app/src/features/messaging/utils/markdown/TypedEmojiMatch.ts b/fluxer_app/src/features/messaging/utils/markdown/TypedEmojiMatch.tsindex da4c19df6..b49cb3beb 100644--- a/fluxer_app/src/features/messaging/utils/markdown/TypedEmojiMatch.ts+++ b/fluxer_app/src/features/messaging/utils/markdown/TypedEmojiMatch.ts@@ -18,7 +18,7 @@ function isTypedEmojiShortcodeBoundary(text: string, start: number, end: number)return !SHORTCODE_WORD_BOUNDARY_CHAR.test(previous) && !SHORTCODE_WORD_BOUNDARY_CHAR.test(next);}-function isExistingCustomEmojiMarkdown(content: string, matchIndex: number): boolean {+export function isExistingCustomEmojiMarkdown(content: string, matchIndex: number): boolean {return content[matchIndex - 1] === '<' || (content[matchIndex - 2] === '<' && content[matchIndex - 1] === 'a');}diff --git a/fluxer_app/src/features/notification/state/MentionFeed.ts b/fluxer_app/src/features/notification/state/MentionFeed.tsindex 2ae071dc6..77d829fb7 100644--- a/fluxer_app/src/features/notification/state/MentionFeed.ts+++ b/fluxer_app/src/features/notification/state/MentionFeed.ts@@ -209,27 +209,11 @@ class MentionFeed {this.recentMentions.unshift(messageRecord);}- private touchMessage(messageId: string): void {+ handleMessageReactionChange(messageId: string): void {const index = this.recentMentions.findIndex((m) => m.id === messageId);if (index === -1) return;this.recentMentions[index] = this.recentMentions[index].withUpdates({});}-- handleMessageReactionAdd(messageId: string): void {- this.touchMessage(messageId);- }-- handleMessageReactionRemove(messageId: string): void {- this.touchMessage(messageId);- }-- handleMessageReactionRemoveAll(messageId: string): void {- this.touchMessage(messageId);- }-- handleMessageReactionRemoveEmoji(messageId: string): void {- this.touchMessage(messageId);- }}const mentionFeed = new MentionFeed();diff --git a/fluxer_app/src/features/platform/components/router/RouterCore.ts b/fluxer_app/src/features/platform/components/router/RouterCore.tsindex 3e10d7e3b..e09e1d4a2 100644--- a/fluxer_app/src/features/platform/components/router/RouterCore.ts+++ b/fluxer_app/src/features/platform/components/router/RouterCore.ts@@ -415,20 +415,7 @@ class RouterImpl implements Router {private async handleNotFound(url: URL, historyState: unknown): Promise<void> {const notFoundRouteId = this.options.notFoundRouteId;- if (!notFoundRouteId) {- this.state = {- ...this.state,- location: url,- matches: [],- navigating: false,- pending: null,- error: new NotFound(),- historyState,- };- this.notify();- return;- }- const nf = this.routeById.get(notFoundRouteId);+ const nf = notFoundRouteId ? this.routeById.get(notFoundRouteId) : undefined;if (!nf) {this.state = {...this.state,diff --git a/fluxer_app/src/features/platform/state/AppStorageBootstrap.ts b/fluxer_app/src/features/platform/state/AppStorageBootstrap.tsindex bc1bfc147..18d323c6d 100644--- a/fluxer_app/src/features/platform/state/AppStorageBootstrap.ts+++ b/fluxer_app/src/features/platform/state/AppStorageBootstrap.ts@@ -13,23 +13,23 @@ export type {AppStorageSessionAccount,} from '@app/features/platform/state/AppStorageBootstrapContract';-async function initializeSignedOutStorage(options?: {readonly scoped?: boolean}): Promise<void> {- await initializeAppStorage(options);+async function initializeSignedOutStorage(): Promise<void> {+ await initializeAppStorage();await activateAppStorageScope(null);Logger.refreshGlobalLogLevel();}-export async function startAppStorage(options?: {readonly scoped?: boolean}): Promise<AppStorageBootstrapHandle> {+export async function startAppStorage(): Promise<AppStorageBootstrapHandle> {const now = Date.now();const desktopAuthority = await DesktopStorageAuthority.prepareBoot();if (desktopAuthority.isCommitted) {- await initializeSignedOutStorage(options);+ await initializeSignedOutStorage();return AppStorageFinalizationSession.forCommittedAuthority(desktopAuthority);}const migration = await AppStorageMigrationCoordinator.prepare(now);const webBackend = getPersistentStorageBackend();- await initializeSignedOutStorage(options);+ await initializeSignedOutStorage();return AppStorageFinalizationSession.forMigration({desktopAuthority,migration,diff --git a/fluxer_app/src/features/platform/state/PersistentStorage.ts b/fluxer_app/src/features/platform/state/PersistentStorage.tsindex 2d32bb975..2cbce412a 100644--- a/fluxer_app/src/features/platform/state/PersistentStorage.ts+++ b/fluxer_app/src/features/platform/state/PersistentStorage.ts@@ -245,7 +245,7 @@ function readThroughLegacyValue(key: string): string | null {}function readValue(key: string): string | null {- if (!scopedStorageActive()) {+ if (!scopedStorageEngaged) {return readRawStorageItem(key);}if (RAW_ONLY_APP_STORAGE_KEYS.has(key)) {@@ -289,7 +289,7 @@ function forgetDeletedKey(scope: string, key: string): void {}function writeValue(key: string, value: string | null): void {- if (!scopedStorageActive() || RAW_ONLY_APP_STORAGE_KEYS.has(key)) {+ if (!scopedStorageEngaged || RAW_ONLY_APP_STORAGE_KEYS.has(key)) {writeRawStorageItem(key, value);return;}@@ -308,14 +308,14 @@ function writeValue(key: string, value: string | null): void {}function hasUnsettledWriteFailure(key: string): boolean {- if (!scopedStorageActive() || RAW_ONLY_APP_STORAGE_KEYS.has(key)) {+ if (!scopedStorageEngaged || RAW_ONLY_APP_STORAGE_KEYS.has(key)) {return false;}return writeQueue.hasFailure(storageScopeForKey(key), key);}function allKeys(): Array<string> {- if (!scopedStorageActive()) {+ if (!scopedStorageEngaged) {return rawStorageKeys();}const keys = [...scopedCache.keys()];@@ -551,7 +551,7 @@ async function adoptRemoteDeletedKeys(scope: string): Promise<void> {}async function applyRemoteCommit(scope: string, key: string): Promise<void> {- if (!scopedStorageActive() || (scope !== GLOBAL_APP_STORAGE_SCOPE && scope !== activeScope)) {+ if (!scopedStorageEngaged || (scope !== GLOBAL_APP_STORAGE_SCOPE && scope !== activeScope)) {return;}if (key === AppStorageKey.ACCOUNT_RESET_KEPT_KEYS) {@@ -591,7 +591,7 @@ async function applyRemoteCommit(scope: string, key: string): Promise<void> {}async function applyRemoteScopeReload(scope: string): Promise<void> {- if (!scopedStorageActive() || (scope !== GLOBAL_APP_STORAGE_SCOPE && scope !== activeScope)) {+ if (!scopedStorageEngaged || (scope !== GLOBAL_APP_STORAGE_SCOPE && scope !== activeScope)) {return;}const reloadScope = activeScope;@@ -622,7 +622,7 @@ async function applyRemoteScopeReload(scope: string): Promise<void> {if (typeof window !== 'undefined' && rawStorageKind() !== 'memory') {window.addEventListener('storage', (event: StorageEvent) => {- if (scopedStorageActive() || !isRawStorageArea(event.storageArea)) {+ if (scopedStorageEngaged || !isRawStorageArea(event.storageArea)) {return;}notifyListeners({@@ -656,7 +656,7 @@ export function subscribeAppStorageScope(listener: AppStorageScopeListener): ()};}-export async function initializeAppStorage(options?: {readonly scoped?: boolean}): Promise<void> {+export async function initializeAppStorage(): Promise<void> {if (storageInitialized) {await flushAppStorageWrites();return;@@ -723,7 +723,7 @@ export async function activateAppStorageScope(scope: string | null): Promise<voiconst nextScope = normalizeAppStorageScope(scope);await runTransition(async () => {const previousScope = activeScope;- if (!scopedStorageActive()) {+ if (!scopedStorageEngaged) {activeScope = nextScope;return;}@@ -739,7 +739,7 @@ export async function activateAppStorageScope(scope: string | null): Promise<voiexport async function deleteAppStorageScope(scope: string): Promise<void> {const normalizedScope = normalizeAppStorageScope(scope);await runTransition(async () => {- if (!scopedStorageActive()) {+ if (!scopedStorageEngaged) {removeEntries(collectEntries(() => true));return;}@@ -770,7 +770,7 @@ export async function deleteAppStorageScope(scope: string): Promise<void> {export async function resetActiveAccountScope(keysToKeep: ReadonlyArray<string>): Promise<void> {const keepSet = new Set(keysToKeep);await runTransition(async () => {- if (!scopedStorageActive()) {+ if (!scopedStorageEngaged) {removeEntries(collectEntries((key) => !keepSet.has(key)));return;}@@ -798,7 +798,7 @@ export async function resetActiveAccountScope(keysToKeep: ReadonlyArray<string>)export async function resetAppStorage(keysToKeep: ReadonlyArray<string>): Promise<void> {const keepSet = new Set(keysToKeep);await runTransition(async () => {- if (!scopedStorageActive()) {+ if (!scopedStorageEngaged) {removeEntries(collectEntries((key) => !keepSet.has(key)));return;}diff --git a/fluxer_app/src/features/platform/transport/RestTransport.ts b/fluxer_app/src/features/platform/transport/RestTransport.tsindex 733e8d318..84c1d7bca 100644--- a/fluxer_app/src/features/platform/transport/RestTransport.ts+++ b/fluxer_app/src/features/platform/transport/RestTransport.ts@@ -324,8 +324,7 @@ async function runWithSudoEscalation<T>(if (sudoApplied) sudo?.onFailure(err);throw err;}- if (sudoVerificationFailed) {- sudo.onFailure(err);+ const reprompt = async (nextPhase: SudoPhase): Promise<RestResponse<T>> => {const merged = await awaitAccountScopedInteraction(ticket, sudo.prompt(method, path, err));if (!merged) throw err;return runWithSudoEscalation<T>(@@ -335,40 +334,22 @@ async function runWithSudoEscalation<T>(method,path,options,- 'reissued',+ nextPhase,mergeBody(options, merged),);+ };+ if (sudoVerificationFailed) {+ sudo.onFailure(err);+ return reprompt('reissued');}switch (phase) {case 'fresh': {sudo.invalidate();- const merged = await awaitAccountScopedInteraction(ticket, sudo.prompt(method, path, err));- if (!merged) throw err;- return runWithSudoEscalation<T>(- state,- routing,- ticket,- method,- path,- options,- 'reissued',- mergeBody(options, merged),- );+ return reprompt('reissued');}case 'reissued': {sudo.onFailure(err);- const second = await awaitAccountScopedInteraction(ticket, sudo.prompt(method, path, err));- if (!second) throw err;- return runWithSudoEscalation<T>(- state,- routing,- ticket,- method,- path,- options,- 'reissued-twice',- mergeBody(options, second),- );+ return reprompt('reissued-twice');}case 'reissued-twice': {sudo.onFailure(err);diff --git a/fluxer_app/src/features/read_state/state/read_states/ReadStateIncomingMessageMachine.ts b/fluxer_app/src/features/read_state/state/read_states/ReadStateIncomingMessageMachine.tsindex 4f709f1b8..e437fb95b 100644--- a/fluxer_app/src/features/read_state/state/read_states/ReadStateIncomingMessageMachine.ts+++ b/fluxer_app/src/features/read_state/state/read_states/ReadStateIncomingMessageMachine.ts@@ -128,14 +128,8 @@ function createReadStateIncomingMessageSnapshot(return initialTransition(readStateIncomingMessageMachine, input)[0];}-function selectReadStateIncomingMessageDecision(- snapshot: ReadStateIncomingMessageSnapshot,-): ReadStateIncomingMessageDecision {- return getDecision(snapshot);-}-export function resolveReadStateIncomingMessageDecision(input: ReadStateIncomingMessageInput,): ReadStateIncomingMessageDecision {- return selectReadStateIncomingMessageDecision(createReadStateIncomingMessageSnapshot(input));+ return getDecision(createReadStateIncomingMessageSnapshot(input));}diff --git a/fluxer_app/src/features/search/components/search/ChannelFilterSheet.tsx b/fluxer_app/src/features/search/components/search/ChannelFilterSheet.tsxindex e98acb413..aa3b7570f 100644--- a/fluxer_app/src/features/search/components/search/ChannelFilterSheet.tsx+++ b/fluxer_app/src/features/search/components/search/ChannelFilterSheet.tsx@@ -4,7 +4,7 @@ import type {Channel} from '@app/features/channel/models/Channel';import Channels from '@app/features/channel/state/Channels';import * as ChannelUtils from '@app/features/channel/utils/ChannelUtils';import {PASSWORD_MANAGER_IGNORE_ATTRIBUTES} from '@app/features/platform/utils/PasswordManagerAutocomplete';-import styles from '@app/features/search/components/search/ChannelFilterSheet.module.css';+import styles from '@app/features/search/components/search/FilterSheet.module.css';import {remFromPx} from '@app/features/theme/layout/RemFromPx';import {BottomSheet} from '@app/features/ui/bottom_sheet/BottomSheet';import {Button} from '@app/features/ui/button/Button';@@ -128,20 +128,17 @@ export const ChannelFilterSheet: React.FC<ChannelFilterSheetProps> = observer(key={channelOption.id}type="button"aria-pressed={isSelected}- className={clsx(styles.channelItem, isSelected && styles.channelItemSelected)}+ className={clsx(styles.item, isSelected && styles.itemSelected)}onClick={() => toggleChannel(channelOption.id)}data-flx="search.search.channel-filter-sheet.channel-item.toggle-channel.button">{ChannelUtils.getIcon(channelOption, {className: styles.channelIcon})}- <div className={styles.channelInfo} data-flx="search.search.channel-filter-sheet.channel-info">- <span className={styles.channelName} data-flx="search.search.channel-filter-sheet.channel-name">+ <div className={styles.info} data-flx="search.search.channel-filter-sheet.channel-info">+ <span className={styles.name} data-flx="search.search.channel-filter-sheet.channel-name">{channelOption.name || <Trans>Unnamed channel</Trans>}</span>{parent?.name && (- <span- className={styles.categoryName}- data-flx="search.search.channel-filter-sheet.category-name"- >+ <span className={styles.subtitle} data-flx="search.search.channel-filter-sheet.category-name">{parent.name}</span>)}diff --git a/fluxer_app/src/features/search/components/search/ChannelFilterSheet.module.css b/fluxer_app/src/features/search/components/search/FilterSheet.module.csssimilarity index 91%rename from fluxer_app/src/features/search/components/search/ChannelFilterSheet.module.cssrename to fluxer_app/src/features/search/components/search/FilterSheet.module.cssindex d8267bde0..54d9446ce 100644--- a/fluxer_app/src/features/search/components/search/ChannelFilterSheet.module.css+++ b/fluxer_app/src/features/search/components/search/FilterSheet.module.css@@ -61,7 +61,7 @@padding: 0 1rem 2.5rem;}-.channelItem {+.item {display: flex;align-items: center;width: 100%;@@ -77,50 +77,54 @@user-select: none;}-.channelItem:active {+.item:active {background-color: var(--background-modifier-selected);}@media (hover: hover) and (pointer: fine) {- .channelItem:hover {+ .item:hover {background-color: var(--background-modifier-hover);}}-.channelItemSelected {+.itemSelected {background-color: color-mix(in srgb, var(--brand-primary-light) 10%, transparent);}-:global(.theme-light) .channelItemSelected {+:global(.theme-light) .itemSelected {background-color: color-mix(in srgb, var(--brand-primary) 10%, transparent);}@media (hover: hover) and (pointer: fine) {- .channelItemSelected:hover {+ .itemSelected:hover {background-color: color-mix(in srgb, var(--brand-primary-light) 15%, transparent);}- :global(.theme-light) .channelItemSelected:hover {+ :global(.theme-light) .itemSelected:hover {background-color: color-mix(in srgb, var(--brand-primary) 15%, transparent);}}+.avatar,.channelIcon {flex-shrink: 0;margin-inline-end: 0.75rem;+}++.channelIcon {height: 1.25rem;width: 1.25rem;color: var(--text-secondary);}-.channelInfo {+.info {flex: 1;display: flex;flex-direction: column;min-width: 0;}-.channelName {+.name {font-size: 0.9375rem;font-weight: 600;color: var(--text-primary);@@ -129,7 +133,7 @@text-overflow: ellipsis;}-.categoryName {+.subtitle {font-size: 0.8125rem;color: var(--text-secondary);white-space: nowrap;diff --git a/fluxer_app/src/features/search/components/search/UserFilterSheet.module.css b/fluxer_app/src/features/search/components/search/UserFilterSheet.module.cssdeleted file mode 100644index c68ee2344..000000000--- a/fluxer_app/src/features/search/components/search/UserFilterSheet.module.css+++ /dev/null@@ -1,158 +0,0 @@-/* SPDX-License-Identifier: AGPL-3.0-or-later */--.container {- display: flex;- flex-direction: column;- height: 100%;- overflow: hidden;- padding-top: 0.5rem;-}--.searchContainer {- padding: 0 1rem 0.75rem;-}--.searchInputWrapper {- display: flex;- align-items: center;- background-color: var(--background-tertiary);- border-radius: 0.5rem;- padding: 0.5rem 0.75rem;- gap: 0.5rem;-}--.searchIcon {- flex-shrink: 0;- color: var(--text-secondary);-}--.searchInput {- flex: 1;- border: none;- background: transparent;- color: var(--text-primary);- font-size: 1rem;- outline: none;- padding: 0;-}--.searchInput::placeholder {- color: var(--text-secondary);-}--.clearButton {- flex-shrink: 0;- display: flex;- align-items: center;- justify-content: center;- padding: 0.125rem;- border: none;- background: transparent;- color: var(--text-secondary);- cursor: pointer;-}--.scroller {- flex: 1;- overflow-y: auto;-}--.listContent {- padding: 0 1rem 2.5rem;-}--.userItem {- display: flex;- align-items: center;- width: 100%;- padding: 0.75rem;- border: none;- background: transparent;- border-radius: 0.75rem;- cursor: pointer;- transition: none;- text-align: start;- touch-action: manipulation;- -webkit-tap-highlight-color: transparent;- user-select: none;-}--.userItem:active {- background-color: var(--background-modifier-selected);-}--@media (hover: hover) and (pointer: fine) {- .userItem:hover {- background-color: var(--background-modifier-hover);- }-}--.userItemSelected {- background-color: color-mix(in srgb, var(--brand-primary-light) 10%, transparent);-}--:global(.theme-light) .userItemSelected {- background-color: color-mix(in srgb, var(--brand-primary) 10%, transparent);-}--@media (hover: hover) and (pointer: fine) {- .userItemSelected:hover {- background-color: color-mix(in srgb, var(--brand-primary-light) 15%, transparent);- }-- :global(.theme-light) .userItemSelected:hover {- background-color: color-mix(in srgb, var(--brand-primary) 15%, transparent);- }-}--.avatar {- flex-shrink: 0;- margin-inline-end: 0.75rem;-}--.userInfo {- flex: 1;- display: flex;- flex-direction: column;- min-width: 0;-}--.displayName {- font-size: 0.9375rem;- font-weight: 600;- color: var(--text-primary);- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;-}--.username {- font-size: 0.8125rem;- color: var(--text-secondary);- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;-}--.checkIcon {- flex-shrink: 0;- color: var(--brand-primary-light);-}--:global(.theme-light) .checkIcon {- color: var(--brand-primary-foreground);-}--.emptyState {- padding: 2.5rem 1rem;- text-align: center;- font-size: 1rem;- color: var(--text-secondary);-}--.footer {- display: flex;- justify-content: flex-end;- padding: 0.75rem 1rem;- border-top: 0.0625rem solid var(--border-color);-}diff --git a/fluxer_app/src/features/search/components/search/UserFilterSheet.tsx b/fluxer_app/src/features/search/components/search/UserFilterSheet.tsxindex 2445cc6c3..2032e2935 100644--- a/fluxer_app/src/features/search/components/search/UserFilterSheet.tsx+++ b/fluxer_app/src/features/search/components/search/UserFilterSheet.tsx@@ -4,7 +4,7 @@ import type {Channel} from '@app/features/channel/models/Channel';import Guilds from '@app/features/guild/state/Guilds';import GuildMembers from '@app/features/member/state/GuildMembers';import {PASSWORD_MANAGER_IGNORE_ATTRIBUTES} from '@app/features/platform/utils/PasswordManagerAutocomplete';-import styles from '@app/features/search/components/search/UserFilterSheet.module.css';+import styles from '@app/features/search/components/search/FilterSheet.module.css';import {remFromPx} from '@app/features/theme/layout/RemFromPx';import {BottomSheet} from '@app/features/ui/bottom_sheet/BottomSheet';import {Button} from '@app/features/ui/button/Button';@@ -147,7 +147,7 @@ export const UserFilterSheet: React.FC<UserFilterSheetProps> = observer(key={user.id}type="button"aria-pressed={isSelected}- className={clsx(styles.userItem, isSelected && styles.userItemSelected)}+ className={clsx(styles.item, isSelected && styles.itemSelected)}onClick={() => toggleUser(user.id)}data-flx="search.search.user-filter-sheet.user-item.toggle-user.button">@@ -159,11 +159,11 @@ export const UserFilterSheet: React.FC<UserFilterSheetProps> = observer(className={styles.avatar}data-flx="search.search.user-filter-sheet.avatar"/>- <div className={styles.userInfo} data-flx="search.search.user-filter-sheet.user-info">- <span className={styles.displayName} data-flx="search.search.user-filter-sheet.display-name">+ <div className={styles.info} data-flx="search.search.user-filter-sheet.user-info">+ <span className={styles.name} data-flx="search.search.user-filter-sheet.display-name">{displayName}</span>- <span className={styles.username} data-flx="search.search.user-filter-sheet.username">+ <span className={styles.subtitle} data-flx="search.search.user-filter-sheet.username">{NicknameUtils.formatUserTagForStreamerMode(user)}</span></div>diff --git a/fluxer_app/src/features/ui/components/form/FormInput.tsx b/fluxer_app/src/features/ui/components/form/FormInput.tsxindex 8fb3d883e..0b29fc3a9 100644--- a/fluxer_app/src/features/ui/components/form/FormInput.tsx+++ b/fluxer_app/src/features/ui/components/form/FormInput.tsx@@ -453,72 +453,29 @@ export const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(const labelRight = useMemo(() => (<div className={styles.labelContainerWithGap} data-flx="ui.form.input.label-right.label-container-with-gap">- {!innerActionButton && characterCounter}+ {characterCounter}{actionButton}</div>),- [innerActionButton, characterCounter, actionButton],+ [characterCounter, actionButton],);- const textareaWithActions = useMemo(- () =>- innerActionButton ? (- <div- ref={textareaWrapperRef}- className={clsx(styles.textareaWrapper, surfaceStyles.surface, error ? styles.error : styles.focusable)}- data-flx="ui.form.input.textarea-with-actions.textarea-wrapper"- >- <TextareaAutosize- data-flx="ui.form.input.textarea-with-actions.textarea"- {...textareaProps}- className={clsx(scrollerStyles.scroller, scrollerStyles.scrollerTextarea, styles.textarea)}- ref={setTextareaRefs}- />- <div className={styles.textareaActions} data-flx="ui.form.input.textarea-with-actions.textarea-actions">- {innerActionButton}- {showCharacterCount && maxLength && (- <div- className={styles.characterCountContainer}- data-flx="ui.form.input.textarea-with-actions.character-count-container"- >- {characterCountTooltip ? (- characterCountTooltip(maxLength - currentLength, maxLength, currentLength)- ) : (- <>- <span- className={styles.characterCount}- aria-hidden="true"- data-flx="ui.form.input.textarea-with-actions.character-count"- >- {numberFormat.format(currentLength)}/{numberFormat.format(maxLength)}- </span>- <CharacterCountAnnouncer- currentLength={currentLength}- maxLength={maxLength}- data-flx="ui.form.form-input.textarea-with-actions.character-count-announcer"- />- </>- )}- </div>- )}- </div>- </div>- ) : null,- [- innerActionButton,- textareaWrapperRef,- error,- textareaProps,- setTextareaRefs,- showCharacterCount,- maxLength,- characterCountTooltip,- currentLength,- numberFormat,- ],- );- const simpleTextarea = useMemo(- () =>- !innerActionButton ? (+ return (+ <FieldSet+ error={error}+ errorId={errorId}+ footer={footer}+ label={label}+ labelRight={labelRight}+ htmlFor={textareaId}+ data-flx="ui.form.input.textarea.field-set"+ >+ <FocusRing+ focusTarget={textareaRef}+ ringTarget={textareaRef}+ offset={-2}+ enabled={!disabled}+ data-flx="ui.form.input.textarea.focus-ring"+ ><BaseTextareadata-flx="ui.form.input.simple-textarea.error"{...textareaProps}diff --git a/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.ts b/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.tsindex 1b77f0f31..f7b3a4528 100644--- a/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.ts+++ b/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.ts@@ -4,17 +4,14 @@ export const WINDOW_FOCUSED_CLASS = 'window-focused';export const WINDOW_FOCUS_ACTIVATION_GUARD_CLASS = 'window-focus-activation-guard';export const UNFOCUSED_FULLY_INTERACTIVE_CLASS = 'unfocused-fully-interactive';export const WINDOW_HOVER_CONTROLS_CHANGE_EVENT = 'fluxer-window-hover-controls-change';-const DEFAULT_GUARD_TIMEOUT_MS = 250;-const DEFAULT_RELEASE_CLEAR_DELAY_MS = 50;-const DEFAULT_MAX_GUARD_TIMEOUT_MS = 5000;+const GUARD_TIMEOUT_MS = 250;+const RELEASE_CLEAR_DELAY_MS = 50;+const MAX_GUARD_TIMEOUT_MS = 5000;interface WindowFocusInteractionGuardOptions {root?: HTMLElement;windowTarget?: Window;initiallyFocused?: boolean;- guardTimeoutMs?: number;- releaseClearDelayMs?: number;- maxGuardTimeoutMs?: number;}export interface WindowFocusInteractionGuard {@@ -47,9 +44,6 @@ export function createWindowFocusInteractionGuard({root = document.documentElement,windowTarget = window,initiallyFocused = root.classList.contains(WINDOW_FOCUSED_CLASS),- guardTimeoutMs = DEFAULT_GUARD_TIMEOUT_MS,- releaseClearDelayMs = DEFAULT_RELEASE_CLEAR_DELAY_MS,- maxGuardTimeoutMs = DEFAULT_MAX_GUARD_TIMEOUT_MS,}: WindowFocusInteractionGuardOptions = {}): WindowFocusInteractionGuard {let focused = initiallyFocused;let wasBlurred = !initiallyFocused;@@ -94,7 +88,7 @@ export function createWindowFocusInteractionGuard({if (!activationPointerInProgress) {clearActivationGuard();}- }, guardTimeoutMs);+ }, GUARD_TIMEOUT_MS);};const beginActivationGuard = (pointerInProgress: boolean) => {clearReleaseTimer();@@ -108,7 +102,7 @@ export function createWindowFocusInteractionGuard({maxGuardTimer = windowTarget.setTimeout(() => {maxGuardTimer = null;clearActivationGuard();- }, maxGuardTimeoutMs);+ }, MAX_GUARD_TIMEOUT_MS);}};const scheduleClearAfterActivationClick = () => {@@ -119,7 +113,7 @@ export function createWindowFocusInteractionGuard({releaseTimer = windowTarget.setTimeout(() => {releaseTimer = null;clearActivationGuard();- }, releaseClearDelayMs);+ }, RELEASE_CLEAR_DELAY_MS);};const handlePointerStart: EventListener = () => {if (wasBlurred || !focused || isWindowFocusActivationGuardActive(root)) {diff --git a/fluxer_app/src/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine.ts b/fluxer_app/src/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine.tsindex 599148b5d..64c064446 100644--- a/fluxer_app/src/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine.ts+++ b/fluxer_app/src/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine.ts@@ -196,28 +196,19 @@ const profileAssetCustomizationStateMachine = setup({id: 'profileAssetCustomization',context: () => createContext(),initial: 'unhydrated',+ on: {+ 'asset.remoteApplied': {target: '.clean', actions: 'applyRemote'},+ 'asset.committed': {target: '.committed', actions: 'commitRemote'},+ 'asset.modeSelected': {target: '.routing', actions: 'selectMode'},+ 'asset.uploaded': {target: '.routing', actions: 'applyUpload'},+ 'asset.cleared': {target: '.routing', actions: 'clearAsset'},+ },states: {- unhydrated: {- on: {- 'asset.remoteApplied': {target: 'clean', actions: 'applyRemote'},- 'asset.committed': {target: 'committed', actions: 'commitRemote'},- 'asset.modeSelected': {target: 'routing', actions: 'selectMode'},- 'asset.uploaded': {target: 'routing', actions: 'applyUpload'},- 'asset.cleared': {target: 'routing', actions: 'clearAsset'},- },- },+ unhydrated: {},routing: {always: [{guard: 'isDirty', target: 'dirty'}, {target: 'clean'}],},- clean: {- on: {- 'asset.remoteApplied': {target: 'clean', actions: 'applyRemote'},- 'asset.committed': {target: 'committed', actions: 'commitRemote'},- 'asset.modeSelected': {target: 'routing', actions: 'selectMode'},- 'asset.uploaded': {target: 'routing', actions: 'applyUpload'},- 'asset.cleared': {target: 'routing', actions: 'clearAsset'},- },- },+ clean: {},dirty: {on: {'asset.remoteApplied': [diff --git a/fluxer_app/src/features/voice/components/ActiveScreenShareMenu.tsx b/fluxer_app/src/features/voice/components/ActiveScreenShareMenu.tsxindex e1228155d..aa401c7d2 100644--- a/fluxer_app/src/features/voice/components/ActiveScreenShareMenu.tsx+++ b/fluxer_app/src/features/voice/components/ActiveScreenShareMenu.tsx@@ -34,7 +34,6 @@ export interface ActiveScreenShareMenuProps {shareContext: StreamSettingsShareContext;shareContextResolved: boolean;iconClassName?: string;- additionalActions?: React.ReactNode;tail?: React.ReactNode;}@@ -58,7 +57,6 @@ export const ActiveScreenShareMenu: React.FC<ActiveScreenShareMenuProps> = ({shareContext,shareContextResolved,iconClassName,- additionalActions,tail,}) => {const {i18n} = useLingui();@@ -106,7 +104,6 @@ export const ActiveScreenShareMenu: React.FC<ActiveScreenShareMenuProps> = ({>{i18n._(CHANGE_STREAM_DESCRIPTOR)}</MenuItem>- {additionalActions}{!isWeb && (<StreamSettingsMenuContentapplyToLiveStreamdiff --git a/fluxer_app/src/features/voice/components/StreamInfoPill.tsx b/fluxer_app/src/features/voice/components/StreamInfoPill.tsxindex 638b16f8a..36ba2ac0a 100644--- a/fluxer_app/src/features/voice/components/StreamInfoPill.tsx+++ b/fluxer_app/src/features/voice/components/StreamInfoPill.tsx@@ -1,7 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {LiveBadge} from '@app/features/ui/components/LiveBadge';-import type {TooltipPosition} from '@app/features/ui/tooltip/Tooltip';import styles from '@app/features/voice/components/StreamInfoPill.module.css';import type {StreamTrackInfo} from '@app/features/voice/components/useStreamTrackInfo';import type {ScreenShareTarget} from '@app/features/voice/utils/ScreenShareOptions';@@ -52,16 +51,9 @@ interface StreamInfoPillProps {className?: string;showLiveBadge?: boolean;tone?: StreamInfoPillTone;- liveBadgeTooltipPosition?: TooltipPosition;}-export function StreamInfoPill({- info,- className,- showLiveBadge = true,- tone = 'default',- liveBadgeTooltipPosition,-}: StreamInfoPillProps) {+export function StreamInfoPill({info, className, showLiveBadge = true, tone = 'default'}: StreamInfoPillProps) {const {i18n} = useLingui();const labelText = useMemo(() => {if ('target' in info) {@@ -85,13 +77,7 @@ export function StreamInfoPill({>{labelText}</span>- {showLiveBadge && (- <LiveBadge- tone={tone}- tooltipPosition={liveBadgeTooltipPosition}- data-flx="voice.stream-info-pill.live-badge"- />- )}+ {showLiveBadge && <LiveBadge tone={tone} data-flx="voice.stream-info-pill.live-badge" />}</div>);}diff --git a/fluxer_app/src/features/voice/components/StreamWatchHoverCard.tsx b/fluxer_app/src/features/voice/components/StreamWatchHoverCard.tsxindex d639dd27c..edc6cbb55 100644--- a/fluxer_app/src/features/voice/components/StreamWatchHoverCard.tsx+++ b/fluxer_app/src/features/voice/components/StreamWatchHoverCard.tsx@@ -5,15 +5,11 @@ import {isKeyboardActivationKey} from '@app/features/input/utils/KeyboardUtils';import {remFromPx} from '@app/features/theme/layout/RemFromPx';import {Button} from '@app/features/ui/button/Button';import {Spinner} from '@app/features/ui/components/Spinner';-import {Tooltip} from '@app/features/ui/tooltip/Tooltip';import styles from '@app/features/voice/components/StreamWatchHoverCard.module.css';-import {- ADD_STREAM_DESCRIPTOR,- WATCHING_STREAM_DESCRIPTOR,-} from '@app/features/voice/utils/VoiceSharedMessageDescriptors';+import {WATCHING_STREAM_DESCRIPTOR} from '@app/features/voice/utils/VoiceSharedMessageDescriptors';import {msg} from '@lingui/core/macro';import {useLingui} from '@lingui/react/macro';-import {MonitorPlayIcon, PlusIcon} from '@phosphor-icons/react';+import {MonitorPlayIcon} from '@phosphor-icons/react';import {clsx} from 'clsx';import type React from 'react';import {useCallback} from 'react';@@ -36,34 +32,26 @@ interface StreamWatchHoverCardProps {previewUrl: string | null;isPreviewLoading: boolean;watchLabel: string;- addLabel?: string;onWatch: (event: React.SyntheticEvent) => void;- onAddStream?: (event: React.SyntheticEvent) => void;onPreviewClick?: (event: React.MouseEvent) => void;watchDisabled?: boolean;isWatching?: boolean;isSubmitting?: boolean;variant?: 'compact' | 'list';showProtip?: boolean;- showAddButton?: boolean;- addTooltip?: string;}export const StreamWatchHoverCard: React.FC<StreamWatchHoverCardProps> = ({previewUrl,isPreviewLoading,watchLabel,- addLabel,onWatch,- onAddStream,onPreviewClick,watchDisabled = false,isWatching = false,isSubmitting = false,variant = 'list',showProtip = false,- showAddButton = false,- addTooltip,}) => {const {i18n} = useLingui();const isCompact = variant === 'compact';@@ -178,20 +166,6 @@ export const StreamWatchHoverCard: React.FC<StreamWatchHoverCardProps> = ({>{watchLabel}</Button>- {showAddButton && onAddStream && (- <Tooltip text={addTooltip ?? ''} data-flx="voice.stream-watch-hover-card.tooltip">- <Button- fitContent- leftIcon={<PlusIcon size={remFromPx(18)} data-flx="voice.stream-watch-hover-card.plus-icon" />}- onClick={onAddStream}- disabled={watchDisabled}- className={styles.listButton}- data-flx="voice.stream-watch-hover-card.list-button.add-stream"- >- {addLabel ?? i18n._(ADD_STREAM_DESCRIPTOR)}- </Button>- </Tooltip>- )}</div>{showProtip && (<div className={styles.protipRow} data-flx="voice.stream-watch-hover-card.protip-row">diff --git a/fluxer_app/src/features/voice/components/VoiceCallLayoutPresentationStateMachine.ts b/fluxer_app/src/features/voice/components/VoiceCallLayoutPresentationStateMachine.tsindex 88df828ce..af1041aef 100644--- a/fluxer_app/src/features/voice/components/VoiceCallLayoutPresentationStateMachine.ts+++ b/fluxer_app/src/features/voice/components/VoiceCallLayoutPresentationStateMachine.ts@@ -140,6 +140,11 @@ const voiceCallLayoutPresentationStateMachine = setup({id: 'voiceCallLayoutPresentation',context: ({input}) => createVoiceCallLayoutPresentationContext(input),initial: 'routing',+ on: {+ 'presentation.update': {target: '.routing', actions: 'applyInput'},+ 'participants.toggle': {target: '.routing', actions: 'toggleParticipantsGrid'},+ 'participants.collapse': {target: '.routing', actions: 'collapseParticipantsGrid'},+ },states: {routing: {always: [@@ -149,34 +154,10 @@ const voiceCallLayoutPresentationStateMachine = setup({{target: 'focusLayout'},],},- gridLayout: {- on: {- 'presentation.update': {target: 'routing', actions: 'applyInput'},- 'participants.toggle': {target: 'routing', actions: 'toggleParticipantsGrid'},- 'participants.collapse': {target: 'routing', actions: 'collapseParticipantsGrid'},- },- },- focusFallbackGrid: {- on: {- 'presentation.update': {target: 'routing', actions: 'applyInput'},- 'participants.toggle': {target: 'routing', actions: 'toggleParticipantsGrid'},- 'participants.collapse': {target: 'routing', actions: 'collapseParticipantsGrid'},- },- },- focusLayout: {- on: {- 'presentation.update': {target: 'routing', actions: 'applyInput'},- 'participants.toggle': {target: 'routing', actions: 'toggleParticipantsGrid'},- 'participants.collapse': {target: 'routing', actions: 'collapseParticipantsGrid'},- },- },- focusParticipantsExpanded: {- on: {- 'presentation.update': {target: 'routing', actions: 'applyInput'},- 'participants.toggle': {target: 'routing', actions: 'toggleParticipantsGrid'},- 'participants.collapse': {target: 'routing', actions: 'collapseParticipantsGrid'},- },- },+ gridLayout: {},+ focusFallbackGrid: {},+ focusLayout: {},+ focusParticipantsExpanded: {},},});diff --git a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds.ts b/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds.tsindex 33c3fe5b1..a27047697 100644--- a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds.ts+++ b/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds.ts@@ -7,46 +7,23 @@ import {} from '@app/features/voice/state/CompactVoiceCallHeight';export const COMPACT_HEIGHT_MIN = COMPACT_VOICE_CALL_HEIGHT_MIN;-const COMPACT_HEIGHT_VIEWPORT_MARGIN = 32;const COMPACT_HEIGHT_CHAT_AREA_RESERVATION = 220;export const COMPACT_HEIGHT_MESSAGES_SLIVER = 56;-function resolveCompactHeightMax({- compactHeightMin,- viewportHeight,- chatAreaReservation = COMPACT_HEIGHT_CHAT_AREA_RESERVATION,- viewportMargin = COMPACT_HEIGHT_VIEWPORT_MARGIN,- hardCap = COMPACT_VOICE_CALL_HEIGHT_MAX,-}: {- compactHeightMin: number;- viewportHeight: number;- chatAreaReservation?: number;- viewportMargin?: number;- hardCap?: number;-}): number {- const reservation = Math.max(viewportMargin, chatAreaReservation);- const viewportLimitedMax = Math.round(viewportHeight - reservation);- return Math.max(compactHeightMin, Math.min(viewportLimitedMax, hardCap));-}-export function getCompactHeightMax(compactHeightMin: number): number {- return resolveCompactHeightMax({- compactHeightMin,- viewportHeight: appZoomLayoutPx(window.innerHeight),- });+ const viewportLimitedMax = Math.round(appZoomLayoutPx(window.innerHeight) - COMPACT_HEIGHT_CHAT_AREA_RESERVATION);+ return Math.max(compactHeightMin, Math.min(viewportLimitedMax, COMPACT_VOICE_CALL_HEIGHT_MAX));}export function resolveCompactHeightMaxFromLayout({compactHeightMin,availableSpan,chatReservation,- hardCap = COMPACT_VOICE_CALL_HEIGHT_MAX,}: {compactHeightMin: number;availableSpan: number;chatReservation: number;- hardCap?: number;}): number {const limited = Math.round(availableSpan - chatReservation);- return Math.max(compactHeightMin, Math.min(limited, hardCap));+ return Math.max(compactHeightMin, Math.min(limited, COMPACT_VOICE_CALL_HEIGHT_MAX));}diff --git a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaFullscreen.ts b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaFullscreen.tsindex a98925bd7..e2ea2d3c2 100644--- a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaFullscreen.ts+++ b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaFullscreen.ts@@ -1,11 +1,5 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {- getExtendedDocument,- supportsMozRequestFullScreen,- supportsMsRequestFullscreen,- supportsWebkitRequestFullscreen,-} from '@app/features/platform/types/Browser';import {Logger} from '@app/features/platform/utils/AppLogger';import {getFullscreenElement} from '@app/features/platform/utils/FullscreenMediaUtils';import type {ExtendedHTMLElement, ExtendedHTMLVideoElement} from '@app/types/browser.d';@@ -16,7 +10,6 @@ const logger = new Logger('useMediaFullscreen');export interface UseMediaFullscreenOptions {containerRef: React.RefObject<HTMLElement | null> | React.RefObject<HTMLElement>;videoRef?: React.RefObject<HTMLVideoElement | null>;- onFullscreenChange?: (isFullscreen: boolean) => void;}export interface UseMediaFullscreenReturn {@@ -27,58 +20,20 @@ export interface UseMediaFullscreenReturn {toggleFullscreen: () => Promise<void>;}-function supportsContainerFullscreenAPI(): boolean {- const doc = getExtendedDocument();- return !!(- document.fullscreenEnabled ||- doc.webkitFullscreenEnabled ||- doc.mozFullScreenEnabled ||- doc.msFullscreenEnabled- );-}-function supportsIOSVideoFullscreen(videoElement: HTMLVideoElement | null): boolean {if (!videoElement) return false;const extendedVideo = videoElement as ExtendedHTMLVideoElement;return !!(extendedVideo.webkitSupportsFullscreen || extendedVideo.webkitEnterFullscreen);}-async function requestFullscreen(element: HTMLElement): Promise<void> {- if (element.requestFullscreen) {- await element.requestFullscreen();- } else if (supportsWebkitRequestFullscreen(element)) {- const extendedElement = element as ExtendedHTMLElement;- await extendedElement.webkitRequestFullscreen!();- } else if (supportsMozRequestFullScreen(element)) {- const extendedElement = element as ExtendedHTMLElement;- await extendedElement.mozRequestFullScreen!();- } else if (supportsMsRequestFullscreen(element)) {- const extendedElement = element as ExtendedHTMLElement;- await extendedElement.msRequestFullscreen!();- }-}--async function exitFullscreenAPI(): Promise<void> {- const doc = getExtendedDocument();- if (document.exitFullscreen) {- await document.exitFullscreen();- } else if (doc.webkitExitFullscreen) {- await doc.webkitExitFullscreen();- } else if (doc.mozCancelFullScreen) {- await doc.mozCancelFullScreen();- } else if (doc.msExitFullscreen) {- await doc.msExitFullscreen();- }-}-export function useMediaFullscreen(options: UseMediaFullscreenOptions): UseMediaFullscreenReturn {- const {containerRef, videoRef, onFullscreenChange} = options;+ const {containerRef, videoRef} = options;const [isFullscreen, setIsFullscreen] = useState(false);- const [supportsFullscreen, setSupportsFullscreen] = useState(() => supportsContainerFullscreenAPI());+ const [supportsFullscreen, setSupportsFullscreen] = useState(() => supportsFullscreenAPI());const [useIOSFullscreen, setUseIOSFullscreen] = useState(false);const claimedFullscreenHostRef = useRef<Element | null>(null);useEffect(() => {- const hasContainerSupport = supportsContainerFullscreenAPI();+ const hasContainerSupport = supportsFullscreenAPI();const hasIOSSupport = supportsIOSVideoFullscreen(videoRef?.current ?? null);setSupportsFullscreen(hasContainerSupport || hasIOSSupport);setUseIOSFullscreen(!hasContainerSupport && hasIOSSupport);@@ -89,14 +44,11 @@ export function useMediaFullscreen(options: UseMediaFullscreenOptions): UseMediaconst isNowFullscreen = fullscreenElement === containerRef.current;claimedFullscreenHostRef.current = isNowFullscreen ? fullscreenElement : null;setIsFullscreen(isNowFullscreen);- onFullscreenChange?.(isNowFullscreen);};const handleIOSFullscreenChange = () => {const video = videoRef?.current as ExtendedHTMLVideoElement | null;if (video) {- const isNowFullscreen = video.webkitDisplayingFullscreen ?? false;- setIsFullscreen(isNowFullscreen);- onFullscreenChange?.(isNowFullscreen);+ setIsFullscreen(video.webkitDisplayingFullscreen ?? false);}};document.addEventListener('fullscreenchange', handleFullscreenChange);@@ -118,7 +70,7 @@ export function useMediaFullscreen(options: UseMediaFullscreenOptions): UseMediavideo.removeEventListener('webkitendfullscreen', handleIOSFullscreenChange);}};- }, [containerRef, videoRef, onFullscreenChange]);+ }, [containerRef, videoRef]);useEffect(() => {return () => {const claimedHost = claimedFullscreenHostRef.current;@@ -142,7 +94,7 @@ export function useMediaFullscreen(options: UseMediaFullscreenOptions): UseMedia}}const container = containerRef.current;- if (!container || !supportsContainerFullscreenAPI()) return;+ if (!container || !supportsFullscreenAPI()) return;try {await requestFullscreen(container);} catch (error) {diff --git a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaKeyboard.ts b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaKeyboard.tsindex dc5bbe85a..845fc8ab3 100644--- a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaKeyboard.ts+++ b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaKeyboard.ts@@ -162,7 +162,7 @@ export function useMediaKeyboard(options: UseMediaKeyboardOptions): UseMediaKeybreturn true;} else if (keyMatches(key, SEEK_BACKWARD_KEYS)) {event.preventDefault();- onSeekBackward?.(seekAmount);+ onSeekBackward?.(SEEK_STEP);return true;} else if (key === 'ArrowLeft') {event.preventDefault();@@ -170,7 +170,7 @@ export function useMediaKeyboard(options: UseMediaKeyboardOptions): UseMediaKeybreturn true;} else if (keyMatches(key, SEEK_FORWARD_KEYS)) {event.preventDefault();- onSeekForward?.(seekAmount);+ onSeekForward?.(SEEK_STEP);return true;} else if (key === 'ArrowRight') {event.preventDefault();@@ -178,11 +178,11 @@ export function useMediaKeyboard(options: UseMediaKeyboardOptions): UseMediaKeybreturn true;} else if (keyMatches(key, VOLUME_UP_KEYS)) {event.preventDefault();- onVolumeUp?.(volumeStep);+ onVolumeUp?.(VOLUME_STEP);return true;} else if (keyMatches(key, VOLUME_DOWN_KEYS)) {event.preventDefault();- onVolumeDown?.(volumeStep);+ onVolumeDown?.(VOLUME_STEP);return true;} else if (keyMatches(key, MUTE_KEYS)) {event.preventDefault();diff --git a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPiP.ts b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPiP.tsindex 9e135169c..550599b02 100644--- a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPiP.ts+++ b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPiP.ts@@ -8,7 +8,6 @@ const logger = new Logger('useMediaPiP');export interface UseMediaPiPOptions {videoRef: React.RefObject<HTMLVideoElement | null> | React.RefObject<HTMLVideoElement>;- onPiPChange?: (isPiP: boolean) => void;}export interface UseMediaPiPReturn {@@ -20,7 +19,7 @@ export interface UseMediaPiPReturn {}export function useMediaPiP(options: UseMediaPiPOptions): UseMediaPiPReturn {- const {videoRef, onPiPChange} = options;+ const {videoRef} = options;const [isPiP, setIsPiP] = useState(false);const [supportsPiP] = useState(() => {if (!document.pictureInPictureEnabled) return false;@@ -29,14 +28,8 @@ export function useMediaPiP(options: UseMediaPiPOptions): UseMediaPiPReturn {useEffect(() => {const video = videoRef.current;if (!video) return;- const handleEnterPiP = () => {- setIsPiP(true);- onPiPChange?.(true);- };- const handleLeavePiP = () => {- setIsPiP(false);- onPiPChange?.(false);- };+ const handleEnterPiP = () => setIsPiP(true);+ const handleLeavePiP = () => setIsPiP(false);video.addEventListener('enterpictureinpicture', handleEnterPiP);video.addEventListener('leavepictureinpicture', handleLeavePiP);if (document.pictureInPictureElement === video) {@@ -46,7 +39,7 @@ export function useMediaPiP(options: UseMediaPiPOptions): UseMediaPiPReturn {video.removeEventListener('enterpictureinpicture', handleEnterPiP);video.removeEventListener('leavepictureinpicture', handleLeavePiP);};- }, [videoRef, onPiPChange]);+ }, [videoRef]);const enterPiP = useCallback(async () => {const video = videoRef.current;if (!video || !supportsPiP) return;diff --git a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPlayer.ts b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPlayer.tsindex 64b8f0a8f..e4db6a8f8 100644--- a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPlayer.ts+++ b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaPlayer.ts@@ -39,13 +39,10 @@ export interface UseMediaPlayerOptions {mediaKind?: MediaPlaybackKind;autoPlay?: boolean;loop?: boolean;- initialPlaybackRate?: number;persistPlaybackRate?: boolean;onEnded?: () => void;onError?: (error: Error, code: MediaFailureCode) => void;onPlay?: () => void;- onPause?: () => void;- onTimeUpdate?: (currentTime: number) => void;onLoadedMetadata?: (duration: number, media: HTMLMediaElement) => void;}@@ -106,19 +103,16 @@ export function useMediaPlayer(options: UseMediaPlayerOptions = {}): UseMediaPlamediaKind = 'video',autoPlay = false,loop = false,- initialPlaybackRate,persistPlaybackRate = true,onEnded,onError,onPlay,- onPause,- onTimeUpdate,onLoadedMetadata,} = options;const mediaRef = useRef<HTMLMediaElement | null>(null);useInAppMediaSoundCapture(mediaRef);- const callbacksRef = useRef({onEnded, onError, onPlay, onPause, onTimeUpdate, onLoadedMetadata});- callbacksRef.current = {onEnded, onError, onPlay, onPause, onTimeUpdate, onLoadedMetadata};+ const callbacksRef = useRef({onEnded, onError, onPlay, onLoadedMetadata});+ callbacksRef.current = {onEnded, onError, onPlay, onLoadedMetadata};const initialElementSettingsRef = useRef({loop});const [state, setState] = useState<MediaPlayerState>(() => ({isPlaying: false,@@ -128,7 +122,7 @@ export function useMediaPlayer(options: UseMediaPlayerOptions = {}): UseMediaPlaisSeeking: false,currentTime: 0,duration: 0,- playbackRate: initialPlaybackRate ?? (persistPlaybackRate ? getStoredPlaybackRate(mediaKind) : 1),+ playbackRate: persistPlaybackRate ? getStoredPlaybackRate(mediaKind) : 1,error: null,failureCode: null,}));@@ -162,7 +156,6 @@ export function useMediaPlayer(options: UseMediaPlayerOptions = {}): UseMediaPlaisPlaying: false,isPaused: true,}));- callbacksRef.current.onPause?.();};const handleEnded = () => {clearPendingSeekTarget(media);@@ -179,7 +172,6 @@ export function useMediaPlayer(options: UseMediaPlayerOptions = {}): UseMediaPlaconst handleTimeUpdate = () => {const currentTime = quantiseMediaTimeToSecond(media.currentTime);setState((prev) => (prev.currentTime === currentTime ? prev : {...prev, currentTime}));- callbacksRef.current.onTimeUpdate?.(media.currentTime);};const publishDuration = () => {const duration = Number.isFinite(media.duration) ? media.duration : 0;diff --git a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaVolume.ts b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaVolume.tsindex 1354c43d0..b19206fd5 100644--- a/fluxer_app/src/features/voice/components/media_player/hooks/useMediaVolume.ts+++ b/fluxer_app/src/features/voice/components/media_player/hooks/useMediaVolume.ts@@ -25,11 +25,8 @@ function volumeSettingFromMediaGain(gain: number): number {interface UseMediaVolumeOptions {mediaRef: React.RefObject<HTMLMediaElement | null>;- initialVolume?: number;- initialMuted?: boolean;persist?: boolean;onVolumeChange?: (volume: number) => void;- onMuteChange?: (muted: boolean) => void;}export interface UseMediaVolumeReturn {@@ -110,34 +107,29 @@ function publishStoredVolumeSetting(next: StoredVolumeSetting): void {}export function useMediaVolume(options: UseMediaVolumeOptions): UseMediaVolumeReturn {- const {mediaRef, initialVolume, initialMuted, persist = true, onVolumeChange, onMuteChange} = options;- const tracksSharedSetting = persist && initialVolume === undefined && initialMuted === undefined;+ const {mediaRef, persist = true, onVolumeChange} = options;const sharedSetting = useSyncExternalStore(subscribeStoredVolumeSetting,readStoredVolumeSetting,readStoredVolumeSetting,);- const [ownVolume, setOwnVolume] = useState(() => initialVolume ?? (persist ? getStoredVolume() : DEFAULT_VOLUME));- const [ownMuted, setOwnMuted] = useState(() => initialMuted ?? (persist ? getStoredMuted() : false));- const volume = tracksSharedSetting ? sharedSetting.volume : ownVolume;- const isMuted = tracksSharedSetting ? sharedSetting.muted : ownMuted;+ const [ownVolume, setOwnVolume] = useState(() => (persist ? getStoredVolume() : DEFAULT_VOLUME));+ const [ownMuted, setOwnMuted] = useState(() => (persist ? getStoredMuted() : false));+ const volume = persist ? sharedSetting.volume : ownVolume;+ const isMuted = persist ? sharedSetting.muted : ownMuted;const previousVolumeRef = useRef(volume > 0 ? volume : DEFAULT_VOLUME);const settingRef = useRef({volume, isMuted});settingRef.current = {volume, isMuted};const commitSetting = useCallback((nextVolume: number, nextMuted: boolean) => {- if (tracksSharedSetting) {+ if (persist) {publishStoredVolumeSetting({volume: nextVolume, muted: nextMuted});return;}setOwnVolume(nextVolume);setOwnMuted(nextMuted);- if (persist) {- storeVolume(nextVolume);- storeMuted(nextMuted);- }},- [persist, tracksSharedSetting],+ [persist],);useEffect(() => {const media = mediaRef.current;@@ -172,9 +164,8 @@ export function useMediaVolume(options: UseMediaVolumeOptions): UseMediaVolumeRemedia.volume = mediaGainFromVolumeSetting(nextVolume);}commitSetting(nextVolume, muted);- onMuteChange?.(muted);},- [mediaRef, commitSetting, onMuteChange],+ [mediaRef, commitSetting],);const setVolume = useCallback((newVolume: number) => {diff --git a/fluxer_app/src/features/voice/components/media_player/utils/MediaSeekUtils.ts b/fluxer_app/src/features/voice/components/media_player/utils/MediaSeekUtils.tsindex 419ff6226..850e17ade 100644--- a/fluxer_app/src/features/voice/components/media_player/utils/MediaSeekUtils.ts+++ b/fluxer_app/src/features/voice/components/media_player/utils/MediaSeekUtils.ts@@ -155,14 +155,10 @@ export function detachMediaElementSource(media: HTMLMediaElement | null | undefiexport function resolveDoubleTapSeekDirection(previousTap: SeekTapPoint | null,currentTap: SeekTapPoint,- options: {- maxIntervalMs?: number;- sideZoneRatio?: number;- } = {},): SeekDirection | null {- const {maxIntervalMs = 360, sideZoneRatio = 0.42} = options;+ const sideZoneRatio = 0.42;if (!previousTap) return null;- if (currentTap.time - previousTap.time > maxIntervalMs) return null;+ if (currentTap.time - previousTap.time > 360) return null;if (currentTap.width <= 0 || previousTap.width <= 0) return null;const currentRatio = currentTap.x / currentTap.width;diff --git a/fluxer_app/src/features/voice/components/modals/CameraPreviewModal.tsx b/fluxer_app/src/features/voice/components/modals/CameraPreviewModal.tsxindex ab8b4a581..0bea2831b 100644--- a/fluxer_app/src/features/voice/components/modals/CameraPreviewModal.tsx+++ b/fluxer_app/src/features/voice/components/modals/CameraPreviewModal.tsx@@ -394,7 +394,7 @@ const CameraEffectStrengthSlider = ({label, value, onChange, resetLabel, dataFlxconst CameraPreviewModalContent = observer((props: CameraPreviewModalProps) => {const {i18n} = useLingui();useMediaEngineVersion();- const {localParticipant, onEnabled, onEnableCamera, isCameraEnabled, showEnableCameraButton = true} = props;+ const {localParticipant, onEnableCamera, isCameraEnabled, showEnableCameraButton = true} = props;const cameraAlreadyOn = isCameraEnabled === true;const voiceBackgroundsAvailable = areVoiceBackgroundsAvailable();const channelId = MediaEngine.channelId;@@ -597,7 +597,7 @@ const CameraPreviewModalContent = observer((props: CameraPreviewModalProps) => {dataFlx: 'voice.camera-preview-modal.enable-camera-error-modal',});}- }, [i18n, localParticipant, onEnabled, onEnableCamera, videoDevices]);+ }, [i18n, localParticipant, onEnableCamera, videoDevices]);useEffect(() => {isMountedRef.current = true;const unsubscribeDevices = VoiceDevicePermissionState.subscribe(handleDeviceUpdate);diff --git a/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/NativeDisplayPickerState.tsx b/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/NativeDisplayPickerState.tsxindex 2f003147a..106c212db 100644--- a/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/NativeDisplayPickerState.tsx+++ b/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/NativeDisplayPickerState.tsx@@ -11,9 +11,6 @@ interface NativeDisplayPickerStateProps {pickerActionLabel: string;onPickerAction: () => void;pickerActionPending: boolean;- secondaryActionLabel?: string;- onSecondaryAction?: () => void;- secondaryActionPending?: boolean;showDesktopDownloadCta: boolean;}@@ -22,9 +19,6 @@ export const NativeDisplayPickerState: React.FC<NativeDisplayPickerStateProps> =pickerActionLabel,onPickerAction,pickerActionPending,- secondaryActionLabel,- onSecondaryAction,- secondaryActionPending = false,showDesktopDownloadCta,}) => {return (@@ -49,16 +43,6 @@ export const NativeDisplayPickerState: React.FC<NativeDisplayPickerStateProps> =>{pickerActionLabel}</Button>- {secondaryActionLabel && onSecondaryAction && (- <Button- variant="secondary"- onClick={onSecondaryAction}- submitting={secondaryActionPending}- data-flx="voice.screen-share-picker-modal.button.game-capture"- >- {secondaryActionLabel}- </Button>- )}</div>{showDesktopDownloadCta && (<DesktopDownloadCta data-flx="voice.screen-share-picker-modal.native-display-picker-state.desktop-download-cta" />diff --git a/fluxer_app/src/features/voice/components/useVoiceCallAppFullscreen.ts b/fluxer_app/src/features/voice/components/useVoiceCallAppFullscreen.tsindex 8aa561557..0d651877c 100644--- a/fluxer_app/src/features/voice/components/useVoiceCallAppFullscreen.ts+++ b/fluxer_app/src/features/voice/components/useVoiceCallAppFullscreen.ts@@ -1,17 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {- getExtendedDocument,- supportsMozRequestFullScreen,- supportsMsRequestFullscreen,- supportsWebkitRequestFullscreen,-} from '@app/features/platform/types/Browser';import {Logger} from '@app/features/platform/utils/AppLogger';-import {getFullscreenElement} from '@app/features/platform/utils/FullscreenMediaUtils';-import {setActivePortalHost} from '@app/features/ui/overlay/PortalHostContext';-import Modal from '@app/features/ui/state/Modal';+import {+ exitFullscreenAPI,+ requestFullscreen,+ supportsFullscreenAPI,+} from '@app/features/voice/components/media_player/hooks/useMediaFullscreen';import VoiceCallFullscreen from '@app/features/voice/state/VoiceCallFullscreen';-import type {ExtendedHTMLElement} from '@app/types/browser.d';import type {RefObject} from 'react';import {useCallback, useEffect, useRef, useState} from 'react';@@ -29,56 +24,6 @@ interface UseVoiceCallAppFullscreenReturn {toggleFullscreen: () => Promise<void>;}-function supportsFullscreenAPI(): boolean {- const doc = getExtendedDocument();- return !!(- document.fullscreenEnabled ||- doc.webkitFullscreenEnabled ||- doc.mozFullScreenEnabled ||- doc.msFullscreenEnabled- );-}--async function requestFullscreen(element: HTMLElement): Promise<void> {- if (element.requestFullscreen) {- await element.requestFullscreen();- return;- }- if (supportsWebkitRequestFullscreen(element)) {- const extendedElement = element as ExtendedHTMLElement;- await extendedElement.webkitRequestFullscreen!();- return;- }- if (supportsMozRequestFullScreen(element)) {- const extendedElement = element as ExtendedHTMLElement;- await extendedElement.mozRequestFullScreen!();- return;- }- if (supportsMsRequestFullscreen(element)) {- const extendedElement = element as ExtendedHTMLElement;- await extendedElement.msRequestFullscreen!();- }-}--async function exitFullscreenAPI(): Promise<void> {- const doc = getExtendedDocument();- if (document.exitFullscreen) {- await document.exitFullscreen();- return;- }- if (doc.webkitExitFullscreen) {- await doc.webkitExitFullscreen();- return;- }- if (doc.mozCancelFullScreen) {- await doc.mozCancelFullScreen();- return;- }- if (doc.msExitFullscreen) {- await doc.msExitFullscreen();- }-}-const VOICE_CALL_FULLSCREEN_ATTR = 'data-voice-call-fullscreen';export function useVoiceCallAppFullscreen(options: UseVoiceCallAppFullscreenOptions): UseVoiceCallAppFullscreenReturn {diff --git a/fluxer_app/src/features/voice/diagnostics/VoiceStatsDB.ts b/fluxer_app/src/features/voice/diagnostics/VoiceStatsDB.tsindex cf282adbd..11a386d4c 100644--- a/fluxer_app/src/features/voice/diagnostics/VoiceStatsDB.ts+++ b/fluxer_app/src/features/voice/diagnostics/VoiceStatsDB.ts@@ -9,12 +9,6 @@ const DB_VERSION = 1;const STORE_NAME = 'stats';const browserIndexedDB = getProtectedIndexedDB();-interface StatEntry {- reportId: string;- bytes: number;- timestamp: number;-}-const IDB_TIMEOUT = 5000;class VoiceStatsDB {@@ -60,41 +54,6 @@ class VoiceStatsDB {return this.initPromise;}- async set(reportId: string, bytes: number, timestamp: number): Promise<void> {- await this.init();- if (!this.db) return;- return new Promise((resolve, reject) => {- const transaction = this.db!.transaction([STORE_NAME], 'readwrite');- const store = transaction.objectStore(STORE_NAME);- const entry: StatEntry = {reportId, bytes, timestamp};- const request = store.put(entry);- request.onsuccess = () => resolve();- request.onerror = () => reject(request.error);- });- }-- async get(reportId: string): Promise<{- bytes: number;- timestamp: number;- } | null> {- await this.init();- if (!this.db) return null;- return new Promise((resolve, reject) => {- const transaction = this.db!.transaction([STORE_NAME], 'readonly');- const store = transaction.objectStore(STORE_NAME);- const request = store.get(reportId);- request.onsuccess = () => {- const entry = request.result as StatEntry | undefined;- if (entry) {- resolve({bytes: entry.bytes, timestamp: entry.timestamp});- } else {- resolve(null);- }- };- request.onerror = () => reject(request.error);- });- }-async clear(): Promise<void> {await this.init();if (!this.db) return;@@ -106,30 +65,6 @@ class VoiceStatsDB {request.onerror = () => reject(request.error);});}-- async clearOldEntries(maxAgeMs: number): Promise<void> {- await this.init();- if (!this.db) return;- const cutoffTime = Date.now() - maxAgeMs;- return new Promise((resolve, reject) => {- const transaction = this.db!.transaction([STORE_NAME], 'readwrite');- const store = transaction.objectStore(STORE_NAME);- const request = store.openCursor();- request.onsuccess = (event) => {- const cursor = (event.target as IDBRequest<IDBCursorWithValue>).result;- if (cursor) {- const entry = cursor.value as StatEntry;- if (entry.timestamp < cutoffTime) {- cursor.delete();- }- cursor.continue();- } else {- resolve();- }- };- request.onerror = () => reject(request.error);- });- }}export const voiceStatsDB = new VoiceStatsDB();diff --git a/fluxer_app/src/features/voice/engine/MediaEngineFacade.ts b/fluxer_app/src/features/voice/engine/MediaEngineFacade.tsindex cf48a9213..8d2e76cbc 100644--- a/fluxer_app/src/features/voice/engine/MediaEngineFacade.ts+++ b/fluxer_app/src/features/voice/engine/MediaEngineFacade.ts@@ -2265,11 +2265,7 @@ class MediaEngineFacade extends Store {async ensureLinuxScreenShareAudioPublication(linuxRule?: NonNullable<NativeAudioStartOptions['linuxRule']>,): Promise<boolean> {- return voiceEngineV2AppScreenShareExecutionAdapter.ensureLinuxScreenShareAudioPublication(- this.room,- linuxRule,- options,- );+ return voiceEngineV2AppScreenShareExecutionAdapter.ensureLinuxScreenShareAudioPublication(this.room, linuxRule);}async ensureWindowScreenShareAudioPublication(sourceId: string): Promise<boolean> {diff --git a/fluxer_app/src/features/voice/engine/VoiceIdleActivityBridge.ts b/fluxer_app/src/features/voice/engine/VoiceIdleActivityBridge.tsindex 3c9e0f96d..1815800db 100644--- a/fluxer_app/src/features/voice/engine/VoiceIdleActivityBridge.ts+++ b/fluxer_app/src/features/voice/engine/VoiceIdleActivityBridge.ts@@ -13,7 +13,6 @@ type VoiceActivitySource = Readonly<{}>;type NoteVoiceActivityOptions = Readonly<{force?: boolean;- now?: number;speaking?: boolean;}>;@@ -45,7 +44,7 @@ export function noteLocalVoiceActivity(options?: NoteVoiceActivityOptions,): boolean {if (!source || !shouldRecordVoiceActivity(source, options)) return false;- maybeRecordActivity(options?.now ?? Date.now(), options?.force === true);+ maybeRecordActivity(Date.now(), options?.force === true);return true;}diff --git a/fluxer_app/src/features/voice/engine/VoiceLatencyTracker.ts b/fluxer_app/src/features/voice/engine/VoiceLatencyTracker.tsindex c02eaf02b..af2e630c8 100644--- a/fluxer_app/src/features/voice/engine/VoiceLatencyTracker.ts+++ b/fluxer_app/src/features/voice/engine/VoiceLatencyTracker.ts@@ -3,7 +3,7 @@import type {VoiceEngineV2LatencyDataPoint as LatencyDataPoint} from '@fluxer/voice_engine_v2/src/protocol/types';const DEFAULT_VOICE_LATENCY_HISTORY_LIMIT = 60;-const DEFAULT_VOICE_LATENCY_STALE_AFTER_MS = 10_000;+const VOICE_LATENCY_STALE_AFTER_MS = 10_000;type VoiceLatencyStatus = 'idle' | 'measuring' | 'fresh' | 'stale';@@ -24,18 +24,15 @@ export interface VoiceLatencySnapshotOptions {export interface VoiceLatencyRecordOptions {historyLimit?: number;- staleAfterMs?: number;}function latencyStatusFor(snapshot: Pick<VoiceLatencySnapshot, 'tracking' | 'currentLatency' | 'lastSampledAt'>,now: number,- options: VoiceLatencyRecordOptions = {},): VoiceLatencyStatus {if (!snapshot.tracking) return 'idle';if (snapshot.currentLatency == null || snapshot.lastSampledAt == null) return 'measuring';- const staleAfterMs = options.staleAfterMs ?? DEFAULT_VOICE_LATENCY_STALE_AFTER_MS;- return now - snapshot.lastSampledAt > staleAfterMs ? 'stale' : 'fresh';+ return now - snapshot.lastSampledAt > VOICE_LATENCY_STALE_AFTER_MS ? 'stale' : 'fresh';}function roundedLatency(latency: number): number | null {@@ -84,19 +81,17 @@ export function createVoiceLatencySnapshot(options: VoiceLatencySnapshotOptionsexport function startVoiceLatencyTracking(snapshot: VoiceLatencySnapshot,now: number = Date.now(),- options: VoiceLatencyRecordOptions = {},): VoiceLatencySnapshot {const next = {...snapshot, tracking: true, lastObservedAt: snapshot.lastObservedAt ?? now};- return {...next, status: latencyStatusFor(next, now, options)};+ return {...next, status: latencyStatusFor(next, now)};}export function stopVoiceLatencyTracking(snapshot: VoiceLatencySnapshot,now: number = Date.now(),- options: VoiceLatencyRecordOptions = {},): VoiceLatencySnapshot {const next = {...snapshot, tracking: false, lastObservedAt: snapshot.lastObservedAt ?? now};- return {...next, status: latencyStatusFor(next, now, options)};+ return {...next, status: latencyStatusFor(next, now)};}export function resetVoiceLatencySnapshot(options: VoiceLatencySnapshotOptions = {}): VoiceLatencySnapshot {@@ -106,10 +101,9 @@ export function resetVoiceLatencySnapshot(options: VoiceLatencySnapshotOptions =export function observeVoiceLatencyGap(snapshot: VoiceLatencySnapshot,timestamp: number = Date.now(),- options: VoiceLatencyRecordOptions = {},): VoiceLatencySnapshot {const next = {...snapshot, lastObservedAt: timestamp};- return {...next, status: latencyStatusFor(next, timestamp, options)};+ return {...next, status: latencyStatusFor(next, timestamp)};}export function recordVoiceLatencySample(@@ -119,7 +113,7 @@ export function recordVoiceLatencySample(options: VoiceLatencyRecordOptions = {},): VoiceLatencySnapshot {const sample = roundedLatency(latency);- if (sample == null) return observeVoiceLatencyGap(snapshot, timestamp, options);+ if (sample == null) return observeVoiceLatencyGap(snapshot, timestamp);const historyLimit = options.historyLimit ?? DEFAULT_VOICE_LATENCY_HISTORY_LIMIT;const latencyHistory = appendLatencySample(snapshot.latencyHistory, {timestamp, latency: sample}, historyLimit);const next = {diff --git a/fluxer_app/src/features/voice/engine/VoicePermissionStateMachine.ts b/fluxer_app/src/features/voice/engine/VoicePermissionStateMachine.tsindex 5fc327e86..607283ea6 100644--- a/fluxer_app/src/features/voice/engine/VoicePermissionStateMachine.ts+++ b/fluxer_app/src/features/voice/engine/VoicePermissionStateMachine.ts@@ -284,38 +284,24 @@ const voicePermissionStateMachine = setup({id: 'voicePermission',context: () => initialContext(),initial: 'routing',+ on: {+ 'permission.watch.start': {target: '.routing', actions: 'startWatch'},+ 'permission.watch.stop': {target: '.routing', actions: 'stopWatch'},+ 'permission.room.set': {target: '.routing', actions: 'setRoomPresence'},+ 'permission.update': {target: '.routing', actions: 'updatePermissions'},+ 'permission.change': {target: '.routing', actions: 'changePermission'},+ 'permission.set': {target: '.routing', actions: 'setPermissions'},+ 'subscription.initialize': {target: '.routing', actions: 'initializeSubscriptions'},+ 'deafen.apply': {target: '.routing', actions: 'applyDeafen'},+ 'permission.reset': {target: '.routing', actions: 'reset'},+ 'permission.clearCommands': {actions: 'clearCommands'},+ },states: {routing: {always: [{guard: 'watcherActive', target: 'watching'}, {target: 'inactive'}],},- inactive: {- on: {- 'permission.watch.start': {target: 'routing', actions: 'startWatch'},- 'permission.watch.stop': {target: 'routing', actions: 'stopWatch'},- 'permission.room.set': {target: 'routing', actions: 'setRoomPresence'},- 'permission.update': {target: 'routing', actions: 'updatePermissions'},- 'permission.change': {target: 'routing', actions: 'changePermission'},- 'permission.set': {target: 'routing', actions: 'setPermissions'},- 'subscription.initialize': {target: 'routing', actions: 'initializeSubscriptions'},- 'deafen.apply': {target: 'routing', actions: 'applyDeafen'},- 'permission.reset': {target: 'routing', actions: 'reset'},- 'permission.clearCommands': {actions: 'clearCommands'},- },- },- watching: {- on: {- 'permission.watch.start': {target: 'routing', actions: 'startWatch'},- 'permission.watch.stop': {target: 'routing', actions: 'stopWatch'},- 'permission.room.set': {target: 'routing', actions: 'setRoomPresence'},- 'permission.update': {target: 'routing', actions: 'updatePermissions'},- 'permission.change': {target: 'routing', actions: 'changePermission'},- 'permission.set': {target: 'routing', actions: 'setPermissions'},- 'subscription.initialize': {target: 'routing', actions: 'initializeSubscriptions'},- 'deafen.apply': {target: 'routing', actions: 'applyDeafen'},- 'permission.reset': {target: 'routing', actions: 'reset'},- 'permission.clearCommands': {actions: 'clearCommands'},- },- },+ inactive: {},+ watching: {},},});diff --git a/fluxer_app/src/features/voice/engine/VoiceScreenShareStateMachine.ts b/fluxer_app/src/features/voice/engine/VoiceScreenShareStateMachine.tsindex 65d51f5c2..58a4396d2 100644--- a/fluxer_app/src/features/voice/engine/VoiceScreenShareStateMachine.ts+++ b/fluxer_app/src/features/voice/engine/VoiceScreenShareStateMachine.ts@@ -289,6 +289,23 @@ const voiceScreenShareStateMachine = setup({context: () => initialContext(),initial: 'routing',on: {+ 'share.start': {target: '.routing', actions: 'start'},+ 'share.restore': {target: '.routing', actions: 'restore'},+ 'share.stop': {target: '.routing', actions: 'stop'},+ 'share.replace': {target: '.routing', actions: 'replace'},+ 'share.resolve': {target: '.routing', actions: 'resolve'},+ 'share.reject': {target: '.routing', actions: 'reject'},+ 'share.cancel': {target: '.routing', actions: 'reject'},+ 'share.endedStop.start': {target: '.routing', actions: 'startEndedStop'},+ 'share.endedStop.finish': {target: '.routing', actions: 'finishEndedStop'},+ 'share.encoderVerification.scheduled': {target: '.routing', actions: 'scheduleEncoderVerification'},+ 'share.encoderVerification.cleared': {target: '.routing', actions: 'clearEncoderVerification'},+ 'share.streamingPriority.set': {target: '.routing', actions: 'setStreamingPriority'},+ 'share.publicationReplace.set': {target: '.routing', actions: 'setPublicationReplaceInFlight'},+ 'share.queuedStop.clear': {target: '.routing', actions: 'clearQueuedStop'},+ 'share.localWatcher.sync': {target: '.routing', actions: 'syncLocalWatcher'},+ 'share.clearWatchCommands': {actions: 'clearWatchCommands'},+ 'share.reset': {target: '.routing', actions: 'reset'},'share.codecReadiness.loading': {actions: 'setCodecReadiness'},'share.codecReadiness.ready': {actions: 'setCodecReadiness'},'share.codecReadiness.timeout': {actions: 'setCodecReadiness'},@@ -298,57 +315,14 @@ const voiceScreenShareStateMachine = setup({routing: {always: [{guard: 'isPending', target: 'pending'}, {guard: 'isActive', target: 'active'}, {target: 'inactive'}],},- inactive: {- on: {- 'share.start': {target: 'routing', actions: 'start'},- 'share.restore': {target: 'routing', actions: 'restore'},- 'share.stop': {target: 'routing', actions: 'stop'},- 'share.replace': {target: 'routing', actions: 'replace'},- 'share.resolve': {target: 'routing', actions: 'resolve'},- 'share.reject': {target: 'routing', actions: 'reject'},- 'share.cancel': {target: 'routing', actions: 'reject'},- 'share.endedStop.start': {target: 'routing', actions: 'startEndedStop'},- 'share.endedStop.finish': {target: 'routing', actions: 'finishEndedStop'},- 'share.encoderVerification.scheduled': {target: 'routing', actions: 'scheduleEncoderVerification'},- 'share.encoderVerification.cleared': {target: 'routing', actions: 'clearEncoderVerification'},- 'share.streamingPriority.set': {target: 'routing', actions: 'setStreamingPriority'},- 'share.publicationReplace.set': {target: 'routing', actions: 'setPublicationReplaceInFlight'},- 'share.queuedStop.clear': {target: 'routing', actions: 'clearQueuedStop'},- 'share.localWatcher.sync': {target: 'routing', actions: 'syncLocalWatcher'},- 'share.clearWatchCommands': {actions: 'clearWatchCommands'},- 'share.reset': {target: 'routing', actions: 'reset'},- },- },- active: {- on: {- 'share.start': {target: 'routing', actions: 'start'},- 'share.restore': {target: 'routing', actions: 'restore'},- 'share.stop': {target: 'routing', actions: 'stop'},- 'share.replace': {target: 'routing', actions: 'replace'},- 'share.resolve': {target: 'routing', actions: 'resolve'},- 'share.reject': {target: 'routing', actions: 'reject'},- 'share.cancel': {target: 'routing', actions: 'reject'},- 'share.endedStop.start': {target: 'routing', actions: 'startEndedStop'},- 'share.endedStop.finish': {target: 'routing', actions: 'finishEndedStop'},- 'share.encoderVerification.scheduled': {target: 'routing', actions: 'scheduleEncoderVerification'},- 'share.encoderVerification.cleared': {target: 'routing', actions: 'clearEncoderVerification'},- 'share.streamingPriority.set': {target: 'routing', actions: 'setStreamingPriority'},- 'share.publicationReplace.set': {target: 'routing', actions: 'setPublicationReplaceInFlight'},- 'share.queuedStop.clear': {target: 'routing', actions: 'clearQueuedStop'},- 'share.localWatcher.sync': {target: 'routing', actions: 'syncLocalWatcher'},- 'share.clearWatchCommands': {actions: 'clearWatchCommands'},- 'share.reset': {target: 'routing', actions: 'reset'},- },- },+ inactive: {},+ active: {},pending: {on: {'share.start': {actions: 'start'},'share.restore': {actions: 'restore'},'share.stop': {actions: 'stop'},'share.replace': {actions: 'replace'},- 'share.resolve': {target: 'routing', actions: 'resolve'},- 'share.reject': {target: 'routing', actions: 'reject'},- 'share.cancel': {target: 'routing', actions: 'reject'},'share.endedStop.start': {actions: 'startEndedStop'},'share.endedStop.finish': {actions: 'finishEndedStop'},'share.encoderVerification.scheduled': {actions: 'scheduleEncoderVerification'},@@ -357,8 +331,6 @@ const voiceScreenShareStateMachine = setup({'share.publicationReplace.set': {actions: 'setPublicationReplaceInFlight'},'share.queuedStop.clear': {actions: 'clearQueuedStop'},'share.localWatcher.sync': {actions: 'syncLocalWatcher'},- 'share.clearWatchCommands': {actions: 'clearWatchCommands'},- 'share.reset': {target: 'routing', actions: 'reset'},},},},diff --git a/fluxer_app/src/features/voice/engine/VoiceStatsStateMachine.ts b/fluxer_app/src/features/voice/engine/VoiceStatsStateMachine.tsindex 3d4804e84..fcc665c5a 100644--- a/fluxer_app/src/features/voice/engine/VoiceStatsStateMachine.ts+++ b/fluxer_app/src/features/voice/engine/VoiceStatsStateMachine.ts@@ -416,6 +416,22 @@ const voiceStatsStateMachine = setup({id: 'voiceStats',context: () => initialContext(),initial: 'routing',+ on: {+ 'room.set': {target: '.routing', actions: 'setRoom'},+ 'latency.start': {target: '.routing', actions: 'startLatency'},+ 'latency.stop': {target: '.routing', actions: 'stopLatency'},+ 'latency.sample': {target: '.routing', actions: 'recordLatencySample'},+ 'latency.gap': {target: '.routing', actions: 'recordLatencyGap'},+ 'stats.start': {target: '.routing', actions: 'startStats'},+ 'stats.stop': {target: '.routing', actions: 'stopStats'},+ 'stats.tick': {target: '.routing', actions: 'tickStats'},+ 'stats.collectionStarted': {target: '.routing', actions: 'startCollection'},+ 'stats.collectionSucceeded': {target: '.routing', actions: 'applyCollectionResult'},+ 'stats.collectionFinished': {target: '.routing', actions: 'finishCollection'},+ 'reconnection.increment': {target: '.routing', actions: 'incrementReconnectionCount'},+ 'stats.reset': {target: '.routing', actions: 'reset'},+ 'stats.cleanup': {target: '.routing', actions: 'reset'},+ },states: {routing: {always: [@@ -425,78 +441,10 @@ const voiceStatsStateMachine = setup({{target: 'idle'},],},- idle: {- on: {- 'room.set': {target: 'routing', actions: 'setRoom'},- 'latency.start': {target: 'routing', actions: 'startLatency'},- 'latency.stop': {target: 'routing', actions: 'stopLatency'},- 'latency.sample': {target: 'routing', actions: 'recordLatencySample'},- 'latency.gap': {target: 'routing', actions: 'recordLatencyGap'},- 'stats.start': {target: 'routing', actions: 'startStats'},- 'stats.stop': {target: 'routing', actions: 'stopStats'},- 'stats.tick': {target: 'routing', actions: 'tickStats'},- 'stats.collectionStarted': {target: 'routing', actions: 'startCollection'},- 'stats.collectionSucceeded': {target: 'routing', actions: 'applyCollectionResult'},- 'stats.collectionFinished': {target: 'routing', actions: 'finishCollection'},- 'reconnection.increment': {target: 'routing', actions: 'incrementReconnectionCount'},- 'stats.reset': {target: 'routing', actions: 'reset'},- 'stats.cleanup': {target: 'routing', actions: 'reset'},- },- },- trackingLatency: {- on: {- 'room.set': {target: 'routing', actions: 'setRoom'},- 'latency.start': {target: 'routing', actions: 'startLatency'},- 'latency.stop': {target: 'routing', actions: 'stopLatency'},- 'latency.sample': {target: 'routing', actions: 'recordLatencySample'},- 'latency.gap': {target: 'routing', actions: 'recordLatencyGap'},- 'stats.start': {target: 'routing', actions: 'startStats'},- 'stats.stop': {target: 'routing', actions: 'stopStats'},- 'stats.tick': {target: 'routing', actions: 'tickStats'},- 'stats.collectionStarted': {target: 'routing', actions: 'startCollection'},- 'stats.collectionSucceeded': {target: 'routing', actions: 'applyCollectionResult'},- 'stats.collectionFinished': {target: 'routing', actions: 'finishCollection'},- 'reconnection.increment': {target: 'routing', actions: 'incrementReconnectionCount'},- 'stats.reset': {target: 'routing', actions: 'reset'},- 'stats.cleanup': {target: 'routing', actions: 'reset'},- },- },- trackingStats: {- on: {- 'room.set': {target: 'routing', actions: 'setRoom'},- 'latency.start': {target: 'routing', actions: 'startLatency'},- 'latency.stop': {target: 'routing', actions: 'stopLatency'},- 'latency.sample': {target: 'routing', actions: 'recordLatencySample'},- 'latency.gap': {target: 'routing', actions: 'recordLatencyGap'},- 'stats.start': {target: 'routing', actions: 'startStats'},- 'stats.stop': {target: 'routing', actions: 'stopStats'},- 'stats.tick': {target: 'routing', actions: 'tickStats'},- 'stats.collectionStarted': {target: 'routing', actions: 'startCollection'},- 'stats.collectionSucceeded': {target: 'routing', actions: 'applyCollectionResult'},- 'stats.collectionFinished': {target: 'routing', actions: 'finishCollection'},- 'reconnection.increment': {target: 'routing', actions: 'incrementReconnectionCount'},- 'stats.reset': {target: 'routing', actions: 'reset'},- 'stats.cleanup': {target: 'routing', actions: 'reset'},- },- },- trackingBoth: {- on: {- 'room.set': {target: 'routing', actions: 'setRoom'},- 'latency.start': {target: 'routing', actions: 'startLatency'},- 'latency.stop': {target: 'routing', actions: 'stopLatency'},- 'latency.sample': {target: 'routing', actions: 'recordLatencySample'},- 'latency.gap': {target: 'routing', actions: 'recordLatencyGap'},- 'stats.start': {target: 'routing', actions: 'startStats'},- 'stats.stop': {target: 'routing', actions: 'stopStats'},- 'stats.tick': {target: 'routing', actions: 'tickStats'},- 'stats.collectionStarted': {target: 'routing', actions: 'startCollection'},- 'stats.collectionSucceeded': {target: 'routing', actions: 'applyCollectionResult'},- 'stats.collectionFinished': {target: 'routing', actions: 'finishCollection'},- 'reconnection.increment': {target: 'routing', actions: 'incrementReconnectionCount'},- 'stats.reset': {target: 'routing', actions: 'reset'},- 'stats.cleanup': {target: 'routing', actions: 'reset'},- },- },+ idle: {},+ trackingLatency: {},+ trackingStats: {},+ trackingBoth: {},},});diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppControllerHost.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppControllerHost.tsindex f79e6a2ae..72a262a5a 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppControllerHost.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppControllerHost.ts@@ -16,22 +16,17 @@ import {VoiceEngineV2Controller} from '@fluxer/voice_engine_v2/src/runtime/Voiceimport {type VoiceEngineV2EventLogSpillSink,VoiceEngineV2Runtime,- type VoiceEngineV2RuntimeClock,type VoiceEngineV2RuntimeListener,} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Runtime';export interface VoiceEngineV2AppControllerHostOptions {ports: VoiceEngineV2HostPorts;- clock?: VoiceEngineV2RuntimeClock;eventLogSpillSink: VoiceEngineV2EventLogSpillSink;- queuedCommandsCap?: number;- resourceQueuesCap?: number;}export interface VoiceEngineV2AppControllerHostWaitOptions {description?: string;staleCompletion?: 'reject' | 'resolve';- timeoutMs?: number;onCommandsPlanned?: (commands: ReadonlyArray<VoiceEngineV2Command>) => void;}@@ -90,10 +85,7 @@ export class VoiceEngineV2AppControllerHost {constructor(options: VoiceEngineV2AppControllerHostOptions) {this.runtime = new VoiceEngineV2Runtime(new VoiceEngineV2HostPortImplementation(options.ports), {- clock: options.clock,eventLogSpillSink: options.eventLogSpillSink,- ...(options.queuedCommandsCap !== undefined ? {queuedCommandsCap: options.queuedCommandsCap} : {}),- ...(options.resourceQueuesCap !== undefined ? {resourceQueuesCap: options.resourceQueuesCap} : {}),});this.controller = new VoiceEngineV2Controller(this.runtime);this.runtime.subscribeDiagnostics((diagnostic) => {@@ -135,7 +127,6 @@ export class VoiceEngineV2AppControllerHost {const pending = new Set<VoiceEngineV2OperationId>();const description = options.description ?? 'voice engine v2 command';const staleCompletion = options.staleCompletion ?? 'reject';- const timeoutMs = options.timeoutMs ?? VOICE_ENGINE_V2_APP_COMMAND_WAIT_TIMEOUT_MS;return new Promise((resolve, reject) => {let actionComplete = false;let timer: ReturnType<typeof setTimeout> | null = null;@@ -154,7 +145,10 @@ export class VoiceEngineV2AppControllerHost {if (!actionComplete) addPendingCommands(pending, plannedCommands, transition.commands);this.consumeTerminalEvent(event, pending, {description, staleCompletion}, settle);});- timer = setTimeout(() => settle(buildWaitTimeout(description, pending)), timeoutMs);+ timer = setTimeout(+ () => settle(buildWaitTimeout(description, pending)),+ VOICE_ENGINE_V2_APP_COMMAND_WAIT_TIMEOUT_MS,+ );try {action();actionComplete = true;diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDevicesAdapter.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDevicesAdapter.tsindex 6195a020e..8b49cdbb3 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDevicesAdapter.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDevicesAdapter.ts@@ -33,10 +33,6 @@ type VoiceEngineV2AppDevicesEvent = VoiceEngineV2AppDevicesChangedEvent | VoiceEtype VoiceEngineV2AppDevicesListener = (event: VoiceEngineV2AppDevicesEvent) => void;-export interface VoiceEngineV2AppDevicesAdapterOptions {- enumerator?: VoiceEngineV2AppDevicesEnumerator | null;-}-export interface VoiceEngineV2AppDevicesAdapter extends DevicePort {subscribe(listener: VoiceEngineV2AppDevicesListener): () => void;getLastInventory(): VoiceEngineV2DeviceInventory;@@ -49,11 +45,8 @@ interface DevicesAdapterState {listeners: Set<VoiceEngineV2AppDevicesListener>;}-export function createVoiceEngineV2AppDevicesAdapter(- options: VoiceEngineV2AppDevicesAdapterOptions = {},-): VoiceEngineV2AppDevicesAdapter {- assert.ok(options !== null && typeof options === 'object', 'devices adapter requires options object');- const enumerator = resolveEnumerator(options.enumerator);+export function createVoiceEngineV2AppDevicesAdapter(): VoiceEngineV2AppDevicesAdapter {+ const enumerator = resolveEnumerator();const state: DevicesAdapterState = {inventory: emptyVoiceEngineV2DeviceInventory(),requiresPermission: false,@@ -144,14 +137,7 @@ function emitChanged(state: DevicesAdapterState, reason: VoiceEngineV2DeviceChan});}-function resolveEnumerator(- candidate: VoiceEngineV2AppDevicesEnumerator | null | undefined,-): VoiceEngineV2AppDevicesEnumerator | null {- if (candidate === null) return null;- if (candidate !== undefined) {- if (typeof candidate.enumerateDevices !== 'function') return null;- return candidate;- }+function resolveEnumerator(): VoiceEngineV2AppDevicesEnumerator | null {if (typeof navigator === 'undefined') return null;const media = navigator.mediaDevices;if (!media || typeof media.enumerateDevices !== 'function') return null;diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter.tsindex feabea10e..874504949 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter.ts@@ -20,17 +20,15 @@ export interface VoiceEngineV2AppDiagnosticsLogger {export interface VoiceEngineV2AppDiagnosticsAdapterOptions {logger: VoiceEngineV2AppDiagnosticsLogger;- fallbackLevel?: VoiceEngineV2DiagnosticsLevel;- onError?: (code: string, error: unknown) => void;}-function normaliseLevel(level: string, fallback: VoiceEngineV2DiagnosticsLevel): VoiceEngineV2DiagnosticsLevel {+function normaliseLevel(level: string): VoiceEngineV2DiagnosticsLevel {assert.equal(typeof level, 'string', 'diagnostics level must be a string');const lower = level.toLowerCase();if (KNOWN_LEVELS.has(lower as VoiceEngineV2DiagnosticsLevel)) {return lower as VoiceEngineV2DiagnosticsLevel;}- return fallback;+ return 'info';}function dispatch(@@ -66,10 +64,7 @@ export function createVoiceEngineV2AppDiagnosticsAdapter(): DiagnosticsPort {assert.ok(options !== null && typeof options === 'object', 'voice-engine-v2 diagnostics adapter requires options');assert.ok(options.logger !== null && typeof options.logger === 'object', 'diagnostics adapter requires a logger');- const fallback = options.fallbackLevel ?? 'info';- assert.ok(KNOWN_LEVELS.has(fallback), 'diagnostics adapter fallbackLevel must be a known level');const logger = options.logger;- const onError = options.onError;return {async log(level: string, code: string, message: string, detail?: unknown): Promise<void> {assert.equal(typeof code, 'string', 'diagnostics code must be a string');@@ -83,13 +78,11 @@ export function createVoiceEngineV2AppDiagnosticsAdapter(message.length <= VOICE_ENGINE_V2_DIAGNOSTICS_MESSAGE_MAX_LENGTH,'diagnostics message exceeds the maximum length',);- const resolvedLevel = normaliseLevel(level, fallback);+ const resolvedLevel = normaliseLevel(level);const payload: Record<string, unknown> = detail === undefined ? {code, message} : {code, message, detail};try {dispatch(logger, resolvedLevel, payload);- } catch (error) {- onError?.(code, error);- }+ } catch {}},};}diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink.tsindex 932b3e168..2d744343e 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink.ts@@ -7,7 +7,6 @@ import type {} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Runtime';const VOICE_ENGINE_V2_APP_EVENT_LOG_SPILL_WARN_INTERVAL_MS = 60_000;-const VOICE_ENGINE_V2_APP_EVENT_LOG_SPILL_WARN_INTERVAL_MAX_MS = 3_600_000;const RESOLVED_SPILL_WRITE = Promise.resolve();@@ -17,9 +16,6 @@ interface VoiceEngineV2AppEventLogSpillLogger {export interface VoiceEngineV2AppEventLogSpillLoggerSinkOptions {logger: VoiceEngineV2AppEventLogSpillLogger;- warnIntervalMs?: number;- nowMs?: () => number;- onLoggerError?: (error: unknown) => void;}export interface VoiceEngineV2AppEventLogSpillLoggerSink extends VoiceEngineV2EventLogSpillSink {@@ -32,12 +28,11 @@ function assertTimestampMs(value: number, label: string): void {assert.ok(value >= 0, `${label} must be non-negative`);}-function shouldWarn(nowMs: number, lastWarnAtMs: number | null, warnIntervalMs: number): boolean {+function shouldWarn(nowMs: number, lastWarnAtMs: number | null): boolean {assertTimestampMs(nowMs, 'event log spill warning timestamp');- assert.ok(warnIntervalMs >= 1, 'event log spill warning interval must be positive');if (lastWarnAtMs === null) return true;assertTimestampMs(lastWarnAtMs, 'last event log spill warning timestamp');- return nowMs - lastWarnAtMs >= warnIntervalMs;+ return nowMs - lastWarnAtMs >= VOICE_ENGINE_V2_APP_EVENT_LOG_SPILL_WARN_INTERVAL_MS;}export function createVoiceEngineV2AppEventLogSpillLoggerSink(@@ -53,19 +48,7 @@ export function createVoiceEngineV2AppEventLogSpillLoggerSink('function','event log spill logger sink requires logger.warn to be callable',);- const warnIntervalMs = options.warnIntervalMs ?? VOICE_ENGINE_V2_APP_EVENT_LOG_SPILL_WARN_INTERVAL_MS;- assert.ok(Number.isInteger(warnIntervalMs), 'event log spill warning interval must be an integer');- assert.ok(warnIntervalMs >= 1, 'event log spill warning interval must be >= 1');- assert.ok(- warnIntervalMs <= VOICE_ENGINE_V2_APP_EVENT_LOG_SPILL_WARN_INTERVAL_MAX_MS,- 'event log spill warning interval exceeds the maximum',- );- if (options.nowMs !== undefined) {- assert.equal(typeof options.nowMs, 'function', 'event log spill logger sink nowMs must be callable');- }const logger = options.logger;- const nowMs = options.nowMs ?? Date.now;- const onLoggerError = options.onLoggerError;let swallowedErrorCount = 0;let evictedEntryCount = 0;let suppressedEvictedEntryCount = 0;@@ -79,11 +62,11 @@ export function createVoiceEngineV2AppEventLogSpillLoggerSink(assert.ok(entry !== null && typeof entry === 'object', 'event log spill entry must be an object');assert.ok(Number.isInteger(entry.sequence), 'event log spill entry sequence must be an integer');assert.ok(entry.sequence >= 1, 'event log spill entry sequence must be >= 1');- const currentMs = nowMs();+ const currentMs = Date.now();assertTimestampMs(currentMs, 'event log spill logger timestamp');evictedEntryCount += 1;assert.ok(evictedEntryCount >= 1, 'evicted entry count must increment');- if (!shouldWarn(currentMs, lastWarnAtMs, warnIntervalMs)) {+ if (!shouldWarn(currentMs, lastWarnAtMs)) {suppressedEvictedEntryCount += 1;assert.ok(suppressedEvictedEntryCount >= 1, 'suppressed evicted entry count must increment');return RESOLVED_SPILL_WRITE;@@ -97,11 +80,10 @@ export function createVoiceEngineV2AppEventLogSpillLoggerSink(suppressedEvictedEntryCount,});suppressedEvictedEntryCount = 0;- } catch (error) {+ } catch {swallowedErrorCount += 1;suppressedEvictedEntryCount += 1;assert.ok(swallowedErrorCount > 0, 'swallowed error count must increment on logger failure');- if (onLoggerError) onLoggerError(error);}return RESOLVED_SPILL_WRITE;},diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter.tsindex 4240588d3..dc7c4c5b8 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter.ts@@ -23,7 +23,6 @@ export interface VoiceEngineV2AppLifecycleAdapterOptions {readonly disposables: ReadonlyArray<VoiceEngineV2AppLifecycleDisposable>;readonly logger: VoiceEngineV2AppDiagnosticsLogger;readonly clock: VoiceEngineV2ClockPort;- readonly teardownPerDisposableTimeoutMs?: number;}function isPositiveInteger(value: unknown): value is number {@@ -42,7 +41,6 @@ export class VoiceEngineV2AppLifecycleAdapter {private readonly logger: VoiceEngineV2AppDiagnosticsLogger;private readonly clock: VoiceEngineV2ClockPort;private readonly registry: Map<number, VoiceEngineV2AppLifecycleRegistration>;- private readonly teardownTimeoutMs: number;private tornDown: boolean;constructor(options: VoiceEngineV2AppLifecycleAdapterOptions) {@@ -52,8 +50,6 @@ export class VoiceEngineV2AppLifecycleAdapter {assert.ok(options.logger !== null && typeof options.logger === 'object', 'lifecycle adapter requires a logger');assert.ok(options.clock !== null && typeof options.clock === 'object', 'lifecycle adapter requires a clock');assert.equal(typeof options.clock.now, 'function', 'lifecycle adapter clock must implement now()');- const timeoutMs = options.teardownPerDisposableTimeoutMs ?? TEARDOWN_PER_DISPOSABLE_TIMEOUT_MS;- assert.ok(isPositiveInteger(timeoutMs), 'lifecycle adapter teardown timeout must be a positive integer');for (const disposable of options.disposables) {assert.ok(disposable !== null && typeof disposable === 'object',@@ -66,7 +62,6 @@ export class VoiceEngineV2AppLifecycleAdapter {this.logger = options.logger;this.clock = options.clock;this.registry = new Map();- this.teardownTimeoutMs = timeoutMs;this.tornDown = false;}@@ -131,7 +126,7 @@ export class VoiceEngineV2AppLifecycleAdapter {assert.ok(disposable !== null && typeof disposable === 'object', 'disposeWithTimeout requires a disposable');assert.equal(typeof disposable.dispose, 'function', 'disposeWithTimeout requires dispose() method');const startedAt = this.clock.now();- const budgetMs = this.teardownTimeoutMs;+ const budgetMs = TEARDOWN_PER_DISPOSABLE_TIMEOUT_MS;let timeoutHandle: VoiceEngineV2AppLifecycleTimeoutHandle | undefined;const timeoutPromise = new Promise<'timeout'>((resolve) => {timeoutHandle = globalThis.setTimeout(() => {diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppRemoteSpeakingAdapter.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppRemoteSpeakingAdapter.tsindex 028d1f5e1..0e4166b7a 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppRemoteSpeakingAdapter.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppRemoteSpeakingAdapter.ts@@ -50,10 +50,6 @@ interface AnalyserHandle {nextTickAtMs: number;}-interface VoiceEngineV2AppRemoteSpeakingAdapterOptions {- autoSchedule?: boolean;-}-class VoiceEngineV2AppRemoteSpeakingAdapter {private audioContext: AudioContext | null = null;private audioContextIsShared = false;@@ -61,11 +57,6 @@ class VoiceEngineV2AppRemoteSpeakingAdapter {private hydratedRoom: Room | null = null;private machineSnapshot: VoiceRemoteSpeakingSnapshot = createVoiceRemoteSpeakingSnapshot();private autoScheduleTimerId: number | null = null;- private readonly autoSchedule: boolean;-- constructor(options: VoiceEngineV2AppRemoteSpeakingAdapterOptions = {}) {- this.autoSchedule = options.autoSchedule ?? true;- }private transition(event: VoiceRemoteSpeakingEvent): ReadonlyArray<VoiceRemoteSpeakingCommand> {this.machineSnapshot = transitionVoiceRemoteSpeakingSnapshot(this.machineSnapshot, event);@@ -319,7 +310,6 @@ class VoiceEngineV2AppRemoteSpeakingAdapter {}private ensureAutoSchedule(): void {- if (!this.autoSchedule) return;if (this.autoScheduleTimerId !== null) return;if (typeof window === 'undefined') return;this.autoScheduleTimerId = window.setInterval(() => {diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareExecutionAdapter.tsx b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareExecutionAdapter.tsxindex 207ebd039..19d43e0a2 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareExecutionAdapter.tsx+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareExecutionAdapter.tsx@@ -861,14 +861,12 @@ class VoiceEngineV2AppScreenShareExecutionAdapter extends Store {const participant = room?.localParticipant;if (!participant?.isScreenShareEnabled) return false;if (!linuxRule) return false;- if (options.replaceExisting !== true) {- const reconfigured = await reconfigureLinuxNativeAudioRouting(linuxRule, options);- if (reconfigured !== 'unsupported') {- this.syncPersistedScreenShareAudioPreferenceInternal(participant);- return true;- }+ const reconfigured = await reconfigureLinuxNativeAudioRouting(linuxRule);+ if (reconfigured !== 'unsupported') {+ this.syncPersistedScreenShareAudioPreferenceInternal(participant);+ return true;}- const capturedTrack = await captureNativeAudioTrackForLinuxRouting(linuxRule, options);+ const capturedTrack = await captureNativeAudioTrackForLinuxRouting(linuxRule);if (!capturedTrack) return false;let adopted = false;try {diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge.tsindex b85534411..96fe66392 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge.ts@@ -28,7 +28,6 @@ const VALID_LIFECYCLE_KINDS: ReadonlySet<NativeScreenCaptureLifecycleMessage['kiconst MAX_SOURCE_ID_LENGTH = 256;const MAX_REGISTRY_CAP = 64;-const CLOSED_CLEAN_DEDUP_WINDOW_MS = 500;export type VoiceEngineV2AppSourceLifecycleDispatch = (event: VoiceEngineV2Event) => void;@@ -36,25 +35,9 @@ type VoiceEngineV2AppSourceLifecycleSubscribe = (callback: (message: NativeScreenCaptureLifecycleMessage) => void,) => () => void;-interface VoiceEngineV2AppSourceLifecycleClosedCleanInfo {- captureId: string;- sourceId: string;- source: 'delegate' | 'programmatic' | 'unknown';- atMs: number;-}--export type VoiceEngineV2AppSourceLifecycleClosedCleanCallback = (- info: VoiceEngineV2AppSourceLifecycleClosedCleanInfo,-) => void;-export interface VoiceEngineV2AppSourceLifecycleBridgeOptions {dispatch: VoiceEngineV2AppSourceLifecycleDispatch;subscribe: VoiceEngineV2AppSourceLifecycleSubscribe;- diagnostics?: DiagnosticsPort;- onClosedClean?: VoiceEngineV2AppSourceLifecycleClosedCleanCallback;- clock?: SourceLifecycleClock;- now?: () => number;- cap?: number;}export interface VoiceEngineV2AppSourceLifecycleBindOptions {@@ -124,9 +107,6 @@ export class VoiceEngineV2AppSourceLifecycleBridge {private readonly diagnostics: DiagnosticsPort;private readonly registry: SourceLifecycleRegistry;private readonly bindingsByCapture: Map<string, RegisteredBinding>;- private readonly closedCleanLastAtMs: Map<string, number>;- private readonly onClosedClean: VoiceEngineV2AppSourceLifecycleClosedCleanCallback | null;- private readonly now: () => number;private readonly unsubscribe: () => void;private disposed = false;@@ -134,19 +114,12 @@ export class VoiceEngineV2AppSourceLifecycleBridge {assert.ok(options, 'bridge options must not be null');assert.equal(typeof options.dispatch, 'function', 'dispatch must be a function');assert.equal(typeof options.subscribe, 'function', 'subscribe must be a function');- const cap = options.cap ?? MAX_REGISTRY_CAP;- assert.ok(Number.isInteger(cap), 'cap must be an integer');- assert.ok(cap >= 1, 'cap must be >= 1');- this.now = options.now ?? defaultNow;- const clock = options.clock ?? makeBigIntClock(this.now);this.dispatch = options.dispatch;- this.diagnostics =- options.diagnostics ??- createVoiceEngineV2AppDiagnosticsAdapter({logger: new Logger('VoiceEngineV2AppSourceLifecycleBridge')});- this.registry = new SourceLifecycleRegistry(clock, cap);+ this.diagnostics = createVoiceEngineV2AppDiagnosticsAdapter({+ logger: new Logger('VoiceEngineV2AppSourceLifecycleBridge'),+ });+ this.registry = new SourceLifecycleRegistry(makeBigIntClock(defaultNow), MAX_REGISTRY_CAP);this.bindingsByCapture = new Map<string, RegisteredBinding>();- this.closedCleanLastAtMs = new Map<string, number>();- this.onClosedClean = options.onClosedClean ?? null;this.unsubscribe = options.subscribe((message) => this.handleNativeMessage(message));assert.equal(typeof this.unsubscribe, 'function', 'subscribe must return a disposer');}@@ -166,7 +139,7 @@ export class VoiceEngineV2AppSourceLifecycleBridge {since: registration.state.since,attempts: 0,fault: null,- atMs: this.now(),+ atMs: defaultNow(),};this.dispatch(event);return true;@@ -182,7 +155,6 @@ export class VoiceEngineV2AppSourceLifecycleBridge {const binding = this.bindingsByCapture.get(captureId);if (!binding) return false;this.bindingsByCapture.delete(captureId);- this.closedCleanLastAtMs.delete(captureId);const removed = this.registry.remove(binding.sourceId);assert.equal(removed, true, 'unbind must remove the registry entry');this.dispatch({type: 'sourceLifecycle.removed', sourceId: binding.sourceId});@@ -240,7 +212,7 @@ export class VoiceEngineV2AppSourceLifecycleBridge {since: result.state.since,attempts: deriveAttempts(result.state),fault: deriveFault(result.state),- atMs: this.now(),+ atMs: defaultNow(),};this.dispatch(event);}@@ -257,10 +229,7 @@ export class VoiceEngineV2AppSourceLifecycleBridge {this.reportDiagnostic(binding, message);return;}- if (message.kind === 'closed-clean') {- this.notifyClosedClean(binding, message);- return;- }+ if (message.kind === 'closed-clean') return;const lifecycleEvent = translateLifecycleEvent(message.kind);if (!lifecycleEvent) return;const result = this.registry.dispatch(binding.sourceId, lifecycleEvent);@@ -272,30 +241,11 @@ export class VoiceEngineV2AppSourceLifecycleBridge {since: result.state.since,attempts: deriveAttempts(result.state),fault: deriveFault(result.state),- atMs: this.now(),+ atMs: defaultNow(),};this.dispatch(event);}- private notifyClosedClean(binding: RegisteredBinding, message: NativeScreenCaptureLifecycleMessage): void {- assert.equal(message.kind, 'closed-clean', 'notifyClosedClean expects closed-clean kind');- assert.ok(binding.captureId.length > 0, 'closed-clean binding must have captureId');- const nowMs = this.now();- const lastMs = this.closedCleanLastAtMs.get(binding.captureId);- const withinWindow = lastMs !== undefined && nowMs - lastMs < CLOSED_CLEAN_DEDUP_WINDOW_MS;- if (withinWindow) return;- this.closedCleanLastAtMs.set(binding.captureId, nowMs);- if (!this.onClosedClean) return;- const source: 'delegate' | 'programmatic' | 'unknown' =- message.source === 'delegate' || message.source === 'programmatic' ? message.source : 'unknown';- this.onClosedClean({- captureId: binding.captureId,- sourceId: binding.sourceId,- source,- atMs: nowMs,- });- }-private reportDiagnostic(binding: RegisteredBinding, message: NativeScreenCaptureLifecycleMessage): void {assert.equal(message.kind, 'diagnostic', 'reportDiagnostic expects diagnostic kind');assert.ok(binding.captureId.length > 0, 'diagnostic binding must have captureId');diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter.tsindex 22712e697..9435ed8b9 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter.ts@@ -564,32 +564,11 @@ function toVoiceEngineV2Stats(rttMs: number | null, tracks: ReadonlyArray<PerTra};}-export interface VoiceEngineV2AppStatsHostAdapterScheduler {- setInterval(handler: () => void, intervalMs: number): unknown;- clearInterval(handle: unknown): void;-}--export interface VoiceEngineV2AppStatsHostAdapterOptions {- now?: () => number;- scheduler?: VoiceEngineV2AppStatsHostAdapterScheduler;-}--const DEFAULT_STATS_SCHEDULER: VoiceEngineV2AppStatsHostAdapterScheduler = {- setInterval(handler, intervalMs) {- return setInterval(handler, intervalMs);- },- clearInterval(handle) {- clearInterval(handle as NodeJS.Timeout);- },-};-export class VoiceEngineV2AppStatsHostAdapter extends Store {- private readonly now: () => number;- private readonly scheduler: VoiceEngineV2AppStatsHostAdapterScheduler;private room: Room | null = null;- private latencyIntervalId: unknown = null;- private statsIntervalId: unknown = null;- private statsClockIntervalId: unknown = null;+ private latencyIntervalId: ReturnType<typeof setInterval> | null = null;+ private statsIntervalId: ReturnType<typeof setInterval> | null = null;+ private statsClockIntervalId: ReturnType<typeof setInterval> | null = null;private statsSnapshot: VoiceStatsSnapshot = createVoiceStatsSnapshot();currentLatency: number | null = null;averageLatency: number | null = null;@@ -602,14 +581,6 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {reconnectionCount: number = 0;private graphStatsConnectionId: string | null = null;- constructor(options: VoiceEngineV2AppStatsHostAdapterOptions = {}) {- super();- this.now = options.now ?? (() => Date.now());- this.scheduler = options.scheduler ?? DEFAULT_STATS_SCHEDULER;- assert.equal(typeof this.now, 'function', 'now must be function');- assertNonNullObject(this.scheduler, 'scheduler');- }-private transitionStats(event: VoiceStatsEvent): void {this.update(() => {this.applyStatsEvent(event);@@ -660,7 +631,7 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {assert.ok(room === null || typeof room === 'object', 'room must be null or object');this.update(() => {this.room = room;- this.applyStatsEvent({type: 'room.set', roomIdentity: room, now: this.now()});+ this.applyStatsEvent({type: 'room.set', roomIdentity: room, now: Date.now()});});assert.equal(this.room, room, 'room must be persisted after set');}@@ -675,7 +646,7 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {inbound: [],};}- const now = this.now();+ const now = Date.now();assertFiniteNumber(now, 'now');const tracks: Array<PerTrackStats> = [];const activeCounterIds = new Set<string>();@@ -716,18 +687,18 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {private clearLatencyInterval(): void {if (this.latencyIntervalId === null) return;- this.scheduler.clearInterval(this.latencyIntervalId);+ clearInterval(this.latencyIntervalId);this.latencyIntervalId = null;}private clearStatsInterval(): void {if (this.statsIntervalId === null) return;- this.scheduler.clearInterval(this.statsIntervalId);+ clearInterval(this.statsIntervalId);this.statsIntervalId = null;}private onLatencyTick(): void {- const timestamp = this.now();+ const timestamp = Date.now();const engineWrap = this.room as RoomWithEngine;if (!engineWrap?.engine?.client?.rtt) {this.transitionStats({type: 'latency.gap', timestamp});@@ -741,7 +712,7 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {this.transitionStats({type: 'latency.start'});if (this.latencyIntervalId !== null) return;logger.debug('Starting latency tracking');- this.latencyIntervalId = this.scheduler.setInterval(() => this.onLatencyTick(), LATENCY_UPDATE_INTERVAL_MS);+ this.latencyIntervalId = setInterval(() => this.onLatencyTick(), LATENCY_UPDATE_INTERVAL_MS);assert.ok(this.latencyIntervalId !== null, 'latencyIntervalId must be set');}@@ -753,15 +724,15 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {private startStatsClock(): void {if (this.statsClockIntervalId !== null) return;- this.transitionStats({type: 'stats.tick', timestamp: this.now()});- this.statsClockIntervalId = this.scheduler.setInterval(() => {- this.transitionStats({type: 'stats.tick', timestamp: this.now()});+ this.transitionStats({type: 'stats.tick', timestamp: Date.now()});+ this.statsClockIntervalId = setInterval(() => {+ this.transitionStats({type: 'stats.tick', timestamp: Date.now()});}, STATS_CLOCK_INTERVAL_MS);}private stopStatsClock(): void {if (this.statsClockIntervalId === null) return;- this.scheduler.clearInterval(this.statsClockIntervalId);+ clearInterval(this.statsClockIntervalId);this.statsClockIntervalId = null;}@@ -798,7 +769,7 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {const subscriber = engine.pcManager.subscriber;const peerConnectionMode = engine.pcManager.mode;if (!publisher && !subscriber) return;- const now = this.now();+ const now = Date.now();const tracks: Array<PerTrackStats> = [];const activeCounterIds = new Set<string>();const rtpCounters = new Map<string, VoiceStatsRtpCounter>(decision.rtpCounters);@@ -882,7 +853,7 @@ export class VoiceEngineV2AppStatsHostAdapter extends Store {this.startStatsClock();if (this.statsIntervalId !== null) return;logger.debug('Starting stats tracking');- this.statsIntervalId = this.scheduler.setInterval(() => {+ this.statsIntervalId = setInterval(() => {void this.runStatsCollectionTick();}, STATS_UPDATE_INTERVAL_MS);assert.ok(this.statsIntervalId !== null, 'statsIntervalId must be set');diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter.tsindex f31c38f06..24ead35cc 100644--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter.ts+++ b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter.ts@@ -22,7 +22,7 @@ export interface VoiceEngineV2AppTimerAdapterOptions {}interface RegistryEntry {- handle: VoiceEngineV2AppTimerHandle;+ handle: ReturnType<typeof setTimeout>;scheduledAtMs: number;}@@ -75,11 +75,7 @@ export function createVoiceEngineV2AppTimerAdapter(options: VoiceEngineV2AppTime'voice-engine-v2 timer adapter requires a clock',);const clock = options.clock;- const scheduler = options.scheduler ?? defaultScheduler();- assert.equal(typeof scheduler.setTimeout, 'function', 'timer adapter scheduler must expose setTimeout');- assert.equal(typeof scheduler.clearTimeout, 'function', 'timer adapter scheduler must expose clearTimeout');- const cap = options.registryCap ?? VOICE_ENGINE_V2_TIMER_REGISTRY_CAP;- assert.ok(Number.isInteger(cap) && cap > 0, 'voice-engine-v2 timer adapter registryCap must be a positive integer');+ const cap = VOICE_ENGINE_V2_TIMER_REGISTRY_CAP;const registry = new Map<string, RegistryEntry>();const onFire = options.onFire;const onError = options.onError;@@ -88,7 +84,7 @@ export function createVoiceEngineV2AppTimerAdapter(options: VoiceEngineV2AppTimeassertOptions(timerOptions);const existing = registry.get(timerOptions.timerId);if (existing !== undefined) {- scheduler.clearTimeout(existing.handle);+ clearTimeout(existing.handle);registry.delete(timerOptions.timerId);}if (registry.size >= cap) {@@ -96,7 +92,7 @@ export function createVoiceEngineV2AppTimerAdapter(options: VoiceEngineV2AppTime}const scheduledAtMs = readClockMs(clock);const timerId = timerOptions.timerId;- const handle = scheduler.setTimeout(() => {+ const handle = setTimeout(() => {const entry = registry.get(timerId);if (entry === undefined) return;registry.delete(timerId);@@ -115,7 +111,7 @@ export function createVoiceEngineV2AppTimerAdapter(options: VoiceEngineV2AppTimeassert.ok(timerId.length > 0, 'voice-engine-v2 timer cancel timerId must not be empty');const entry = registry.get(timerId);if (entry === undefined) return;- scheduler.clearTimeout(entry.handle);+ clearTimeout(entry.handle);registry.delete(timerId);assert.ok(!registry.has(timerId), 'voice-engine-v2 timer registry must not retain cancelled entries');},diff --git a/fluxer_app/src/features/voice/hooks/useActivityRecorder.ts b/fluxer_app/src/features/voice/hooks/useActivityRecorder.tsindex 539199e81..bfe40292e 100644--- a/fluxer_app/src/features/voice/hooks/useActivityRecorder.ts+++ b/fluxer_app/src/features/voice/hooks/useActivityRecorder.ts@@ -3,23 +3,15 @@import Idle from '@app/features/ui/state/Idle';import {useCallback, useRef} from 'react';-const DEFAULT_THROTTLE_INTERVAL = 2000;+const THROTTLE_INTERVAL = 2000;-interface UseActivityRecorderOptions {- throttleInterval?: number;-}--export const useActivityRecorder = (options?: UseActivityRecorderOptions) => {- const throttleInterval = options?.throttleInterval ?? DEFAULT_THROTTLE_INTERVAL;+export const useActivityRecorder = () => {const lastActivityRef = useRef(0);- return useCallback(- (force = false) => {- const now = Date.now();- if (force || now - lastActivityRef.current > throttleInterval) {- lastActivityRef.current = now;- Idle.recordActivity();- }- },- [throttleInterval],- );+ return useCallback((force = false) => {+ const now = Date.now();+ if (force || now - lastActivityRef.current > THROTTLE_INTERVAL) {+ lastActivityRef.current = now;+ Idle.recordActivity();+ }+ }, []);};diff --git a/fluxer_app/src/features/voice/hooks/useMediaDevices.ts b/fluxer_app/src/features/voice/hooks/useMediaDevices.tsindex 39b92ca5d..cf96e3e99 100644--- a/fluxer_app/src/features/voice/hooks/useMediaDevices.ts+++ b/fluxer_app/src/features/voice/hooks/useMediaDevices.ts@@ -11,7 +11,6 @@ interface UseMediaDevicesOptions {interface RefreshOptions {requestPermissions?: boolean;- forceRefresh?: boolean;}type UseMediaDevicesResult = VoiceDeviceState & {@@ -29,7 +28,7 @@ export const useMediaDevices = (options: UseMediaDevicesOptions = {}): UseMediaDconst refreshDevices = useCallback(async (refreshOptions?: RefreshOptions) => {await VoiceDevicePermissionState.ensureDevices({- forceRefresh: refreshOptions?.forceRefresh ?? true,+ forceRefresh: true,requestPermissions: refreshOptions?.requestPermissions ?? requestPermissions,});},diff --git a/fluxer_app/src/features/voice/utils/VideoBackgroundProcessor.ts b/fluxer_app/src/features/voice/utils/VideoBackgroundProcessor.tsindex dd7a33034..489f1be05 100644--- a/fluxer_app/src/features/voice/utils/VideoBackgroundProcessor.ts+++ b/fluxer_app/src/features/voice/utils/VideoBackgroundProcessor.ts@@ -2,11 +2,7 @@import {Logger} from '@app/features/platform/utils/AppLogger';import {getBackgroundMediaObjectURL} from '@app/features/theme/utils/BackgroundImageDB';-import VoiceSettings, {- type BackgroundImage,- BLUR_BACKGROUND_ID,- NONE_BACKGROUND_ID,-} from '@app/features/voice/state/VoiceSettings';+import VoiceSettings, {BLUR_BACKGROUND_ID, NONE_BACKGROUND_ID} from '@app/features/voice/state/VoiceSettings';import {type CameraVideoProcessorHandle,type CameraVideoProcessorOptions,@@ -22,7 +18,6 @@ const logger = new Logger('VideoBackgroundProcessor');export interface BackgroundProcessorOptions {backgroundImageId?: string;- backgroundImages?: Array<BackgroundImage>;}export interface AppliedBackgroundProcessor {@@ -128,7 +123,7 @@ async function resolveBackgroundEffectConfig(if (backgroundImageId === BLUR_BACKGROUND_ID) {return {mode: CameraBackgroundMode.BLUR, blurStrength};}- const backgroundImages = options?.backgroundImages ?? VoiceSettings.getBackgroundImages();+ const backgroundImages = VoiceSettings.getBackgroundImages();const hasImage = backgroundImages.some((image) => image.id === backgroundImageId);if (!hasImage) {throw new Error(`Custom camera background is not present in the saved media list: ${backgroundImageId}`);diff --git a/fluxer_app/src/features/voice/utils/VoiceCameraCapacity.ts b/fluxer_app/src/features/voice/utils/VoiceCameraCapacity.tsindex 8ed8d2ad2..6c1425ba5 100644--- a/fluxer_app/src/features/voice/utils/VoiceCameraCapacity.ts+++ b/fluxer_app/src/features/voice/utils/VoiceCameraCapacity.ts@@ -12,7 +12,6 @@ export interface VoiceCameraUserCapInput {voiceStates: Readonly<Record<string, VoiceCameraCapacityVoiceState>>;currentUserId: string | null;isOwnCameraEnabled: boolean;- limit?: number;}function countDistinctCameraUsers(voiceStates: Readonly<Record<string, VoiceCameraCapacityVoiceState>>): number {@@ -31,9 +30,6 @@ function countDistinctCameraUsers(voiceStates: Readonly<Record<string, VoiceCame}export function isCameraUserCapBlocked(input: VoiceCameraUserCapInput): boolean {- const limit = input.limit ?? VOICE_CHANNEL_CAMERA_USER_LIMIT;- assert.ok(Number.isInteger(limit), 'camera user limit must be an integer');- assert.ok(limit > 0, 'camera user limit must be positive');if (input.isOwnCameraEnabled) return false;if (input.currentUserId) {for (const connectionId in input.voiceStates) {@@ -43,5 +39,5 @@ export function isCameraUserCapBlocked(input: VoiceCameraUserCapInput): booleanif (voiceState.self_video === true) return false;}}- return countDistinctCameraUsers(input.voiceStates) >= limit;+ return countDistinctCameraUsers(input.voiceStates) >= VOICE_CHANNEL_CAMERA_USER_LIMIT;}diff --git a/fluxer_app/src/features/voice/utils/VoiceTtsUtils.tsx b/fluxer_app/src/features/voice/utils/VoiceTtsUtils.tsxindex b388afde0..5afe676f6 100644--- a/fluxer_app/src/features/voice/utils/VoiceTtsUtils.tsx+++ b/fluxer_app/src/features/voice/utils/VoiceTtsUtils.tsx@@ -149,7 +149,6 @@ function hasRecentlySpoken(messageId: string): boolean {interface SpeakTextOptions {text: string;- interrupt?: boolean;maxLength?: number;rate?: number;onStart?: () => void;@@ -174,10 +173,8 @@ interface SpeakCallbacks {function speakText(options: SpeakTextOptions): void {ensureInitialized();- const {text, interrupt = true, maxLength, rate, onStart, onEnd, onError} = options;- if (interrupt) {- stopSpeaking();- }+ const {text, maxLength, rate, onStart, onEnd, onError} = options;+ stopSpeaking();const sessionId = beginSpeechSession();const callbacks: SpeakCallbacks = {onStart, onEnd, onError};if (canUseNativeSpeech()) {diff --git a/fluxer_app/src/features/window/hooks/useFluxerDocumentTitle.ts b/fluxer_app/src/features/window/hooks/useFluxerDocumentTitle.tsindex 6b1541e71..eee4d1a52 100644--- a/fluxer_app/src/features/window/hooks/useFluxerDocumentTitle.ts+++ b/fluxer_app/src/features/window/hooks/useFluxerDocumentTitle.ts@@ -8,10 +8,6 @@ import {useEffect} from 'react';type TitlePart = string | null | undefined;type TitleInput = TitlePart | Array<TitlePart>;-interface UseDocumentTitleOptions {- preserveTitleOnUnmount?: boolean;-}-interface BadgeState {mentionCount: number;hasUnread: boolean;@@ -55,18 +51,15 @@ export const updateDocumentTitleBadge = (mentionCount: number, hasUnread: booleacurrentBadgeState = {mentionCount, hasUnread};updateDocumentTitle();};-export const useFluxerDocumentTitle = (title?: TitleInput, options?: UseDocumentTitleOptions) => {+export const useFluxerDocumentTitle = (title?: TitleInput) => {const partsKey = JSON.stringify(normalizeTitleParts(title));- const preserveTitleOnUnmount = options?.preserveTitleOnUnmount;useEffect(() => {const previousParts = currentTitleParts;currentTitleParts = JSON.parse(partsKey) as Array<string>;updateDocumentTitle();return () => {- if (!preserveTitleOnUnmount) {- currentTitleParts = previousParts;- updateDocumentTitle();- }+ currentTitleParts = previousParts;+ updateDocumentTitle();};- }, [partsKey, preserveTitleOnUnmount]);+ }, [partsKey]);};diff --git a/fluxer_app/src/lib/forms/RemoteFormReset.ts b/fluxer_app/src/lib/forms/RemoteFormReset.tsindex 31fdd1c3a..92a6296d3 100644--- a/fluxer_app/src/lib/forms/RemoteFormReset.ts+++ b/fluxer_app/src/lib/forms/RemoteFormReset.ts@@ -10,20 +10,6 @@ type RemoteFormIdentityKey = string | number | boolean | null | undefined;type RemoteFormAutomaticResetReason = 'initial' | 'identity-change' | 'remote-clean';export type RemoteFormResetReason = RemoteFormAutomaticResetReason | 'commit' | 'explicit-reset';-interface RemoteFormResetOptions {- readonly keepDefaultValues?: boolean;- readonly keepDirty?: boolean;- readonly keepDirtyValues?: boolean;- readonly keepErrors?: boolean;- readonly keepIsSubmitted?: boolean;- readonly keepIsSubmitSuccessful?: boolean;- readonly keepIsValid?: boolean;- readonly keepIsValidating?: boolean;- readonly keepSubmitCount?: boolean;- readonly keepTouched?: boolean;- readonly keepValues?: boolean;-}-interface RemoteFormResetDecision {readonly shouldReset: boolean;readonly reason?: RemoteFormResetReason;@@ -126,10 +112,7 @@ interface UseRemoteFormResetBaseOptions<TFormValues extends FieldValues, TRemotereadonly form: UseFormReturn<TFormValues>;readonly identityKey: RemoteFormIdentityKey;readonly remoteValues: TRemoteValues | null | undefined;- readonly enabled?: boolean;readonly isDirty?: boolean;- readonly resetOptions?: RemoteFormResetOptions;- readonly areRemoteValuesEqual?: (left: TRemoteValues, right: TRemoteValues) => boolean;readonly onApply?: (remoteValues: TRemoteValues, reason: RemoteFormResetReason) => void;}@@ -160,18 +143,13 @@ export function useRemoteFormReset<TFormValues extends FieldValues, TRemoteValueform,identityKey,remoteValues,- enabled = true,isDirty,- resetOptions,getFormValues,- areRemoteValuesEqual = isEqual,onApply,}: UseRemoteFormResetOptions<TFormValues, TRemoteValues>): UseRemoteFormResetResult<TRemoteValues> {const latestRemoteValuesRef = useRef<TRemoteValues | null | undefined>(remoteValues);const latestIdentityKeyRef = useRef<RemoteFormIdentityKey>(identityKey);- const latestResetOptionsRef = useRef(resetOptions);const latestGetFormValuesRef = useRef(resolveFormValueMapper(getFormValues));- const latestAreRemoteValuesEqualRef = useRef(areRemoteValuesEqual);const latestOnApplyRef = useRef(onApply);const resetMachineSnapshotRef = useRef(createRemoteFormResetMachineSnapshot());const lastAppliedIdentityKeyRef = useRef<RemoteFormIdentityKey>(undefined);@@ -181,9 +159,7 @@ export function useRemoteFormReset<TFormValues extends FieldValues, TRemoteValuelatestRemoteValuesRef.current = remoteValues;latestIdentityKeyRef.current = identityKey;- latestResetOptionsRef.current = resetOptions;latestGetFormValuesRef.current = resolveFormValueMapper(getFormValues);- latestAreRemoteValuesEqualRef.current = areRemoteValuesEqual;latestOnApplyRef.current = onApply;const applyRemoteValues = useCallback(@@ -193,7 +169,7 @@ export function useRemoteFormReset<TFormValues extends FieldValues, TRemoteValuetype: reason === 'explicit-reset' ? 'remote.explicitReset' : 'remote.commit',});}- form.reset(latestGetFormValuesRef.current(values), latestResetOptionsRef.current);+ form.reset(latestGetFormValuesRef.current(values));lastAppliedIdentityKeyRef.current = latestIdentityKeyRef.current;lastAppliedRemoteValuesRef.current = values;latestOnApplyRef.current?.(values, reason);@@ -202,13 +178,13 @@ export function useRemoteFormReset<TFormValues extends FieldValues, TRemoteValue);useLayoutEffect(() => {- if (!enabled || remoteValues == null) return;+ if (remoteValues == null) return;const identityChanged = !Object.is(lastAppliedIdentityKeyRef.current, identityKey);const lastAppliedRemoteValues = lastAppliedRemoteValuesRef.current;const remoteValuesChanged =getRemoteFormResetMachineStateValue(resetMachineSnapshotRef.current) === 'unhydrated' ||lastAppliedRemoteValues == null ||- !latestAreRemoteValuesEqualRef.current(lastAppliedRemoteValues, remoteValues);+ !isEqual(lastAppliedRemoteValues, remoteValues);const snapshot = transitionRemoteFormResetSnapshot(resetMachineSnapshotRef.current, {type: 'remote.inspect',identityChanged,@@ -220,7 +196,7 @@ export function useRemoteFormReset<TFormValues extends FieldValues, TRemoteValueif (decision.shouldReset && decision.reason) {applyRemoteValues(remoteValues, decision.reason, false);}- }, [applyRemoteValues, enabled, identityKey, remoteValues, resolvedIsDirty]);+ }, [applyRemoteValues, identityKey, remoteValues, resolvedIsDirty]);const resetToRemoteValues = useCallback(() => {const latestRemoteValues = latestRemoteValuesRef.current;diff --git a/fluxer_app/src/lib/overlay/KeyedActionGuard.ts b/fluxer_app/src/lib/overlay/KeyedActionGuard.tsindex fb283eedc..b9f547031 100644--- a/fluxer_app/src/lib/overlay/KeyedActionGuard.ts+++ b/fluxer_app/src/lib/overlay/KeyedActionGuard.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-const DEFAULT_RELEASE_DELAY_MS = 2000;+const RELEASE_DELAY_MS = 2000;export interface KeyedActionGuard {begin: (key: string) => boolean;@@ -8,13 +8,7 @@ export interface KeyedActionGuard {scheduleRelease: (key: string) => void;}-interface KeyedActionGuardOptions {- releaseDelayMs?: number;-}--export function createKeyedActionGuard({- releaseDelayMs = DEFAULT_RELEASE_DELAY_MS,-}: KeyedActionGuardOptions = {}): KeyedActionGuard {+export function createKeyedActionGuard(): KeyedActionGuard {const inFlight = new Set<string>();const releaseTimers = new Map<string, NodeJS.Timeout>();const clearScheduledRelease = (key: string): void => {@@ -40,7 +34,7 @@ export function createKeyedActionGuard({const releaseTimer = setTimeout(() => {inFlight.delete(key);releaseTimers.delete(key);- }, releaseDelayMs);+ }, RELEASE_DELAY_MS);releaseTimers.set(key, releaseTimer);},};