@masterteam/components 0.0.351 → 0.0.352

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.
@@ -337,10 +337,13 @@ class UploadField {
337
337
  * every selected/dropped file against before uploading to the backend.
338
338
  */
339
339
  effectiveAccept = computed(() => {
340
+ const configured = normalizeAcceptSpec(this.accept());
341
+ // A circle field is an image picker. Honour a narrower image-only spec
342
+ // (e.g. a favicon's ".png,.ico,.svg"), otherwise fall back to any image.
340
343
  if (this.shape() === 'circle') {
341
- return 'image/*';
344
+ return isImageOnlyAccept(configured) ? configured : 'image/*';
342
345
  }
343
- return normalizeAcceptSpec(this.accept());
346
+ return configured;
344
347
  }, ...(ngDevMode ? [{ debugName: "effectiveAccept" }] : /* istanbul ignore next */ []));
345
348
  /**
346
349
  * Human-friendly, de-duplicated list of accepted types shown next to the
@@ -395,6 +398,8 @@ class UploadField {
395
398
  disabled = signal(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
396
399
  policyChecking = signal(true, ...(ngDevMode ? [{ debugName: "policyChecking" }] : /* istanbul ignore next */ []));
397
400
  policyUnavailable = signal(false, ...(ngDevMode ? [{ debugName: "policyUnavailable" }] : /* istanbul ignore next */ []));
401
+ /** Backend cap from the capabilities endpoint; unknown until it loads. */
402
+ maxFileSizeBytes = signal(undefined, ...(ngDevMode ? [{ debugName: "maxFileSizeBytes" }] : /* istanbul ignore next */ []));
398
403
  uploadProgress = signal(0, ...(ngDevMode ? [{ debugName: "uploadProgress" }] : /* istanbul ignore next */ []));
399
404
  loading = signal(false, ...(ngDevMode ? [{ debugName: "loading" }] : /* istanbul ignore next */ []));
