-
-
Notifications
You must be signed in to change notification settings - Fork 591
/
Excalidraw.tsx
269 lines (239 loc) · 7.34 KB
/
Excalidraw.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { useQuery } from '@tanstack/react-query'
import React, { forwardRef, useImperativeHandle, useMemo, useRef } from 'react'
import { patch } from 'jsondiffpatch'
import type { ExcalidrawElement } from '@excalidraw/excalidraw/types/element/types'
import type {
AppState,
BinaryFiles,
ExcalidrawImperativeAPI,
} from '@excalidraw/excalidraw/types/types'
import type { Delta } from 'jsondiffpatch'
import type { FC } from 'react'
import {
Excalidraw as Board,
exportToBlob,
exportToSvg,
} from '@excalidraw/excalidraw'
import { useIsMobile } from '~/atoms'
import { API_URL } from '~/constants/env'
import { useIsDark } from '~/hooks/common/use-is-dark'
import { cloneDeep } from '~/lib/_'
import { stopPropagation } from '~/lib/dom'
import { clsxm, safeJsonParse } from '~/lib/helper'
import { toast } from '~/lib/toast'
import { MotionButtonBase } from '../button'
import { useModalStack } from '../modal'
export interface ExcalidrawProps {
zenModeEnabled?: boolean
viewModeEnabled?: boolean
showExtendButton?: boolean
onChange?: (
elements: readonly ExcalidrawElement[],
appState: AppState,
files: BinaryFiles,
) => void
className?: string
onReady?: (api: ExcalidrawImperativeAPI) => void
////
data?: object
refUrl?: string
patchDiffDelta?: Delta
}
export interface ExcalidrawRefObject {
getRefData(): ExcalidrawElement | null | undefined
getDiffDelta(): Delta | null | undefined
}
export const Excalidraw = forwardRef<
ExcalidrawRefObject,
Omit<ExcalidrawProps, 'refUrl' | 'patchDiffDelta' | 'data'> & {
data: string
}
>((props, ref) => {
const { data, ...rest } = props
const transformedProps: {
data?: ExcalidrawElement
refUrl?: string
patchDiffDelta?: Delta
} = useMemo(() => {
if (!data) return {}
const tryParseJson = safeJsonParse(data)
if (!tryParseJson) {
// 1. data 是 string,取第一行判断
const splittedLines = data.split('\n')
const firstLine = splittedLines[0]
const otherLines = splittedLines.slice(1).join('\n')
const props = {} as any
// 第一行是地址
if (firstLine.startsWith('http')) {
props.refUrl = firstLine
}
// 第一行是 ref:file/:filename
// 命中后端文件
else if (firstLine.startsWith('ref:')) {
props.refUrl = `${API_URL}/objects/${firstLine.slice(4)}`
}
if (otherLines.trim().length > 0) {
// 识别为其他行是 delta diff
props.patchDiffDelta = safeJsonParse(otherLines)
}
return props
} else {
return {
data: tryParseJson as ExcalidrawElement,
}
}
}, [data])
const internalRef = useRef<InternelExcalidrawRefObject>(null)
useImperativeHandle(ref, () => ({
getRefData() {
return internalRef.current?.getRemoteData()
},
getDiffDelta() {
return transformedProps.patchDiffDelta
},
}))
return <ExcalidrawImpl ref={internalRef} {...rest} {...transformedProps} />
})
Excalidraw.displayName = 'Excalidraw'
interface InternelExcalidrawRefObject {
getRemoteData(): ExcalidrawElement | null | undefined
}
const ExcalidrawImpl = forwardRef<InternelExcalidrawRefObject, ExcalidrawProps>(
(
{
data,
refUrl,
patchDiffDelta,
viewModeEnabled = true,
zenModeEnabled = true,
onChange,
className,
showExtendButton = true,
onReady,
},
ref,
) => {
const excalidrawAPIRef = React.useRef<ExcalidrawImperativeAPI>()
const modal = useModalStack()
const isMobile = useIsMobile()
const { data: refData, isLoading } = useQuery({
queryKey: ['excalidraw', refUrl as string],
queryFn: async ({ queryKey }) => {
const [_, refUrl] = queryKey
const res = await fetch(refUrl)
return await res.json()
},
enabled: !!refUrl,
})
useImperativeHandle(ref, () => {
return {
getRemoteData() {
return refData
},
}
})
const finalDataIfRefUrl = useMemo(() => {
if (!refData) return null
return patch(cloneDeep(refData), patchDiffDelta)
}, [refData, refUrl])
const isDarkMode = useIsDark()
const finalData = useMemo(() => {
const finalData = data || finalDataIfRefUrl
if (!finalData && !isLoading) {
console.error('Excalidraw: data not exist')
}
return finalData as ExcalidrawElement
}, [data, finalDataIfRefUrl, isLoading])
return (
<div
onKeyDown={stopPropagation}
onKeyUp={stopPropagation}
className={clsxm('relative h-[500px] w-full', className)}
>
{isLoading && (
<div className="absolute inset-0 z-[10] flex center">
<div className="loading loading-spinner" />
</div>
)}
<Board
key={
refUrl ? `excalidraw-refData-loading-${isLoading}` : 'excalidraw'
}
theme={isDarkMode ? 'dark' : 'light'}
initialData={finalData}
detectScroll={false}
zenModeEnabled={zenModeEnabled}
onChange={onChange}
viewModeEnabled={viewModeEnabled}
excalidrawAPI={(api) => {
excalidrawAPIRef.current = api
setTimeout(() => {
api.scrollToContent(undefined, {
fitToContent: true,
})
}, 1000)
onReady?.(api)
}}
/>
{viewModeEnabled && showExtendButton && (
<MotionButtonBase
onClick={async () => {
if (!excalidrawAPIRef.current) {
toast.error('Excalidraw API not ready')
return
}
const elements = excalidrawAPIRef.current.getSceneElements()
if (isMobile) {
const blob = await exportToBlob({
elements,
files: null,
})
window.open(window.URL.createObjectURL(blob))
} else {
const windowRect = {
w: window.innerWidth,
h: window.innerHeight,
}
const $svg = await exportToSvg({
elements,
files: null,
maxWidthOrHeight: Math.min(
windowRect.h * 0.7,
windowRect.w * 0.9,
),
appState: { theme: isDarkMode ? 'dark' : 'light' },
exportPadding: 12,
})
modal.present({
title: 'Preview',
content: () => <SvgPreview svgElement={$svg} />,
clickOutsideToDismiss: true,
})
}
}}
className={clsxm(
'absolute bottom-2 right-2 z-10 box-content flex h-5 w-5 rounded-md border p-2 center',
'border-zinc-200 text-zinc-600',
'dark:border-neutral-800 dark:text-zinc-500',
)}
>
<i className="icon-[mingcute--external-link-line]" />
</MotionButtonBase>
)}
</div>
)
},
)
ExcalidrawImpl.displayName = 'ExcalidrawImpl'
const SvgPreview: FC<{
svgElement: SVGSVGElement
}> = ({ svgElement }) => {
return (
<div
className="relative w-full overflow-auto [&>svg]:!h-full [&>svg]:!w-full [&>svg]:max-w-full"
dangerouslySetInnerHTML={{
__html: svgElement.outerHTML,
}}
/>
)
}