forked from ikuaitu/vue-fabric-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServersPlugin.ts
355 lines (321 loc) · 9.58 KB
/
ServersPlugin.ts
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
/*
* @Author: 秦少卫
* @Date: 2023-06-20 12:52:09
* @LastEditors: 秦少卫
* @LastEditTime: 2024-07-25 17:40:14
* @Description: 内部插件
*/
import { v4 as uuid } from 'uuid';
import { selectFiles, clipboardText, downFile } from './utils/utils';
import { fabric } from 'fabric';
import type { IEditor, IPluginTempl } from '@kuaitu/core';
import { SelectEvent, SelectMode } from './eventType';
type IPlugin = Pick<
ServersPlugin,
| 'insert'
| 'loadJSON'
| 'getJson'
| 'dragAddItem'
| 'clipboard'
| 'clipboardBase64'
| 'saveJson'
| 'saveSvg'
| 'saveImg'
| 'clear'
| 'preview'
| 'getSelectMode'
| 'getExtensionKey'
>;
declare module '@kuaitu/core' {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface IEditor extends IPlugin {}
}
function transformText(objects: any) {
if (!objects) return;
objects.forEach((item: any) => {
if (item.objects) {
transformText(item.objects);
} else {
item.type === 'text' && (item.type = 'textbox');
}
});
}
class ServersPlugin implements IPluginTempl {
public selectedMode: SelectMode;
static pluginName = 'ServersPlugin';
static apis = [
'insert',
'loadJSON',
'getJson',
'dragAddItem',
'clipboard',
'clipboardBase64',
'saveJson',
'saveSvg',
'saveImg',
'clear',
'preview',
'getSelectMode',
'getExtensionKey',
];
static events = [SelectMode.ONE, SelectMode.MULTI, SelectEvent.CANCEL];
// public hotkeys: string[] = ['left', 'right', 'down', 'up'];
constructor(public canvas: fabric.Canvas, public editor: IEditor) {
this.selectedMode = SelectMode.EMPTY;
this._initSelectEvent();
}
private _initSelectEvent() {
this.canvas.on('selection:created', () => this._emitSelectEvent());
this.canvas.on('selection:updated', () => this._emitSelectEvent());
this.canvas.on('selection:cleared', () => this._emitSelectEvent());
}
private _emitSelectEvent() {
if (!this.canvas) {
throw TypeError('还未初始化');
}
const actives = this.canvas
.getActiveObjects()
.filter((item) => !(item instanceof fabric.GuideLine)); // 过滤掉辅助线
if (actives && actives.length === 1) {
this.selectedMode = SelectMode.ONE;
this.editor.emit(SelectEvent.ONE, actives);
} else if (actives && actives.length > 1) {
this.selectedMode = SelectMode.MULTI;
this.editor.emit(SelectEvent.MULTI, actives);
} else {
this.editor.emit(SelectEvent.CANCEL);
}
}
getSelectMode() {
return String(this.selectedMode);
}
insert(callback?: () => void) {
selectFiles({ accept: '.json' }).then((files) => {
if (files && files.length > 0) {
const file = files[0];
const reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = () => {
this.loadJSON(reader.result as string, callback);
};
}
});
}
// 设置path属性
renderITextPath(textPaths: Record<'id' | 'path', any>[]) {
textPaths.forEach((item) => {
const object = this.canvas.getObjects().find((o) => o.id === item.id);
if (object) {
fabric.Path.fromObject(item.path, (e) => {
object.set('path', e);
});
}
});
}
async loadJSON(jsonFile: string | object, callback?: () => void) {
// 确保元素存在id
const temp = typeof jsonFile === 'string' ? JSON.parse(jsonFile) : jsonFile;
const textPaths: Record<'id' | 'path', any>[] = [];
temp.objects.forEach((item: any) => {
!item.id && (item.id = uuid());
// 收集所有路径文本元素i-text,并设置path为null
if (item.type === 'i-text' && item.path) {
textPaths.push({ id: item.id, path: item.path });
item.path = null;
}
});
// hookTransform遍历
const tempTransform = await this._transform(temp);
jsonFile = JSON.stringify(tempTransform);
// 加载前钩子
this.editor.hooksEntity.hookImportBefore.callAsync(jsonFile, () => {
this.canvas.loadFromJSON(jsonFile, () => {
// 把i-text对应的path加上
this.renderITextPath(textPaths);
this.canvas.renderAll();
// 加载后钩子
this.editor.hooksEntity.hookImportAfter.callAsync(jsonFile, () => {
// 修复导入带水印的json无法清除问题 #359
this.editor?.updateDrawStatus &&
typeof this.editor.updateDrawStatus === 'function' &&
this.editor.updateDrawStatus(!!temp['overlayImage']);
this.canvas.renderAll();
callback && callback();
this.editor.emit('loadJson');
});
});
});
}
async _transform(json: any) {
await this.promiseCallAsync(json);
if (json.objects) {
const all = json.objects.map((item: any) => {
return this._transform(item);
});
await Promise.all(all);
}
return json;
}
promiseCallAsync(item: any) {
return new Promise((resolve) => {
this.editor.hooksEntity.hookTransform.callAsync(item, () => {
resolve(item);
});
});
}
getJson() {
const keys = this.getExtensionKey();
return this.canvas.toJSON(keys);
}
getExtensionKey() {
return [
'id',
'gradientAngle',
'selectable',
'hasControls',
'linkData',
'editable',
'extensionType',
'extension',
'verticalAlign',
'roundValue',
];
}
/**
* @description: 拖拽添加到画布
* @param {Event} event
* @param {Object} item
*/
dragAddItem(item: fabric.Object, event?: DragEvent) {
if (event) {
const { left, top } = this.canvas.getSelectionElement().getBoundingClientRect();
if (event.x < left || event.y < top || item.width === undefined) return;
const point = {
x: event.x - left,
y: event.y - top,
};
const pointerVpt = this.canvas.restorePointerVpt(point);
item.left = pointerVpt.x - item.width / 2;
item.top = pointerVpt.y;
}
const { width } = this._getSaveOption();
width && item.scaleToWidth(width / 2);
this.canvas.add(item);
this.canvas.setActiveObject(item);
!event && this.editor.position('center');
this.canvas.requestRenderAll();
}
clipboard() {
const jsonStr = this.getJson();
return clipboardText(JSON.stringify(jsonStr, null, '\t'));
}
async clipboardBase64() {
const dataUrl = await this.preview();
return clipboardText(dataUrl);
}
async saveJson() {
const dataUrl = this.getJson();
// 把文本text转为textgroup,让导入可以编辑
await transformText(dataUrl.objects);
const fileStr = `data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(dataUrl, null, '\t')
)}`;
downFile(fileStr, 'json');
}
saveSvg() {
this.editor.hooksEntity.hookSaveBefore.callAsync('', () => {
const { fontOption, svgOption } = this._getSaveSvgOption();
fabric.fontPaths = {
...fontOption,
};
const dataUrl = this.canvas.toSVG(svgOption);
const fileStr = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(dataUrl)}`;
this.editor.hooksEntity.hookSaveAfter.callAsync(fileStr, () => {
downFile(fileStr, 'svg');
});
});
}
saveImg() {
this.editor.hooksEntity.hookSaveBefore.callAsync('', () => {
const option = this._getSaveOption();
this.canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
const dataUrl = this.canvas.toDataURL(option);
this.editor.hooksEntity.hookSaveAfter.callAsync(dataUrl, () => {
downFile(dataUrl, 'png');
});
});
}
preview() {
return new Promise<string>((resolve) => {
this.editor.hooksEntity.hookSaveBefore.callAsync('', () => {
const option = this._getSaveOption();
this.canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
this.canvas.renderAll();
const dataUrl = this.canvas.toDataURL(option);
this.editor.hooksEntity.hookSaveAfter.callAsync(dataUrl, () => {
resolve(dataUrl);
});
});
});
}
_getSaveSvgOption() {
const workspace = this.canvas.getObjects().find((item) => item.id === 'workspace');
let fontFamilyArry = this.canvas
.getObjects()
.filter((item) => item.type == 'textbox')
.map((item) => item.fontFamily);
fontFamilyArry = Array.from(new Set(fontFamilyArry));
const fontList = this.editor.getPlugin('FontPlugin').cacheList;
const fontEntry = {};
for (const font of fontFamilyArry) {
const item = fontList.find((item) => item.name === font);
fontEntry[font] = item.file;
}
console.log('_getSaveSvgOption', fontEntry);
const { left, top, width, height } = workspace as fabric.Object;
return {
fontOption: fontEntry,
svgOption: {
width,
height,
viewBox: {
x: left,
y: top,
width,
height,
},
},
};
}
_getSaveOption() {
const workspace = this.canvas
.getObjects()
.find((item: fabric.Object) => item.id === 'workspace');
console.log('getObjects', this.canvas.getObjects());
const { left, top, width, height } = workspace as fabric.Object;
const option = {
name: 'New Image',
format: 'png',
quality: 1,
width,
height,
left,
top,
};
return option;
}
clear() {
this.canvas.getObjects().forEach((obj) => {
if (obj.id !== 'workspace') {
this.canvas.remove(obj);
}
});
this.editor?.setWorkspaseBg('#fff');
this.canvas.discardActiveObject();
this.canvas.renderAll();
}
destroy() {
console.log('pluginDestroy');
}
}
export default ServersPlugin;