react-dnd#DndProvider JavaScript Examples
The following examples show how to use
react-dnd#DndProvider.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.prod.jsx From ashteki with GNU Affero General Public License v3.0 | 6 votes |
render( <DndProvider backend={TouchBackend} options={{ enableMouseEvents: true }}> <Provider store={store}> <div className='body'> <ReduxToastr timeOut={4000} newestOnTop preventDuplicates position='top-right' transitionIn='fadeIn' transitionOut='fadeOut' /> <ErrorBoundary message={ "We're sorry, a critical error has occured in the client and we're unable to show you anything. Please try refreshing your browser after filling out a report." } > <Application /> </ErrorBoundary> </div> </Provider> </DndProvider>, document.getElementById('component') );
Example #2
Source File: index.dev.jsx From ashteki with GNU Affero General Public License v3.0 | 6 votes |
render = () => {
const Application = require('./Application').default;
ReactDOM.render(
<Provider store={store}>
<DndProvider backend={TouchBackend} options={{ enableMouseEvents: true }}>
<div className='body'>
<ReduxToastr
timeOut={4000}
newestOnTop
preventDuplicates
position='top-right'
transitionIn='fadeIn'
transitionOut='fadeOut'
/>
<Application />
</div>
</DndProvider>
</Provider>,
document.getElementById('component')
);
}
Example #3
Source File: index.js From h5-Dooring with GNU General Public License v3.0 | 6 votes |
function BasicLayout(props) {
return (
<div className={styles.layout}>
<DndProvider backend={HTML5Backend}>
<Container {...props} />
</DndProvider>
</div>
);
}
Example #4
Source File: FieldControlDialog.js From acsys with MIT License | 6 votes |
export default function FieldControlDialog(props) {
return (
<Dialog
open={props.open}
onClose={props.closeDialog}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
maxWidth={'lg'}
>
<DialogTitle id="alert-dialog-title">{props.title}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description"></DialogContentText>
<div>
<DndProvider backend={props.backend}>{props.component}</DndProvider>
</div>
</DialogContent>
<DialogActions>
<Button onClick={props.action} color="primary" autoFocus>
{props.actionProcess && <CircularProgress size={24} />}
{!props.actionProcess && 'Save'}
</Button>
<Button onClick={props.closeDialog} color="primary" autoFocus>
Cancel
</Button>
</DialogActions>
</Dialog>
);
}
Example #5
Source File: FinancesApp.js From actual with MIT License | 6 votes |
function FinancesAppWithContext(props) {
let app = useMemo(() => <FinancesApp {...props} />, [props]);
return (
<SpreadsheetProvider>
<TitlebarProvider>
<SidebarProvider>
<BudgetMonthCountProvider>
<PayeesProvider>
<AccountsProvider>
<DndProvider backend={Backend}>{app}</DndProvider>
</AccountsProvider>
</PayeesProvider>
</BudgetMonthCountProvider>
</SidebarProvider>
</TitlebarProvider>
</SpreadsheetProvider>
);
}
Example #6
Source File: Root.js From virtualdojo-rooms with GNU General Public License v3.0 | 6 votes |
function Root() {
return (
<DndProvider backend={Backend}>
<ThemeProvider theme={theme}>
<CssBaseline />
<StateProvider>
<App />
</StateProvider>
</ThemeProvider>
</DndProvider>
);
}
Example #7
Source File: sidebar.usage.js From actual with MIT License | 6 votes |
function makeSidebar(selected) {
return withState({ selected }, ({ state: { selected }, setState }) => {
return (
<Router initialEntries={[selected]} initialIndex={0}>
<DndProvider backend={Backend}>
<Sidebar
budgetName="Personal"
accounts={accounts}
getBalanceQuery={account => ({ expr: 10000 })}
getOnBudgetBalance={() => ({ expr: 30000 })}
getOffBudgetBalance={() => ({ expr: 10000 })}
showClosedAccounts={true}
style={{ paddingBottom: 100 }}
/>
</DndProvider>
</Router>
);
});
}
Example #8
Source File: custom-tab-bar-node.jsx From virtuoso-design-system with MIT License | 6 votes |
render() {
const { order } = this.state;
const { children } = this.props;
const tabs = [];
React.Children.forEach(children, c => {
tabs.push(c);
});
const orderTabs = tabs.slice().sort((a, b) => {
const orderA = order.indexOf(a.key);
const orderB = order.indexOf(b.key);
if (orderA !== -1 && orderB !== -1) {
return orderA - orderB;
}
if (orderA !== -1) {
return -1;
}
if (orderB !== -1) {
return 1;
}
const ia = tabs.indexOf(a);
const ib = tabs.indexOf(b);
return ia - ib;
});
return (
<DndProvider backend={HTML5Backend}>
<Tabs renderTabBar={this.renderTabBar} {...this.props}>
{orderTabs}
</Tabs>
</DndProvider>
);
}
Example #9
Source File: viewerbaseDragDropContext.js From vindr-lab-viewer with MIT License | 6 votes |
// See https://github.com/react-dnd/react-dnd/issues/186#issuecomment-335429067
// https://github.com/react-dnd/react-dnd/issues/186#issuecomment-282789420
//
// http://react-dnd.github.io/react-dnd/docs/api/drag-drop-context
export default function viewerbaseDragDropContext(DecoratedClass) {
const backend = isTouchDevice ? TouchBackend : HTML5Backend;
const opts = isTouchDevice ? { enableMouseEvents: true } : {};
return (props) => (
<DndProvider backend={backend} opts={opts}>
<DecoratedClass {...props}/>
</DndProvider>
);
}
Example #10
Source File: index.js From ant-simple-pro with MIT License | 6 votes |
Index = memo(function Index(props) {
return (
<PageLayout>
<p style={{ textAlign: 'center', padding: '10px 0' }}>
实现一个简单的可视化页面生成器
<code>
(简易版本,大致的架子,要想开发完整的,请查看这个项目
<a href="https://github.com/lgf196/ant-simple-draw">
ant-simple-draw
</a>
)
</code>
</p>
<DndProvider backend={HTML5Backend}>
<Container />
</DndProvider>
</PageLayout>
);
})
Example #11
Source File: QueueSection.test.js From qasong with ISC License | 6 votes |
describe("<QueueSection />", () => {
it("renders an empty div if id is falsy", () => {
const wrapper = shallow(<QueueSection queue={[{}]} />);
expect(wrapper.find("div")).toHaveLength(1);
});
it("renders the Youtube component if id is truthy", () => {
const wrapper = shallow(<QueueSection queue={[{}]} />);
expect(wrapper.find(DndProvider)).toHaveLength(1);
});
});
Example #12
Source File: QueueCard.test.js From qasong with ISC License | 6 votes |
describe("<QueueCard />", () => {
it("renders a div", () => {
const wrapper = shallow(
<DndProvider backend={HTML5Backend}>
<QueueCard title={"Hello Test"} />
</DndProvider>
);
expect(wrapper);
});
});
Example #13
Source File: SignDocContainer.js From signdocs with MIT License | 5 votes |
SignDocContainer = () => {
const [_currSignatory, setCurrSignatory] = useState('');
const history = useHistory();
const { docId } = useParams();
const { docErrors, doc, loading } = useFetchDoc({ docId });
const signatories = useSelector(getSignatories(docId));
const currentUser = useSelector(getCurrentUser);
const allCFs = useSelector(getArrayOfContentFieldsByDocId(docId));
const allCFsAreSigned = allCFs.every((cf) => !!cf.type.match(/^FILLED/));
const myCFs = allCFs.filter((cf) => cf.signatoryId === currentUser.id);
const allMyCFsAreSigned = myCFs.every((cf) => !!cf.type.match(/^FILLED/));
const isOwner = doc?.ownerId === currentUser.id;
const breadCrumbsHistory = [
{
to: '/documents',
title: 'Documents',
},
{
to: `/documents/${docId}`,
title: doc.title,
},
{
to: `/documents/${docId}/sign`,
title: 'Sign',
},
];
if (loading || !doc || doc === undefined) return <div>Loading...</div>;
if (docErrors?.status === 404)
return <FourOhFour from={history.location.pathname} errors={docErrors} />;
return (
<div id="sign-doc-container">
<BreadCrumbs history={breadCrumbsHistory} />
<h1>Sign your document</h1>
<div className="scroll-container">
<div className="pdf-drag-container">
<DndProvider backend={HTML5Backend}>
<div className="side-bar">
<Signatories
signatories={signatories}
onChangeSignatory={(sigId) => setCurrSignatory(sigId)}
/>
{allMyCFsAreSigned && (
<CallToFinalize
docId={docId}
allCFsAreSigned={allCFsAreSigned}
isOwner={isOwner}
/>
)}
</div>
{doc && doc.fileUrl && (
<div id="pdf-document-container">
<SignPDF doc={doc} signatories={signatories} />
</div>
)}
</DndProvider>
</div>
</div>
</div>
);
}
Example #14
Source File: Rooms.js From virtualdojo-rooms with GNU General Public License v3.0 | 5 votes |
function Rooms() {
const { currentUser, event, rooms, error } = useContext(store);
const { palette } = useTheme();
const theme = {
container: { background: palette.primary.main },
modal: { background: palette.background.default },
listItem: {
background: palette.grey[200],
padding: "10px",
margin: "5px",
borderRadius: "2%",
},
};
return (
<DndProvider backend={Backend}>
<Grid container>
{currentUser.isMentor && (
<Grid item xs>
<div style={theme.listItem}>
<AddRoom userId={currentUser.userId} eventId={event.eventId} />
</div>
</Grid>
)}
<Grid item xs={12}>
<ErrorMessage errorCode={error}></ErrorMessage>
</Grid>
<Grid
container
item
xs={12}
spacing={3}
style={{ margin: "10px" }}
alignContent={"flex-start"}
alignItems={"flex-start"}
>
{rooms.map((room) => (
<Grid item container xs={4} key={room.roomId} spacing={1}>
<Room
room={room}
eventId={event.eventId}
currentUser={currentUser}
/>
</Grid>
))}
</Grid>
</Grid>
</DndProvider>
);
}
Example #15
Source File: index.js From the-eye-knows-the-garbage with MIT License | 5 votes |
CheckboxList = function CheckboxList(_ref3) {
var list = _ref3.list,
className = _ref3.className,
_ref3$showTitle = _ref3.showTitle,
showTitle = _ref3$showTitle === void 0 ? true : _ref3$showTitle,
listTitle = _ref3.title;
var _Container$useContain2 = Container.useContainer(),
columnsMap = _Container$useContain2.columnsMap,
setColumnsMap = _Container$useContain2.setColumnsMap,
sortKeyColumns = _Container$useContain2.sortKeyColumns,
setSortKeyColumns = _Container$useContain2.setSortKeyColumns;
var show = list && list.length > 0;
if (!show) {
return null;
}
var move = function move(id, targetIndex) {
var newColumns = _toConsumableArray(sortKeyColumns);
var findIndex = newColumns.findIndex(function (columnKey) {
return columnKey === id;
});
var key = newColumns[findIndex];
newColumns.splice(findIndex, 1);
if (targetIndex === 0) {
newColumns.unshift(key);
} else {
newColumns.splice(targetIndex, 0, key);
}
setSortKeyColumns(newColumns);
};
var listDom = list.map(function (_ref4, index) {
var key = _ref4.key,
dataIndex = _ref4.dataIndex,
title = _ref4.title,
fixed = _ref4.fixed,
rest = _objectWithoutProperties(_ref4, ["key", "dataIndex", "title", "fixed"]);
var columnKey = genColumnKey(key, dataIndex, rest.index);
return React.createElement(DnDItem, {
index: index,
id: "".concat(columnKey, "_").concat(rest.index),
key: columnKey,
end: function end(id, targetIndex) {
move(id, targetIndex);
}
}, React.createElement(CheckboxListItem, {
setColumnsMap: setColumnsMap,
columnKey: columnKey || "".concat(index),
columnsMap: columnsMap,
title: title,
fixed: fixed,
className: className
}));
});
return React.createElement(DndProvider, {
backend: Backend
}, showTitle && React.createElement("span", {
className: "".concat(className, "-list-title")
}, listTitle), listDom);
}
Example #16
Source File: drag-sorting.jsx From virtuoso-design-system with MIT License | 5 votes |
DragSortingTable = () => {
const [data, setData] = useState([
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
},
]);
const components = {
body: {
row: DragableBodyRow,
},
};
const moveRow = useCallback(
(dragIndex, hoverIndex) => {
const dragRow = data[dragIndex];
setData(
update(data, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragRow],
],
}),
);
},
[data],
);
return (
<DndProvider backend={HTML5Backend}>
<Table
columns={columns}
dataSource={data}
components={components}
onRow={(record, index) => ({
index,
moveRow,
})}
/>
</DndProvider>
);
}
Example #17
Source File: drag-sorting.jsx From virtuoso-design-system with MIT License | 5 votes |
DragSortingUpload = () => {
const [fileList, setFileList] = useState([
{
uid: '-1',
name: 'image1.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-2',
name: 'image2.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-3',
name: 'image3.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-4',
name: 'image4.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-5',
name: 'image.png',
status: 'error',
},
]);
const moveRow = useCallback(
(dragIndex, hoverIndex) => {
const dragRow = fileList[dragIndex];
setFileList(
update(fileList, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragRow],
],
}),
);
},
[fileList],
);
const onChange = ({ fileList: newFileList }) => {
setFileList(newFileList);
};
return (
<DndProvider backend={HTML5Backend}>
<Upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
fileList={fileList}
onChange={onChange}
itemRender={(originNode, file, currFileList) => (
<DragableUploadListItem
originNode={originNode}
file={file}
fileList={currFileList}
moveRow={moveRow}
/>
)}
>
<Button icon={<UploadOutlined />}>Click to Upload</Button>
</Upload>
</DndProvider>
);
}
Example #18
Source File: PrepareDocContainer.js From signdocs with MIT License | 5 votes |
PrepareDocContainer = () => {
const [currSignatory, setCurrSignatory] = useState('');
const history = useHistory();
const { docId } = useParams();
const { docErrors, doc, loading } = useFetchDoc({ docId });
const signatories = useSelector(getSignatories(docId));
const breadCrumbsHistory = [
{
to: '/documents',
title: 'Documents',
},
{
to: `/documents/${doc.id}`,
title: doc.title,
},
{
to: `/documents/${doc.id}/prepare`,
title: 'Prepare',
},
];
if (loading || !doc || doc === undefined) return <div>Loading...</div>;
if (docErrors?.status === 404)
return <FourOhFour from={history.location.pathname} errors={docErrors} />;
return (
<div id="prep-doc-container">
<BreadCrumbs history={breadCrumbsHistory} />
<h1>Prepare your document for signatures</h1>
<div className="scroll-container">
<div className="pdf-drag-container">
<DndProvider backend={HTML5Backend} displayName="DndProvider">
<div className="side-bar">
<Signatories
currSignatory={currSignatory}
signatories={signatories}
onChangeSignatory={(sigId) => setCurrSignatory(sigId)}
/>
<Fields currSignatory={currSignatory} />
<CallToSignDoc docId={doc.id} status={doc.status} />
</div>
{doc && doc.fileUrl && (
<div id="pdf-document-container">
<PrepPDF doc={doc} />
</div>
)}
</DndProvider>
</div>
</div>
</div>
);
}
Example #19
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
render() {
const { saving = false, fetching = false, bankPath, match } = this.props;
const { contextState } = this.state;
return (
<DndProvider backend={HTML5Backend}>
<DynamicConfigContext.Provider value={contextState}>
<Header
title={intl.get('hpfm.ui.model.page.configure').d('页面配置')}
backPath={bankPath}
>
<ButtonPermission
type="primary"
permissionList={[
{
code: `${match.path}.button.save`,
type: 'button',
meaning: '页面自定义页面配置-保存',
},
]}
onClick={this.handleSaveBtnClick}
loading={saving}
>
{intl.get('hzero.common.button.save').d('保存')}
</ButtonPermission>
<ButtonPermission
permissionList={[
{
code: `${match.path}.button.preview`,
type: 'button',
meaning: '页面自定义页面配置-预览',
},
]}
onClick={this.handleGotoPreview}
>
{intl.get('hzero.common.button.preview').d('预览')}
</ButtonPermission>
</Header>
<Content style={{ padding: 0, display: 'flex', flexDirection: 'column' }}>
<div className={styles['dynamic-config']}>
<div className={styles['pick-box-panel']}>
<Spin spinning={saving || fetching}>{this.renderPickBoxPanel()}</Spin>
</div>
<div className={styles['designer-panel']}>
<Spin spinning={saving || fetching}>{this.renderDesignerPanel()}</Spin>
</div>
<div className={styles['prop-panel']}>
<Spin spinning={saving || fetching}>{this.renderPropPanel()}</Spin>
</div>
</div>
</Content>
</DynamicConfigContext.Provider>
</DndProvider>
);
}
Example #20
Source File: LicenseField.js From react-invenio-deposit with MIT License | 5 votes |
render() {
const {
label,
labelIcon,
fieldPath,
uiFieldPath,
form: { values, errors },
move: formikArrayMove,
push: formikArrayPush,
remove: formikArrayRemove,
replace: formikArrayReplace,
required,
} = this.props;
const uiRights = getIn(values, uiFieldPath, []);
return (
<DndProvider backend={HTML5Backend}>
<Form.Field required={required}>
<FieldLabel
htmlFor={fieldPath}
icon={labelIcon}
label={label}
/>
<List>
{getIn(values, fieldPath, []).map((value, index) => {
const license = new VisibleLicense(uiRights, value, index);
return (
<LicenseFieldItem
key={license.key}
license={license}
moveLicense={formikArrayMove}
replaceLicense={formikArrayReplace}
removeLicense={formikArrayRemove}
searchConfig={this.props.searchConfig}
serializeLicenses={this.props.serializeLicenses}
/>
);
})}
<LicenseModal
searchConfig={this.props.searchConfig}
trigger={
<Button type="button" key="standard" icon labelPosition="left">
<Icon name="add" />
{i18next.t('Add standard')}
</Button>
}
onLicenseChange={(selectedLicense) => {
formikArrayPush(selectedLicense);
}}
mode="standard"
action="add"
serializeLicenses={this.props.serializeLicenses}
/>
<LicenseModal
searchConfig={this.props.searchConfig}
trigger={
<Button type="button" key="custom" icon labelPosition="left">
<Icon name="add" />
{i18next.t('Add custom')}
</Button>
}
onLicenseChange={(selectedLicense) => {
formikArrayPush(selectedLicense);
}}
mode="custom"
action="add"
/>
</List>
</Form.Field>
</DndProvider>
);
}
Example #21
Source File: Game.js From cards-of-personality-frontend with GNU Affero General Public License v3.0 | 4 votes |
render() {
return (
<>
<div className={`Game ${this.state.isTourOpen ? 'is-tourActive' : ''}`}>
<GlobalStyle />
{this.state.showNamePopup && (
<NamePopup
handleSubmit={this.handleSubmit}
inviteInputRef={this.inviteInputRef}
roomId={this.roomId}
copyLink={this.copyLink}
updateMyName={this.updateMyName}
myName={this.state.myName}
nameError={this.state.nameError}
reactGA={this.props.reactGA}
/>
)}
<DndProvider
backend={TouchBackend}
options={{ enableMouseEvents: true }}
>
<Table>
<CardsWrap>
<Piles>
<CardWrap isPickUpPile className="Game-bigBlackCard">
<BlackCardDrop
addBlackCardBackToPile={this.addBlackCardBackToPile}
>
{this.state.blackCards
.slice(
Math.max(
this.state.blackCards.length - (MAX_PLAYERS + 1),
0
)
)
.map((text, index) => (
<BlackCard
setUserIsDragging={this.setUserIsDragging}
key={text}
id={index}
text={text}
socket={this.socket}
isMyCardsOpen={this.state.isMyCardsOpen}
isSubmittedTableOpen={this.state.isSubmittedTableOpen}
/>
))}
</BlackCardDrop>
</CardWrap>
<CardWrap isPickUpPile innerRef={this.whiteCardRef} className="WhiteCardPile">
{this.state.whiteCards
.slice(
Math.max(
this.state.whiteCards.length - (MAX_PLAYERS + 1),
0
)
)
.map((text, index) => (
<PickUpPile
setUserIsDragging={this.setUserIsDragging}
key={text}
id={index}
text={text}
socket={this.socket}
isMyCardsOpen={this.state.isMyCardsOpen}
isSubmittedTableOpen={this.state.isSubmittedTableOpen}
/>
))}
{!this.state.showNamePopup &&
this.state.myCards.length > 0 &&
!this.state.animationOver && (
<AnimatedDraw
cardDimensions={this.state.cardDimensions}
myCards={this.state.myCards}
onAnimationEnd={this.setAnimationOver}
>
<DraggableCard
bgColor="#fff"
isBroadcastingDrag={false}
isFlipBroadcasted={false}
color="#000"
type="whiteCard"
setUserIsDragging={this.setUserIsDragging}
isFlippable={false}
/>
</AnimatedDraw>
)}
</CardWrap>
</Piles>
<PlayerDecks className="Table-playerDecks">
{this.state.players &&
this.state.players.map(({ name }, index) => (
<PlayerDrop
className={index === 0 ? 'PlayerOneSlot' : index === 1 ? 'PlayerTwoSlot' : ''}
setUserIsDragging={this.setUserIsDragging}
userIsDragging={this.state.userIsDragging}
key={index}
index={index}
socket={this.socket}
addCardToPlayer={this.addCardToPlayer}
players={this.state.players}
myName={this.state.myName}
winningPlayerIndex={this.state.winningPlayerIndex}
isMyCardsOpen={this.state.isMyCardsOpen}
isSubmittedTableOpen={this.state.isSubmittedTableOpen}
/>
))}
{this.getBlankPlayerCards(this.state.players).map(
(num, index) => (
<BlankPlayerCard
className={this.state.players && this.state.players.length === 1 && index === 0 ? 'PlayerTwoSlot' : ''}
key={num}
index={index}
count={this.state.players.length}
/>
)
)}
</PlayerDecks>
</CardsWrap>
<MyCardsDropZone
setUserIsDragging={this.setUserIsDragging}
blackCards={this.state.blackCards}
userIsDragging={this.state.userIsDragging}
socket={this.socket}
discardACard={this.discardACard}
addCardToMyCards={this.addCardToMyCards}
submitACard={this.submitACard}
submittedCards={this.state.submittedCards}
myCards={this.state.myCards}
myName={this.state.myName}
setChatOpen={this.setChatOpen}
unreadCount={this.state.unreadCount}
setMyCardsOpen={this.setMyCardsOpen}
setSubmittedTableOpen={this.setSubmittedTableOpen}
isMyCardsOpen={this.state.isMyCardsOpen}
isSubmittedTableOpen={this.state.isSubmittedTableOpen}
/>
</Table>
</DndProvider>
<ToastContainer
limit={1}
hideProgressBar
closeOnClick
transition={Slide}
pauseOnFocusLoss={false}
/>
<ChatBox
chatOpen={this.state.chatOpen}
setChatOpen={this.setChatOpen}
socket={this.socket}
myName={this.state.myName}
setUnreadCount={this.setUnreadCount}
reactGA={this.props.reactGA}
roomId={this.roomId}
/>
</div>
<Tour
steps={this.getSteps()}
closeWithMask={false}
isOpen={this.state.isTourOpen}
onRequestClose={this.setTourClosed}
highlightedMaskClassName="is-highlighted"
maskClassName="MaskOverlay"
rounded={8}
accentColor="#2cce9f"
lastStepNextButton={<DoneButton type="button">Got it!</DoneButton>}
/>
</>
);
}
Example #22
Source File: Table.js From os-league-tools with MIT License | 4 votes |
export default function Table({
columns,
data,
filters = [],
filterState,
globalFilter,
defaultColumn,
initialState,
ExpandedRow,
customFilterProps = {},
enableResizeColumns = true,
}) {
const [records, setRecords] = useState(data);
useEffect(() => {
if (filters.length) {
setRecords(data.filter(record => filters.every(filter => filter(record, filterState, customFilterProps))));
} else {
setRecords(data);
}
}, [filterState, data, customFilterProps]);
const table = useTable(
{
initialState: { pageSize: 25, ...initialState },
columns,
data: records,
defaultColumn,
globalFilter,
manualFilters: true,
autoResetGlobalFilter: false,
autoResetSortBy: false,
autoResetPage: false,
autoResetExpanded: false,
getRowId: useCallback(row => row.id, []),
},
useFlexLayout,
useResizeColumns,
useGlobalFilter,
useSortBy,
useExpanded,
usePagination
);
useEffect(() => {
// Reset to first page when filters are changed
table.gotoPage(0);
}, [filterState]);
const moveRow = (dragIndex, hoverIndex) => {
const dragRecord = records[dragIndex];
setRecords(
update(records, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragRecord],
],
})
);
};
return (
<>
<div className='flex flex-row flex-wrap justify-between pb-3 px-3 items-end'>
<span className='italic text-sm'>Showing: {table.page.length} rows</span>
<SearchBox globalFilter={table.state.globalFilter} setGlobalFilter={table.setGlobalFilter} />
</div>
<div className='overflow-auto px-3'>
<DndProvider backend={HTML5Backend}>
<div {...table.getTableProps()} style={{ minWidth: 'min-content' }}>
<div>
{table.headerGroups.map(headerGroup => (
<div
{...headerGroup.getHeaderGroupProps()}
className='heading-accent-md leading-loose border-b border-accent w-full'
>
{headerGroup.headers.map(column => (
<div
{...column.getHeaderProps(column.getSortByToggleProps())}
className='relative font-bold text-center'
>
{column.render('Header')}
{column.isSorted && (
<span className='icon-base absolute'>
{column.isSortedDesc ? 'arrow_drop_down' : 'arrow_drop_up'}
</span>
)}
{enableResizeColumns && (
<span {...column.getResizerProps()} className='resizer icon-lg'>
drag_handle
</span>
)}
</div>
))}
</div>
))}
</div>
<div {...table.getTableBodyProps()}>
{table.page.map(
(row, index) =>
table.prepareRow(row) || (
<Row
index={index}
row={row}
moveRow={moveRow}
isReorderEnabled={filterState?.reorderEnabled}
ExpandedRow={ExpandedRow}
{...row.getRowProps()}
/>
)
)}
</div>
<div className='flex flex-col justify-center text-center'>
<div>
<PageButton
onClick={() => table.gotoPage(0)}
disabled={!table.canPreviousPage}
text='<<'
/>
<PageButton
onClick={() => table.previousPage()}
disabled={!table.canPreviousPage}
text='<'
/>
<span className='text-xs'>
{table.state.pageIndex + 1} of {table.pageOptions.length}
</span>
<PageButton onClick={() => table.nextPage()} disabled={!table.canNextPage} text='>' />
<PageButton
onClick={() => table.gotoPage(table.pageCount - 1)}
disabled={!table.canNextPage}
text='>>'
/>
</div>
<span className='text-xs'>
Show:
<select
className='input-primary text-xs p-0 ml-1 text-center'
value={table.state.pageSize}
onChange={e => {
table.setPageSize(Number(e.target.value));
}}
>
{[25, 50, 100, 200].map(pageSize => (
<option key={pageSize} value={pageSize}>
{pageSize}
</option>
))}
</select>
</span>
</div>
</div>
</DndProvider>
</div>
</>
);
}
Example #23
Source File: MetaColumnsTable.js From hzero-front with Apache License 2.0 | 4 votes |
/**
* render
* @returns React.element
*/
render() {
const { loading, dataSource = [], metaColumnsRowSelection, type, sortType } = this.props;
const columns = [
{
title: intl.get('hrpt.common.view.serialNumber').d('序号'),
dataIndex: 'ordinal',
width: 60,
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.name').d('列名'),
dataIndex: 'name',
width: 120,
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.text').d('标题'),
dataIndex: 'text',
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.type').d('列类型'),
dataIndex: 'type',
width: 100,
render: (val) => valueMapMeaning(type, val),
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.dataType').d('数据类型'),
dataIndex: 'dataType',
width: 100,
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.format').d('格式掩码'),
dataIndex: 'format',
width: 100,
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.width').d('宽度'),
dataIndex: 'width',
width: 60,
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.decimals').d('精度'),
dataIndex: 'decimals',
width: 60,
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.sortType').d('排序类型'),
dataIndex: 'sortType',
width: 100,
render: (val) => valueMapMeaning(sortType, val),
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.configure').d('配置'),
children: [
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.percent').d('百分比'),
dataIndex: 'percent',
width: 80,
render: yesOrNoRender,
},
{
title: intl.get('hrpt.reportDefinition.model.reportDefinition.hidden').d('隐藏'),
dataIndex: 'hidden',
width: 80,
render: yesOrNoRender,
},
],
},
{
title: intl.get('hzero.common.button.action').d('操作'),
dataIndex: 'option',
width: 60,
fixed: 'right',
render: (val, record) => {
const operators = [];
operators.push({
key: 'edit',
ele: (
<a onClick={() => this.editOption(record)}>
{intl.get('hzero.common.button.edit').d('编辑')}
</a>
),
len: 2,
title: intl.get('hzero.common.button.edit').d('编辑'),
});
return operatorRender(operators);
},
},
];
return (
<DndProvider backend={HTML5Backend}>
<Table
bordered
rowKey="ordinal"
rowSelection={metaColumnsRowSelection}
loading={loading}
columns={columns}
scroll={{ x: tableScrollWidth(columns) }}
dataSource={dataSource}
components={this.components}
onRow={(record, index) => ({
index,
moveRow: this.moveRow,
})}
pagination={false}
/>
</DndProvider>
);
}
Example #24
Source File: QueueSection.js From qasong with ISC License | 4 votes |
function QueueSection({ nowPlaying, setNowPlaying, queue, setQueue }) {
const [displayMode, setDisplayMode] = useState("list");
const [displaySaved, setDisplaySaved] = useState(false);
const [confirmDialog, setConfirmDialog] = useState({
isOpen: false,
title: "",
subTitle: "",
});
const handleClickQueueItem = (qid) => {
setNowPlaying(queue.find((item) => item.qid === qid));
};
const handleClickSave = () => {
setDisplaySaved(true);
setTimeout(() => {
setDisplaySaved(false);
}, 3000);
};
const moveCard = useCallback(
(dragIndex, hoverIndex) => {
const dragCard = queue[dragIndex];
setQueue(
update(queue, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard],
],
})
);
},
[queue]
);
if (!queue.length > 0) {
return (
<div style={{ maxWidth: "800px", margin: "0 auto 200px auto" }}>
<Typography align="center">
<i> No queue exists. </i>
Click
<IconButton disabled>
<QueueIcon />
</IconButton>
icon to add song to your queue.
</Typography>
<Box m={3}>
<Grid container alignItems="center">
<Grid item>
<Typography variant="h5">
<Skeleton variant="text" width={100} height={50} />
</Typography>
</Grid>
<Grid item>
<PlayQueueButton disabled />
</Grid>
<Grid item>
<ShuffleButton disabled />
</Grid>
<Grid item>
<DisplayModeButton disabled />
</Grid>
<Grid item>
<SaveQueueButton disabled />
</Grid>
<Grid item>
<ClearButton disabled />
</Grid>
</Grid>
</Box>
{[1, 2, 3].map((index) => {
return (
<Grid container key={index}>
<Grid item xs={1}>
<IconButton disabled>
<PlayArrowIcon />
</IconButton>
</Grid>
<Grid item xs={9}>
<Typography>
<Skeleton variant="text" width={300} height={50} />
</Typography>
</Grid>
<Grid item xs={1}>
<IconButton disabled>
<DragHandleIcon />
</IconButton>
</Grid>
<Grid item xs={1}>
<Typography>
<Skeleton variant="text" width={100} height={50} />
</Typography>
</Grid>
</Grid>
);
})}
</div>
);
}
return (
<div style={{ maxWidth: "800px", margin: "0 auto 200px auto" }}>
<Box m={3}>
<Grid container alignItems="center" spacing={1}>
<Grid item>
<Typography variant="h5">
{queue.length > 0 && `${queue.length} songs`}
</Typography>
</Grid>
<Grid item>
<PlayQueueButton {...{ setNowPlaying, queue }} />
</Grid>
<Grid item>
<ShuffleButton {...{ queue, setQueue, setNowPlaying }} />
</Grid>
<Grid item>
<DisplayModeButton {...{ displayMode, setDisplayMode }} />
</Grid>
<Grid item onClick={handleClickSave}>
<SaveQueueButton {...{ queue }} />
</Grid>
<Grid
item
onClick={() => {
setConfirmDialog({
isOpen: true,
title: "Are you sure you want to clear the queue?",
subTitle: "You can't undo this operation.",
});
}}
>
<ClearButton {...{ setQueue }} />
</Grid>
{displaySaved ? (
<Grid item md={5} xs={12} spacing={3}>
<Alert severity="success" color="warning" variant="outlined">
<i>Queue Has Been Successfully Saved</i>
</Alert>
</Grid>
) : null}
</Grid>
<ConfirmClearDialog
setQueue={setQueue}
confirmDialog={confirmDialog}
setConfirmDialog={setConfirmDialog}
/>
</Box>
<DndProvider backend={isMobile ? TouchBackend : HTML5Backend}>
{displayMode === "list" ? (
<Grid container direction="column">
{queue.map((item, index) => {
return (
<QueueRow
{...item}
key={item.qid}
queue={queue}
setQueue={setQueue}
index={index}
nowPlaying={nowPlaying}
onClickMusicRow={handleClickQueueItem}
moveCard={moveCard}
/>
);
})}
</Grid>
) : (
queue.map((item, index) => (
<QueueCard
{...item}
key={item.qid}
queue={queue}
setQueue={setQueue}
index={index}
nowPlaying={nowPlaying}
onClickImage={handleClickQueueItem}
moveCard={moveCard}
/>
))
)}
</DndProvider>
</div>
);
}
Example #25
Source File: FundingField.js From react-invenio-deposit with MIT License | 4 votes |
function FundingFieldForm(props) {
const {
label,
labelIcon,
fieldPath,
form: { values },
move: formikArrayMove,
push: formikArrayPush,
remove: formikArrayRemove,
replace: formikArrayReplace,
required,
} = props;
const deserializeAward = props.deserializeAward
? props.deserializeAward
: (award) => ({
title: award?.title_l10n,
number: award.number,
funder: award.funder ?? '',
id: award.id,
...(award.identifiers && { identifiers: award.identifiers }),
...(award.acronym && { acronym: award.acronym }),
});
const deserializeFunder = props.deserializeFunder
? props.deserializeFunder
: (funder) => ({
id: funder.id,
name: funder.name,
...(funder.pid && { pid: funder.pid }),
...(funder.country && { country: funder.country }),
...(funder.identifiers && { identifiers: funder.identifiers }),
});
const computeFundingContents = props.computeFundingContents
? props.computeFundingContents
: (funding) => {
let headerContent,
descriptionContent = '';
let awardOrFunder = 'award';
if (funding.award) {
headerContent = funding.award.title;
}
if (funding.funder) {
const funderName =
funding?.funder?.name ??
funding.funder?.title ??
funding?.funder?.id ??
'';
descriptionContent = funderName;
if (!headerContent) {
awardOrFunder = 'funder';
headerContent = funderName;
descriptionContent = '';
}
}
return { headerContent, descriptionContent, awardOrFunder };
};
return (
<DndProvider backend={HTML5Backend}>
<Form.Field required={required}>
<FieldLabel
htmlFor={fieldPath}
icon={labelIcon}
label={label}
></FieldLabel>
<List>
{getIn(values, fieldPath, []).map((value, index, array) => {
const arrayPath = fieldPath;
const indexPath = index;
const key = `${arrayPath}.${indexPath}`;
// if award does not exist or has no id, it's a custom one
const awardType = value?.award?.id ? 'standard' : 'custom';
return (
<FundingFieldItem
key={key}
{...{
index,
compKey: key,
fundingItem: value,
awardType,
moveFunding: formikArrayMove,
replaceFunding: formikArrayReplace,
removeFunding: formikArrayRemove,
searchConfig: props.searchConfig,
computeFundingContents: computeFundingContents,
deserializeAward: deserializeAward,
deserializeFunder: deserializeFunder,
}}
/>
);
})}
<FundingModal
searchConfig={props.searchConfig}
trigger={
<Button type="button" key="custom" icon labelPosition="left" className="mb-5">
<Icon name="add" />
{i18next.t('Add award')}
</Button>
}
onAwardChange={(selectedFunding) => {
formikArrayPush(selectedFunding);
}}
mode="standard"
action="add"
deserializeAward={deserializeAward}
deserializeFunder={deserializeFunder}
computeFundingContents={computeFundingContents}
/>
<FundingModal
searchConfig={props.searchConfig}
trigger={
<Button type="button" key="custom" icon labelPosition="left">
<Icon name="add" />
{i18next.t('Add custom')}
</Button>
}
onAwardChange={(selectedFunding) => {
formikArrayPush(selectedFunding);
}}
mode="custom"
action="add"
deserializeAward={deserializeAward}
deserializeFunder={deserializeFunder}
computeFundingContents={computeFundingContents}
/>
</List>
</Form.Field>
</DndProvider>
);
}
Example #26
Source File: CreatibutorsField.js From react-invenio-deposit with MIT License | 4 votes |
render() {
const {
form: { values, errors, initialErrors, initialValues },
remove: formikArrayRemove,
replace: formikArrayReplace,
move: formikArrayMove,
name: fieldPath,
label,
labelIcon,
roleOptions,
schema,
modal,
autocompleteNames,
addButtonLabel,
} = this.props;
const creatibutorsList = getIn(values, fieldPath, []);
const formikInitialValues = getIn(initialValues, fieldPath, []);
const error = getIn(errors, fieldPath, null);
const initialError = getIn(initialErrors, fieldPath, null);
const creatibutorsError =
error || (creatibutorsList === formikInitialValues && initialError);
return (
<DndProvider backend={HTML5Backend}>
<Form.Field
required={schema === 'creators'}
className={creatibutorsError ? 'error' : ''}
>
<FieldLabel htmlFor={fieldPath} icon={labelIcon} label={label} />
<List>
{creatibutorsList.map((value, index, array) => {
const key = `${fieldPath}.${index}`;
const identifiersError =
creatibutorsError &&
creatibutorsError[index]?.person_or_org?.identifiers;
const displayName = creatibutorNameDisplay(value);
return (
<CreatibutorsFieldItem
key={key}
identifiersError={identifiersError}
{...{
displayName,
index,
roleOptions,
schema,
compKey: key,
initialCreatibutor: value,
removeCreatibutor: formikArrayRemove,
replaceCreatibutor: formikArrayReplace,
moveCreatibutor: formikArrayMove,
addLabel: modal.addLabel,
editLabel: modal.editLabel,
autocompleteNames: autocompleteNames,
}}
/>
);
})}
<CreatibutorsModal
onCreatibutorChange={this.handleOnContributorChange}
action="add"
addLabel={modal.addLabel}
editLabel={modal.editLabel}
roleOptions={sortOptions(roleOptions)}
schema={schema}
autocompleteNames={autocompleteNames}
trigger={
<Button type="button" icon labelPosition="left">
<Icon name="add" />
{addButtonLabel}
</Button>
}
/>
{creatibutorsError && typeof creatibutorsError == 'string' && (
<Label pointing="left" prompt>
{creatibutorsError}
</Label>
)}
</List>
</Form.Field>
</DndProvider>
);
}
Example #27
Source File: settings-view.js From Quest with MIT License | 4 votes |
export function SettingsView({ store }) {
const configuration = useStateLink(store);
const [isClosed, setIsClosed] = React.useState(false);
const [isReordering, setIsReordering] = React.useState(false);
const [items, setItems] = React.useState([]);
useShortcut("close", () => setIsClosed(true));
if (isClosed) {
return <Redirect to="/" />;
}
function onReorderingClicked() {
if (isReordering) {
setIsReordering(false);
reorderModules(configuration, items);
} else {
setItems(
configuration.nested.modules.nested.map((module, id) => ({
id,
itemId: module.nested.id.get(),
text: module.nested.name.get(),
}))
);
setIsReordering(true);
}
}
return (
<div>
<div className={styles.settingsHeader}>
<div style={{ flexGrow: 1 }}>
<H1>Settings</H1>
<p>{"Credentials and keys are stored encrypted."}</p>
</div>
<div>
<ButtonLink minimal rightIcon="cross" to="/">
Close
</ButtonLink>
</div>
</div>
<div className={styles.wrapper}>
<div className={styles.settingsBody}>
<H4>Modules</H4>
<div style={{ display: "flex" }}>
<Select
disabled={isReordering}
itemPredicate={(query, module) =>
module.name.toLowerCase().indexOf(query.toLowerCase()) >= 0
}
items={availableModules}
itemRenderer={moduleItemRenderer}
onItemSelect={(module) => {
configuration.nested.modules.set((modules) =>
modules.concat(createDefaultValuesForModule(module.type))
);
}}
>
<Button disabled={isReordering} icon="plus">
Add search module
</Button>
</Select>
<div style={{ flexGrow: "1" }} />
<Button
disabled={configuration.nested.modules.get().length < 2}
minimal={!isReordering}
intent={isReordering ? "primary" : "none"}
icon={isReordering ? "small-tick" : "swap-vertical"}
onClick={onReorderingClicked}
>
{isReordering ? "Done" : "Reorder"}
</Button>
</div>
{isReordering && (
<DndProvider backend={Backend}>
<SortableList initialItems={items} onChange={setItems} />
</DndProvider>
)}
{!isReordering &&
configuration.nested.modules.nested.map((moduleState) => (
<ErrorBoundary key={moduleState.nested.id.get()}>
<SettingCard
moduleState={moduleState}
onDelete={(id) =>
configuration.nested.modules.set((modules) =>
modules.filter((module) => module.id !== id)
)
}
/>
</ErrorBoundary>
))}
<H4>Appearance</H4>
<UIPreferences store={configuration.nested.appearance} />
<H4>Shortcuts</H4>
<p>
Use <kbd>Tab</kbd> and the arrow keys to navigate between the search results.
</p>
<Card>
<HTMLTable style={{ border: "none", width: "100%" }}>
<tbody>
{Object.entries(configSchema.properties.shortcuts.properties).map(
([id, action]) => (
<tr key={id}>
<td style={{ borderLeft: "none", boxShadow: "none" }}>
{action.description}
</td>
<td style={{ borderLeft: "none", boxShadow: "none", textAlign: "right" }}>
<kbd className={styles.shortcut}>
{Shortcut.shortcut2symbols(action.default)}
</kbd>
</td>
</tr>
)
)}
</tbody>
</HTMLTable>
</Card>
<div style={{ display: "flex" }}>
<ButtonLink icon="cog" minimal to="/json-config">
Edit configuration
</ButtonLink>
<div style={{ flexGrow: 1 }} />
<ExternalLink href="https://github.com/hverlin/Quest" style={{ alignSelf: "center" }}>
Learn more about Quest ({version})
</ExternalLink>
</div>
</div>
</div>
</div>
);
}
Example #28
Source File: index.usage.js From actual with MIT License | 4 votes |
render() {
let { maxMonths } = this.props;
let {
startMonth,
categoryGroups,
collapsed,
newCategoryForGroup
} = this.state;
let rolloverComponents = {
SummaryComponent: rollover.BudgetSummary,
ExpenseCategoryComponent: rollover.ExpenseCategoryMonth,
ExpenseGroupComponent: rollover.ExpenseGroupMonth,
IncomeCategoryComponent: rollover.IncomeCategoryMonth,
IncomeGroupComponent: rollover.IncomeGroupMonth,
BudgetTotalsComponent: rollover.BudgetTotalsMonth,
IncomeHeaderComponent: rollover.IncomeHeaderMonth
};
return (
<DndProvider backend={Backend}>
<RolloverContext
categoryGroups={categoryGroups}
summaryCollapsed={false}
>
<View
style={{
height: 800,
backgroundColor: colors.n10,
overflow: 'hidden'
}}
>
<DynamicBudgetTable
prewarmStartMonth={startMonth}
startMonth={startMonth}
monthBounds={{
start: monthUtils.subMonths('2017-01', 3),
end: '2017-10'
}}
maxMonths={maxMonths}
onMonthSelect={month => {
this.setState({ startMonth: month });
}}
categoryGroups={categoryGroups}
collapsed={collapsed}
setCollapsed={collapsed => {
this.setState({ collapsed });
}}
newCategoryForGroup={newCategoryForGroup}
dataComponents={rolloverComponents}
// onAddCategory={groupId => {}}
onSavePrefs={() => {}}
onShowNewCategory={groupId => {
this.setState({
newCategoryForGroup: groupId,
collapsed: collapsed.filter(c => c !== groupId)
});
}}
onHideNewCategory={() => {
this.setState({ newCategoryForGroup: null });
}}
onSaveCategory={cat => {
if (cat.id === 'new') {
cat.id = Math.random().toString();
this.setState({
categoryGroups: categoryGroups.map(group => {
if (group.id === cat.cat_group) {
return {
...group,
categories: group.categories.concat([cat])
};
}
return group;
}),
newCategoryForGroup: null
});
} else {
this.setState({
categoryGroups: categoryGroups.map(group => {
if (group.id === cat.cat_group) {
return {
...group,
categories: group.categories.map(c =>
c.id === cat.id ? cat : c
)
};
}
return group;
})
});
}
}}
onSaveGroup={group => {
this.setState({
categoryGroups: categoryGroups.map(g =>
g.id === group.id ? group : g
)
});
}}
onDeleteCategory={id => {
this.setState({
categoryGroups: categoryGroups.map(group => {
return {
...group,
categories: group.categories.filter(c => c.id !== id)
};
})
});
}}
onDeleteGroup={id =>
this.setState({
categoryGroups: categoryGroups.filter(g => g.id !== id)
})
}
onReorderCategory={sortInfo => {}}
onReorderGroup={sortInfo => {}}
/>
</View>
</RolloverContext>
</DndProvider>
);
}
Example #29
Source File: Inventory.js From CyberStateRP with MIT License | 4 votes |
Inventory = props => {
const itemMenus = popupSettings()
const updateDraggedItem = item => {
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
draggedItem: item,
}
})
}
const updateInventory = inventory => {
// сохранение clientStorage.inventoryItems
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
personInventory: inventory,
}
})
}
const updateVehicleInventory = inventory => {
// сохранение clientStorage.inventoryItems
//console.log(`inventory: ${JSON.stringify(inventory)}`)
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
vehicleInventory: inventory,
}
})
}
const updateHoverIndexes = indx => {
// сохранение clientStorage.inventoryItems
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
hoverIndexes: indx,
}
})
}
const updateVehicleInventorySettings = settings => {
// сохранение clientStorage.inventoryItems
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
vehicleInventorySettings: settings,
}
})
}
const updateItemPos = (sqlId, parentId, index, inVehicle) => {
alt.emit(
'events.emitServer',
'item.updatePos',
JSON.stringify([sqlId, parentId, index, inVehicle])
)
}
const mergeItems = (sqlId, targetSqlId) => {
alt.emit(
'events.emitServer',
'items.merge',
JSON.stringify([sqlId, targetSqlId])
)
}
const updatePersonItems = personItems => {
// сохранение clientStorage.inventoryItems
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
personItems,
}
})
}
const findItemBySqlId = sqlId => {
const aItem = find(inv.personInventory, { sqlId }) // eslint-disable-line
if (aItem) return aItem
for (let i = 0; i < inv.personInventory.length; i++) { // eslint-disable-line
const bItem = find(inv.personInventory[i].items, { sqlId }) // eslint-disable-line
if (bItem) return bItem
}
}
const findVehItemBySqlId = (vehInv, sqlId) => {
const aItem = find(
vehInv, // eslint-disable-line
item => item.sqlId === sqlId
)
if (aItem) return aItem
return null
}
const showModal = (modalVisible, item, bounds) => {
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
modal: {
active: modalVisible,
top: bounds.top - 25,
left: bounds.right + 5,
desc: getItemName(item.sqlId), // eslint-disable-line no-use-before-define
},
}
})
}
const hideItemMenu = () => {
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
itemMenu: {
active: false,
},
}
})
}
const hideModal = () => {
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
modal: {
active: false,
},
}
})
}
const hideModals = () => {
setInv(prevState => { // eslint-disable-line no-use-before-define
return {
...prevState,
modal: {
active: false,
},
itemMenu: {
active: false,
},
}
})
}
const showItemMenu = (modalVisible, item, bounds) => {
setInv(prevState => { // eslint-disable-line no-use-before-define
//console.log(bounds)
return {
...prevState,
itemMenu: {
active: modalVisible,
top: bounds.bottom + 5,
left: bounds.right + 5,
sqlId: item.sqlId,
menu: itemMenus[item.itemId],
},
}
})
}
const inventoryData = {
personInventory: [],
vehicleInventory: [],
draggedItem: {},
forbiddenItems: {
7: [3, 7, 8, 9, 13],
8: [3, 7, 8, 9, 13],
13: [13],
},
modal: {
active: false,
top: 0,
left: 0,
desc: '',
},
itemMenu: {
active: false,
top: 0,
left: 0,
desc: '',
},
vehicleInventorySettings: {
width: 5,
height: 10,
sqlId: -1,
name: '',
},
personItems: {
money: 0,
bankMoney: 0,
health: 0,
satiety: 0,
thirst: 0,
armor: 0,
},
weaponAmmo: {
20: 37, // 9mm
21: 38, // 12mm
22: 40, // 5.56mm
23: 39, // 7.62mm
44: 37,
45: 37,
46: 37,
47: 37,
48: 37,
49: 38,
50: 39,
51: 40,
52: 39,
53: 39,
100: 39,
},
drugsIds: [55, 56, 57, 58],
hoverIndexes: {},
updateDraggedItem,
updateInventory,
updateVehicleInventory,
updateHoverIndexes,
updatePersonItems,
updateItemPos,
updateVehicleInventorySettings,
showModal,
showItemMenu,
hideItemMenu,
hideModal,
findVehItemBySqlId,
findItemBySqlId,
mergeItems,
}
// set extra fields
const [inv, setInv] = useState(inventoryData)
const [active, setActive] = useState(false)
// settings defaults
useEffect(() => {
initEvents()
}, [])
// findItem
const findArrayItemByItemId = itemIds => {
const array = {}
for (let i = 0; i < itemIds.length; i++) {
find(inv.personInventory, item => item.itemId === itemIds[i])
}
return array
}
const updateItemInInv = (sqlId, params, inventory) => {
const immInv = inventory
const item = find(immInv, { sqlId })
if (item) {
const newItem = { ...item, params }
remove(
immInv,
aItem => aItem.sqlId === sqlId
)
immInv.push(newItem)
} else {
for (let i = 0; i < immInv.length; i++) {
if (Object.prototype.hasOwnProperty.call(immInv[i], 'items')) {
const parentItem = immInv[i]
const finalItem = find(parentItem.items, { sqlId })
if (finalItem) {
const newItem = { ...finalItem, params }
remove(
parentItem.items,
aItem => aItem.sqlId === sqlId
)
parentItem.items.push(newItem)
const parentIndex = findIndex(
immInv,
singleItem => singleItem.sqlId === parentItem.sqlId
)
immInv.splice(parentIndex, 1, parentItem)
}
}
}
}
return immInv
}
const invItemNames = {
3: item => { // armour
const info = window.clientStorage.inventoryItems[item.itemId - 1]
let { name } = info
if (item.params.faction) name += ` ${getNameByFactionId(item.params.faction)}`
return `${name} [${item.params.armour}%]`
},
5: item => { // VISA
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} ${item.params.count}$`
},
6: item => { // hat
const info = window.clientStorage.inventoryItems[item.itemId - 1]
if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
return info.name
},
7: item => { // top
const info = window.clientStorage.inventoryItems[item.itemId - 1]
if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
return info.name
},
8: item => { // legs
const info = window.clientStorage.inventoryItems[item.itemId - 1]
if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
return info.name
},
9: item => { // feets
const info = window.clientStorage.inventoryItems[item.itemId - 1]
if (item.params.faction) return `${info.name} ${getNameByFactionId(item.params.faction)}`
return info.name
},
24: item => { // аптечка
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count} ед.]`
},
25: item => { // пластырь
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count} ед.]`
},
29: item => { // удостоверение PD
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} №${item.params.owner}`
},
34: item => { // пачка сигарет
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count} шт.]`
},
36: item => { // канистра
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count}/${item.params.maxCount} л.]`
},
37: item => { // патроны
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.ammo} шт.]`
},
38: item => { // патроны
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.ammo} шт.]`
},
39: item => { // патроны
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.ammo} шт.]`
},
40: item => { // патроны
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.ammo} шт.]`
},
54: item => { // ключи авто
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} ${item.params.model}`
},
55: item => { // нарко
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count} г.]`
},
56: item => { // нарко
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count} г.]`
},
57: item => { // нарко
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count} г.]`
},
58: item => { // нарко
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} [${item.params.count} г.]`
},
59: item => { // ключи дома
const info = window.clientStorage.inventoryItems[item.itemId - 1]
return `${info.name} №${item.params.house}`
},
}
const getItemName = sqlId => {
let item = findItemBySqlId(sqlId)
if (!item) item = window.inventoryAPI.getVehItem(sqlId);
if (!item) return 'Неизвестный'
if (!invItemNames[item.itemId]) return window.clientStorage.inventoryItems[item.itemId - 1].name
return invItemNames[item.itemId](item)
}
const handleUserKeyPress = useCallback(event => {
const { keyCode } = event
if (keyCode === 73) {
window.inventoryAPI.show(!window.inventoryAPI.active())
}
}, [])
window.inventoryAPI = {
active: () => {
return active
},
add: (_sqlId, _item) => {
const item = _item
const { personInventory } = inv
const fullInv = personInventory
// console.log(`isPersonItem item: ${JSON.stringify(item)}`)
if (isPersonItem(item)) {
const newItem = {
...item,
gridX: 0,
gridY: 0,
width: window.clientStorage.inventoryItems[item.itemId - 1].width,
height: window.clientStorage.inventoryItems[item.itemId - 1].height,
parentId: -1,
}
if (isContainerItem(item)) {
newItem.items = []
// console.log(`Container item: ${JSON.stringify(item)}`)
Object.keys(item.items).forEach(key => {
const { gridX, gridY } = indexToXY(
window.clientStorage.inventoryItems[item.itemId - 1].width,
window.clientStorage.inventoryItems[item.itemId - 1].height,
item.items[key].index
)
const subItem = {
...item.items[key],
gridX,
gridY,
width: window.clientStorage.inventoryItems[item.items[key].itemId - 1].width,
height: window.clientStorage.inventoryItems[item.items[key].itemId - 1].height,
}
newItem.items.push(subItem)
})
}
// console.log(`newItem ${JSON.stringify(newItem)}`)
fullInv.push(newItem)
} else {
// console.log(`item: ${JSON.stringify(item)}`)
const parentItem = window.inventoryAPI.getItem(item.parentId)
// console.log(`parentItem: ${JSON.stringify(parentItem)}`)
const { gridX, gridY } = indexToXY(
window.clientStorage.inventoryItems[parentItem.itemId - 1].width,
window.clientStorage.inventoryItems[parentItem.itemId - 1].height,
item.index
)
const newItem = {
...item,
gridX,
gridY,
width: window.clientStorage.inventoryItems[item.itemId - 1].width,
height: window.clientStorage.inventoryItems[item.itemId - 1].height,
}
if (isContainerItem(newItem)) {
newItem.items = []
Object.keys(item.items).forEach(key => {
const { aGridX, aGridY } = indexToXY(
window.clientStorage.inventoryItems[item.itemId - 1].width,
window.clientStorage.inventoryItems[item.items[key].itemId - 1].height,
item.items[key].index
)
const subItem = {
...item.items[key],
aGridX,
aGridY,
width: window.clientStorage.inventoryItems[item.items[key].itemId - 1].width,
height: window.clientStorage.inventoryItems[item.items[key].itemId - 1].height,
}
newItem.items.push(subItem)
})
}
parentItem.items.push(newItem)
const parentIndex = findIndex(
fullInv,
singleItem => singleItem.sqlId === parentItem.sqlId
)
fullInv.splice(parentIndex, 1, parentItem)
}
//console.log(JSON.stringify(inv.personInventory))
updateInventory(fullInv)
},
updateData: (sqlId, newSqlId, parentSqlId) => {
// могут быть баги
//console.log(`${sqlId}, ${newSqlId}, ${parentSqlId}`)
const newInv = updateItemInInv(
sqlId,
{ parentId: parentSqlId, sqlId: newSqlId },
inv.personInventory
)
updateInventory(newInv)
//console.log(`1: ${JSON.stringify(newInv)}`)
},
updateDataVeh: (sqlId, newSqlId, parentSqlId) => {
// могут быть баги
//console.log(`${sqlId}, ${newSqlId}, ${parentSqlId}`)
const vehInv = updateItemInInv(sqlId, { sqlId: newSqlId }, inv.vehicleInventory)
updateVehicleInventory(vehInv)
//console.log(`10: ${JSON.stringify(vehInv)}`)
},
addVehicleItems: (_items, _veh, rows, cols) => {
const items = _items
const veh = _veh
//console.log(`VEHITEMS: ${JSON.stringify(_items)}`)
const immVehInv = []
updateVehicleInventorySettings(
{
width: cols,
height: rows,
name: veh.name,
sqlId: veh.sqlId,
}
)
updateVehicleInventory([])
Object.keys(items).forEach(key => {
const vehItem = items[key]
const { gridX, gridY } = indexToXY(cols, rows, vehItem.index)
const fullItem = {
...vehItem,
gridX,
gridY,
width: window.clientStorage.inventoryItems[vehItem.itemId - 1].width,
height: window.clientStorage.inventoryItems[vehItem.itemId - 1].height,
inVehicle: true
}
immVehInv.push(fullItem)
})
updateVehicleInventory(immVehInv)
//console.log(`2: ${JSON.stringify(immVehInv)}`)
},
delete: sqlId => {
const invImm = inv.personInventory
// console.log(`SQLID: ${sqlId}`)
const item = findItemBySqlId(sqlId)
// console.log(`ITEM: ${JSON.stringify(item)}`)
if (item) {
if (item.parentId === -1 || !item.parentId) {
//console.log(`ITEM: ${JSON.stringify(item)}`)
remove(invImm, aItem => aItem.sqlId === sqlId)
} else {
const parentItem = findItemBySqlId(item.parentId)
//console.log(`PARENT: ${JSON.stringify(parentItem)}`)
remove(parentItem.items, aItem => aItem.sqlId === sqlId)
const parentIndex = findIndex(
invImm,
singleItem => singleItem.sqlId === parentItem.sqlId
)
invImm.splice(parentIndex, 1, parentItem)
}
updateInventory(invImm)
// window.clientStorage.inventoryWeight = window.inventoryAPI.getCommonWeight()
// выставить размер инвентаря
// $('#inventory .weight').text(clientStorage.inventoryWeight.toFixed(1))
}
},
deleteVehicleItems: () => {
updateVehicleInventory([])
},
enable: enable => {
if (enable) {
window.addEventListener('keydown', handleUserKeyPress)
} else {
window.inventoryAPI.show(enable)
window.removeEventListener('keydown', handleUserKeyPress)
}
},
getItem: sqlId => {
return findItemBySqlId(sqlId)
},
getArrayByItemId: _itemIds => {
let itemIds = ''
if (typeof _itemIds === 'string') itemIds = JSON.parse(_itemIds)
if (!Array.isArray(itemIds)) itemIds = [itemIds]
return findArrayItemByItemId(itemIds)
},
getVehItem: (sqlId) => {
const aItem = find(
inv.vehicleInventory, // eslint-disable-line
item => item.sqlId === sqlId
)
if (aItem) return aItem
return null
},
setHealth: _value => {
const value = parseInt(_value, 10)
updatePersonItems({ health: value })
},
setSatiety: _value => {
const value = parseInt(_value, 10)
updatePersonItems({ satiety: value })
},
setThirst: _value => {
const value = parseInt(_value, 10)
updatePersonItems({ thirst: value })
},
setArmour: _value => {
const value = parseInt(_value, 10)
const immInv = inv.personInventory
const item = find(immInv, aItem => (aItem.itemId === 3 && aItem.parentId === -1))
if (!item) {
const newItem = { ...item, params: { armour: value } }
remove(immInv, aItem => (aItem.itemId === 3 && aItem.parentId === -1))
immInv.push(newItem)
}
updatePersonItems(immInv)
},
show: enable => {
if (enable) {
if (window.medicTablet.active()
|| window.pdTablet.active()
|| window.clientStorage.hasCuffs
|| window.telePhone.active()
//|| window.armyTablet.active()
// || window.sheriffTablet.active()
//|| window.fibTablet.active()
|| window.playerMenu.active()
|| window.consoleAPI.active()
|| window.modalAPI.active()
|| window.playerMenu.active()
|| window.chatAPI.active()
//|| window.tradeAPI.active()
|| window.documentsAPI.active()
|| window.houseMenu.__vue__.active()) return
alt.emit('Cursor::show', true)
alt.emit('setInventoryActive', true)
alt.emit('setBlockControl', true)
alt.emit('toBlur', 200)
setActive(enable)
} else {
if (window.consoleAPI.active()) return
alt.emit('setInventoryActive', false)
alt.emit('Cursor::show', false)
alt.emit('setBlockControl', false)
hideItemMenu()
hideModal()
alt.emit('fromBlur', 200)
setActive(enable)
}
},
updateParams: (_sqlId, _params) => {
const sqlId = parseInt(_sqlId, 10)
const params = _params
const newInv = updateItemInInv(sqlId, params, inv.personInventory)
updateInventory(newInv)
},
updateParamsVeh: (_sqlId, _params) => {
const sqlId = parseInt(_sqlId, 10)
const params = JSON.parse(_params)
const newInv = updateItemInInv(sqlId, { params }, inv.vehicleInventory)
updateInventory(newInv)
},
vehAdd: (_sqlId, _item) => {
// const sqlId = parseInt(_sqlId, 10)
const item = _item
const { vehicleInventory } = inv
const fullInv = vehicleInventory
let newItem = item
newItem.inVehicle = true
if (!item.parentId || item.parentId === -1) {
delete item.parentId
}
const { gridX, gridY } = indexToXY(
inv.vehicleInventorySettings.width,
inv.vehicleInventorySettings.height,
item.index
)
newItem = {
...newItem,
gridX,
gridY,
width: window.clientStorage.inventoryItems[item.itemId - 1].width,
height: window.clientStorage.inventoryItems[item.itemId - 1].height,
inVehicle: true,
}
fullInv.push(newItem)
updateVehicleInventory(fullInv)
//console.log(`3: ${JSON.stringify(fullInv)}`)
},
vehDelete: sqlId => {
const invImm = inv.vehicleInventory
const item = findVehItemBySqlId(invImm, sqlId)
if (item.parentId === -1 || !item.parentId) {
remove(invImm, { sqlId })
} else {
const parentItem = findItemBySqlId(item.parentId)
remove(parentItem.items, { sqlId })
const parentIndex = findIndex(
invImm,
singleItem => singleItem.sqlId === parentItem.sqlId
)
invImm.splice(parentIndex, 1, parentItem)
}
// vehicle check weight
},
}
return (
active &&
<DndProvider backend={MouseBackEnd}>
<InventoryContext.Provider
value={{ inv }}
>
<div id="invWrapper">
<ResponsiveStyler>
<div
id="playerInventory"
style={{ display: active ? 'grid' : 'none' }}
role="presentation"
onClick={hideModals}
>
{ window.clientStorage.bootVehicleId !== -1
&& <LeftInventory />
}
<PersonInventory />
<RightInventory />
</div>
</ResponsiveStyler>
<InventoryMenu />
<InventoryModal />
<InventoryDragModal />
</div>
</InventoryContext.Provider>
</DndProvider>
)
}