UNPKG

@selfcommunity/react-ui

Version:

React UI Components to integrate a Community created with SelfCommunity Platform.

243 lines (238 loc) • 18.1 kB
import { __rest } from "tslib"; import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime"; import { Box, Button, Chip, Divider, FormControl, Grid, Icon, IconButton, InputAdornment, InputLabel, MenuItem, Radio, Select, styled, TextField, Typography, useMediaQuery, useTheme, useThemeProps } from '@mui/material'; import { Endpoints, http } from '@selfcommunity/api-services'; import { SCPreferences, SCPreferencesContext, SCUserContext, UserUtils } from '@selfcommunity/react-core'; import { SCEventDateFilterType, SCEventLocationFilterType, SCEventSubscriptionStatusType } from '@selfcommunity/types'; import { Logger } from '@selfcommunity/utils'; import classNames from 'classnames'; import PubSub from 'pubsub-js'; import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { FormattedMessage } from 'react-intl'; import { SCOPE_SC_UI } from '../../constants/Errors'; import { DEFAULT_PAGINATION_OFFSET } from '../../constants/Pagination'; import { SCGroupEventType, SCTopicType } from '../../constants/PubSub'; import CreateEventButton from '../CreateEventButton'; import Event, { EventSkeleton } from '../Event'; import Skeleton from '../Events/Skeleton'; import { PREFIX } from './constants'; import LocationEventsFilter from './LocationEventsFilter'; import PastEventsFilter from './PastEventsFilter'; import OngoingEventsFilter from './OngoingEventsFilter'; const classes = { root: `${PREFIX}-root`, filters: `${PREFIX}-filters`, events: `${PREFIX}-events`, sectionTitle: `${PREFIX}-section-title`, divider: `${PREFIX}-divider`, item: `${PREFIX}-item`, itemSkeleton: `${PREFIX}-item-skeleton`, noResults: `${PREFIX}-no-results`, showMore: `${PREFIX}-show-more`, search: `${PREFIX}-search` }; const options = [ { value: SCEventDateFilterType.ALL, label: _jsx(FormattedMessage, { id: "ui.events.select.any", defaultMessage: "ui.events.select.any" }) }, { value: SCEventDateFilterType.TODAY, label: _jsx(FormattedMessage, { id: "ui.events.select.today", defaultMessage: "ui.events.select.today" }) }, { value: SCEventDateFilterType.TOMORROW, label: _jsx(FormattedMessage, { id: "ui.events.select.tomorrow", defaultMessage: "ui.events.select.tomorrow" }) }, { value: SCEventDateFilterType.THIS_WEEK, label: _jsx(FormattedMessage, { id: "ui.events.select.thisWeek", defaultMessage: "ui.events.select.thisWeek" }) }, { value: SCEventDateFilterType.NEXT_WEEK, label: _jsx(FormattedMessage, { id: "ui.events.select.nextWeek", defaultMessage: "ui.events.select.nextWeek" }) }, { value: SCEventDateFilterType.THIS_MONTH, label: _jsx(FormattedMessage, { id: "ui.events.select.thisMonth", defaultMessage: "ui.events.select.thisMonth" }) } ]; const Root = styled(Box, { name: PREFIX, slot: 'Root' })(() => ({})); export const EventsChipRoot = styled(Chip, { name: PREFIX, slot: 'EventsChipRoot', shouldForwardProp: (prop) => prop !== 'showFollowed' && prop !== 'showPastEvents' && prop !== 'showOngoingEvents' })(() => ({})); /** * > API documentation for the Community-JS Events component. Learn about the available props and the CSS API. * * * The Events component renders the list of all available events. * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/Events) #### Import ```jsx import {Events} from '@selfcommunity/react-ui'; ``` #### Component Name The name `SCEvents` can be used when providing style overrides in the theme. #### CSS |Rule Name|Global class|Description| |---|---|---| |root|.SCEvents-root|Styles applied to the root element.| |filters|.SCEvents-filters|Styles applied to the title element.| |events|.SCEvents-events|Styles applied to the title element.| |item|.SCEvents-item|Styles applied to the title element.| |noResults|.SCEvents-no-results|Styles applied to no results section.| |showMore|.SCEvents-show-more|Styles applied to show more button element.| * @param inProps */ export default function Events(inProps) { // PROPS const props = useThemeProps({ props: inProps, name: PREFIX }); const { endpoint = Endpoints.SearchEvents, endpointQueryParams = { limit: 8, offset: DEFAULT_PAGINATION_OFFSET }, className, EventComponentProps = { elevation: 0, square: true }, EventsSkeletonComponentProps = {}, EventSkeletonComponentProps = { elevation: 0, square: true }, GridContainerComponentProps = {}, GridItemComponentProps = {}, CreateEventButtonProps = {}, showFilters = false, filters, general = true, hideTitle = false } = props, rest = __rest(props, ["endpoint", "endpointQueryParams", "className", "EventComponentProps", "EventsSkeletonComponentProps", "EventSkeletonComponentProps", "GridContainerComponentProps", "GridItemComponentProps", "CreateEventButtonProps", "showFilters", "filters", "general", "hideTitle"]); // STATE const [events, setEvents] = useState([]); const [loading, setLoading] = useState(true); const [next, setNext] = useState(null); const [query, setQuery] = useState(''); const [dateSearch, setDateSearch] = useState(options[0].value); const [location, setLocation] = useState(SCEventLocationFilterType.ANY); const [showFollowed, setShowFollowed] = useState(false); const [showPastEvents, setShowPastEvents] = useState(false); const [showOngoingEvents, setShowOngoingEvents] = useState(false); const [showMyEvents, setShowMyEvents] = useState(false); const showUserEvents = !general && (events.length || (!events.length && (showPastEvents || showMyEvents || location !== SCEventLocationFilterType.ANY))); // CONTEXT const scUserContext = useContext(SCUserContext); const scPreferencesContext = useContext(SCPreferencesContext); const onlyStaffEnabled = useMemo(() => scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_EVENTS_ONLY_STAFF_ENABLED].value, [scPreferencesContext.preferences]); // MEMO const contentAvailability = SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences && scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value; // CONST const authUserId = scUserContext.user ? scUserContext.user.id : null; const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down('md')); // REFS const updatesSubscription = useRef(null); // HANDLERS const handleChipClick = () => { setShowFollowed(!showFollowed); }; const handleDeleteClick = () => { setShowFollowed(false); }; const handleChipPastClick = () => { setShowPastEvents(!showPastEvents); }; const handleDeletePastClick = () => { setShowPastEvents(false); }; const handleChipOngoingClick = () => { setShowOngoingEvents(!showOngoingEvents); }; const handleDeleteOngoingClick = () => { setShowOngoingEvents(false); }; /** * Fetches events list */ const fetchEvents = () => { setLoading(true); return http .request({ url: endpoint.url({}), method: endpoint.method, params: Object.assign(Object.assign({}, endpointQueryParams), (general ? Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (query && { search: query })), (dateSearch !== SCEventDateFilterType.ALL && { date_filter: dateSearch })), (location !== SCEventLocationFilterType.ANY && { location })), (showFollowed && { follows: showFollowed })), (showOngoingEvents && { date_filter: SCEventDateFilterType.NOT_PAST })) : Object.assign(Object.assign(Object.assign({ subscription_status: SCEventSubscriptionStatusType.GOING }, (location !== SCEventLocationFilterType.ANY && { location })), (showPastEvents && { past: showPastEvents })), (showMyEvents && { created_by: authUserId })))) }) .then((res) => { setEvents(res.data.results); setNext(res.data.next); setLoading(false); }) .catch((error) => { Logger.error(SCOPE_SC_UI, error); }); }; /** * On mount, fetches events list */ useEffect(() => { if (!contentAvailability && !authUserId) { return; } else { fetchEvents(); } }, [contentAvailability, authUserId, dateSearch, location, showFollowed, showPastEvents, showMyEvents, showOngoingEvents]); /** * Subscriber for pubsub callback */ const onDeleteEventHandler = useCallback((_msg, deleted) => { setEvents((prev) => { if (prev.some((e) => e.id === deleted)) { return prev.filter((e) => e.id !== deleted); } return prev; }); }, [events]); /** * On mount, subscribe to receive event updates (only delete) */ useEffect(() => { if (events) { updatesSubscription.current = PubSub.subscribe(`${SCTopicType.EVENT}.${SCGroupEventType.DELETE}`, onDeleteEventHandler); } return () => { updatesSubscription.current && PubSub.unsubscribe(updatesSubscription.current); }; }, [events]); const handleNext = useMemo(() => () => { if (!next) { return; } return http .request({ url: next, method: general ? Endpoints.SearchEvents.method : Endpoints.GetUserEvents.method }) .then((res) => { setEvents([...events, ...res.data.results]); setNext(res.data.next); }) .catch((error) => console.log(error)) .then(() => setLoading(false)); }, [next]); /** * Handle change filter name * @param event */ const handleOnChangeFilterName = (event) => { setQuery(event.target.value); }; /** * Handle change time frame * @param event */ const handleOnChangeTimeFrame = (event) => { setDateSearch(event.target.value); }; /** * Handle change location * @param event */ const handleOnChangeLocation = (event) => { setLocation(event.target.value); }; /** * Renders events list */ const content = (_jsxs(_Fragment, { children: [showFilters && (_jsx(Grid, Object.assign({ container: true, className: classes.filters, gap: 2 }, { children: filters ? (filters) : showUserEvents ? (_jsxs(_Fragment, { children: [_jsx(Grid, Object.assign({ item: true }, { children: _jsx(EventsChipRoot, { color: showMyEvents ? 'secondary' : 'default', variant: showMyEvents ? 'filled' : 'outlined', label: _jsx(FormattedMessage, { id: "ui.events.filterByCreatedByMe", defaultMessage: "ui.events.filterByCreatedByMe" }), onClick: () => setShowMyEvents(!showMyEvents), // @ts-expect-error this is needed to use showFollowed into SCEvents showFollowed: showMyEvents, deleteIcon: showMyEvents ? _jsx(Icon, { children: "close" }) : null, onDelete: showMyEvents ? () => setShowMyEvents(false) : null, disabled: loading }) })), _jsx(Grid, Object.assign({ item: true }, { children: _jsx(PastEventsFilter, { showPastEvents: showPastEvents, handleClick: handleChipPastClick, handleDeleteClick: handleDeletePastClick, disabled: loading }) })), _jsx(Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: _jsx(LocationEventsFilter, { value: location, disabled: loading, handleOnChange: handleOnChangeLocation }) }))] })) : general ? (_jsxs(_Fragment, { children: [_jsx(Grid, Object.assign({ item: true, xs: 12, md: 3 }, { children: _jsx(TextField, { className: classes.search, size: 'small', fullWidth: true, value: query, label: _jsx(FormattedMessage, { id: "ui.events.filterByName", defaultMessage: "ui.events.filterByName" }), variant: "outlined", onChange: handleOnChangeFilterName, disabled: loading, onKeyUp: (e) => { e.preventDefault(); if (e.key === 'Enter') { fetchEvents(); } }, InputProps: { endAdornment: (_jsx(InputAdornment, Object.assign({ position: "end" }, { children: isMobile ? (_jsx(IconButton, Object.assign({ onClick: () => fetchEvents(), disabled: loading }, { children: _jsx(Icon, { children: "search" }) }))) : (_jsx(Button, { size: "small", variant: "contained", color: "secondary", onClick: () => fetchEvents(), endIcon: _jsx(Icon, { children: "search" }), disabled: loading })) }))) } }) })), _jsx(Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: _jsxs(FormControl, Object.assign({ fullWidth: true }, { children: [_jsx(InputLabel, { children: _jsx(FormattedMessage, { id: "ui.events.filterByDate", defaultMessage: "ui.events.filterByDate" }) }), _jsx(Select, Object.assign({ disabled: showOngoingEvents || loading, size: 'small', label: _jsx(FormattedMessage, { id: "ui.events.filterByDate", defaultMessage: "ui.events.filterByDate" }), value: dateSearch, onChange: handleOnChangeTimeFrame, renderValue: (selected) => options.find((option) => option.value === selected).label }, { children: options.map((option) => (_jsxs(MenuItem, Object.assign({ value: option.value }, { children: [_jsx(Radio, { checked: dateSearch === option.value, value: option.value, name: "radio-button-select", inputProps: { 'aria-label': option.label } }), option.label] }), option.value))) }))] })) })), _jsx(Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: _jsx(LocationEventsFilter, { value: location, disabled: loading, handleOnChange: handleOnChangeLocation }) })), authUserId && (_jsx(Grid, Object.assign({ item: true }, { children: _jsx(EventsChipRoot, { color: showFollowed ? 'secondary' : 'default', variant: showFollowed ? 'filled' : 'outlined', label: _jsx(FormattedMessage, { id: "ui.events.filterByFollowedInterest", defaultMessage: "ui.events.filterByFollowedInterest" }), onClick: handleChipClick, // @ts-expect-error this is needed to use showFollowed into SCEvents showFollowed: showFollowed, deleteIcon: showFollowed ? _jsx(Icon, { children: "close" }) : null, onDelete: showFollowed ? handleDeleteClick : null, disabled: loading }) }))), _jsx(Grid, Object.assign({ item: true }, { children: _jsx(OngoingEventsFilter, { showOngoingEvents: showOngoingEvents, handleClick: handleChipOngoingClick, handleDeleteClick: handleDeleteOngoingClick, disabled: dateSearch !== SCEventDateFilterType.ALL || loading }) }))] })) : null }))), _jsx(_Fragment, { children: loading ? (_jsx(Skeleton, Object.assign({}, EventsSkeletonComponentProps, { EventSkeletonProps: EventSkeletonComponentProps }))) : (_jsx(_Fragment, { children: !events.length ? (_jsx(Box, Object.assign({ className: classes.noResults }, { children: general ? (_jsxs(_Fragment, { children: [_jsx(EventSkeleton, Object.assign({}, EventSkeletonComponentProps, { skeletonsAnimation: false, actions: (onlyStaffEnabled && UserUtils.isStaff(scUserContext.user)) || !onlyStaffEnabled ? (_jsx(CreateEventButton, Object.assign({}, CreateEventButtonProps))) : null })), _jsx(Typography, Object.assign({ variant: "body1" }, { children: _jsx(FormattedMessage, { id: "ui.events.noEvents.title", defaultMessage: "ui.events.noEvents.title" }) }))] })) : showUserEvents ? (_jsx(_Fragment, { children: _jsx(Typography, Object.assign({ variant: "body1" }, { children: _jsx(FormattedMessage, { id: "ui.events.noEvents.title.personal", defaultMessage: "ui.events.noEvents.title.personal" }) })) })) : null }))) : (_jsxs(_Fragment, { children: [_jsx(Grid, Object.assign({ container: true, spacing: { xs: 2 }, className: classes.events }, GridContainerComponentProps, { children: _jsxs(_Fragment, { children: [events.map((event) => (_jsx(Grid, Object.assign({ item: true, xs: 12, sm: 12, md: 6, className: classes.item }, GridItemComponentProps, { children: _jsx(Event, Object.assign({ event: event, eventId: event.id }, EventComponentProps)) }), event.id))), authUserId && events.length % 2 !== 0 && (_jsx(Grid, Object.assign({ item: true, xs: 12, sm: 12, md: 6, className: classes.itemSkeleton }, GridItemComponentProps, { children: _jsx(EventSkeleton, Object.assign({}, EventSkeletonComponentProps, { skeletonsAnimation: false, actions: _jsx(CreateEventButton, Object.assign({ variant: "outlined", color: "primary", size: "small" }, CreateEventButtonProps, { children: _jsx(FormattedMessage, { id: "ui.events.skeleton.action.add", defaultMessage: "ui.events.skeleton.action.add" }) })) })) }), 'skeleton-item'))] }) })), Boolean(next) && (_jsx(Button, Object.assign({ color: "secondary", variant: "text", onClick: handleNext, className: classes.showMore }, { children: _jsx(FormattedMessage, { id: "ui.events.button.seeMore", defaultMessage: "ui.events.button.seeMore" }) })))] })) })) })] })); /** * Renders root object (if content availability community option is false and user is anonymous, component is hidden) */ if (!contentAvailability && !scUserContext.user) { return null; } return (_jsxs(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: [_jsx(_Fragment, { children: showUserEvents && !hideTitle ? (_jsxs(_Fragment, { children: [_jsx(Typography, Object.assign({ variant: "h4", className: classes.sectionTitle }, { children: _jsx(FormattedMessage, { id: "ui.events.myEvents.title", defaultMessage: "ui.events.myEvents.title" }) })), _jsx(Divider, { className: classes.divider })] })) : general ? (_jsxs(_Fragment, { children: [_jsx(Typography, Object.assign({ variant: "h4", className: classes.sectionTitle }, { children: _jsx(FormattedMessage, { id: "ui.events.allEvents.title", defaultMessage: "ui.events.allEvents.title" }) })), _jsx(Divider, { className: classes.divider })] })) : null }), content] }))); }