diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 8d22671f0..a866e8058 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -25,4 +25,5 @@ Fixes # - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). + diff --git a/src/app/components/ConfirmPasswordMatch.tsx b/src/app/components/ConfirmPasswordMatch.tsx index b004b3829..1b8d998e3 100644 --- a/src/app/components/ConfirmPasswordMatch.tsx +++ b/src/app/components/ConfirmPasswordMatch.tsx @@ -7,8 +7,8 @@ type ConfirmPasswordMatchProps = { children: ( match: boolean, doMatch: () => void, - passRef: RefObject, - confPassRef: RefObject + passRef: RefObject, + confPassRef: RefObject ) => ReactNode; }; export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPasswordMatchProps) { diff --git a/src/app/components/MobileSwipeDownModal.tsx b/src/app/components/MobileSwipeDownModal.tsx index 5b8594844..77b0a580c 100644 --- a/src/app/components/MobileSwipeDownModal.tsx +++ b/src/app/components/MobileSwipeDownModal.tsx @@ -1,4 +1,4 @@ -import type { ComponentProps, CSSProperties, RefObject } from 'react'; +import type { ComponentProps, CSSProperties, RefObject } from "react"; import React, { createContext, useCallback, @@ -6,17 +6,17 @@ import React, { useLayoutEffect, useRef, useState, -} from 'react'; -import { createPortal } from 'react-dom'; -import { Box } from 'folds'; -import FocusTrap from 'focus-trap-react'; -import { useDrag } from '@use-gesture/react'; -import * as css from '$features/room/message/styles.css'; -import { useDismissOnBack } from '$utils/androidBack'; -import { stopPropagation } from '$utils/keyboard'; -import { getMobileSheetTiming, useMobileSheetAnimation } from './mobileSheetAnimation'; -import { MOBILE_SHEET_DURATION_MS, MOBILE_SHEET_EASING } from './mobileSheetAnimationConstants'; -import * as animationCss from './mobileSheetAnimation.css'; +} from "react"; +import { createPortal } from "react-dom"; +import { Box } from "folds"; +import FocusTrap from "focus-trap-react"; +import { useDrag } from "@use-gesture/react"; +import * as css from "$features/room/message/styles.css"; +import { useDismissOnBack } from "$utils/androidBack"; +import { stopPropagation } from "$utils/keyboard"; +import { getMobileSheetTiming, useMobileSheetAnimation } from "./mobileSheetAnimation"; +import { MOBILE_SHEET_DURATION_MS, MOBILE_SHEET_EASING } from "./mobileSheetAnimationConstants"; +import * as animationCss from "./mobileSheetAnimation.css"; interface MobileSwipeDownModalProps { children: () => React.ReactNode; @@ -30,7 +30,7 @@ interface MobileSwipeDownModalProps { keyboardAware?: boolean; } -type FocusTrapOptions = ComponentProps['focusTrapOptions']; +type FocusTrapOptions = ComponentProps["focusTrapOptions"]; const MobileSheetCloseContext = createContext<(() => void) | null>(null); @@ -42,8 +42,8 @@ const DISMISS_VELOCITY = 0.5; /** Keeps a fling that lands at the top of a list from turning into a sheet drag. */ const DRAG_BLOCKED_COOLDOWN_MS = 200; -const HANDLE_ATTRIBUTE = 'data-mobile-sheet-handle'; -const NO_DRAG_ATTRIBUTE = 'data-mobile-sheet-no-drag'; +const HANDLE_ATTRIBUTE = "data-mobile-sheet-handle"; +const NO_DRAG_ATTRIBUTE = "data-mobile-sheet-no-drag"; function getKeyboardOverlap(): number { const viewport = window.visualViewport; @@ -57,7 +57,7 @@ function findScroller(from: HTMLElement | null, boundary: HTMLElement): HTMLElem while (element && element !== boundary) { const { overflowY } = window.getComputedStyle(element); if ( - (overflowY === 'auto' || overflowY === 'scroll') && + (overflowY === "auto" || overflowY === "scroll") && element.scrollHeight > element.clientHeight ) { return element; @@ -123,15 +123,15 @@ export function MobileSwipeDownModal({ sheet.style.transition = animate && !shouldReduceMotion ? `transform ${MOBILE_SHEET_DURATION_MS}ms ${MOBILE_SHEET_EASING}` - : ''; - sheet.style.transform = y === 0 ? '' : `translate3d(0, ${y}px, 0)`; + : ""; + sheet.style.transform = y === 0 ? "" : `translate3d(0, ${y}px, 0)`; // Once lifted above the keyboard the bottom inset is no longer a safe area. sheet.style.setProperty( - '--mobile-sheet-safe-bottom', - keyboardOffset.current > 0 ? '0px' : '' + "--mobile-sheet-safe-bottom", + keyboardOffset.current > 0 ? "0px" : "", ); }, - [shouldReduceMotion] + [shouldReduceMotion], ); useLayoutEffect(() => { @@ -144,7 +144,7 @@ export function MobileSwipeDownModal({ const next = Math.max(stableViewportHeight, window.innerHeight); if (next === stableViewportHeight) return; stableViewportHeight = next; - sheetRef.current?.style.setProperty('--mobile-sheet-viewport', `${next}px`); + sheetRef.current?.style.setProperty("--mobile-sheet-viewport", `${next}px`); }; // The two viewports shrink in separate stages. Mid-way the visual one alone @@ -157,7 +157,7 @@ export function MobileSwipeDownModal({ if (closingRef.current) return; publishViewportHeight(); const visible = window.visualViewport?.height ?? window.innerHeight; - sheetRef.current?.style.setProperty('--mobile-sheet-visible', `${visible}px`); + sheetRef.current?.style.setProperty("--mobile-sheet-visible", `${visible}px`); const next = getKeyboardOverlap(); if (next === keyboardOffset.current) return; @@ -181,19 +181,19 @@ export function MobileSwipeDownModal({ const viewport = window.visualViewport; applySettled(); - window.addEventListener('resize', handleViewportChange); - window.addEventListener('scroll', handleViewportChange); - window.addEventListener('orientationchange', handleOrientationChange); - viewport?.addEventListener('resize', handleViewportChange); - viewport?.addEventListener('scroll', handleViewportChange); + window.addEventListener("resize", handleViewportChange); + window.addEventListener("scroll", handleViewportChange); + window.addEventListener("orientationchange", handleOrientationChange); + viewport?.addEventListener("resize", handleViewportChange); + viewport?.addEventListener("scroll", handleViewportChange); return () => { window.clearTimeout(settleTimer); - window.removeEventListener('resize', handleViewportChange); - window.removeEventListener('scroll', handleViewportChange); - window.removeEventListener('orientationchange', handleOrientationChange); - viewport?.removeEventListener('resize', handleViewportChange); - viewport?.removeEventListener('scroll', handleViewportChange); + window.removeEventListener("resize", handleViewportChange); + window.removeEventListener("scroll", handleViewportChange); + window.removeEventListener("orientationchange", handleOrientationChange); + viewport?.removeEventListener("resize", handleViewportChange); + viewport?.removeEventListener("scroll", handleViewportChange); }; }, [keyboardAware, applySheetOffset]); @@ -209,16 +209,16 @@ export function MobileSwipeDownModal({ } container.getAnimations().forEach((animation) => animation.cancel()); - container.style.transition = ''; + container.style.transition = ""; const startY = touchYDiff.current - keyboardOffset.current; const animation = container.animate( - [{ transform: `translate3d(0, ${startY}px, 0)` }, { transform: 'translate3d(0, 100%, 0)' }], + [{ transform: `translate3d(0, ${startY}px, 0)` }, { transform: "translate3d(0, 100%, 0)" }], { ...getMobileSheetTiming(shouldReduceMotion), duration: shouldReduceMotion ? 0 : 140, - } + }, ); - animation.addEventListener('finish', requestClose, { once: true }); + animation.addEventListener("finish", requestClose, { once: true }); }, [requestClose, shouldReduceMotion]); // Android back closes the overlay instead of navigating away. @@ -285,10 +285,10 @@ export function MobileSwipeDownModal({ target: sheetRef, eventOptions: { passive: false }, pointer: { capture: false, touch: true }, - axis: 'y', + axis: "y", // MobileMenuItem owns tap activation for marked actions; the sheet owns drag arbitration. filterTaps: false, - } + }, ); // A sheet opened by a long press mounts under the finger, and releasing it @@ -296,7 +296,7 @@ export function MobileSwipeDownModal({ // backdrop is a dismiss. const handleBackdropClick = (e: React.MouseEvent) => { const fromTouch = - e.nativeEvent instanceof PointerEvent && e.nativeEvent.pointerType === 'touch'; + e.nativeEvent instanceof PointerEvent && e.nativeEvent.pointerType === "touch"; if (fromTouch && !backdropTouchRef.current) return; closeWithAnimation(); }; @@ -306,7 +306,7 @@ export function MobileSwipeDownModal({ className={css.MessageMobileDragHandle} data-gestures="ignore" data-testid="mobile-sheet-drag-handle" - {...{ [HANDLE_ATTRIBUTE]: '' }} + {...{ [HANDLE_ATTRIBUTE]: "" }} >
@@ -356,10 +356,10 @@ export function MobileSwipeDownModal({ return createPortal( e.stopPropagation()} onPointerMove={(e: React.PointerEvent) => e.stopPropagation()} onPointerUp={(e: React.PointerEvent) => e.stopPropagation()} @@ -386,6 +386,6 @@ export function MobileSwipeDownModal({
{dialog}
, - target + target, ); } diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index d29f6333e..0c51c88da 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -1,4 +1,4 @@ -import type { CSSProperties } from 'react'; +import type { CSSProperties, JSX } from 'react'; import { memo, useMemo, useCallback } from 'react'; import type { IPreviewUrlResponse, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; import { MsgType } from '$types/matrix-sdk'; diff --git a/src/app/components/SettingsShell.tsx b/src/app/components/SettingsShell.tsx index b02699151..581fd4ea4 100644 --- a/src/app/components/SettingsShell.tsx +++ b/src/app/components/SettingsShell.tsx @@ -1,4 +1,4 @@ -import type { ComponentType, ReactNode } from 'react'; +import type { ComponentType, JSX, ReactNode } from 'react'; import type { IconProps } from '@phosphor-icons/react'; import { Box, config, IconButton, MenuItem, Text } from 'folds'; import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '$components/page'; diff --git a/src/app/components/app-shell/SystemBarShell.tsx b/src/app/components/app-shell/SystemBarShell.tsx index 7d3127a2f..d0ae5fee3 100644 --- a/src/app/components/app-shell/SystemBarShell.tsx +++ b/src/app/components/app-shell/SystemBarShell.tsx @@ -34,13 +34,13 @@ function rgbToArgb(color: string): number | undefined { // Color of the surface adjacent to a strip; on Android also tints the native system bar. function useBarColor( - probeRef: RefObject, + probeRef: RefObject, edge: 'top' | 'bottom', android: boolean, enabled: boolean ): string | undefined { const [color, setColor] = useState(); - const lastRef = useRef(); + const lastRef = useRef(undefined); useEffect(() => { if (!enabled) return undefined; @@ -106,7 +106,7 @@ type SystemBarStripProps = { edge: 'top' | 'bottom'; size: string; background: string; - stripRef?: RefObject; + stripRef?: RefObject; transition?: string; }; diff --git a/src/app/components/editor/Editor.tsx b/src/app/components/editor/Editor.tsx index 413aba42d..bddadbed9 100644 --- a/src/app/components/editor/Editor.tsx +++ b/src/app/components/editor/Editor.tsx @@ -171,7 +171,7 @@ export const CustomEditor = forwardRef( ]); const rootRef = useRef(null); const editableRef = useRef(null); - const focusScrollTimerRef = useRef(); + const focusScrollTimerRef = useRef(undefined); const rowRef = useRef(null); const beforeRef = useRef(null); const afterRef = useRef(null); diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index 6c8d78a04..32ca2f14f 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -372,7 +372,7 @@ function StickerSidebar({ } type EmojiGroupHolderProps = { - contentScrollRef: RefObject; + contentScrollRef: RefObject; previewAtom: PrimitiveAtom; children?: ReactNode; onGroupItemClick: MouseEventHandler; diff --git a/src/app/components/message/RenderBody.tsx b/src/app/components/message/RenderBody.tsx index 6a40953cb..f9c32e7ec 100644 --- a/src/app/components/message/RenderBody.tsx +++ b/src/app/components/message/RenderBody.tsx @@ -1,4 +1,4 @@ -import type { KeyboardEventHandler, MouseEventHandler } from 'react'; +import type { JSX, KeyboardEventHandler, MouseEventHandler } from 'react'; import { useEffect, useState } from 'react'; import type { HTMLReactParserOptions } from 'html-react-parser'; import parse from 'html-react-parser'; diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 66cf450c2..e6b40a271 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -1,7 +1,7 @@ import { Box, Chip, Text, as, color, toRem } from 'folds'; import type { EventTimelineSet, IMentions, Room } from '$types/matrix-sdk'; import { EventType, MsgType } from '$types/matrix-sdk'; -import type { MouseEventHandler, ReactNode } from 'react'; +import type { JSX, MouseEventHandler, ReactNode } from 'react'; import { useCallback, useMemo } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import classNames from 'classnames'; diff --git a/src/app/components/page/MobileNavDrawer.tsx b/src/app/components/page/MobileNavDrawer.tsx index 9d4d2c117..c3fc39d38 100644 --- a/src/app/components/page/MobileNavDrawer.tsx +++ b/src/app/components/page/MobileNavDrawer.tsx @@ -94,11 +94,11 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra const positionRef = useRef(0); const [panelIntent, setPanelIntent] = useState(contentOpen ? 1 : 0); - const gestureRef = useRef(); + const gestureRef = useRef(undefined); const messageTargetsRef = useRef(new WeakMap()); const chatTargetsRef = useRef(new WeakMap()); - const settleAnimationRef = useRef(); - const programmaticTargetRef = useRef(); + const settleAnimationRef = useRef(undefined); + const programmaticTargetRef = useRef(undefined); const setTrackPosition = useCallback((position: number) => { positionRef.current = position; diff --git a/src/app/components/text-viewer/TextViewer.test.tsx b/src/app/components/text-viewer/TextViewer.test.tsx index 8308ec100..40ebf1374 100644 --- a/src/app/components/text-viewer/TextViewer.test.tsx +++ b/src/app/components/text-viewer/TextViewer.test.tsx @@ -1,3 +1,4 @@ +import type { JSX } from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { afterEach, describe, expect, it, vi } from 'vitest'; diff --git a/src/app/features/call/CallView.tsx b/src/app/features/call/CallView.tsx index 62d79cd6d..6e8db64a4 100644 --- a/src/app/features/call/CallView.tsx +++ b/src/app/features/call/CallView.tsx @@ -142,7 +142,7 @@ function CallPrescreen() { } type CallJoinedProps = { - containerRef: RefObject; + containerRef: RefObject; }; function CallJoined({ containerRef }: CallJoinedProps) { diff --git a/src/app/features/message-search/SearchInput.tsx b/src/app/features/message-search/SearchInput.tsx index db3a169bf..c79b0bfb9 100644 --- a/src/app/features/message-search/SearchInput.tsx +++ b/src/app/features/message-search/SearchInput.tsx @@ -5,7 +5,7 @@ import { sizedIcon, MagnifyingGlass, X } from '$components/icons/phosphor'; type SearchProps = { active?: boolean; loading?: boolean; - searchInputRef: RefObject; + searchInputRef: RefObject; onSearch: (term: string) => void; onReset: () => void; }; diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index d081c7e22..7de46cb5e 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -282,7 +282,7 @@ const createUploadItemKey = () => interface RoomInputProps { editor: Editor; - fileDropContainerRef: RefObject; + fileDropContainerRef: RefObject; roomId: string; room: Room; threadRootId?: string; @@ -376,7 +376,7 @@ export const RoomInput = forwardRef( roomUploadAtomFamily, selectedFiles.map((f) => f.file) ); - const uploadBoardHandlers = useRef(); + const uploadBoardHandlers = useRef(undefined); const longPressTimer = useRef | null>(null); const isLongPress = useRef(false); const suppressBlurRefocusRef = useRef(false); @@ -603,8 +603,8 @@ export const RoomInput = forwardRef( [room] ); - const prevEditingEventId = useRef(); - const preEditDraftRef = useRef(); + const prevEditingEventId = useRef(undefined); + const preEditDraftRef = useRef(undefined); useEffect(() => { if (!isMobileOrTablet()) { prevEditingEventId.current = undefined; @@ -2317,7 +2317,10 @@ export const RoomInput = forwardRef( align="End" anchor={(() => { if (emojiBoardTab === undefined) return undefined; - const buttonRefs: Record> = { + const buttonRefs: Record< + EditorButtonId, + RefObject + > = { gif: gifBtnRef, sticker: stickerBtnRef, emoji: emojiBtnRef, diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index cf0068ce3..6e4f5da83 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -75,7 +75,7 @@ const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { export function RoomView({ eventId }: { eventId?: string }) { const roomInputRef = useRef(null); const roomViewRef = useRef(null); - const editLastMessageRef = useRef<(() => void) | undefined>(); + const editLastMessageRef = useRef<(() => void) | undefined>(undefined); const [hideReads] = useSetting(settingsAtom, 'hideReads'); const screenSize = useScreenSizeContext(); diff --git a/src/app/features/room/message/Message.test.tsx b/src/app/features/room/message/Message.test.tsx new file mode 100644 index 000000000..d218c6b09 --- /dev/null +++ b/src/app/features/room/message/Message.test.tsx @@ -0,0 +1,100 @@ +import { createRef } from 'react'; +import { render } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { Message } from './Message'; + +/* oxlint-disable typescript/no-explicit-any */ + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => + ({ + getUserId: () => '@me:example.com', + mxcUrlToHttp: () => null, + }) as any, +})); + +vi.mock('$hooks/useMediaAuthentication', () => ({ + useMediaAuthentication: () => false, +})); + +vi.mock('$hooks/useUserProfile', () => ({ + useUserProfile: () => ({}), +})); + +vi.mock('$hooks/useSableCosmetics', () => ({ + useSableCosmetics: () => ({ color: undefined, font: undefined }), +})); + +vi.mock('$hooks/useRoomMemberHydration', () => ({ + useRoomMemberHydration: () => undefined, +})); + +vi.mock('$hooks/useRenderableMediaUrl', () => ({ + useRenderableMediaUrl: () => undefined, +})); + +vi.mock('$hooks/useMentionClickHandler', () => ({ + useMentionClickHandler: () => undefined, +})); + +vi.mock('$state/hooks/settings', () => ({ + useSetting: () => [false, vi.fn<() => void>()], +})); + +const createRoom = () => + ({ + roomId: '!room:example.com', + emit: () => {}, + getTimelineForEvent: () => undefined, + getMember: () => undefined, + }) as any; + +const createMessageEvent = () => + ({ + getContent: () => ({ msgtype: 'm.text', body: 'hello world' }), + getClearContent: () => ({ msgtype: 'm.text', body: 'hello world' }), + getId: () => '$evt:example.com', + getTs: () => 1700000000000, + getSender: () => '@alice:example.com', + getType: () => 'm.room.message', + sender: null, + on: () => {}, + off: () => {}, + }) as any; + +describe('Message forwarded ref', () => { + it('exposes the inner message HTMLDivElement on mount and clears on unmount', () => { + const ref = createRef(); + + const { container, unmount } = render( + {}} + onUsernameClick={() => {}} + onReplyClick={() => {}} + onReactionToggle={() => {}} + hour24Clock + dateFormatString="dd MMM yyyy" + senderId="@alice:example.com" + senderDisplayName="Alice" + > + hello world + + ); + + const messageDiv = container.querySelector('[tabindex="0"]'); + expect(messageDiv).not.toBeNull(); + expect(ref.current).toBeInstanceOf(HTMLDivElement); + expect(ref.current).toBe(messageDiv); + expect(ref.current).toHaveTextContent('hello world'); + + unmount(); + + expect(ref.current).toBeNull(); + }); +}); diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 12f15fd3c..6ba53b466 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -12,7 +12,7 @@ import { config, toRem, } from 'folds'; -import type { KeyboardEventHandler, MouseEventHandler, MouseEvent, ReactNode } from 'react'; +import type { JSX, KeyboardEventHandler, MouseEventHandler, MouseEvent, ReactNode } from 'react'; import { memo, useCallback, @@ -358,11 +358,7 @@ function MessageInternal( msc2723ForwardedMessageProps, ...props }: MessageProps & { className?: string; children?: ReactNode }, - ref: - | ((instance: HTMLDivElement | null) => void) - | React.RefObject - | null - | undefined + ref: React.Ref | undefined ) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index 3d9b30689..9df15d377 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -1,5 +1,5 @@ import { useMemo, useState } from 'react'; -import type { ComponentType, ReactNode } from 'react'; +import type { ComponentType, JSX, ReactNode } from 'react'; import { DesktopIcon, type IconProps } from '@phosphor-icons/react'; import { Avatar, Box, Button, config, Text } from 'folds'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; diff --git a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx index 32ce3c78c..65907d319 100644 --- a/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx +++ b/src/app/features/settings/notifications/NotificationTransportRuntimeFeature.tsx @@ -61,7 +61,7 @@ export function NotificationTransportRuntimeFeature() { const [useRichPushPayloads] = useSetting(settingsAtom, 'useRichPushPayloads'); const [pushNotifyUrlOverride] = useSetting(settingsAtom, 'pushNotifyUrlOverride'); - const runtimeRef = useRef(); + const runtimeRef = useRef(undefined); if (!runtimeRef.current) runtimeRef.current = new NotificationTransportRuntime(); // Read fresh by the listener for each incoming push, so toggling display diff --git a/src/app/hooks/timeline/useProcessedTimeline.ts b/src/app/hooks/timeline/useProcessedTimeline.ts index 748282003..f29872253 100644 --- a/src/app/hooks/timeline/useProcessedTimeline.ts +++ b/src/app/hooks/timeline/useProcessedTimeline.ts @@ -576,7 +576,7 @@ export function useProcessedTimeline({ hiddenEventReactionRedactionTimeline, hiddenEventOther, } = hiddenEvents; - const cacheRef = useRef(); + const cacheRef = useRef(undefined); return useMemo(() => { const timelineEvents = flattenTimelineEvents(linkedTimelines); diff --git a/src/app/hooks/useCallEmbed.ts b/src/app/hooks/useCallEmbed.ts index c55cfe831..1f93a8a95 100644 --- a/src/app/hooks/useCallEmbed.ts +++ b/src/app/hooks/useCallEmbed.ts @@ -28,9 +28,9 @@ export const useCallEmbed = (): CallEmbed | undefined => { return callEmbed; }; -const CallEmbedRefContext = createContext | undefined>(undefined); +const CallEmbedRefContext = createContext | undefined>(undefined); export const CallEmbedRefContextProvider = CallEmbedRefContext.Provider; -const useCallEmbedRef = (): RefObject => { +const useCallEmbedRef = (): RefObject => { const ref = useContext(CallEmbedRefContext); if (!ref) { throw new Error('CallEmbedRef is not provided!'); @@ -152,7 +152,9 @@ export const useCallThemeSync = (embed: CallEmbed) => { }, [theme.kind, embed]); }; -export const useCallEmbedPlacementSync = (containerViewRef: RefObject): void => { +export const useCallEmbedPlacementSync = ( + containerViewRef: RefObject +): void => { const callEmbedRef = useCallEmbedRef(); const syncCallEmbedPlacement = useCallback(() => { diff --git a/src/app/hooks/useDebounce.ts b/src/app/hooks/useDebounce.ts index 5f33976a3..e9e97a075 100644 --- a/src/app/hooks/useDebounce.ts +++ b/src/app/hooks/useDebounce.ts @@ -10,7 +10,7 @@ export function useDebounce( callback: DebounceCallback, options?: DebounceOptions ): DebounceCallback { - const timeoutIdRef = useRef(); + const timeoutIdRef = useRef(undefined); const { wait, immediate } = options ?? {}; const debounceCallback = useCallback( diff --git a/src/app/hooks/useFileDrop.test.tsx b/src/app/hooks/useFileDrop.test.tsx new file mode 100644 index 000000000..1d24713b5 --- /dev/null +++ b/src/app/hooks/useFileDrop.test.tsx @@ -0,0 +1,94 @@ +import { describe, it, expect, vi } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import type { RefObject } from 'react'; +import { useFileDropZone } from './useFileDrop'; + +// jsdom has no DragEvent/DataTransfer constructors, so drag events are faked +// with a plain Event carrying a minimal `dataTransfer` stand-in. +type FakeDataTransfer = { types: string[] } | { files: File[] }; + +const fireDragEvent = (target: HTMLElement, type: string, dataTransfer?: FakeDataTransfer) => { + const evt = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(evt, 'dataTransfer', { value: dataTransfer, configurable: true }); + act(() => { + target.dispatchEvent(evt); + }); +}; + +const setupZone = () => { + const target = document.createElement('div'); + const zoneRef: RefObject = { current: target }; + return { target, zoneRef }; +}; + +describe('useFileDropZone', () => { + it('ignores drags that do not contain files', () => { + const { target, zoneRef } = setupZone(); + const onDrop = vi.fn<(files: File[]) => void>(); + const { result } = renderHook(() => useFileDropZone(zoneRef, onDrop)); + + fireDragEvent(target, 'dragenter', { types: ['text/plain', 'text/uri-list'] }); + fireDragEvent(target, 'dragover'); + fireDragEvent(target, 'dragleave'); + + expect(result.current).toBe(false); + expect(onDrop).not.toHaveBeenCalled(); + }); + + it('activates on dragenter with files and only deactivates on dragleave after dragover', () => { + const { target, zoneRef } = setupZone(); + const { result } = renderHook(() => useFileDropZone(zoneRef, vi.fn())); + + fireDragEvent(target, 'dragenter', { types: ['Files'] }); + expect(result.current).toBe(true); + + // start -> leave is not enough; a dragover must happen first. + fireDragEvent(target, 'dragleave'); + expect(result.current).toBe(true); + + fireDragEvent(target, 'dragover'); + expect(result.current).toBe(true); + + fireDragEvent(target, 'dragleave'); + expect(result.current).toBe(false); + }); + + it('invokes onDrop with the dropped files and deactivates the zone', () => { + const { target, zoneRef } = setupZone(); + const onDrop = vi.fn<(files: File[]) => void>(); + const { result } = renderHook(() => useFileDropZone(zoneRef, onDrop)); + + fireDragEvent(target, 'dragenter', { types: ['Files'] }); + expect(result.current).toBe(true); + + const fileA = new File(['a'], 'a.txt', { type: 'text/plain' }); + const fileB = new File(['b'], 'b.txt', { type: 'text/plain' }); + fireDragEvent(target, 'drop', { files: [fileA, fileB] }); + + expect(onDrop).toHaveBeenCalledTimes(1); + expect(onDrop).toHaveBeenCalledWith([fileA, fileB]); + expect(result.current).toBe(false); + }); + + it('removes all drop-zone event listeners on unmount', () => { + const { target, zoneRef } = setupZone(); + const addSpy = vi.spyOn(target, 'addEventListener'); + const removeSpy = vi.spyOn(target, 'removeEventListener'); + + const { unmount } = renderHook(() => useFileDropZone(zoneRef, vi.fn())); + + const registered = new Map(addSpy.mock.calls.map(([type, listener]) => [type, listener])); + expect([...registered.keys()].toSorted()).toEqual([ + 'dragenter', + 'dragleave', + 'dragover', + 'drop', + ]); + + unmount(); + + registered.forEach((listener, type) => { + expect(removeSpy).toHaveBeenCalledWith(type, listener); + }); + }); +}); diff --git a/src/app/hooks/useFileDrop.ts b/src/app/hooks/useFileDrop.ts index d448b5e88..751f64b77 100644 --- a/src/app/hooks/useFileDrop.ts +++ b/src/app/hooks/useFileDrop.ts @@ -3,10 +3,10 @@ import { useState, useEffect, useRef } from 'react'; import { getDataTransferFiles } from '$utils/dom'; export const useFileDropZone = ( - zoneRef: RefObject, + zoneRef: RefObject, onDrop: (file: File[]) => void ): boolean => { - const dragStateRef = useRef<'start' | 'leave' | 'over'>(); + const dragStateRef = useRef<'start' | 'leave' | 'over' | undefined>(undefined); const [active, setActive] = useState(false); useEffect(() => { diff --git a/src/app/hooks/useSettingsSync.ts b/src/app/hooks/useSettingsSync.ts index 83b747c46..184021e96 100644 --- a/src/app/hooks/useSettingsSync.ts +++ b/src/app/hooks/useSettingsSync.ts @@ -104,7 +104,7 @@ export function useSettingsSyncEffect(): void { useAccountDataCallback(mx, onAccountData); // Debounced upload whenever settings change - const timerRef = useRef>(); + const timerRef = useRef | undefined>(undefined); useEffect(() => { clearTimeout(timerRef.current); const generation = ++uploadGenerationRef.current; diff --git a/src/app/hooks/useThrottle.ts b/src/app/hooks/useThrottle.ts index 12b249f29..b11c01692 100644 --- a/src/app/hooks/useThrottle.ts +++ b/src/app/hooks/useThrottle.ts @@ -11,8 +11,8 @@ export function useThrottle( callback: ThrottleCallback, options?: ThrottleOptions ): ThrottleCallback { - const timeoutIdRef = useRef(); - const argsRef = useRef(); + const timeoutIdRef = useRef(undefined); + const argsRef = useRef(undefined); const { wait, immediate } = options ?? {}; const debounceCallback = useCallback( diff --git a/src/app/hooks/useTimelineScrollActivity.ts b/src/app/hooks/useTimelineScrollActivity.ts index 100a0fef6..f53f4bc61 100644 --- a/src/app/hooks/useTimelineScrollActivity.ts +++ b/src/app/hooks/useTimelineScrollActivity.ts @@ -11,7 +11,7 @@ export const useScrollActivity = ( ): { isScrolling: boolean; notifyScroll: () => void } => { const [isScrolling, setIsScrolling] = useState(false); const isScrollingRef = useRef(false); - const idleTimerRef = useRef>(); + const idleTimerRef = useRef | undefined>(undefined); const notifyScroll = useCallback(() => { if (!isScrollingRef.current) { diff --git a/src/app/pages/App.tsx b/src/app/pages/App.tsx index 58e865900..c75c3da92 100644 --- a/src/app/pages/App.tsx +++ b/src/app/pages/App.tsx @@ -72,7 +72,7 @@ function renderSentryErrorFallback({ error, eventId }: { error: unknown; eventId function App() { const screenSize = useScreenSize(); useCompositionEndTracking(); - const jotaiStoreRef = useRef>(); + const jotaiStoreRef = useRef | undefined>(undefined); if (!jotaiStoreRef.current) { jotaiStoreRef.current = createStore(); } diff --git a/src/app/pages/client/explore/Server.tsx b/src/app/pages/client/explore/Server.tsx index d185b2a64..a49c7aa5c 100644 --- a/src/app/pages/client/explore/Server.tsx +++ b/src/app/pages/client/explore/Server.tsx @@ -90,7 +90,7 @@ const FALLBACK_ROOMS_LIMIT = 24; type SearchProps = { active?: boolean; loading?: boolean; - searchInputRef: RefObject; + searchInputRef: RefObject; onSearch: (term: string) => void; onReset: () => void; }; diff --git a/src/app/pages/client/inbox/Bookmarks.tsx b/src/app/pages/client/inbox/Bookmarks.tsx index d1248a275..0c0076f45 100644 --- a/src/app/pages/client/inbox/Bookmarks.tsx +++ b/src/app/pages/client/inbox/Bookmarks.tsx @@ -392,7 +392,7 @@ function BookmarkResultGroup({ type BookmarkFilterInputProps = { active?: boolean; loading?: boolean; - searchInputRef: React.RefObject; + searchInputRef: React.RefObject; onChange: ChangeEventHandler; }; function BookmarkFilterInput({ diff --git a/src/app/plugins/react-custom-html-parser.test.tsx b/src/app/plugins/react-custom-html-parser.test.tsx index 01d1ef3b1..fa78ce1d3 100644 --- a/src/app/plugins/react-custom-html-parser.test.tsx +++ b/src/app/plugins/react-custom-html-parser.test.tsx @@ -1,3 +1,4 @@ +import type { JSX } from 'react'; import { render, screen } from '@testing-library/react'; import parse from 'html-react-parser'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -95,7 +96,7 @@ describe('getReactCustomHtmlParser code blocks', () => { language: 'rust', allowDetect: false, }), - expect.anything() + undefined ); }); diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index 17cbb84fb..4a2b661dc 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -1,5 +1,11 @@ /* oxlint-disable jsx-a11y/alt-text */ -import type { CSSProperties, ComponentPropsWithoutRef, ReactEventHandler, ReactNode } from 'react'; +import type { + CSSProperties, + ComponentPropsWithoutRef, + JSX, + ReactEventHandler, + ReactNode, +} from 'react'; import { Fragment, useEffect, useMemo, useState } from 'react'; import type { HTMLReactParserOptions } from 'html-react-parser'; import { attributesToProps, domToReact, Element, Text as DOMText } from 'html-react-parser'; diff --git a/src/app/state/hooks/desktopSettings.test.tsx b/src/app/state/hooks/desktopSettings.test.tsx index 451753840..518ad36ec 100644 --- a/src/app/state/hooks/desktopSettings.test.tsx +++ b/src/app/state/hooks/desktopSettings.test.tsx @@ -1,4 +1,4 @@ -import { renderHook, act } from '@testing-library/react'; +import { act, renderHook, waitFor } from '@testing-library/react'; import { createStore, Provider } from 'jotai'; import { createElement, type ReactNode } from 'react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -76,12 +76,11 @@ describe('useDesktopSetting', () => { wrapper: makeWrapper(store), }); - await vi.waitFor(() => { + await waitFor(() => { expect(store.get(desktopSettingsReadyAtom)).toBe(true); + expect(result.current[0]).toBe(false); }); - expect(result.current[0]).toBe(false); - await act(async () => { await result.current[1](true); }); @@ -113,7 +112,7 @@ describe('useDesktopSetting', () => { wrapper: makeWrapper(store), }); - await vi.waitFor(() => { + await waitFor(() => { expect(store.get(desktopSettingsReadyAtom)).toBe(true); }); diff --git a/src/app/utils/ASCIILexicalTable.ts b/src/app/utils/ASCIILexicalTable.ts index bcda50f86..a39287d53 100644 --- a/src/app/utils/ASCIILexicalTable.ts +++ b/src/app/utils/ASCIILexicalTable.ts @@ -305,7 +305,7 @@ export const orderKeys = ( ): Array | undefined => { const newKeys: string[] = []; - for (let i = 0; i < keys.length; ) { + for (let i = 0; i < keys.length;) { const key = keys[i]; const collectedKeys: string[] = []; const [nextKeyIndex, nextKey] = findNextFilledKey(i + 1, keys); diff --git a/src/test/setup.ts b/src/test/setup.ts index 9a4e92f4a..8c963187f 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -7,3 +7,13 @@ class ResizeObserverPolyfill { } globalThis.ResizeObserver = globalThis.ResizeObserver ?? ResizeObserverPolyfill; + +class IntersectionObserverPolyfill { + observe() {} + unobserve() {} + disconnect() {} +} + +globalThis.IntersectionObserver = + globalThis.IntersectionObserver ?? + (IntersectionObserverPolyfill as unknown as typeof IntersectionObserver); diff --git a/vite.config.ts b/vite.config.ts index f980a90c8..e5be7e190 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -82,8 +82,8 @@ const copyFiles = { }, { src: 'node_modules/pdfjs-dist/build/pdf.worker.min.mjs', - dest: '', - rename: 'pdf.worker.min.js', + dest: '.', + rename: { name: 'pdf.worker.min.js', stripBase: true as const }, }, { src: 'config.json',