labellife-design-tool 2.5.7 → 2.7.0

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/README.md CHANGED
@@ -259,6 +259,48 @@ const dispose = store.on('change', (data) => {
259
259
  dispose(); // Remove listener
260
260
  ```
261
261
 
262
+ ### Activity Log
263
+
264
+ The store keeps a plain-English record of what the user did, one sentence per
265
+ meaningful action, for analytics. It never contains image data or image URLs.
266
+
267
+ ```js
268
+ store.getActivityLog();
269
+ // [
270
+ // 'Started from a template, 50 x 30 mm, 1 page, with 2 texts ("Happy Birthday", "Name"), 1 image.',
271
+ // 'The template asked for 1 variable: "First Name" (text).',
272
+ // 'Selected template "Birthday Card".', // added by the host via recordActivity
273
+ // 'User entered "Anna" for variable "First Name".',
274
+ // 'Added a text "Welcome".',
275
+ // 'Changed the font size of the text "Welcome" from 20 to 32.',
276
+ // 'Added an image (uploaded by the user).',
277
+ // 'Final label: 3 texts, 2 images, 50 x 30 mm.',
278
+ // ]
279
+
280
+ store.recordActivity('Selected template "Birthday Card".'); // host adds its own sentence
281
+ store.clearActivityLog();
282
+ ```
283
+
284
+ - Each committed change (the same moments the undo history records) becomes one sentence. Quick repeats on the
285
+ same element and property within 1.5 s merge into one sentence, and a change that returns to where it started
286
+ disappears.
287
+ - `loadJSON()` and `store.clear()` start a new log. Undo and redo add `Undid the last change.` / `Redid the last change.`
288
+ - Input-field popup answers are logged for the built-in dialogs and for host-supplied ones, e.g.
289
+ `User chose "Option A" for variable "Size".`, `User skipped variable "Photo".`
290
+ - Sentences are always English (not translated) and the log only lives in memory.
291
+
292
+ Options (call once at startup; typed text can contain personal data, so you can turn it off):
293
+
294
+ ```js
295
+ import { setActivityLogOptions } from 'labellife-design-tool';
296
+
297
+ setActivityLogOptions({
298
+ includeTextContent: true, // false: texts and answers are replaced by "(value hidden)" / left out
299
+ maxTextLength: 40, // longer texts are cut with an ellipsis
300
+ maxEntries: 300, // oldest actions are dropped beyond this
301
+ });
302
+ ```
303
+
262
304
  ### Font Management
263
305
 
264
306
  ```js
@@ -9,6 +9,7 @@ var material = require('@mui/material');
9
9
  var CloseIcon = require('@mui/icons-material/Close');
10
10
  var jsxRuntime = require('react/jsx-runtime');
11
11
  var Konva = require('konva');
12
+ var mobxStateTree = require('mobx-state-tree');
12
13
  var CloudUploadIcon = require('@mui/icons-material/CloudUpload');
13
14
  var ArrowBackIcon = require('@mui/icons-material/ArrowBack');
14
15
 
@@ -205,6 +206,179 @@ function t(key, defaultValue) {
205
206
  return defaultValue || key;
206
207
  }
207
208
 
209
+ function clip(text, max) {
210
+ var s = String(text == null ? '' : text);
211
+ return s.length > max ? "".concat(s.slice(0, max), "\u2026") : s;
212
+ }
213
+ function imageSource(src) {
214
+ var s = String(src || '');
215
+ if (s.startsWith('data:') || s.startsWith('blob:')) return 'uploaded';
216
+ if (s.toLowerCase().includes('unsplash')) return 'stock photo';
217
+ return '';
218
+ }
219
+ var _short = function _short(v) {
220
+ var s = String(v == null ? '' : v);
221
+ return "".concat(s.length, ":").concat(s.slice(0, 40));
222
+ };
223
+ var isLocked = function isLocked(el) {
224
+ return el.draggable === false && el.resizable === false && el.contentEditable === false && el.styleEditable === false;
225
+ };
226
+ var quotedText = function quotedText(el, n, opts) {
227
+ return opts.includeTextContent && el.text ? "\"".concat(clip(el.text, opts.maxTextLength), "\"") : n;
228
+ };
229
+
230
+ // One row per property group: how to read its value, and how to word the change.
231
+ // A new property is one new row. `render(ctx)` returns (from, to) => sentence so a
232
+ // merged entry can be re-worded with its first `from` and last `to`.
233
+ var ROWS = [{
234
+ key: 'text',
235
+ props: ['text'],
236
+ render: function render(_ref8) {
237
+ var opts = _ref8.opts;
238
+ return function (f, t) {
239
+ return opts.includeTextContent ? "Changed the text \"".concat(clip(f, opts.maxTextLength), "\" to \"").concat(clip(t, opts.maxTextLength), "\".") : 'Changed the text.';
240
+ };
241
+ }
242
+ }, {
243
+ key: 'fontFamily',
244
+ props: ['fontFamily'],
245
+ render: function render(_ref9) {
246
+ var n = _ref9.n;
247
+ return function (f, t) {
248
+ return "Changed the font of ".concat(n, " to ").concat(t, ".");
249
+ };
250
+ }
251
+ }, {
252
+ key: 'fontSize',
253
+ props: ['fontSize'],
254
+ render: function render(_ref0) {
255
+ var n = _ref0.n;
256
+ return function (f, t) {
257
+ return "Changed the font size of ".concat(n, " from ").concat(f, " to ").concat(t, ".");
258
+ };
259
+ }
260
+ }, {
261
+ key: 'fill',
262
+ props: ['fill'],
263
+ render: function render(_ref1) {
264
+ var n = _ref1.n;
265
+ return function (f, t) {
266
+ return "Changed the colour of ".concat(n, " to ").concat(t, ".");
267
+ };
268
+ }
269
+ }, {
270
+ key: 'position',
271
+ props: ['x', 'y'],
272
+ render: function render(_ref10) {
273
+ var n = _ref10.n;
274
+ return function () {
275
+ return "Moved ".concat(n, ".");
276
+ };
277
+ }
278
+ }, {
279
+ key: 'size',
280
+ props: ['width', 'height'],
281
+ render: function render(_ref11) {
282
+ var n = _ref11.n;
283
+ return function () {
284
+ return "Resized ".concat(n, ".");
285
+ };
286
+ }
287
+ }, {
288
+ key: 'rotation',
289
+ props: ['rotation'],
290
+ render: function render(_ref12) {
291
+ var n = _ref12.n;
292
+ return function (f, t) {
293
+ return "Rotated ".concat(n, " to ").concat(t, " degrees.");
294
+ };
295
+ }
296
+ }, {
297
+ key: 'visible',
298
+ props: ['visible'],
299
+ render: function render(_ref13) {
300
+ var n = _ref13.n;
301
+ return function (f, t) {
302
+ return t ? "Showed ".concat(n, ".") : "Hid ".concat(n, ".");
303
+ };
304
+ }
305
+ }, {
306
+ key: 'lock',
307
+ props: ['draggable', 'resizable', 'contentEditable', 'styleEditable'],
308
+ value: isLocked,
309
+ render: function render(_ref14) {
310
+ var n = _ref14.n;
311
+ return function (f, t) {
312
+ return t ? "Locked ".concat(n, ".") : "Unlocked ".concat(n, ".");
313
+ };
314
+ }
315
+ }, {
316
+ key: 'crop',
317
+ props: ['cropX', 'cropY', 'cropWidth', 'cropHeight'],
318
+ render: function render(_ref15) {
319
+ var n = _ref15.n;
320
+ return function () {
321
+ return "Cropped ".concat(n, ".");
322
+ };
323
+ }
324
+ }, {
325
+ key: 'clipSrc',
326
+ props: ['clipSrc'],
327
+ render: function render(_ref16) {
328
+ var n = _ref16.n;
329
+ return function (f, t) {
330
+ return t ? "Applied a mask to ".concat(n, ".") : "Removed the mask from ".concat(n, ".");
331
+ };
332
+ }
333
+ }, {
334
+ key: 'curveEnabled',
335
+ props: ['curveEnabled'],
336
+ render: function render(_ref17) {
337
+ var n = _ref17.n,
338
+ next = _ref17.next,
339
+ opts = _ref17.opts;
340
+ return function (f, t) {
341
+ return t ? "Applied curved text to ".concat(quotedText(next, n, opts), ".") : "Removed the curve from ".concat(n, ".");
342
+ };
343
+ }
344
+ }, {
345
+ key: 'shadowEnabled',
346
+ props: ['shadowEnabled'],
347
+ render: function render(_ref18) {
348
+ var n = _ref18.n;
349
+ return function (f, t) {
350
+ return t ? "Added a shadow to ".concat(n, ".") : "Removed the shadow from ".concat(n, ".");
351
+ };
352
+ }
353
+ }, {
354
+ key: 'grayscaleEnabled',
355
+ props: ['grayscaleEnabled'],
356
+ render: function render(_ref19) {
357
+ var n = _ref19.n;
358
+ return function (f, t) {
359
+ return t ? "Made ".concat(n, " grayscale.") : "Removed the grayscale from ".concat(n, ".");
360
+ };
361
+ }
362
+ }, {
363
+ key: 'src',
364
+ props: ['src'],
365
+ value: function value(el) {
366
+ return _short(el.src);
367
+ },
368
+ render: function render(_ref20) {
369
+ var n = _ref20.n,
370
+ next = _ref20.next;
371
+ return function () {
372
+ var source = imageSource(next.src);
373
+ var note = source === 'uploaded' ? ' (uploaded by the user)' : source ? " (".concat(source, ")") : '';
374
+ return "Replaced ".concat(n).concat(note, ".");
375
+ };
376
+ }
377
+ }];
378
+ new Set(['id', 'type', 'custom', 'children'].concat(_toConsumableArray(ROWS.flatMap(function (r) {
379
+ return r.props;
380
+ }))));
381
+
208
382
  // ── Input Fields Dialog Config ───────────────────────────────────────
209
383
  var INPUT_FIELDS_CONFIG_KEY = '__labellife_input_fields_config__';
210
384
  if (typeof window !== 'undefined' && !window[INPUT_FIELDS_CONFIG_KEY]) {
@@ -1249,10 +1423,25 @@ function computeCurvedCacheBounds(element) {
1249
1423
  function syncHeightKeepingCenter(element, newHeight) {
1250
1424
  if (Math.abs(newHeight - element.height) <= 1) return;
1251
1425
  var deltaY = (newHeight - element.height) / 2;
1252
- element.set({
1426
+ var attrs = {
1253
1427
  height: newHeight,
1254
1428
  y: element.y - deltaY
1255
- });
1429
+ };
1430
+ element.set(attrs);
1431
+ // An automatic re-layout, not a user action: keep it out of the activity log.
1432
+ if (element.store && element.store.syncActivityBaseline) {
1433
+ element.store.syncActivityBaseline(element.id, attrs);
1434
+ }
1435
+ }
1436
+
1437
+ // Safari doesn't make a webfont available to canvas (not even to measureText) until some
1438
+ // canvas has actually drawn text with it, so loading alone isn't enough: draw once on a
1439
+ // hidden canvas to activate the face, then measure.
1440
+ var _scratchCtx = null;
1441
+ function primeCanvasFont(font, text) {
1442
+ if (!_scratchCtx) _scratchCtx = document.createElement('canvas').getContext('2d');
1443
+ _scratchCtx.font = font;
1444
+ _scratchCtx.fillText(text || 'Hamburgefonstiv', 0, 0);
1256
1445
  }
1257
1446
 
1258
1447
  // Safari can resolve document.fonts.load() (and fire loadingdone) before the canvas
@@ -1272,6 +1461,7 @@ function waitForCanvasFont(fontSpec, family, sample, isCancelled) {
1272
1461
  var frames = 0;
1273
1462
  var _check = function check() {
1274
1463
  if (isCancelled() || frames >= FONT_READY_MAX_FRAMES) return resolve();
1464
+ primeCanvasFont("".concat(fontSpec, " \"").concat(family, "\", serif"), text);
1275
1465
  var withFont = widthWith("".concat(fontSpec, " \"").concat(family, "\", serif"));
1276
1466
  var withFallbackSerif = widthWith("".concat(fontSpec, " serif"));
1277
1467
  var withFallbackSans = widthWith("".concat(fontSpec, " sans-serif"));
@@ -1282,6 +1472,28 @@ function waitForCanvasFont(fontSpec, family, sample, isCancelled) {
1282
1472
  _check();
1283
1473
  });
1284
1474
  }
1475
+
1476
+ // TEMPORARY font-timing diagnostics. Enable in the browser console with
1477
+ // window.__labellifeFontDebug = true
1478
+ // before loading a template, then copy the "[font-debug]" lines. Remove once Safari is sorted.
1479
+ function fontDebug(label, element, node) {
1480
+ if (typeof window === 'undefined' || !window.__labellifeFontDebug) return;
1481
+ try {
1482
+ var family = element.fontFamily;
1483
+ var faces = [];
1484
+ document.fonts.forEach(function (f) {
1485
+ if (f.family.replace(/["']/g, '') === family) faces.push("".concat(f.weight, "/").concat(f.status, "/").concat(f.unicodeRange.slice(0, 18)));
1486
+ });
1487
+ var lines = node && node.textArr ? node.textArr.map(function (l) {
1488
+ return Math.round(l.width);
1489
+ }) : null;
1490
+ // eslint-disable-next-line no-console
1491
+ console.log("[font-debug] t=".concat(Math.round(performance.now()), " ").concat(label, " family=\"").concat(family, "\" ") + "check=".concat(document.fonts.check("16px \"".concat(family, "\"")), " faces=").concat(JSON.stringify(faces), " ") + "boxW=".concat(Math.round(element.width), " nodeW=").concat(node ? Math.round(node.width()) : '-', " ") + "lineWidths=".concat(JSON.stringify(lines), " lines=").concat(lines ? lines.length : '-'));
1492
+ } catch (e) {
1493
+ // eslint-disable-next-line no-console
1494
+ console.log('[font-debug] failed', e);
1495
+ }
1496
+ }
1285
1497
  var TextElementComponent = mobxReactLite.observer(function (_ref) {
1286
1498
  var _element$backgroundOp;
1287
1499
  var element = _ref.element;
@@ -1309,6 +1521,7 @@ var TextElementComponent = mobxReactLite.observer(function (_ref) {
1309
1521
  var _node$getLayer2;
1310
1522
  var node = textRef.current;
1311
1523
  if (!node) return;
1524
+ fontDebug('relayout:before', element, node);
1312
1525
 
1313
1526
  // CurvedText's sceneFunc re-measures glyphs via ctx.measureText on
1314
1527
  // every draw (no internal cached layout like Konva.Text has), so
@@ -1319,9 +1532,21 @@ var TextElementComponent = mobxReactLite.observer(function (_ref) {
1319
1532
  (_node$getLayer = node.getLayer()) === null || _node$getLayer === void 0 || _node$getLayer.batchDraw();
1320
1533
  return;
1321
1534
  }
1322
- var f = node.fontFamily();
1323
- node.fontFamily('serif');
1324
- node.fontFamily(f);
1535
+
1536
+ // Re-run Konva's own layout directly — what changing `align` does, which is the manual
1537
+ // workaround that fixes this in Safari. Toggling fontFamily is the fallback if the
1538
+ // private method is ever removed.
1539
+ if (typeof node._getContextFont === 'function') {
1540
+ primeCanvasFont(node._getContextFont(), node.text());
1541
+ }
1542
+ if (typeof node._setTextData === 'function') {
1543
+ node._setTextData();
1544
+ } else {
1545
+ var f = node.fontFamily();
1546
+ node.fontFamily('serif');
1547
+ node.fontFamily(f);
1548
+ }
1549
+ fontDebug('relayout:after', element, node);
1325
1550
  var h = node.height();
1326
1551
  if (h > 0) {
1327
1552
  setTextHeight(h);
@@ -1333,12 +1558,16 @@ var TextElementComponent = mobxReactLite.observer(function (_ref) {
1333
1558
  }
1334
1559
  (_node$getLayer2 = node.getLayer()) === null || _node$getLayer2 === void 0 || _node$getLayer2.batchDraw();
1335
1560
  };
1561
+ React.useEffect(function () {
1562
+ fontDebug('mount', element, textRef.current);
1563
+ }, []);
1336
1564
 
1337
1565
  // Any font finishing a load (covers fonts requested elsewhere, e.g. store.loadFont).
1338
1566
  React.useEffect(function () {
1339
1567
  // Two frames' delay: Safari's canvas can still be on the fallback at event time.
1340
1568
  var onFontLoaded = function onFontLoaded() {
1341
- return requestAnimationFrame(function () {
1569
+ fontDebug('loadingdone', element, textRef.current);
1570
+ requestAnimationFrame(function () {
1342
1571
  return requestAnimationFrame(function () {
1343
1572
  var _relayoutRef$current;
1344
1573
  return (_relayoutRef$current = relayoutRef.current) === null || _relayoutRef$current === void 0 ? void 0 : _relayoutRef$current.call(relayoutRef);
@@ -1369,8 +1598,17 @@ var TextElementComponent = mobxReactLite.observer(function (_ref) {
1369
1598
  var _relayoutRef$current2;
1370
1599
  if (!cancelled) (_relayoutRef$current2 = relayoutRef.current) === null || _relayoutRef$current2 === void 0 || _relayoutRef$current2.call(relayoutRef);
1371
1600
  })["catch"](function () {});
1601
+ // Safari can still be on fallback metrics after the checks above, and re-measuring is
1602
+ // idempotent, so repeat a few times while the page settles.
1603
+ var retryTimers = [300, 1000, 2500].map(function (ms) {
1604
+ return setTimeout(function () {
1605
+ var _relayoutRef$current3;
1606
+ if (!cancelled) (_relayoutRef$current3 = relayoutRef.current) === null || _relayoutRef$current3 === void 0 || _relayoutRef$current3.call(relayoutRef);
1607
+ }, ms);
1608
+ });
1372
1609
  return function () {
1373
1610
  cancelled = true;
1611
+ retryTimers.forEach(clearTimeout);
1374
1612
  };
1375
1613
  }, [element.fontFamily, element.fontWeight, element.fontStyle]);
1376
1614
 
@@ -1552,10 +1790,10 @@ var TextElementComponent = mobxReactLite.observer(function (_ref) {
1552
1790
  var cancel = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
1553
1791
  if (removed) return;
1554
1792
  removed = true;
1555
- element.set({
1556
- text: cancel ? originalText : textarea.value
1793
+ element.finishEdit({
1794
+ text: cancel ? originalText : textarea.value,
1795
+ originalText: originalText
1557
1796
  });
1558
- element.toggleEditMode(false);
1559
1797
  if (textareaRef.current === textarea) textareaRef.current = null;
1560
1798
  if (textarea.parentNode) {
1561
1799
  textarea.parentNode.removeChild(textarea);
@@ -2855,6 +3093,17 @@ var InputFieldsDialog = mobxReactLite.observer(function (_ref2) {
2855
3093
  var config = getInputFieldsConfig();
2856
3094
  var pendingFields = store._pendingInputFields || [];
2857
3095
 
3096
+ // Plain-English activity log (see model/activity-log.js). Called after the
3097
+ // element has been updated so the log can re-baseline past that change.
3098
+ var logAnswer = function logAnswer(action, el, value) {
3099
+ if (typeof store.logPopupAnswer !== 'function') return;
3100
+ store.logPopupAnswer({
3101
+ action: action,
3102
+ field: el ? mobxStateTree.getSnapshot(el) : undefined,
3103
+ value: value
3104
+ });
3105
+ };
3106
+
2858
3107
  // When disabled, clear any pending fields so they are treated as skipped
2859
3108
  React.useEffect(function () {
2860
3109
  if (!enabled && pendingFields.length > 0) {
@@ -2910,6 +3159,7 @@ var InputFieldsDialog = mobxReactLite.observer(function (_ref2) {
2910
3159
  text: previousValue || ''
2911
3160
  });
2912
3161
  }
3162
+ logAnswer('back', el);
2913
3163
  isGoingBackRef.current = true;
2914
3164
  store._unresolveInputField(el);
2915
3165
  }
@@ -2957,9 +3207,11 @@ var InputFieldsDialog = mobxReactLite.observer(function (_ref2) {
2957
3207
  });
2958
3208
  }
2959
3209
  }
3210
+ logAnswer('submit', el, value);
2960
3211
  store._resolveInputField(elementId);
2961
3212
  if (fields.length <= 1) {
2962
3213
  _flushRemovedElements();
3214
+ logAnswer('finish');
2963
3215
  store.history.addUndoState();
2964
3216
  if (_onComplete) _onComplete();
2965
3217
  } else {
@@ -2985,10 +3237,12 @@ var InputFieldsDialog = mobxReactLite.observer(function (_ref2) {
2985
3237
  skipped: true,
2986
3238
  removed: shouldRemove
2987
3239
  });
3240
+ logAnswer('skip', el);
2988
3241
  store._resolveInputField(elementId);
2989
3242
  if (fields.length <= 1) {
2990
3243
  var hadRemovals = removedDueToSkipRef.current.length > 0;
2991
3244
  _flushRemovedElements();
3245
+ logAnswer('finish');
2992
3246
  if (hadRemovals) store.history.addUndoState();
2993
3247
  if (_onComplete) _onComplete();
2994
3248
  } else {
@@ -3019,6 +3273,7 @@ var InputFieldsDialog = mobxReactLite.observer(function (_ref2) {
3019
3273
  text: previousValue || ''
3020
3274
  });
3021
3275
  }
3276
+ logAnswer('back', el);
3022
3277
  store._unresolveInputField(el);
3023
3278
  }
3024
3279
  setDisplayIndex(function (prev) {
@@ -3053,6 +3308,7 @@ var InputFieldsDialog = mobxReactLite.observer(function (_ref2) {
3053
3308
  canGoBack: canGoBack,
3054
3309
  onComplete: function onComplete() {
3055
3310
  _flushRemovedElements();
3311
+ logAnswer('finish');
3056
3312
  store.history.addUndoState();
3057
3313
  if (_onComplete) _onComplete();
3058
3314
  }