@hprint/plugins 0.0.8 → 0.0.9-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,541 @@
1
+ import { fabric } from '@hprint/core';
2
+ import type { IEditor, IPluginTempl } from '@hprint/core';
3
+ import { getUnit, convertSingle, formatOriginValues } from '../utils/units';
4
+
5
+ export type ImageTextListLayout =
6
+ | 'item-vertical'
7
+ | 'icon-text-split'
8
+ | 'icon-only'
9
+ | 'text-only';
10
+
11
+ export interface ImageTextListItem {
12
+ src: string;
13
+ name: string;
14
+ }
15
+
16
+ export interface ImageTextListOptions {
17
+ items?: ImageTextListItem[];
18
+ _renderItems?: ImageTextListItem[];
19
+ _clipContent?: boolean;
20
+ layout?: ImageTextListLayout;
21
+ width?: number;
22
+ height?: number;
23
+ iconSize?: number;
24
+ horizontalGap?: number;
25
+ verticalGap?: number;
26
+ itemGap?: number;
27
+ fontFamily?: string;
28
+ fontSize?: number;
29
+ fontWeight?: string;
30
+ fontStyle?: string;
31
+ underline?: boolean | string;
32
+ linethrough?: boolean | string;
33
+ textAlign?: 'left' | 'center' | 'right' | 'justify';
34
+ textWrap?: boolean;
35
+ lineHeight?: number;
36
+ charSpacing?: number;
37
+ color?: string;
38
+ [key: string]: any;
39
+ }
40
+
41
+ type ImageTextListGroup = fabric.Group & {
42
+ extensionType?: string;
43
+ extension?: ImageTextListOptions;
44
+ _originSize?: Record<string, any>;
45
+ setExtension?: (fields: Record<string, any>) => Promise<void>;
46
+ setExtensionByUnit?: (fields: Record<string, any>) => Promise<void>;
47
+ setByUnit?: (field: string, value: any) => Promise<any>;
48
+ __imageTextListModified?: () => void;
49
+ };
50
+
51
+ type IPlugin = Pick<
52
+ ImageTextListPlugin,
53
+ 'createImageTextList' | 'initImageTextListEvents' | 'refreshImageTextList'
54
+ >;
55
+
56
+ declare module '@hprint/core' {
57
+ interface IEditor extends IPlugin {}
58
+ }
59
+
60
+ const DEFAULT_OPTIONS: Required<
61
+ Pick<
62
+ ImageTextListOptions,
63
+ | 'layout'
64
+ | 'width'
65
+ | 'iconSize'
66
+ | 'horizontalGap'
67
+ | 'verticalGap'
68
+ | 'itemGap'
69
+ | 'fontFamily'
70
+ | 'fontSize'
71
+ | 'fontWeight'
72
+ | 'fontStyle'
73
+ | 'underline'
74
+ | 'linethrough'
75
+ | 'textAlign'
76
+ | 'textWrap'
77
+ | 'lineHeight'
78
+ | 'charSpacing'
79
+ | 'color'
80
+ >
81
+ > = {
82
+ layout: 'item-vertical',
83
+ width: 30,
84
+ iconSize: 5,
85
+ horizontalGap: 1.5,
86
+ verticalGap: 1.5,
87
+ itemGap: 1.5,
88
+ fontFamily: 'Microsoft YaHei',
89
+ fontSize: 3,
90
+ fontWeight: 'normal',
91
+ fontStyle: 'normal',
92
+ underline: false,
93
+ linethrough: false,
94
+ textAlign: 'left',
95
+ textWrap: true,
96
+ lineHeight: 1.5,
97
+ charSpacing: 0,
98
+ color: '#000000',
99
+ };
100
+
101
+ class ImageTextListPlugin implements IPluginTempl {
102
+ static pluginName = 'ImageTextListPlugin';
103
+ static apis = [
104
+ 'createImageTextList',
105
+ 'initImageTextListEvents',
106
+ 'refreshImageTextList',
107
+ ];
108
+
109
+ constructor(
110
+ public canvas: fabric.Canvas,
111
+ public editor: IEditor
112
+ ) {}
113
+
114
+ async hookTransform(object: any) {
115
+ if (object.extensionType !== 'imageTextList') return;
116
+ const left = object.left;
117
+ const top = object.top;
118
+ const group = await this.buildGroup(object.extension || {});
119
+ const transformed = group.toObject(this.editor.getExtensionKey?.() || []);
120
+ Object.assign(object, transformed, {
121
+ left,
122
+ top,
123
+ extensionType: 'imageTextList',
124
+ extension: this.normalizeOptions(object.extension || {}),
125
+ });
126
+ }
127
+
128
+ async hookTransformObjectEnd(...args: unknown[]) {
129
+ const { originObject, fabricObject } = args[0] as {
130
+ originObject: any;
131
+ fabricObject: ImageTextListGroup;
132
+ };
133
+ if (originObject.extensionType === 'imageTextList') {
134
+ this.initImageTextListEvents(fabricObject);
135
+ }
136
+ }
137
+
138
+ async createImageTextList(
139
+ items: ImageTextListItem[],
140
+ options: ImageTextListOptions = {}
141
+ ): Promise<ImageTextListGroup> {
142
+ const extension = this.normalizeOptions({ ...options, items });
143
+ const group = await this.buildGroup(extension);
144
+ group.set({
145
+ extensionType: 'imageTextList',
146
+ extension,
147
+ } as any);
148
+ this.updateOriginSize(group, extension);
149
+ this.initImageTextListEvents(group);
150
+ return group;
151
+ }
152
+
153
+ initImageTextListEvents(group: ImageTextListGroup) {
154
+ group.setExtension = async (fields: Record<string, any>) => {
155
+ const extension = this.normalizeOptions({
156
+ ...(group.get('extension') || {}),
157
+ ...(fields || {}),
158
+ });
159
+ group.set('extension', extension);
160
+ await this.refreshImageTextList(group);
161
+ };
162
+ group.setExtensionByUnit = group.setExtension;
163
+
164
+ this.editor.addSetAndSyncByUnit?.(group);
165
+ const originalSetByUnit = group.setByUnit?.bind(group);
166
+ if (originalSetByUnit) {
167
+ group.setByUnit = async (field: string, value: any) => {
168
+ if (field === 'width' || field === 'height') {
169
+ const extension = this.normalizeOptions({
170
+ ...(group.get('extension') || {}),
171
+ [field]: Number(value),
172
+ });
173
+ group.set('extension', extension);
174
+ await this.refreshImageTextList(group);
175
+ return group;
176
+ }
177
+ return originalSetByUnit(field, value);
178
+ };
179
+ }
180
+
181
+ if (group.__imageTextListModified) {
182
+ group.off('modified', group.__imageTextListModified);
183
+ }
184
+ group.__imageTextListModified = () => {
185
+ const scaleX = group.scaleX || 1;
186
+ const scaleY = group.scaleY || 1;
187
+ if (scaleX === 1 && scaleY === 1) return;
188
+ const extension = this.normalizeOptions(group.get('extension') || {});
189
+ const widthPx = Math.max(1, (group.width || 1) * scaleX);
190
+ const heightPx = Math.max(1, (group.height || 1) * scaleY);
191
+ group.set({ scaleX: 1, scaleY: 1 });
192
+ group.set('extension', {
193
+ ...extension,
194
+ width:
195
+ getUnit(this.editor) === 'px'
196
+ ? widthPx
197
+ : this.editor.getSizeByUnit(widthPx),
198
+ height:
199
+ getUnit(this.editor) === 'px'
200
+ ? heightPx
201
+ : this.editor.getSizeByUnit(heightPx),
202
+ });
203
+ void this.refreshImageTextList(group);
204
+ };
205
+ group.on('modified', group.__imageTextListModified);
206
+ }
207
+
208
+ async refreshImageTextList(group: ImageTextListGroup) {
209
+ const currentExtension = this.normalizeOptions(group.get('extension') || {});
210
+ const extension = {
211
+ ...currentExtension,
212
+ _clipContent:
213
+ currentExtension._clipContent === true ||
214
+ Boolean(group.clipPath),
215
+ };
216
+ const left = group.left;
217
+ const top = group.top;
218
+ const replacement = await this.buildGroup(extension);
219
+ const children = replacement.getObjects();
220
+
221
+ (group as any)._objects = children;
222
+ children.forEach((child) => {
223
+ child.group = group;
224
+ });
225
+ (replacement as any)._objects = [];
226
+
227
+ group.set({
228
+ left,
229
+ top,
230
+ width: replacement.width,
231
+ height: replacement.height,
232
+ scaleX: 1,
233
+ scaleY: 1,
234
+ visible: replacement.visible,
235
+ clipPath: replacement.clipPath,
236
+ objectCaching: Boolean(replacement.clipPath),
237
+ dirty: true,
238
+ });
239
+ group.set('extension', extension);
240
+ this.updateOriginSize(group, extension);
241
+ group.setCoords();
242
+ this.canvas.requestRenderAll();
243
+ }
244
+
245
+ private normalizeOptions(options: ImageTextListOptions) {
246
+ return {
247
+ ...DEFAULT_OPTIONS,
248
+ ...options,
249
+ items: Array.isArray(options.items) ? options.items : [],
250
+ } as ImageTextListOptions;
251
+ }
252
+
253
+ private toPx(value: number | undefined) {
254
+ return convertSingle(Number(value) || 0, getUnit(this.editor));
255
+ }
256
+
257
+ private getItems(options: ImageTextListOptions) {
258
+ return (
259
+ options._renderItems?.length
260
+ ? options._renderItems
261
+ : options.items || []
262
+ ).filter((item) => item && (item.src || item.name));
263
+ }
264
+
265
+ private createText(
266
+ text: string,
267
+ options: ImageTextListOptions,
268
+ width?: number
269
+ ) {
270
+ const fontSize = Math.max(1, this.toPx(options.fontSize));
271
+ const charSpacingPx = Math.max(0, this.toPx(options.charSpacing));
272
+ const common = {
273
+ fontFamily: options.fontFamily,
274
+ fontSize,
275
+ fontWeight: options.fontWeight as any,
276
+ fontStyle: options.fontStyle as any,
277
+ underline: Boolean(options.underline),
278
+ linethrough: Boolean(options.linethrough),
279
+ fill: options.color,
280
+ textAlign: options.textAlign,
281
+ lineHeight: Number(options.lineHeight) || 1,
282
+ charSpacing: (charSpacingPx / fontSize) * 1000,
283
+ splitByGrapheme: true,
284
+ selectable: false,
285
+ evented: false,
286
+ objectCaching: false,
287
+ };
288
+ const textObject = width && options.textWrap !== false
289
+ ? new fabric.Textbox(text || '', { ...common, width })
290
+ : new fabric.Text(text || '', common);
291
+ textObject.initDimensions();
292
+ textObject.setCoords();
293
+ return textObject;
294
+ }
295
+
296
+ private loadImage(src: string, size: number) {
297
+ return new Promise<fabric.Image | null>((resolve) => {
298
+ if (!src) return resolve(null);
299
+ fabric.Image.fromURL(
300
+ src,
301
+ (image) => {
302
+ if (!image) return resolve(null);
303
+ image.set({
304
+ scaleX: size / Math.max(1, image.width || 1),
305
+ scaleY: size / Math.max(1, image.height || 1),
306
+ selectable: false,
307
+ evented: false,
308
+ objectCaching: false,
309
+ });
310
+ resolve(image);
311
+ },
312
+ { crossOrigin: 'anonymous' }
313
+ );
314
+ });
315
+ }
316
+
317
+ private async buildGroup(options: ImageTextListOptions) {
318
+ const normalized = this.normalizeOptions(options);
319
+ const items = this.getItems(normalized);
320
+ const width = Math.max(1, this.toPx(normalized.width));
321
+ if (!items.length) {
322
+ return this.createGroup([], width, 1, false);
323
+ }
324
+
325
+ const layout = normalized.layout || DEFAULT_OPTIONS.layout;
326
+ const showIcon = layout !== 'text-only';
327
+ const showText = layout !== 'icon-only';
328
+ const iconSize = Math.max(1, this.toPx(normalized.iconSize));
329
+ const horizontalGap = Math.max(0, this.toPx(normalized.horizontalGap));
330
+ const verticalGap = Math.max(0, this.toPx(normalized.verticalGap));
331
+ const itemGap = Math.max(0, this.toPx(normalized.itemGap));
332
+ const images = showIcon
333
+ ? await Promise.all(items.map((item) => this.loadImage(item.src, iconSize)))
334
+ : items.map(() => null);
335
+ const objects: fabric.Object[] = [];
336
+ let cursorY = 0;
337
+
338
+ if (layout === 'icon-text-split') {
339
+ const iconRows = this.flowRows(
340
+ items.map(() => iconSize),
341
+ width,
342
+ horizontalGap
343
+ );
344
+ iconRows.forEach((row) => {
345
+ row.items.forEach((cell) => {
346
+ const image = images[cell.index];
347
+ if (image) {
348
+ image.set({ left: cell.x, top: cursorY });
349
+ objects.push(image);
350
+ }
351
+ });
352
+ cursorY += iconSize + verticalGap;
353
+ });
354
+ items.forEach((item) => {
355
+ const text = this.createText(item.name || '', normalized, width);
356
+ text.set({ left: 0, top: cursorY });
357
+ objects.push(text);
358
+ cursorY += text.getScaledHeight() + itemGap;
359
+ });
360
+ } else if (layout === 'item-vertical') {
361
+ const textLeft = iconSize + horizontalGap;
362
+ const textWidth = Math.max(1, width - textLeft);
363
+ items.forEach((item, index) => {
364
+ const image = images[index];
365
+ const text = this.createText(
366
+ item.name || '',
367
+ normalized,
368
+ textWidth
369
+ );
370
+ const textHeight = text.getScaledHeight();
371
+ const rowHeight = Math.max(iconSize, textHeight);
372
+ if (image) {
373
+ image.set({
374
+ left: 0,
375
+ top: cursorY + (rowHeight - iconSize) / 2,
376
+ });
377
+ objects.push(image);
378
+ }
379
+ text.set({
380
+ left: textLeft,
381
+ top: cursorY + (rowHeight - textHeight) / 2,
382
+ });
383
+ objects.push(text);
384
+ cursorY += rowHeight + verticalGap;
385
+ });
386
+ } else {
387
+ const textObjects = items.map((item) =>
388
+ showText ? this.createText(item.name || '', normalized) : null
389
+ );
390
+ const itemWidths = items.map((_, index) => {
391
+ const textWidth = textObjects[index]?.getScaledWidth() || 0;
392
+ if (showIcon && showText)
393
+ return iconSize + horizontalGap + textWidth;
394
+ return showIcon ? iconSize : textWidth;
395
+ });
396
+ const rows = this.flowRows(itemWidths, width, horizontalGap);
397
+ rows.forEach((row) => {
398
+ const rowHeight = Math.max(
399
+ showIcon ? iconSize : 0,
400
+ ...row.items.map(
401
+ (cell) => textObjects[cell.index]?.getScaledHeight() || 0
402
+ )
403
+ );
404
+ row.items.forEach((cell) => {
405
+ let x = cell.x;
406
+ const image = images[cell.index];
407
+ const text = textObjects[cell.index];
408
+ if (showIcon && image) {
409
+ image.set({
410
+ left: x,
411
+ top: cursorY + (rowHeight - iconSize) / 2,
412
+ });
413
+ objects.push(image);
414
+ x += iconSize + (showText ? horizontalGap : 0);
415
+ }
416
+ if (showText && text) {
417
+ text.set({
418
+ left: x,
419
+ top: cursorY + (rowHeight - text.getScaledHeight()) / 2,
420
+ });
421
+ objects.push(text);
422
+ }
423
+ });
424
+ cursorY += rowHeight + verticalGap;
425
+ });
426
+ }
427
+
428
+ const trailingGap =
429
+ layout === 'icon-text-split' ? itemGap : verticalGap;
430
+ const naturalHeight = Math.max(1, cursorY - trailingGap);
431
+ const configuredHeight = Number(normalized.height);
432
+ const height =
433
+ configuredHeight > 0
434
+ ? Math.max(1, this.toPx(configuredHeight))
435
+ : naturalHeight;
436
+ return this.createGroup(
437
+ objects,
438
+ width,
439
+ height,
440
+ true,
441
+ normalized._clipContent
442
+ );
443
+ }
444
+
445
+ private createGroup(
446
+ objects: fabric.Object[],
447
+ width: number,
448
+ height: number,
449
+ visible: boolean,
450
+ clipContent = false
451
+ ) {
452
+ const boundary = new fabric.Rect({
453
+ left: 0,
454
+ top: 0,
455
+ width,
456
+ height,
457
+ fill: 'rgba(0,0,0,0)',
458
+ strokeWidth: 0,
459
+ selectable: false,
460
+ evented: false,
461
+ });
462
+ const group = new fabric.Group([boundary], {
463
+ width,
464
+ height,
465
+ visible,
466
+ // Fabric 5 renders clipPath through the object cache.
467
+ objectCaching: clipContent,
468
+ subTargetCheck: false,
469
+ clipPath: clipContent
470
+ ? new fabric.Rect({
471
+ width,
472
+ height,
473
+ originX: 'center',
474
+ originY: 'center',
475
+ })
476
+ : undefined,
477
+ }) as ImageTextListGroup;
478
+
479
+ // Keep the configured boundary fixed. Overflowing content starts at the
480
+ // group's top edge and grows downward without changing the group size.
481
+ objects.forEach((object) => {
482
+ object.set({
483
+ left: (object.left || 0) - width / 2,
484
+ top: (object.top || 0) - height / 2,
485
+ });
486
+ object.group = group;
487
+ });
488
+ (group as any)._objects.push(...objects);
489
+ group.setCoords();
490
+ return group;
491
+ }
492
+
493
+ private flowRows(widths: number[], maxWidth: number, gap: number) {
494
+ const rows: Array<{
495
+ items: Array<{ index: number; x: number; width: number }>;
496
+ }> = [];
497
+ let row = {
498
+ items: [] as Array<{ index: number; x: number; width: number }>,
499
+ };
500
+ let x = 0;
501
+ widths.forEach((rawWidth, index) => {
502
+ const width = Math.min(Math.max(1, rawWidth), maxWidth);
503
+ if (row.items.length && x + width > maxWidth) {
504
+ rows.push(row);
505
+ row = { items: [] };
506
+ x = 0;
507
+ }
508
+ row.items.push({ index, x, width });
509
+ x += width + gap;
510
+ });
511
+ if (row.items.length) rows.push(row);
512
+ return rows;
513
+ }
514
+
515
+ private updateOriginSize(
516
+ group: ImageTextListGroup,
517
+ extension: ImageTextListOptions
518
+ ) {
519
+ const unit = getUnit(this.editor);
520
+ const origin = group._originSize || {};
521
+ group._originSize = {
522
+ ...origin,
523
+ [unit]: formatOriginValues(
524
+ {
525
+ ...(origin[unit] || {}),
526
+ width: extension.width,
527
+ height:
528
+ extension.height ??
529
+ (unit === 'px'
530
+ ? group.height
531
+ : this.editor.getSizeByUnit(group.height || 1)),
532
+ },
533
+ (this.editor as any).getPrecision?.()
534
+ ),
535
+ };
536
+ }
537
+
538
+ destroy() {}
539
+ }
540
+
541
+ export default ImageTextListPlugin;
@@ -45,11 +45,29 @@ class QrCodePlugin implements IPluginTempl {
45
45
  }
