-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditor.tsx
More file actions
481 lines (439 loc) · 16.4 KB
/
Copy pathEditor.tsx
File metadata and controls
481 lines (439 loc) · 16.4 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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import React, { useState, useEffect } from 'react';
import {Editor, ShortcutKey} from 'amis-editor';
import {inject, observer} from 'mobx-react';
import {RouteComponentProps} from 'react-router-dom';
import {toast, Select} from 'amis';
import {currentLocale} from 'i18n-runtime';
import {Icon} from '../icons/index';
import {IMainStore} from '../store';
import '../editor/DisabledEditorPlugin'; // 用于隐藏一些不需要的Editor预置组件
import '../renderer/MyRenderer';
import '../editor/MyRenderer';
let currentUuid = '';
let host = `${window.location.protocol}//${window.location.host}`;
// 如果在 gh-pages 里面
if (/^\/amis-editor-demo/.test(window.location.pathname)) {
host += '/amis-editor';
}
const schemaUrl = `${host}/schema.json`;
const editorLanguages = [
{
label: '简体中文',
value: 'zh-CN'
},
{
label: 'English',
value: 'en-US'
}
];
export default inject('store')(
observer(function ({
store,
history,
match
}: {store: IMainStore} & RouteComponentProps<{id: string}>) {
const uuid: string = match.params.id;
const curLanguage = currentLocale(); // 获取当前语料类型
const [pageData, setPageData] = useState<any>(null);
const [loading, setLoading] = useState<boolean>(true);
// console.log('当前 UUID:', uuid);
// console.log('当前 schema url:', schemaUrl);
// 辅助函数:根据输入参数找到实际的存储 key
const findActualStorageKey = (inputParam: string): string => {
// 如果是完整 UUID 格式,直接返回
if (inputParam.length === 36 && inputParam.includes('-')) {
return inputParam;
}
// 如果是短格式 UUID 或数字序号,需要查找实际的 key
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.length === 36 && key.includes('-')) {
const testData = localStorage.getItem(key);
if (testData) {
try {
const testParsed = JSON.parse(testData);
if (testParsed && (testParsed.schema || testParsed.type === 'page')) {
// 对于数字序号,我们需要更复杂的匹配逻辑
// 这里简化处理,返回找到的第一个匹配项
return key;
}
} catch (e) {
// 忽略解析错误
}
}
}
}
// 如果没找到,返回原始参数
return inputParam;
};
// 从 localStorage 获取页面数据
useEffect(() => {
if (uuid !== currentUuid) {
currentUuid = uuid;
// console.log('🔍 切换到参数:', uuid, '的页面');
// console.log('📊 参数分析:', {
// value: uuid,
// type: typeof uuid,
// length: uuid.length,
// isNumber: /^\d+$/.test(uuid),
// isShortUUID: uuid.startsWith('u:'),
// isFullUUID: uuid.length === 36 && uuid.includes('-')
// });
// 尝试从 localStorage 获取页面数据
let storedPageData = localStorage.getItem(uuid);
let actualKey = uuid;
let matchMethod = 'direct';
// 如果直接获取失败,尝试其他匹配策略
if (!storedPageData) {
// console.log('❌ 直接匹配失败,开始智能匹配...');
// 策略1: 如果是短格式 UUID (u:xxxxx),查找完整 UUID
if (uuid.startsWith('u:')) {
// console.log('🔍 检测到短格式 UUID,尝试查找完整 UUID...');
matchMethod = 'short-to-full';
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.length === 36 && key.includes('-')) {
const testData = localStorage.getItem(key);
if (testData) {
try {
const testParsed = JSON.parse(testData);
if (testParsed && (testParsed.schema || testParsed.type === 'page')) {
console.log('🎯 找到匹配的完整 UUID:', key);
storedPageData = testData;
actualKey = key;
break;
}
} catch (e) {
// 忽略解析错误,继续查找
}
}
}
}
}
// 策略2: 如果是数字序号,按索引查找页面数据
else if (/^\d+$/.test(uuid)) {
// console.log('🔢 检测到数字序号,尝试按索引查找页面数据...');
matchMethod = 'index-based';
const pageIndex = parseInt(uuid, 10);
const allPageKeys = [];
// 收集所有可能的页面数据 keys
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.length === 36 && key.includes('-')) {
const testData = localStorage.getItem(key);
if (testData) {
try {
const testParsed = JSON.parse(testData);
if (testParsed && (testParsed.schema || testParsed.type === 'page')) {
allPageKeys.push({
key: key,
data: testData,
parsed: testParsed
});
}
} catch (e) {
// 忽略解析错误
}
}
}
}
// console.log('📋 找到的页面数据列表:', allPageKeys.map(item => ({
// key: item.key,
// title: item.parsed.title || item.parsed.name || 'Untitled'
// })));
// 按索引获取页面数据
if (allPageKeys.length > pageIndex) {
const targetPage = allPageKeys[pageIndex];
console.log('🎯 按索引', pageIndex, '找到页面:', targetPage.key);
storedPageData = targetPage.data;
actualKey = targetPage.key;
} else {
console.warn('⚠️ 索引', pageIndex, '超出范围,总页面数:', allPageKeys.length);
}
}
// 策略3: 如果以上都失败,尝试模糊匹配
if (!storedPageData) {
console.log('🔍 尝试模糊匹配...');
matchMethod = 'fuzzy';
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.length === 36 && key.includes('-')) {
const testData = localStorage.getItem(key);
if (testData) {
try {
const testParsed = JSON.parse(testData);
if (testParsed && (testParsed.schema || testParsed.type === 'page')) {
console.log('🎯 模糊匹配找到页面数据:', key);
storedPageData = testData;
actualKey = key;
break;
}
} catch (e) {
// 忽略解析错误,继续查找
}
}
}
}
}
} else {
console.log('✅ 直接匹配成功');
}
if (storedPageData) {
try {
const parsedData = JSON.parse(storedPageData);
// console.log('✅ 页面数据匹配成功!');
// console.log('📊 匹配详情:', {
// inputParam: uuid,
// matchMethod: matchMethod,
// actualKey: actualKey,
// dataTitle: parsedData.title || parsedData.name || 'Untitled'
// });
// console.log('📄 页面数据:', parsedData);
setPageData(parsedData);
// 更新 store 中的 schema
if (parsedData.schema) {
store.updateSchema(parsedData.schema);
} else if (parsedData && typeof parsedData === 'object' && parsedData.type) {
// 如果 parsedData 本身就是 schema
store.updateSchema(parsedData);
}
} catch (error) {
console.error('❌ 解析页面数据失败:', error);
toast.error('页面数据格式错误', '错误');
}
} else {
// console.warn('❌ 所有匹配策略都失败了');
// console.log('📊 匹配尝试总结:', {
// inputParam: uuid,
// paramType: typeof uuid,
// isNumber: /^\d+$/.test(uuid),
// isShortUUID: uuid.startsWith('u:'),
// isFullUUID: uuid.length === 36 && uuid.includes('-'),
// lastMatchMethod: matchMethod
// });
// console.log('📋 当前 localStorage 中的所有 keys:', Object.keys(localStorage));
// 显示更详细的错误信息
const errorMessage = /^\d+$/.test(uuid)
? `未找到索引为 ${uuid} 的页面数据`
: `未找到参数为 ${uuid} 的页面数据`;
toast.warning(errorMessage, '警告');
}
setLoading(false);
}
}, [uuid, store]);
function save() {
// 如果在 iframe 中,通过 PostMessage 通知父窗口保存
if (window.parent !== window) {
window.parent.postMessage({
type: 'SAVE_SCHEMA',
data: {
uuid: uuid,
schema: store.schema
}
}, '*');
} else {
// 独立模式下的保存逻辑 - 更新 localStorage 中的数据
if (pageData) {
const updatedPageData = {
...pageData,
...store.schema
};
// 使用辅助函数确定正确的存储 key
const storageKey = findActualStorageKey(uuid);
// console.log('� 保存数据到 key:', storageKey, '(原始参数:', uuid, ')');
localStorage.setItem(storageKey, JSON.stringify(updatedPageData));
setPageData(updatedPageData);
toast.success('保存成功', '提示');
} else {
toast.error('页面数据不存在,无法保存', '错误');
}
}
}
function onChange(value: any) {
store.updateSchema(value);
// 实时更新 localStorage 中以 UUID 为键的数据(无论是否在 iframe 中)
if (pageData) {
const updatedPageData = {
...pageData,
...value
};
// 确定正确的存储 key
let storageKey = uuid;
// 如果当前 UUID 是短格式,尝试找到完整的 UUID key
if (uuid.startsWith('u:')) {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.length === 36 && key.includes('-')) {
const testData = localStorage.getItem(key);
if (testData) {
try {
const testParsed = JSON.parse(testData);
if (testParsed && (testParsed.schema || testParsed.type === 'page')) {
storageKey = key;
break;
}
} catch (e) {
// 忽略解析错误
}
}
}
}
}
// 更新 localStorage 中以 UUID 为键的数据,供保存按钮使用
localStorage.setItem(storageKey, JSON.stringify(updatedPageData));
setPageData(updatedPageData);
console.log('🔄 实时更新 localStorage:', {
key: storageKey,
schema: value,
updatedData: updatedPageData
});
}
// 如果在 iframe 中,通知父窗口 schema 已变更
if (window.parent !== window) {
window.parent.postMessage({
type: 'SCHEMA_CHANGED',
data: {
uuid: uuid,
schema: value
}
}, '*');
}
}
function changeLocale(value: string) {
localStorage.setItem('suda-i18n-locale', value);
window.location.reload();
}
function exit() {
// 退出编辑器,返回到页面列表或关闭窗口
if (window.parent !== window) {
// 如果在 iframe 中,通知父窗口关闭编辑器
window.parent.postMessage({
type: 'CLOSE_EDITOR',
data: { uuid: uuid }
}, '*');
} else {
// 独立模式下返回首页或页面列表
history.push('/');
}
}
// 如果正在加载或没有页面数据,显示加载状态
if (loading) {
return (
<div className="Editor-Demo">
<div className="Editor-header">
<div className="Editor-title">DDN Hub 可视化编辑器 - 加载中...</div>
</div>
<div className="Editor-inner" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '400px' }}>
<div>正在加载页面数据...</div>
</div>
</div>
);
}
// 如果没有找到页面数据,显示错误状态
if (!pageData) {
return (
<div className="Editor-Demo">
<div className="Editor-header">
<div className="Editor-title">DDN Hub 可视化编辑器 - 页面未找到</div>
<div className="Editor-header-actions">
<div className={`header-action-btn exit-btn`} onClick={exit}>
返回
</div>
</div>
</div>
<div className="Editor-inner" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '400px' }}>
<div>
<p>未找到 UUID 为 {uuid} 的页面数据</p>
<p>请确保页面数据已正确保存到 localStorage 中</p>
</div>
</div>
</div>
);
}
return (
<div className="Editor-Demo">
<div className="Editor-header">
<div className="Editor-title">
DDN Hub 可视化编辑器
</div>
<div className="Editor-view-mode-group-container">
<div className="Editor-view-mode-group">
<div
className={`Editor-view-mode-btn editor-header-icon ${
!store.isMobile ? 'is-active' : ''
}`}
onClick={() => {
store.setIsMobile(false);
}}
>
<Icon icon="pc-preview" title="PC模式" />
</div>
<div
className={`Editor-view-mode-btn editor-header-icon ${
store.isMobile ? 'is-active' : ''
}`}
onClick={() => {
store.setIsMobile(true);
}}
>
<Icon icon="h5-preview" title="移动模式" />
</div>
</div>
</div>
<div className="Editor-header-actions">
<ShortcutKey />
<Select
className="margin-left-space"
options={editorLanguages}
value={curLanguage}
clearable={false}
onChange={(e: any) => changeLocale(e.value)}
/>
<div
className={`header-action-btn m-1 ${
store.preview ? 'primary' : ''
}`}
onClick={() => {
store.setPreview(!store.preview);
}}
>
{store.preview ? '编辑' : '预览'}
</div>
{!store.preview && (
<div className={`header-action-btn save-btn m-1`} onClick={save}>
保存
</div>
)}
{/* {!store.preview && (
<div className={`header-action-btn exit-btn`} onClick={exit}>
退出
</div>
)} */}
</div>
</div>
<div className="Editor-inner">
<Editor
theme={'cxd'}
preview={store.preview}
isMobile={store.isMobile}
value={store.schema}
onChange={onChange}
onPreview={() => {
store.setPreview(true);
}}
onSave={save}
className="is-fixed"
$schemaUrl={schemaUrl}
showCustomRenderersPanel={true}
amisEnv={{
fetcher: store.fetcher,
notify: store.notify,
alert: store.alert,
copy: store.copy
}}
/>
</div>
</div>
);
})
);