forked from LiveDuo/destack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Editor.tsx
88 lines (73 loc) · 2.28 KB
/
Editor.tsx
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import React, { useEffect, useContext } from 'react'
import { Editor as CraftEditor, Frame, Element, useEditor, Resolver } from '@craftjs/core'
import Viewport from '../viewport'
import EditorElement from './EditorElement'
import { Container } from '../shared/Container'
import { loadTemplate, saveTemplateDebounce } from '../utils/fetch'
import PoweredBy from './PoweredBy'
import { ThemeContext, ThemeProvider } from '../store'
interface FrameProps {
data: any
standaloneServer: boolean
}
const DEFAULT_TEMPLATE = {
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { width: '100%', height: '800px' },
displayName: 'Container',
custom: { displayName: 'App' },
},
}
const FrameEditor: React.FC<FrameProps> = ({ data, standaloneServer }) => {
const { actions } = useEditor()
const loadData = async () => {
if (data) {
const templateData = data.find(({ name }: any) => name === `${location.pathname}.json`)
const content = JSON.parse(templateData.content)
actions.deserialize(content)
} else {
const result = await loadTemplate(standaloneServer)
const content = JSON.parse(result as string)
actions.deserialize(content.ROOT ? content : DEFAULT_TEMPLATE) // NOTE: also loads the data in the editor
}
}
useEffect(() => {
loadData()
}, [])
return !data ? (
<ThemeProvider standaloneServer={standaloneServer}>
<Viewport>
<Frame>
<Element canvas is={Container} children={[]} custom={{ displayName: 'App' }} />
</Frame>
</Viewport>
</ThemeProvider>
) : (
<div className="page-container">
<Frame />
<PoweredBy />
</div>
)
}
interface EditorProps {
data: any
standaloneServer: boolean
}
const Editor: React.FC<EditorProps> = ({ data, standaloneServer }) => {
const { resolver } = useContext(ThemeContext)
const onStateChange = (e: any) => {
saveTemplateDebounce(e, standaloneServer)
}
return (
<CraftEditor
resolver={resolver as Resolver}
enabled={!data}
onRender={({ render }) => <EditorElement render={render} standaloneServer={standaloneServer} />} //
onNodesChange={onStateChange}
>
<FrameEditor data={data} standaloneServer={standaloneServer} />
</CraftEditor>
)
}
export default Editor