46
46
  }
47
47
 
48
- async hookTransformObjectEnd({ originObject, fabricObject }: { originObject: any, fabricObject: any }) {
49
- if (originObject.extensionType === 'qrcode') {
50
- this.initQrcodeEvents(fabricObject);
51
- }
52
- }
48
+ async hookTransformObjectEnd({ originObject, fabricObject }: { originObject: any, fabricObject: any }) {
49
+ if (originObject.extensionType === 'qrcode') {
50
+ this.initQrcodeEvents(fabricObject);
51
+ }
52
+ }
53
+
54
+ async hookImportAfter() {
55
+ const qrcodeObjects = this.canvas
56
+ .getObjects()
57
+ .filter(
58
+ (obj: any) =>
59
+ obj.type === 'image' && obj.extensionType === 'qrcode'
60
+ ) as fabric.Image[];
61
+
62
+ await Promise.all(
63
+ qrcodeObjects.map(async (imgEl) => {
64
+ this.initQrcodeEvents(imgEl);
65
+ await this._updateQrCodeImage(imgEl, true);
66
+ })
67
+ );
68
+
69
+ this.canvas.renderAll();
70
+ }
53
71
 
54
72
  async _getQrCodeResult(options: any): Promise<{ url: string; width: number; height: number }> {
55
73
  const zoom = this.canvas.getZoom() || 1;
@@ -123,11 +141,11 @@ class QrCodePlugin implements IPluginTempl {
123
141
  return options;
124
142
  }
125
143
 
126
- private async _updateQrCodeImage(imgEl: fabric.Image, immediate = false) {
127
- const extension = imgEl.get('extension');
128
- if (!extension) return;
129
- const updateFn = async () => {
130
- const currentWidth = imgEl.getScaledWidth();
144
+ private async _updateQrCodeImage(imgEl: fabric.Image, immediate = false) {
145
+ const extension = imgEl.get('extension');
146
+ if (!extension) return;
147
+ const updateFn = async () => {
148
+ const currentWidth = imgEl.getScaledWidth();
131
149
  const currentHeight = imgEl.getScaledHeight();
132
150
  const size = Math.max(currentWidth, currentHeight);
133
151
  const options = {
@@ -135,11 +153,11 @@ class QrCodePlugin implements IPluginTempl {
135
153
  width: size,
136
154
  height: size,
137
155
  };
138
- const paramsOption = this._paramsToOption(options);
139
- try {
140
- const url = await this._getBase64Str(paramsOption);
141
- await new Promise<void>((resolve) => {
142
- imgEl.setSrc(url, () => {
156
+ const paramsOption = this._paramsToOption(options);
157
+ try {
158
+ const url = await this._getBase64Str(paramsOption);
159
+ await new Promise<void>((resolve) => {
160
+ imgEl.setSrc(url, () => {
143
161
  this._setImageScale(imgEl, currentWidth, currentHeight);
144
162
  imgEl.set('extension', options);
145
163
  this.canvas.renderAll();