Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(app): add the account tile grid with drag reordering

Hampusaaee3f0f58ad
diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherAccountMenu.tsx b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherAccountMenu.tsx
new file mode 100644
index 000000000..748827891
--- /dev/null
+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherAccountMenu.tsx
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {
+ MOVE_LEFT_DESCRIPTOR,
+ MOVE_RIGHT_DESCRIPTOR,
+} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherMessages';
+import {SIGN_IN_AGAIN_DESCRIPTOR} from '@app/features/auth/components/accounts/account_switcher_modal/AccountPickerShared';
+import {COPY_USER_ID_DESCRIPTOR, SIGN_OUT_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';
+import {remFromPx} from '@app/features/theme/layout/RemFromPx';
+import {CopyIdIcon, LeaveIcon} from '@app/features/ui/action_menu/ContextMenuIcons';
+import {MenuGroup} from '@app/features/ui/action_menu/MenuGroup';
+import {MenuItem} from '@app/features/ui/action_menu/MenuItem';
+import {useLingui} from '@lingui/react/macro';
+import {ArrowLeftIcon, ArrowRightIcon, SignInIcon} from '@phosphor-icons/react';
+import type React from 'react';
+
+interface AccountSwitcherAccountMenuProps {
+ readonly isExpired: boolean;
+ readonly onMoveLeft: (() => void) | null;
+ readonly onMoveRight: (() => void) | null;
+ readonly onSignInAgain: () => void;
+ readonly onCopyUserId: () => void;
+ readonly onSignOut: () => void;
+}
+
+export function AccountSwitcherAccountMenu({
+ isExpired,
+ onMoveLeft,
+ onMoveRight,
+ onSignInAgain,
+ onCopyUserId,
+ onSignOut,
+}: AccountSwitcherAccountMenuProps): React.ReactElement {
+ const {i18n} = useLingui();
+ return (
+ <>
+ <MenuGroup data-flx="auth.accounts.account-switcher.account-menu.group">
+ {isExpired ? (
+ <MenuItem
+ icon={
+ <SignInIcon
+ size={remFromPx(16)}
+ weight="fill"
+ data-flx="auth.accounts.account-switcher.account-menu.sign-in-icon"
+ />
+ }
+ onClick={onSignInAgain}
+ data-flx="auth.accounts.account-switcher.account-menu.menu-item.sign-in-again"
+ >
+ {i18n._(SIGN_IN_AGAIN_DESCRIPTOR)}
+ </MenuItem>
+ ) : null}
+ <MenuItem
+ icon={<CopyIdIcon data-flx="auth.accounts.account-switcher.account-menu.copy-id-icon" />}
+ onClick={onCopyUserId}
+ data-flx="auth.accounts.account-switcher.account-menu.menu-item.copy-user-id"
+ >
+ {i18n._(COPY_USER_ID_DESCRIPTOR)}
+ </MenuItem>
+ </MenuGroup>
+ <MenuGroup data-flx="auth.accounts.account-switcher.account-menu.move-group">
+ {onMoveLeft == null ? null : (
+ <MenuItem
+ icon={
+ <ArrowLeftIcon
+ size={remFromPx(16)}
+ weight="bold"
+ data-flx="auth.accounts.account-switcher.account-menu.move-left-icon"
+ />
+ }
+ onClick={onMoveLeft}
+ data-flx="auth.accounts.account-switcher.account-menu.menu-item.move-left"
+ >
+ {i18n._(MOVE_LEFT_DESCRIPTOR)}
+ </MenuItem>
+ )}
+ {onMoveRight == null ? null : (
+ <MenuItem
+ icon={
+ <ArrowRightIcon
+ size={remFromPx(16)}
+ weight="bold"
+ data-flx="auth.accounts.account-switcher.account-menu.move-right-icon"
+ />
+ }
+ onClick={onMoveRight}
+ data-flx="auth.accounts.account-switcher.account-menu.menu-item.move-right"
+ >
+ {i18n._(MOVE_RIGHT_DESCRIPTOR)}
+ </MenuItem>
+ )}
+ </MenuGroup>
+ <MenuGroup data-flx="auth.accounts.account-switcher.account-menu.danger-group">
+ <MenuItem
+ icon={<LeaveIcon data-flx="auth.accounts.account-switcher.account-menu.sign-out-icon" />}
+ danger
+ onClick={onSignOut}
+ data-flx="auth.accounts.account-switcher.account-menu.menu-item.sign-out"
+ >
+ {i18n._(SIGN_OUT_DESCRIPTOR)}
+ </MenuItem>
+ </MenuGroup>
+ </>
+ );
+}
diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherGrid.tsx b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherGrid.tsx
new file mode 100644
index 000000000..cdaab6dd2
--- /dev/null
+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherGrid.tsx
@@ -0,0 +1,352 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {useAccountAvatarURL} from '@app/features/auth/AccountAvatarUtils';
+import {useAccountDisplayIdentityView} from '@app/features/auth/components/accounts/AccountIdentity';
+import {
+ AccountTileConnection,
+ getAccountTileActivity,
+} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherActivity';
+import styles from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherGrid.module.css';
+import {
+ CONNECTION_OFFLINE_DESCRIPTOR,
+ CURRENT_ACCOUNT_DESCRIPTOR,
+ HAS_UNREAD_MESSAGES_DESCRIPTOR,
+ ON_INSTANCE_DESCRIPTOR,
+ RECONNECTING_DESCRIPTOR,
+ SLOT_POSITION_DESCRIPTOR,
+} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherMessages';
+import type {SwitcherAvatarMediaSize} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherNavigation';
+import {
+ type AccountMenuTrigger,
+ AccountSwitcherAddTile,
+ type AccountSwitcherTileModel,
+ AccountSwitcherTileView,
+ AccountTileLineTone,
+ ADD_ACCOUNT_TILE_KEY,
+} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherTile';
+import {useAccountInstanceBadge} from '@app/features/auth/components/accounts/account_switcher/useAccountInstanceBadge';
+import {
+ type AccountTileReorderHandlers,
+ useAccountGridReorder,
+ useAccountTileReorder,
+} from '@app/features/auth/components/accounts/account_switcher/useAccountTileReorder';
+import {
+ SAVED_ACCOUNTS_DESCRIPTOR,
+ SESSION_EXPIRED_DESCRIPTOR,
+} from '@app/features/auth/components/accounts/account_switcher_modal/AccountPickerShared';
+import {ADD_AN_ACCOUNT_DESCRIPTOR} from '@app/features/auth/components/accounts/account_switcher_modal/AccountSwitcherAuthFlow';
+import type {InstanceInfo} from '@app/features/auth/flow/instance_selector/InstanceDirectoryStorage';
+import {getAccountKey} from '@app/features/auth/state/AccountStorageKey';
+import {MENTION_COUNT_ARIA_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';
+import type {Account} from '@app/features/platform/state/AuthSession';
+import type {I18n} from '@lingui/core';
+import {useLingui} from '@lingui/react/macro';
+import {observer} from 'mobx-react-lite';
+import type React from 'react';
+import {useCallback} from 'react';
+
+interface SecondLine {
+ readonly text: string;
+ readonly tone: AccountTileLineTone;
+}
+
+interface SecondLineInput {
+ readonly i18n: I18n;
+ readonly isExpired: boolean;
+ readonly connection: AccountTileConnection;
+ readonly showInstance: boolean;
+ readonly instanceHost: string | null;
+ readonly usernameLine: string;
+ readonly displayName: string;
+}
+
+function resolveSecondLine({
+ i18n,
+ isExpired,
+ connection,
+ showInstance,
+ instanceHost,
+ usernameLine,
+ displayName,
+}: SecondLineInput): SecondLine {
+ if (isExpired) {
+ return {text: i18n._(SESSION_EXPIRED_DESCRIPTOR), tone: AccountTileLineTone.DANGER};
+ }
+ if (connection === AccountTileConnection.RECONNECTING) {
+ return {text: i18n._(RECONNECTING_DESCRIPTOR), tone: AccountTileLineTone.WARNING};
+ }
+ if (connection === AccountTileConnection.OFFLINE) {
+ return {text: i18n._(CONNECTION_OFFLINE_DESCRIPTOR), tone: AccountTileLineTone.WARNING};
+ }
+ if (showInstance && instanceHost != null) {
+ return {text: instanceHost, tone: AccountTileLineTone.MUTED};
+ }
+ return {text: usernameLine === displayName ? '' : usernameLine, tone: AccountTileLineTone.MUTED};
+}
+
+interface AriaLabelInput {
+ readonly i18n: I18n;
+ readonly displayName: string;
+ readonly usernameLine: string;
+ readonly instanceLabel: string | null;
+ readonly isCurrent: boolean;
+ readonly statusLine: string | null;
+ readonly mentionCount: number;
+ readonly hasUnread: boolean;
+ readonly slot: number | null;
+}
+
+function buildTileAriaLabel({
+ i18n,
+ displayName,
+ usernameLine,
+ instanceLabel,
+ isCurrent,
+ statusLine,
+ mentionCount,
+ hasUnread,
+ slot,
+}: AriaLabelInput): string {
+ const parts = [displayName];
+ if (usernameLine.length > 0 && usernameLine !== displayName) {
+ parts.push(usernameLine);
+ }
+ if (instanceLabel != null) {
+ parts.push(i18n._(ON_INSTANCE_DESCRIPTOR, {instanceLabel}));
+ }
+ if (isCurrent) {
+ parts.push(i18n._(CURRENT_ACCOUNT_DESCRIPTOR));
+ }
+ if (statusLine != null) {
+ parts.push(statusLine);
+ }
+ if (mentionCount > 0) {
+ parts.push(i18n._(MENTION_COUNT_ARIA_DESCRIPTOR, {mentionCount}));
+ } else if (hasUnread) {
+ parts.push(i18n._(HAS_UNREAD_MESSAGES_DESCRIPTOR));
+ }
+ if (slot != null) {
+ parts.push(i18n._(SLOT_POSITION_DESCRIPTOR, {slot: slot + 1}));
+ }
+ return parts.join(', ');
+}
+
+interface AccountSwitcherGridReorder extends AccountTileReorderHandlers {
+ readonly order: ReadonlyArray<string>;
+ readonly enabled: boolean;
+ readonly isReordering: boolean;
+ readonly animateLayout: boolean;
+}
+
+interface AccountSwitcherGridState {
+ readonly activeKey: string | null;
+ readonly isManaging: boolean;
+ readonly pendingKey: string | null;
+ readonly menuKey: string | null;
+ readonly isBusy: boolean;
+}
+
+interface AccountTileProps extends AccountSwitcherGridState {
+ readonly account: Account;
+ readonly slot: number | null;
+ readonly currentAccountKey: string | null;
+ readonly showInstance: boolean;
+ readonly knownInstances: ReadonlyArray<InstanceInfo>;
+ readonly mediaSize: SwitcherAvatarMediaSize;
+ readonly reorder: AccountSwitcherGridReorder;
+ readonly onFocusTile: (key: string) => void;
+ readonly onActivate: (accountKey: string, event: React.MouseEvent<HTMLButtonElement>) => void;
+ readonly onOpenMenu: (accountKey: string, trigger: AccountMenuTrigger) => void;
+}
+
+const AccountTile = observer(function AccountTile({
+ account,
+ slot,
+ currentAccountKey,
+ showInstance,
+ knownInstances,
+ mediaSize,
+ reorder,
+ activeKey,
+ isManaging,
+ pendingKey,
+ menuKey,
+ isBusy,
+ onFocusTile,
+ onActivate,
+ onOpenMenu,
+}: AccountTileProps): React.ReactElement {
+ const {i18n} = useLingui();
+ const accountKey = getAccountKey(account);
+ const isCurrent = accountKey === currentAccountKey;
+ const identity = useAccountDisplayIdentityView(account);
+ const avatarUrl = useAccountAvatarURL(account, mediaSize);
+ const instanceBadge = useAccountInstanceBadge(account, knownInstances, showInstance);
+ const activity = getAccountTileActivity(accountKey, isCurrent);
+ const isExpired = account.isValid === false;
+ const {isDragging, dragRef, dropRef} = useAccountTileReorder({
+ accountKey,
+ enabled: reorder.enabled,
+ order: reorder.order,
+ onMoveTile: reorder.onMoveTile,
+ onDropTile: reorder.onDropTile,
+ onDragEnd: reorder.onDragEnd,
+ });
+ const usernameLine =
+ identity.discriminatorLabel == null
+ ? identity.usernameLabel
+ : `${identity.usernameLabel}${identity.discriminatorLabel}`;
+ const secondLine = resolveSecondLine({
+ i18n,
+ isExpired,
+ connection: activity.connection,
+ showInstance,
+ instanceHost: instanceBadge?.title ?? null,
+ usernameLine,
+ displayName: identity.displayLabel,
+ });
+ const tile: AccountSwitcherTileModel = {
+ accountKey,
+ displayName: identity.displayLabel,
+ secondLine: secondLine.text,
+ secondLineTone: secondLine.tone,
+ avatarUrl,
+ instanceBadge,
+ isCurrent,
+ isExpired,
+ mentionCount: isExpired ? 0 : activity.mentionCount,
+ hasUnread: !isExpired && activity.hasUnread,
+ ariaLabel: buildTileAriaLabel({
+ i18n,
+ displayName: identity.displayLabel,
+ usernameLine,
+ instanceLabel: instanceBadge?.label ?? null,
+ isCurrent,
+ statusLine: secondLine.tone === AccountTileLineTone.MUTED ? null : secondLine.text,
+ mentionCount: isExpired ? 0 : activity.mentionCount,
+ hasUnread: !isExpired && activity.hasUnread,
+ slot,
+ }),
+ };
+ return (
+ <AccountSwitcherTileView
+ tile={tile}
+ drag={{
+ isDragging,
+ isReordering: reorder.isReordering,
+ animateLayout: reorder.animateLayout,
+ dragRef,
+ dropRef,
+ }}
+ isActive={activeKey === accountKey}
+ isManaging={isManaging}
+ isPending={pendingKey === accountKey}
+ isDimmed={pendingKey != null && pendingKey !== accountKey}
+ isMenuOpen={menuKey === accountKey}
+ disabled={isBusy && pendingKey !== accountKey}
+ onFocusTile={onFocusTile}
+ onActivate={onActivate}
+ onOpenMenu={onOpenMenu}
+ data-flx="auth.accounts.account-switcher.grid.tile"
+ />
+ );
+});
+
+interface AccountSwitcherGridProps extends AccountSwitcherGridState {
+ readonly gridRef: (node: HTMLUListElement | null) => void;
+ readonly accounts: ReadonlyArray<Account>;
+ readonly slotByKey: ReadonlyMap<string, number>;
+ readonly currentAccountKey: string | null;
+ readonly showInstance: boolean;
+ readonly knownInstances: ReadonlyArray<InstanceInfo>;
+ readonly mediaSize: SwitcherAvatarMediaSize;
+ readonly reorder: AccountSwitcherGridReorder;
+ readonly showAddTile: boolean;
+ readonly onFocusTile: (key: string) => void;
+ readonly onActivate: (accountKey: string, event: React.MouseEvent<HTMLButtonElement>) => void;
+ readonly onOpenMenu: (accountKey: string, trigger: AccountMenuTrigger) => void;
+ readonly onAdd: () => void;
+ readonly onKeyDown: (event: React.KeyboardEvent<HTMLUListElement>) => void;
+}
+
+export const AccountSwitcherGrid = observer(function AccountSwitcherGrid({
+ gridRef,
+ accounts,
+ slotByKey,
+ currentAccountKey,
+ showInstance,
+ knownInstances,
+ mediaSize,
+ reorder,
+ showAddTile,
+ activeKey,
+ isManaging,
+ pendingKey,
+ menuKey,
+ isBusy,
+ onFocusTile,
+ onActivate,
+ onOpenMenu,
+ onAdd,
+ onKeyDown,
+}: AccountSwitcherGridProps): React.ReactElement {
+ const {i18n} = useLingui();
+ const dropRef = useAccountGridReorder({
+ order: reorder.order,
+ onMoveTile: reorder.onMoveTile,
+ onDropTile: reorder.onDropTile,
+ });
+ const setGridNode = useCallback(
+ (node: HTMLUListElement | null) => {
+ gridRef(node);
+ dropRef(node);
+ },
+ [dropRef, gridRef],
+ );
+ return (
+ <ul
+ ref={setGridNode}
+ className={styles.grid}
+ aria-label={i18n._(SAVED_ACCOUNTS_DESCRIPTOR)}
+ aria-busy={isBusy}
+ onKeyDown={onKeyDown}
+ data-flx="auth.accounts.account-switcher.grid"
+ >
+ {accounts.map((account) => {
+ const accountKey = getAccountKey(account);
+ return (
+ <AccountTile
+ key={accountKey}
+ account={account}
+ slot={slotByKey.get(accountKey) ?? null}
+ currentAccountKey={currentAccountKey}
+ showInstance={showInstance}
+ knownInstances={knownInstances}
+ mediaSize={mediaSize}
+ reorder={reorder}
+ activeKey={activeKey}
+ isManaging={isManaging}
+ pendingKey={pendingKey}
+ menuKey={menuKey}
+ isBusy={isBusy}
+ onFocusTile={onFocusTile}
+ onActivate={onActivate}
+ onOpenMenu={onOpenMenu}
+ data-flx="auth.accounts.account-switcher.grid.account-tile"
+ />
+ );
+ })}
+ {showAddTile ? (
+ <AccountSwitcherAddTile
+ label={i18n._(ADD_AN_ACCOUNT_DESCRIPTOR)}
+ isActive={activeKey === ADD_ACCOUNT_TILE_KEY}
+ isDimmed={pendingKey != null}
+ disabled={isBusy}
+ onFocusTile={onFocusTile}
+ onAdd={onAdd}
+ data-flx="auth.accounts.account-switcher.grid.add-tile"
+ />
+ ) : null}
+ </ul>
+ );
+});
diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountTileDropIndex.ts b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountTileDropIndex.ts
new file mode 100644
index 000000000..9eb4fcd87
--- /dev/null
+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountTileDropIndex.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+interface AccountSlotBox {
+ readonly left: number;
+ readonly top: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+interface AccountGridPoint {
+ readonly x: number;
+ readonly y: number;
+}
+
+interface AccountGridRow {
+ readonly first: number;
+ readonly centerY: number;
+ readonly centers: ReadonlyArray<number>;
+}
+
+export interface AccountGridLayout {
+ readonly rows: ReadonlyArray<AccountGridRow>;
+ readonly rowOf: ReadonlyArray<number>;
+ readonly rtl: boolean;
+}
+
+export function buildAccountGridLayout(slots: ReadonlyArray<AccountSlotBox>, rtl: boolean): AccountGridLayout {
+ const rows: Array<{first: number; top: number; centerY: number; centers: Array<number>}> = [];
+ const rowOf: Array<number> = [];
+ slots.forEach((slot, index) => {
+ const centerX = slot.left + slot.width / 2;
+ const row = rows.at(-1);
+ if (row == null || Math.abs(slot.top - row.top) > slot.height / 2) {
+ rows.push({
+ first: index,
+ top: slot.top,
+ centerY: slot.top + slot.height / 2,
+ centers: [rtl ? -centerX : centerX],
+ });
+ } else {
+ row.centers.push(rtl ? -centerX : centerX);
+ }
+ rowOf.push(rows.length - 1);
+ });
+ return {rows, rowOf, rtl};
+}
+
+function positionInRow(row: AccountGridRow, u: number): number {
+ const {first, centers} = row;
+ const lastOffset = centers.length - 1;
+ if (u < centers[0]) {
+ return first - 0.5;
+ }
+ if (u > centers[lastOffset]) {
+ return first + lastOffset + 0.5;
+ }
+ if (lastOffset === 0) {
+ return first;
+ }
+ let offset = 0;
+ while (offset + 1 < lastOffset && u >= centers[offset + 1]) {
+ offset += 1;
+ }
+ return first + offset + (u - centers[offset]) / (centers[offset + 1] - centers[offset]);
+}
+
+export interface AccountDropTarget {
+ readonly index: number;
+ readonly row: number;
+}
+
+export function initialAccountDropTarget(layout: AccountGridLayout, index: number): AccountDropTarget {
+ return {index, row: layout.rowOf[index] ?? 0};
+}
+
+function resolveIndex(position: number, row: number, indexRow: number, current: number): number {
+ if (row > indexRow) {
+ return Math.floor(position);
+ }
+ if (row < indexRow) {
+ return Math.ceil(position);
+ }
+ if (position >= current + 1) {
+ return Math.floor(position);
+ }
+ if (position <= current - 1) {
+ return Math.ceil(position);
+ }
+ return current;
+}
+
+export function resolveAccountDropTarget(
+ layout: AccountGridLayout,
+ pointer: AccountGridPoint,
+ current: AccountDropTarget,
+): AccountDropTarget {
+ const {rows, rowOf} = layout;
+ const indexRow = rowOf[current.index];
+ if (indexRow == null) {
+ return current;
+ }
+ let row = Math.min(current.row, rows.length - 1);
+ while (row + 1 < rows.length && pointer.y >= rows[row + 1].centerY) {
+ row += 1;
+ }
+ while (row > 0 && pointer.y <= rows[row - 1].centerY) {
+ row -= 1;
+ }
+ const position = positionInRow(rows[row], layout.rtl ? -pointer.x : pointer.x);
+ return {index: resolveIndex(position, row, indexRow, current.index), row};
+}
diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/useAccountTileReorder.ts b/fluxer_app/src/features/auth/components/accounts/account_switcher/useAccountTileReorder.ts
new file mode 100644
index 000000000..1d386f261
--- /dev/null
+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/useAccountTileReorder.ts
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {isKeyboardDragActive} from '@app/features/app/components/layout/dnd/KeyboardDragMode';
+import {type AccountTileDragItem, DragItemType} from '@app/features/app/components/layout/types/DndTypes';
+import {
+ type AccountDropTarget,
+ type AccountGridLayout,
+ buildAccountGridLayout,
+ initialAccountDropTarget,
+ resolveAccountDropTarget,
+} from '@app/features/auth/components/accounts/account_switcher/AccountTileDropIndex';
+import {useCallback, useRef} from 'react';
+import {useDrag, useDrop} from 'react-dnd';
+
+export interface AccountTileReorderHandlers {
+ readonly onMoveTile: (draggedKey: string, index: number) => void;
+ readonly onDropTile: () => void;
+ readonly onDragEnd: () => void;
+}
+
+interface UseAccountTileReorderOptions extends AccountTileReorderHandlers {
+ readonly accountKey: string;
+ readonly enabled: boolean;
+ readonly order: ReadonlyArray<string>;
+}
+
+export interface AccountTileReorder {
+ readonly isDragging: boolean;
+ readonly dragRef: (node: HTMLElement | null) => void;
+ readonly dropRef: (node: HTMLElement | null) => void;
+}
+
+export function useAccountTileReorder({
+ accountKey,
+ enabled,
+ order,
+ onMoveTile,
+ onDropTile,
+ onDragEnd,
+}: UseAccountTileReorderOptions): AccountTileReorder {
+ const [{isDragging}, connectDrag] = useDrag(
+ () => ({
+ type: DragItemType.ACCOUNT_TILE,
+ item: (): AccountTileDragItem => ({type: DragItemType.ACCOUNT_TILE, accountKey}),
+ canDrag: enabled,
+ collect: (monitor) => ({isDragging: monitor.isDragging()}),
+ end: () => onDragEnd(),
+ }),
+ [accountKey, enabled, onDragEnd],
+ );
+ const [, connectDrop] = useDrop(
+ () => ({
+ accept: DragItemType.ACCOUNT_TILE,
+ hover: (dragged: AccountTileDragItem) => {
+ const target = order.indexOf(accountKey);
+ if (isKeyboardDragActive() && dragged.accountKey !== accountKey && target >= 0) {
+ onMoveTile(dragged.accountKey, target);
+ }
+ },
+ drop: () => {
+ onDropTile();
+ },
+ }),
+ [accountKey, onDropTile, onMoveTile, order],
+ );
+ const dragRef = useCallback((node: HTMLElement | null) => connectDrag(node), [connectDrag]);
+ const dropRef = useCallback((node: HTMLElement | null) => connectDrop(node), [connectDrop]);
+ return {isDragging, dragRef, dropRef};
+}
+
+interface AccountGridDragSession {
+ readonly item: AccountTileDragItem;
+ layout: AccountGridLayout;
+ width: number;
+ target: AccountDropTarget;
+}
+
+function measureAccountGrid(grid: HTMLElement): AccountGridLayout {
+ const slots = Array.from(grid.querySelectorAll<HTMLElement>(':scope > [data-account-slot]'), (node) => {
+ const gridIsParent = node.offsetParent === grid;
+ return {
+ left: node.offsetLeft + (gridIsParent ? grid.clientLeft : -grid.offsetLeft),
+ top: node.offsetTop + (gridIsParent ? grid.clientTop : -grid.offsetTop),
+ width: node.offsetWidth,
+ height: node.offsetHeight,
+ };
+ });
+ return buildAccountGridLayout(slots, getComputedStyle(grid).direction === 'rtl');
+}
+
+interface UseAccountGridReorderOptions {
+ readonly order: ReadonlyArray<string>;
+ readonly onMoveTile: (draggedKey: string, index: number) => void;
+ readonly onDropTile: () => void;
+}
+
+export function useAccountGridReorder({
+ order,
+ onMoveTile,
+ onDropTile,
+}: UseAccountGridReorderOptions): (node: HTMLElement | null) => void {
+ const gridNodeRef = useRef<HTMLElement | null>(null);
+ const sessionRef = useRef<AccountGridDragSession | null>(null);
+ const [, connectDrop] = useDrop(
+ () => ({
+ accept: DragItemType.ACCOUNT_TILE,
+ hover: (dragged: AccountTileDragItem, monitor) => {
+ const grid = gridNodeRef.current;
+ const pointer = monitor.getClientOffset();
+ if (grid == null || pointer == null || isKeyboardDragActive()) {
+ return;
+ }
+ let session = sessionRef.current;
+ if (session == null || session.item !== dragged) {
+ const index = order.indexOf(dragged.accountKey);
+ if (index < 0) {
+ return;
+ }
+ const layout = measureAccountGrid(grid);
+ session = {item: dragged, layout, width: grid.clientWidth, target: initialAccountDropTarget(layout, index)};
+ sessionRef.current = session;
+ } else if (session.width !== grid.clientWidth) {
+ session.layout = measureAccountGrid(grid);
+ session.width = grid.clientWidth;
+ session.target = initialAccountDropTarget(session.layout, session.target.index);
+ }
+ const origin = grid.getBoundingClientRect();
+ const previous = session.target;
+ session.target = resolveAccountDropTarget(
+ session.layout,
+ {x: pointer.x - origin.left, y: pointer.y - origin.top},
+ previous,
+ );
+ if (session.target.index !== previous.index) {
+ onMoveTile(dragged.accountKey, session.target.index);
+ }
+ },
+ drop: (_item, monitor) => {
+ if (!monitor.didDrop()) {
+ onDropTile();
+ }
+ },
+ }),
+ [onDropTile, onMoveTile, order],
+ );
+ return useCallback(
+ (node: HTMLElement | null) => {
+ gridNodeRef.current = node;
+ connectDrop(node);
+ },
+ [connectDrop],
+ );
+}