400
405
  uploadInteractionDisabled = computed(() => this.disabled() ||
@@ -406,6 +411,8 @@ class UploadField {
406
411
  uploader = inject(UploaderService);
407
412
  destroyRef = inject(DestroyRef);
408
413
  pendingUploads = signal(0, ...(ngDevMode ? [{ debugName: "pendingUploads" }] : /* istanbul ignore next */ []));
414
+ validationRun = 0;
415
+ destroyed = false;
409
416
  metadataSubscription;
410
417
  metadataHydrationKey = null;
411
418
  metadataHydrationContext;
@@ -416,6 +423,10 @@ class UploadField {
416
423
  if (this.ngControl) {
417
424
  this.ngControl.valueAccessor = this;
418
425
  }
426
+ this.destroyRef.onDestroy(() => {
427
+ this.destroyed = true;
428
+ this.validationRun += 1;
429
+ });
419
430
  effect((onCleanup) => {
420
431
  const endpoint = this.endPoint();
421
432
  const context = this.context();
@@ -427,10 +438,12 @@ class UploadField {
427
438
  .subscribe({
428
439
  next: (capabilities) => {
429
440
  this.policyUnavailable.set(!capabilities.uploadEnabled);
441
+ this.maxFileSizeBytes.set(capabilities.maxFileSizeBytes);
430
442
  this.policyChecking.set(false);
431
443
  },
432
444
  error: () => {
433
445
  this.policyUnavailable.set(true);
446
+ this.maxFileSizeBytes.set(undefined);
434
447
  this.policyChecking.set(false);
435
448
  },
436
449
  });
@@ -506,41 +519,69 @@ class UploadField {
506
519
  if (!selectedFiles.length) {
507
520
  return;
508
521
  }
522
+ // The current value is only replaced once a new file is accepted and
523
+ // uploaded, so a refused file leaves the existing image untouched.
509
524
  this.cancelMetadataHydration();
510
- if (!this.isMultipleEnabled()) {
511
- this.value.set(null);
512
- }
513
525
  this.prepareFiles(selectedFiles);
514
526
  if (input) {
515
527
  input.value = '';
516
528
  }
517
529
  }
518
530
  prepareFiles(files) {
531
+ const run = ++this.validationRun;
519
532
  this.ngControl.control?.setErrors({ uploading: true });
520
533
  const accept = this.effectiveAccept();
521
534
  const rejected = files.filter((file) => !isFileAccepted(file, accept));
522
535
  if (rejected.length) {
523
- this.ngControl.control?.setErrors({
536
+ this.refuse({
524
537
  invalidFileType: {
525
538
  message: this.transloco.translate('components.validation.invalidFileType', { types: this.acceptedTypesLabel() || accept }),
526
539
  },
527
540
  });
528
- // The control is invalid but `mt-field-validation` only renders once the
529
- // control is touched — mark it so the rejection message is visible.
530
- this.ngControl.control?.markAsTouched();
531
541
  return;
532
542
  }
533
543
  const sizeLimit = this.effectiveSizeLimit();
534
- const oversized = sizeLimit == null ? [] : files.filter((file) => file.size > sizeLimit);
535
- if (oversized.length) {
536
- this.ngControl.control?.setErrors({
537
- fileSizeLimited: { size: formatFileSize(sizeLimit ?? 0) },
538
- });
539
- this.ngControl.control?.markAsTouched();
544
+ if (sizeLimit != null && files.some((file) => file.size > sizeLimit)) {
545
+ this.refuse({ fileSizeLimited: { size: formatFileSize(sizeLimit) } });
546
+ return;
547
+ }
548
+ // Check the backend cap here too so an oversized image is refused before
549
+ // it is decoded. If the cap is unknown the uploader enforces it later.
550
+ const maxBytes = this.maxFileSizeBytes();
551
+ if (maxBytes != null && files.some((file) => file.size > maxBytes)) {
552
+ this.refuse({ fileSizeLimited: { size: formatFileSize(maxBytes) } });
540
553
  return;
541
554
  }
542
555
  const filesToUpload = this.isMultipleEnabled() ? files : [files[0]];
543
- filesToUpload.forEach((file) => this.uploadFile(file));
556
+ if (!isImageOnlyAccept(accept)) {
557
+ filesToUpload.forEach((file) => this.uploadFile(file));
558
+ return;
559
+ }
560
+ // Image-only fields: the extension/MIME can be faked, so make sure the
561
+ // browser can actually decode each file before uploading anything.
562
+ void Promise.all(filesToUpload.map(decodeImage)).then((results) => {
563
+ // A newer selection or destroying the field supersedes this run.
564
+ if (run !== this.validationRun || this.destroyed) {
565
+ return;
566
+ }
567
+ if (results.some((ok) => !ok)) {
568
+ this.refuse({
569
+ invalidImage: {
570
+ message: this.transloco.translate('components.validation.invalidImage'),
571
+ },
572
+ });
573
+ return;
574
+ }
575
+ filesToUpload.forEach((file) => this.uploadFile(file));
576
+ });
577
+ }
578
+ /**
579
+ * Marks the selection as refused. `mt-field-validation` only renders once the
580
+ * control is touched, so touch it to make the message visible.
581
+ */
582
+ refuse(errors) {
583
+ this.ngControl.control?.setErrors(errors);
584
+ this.ngControl.control?.markAsTouched();
544
585
  }
545
586
  uploadFile(file) {
546
587
  this.pendingUploads.update((count) => count + 1);
@@ -634,9 +675,6 @@ class UploadField {
634
675
  return;
635
676
  }
636
677
  this.cancelMetadataHydration();
637
- if (!this.isMultipleEnabled()) {
638
- this.value.set(null);
639
- }
640
678
  this.prepareFiles(files);
641
679
  }
642
680
  resolveImgPath(value) {
@@ -803,6 +841,68 @@ function isFileAccepted(file, accept) {
803
841
  return !!fileType && fileType === token;
804
842
  });
805
843
  }
844
+ const IMAGE_EXTENSIONS = new Set([
845
+ '.png',
846
+ '.jpg',
847
+ '.jpeg',
848
+ '.jfif',
849
+ '.gif',
850
+ '.webp',
851
+ '.avif',
852
+ '.apng',
853
+ '.bmp',
854
+ '.svg',
855
+ '.ico',
856
+ ]);
857
+ /**
858
+ * True when every token of the accept spec is an image type, so the browser
859
+ * can be asked to decode the file. Mixed specs (e.g. ".png,.pdf") and
860
+ * catch-alls are not image-only and keep the old behaviour.
861
+ */
862
+ function isImageOnlyAccept(accept) {
863
+ const tokens = (accept ?? '')
864
+ .split(',')
865
+ .map((token) => token.trim().toLowerCase())
866
+ .filter((token) => token.length > 0);
867
+ return (tokens.length > 0 &&
868
+ tokens.every((token) => token.startsWith('.')
869
+ ? IMAGE_EXTENSIONS.has(token)
870
+ : token.startsWith('image/')));
871
+ }
872
+ const IMAGE_DECODE_TIMEOUT_MS = 10_000;
873
+ /** Resolves true when the browser can load and decode the file as an image. */
874
+ function decodeImage(file) {
875
+ return new Promise((resolve) => {
876
+ const url = URL.createObjectURL(file);
877
+ const image = new Image();
878
+ let settled = false;
879
+ const finish = (ok) => {
880
+ if (settled) {
881
+ return;
882
+ }
883
+ settled = true;
884
+ clearTimeout(timer);
885
+ image.onload = null;
886
+ image.onerror = null;
887
+ URL.revokeObjectURL(url);
888
+ resolve(ok);
889
+ };
890
+ const timer = setTimeout(() => finish(false), IMAGE_DECODE_TIMEOUT_MS);
891
+ const isSvg = file.type.toLowerCase() === 'image/svg+xml' ||
892
+ file.name.toLowerCase().endsWith('.svg');
893
+ image.onerror = () => finish(false);
894
+ image.onload = () => {
895
+ if (typeof image.decode !== 'function') {
896
+ finish(true);
897
+ return;
898
+ }
899
+ // decode() can reject SVGs that have no intrinsic size even though they
900
+ // render fine, so a loaded SVG is accepted regardless.
901
+ image.decode().then(() => finish(true), () => finish(isSvg));
902
+ };
903
+ image.src = url;
904
+ });
905
+ }
806
906
  /**
807
907
  * Formats a byte count into a short, human-readable label for validation
808
908
  * messages (e.g. 104857600 -> "100 MB"). Whole numbers drop the decimal.