@interlacejs/quiz 0.2.2 → 0.3.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/dist/index.cjs CHANGED
@@ -341,6 +341,66 @@ function getQuizAuthoringIssues(data) {
341
341
  return issues;
342
342
  }
343
343
 
344
+ // src/image-file.ts
345
+ var MAX_IMAGE_UPLOAD_MB = 10;
346
+ var KEEP_AS_IS_BYTES = 200 * 1024;
347
+ var MAX_DIMENSION = 1280;
348
+ var MAX_DATA_URL_LENGTH = 1.4 * 1024 * 1024;
349
+ var TOO_LARGE = "This image is too large. Try a smaller one, or use a URL.";
350
+ async function imageFileToDataUrl(file) {
351
+ if (!file.type.startsWith("image/")) {
352
+ throw new Error("Choose an image file.");
353
+ }
354
+ if (file.size > MAX_IMAGE_UPLOAD_MB * 1024 * 1024) {
355
+ throw new Error(`The image must be ${MAX_IMAGE_UPLOAD_MB} MB or smaller.`);
356
+ }
357
+ let url;
358
+ if (file.size <= KEEP_AS_IS_BYTES || file.type === "image/svg+xml") {
359
+ url = await readAsDataUrl(file);
360
+ } else {
361
+ url = await resize(file);
362
+ }
363
+ if (url.length > MAX_DATA_URL_LENGTH) throw new Error(TOO_LARGE);
364
+ return url;
365
+ }
366
+ function readAsDataUrl(file) {
367
+ return new Promise((resolve, reject) => {
368
+ const reader = new FileReader();
369
+ reader.onload = () => resolve(String(reader.result));
370
+ reader.onerror = () => reject(new Error("Couldn't read that image."));
371
+ reader.readAsDataURL(file);
372
+ });
373
+ }
374
+ async function resize(file) {
375
+ const image = await loadImage(file);
376
+ const longest = Math.max(image.naturalWidth, image.naturalHeight);
377
+ const scale = Math.min(1, MAX_DIMENSION / longest);
378
+ const canvas = document.createElement("canvas");
379
+ canvas.width = Math.max(1, Math.round(image.naturalWidth * scale));
380
+ canvas.height = Math.max(1, Math.round(image.naturalHeight * scale));
381
+ const context = canvas.getContext("2d");
382
+ if (!context) throw new Error("Couldn't read that image.");
383
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
384
+ const type = file.type === "image/jpeg" ? "image/jpeg" : "image/webp";
385
+ const url = canvas.toDataURL(type, 0.85);
386
+ return url.length <= MAX_DATA_URL_LENGTH ? url : canvas.toDataURL("image/jpeg", 0.8);
387
+ }
388
+ function loadImage(file) {
389
+ return new Promise((resolve, reject) => {
390
+ const objectUrl = URL.createObjectURL(file);
391
+ const image = new Image();
392
+ image.onload = () => {
393
+ URL.revokeObjectURL(objectUrl);
394
+ resolve(image);
395
+ };
396
+ image.onerror = () => {
397
+ URL.revokeObjectURL(objectUrl);
398
+ reject(new Error("Couldn't read that image."));
399
+ };
400
+ image.src = objectUrl;
401
+ });
402
+ }
403
+
344
404
  // src/quiz-editor.ts
345
405
  var quizEditorControllers = /* @__PURE__ */ new WeakMap();
346
406
  var editorInstanceCount = 0;
@@ -355,10 +415,8 @@ function createPreview(media, className) {
355
415
  img.className = className;
356
416
  img.src = media.src;
357
417
  img.style.maxWidth = "100%";
358
- img.style.maxHeight = "160px";
359
- img.style.height = "auto";
360
- img.style.borderRadius = `${import_core.RADIUS.sm}`;
361
- img.style.marginTop = `${import_core.SPACE[1]}px`;
418
+ img.style.maxHeight = "100%";
419
+ img.style.objectFit = "contain";
362
420
  if (media.alt) img.alt = media.alt;
363
421
  return img;
364
422
  }
@@ -471,6 +529,18 @@ function setFieldError(input, error, message) {
471
529
  input.removeAttribute("aria-describedby");
472
530
  }
473
531
  }
