-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.tsx
More file actions
56 lines (47 loc) · 1.82 KB
/
index.tsx
File metadata and controls
56 lines (47 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
Copyright (c) 2022 Skyflow, Inc.
*/
import React, { FC, useState } from 'react'
import { ELEMENT_CREATED } from '../../utils/constants'
import EventEmitter from '../../utils/event-emitter'
import ComposableContainer from 'skyflow-js/types/core/external/collect/compose-collect-container';
import Skyflow from 'skyflow-js'
import { v4 as uuid } from 'uuid';
import { ComposableSubmitResponse } from '../../common';
export interface IComposableContainer {
children?: React.ReactNode
container: ComposableContainer
id?: string
onSubmit?: (response?: ComposableSubmitResponse) => void
}
const ComposableContainerComponent: FC<IComposableContainer> = ({ children, ...props }) => {
const uniqueDivId = uuid();
const [currentCount, setCurrentCount] = useState(0);
const eventEmitter: EventEmitter = new EventEmitter();
eventEmitter.on(ELEMENT_CREATED, (data) => {
setCurrentCount((prev) => prev + 1);
});
const iterateOverChildren = (children: React.ReactNode) => {
return React.Children.map(children, (child) => {
if (!React.isValidElement(child)) return child;
return React.cloneElement(child, { eventEmitter: eventEmitter } as Partial<unknown>)
})
};
React.useEffect(() => {
try {
if (currentCount === React.Children.count(children)){
props.container.mount(props.id ? `#${props.id}` : `#COMPOSABLE_CONTAINER-id-${uniqueDivId}`);
if(props.onSubmit)
props.container.on(Skyflow.EventName.SUBMIT,props.onSubmit)
}
} catch (e) {
// eslint-disable-next-line no-console
console.error(e)
}
}, [currentCount])
return <div id={props.id ? props.id : `COMPOSABLE_CONTAINER-id-${uniqueDivId}`} style={{ width:'inherit',
height:'100%'}}>
{iterateOverChildren(children)}
</div>
}
export default ComposableContainerComponent;