@selfcommunity/react-ui
Version:
React UI Components to integrate a Community created with SelfCommunity Platform.
168 lines (160 loc) • 9 kB
JavaScript
import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useEffect, useMemo, useReducer, useState } from 'react';
import { styled } from '@mui/material/styles';
import List from '@mui/material/List';
import { Button, CardContent, ListItem, Typography, useMediaQuery, useTheme } from '@mui/material';
import { Endpoints, http, SuggestionService } from '@selfcommunity/api-services';
import { CacheStrategies, Logger } from '@selfcommunity/utils';
import { SCCache, useSCUser } from '@selfcommunity/react-core';
import Skeleton from '../CategoryTrendingFeedWidget/Skeleton';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import BaseDialog from '../../shared/BaseDialog';
import InfiniteScroll from '../../shared/InfiniteScroll';
import Widget from '../Widget';
import { useThemeProps } from '@mui/system';
import PollSnippet, { PollSnippetSkeleton } from './PollSnippet';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import { PREFIX } from './constants';
const classes = {
root: `${PREFIX}-root`,
title: `${PREFIX}-title`,
noResults: `${PREFIX}-no-results`,
showMore: `${PREFIX}-show-more`,
dialogRoot: `${PREFIX}-dialog-root`,
endMessage: `${PREFIX}-end-message`,
pollSnippet: `${PREFIX}-poll-snippet`
};
const Root = styled(Widget, {
name: PREFIX,
slot: 'Root'
})(() => ({}));
const DialogRoot = styled(BaseDialog, {
name: PREFIX,
slot: 'DialogRoot'
})(() => ({}));
/**
* > API documentation for the Community-JS Poll Suggestion Widget component. Learn about the available props and the CSS API.
*
*
* This component renders a list of suggested polls.
* Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/PollSuggestion)
#### Import
```jsx
import {PollSuggestionWidget} from '@selfcommunity/react-ui';
```
#### Component Name
The name `SCPollSuggestionWidget` can be used when providing style overrides in the theme.
#### CSS
|Rule Name|Global class|Description|
|---|---|---|
|root|.SCPollSuggestionWidget-root|Styles applied to the root element.|
|title|.SCPollSuggestionWidget-title|Styles applied to the title element.|
|noResults|.SCPollSuggestionWidget-no-results|Styles applied to no results section.|
|showMore|.SCPollSuggestionWidget-show-more|Styles applied to show more button element.|
|dialogRoot|.SCPollSuggestionWidget-dialog-root|Styles applied to the root dialog element.|
|endMessage|.SCPollSuggestionWidget-end-message|Styles applied to the end message element.|
|pollSnippet|.SCPollSuggestionWidget-poll-snippet|Styles applied to the poll snippet element.|
*
* @param inProps
*/
export default function PollSuggestionWidget(inProps) {
// PROPS
const props = useThemeProps({
props: inProps,
name: PREFIX
});
const { autoHide = true, limit = 3, PollSnippetProps = {}, className, cacheStrategy = CacheStrategies.NETWORK_ONLY, onHeightChange, onStateChange, DialogProps = {} } = props, rest = __rest(props, ["autoHide", "limit", "PollSnippetProps", "className", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps"]);
// STATE
const [state, dispatch] = useReducer(dataWidgetReducer, {
isLoadingNext: false,
next: null,
cacheKey: SCCache.getWidgetStateCacheKey(SCCache.POLL_SUGGESTION_TOOLS_STATE_CACHE_PREFIX_KEY),
cacheStrategy,
visibleItems: limit
}, stateWidgetInitializer);
const [openDialog, setOpenDialog] = useState(false);
// CONTEXT
const scUserContext = useSCUser();
// HOOKS
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
/**
* Initialize component
* Fetch data only if the component is not initialized, and it is not loading data
*/
const _initComponent = useMemo(() => () => {
if (!state.initialized && !state.isLoadingNext) {
dispatch({ type: actionWidgetTypes.LOADING_NEXT });
SuggestionService.getPollSuggestion({ limit })
.then((payload) => {
dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
})
.catch((error) => {
dispatch({ type: actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
Logger.error(SCOPE_SC_UI, error);
});
}
}, [state.isLoadingNext, state.initialized, limit, dispatch]);
// EFFECTS
useEffect(() => {
let _t;
if (scUserContext.user) {
_t = setTimeout(_initComponent);
return () => {
_t && clearTimeout(_t);
};
}
}, [scUserContext.user]);
useEffect(() => {
if (openDialog && state.next && state.results.length === limit && state.initialized) {
dispatch({ type: actionWidgetTypes.LOADING_NEXT });
SuggestionService.getPollSuggestion({ offset: limit, limit: 10 })
.then((payload) => {
dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: payload });
})
.catch((error) => {
dispatch({ type: actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
Logger.error(SCOPE_SC_UI, error);
});
}
}, [openDialog, state.next, state.results.length, state.initialized, limit]);
/**
* Virtual feed update
*/
useEffect(() => {
onHeightChange && onHeightChange();
}, [state.results]);
useEffect(() => {
if (scUserContext.user && cacheStrategy === CacheStrategies.NETWORK_ONLY) {
onStateChange && onStateChange({ cacheStrategy: CacheStrategies.CACHE_FIRST });
}
}, [scUserContext.user]);
// HANDLERS
const handleNext = useMemo(() => () => {
dispatch({ type: actionWidgetTypes.LOADING_NEXT });
http
.request({
url: state.next,
method: Endpoints.PollSuggestion.method
})
.then((res) => {
dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
});
}, [dispatch, state.next, state.isLoadingNext, state.initialized]);
const handleToggleDialogOpen = () => {
setOpenDialog((prev) => !prev);
};
// RENDER
if ((autoHide && !state.count && state.initialized) || !scUserContext.user) {
return _jsx(HiddenPlaceholder, {});
}
if (!state.initialized) {
return _jsx(Skeleton, {});
}
const content = (_jsxs(CardContent, { children: [_jsx(Typography, Object.assign({ className: classes.title, variant: "h5" }, { children: _jsx(FormattedMessage, { id: "ui.pollSuggestionWidget.title", defaultMessage: "ui.pollSuggestionWidget.title" }) })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.pollSuggestionWidget.noResults", defaultMessage: "ui.pollSuggestionWidget.noResults" }) }))) : (_jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, state.visibleItems).map((obj) => (_jsx(ListItem, { children: _jsx(PollSnippet, Object.assign({ className: classes.pollSnippet, elevation: 0, feedObj: obj }, PollSnippetProps)) }, obj.id))) }), state.count > state.visibleItems && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.pollSuggestionWidget.button.showAll", defaultMessage: "ui.pollSuggestionWidget.button.showAll" }) })))] })), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { defaultMessage: "ui.pollSuggestionWidget.title", id: "ui.pollSuggestionWidget.title" }), onClose: handleToggleDialogOpen, open: openDialog }, DialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: _jsx(PollSnippetSkeleton, Object.assign({ elevation: 0 }, PollSnippetProps)), height: isMobile ? '100%' : 400, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.pollSuggestionWidget.noMoreResults", defaultMessage: "ui.pollSuggestionWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((obj) => (_jsx(ListItem, { children: _jsx(PollSnippet, Object.assign({ className: classes.pollSnippet, elevation: 0, feedObj: obj }, PollSnippetProps)) }, obj.id))) }) })) })))] }));
return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}