Files
upstream-rocketchat/apps/meteor/client/views/room/composer/hooks/useComposerBoxPopup.ts
upstream-mirror 30810eecd7
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 2s
snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:21:02 +05:00

286 lines
7.6 KiB
TypeScript

import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import type { UseQueryResult } from '@tanstack/react-query';
import type { MutableRefObject } from 'react';
import { useEffect, useCallback, useState, useRef } from 'react';
import { useComposerBoxPopupQueries } from './useComposerBoxPopupQueries';
import { useChat } from '../../contexts/ChatContext';
import type { ComposerPopupOption } from '../../contexts/ComposerPopupContext';
type ComposerBoxPopupImperativeCommands<T> = MutableRefObject<
| {
getFilter?: () => string;
select?: (s: T) => void;
}
| undefined
>;
type ComposerBoxPopupOptions<T extends { _id: string; sort?: number | undefined }> = ComposerPopupOption<T>;
type ComposerBoxPopupResult<T extends { _id: string; sort?: number }> =
| {
option: ComposerPopupOption<T>;
items: UseQueryResult<T[]>[];
focused: T | undefined;
select: (item: T) => void;
callbackRef: (node: HTMLElement) => void;
commandsRef: ComposerBoxPopupImperativeCommands<T>;
suspended: boolean;
filter: unknown;
clear: () => void;
}
| {
option: undefined;
items: undefined;
focused: undefined;
callbackRef: (node: HTMLElement) => void;
select: undefined;
commandsRef: ComposerBoxPopupImperativeCommands<T>;
suspended: undefined;
filter: unknown;
clear: () => void;
};
const keys = {
TAB: 9,
ENTER: 13,
ESC: 27,
ARROW_UP: 38,
ARROW_DOWN: 40,
} as const;
export const useComposerBoxPopup = <T extends { _id: string; sort?: number }>(
options: ComposerBoxPopupOptions<T>[],
): ComposerBoxPopupResult<T> => {
const [optionIndex, setOptionIndex] = useState<number>(-1);
const [focused, setFocused] = useState<T | undefined>(undefined);
const [filter, setFilter] = useState('');
const option = options[optionIndex];
const commandsRef: ComposerBoxPopupImperativeCommands<T> = useRef(undefined);
const { queries: items, suspended } = useComposerBoxPopupQueries(filter, option) as {
queries: UseQueryResult<T[]>[];
suspended: boolean;
};
const chat = useChat();
useEffect(() => {
if (!option) {
return;
}
if (option?.preview && suspended) {
setFocused(undefined);
return;
}
setFocused((focused) => {
const sortedItems = items
.filter((item) => item.isSuccess)
.flatMap((item) => item.data)
.sort((a, b) => (('sort' in a && a.sort) || 0) - (('sort' in b && b.sort) || 0));
return sortedItems.find((item) => item._id === focused?._id) ?? sortedItems[0];
});
}, [items, option, suspended]);
const select = useStableCallback((item: T) => {
if (!option) {
throw new Error('No popup is open');
}
if (commandsRef.current?.select) {
commandsRef.current.select(item);
} else {
const value = chat?.composer?.substring(0, chat?.composer?.selection.start);
const selector =
option.matchSelectorRegex ??
(option.triggerAnywhere ? new RegExp(`(?:^| |\n)(${option.trigger})([^\\s]*$)`) : new RegExp(`(?:^)(${option.trigger})([^\\s]*$)`));
const result = value?.match(selector);
if (!result || !value) {
return;
}
chat?.composer?.replaceText((option.prefix ?? option.trigger ?? '') + option.getValue(item) + (option.suffix ?? ''), {
start: value.lastIndexOf(result[1] + result[2]),
end: chat?.composer?.selection.start,
});
}
setOptionIndex(-1);
setFocused(undefined);
});
const setOptionByInput = useStableCallback((): ComposerBoxPopupOptions<T> | undefined => {
const value = chat?.composer?.substring(0, chat?.composer?.selection.start);
if (!value) {
setOptionIndex(-1);
setFocused(undefined);
return;
}
const optionIndex = options.findIndex(({ trigger, matchSelectorRegex, triggerAnywhere, triggerLength }) => {
const selector =
matchSelectorRegex ?? (triggerAnywhere ? new RegExp(`(?:^| |\n)(${trigger})[^\\s]*$`) : new RegExp(`(?:^)(${trigger})[^\\s]*$`));
const result = selector.test(value);
if (!triggerLength || !result) {
return result;
}
const filter = value.match(selector);
return filter && triggerLength < filter[0].length;
});
setOptionIndex(optionIndex);
const option = options[optionIndex];
if (!option) {
setFocused(undefined);
setFilter('');
}
if (option) {
const selector =
option.matchSelectorRegex ??
(option.triggerAnywhere ? new RegExp(`(?:^| |\n)(${option.trigger})([^\\s]*$)`) : new RegExp(`(?:^)(${option.trigger})([^\\s]*$)`));
const result = value.match(selector);
setFilter(commandsRef.current?.getFilter?.() ?? (result ? result[2] : ''));
}
return option;
});
const handleFocus = useStableCallback(() => {
if (option) {
return;
}
setOptionByInput();
});
const handleInput = useStableCallback(() => {
setOptionByInput();
});
const handleKeyUp = useStableCallback((event: KeyboardEvent) => {
if (event.which === keys.ESC) {
if (option?.closeOnEsc === true) {
setOptionIndex(-1);
setFocused(undefined);
event.preventDefault();
event.stopImmediatePropagation();
}
return;
}
setOptionByInput();
});
const handleKeyDown = useStableCallback((event: KeyboardEvent) => {
if (!option) {
return;
}
if (event.which === keys.ENTER || event.which === keys.TAB) {
if (!focused) {
return;
}
select(focused);
event.preventDefault();
event.stopImmediatePropagation();
return true;
}
if (event.which === keys.ARROW_UP && !(event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) {
setFocused((focused) => {
const list = items
.filter((item) => item.isSuccess)
.flatMap((item) => item.data)
.sort((a, b) => (('sort' in a && a.sort) || 0) - (('sort' in b && b.sort) || 0));
if (!list) {
return;
}
const focusedIndex = list.findIndex((item) => item === focused);
return focusedIndex > 0 ? list[focusedIndex - 1] : list[list.length - 1];
});
event.preventDefault();
event.stopImmediatePropagation();
return true;
}
if (event.which === keys.ARROW_DOWN && !(event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) {
setFocused((focused) => {
const list = items
.filter((item) => item.isSuccess)
.flatMap((item) => item.data)
.sort((a, b) => (('sort' in a && a.sort) || 0) - (('sort' in b && b.sort) || 0));
if (!list) {
return undefined;
}
const focusedIndex = list.findIndex((item) => item === focused);
return focusedIndex < list.length - 1 ? list[focusedIndex + 1] : list[0];
});
event.preventDefault();
event.stopImmediatePropagation();
return true;
}
});
const clear = useStableCallback(() => {
setOptionIndex(-1);
setFocused(undefined);
setFilter('');
});
const ref = useRef<HTMLElement | null>(null);
const callbackRef = useCallback(
(node: HTMLElement | null) => {
if (ref.current) {
ref.current.removeEventListener('input', handleInput);
ref.current.removeEventListener('keyup', handleKeyUp);
ref.current.removeEventListener('keydown', handleKeyDown);
ref.current.removeEventListener('focus', handleFocus);
ref.current = null;
}
if (node) {
ref.current = node;
node.addEventListener('input', handleInput);
node.addEventListener('keyup', handleKeyUp);
node.addEventListener('keydown', handleKeyDown);
node.addEventListener('focus', handleFocus);
}
},
[handleInput, handleKeyUp, handleKeyDown, handleFocus],
);
if (!option) {
return {
option: undefined,
items: undefined,
focused: undefined,
select: undefined,
callbackRef,
commandsRef,
suspended: undefined,
filter: undefined,
clear,
};
}
return {
option,
items,
focused,
select,
callbackRef,
commandsRef,
suspended,
filter,
clear,
};
};