snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
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 1s
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 1s
This commit is contained in:
116
apps/meteor/client/views/admin/customSounds/AddCustomSound.tsx
Normal file
116
apps/meteor/client/views/admin/customSounds/AddCustomSound.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
import { Field, FieldLabel, FieldRow, TextInput, Box, Margins, Button, ButtonGroup, IconButton } from '@rocket.chat/fuselage';
|
||||
import { ContextualbarScrollableContent, ContextualbarFooter } from '@rocket.chat/ui-client';
|
||||
import { useToastMessageDispatch, type UploadResult } from '@rocket.chat/ui-contexts';
|
||||
import fileSize from 'filesize';
|
||||
import type { ChangeEvent } from 'react';
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { validate } from './lib';
|
||||
import { CUSTOM_SOUND_ALLOWED_MIME_TYPES, MAX_CUSTOM_SOUND_SIZE_BYTES } from '../../../../lib/constants';
|
||||
import { useEndpointUploadMutation } from '../../../hooks/useEndpointUploadMutation';
|
||||
import { useSingleFileInput } from '../../../hooks/useSingleFileInput';
|
||||
|
||||
export type AddCustomSoundProps = {
|
||||
goToNew: (_id: string) => () => void;
|
||||
close: () => void;
|
||||
onChange: () => void;
|
||||
};
|
||||
|
||||
type CustomSoundCreateResult = UploadResult & {
|
||||
sound: {
|
||||
_id: string;
|
||||
};
|
||||
};
|
||||
|
||||
const AddCustomSound = ({ goToNew, close, onChange, ...props }: AddCustomSoundProps) => {
|
||||
const { t } = useTranslation();
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [sound, setSound] = useState<File | undefined>();
|
||||
|
||||
const { mutate: saveAction } = useEndpointUploadMutation<'/v1/custom-sounds.create', CustomSoundCreateResult>(
|
||||
'/v1/custom-sounds.create',
|
||||
{
|
||||
onSuccess: ({ sound }) => {
|
||||
dispatchToastMessage({ type: 'success', message: t('Custom_Sound_Saved_Successfully') });
|
||||
onChange();
|
||||
goToNew(sound._id)();
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const handleChangeFile = useCallback((soundFile: File) => {
|
||||
setSound(soundFile);
|
||||
}, []);
|
||||
|
||||
const [clickUpload] = useSingleFileInput(
|
||||
handleChangeFile,
|
||||
CUSTOM_SOUND_ALLOWED_MIME_TYPES.join(','),
|
||||
'audio',
|
||||
MAX_CUSTOM_SOUND_SIZE_BYTES,
|
||||
() => {
|
||||
dispatchToastMessage({
|
||||
type: 'error',
|
||||
message: t('File_exceeds_allowed_size_of_bytes', { size: fileSize(MAX_CUSTOM_SOUND_SIZE_BYTES, { base: 2, standard: 'jedec' }) }),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
const trimmedName = name.trim();
|
||||
const validation = validate({ name: trimmedName }, sound) as Array<Parameters<typeof t>[0]>;
|
||||
if (validation.length > 0) {
|
||||
const firstInvalidField = validation[0];
|
||||
dispatchToastMessage({
|
||||
type: 'error',
|
||||
message: t('Required_field', { field: t(firstInvalidField) }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
if (sound) {
|
||||
formData.append('sound', sound);
|
||||
}
|
||||
formData.append('name', trimmedName);
|
||||
saveAction(formData);
|
||||
}, [sound, name, saveAction, t, dispatchToastMessage]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ContextualbarScrollableContent {...props}>
|
||||
<Field>
|
||||
<FieldLabel>{t('Name')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<TextInput
|
||||
value={name}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>): void => setName(e.currentTarget.value)}
|
||||
placeholder={t('Name')}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel alignSelf='stretch'>{t('Sound File')}</FieldLabel>
|
||||
<Box display='flex' flexDirection='row' marginBlockStart='none' alignItems='center'>
|
||||
<Margins inline={4}>
|
||||
<IconButton secondary small icon='upload' onClick={clickUpload} />
|
||||
{sound?.name || t('None')}
|
||||
</Margins>
|
||||
</Box>
|
||||
</Field>
|
||||
</ContextualbarScrollableContent>
|
||||
<ContextualbarFooter>
|
||||
<ButtonGroup stretch>
|
||||
<Button onClick={close}>{t('Cancel')}</Button>
|
||||
<Button primary onClick={handleSave}>
|
||||
{t('Save')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</ContextualbarFooter>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddCustomSound;
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Button } from '@rocket.chat/fuselage';
|
||||
import {
|
||||
ContextualbarTitle,
|
||||
ContextualbarClose,
|
||||
ContextualbarHeader,
|
||||
ContextualbarDialog,
|
||||
Page,
|
||||
PageHeader,
|
||||
PageContent,
|
||||
} from '@rocket.chat/ui-client';
|
||||
import { useRoute, useRouteParameter } from '@rocket.chat/ui-contexts';
|
||||
import { useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import AddCustomSound from './AddCustomSound';
|
||||
import CustomSoundsTable from './CustomSoundsTable';
|
||||
import EditCustomSound from './EditCustomSound';
|
||||
|
||||
const CustomSoundsPage = () => {
|
||||
const { t } = useTranslation();
|
||||
const id = useRouteParameter('id');
|
||||
const route = useRoute('custom-sounds');
|
||||
const context = useRouteParameter('context');
|
||||
|
||||
const reload = useRef(() => null);
|
||||
|
||||
const handleItemClick = useCallback(
|
||||
(_id: string) => (): void => {
|
||||
route.push({
|
||||
context: 'edit',
|
||||
id: _id,
|
||||
});
|
||||
},
|
||||
[route],
|
||||
);
|
||||
|
||||
const handleNewButtonClick = useCallback(() => {
|
||||
route.push({ context: 'new' });
|
||||
}, [route]);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
route.push({});
|
||||
}, [route]);
|
||||
|
||||
const handleReload = useCallback(() => {
|
||||
reload.current();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Page flexDirection='row'>
|
||||
<Page name='admin-custom-sounds'>
|
||||
<PageHeader title={t('Sounds')}>
|
||||
<Button primary onClick={handleNewButtonClick} aria-label={t('New')}>
|
||||
{t('New')}
|
||||
</Button>
|
||||
</PageHeader>
|
||||
<PageContent>
|
||||
<CustomSoundsTable reload={reload} onClick={handleItemClick} />
|
||||
</PageContent>
|
||||
</Page>
|
||||
{context && (
|
||||
<ContextualbarDialog onClose={handleClose}>
|
||||
<ContextualbarHeader>
|
||||
<ContextualbarTitle>
|
||||
{context === 'edit' && t('Custom_Sound_Edit')}
|
||||
{context === 'new' && t('Custom_Sound_Add')}
|
||||
</ContextualbarTitle>
|
||||
<ContextualbarClose onClick={handleClose} />
|
||||
</ContextualbarHeader>
|
||||
{context === 'edit' && <EditCustomSound _id={id} close={handleClose} onChange={handleReload} />}
|
||||
{context === 'new' && <AddCustomSound goToNew={handleItemClick} close={handleClose} onChange={handleReload} />}
|
||||
</ContextualbarDialog>
|
||||
)}
|
||||
</Page>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomSoundsPage;
|
||||
@@ -0,0 +1,16 @@
|
||||
import { usePermission } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import CustomSoundsPage from './CustomSoundsPage';
|
||||
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
|
||||
|
||||
const CustomSoundsRoute = () => {
|
||||
const canManageCustomSounds = usePermission('manage-sounds');
|
||||
|
||||
if (!canManageCustomSounds) {
|
||||
return <NotAuthorizedPage />;
|
||||
}
|
||||
|
||||
return <CustomSoundsPage />;
|
||||
};
|
||||
|
||||
export default CustomSoundsRoute;
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { ICustomSound } from '@rocket.chat/core-typings';
|
||||
import { Box, IconButton } from '@rocket.chat/fuselage';
|
||||
import { GenericTableCell, GenericTableRow } from '@rocket.chat/ui-client';
|
||||
import { useCustomSound } from '@rocket.chat/ui-contexts';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type CustomSoundRowProps = {
|
||||
onClick: (soundId: ICustomSound['_id']) => () => void;
|
||||
sound: {
|
||||
name: string;
|
||||
_id: string;
|
||||
};
|
||||
};
|
||||
|
||||
const CustomSoundRow = ({ onClick, sound }: CustomSoundRowProps) => {
|
||||
const { t } = useTranslation();
|
||||
const [isPlay, setPlayAudio] = useState(false);
|
||||
const customSound = useCustomSound();
|
||||
|
||||
const handleToggle = useCallback(
|
||||
(sound: ICustomSound['_id']) => {
|
||||
setPlayAudio(!isPlay);
|
||||
if (!isPlay) {
|
||||
return customSound.play(sound);
|
||||
}
|
||||
|
||||
return customSound.pause(sound);
|
||||
},
|
||||
[customSound, isPlay],
|
||||
);
|
||||
|
||||
return (
|
||||
<GenericTableRow
|
||||
key={sound._id}
|
||||
onKeyDown={onClick(sound._id)}
|
||||
onClick={onClick(sound._id)}
|
||||
tabIndex={0}
|
||||
role='link'
|
||||
action
|
||||
qa-emoji-id={sound._id}
|
||||
>
|
||||
<GenericTableCell>
|
||||
<Box withTruncatedText>{sound.name}</Box>
|
||||
</GenericTableCell>
|
||||
<GenericTableCell>
|
||||
<IconButton
|
||||
icon={!isPlay ? 'play' : 'pause'}
|
||||
small
|
||||
aria-label={!isPlay ? t('Play') : t('Pause')}
|
||||
onClick={(e): void => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleToggle(sound._id);
|
||||
}}
|
||||
/>
|
||||
</GenericTableCell>
|
||||
</GenericTableRow>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomSoundRow;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { composeStories } from '@storybook/react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
|
||||
import * as stories from './CustomSoundsTable.stories';
|
||||
|
||||
const mockSounds = Array.from({ length: 25 }, (_, i) => ({
|
||||
_id: `sound-${i}`,
|
||||
name: `Custom Sound ${i + 1}`,
|
||||
extension: 'mp3',
|
||||
_updatedAt: '2024-01-01T00:00:00.000Z',
|
||||
}));
|
||||
|
||||
const getMockedAppRoot = () =>
|
||||
mockAppRoot().withEndpoint('GET', '/v1/custom-sounds.list', () => ({
|
||||
sounds: mockSounds,
|
||||
total: 50,
|
||||
count: 25,
|
||||
offset: 0,
|
||||
}));
|
||||
|
||||
test('should enable pagination when data.total exceeds itemsPerPage', async () => {
|
||||
const { Default } = composeStories(stories);
|
||||
render(<Default />, { wrapper: getMockedAppRoot().build() });
|
||||
|
||||
const firstSound = await screen.findByText('Custom Sound 1');
|
||||
expect(firstSound).toBeInTheDocument();
|
||||
|
||||
const nextPageButton = screen.getByRole('button', { name: 'Next page' });
|
||||
expect(nextPageButton).toBeInTheDocument();
|
||||
expect(nextPageButton).not.toBeDisabled();
|
||||
|
||||
const pageTwoButton = screen.getByRole('button', { name: 'Page 2' });
|
||||
expect(pageTwoButton).toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Margins } from '@rocket.chat/fuselage';
|
||||
import { PageContent } from '@rocket.chat/ui-client';
|
||||
import type { Meta, StoryFn } from '@storybook/react';
|
||||
import { useRef } from 'react';
|
||||
import { action } from 'storybook/actions';
|
||||
|
||||
import CustomSoundsTable from './CustomSoundsTable';
|
||||
|
||||
export default {
|
||||
component: CustomSoundsTable,
|
||||
decorators: [
|
||||
(fn) => (
|
||||
<PageContent marginBlock='neg-x8'>
|
||||
<Margins block={8}>{fn()}</Margins>
|
||||
</PageContent>
|
||||
),
|
||||
],
|
||||
} satisfies Meta<typeof CustomSoundsTable>;
|
||||
|
||||
const Template: StoryFn<typeof CustomSoundsTable> = (args) => {
|
||||
const reloadRef = useRef(() => undefined);
|
||||
return <CustomSoundsTable {...args} reload={reloadRef} />;
|
||||
};
|
||||
|
||||
export const Default = {
|
||||
render: Template,
|
||||
|
||||
args: {
|
||||
onClick: () => action('clicked'),
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Pagination, States, StatesIcon, StatesActions, StatesAction, StatesTitle } from '@rocket.chat/fuselage';
|
||||
import { useDebouncedValue } from '@rocket.chat/fuselage-hooks';
|
||||
import {
|
||||
GenericTable,
|
||||
GenericTableBody,
|
||||
GenericTableHeader,
|
||||
GenericTableHeaderCell,
|
||||
GenericTableLoadingTable,
|
||||
usePagination,
|
||||
useSort,
|
||||
} from '@rocket.chat/ui-client';
|
||||
import { useTranslation, useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { MutableRefObject } from 'react';
|
||||
import { useState, useMemo, useEffect } from 'react';
|
||||
|
||||
import CustomSoundRow from './CustomSoundRow';
|
||||
import FilterByText from '../../../../components/FilterByText';
|
||||
import GenericNoResults from '../../../../components/GenericNoResults';
|
||||
|
||||
export type CustomSoundsTableProps = {
|
||||
onClick: (soundId: string) => () => void;
|
||||
reload: MutableRefObject<() => void>;
|
||||
};
|
||||
|
||||
const CustomSoundsTable = ({ reload, onClick }: CustomSoundsTableProps) => {
|
||||
const t = useTranslation();
|
||||
const { sortBy, sortDirection, setSort } = useSort<'name'>('name');
|
||||
const { current, itemsPerPage, setItemsPerPage: onSetItemsPerPage, setCurrent: onSetCurrent, ...paginationProps } = usePagination();
|
||||
|
||||
const [text, setText] = useState('');
|
||||
|
||||
const query = useDebouncedValue(
|
||||
useMemo(
|
||||
() => ({
|
||||
name: text,
|
||||
sort: `{ "${sortBy}": ${sortDirection === 'asc' ? 1 : -1} }`,
|
||||
...(itemsPerPage && { count: itemsPerPage }),
|
||||
...(current && { offset: current }),
|
||||
}),
|
||||
[text, itemsPerPage, current, sortBy, sortDirection],
|
||||
),
|
||||
500,
|
||||
);
|
||||
|
||||
const getSounds = useEndpoint('GET', '/v1/custom-sounds.list');
|
||||
const { data, refetch, isLoading, isError, isSuccess } = useQuery({
|
||||
queryKey: ['custom-sounds', query],
|
||||
queryFn: async () => getSounds(query),
|
||||
refetchOnMount: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
reload.current = refetch;
|
||||
}, [reload, refetch]);
|
||||
|
||||
const headers = (
|
||||
<>
|
||||
<GenericTableHeaderCell key='name' direction={sortDirection} active={sortBy === 'name'} onClick={setSort} sort='name'>
|
||||
{t('Name')}
|
||||
</GenericTableHeaderCell>
|
||||
<GenericTableHeaderCell width='x40' key='action' />
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<FilterByText value={text} onChange={(event) => setText(event.target.value)} />
|
||||
{isLoading && (
|
||||
<GenericTable>
|
||||
<GenericTableHeader>{headers}</GenericTableHeader>
|
||||
<GenericTableBody>
|
||||
<GenericTableLoadingTable headerCells={2} />
|
||||
</GenericTableBody>
|
||||
</GenericTable>
|
||||
)}
|
||||
{isSuccess && data?.sounds.length > 0 && (
|
||||
<>
|
||||
<GenericTable>
|
||||
<GenericTableHeader>{headers}</GenericTableHeader>
|
||||
<GenericTableBody>
|
||||
{data.sounds.map((sound) => (
|
||||
<CustomSoundRow key={sound._id} sound={sound} onClick={onClick} />
|
||||
))}
|
||||
</GenericTableBody>
|
||||
</GenericTable>
|
||||
<Pagination
|
||||
divider
|
||||
current={current}
|
||||
itemsPerPage={itemsPerPage}
|
||||
count={data?.total || 0}
|
||||
onSetItemsPerPage={onSetItemsPerPage}
|
||||
onSetCurrent={onSetCurrent}
|
||||
{...paginationProps}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{isSuccess && data?.sounds.length === 0 && <GenericNoResults />}
|
||||
{isError && (
|
||||
<States>
|
||||
<StatesIcon name='warning' variation='danger' />
|
||||
<StatesTitle>{t('Something_went_wrong')}</StatesTitle>
|
||||
<StatesActions>
|
||||
<StatesAction onClick={() => refetch()}>{t('Reload_page')}</StatesAction>
|
||||
</StatesActions>
|
||||
</States>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomSoundsTable;
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './CustomSoundsTable';
|
||||
@@ -0,0 +1,45 @@
|
||||
import { ContextualbarEmptyContent } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import EditSound from './EditSound';
|
||||
import { FormSkeleton } from '../../../components/Skeleton';
|
||||
|
||||
export type EditCustomSoundProps = {
|
||||
_id: string | undefined;
|
||||
onChange?: () => void;
|
||||
close: () => void;
|
||||
};
|
||||
|
||||
function EditCustomSound({ _id, onChange, close, ...props }: EditCustomSoundProps) {
|
||||
const getSound = useEndpoint('GET', '/v1/custom-sounds.getOne');
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['custom-sound', _id],
|
||||
queryFn: () => {
|
||||
if (!_id) {
|
||||
throw new Error('Cannot fetch custom sound: missing _id in query.');
|
||||
}
|
||||
return getSound({ _id });
|
||||
},
|
||||
enabled: !!_id,
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return <FormSkeleton paddingInline={20} />;
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return <ContextualbarEmptyContent icon='warning' title={t('No_results_found')} />;
|
||||
}
|
||||
|
||||
const handleChange: () => void = () => {
|
||||
onChange?.();
|
||||
};
|
||||
|
||||
return <EditSound data={data.sound} close={close} onChange={handleChange} {...props} />;
|
||||
}
|
||||
|
||||
export default EditCustomSound;
|
||||
154
apps/meteor/client/views/admin/customSounds/EditSound.tsx
Normal file
154
apps/meteor/client/views/admin/customSounds/EditSound.tsx
Normal file
@@ -0,0 +1,154 @@
|
||||
import { Box, Button, ButtonGroup, Margins, TextInput, Field, FieldLabel, FieldRow, IconButton } from '@rocket.chat/fuselage';
|
||||
import { GenericModal, ContextualbarScrollableContent, ContextualbarFooter } from '@rocket.chat/ui-client';
|
||||
import { useSetModal, useToastMessageDispatch, useEndpoint } from '@rocket.chat/ui-contexts';
|
||||
import fileSize from 'filesize';
|
||||
import type { ChangeEvent } from 'react';
|
||||
import { useCallback, useState, useMemo, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { validate } from './lib';
|
||||
import { CUSTOM_SOUND_ALLOWED_MIME_TYPES, MAX_CUSTOM_SOUND_SIZE_BYTES } from '../../../../lib/constants';
|
||||
import { useEndpointUploadMutation } from '../../../hooks/useEndpointUploadMutation';
|
||||
import { useSingleFileInput } from '../../../hooks/useSingleFileInput';
|
||||
|
||||
export type EditSoundProps = {
|
||||
close: () => void;
|
||||
onChange: () => void;
|
||||
data: {
|
||||
_id: string;
|
||||
name: string;
|
||||
extension: string;
|
||||
};
|
||||
};
|
||||
|
||||
function EditSound({ close, onChange, data, ...props }: EditSoundProps) {
|
||||
const { t } = useTranslation();
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const setModal = useSetModal();
|
||||
|
||||
const { _id, name: previousName } = data || {};
|
||||
|
||||
const [name, setName] = useState(() => data?.name ?? '');
|
||||
const [file, setFile] = useState<File | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
setName(previousName || '');
|
||||
setFile(undefined);
|
||||
}, [_id, previousName]);
|
||||
|
||||
const deleteCustomSoundEndpoint = useEndpoint('POST', '/v1/custom-sounds.delete');
|
||||
|
||||
const { mutate: saveAction } = useEndpointUploadMutation('/v1/custom-sounds.update', {
|
||||
onSuccess: () => {
|
||||
dispatchToastMessage({ type: 'success', message: t('Custom_Sound_Saved_Successfully') });
|
||||
onChange();
|
||||
close();
|
||||
},
|
||||
});
|
||||
|
||||
const handleChangeFile = useCallback((soundFile: File) => {
|
||||
setFile(soundFile);
|
||||
}, []);
|
||||
|
||||
const hasUnsavedChanges = useMemo(() => previousName !== name || !!file, [name, previousName, file]);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
const trimmedName = name.trim();
|
||||
const validation = validate({ _id, name: trimmedName }, file);
|
||||
if (validation.length > 0) {
|
||||
const firstInvalidField = validation[0];
|
||||
dispatchToastMessage({
|
||||
type: 'error',
|
||||
message: t('Required_field', { field: t(firstInvalidField) }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('_id', _id);
|
||||
formData.append('name', trimmedName);
|
||||
if (file) {
|
||||
formData.append('sound', file);
|
||||
}
|
||||
saveAction(formData);
|
||||
}, [_id, dispatchToastMessage, name, saveAction, file, t]);
|
||||
|
||||
const handleDeleteButtonClick = useCallback(() => {
|
||||
const handleDelete = async (): Promise<void> => {
|
||||
try {
|
||||
await deleteCustomSoundEndpoint({ _id });
|
||||
dispatchToastMessage({ type: 'success', message: t('Custom_Sound_Has_Been_Deleted') });
|
||||
} catch (error) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
} finally {
|
||||
setModal(null);
|
||||
close?.();
|
||||
onChange();
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = (): void => setModal(null);
|
||||
|
||||
setModal(
|
||||
<GenericModal variant='danger' onConfirm={handleDelete} onCancel={handleCancel} onClose={handleCancel} confirmText={t('Delete')}>
|
||||
{t('Custom_Sound_Delete_Warning')}
|
||||
</GenericModal>,
|
||||
);
|
||||
}, [_id, close, deleteCustomSoundEndpoint, dispatchToastMessage, onChange, setModal, t]);
|
||||
|
||||
const [clickUpload] = useSingleFileInput(
|
||||
handleChangeFile,
|
||||
CUSTOM_SOUND_ALLOWED_MIME_TYPES.join(','),
|
||||
'audio',
|
||||
MAX_CUSTOM_SOUND_SIZE_BYTES,
|
||||
() => {
|
||||
dispatchToastMessage({
|
||||
type: 'error',
|
||||
message: t('File_exceeds_allowed_size_of_bytes', { size: fileSize(MAX_CUSTOM_SOUND_SIZE_BYTES, { base: 2, standard: 'jedec' }) }),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ContextualbarScrollableContent {...props}>
|
||||
<Field>
|
||||
<FieldLabel>{t('Name')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<TextInput
|
||||
value={name}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>): void => setName(e.currentTarget.value)}
|
||||
placeholder={t('Name')}
|
||||
/>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel alignSelf='stretch'>{t('Sound File')}</FieldLabel>
|
||||
<Box display='flex' flexDirection='row' marginBlockStart='none' alignItems='center'>
|
||||
<Margins inline={4}>
|
||||
<IconButton secondary small icon='upload' onClick={clickUpload} />
|
||||
{file?.name || (data?.name && data?.extension && `${data.name}.${data.extension}`) || t('None')}
|
||||
</Margins>
|
||||
</Box>
|
||||
</Field>
|
||||
</ContextualbarScrollableContent>
|
||||
<ContextualbarFooter>
|
||||
<ButtonGroup stretch>
|
||||
<Button onClick={close}>{t('Cancel')}</Button>
|
||||
<Button primary onClick={handleSave} disabled={!hasUnsavedChanges}>
|
||||
{t('Save')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
<Box marginBlockStart={8}>
|
||||
<ButtonGroup stretch>
|
||||
<Button icon='trash' danger onClick={handleDeleteButtonClick}>
|
||||
{t('Delete')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</Box>
|
||||
</ContextualbarFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default EditSound;
|
||||
25
apps/meteor/client/views/admin/customSounds/lib.ts
Normal file
25
apps/meteor/client/views/admin/customSounds/lib.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { CUSTOM_SOUND_ALLOWED_MIME_TYPES } from '../../../../lib/constants';
|
||||
|
||||
type ClientCustomSoundData = {
|
||||
_id?: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
// Here previousData will define if it is an update or a new entry
|
||||
export function validate(soundData: ClientCustomSoundData, soundFile?: File): ('Name' | 'Sound File' | 'FileType')[] {
|
||||
const errors: ('Name' | 'Sound File' | 'FileType')[] = [];
|
||||
|
||||
if (!soundData.name) {
|
||||
errors.push('Name');
|
||||
}
|
||||
|
||||
if (!soundData._id && !soundFile) {
|
||||
errors.push('Sound File');
|
||||
}
|
||||
|
||||
if (soundFile && !CUSTOM_SOUND_ALLOWED_MIME_TYPES.includes(soundFile.type)) {
|
||||
errors.push('FileType');
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
Reference in New Issue
Block a user