@remit/ui 0.0.218 → 0.0.220

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": "@remit/ui",
3
- "version": "0.0.218",
3
+ "version": "0.0.220",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "src"
@@ -12,7 +12,9 @@ import {
12
12
  VIEWPORT_META,
13
13
  } from "./email-frame-css.js";
14
14
  import {
15
+ fitScale,
15
16
  IsolatedEmailFrame,
17
+ MIN_FIT_SCALE,
16
18
  measureContentAxis,
17
19
  } from "./isolated-email-frame.js";
18
20
 
@@ -93,6 +95,38 @@ describe("measureContentAxis (the frame's height, and only its height)", () => {
93
95
  });
94
96
  });
95
97
 
98
+ describe("fitScale (a wide mail shrinks to the frame, never grows)", () => {
99
+ it("scales a 600px newsletter into a 390px phone frame", () => {
100
+ assert.equal(fitScale(600, 390), 0.65);
101
+ assert.equal(600 * fitScale(600, 390), 390);
102
+ });
103
+
104
+ it("leaves mail that fits at its own size", () => {
105
+ assert.equal(fitScale(320, 390), 1);
106
+ assert.equal(fitScale(390, 390), 1);
107
+ });
108
+
109
+ it("never scales narrow mail up to fill a wide frame", () => {
110
+ assert.equal(fitScale(200, 1200), 1);
111
+ });
112
+
113
+ it("ignores the pixel a fractional column rounds the mail over by", () => {
114
+ assert.equal(fitScale(391, 390), 1);
115
+ assert.ok(fitScale(392, 390) < 1);
116
+ });
117
+
118
+ it("stops at a readable floor however wide the mail is", () => {
119
+ assert.equal(MIN_FIT_SCALE, 0.5);
120
+ assert.equal(fitScale(3000, 390), MIN_FIT_SCALE);
121
+ assert.equal(fitScale(100_000, 390), MIN_FIT_SCALE);
122
+ assert.equal(fitScale(780, 390), MIN_FIT_SCALE);
123
+ });
124
+
125
+ it("leaves a frame that has not laid out yet alone", () => {
126
+ assert.equal(fitScale(600, 0), 1);
127
+ });
128
+ });
129
+
96
130
  describe("generateScrollportCSS (the document holds its own overflow)", () => {
97
131
  it("makes the body the scrollport rather than the frame", () => {
98
132
  assert.match(generateScrollportCSS(), /body\{overflow-x:auto\}/);
@@ -1,7 +1,7 @@
1
1
  import type { Decorator, Meta, StoryObj } from "@storybook/react-vite";
2
2
  import { expect, waitFor } from "storybook/test";
3
3
  import { generateLayoutClampCSS } from "../lib/email-layout-clamp.js";
4
- import { IsolatedEmailFrame } from "./isolated-email-frame.js";
4
+ import { IsolatedEmailFrame, MIN_FIT_SCALE } from "./isolated-email-frame.js";
5
5
 
6
6
  /**
7
7
  * `IsolatedEmailFrame` renders sanitized email HTML in a sandboxed iframe that is
@@ -17,9 +17,9 @@ import { IsolatedEmailFrame } from "./isolated-email-frame.js";
17
17
  *
18
18
  * The app's layout never reacts to what is inside the frame. Mail that can
19
19
  * reflow does, against the pane's width; mail that genuinely cannot — a table
20
- * with its own `min-width`, an image the same, a `pre` the author pinned —
21
- * scrolls inside the document, and neither the pane nor the page moves sideways
22
- * at any width.
20
+ * with its own `min-width`, an image the same, a `pre` the author pinned — is
21
+ * laid out at its own width and scaled down to fit the frame, the way K-9 Mail
22
+ * shows it, and neither the pane nor the page moves sideways at any width.
23
23
  */
24
24
 
25
25
  // The sanitizer's own clamp — clamps wide author markup (fixed-width
@@ -103,7 +103,7 @@ const PLAIN = `${LAYOUT_CLAMP_CSS}
103
103
 
104
104
  // Mail that genuinely cannot fit: an inline `min-width` on the table outranks
105
105
  // the clamp's `* { min-width: 0 }`, so 1200px of columns stay 1200px wide and
106
- // the email's own document is what the reader scrolls to see the rest.
106
+ // the email's own document is scaled down to fit the frame.
107
107
  const WIDE_TABLE = `${LAYOUT_CLAMP_CSS}
108
108
  <div style="font-family: Helvetica, Arial, sans-serif; color:#1a1a1a;">
109
109
  <h1 style="font-size:20px;margin:0 0 12px;">Q2 regional breakdown</h1>
@@ -219,8 +219,8 @@ type Story = StoryObj<typeof IsolatedEmailFrame>;
219
219
 
220
220
  /** #727: a 600px fixed-width Node Weekly table at a 390px phone width. The inline
221
221
  * `min-width:600px` on the `<td>` beats the clamp so the table can't collapse;
222
- * it scrolls inside the document instead, and the phone-width box around it
223
- * stays put. */
222
+ * it is scaled down to fit instead, and the phone-width box around it stays
223
+ * put. */
224
224
  export const NodeWeeklyMobile: Story = {
225
225
  args: {
226
226
  html: NODE_WEEKLY,
@@ -243,7 +243,7 @@ export const NodeWeeklyDesktop: Story = {
243
243
  };
244
244
 
245
245
  /** Gaslicht.com-style 600px fixed-width marketing mail at phone width: the hero
246
- * image reflows to the frame and the fixed body scrolls inside the document. */
246
+ * image reflows to the frame and the fixed body is scaled down to fit. */
247
247
  export const GaslichtMobile: Story = {
248
248
  args: {
249
249
  html: GASLICHT,
@@ -318,9 +318,9 @@ export const SubstackFractionalColumn: Story = {
318
318
  decorators: [FRACTIONAL_COLUMN],
319
319
  };
320
320
 
321
- /** A 1200px table that genuinely does not fit: it scrolls inside the document,
321
+ /** A 1200px table that genuinely does not fit: it is scaled down to the frame,
322
322
  * and the column holding the frame never grows a scrollbar of its own. */
323
- export const WideTableScrollsInPlace: Story = {
323
+ export const WideTableScalesToTheColumn: Story = {
324
324
  args: {
325
325
  html: WIDE_TABLE,
326
326
  variant: "framed",
@@ -330,8 +330,8 @@ export const WideTableScrollsInPlace: Story = {
330
330
  decorators: [COLUMN],
331
331
  };
332
332
 
333
- /** The same table on a phone: the same in-document scroll, one behaviour at
334
- * every width. */
333
+ /** The same table on a phone, where fitting it would take it below the readable
334
+ * floor: it is shown at the floor scale and scrolls sideways for the rest. */
335
335
  export const WideTableMobile: Story = {
336
336
  args: {
337
337
  html: WIDE_TABLE,
@@ -425,7 +425,7 @@ export const PreformattedTextKeepsItsSpacing: Story = {
425
425
  };
426
426
 
427
427
  /* ------------------------------------------------------------------ */
428
- /* Overflow belongs to the document, not to the app */
428
+ /* Mail wider than the frame is scaled to fit it */
429
429
  /* ------------------------------------------------------------------ */
430
430
 
431
431
  // An image with a min-width of its own: the clamp's `max-width:100% !important`
@@ -464,22 +464,48 @@ const BARE_PHONE: Decorator = (Story) => (
464
464
  </div>
465
465
  );
466
466
 
467
- /**
468
- * Content that genuinely cannot wrap scrolls where it lives — inside the
469
- * document — and nothing outside the frame moves sideways for it. The frame is
470
- * the pane's width and the pane has nothing to scroll, so there is no route for
471
- * the overflow to reach the page either.
472
- */
473
- const assertScrollsInsideTheDocument = async (canvasElement: HTMLElement) => {
467
+ const transformOf = (element: Element): string =>
468
+ element.ownerDocument.defaultView?.getComputedStyle(element).transform ?? "";
469
+
470
+ const scaleOf = (body: HTMLElement): number =>
471
+ body.getBoundingClientRect().width / body.offsetWidth;
472
+
473
+ const widestRight = (body: HTMLElement): number =>
474
+ Math.max(
475
+ body.getBoundingClientRect().right,
476
+ ...[...body.querySelectorAll("*")].map(
477
+ (element) => element.getBoundingClientRect().right,
478
+ ),
479
+ );
480
+
481
+ const scrollsSideways = (body: HTMLElement): boolean =>
482
+ body.ownerDocument.defaultView?.getComputedStyle(body).overflowX !==
483
+ "visible" && body.scrollWidth > body.clientWidth;
484
+
485
+ const scaledFrame = async (canvasElement: HTMLElement) => {
474
486
  const iframe = canvasElement.querySelector("iframe");
475
487
  if (!iframe) throw new Error("no email frame in the story");
476
- await waitFor(() => {
477
- const body = iframe.contentDocument?.body;
478
- if (!body) throw new Error("the frame has not parsed its document yet");
479
- if (body.scrollWidth <= body.clientWidth) {
480
- throw new Error("the document is not holding its own overflow yet");
488
+ return await waitFor(() => {
489
+ const doc = iframe.contentDocument;
490
+ const body = doc?.body;
491
+ if (!doc || !body) {
492
+ throw new Error("the frame has not parsed its document yet");
493
+ }
494
+ if (transformOf(body) === "none") {
495
+ throw new Error("the document has not been scaled to the frame yet");
496
+ }
497
+ const height = body.getBoundingClientRect().height;
498
+ if (Math.abs(iframe.getBoundingClientRect().height - height) > 1) {
499
+ throw new Error("the frame is not as tall as the scaled mail");
481
500
  }
501
+ return { iframe, body, frameWidth: doc.documentElement.clientWidth };
482
502
  });
503
+ };
504
+
505
+ const assertPaneHoldsStill = async (
506
+ canvasElement: HTMLElement,
507
+ iframe: HTMLIFrameElement,
508
+ ) => {
483
509
  const pane = canvasElement.querySelector<HTMLElement>("[data-pane]");
484
510
  if (!pane) throw new Error("no pane in the story");
485
511
  await expect(iframe.getBoundingClientRect().width).toBeLessThanOrEqual(
@@ -488,8 +514,37 @@ const assertScrollsInsideTheDocument = async (canvasElement: HTMLElement) => {
488
514
  await expect(pane.scrollWidth).toBeLessThanOrEqual(pane.clientWidth);
489
515
  };
490
516
 
517
+ /**
518
+ * Content that genuinely cannot wrap is laid out at its own width and scaled
519
+ * down until it fits the frame: every part of the scaled mail lands inside the
520
+ * frame, nothing inside it scrolls sideways, and the frame is exactly as tall as
521
+ * the scaled mail. Nothing outside the frame moves sideways for it either.
522
+ */
523
+ const assertScaledToFit = async (canvasElement: HTMLElement) => {
524
+ const { iframe, body, frameWidth } = await scaledFrame(canvasElement);
525
+ await expect(scaleOf(body)).toBeGreaterThan(MIN_FIT_SCALE);
526
+ await expect(widestRight(body)).toBeLessThanOrEqual(frameWidth + 0.5);
527
+ await expect(scrollsSideways(body)).toBe(false);
528
+ await assertPaneHoldsStill(canvasElement, iframe);
529
+ };
530
+
531
+ /**
532
+ * Mail too wide to fit at a readable scale stops at the floor: the body is the
533
+ * frame's width at that scale and the rest of the mail scrolls sideways inside
534
+ * it, never in the pane.
535
+ */
536
+ const assertScrollsAtTheFloor = async (canvasElement: HTMLElement) => {
537
+ const { iframe, body, frameWidth } = await scaledFrame(canvasElement);
538
+ await expect(Math.abs(scaleOf(body) - MIN_FIT_SCALE)).toBeLessThan(0.01);
539
+ await expect(body.getBoundingClientRect().right).toBeLessThanOrEqual(
540
+ frameWidth + 0.5,
541
+ );
542
+ await expect(scrollsSideways(body)).toBe(true);
543
+ await assertPaneHoldsStill(canvasElement, iframe);
544
+ };
545
+
491
546
  /** A 1200px table on a desktop reading column. */
492
- export const WideTableScrollsInsideTheDocument: Story = {
547
+ export const WideTableScalesToFitTheFrame: Story = {
493
548
  args: {
494
549
  html: WIDE_TABLE,
495
550
  variant: "framed",
@@ -498,12 +553,12 @@ export const WideTableScrollsInsideTheDocument: Story = {
498
553
  },
499
554
  decorators: [BARE_PANE],
500
555
  play: async ({ canvasElement }) => {
501
- await assertScrollsInsideTheDocument(canvasElement);
556
+ await assertScaledToFit(canvasElement);
502
557
  },
503
558
  };
504
559
 
505
- /** The same table on a phone. */
506
- export const WideTableScrollsInsideTheDocumentOnAPhone: Story = {
560
+ /** The same table on a phone, a third of it wide: past the floor. */
561
+ export const WideTableScrollsAtTheFloorOnAPhone: Story = {
507
562
  args: {
508
563
  html: WIDE_TABLE,
509
564
  variant: "framed",
@@ -512,12 +567,12 @@ export const WideTableScrollsInsideTheDocumentOnAPhone: Story = {
512
567
  },
513
568
  decorators: [BARE_PHONE],
514
569
  play: async ({ canvasElement }) => {
515
- await assertScrollsInsideTheDocument(canvasElement);
570
+ await assertScrollsAtTheFloor(canvasElement);
516
571
  },
517
572
  };
518
573
 
519
574
  /** A 1400px image on a desktop reading column. */
520
- export const OversizedImageScrollsInsideTheDocument: Story = {
575
+ export const OversizedImageScalesToFitTheFrame: Story = {
521
576
  args: {
522
577
  html: OVERSIZED_IMAGE,
523
578
  variant: "framed",
@@ -526,12 +581,12 @@ export const OversizedImageScrollsInsideTheDocument: Story = {
526
581
  },
527
582
  decorators: [BARE_PANE],
528
583
  play: async ({ canvasElement }) => {
529
- await assertScrollsInsideTheDocument(canvasElement);
584
+ await assertScaledToFit(canvasElement);
530
585
  },
531
586
  };
532
587
 
533
- /** The same image on a phone. */
534
- export const OversizedImageScrollsInsideTheDocumentOnAPhone: Story = {
588
+ /** The same image on a phone: past the floor. */
589
+ export const OversizedImageScrollsAtTheFloorOnAPhone: Story = {
535
590
  args: {
536
591
  html: OVERSIZED_IMAGE,
537
592
  variant: "framed",
@@ -540,12 +595,12 @@ export const OversizedImageScrollsInsideTheDocumentOnAPhone: Story = {
540
595
  },
541
596
  decorators: [BARE_PHONE],
542
597
  play: async ({ canvasElement }) => {
543
- await assertScrollsInsideTheDocument(canvasElement);
598
+ await assertScrollsAtTheFloor(canvasElement);
544
599
  },
545
600
  };
546
601
 
547
602
  /** A pinned code listing on a desktop reading column. */
548
- export const PinnedPreScrollsInsideTheDocument: Story = {
603
+ export const PinnedPreScalesToFitTheFrame: Story = {
549
604
  args: {
550
605
  html: PINNED_PRE,
551
606
  variant: "framed",
@@ -554,12 +609,12 @@ export const PinnedPreScrollsInsideTheDocument: Story = {
554
609
  },
555
610
  decorators: [BARE_PANE],
556
611
  play: async ({ canvasElement }) => {
557
- await assertScrollsInsideTheDocument(canvasElement);
612
+ await assertScaledToFit(canvasElement);
558
613
  },
559
614
  };
560
615
 
561
- /** The same listing on a phone. */
562
- export const PinnedPreScrollsInsideTheDocumentOnAPhone: Story = {
616
+ /** The same listing on a phone: past the floor. */
617
+ export const PinnedPreScrollsAtTheFloorOnAPhone: Story = {
563
618
  args: {
564
619
  html: PINNED_PRE,
565
620
  variant: "framed",
@@ -568,7 +623,7 @@ export const PinnedPreScrollsInsideTheDocumentOnAPhone: Story = {
568
623
  },
569
624
  decorators: [BARE_PHONE],
570
625
  play: async ({ canvasElement }) => {
571
- await assertScrollsInsideTheDocument(canvasElement);
626
+ await assertScrollsAtTheFloor(canvasElement);
572
627
  },
573
628
  };
574
629
 
@@ -648,8 +703,8 @@ const PAGE_WIDE_PANE: Decorator = (Story) => (
648
703
  );
649
704
 
650
705
  /**
651
- * A 1400px image in a pane the width of the page. The mail scrolls where it
652
- * lives and the page holds still — the app never learns how wide the picture
706
+ * A 1400px image in a pane the width of the page. The mail is scaled to its
707
+ * frame and the page holds still — the app never learns how wide the picture
653
708
  * was.
654
709
  */
655
710
  export const OversizedImageLeavesThePageStill: Story = {
@@ -675,3 +730,180 @@ export const OversizedImageLeavesThePageStill: Story = {
675
730
  await expect(page.scrollWidth).toBeLessThanOrEqual(page.clientWidth);
676
731
  },
677
732
  };
733
+
734
+ /* ------------------------------------------------------------------ */
735
+ /* A fixed-width newsletter on a phone */
736
+ /* ------------------------------------------------------------------ */
737
+
738
+ // A weekly-digest newsletter laid out at a fixed 600px: a banner that will not
739
+ // shrink below its width and body cells pinned with `min-width`. At device width
740
+ // it ran off the right edge of a phone; it fits by scaling, as K-9 Mail shows it.
741
+ const FIXED_WIDTH_NEWSLETTER = `${LAYOUT_CLAMP_CSS}
742
+ <table width="600" cellpadding="0" cellspacing="0" style="width:600px;min-width:600px;margin:0 auto;border-collapse:collapse;font-family:Helvetica,Arial,sans-serif;color:#1a1a1a;">
743
+ <tr>
744
+ <td style="min-width:600px;padding:0;">
745
+ <img src="${HERO}" alt="Weekly digest" width="600" height="200" style="display:block;min-width:600px;" />
746
+ </td>
747
+ </tr>
748
+ <tr>
749
+ <td style="min-width:552px;padding:24px;background:#ffffff;">
750
+ <h1 style="margin:0 0 12px;font-size:24px;">This week in cloud</h1>
751
+ <p style="margin:0 0 12px;line-height:1.5;">Three pricing changes shipped on
752
+ Tuesday, one of them quietly. The storage tier nobody used is gone, and
753
+ the one everybody used costs a little more.</p>
754
+ <p style="margin:0;line-height:1.5;"><a id="read-more" href="https://example.com/issue/412" style="color:#1a6fb5;">Read the whole issue &rarr;</a></p>
755
+ </td>
756
+ </tr>
757
+ </table>
758
+ `;
759
+
760
+ /** A 600px newsletter on a phone: laid out at its own width and scaled down to
761
+ * the screen, links and all. */
762
+ export const FixedWidthNewsletterFitsThePhone: Story = {
763
+ args: {
764
+ html: FIXED_WIDTH_NEWSLETTER,
765
+ variant: "framed",
766
+ isDark: false,
767
+ declares: DESIGNED,
768
+ },
769
+ globals: { viewport: { value: "mobile" } },
770
+ decorators: [BARE_PHONE],
771
+ play: async ({ canvasElement }) => {
772
+ await assertScaledToFit(canvasElement);
773
+ const link = await frameElement(canvasElement, "read-more");
774
+ await expect(link.getAttribute("href")).toBe(
775
+ "https://example.com/issue/412",
776
+ );
777
+ const target = link.getBoundingClientRect();
778
+ const tapped = link.ownerDocument.elementFromPoint(
779
+ target.left + target.width / 2,
780
+ target.top + target.height / 2,
781
+ );
782
+ await expect(tapped).toBe(link);
783
+ },
784
+ };
785
+
786
+ /** Mail that fits the phone is shown at its own size: never scaled, up or down. */
787
+ export const NarrowMailIsShownAtItsOwnSize: Story = {
788
+ args: { html: BARE_MAIL, variant: "framed", isDark: false, declares: BARE },
789
+ globals: { viewport: { value: "mobile" } },
790
+ decorators: [BARE_PHONE],
791
+ play: async ({ canvasElement }) => {
792
+ const iframe = canvasElement.querySelector("iframe");
793
+ if (!iframe) throw new Error("no email frame in the story");
794
+ await waitFor(() => {
795
+ if (iframe.getBoundingClientRect().height <= 1) {
796
+ throw new Error("the frame has not measured its mail yet");
797
+ }
798
+ });
799
+ const body = iframe.contentDocument?.body;
800
+ if (!body) throw new Error("the frame has not parsed its document yet");
801
+ await expect(transformOf(body)).toBe("none");
802
+ const frameWidth = iframe.contentDocument?.documentElement.clientWidth ?? 0;
803
+ await expect(
804
+ Math.abs(body.getBoundingClientRect().width - frameWidth),
805
+ ).toBeLessThanOrEqual(1);
806
+ },
807
+ };
808
+
809
+ /** The phone turns to landscape and the frame widens past the newsletter's
810
+ * 600px: the mail is refitted, which here means shown at its own size. */
811
+ export const FixedWidthNewsletterRefitsWhenTheFrameWidens: Story = {
812
+ args: {
813
+ html: FIXED_WIDTH_NEWSLETTER,
814
+ variant: "framed",
815
+ isDark: false,
816
+ declares: DESIGNED,
817
+ },
818
+ decorators: [BARE_PHONE],
819
+ play: async ({ canvasElement }) => {
820
+ await assertScaledToFit(canvasElement);
821
+ const pane = canvasElement.querySelector<HTMLElement>("[data-pane]");
822
+ const body = canvasElement.querySelector("iframe")?.contentDocument?.body;
823
+ if (!pane || !body) throw new Error("no framed mail in the story");
824
+ pane.style.width = "720px";
825
+ await waitFor(() => expect(transformOf(body)).toBe("none"));
826
+ await expect(body.scrollWidth).toBeLessThanOrEqual(body.clientWidth);
827
+ },
828
+ };
829
+
830
+ const FRACTIONAL_PHONE: Decorator = (Story) => (
831
+ <div data-pane className="bg-canvas" style={{ width: 390.5 }}>
832
+ <Story />
833
+ </div>
834
+ );
835
+
836
+ /** A fluid newsletter in a phone column on a fractional boundary. The DOM rounds
837
+ * the widths it reports, so the mail can measure a pixel wider than the frame;
838
+ * that pixel is not a reason to shrink it and blur the text. */
839
+ export const FractionalPhoneColumnIsNotScaled: Story = {
840
+ args: {
841
+ html: SUBSTACK,
842
+ variant: "framed",
843
+ isDark: false,
844
+ declares: DESIGNED,
845
+ },
846
+ decorators: [FRACTIONAL_PHONE],
847
+ play: async ({ canvasElement }) => {
848
+ const iframe = canvasElement.querySelector("iframe");
849
+ if (!iframe) throw new Error("no email frame in the story");
850
+ await waitFor(() => {
851
+ if (iframe.getBoundingClientRect().height <= 1) {
852
+ throw new Error("the frame has not measured its mail yet");
853
+ }
854
+ });
855
+ const body = iframe.contentDocument?.body;
856
+ if (!body) throw new Error("the frame has not parsed its document yet");
857
+ await expect(transformOf(body)).toBe("none");
858
+ },
859
+ };
860
+
861
+ const VERY_WIDE_MAIL = `${LAYOUT_CLAMP_CSS}
862
+ <div style="width:100000px;font-family:Helvetica,Arial,sans-serif;color:#1a1a1a;">
863
+ <p>A generator that set its container a hundred thousand pixels wide.</p>
864
+ </div>
865
+ `;
866
+
867
+ /** A mail a hundred thousand pixels wide: fitting it would shrink it to nothing,
868
+ * so it stops at the readable floor and scrolls sideways for the rest. */
869
+ export const VeryWideMailScrollsAtTheFloor: Story = {
870
+ args: {
871
+ html: VERY_WIDE_MAIL,
872
+ variant: "framed",
873
+ isDark: false,
874
+ declares: DESIGNED,
875
+ },
876
+ decorators: [BARE_PHONE],
877
+ play: async ({ canvasElement }) => {
878
+ await assertScrollsAtTheFloor(canvasElement);
879
+ },
880
+ };
881
+
882
+ const PADDED_FULL_WIDTH_MAIL = `${LAYOUT_CLAMP_CSS}
883
+ <table width="600" style="width:600px;min-width:600px;border-collapse:collapse;">
884
+ <tr><td style="min-width:600px;padding:0;background:#1d1d2b;color:#ffffff;">Weekly digest</td></tr>
885
+ </table>
886
+ <div id="padded" style="width:100%;padding:0 40px;background:#efefef;font-family:Helvetica,Arial,sans-serif;">
887
+ <p>A block as wide as the mail plus padding of its own, which overflows any width it is given.</p>
888
+ </div>
889
+ `;
890
+
891
+ /** A `width:100%` block with padding beside a 600px table: it overflows the
892
+ * width the mail is laid out at, and the scale covers that overflow too, so no
893
+ * sliver is left to scroll. */
894
+ export const PaddedFullWidthBlockFitsWithTheRest: Story = {
895
+ args: {
896
+ html: PADDED_FULL_WIDTH_MAIL,
897
+ variant: "framed",
898
+ isDark: false,
899
+ declares: DESIGNED,
900
+ },
901
+ decorators: [BARE_PHONE],
902
+ play: async ({ canvasElement }) => {
903
+ await assertScaledToFit(canvasElement);
904
+ const padded = await frameElement(canvasElement, "padded");
905
+ await expect(padded.getBoundingClientRect().right).toBeLessThanOrEqual(
906
+ padded.ownerDocument.documentElement.clientWidth + 0.5,
907
+ );
908
+ },
909
+ };
@@ -66,6 +66,66 @@ export const measureContentAxis = (
66
66
  max: number,
67
67
  ): number => Math.min(Math.ceil(Math.max(bodyScroll, rootScroll)), max);
68
68
 
69
+ /**
70
+ * The smallest a mail is scaled to. Below it text stops being readable, so mail
71
+ * wider still is shown at this scale and scrolls sideways for the rest.
72
+ */
73
+ export const MIN_FIT_SCALE = 0.5;
74
+
75
+ /**
76
+ * How far a document laid out wider than the frame is scaled down to fit it, the
77
+ * way K-9 Mail and Gmail show a fixed-width newsletter on a phone. Never above 1:
78
+ * mail that fits is shown at its own size, and a pixel of rounding against a
79
+ * fractional column is not a reason to blur it.
80
+ */
81
+ export const fitScale = (
82
+ contentWidth: number,
83
+ viewportWidth: number,
84
+ ): number =>
85
+ viewportWidth > 0 && contentWidth > viewportWidth + 1
86
+ ? Math.max(viewportWidth / contentWidth, MIN_FIT_SCALE)
87
+ : 1;
88
+
89
+ const FIT_PROPERTIES = [
90
+ "box-sizing",
91
+ "width",
92
+ "max-width",
93
+ "transform",
94
+ "transform-origin",
95
+ "margin-bottom",
96
+ "overflow-x",
97
+ ];
98
+
99
+ /**
100
+ * Lay the mail out at its own width and scale it into the frame. The body is
101
+ * measured unscaled first, so every pass starts from the mail's natural layout
102
+ * and a wider or narrower frame refits from scratch. The negative bottom margin
103
+ * takes back the height the transform removed, so the document's scroll height
104
+ * is the scaled one. Content that overflows the width it was given, such as a
105
+ * `width:100%` block with padding, is measured after that width is set and
106
+ * shown rather than scrolled, since the scale covers it. Mail too wide to fit at
107
+ * the floor scale keeps scrolling sideways inside a body as wide as the frame.
108
+ */
109
+ const fitToFrame = (body: HTMLElement): number => {
110
+ for (const property of FIT_PROPERTIES) body.style.removeProperty(property);
111
+ const viewport = body.clientWidth;
112
+ const natural = body.scrollWidth;
113
+ if (fitScale(natural, viewport) === 1) return 1;
114
+ const set = (property: string, value: string) =>
115
+ body.style.setProperty(property, value, "important");
116
+ set("box-sizing", "border-box");
117
+ set("max-width", "none");
118
+ set("width", `${natural}px`);
119
+ const laidOut = Math.max(natural, body.scrollWidth);
120
+ const scale = fitScale(laidOut, viewport);
121
+ if (scale > MIN_FIT_SCALE) set("overflow-x", "visible");
122
+ else set("width", `${viewport / MIN_FIT_SCALE}px`);
123
+ set("transform-origin", "0 0");
124
+ set("transform", `scale(${scale})`);
125
+ set("margin-bottom", `${-body.offsetHeight * (1 - scale)}px`);
126
+ return scale;
127
+ };
128
+
69
129
  /** Named (non-character) keys worth replaying: moving around and closing. */
70
130
  const FORWARDED_NAMED_KEYS = new Set([
71
131
  "Enter",
@@ -130,9 +190,9 @@ const forwardKeyDown = (event: KeyboardEvent) => {
130
190
  * the srcDoc assembly and the height. The width is the app's layout and nothing
131
191
  * else — the frame is never widened to fit the mail, so no measurement of the
132
192
  * email can move a box the reader can see. Content that genuinely cannot wrap (a
133
- * fixed-width table, an oversized image, a `pre` the author pinned) scrolls
134
- * inside the document, where it lives; the pane and the page never learn about
135
- * it.
193
+ * fixed-width table, an oversized image, a `pre` the author pinned) is laid out
194
+ * at its own width and scaled down inside the document to fit the frame; the
195
+ * pane and the page never learn about it.
136
196
  *
137
197
  * Height is the one axis the frame reads off its content: a seamless inline
138
198
  * frame has to grow to the mail it shows or it would scroll internally against
@@ -161,14 +221,28 @@ export const IsolatedEmailFrame = ({
161
221
  const doc = iframe.contentDocument;
162
222
  if (!doc?.body) return;
163
223
  const root = doc.documentElement;
164
- const next = measureContentAxis(
165
- doc.body.scrollHeight,
166
- root?.scrollHeight ?? 0,
167
- MAX_HEIGHT_PX,
168
- );
224
+ const scale = fitToFrame(doc.body);
225
+ const next =
226
+ scale < 1
227
+ ? measureContentAxis(
228
+ doc.body.getBoundingClientRect().height,
229
+ 0,
230
+ MAX_HEIGHT_PX,
231
+ )
232
+ : measureContentAxis(
233
+ doc.body.scrollHeight,
234
+ root?.scrollHeight ?? 0,
235
+ MAX_HEIGHT_PX,
236
+ );
169
237
  setHeight((prev) => (prev === next ? prev : next));
170
238
  };
171
239
 
240
+ let pendingFrame = 0;
241
+ const measureNextFrame = () => {
242
+ cancelAnimationFrame(pendingFrame);
243
+ pendingFrame = requestAnimationFrame(measure);
244
+ };
245
+
172
246
  let observer: ResizeObserver | undefined;
173
247
  let keyDoc: Document | undefined;
174
248
  const handleLoad = () => {
@@ -183,7 +257,7 @@ export const IsolatedEmailFrame = ({
183
257
  keyDoc = undefined;
184
258
  const doc = iframe.contentDocument;
185
259
  if (!doc?.body) return;
186
- observer = new ResizeObserver(measure);
260
+ observer = new ResizeObserver(measureNextFrame);
187
261
  observer.observe(doc.body);
188
262
  if (doc.documentElement) observer.observe(doc.documentElement);
189
263
  // A ResizeObserver watches the body's BOX, which reflows with the pane
@@ -204,6 +278,7 @@ export const IsolatedEmailFrame = ({
204
278
  keyDoc?.removeEventListener("keydown", forwardKeyDown);
205
279
  keyDoc?.removeEventListener("load", measure, true);
206
280
  observer?.disconnect();
281
+ cancelAnimationFrame(pendingFrame);
207
282
  };
208
283
  }, []);
209
284
 
@@ -113,4 +113,15 @@ describe("MobileReadingPane", () => {
113
113
  assert.match(html, /title="Reply"/);
114
114
  assert.doesNotMatch(html, /title="Reply \(r\)"/);
115
115
  });
116
+
117
+ it("keeps pinch-zoom enabled on the scroll area when swipe handlers are set", () => {
118
+ const html = renderToString(
119
+ createElement(MobileReadingPane, {
120
+ thread,
121
+ onBack: () => undefined,
122
+ touchHandlers: { onTouchStart: () => undefined },
123
+ }),
124
+ );
125
+ assert.match(html, /touch-action:\s*pan-y pinch-zoom/);
126
+ });
116
127
  });
@@ -131,7 +131,7 @@ export function MobileReadingPane({
131
131
 
132
132
  <div
133
133
  className="flex-1 overflow-y-auto"
134
- style={touchHandlers ? { touchAction: "pan-y" } : undefined}
134
+ style={touchHandlers ? { touchAction: "pan-y pinch-zoom" } : undefined}
135
135
  {...touchHandlers}
136
136
  >
137
137
  {/* Newest first, as on the wide pane. */}