@sequent-org/moodboard 1.3.0 → 1.3.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sequent-org/moodboard",
3
- "version": "1.3.0",
3
+ "version": "1.3.3",
4
4
  "type": "module",
5
5
  "description": "Interactive moodboard",
6
6
  "main": "./src/index.js",
@@ -17,6 +17,85 @@ function rememberCursorPosition(manager, event) {
17
17
  manager.eventBus.emit(Events.UI.CursorMove, { x: event.x, y: event.y });
18
18
  }
19
19
 
20
+ function nowMs() {
21
+ if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
22
+ return performance.now();
23
+ }
24
+ return Date.now();
25
+ }
26
+
27
+ function isDropDebugEnabled() {
28
+ try {
29
+ if (typeof window === 'undefined') return false;
30
+ if (window.__MB_DND_DEBUG__ === true) return true;
31
+ if (window.localStorage && typeof window.localStorage.getItem === 'function') {
32
+ return window.localStorage.getItem('mb:dnd:debug') === '1';
33
+ }
34
+ } catch (_) {}
35
+ return false;
36
+ }
37
+
38
+ function createDropDiagnostics() {
39
+ return {
40
+ enabled: isDropDebugEnabled(),
41
+ dropId: `drop-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
42
+ startedAt: nowMs()
43
+ };
44
+ }
45
+
46
+ function logDropDebug(diagnostics, stage, payload = {}) {
47
+ if (!diagnostics?.enabled) return;
48
+ try {
49
+ const elapsedMs = Math.round(nowMs() - diagnostics.startedAt);
50
+ console.debug('[moodboard:dnd]', {
51
+ dropId: diagnostics.dropId,
52
+ stage,
53
+ elapsedMs,
54
+ ...payload
55
+ });
56
+ } catch (_) {}
57
+ }
58
+
59
+ const DROP_LIMITS = {
60
+ maxFilesPerDrop: 50,
61
+ maxFileSizeBytes: 50 * 1024 * 1024
62
+ };
63
+
64
+ function showDropWarning(manager, message, diagnostics, extra = {}) {
65
+ logDropDebug(diagnostics, 'drop_warning', { message, ...extra });
66
+ try {
67
+ const ws = (typeof window !== 'undefined' && window.moodboard && window.moodboard.workspaceManager)
68
+ ? window.moodboard.workspaceManager
69
+ : null;
70
+ if (ws && typeof ws.showNotification === 'function') {
71
+ ws.showNotification(message);
72
+ }
73
+ } catch (_) {}
74
+ }
75
+
76
+ async function mapWithConcurrency(items, limit, iterator) {
77
+ const safeLimit = Math.max(1, Number.isFinite(limit) ? Math.floor(limit) : 1);
78
+ const results = new Array(items.length);
79
+ let nextIndex = 0;
80
+
81
+ const worker = async () => {
82
+ while (true) {
83
+ const currentIndex = nextIndex;
84
+ nextIndex += 1;
85
+ if (currentIndex >= items.length) return;
86
+ results[currentIndex] = await iterator(items[currentIndex], currentIndex);
87
+ }
88
+ };
89
+
90
+ const workers = [];
91
+ const workersCount = Math.min(safeLimit, items.length);
92
+ for (let i = 0; i < workersCount; i += 1) {
93
+ workers.push(worker());
94
+ }
95
+ await Promise.all(workers);
96
+ return results;
97
+ }
98
+
20
99
  export class ToolEventRouter {
21
100
  static handleMouseDown(manager, event) {
22
101
  if (!manager.activeTool) return;
@@ -142,6 +221,10 @@ export class ToolEventRouter {
142
221
 
143
222
  static async handleDrop(manager, event) {
144
223
  event.preventDefault();
224
+ const diagnostics = createDropDiagnostics();
225
+ manager._dropSessionSeq = (manager._dropSessionSeq || 0) + 1;
226
+ const dropSession = manager._dropSessionSeq;
227
+ const isCurrentDrop = () => manager._dropSessionSeq === dropSession;
145
228
 
146
229
  const rect = manager.container.getBoundingClientRect();
147
230
  const x = event.clientX - rect.left;
@@ -150,9 +233,51 @@ export class ToolEventRouter {
150
233
  manager.eventBus.emit(Events.UI.CursorMove, { x, y });
151
234
 
152
235
  const dt = event.dataTransfer;
153
- if (!dt) return;
236
+ if (!dt) {
237
+ logDropDebug(diagnostics, 'drop_no_data_transfer');
238
+ return;
239
+ }
240
+ logDropDebug(diagnostics, 'drop_received', {
241
+ localX: Math.round(x),
242
+ localY: Math.round(y),
243
+ filesCount: dt.files ? dt.files.length : 0
244
+ });
245
+
246
+ const toWorldPosition = (screenX, screenY) => {
247
+ const world = manager.core?.pixi?.worldLayer || manager.core?.pixi?.app?.stage;
248
+ const scale = world?.scale?.x || 1;
249
+ if (!world) {
250
+ return { x: Math.round(screenX), y: Math.round(screenY) };
251
+ }
252
+ return {
253
+ x: Math.round((screenX - (world.x || 0)) / scale),
254
+ y: Math.round((screenY - (world.y || 0)) / scale)
255
+ };
256
+ };
257
+ const getFanOffset = (offsetIndex) => {
258
+ if (offsetIndex <= 0) return { dx: 0, dy: 0 };
259
+ const step = 25;
260
+ const directions = [
261
+ { x: 1, y: 0 },
262
+ { x: 1, y: 1 },
263
+ { x: 0, y: 1 },
264
+ { x: -1, y: 1 },
265
+ { x: -1, y: 0 },
266
+ { x: -1, y: -1 },
267
+ { x: 0, y: -1 },
268
+ { x: 1, y: -1 }
269
+ ];
270
+ const index = offsetIndex - 1;
271
+ const direction = directions[index % directions.length];
272
+ const ring = Math.floor(index / directions.length) + 1;
273
+ return { dx: direction.x * step * ring, dy: direction.y * step * ring };
274
+ };
154
275
 
155
276
  const emitAt = (src, name, imageId = null, offsetIndex = 0) => {
277
+ if (!isCurrentDrop()) {
278
+ logDropDebug(diagnostics, 'emit_skipped_stale_drop', { route: 'image', offsetIndex });
279
+ return;
280
+ }
156
281
  const offset = 25 * offsetIndex;
157
282
  manager.eventBus.emit(Events.UI.PasteImageAt, {
158
283
  x: x + offset,
@@ -164,45 +289,123 @@ export class ToolEventRouter {
164
289
  };
165
290
 
166
291
  const files = dt.files ? Array.from(dt.files) : [];
167
- const imageFiles = files.filter((file) => file.type && file.type.startsWith('image/'));
292
+ let limitedFiles = files;
293
+ if (limitedFiles.length > DROP_LIMITS.maxFilesPerDrop) {
294
+ showDropWarning(
295
+ manager,
296
+ `Обработаны первые ${DROP_LIMITS.maxFilesPerDrop} файлов из ${limitedFiles.length}`,
297
+ diagnostics,
298
+ { filesCount: limitedFiles.length, maxFilesPerDrop: DROP_LIMITS.maxFilesPerDrop }
299
+ );
300
+ limitedFiles = limitedFiles.slice(0, DROP_LIMITS.maxFilesPerDrop);
301
+ }
302
+ const oversized = limitedFiles.filter((file) => (file?.size || 0) > DROP_LIMITS.maxFileSizeBytes);
303
+ if (oversized.length > 0) {
304
+ showDropWarning(
305
+ manager,
306
+ `Пропущено ${oversized.length} файлов: размер каждого должен быть не более 50 МБ`,
307
+ diagnostics,
308
+ { oversizedCount: oversized.length, maxFileSizeBytes: DROP_LIMITS.maxFileSizeBytes }
309
+ );
310
+ limitedFiles = limitedFiles.filter((file) => (file?.size || 0) <= DROP_LIMITS.maxFileSizeBytes);
311
+ }
312
+
313
+ const imageFiles = limitedFiles.filter((file) => file.type && file.type.startsWith('image/'));
168
314
  if (imageFiles.length > 0) {
169
- let index = 0;
170
- for (const file of imageFiles) {
315
+ logDropDebug(diagnostics, 'route_image_files', { count: imageFiles.length });
316
+ const imagePlacements = await mapWithConcurrency(imageFiles, 2, async (file, index) => {
317
+ logDropDebug(diagnostics, 'image_upload_start', {
318
+ fileName: file.name || 'image',
319
+ fileSize: file.size || 0,
320
+ mimeType: file.type || null
321
+ });
171
322
  try {
172
323
  if (manager.core && manager.core.imageUploadService) {
173
324
  const uploadResult = await manager.core.imageUploadService.uploadImage(file, file.name || 'image');
174
- emitAt(uploadResult.url, uploadResult.name, uploadResult.imageId || uploadResult.id, index++);
325
+ if (!isCurrentDrop()) {
326
+ logDropDebug(diagnostics, 'image_upload_stale_drop_ignored', {
327
+ fileName: uploadResult?.name || file.name || 'image'
328
+ });
329
+ return null;
330
+ }
331
+ logDropDebug(diagnostics, 'image_upload_success', {
332
+ fileName: uploadResult?.name || file.name || 'image',
333
+ imageId: uploadResult?.imageId || uploadResult?.id || null
334
+ });
335
+ return {
336
+ src: uploadResult.url,
337
+ name: uploadResult.name,
338
+ imageId: uploadResult.imageId || uploadResult.id || null,
339
+ index
340
+ };
175
341
  } else {
176
- await new Promise((resolve) => {
342
+ const localSrc = await new Promise((resolve) => {
177
343
  const reader = new FileReader();
178
344
  reader.onload = () => {
179
- emitAt(reader.result, file.name || 'image', null, index++);
180
- resolve();
345
+ resolve(reader.result);
181
346
  };
182
347
  reader.readAsDataURL(file);
183
348
  });
349
+ if (!isCurrentDrop()) {
350
+ logDropDebug(diagnostics, 'image_local_fallback_stale_drop_ignored', {
351
+ fileName: file.name || 'image'
352
+ });
353
+ return null;
354
+ }
355
+ logDropDebug(diagnostics, 'image_local_fallback_success', {
356
+ fileName: file.name || 'image'
357
+ });
358
+ return {
359
+ src: localSrc,
360
+ name: file.name || 'image',
361
+ imageId: null,
362
+ index
363
+ };
184
364
  }
185
365
  } catch (error) {
186
366
  console.warn('Ошибка загрузки изображения через drag-and-drop:', error);
187
- await new Promise((resolve) => {
367
+ logDropDebug(diagnostics, 'image_upload_error', {
368
+ fileName: file.name || 'image',
369
+ message: error?.message || String(error)
370
+ });
371
+ const fallbackSrc = await new Promise((resolve) => {
188
372
  const reader = new FileReader();
189
373
  reader.onload = () => {
190
- emitAt(reader.result, file.name || 'image', null, index++);
191
- resolve();
374
+ resolve(reader.result);
192
375
  };
193
376
  reader.readAsDataURL(file);
194
377
  });
378
+ if (!isCurrentDrop()) {
379
+ logDropDebug(diagnostics, 'image_error_fallback_stale_drop_ignored', {
380
+ fileName: file.name || 'image'
381
+ });
382
+ return null;
383
+ }
384
+ logDropDebug(diagnostics, 'image_error_fallback_success', {
385
+ fileName: file.name || 'image'
386
+ });
387
+ return {
388
+ src: fallbackSrc,
389
+ name: file.name || 'image',
390
+ imageId: null,
391
+ index
392
+ };
195
393
  }
394
+ });
395
+ for (const placement of imagePlacements) {
396
+ if (!placement) continue;
397
+ emitAt(placement.src, placement.name, placement.imageId, placement.index);
196
398
  }
399
+ logDropDebug(diagnostics, 'drop_done', { route: 'image_files', itemsProcessed: imageFiles.length });
197
400
  return;
198
401
  }
199
402
 
200
- const nonImageFiles = files.filter((file) => !file.type || !file.type.startsWith('image/'));
403
+ const nonImageFiles = limitedFiles.filter((file) => !file.type || !file.type.startsWith('image/'));
201
404
  if (nonImageFiles.length > 0) {
202
- let index = 0;
203
- for (const file of nonImageFiles) {
204
- const offset = 25 * index++;
205
- const position = { x: x + offset, y: y + offset };
405
+ logDropDebug(diagnostics, 'route_non_image_files', { count: nonImageFiles.length });
406
+ const filePlacements = await mapWithConcurrency(nonImageFiles, 2, async (file, index) => {
407
+ const fanOffset = getFanOffset(index);
408
+ const worldPoint = toWorldPosition(x + fanOffset.dx, y + fanOffset.dy);
206
409
  const fallbackProps = {
207
410
  fileName: file.name || 'file',
208
411
  fileSize: file.size || 0,
@@ -212,13 +415,40 @@ export class ToolEventRouter {
212
415
  width: 120,
213
416
  height: 140
214
417
  };
418
+ const position = {
419
+ x: Math.round(worldPoint.x - fallbackProps.width / 2),
420
+ y: Math.round(worldPoint.y - fallbackProps.height / 2)
421
+ };
422
+ logDropDebug(diagnostics, 'file_prepare', {
423
+ fileName: fallbackProps.fileName,
424
+ worldX: worldPoint.x,
425
+ worldY: worldPoint.y,
426
+ placeX: position.x,
427
+ placeY: position.y
428
+ });
215
429
  try {
216
430
  if (manager.core && manager.core.fileUploadService) {
217
431
  const uploadResult = await manager.core.fileUploadService.uploadFile(file, file.name || 'file');
218
- manager.eventBus.emit(Events.UI.ToolbarAction, {
432
+ if (!isCurrentDrop()) {
433
+ logDropDebug(diagnostics, 'file_upload_stale_drop_ignored', {
434
+ fileName: uploadResult?.name || fallbackProps.fileName
435
+ });
436
+ return null;
437
+ }
438
+ const objectWidth = fallbackProps.width;
439
+ const objectHeight = fallbackProps.height;
440
+ const centeredPosition = {
441
+ x: Math.round(worldPoint.x - objectWidth / 2),
442
+ y: Math.round(worldPoint.y - objectHeight / 2)
443
+ };
444
+ logDropDebug(diagnostics, 'file_upload_success', {
445
+ fileName: uploadResult?.name || fallbackProps.fileName,
446
+ fileId: uploadResult?.fileId || uploadResult?.id || null
447
+ });
448
+ return {
219
449
  type: 'file',
220
450
  id: 'file',
221
- position,
451
+ position: centeredPosition,
222
452
  properties: {
223
453
  fileName: uploadResult.name,
224
454
  fileSize: uploadResult.size,
@@ -229,35 +459,65 @@ export class ToolEventRouter {
229
459
  height: 140
230
460
  },
231
461
  fileId: uploadResult.fileId || uploadResult.id || null
232
- });
462
+ };
233
463
  } else {
234
- manager.eventBus.emit(Events.UI.ToolbarAction, {
464
+ if (!isCurrentDrop()) {
465
+ logDropDebug(diagnostics, 'file_local_fallback_stale_drop_ignored', {
466
+ fileName: fallbackProps.fileName
467
+ });
468
+ return null;
469
+ }
470
+ logDropDebug(diagnostics, 'file_local_fallback_success', {
471
+ fileName: fallbackProps.fileName
472
+ });
473
+ return {
235
474
  type: 'file',
236
475
  id: 'file',
237
476
  position,
238
477
  properties: fallbackProps
239
- });
478
+ };
240
479
  }
241
480
  } catch (error) {
242
481
  console.warn('Ошибка загрузки файла через drag-and-drop:', error);
243
- manager.eventBus.emit(Events.UI.ToolbarAction, {
482
+ logDropDebug(diagnostics, 'file_upload_error', {
483
+ fileName: fallbackProps.fileName,
484
+ message: error?.message || String(error)
485
+ });
486
+ if (!isCurrentDrop()) {
487
+ logDropDebug(diagnostics, 'file_error_fallback_stale_drop_ignored', {
488
+ fileName: fallbackProps.fileName
489
+ });
490
+ return null;
491
+ }
492
+ logDropDebug(diagnostics, 'file_error_fallback_success', {
493
+ fileName: fallbackProps.fileName
494
+ });
495
+ return {
244
496
  type: 'file',
245
497
  id: 'file',
246
498
  position,
247
499
  properties: fallbackProps
248
- });
500
+ };
249
501
  }
502
+ });
503
+ for (const actionPayload of filePlacements) {
504
+ if (!actionPayload) continue;
505
+ if (!isCurrentDrop()) break;
506
+ manager.eventBus.emit(Events.UI.ToolbarAction, actionPayload);
250
507
  }
508
+ logDropDebug(diagnostics, 'drop_done', { route: 'non_image_files', itemsProcessed: nonImageFiles.length });
251
509
  return;
252
510
  }
253
511
 
254
512
  const html = dt.getData('text/html');
255
513
  if (html && html.includes('<img')) {
514
+ logDropDebug(diagnostics, 'route_html_image');
256
515
  const match = html.match(/<img[^>]*src\s*=\s*"([^"]+)"/i);
257
516
  if (match && match[1]) {
258
517
  const url = match[1];
259
518
  if (/^data:image\//i.test(url)) {
260
519
  emitAt(url, 'clipboard-image.png');
520
+ logDropDebug(diagnostics, 'drop_done', { route: 'html_data_image' });
261
521
  return;
262
522
  }
263
523
  if (/^https?:\/\//i.test(url)) {
@@ -270,8 +530,10 @@ export class ToolEventRouter {
270
530
  reader.readAsDataURL(blob);
271
531
  });
272
532
  emitAt(dataUrl, url.split('/').pop() || 'image');
533
+ logDropDebug(diagnostics, 'drop_done', { route: 'html_http_image_fetched' });
273
534
  } catch (_) {
274
535
  emitAt(url, url.split('/').pop() || 'image');
536
+ logDropDebug(diagnostics, 'drop_done', { route: 'html_http_image_direct' });
275
537
  }
276
538
  return;
277
539
  }
@@ -280,6 +542,7 @@ export class ToolEventRouter {
280
542
 
281
543
  const uriList = dt.getData('text/uri-list') || '';
282
544
  if (uriList) {
545
+ logDropDebug(diagnostics, 'route_uri_list');
283
546
  const lines = uriList.split('\n').filter((line) => !!line && !line.startsWith('#'));
284
547
  const urls = lines.filter((line) => /^https?:\/\//i.test(line));
285
548
  let index = 0;
@@ -299,17 +562,22 @@ export class ToolEventRouter {
299
562
  emitAt(url, url.split('/').pop() || 'image', index++);
300
563
  }
301
564
  }
302
- if (index > 0) return;
565
+ if (index > 0) {
566
+ logDropDebug(diagnostics, 'drop_done', { route: 'uri_list_images', itemsProcessed: index });
567
+ return;
568
+ }
303
569
  }
304
570
 
305
571
  const text = dt.getData('text/plain') || '';
306
572
  if (text) {
573
+ logDropDebug(diagnostics, 'route_text_plain');
307
574
  const trimmed = text.trim();
308
575
  const isDataUrl = /^data:image\//i.test(trimmed);
309
576
  const isHttpUrl = /^https?:\/\//i.test(trimmed);
310
577
  const looksLikeImage = /(png|jpe?g|gif|webp|bmp|svg)(\?.*)?$/i.test(trimmed);
311
578
  if (isDataUrl) {
312
579
  emitAt(trimmed, 'clipboard-image.png');
580
+ logDropDebug(diagnostics, 'drop_done', { route: 'text_data_image' });
313
581
  return;
314
582
  }
315
583
  if (isHttpUrl && looksLikeImage) {
@@ -322,11 +590,14 @@ export class ToolEventRouter {
322
590
  reader.readAsDataURL(blob);
323
591
  });
324
592
  emitAt(dataUrl, trimmed.split('/').pop() || 'image');
593
+ logDropDebug(diagnostics, 'drop_done', { route: 'text_http_image_fetched' });
325
594
  } catch (_) {
326
595
  emitAt(trimmed, trimmed.split('/').pop() || 'image');
596
+ logDropDebug(diagnostics, 'drop_done', { route: 'text_http_image_direct' });
327
597
  }
328
598
  }
329
599
  }
600
+ logDropDebug(diagnostics, 'drop_done', { route: 'no_supported_payload' });
330
601
  }
331
602
 
332
603
  static handleKeyDown(manager, event) {
package/src/ui/Toolbar.js CHANGED
@@ -46,7 +46,13 @@ export class Toolbar {
46
46
  console.error('❌ Ошибка загрузки иконок:', error);
47
47
  }
48
48
 
49
- this._toolActivatedHandler = ({ tool }) => this.setActiveToolbarButton(tool);
49
+ this._toolActivatedHandler = ({ tool }) => {
50
+ this.setActiveToolbarButton(tool);
51
+ // Draw palette must stay open only while draw tool is active.
52
+ if (tool !== 'draw') {
53
+ this.closeDrawPopup();
54
+ }
55
+ };
50
56
  this.createToolbar();
51
57
  this.attachEvents();
52
58
  this.setupHistoryEvents();
@@ -133,9 +139,13 @@ export class Toolbar {
133
139
  const isDrawButton = e.target.closest && e.target.closest('.moodboard-toolbar__button--pencil');
134
140
  const isEmojiButton = e.target.closest && e.target.closest('.moodboard-toolbar__button--emoji');
135
141
  const isFrameButton = e.target.closest && e.target.closest('.moodboard-toolbar__button--frame');
142
+ const isDrawActive = !!(this.element && this.element.querySelector('.moodboard-toolbar__button--pencil.moodboard-toolbar__button--active'));
143
+
136
144
  if (!isInsideToolbar && !isInsideShapesPopup && !isShapesButton && !isInsideDrawPopup && !isDrawButton && !isInsideEmojiPopup && !isEmojiButton && !isInsideFramePopup && !isFrameButton) {
137
145
  this.closeShapesPopup();
138
- this.closeDrawPopup();
146
+ if (!isDrawActive) {
147
+ this.closeDrawPopup();
148
+ }
139
149
  this.closeEmojiPopup();
140
150
  this.closeFramePopup();
141
151
  }
@@ -232,6 +232,9 @@ export class ToolbarPopupsController {
232
232
  const row2 = document.createElement('div');
233
233
  row2.className = 'moodboard-draw__row';
234
234
  this.toolbar.drawRow2 = row2;
235
+ const clearActivePresetButtons = () => {
236
+ row2.querySelectorAll('.moodboard-draw__btn--active').forEach((el) => el.classList.remove('moodboard-draw__btn--active'));
237
+ };
235
238
 
236
239
  const pencilPresetEl = document.createElement('div');
237
240
  pencilPresetEl.className = 'moodboard-draw__row';
@@ -267,7 +270,7 @@ export class ToolbarPopupsController {
267
270
  btn.appendChild(holder);
268
271
  btn.addEventListener('click', () => {
269
272
  this.toolbar.animateButton(btn);
270
- pencilPresetEl.querySelectorAll('.moodboard-draw__btn--active').forEach((el) => el.classList.remove('moodboard-draw__btn--active'));
273
+ clearActivePresetButtons();
271
274
  btn.classList.add('moodboard-draw__btn--active');
272
275
  const width = s.width;
273
276
  const color = parseInt(s.color.replace('#', ''), 16);
@@ -291,7 +294,7 @@ export class ToolbarPopupsController {
291
294
  btn.appendChild(sw);
292
295
  btn.addEventListener('click', () => {
293
296
  this.toolbar.animateButton(btn);
294
- markerPresetEl.querySelectorAll('.moodboard-draw__btn--active').forEach((el) => el.classList.remove('moodboard-draw__btn--active'));
297
+ clearActivePresetButtons();
295
298
  btn.classList.add('moodboard-draw__btn--active');
296
299
  const color = parseInt(s.color.replace('#', ''), 16);
297
300
  this.toolbar.eventBus.emit(Events.Draw.BrushSet, { mode: 'marker', color, width: 8 });