Merge branch 'group-requests' into 'develop'

Groups: improve pending memberships, standardize "authorize/reject" buttons throughout the UI

See merge request soapbox-pub/soapbox!2370
This commit is contained in:
Alex Gleason 2023-03-23 17:05:14 +00:00
commit 948d66bcab
33 changed files with 814 additions and 280 deletions

View file

@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Posts: truncate Nostr pubkeys in reply mentions.
- Posts: upgraded emoji picker component.
- UI: unified design of "approve" and "reject" buttons in follow requests and waitlist.
### Fixed
- Posts: fixed emojis being cut off in reactions modal.

View file

@ -789,9 +789,11 @@ const submitGroupEditor = (shouldReset?: boolean) => (dispatch: AppDispatch, get
const note = getState().group_editor.note;
const avatar = getState().group_editor.avatar;
const header = getState().group_editor.header;
const visibility = getState().group_editor.locked ? 'members_only' : 'everyone'; // Truth Social
const params: Record<string, any> = {
display_name: displayName,
group_visibility: visibility,
note,
};

View file

@ -0,0 +1,72 @@
import React, { useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { HStack, IconButton, Text } from 'soapbox/components/ui';
interface IAuthorizeRejectButtons {
onAuthorize(): Promise<unknown> | unknown
onReject(): Promise<unknown> | unknown
}
/** Buttons to approve or reject a pending item, usually an account. */
const AuthorizeRejectButtons: React.FC<IAuthorizeRejectButtons> = ({ onAuthorize, onReject }) => {
const [state, setState] = useState<'authorized' | 'rejected' | 'pending'>('pending');
async function handleAuthorize() {
try {
await onAuthorize();
setState('authorized');
} catch (e) {
console.error(e);
}
}
async function handleReject() {
try {
await onReject();
setState('rejected');
} catch (e) {
console.error(e);
}
}
switch (state) {
case 'pending':
return (
<HStack space={3} alignItems='center'>
<IconButton
src={require('@tabler/icons/x.svg')}
onClick={handleReject}
theme='seamless'
className='h-10 w-10 items-center justify-center border-2 border-danger-600/10 hover:border-danger-600'
iconClassName='h-6 w-6 text-danger-600'
/>
<IconButton
src={require('@tabler/icons/check.svg')}
onClick={handleAuthorize}
theme='seamless'
className='h-10 w-10 items-center justify-center border-2 border-primary-500/10 hover:border-primary-500'
iconClassName='h-6 w-6 text-primary-500'
/>
</HStack>
);
case 'authorized':
return (
<div className='rounded-full bg-gray-100 px-4 py-2 dark:bg-gray-800'>
<Text theme='muted' size='sm'>
<FormattedMessage id='authorize.success' defaultMessage='Approved' />
</Text>
</div>
);
case 'rejected':
return (
<div className='rounded-full bg-gray-100 px-4 py-2 dark:bg-gray-800'>
<Text theme='muted' size='sm'>
<FormattedMessage id='reject.success' defaultMessage='Rejected' />
</Text>
</div>
);
}
};
export { AuthorizeRejectButtons };

View file

@ -0,0 +1,54 @@
import clsx from 'clsx';
import React from 'react';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import { HStack, Icon, Text } from 'soapbox/components/ui';
interface IPendingItemsRow {
/** Path to navigate the user when clicked. */
to: string
/** Number of pending items. */
count: number
/** Size of the icon. */
size?: 'md' | 'lg'
}
const PendingItemsRow: React.FC<IPendingItemsRow> = ({ to, count, size = 'md' }) => {
return (
<Link to={to} className='group' data-testid='pending-items-row'>
<HStack alignItems='center' justifyContent='between'>
<HStack alignItems='center' space={2}>
<div className={clsx('rounded-full bg-primary-200 text-primary-500 dark:bg-primary-800 dark:text-primary-200', {
'p-3': size === 'lg',
'p-2.5': size === 'md',
})}
>
<Icon
src={require('@tabler/icons/exclamation-circle.svg')}
className={clsx({
'h-5 w-5': size === 'md',
'h-7 w-7': size === 'lg',
})}
/>
</div>
<Text weight='bold' size='md'>
<FormattedMessage
id='groups.pending.count'
defaultMessage='{number, plural, one {# pending request} other {# pending requests}}'
values={{ number: count }}
/>
</Text>
</HStack>
<Icon
src={require('@tabler/icons/chevron-right.svg')}
className='h-5 w-5 text-gray-600 transition-colors group-hover:text-gray-700 dark:text-gray-600 dark:group-hover:text-gray-500'
/>
</HStack>
</Link>
);
};
export { PendingItemsRow };

View file

@ -64,7 +64,7 @@ const CardHeader: React.FC<ICardHeader> = ({ className, children, backHref, onBa
const backAttributes = backHref ? { to: backHref } : { onClick: onBackClick };
return (
<Comp {...backAttributes} className='text-gray-900 focus:ring-2 focus:ring-primary-500 dark:text-gray-100' aria-label={intl.formatMessage(messages.back)}>
<Comp {...backAttributes} className='rounded-full text-gray-900 focus:ring-2 focus:ring-primary-500 dark:text-gray-100' aria-label={intl.formatMessage(messages.back)}>
<SvgIcon src={require('@tabler/icons/arrow-left.svg')} className='h-6 w-6 rtl:rotate-180' />
<span className='sr-only' data-testid='back-button'>{intl.formatMessage(messages.back)}</span>
</Comp>

View file

@ -156,7 +156,7 @@ const Tabs = ({ items, activeItem }: ITabs) => {
>
<div className='relative'>
{count ? (
<span className='absolute -top-2 left-full ml-1'>
<span className='absolute left-full ml-2'>
<Counter count={count} />
</span>
) : null}

View file

@ -1,4 +1,12 @@
import { deleteEntities, entitiesFetchFail, entitiesFetchRequest, importEntities } from '../actions';
import {
deleteEntities,
dismissEntities,
entitiesFetchFail,
entitiesFetchRequest,
entitiesFetchSuccess,
importEntities,
incrementEntities,
} from '../actions';
import reducer, { State } from '../reducer';
import { createListState } from '../utils';
@ -36,7 +44,8 @@ test('import entities into a list', () => {
const cache = result.TestEntity as EntityCache<TestEntity>;
expect(cache.store['2']!.msg).toBe('benis');
expect(cache.lists.thingies?.ids.size).toBe(3);
expect(cache.lists.thingies!.ids.size).toBe(3);
expect(cache.lists.thingies!.state.totalCount).toBe(3);
// Now try adding an additional item.
const entities2: TestEntity[] = [
@ -48,7 +57,8 @@ test('import entities into a list', () => {
const cache2 = result2.TestEntity as EntityCache<TestEntity>;
expect(cache2.store['4']!.msg).toBe('hehe');
expect(cache2.lists.thingies?.ids.size).toBe(4);
expect(cache2.lists.thingies!.ids.size).toBe(4);
expect(cache2.lists.thingies!.state.totalCount).toBe(4);
// Finally, update an item.
const entities3: TestEntity[] = [
@ -60,7 +70,8 @@ test('import entities into a list', () => {
const cache3 = result3.TestEntity as EntityCache<TestEntity>;
expect(cache3.store['2']!.msg).toBe('yolofam');
expect(cache3.lists.thingies?.ids.size).toBe(4); // unchanged
expect(cache3.lists.thingies!.ids.size).toBe(4); // unchanged
expect(cache3.lists.thingies!.state.totalCount).toBe(4);
});
test('fetching updates the list state', () => {
@ -79,6 +90,44 @@ test('failure adds the error to the state', () => {
expect(result.TestEntity!.lists.thingies!.state.error).toBe(error);
});
test('import entities with override', () => {
const state: State = {
TestEntity: {
store: { '1': { id: '1' }, '2': { id: '2' }, '3': { id: '3' } },
lists: {
thingies: {
ids: new Set(['1', '2', '3']),
state: { ...createListState(), totalCount: 3 },
},
},
},
};
const entities: TestEntity[] = [
{ id: '4', msg: 'yolo' },
{ id: '5', msg: 'benis' },
];
const now = new Date();
const action = entitiesFetchSuccess(entities, 'TestEntity', 'thingies', {
next: undefined,
prev: undefined,
totalCount: 2,
error: null,
fetched: true,
fetching: false,
lastFetchedAt: now,
invalid: false,
}, true);
const result = reducer(state, action);
const cache = result.TestEntity as EntityCache<TestEntity>;
expect([...cache.lists.thingies!.ids]).toEqual(['4', '5']);
expect(cache.lists.thingies!.state.lastFetchedAt).toBe(now); // Also check that newState worked
});
test('deleting items', () => {
const state: State = {
TestEntity: {
@ -86,7 +135,7 @@ test('deleting items', () => {
lists: {
'': {
ids: new Set(['1', '2', '3']),
state: createListState(),
state: { ...createListState(), totalCount: 3 },
},
},
},
@ -97,4 +146,64 @@ test('deleting items', () => {
expect(result.TestEntity!.store).toMatchObject({ '2': { id: '2' } });
expect([...result.TestEntity!.lists['']!.ids]).toEqual(['2']);
expect(result.TestEntity!.lists['']!.state.totalCount).toBe(1);
});
test('dismiss items', () => {
const state: State = {
TestEntity: {
store: { '1': { id: '1' }, '2': { id: '2' }, '3': { id: '3' } },
lists: {
yolo: {
ids: new Set(['1', '2', '3']),
state: { ...createListState(), totalCount: 3 },
},
},
},
};
const action = dismissEntities(['3', '1'], 'TestEntity', 'yolo');
const result = reducer(state, action);
expect(result.TestEntity!.store).toMatchObject(state.TestEntity!.store);
expect([...result.TestEntity!.lists.yolo!.ids]).toEqual(['2']);
expect(result.TestEntity!.lists.yolo!.state.totalCount).toBe(1);
});
test('increment items', () => {
const state: State = {
TestEntity: {
store: { '1': { id: '1' }, '2': { id: '2' }, '3': { id: '3' } },
lists: {
thingies: {
ids: new Set(['1', '2', '3']),
state: { ...createListState(), totalCount: 3 },
},
},
},
};
const action = incrementEntities('TestEntity', 'thingies', 1);
const result = reducer(state, action);
expect(result.TestEntity!.lists.thingies!.state.totalCount).toBe(4);
});
test('decrement items', () => {
const state: State = {
TestEntity: {
store: { '1': { id: '1' }, '2': { id: '2' }, '3': { id: '3' } },
lists: {
thingies: {
ids: new Set(['1', '2', '3']),
state: { ...createListState(), totalCount: 3 },
},
},
},
};
const action = incrementEntities('TestEntity', 'thingies', -1);
const result = reducer(state, action);
expect(result.TestEntity!.lists.thingies!.state.totalCount).toBe(2);
});

View file

@ -2,9 +2,12 @@ import type { Entity, EntityListState } from './types';
const ENTITIES_IMPORT = 'ENTITIES_IMPORT' as const;
const ENTITIES_DELETE = 'ENTITIES_DELETE' as const;
const ENTITIES_DISMISS = 'ENTITIES_DISMISS' as const;
const ENTITIES_INCREMENT = 'ENTITIES_INCREMENT' as const;
const ENTITIES_FETCH_REQUEST = 'ENTITIES_FETCH_REQUEST' as const;
const ENTITIES_FETCH_SUCCESS = 'ENTITIES_FETCH_SUCCESS' as const;
const ENTITIES_FETCH_FAIL = 'ENTITIES_FETCH_FAIL' as const;
const ENTITIES_INVALIDATE_LIST = 'ENTITIES_INVALIDATE_LIST' as const;
/** Action to import entities into the cache. */
function importEntities(entities: Entity[], entityType: string, listKey?: string) {
@ -29,6 +32,24 @@ function deleteEntities(ids: Iterable<string>, entityType: string, opts: DeleteE
};
}
function dismissEntities(ids: Iterable<string>, entityType: string, listKey: string) {
return {
type: ENTITIES_DISMISS,
ids,
entityType,
listKey,
};
}
function incrementEntities(entityType: string, listKey: string, diff: number) {
return {
type: ENTITIES_INCREMENT,
entityType,
listKey,
diff,
};
}
function entitiesFetchRequest(entityType: string, listKey?: string) {
return {
type: ENTITIES_FETCH_REQUEST,
@ -37,13 +58,20 @@ function entitiesFetchRequest(entityType: string, listKey?: string) {
};
}
function entitiesFetchSuccess(entities: Entity[], entityType: string, listKey?: string, newState?: EntityListState) {
function entitiesFetchSuccess(
entities: Entity[],
entityType: string,
listKey?: string,
newState?: EntityListState,
overwrite = false,
) {
return {
type: ENTITIES_FETCH_SUCCESS,
entityType,
entities,
listKey,
newState,
overwrite,
};
}
@ -56,25 +84,42 @@ function entitiesFetchFail(entityType: string, listKey: string | undefined, erro
};
}
function invalidateEntityList(entityType: string, listKey: string) {
return {
type: ENTITIES_INVALIDATE_LIST,
entityType,
listKey,
};
}
/** Any action pertaining to entities. */
type EntityAction =
ReturnType<typeof importEntities>
| ReturnType<typeof deleteEntities>
| ReturnType<typeof dismissEntities>
| ReturnType<typeof incrementEntities>
| ReturnType<typeof entitiesFetchRequest>
| ReturnType<typeof entitiesFetchSuccess>
| ReturnType<typeof entitiesFetchFail>;
| ReturnType<typeof entitiesFetchFail>
| ReturnType<typeof invalidateEntityList>;
export {
ENTITIES_IMPORT,
ENTITIES_DELETE,
ENTITIES_DISMISS,
ENTITIES_INCREMENT,
ENTITIES_FETCH_REQUEST,
ENTITIES_FETCH_SUCCESS,
ENTITIES_FETCH_FAIL,
ENTITIES_INVALIDATE_LIST,
importEntities,
deleteEntities,
dismissEntities,
incrementEntities,
entitiesFetchRequest,
entitiesFetchSuccess,
entitiesFetchFail,
invalidateEntityList,
EntityAction,
};

View file

@ -1,4 +1,5 @@
export enum Entities {
ACCOUNTS = 'Accounts',
GROUPS = 'Groups',
GROUP_RELATIONSHIPS = 'GroupRelationships',
GROUP_MEMBERSHIPS = 'GroupMemberships',

View file

@ -1,3 +1,7 @@
export { useEntities } from './useEntities';
export { useEntity } from './useEntity';
export { useEntityActions } from './useEntityActions';
export { useEntityActions } from './useEntityActions';
export { useCreateEntity } from './useCreateEntity';
export { useDeleteEntity } from './useDeleteEntity';
export { useDismissEntity } from './useDismissEntity';
export { useIncrementEntity } from './useIncrementEntity';

View file

@ -3,4 +3,30 @@ import type z from 'zod';
type EntitySchema<TEntity extends Entity = Entity> = z.ZodType<TEntity, z.ZodTypeDef, any>;
export type { EntitySchema };
/**
* Tells us where to find/store the entity in the cache.
* This value is accepted in hooks, but needs to be parsed into an `EntitiesPath`
* before being passed to the store.
*/
type ExpandedEntitiesPath = [
/** Name of the entity type for use in the global cache, eg `'Notification'`. */
entityType: string,
/**
* Name of a particular index of this entity type.
* Multiple params get combined into one string with a `:` separator.
*/
...listKeys: string[],
]
/** Used to look up an entity in a list. */
type EntitiesPath = [entityType: string, listKey: string]
/** Used to look up a single entity by its ID. */
type EntityPath = [entityType: string, entityId: string]
export type {
EntitySchema,
ExpandedEntitiesPath,
EntitiesPath,
EntityPath,
};

View file

@ -0,0 +1,76 @@
import { z } from 'zod';
import { useAppDispatch } from 'soapbox/hooks';
import { importEntities } from '../actions';
import { parseEntitiesPath } from './utils';
import type { Entity } from '../types';
import type { EntitySchema, ExpandedEntitiesPath } from './types';
type CreateFn<Params, Result> = (params: Params) => Promise<Result> | Result;
interface UseCreateEntityOpts<TEntity extends Entity = Entity> {
schema?: EntitySchema<TEntity>
}
type CreateEntityResult<TEntity extends Entity = Entity, Result = unknown, Error = unknown> =
{
success: true
result: Result
entity: TEntity
} | {
success: false
error: Error
}
interface EntityCallbacks<TEntity extends Entity = Entity, Error = unknown> {
onSuccess?(entity: TEntity): void
onError?(error: Error): void
}
function useCreateEntity<TEntity extends Entity = Entity, Params = any, Result = unknown>(
expandedPath: ExpandedEntitiesPath,
createFn: CreateFn<Params, Result>,
opts: UseCreateEntityOpts<TEntity> = {},
) {
const { entityType, listKey } = parseEntitiesPath(expandedPath);
const dispatch = useAppDispatch();
return async function createEntity(
params: Params,
callbacks: EntityCallbacks = {},
): Promise<CreateEntityResult<TEntity>> {
try {
const result = await createFn(params);
const schema = opts.schema || z.custom<TEntity>();
const entity = schema.parse(result);
// TODO: optimistic updating
dispatch(importEntities([entity], entityType, listKey));
if (callbacks.onSuccess) {
callbacks.onSuccess(entity);
}
return {
success: true,
result,
entity,
};
} catch (error) {
if (callbacks.onError) {
callbacks.onError(error);
}
return {
success: false,
error,
};
}
};
}
export { useCreateEntity };

View file

@ -0,0 +1,50 @@
import { useAppDispatch, useGetState } from 'soapbox/hooks';
import { deleteEntities, importEntities } from '../actions';
type DeleteFn<T> = (entityId: string) => Promise<T> | T;
interface EntityCallbacks {
onSuccess?(): void
}
/**
* Optimistically deletes an entity from the store.
* This hook should be used to globally delete an entity from all lists.
* To remove an entity from a single list, see `useDismissEntity`.
*/
function useDeleteEntity<T = unknown>(
entityType: string,
deleteFn: DeleteFn<T>,
) {
const dispatch = useAppDispatch();
const getState = useGetState();
return async function deleteEntity(entityId: string, callbacks: EntityCallbacks = {}): Promise<T> {
// Get the entity before deleting, so we can reverse the action if the API request fails.
const entity = getState().entities[entityType]?.store[entityId];
// Optimistically delete the entity from the _store_ but keep the lists in tact.
dispatch(deleteEntities([entityId], entityType, { preserveLists: true }));
try {
const result = await deleteFn(entityId);
// Success - finish deleting entity from the state.
dispatch(deleteEntities([entityId], entityType));
if (callbacks.onSuccess) {
callbacks.onSuccess();
}
return result;
} catch (e) {
if (entity) {
// If the API failed, reimport the entity.
dispatch(importEntities([entity], entityType));
}
throw e;
}
};
}
export { useDeleteEntity };

View file

@ -0,0 +1,28 @@
import { useAppDispatch } from 'soapbox/hooks';
import { dismissEntities } from '../actions';
import { parseEntitiesPath } from './utils';
import type { ExpandedEntitiesPath } from './types';
type DismissFn<T> = (entityId: string) => Promise<T> | T;
/**
* Removes an entity from a specific list.
* To remove an entity globally from all lists, see `useDeleteEntity`.
*/
function useDismissEntity<T = unknown>(expandedPath: ExpandedEntitiesPath, dismissFn: DismissFn<T>) {
const { entityType, listKey } = parseEntitiesPath(expandedPath);
const dispatch = useAppDispatch();
// TODO: optimistic dismissing
return async function dismissEntity(entityId: string): Promise<T> {
const result = await dismissFn(entityId);
dispatch(dismissEntities([entityId], entityType, listKey));
return result;
};
}
export { useDismissEntity };

View file

@ -4,25 +4,16 @@ import z from 'zod';
import { getNextLink, getPrevLink } from 'soapbox/api';
import { useApi, useAppDispatch, useAppSelector, useGetState } from 'soapbox/hooks';
import { filteredArray } from 'soapbox/schemas/utils';
import { realNumberSchema } from 'soapbox/utils/numbers';
import { entitiesFetchFail, entitiesFetchRequest, entitiesFetchSuccess } from '../actions';
import { entitiesFetchFail, entitiesFetchRequest, entitiesFetchSuccess, invalidateEntityList } from '../actions';
import { parseEntitiesPath } from './utils';
import type { Entity, EntityListState } from '../types';
import type { EntitySchema } from './types';
import type { EntitiesPath, EntitySchema, ExpandedEntitiesPath } from './types';
import type { RootState } from 'soapbox/store';
/** Tells us where to find/store the entity in the cache. */
type EntityPath = [
/** Name of the entity type for use in the global cache, eg `'Notification'`. */
entityType: string,
/**
* Name of a particular index of this entity type.
* Multiple params get combined into one string with a `:` separator.
* You can use empty-string (`''`) if you don't need separate lists.
*/
...listKeys: string[],
]
/** Additional options for the hook. */
interface UseEntitiesOpts<TEntity extends Entity> {
/** A zod schema to parse the API entities. */
@ -39,7 +30,7 @@ interface UseEntitiesOpts<TEntity extends Entity> {
/** A hook for fetching and displaying API entities. */
function useEntities<TEntity extends Entity>(
/** Tells us where to find/store the entity in the cache. */
path: EntityPath,
expandedPath: ExpandedEntitiesPath,
/** API route to GET, eg `'/api/v1/notifications'`. If undefined, nothing will be fetched. */
endpoint: string | undefined,
/** Additional options for the hook. */
@ -49,9 +40,7 @@ function useEntities<TEntity extends Entity>(
const dispatch = useAppDispatch();
const getState = useGetState();
const [entityType, ...listKeys] = path;
const listKey = listKeys.join(':');
const { entityType, listKey, path } = parseEntitiesPath(expandedPath);
const entities = useAppSelector(state => selectEntities<TEntity>(state, path));
const isEnabled = opts.enabled ?? true;
@ -59,11 +48,13 @@ function useEntities<TEntity extends Entity>(
const lastFetchedAt = useListState(path, 'lastFetchedAt');
const isFetched = useListState(path, 'fetched');
const isError = !!useListState(path, 'error');
const totalCount = useListState(path, 'totalCount');
const isInvalid = useListState(path, 'invalid');
const next = useListState(path, 'next');
const prev = useListState(path, 'prev');
const fetchPage = async(url: string): Promise<void> => {
const fetchPage = async(url: string, overwrite = false): Promise<void> => {
// Get `isFetching` state from the store again to prevent race conditions.
const isFetching = selectListState(getState(), path, 'fetching');
if (isFetching) return;
@ -73,15 +64,18 @@ function useEntities<TEntity extends Entity>(
const response = await api.get(url);
const schema = opts.schema || z.custom<TEntity>();
const entities = filteredArray(schema).parse(response.data);
const parsedCount = realNumberSchema.safeParse(response.headers['x-total-count']);
dispatch(entitiesFetchSuccess(entities, entityType, listKey, {
next: getNextLink(response),
prev: getPrevLink(response),
totalCount: parsedCount.success ? parsedCount.data : undefined,
fetching: false,
fetched: true,
error: null,
lastFetchedAt: new Date(),
}));
invalid: false,
}, overwrite));
} catch (error) {
dispatch(entitiesFetchFail(entityType, listKey, error));
}
@ -89,7 +83,7 @@ function useEntities<TEntity extends Entity>(
const fetchEntities = async(): Promise<void> => {
if (endpoint) {
await fetchPage(endpoint);
await fetchPage(endpoint, true);
}
};
@ -105,10 +99,19 @@ function useEntities<TEntity extends Entity>(
}
};
const invalidate = () => {
dispatch(invalidateEntityList(entityType, listKey));
};
const staleTime = opts.staleTime ?? 60000;
useEffect(() => {
if (isEnabled && !isFetching && (!lastFetchedAt || lastFetchedAt.getTime() + staleTime <= Date.now())) {
if (!isEnabled) return;
if (isFetching) return;
const isUnset = !lastFetchedAt;
const isStale = lastFetchedAt ? Date.now() >= lastFetchedAt.getTime() + staleTime : false;
if (isInvalid || isUnset || isStale) {
fetchEntities();
}
}, [endpoint, isEnabled]);
@ -120,18 +123,22 @@ function useEntities<TEntity extends Entity>(
fetchPreviousPage,
hasNextPage: !!next,
hasPreviousPage: !!prev,
totalCount,
isError,
isFetched,
isFetching,
isLoading: isFetching && entities.length === 0,
invalidate,
/** The `X-Total-Count` from the API if available, or the length of items in the store. */
count: typeof totalCount === 'number' ? totalCount : entities.length,
};
}
/** Get cache at path from Redux. */
const selectCache = (state: RootState, path: EntityPath) => state.entities[path[0]];
const selectCache = (state: RootState, path: EntitiesPath) => state.entities[path[0]];
/** Get list at path from Redux. */
const selectList = (state: RootState, path: EntityPath) => {
const selectList = (state: RootState, path: EntitiesPath) => {
const [, ...listKeys] = path;
const listKey = listKeys.join(':');
@ -139,18 +146,18 @@ const selectList = (state: RootState, path: EntityPath) => {
};
/** Select a particular item from a list state. */
function selectListState<K extends keyof EntityListState>(state: RootState, path: EntityPath, key: K) {
function selectListState<K extends keyof EntityListState>(state: RootState, path: EntitiesPath, key: K) {
const listState = selectList(state, path)?.state;
return listState ? listState[key] : undefined;
}
/** Hook to get a particular item from a list state. */
function useListState<K extends keyof EntityListState>(path: EntityPath, key: K) {
function useListState<K extends keyof EntityListState>(path: EntitiesPath, key: K) {
return useAppSelector(state => selectListState(state, path, key));
}
/** Get list of entities from Redux. */
function selectEntities<TEntity extends Entity>(state: RootState, path: EntityPath): readonly TEntity[] {
function selectEntities<TEntity extends Entity>(state: RootState, path: EntitiesPath): readonly TEntity[] {
const cache = selectCache(state, path);
const list = selectList(state, path);

View file

@ -6,9 +6,7 @@ import { useApi, useAppDispatch, useAppSelector } from 'soapbox/hooks';
import { importEntities } from '../actions';
import type { Entity } from '../types';
import type { EntitySchema } from './types';
type EntityPath = [entityType: string, entityId: string]
import type { EntitySchema, EntityPath } from './types';
/** Additional options for the hook. */
interface UseEntityOpts<TEntity extends Entity> {

View file

@ -1,105 +1,44 @@
import { useState } from 'react';
import { z } from 'zod';
import { useApi, useAppDispatch, useGetState } from 'soapbox/hooks';
import { useApi } from 'soapbox/hooks';
import { deleteEntities, importEntities } from '../actions';
import { useCreateEntity } from './useCreateEntity';
import { useDeleteEntity } from './useDeleteEntity';
import { parseEntitiesPath } from './utils';
import type { Entity } from '../types';
import type { EntitySchema } from './types';
import type { AxiosResponse } from 'axios';
type EntityPath = [entityType: string, listKey?: string]
import type { EntitySchema, ExpandedEntitiesPath } from './types';
interface UseEntityActionsOpts<TEntity extends Entity = Entity> {
schema?: EntitySchema<TEntity>
}
interface CreateEntityResult<TEntity extends Entity = Entity> {
response: AxiosResponse
entity: TEntity
}
interface DeleteEntityResult {
response: AxiosResponse
}
interface EntityActionEndpoints {
post?: string
delete?: string
}
interface EntityCallbacks<TEntity extends Entity = Entity> {
onSuccess?(entity?: TEntity): void
}
function useEntityActions<TEntity extends Entity = Entity, P = any>(
path: EntityPath,
function useEntityActions<TEntity extends Entity = Entity, Params = any>(
expandedPath: ExpandedEntitiesPath,
endpoints: EntityActionEndpoints,
opts: UseEntityActionsOpts<TEntity> = {},
) {
const api = useApi();
const dispatch = useAppDispatch();
const getState = useGetState();
const [entityType, listKey] = path;
const { entityType, path } = parseEntitiesPath(expandedPath);
const [isLoading, setIsLoading] = useState<boolean>(false);
function createEntity(params: P, callbacks: EntityCallbacks = {}): Promise<CreateEntityResult<TEntity>> {
if (!endpoints.post) return Promise.reject(endpoints);
setIsLoading(true);
return api.post(endpoints.post, params).then((response) => {
const schema = opts.schema || z.custom<TEntity>();
const entity = schema.parse(response.data);
// TODO: optimistic updating
dispatch(importEntities([entity], entityType, listKey));
if (callbacks.onSuccess) {
callbacks.onSuccess(entity);
}
setIsLoading(false);
return {
response,
entity,
};
});
}
function deleteEntity(entityId: string, callbacks: EntityCallbacks = {}): Promise<DeleteEntityResult> {
const deleteEntity = useDeleteEntity(entityType, (entityId) => {
if (!endpoints.delete) return Promise.reject(endpoints);
// Get the entity before deleting, so we can reverse the action if the API request fails.
const entity = getState().entities[entityType]?.store[entityId];
// Optimistically delete the entity from the _store_ but keep the lists in tact.
dispatch(deleteEntities([entityId], entityType, { preserveLists: true }));
return api.delete(endpoints.delete.replace(':id', entityId))
.finally(() => setIsLoading(false));
});
setIsLoading(true);
return api.delete(endpoints.delete.replaceAll(':id', entityId)).then((response) => {
if (callbacks.onSuccess) {
callbacks.onSuccess();
}
// Success - finish deleting entity from the state.
dispatch(deleteEntities([entityId], entityType));
return {
response,
};
}).catch((e) => {
if (entity) {
// If the API failed, reimport the entity.
dispatch(importEntities([entity], entityType));
}
throw e;
}).finally(() => {
setIsLoading(false);
});
}
const createEntity = useCreateEntity(path, (params: Params) => {
if (!endpoints.post) return Promise.reject(endpoints);
return api.post(endpoints.post, params)
.finally(() => setIsLoading(false));
}, opts);
return {
createEntity,

View file

@ -0,0 +1,33 @@
import { useAppDispatch } from 'soapbox/hooks';
import { incrementEntities } from '../actions';
import { parseEntitiesPath } from './utils';
import type { ExpandedEntitiesPath } from './types';
type IncrementFn<T> = (entityId: string) => Promise<T> | T;
/**
* Increases (or decreases) the `totalCount` in the entity list by the specified amount.
* This only works if the API returns an `X-Total-Count` header and your components read it.
*/
function useIncrementEntity<T = unknown>(
expandedPath: ExpandedEntitiesPath,
diff: number,
incrementFn: IncrementFn<T>,
) {
const { entityType, listKey } = parseEntitiesPath(expandedPath);
const dispatch = useAppDispatch();
return async function incrementEntity(entityId: string): Promise<void> {
dispatch(incrementEntities(entityType, listKey, diff));
try {
await incrementFn(entityId);
} catch (e) {
dispatch(incrementEntities(entityType, listKey, diff * -1));
}
};
}
export { useIncrementEntity };

View file

@ -0,0 +1,15 @@
import type { EntitiesPath, ExpandedEntitiesPath } from './types';
function parseEntitiesPath(expandedPath: ExpandedEntitiesPath) {
const [entityType, ...listKeys] = expandedPath;
const listKey = (listKeys || []).join(':');
const path: EntitiesPath = [entityType, listKey];
return {
entityType,
listKey,
path,
};
}
export { parseEntitiesPath };

View file

@ -3,10 +3,13 @@ import produce, { enableMapSet } from 'immer';
import {
ENTITIES_IMPORT,
ENTITIES_DELETE,
ENTITIES_DISMISS,
ENTITIES_FETCH_REQUEST,
ENTITIES_FETCH_SUCCESS,
ENTITIES_FETCH_FAIL,
EntityAction,
ENTITIES_INVALIDATE_LIST,
ENTITIES_INCREMENT,
} from './actions';
import { createCache, createList, updateStore, updateList } from './utils';
@ -27,17 +30,25 @@ const importEntities = (
entities: Entity[],
listKey?: string,
newState?: EntityListState,
overwrite = false,
): State => {
return produce(state, draft => {
const cache = draft[entityType] ?? createCache();
cache.store = updateStore(cache.store, entities);
if (typeof listKey === 'string') {
let list = { ...(cache.lists[listKey] ?? createList()) };
let list = cache.lists[listKey] ?? createList();
if (overwrite) {
list.ids = new Set();
}
list = updateList(list, entities);
if (newState) {
list.state = newState;
}
cache.lists[listKey] = list;
}
@ -59,7 +70,13 @@ const deleteEntities = (
if (!opts?.preserveLists) {
for (const list of Object.values(cache.lists)) {
list?.ids.delete(id);
if (list) {
list.ids.delete(id);
if (typeof list.state.totalCount === 'number') {
list.state.totalCount--;
}
}
}
}
}
@ -68,6 +85,47 @@ const deleteEntities = (
});
};
const dismissEntities = (
state: State,
entityType: string,
ids: Iterable<string>,
listKey: string,
) => {
return produce(state, draft => {
const cache = draft[entityType] ?? createCache();
const list = cache.lists[listKey];
if (list) {
for (const id of ids) {
list.ids.delete(id);
if (typeof list.state.totalCount === 'number') {
list.state.totalCount--;
}
}
draft[entityType] = cache;
}
});
};
const incrementEntities = (
state: State,
entityType: string,
listKey: string,
diff: number,
) => {
return produce(state, draft => {
const cache = draft[entityType] ?? createCache();
const list = cache.lists[listKey];
if (typeof list?.state?.totalCount === 'number') {
list.state.totalCount += diff;
draft[entityType] = cache;
}
});
};
const setFetching = (
state: State,
entityType: string,
@ -89,6 +147,14 @@ const setFetching = (
});
};
const invalidateEntityList = (state: State, entityType: string, listKey: string) => {
return produce(state, draft => {
const cache = draft[entityType] ?? createCache();
const list = cache.lists[listKey] ?? createList();
list.state.invalid = true;
});
};
/** Stores various entity data and lists in a one reducer. */
function reducer(state: Readonly<State> = {}, action: EntityAction): State {
switch (action.type) {
@ -96,12 +162,18 @@ function reducer(state: Readonly<State> = {}, action: EntityAction): State {
return importEntities(state, action.entityType, action.entities, action.listKey);
case ENTITIES_DELETE:
return deleteEntities(state, action.entityType, action.ids, action.opts);
case ENTITIES_DISMISS:
return dismissEntities(state, action.entityType, action.ids, action.listKey);
case ENTITIES_INCREMENT:
return incrementEntities(state, action.entityType, action.listKey, action.diff);
case ENTITIES_FETCH_SUCCESS:
return importEntities(state, action.entityType, action.entities, action.listKey, action.newState);
return importEntities(state, action.entityType, action.entities, action.listKey, action.newState, action.overwrite);
case ENTITIES_FETCH_REQUEST:
return setFetching(state, action.entityType, action.listKey, true);
case ENTITIES_FETCH_FAIL:
return setFetching(state, action.entityType, action.listKey, false, action.error);
case ENTITIES_INVALIDATE_LIST:
return invalidateEntityList(state, action.entityType, action.listKey);
default:
return state;
}

View file

@ -23,6 +23,8 @@ interface EntityListState {
next: string | undefined
/** Previous URL for pagination, if any. */
prev: string | undefined
/** Total number of items according to the API. */
totalCount: number | undefined
/** Error returned from the API, if any. */
error: any
/** Whether data has already been fetched */
@ -31,6 +33,8 @@ interface EntityListState {
fetching: boolean
/** Date of the last API fetch for this list. */
lastFetchedAt: Date | undefined
/** Whether the entities should be refetched on the next component mount. */
invalid: boolean
}
/** Cache data pertaining to a paritcular entity type.. */

View file

@ -11,9 +11,16 @@ const updateStore = (store: EntityStore, entities: Entity[]): EntityStore => {
/** Update the list with new entity IDs. */
const updateList = (list: EntityList, entities: Entity[]): EntityList => {
const newIds = entities.map(entity => entity.id);
const ids = new Set([...Array.from(list.ids), ...newIds]);
if (typeof list.state.totalCount === 'number') {
const sizeDiff = ids.size - list.ids.size;
list.state.totalCount += sizeDiff;
}
return {
...list,
ids: new Set([...Array.from(list.ids), ...newIds]),
ids,
};
};
@ -33,10 +40,12 @@ const createList = (): EntityList => ({
const createListState = (): EntityListState => ({
next: undefined,
prev: undefined,
totalCount: 0,
error: null,
fetched: false,
fetching: false,
lastFetchedAt: undefined,
invalid: false,
});
export {

View file

@ -3,7 +3,8 @@ import { defineMessages, useIntl } from 'react-intl';
import { approveUsers } from 'soapbox/actions/admin';
import { rejectUserModal } from 'soapbox/actions/moderation';
import { Stack, HStack, Text, IconButton } from 'soapbox/components/ui';
import { AuthorizeRejectButtons } from 'soapbox/components/authorize-reject-buttons';
import { Stack, HStack, Text } from 'soapbox/components/ui';
import { useAppSelector, useAppDispatch } from 'soapbox/hooks';
import { makeGetAccount } from 'soapbox/selectors';
import toast from 'soapbox/toast';
@ -29,19 +30,21 @@ const UnapprovedAccount: React.FC<IUnapprovedAccount> = ({ accountId }) => {
if (!account) return null;
const handleApprove = () => {
dispatch(approveUsers([account.id]))
return dispatch(approveUsers([account.id]))
.then(() => {
const message = intl.formatMessage(messages.approved, { acct: `@${account.acct}` });
toast.success(message);
})
.catch(() => {});
});
};
const handleReject = () => {
dispatch(rejectUserModal(intl, account.id, () => {
const message = intl.formatMessage(messages.rejected, { acct: `@${account.acct}` });
toast.info(message);
}));
return new Promise<void>((resolve) => {
dispatch(rejectUserModal(intl, account.id, () => {
const message = intl.formatMessage(messages.rejected, { acct: `@${account.acct}` });
toast.info(message);
resolve();
}));
});
};
return (
@ -55,20 +58,12 @@ const UnapprovedAccount: React.FC<IUnapprovedAccount> = ({ accountId }) => {
</Text>
</Stack>
<HStack space={2} alignItems='center'>
<IconButton
src={require('@tabler/icons/check.svg')}
onClick={handleApprove}
theme='outlined'
iconClassName='p-1 text-gray-600 dark:text-gray-400'
<Stack justifyContent='center'>
<AuthorizeRejectButtons
onAuthorize={handleApprove}
onReject={handleReject}
/>
<IconButton
src={require('@tabler/icons/x.svg')}
onClick={handleReject}
theme='outlined'
iconClassName='p-1 text-gray-600 dark:text-gray-400'
/>
</HStack>
</Stack>
</HStack>
);
};

View file

@ -1,36 +1,23 @@
import React, { useCallback } from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { authorizeFollowRequest, rejectFollowRequest } from 'soapbox/actions/accounts';
import Account from 'soapbox/components/account';
import { Button, HStack } from 'soapbox/components/ui';
import { AuthorizeRejectButtons } from 'soapbox/components/authorize-reject-buttons';
import { useAppDispatch, useAppSelector } from 'soapbox/hooks';
import { makeGetAccount } from 'soapbox/selectors';
const messages = defineMessages({
authorize: { id: 'follow_request.authorize', defaultMessage: 'Authorize' },
reject: { id: 'follow_request.reject', defaultMessage: 'Reject' },
});
interface IAccountAuthorize {
id: string
}
const AccountAuthorize: React.FC<IAccountAuthorize> = ({ id }) => {
const intl = useIntl();
const dispatch = useAppDispatch();
const getAccount = useCallback(makeGetAccount(), []);
const account = useAppSelector((state) => getAccount(state, id));
const onAuthorize = () => {
dispatch(authorizeFollowRequest(id));
};
const onReject = () => {
dispatch(rejectFollowRequest(id));
};
const onAuthorize = () => dispatch(authorizeFollowRequest(id));
const onReject = () => dispatch(rejectFollowRequest(id));
if (!account) return null;
@ -39,22 +26,10 @@ const AccountAuthorize: React.FC<IAccountAuthorize> = ({ id }) => {
<Account
account={account}
action={
<HStack className='ml-1' space={2}>
<Button
theme='secondary'
size='sm'
text={intl.formatMessage(messages.authorize)}
icon={require('@tabler/icons/check.svg')}
onClick={onAuthorize}
/>
<Button
theme='danger'
size='sm'
text={intl.formatMessage(messages.reject)}
icon={require('@tabler/icons/x.svg')}
onClick={onReject}
/>
</HStack>
<AuthorizeRejectButtons
onAuthorize={onAuthorize}
onReject={onReject}
/>
}
/>
</div>

View file

@ -1,8 +1,11 @@
import clsx from 'clsx';
import React, { useMemo } from 'react';
import { PendingItemsRow } from 'soapbox/components/pending-items-row';
import ScrollableList from 'soapbox/components/scrollable-list';
import { useGroup } from 'soapbox/hooks';
import { useGroupMembershipRequests } from 'soapbox/hooks/api/groups/useGroupMembershipRequests';
import { useGroupMembers } from 'soapbox/hooks/api/useGroupMembers';
import { useGroup } from 'soapbox/queries/groups';
import { GroupRoles } from 'soapbox/schemas/group-member';
import PlaceholderAccount from '../placeholder/components/placeholder-account';
@ -22,8 +25,9 @@ const GroupMembers: React.FC<IGroupMembers> = (props) => {
const { groupMembers: owners, isFetching: isFetchingOwners } = useGroupMembers(groupId, GroupRoles.OWNER);
const { groupMembers: admins, isFetching: isFetchingAdmins } = useGroupMembers(groupId, GroupRoles.ADMIN);
const { groupMembers: users, isFetching: isFetchingUsers, fetchNextPage, hasNextPage } = useGroupMembers(groupId, GroupRoles.USER);
const { isFetching: isFetchingPending, count: pendingCount } = useGroupMembershipRequests(groupId);
const isLoading = isFetchingGroup || isFetchingOwners || isFetchingAdmins || isFetchingUsers;
const isLoading = isFetchingGroup || isFetchingOwners || isFetchingAdmins || isFetchingUsers || isFetchingPending;
const members = useMemo(() => [
...owners,
@ -37,12 +41,17 @@ const GroupMembers: React.FC<IGroupMembers> = (props) => {
scrollKey='group-members'
hasMore={hasNextPage}
onLoadMore={fetchNextPage}
isLoading={isLoading || !group}
showLoading={!group || isLoading && members.length === 0}
isLoading={!group || isLoading}
showLoading={!group || isFetchingPending || isLoading && members.length === 0}
placeholderComponent={PlaceholderAccount}
placeholderCount={3}
className='divide-y divide-solid divide-gray-300'
className='divide-y divide-solid divide-gray-200 dark:divide-gray-800'
itemClassName='py-3 last:pb-0'
prepend={(pendingCount > 0) && (
<div className={clsx('py-3', { 'border-b border-gray-200 dark:border-gray-800': members.length })}>
<PendingItemsRow to={`/groups/${groupId}/manage/requests`} count={pendingCount} />
</div>
)}
>
{members.map((member) => (
<GroupMemberListItem

View file

@ -1,70 +1,48 @@
import React, { useCallback, useEffect } from 'react';
import React from 'react';
import { FormattedMessage, defineMessages, useIntl } from 'react-intl';
import { authorizeGroupMembershipRequest, fetchGroupMembershipRequests, rejectGroupMembershipRequest } from 'soapbox/actions/groups';
import Account from 'soapbox/components/account';
import { AuthorizeRejectButtons } from 'soapbox/components/authorize-reject-buttons';
import ScrollableList from 'soapbox/components/scrollable-list';
import { Button, Column, HStack, Spinner } from 'soapbox/components/ui';
import { useAppDispatch, useAppSelector, useGroup } from 'soapbox/hooks';
import { makeGetAccount } from 'soapbox/selectors';
import { Column, HStack, Spinner } from 'soapbox/components/ui';
import { useGroup } from 'soapbox/hooks';
import { useGroupMembershipRequests } from 'soapbox/hooks/api/groups/useGroupMembershipRequests';
import toast from 'soapbox/toast';
import ColumnForbidden from '../ui/components/column-forbidden';
import type { Account as AccountEntity } from 'soapbox/schemas';
type RouteParams = { id: string };
const messages = defineMessages({
heading: { id: 'column.group_pending_requests', defaultMessage: 'Pending requests' },
authorize: { id: 'group.group_mod_authorize', defaultMessage: 'Accept' },
authorized: { id: 'group.group_mod_authorize.success', defaultMessage: 'Accepted @{name} to group' },
reject: { id: 'group.group_mod_reject', defaultMessage: 'Reject' },
rejected: { id: 'group.group_mod_reject.success', defaultMessage: 'Rejected @{name} from group' },
authorizeFail: { id: 'group.group_mod_authorize.fail', defaultMessage: 'Failed to approve @{name}' },
rejectFail: { id: 'group.group_mod_reject.fail', defaultMessage: 'Failed to reject @{name}' },
});
interface IMembershipRequest {
accountId: string
groupId: string
account: AccountEntity
onAuthorize(account: AccountEntity): Promise<unknown>
onReject(account: AccountEntity): Promise<unknown>
}
const MembershipRequest: React.FC<IMembershipRequest> = ({ accountId, groupId }) => {
const intl = useIntl();
const dispatch = useAppDispatch();
const getAccount = useCallback(makeGetAccount(), []);
const account = useAppSelector((state) => getAccount(state, accountId));
const MembershipRequest: React.FC<IMembershipRequest> = ({ account, onAuthorize, onReject }) => {
if (!account) return null;
const handleAuthorize = () =>
dispatch(authorizeGroupMembershipRequest(groupId, accountId)).then(() => {
toast.success(intl.formatMessage(messages.authorized, { name: account.acct }));
});
const handleReject = () =>
dispatch(rejectGroupMembershipRequest(groupId, accountId)).then(() => {
toast.success(intl.formatMessage(messages.rejected, { name: account.acct }));
});
const handleAuthorize = () => onAuthorize(account);
const handleReject = () => onReject(account);
return (
<HStack space={1} alignItems='center' justifyContent='between' className='p-2.5'>
<div className='w-full'>
<Account account={account} withRelationship={false} />
</div>
<HStack space={2}>
<Button
theme='secondary'
size='sm'
text={intl.formatMessage(messages.authorize)}
onClick={handleAuthorize}
/>
<Button
theme='danger'
size='sm'
text={intl.formatMessage(messages.reject)}
onClick={handleReject}
/>
</HStack>
<AuthorizeRejectButtons
onAuthorize={handleAuthorize}
onReject={handleReject}
/>
</HStack>
);
};
@ -74,19 +52,14 @@ interface IGroupMembershipRequests {
}
const GroupMembershipRequests: React.FC<IGroupMembershipRequests> = ({ params }) => {
const intl = useIntl();
const dispatch = useAppDispatch();
const id = params?.id;
const intl = useIntl();
const { group } = useGroup(id);
const accountIds = useAppSelector((state) => state.user_lists.membership_requests.get(id)?.items);
useEffect(() => {
dispatch(fetchGroupMembershipRequests(id));
}, [id]);
const { accounts, authorize, reject, isLoading } = useGroupMembershipRequests(id);
if (!group || !group.relationship || !accountIds) {
if (!group || !group.relationship || isLoading) {
return (
<Column label={intl.formatMessage(messages.heading)}>
<Spinner />
@ -95,20 +68,39 @@ const GroupMembershipRequests: React.FC<IGroupMembershipRequests> = ({ params })
}
if (!group.relationship.role || !['owner', 'admin', 'moderator'].includes(group.relationship.role)) {
return (<ColumnForbidden />);
return <ColumnForbidden />;
}
const emptyMessage = <FormattedMessage id='empty_column.group_membership_requests' defaultMessage='There are no pending membership requests for this group.' />;
async function handleAuthorize(account: AccountEntity) {
try {
await authorize(account.id);
} catch (_e) {
toast.error(intl.formatMessage(messages.authorizeFail, { name: account.username }));
}
}
async function handleReject(account: AccountEntity) {
try {
await reject(account.id);
} catch (_e) {
toast.error(intl.formatMessage(messages.rejectFail, { name: account.username }));
}
}
return (
<Column label={intl.formatMessage(messages.heading)} backHref={`/groups/${id}/manage`}>
<Column label={intl.formatMessage(messages.heading)}>
<ScrollableList
scrollKey='group_membership_requests'
emptyMessage={emptyMessage}
emptyMessage={<FormattedMessage id='empty_column.group_membership_requests' defaultMessage='There are no pending membership requests for this group.' />}
>
{accountIds.map((accountId) =>
<MembershipRequest key={accountId} accountId={accountId} groupId={id} />,
)}
{accounts.map((account) => (
<MembershipRequest
key={account.id}
account={account}
onAuthorize={handleAuthorize}
onReject={handleReject}
/>
))}
</ScrollableList>
</Column>
);

View file

@ -45,7 +45,7 @@ describe('<PendingGroupRows />', () => {
it('should not render', () => {
renderApp(store);
expect(screen.queryAllByTestId('pending-groups-row')).toHaveLength(0);
expect(screen.queryAllByTestId('pending-items-row')).toHaveLength(0);
});
});
@ -69,7 +69,7 @@ describe('<PendingGroupRows />', () => {
it('should not render', () => {
renderApp(store);
expect(screen.queryAllByTestId('pending-groups-row')).toHaveLength(0);
expect(screen.queryAllByTestId('pending-items-row')).toHaveLength(0);
});
});
@ -95,7 +95,7 @@ describe('<PendingGroupRows />', () => {
renderApp(store);
await waitFor(() => {
expect(screen.queryAllByTestId('pending-groups-row')).toHaveLength(1);
expect(screen.queryAllByTestId('pending-items-row')).toHaveLength(1);
});
});
});

View file

@ -1,8 +1,7 @@
import React from 'react';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import { Divider, HStack, Icon, Text } from 'soapbox/components/ui';
import { PendingItemsRow } from 'soapbox/components/pending-items-row';
import { Divider } from 'soapbox/components/ui';
import { useFeatures } from 'soapbox/hooks';
import { usePendingGroups } from 'soapbox/queries/groups';
@ -17,31 +16,11 @@ export default () => {
return (
<>
<Link to='/groups/pending-requests' className='group' data-testid='pending-groups-row'>
<HStack alignItems='center' justifyContent='between'>
<HStack alignItems='center' space={2}>
<div className='rounded-full bg-primary-200 p-3 text-primary-500 dark:bg-primary-800 dark:text-primary-200'>
<Icon
src={require('@tabler/icons/exclamation-circle.svg')}
className='h-7 w-7'
/>
</div>
<Text weight='bold' size='md'>
<FormattedMessage
id='groups.pending.count'
defaultMessage='{number, plural, one {# pending request} other {# pending requests}}'
values={{ number: groups.length }}
/>
</Text>
</HStack>
<Icon
src={require('@tabler/icons/chevron-right.svg')}
className='h-5 w-5 text-gray-600 transition-colors group-hover:text-gray-700 dark:text-gray-600 dark:group-hover:text-gray-500'
/>
</HStack>
</Link>
<PendingItemsRow
to='/groups/pending-requests'
count={groups.length}
size='lg'
/>
<Divider />
</>

View file

@ -0,0 +1,38 @@
import { Entities } from 'soapbox/entity-store/entities';
import { useEntities, useIncrementEntity } from 'soapbox/entity-store/hooks';
import { useApi } from 'soapbox/hooks/useApi';
import { accountSchema } from 'soapbox/schemas';
import type { ExpandedEntitiesPath } from 'soapbox/entity-store/hooks/types';
function useGroupMembershipRequests(groupId: string) {
const api = useApi();
const path: ExpandedEntitiesPath = [Entities.ACCOUNTS, 'membership_requests', groupId];
const { entities, invalidate, ...rest } = useEntities(
path,
`/api/v1/groups/${groupId}/membership_requests`,
{ schema: accountSchema },
);
const authorize = useIncrementEntity(path, -1, (accountId: string) => {
return api
.post(`/api/v1/groups/${groupId}/membership_requests/${accountId}/authorize`)
.then(invalidate);
});
const reject = useIncrementEntity(path, -1, (accountId: string) => {
return api
.post(`/api/v1/groups/${groupId}/membership_requests/${accountId}/reject`)
.then(invalidate);
});
return {
accounts: entities,
authorize,
reject,
...rest,
};
}
export { useGroupMembershipRequests };

View file

@ -11,7 +11,7 @@ function useGroups() {
const features = useFeatures();
const { entities, ...result } = useEntities<Group>(
[Entities.GROUPS, ''],
[Entities.GROUPS],
'/api/v1/groups',
{ enabled: features.groups, schema: groupSchema },
);

View file

@ -192,6 +192,7 @@
"auth.invalid_credentials": "Wrong username or password",
"auth.logged_out": "Logged out.",
"auth_layout.register": "Create an account",
"authorize.success": "Approved",
"backups.actions.create": "Create backup",
"backups.empty_message": "No backups found. {action}",
"backups.empty_message.action": "Create one now?",
@ -768,16 +769,14 @@
"group.cancel_request": "Cancel Request",
"group.delete.success": "Group successfully deleted",
"group.demote.user.success": "@{name} is now a member",
"group.group_mod_authorize": "Accept",
"group.group_mod_authorize.success": "Accepted @{name} to group",
"group.group_mod_authorize.fail": "Failed to approve @{name}",
"group.group_mod_block": "Ban from group",
"group.group_mod_block.success": "@{name} is banned",
"group.group_mod_demote": "Remove {role} role",
"group.group_mod_kick": "Kick @{name} from group",
"group.group_mod_kick.success": "Kicked @{name} from group",
"group.group_mod_promote_mod": "Assign {role} role",
"group.group_mod_reject": "Reject",
"group.group_mod_reject.success": "Rejected @{name} from group",
"group.group_mod_reject.fail": "Failed to reject @{name}",
"group.group_mod_unblock": "Unblock",
"group.group_mod_unblock.success": "Unblocked @{name} from group",
"group.header.alt": "Group header",
@ -1202,6 +1201,7 @@
"registrations.unprocessable_entity": "This username has already been taken.",
"registrations.username.hint": "May only contain A-Z, 0-9, and underscores",
"registrations.username.label": "Your username",
"reject.success": "Rejected",
"relative_time.days": "{number}d",
"relative_time.hours": "{number}h",
"relative_time.just_now": "now",

View file

@ -13,6 +13,7 @@ import {
SuggestedGroupsPanel,
} from 'soapbox/features/ui/util/async-components';
import { useGroup, useOwnAccount } from 'soapbox/hooks';
import { useGroupMembershipRequests } from 'soapbox/hooks/api/groups/useGroupMembershipRequests';
import { Group } from 'soapbox/schemas';
import { Tabs } from '../components/ui';
@ -64,17 +65,12 @@ const GroupPage: React.FC<IGroupPage> = ({ params, children }) => {
const id = params?.id || '';
const { group } = useGroup(id);
const { accounts: pending } = useGroupMembershipRequests(id);
const isMember = !!group?.relationship?.member;
const isBlocked = group?.relationship?.blocked_by;
const isPrivate = group?.locked;
// if ((group as any) === false) {
// return (
// <MissingIndicator />
// );
// }
const items = [
{
text: intl.formatMessage(messages.all),
@ -85,6 +81,7 @@ const GroupPage: React.FC<IGroupPage> = ({ params, children }) => {
text: intl.formatMessage(messages.members),
to: `/groups/${group?.id}/members`,
name: '/groups/:id/members',
count: pending.length,
},
];

View file

@ -1,9 +1,13 @@
import React from 'react';
import { FormattedNumber } from 'react-intl';
import { z } from 'zod';
/** Check if a value is REALLY a number. */
export const isNumber = (value: unknown): value is number => typeof value === 'number' && !isNaN(value);
/** The input is a number and is not NaN. */
export const realNumberSchema = z.coerce.number().refine(n => !isNaN(n));
export const secondsToDays = (seconds: number) => Math.floor(seconds / (3600 * 24));
const roundDown = (num: number) => {