532
+ function isDataUrl(src) {
533
+ return src.startsWith("data:");
534
+ }
535
+ function createLinkButton(text, className) {
536
+ const button = createButton(text, "ghost", className);
537
+ button.style.padding = `0 ${import_core.SPACE[1]}px`;
538
+ button.style.minHeight = "0";
539
+ button.style.height = "auto";
540
+ button.style.color = import_core.COLORS.accent;
541
+ button.style.fontSize = `${import_core.TYPE.sm}px`;
542
+ return button;
543
+ }
474
544
  function createMediaEditor(options) {
475
545
  const { classPrefix, idPrefix } = options;
476
546
  const root = document.createElement("div");
@@ -485,65 +555,225 @@ function createMediaEditor(options) {
485
555
  panel.className = `${classPrefix}-panel`;
486
556
  panel.style.flexDirection = "column";
487
557
  panel.style.gap = `${import_core.SPACE[2]}px`;
488
- panel.style.padding = `${import_core.SPACE[3]}px`;
489
- panel.style.backgroundColor = import_core.COLORS.surfaceRaised;
490
- panel.style.border = `1px solid ${import_core.COLORS.border}`;
491
- panel.style.borderRadius = `${import_core.RADIUS.md}`;
558
+ const fileInput = document.createElement("input");
559
+ fileInput.type = "file";
560
+ fileInput.accept = "image/*";
561
+ fileInput.className = `${classPrefix}-file`;
562
+ fileInput.tabIndex = -1;
563
+ fileInput.setAttribute("aria-hidden", "true");
564
+ setShown(fileInput, false);
565
+ const dropzone = document.createElement("div");
566
+ dropzone.className = `${classPrefix}-dropzone`;
567
+ dropzone.style.flexDirection = "column";
568
+ dropzone.style.alignItems = "center";
569
+ dropzone.style.gap = `${import_core.SPACE[1]}px`;
570
+ dropzone.style.padding = `${import_core.SPACE[4]}px ${import_core.SPACE[3]}px`;
571
+ dropzone.style.border = `1px dashed ${import_core.COLORS.borderStrong}`;
572
+ dropzone.style.borderRadius = `${import_core.RADIUS.md}`;
573
+ dropzone.style.backgroundColor = import_core.COLORS.surfaceRaised;
574
+ dropzone.style.textAlign = "center";
575
+ dropzone.style.cursor = "pointer";
576
+ dropzone.style.transition = "border-color 120ms, background-color 120ms";
577
+ const dropText = document.createElement("p");
578
+ dropText.style.margin = "0";
579
+ dropText.style.fontSize = `${import_core.TYPE.sm}px`;
580
+ dropText.style.color = import_core.COLORS.text;
581
+ const uploadButton = createLinkButton("browse", `${classPrefix}-upload`);
582
+ uploadButton.style.textDecoration = "underline";
583
+ uploadButton.style.fontWeight = "600";
584
+ dropText.append("Drag an image here, or ", uploadButton);
585
+ const dropHint = document.createElement("p");
586
+ dropHint.className = "interlace-hint";
587
+ dropHint.style.margin = "0";
588
+ dropHint.textContent = `JPG, PNG, GIF, WebP or SVG, up to ${MAX_IMAGE_UPLOAD_MB} MB`;
589
+ const busyText = document.createElement("p");
590
+ busyText.className = "interlace-hint";
591
+ busyText.style.margin = "0";
592
+ busyText.textContent = "Adding image\u2026";
593
+ busyText.setAttribute("role", "status");
594
+ setShown(busyText, false);
595
+ dropzone.append(dropText, dropHint, busyText);
492
596
  const srcInput = createInput(
493
597
  `${classPrefix}-src`,
494
598
  `${idPrefix}-src`,
495
599
  "https://example.com/image.png"
496
600
  );
601
+ const urlField = createField("Image URL", srcInput);
602
+ const card = document.createElement("div");
603
+ card.className = `${classPrefix}-card`;
604
+ card.style.gap = `${import_core.SPACE[3]}px`;
605
+ card.style.alignItems = "flex-start";
606
+ card.style.padding = `${import_core.SPACE[2]}px`;
607
+ card.style.border = `1px solid ${import_core.COLORS.border}`;
608
+ card.style.borderRadius = `${import_core.RADIUS.md}`;
609
+ card.style.backgroundColor = import_core.COLORS.surfaceRaised;
610
+ const previewSlot = document.createElement("div");
611
+ previewSlot.className = options.previewSlotClass;
612
+ previewSlot.style.flex = "0 0 auto";
613
+ previewSlot.style.width = "112px";
614
+ previewSlot.style.height = "84px";
615
+ previewSlot.style.display = "flex";
616
+ previewSlot.style.alignItems = "center";
617
+ previewSlot.style.justifyContent = "center";
618
+ previewSlot.style.overflow = "hidden";
619
+ previewSlot.style.borderRadius = `${import_core.RADIUS.sm}`;
620
+ previewSlot.style.backgroundColor = import_core.COLORS.surface;
621
+ previewSlot.style.border = `1px solid ${import_core.COLORS.border}`;
622
+ previewSlot.style.color = import_core.COLORS.textMuted;
623
+ previewSlot.style.fontSize = `${import_core.TYPE.sm}px`;
624
+ previewSlot.style.textAlign = "center";
497
625
  const altInput = createInput(
498
626
  `${classPrefix}-alt`,
499
627
  `${idPrefix}-alt`,
500
628
  "Describe the image for screen readers"
501
629
  );
502
- const previewSlot = document.createElement("div");
503
- previewSlot.className = options.previewSlotClass;
504
- const removeButton = createButton(
505
- "Remove image",
506
- "ghost",
507
- `${classPrefix}-remove`
508
- );
509
- removeButton.style.alignSelf = "flex-start";
510
- panel.append(
511
- createField("Image URL", srcInput),
512
- createField("Image description (alt text)", altInput),
513
- previewSlot,
514
- removeButton
630
+ const replaceButton = createLinkButton("Replace", `${classPrefix}-replace`);
631
+ const removeButton = createLinkButton("Remove", `${classPrefix}-remove`);
632
+ removeButton.style.color = import_core.COLORS.errorText;
633
+ const actions = document.createElement("div");
634
+ actions.style.display = "flex";
635
+ actions.style.gap = `${import_core.SPACE[2]}px`;
636
+ actions.append(replaceButton, removeButton);
637
+ const details = document.createElement("div");
638
+ details.style.flex = "1 1 auto";
639
+ details.style.minWidth = "0";
640
+ details.style.display = "flex";
641
+ details.style.flexDirection = "column";
642
+ details.style.gap = `${import_core.SPACE[1]}px`;
643
+ const altField = createField("Alt text", altInput);
644
+ details.append(urlField, altField, actions);
645
+ card.append(previewSlot, details);
646
+ const uploadError = createErrorText(
647
+ `${idPrefix}-upload-error`,
648
+ `${classPrefix}-upload-error`
515
649
  );
650
+ uploadError.setAttribute("role", "alert");
651
+ const modeButton = createLinkButton("", `${classPrefix}-mode`);
652
+ const cancelButton = createLinkButton("Cancel", `${classPrefix}-cancel`);
653
+ cancelButton.style.color = import_core.COLORS.textMuted;
654
+ const links = document.createElement("div");
655
+ links.style.justifyContent = "space-between";
656
+ links.append(modeButton, cancelButton);
657
+ panel.append(fileInput, dropzone, card, uploadError, links);
516
658
  root.append(addButton, panel);
659
+ let src = "";
660
+ let urlMode = false;
661
+ const render = () => {
662
+ const hasImage = src.length > 0;
663
+ const img = previewSlot.querySelector("img");
664
+ if (!img) previewSlot.textContent = "Preview";
665
+ else
666
+ img.onerror = () => {
667
+ previewSlot.textContent = "Can't load this image";
668
+ };
669
+ setShown(dropzone, !hasImage && !urlMode, "flex");
670
+ setShown(card, hasImage || urlMode, "flex");
671
+ setShown(urlField, urlMode || hasImage && !isDataUrl(src), "flex");
672
+ setShown(altField, hasImage, "flex");
673
+ setShown(actions, hasImage, "flex");
674
+ setShown(links, !hasImage, "flex");
675
+ modeButton.textContent = urlMode ? "Upload an image instead" : "Use an image URL instead";
676
+ };
517
677
  const setExpanded = (expanded) => {
518
678
  setShown(panel, expanded, "flex");
519
679
  setShown(addButton, !expanded);
520
680
  addButton.setAttribute("aria-expanded", String(expanded));
521
681
  };
522
682
  setExpanded(false);
523
- const handleEdit = () => {
524
- const media = buildMediaRef(srcInput.value, altInput.value);
683
+ render();
684
+ const setUploadError = (message) => {
685
+ uploadError.textContent = message ?? "";
686
+ setShown(uploadError, message !== null);
687
+ };
688
+ const emit = () => {
689
+ const media = buildMediaRef(src, altInput.value);
525
690
  syncPreview(previewSlot, media, options.previewClass);
691
+ render();
526
692
  options.onEdit(media);
527
693
  };
528
- srcInput.addEventListener("input", handleEdit);
529
- altInput.addEventListener("input", handleEdit);
530
- addButton.addEventListener("click", () => {
531
- setExpanded(true);
532
- options.onExpand();
533
- srcInput.focus();
694
+ srcInput.addEventListener("input", () => {
695
+ src = srcInput.value;
696
+ setUploadError(null);
697
+ emit();
534
698
  });
535
- removeButton.addEventListener("click", () => {
699
+ altInput.addEventListener("input", emit);
700
+ const useFile = async (file) => {
701
+ if (!file) return;
702
+ setUploadError(null);
703
+ setShown(busyText, true);
704
+ try {
705
+ src = await imageFileToDataUrl(file);
706
+ urlMode = false;
707
+ srcInput.value = "";
708
+ emit();
709
+ } catch (error) {
710
+ setUploadError(
711
+ error instanceof Error ? error.message : "Couldn't use that image."
712
+ );
713
+ } finally {
714
+ setShown(busyText, false);
715
+ }
716
+ };
717
+ fileInput.addEventListener("change", () => {
718
+ const file = fileInput.files?.[0];
719
+ fileInput.value = "";
720
+ void useFile(file);
721
+ });
722
+ dropzone.addEventListener("click", () => fileInput.click());
723
+ uploadButton.addEventListener("click", (event) => {
724
+ event.stopPropagation();
725
+ fileInput.click();
726
+ });
727
+ replaceButton.addEventListener("click", () => fileInput.click());
728
+ const setDragOver = (over) => {
729
+ dropzone.style.borderColor = over ? import_core.COLORS.accent : import_core.COLORS.borderStrong;
730
+ dropzone.style.backgroundColor = over ? import_core.COLORS.accentLighter : import_core.COLORS.surfaceRaised;
731
+ };
732
+ dropzone.addEventListener("dragover", (event) => {
733
+ event.preventDefault();
734
+ setDragOver(true);
735
+ });
736
+ dropzone.addEventListener("dragleave", () => setDragOver(false));
737
+ dropzone.addEventListener("drop", (event) => {
738
+ event.preventDefault();
739
+ setDragOver(false);
740
+ void useFile(event.dataTransfer?.files?.[0]);
741
+ });
742
+ modeButton.addEventListener("click", () => {
743
+ urlMode = !urlMode;
744
+ setUploadError(null);
745
+ render();
746
+ if (urlMode) srcInput.focus();
747
+ else uploadButton.focus();
748
+ });
749
+ const clear = () => {
750
+ src = "";
751
+ urlMode = false;
536
752
  srcInput.value = "";
537
753
  altInput.value = "";
754
+ setUploadError(null);
538
755
  syncPreview(previewSlot, void 0, options.previewClass);
756
+ render();
539
757
  setExpanded(false);
540
- options.onRemove();
541
758
  addButton.focus();
759
+ };
760
+ cancelButton.addEventListener("click", clear);
761
+ removeButton.addEventListener("click", () => {
762
+ clear();
763
+ options.onRemove();
764
+ });
765
+ addButton.addEventListener("click", () => {
766
+ setExpanded(true);
767
+ options.onExpand();
768
+ uploadButton.focus();
542
769
  });
543
770
  const sync = (media, expanded) => {
544
- setValue(srcInput, media?.src ?? "");
771
+ src = media?.src ?? "";
772
+ setValue(srcInput, isDataUrl(src) ? "" : src);
545
773
  setValue(altInput, media?.alt ?? "");
546
774
  syncPreview(previewSlot, media, options.previewClass);
775
+ urlMode = src.length > 0 && !isDataUrl(src);
776
+ render();
547
777
  setExpanded(expanded);
548
778
  };
549
779
  return { root, srcInput, altInput, previewSlot, sync };