@vinena/knobs 0.5.0 → 0.5.2

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.
Files changed (75) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +7 -0
  3. package/dist/early.global.js +6 -6
  4. package/dist/{elementsview-6g274ptr.js → elementsview-2z4pkrdz.js} +4 -4
  5. package/dist/{elementsview-pkzp9kc6.js → elementsview-qn8qyksa.js} +4 -4
  6. package/dist/engine/browserdraw.d.ts +24 -2
  7. package/dist/engine/browserkit.d.ts +18 -1
  8. package/dist/engine/browserui.d.ts +162 -22
  9. package/dist/engine/devicon.d.ts +59 -0
  10. package/dist/engine/fit.d.ts +4 -3
  11. package/dist/engine/foldflip.d.ts +40 -0
  12. package/dist/engine/identity.d.ts +7 -4
  13. package/dist/engine/mock.d.ts +16 -0
  14. package/dist/engine/mockdata.d.ts +4 -1
  15. package/dist/engine/mockdraw.d.ts +14 -2
  16. package/dist/engine/pageshot.d.ts +5 -2
  17. package/dist/engine/safaridraw.d.ts +162 -10
  18. package/dist/engine/screen.d.ts +24 -0
  19. package/dist/engine/store.d.ts +2 -1
  20. package/dist/engine/tabicon.d.ts +43 -0
  21. package/dist/engine/toplayer.d.ts +62 -0
  22. package/dist/engine/touchpointer.d.ts +0 -21
  23. package/dist/engine/underbar.d.ts +61 -0
  24. package/dist/{framekit-g96t6nmq.js → framekit-te90cjs0.js} +2325 -1572
  25. package/dist/{framekit-3n7p79ht.js → framekit-w0v516w5.js} +2325 -1572
  26. package/dist/host.d.ts +51 -0
  27. package/dist/{index-64rd634h.js → index-30fc6php.js} +1 -1
  28. package/dist/{index-dvr4x91q.js → index-9re7sv56.js} +20 -8
  29. package/dist/{index-0casarhy.js → index-agwr37gw.js} +1 -1
  30. package/dist/{index-2d6wvs8h.js → index-dan2kpsd.js} +4 -4
  31. package/dist/{index-kzsb9drs.js → index-hv02xka3.js} +20 -8
  32. package/dist/{index-peh33xjv.js → index-pewcdh28.js} +1 -1
  33. package/dist/{index-d0cjxjsm.js → index-r72tz2vn.js} +1 -1
  34. package/dist/{index-33x9hxe3.js → index-sxe5079a.js} +605 -187
  35. package/dist/{index-5d6qzte3.js → index-trx7bxdk.js} +4 -4
  36. package/dist/{index-5baxvd3v.js → index-xjhwp5cj.js} +275 -112
  37. package/dist/index.d.ts +26 -1
  38. package/dist/index.global.js +270 -176
  39. package/dist/index.js +398 -124
  40. package/dist/instance.d.ts +23 -4
  41. package/dist/{react-pdvseef0.js → react-05jh9jv5.js} +1 -1
  42. package/dist/{react-4kbj1t4h.js → react-16spgn0h.js} +1 -1
  43. package/dist/{react-65tgdbs8.js → react-4pvp6amm.js} +1 -1
  44. package/dist/{react-qv0nykcv.js → react-ayg1bgw3.js} +602 -184
  45. package/dist/{react-xxfpfddf.js → react-exjcpxma.js} +1 -1
  46. package/dist/{react-carf84xv.js → react-fm9y8dbn.js} +275 -112
  47. package/dist/{react-mv9y20jy.js → react-sw8d8c94.js} +4 -4
  48. package/dist/{react-71a9ypex.js → react-zy1mmhgz.js} +4 -4
  49. package/dist/react.js +394 -123
  50. package/dist/{storageview-vdkbp6rt.js → storageview-r595qpt9.js} +4 -4
  51. package/dist/{storageview-j9d44f99.js → storageview-s7heg93p.js} +4 -4
  52. package/dist/types.d.ts +7 -0
  53. package/dist/ui/footer.d.ts +9 -2
  54. package/dist/ui/panel.d.ts +16 -2
  55. package/dist/ui/settings.d.ts +17 -1
  56. package/dist/version.d.ts +2 -0
  57. package/package.json +3 -2
  58. package/skills/devknobs/SKILL.md +1 -1
  59. package/dist/elementsview-jnkbhzkj.js +0 -2873
  60. package/dist/elementsview-tf4qzmtw.js +0 -2874
  61. package/dist/engine/endroom.d.ts +0 -21
  62. package/dist/framekit-095qevka.js +0 -8838
  63. package/dist/framekit-q5aad770.js +0 -8839
  64. package/dist/index-hw56t3zy.js +0 -4800
  65. package/dist/index-k015tb6c.js +0 -357
  66. package/dist/index-ke6v7919.js +0 -4801
  67. package/dist/index-qxye1j73.js +0 -528
  68. package/dist/index-z5ytnj01.js +0 -4563
  69. package/dist/index-zvze25nf.js +0 -686
  70. package/dist/react-eygws6cx.js +0 -358
  71. package/dist/react-sq9pkw4k.js +0 -687
  72. package/dist/react-vjm88w4t.js +0 -4564
  73. package/dist/react-znfrjqk8.js +0 -529
  74. package/dist/storageview-sb23henh.js +0 -2729
  75. package/dist/storageview-vf8v8q8j.js +0 -2728
@@ -28,12 +28,12 @@ import {
28
28
  turnOf,
29
29
  turnedPose,
30
30
  windowRect
31
- } from "./index-peh33xjv.js";
31
+ } from "./index-pewcdh28.js";
32
32
  import {
33
33
  hush,
34
34
  hushOnce,
35
35
  quietFetch
36
- } from "./index-d0cjxjsm.js";
36
+ } from "./index-r72tz2vn.js";
37
37
  import {
38
38
  copyText
39
39
  } from "./index-ztnjefrh.js";
@@ -48,13 +48,16 @@ import {
48
48
  MAT_COLOR_NAMES,
49
49
  SAFARI_TEXT,
50
50
  UNFRAMED,
51
+ ZOOM_MAX,
51
52
  ZOOM_PRESETS,
52
53
  Z_INDEX,
53
54
  __export,
54
55
  addStyle,
55
56
  adoptEarly,
57
+ alphaAt,
56
58
  anchorScroll,
57
59
  apply3 as apply,
60
+ apply4 as apply2,
58
61
  barsOf,
59
62
  barsStep,
60
63
  baseMatchMedia,
@@ -63,11 +66,9 @@ import {
63
66
  coarse,
64
67
  deviceOf,
65
68
  dropEarly,
66
- endRoom,
67
69
  ensureStyle,
68
70
  equip,
69
71
  equip1 as equip2,
70
- findStyle,
71
72
  follow,
72
73
  formId,
73
74
  formOf,
@@ -75,6 +76,7 @@ import {
75
76
  handing,
76
77
  handsSchemeDown,
77
78
  hasTouch,
79
+ islandOf,
78
80
  keep,
79
81
  keepDrawing,
80
82
  layoutOf,
@@ -88,6 +90,7 @@ import {
88
90
  openOf,
89
91
  ownReload,
90
92
  parseColor,
93
+ parseHex,
91
94
  percent,
92
95
  placeIn,
93
96
  plainFrame,
@@ -97,7 +100,10 @@ import {
97
100
  readMessage,
98
101
  readSnapshot,
99
102
  removeStyle,
103
+ round,
104
+ runsUnderBars,
100
105
  screenOf,
106
+ screenSizeOf,
101
107
  settles,
102
108
  snapshotKey,
103
109
  stepZoom,
@@ -106,12 +112,13 @@ import {
106
112
  styleNode,
107
113
  turn,
108
114
  turnRadius,
115
+ turnRect,
109
116
  turnSides,
110
117
  uaPreset,
111
118
  userAgentOf,
112
119
  viewportOf,
113
120
  wheelZoom
114
- } from "./index-5baxvd3v.js";
121
+ } from "./index-xjhwp5cj.js";
115
122
 
116
123
  // src/engine/width.ts
117
124
  var exports_width = {};
@@ -130,7 +137,7 @@ __export(exports_width, {
130
137
  frameWindow: () => frameWindow,
131
138
  foldDevice: () => foldDevice2,
132
139
  fit: () => fit,
133
- apply: () => apply2,
140
+ apply: () => apply3,
134
141
  STRIP: () => STRIP,
135
142
  RIDE_SLOW: () => RIDE_SLOW,
136
143
  FRAME_API_WAIT: () => FRAME_API_WAIT
@@ -159,6 +166,7 @@ function patchWindow(view, state) {
159
166
  const identity = identityOf(state);
160
167
  Reflect.set(view, PATCHED, identity);
161
168
  apply(state.ua, view);
169
+ apply2(screenSizeOf(state), view);
162
170
  if (identity.touch) {
163
171
  equip2(view, uaPreset(state.ua.preset) === undefined);
164
172
  coarse(view);
@@ -2970,7 +2978,7 @@ var BEZELS = {
2970
2978
  opening: [60, 72, 1260, 2736],
2971
2979
  body: [6, 26, 1375, 2854],
2972
2980
  cutout: [503.25, 133.05, 373.76, 107.91],
2973
- radius: PRO
2981
+ radius: 65
2974
2982
  }
2975
2983
  },
2976
2984
  "iphone-17": {
@@ -3155,6 +3163,7 @@ function bezelMock(id, orientation) {
3155
3163
  const own = orientation === "landscape" ? found.landscape : undefined;
3156
3164
  const bezel = own ?? found.portrait;
3157
3165
  const turned = orientation === "landscape" && !own;
3166
+ const clockwise = turned && device.clockwise === true;
3158
3167
  const screen = turn(device, own ? "landscape" : "portrait");
3159
3168
  const scale = density(screen, bezel);
3160
3169
  const [x, y, w, h] = bezel.opening;
@@ -3171,22 +3180,27 @@ function bezelMock(id, orientation) {
3171
3180
  };
3172
3181
  const width = (right - left) / scale;
3173
3182
  const height = (bottom - top) / scale;
3174
- const sides = turned ? turnSides(inset) : inset;
3183
+ const sides = turned ? turnSides(inset, clockwise) : inset;
3175
3184
  const size = turned ? { width: height, height: width } : { width, height };
3185
+ const island = islandOf(id);
3186
+ const flat = island && round("sensor", { ...island, x: inset.left + island.x, y: inset.top + island.y });
3187
+ const parts = flat ? [turned ? turnRect(flat, width, height, clockwise) : flat] : [];
3176
3188
  return {
3177
3189
  ...size,
3178
3190
  inset: sides,
3179
3191
  body: { x: 0, y: 0, ...size },
3180
- screenRadius: turned ? turnRadius(bezel.radius) : bezel.radius,
3192
+ screenRadius: turned ? turnRadius(bezel.radius, clockwise) : bezel.radius,
3193
+ continuous: island !== null,
3181
3194
  bodyRadius: 0,
3182
- parts: [],
3195
+ parts,
3183
3196
  image: {
3184
3197
  file: bezel.file,
3185
3198
  x: -left / scale,
3186
3199
  y: -top / scale,
3187
3200
  width: bezel.size[0] / scale,
3188
3201
  height: bezel.size[1] / scale,
3189
- turn: turned ? width : null
3202
+ turn: turned ? clockwise ? height : width : null,
3203
+ ...clockwise ? { clockwise } : {}
3190
3204
  }
3191
3205
  };
3192
3206
  }
@@ -3559,8 +3573,7 @@ var GLYPHS = {
3559
3573
  bookmarks: () => [],
3560
3574
  tabs: () => [],
3561
3575
  reload: () => [],
3562
- page: () => [],
3563
- more: () => []
3576
+ page: () => []
3564
3577
  };
3565
3578
  function box(className, rect) {
3566
3579
  const node = el("div", className);
@@ -3646,32 +3659,8 @@ function buildChrome(full, mini, look) {
3646
3659
  };
3647
3660
  }
3648
3661
 
3649
- // src/engine/endroom.ts
3650
- var NAME = "endroom";
3651
- var VARIABLE = "--devknobs-end-room";
3652
- var CSS = `:root{${VARIABLE}:0px}html{margin-bottom:var(${VARIABLE})!important}`;
3653
- function holder(style) {
3654
- const rule = style.sheet?.cssRules[0];
3655
- return rule?.style ?? null;
3656
- }
3657
- function give(doc, room) {
3658
- const existing = findStyle(NAME, doc);
3659
- const held = existing ? holder(existing) : null;
3660
- const had = Number.parseFloat(held?.getPropertyValue(VARIABLE) ?? "") || 0;
3661
- if (room <= 0) {
3662
- existing?.remove();
3663
- return had;
3664
- }
3665
- if (had === room)
3666
- return had;
3667
- const style = existing ?? ensureStyle(NAME, doc);
3668
- if (!existing)
3669
- style.textContent = CSS;
3670
- holder(style)?.setProperty(VARIABLE, `${room}px`);
3671
- return had;
3672
- }
3673
-
3674
3662
  // src/engine/safaridraw.ts
3663
+ var DOMAIN_WEIGHT = 500;
3675
3664
  var SAFARI_CSS = `
3676
3665
  .safari {
3677
3666
  color: #000;
@@ -3693,27 +3682,37 @@ var SAFARI_CSS = `
3693
3682
  }
3694
3683
  .safari.dark { color: #f3f3f8; }
3695
3684
  .safari .surface > *, .safari .side > *, .safari .field > * { position: absolute; }
3696
- /* Glass over the page: a fill the page shows faintly through, blurred. */
3697
- .safari .capsule, .safari .card, .safari .surface {
3698
- background: rgba(255, 255, 255, 0.78);
3699
- box-shadow: 0 8px 28px rgba(0, 0, 0, 0.1), 0 0 0 0.5px rgba(0, 0, 0, 0.06);
3700
- -webkit-backdrop-filter: blur(10px) saturate(1.8);
3701
- backdrop-filter: blur(10px) saturate(1.8);
3702
- }
3703
- .safari .card, .safari[data-state="max"] .surface.from-card {
3704
- background: rgba(250, 250, 250, 0.82);
3705
- }
3706
- .safari .field { background: rgba(0, 0, 0, 0.05); }
3707
- /* Sampled from a real iPhone over a dark page. */
3708
- .safari.dark .capsule, .safari.dark .surface {
3709
- background: rgba(40, 40, 42, 0.75);
3710
- box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.13);
3711
- }
3712
- .safari.dark .card, .safari.dark[data-state="max"] .surface.from-card {
3713
- background: rgba(46, 46, 48, 0.8);
3714
- box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.12);
3715
- }
3716
- .safari.dark .field { background: rgba(0, 0, 0, 0.14); }
3685
+ /* Glass over the page: a fill in the tone of the page under it, which shows faintly through, blurred. */
3686
+ .safari .capsule, .safari .surface {
3687
+ -webkit-backdrop-filter: blur(10px);
3688
+ backdrop-filter: blur(10px);
3689
+ }
3690
+ .safari [data-tone="light"] { color: #000; }
3691
+ .safari [data-tone="dark"] { color: #fff; }
3692
+ /* Light glass: a thin darker ring outside (#c8c8c8 on white), a white highlight inside, a soft wide shadow. */
3693
+ .safari [data-rim="none"] {
3694
+ box-shadow:
3695
+ 0 0 0 0.67px rgba(0, 0, 0, 0.215),
3696
+ inset 0 0 0 1px rgba(255, 255, 255, 0.6),
3697
+ 0 6px 24px rgba(0, 0, 0, 0.065);
3698
+ }
3699
+ /* Glass in a page's hue: a lighter rim of its own color inside, iOS 27's darker ring outside. */
3700
+ .safari [data-rim="tint"] {
3701
+ box-shadow:
3702
+ 0 0 0 0.67px rgba(0, 0, 0, 0.215),
3703
+ inset 0 0 0 1px rgba(255, 255, 255, 0.22),
3704
+ 0 6px 24px rgba(0, 0, 0, 0.1);
3705
+ }
3706
+ /* Dark glass: a rim as bright at the bottom as at the top (#585858 fading to #2b2b2b on #222), the darker ring outside, and no shadow. */
3707
+ .safari [data-rim="highlight"] {
3708
+ box-shadow:
3709
+ 0 0 0 0.67px rgba(0, 0, 0, 0.215),
3710
+ inset 0 0 0 1px rgba(255, 255, 255, 0.24),
3711
+ inset 0 0 1.5px 1.5px rgba(255, 255, 255, 0.04);
3712
+ }
3713
+ /* Bottom's field: toward #ddd in light (#fcfcfc to #f2f2f2, #888 to #a3a3a3), toward #1f1f1f in dark. */
3714
+ .safari .field { background: rgba(221, 221, 221, 0.32); }
3715
+ .safari [data-tone="dark"] .field { background: rgba(31, 31, 31, 0.73); }
3717
3716
  .safari .glyph {
3718
3717
  fill: none;
3719
3718
  stroke: currentColor;
@@ -3721,13 +3720,13 @@ var SAFARI_CSS = `
3721
3720
  stroke-linecap: round;
3722
3721
  stroke-linejoin: round;
3723
3722
  }
3724
- .safari .glyph .solid { fill: currentColor; stroke: none; }
3725
3723
  /* Reload and stop are a shade lighter than the other glyphs and thinner, as measured. */
3726
3724
  .safari .glyph .reload { stroke-width: 1.6; }
3727
3725
  .safari .glyph .stop { stroke-width: 1.82; }
3728
- .safari.light .glyph .reload, .safari.light .glyph .stop { stroke: #191919; }
3729
- .safari .glyph.off { color: #babac7; }
3730
- .safari.dark .glyph.off { color: #58585b; }
3726
+ .safari .glyph .page { stroke-width: 2; }
3727
+ .safari [data-tone="light"] .glyph .reload, .safari [data-tone="light"] .glyph .stop { stroke: #191919; }
3728
+ /* A button that does nothing: its glyph at 30%, #babac7 on white glass, #58585b on dark. */
3729
+ .safari .glyph.off { stroke-opacity: 0.3; fill-opacity: 0.3; }
3731
3730
  .safari .domain {
3732
3731
  left: 50%;
3733
3732
  white-space: nowrap;
@@ -3735,14 +3734,14 @@ var SAFARI_CSS = `
3735
3734
  text-overflow: ellipsis;
3736
3735
  text-align: center;
3737
3736
  font-size: ${SAFARI_TEXT.field}px;
3738
- font-weight: 400;
3739
- letter-spacing: -0.2px;
3737
+ font-weight: ${DOMAIN_WEIGHT};
3740
3738
  transform: translate(-50%, -50%);
3741
3739
  }
3742
- .safari .time { font-weight: 600; letter-spacing: -0.3px; transform: translate(-50%, -50%); }
3740
+ .safari .time { font-weight: 600; transform: translate(-50%, -50%); }
3743
3741
  .safari .status { fill: currentColor; }
3744
- .safari .level { fill: #fff; font-size: 9.5px; font-weight: 600; letter-spacing: -0.3px; }
3745
- .safari.dark .level { fill: #000; }
3742
+ /* The battery's uncharged rest: #b2b2b2 on white, #808080 on black. */
3743
+ .safari .status .rest { fill-opacity: 0.3; }
3744
+ .safari.dark .status .rest { fill-opacity: 0.5; }
3746
3745
  /* One surface morphs: its box, corners and color, and the domain glides in it. */
3747
3746
  .safari .surface {
3748
3747
  overflow: hidden;
@@ -3755,7 +3754,10 @@ var SAFARI_CSS = `
3755
3754
  background-color var(--main) ${MORPH.ease},
3756
3755
  box-shadow var(--main) ${MORPH.ease};
3757
3756
  }
3758
- .safari .domain, .safari .fade {
3757
+ /* A minimized Safari's wash under the status bar comes and goes with the bars. */
3758
+ .safari .scrim { left: 0; right: 0; opacity: 0; transition: opacity var(--main) ${MORPH.ease}; }
3759
+ .safari[data-state="min"] .scrim[data-on="true"] { opacity: 1; }
3760
+ .safari .domain {
3759
3761
  transition:
3760
3762
  top var(--main) ${MORPH.ease},
3761
3763
  height var(--main) ${MORPH.ease},
@@ -3830,11 +3832,7 @@ var GLYPHS2 = {
3830
3832
  path2("M6.66 0.92A6.59 6.59 0 1 1 2.93 -5.02", "reload"),
3831
3833
  path2("M-0.15 -8.89L3.26 -5.33L-0.16 -1.93", "reload")
3832
3834
  ],
3833
- page: () => [
3834
- svgNode("rect", { x: -6.8, y: -8.1, width: 13.6, height: 8.6, rx: 2.4 }),
3835
- path2("M-6.8 4.2H6.8M-6.8 8.1H2.6")
3836
- ],
3837
- more: () => [-7.8, 0, 7.8].map((x) => svgNode("circle", { cx: x, cy: 0, r: 2, class: "solid" })),
3835
+ page: () => [path2("M-6.3 -5.1H8M-6.3 0H8M-6.3 5.1H3", "page")],
3838
3836
  plus: () => [path2("M0 -8.5V8.5M-8.5 0H8.5")],
3839
3837
  home: () => [],
3840
3838
  tune: () => [],
@@ -3844,65 +3842,183 @@ var GLYPHS2 = {
3844
3842
  function stopGlyph() {
3845
3843
  return [path2("M-5.66 -5.54L5.88 6M5.88 -5.54L-5.66 6", "stop")];
3846
3844
  }
3845
+ var STATUS_GLYPHS = {
3846
+ regular: {
3847
+ time: { size: 18, spacing: -0.09, drop: 0.33 },
3848
+ gap: 8.5,
3849
+ signal: { width: 3.33, pitch: 5.67, heights: [6.33, 8.67, 11, 13.67], radius: 1.1, drop: 7.67 },
3850
+ wifi: {
3851
+ width: 18.67,
3852
+ height: 13.67,
3853
+ bands: [0, 3.14, 6.09, 7.83, 10.78, 12.57],
3854
+ angle: 45.4,
3855
+ round: 1.1,
3856
+ drop: 7.33
3857
+ },
3858
+ battery: { width: 26.33, height: 13.67, radius: 4.67, gap: 0.67, cap: [2, 5], drop: -0.5 }
3859
+ },
3860
+ large: {
3861
+ time: { size: 19, spacing: -0.09, drop: 0.5 },
3862
+ gap: 8.67,
3863
+ signal: { width: 3.67, pitch: 6.11, heights: [7, 9.33, 12, 15], radius: 1.2, drop: 8.33 },
3864
+ wifi: {
3865
+ width: 20.33,
3866
+ height: 15,
3867
+ bands: [0, 3.45, 6.68, 8.59, 11.83, 13.79],
3868
+ angle: 45,
3869
+ round: 1.2,
3870
+ drop: 8
3871
+ },
3872
+ battery: { width: 29.33, height: 15, radius: 5, gap: 1, cap: [2, 5], drop: -0.5 }
3873
+ }
3874
+ };
3847
3875
  function fan(from, to, angle) {
3848
3876
  const rad = angle * Math.PI / 180;
3849
3877
  const at = (r, side) => `${(side * r * Math.sin(rad)).toFixed(2)} ${(-r * Math.cos(rad)).toFixed(2)}`;
3850
3878
  const inner = from > 0 ? `L${at(from, 1)}A${from} ${from} 0 0 0 ${at(from, -1)}Z` : "L0 0Z";
3851
3879
  return `M${at(to, -1)}A${to} ${to} 0 0 1 ${at(to, 1)}${inner}`;
3852
3880
  }
3853
- function wifi(x, y) {
3854
- const svg = svgNode("svg", { class: "status", viewBox: "-8.5 -12.3 17 12.3" });
3855
- place(svg, x, y - 6.15, 17, 12.3);
3856
- svg.append(...[fan(0, 3.6, 46), fan(5.5, 8.2, 46), fan(9.9, 12.3, 46)].map((d) => {
3857
- const round = { "stroke-linejoin": "round", stroke: "currentColor", "stroke-width": 0.6 };
3858
- return svgNode("path", { d, ...round });
3859
- }));
3881
+ function wifi(x, bottom, size) {
3882
+ const { width, height, bands, angle, round: round2 } = size;
3883
+ const viewBox = `${-width / 2} ${round2 / 2 - height} ${width} ${height}`;
3884
+ const svg = svgNode("svg", { class: "status", viewBox });
3885
+ place(svg, x, bottom - height, width, height);
3886
+ const stroke = { "stroke-linejoin": "round", stroke: "currentColor", "stroke-width": round2 };
3887
+ const pairs = [0, 2, 4].map((at) => fan(bands[at] ?? 0, bands[at + 1] ?? 0, angle));
3888
+ svg.append(...pairs.map((d) => svgNode("path", { d, ...stroke })));
3860
3889
  return svg;
3861
3890
  }
3862
- function signal(x, y) {
3863
- const svg = svgNode("svg", { class: "status", viewBox: "0 0 18 12" });
3864
- place(svg, x, y - 6, 18, 12);
3865
- svg.append(...[4.4, 6.8, 9.2, 12].map((height, at) => svgNode("rect", { x: at * 4.93, y: 12 - height, width: 3.2, height, rx: 1 })));
3891
+ function signal(x, bottom, size) {
3892
+ const { width, pitch, heights, radius } = size;
3893
+ const tall = Math.max(...heights);
3894
+ const wide = pitch * (heights.length - 1) + width;
3895
+ const svg = svgNode("svg", { class: "status", viewBox: `0 0 ${wide} ${tall}` });
3896
+ place(svg, x, bottom - tall, wide, tall);
3897
+ svg.append(...heights.map((height, at) => svgNode("rect", { x: at * pitch, y: tall - height, width, height, rx: radius })));
3866
3898
  return svg;
3867
3899
  }
3868
- function battery(x, y) {
3869
- const svg = svgNode("svg", { class: "status", viewBox: "0 0 27.3 13" });
3870
- place(svg, x, y - 6.5, 27.3, 13);
3871
- const level = svgNode("text", {
3872
- class: "level",
3873
- x: 12.6,
3874
- y: 6.9,
3875
- "text-anchor": "middle",
3876
- "dominant-baseline": "middle"
3877
- });
3878
- level.textContent = String(CHARGE);
3879
- const edge = (25.2 * CHARGE / 100).toFixed(2);
3880
- svg.append(svgNode("rect", { x: 0, y: 0, width: 25.2, height: 13, rx: 4.2, "fill-opacity": 0.4 }), svgNode("path", { d: `M4.2 0H${edge}V13H4.2A4.2 4.2 0 0 1 0 8.8V4.2A4.2 4.2 0 0 1 4.2 0Z` }), level, svgNode("path", {
3881
- d: "M26.1 4.6a1.2 1.2 0 0 1 1.2 1.2v1.4a1.2 1.2 0 0 1-1.2 1.2Z",
3882
- "fill-opacity": 0.4
3900
+ function batteryWidth(size) {
3901
+ return size.width + size.gap + size.cap[0];
3902
+ }
3903
+ function chargedPath(width, height, radius, level) {
3904
+ const r = Math.min(radius, height / 2, width / 2);
3905
+ const x = Math.max(0, Math.min(width, level));
3906
+ const inset = (along) => r - Math.sqrt(Math.max(0, r * r - (r - along) ** 2));
3907
+ const f = (n) => Number(n.toFixed(3));
3908
+ if (x <= r) {
3909
+ const y2 = inset(x);
3910
+ return `M${f(x)} ${f(y2)}A${r} ${r} 0 0 0 0 ${r}V${f(height - r)}A${r} ${r} 0 0 0 ${f(x)} ${f(height - y2)}Z`;
3911
+ }
3912
+ const left = `H${r}A${r} ${r} 0 0 0 0 ${r}V${f(height - r)}A${r} ${r} 0 0 0 ${r} ${height}`;
3913
+ if (x < width - r)
3914
+ return `M${f(x)} 0${left}H${f(x)}Z`;
3915
+ const y = inset(width - x);
3916
+ return `M${f(x)} ${f(y)}A${r} ${r} 0 0 0 ${f(width - r)} 0${left}` + `H${f(width - r)}A${r} ${r} 0 0 0 ${f(x)} ${f(height - y)}Z`;
3917
+ }
3918
+ function batteryParts(size, charge) {
3919
+ const { width, height, radius, gap, cap } = size;
3920
+ const [capWidth, capHeight] = cap;
3921
+ return {
3922
+ body: { x: 0, y: 0, width, height, rx: radius },
3923
+ level: { d: chargedPath(width, height, radius, width * charge / 100) },
3924
+ cap: { x: width + gap, y: (height - capHeight) / 2, width: capWidth, height: capHeight }
3925
+ };
3926
+ }
3927
+ function battery(x, middle, size) {
3928
+ const wide = batteryWidth(size);
3929
+ const svg = svgNode("svg", { class: "status", viewBox: `0 0 ${wide} ${size.height}` });
3930
+ place(svg, x, middle - size.height / 2, wide, size.height);
3931
+ const { body, level, cap } = batteryParts(size, CHARGE);
3932
+ const r = Math.min(cap.width, cap.height / 2);
3933
+ const end = cap.x + cap.width;
3934
+ const bottom = cap.y + cap.height;
3935
+ svg.append(svgNode("rect", { ...body, class: "rest" }), svgNode("path", level), svgNode("path", {
3936
+ d: `M${cap.x} ${cap.y}H${end - r}A${r} ${r} 0 0 1 ${end} ${cap.y + r}` + `V${bottom - r}A${r} ${r} 0 0 1 ${end - r} ${bottom}H${cap.x}Z`,
3937
+ class: "rest"
3883
3938
  }));
3884
3939
  return svg;
3885
3940
  }
3886
3941
  function statusBar(status) {
3942
+ const glyphs = status.large ? STATUS_GLYPHS.large : STATUS_GLYPHS.regular;
3887
3943
  const time = el("div", "time", "04:20");
3888
3944
  time.style.left = `${status.time.x}px`;
3889
- time.style.top = `${status.time.y}px`;
3945
+ time.style.top = `${status.time.y + glyphs.time.drop}px`;
3890
3946
  time.style.fontSize = `${status.time.size}px`;
3947
+ time.style.letterSpacing = `${glyphs.time.spacing}px`;
3891
3948
  const { icons } = status;
3949
+ const { signal: bars, wifi: air, battery: cell } = glyphs;
3892
3950
  if (icons.align === "start") {
3893
3951
  const end = status.battery ?? { x: icons.x, y: icons.y };
3952
+ const bottom = icons.y + Math.max(...bars.heights) / 2;
3894
3953
  const nodes = [
3895
- signal(icons.x, icons.y),
3896
- wifi(icons.x + 23, icons.y),
3897
- battery(end.x - 27.3, end.y)
3954
+ signal(icons.x, bottom, bars),
3955
+ wifi(icons.x + 23, icons.y + air.height / 2, air),
3956
+ battery(end.x - batteryWidth(cell), end.y, cell)
3898
3957
  ];
3899
3958
  for (const node of nodes)
3900
3959
  node.style.transform = "scale(0.85)";
3901
3960
  return [time, ...nodes];
3902
3961
  }
3903
- const cell = icons.x - 27.3;
3904
- const air = cell - 7.3 - 17;
3905
- return [time, signal(air - 6 - 18, icons.y), wifi(air, icons.y), battery(cell, icons.y)];
3962
+ const right = icons.x - batteryWidth(cell);
3963
+ const middle = right - glyphs.gap - air.width;
3964
+ const left = middle - glyphs.gap - (bars.pitch * (bars.heights.length - 1) + bars.width);
3965
+ return [
3966
+ time,
3967
+ signal(left, icons.y + bars.drop, bars),
3968
+ wifi(middle, icons.y + air.drop, air),
3969
+ battery(right, icons.y + cell.drop, cell)
3970
+ ];
3971
+ }
3972
+ var DUO_GLYPHS = {
3973
+ time: { spacing: 0, drop: 0.8 },
3974
+ ends: 55,
3975
+ dots: [-30.5, -10, 10, 30.5],
3976
+ dot: 2,
3977
+ rest: 0.35,
3978
+ wifi: {
3979
+ width: 18.2,
3980
+ height: 13.33,
3981
+ bands: [0, 3.06, 5.94, 7.64, 10.51, 12.26],
3982
+ angle: 45.4,
3983
+ round: 1.1,
3984
+ drop: 0
3985
+ }
3986
+ };
3987
+ function onCircle(r, angle) {
3988
+ const rad = angle * Math.PI / 180;
3989
+ return `${(r * Math.cos(rad)).toFixed(2)} ${(r * Math.sin(rad)).toFixed(2)}`;
3990
+ }
3991
+ function arc(r, from, to) {
3992
+ const large = to - from > 180 ? 1 : 0;
3993
+ return `M${onCircle(r, from)}A${r} ${r} 0 ${large} 1 ${onCircle(r, to)}`;
3994
+ }
3995
+ function ring(x, y, size) {
3996
+ const { radius, stroke } = size;
3997
+ const reach = radius + stroke;
3998
+ const svg = svgNode("svg", { class: "status ring", viewBox: `${-reach} ${-reach} ${2 * reach} ${2 * reach}` });
3999
+ place(svg, x - reach, y - reach, 2 * reach, 2 * reach);
4000
+ const from = 90 + DUO_GLYPHS.ends;
4001
+ const to = 450 - DUO_GLYPHS.ends;
4002
+ const charged = from + (to - from) * CHARGE / 100;
4003
+ const line = { fill: "none", stroke: "currentColor", "stroke-width": stroke, "stroke-linecap": "round" };
4004
+ svg.append(svgNode("path", { d: arc(radius, charged, to), ...line, "stroke-opacity": DUO_GLYPHS.rest }), svgNode("path", { d: arc(radius, from, charged), ...line }), ...DUO_GLYPHS.dots.map((angle) => {
4005
+ const rad = (90 + angle) * Math.PI / 180;
4006
+ return svgNode("circle", { cx: radius * Math.cos(rad), cy: radius * Math.sin(rad), r: DUO_GLYPHS.dot });
4007
+ }));
4008
+ return svg;
4009
+ }
4010
+ function statusColumn(column) {
4011
+ const time = el("div", "time", "04:20");
4012
+ time.style.left = `${column.time.x}px`;
4013
+ time.style.top = `${column.time.y + DUO_GLYPHS.time.drop}px`;
4014
+ time.style.fontSize = `${column.time.size}px`;
4015
+ time.style.letterSpacing = `${DUO_GLYPHS.time.spacing}px`;
4016
+ const air = DUO_GLYPHS.wifi;
4017
+ return [
4018
+ time,
4019
+ ring(column.x, column.ring.y, column.ring),
4020
+ wifi(column.x - air.width / 2, column.ring.y + air.height / 2, air)
4021
+ ];
3906
4022
  }
3907
4023
  function pressOf(glyph, actions) {
3908
4024
  if (glyph === "back")
@@ -3919,33 +4035,135 @@ function glyphIn(mark, origin, className, actions) {
3919
4035
  svg.style.top = `${mark.y - origin.y - 15}px`;
3920
4036
  return svg;
3921
4037
  }
4038
+ function domainOf(host) {
4039
+ return host.replace(/:\d+$/, "");
4040
+ }
3922
4041
  function pillBox(pill, host) {
3923
- const width = Math.round(textWidth(host, SAFARI_TEXT.pill, 400, -0.2)) + 38;
4042
+ const size = pill.text?.size ?? SAFARI_TEXT.pill;
4043
+ const width = Math.round(textWidth(domainOf(host), size, DOMAIN_WEIGHT)) + (pill.text?.pad ?? 0);
3924
4044
  return { x: pill.x - width / 2, y: pill.y, width, height: pill.height };
3925
4045
  }
4046
+ function hslOf({ red, green, blue }) {
4047
+ const [r, g, b] = [red / 255, green / 255, blue / 255];
4048
+ const high = Math.max(r, g, b);
4049
+ const low = Math.min(r, g, b);
4050
+ const lightness = (high + low) / 2;
4051
+ const span = high - low;
4052
+ if (span === 0)
4053
+ return [0, 0, lightness];
4054
+ const saturation = span / (1 - Math.abs(2 * lightness - 1));
4055
+ const hue = high === r ? (g - b) / span + 6 : high === g ? (b - r) / span + 2 : (r - g) / span + 4;
4056
+ return [hue * 60 % 360, saturation, lightness];
4057
+ }
4058
+ function fromHsl(hue, saturation, lightness) {
4059
+ const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
4060
+ const at = (hue % 360 + 360) % 360 / 60;
4061
+ const second = chroma * (1 - Math.abs(at % 2 - 1));
4062
+ const sectors = [
4063
+ [chroma, second, 0],
4064
+ [second, chroma, 0],
4065
+ [0, chroma, second],
4066
+ [0, second, chroma],
4067
+ [second, 0, chroma],
4068
+ [chroma, 0, second]
4069
+ ];
4070
+ const [r = 0, g = 0, b = 0] = sectors[Math.floor(at) % 6] ?? [];
4071
+ const m = lightness - chroma / 2;
4072
+ return { red: (r + m) * 255, green: (g + m) * 255, blue: (b + m) * 255, alpha: 1 };
4073
+ }
4074
+ function hexOf({ red, green, blue }) {
4075
+ const pair = (channel) => Math.min(255, Math.max(0, Math.round(channel))).toString(16).padStart(2, "0");
4076
+ return `#${pair(red)}${pair(green)}${pair(blue)}`;
4077
+ }
4078
+ var GLASS_GRAY = { light: [137, 248], dark: [34, 179] };
4079
+ function glassTint(under, scheme) {
4080
+ const [hue, saturation, lightness] = hslOf(under);
4081
+ const [low, high] = GLASS_GRAY[scheme];
4082
+ const gray = low + (high - low) * lightness;
4083
+ const neutral = { red: gray, green: gray, blue: gray, alpha: 1 };
4084
+ const light = scheme === "light";
4085
+ const hued = light ? fromHsl(hue - 4, Math.min(1, saturation * 1.3 + 0.05), Math.min(0.9, lightness + 0.26)) : fromHsl(hue, Math.min(1, saturation + 0.15), Math.min(0.9, lightness * 1.4 - 0.1));
4086
+ const chroma = saturation * (1 - Math.abs(2 * lightness - 1));
4087
+ const share = Math.min(1, chroma / (light ? 0.8 : 0.7));
4088
+ const mix = (a, b) => a + (b - a) * share;
4089
+ const fill = {
4090
+ red: mix(neutral.red, hued.red),
4091
+ green: mix(neutral.green, hued.green),
4092
+ blue: mix(neutral.blue, hued.blue),
4093
+ alpha: 1
4094
+ };
4095
+ const glyph = light ? "dark" : "light";
4096
+ const rim = share > 0.3 ? "tint" : light ? "none" : "highlight";
4097
+ return { fill: hexOf(fill), glyph, rim };
4098
+ }
4099
+ var GLASS_ALPHA = 0.9;
4100
+ function glassFill(fill, under) {
4101
+ const own = (want, page) => Math.min(255, Math.max(0, Math.round((want - (1 - GLASS_ALPHA) * page) / GLASS_ALPHA)));
4102
+ const [r, g, b] = [
4103
+ own(fill.red, under.red),
4104
+ own(fill.green, under.green),
4105
+ own(fill.blue, under.blue)
4106
+ ];
4107
+ return `rgba(${r}, ${g}, ${b}, ${GLASS_ALPHA})`;
4108
+ }
4109
+ var WHITE = { red: 255, green: 255, blue: 255, alpha: 1 };
4110
+ function underAt(look, x, y) {
4111
+ let best = null;
4112
+ let far = Infinity;
4113
+ for (const sample of look.under) {
4114
+ const distance = Math.hypot(sample.x - x, sample.y - y);
4115
+ if (distance < far) {
4116
+ far = distance;
4117
+ best = sample.color;
4118
+ }
4119
+ }
4120
+ return parseColor(best ?? look.background) ?? WHITE;
4121
+ }
4122
+ function tintGlass(node, box2, look) {
4123
+ const under = underAt(look, box2.x + box2.width / 2, box2.y + box2.height / 2);
4124
+ const tint = glassTint(under, look.scheme);
4125
+ node.style.backgroundColor = glassFill(parseHex(tint.fill) ?? WHITE, under);
4126
+ node.dataset.tone = tint.glyph === "dark" ? "light" : "dark";
4127
+ node.dataset.rim = tint.rim;
4128
+ return under;
4129
+ }
3926
4130
  function placeBox(node, box2, radius) {
3927
4131
  place(node, box2.x, box2.y, box2.width, box2.height);
3928
4132
  node.style.borderRadius = `${radius}px`;
3929
4133
  }
3930
- function placeFade(node, fade, look) {
3931
- node.hidden = fade === null;
3932
- if (!fade)
3933
- return;
3934
- node.style.top = `${fade.y}px`;
3935
- node.style.height = `${fade.height}px`;
3936
- const color = (alpha) => look.background.replace(/^rgb\((.*)\)$/, `rgba($1, ${alpha})`);
3937
- const stops = fade.stops.map(({ at, alpha }) => `${color(alpha)} ${at}px`);
4134
+ function over(top, under, alpha) {
4135
+ const mix = (a, b) => a * alpha + b * (1 - alpha);
4136
+ return {
4137
+ red: mix(top.red, under.red),
4138
+ green: mix(top.green, under.green),
4139
+ blue: mix(top.blue, under.blue),
4140
+ alpha: 1
4141
+ };
4142
+ }
4143
+ function scrimOver(node, mini, look) {
4144
+ const { scrim, status } = mini;
4145
+ const held = look.top !== look.background;
4146
+ node.dataset.on = String(scrim !== null && !held);
4147
+ if (!scrim || held)
4148
+ return null;
4149
+ const page = parseColor(look.background) ?? WHITE;
4150
+ const { red, green, blue } = page;
4151
+ node.style.top = `${scrim.y}px`;
4152
+ node.style.height = `${scrim.height}px`;
4153
+ const stops = scrim.stops.map(({ at, alpha }) => `rgba(${red}, ${green}, ${blue}, ${alpha}) ${at}px`);
3938
4154
  node.style.background = `linear-gradient(to bottom, ${stops.join(", ")})`;
4155
+ const content = underAt(look, scrim.at.x, scrim.at.y);
4156
+ return over(page, content, alphaAt(scrim, status?.time.y ?? 0));
3939
4157
  }
3940
4158
  function buildSafari(full, mini, look, actions) {
3941
4159
  const root = el("div", "safari");
3942
4160
  root.style.inset = "0";
3943
- const fade = el("div", "fade");
3944
- fade.style.left = "0";
3945
- fade.style.right = "0";
3946
- root.append(fade);
4161
+ const scrim = el("div", "scrim");
4162
+ root.append(scrim);
3947
4163
  if (full.status)
3948
4164
  root.append(...statusBar(full.status));
4165
+ const column = full.column ? statusColumn(full.column) : [];
4166
+ root.append(...column);
3949
4167
  const pill = mini.shapes.find((shape) => shape.kind === "pill") ?? null;
3950
4168
  const main = pill ? full.shapes.find((shape) => shape.kind === "card") ?? full.shapes.find((shape) => shape.text !== undefined) ?? null : null;
3951
4169
  let surface = null;
@@ -3995,11 +4213,13 @@ function buildSafari(full, mini, look, actions) {
3995
4213
  progress.hidden = true;
3996
4214
  surface?.append(progress);
3997
4215
  let loads3 = 0;
4216
+ const sides = [];
3998
4217
  for (const shape of full.shapes) {
3999
4218
  if (shape === main || shape.kind === "field")
4000
4219
  continue;
4001
4220
  const side = el("div", "side capsule");
4002
4221
  placeBox(side, shape, shape.radius);
4222
+ sides.push({ node: side, box: shape });
4003
4223
  const middle = shape.x + shape.width / 2;
4004
4224
  const across = full.orientation === "landscape";
4005
4225
  const toward = main ? main.x + main.width / 2 : middle;
@@ -4021,11 +4241,18 @@ function buildSafari(full, mini, look, actions) {
4021
4241
  root,
4022
4242
  apply(minimized, sight) {
4023
4243
  root.dataset.state = minimized ? "min" : "max";
4024
- root.className = sight.dark ? "safari dark" : "safari light";
4025
- placeFade(fade, (minimized ? mini : full).fade, sight);
4244
+ const behind = scrimOver(scrim, mini, sight);
4245
+ const own = full.column && !full.column.strip ? sight.background : sight.top;
4246
+ const strip = (minimized ? behind : null) ?? parseColor(own) ?? WHITE;
4247
+ const darkStrip = luminance(strip.red, strip.green, strip.blue) < 0.4;
4248
+ root.className = darkStrip ? "safari dark" : "safari light";
4249
+ for (const node of column)
4250
+ node.style.display = minimized && !mini.column ? "none" : "";
4026
4251
  for (const text of Array.from(root.querySelectorAll(".domain"))) {
4027
- text.textContent = sight.host;
4252
+ text.textContent = domainOf(sight.host);
4028
4253
  }
4254
+ for (const { node, box: box2 } of sides)
4255
+ tintGlass(node, box2, sight);
4029
4256
  for (const { node, glyph } of glyphs) {
4030
4257
  const off = glyph === "back" && !sight.canBack || glyph === "forward" && !sight.canForward;
4031
4258
  node.classList.toggle("off", off);
@@ -4034,9 +4261,10 @@ function buildSafari(full, mini, look, actions) {
4034
4261
  if (surface && domain && main && pill) {
4035
4262
  const box2 = minimized ? pillBox(pill, sight.host) : main;
4036
4263
  placeBox(surface, box2, minimized ? pill.radius : main.radius);
4264
+ tintGlass(surface, box2, sight);
4037
4265
  const top = minimized ? pill.height / 2 : Number(domain.dataset.top);
4038
4266
  domain.style.top = `${top}px`;
4039
- const scale = minimized ? SAFARI_TEXT.pill / SAFARI_TEXT.field : 1;
4267
+ const scale = minimized ? (pill.text?.size ?? SAFARI_TEXT.pill) / SAFARI_TEXT.field : 1;
4040
4268
  domain.style.transform = `translate(-50%, -50%) scale(${scale})`;
4041
4269
  }
4042
4270
  },
@@ -4074,1534 +4302,2000 @@ function buildSafari(full, mini, look, actions) {
4074
4302
  duration: PROGRESS.finish,
4075
4303
  easing: "ease-out"
4076
4304
  });
4077
- const fade2 = progress.animate([{ opacity: 1 }, { opacity: 0 }], {
4305
+ const fade = progress.animate([{ opacity: 1 }, { opacity: 0 }], {
4078
4306
  delay: PROGRESS.finish,
4079
4307
  duration: PROGRESS.fade,
4080
4308
  easing: "ease-out",
4081
4309
  fill: "forwards"
4082
4310
  });
4083
- fade2.finished.then(() => {
4311
+ fade.finished.then(() => {
4084
4312
  if (load !== loads3)
4085
4313
  return;
4086
4314
  progress.hidden = true;
4087
- fade2.cancel();
4315
+ fade.cancel();
4088
4316
  }, () => {});
4089
4317
  }
4090
4318
  };
4091
4319
  }
4092
4320
 
4093
- // src/engine/browserdraw.ts
4094
- var BARS_CSS = `
4095
- .browser {
4096
- position: absolute;
4097
- top: 0;
4098
- left: 0;
4099
- overflow: hidden;
4100
- transform-origin: 0 0;
4101
- pointer-events: none;
4102
- cursor: default;
4103
- user-select: none;
4104
- -webkit-user-select: none;
4105
- font-family: ${FONT};
4106
- font-weight: 400;
4107
- -webkit-font-smoothing: antialiased;
4108
- line-height: 1;
4109
- }
4110
- .browser > *,
4111
- .browser > * > *,
4112
- .browser .group > * {
4113
- position: absolute;
4114
- box-sizing: border-box;
4321
+ // src/engine/objectfit.ts
4322
+ var MIDDLE = { share: 0.5, px: 0 };
4323
+ function words(text) {
4324
+ const parts = [];
4325
+ let depth = 0;
4326
+ let word = "";
4327
+ for (const char of text.trim()) {
4328
+ if (char === "(")
4329
+ depth++;
4330
+ if (char === ")")
4331
+ depth--;
4332
+ if (/\s/.test(char) && depth === 0) {
4333
+ if (word)
4334
+ parts.push(word);
4335
+ word = "";
4336
+ } else
4337
+ word += char;
4338
+ }
4339
+ if (word)
4340
+ parts.push(word);
4341
+ return parts;
4115
4342
  }
4116
- .browser svg { overflow: visible; }
4117
- .browser .press { pointer-events: auto; cursor: default; }
4118
- ${SAFARI_CSS}
4119
- ${CHROME_CSS}
4120
- `;
4121
- var BUILDERS = { safari: buildSafari, chrome: buildChrome };
4122
- function toRgb(color) {
4123
- const parsed = parseColor(color);
4124
- if (parsed)
4125
- return parsed;
4126
- try {
4127
- const canvas = document.createElement("canvas");
4128
- canvas.width = 1;
4129
- canvas.height = 1;
4130
- const context = canvas.getContext("2d", { willReadFrequently: true });
4131
- if (!context)
4132
- return null;
4133
- context.fillStyle = color;
4134
- context.fillRect(0, 0, 1, 1);
4135
- const [r = 0, g = 0, b = 0, a = 0] = context.getImageData(0, 0, 1, 1).data;
4136
- return { red: r, green: g, blue: b, alpha: a / 255 };
4137
- } catch {
4343
+ function offsetOf(word) {
4344
+ const terms = Array.from(word.matchAll(/([+-])?\s*(\d*\.?\d+(?:e[+-]?\d+)?)(%|px)?/gi));
4345
+ if (terms.length === 0 || !/^(calc\(.*\)|[+-]?[\d.]+(e[+-]?\d+)?(%|px)?)$/i.test(word))
4138
4346
  return null;
4347
+ const offset = { share: 0, px: 0 };
4348
+ for (const [, sign, digits = "0", unit] of terms) {
4349
+ const value = Number(digits) * (sign === "-" ? -1 : 1);
4350
+ if (unit === "%")
4351
+ offset.share += value / 100;
4352
+ else
4353
+ offset.px += value;
4139
4354
  }
4355
+ return offset;
4140
4356
  }
4141
- function backgroundOf(doc, view, dark) {
4142
- const root = view.getComputedStyle(doc.documentElement);
4143
- const schemes = root.colorScheme ?? "";
4144
- const canvasDark = schemes.includes("dark") && (dark || !schemes.includes("light"));
4145
- let base = canvasDark ? [18, 18, 18] : [255, 255, 255];
4146
- const layers = [doc.body, doc.documentElement].filter((node) => !!node);
4147
- for (const node of layers) {
4148
- const color = toRgb(view.getComputedStyle(node).backgroundColor);
4149
- if (!color || color.alpha === 0)
4150
- continue;
4151
- const { red, green, blue, alpha } = color;
4152
- const [r, g, b] = base;
4153
- const over = (top, under) => Math.round(top * alpha + under * (1 - alpha));
4154
- base = [over(red, r), over(green, g), over(blue, b)];
4357
+ function fromFar(offset) {
4358
+ return { share: 1 - offset.share, px: 0 - offset.px };
4359
+ }
4360
+ function objectPosition(position) {
4361
+ let x = null;
4362
+ let y = null;
4363
+ const plain = [];
4364
+ const list = words(position.toLowerCase());
4365
+ const counted = list.length > 2;
4366
+ for (let at = 0;at < list.length; at++) {
4367
+ const word = list[at] ?? "";
4368
+ const next = offsetOf(list[at + 1] ?? "");
4369
+ if (word === "left" || word === "right" || word === "top" || word === "bottom") {
4370
+ const far = word === "right" || word === "bottom";
4371
+ const edge = counted && next || { share: 0, px: 0 };
4372
+ if (counted && next)
4373
+ at++;
4374
+ const offset = far ? fromFar(edge) : edge;
4375
+ if (word === "left" || word === "right")
4376
+ x = offset;
4377
+ else
4378
+ y = offset;
4379
+ } else if (word === "center")
4380
+ plain.push(MIDDLE);
4381
+ else {
4382
+ const offset = offsetOf(word);
4383
+ if (offset)
4384
+ plain.push(offset);
4385
+ }
4155
4386
  }
4156
- return base;
4387
+ for (const offset of plain) {
4388
+ if (!x)
4389
+ x = offset;
4390
+ else if (!y)
4391
+ y = offset;
4392
+ }
4393
+ return [x ?? MIDDLE, y ?? MIDDLE];
4157
4394
  }
4158
- function readLook(frame2) {
4159
- const fallback = {
4160
- background: "rgb(255, 255, 255)",
4161
- dark: false,
4162
- scheme: "light",
4163
- host: "",
4164
- canBack: false,
4165
- canForward: false
4395
+ function objectPlace(fit, position, natural, box2) {
4396
+ if (!(natural.width > 0 && natural.height > 0 && box2.width > 0 && box2.height > 0))
4397
+ return null;
4398
+ const across = box2.width / natural.width;
4399
+ const down = box2.height / natural.height;
4400
+ const whole = Math.min(across, down);
4401
+ let size = { width: box2.width, height: box2.height };
4402
+ const scaled = (scale) => ({ width: natural.width * scale, height: natural.height * scale });
4403
+ if (fit === "contain")
4404
+ size = scaled(whole);
4405
+ else if (fit === "cover")
4406
+ size = scaled(Math.max(across, down));
4407
+ else if (fit === "none")
4408
+ size = scaled(1);
4409
+ else if (fit === "scale-down")
4410
+ size = scaled(Math.min(1, whole));
4411
+ const [x, y] = objectPosition(position);
4412
+ const left = box2.x + (box2.width - size.width) * x.share + x.px;
4413
+ const top = box2.y + (box2.height - size.height) * y.share + y.px;
4414
+ const to = {
4415
+ x: Math.max(left, box2.x),
4416
+ y: Math.max(top, box2.y),
4417
+ width: Math.min(left + size.width, box2.x + box2.width) - Math.max(left, box2.x),
4418
+ height: Math.min(top + size.height, box2.y + box2.height) - Math.max(top, box2.y)
4419
+ };
4420
+ if (!(to.width > 0 && to.height > 0))
4421
+ return null;
4422
+ const wide = natural.width / size.width;
4423
+ const tall = natural.height / size.height;
4424
+ return {
4425
+ from: { x: (to.x - left) * wide, y: (to.y - top) * tall, width: to.width * wide, height: to.height * tall },
4426
+ to
4166
4427
  };
4167
- try {
4168
- const view = frame2.contentWindow;
4169
- const doc = frame2.contentDocument;
4170
- if (!view || !doc?.documentElement)
4171
- return fallback;
4172
- const scheme = view.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
4173
- const [r, g, b] = backgroundOf(doc, view, scheme === "dark");
4174
- const navigation = navigationOf(view);
4175
- const can = (key) => {
4176
- const value = navigation && Reflect.get(navigation, key);
4177
- return typeof value === "boolean" ? value : null;
4178
- };
4179
- return {
4180
- background: `rgb(${r}, ${g}, ${b})`,
4181
- dark: luminance(r, g, b) < 0.4,
4182
- scheme,
4183
- host: view.location.host,
4184
- canBack: can("canGoBack") ?? view.history.length > 1,
4185
- canForward: can("canGoForward") ?? false
4186
- };
4187
- } catch {
4188
- return fallback;
4189
- }
4190
4428
  }
4191
- function reaches(frame2) {
4192
- try {
4193
- return !!frame2.contentDocument?.documentElement;
4194
- } catch {
4195
- return false;
4429
+
4430
+ // src/engine/pagefonts.ts
4431
+ var kept2 = null;
4432
+ var READ = /^(woff2?|truetype|opentype|collection)(-variations)?$/;
4433
+ var URL_OF = /^url\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^)]*))\s*\)/i;
4434
+ var CHUNK = 32768;
4435
+ function cut(text, mark) {
4436
+ const parts = [];
4437
+ let depth = 0;
4438
+ let quote = "";
4439
+ let from = 0;
4440
+ for (let at = 0;at < text.length; at++) {
4441
+ const char = text[at];
4442
+ if (char === "\\")
4443
+ at++;
4444
+ else if (quote)
4445
+ quote = char === quote ? "" : quote;
4446
+ else if (char === '"' || char === "'")
4447
+ quote = char;
4448
+ else if (char === "(")
4449
+ depth++;
4450
+ else if (char === ")")
4451
+ depth--;
4452
+ else if (char === mark && depth === 0) {
4453
+ parts.push(text.slice(from, at));
4454
+ from = at + 1;
4455
+ }
4196
4456
  }
4457
+ parts.push(text.slice(from));
4458
+ return parts;
4197
4459
  }
4198
- var RESTYLE = 120;
4199
- var LOAD_WAIT = 5000;
4200
- function same(a, b) {
4201
- return JSON.stringify(a) === JSON.stringify(b);
4460
+ function faceKey(family, weight, style, range) {
4461
+ const name = family.trim().replace(/^(["'])(.*)\1$/, "$2").toLowerCase();
4462
+ const plain = (value) => value.trim().toLowerCase().replace(/\s+/g, " ") || "normal";
4463
+ const heavy = plain(weight).replace(/\bnormal\b/g, "400").replace(/\bbold\b/g, "700");
4464
+ const chars = (range.trim() || "U+0-10FFFF").toLowerCase().split(",").map((part) => part.trim().replace(/^u\+/, "").split("-").map((end) => end.replace(/^0+(?=.)/, "")).join("-")).join(",");
4465
+ return [name, heavy, plain(style), chars].join("|");
4202
4466
  }
4203
- function createBrowser(glass, frame2, onChange, onReload = () => {}, ready = () => true) {
4204
- const blank = el("div", "screenblank");
4205
- blank.hidden = true;
4206
- glass.append(blank);
4207
- const layer = el("div", "browser");
4208
- layer.setAttribute("aria-hidden", "true");
4209
- let view = null;
4210
- let look = null;
4211
- let painted = null;
4212
- let built = "";
4213
- let applied = null;
4214
- let shrinking = 0;
4215
- let later = 0;
4216
- let query = null;
4217
- let watched = null;
4218
- let href = "";
4219
- let motion = BARS_START;
4220
- let busy = false;
4221
- let loadWait = 0;
4222
- const still2 = () => baseMatchMedia("(prefers-reduced-motion: reduce)").matches;
4223
- const step = (event) => {
4224
- const before = motion.minimized;
4225
- motion = barsStep(motion, event);
4226
- if (motion.minimized !== before)
4227
- queueMicrotask(onChange);
4228
- };
4229
- const onScroll = () => {
4230
- const page = frame2.contentWindow;
4231
- if (page)
4232
- step({ type: "scroll", y: page.scrollY, time: performance.now() });
4233
- };
4234
- const actions = {
4235
- back: () => frame2.contentWindow?.history.back(),
4236
- forward: () => frame2.contentWindow?.history.forward(),
4237
- reload: () => {
4238
- if (busy) {
4239
- frame2.contentWindow?.stop();
4240
- stopLoading();
4241
- return;
4242
- }
4243
- onReload();
4244
- keep(frame2.contentWindow, "frame");
4245
- frame2.contentWindow?.location.reload();
4246
- },
4247
- expand: () => step({ type: "tap" })
4248
- };
4249
- const roomFrame = () => {
4250
- const bars = view?.bars ?? null;
4251
- try {
4252
- const page = frame2.contentWindow;
4253
- const doc = frame2.contentDocument;
4254
- if (!page || !doc?.documentElement)
4255
- return;
4256
- const room = bars ? endRoom(bars.screen, bars.orientation, bars.layout, bars.minimized, bars.edge) : 0;
4257
- const had = give(doc, room);
4258
- if (had === room)
4259
- return;
4260
- step({ type: "resize", time: performance.now() });
4261
- const end = doc.documentElement.scrollHeight - page.innerHeight;
4262
- if (room < had || page.scrollY <= 1 || page.scrollY < end - (room - had) - 1)
4263
- return;
4264
- page.scrollTo({ top: end, behavior: still2() ? "instant" : "smooth" });
4265
- } catch {}
4266
- };
4267
- const sizeFrame = () => {
4268
- if (!view)
4269
- return;
4270
- view.sizeFrame();
4271
- if (!same(view.page, applied))
4272
- step({ type: "resize", time: performance.now() });
4273
- applied = view.page;
4274
- roomFrame();
4275
- };
4276
- const placeFrame = (instant) => {
4277
- const page = view?.page ?? null;
4278
- const shrinks = !instant && page && applied && page.height < applied.height;
4279
- clearTimeout(shrinking);
4280
- if (!shrinks) {
4281
- sizeFrame();
4282
- return;
4283
- }
4284
- shrinking = window.setTimeout(() => {
4285
- if (same(view?.page ?? null, page))
4286
- sizeFrame();
4287
- }, MORPH.expand);
4288
- };
4289
- const back = () => {
4290
- frame2.style.background = reaches(frame2) ? (look ??= readLook(frame2)).background : "";
4291
- };
4292
- const draw = () => {
4293
- const bars = view?.bars ?? null;
4294
- if (!view || !bars) {
4295
- clearTimeout(shrinking);
4296
- layer.replaceChildren();
4297
- glass.style.background = "";
4298
- back();
4299
- painted = null;
4300
- built = "";
4301
- if (view)
4302
- sizeFrame();
4467
+ function base64(bytes) {
4468
+ let text = "";
4469
+ for (let at = 0;at < bytes.length; at += CHUNK)
4470
+ text += String.fromCharCode(...bytes.subarray(at, at + CHUNK));
4471
+ return btoa(text);
4472
+ }
4473
+ function fetchFont(url, fonts) {
4474
+ fonts.set(url, null);
4475
+ quietFetch(url).then(async (response) => {
4476
+ if (!response.ok)
4303
4477
  return;
4304
- }
4305
- look ??= readLook(frame2);
4306
- glass.style.background = look.background;
4307
- back();
4308
- const { platform, layout, screen, orientation, edge } = bars;
4309
- const base = JSON.stringify([platform, layout, screen, orientation, edge, view.follow]);
4310
- const fresh2 = base !== built || !painted;
4311
- const instant = fresh2 || still2();
4312
- if (fresh2) {
4313
- const other = barsOf(screen, orientation, layout, !bars.minimized, edge);
4314
- const full = bars.minimized ? other : bars;
4315
- const mini = bars.minimized ? bars : other;
4316
- const shown2 = { ...actions, expand: view.follow ? actions.expand : undefined };
4317
- if (!full || !mini)
4318
- return;
4319
- painted = BUILDERS[bars.platform](full, mini, look, shown2);
4320
- layer.replaceChildren(painted.root);
4321
- built = base;
4322
- if (busy)
4323
- painted.loading?.(true, true);
4324
- }
4325
- if (instant)
4326
- layer.setAttribute("data-instant", "");
4327
- painted?.apply(bars.minimized, look);
4328
- if (instant) {
4329
- layer.offsetWidth;
4330
- layer.removeAttribute("data-instant");
4331
- }
4332
- placeFrame(instant);
4333
- };
4334
- const pageOf = () => {
4335
- try {
4336
- return frame2.contentDocument;
4337
- } catch {
4338
- return null;
4339
- }
4478
+ const type = /^[\w.+-]+\/[\w.+-]+/.exec(response.headers.get("content-type") ?? "")?.[0];
4479
+ const bytes = new Uint8Array(await response.arrayBuffer());
4480
+ fonts.set(url, `data:${type ?? "application/octet-stream"};base64,${base64(bytes)}`);
4481
+ }).catch(() => {});
4482
+ }
4483
+ function faceWith(css, base, used, fonts) {
4484
+ const open = css.indexOf("{");
4485
+ const close = css.lastIndexOf("}");
4486
+ if (open < 0 || close < open)
4487
+ return css;
4488
+ const parts = cut(css.slice(open + 1, close), ";");
4489
+ const named = (name) => {
4490
+ const part = parts.find((part2) => part2.split(":")[0]?.trim().toLowerCase() === name);
4491
+ return part ? part.slice(part.indexOf(":") + 1).trim() : "";
4340
4492
  };
4341
- const showLoading = (on, seed) => {
4342
- busy = on;
4343
- if (seed) {
4344
- look = seed;
4345
- draw();
4493
+ if (!used.has(faceKey(named("font-family"), named("font-weight"), named("font-style"), named("unicode-range")))) {
4494
+ return css;
4495
+ }
4496
+ const sources = cut(named("src"), ",").map((source2) => source2.trim());
4497
+ const at = sources.findIndex((source2) => {
4498
+ const format = /format\(\s*["']?([\w-]+)["']?\s*\)/i.exec(source2)?.[1];
4499
+ return URL_OF.test(source2) && (!format || READ.test(format.toLowerCase()));
4500
+ });
4501
+ const source = sources[at];
4502
+ const found = source ? URL_OF.exec(source) : null;
4503
+ if (!source || !found)
4504
+ return css;
4505
+ const address = (found[1] ?? found[2] ?? found[3] ?? "").trim().replace(/\\(.)/g, "$1");
4506
+ if (/^data:/i.test(address))
4507
+ return css;
4508
+ let url;
4509
+ try {
4510
+ url = new URL(address, base).href;
4511
+ } catch {
4512
+ return css;
4513
+ }
4514
+ const data = fonts.get(url);
4515
+ if (data === undefined)
4516
+ fetchFont(url, fonts);
4517
+ if (!data)
4518
+ return css;
4519
+ const locals = sources.slice(0, at).filter((source2) => /^local\(/i.test(source2));
4520
+ const src = [...locals, `url("${data}")${source.slice(found[0].length)}`].join(", ");
4521
+ const next = parts.map((part) => part.split(":")[0]?.trim().toLowerCase() === "src" ? ` src: ${src}` : part);
4522
+ return `${css.slice(0, open + 1)}${next.join(";")}${css.slice(close)}`;
4523
+ }
4524
+ function holdsRules(rule) {
4525
+ return "cssRules" in rule;
4526
+ }
4527
+ function keptFor(doc) {
4528
+ if (kept2?.doc === doc)
4529
+ return kept2.fonts;
4530
+ forgetFonts();
4531
+ const set = doc.fonts;
4532
+ const again = () => fetchFonts(doc);
4533
+ set?.addEventListener("loadingdone", again);
4534
+ kept2 = { doc, fonts: new Map, stop: () => set?.removeEventListener("loadingdone", again) };
4535
+ return kept2.fonts;
4536
+ }
4537
+ function embedFonts(doc) {
4538
+ const fonts = keptFor(doc);
4539
+ const used = new Set;
4540
+ const set = doc.fonts;
4541
+ if (set) {
4542
+ for (const face of set) {
4543
+ if (face.status === "loaded")
4544
+ used.add(faceKey(face.family, face.weight, face.style, face.unicodeRange));
4346
4545
  }
4347
- painted?.loading?.(on, still2());
4348
- if (!on)
4349
- browser.refresh();
4350
- };
4351
- const stopLoading = () => {
4352
- if (loadWait)
4353
- window.cancelAnimationFrame(loadWait);
4354
- loadWait = 0;
4355
- if (!busy)
4356
- return;
4357
- blank.hidden = true;
4358
- showLoading(false, null);
4359
- };
4360
- const startLoading = (seed) => {
4361
- blank.style.background = (seed ?? look ?? readLook(frame2)).background;
4362
- blank.hidden = false;
4363
- showLoading(true, seed);
4364
- if (loadWait)
4365
- window.cancelAnimationFrame(loadWait);
4366
- const end = performance.now() + LOAD_WAIT;
4367
- const gone = pageOf();
4368
- const check = () => {
4369
- loadWait = 0;
4370
- const next = gone === null || pageOf() !== gone;
4371
- if (next && ready() || performance.now() >= end)
4372
- stopLoading();
4373
- else
4374
- loadWait = window.requestAnimationFrame(check);
4375
- };
4376
- loadWait = window.requestAnimationFrame(check);
4377
- };
4378
- const read = () => {
4379
- try {
4380
- const page = frame2.contentWindow;
4381
- const doc = frame2.contentDocument;
4382
- if (page && doc && doc !== watched) {
4383
- query?.removeEventListener("change", read);
4384
- query = page.matchMedia("(prefers-color-scheme: dark)");
4385
- query.addEventListener("change", read);
4386
- page.addEventListener("scroll", onScroll, { passive: true });
4387
- watched = doc;
4388
- }
4389
- const now = page?.location.href ?? "";
4390
- if (now !== href) {
4391
- href = now;
4392
- step({ type: "navigate" });
4393
- }
4394
- } catch {
4395
- query = null;
4546
+ }
4547
+ const embed = (rule) => {
4548
+ let css = rule.cssText;
4549
+ if (used.size === 0 || !css.includes("@font-face"))
4550
+ return css;
4551
+ if (!holdsRules(rule)) {
4552
+ const base = rule.parentStyleSheet?.href ?? doc.baseURI;
4553
+ return css.startsWith("@font-face") ? faceWith(css, base, used, fonts) : css;
4396
4554
  }
4397
- if (!busy || !look)
4398
- look = readLook(frame2);
4399
- draw();
4400
- };
4401
- const browser = {
4402
- show(next) {
4403
- view = next;
4404
- if (next.bars && !layer.isConnected)
4405
- glass.append(layer);
4406
- if (!next.bars)
4407
- layer.remove();
4408
- place(layer, 0, 0, next.size.width, next.size.height);
4409
- layer.style.transform = next.zoom === 1 ? "" : `scale(${next.zoom})`;
4410
- draw();
4411
- },
4412
- refresh() {
4413
- if (!view)
4414
- return;
4415
- const again = view.bars ? read : () => {
4416
- if (!busy || !look)
4417
- look = readLook(frame2);
4418
- back();
4419
- };
4420
- again();
4421
- clearTimeout(later);
4422
- later = window.setTimeout(again, RESTYLE);
4423
- },
4424
- minimized: () => motion.minimized,
4425
- page: () => applied,
4426
- startLoading,
4427
- stopLoading,
4428
- look: () => look,
4429
- remove() {
4430
- clearTimeout(later);
4431
- if (loadWait)
4432
- window.cancelAnimationFrame(loadWait);
4433
- loadWait = 0;
4434
- clearTimeout(shrinking);
4435
- query?.removeEventListener("change", read);
4436
- try {
4437
- frame2.contentWindow?.removeEventListener("scroll", onScroll);
4438
- } catch {}
4439
- query = null;
4440
- watched = null;
4441
- layer.remove();
4442
- blank.remove();
4555
+ for (const inner of rule.cssRules) {
4556
+ const next = embed(inner);
4557
+ if (next !== inner.cssText)
4558
+ css = css.split(inner.cssText).join(next);
4443
4559
  }
4560
+ return css;
4444
4561
  };
4445
- return browser;
4562
+ return embed;
4563
+ }
4564
+ function fetchFonts(doc) {
4565
+ const embed = embedFonts(doc);
4566
+ for (const sheet of doc.styleSheets) {
4567
+ try {
4568
+ for (const rule of sheet.cssRules)
4569
+ embed(rule);
4570
+ } catch {}
4571
+ }
4572
+ }
4573
+ function warmFonts(doc) {
4574
+ if (kept2?.doc !== doc)
4575
+ fetchFonts(doc);
4576
+ }
4577
+ function forgetFonts() {
4578
+ kept2?.stop();
4579
+ kept2 = null;
4446
4580
  }
4447
4581
 
4448
- // src/engine/fit.ts
4449
- var STRIP_TOP = 8;
4450
- var STRIP = 24 + STRIP_TOP;
4451
- var MARGIN = 24;
4452
- var BARE = { top: 0, right: 0, bottom: 0, left: 0 };
4453
- function hasStrip(knobs2) {
4454
- const sized = typeof knobs2.width === "number" || typeof knobs2.height === "number";
4455
- return sized || knobs2.zoom !== "fit";
4582
+ // src/engine/pageshot.ts
4583
+ var RES = 0.25;
4584
+ var MOST = 1500;
4585
+ var BUDGET = 6;
4586
+ var INK = 0.4;
4587
+ function canvasOf(width, height) {
4588
+ const canvas = document.createElement("canvas");
4589
+ canvas.width = Math.max(1, Math.round(width));
4590
+ canvas.height = Math.max(1, Math.round(height));
4591
+ const pen = canvas.getContext("2d");
4592
+ return pen ? { canvas, pen } : null;
4456
4593
  }
4457
- function margin(size) {
4458
- return Math.min(MARGIN, size / 4);
4594
+ function clear(color) {
4595
+ return color === "" || color === "transparent" || /^rgba\(.*,\s*0\)$/.test(color);
4459
4596
  }
4460
- function fit(knobs2, size, options = {}) {
4461
- const { frameZoom = 1, aside = 0, side = "right", mock = BARE } = options;
4462
- const room = {
4463
- width: size.width,
4464
- height: Math.max(0, size.height - (hasStrip(knobs2) ? STRIP : 0))
4465
- };
4466
- const sized = typeof knobs2.width === "number";
4467
- const width = typeof knobs2.width === "number" ? knobs2.width : room.width;
4468
- const x = sized ? margin(room.width) : 0;
4469
- const y = typeof knobs2.height === "number" ? margin(room.height) : 0;
4470
- const sides = { width: mock.left + mock.right, height: mock.top + mock.bottom };
4471
- const across = width > 0 && room.width > 0 ? (room.width - 2 * x) / (width + sides.width) : 1;
4472
- const tall = typeof knobs2.height === "number" && knobs2.height > 0 && room.height > 0;
4473
- const upright = (room.height - 2 * y) / (Number(knobs2.height) + sides.height);
4474
- const whole = Math.min(1, across, tall ? upright : 1);
4475
- const height = typeof knobs2.height === "number" ? knobs2.height : room.height / whole;
4476
- const outer = { width: width + sides.width, height: height + sides.height };
4477
- const covered = sized && aside > 0 && aside <= room.width / 2 && (room.width + outer.width * whole) / 2 + x > room.width - aside;
4478
- const fitted = covered ? Math.min(whole, (room.width - aside - 2 * x) / outer.width) : whole;
4479
- const scale = knobs2.zoom === "fit" ? fitted : knobs2.zoom;
4480
- const beside = knobs2.zoom === "fit" && covered ? aside : 0;
4481
- const before = side === "left" ? beside : 0;
4482
- return {
4483
- width,
4484
- height,
4485
- zoom: frameZoom,
4486
- scale,
4487
- fit: fitted,
4488
- transform: scale / frameZoom,
4489
- box: { width: outer.width * scale + 2 * x + beside, height: outer.height * scale + 2 * y },
4490
- left: x + mock.left * scale + before,
4491
- top: y + mock.top * scale
4597
+ var MEDIA = "img, video, canvas";
4598
+ function mediaOf(node) {
4599
+ if ("naturalWidth" in node) {
4600
+ const loaded = node.complete && node.naturalWidth > 0 && node.naturalHeight > 0;
4601
+ return loaded ? { source: node, width: node.naturalWidth, height: node.naturalHeight } : null;
4602
+ }
4603
+ if ("videoWidth" in node) {
4604
+ const playing = node.readyState >= 2 && node.videoWidth > 0 && node.videoHeight > 0;
4605
+ return playing ? { source: node, width: node.videoWidth, height: node.videoHeight } : null;
4606
+ }
4607
+ return node.width > 0 && node.height > 0 ? { source: node, width: node.width, height: node.height } : null;
4608
+ }
4609
+ function radiusOf(value, wide, tall) {
4610
+ const [across = "0", down = across] = value.trim().split(/\s+/);
4611
+ const px = (text, of) => (text.endsWith("%") ? Number.parseFloat(text) / 100 * of : Number.parseFloat(text)) || 0;
4612
+ return { x: px(across, wide), y: px(down, tall) };
4613
+ }
4614
+ function drawMedia(pen, media, rect, style) {
4615
+ const px = (value) => Number.parseFloat(value) || 0;
4616
+ const left = px(style.borderLeftWidth) + px(style.paddingLeft);
4617
+ const right = px(style.borderRightWidth) + px(style.paddingRight);
4618
+ const top = px(style.borderTopWidth) + px(style.paddingTop);
4619
+ const bottom = px(style.borderBottomWidth) + px(style.paddingBottom);
4620
+ const box2 = { x: rect.left + left, y: rect.top + top, width: rect.width - left - right, height: rect.height - top - bottom };
4621
+ const placed = objectPlace(style.objectFit, style.objectPosition, media, box2);
4622
+ if (!placed)
4623
+ return;
4624
+ const corner = (value, across, down) => {
4625
+ const radius = radiusOf(value, rect.width, rect.height);
4626
+ return { x: Math.max(0, radius.x - across), y: Math.max(0, radius.y - down) };
4492
4627
  };
4628
+ const corners = [
4629
+ corner(style.borderTopLeftRadius, left, top),
4630
+ corner(style.borderTopRightRadius, right, top),
4631
+ corner(style.borderBottomRightRadius, right, bottom),
4632
+ corner(style.borderBottomLeftRadius, left, bottom)
4633
+ ];
4634
+ const { from, to } = placed;
4635
+ pen.save();
4636
+ if (corners.some((radius) => radius.x > 0 && radius.y > 0)) {
4637
+ pen.beginPath();
4638
+ pen.roundRect(box2.x, box2.y, box2.width, box2.height, corners);
4639
+ pen.clip();
4640
+ }
4641
+ if (style.imageRendering === "pixelated" || style.imageRendering === "crisp-edges")
4642
+ pen.imageSmoothingEnabled = false;
4643
+ pen.drawImage(media.source, from.x, from.y, from.width, from.height, to.x, to.y, to.width, to.height);
4644
+ pen.restore();
4493
4645
  }
4494
- function origin(place2, room) {
4495
- return {
4496
- x: Math.max(0, (room.width - place2.box.width) / 2) + place2.left,
4497
- y: Math.max(0, (room.height - place2.box.height) / 2) + place2.top
4646
+ function picturesKey(doc) {
4647
+ const parts = [];
4648
+ for (const node of doc.querySelectorAll(MEDIA)) {
4649
+ if (!("naturalWidth" in node))
4650
+ return null;
4651
+ const address = node.currentSrc;
4652
+ parts.push(`${address.length}:${address.slice(-64)}@${node.naturalWidth}x${node.naturalHeight}`);
4653
+ }
4654
+ return parts.join(" ");
4655
+ }
4656
+ function shotKey(at) {
4657
+ const { size, frame: frame2, view, scroll } = at;
4658
+ return JSON.stringify([
4659
+ [size.width, size.height, at.color, at.layout],
4660
+ [frame2.x, frame2.y, frame2.width],
4661
+ [view.width, view.height, scroll.x, scroll.y],
4662
+ [at.dpr, at.text, at.pictures]
4663
+ ]);
4664
+ }
4665
+ function shootPage(frame2, glass, size, color, layout = "") {
4666
+ const doc = frame2.contentDocument;
4667
+ const view = frame2.contentWindow;
4668
+ const screen = glass.getBoundingClientRect();
4669
+ const box2 = frame2.getBoundingClientRect();
4670
+ if (!doc?.body || !view || screen.width <= 0 || view.innerWidth <= 0)
4671
+ return null;
4672
+ const shown2 = picturesKey(doc);
4673
+ const css = size.width / screen.width;
4674
+ const near = (value) => Math.round(value * css * 1000) / 1000;
4675
+ const key = shotKey({
4676
+ size,
4677
+ color,
4678
+ layout,
4679
+ frame: { x: near(box2.left - screen.left), y: near(box2.top - screen.top), width: near(box2.width) },
4680
+ view: { width: view.innerWidth, height: view.innerHeight },
4681
+ scroll: { x: view.scrollX, y: view.scrollY },
4682
+ dpr: view.devicePixelRatio,
4683
+ text: view.getComputedStyle(doc.documentElement).fontSize,
4684
+ pictures: shown2 ?? ""
4685
+ });
4686
+ const kept3 = shown2 === null || !unchanged(doc) ? null : shots.get(doc)?.get(key);
4687
+ if (kept3)
4688
+ return kept3;
4689
+ const drawn = canvasOf(size.width * RES, size.height * RES);
4690
+ if (!drawn)
4691
+ return null;
4692
+ const { canvas, pen } = drawn;
4693
+ pen.fillStyle = color;
4694
+ pen.fillRect(0, 0, canvas.width, canvas.height);
4695
+ const scale = box2.width * css / view.innerWidth;
4696
+ pen.setTransform(RES * scale, 0, 0, RES * scale, RES * (box2.left - screen.left) * css, RES * (box2.top - screen.top) * css);
4697
+ pen.beginPath();
4698
+ pen.rect(0, 0, view.innerWidth, view.innerHeight);
4699
+ pen.clip();
4700
+ const pictures = new Map;
4701
+ for (const node of doc.querySelectorAll(MEDIA)) {
4702
+ const media = mediaOf(node);
4703
+ if (media)
4704
+ pictures.set(node, media);
4705
+ }
4706
+ const range = doc.createRange();
4707
+ const tall = view.innerHeight;
4708
+ let seen = 0;
4709
+ const pinned = [];
4710
+ const deadline = performance.now() + BUDGET;
4711
+ const draw = (node, alpha, lifted) => {
4712
+ if (seen++ > MOST || seen % 50 === 0 && performance.now() > deadline)
4713
+ return;
4714
+ if (node.hasAttribute("data-devknobs"))
4715
+ return;
4716
+ const style = view.getComputedStyle(node);
4717
+ if (style.display === "none")
4718
+ return;
4719
+ if (!lifted && (style.position === "fixed" || style.position === "sticky")) {
4720
+ pinned.push([node, alpha]);
4721
+ return;
4722
+ }
4723
+ const rect = node.getBoundingClientRect();
4724
+ const area = rect.width > 0 && rect.height > 0;
4725
+ if (area && (rect.bottom < 0 || rect.top > tall))
4726
+ return;
4727
+ const shown3 = alpha * (Number.parseFloat(style.opacity) || 0);
4728
+ if (shown3 <= 0)
4729
+ return;
4730
+ if (area && style.visibility !== "hidden") {
4731
+ pen.globalAlpha = shown3;
4732
+ if (!clear(style.backgroundColor)) {
4733
+ pen.fillStyle = style.backgroundColor;
4734
+ pen.beginPath();
4735
+ pen.roundRect(rect.left, rect.top, rect.width, rect.height, Number.parseFloat(style.borderTopLeftRadius) || 0);
4736
+ pen.fill();
4737
+ }
4738
+ const picture = pictures.get(node);
4739
+ if (picture)
4740
+ drawMedia(pen, picture, rect, style);
4741
+ pen.fillStyle = style.color;
4742
+ pen.globalAlpha = shown3 * INK;
4743
+ for (const text of node.childNodes) {
4744
+ if (text.nodeType !== Node.TEXT_NODE || !text.textContent?.trim())
4745
+ continue;
4746
+ range.selectNodeContents(text);
4747
+ for (const line of range.getClientRects())
4748
+ pen.fillRect(line.left, line.top, line.width, line.height);
4749
+ }
4750
+ }
4751
+ for (const child of node.children)
4752
+ draw(child, shown3, lifted);
4498
4753
  };
4754
+ for (const child of doc.body.children)
4755
+ draw(child, 1, false);
4756
+ for (const [node, alpha] of pinned)
4757
+ draw(node, alpha, true);
4758
+ if (shown2 !== null)
4759
+ keepShot(doc, key, canvas);
4760
+ return canvas;
4499
4761
  }
4500
- function label(place2, knobs2, page = place2) {
4501
- const name = formOf(knobs2.device, knobs2.posture)?.label;
4502
- let text = name ? `${name} · ${page.width}` : String(page.width);
4503
- if (typeof knobs2.height === "number")
4504
- text += ` × ${page.height}`;
4505
- if (typeof knobs2.dpr === "number")
4506
- text += ` · ${knobs2.dpr}x`;
4507
- return text;
4508
- }
4509
-
4510
- // src/engine/mat.ts
4511
- function colorRules() {
4512
- return MAT_COLOR_NAMES.map((name) => {
4513
- const paint = MAT_COLORS[name];
4514
- return `[data-mat="${name}"] { --mat: ${matGradient(paint.srgb)}; --mat-p3: ${matGradient(paint.p3)}; --mat-line: ${paint.line}; }`;
4515
- }).join(`
4516
- `);
4762
+ var shots = new WeakMap;
4763
+ var watched = null;
4764
+ function forgetShots() {
4765
+ watched?.observer.disconnect();
4766
+ watched = null;
4767
+ shots = new WeakMap;
4768
+ forgetFonts();
4517
4769
  }
4518
- var MAT_CSS = `
4519
- ${colorRules()}
4520
- .mat {
4521
- position: absolute;
4522
- top: 0;
4523
- left: 0;
4524
- width: 100%;
4525
- height: 100%;
4526
- pointer-events: none;
4527
- fill: var(--mat-line);
4770
+ function unchanged(doc) {
4771
+ if (watched?.doc !== doc)
4772
+ return false;
4773
+ if (watched.observer.takeRecords().length > 0)
4774
+ watched.changed = true;
4775
+ return !watched.changed;
4528
4776
  }
4529
- .mat .cell { opacity: 0.07; }
4530
- .mat .major { opacity: 0.14; }
4531
- .mat .span { opacity: 0.26; }
4532
- .mat .angle { fill: none; stroke: var(--mat-line); }
4533
- .mat .mark, .mat .tick { opacity: 0.55; }
4534
- .mat text {
4535
- font: 9px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
4536
- font-variant-numeric: tabular-nums;
4537
- opacity: 0.5;
4538
- }`;
4539
- var CELL = 10;
4540
- var MAJOR = 50;
4541
- var SPAN = 100;
4542
- var TICK = { cell: 3, major: 5, span: 9 };
4543
- var ANGLES = [15, 30, 45, 60, 75];
4544
- var GUIDE = { line: 0.15, half: 0.22 };
4545
- var ARC = 40;
4546
- var LABEL = { radius: 240, off: 3, top: 40, room: 24 };
4547
- var FOOT = 30;
4548
- var NUMBER = 24;
4549
- function ticks(length) {
4550
- const out = [];
4551
- for (let at = CELL;at < length; at += CELL) {
4552
- const size = at % SPAN === 0 ? TICK.span : at % MAJOR === 0 ? TICK.major : TICK.cell;
4553
- out.push({ at, size });
4777
+ function keepShot(doc, key, canvas) {
4778
+ if (!unchanged(doc)) {
4779
+ watched?.observer.disconnect();
4780
+ shots = new WeakMap;
4781
+ const Observer = doc.defaultView?.MutationObserver;
4782
+ if (!Observer)
4783
+ return;
4784
+ const observer = new Observer(() => {
4785
+ if (watched?.observer === observer)
4786
+ watched.changed = true;
4787
+ observer.disconnect();
4788
+ });
4789
+ observer.observe(doc, { subtree: true, childList: true, attributes: true, characterData: true });
4790
+ watched = { doc, changed: false, observer };
4554
4791
  }
4555
- return out;
4792
+ const kept3 = shots.get(doc) ?? new Map;
4793
+ kept3.set(key, canvas);
4794
+ shots.set(doc, kept3);
4556
4795
  }
4557
- function numbers(length, avoid) {
4558
- const out = [];
4559
- for (let at = SPAN;at + NUMBER <= length; at += SPAN) {
4560
- if (avoid && at + NUMBER > avoid.from && at < avoid.to)
4561
- continue;
4562
- out.push(at);
4563
- }
4564
- return out;
4796
+ var KEPT = 8;
4797
+ function blurPictures(shot, width, across, widths = blurWidths().slice(1)) {
4798
+ const length = across ? shot.height : shot.width;
4799
+ return widths.map((wide) => {
4800
+ const coarse2 = Math.max(1, wide * shot.width / width);
4801
+ const margin = blurMargin(coarse2);
4802
+ const padded = canvasOf(shot.width + (across ? 0 : 2 * margin), shot.height + (across ? 2 * margin : 0));
4803
+ if (!padded)
4804
+ return { canvas: blurPicture(shot, coarse2), long: length };
4805
+ padded.pen.fillStyle = "#000";
4806
+ padded.pen.fillRect(0, 0, padded.canvas.width, padded.canvas.height);
4807
+ padded.pen.drawImage(shot, across ? 0 : margin, across ? margin : 0);
4808
+ const canvas = blurPicture(padded.canvas, coarse2);
4809
+ if (canvas !== padded.canvas)
4810
+ spend(padded.canvas);
4811
+ return { canvas, long: length + 2 * margin };
4812
+ });
4565
4813
  }
4566
- function lines(across, length, hair) {
4567
- return across.map((at) => `M${at} 0h${hair}v${length}h${-hair}ZM0 ${at}h${length}v${hair}h${-length}Z`).join("");
4814
+ function blurMargin(coarse2) {
4815
+ return Math.ceil(2 * coarse2);
4568
4816
  }
4569
- function vertex(height) {
4570
- const y = Math.floor((height - FOOT) / SPAN) * SPAN;
4571
- return y > 0 ? { x: 0, y } : null;
4817
+ function marginPlace(shot, padded) {
4818
+ const exact = (value) => Math.round(value * 1e4) / 1e4;
4819
+ return { start: exact((shot - padded) / 2 / shot * 100), size: exact(padded / shot * 100) };
4572
4820
  }
4573
- function direction(angle) {
4574
- const turn2 = angle * Math.PI / 180;
4575
- return { x: Math.cos(turn2), y: -Math.sin(turn2) };
4821
+ function spend(canvas) {
4822
+ canvas.width = 0;
4823
+ canvas.height = 0;
4576
4824
  }
4577
- function exit(from, angle, size) {
4578
- const step = direction(angle);
4579
- const toTop = step.y < 0 ? from.y / -step.y : Infinity;
4580
- const toRight = step.x > 0 ? (size.width - from.x) / step.x : Infinity;
4581
- if (toTop <= toRight)
4582
- return { x: from.x + toTop * step.x, y: 0 };
4583
- return { x: size.width, y: from.y + toRight * step.y };
4825
+ function blurPicture(shot, coarse2) {
4826
+ const halvings = Math.ceil(Math.log2(coarse2) - 0.000000001);
4827
+ const { width, height } = shot;
4828
+ const sized = (level) => {
4829
+ const scale = Math.min(1, 2 ** level / coarse2);
4830
+ return canvasOf(width * scale, height * scale);
4831
+ };
4832
+ let at = shot;
4833
+ const step = (level, smooth) => {
4834
+ const next = sized(level);
4835
+ if (!next)
4836
+ return false;
4837
+ if (smooth)
4838
+ next.pen.imageSmoothingQuality = "high";
4839
+ next.pen.drawImage(at, 0, 0, next.canvas.width, next.canvas.height);
4840
+ if (at !== shot)
4841
+ spend(at);
4842
+ at = next.canvas;
4843
+ return true;
4844
+ };
4845
+ for (let level = halvings - 1;level >= 0; level--)
4846
+ if (!step(level, false))
4847
+ return at;
4848
+ for (let level = 1;level <= Math.min(Math.log2(KEPT), halvings); level++)
4849
+ if (!step(level, true))
4850
+ return at;
4851
+ return at;
4584
4852
  }
4585
- function along(from, angle, radius, off = 0) {
4586
- const step = direction(angle);
4587
- return { x: from.x + radius * step.x + off * step.y, y: from.y + radius * step.y - off * step.x };
4853
+ function blankUrl(width, height) {
4854
+ return svgUrl(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"/>`);
4588
4855
  }
4589
- function drawMat(size, hair, avoid, bleed = { left: 0, right: 0 }) {
4590
- const svg = svgNode("svg", { class: "mat", "aria-hidden": "true" });
4591
- const sheet = svgNode("g", { transform: `translate(${bleed.left} 0)` });
4592
- const half = SPAN / 2;
4593
- const minor = [];
4594
- for (let at = CELL;at < SPAN; at += CELL)
4595
- if (at !== half)
4596
- minor.push(at);
4597
- const arm = 6;
4598
- const pattern = svgNode("pattern", {
4599
- id: "mat-grid",
4600
- x: -half,
4601
- y: -half,
4602
- width: SPAN,
4603
- height: SPAN,
4604
- patternUnits: "userSpaceOnUse"
4605
- });
4606
- pattern.append(svgNode("path", { class: "cell", d: lines(minor, SPAN, hair) }), svgNode("path", { class: "major", d: lines([0], SPAN, hair) }), svgNode("path", { class: "span", d: lines([half], SPAN, hair) }), svgNode("path", {
4607
- class: "mark",
4608
- d: `M${half - arm} ${half}h${2 * arm + hair}v${hair}h${-2 * arm - hair}Z` + `M${half} ${half - arm}h${hair}v${2 * arm + hair}h${-hair}Z`
4609
- }));
4610
- const defs = svgNode("defs", {});
4611
- defs.append(pattern);
4612
- const top = ticks(size.width).map((tick) => `M${tick.at} 0h${hair}v${tick.size}h${-hair}Z`).join("");
4613
- const left = ticks(size.height).map((tick) => `M0 ${tick.at}h${tick.size}v${hair}h${-tick.size}Z`).join("");
4614
- sheet.append(svgNode("rect", {
4615
- x: -bleed.left,
4616
- width: bleed.left + size.width + bleed.right,
4617
- height: "100%",
4618
- fill: "url(#mat-grid)"
4619
- }), svgNode("path", { class: "tick", d: top + left }));
4620
- svg.append(defs, sheet);
4621
- const origin2 = vertex(size.height);
4622
- if (origin2) {
4623
- const base = along(origin2, 0, ARC);
4624
- const rim = { x: origin2.x, y: origin2.y - ARC };
4625
- const arc = svgNode("path", {
4626
- class: "angle",
4627
- d: `M${base.x} ${base.y}A${ARC} ${ARC} 0 0 0 ${rim.x} ${rim.y}`,
4628
- "stroke-width": hair
4629
- });
4630
- arc.style.opacity = String(GUIDE.line);
4631
- sheet.append(arc);
4632
- for (const angle of ANGLES) {
4633
- const start = along(origin2, angle, ARC);
4634
- const end = exit(origin2, angle, size);
4635
- const line = svgNode("path", {
4636
- class: "angle",
4637
- d: `M${start.x} ${start.y}L${end.x} ${end.y}`,
4638
- "stroke-width": hair
4639
- });
4640
- line.style.opacity = String(angle === 45 ? GUIDE.half : GUIDE.line);
4641
- sheet.append(line);
4642
- const reach = Math.hypot(end.x - origin2.x, end.y - origin2.y);
4643
- const at = along(origin2, angle, LABEL.radius, LABEL.off);
4644
- if (reach < LABEL.radius + LABEL.room || at.y < LABEL.top)
4645
- continue;
4646
- const text = svgNode("text", {
4647
- x: at.x,
4648
- y: at.y,
4649
- transform: `rotate(${-angle} ${at.x} ${at.y})`
4650
- });
4651
- text.textContent = `${angle}°`;
4652
- sheet.append(text);
4856
+ function blankPictures(live, copy) {
4857
+ const shown2 = live.querySelectorAll("img");
4858
+ copy.querySelectorAll("img").forEach((image, index) => {
4859
+ const from = shown2[index];
4860
+ if (!from || !from.complete || !(from.naturalWidth > 0 && from.naturalHeight > 0))
4861
+ return;
4862
+ for (const name of ["srcset", "sizes", "loading"])
4863
+ image.removeAttribute(name);
4864
+ const holder = image.parentElement;
4865
+ if (holder?.localName === "picture")
4866
+ for (const source of holder.querySelectorAll("source"))
4867
+ source.remove();
4868
+ image.setAttribute("src", blankUrl(from.naturalWidth, from.naturalHeight));
4869
+ });
4870
+ }
4871
+ function copyPage(frame2, leave) {
4872
+ const doc = frame2.contentDocument;
4873
+ if (!doc?.documentElement)
4874
+ return null;
4875
+ const rules = [];
4876
+ const written2 = embedFonts(doc);
4877
+ for (const sheet of [...doc.styleSheets, ...doc.adoptedStyleSheets ?? []]) {
4878
+ try {
4879
+ for (const rule of sheet.cssRules)
4880
+ rules.push(written2(rule));
4881
+ } catch {}
4882
+ }
4883
+ const inert = doc.implementation.createHTMLDocument("");
4884
+ const root = inert.importNode(doc.documentElement, true);
4885
+ if (leave) {
4886
+ const live = doc.documentElement.getElementsByTagName("*");
4887
+ const copied = root.getElementsByTagName("*");
4888
+ for (let index = 0;index < live.length; index++) {
4889
+ const node = live[index];
4890
+ if (node && leave(node))
4891
+ copied[index]?.setAttribute("data-devknobs", "");
4653
4892
  }
4654
4893
  }
4655
- for (const at of numbers(size.width, avoid)) {
4656
- const text = svgNode("text", { x: at + 3, y: TICK.span + 1 });
4657
- text.textContent = String(at);
4658
- sheet.append(text);
4894
+ blankPictures(doc.documentElement, root);
4895
+ for (const node of root.querySelectorAll("script, link, style, noscript, [data-devknobs]"))
4896
+ node.remove();
4897
+ const style = inert.createElement("style");
4898
+ style.textContent = rules.join(`
4899
+ `);
4900
+ (root.querySelector("head") ?? root).append(style);
4901
+ return root;
4902
+ }
4903
+ var LONE_HALF = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
4904
+ function svgUrl(svg) {
4905
+ const whole = typeof svg.toWellFormed === "function" ? svg.toWellFormed() : svg.replace(LONE_HALF, "�");
4906
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(whole)}`;
4907
+ }
4908
+ function rootSize(doc, view) {
4909
+ const size = view.getComputedStyle(doc.documentElement).fontSize;
4910
+ return size ? `font-size:${size} !important` : "";
4911
+ }
4912
+ async function paintPage(frame2, glass, size, color, copy) {
4913
+ const doc = frame2.contentDocument;
4914
+ const view = frame2.contentWindow;
4915
+ const screen = glass.getBoundingClientRect();
4916
+ const box2 = frame2.getBoundingClientRect();
4917
+ if (!doc || !view || screen.width <= 0 || view.innerWidth <= 0)
4918
+ return null;
4919
+ const { innerWidth: width, innerHeight: height, scrollX, scrollY } = view;
4920
+ const css = size.width / screen.width;
4921
+ const scale = box2.width * css / width;
4922
+ const at = { x: (box2.left - screen.left) * css, y: (box2.top - screen.top) * css };
4923
+ let over2 = null;
4924
+ for (const node of doc.querySelectorAll(MEDIA)) {
4925
+ const media = node.closest("[data-devknobs]") ? null : mediaOf(node);
4926
+ const rect = node.getBoundingClientRect();
4927
+ if (!media || rect.bottom <= 0 || rect.top >= height || rect.width <= 0)
4928
+ continue;
4929
+ if (!over2) {
4930
+ over2 = canvasOf(size.width, size.height);
4931
+ over2?.pen.setTransform(scale, 0, 0, scale, at.x, at.y);
4932
+ }
4933
+ try {
4934
+ if (over2)
4935
+ drawMedia(over2.pen, media, rect, view.getComputedStyle(node));
4936
+ } catch {}
4659
4937
  }
4660
- for (const at of numbers(size.height)) {
4661
- const text = svgNode("text", { x: TICK.span + 2, y: at, "dominant-baseline": "middle" });
4662
- text.textContent = String(at);
4663
- sheet.append(text);
4938
+ const root = copy.cloneNode(true);
4939
+ const scrolled = `position:relative;left:${-scrollX}px;top:${-scrollY}px`;
4940
+ const sized = rootSize(doc, view);
4941
+ root.setAttribute("style", `${root.getAttribute("style") ?? ""};${sized};${scrolled}`);
4942
+ const markup = new XMLSerializer().serializeToString(root);
4943
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" style="${sized}">` + `<foreignObject width="100%" height="100%">${markup}</foreignObject></svg>`;
4944
+ const image = new Image;
4945
+ try {
4946
+ image.src = svgUrl(svg);
4947
+ await image.decode();
4948
+ } catch {
4949
+ if (over2)
4950
+ spend(over2.canvas);
4951
+ return null;
4664
4952
  }
4665
- return svg;
4953
+ const drawn = canvasOf(size.width, size.height);
4954
+ if (!drawn)
4955
+ return null;
4956
+ const { canvas, pen } = drawn;
4957
+ pen.fillStyle = color;
4958
+ pen.fillRect(0, 0, canvas.width, canvas.height);
4959
+ pen.setTransform(scale, 0, 0, scale, at.x, at.y);
4960
+ pen.drawImage(image, 0, 0, width, height);
4961
+ if (over2) {
4962
+ pen.setTransform(1, 0, 0, 1, 0, 0);
4963
+ pen.drawImage(over2.canvas, 0, 0);
4964
+ spend(over2.canvas);
4965
+ }
4966
+ return canvas;
4666
4967
  }
4667
4968
 
4668
- // src/engine/foldgl.ts
4669
- function screenLook(open, wedge, free = 1, shaded = null, pane = shaded ?? "inner") {
4670
- const blurred = blurOn();
4671
- const [, wipe, area, far] = shaded ? shadeOf(shaded, open, free) : [1, 0, 0, 0];
4672
- return {
4673
- peak: blurred ? turnBlur(open, pane) : 0,
4674
- edge: blurred ? [tune.edgeHinge * wedge, tune.edgeFree * wedge] : [0, 0],
4675
- free,
4676
- dark: shadesOn() ? freeDepth(open) : 0,
4677
- lit: [wipe, area, far]
4678
- };
4969
+ // src/engine/underbar.ts
4970
+ var UNDERBAR_CSS = `
4971
+ .underbar {
4972
+ position: absolute;
4973
+ overflow: hidden;
4974
+ pointer-events: none;
4975
+ transform-origin: 0 0;
4679
4976
  }
4680
- var WEIGHTS = [0.375, 0.25, 0.0625];
4681
- function wedgeOf(window2, pane, picture, span) {
4682
- const { top, bottom } = darkAt(window2, pane, picture);
4683
- return picture.height > 0 ? Math.max(top, bottom) * span / picture.height : 0;
4977
+ .underbar[hidden] { display: none; }
4978
+ .underbar > img {
4979
+ position: absolute;
4980
+ left: 0;
4981
+ top: 0;
4982
+ max-width: none;
4983
+ will-change: transform;
4684
4984
  }
4685
- function freeOf(window2, pane, picture) {
4686
- if (picture.width <= 0)
4687
- return 1;
4688
- const [a, b, c, d] = window2;
4689
- const seen = pane === "inner" ? picture.x + picture.width - (a[0] + d[0]) / 2 : (b[0] + c[0]) / 2 - picture.x;
4690
- return Math.min(1, Math.max(0, seen / picture.width));
4985
+ `;
4986
+ var GAP = 250;
4987
+ var SHARE = 10;
4988
+ function bandRect(page, height) {
4989
+ if (!page)
4990
+ return null;
4991
+ const top = page.y + page.height;
4992
+ const tall = height - top;
4993
+ return tall >= 0.5 ? { x: page.x, y: top, width: page.width, height: tall } : null;
4691
4994
  }
4692
- function reachOf(shots, pane) {
4693
- let most = 0;
4694
- for (const shot of shots.frames) {
4695
- if (shotPane(shots, shot) !== pane)
4696
- continue;
4697
- const quad = shotQuad(shot, pane);
4698
- const picture = shotPicture(shots, pane, quad);
4699
- most = Math.max(most, wedgeOf(shotWindow(quad, pane, picture), pane, picture, 1));
4700
- }
4701
- return most;
4995
+ function showsBand(bars, look) {
4996
+ if (!bars || bars.platform !== "safari" || !bars.status && !bars.column)
4997
+ return false;
4998
+ return !!look && !look.footer;
4702
4999
  }
4703
- function canvasRect(place2) {
4704
- const { across, part, stage, margin: margin2 } = place2;
4705
- return across ? { x: part.x, y: -margin2, width: part.width, height: stage.height + 2 * margin2 } : { x: -margin2, y: part.y, width: stage.width + 2 * margin2, height: part.height };
5000
+ function bandShift(scrollY, innerHeight, scale) {
5001
+ return -(scrollY + innerHeight) * scale;
4706
5002
  }
4707
- function hingeLine(pane, across, part) {
4708
- const { x, y, width, height } = part;
4709
- if (across)
4710
- return pane === "inner" ? [-1 / width, 0, (x + width) / width] : [1 / width, 0, -x / width];
4711
- return pane === "inner" ? [0, 1 / height, -y / height] : [0, -1 / height, (y + height) / height];
5003
+ var VH = /(-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)[sld]?vh\b/gi;
5004
+ function viewportUnits(css, height) {
5005
+ return css.replace(VH, (_, amount) => `${Math.round(Number(amount) * height) / 100}px`);
4712
5006
  }
4713
- function contextOf(canvas) {
4714
- if (typeof WebGL2RenderingContext === "undefined")
5007
+ function pictureOf(frame2) {
5008
+ const doc = frame2.contentDocument;
5009
+ const view = frame2.contentWindow;
5010
+ if (!doc?.documentElement || !view || view.innerWidth <= 0)
4715
5011
  return null;
4716
- const gl = canvas.getContext("webgl2", {
4717
- alpha: false,
4718
- antialias: false,
4719
- depth: false,
4720
- stencil: false,
4721
- premultipliedAlpha: false,
4722
- powerPreference: "low-power"
4723
- });
4724
- return gl instanceof WebGL2RenderingContext ? gl : null;
5012
+ const { innerWidth: width, innerHeight: tall } = view;
5013
+ const copy = copyPage(frame2, (node) => view.getComputedStyle(node).position === "fixed");
5014
+ if (!copy)
5015
+ return null;
5016
+ for (const style of copy.querySelectorAll("style")) {
5017
+ style.textContent = viewportUnits(style.textContent ?? "", tall);
5018
+ }
5019
+ for (const node of copy.querySelectorAll("[style]")) {
5020
+ node.setAttribute("style", viewportUnits(node.getAttribute("style") ?? "", tall));
5021
+ }
5022
+ const full = Math.max(doc.documentElement.scrollHeight, tall);
5023
+ const root = doc.documentElement.getBoundingClientRect().height;
5024
+ const sized = rootSize(doc, view);
5025
+ copy.setAttribute("style", `${copy.getAttribute("style") ?? ""};${sized};height:${root}px !important`);
5026
+ const markup = new XMLSerializer().serializeToString(copy);
5027
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${full}" style="${sized}">` + `<foreignObject width="100%" height="100%">${markup}</foreignObject></svg>`;
5028
+ return { src: svgUrl(svg), width, height: full };
5029
+ }
5030
+ function createUnderbar(glass, frame2) {
5031
+ const band = el("div", "underbar");
5032
+ band.setAttribute("aria-hidden", "true");
5033
+ band.hidden = true;
5034
+ glass.append(band);
5035
+ let image = null;
5036
+ let picture = null;
5037
+ let taken = "";
5038
+ let watched2 = null;
5039
+ let observer = null;
5040
+ let changed = true;
5041
+ let waiting = 0;
5042
+ let painting = false;
5043
+ let last = 0;
5044
+ let cost = 0;
5045
+ let wide = 0;
5046
+ const keyOf = () => {
5047
+ try {
5048
+ const doc = frame2.contentDocument;
5049
+ const view = frame2.contentWindow;
5050
+ if (!doc?.documentElement || !view)
5051
+ return null;
5052
+ if (doc !== watched2) {
5053
+ observer?.disconnect();
5054
+ const next = new MutationObserver(() => {
5055
+ changed = true;
5056
+ soon();
5057
+ });
5058
+ next.observe(doc, { subtree: true, childList: true, attributes: true, characterData: true });
5059
+ observer = next;
5060
+ watched2 = doc;
5061
+ changed = true;
5062
+ image?.remove();
5063
+ image = null;
5064
+ picture = null;
5065
+ taken = "";
5066
+ }
5067
+ return `${view.innerWidth}|${view.innerHeight}|${doc.documentElement.scrollHeight}`;
5068
+ } catch {
5069
+ return null;
5070
+ }
5071
+ };
5072
+ const move = () => {
5073
+ if (band.hidden || !image || !picture)
5074
+ return;
5075
+ try {
5076
+ const view = frame2.contentWindow;
5077
+ if (!view)
5078
+ return;
5079
+ const shift = bandShift(view.scrollY, view.innerHeight, wide / picture.width);
5080
+ image.style.transform = `translate3d(0, ${shift}px, 0)`;
5081
+ } catch {}
5082
+ };
5083
+ const paint = async () => {
5084
+ waiting = 0;
5085
+ if (band.hidden || painting)
5086
+ return;
5087
+ const key = keyOf();
5088
+ if (key === null) {
5089
+ image?.remove();
5090
+ image = null;
5091
+ picture = null;
5092
+ return;
5093
+ }
5094
+ if (!changed && key === taken)
5095
+ return;
5096
+ painting = true;
5097
+ changed = false;
5098
+ const start = performance.now();
5099
+ let next = null;
5100
+ try {
5101
+ next = pictureOf(frame2);
5102
+ } catch {
5103
+ next = null;
5104
+ }
5105
+ const fresh2 = new Image;
5106
+ let drawn = false;
5107
+ if (next) {
5108
+ fresh2.src = next.src;
5109
+ drawn = await fresh2.decode().then(() => true, () => false);
5110
+ }
5111
+ cost = performance.now() - start;
5112
+ last = performance.now();
5113
+ performance.measure("devknobs underbar picture", { start, duration: cost });
5114
+ painting = false;
5115
+ if (!next || !drawn)
5116
+ return;
5117
+ fresh2.alt = "";
5118
+ if (image)
5119
+ image.replaceWith(fresh2);
5120
+ else
5121
+ band.append(fresh2);
5122
+ image = fresh2;
5123
+ picture = next;
5124
+ taken = key;
5125
+ fit();
5126
+ if (changed)
5127
+ soon();
5128
+ };
5129
+ function soon() {
5130
+ if (waiting || band.hidden)
5131
+ return;
5132
+ const wait = Math.max(0, last + Math.max(GAP, cost * SHARE) - performance.now());
5133
+ waiting = window.setTimeout(() => void paint(), wait);
5134
+ }
5135
+ function fit() {
5136
+ if (!image || !picture)
5137
+ return;
5138
+ image.style.width = `${wide}px`;
5139
+ image.style.height = `${picture.height * wide / picture.width}px`;
5140
+ move();
5141
+ }
5142
+ return {
5143
+ show(rect, zoom, look) {
5144
+ const on = rect !== null && look !== null;
5145
+ band.hidden = !on;
5146
+ if (!rect || !look) {
5147
+ clearTimeout(waiting);
5148
+ waiting = 0;
5149
+ return;
5150
+ }
5151
+ place(band, rect.x * zoom, rect.y * zoom, rect.width, rect.height);
5152
+ wide = rect.width;
5153
+ band.style.transform = zoom === 1 ? "" : `scale(${zoom})`;
5154
+ band.style.background = look.background;
5155
+ const key = keyOf();
5156
+ if (key !== taken || changed)
5157
+ soon();
5158
+ fit();
5159
+ },
5160
+ move,
5161
+ refresh() {
5162
+ changed = true;
5163
+ soon();
5164
+ },
5165
+ remove() {
5166
+ clearTimeout(waiting);
5167
+ observer?.disconnect();
5168
+ observer = null;
5169
+ watched2 = null;
5170
+ band.remove();
5171
+ }
5172
+ };
4725
5173
  }
4726
- var VERTEX = `#version 300 es
4727
- in vec2 corner;
4728
- uniform vec4 view;
4729
- out vec2 pos;
4730
- void main() {
4731
- pos = view.xy + corner * view.zw;
4732
- gl_Position = vec4(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0, 0.0, 1.0);
4733
- }`;
4734
- var FRAGMENT = `#version 300 es
4735
- precision highp float;
4736
- uniform sampler2D page;
4737
- uniform vec2 stage;
4738
- uniform vec2 along;
4739
- uniform vec3 line;
4740
- uniform float peak;
4741
- uniform vec2 edge;
4742
- uniform float free;
4743
- uniform float dark;
4744
- uniform vec2 shape;
4745
- uniform vec2 rimmed;
4746
- uniform vec3 band;
4747
- uniform vec3 lit;
4748
- uniform vec2 run;
4749
- uniform vec3 wiped;
4750
- uniform vec2 soften;
4751
- uniform float grain;
4752
- uniform float px;
4753
- in vec2 pos;
4754
- out vec4 color;
4755
- const float WEIGHTS[3] = float[3](${WEIGHTS.join(", ")});
4756
- float cover(float at, float span, float soft) {
4757
- return smoothstep(-soft, soft, at) * (1.0 - smoothstep(span - soft, span + soft, at));
5174
+
5175
+ // src/engine/browserdraw.ts
5176
+ var BARS_CSS = `
5177
+ .browser {
5178
+ position: absolute;
5179
+ top: 0;
5180
+ left: 0;
5181
+ overflow: hidden;
5182
+ transform-origin: 0 0;
5183
+ pointer-events: none;
5184
+ cursor: default;
5185
+ user-select: none;
5186
+ -webkit-user-select: none;
5187
+ font-family: ${FONT};
5188
+ font-weight: 400;
5189
+ -webkit-font-smoothing: antialiased;
5190
+ line-height: 1;
5191
+ }
5192
+ .browser > *,
5193
+ .browser > * > *,
5194
+ .browser .group > * {
5195
+ position: absolute;
5196
+ box-sizing: border-box;
5197
+ }
5198
+ .browser svg { overflow: visible; }
5199
+ .browser .press { pointer-events: auto; cursor: default; }
5200
+ ${SAFARI_CSS}
5201
+ ${CHROME_CSS}
5202
+ ${UNDERBAR_CSS}
5203
+ `;
5204
+ var BUILDERS = { safari: buildSafari, chrome: buildChrome };
5205
+ function toRgb(color) {
5206
+ const parsed = parseColor(color);
5207
+ if (parsed)
5208
+ return parsed;
5209
+ try {
5210
+ const canvas = document.createElement("canvas");
5211
+ canvas.width = 1;
5212
+ canvas.height = 1;
5213
+ const context = canvas.getContext("2d", { willReadFrequently: true });
5214
+ if (!context)
5215
+ return null;
5216
+ context.fillStyle = color;
5217
+ context.fillRect(0, 0, 1, 1);
5218
+ const [r = 0, g = 0, b = 0, a = 0] = context.getImageData(0, 0, 1, 1).data;
5219
+ return { red: r, green: g, blue: b, alpha: a / 255 };
5220
+ } catch {
5221
+ return null;
5222
+ }
4758
5223
  }
4759
- float shadow(float t) {
4760
- if (dark <= 0.0) return 1.0;
4761
- float across = t / max(free, 0.001);
4762
- float deep = band.z * smoothstep(band.x, 1.0, across) + (1.0 - band.z) * smoothstep(1.0 - band.y, 1.0, across);
4763
- return 1.0 - dark * deep;
5224
+ function backgroundOf(doc, view, dark) {
5225
+ const root = view.getComputedStyle(doc.documentElement);
5226
+ const schemes = root.colorScheme ?? "";
5227
+ const canvasDark = schemes.includes("dark") && (dark || !schemes.includes("light"));
5228
+ let base = canvasDark ? [18, 18, 18] : [255, 255, 255];
5229
+ const layers = [doc.documentElement, doc.body].filter((node) => !!node);
5230
+ for (const node of layers) {
5231
+ const color = toRgb(view.getComputedStyle(node).backgroundColor);
5232
+ if (!color || color.alpha === 0)
5233
+ continue;
5234
+ const { red, green, blue, alpha } = color;
5235
+ const [r, g, b] = base;
5236
+ const over2 = (top, under) => Math.round(top * alpha + under * (1 - alpha));
5237
+ base = [over2(red, r), over2(green, g), over2(blue, b)];
5238
+ }
5239
+ return base;
4764
5240
  }
4765
- float shade(float t) {
4766
- if (lit.x + lit.y + lit.z <= 0.0) return 1.0;
4767
- float uv = run.x + run.y * t;
4768
- float off = abs(uv - wiped.x);
4769
- float wipe = 1.0 - clamp(smoothstep(wiped.y, wiped.z, off) * lit.x, 0.0, 1.0);
4770
- float soft = 1.0 - smoothstep(0.9, 1.3, clamp((off - soften.x) / (soften.y - soften.x) * lit.y, 0.0, 4.0 / 3.0));
4771
- float away = mix(1.0, smoothstep(0.05, 0.5, uv), lit.z);
4772
- return pow(clamp(wipe * soft * soft * away, 0.0, 1.0), 1.0 / 2.2);
5241
+ function rgbOf(color) {
5242
+ return `rgb(${Math.round(color.red)}, ${Math.round(color.green)}, ${Math.round(color.blue)})`;
4773
5243
  }
4774
- vec4 shaded(vec3 rgb, float t) {
4775
- float speck = 0.0;
4776
- if (grain > 0.0 && dark + lit.x + lit.y + lit.z > 0.0) {
4777
- speck = (fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5) * grain / 255.0;
4778
- }
4779
- return vec4(rgb * shadow(t) * shade(min(t, free)) + speck, 1.0);
5244
+ function blend({ red, green, blue, alpha }, [r, g, b]) {
5245
+ const over2 = (top, below) => Math.round(top * alpha + below * (1 - alpha));
5246
+ return [over2(red, r), over2(green, g), over2(blue, b)];
4780
5247
  }
4781
- float seen(vec2 at, float soft) {
4782
- float reach = soft * length(line.xy);
4783
- return cover(dot(along, at), dot(along, stage), soft) * (1.0 - smoothstep(free - reach, free + reach, dot(line.xy, at) + line.z));
5248
+ function rgbText([r, g, b]) {
5249
+ return `rgb(${r}, ${g}, ${b})`;
4784
5250
  }
4785
- void main() {
4786
- vec2 texels = vec2(textureSize(page, 0)) / stage;
4787
- vec2 right = dFdx(pos) * texels;
4788
- vec2 down = dFdy(pos) * texels;
4789
- float sharp = 0.5 * log2(max(1.0, max(dot(right, right), dot(down, down))));
4790
- float t = clamp(dot(line.xy, pos) + line.z, 0.0, 1.0);
4791
- float span = dot(along, stage);
4792
- float at = dot(along, pos);
4793
- float across = free > 0.0 ? min(1.0, t / free) : 1.0;
4794
- float wide = peak * (shape.x + (1.0 - shape.x) * pow(across, shape.y));
4795
- float rim = mix(edge.x, edge.y, t);
4796
- if (rim > 0.0) wide = max(wide, rim * (1.0 - smoothstep(0.0, rimmed.x * rim, min(at, span - at))));
4797
- float gap = rimmed.y * wide;
4798
- float soft = max(0.5 * px, 0.75 * gap);
4799
- float lod = max(sharp, log2(max(1.0, gap * max(texels.x, texels.y))));
4800
- vec3 sum = vec3(0.0);
4801
- if (peak + edge.x + edge.y <= 0.0) {
4802
- sum = textureLod(page, pos / stage, lod).rgb * seen(pos, soft);
4803
- } else {
4804
- for (int y = -2; y <= 2; y++) {
4805
- for (int x = -2; x <= 2; x++) {
4806
- vec2 tap = pos + vec2(float(x), float(y)) * gap;
4807
- float weight = WEIGHTS[abs(x)] * WEIGHTS[abs(y)];
4808
- sum += textureLod(page, tap / stage, lod).rgb * seen(tap, soft) * weight;
4809
- }
4810
- }
4811
- }
4812
- color = shaded(sum, t);
4813
- }`;
4814
- function compile(gl, kind, source) {
4815
- const shader = gl.createShader(kind);
4816
- if (!shader)
4817
- return null;
4818
- gl.shaderSource(shader, source);
4819
- gl.compileShader(shader);
4820
- return shader;
5251
+ function paintOf(view, node) {
5252
+ const color = toRgb(view.getComputedStyle(node).backgroundColor);
5253
+ return color && color.alpha > 0 ? color : null;
4821
5254
  }
4822
- function firstLine(log, otherwise) {
4823
- return log?.trim().split(`
4824
- `)[0]?.trim() || otherwise;
5255
+ function solidOf(view, node) {
5256
+ const color = paintOf(view, node);
5257
+ return color && color.alpha >= 0.5 ? color : null;
4825
5258
  }
4826
- function uploadWhy(error) {
4827
- const name = error instanceof Error ? error.name : String(error);
4828
- const tainted = "the browser holds the picture as another origin's, as one with a picture, video or canvas from another origin drawn in, or a drawing of the page this browser does not trust";
4829
- return `the picture could not be uploaded: ${name}${name === "SecurityError" ? `, ${tainted}` : ""}`;
5259
+ function barAt(doc, view, x, y, edge, base) {
5260
+ let paint = null;
5261
+ for (let node = doc.elementFromPoint(x, y);node; node = node.parentElement) {
5262
+ if (node === doc.body || node === doc.documentElement)
5263
+ return null;
5264
+ paint ??= solidOf(view, node);
5265
+ const { position } = view.getComputedStyle(node);
5266
+ if (position !== "fixed" && position !== "sticky")
5267
+ continue;
5268
+ const box2 = node.getBoundingClientRect();
5269
+ const touches = edge === "top" ? box2.top <= 0.5 : box2.bottom >= view.innerHeight - 0.5;
5270
+ return touches && paint ? rgbText(blend(paint, base)) : null;
5271
+ }
5272
+ return null;
4830
5273
  }
4831
- function screenGl(place2, refused) {
4832
- const canvas = document.createElement("canvas");
4833
- const gl = contextOf(canvas);
4834
- if (!gl) {
4835
- refused(typeof WebGL2RenderingContext === "undefined" ? "this browser has no WebGL2" : "the canvas gave no WebGL2 context", null);
4836
- return null;
5274
+ function edgeBar(doc, view, edge, base) {
5275
+ const width = view.innerWidth;
5276
+ const y = edge === "top" ? 0.5 : view.innerHeight - 1;
5277
+ const colors = [width / 2, 1, width - 1].map((x) => barAt(doc, view, x, y, edge, base));
5278
+ const [middle = null] = colors;
5279
+ return colors.every((color) => color !== null) ? middle : null;
5280
+ }
5281
+ function colorAt(doc, view, x, y, base) {
5282
+ const layers = [];
5283
+ for (const node of doc.elementsFromPoint(x, y)) {
5284
+ if (node === doc.body || node === doc.documentElement)
5285
+ break;
5286
+ const color = layers.length === 0 ? solidOf(view, node) : paintOf(view, node);
5287
+ if (!color)
5288
+ continue;
5289
+ layers.push(color);
5290
+ if (color.alpha >= 1)
5291
+ break;
4837
5292
  }
4838
- const rect = canvasRect(place2);
4839
- const most = Math.max(1, gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) || 4096);
4840
- const density2 = Math.min(place2.density, most / rect.width, most / rect.height);
4841
- canvas.width = Math.max(1, Math.round(rect.width * density2));
4842
- canvas.height = Math.max(1, Math.round(rect.height * density2));
4843
- canvas.style.position = "absolute";
4844
- canvas.style.display = "block";
4845
- canvas.style.left = `${rect.x}px`;
4846
- canvas.style.top = `${rect.y}px`;
4847
- canvas.style.width = `${rect.width}px`;
4848
- canvas.style.height = `${rect.height}px`;
4849
- const vertex2 = compile(gl, gl.VERTEX_SHADER, VERTEX);
4850
- const fragment = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);
4851
- const program = gl.createProgram();
4852
- const corners = gl.createBuffer();
4853
- const texture = gl.createTexture();
4854
- const free = () => {
4855
- gl.deleteTexture(texture);
4856
- gl.deleteBuffer(corners);
4857
- gl.deleteProgram(program);
4858
- gl.deleteShader(vertex2);
4859
- gl.deleteShader(fragment);
4860
- gl.getExtension("WEBGL_lose_context")?.loseContext();
4861
- canvas.remove();
4862
- };
4863
- if (!vertex2 || !fragment || !program || !corners || !texture) {
4864
- const why = gl.isContextLost() ? "the WebGL2 context was lost as it was made" : "WebGL2 made no shader, program, buffer or texture";
4865
- free();
4866
- refused(why, null);
5293
+ if (layers.length === 0)
4867
5294
  return null;
5295
+ return rgbText(layers.reduceRight((under, color) => blend(color, under), base));
5296
+ }
5297
+ function readLook(frame2, probe = null) {
5298
+ const white = "rgb(255, 255, 255)";
5299
+ const fallback = {
5300
+ background: white,
5301
+ top: white,
5302
+ bottom: white,
5303
+ footer: false,
5304
+ under: [],
5305
+ dark: false,
5306
+ scheme: "light",
5307
+ host: "",
5308
+ canBack: false,
5309
+ canForward: false
5310
+ };
5311
+ try {
5312
+ const view = frame2.contentWindow;
5313
+ const doc = frame2.contentDocument;
5314
+ if (!view || !doc?.documentElement)
5315
+ return fallback;
5316
+ const scheme = view.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
5317
+ const base = backgroundOf(doc, view, scheme === "dark");
5318
+ const [r, g, b] = base;
5319
+ const background = rgbText(base);
5320
+ const top = edgeBar(doc, view, "top", base) ?? background;
5321
+ const last = () => colorAt(doc, view, view.innerWidth / 2, view.innerHeight - 1, base);
5322
+ const footer = edgeBar(doc, view, "bottom", base);
5323
+ const bottom = footer ?? last() ?? background;
5324
+ const under = (probe?.points ?? []).map(({ x, y }) => {
5325
+ const { page } = probe ?? { page: { x: 0, y: 0, width: 0, height: 0 } };
5326
+ const inside = { x: x - page.x, y: y - page.y };
5327
+ if (inside.y < 0)
5328
+ return { x, y, color: top };
5329
+ if (inside.x < 0 || inside.x >= page.width)
5330
+ return { x, y, color: background };
5331
+ if (inside.y >= page.height)
5332
+ return { x, y, color: bottom };
5333
+ const across = Math.min(Math.max(inside.x, 0), page.width - 1);
5334
+ return { x, y, color: colorAt(doc, view, across, inside.y, base) ?? background };
5335
+ });
5336
+ const navigation = navigationOf(view);
5337
+ const can = (key) => {
5338
+ const value = navigation && Reflect.get(navigation, key);
5339
+ return typeof value === "boolean" ? value : null;
5340
+ };
5341
+ return {
5342
+ background,
5343
+ top,
5344
+ bottom,
5345
+ footer: footer !== null,
5346
+ under,
5347
+ dark: luminance(r, g, b) < 0.4,
5348
+ scheme,
5349
+ host: view.location.host,
5350
+ canBack: can("canGoBack") ?? view.history.length > 1,
5351
+ canForward: can("canGoForward") ?? false
5352
+ };
5353
+ } catch {
5354
+ return fallback;
4868
5355
  }
4869
- gl.attachShader(program, vertex2);
4870
- gl.attachShader(program, fragment);
4871
- gl.linkProgram(program);
4872
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
4873
- const log = [vertex2, fragment].map((shader) => gl.getShaderInfoLog(shader)).find((said) => said?.trim()) ?? gl.getProgramInfoLog(program);
4874
- const lost = gl.isContextLost();
4875
- free();
4876
- refused(lost ? "the WebGL2 context was lost as it was made" : `the shader did not compile or link: ${firstLine(log, "no reason given")}`, null);
4877
- return null;
5356
+ }
5357
+ function screenFill(look, bars, page, height) {
5358
+ const strip = bars.status || bars.column || !runsUnderBars(bars.screen.id);
5359
+ if (bars.platform !== "safari" || !strip || !page)
5360
+ return look.background;
5361
+ const held = look.top !== look.background;
5362
+ const top = bars.scrim && !held ? rgbOf(underAt(look, bars.scrim.at.x, bars.scrim.at.y)) : look.top;
5363
+ if (top === look.background && look.bottom === look.background)
5364
+ return look.background;
5365
+ const start = page.y / height * 100;
5366
+ const end = (page.y + page.height) / height * 100;
5367
+ const { background: middle, bottom } = look;
5368
+ const strips = `linear-gradient(to bottom, ${top} ${start}%, ${middle} ${start}%, ${middle} ${end}%, ${bottom} ${end}%)`;
5369
+ const W = turn(bars.screen, bars.orientation).width;
5370
+ const [left, right] = [page.x / W * 100, (page.x + page.width) / W * 100];
5371
+ if (left <= 0 && right >= 100)
5372
+ return strips;
5373
+ const column = `linear-gradient(to right, ${middle} ${left}%, transparent ${left}%, transparent ${right}%, ${middle} ${right}%)`;
5374
+ return `${column}, ${strips}`;
5375
+ }
5376
+ function reaches(frame2) {
5377
+ try {
5378
+ return !!frame2.contentDocument?.documentElement;
5379
+ } catch {
5380
+ return false;
4878
5381
  }
4879
- gl.useProgram(program);
4880
- gl.bindBuffer(gl.ARRAY_BUFFER, corners);
4881
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
4882
- const corner = gl.getAttribLocation(program, "corner");
4883
- gl.enableVertexAttribArray(corner);
4884
- gl.vertexAttribPointer(corner, 2, gl.FLOAT, false, 0, 0);
4885
- const at = (name) => gl.getUniformLocation(program, name);
4886
- const { stage } = place2;
4887
- gl.uniform4f(at("view"), rect.x, rect.y, rect.width, rect.height);
4888
- gl.uniform2f(at("stage"), stage.width, stage.height);
4889
- gl.uniform2f(at("along"), place2.across ? 0 : 1, place2.across ? 1 : 0);
4890
- gl.uniform3f(at("line"), ...hingeLine(place2.pane, place2.across, place2.part));
4891
- gl.uniform1f(at("px"), canvas.width > 0 ? rect.width / canvas.width : 1);
4892
- gl.uniform1i(at("page"), 0);
4893
- const wipe = WIPE[place2.pane];
4894
- gl.uniform2f(at("run"), uvOf(place2.pane, 0), uvOf(place2.pane, 1) - uvOf(place2.pane, 0));
4895
- gl.uniform3f(at("wiped"), wipe.at, wipe.shade[0], wipe.shade[1]);
4896
- gl.uniform2f(at("soften"), wipe.blur[0], wipe.blur[1]);
4897
- const uniforms = { peak: at("peak"), edge: at("edge"), free: at("free"), dark: at("dark"), shape: at("shape"), rimmed: at("rimmed"), band: at("band"), lit: at("lit"), grain: at("grain") };
4898
- gl.bindTexture(gl.TEXTURE_2D, texture);
4899
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
4900
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
4901
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
4902
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
4903
- gl.viewport(0, 0, canvas.width, canvas.height);
4904
- const widest = gl.getParameter(gl.MAX_TEXTURE_SIZE) || 2048;
4905
- let shot = null;
5382
+ }
5383
+ var RESTYLE = 120;
5384
+ var LOAD_WAIT = 5000;
5385
+ function same(a, b) {
5386
+ return JSON.stringify(a) === JSON.stringify(b);
5387
+ }
5388
+ function createBrowser(glass, frame2, onChange, onReload = () => {}, ready = () => true) {
5389
+ const blank = el("div", "screenblank");
5390
+ blank.hidden = true;
5391
+ glass.append(blank);
5392
+ const band = createUnderbar(glass, frame2);
5393
+ const layer = el("div", "browser");
5394
+ layer.setAttribute("aria-hidden", "true");
5395
+ let view = null;
4906
5396
  let look = null;
4907
- let gone = false;
4908
- const draw = (next) => {
4909
- look = next;
4910
- if (gone || !shot)
5397
+ let painted = null;
5398
+ let built = "";
5399
+ let applied = null;
5400
+ let shrinking = 0;
5401
+ let shrinkTo = null;
5402
+ let later = 0;
5403
+ let query = null;
5404
+ let watched2 = null;
5405
+ let href = "";
5406
+ let motion = BARS_START;
5407
+ let landed = false;
5408
+ let busy = false;
5409
+ let loadWait = 0;
5410
+ let sampling = 0;
5411
+ const still2 = () => baseMatchMedia("(prefers-reduced-motion: reduce)").matches;
5412
+ const step = (event) => {
5413
+ const before = motion.minimized;
5414
+ motion = barsStep(motion, event);
5415
+ if (motion.minimized !== before)
5416
+ queueMicrotask(onChange);
5417
+ };
5418
+ const probe = () => {
5419
+ const bars = view?.bars ?? null;
5420
+ if (!view || !bars || bars.platform !== "safari")
5421
+ return null;
5422
+ const { screen, orientation, layout, minimized, edge } = bars;
5423
+ const other = barsOf(screen, orientation, layout, !minimized, edge);
5424
+ const shapes = [...bars.shapes, ...other?.shapes ?? []];
5425
+ const points = shapes.map((shape) => ({
5426
+ x: shape.x + shape.width / 2,
5427
+ y: shape.y + shape.height / 2
5428
+ }));
5429
+ const scrim = bars.scrim ?? other?.scrim;
5430
+ if (scrim)
5431
+ points.push(scrim.at);
5432
+ return { page: view.page ?? { x: 0, y: 0, ...view.size }, points };
5433
+ };
5434
+ const lookNow = () => readLook(frame2, probe());
5435
+ const placeBand = () => {
5436
+ const bars = view?.bars ?? null;
5437
+ const shown2 = view && showsBand(bars, look) && reaches(frame2) ? bandRect(applied, view.size.height) : null;
5438
+ band.show(shown2, view?.zoom ?? 1, look);
5439
+ };
5440
+ const resample = () => {
5441
+ sampling = 0;
5442
+ const bars = view?.bars;
5443
+ if (busy || !look || !view || !bars || bars.platform !== "safari")
4911
5444
  return;
4912
- gl.uniform1f(uniforms.peak, next.peak);
4913
- gl.uniform2f(uniforms.edge, ...next.edge);
4914
- gl.uniform1f(uniforms.free, next.free);
4915
- gl.uniform1f(uniforms.dark, next.dark);
4916
- gl.uniform2f(uniforms.shape, tune.blurHinge, tune.blurRise);
4917
- gl.uniform2f(uniforms.rimmed, tune.edgeReach, tune.blurSpread);
4918
- gl.uniform3f(uniforms.band, tune.darkFrom, tune.darkBand, tune.darkBroad);
4919
- gl.uniform3f(uniforms.lit, ...next.lit);
4920
- gl.uniform1f(uniforms.grain, tune.grain);
4921
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
5445
+ const next = lookNow();
5446
+ if (JSON.stringify(next) === JSON.stringify(look))
5447
+ return;
5448
+ look = next;
5449
+ glass.style.background = screenFill(look, bars, view.page, view.size.height);
5450
+ back();
5451
+ placeBand();
5452
+ painted?.apply(bars.minimized, look);
4922
5453
  };
4923
- canvas.addEventListener("webglcontextlost", () => {
4924
- if (gone)
4925
- return;
4926
- gone = true;
4927
- canvas.remove();
4928
- refused("the WebGL2 context was lost", shot);
4929
- });
4930
- const refuse = (why, next) => {
4931
- if (!gone)
4932
- free();
4933
- gone = true;
4934
- refused(why, next);
5454
+ const growth = () => {
5455
+ const bars = view?.bars;
5456
+ if (!bars)
5457
+ return { room: 0, grow: 0 };
5458
+ const { screen, orientation, layout, edge } = bars;
5459
+ const [full, mini] = [false, true].map((minimized) => viewportOf(screen, orientation, layout, minimized, edge));
5460
+ if (!full || !mini)
5461
+ return { room: 0, grow: 0 };
5462
+ return { room: Math.max(0, full.y - mini.y), grow: Math.max(0, mini.height - full.height) };
4935
5463
  };
4936
- return {
4937
- canvas,
4938
- paint(next) {
4939
- if (gone)
4940
- return refuse("the WebGL2 context is gone", next);
4941
- if (Math.max(next.width, next.height) > widest) {
4942
- return refuse(`the picture, ${next.width} by ${next.height} px, is larger than MAX_TEXTURE_SIZE, ${widest}`, next);
4943
- }
4944
- gl.getError();
4945
- try {
4946
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, next);
4947
- } catch (error) {
4948
- return refuse(uploadWhy(error), next);
5464
+ const onScroll = () => {
5465
+ band.move();
5466
+ landed = false;
5467
+ const page = frame2.contentWindow;
5468
+ if (page) {
5469
+ const { room, grow } = growth();
5470
+ const tall = frame2.contentDocument?.documentElement?.scrollHeight;
5471
+ const rest = typeof tall === "number" ? tall - page.innerHeight - grow : Number.POSITIVE_INFINITY;
5472
+ step({ type: "scroll", y: page.scrollY, time: performance.now(), room, rest });
5473
+ }
5474
+ if (!sampling)
5475
+ sampling = window.requestAnimationFrame(resample);
5476
+ };
5477
+ const actions = {
5478
+ back: () => frame2.contentWindow?.history.back(),
5479
+ forward: () => frame2.contentWindow?.history.forward(),
5480
+ reload: () => {
5481
+ if (busy) {
5482
+ frame2.contentWindow?.stop();
5483
+ stopLoading();
5484
+ return;
4949
5485
  }
4950
- const failed = gl.getError();
4951
- if (failed !== gl.NO_ERROR)
4952
- return refuse(`the picture could not be uploaded: WebGL2 error 0x${failed.toString(16)}`, next);
4953
- gl.generateMipmap(gl.TEXTURE_2D);
4954
- shot = next;
4955
- if (look)
4956
- draw(look);
5486
+ onReload();
5487
+ keep(frame2.contentWindow, "frame");
5488
+ frame2.contentWindow?.location.reload();
4957
5489
  },
4958
- draw,
4959
- release() {
4960
- if (gone)
5490
+ expand: () => step({ type: "tap" })
5491
+ };
5492
+ const sizeFrame = () => {
5493
+ if (!view)
5494
+ return;
5495
+ const before = applied;
5496
+ view.sizeFrame();
5497
+ const page = view.page;
5498
+ if (!same(page, applied))
5499
+ step({ type: "resize", time: performance.now() });
5500
+ applied = page;
5501
+ const moved2 = before && page && before.y !== page.y && before.x === page.x && before.width === page.width;
5502
+ if (moved2) {
5503
+ const fresh2 = landed;
5504
+ landed = false;
5505
+ try {
5506
+ if (!fresh2)
5507
+ frame2.contentWindow?.scrollBy({ top: page.y - before.y, behavior: "instant" });
5508
+ } catch {}
5509
+ }
5510
+ placeBand();
5511
+ };
5512
+ const stopShrink = () => {
5513
+ clearTimeout(shrinking);
5514
+ shrinking = 0;
5515
+ shrinkTo = null;
5516
+ };
5517
+ const placeFrame = (instant) => {
5518
+ const page = view?.page ?? null;
5519
+ const shrinks = !instant && page && applied && page.height < applied.height && page.y === applied.y;
5520
+ if (shrinks && shrinking && same(page, shrinkTo))
5521
+ return;
5522
+ stopShrink();
5523
+ if (!shrinks) {
5524
+ sizeFrame();
5525
+ return;
5526
+ }
5527
+ shrinkTo = page;
5528
+ shrinking = window.setTimeout(() => {
5529
+ shrinking = 0;
5530
+ shrinkTo = null;
5531
+ if (same(view?.page ?? null, page))
5532
+ sizeFrame();
5533
+ }, MORPH.expand);
5534
+ };
5535
+ const back = () => {
5536
+ frame2.style.background = reaches(frame2) ? (look ??= lookNow()).background : "";
5537
+ };
5538
+ const draw = () => {
5539
+ const bars = view?.bars ?? null;
5540
+ if (!view || !bars) {
5541
+ stopShrink();
5542
+ layer.replaceChildren();
5543
+ glass.style.background = "";
5544
+ back();
5545
+ painted = null;
5546
+ built = "";
5547
+ if (view)
5548
+ sizeFrame();
5549
+ placeBand();
5550
+ return;
5551
+ }
5552
+ look ??= lookNow();
5553
+ glass.style.background = screenFill(look, bars, view.page, view.size.height);
5554
+ back();
5555
+ placeBand();
5556
+ const { platform, layout, screen, orientation, edge } = bars;
5557
+ const base = JSON.stringify([platform, layout, screen, orientation, edge, view.follow]);
5558
+ const fresh2 = base !== built || !painted;
5559
+ const instant = fresh2 || still2();
5560
+ if (fresh2) {
5561
+ const other = barsOf(screen, orientation, layout, !bars.minimized, edge);
5562
+ const full = bars.minimized ? other : bars;
5563
+ const mini = bars.minimized ? bars : other;
5564
+ const shown2 = { ...actions, expand: view.follow ? actions.expand : undefined };
5565
+ if (!full || !mini)
4961
5566
  return;
4962
- gone = true;
4963
- free();
5567
+ painted = BUILDERS[bars.platform](full, mini, look, shown2);
5568
+ layer.replaceChildren(painted.root);
5569
+ built = base;
5570
+ if (busy)
5571
+ painted.loading?.(true, true);
5572
+ }
5573
+ if (instant)
5574
+ layer.setAttribute("data-instant", "");
5575
+ painted?.apply(bars.minimized, look);
5576
+ if (instant) {
5577
+ layer.offsetWidth;
5578
+ layer.removeAttribute("data-instant");
4964
5579
  }
5580
+ placeFrame(instant);
4965
5581
  };
4966
- }
4967
-
4968
- // src/engine/objectfit.ts
4969
- var MIDDLE = { share: 0.5, px: 0 };
4970
- function words(text) {
4971
- const parts = [];
4972
- let depth = 0;
4973
- let word = "";
4974
- for (const char of text.trim()) {
4975
- if (char === "(")
4976
- depth++;
4977
- if (char === ")")
4978
- depth--;
4979
- if (/\s/.test(char) && depth === 0) {
4980
- if (word)
4981
- parts.push(word);
4982
- word = "";
4983
- } else
4984
- word += char;
4985
- }
4986
- if (word)
4987
- parts.push(word);
4988
- return parts;
4989
- }
4990
- function offsetOf(word) {
4991
- const terms = Array.from(word.matchAll(/([+-])?\s*(\d*\.?\d+(?:e[+-]?\d+)?)(%|px)?/gi));
4992
- if (terms.length === 0 || !/^(calc\(.*\)|[+-]?[\d.]+(e[+-]?\d+)?(%|px)?)$/i.test(word))
4993
- return null;
4994
- const offset = { share: 0, px: 0 };
4995
- for (const [, sign, digits = "0", unit] of terms) {
4996
- const value = Number(digits) * (sign === "-" ? -1 : 1);
4997
- if (unit === "%")
4998
- offset.share += value / 100;
4999
- else
5000
- offset.px += value;
5001
- }
5002
- return offset;
5003
- }
5004
- function fromFar(offset) {
5005
- return { share: 1 - offset.share, px: 0 - offset.px };
5006
- }
5007
- function objectPosition(position) {
5008
- let x = null;
5009
- let y = null;
5010
- const plain = [];
5011
- const list = words(position.toLowerCase());
5012
- const counted = list.length > 2;
5013
- for (let at = 0;at < list.length; at++) {
5014
- const word = list[at] ?? "";
5015
- const next = offsetOf(list[at + 1] ?? "");
5016
- if (word === "left" || word === "right" || word === "top" || word === "bottom") {
5017
- const far = word === "right" || word === "bottom";
5018
- const edge = counted && next || { share: 0, px: 0 };
5019
- if (counted && next)
5020
- at++;
5021
- const offset = far ? fromFar(edge) : edge;
5022
- if (word === "left" || word === "right")
5023
- x = offset;
5024
- else
5025
- y = offset;
5026
- } else if (word === "center")
5027
- plain.push(MIDDLE);
5028
- else {
5029
- const offset = offsetOf(word);
5030
- if (offset)
5031
- plain.push(offset);
5582
+ const pageOf = () => {
5583
+ try {
5584
+ return frame2.contentDocument;
5585
+ } catch {
5586
+ return null;
5032
5587
  }
5033
- }
5034
- for (const offset of plain) {
5035
- if (!x)
5036
- x = offset;
5037
- else if (!y)
5038
- y = offset;
5039
- }
5040
- return [x ?? MIDDLE, y ?? MIDDLE];
5041
- }
5042
- function objectPlace(fit2, position, natural, box2) {
5043
- if (!(natural.width > 0 && natural.height > 0 && box2.width > 0 && box2.height > 0))
5044
- return null;
5045
- const across = box2.width / natural.width;
5046
- const down = box2.height / natural.height;
5047
- const whole = Math.min(across, down);
5048
- let size = { width: box2.width, height: box2.height };
5049
- const scaled = (scale) => ({ width: natural.width * scale, height: natural.height * scale });
5050
- if (fit2 === "contain")
5051
- size = scaled(whole);
5052
- else if (fit2 === "cover")
5053
- size = scaled(Math.max(across, down));
5054
- else if (fit2 === "none")
5055
- size = scaled(1);
5056
- else if (fit2 === "scale-down")
5057
- size = scaled(Math.min(1, whole));
5058
- const [x, y] = objectPosition(position);
5059
- const left = box2.x + (box2.width - size.width) * x.share + x.px;
5060
- const top = box2.y + (box2.height - size.height) * y.share + y.px;
5061
- const to = {
5062
- x: Math.max(left, box2.x),
5063
- y: Math.max(top, box2.y),
5064
- width: Math.min(left + size.width, box2.x + box2.width) - Math.max(left, box2.x),
5065
- height: Math.min(top + size.height, box2.y + box2.height) - Math.max(top, box2.y)
5066
5588
  };
5067
- if (!(to.width > 0 && to.height > 0))
5068
- return null;
5069
- const wide = natural.width / size.width;
5070
- const tall = natural.height / size.height;
5071
- return {
5072
- from: { x: (to.x - left) * wide, y: (to.y - top) * tall, width: to.width * wide, height: to.height * tall },
5073
- to
5589
+ const showLoading = (on, seed) => {
5590
+ busy = on;
5591
+ if (seed) {
5592
+ look = seed;
5593
+ draw();
5594
+ }
5595
+ painted?.loading?.(on, still2());
5596
+ if (!on)
5597
+ browser.refresh();
5598
+ };
5599
+ const stopLoading = () => {
5600
+ if (loadWait)
5601
+ window.cancelAnimationFrame(loadWait);
5602
+ loadWait = 0;
5603
+ if (!busy)
5604
+ return;
5605
+ blank.hidden = true;
5606
+ showLoading(false, null);
5607
+ };
5608
+ const startLoading = (seed) => {
5609
+ blank.style.background = (seed ?? look ?? lookNow()).background;
5610
+ blank.hidden = false;
5611
+ showLoading(true, seed);
5612
+ if (loadWait)
5613
+ window.cancelAnimationFrame(loadWait);
5614
+ const end = performance.now() + LOAD_WAIT;
5615
+ const gone = pageOf();
5616
+ const check = () => {
5617
+ loadWait = 0;
5618
+ const next = gone === null || pageOf() !== gone;
5619
+ if (next && ready() || performance.now() >= end)
5620
+ stopLoading();
5621
+ else
5622
+ loadWait = window.requestAnimationFrame(check);
5623
+ };
5624
+ loadWait = window.requestAnimationFrame(check);
5625
+ };
5626
+ const read = () => {
5627
+ try {
5628
+ const page = frame2.contentWindow;
5629
+ const doc = frame2.contentDocument;
5630
+ const arrived = doc !== watched2;
5631
+ if (page && doc && doc !== watched2) {
5632
+ query?.removeEventListener("change", read);
5633
+ query = page.matchMedia("(prefers-color-scheme: dark)");
5634
+ query.addEventListener("change", read);
5635
+ page.addEventListener("scroll", onScroll, { passive: true });
5636
+ watched2 = doc;
5637
+ }
5638
+ const now = page?.location.href ?? "";
5639
+ if (now !== href) {
5640
+ href = now;
5641
+ landed = arrived;
5642
+ step({ type: "navigate" });
5643
+ }
5644
+ } catch {
5645
+ query = null;
5646
+ }
5647
+ if (!busy || !look)
5648
+ look = lookNow();
5649
+ draw();
5650
+ };
5651
+ const browser = {
5652
+ show(next) {
5653
+ view = next;
5654
+ if (next.bars && !layer.isConnected)
5655
+ glass.append(layer);
5656
+ if (!next.bars)
5657
+ layer.remove();
5658
+ place(layer, 0, 0, next.size.width, next.size.height);
5659
+ layer.style.transform = next.zoom === 1 ? "" : `scale(${next.zoom})`;
5660
+ draw();
5661
+ },
5662
+ refresh() {
5663
+ if (!view)
5664
+ return;
5665
+ const again = view.bars ? read : () => {
5666
+ if (!busy || !look)
5667
+ look = lookNow();
5668
+ back();
5669
+ };
5670
+ again();
5671
+ band.refresh();
5672
+ clearTimeout(later);
5673
+ later = window.setTimeout(again, RESTYLE);
5674
+ },
5675
+ minimized: () => motion.minimized,
5676
+ page: () => applied,
5677
+ startLoading,
5678
+ stopLoading,
5679
+ look: () => look,
5680
+ remove() {
5681
+ clearTimeout(later);
5682
+ if (sampling)
5683
+ window.cancelAnimationFrame(sampling);
5684
+ sampling = 0;
5685
+ if (loadWait)
5686
+ window.cancelAnimationFrame(loadWait);
5687
+ loadWait = 0;
5688
+ stopShrink();
5689
+ query?.removeEventListener("change", read);
5690
+ try {
5691
+ frame2.contentWindow?.removeEventListener("scroll", onScroll);
5692
+ } catch {}
5693
+ query = null;
5694
+ watched2 = null;
5695
+ layer.remove();
5696
+ blank.remove();
5697
+ band.remove();
5698
+ }
5074
5699
  };
5700
+ return browser;
5075
5701
  }
5076
5702
 
5077
- // src/engine/pagefonts.ts
5078
- var kept2 = null;
5079
- var READ = /^(woff2?|truetype|opentype|collection)(-variations)?$/;
5080
- var URL_OF = /^url\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^)]*))\s*\)/i;
5081
- var CHUNK = 32768;
5082
- function cut(text, mark) {
5083
- const parts = [];
5084
- let depth = 0;
5085
- let quote = "";
5086
- let from = 0;
5087
- for (let at = 0;at < text.length; at++) {
5088
- const char = text[at];
5089
- if (char === "\\")
5090
- at++;
5091
- else if (quote)
5092
- quote = char === quote ? "" : quote;
5093
- else if (char === '"' || char === "'")
5094
- quote = char;
5095
- else if (char === "(")
5096
- depth++;
5097
- else if (char === ")")
5098
- depth--;
5099
- else if (char === mark && depth === 0) {
5100
- parts.push(text.slice(from, at));
5101
- from = at + 1;
5102
- }
5103
- }
5104
- parts.push(text.slice(from));
5105
- return parts;
5106
- }
5107
- function faceKey(family, weight, style, range) {
5108
- const name = family.trim().replace(/^(["'])(.*)\1$/, "$2").toLowerCase();
5109
- const plain = (value) => value.trim().toLowerCase().replace(/\s+/g, " ") || "normal";
5110
- const heavy = plain(weight).replace(/\bnormal\b/g, "400").replace(/\bbold\b/g, "700");
5111
- const chars = (range.trim() || "U+0-10FFFF").toLowerCase().split(",").map((part) => part.trim().replace(/^u\+/, "").split("-").map((end) => end.replace(/^0+(?=.)/, "")).join("-")).join(",");
5112
- return [name, heavy, plain(style), chars].join("|");
5113
- }
5114
- function base64(bytes) {
5115
- let text = "";
5116
- for (let at = 0;at < bytes.length; at += CHUNK)
5117
- text += String.fromCharCode(...bytes.subarray(at, at + CHUNK));
5118
- return btoa(text);
5703
+ // src/engine/fit.ts
5704
+ var STRIP_TOP = 8;
5705
+ var STRIP = 24 + STRIP_TOP;
5706
+ var MARGIN = 24;
5707
+ var BARE = { top: 0, right: 0, bottom: 0, left: 0 };
5708
+ function hasStrip(knobs2) {
5709
+ const sized = typeof knobs2.width === "number" || typeof knobs2.height === "number";
5710
+ return sized || knobs2.zoom !== "fit";
5119
5711
  }
5120
- function fetchFont(url, fonts) {
5121
- fonts.set(url, null);
5122
- quietFetch(url).then(async (response) => {
5123
- if (!response.ok)
5124
- return;
5125
- const type = /^[\w.+-]+\/[\w.+-]+/.exec(response.headers.get("content-type") ?? "")?.[0];
5126
- const bytes = new Uint8Array(await response.arrayBuffer());
5127
- fonts.set(url, `data:${type ?? "application/octet-stream"};base64,${base64(bytes)}`);
5128
- }).catch(() => {});
5712
+ function margin(size) {
5713
+ return Math.min(MARGIN, size / 4);
5129
5714
  }
5130
- function faceWith(css, base, used, fonts) {
5131
- const open = css.indexOf("{");
5132
- const close = css.lastIndexOf("}");
5133
- if (open < 0 || close < open)
5134
- return css;
5135
- const parts = cut(css.slice(open + 1, close), ";");
5136
- const named = (name) => {
5137
- const part = parts.find((part2) => part2.split(":")[0]?.trim().toLowerCase() === name);
5138
- return part ? part.slice(part.indexOf(":") + 1).trim() : "";
5715
+ function fit(knobs2, size, options = {}) {
5716
+ const { frameZoom = 1, aside = 0, side = "right", mock = BARE } = options;
5717
+ const room = {
5718
+ width: size.width,
5719
+ height: Math.max(0, size.height - (hasStrip(knobs2) ? STRIP : 0))
5139
5720
  };
5140
- if (!used.has(faceKey(named("font-family"), named("font-weight"), named("font-style"), named("unicode-range")))) {
5141
- return css;
5142
- }
5143
- const sources = cut(named("src"), ",").map((source2) => source2.trim());
5144
- const at = sources.findIndex((source2) => {
5145
- const format = /format\(\s*["']?([\w-]+)["']?\s*\)/i.exec(source2)?.[1];
5146
- return URL_OF.test(source2) && (!format || READ.test(format.toLowerCase()));
5147
- });
5148
- const source = sources[at];
5149
- const found = source ? URL_OF.exec(source) : null;
5150
- if (!source || !found)
5151
- return css;
5152
- const address = (found[1] ?? found[2] ?? found[3] ?? "").trim().replace(/\\(.)/g, "$1");
5153
- if (/^data:/i.test(address))
5154
- return css;
5155
- let url;
5156
- try {
5157
- url = new URL(address, base).href;
5158
- } catch {
5159
- return css;
5160
- }
5161
- const data = fonts.get(url);
5162
- if (data === undefined)
5163
- fetchFont(url, fonts);
5164
- if (!data)
5165
- return css;
5166
- const locals = sources.slice(0, at).filter((source2) => /^local\(/i.test(source2));
5167
- const src = [...locals, `url("${data}")${source.slice(found[0].length)}`].join(", ");
5168
- const next = parts.map((part) => part.split(":")[0]?.trim().toLowerCase() === "src" ? ` src: ${src}` : part);
5169
- return `${css.slice(0, open + 1)}${next.join(";")}${css.slice(close)}`;
5170
- }
5171
- function holdsRules(rule) {
5172
- return "cssRules" in rule;
5173
- }
5174
- function keptFor(doc) {
5175
- if (kept2?.doc === doc)
5176
- return kept2.fonts;
5177
- forgetFonts();
5178
- const set = doc.fonts;
5179
- const again = () => fetchFonts(doc);
5180
- set?.addEventListener("loadingdone", again);
5181
- kept2 = { doc, fonts: new Map, stop: () => set?.removeEventListener("loadingdone", again) };
5182
- return kept2.fonts;
5183
- }
5184
- function embedFonts(doc) {
5185
- const fonts = keptFor(doc);
5186
- const used = new Set;
5187
- const set = doc.fonts;
5188
- if (set) {
5189
- for (const face of set) {
5190
- if (face.status === "loaded")
5191
- used.add(faceKey(face.family, face.weight, face.style, face.unicodeRange));
5192
- }
5193
- }
5194
- const embed = (rule) => {
5195
- let css = rule.cssText;
5196
- if (used.size === 0 || !css.includes("@font-face"))
5197
- return css;
5198
- if (!holdsRules(rule)) {
5199
- const base = rule.parentStyleSheet?.href ?? doc.baseURI;
5200
- return css.startsWith("@font-face") ? faceWith(css, base, used, fonts) : css;
5201
- }
5202
- for (const inner of rule.cssRules) {
5203
- const next = embed(inner);
5204
- if (next !== inner.cssText)
5205
- css = css.split(inner.cssText).join(next);
5206
- }
5207
- return css;
5721
+ const sized = typeof knobs2.width === "number";
5722
+ const width = typeof knobs2.width === "number" ? knobs2.width : room.width;
5723
+ const x = sized ? margin(room.width) : 0;
5724
+ const y = typeof knobs2.height === "number" ? margin(room.height) : 0;
5725
+ const sides = { width: mock.left + mock.right, height: mock.top + mock.bottom };
5726
+ const across = width > 0 && room.width > 0 ? (room.width - 2 * x) / (width + sides.width) : 1;
5727
+ const tall = typeof knobs2.height === "number" && knobs2.height > 0 && room.height > 0;
5728
+ const upright = (room.height - 2 * y) / (Number(knobs2.height) + sides.height);
5729
+ const whole = Math.min(sized && tall ? ZOOM_MAX : 1, across, tall ? upright : 1);
5730
+ const height = typeof knobs2.height === "number" ? knobs2.height : room.height / whole;
5731
+ const outer = { width: width + sides.width, height: height + sides.height };
5732
+ const covered = sized && aside > 0 && aside <= room.width / 2 && (room.width + outer.width * whole) / 2 + x > room.width - aside;
5733
+ const fitted = covered ? Math.min(whole, (room.width - aside - 2 * x) / outer.width) : whole;
5734
+ const scale = knobs2.zoom === "fit" ? fitted : knobs2.zoom;
5735
+ const beside = knobs2.zoom === "fit" && covered ? aside : 0;
5736
+ const before = side === "left" ? beside : 0;
5737
+ return {
5738
+ width,
5739
+ height,
5740
+ zoom: frameZoom,
5741
+ scale,
5742
+ fit: fitted,
5743
+ transform: scale / frameZoom,
5744
+ box: { width: outer.width * scale + 2 * x + beside, height: outer.height * scale + 2 * y },
5745
+ left: x + mock.left * scale + before,
5746
+ top: y + mock.top * scale
5208
5747
  };
5209
- return embed;
5210
- }
5211
- function fetchFonts(doc) {
5212
- const embed = embedFonts(doc);
5213
- for (const sheet of doc.styleSheets) {
5214
- try {
5215
- for (const rule of sheet.cssRules)
5216
- embed(rule);
5217
- } catch {}
5218
- }
5219
5748
  }
5220
- function warmFonts(doc) {
5221
- if (kept2?.doc !== doc)
5222
- fetchFonts(doc);
5749
+ function origin(place2, room) {
5750
+ return {
5751
+ x: Math.max(0, (room.width - place2.box.width) / 2) + place2.left,
5752
+ y: Math.max(0, (room.height - place2.box.height) / 2) + place2.top
5753
+ };
5223
5754
  }
5224
- function forgetFonts() {
5225
- kept2?.stop();
5226
- kept2 = null;
5755
+ function label(place2, knobs2, page = place2) {
5756
+ const name = formOf(knobs2.device, knobs2.posture)?.label;
5757
+ let text = name ? `${name} · ${page.width}` : String(page.width);
5758
+ if (typeof knobs2.height === "number")
5759
+ text += ` × ${page.height}`;
5760
+ if (typeof knobs2.dpr === "number")
5761
+ text += ` · ${knobs2.dpr}x`;
5762
+ return text;
5227
5763
  }
5228
5764
 
5229
- // src/engine/pageshot.ts
5230
- var RES = 0.25;
5231
- var MOST = 1500;
5232
- var BUDGET = 6;
5233
- var INK = 0.4;
5234
- function canvasOf(width, height) {
5235
- const canvas = document.createElement("canvas");
5236
- canvas.width = Math.max(1, Math.round(width));
5237
- canvas.height = Math.max(1, Math.round(height));
5238
- const pen = canvas.getContext("2d");
5239
- return pen ? { canvas, pen } : null;
5765
+ // src/engine/mat.ts
5766
+ function colorRules() {
5767
+ return MAT_COLOR_NAMES.map((name) => {
5768
+ const paint = MAT_COLORS[name];
5769
+ return `[data-mat="${name}"] { --mat: ${matGradient(paint.srgb)}; --mat-p3: ${matGradient(paint.p3)}; --mat-line: ${paint.line}; }`;
5770
+ }).join(`
5771
+ `);
5240
5772
  }
5241
- function clear(color) {
5242
- return color === "" || color === "transparent" || /^rgba\(.*,\s*0\)$/.test(color);
5773
+ var MAT_CSS = `
5774
+ ${colorRules()}
5775
+ .mat {
5776
+ position: absolute;
5777
+ top: 0;
5778
+ left: 0;
5779
+ width: 100%;
5780
+ height: 100%;
5781
+ pointer-events: none;
5782
+ fill: var(--mat-line);
5243
5783
  }
5244
- var MEDIA = "img, video, canvas";
5245
- function mediaOf(node) {
5246
- if ("naturalWidth" in node) {
5247
- const loaded = node.complete && node.naturalWidth > 0 && node.naturalHeight > 0;
5248
- return loaded ? { source: node, width: node.naturalWidth, height: node.naturalHeight } : null;
5784
+ .mat .cell { opacity: 0.07; }
5785
+ .mat .major { opacity: 0.14; }
5786
+ .mat .span { opacity: 0.26; }
5787
+ .mat .angle { fill: none; stroke: var(--mat-line); }
5788
+ .mat .mark, .mat .tick { opacity: 0.55; }
5789
+ .mat text {
5790
+ font: 9px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
5791
+ font-variant-numeric: tabular-nums;
5792
+ opacity: 0.5;
5793
+ }`;
5794
+ var CELL = 10;
5795
+ var MAJOR = 50;
5796
+ var SPAN = 100;
5797
+ var TICK = { cell: 3, major: 5, span: 9 };
5798
+ var ANGLES = [15, 30, 45, 60, 75];
5799
+ var GUIDE = { line: 0.15, half: 0.22 };
5800
+ var ARC = 40;
5801
+ var LABEL = { radius: 240, off: 3, top: 40, room: 24 };
5802
+ var FOOT = 30;
5803
+ var NUMBER = 24;
5804
+ function ticks(length) {
5805
+ const out = [];
5806
+ for (let at = CELL;at < length; at += CELL) {
5807
+ const size = at % SPAN === 0 ? TICK.span : at % MAJOR === 0 ? TICK.major : TICK.cell;
5808
+ out.push({ at, size });
5249
5809
  }
5250
- if ("videoWidth" in node) {
5251
- const playing = node.readyState >= 2 && node.videoWidth > 0 && node.videoHeight > 0;
5252
- return playing ? { source: node, width: node.videoWidth, height: node.videoHeight } : null;
5810
+ return out;
5811
+ }
5812
+ function numbers(length, avoid) {
5813
+ const out = [];
5814
+ for (let at = SPAN;at + NUMBER <= length; at += SPAN) {
5815
+ if (avoid && at + NUMBER > avoid.from && at < avoid.to)
5816
+ continue;
5817
+ out.push(at);
5253
5818
  }
5254
- return node.width > 0 && node.height > 0 ? { source: node, width: node.width, height: node.height } : null;
5819
+ return out;
5255
5820
  }
5256
- function radiusOf(value, wide, tall) {
5257
- const [across = "0", down = across] = value.trim().split(/\s+/);
5258
- const px = (text, of) => (text.endsWith("%") ? Number.parseFloat(text) / 100 * of : Number.parseFloat(text)) || 0;
5259
- return { x: px(across, wide), y: px(down, tall) };
5821
+ function lines(across, length, hair) {
5822
+ return across.map((at) => `M${at} 0h${hair}v${length}h${-hair}ZM0 ${at}h${length}v${hair}h${-length}Z`).join("");
5260
5823
  }
5261
- function drawMedia(pen, media, rect, style) {
5262
- const px = (value) => Number.parseFloat(value) || 0;
5263
- const left = px(style.borderLeftWidth) + px(style.paddingLeft);
5264
- const right = px(style.borderRightWidth) + px(style.paddingRight);
5265
- const top = px(style.borderTopWidth) + px(style.paddingTop);
5266
- const bottom = px(style.borderBottomWidth) + px(style.paddingBottom);
5267
- const box2 = { x: rect.left + left, y: rect.top + top, width: rect.width - left - right, height: rect.height - top - bottom };
5268
- const placed = objectPlace(style.objectFit, style.objectPosition, media, box2);
5269
- if (!placed)
5270
- return;
5271
- const corner = (value, across, down) => {
5272
- const radius = radiusOf(value, rect.width, rect.height);
5273
- return { x: Math.max(0, radius.x - across), y: Math.max(0, radius.y - down) };
5274
- };
5275
- const corners = [
5276
- corner(style.borderTopLeftRadius, left, top),
5277
- corner(style.borderTopRightRadius, right, top),
5278
- corner(style.borderBottomRightRadius, right, bottom),
5279
- corner(style.borderBottomLeftRadius, left, bottom)
5280
- ];
5281
- const { from, to } = placed;
5282
- pen.save();
5283
- if (corners.some((radius) => radius.x > 0 && radius.y > 0)) {
5284
- pen.beginPath();
5285
- pen.roundRect(box2.x, box2.y, box2.width, box2.height, corners);
5286
- pen.clip();
5287
- }
5288
- if (style.imageRendering === "pixelated" || style.imageRendering === "crisp-edges")
5289
- pen.imageSmoothingEnabled = false;
5290
- pen.drawImage(media.source, from.x, from.y, from.width, from.height, to.x, to.y, to.width, to.height);
5291
- pen.restore();
5824
+ function vertex(height) {
5825
+ const y = Math.floor((height - FOOT) / SPAN) * SPAN;
5826
+ return y > 0 ? { x: 0, y } : null;
5292
5827
  }
5293
- function picturesKey(doc) {
5294
- const parts = [];
5295
- for (const node of doc.querySelectorAll(MEDIA)) {
5296
- if (!("naturalWidth" in node))
5297
- return null;
5298
- const address = node.currentSrc;
5299
- parts.push(`${address.length}:${address.slice(-64)}@${node.naturalWidth}x${node.naturalHeight}`);
5300
- }
5301
- return parts.join(" ");
5828
+ function direction(angle) {
5829
+ const turn2 = angle * Math.PI / 180;
5830
+ return { x: Math.cos(turn2), y: -Math.sin(turn2) };
5302
5831
  }
5303
- function shotKey(at) {
5304
- const { size, frame: frame2, view, scroll } = at;
5305
- return JSON.stringify([
5306
- [size.width, size.height, at.color, at.layout],
5307
- [frame2.x, frame2.y, frame2.width],
5308
- [view.width, view.height, scroll.x, scroll.y],
5309
- [at.dpr, at.text, at.pictures]
5310
- ]);
5832
+ function exit(from, angle, size) {
5833
+ const step = direction(angle);
5834
+ const toTop = step.y < 0 ? from.y / -step.y : Infinity;
5835
+ const toRight = step.x > 0 ? (size.width - from.x) / step.x : Infinity;
5836
+ if (toTop <= toRight)
5837
+ return { x: from.x + toTop * step.x, y: 0 };
5838
+ return { x: size.width, y: from.y + toRight * step.y };
5311
5839
  }
5312
- function shootPage(frame2, glass, size, color, layout = "") {
5313
- const doc = frame2.contentDocument;
5314
- const view = frame2.contentWindow;
5315
- const screen = glass.getBoundingClientRect();
5316
- const box2 = frame2.getBoundingClientRect();
5317
- if (!doc?.body || !view || screen.width <= 0 || view.innerWidth <= 0)
5318
- return null;
5319
- const shown2 = picturesKey(doc);
5320
- const css = size.width / screen.width;
5321
- const near = (value) => Math.round(value * css * 1000) / 1000;
5322
- const key = shotKey({
5323
- size,
5324
- color,
5325
- layout,
5326
- frame: { x: near(box2.left - screen.left), y: near(box2.top - screen.top), width: near(box2.width) },
5327
- view: { width: view.innerWidth, height: view.innerHeight },
5328
- scroll: { x: view.scrollX, y: view.scrollY },
5329
- dpr: view.devicePixelRatio,
5330
- text: view.getComputedStyle(doc.documentElement).fontSize,
5331
- pictures: shown2 ?? ""
5840
+ function along(from, angle, radius, off = 0) {
5841
+ const step = direction(angle);
5842
+ return { x: from.x + radius * step.x + off * step.y, y: from.y + radius * step.y - off * step.x };
5843
+ }
5844
+ function drawMat(size, hair, avoid, bleed = { left: 0, right: 0 }) {
5845
+ const svg = svgNode("svg", { class: "mat", "aria-hidden": "true" });
5846
+ const sheet = svgNode("g", { transform: `translate(${bleed.left} 0)` });
5847
+ const half = SPAN / 2;
5848
+ const minor = [];
5849
+ for (let at = CELL;at < SPAN; at += CELL)
5850
+ if (at !== half)
5851
+ minor.push(at);
5852
+ const arm = 6;
5853
+ const pattern = svgNode("pattern", {
5854
+ id: "mat-grid",
5855
+ x: -half,
5856
+ y: -half,
5857
+ width: SPAN,
5858
+ height: SPAN,
5859
+ patternUnits: "userSpaceOnUse"
5332
5860
  });
5333
- const kept3 = shown2 === null || !unchanged(doc) ? null : shots.get(doc)?.get(key);
5334
- if (kept3)
5335
- return kept3;
5336
- const drawn = canvasOf(size.width * RES, size.height * RES);
5337
- if (!drawn)
5338
- return null;
5339
- const { canvas, pen } = drawn;
5340
- pen.fillStyle = color;
5341
- pen.fillRect(0, 0, canvas.width, canvas.height);
5342
- const scale = box2.width * css / view.innerWidth;
5343
- pen.setTransform(RES * scale, 0, 0, RES * scale, RES * (box2.left - screen.left) * css, RES * (box2.top - screen.top) * css);
5344
- pen.beginPath();
5345
- pen.rect(0, 0, view.innerWidth, view.innerHeight);
5346
- pen.clip();
5347
- const pictures = new Map;
5348
- for (const node of doc.querySelectorAll(MEDIA)) {
5349
- const media = mediaOf(node);
5350
- if (media)
5351
- pictures.set(node, media);
5352
- }
5353
- const range = doc.createRange();
5354
- const tall = view.innerHeight;
5355
- let seen = 0;
5356
- const pinned = [];
5357
- const deadline = performance.now() + BUDGET;
5358
- const draw = (node, alpha, lifted) => {
5359
- if (seen++ > MOST || seen % 50 === 0 && performance.now() > deadline)
5360
- return;
5361
- if (node.hasAttribute("data-devknobs"))
5362
- return;
5363
- const style = view.getComputedStyle(node);
5364
- if (style.display === "none")
5365
- return;
5366
- if (!lifted && (style.position === "fixed" || style.position === "sticky")) {
5367
- pinned.push([node, alpha]);
5368
- return;
5369
- }
5370
- const rect = node.getBoundingClientRect();
5371
- const area = rect.width > 0 && rect.height > 0;
5372
- if (area && (rect.bottom < 0 || rect.top > tall))
5373
- return;
5374
- const shown3 = alpha * (Number.parseFloat(style.opacity) || 0);
5375
- if (shown3 <= 0)
5376
- return;
5377
- if (area && style.visibility !== "hidden") {
5378
- pen.globalAlpha = shown3;
5379
- if (!clear(style.backgroundColor)) {
5380
- pen.fillStyle = style.backgroundColor;
5381
- pen.beginPath();
5382
- pen.roundRect(rect.left, rect.top, rect.width, rect.height, Number.parseFloat(style.borderTopLeftRadius) || 0);
5383
- pen.fill();
5384
- }
5385
- const picture = pictures.get(node);
5386
- if (picture)
5387
- drawMedia(pen, picture, rect, style);
5388
- pen.fillStyle = style.color;
5389
- pen.globalAlpha = shown3 * INK;
5390
- for (const text of node.childNodes) {
5391
- if (text.nodeType !== Node.TEXT_NODE || !text.textContent?.trim())
5392
- continue;
5393
- range.selectNodeContents(text);
5394
- for (const line of range.getClientRects())
5395
- pen.fillRect(line.left, line.top, line.width, line.height);
5396
- }
5861
+ pattern.append(svgNode("path", { class: "cell", d: lines(minor, SPAN, hair) }), svgNode("path", { class: "major", d: lines([0], SPAN, hair) }), svgNode("path", { class: "span", d: lines([half], SPAN, hair) }), svgNode("path", {
5862
+ class: "mark",
5863
+ d: `M${half - arm} ${half}h${2 * arm + hair}v${hair}h${-2 * arm - hair}Z` + `M${half} ${half - arm}h${hair}v${2 * arm + hair}h${-hair}Z`
5864
+ }));
5865
+ const defs = svgNode("defs", {});
5866
+ defs.append(pattern);
5867
+ const top = ticks(size.width).map((tick) => `M${tick.at} 0h${hair}v${tick.size}h${-hair}Z`).join("");
5868
+ const left = ticks(size.height).map((tick) => `M0 ${tick.at}h${tick.size}v${hair}h${-tick.size}Z`).join("");
5869
+ sheet.append(svgNode("rect", {
5870
+ x: -bleed.left,
5871
+ width: bleed.left + size.width + bleed.right,
5872
+ height: "100%",
5873
+ fill: "url(#mat-grid)"
5874
+ }), svgNode("path", { class: "tick", d: top + left }));
5875
+ svg.append(defs, sheet);
5876
+ const origin2 = vertex(size.height);
5877
+ if (origin2) {
5878
+ const base = along(origin2, 0, ARC);
5879
+ const rim = { x: origin2.x, y: origin2.y - ARC };
5880
+ const arc2 = svgNode("path", {
5881
+ class: "angle",
5882
+ d: `M${base.x} ${base.y}A${ARC} ${ARC} 0 0 0 ${rim.x} ${rim.y}`,
5883
+ "stroke-width": hair
5884
+ });
5885
+ arc2.style.opacity = String(GUIDE.line);
5886
+ sheet.append(arc2);
5887
+ for (const angle of ANGLES) {
5888
+ const start = along(origin2, angle, ARC);
5889
+ const end = exit(origin2, angle, size);
5890
+ const line = svgNode("path", {
5891
+ class: "angle",
5892
+ d: `M${start.x} ${start.y}L${end.x} ${end.y}`,
5893
+ "stroke-width": hair
5894
+ });
5895
+ line.style.opacity = String(angle === 45 ? GUIDE.half : GUIDE.line);
5896
+ sheet.append(line);
5897
+ const reach = Math.hypot(end.x - origin2.x, end.y - origin2.y);
5898
+ const at = along(origin2, angle, LABEL.radius, LABEL.off);
5899
+ if (reach < LABEL.radius + LABEL.room || at.y < LABEL.top)
5900
+ continue;
5901
+ const text = svgNode("text", {
5902
+ x: at.x,
5903
+ y: at.y,
5904
+ transform: `rotate(${-angle} ${at.x} ${at.y})`
5905
+ });
5906
+ text.textContent = `${angle}°`;
5907
+ sheet.append(text);
5397
5908
  }
5398
- for (const child of node.children)
5399
- draw(child, shown3, lifted);
5909
+ }
5910
+ for (const at of numbers(size.width, avoid)) {
5911
+ const text = svgNode("text", { x: at + 3, y: TICK.span + 1 });
5912
+ text.textContent = String(at);
5913
+ sheet.append(text);
5914
+ }
5915
+ for (const at of numbers(size.height)) {
5916
+ const text = svgNode("text", { x: TICK.span + 2, y: at, "dominant-baseline": "middle" });
5917
+ text.textContent = String(at);
5918
+ sheet.append(text);
5919
+ }
5920
+ return svg;
5921
+ }
5922
+
5923
+ // src/engine/foldflip.ts
5924
+ function flipRect(rect, room) {
5925
+ return { ...rect, x: room.width - rect.x - rect.width, y: room.height - rect.y - rect.height };
5926
+ }
5927
+ function flipRadius(radius) {
5928
+ if (typeof radius === "number")
5929
+ return radius;
5930
+ const [topLeft, topRight, bottomRight, bottomLeft] = radius;
5931
+ return [bottomRight, bottomLeft, topLeft, topRight];
5932
+ }
5933
+ function flipMock(mock) {
5934
+ const room = { width: mock.width, height: mock.height };
5935
+ const { top, right, bottom, left } = mock.inset;
5936
+ const flipped = {
5937
+ ...mock,
5938
+ inset: { top: bottom, right: left, bottom: top, left: right },
5939
+ body: flipRect(mock.body, room),
5940
+ screenRadius: flipRadius(mock.screenRadius),
5941
+ bodyRadius: flipRadius(mock.bodyRadius),
5942
+ parts: mock.parts.map((part) => flipRect(part, room))
5400
5943
  };
5401
- for (const child of doc.body.children)
5402
- draw(child, 1, false);
5403
- for (const [node, alpha] of pinned)
5404
- draw(node, alpha, true);
5405
- if (shown2 !== null)
5406
- keepShot(doc, key, canvas);
5407
- return canvas;
5944
+ if (!mock.image)
5945
+ return flipped;
5946
+ if (mock.image.turn === null) {
5947
+ const { over: over2, ...still2 } = mock.image;
5948
+ return { ...flipped, image: over2 ? still2 : { ...still2, over: true } };
5949
+ }
5950
+ const { clockwise, ...image } = mock.image;
5951
+ return { ...flipped, image: clockwise ? { ...image, turn: mock.height } : { ...image, turn: mock.width, clockwise: true } };
5408
5952
  }
5409
- var shots = new WeakMap;
5410
- var watched = null;
5411
- function forgetShots() {
5412
- watched?.observer.disconnect();
5413
- watched = null;
5414
- shots = new WeakMap;
5415
- forgetFonts();
5953
+ function coverAcross(shape) {
5954
+ const [device = "", held, posture] = shape.split("|");
5955
+ return held === "landscape" && posture === "closed" && formOf(device, "closed")?.clockwise === true;
5416
5956
  }
5417
- function unchanged(doc) {
5418
- if (watched?.doc !== doc)
5419
- return false;
5420
- if (watched.observer.takeRecords().length > 0)
5421
- watched.changed = true;
5422
- return !watched.changed;
5957
+ function openUpright(shape) {
5958
+ const [device = "", held, posture] = shape.split("|");
5959
+ return held === "portrait" && posture === "open" && formOf(device, "closed")?.clockwise === true;
5423
5960
  }
5424
- function keepShot(doc, key, canvas) {
5425
- if (!unchanged(doc)) {
5426
- watched?.observer.disconnect();
5427
- shots = new WeakMap;
5428
- const Observer = doc.defaultView?.MutationObserver;
5429
- if (!Observer)
5430
- return;
5431
- const observer = new Observer(() => {
5432
- if (watched?.observer === observer)
5433
- watched.changed = true;
5434
- observer.disconnect();
5435
- });
5436
- observer.observe(doc, { subtree: true, childList: true, attributes: true, characterData: true });
5437
- watched = { doc, changed: false, observer };
5961
+ function caseOver(from, to, over2) {
5962
+ if (coverAcross(to))
5963
+ return true;
5964
+ if (!openUpright(to))
5965
+ return false;
5966
+ return coverAcross(from) || from === to && over2;
5967
+ }
5968
+ function flipFace(face, room) {
5969
+ return { ...face, body: face.body && flipMock(face.body), screen: flipRect(face.screen, room) };
5970
+ }
5971
+ var turnedOver = new WeakMap;
5972
+ function flipCanvas(canvas) {
5973
+ const known = turnedOver.get(canvas);
5974
+ if (known)
5975
+ return known;
5976
+ const turned = document.createElement("canvas");
5977
+ turned.width = canvas.width;
5978
+ turned.height = canvas.height;
5979
+ const pen = turned.getContext("2d");
5980
+ if (pen) {
5981
+ pen.translate(canvas.width, canvas.height);
5982
+ pen.rotate(Math.PI);
5983
+ pen.drawImage(canvas, 0, 0);
5984
+ }
5985
+ turnedOver.set(canvas, turned);
5986
+ return turned;
5987
+ }
5988
+ function flipPicture(picture, size) {
5989
+ const { bars } = picture;
5990
+ if (bars) {
5991
+ bars.style.transformOrigin = "0 0";
5992
+ bars.style.transform = `translate(${size.width}px, ${size.height}px) rotate(180deg)`;
5438
5993
  }
5439
- const kept3 = shots.get(doc) ?? new Map;
5440
- kept3.set(key, canvas);
5441
- shots.set(doc, kept3);
5994
+ return {
5995
+ shot: picture.shot && flipCanvas(picture.shot),
5996
+ painted: picture.painted?.then((drawn) => drawn && { ...drawn, shot: flipCanvas(drawn.shot) }) ?? null,
5997
+ bars
5998
+ };
5442
5999
  }
5443
- var KEPT = 8;
5444
- function blurPictures(shot, width, across, widths = blurWidths().slice(1)) {
5445
- const length = across ? shot.height : shot.width;
5446
- return widths.map((wide) => {
5447
- const coarse2 = Math.max(1, wide * shot.width / width);
5448
- const margin2 = blurMargin(coarse2);
5449
- const padded = canvasOf(shot.width + (across ? 0 : 2 * margin2), shot.height + (across ? 2 * margin2 : 0));
5450
- if (!padded)
5451
- return { canvas: blurPicture(shot, coarse2), long: length };
5452
- padded.pen.fillStyle = "#000";
5453
- padded.pen.fillRect(0, 0, padded.canvas.width, padded.canvas.height);
5454
- padded.pen.drawImage(shot, across ? 0 : margin2, across ? margin2 : 0);
5455
- const canvas = blurPicture(padded.canvas, coarse2);
5456
- if (canvas !== padded.canvas)
5457
- spend(padded.canvas);
5458
- return { canvas, long: length + 2 * margin2 };
5459
- });
6000
+
6001
+ // src/engine/foldgl.ts
6002
+ function screenLook(open, wedge, free = 1, shaded = null, pane = shaded ?? "inner") {
6003
+ const blurred = blurOn();
6004
+ const [, wipe, area, far] = shaded ? shadeOf(shaded, open, free) : [1, 0, 0, 0];
6005
+ return {
6006
+ peak: blurred ? turnBlur(open, pane) : 0,
6007
+ edge: blurred ? [tune.edgeHinge * wedge, tune.edgeFree * wedge] : [0, 0],
6008
+ free,
6009
+ dark: shadesOn() ? freeDepth(open) : 0,
6010
+ lit: [wipe, area, far]
6011
+ };
5460
6012
  }
5461
- function blurMargin(coarse2) {
5462
- return Math.ceil(2 * coarse2);
6013
+ var WEIGHTS = [0.375, 0.25, 0.0625];
6014
+ function wedgeOf(window2, pane, picture, span) {
6015
+ const { top, bottom } = darkAt(window2, pane, picture);
6016
+ return picture.height > 0 ? Math.max(top, bottom) * span / picture.height : 0;
5463
6017
  }
5464
- function marginPlace(shot, padded) {
5465
- const exact = (value) => Math.round(value * 1e4) / 1e4;
5466
- return { start: exact((shot - padded) / 2 / shot * 100), size: exact(padded / shot * 100) };
6018
+ function freeOf(window2, pane, picture) {
6019
+ if (picture.width <= 0)
6020
+ return 1;
6021
+ const [a, b, c, d] = window2;
6022
+ const seen = pane === "inner" ? picture.x + picture.width - (a[0] + d[0]) / 2 : (b[0] + c[0]) / 2 - picture.x;
6023
+ return Math.min(1, Math.max(0, seen / picture.width));
5467
6024
  }
5468
- function spend(canvas) {
5469
- canvas.width = 0;
5470
- canvas.height = 0;
6025
+ function reachOf(shots2, pane) {
6026
+ let most = 0;
6027
+ for (const shot of shots2.frames) {
6028
+ if (shotPane(shots2, shot) !== pane)
6029
+ continue;
6030
+ const quad = shotQuad(shot, pane);
6031
+ const picture = shotPicture(shots2, pane, quad);
6032
+ most = Math.max(most, wedgeOf(shotWindow(quad, pane, picture), pane, picture, 1));
6033
+ }
6034
+ return most;
5471
6035
  }
5472
- function blurPicture(shot, coarse2) {
5473
- const halvings = Math.ceil(Math.log2(coarse2) - 0.000000001);
5474
- const { width, height } = shot;
5475
- const sized = (level) => {
5476
- const scale = Math.min(1, 2 ** level / coarse2);
5477
- return canvasOf(width * scale, height * scale);
5478
- };
5479
- let at = shot;
5480
- const step = (level, smooth) => {
5481
- const next = sized(level);
5482
- if (!next)
5483
- return false;
5484
- if (smooth)
5485
- next.pen.imageSmoothingQuality = "high";
5486
- next.pen.drawImage(at, 0, 0, next.canvas.width, next.canvas.height);
5487
- if (at !== shot)
5488
- spend(at);
5489
- at = next.canvas;
5490
- return true;
5491
- };
5492
- for (let level = halvings - 1;level >= 0; level--)
5493
- if (!step(level, false))
5494
- return at;
5495
- for (let level = 1;level <= Math.min(Math.log2(KEPT), halvings); level++)
5496
- if (!step(level, true))
5497
- return at;
5498
- return at;
6036
+ function canvasRect(place2) {
6037
+ const { across, part, stage, margin: margin2 } = place2;
6038
+ return across ? { x: part.x, y: -margin2, width: part.width, height: stage.height + 2 * margin2 } : { x: -margin2, y: part.y, width: stage.width + 2 * margin2, height: part.height };
5499
6039
  }
5500
- function blankUrl(width, height) {
5501
- return svgUrl(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"/>`);
6040
+ function hingeLine(pane, across, part) {
6041
+ const { x, y, width, height } = part;
6042
+ if (across)
6043
+ return pane === "inner" ? [-1 / width, 0, (x + width) / width] : [1 / width, 0, -x / width];
6044
+ return pane === "inner" ? [0, 1 / height, -y / height] : [0, -1 / height, (y + height) / height];
5502
6045
  }
5503
- function blankPictures(live, copy) {
5504
- const shown2 = live.querySelectorAll("img");
5505
- copy.querySelectorAll("img").forEach((image, index) => {
5506
- const from = shown2[index];
5507
- if (!from || !from.complete || !(from.naturalWidth > 0 && from.naturalHeight > 0))
5508
- return;
5509
- for (const name of ["srcset", "sizes", "loading"])
5510
- image.removeAttribute(name);
5511
- const holder2 = image.parentElement;
5512
- if (holder2?.localName === "picture")
5513
- for (const source of holder2.querySelectorAll("source"))
5514
- source.remove();
5515
- image.setAttribute("src", blankUrl(from.naturalWidth, from.naturalHeight));
6046
+ function contextOf(canvas) {
6047
+ if (typeof WebGL2RenderingContext === "undefined")
6048
+ return null;
6049
+ const gl = canvas.getContext("webgl2", {
6050
+ alpha: false,
6051
+ antialias: false,
6052
+ depth: false,
6053
+ stencil: false,
6054
+ premultipliedAlpha: false,
6055
+ powerPreference: "low-power"
5516
6056
  });
6057
+ return gl instanceof WebGL2RenderingContext ? gl : null;
6058
+ }
6059
+ var VERTEX = `#version 300 es
6060
+ in vec2 corner;
6061
+ uniform vec4 view;
6062
+ out vec2 pos;
6063
+ void main() {
6064
+ pos = view.xy + corner * view.zw;
6065
+ gl_Position = vec4(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0, 0.0, 1.0);
6066
+ }`;
6067
+ var FRAGMENT = `#version 300 es
6068
+ precision highp float;
6069
+ uniform sampler2D page;
6070
+ uniform vec2 stage;
6071
+ uniform vec2 along;
6072
+ uniform vec3 line;
6073
+ uniform float peak;
6074
+ uniform vec2 edge;
6075
+ uniform float free;
6076
+ uniform float dark;
6077
+ uniform vec2 shape;
6078
+ uniform vec2 rimmed;
6079
+ uniform vec3 band;
6080
+ uniform vec3 lit;
6081
+ uniform vec2 run;
6082
+ uniform vec3 wiped;
6083
+ uniform vec2 soften;
6084
+ uniform float grain;
6085
+ uniform float px;
6086
+ in vec2 pos;
6087
+ out vec4 color;
6088
+ const float WEIGHTS[3] = float[3](${WEIGHTS.join(", ")});
6089
+ float cover(float at, float span, float soft) {
6090
+ return smoothstep(-soft, soft, at) * (1.0 - smoothstep(span - soft, span + soft, at));
6091
+ }
6092
+ float shadow(float t) {
6093
+ if (dark <= 0.0) return 1.0;
6094
+ float across = t / max(free, 0.001);
6095
+ float deep = band.z * smoothstep(band.x, 1.0, across) + (1.0 - band.z) * smoothstep(1.0 - band.y, 1.0, across);
6096
+ return 1.0 - dark * deep;
6097
+ }
6098
+ float shade(float t) {
6099
+ if (lit.x + lit.y + lit.z <= 0.0) return 1.0;
6100
+ float uv = run.x + run.y * t;
6101
+ float off = abs(uv - wiped.x);
6102
+ float wipe = 1.0 - clamp(smoothstep(wiped.y, wiped.z, off) * lit.x, 0.0, 1.0);
6103
+ float soft = 1.0 - smoothstep(0.9, 1.3, clamp((off - soften.x) / (soften.y - soften.x) * lit.y, 0.0, 4.0 / 3.0));
6104
+ float away = mix(1.0, smoothstep(0.05, 0.5, uv), lit.z);
6105
+ return pow(clamp(wipe * soft * soft * away, 0.0, 1.0), 1.0 / 2.2);
6106
+ }
6107
+ vec4 shaded(vec3 rgb, float t) {
6108
+ float speck = 0.0;
6109
+ if (grain > 0.0 && dark + lit.x + lit.y + lit.z > 0.0) {
6110
+ speck = (fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5) * grain / 255.0;
6111
+ }
6112
+ return vec4(rgb * shadow(t) * shade(min(t, free)) + speck, 1.0);
5517
6113
  }
5518
- function copyPage(frame2) {
5519
- const doc = frame2.contentDocument;
5520
- if (!doc?.documentElement)
5521
- return null;
5522
- const rules = [];
5523
- const written2 = embedFonts(doc);
5524
- for (const sheet of [...doc.styleSheets, ...doc.adoptedStyleSheets ?? []]) {
5525
- try {
5526
- for (const rule of sheet.cssRules)
5527
- rules.push(written2(rule));
5528
- } catch {}
6114
+ float seen(vec2 at, float soft) {
6115
+ float reach = soft * length(line.xy);
6116
+ return cover(dot(along, at), dot(along, stage), soft) * (1.0 - smoothstep(free - reach, free + reach, dot(line.xy, at) + line.z));
6117
+ }
6118
+ void main() {
6119
+ vec2 texels = vec2(textureSize(page, 0)) / stage;
6120
+ vec2 right = dFdx(pos) * texels;
6121
+ vec2 down = dFdy(pos) * texels;
6122
+ float sharp = 0.5 * log2(max(1.0, max(dot(right, right), dot(down, down))));
6123
+ float t = clamp(dot(line.xy, pos) + line.z, 0.0, 1.0);
6124
+ float span = dot(along, stage);
6125
+ float at = dot(along, pos);
6126
+ float across = free > 0.0 ? min(1.0, t / free) : 1.0;
6127
+ float wide = peak * (shape.x + (1.0 - shape.x) * pow(across, shape.y));
6128
+ float rim = mix(edge.x, edge.y, t);
6129
+ if (rim > 0.0) wide = max(wide, rim * (1.0 - smoothstep(0.0, rimmed.x * rim, min(at, span - at))));
6130
+ float gap = rimmed.y * wide;
6131
+ float soft = max(0.5 * px, 0.75 * gap);
6132
+ float lod = max(sharp, log2(max(1.0, gap * max(texels.x, texels.y))));
6133
+ vec3 sum = vec3(0.0);
6134
+ if (peak + edge.x + edge.y <= 0.0) {
6135
+ sum = textureLod(page, pos / stage, lod).rgb * seen(pos, soft);
6136
+ } else {
6137
+ for (int y = -2; y <= 2; y++) {
6138
+ for (int x = -2; x <= 2; x++) {
6139
+ vec2 tap = pos + vec2(float(x), float(y)) * gap;
6140
+ float weight = WEIGHTS[abs(x)] * WEIGHTS[abs(y)];
6141
+ sum += textureLod(page, tap / stage, lod).rgb * seen(tap, soft) * weight;
6142
+ }
6143
+ }
5529
6144
  }
5530
- const inert = doc.implementation.createHTMLDocument("");
5531
- const root = inert.importNode(doc.documentElement, true);
5532
- blankPictures(doc.documentElement, root);
5533
- for (const node of root.querySelectorAll("script, link, style, noscript, [data-devknobs]"))
5534
- node.remove();
5535
- const style = inert.createElement("style");
5536
- style.textContent = rules.join(`
5537
- `);
5538
- (root.querySelector("head") ?? root).append(style);
5539
- return root;
6145
+ color = shaded(sum, t);
6146
+ }`;
6147
+ function compile(gl, kind, source) {
6148
+ const shader = gl.createShader(kind);
6149
+ if (!shader)
6150
+ return null;
6151
+ gl.shaderSource(shader, source);
6152
+ gl.compileShader(shader);
6153
+ return shader;
5540
6154
  }
5541
- var LONE_HALF = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
5542
- function svgUrl(svg) {
5543
- const whole = typeof svg.toWellFormed === "function" ? svg.toWellFormed() : svg.replace(LONE_HALF, "�");
5544
- return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(whole)}`;
6155
+ function firstLine(log, otherwise) {
6156
+ return log?.trim().split(`
6157
+ `)[0]?.trim() || otherwise;
5545
6158
  }
5546
- function rootSize(doc, view) {
5547
- const size = view.getComputedStyle(doc.documentElement).fontSize;
5548
- return size ? `font-size:${size} !important` : "";
6159
+ function uploadWhy(error) {
6160
+ const name = error instanceof Error ? error.name : String(error);
6161
+ const tainted = "the browser holds the picture as another origin's, as one with a picture, video or canvas from another origin drawn in, or a drawing of the page this browser does not trust";
6162
+ return `the picture could not be uploaded: ${name}${name === "SecurityError" ? `, ${tainted}` : ""}`;
5549
6163
  }
5550
- async function paintPage(frame2, glass, size, color, copy) {
5551
- const doc = frame2.contentDocument;
5552
- const view = frame2.contentWindow;
5553
- const screen = glass.getBoundingClientRect();
5554
- const box2 = frame2.getBoundingClientRect();
5555
- if (!doc || !view || screen.width <= 0 || view.innerWidth <= 0)
6164
+ function screenGl(place2, refused) {
6165
+ const canvas = document.createElement("canvas");
6166
+ const gl = contextOf(canvas);
6167
+ if (!gl) {
6168
+ refused(typeof WebGL2RenderingContext === "undefined" ? "this browser has no WebGL2" : "the canvas gave no WebGL2 context", null);
5556
6169
  return null;
5557
- const { innerWidth: width, innerHeight: height, scrollX, scrollY } = view;
5558
- const css = size.width / screen.width;
5559
- const scale = box2.width * css / width;
5560
- const at = { x: (box2.left - screen.left) * css, y: (box2.top - screen.top) * css };
5561
- let over = null;
5562
- for (const node of doc.querySelectorAll(MEDIA)) {
5563
- const media = node.closest("[data-devknobs]") ? null : mediaOf(node);
5564
- const rect = node.getBoundingClientRect();
5565
- if (!media || rect.bottom <= 0 || rect.top >= height || rect.width <= 0)
5566
- continue;
5567
- if (!over) {
5568
- over = canvasOf(size.width, size.height);
5569
- over?.pen.setTransform(scale, 0, 0, scale, at.x, at.y);
5570
- }
5571
- try {
5572
- if (over)
5573
- drawMedia(over.pen, media, rect, view.getComputedStyle(node));
5574
- } catch {}
5575
6170
  }
5576
- const root = copy.cloneNode(true);
5577
- const scrolled = `position:relative;left:${-scrollX}px;top:${-scrollY}px`;
5578
- const sized = rootSize(doc, view);
5579
- root.setAttribute("style", `${root.getAttribute("style") ?? ""};${sized};${scrolled}`);
5580
- const markup = new XMLSerializer().serializeToString(root);
5581
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" style="${sized}">` + `<foreignObject width="100%" height="100%">${markup}</foreignObject></svg>`;
5582
- const image = new Image;
5583
- try {
5584
- image.src = svgUrl(svg);
5585
- await image.decode();
5586
- } catch {
5587
- if (over)
5588
- spend(over.canvas);
6171
+ const rect = canvasRect(place2);
6172
+ const most = Math.max(1, gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) || 4096);
6173
+ const density2 = Math.min(place2.density, most / rect.width, most / rect.height);
6174
+ canvas.width = Math.max(1, Math.round(rect.width * density2));
6175
+ canvas.height = Math.max(1, Math.round(rect.height * density2));
6176
+ canvas.style.position = "absolute";
6177
+ canvas.style.display = "block";
6178
+ canvas.style.left = `${rect.x}px`;
6179
+ canvas.style.top = `${rect.y}px`;
6180
+ canvas.style.width = `${rect.width}px`;
6181
+ canvas.style.height = `${rect.height}px`;
6182
+ const vertex2 = compile(gl, gl.VERTEX_SHADER, VERTEX);
6183
+ const fragment = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);
6184
+ const program = gl.createProgram();
6185
+ const corners = gl.createBuffer();
6186
+ const texture = gl.createTexture();
6187
+ const free = () => {
6188
+ gl.deleteTexture(texture);
6189
+ gl.deleteBuffer(corners);
6190
+ gl.deleteProgram(program);
6191
+ gl.deleteShader(vertex2);
6192
+ gl.deleteShader(fragment);
6193
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
6194
+ canvas.remove();
6195
+ };
6196
+ if (!vertex2 || !fragment || !program || !corners || !texture) {
6197
+ const why = gl.isContextLost() ? "the WebGL2 context was lost as it was made" : "WebGL2 made no shader, program, buffer or texture";
6198
+ free();
6199
+ refused(why, null);
5589
6200
  return null;
5590
6201
  }
5591
- const drawn = canvasOf(size.width, size.height);
5592
- if (!drawn)
6202
+ gl.attachShader(program, vertex2);
6203
+ gl.attachShader(program, fragment);
6204
+ gl.linkProgram(program);
6205
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
6206
+ const log = [vertex2, fragment].map((shader) => gl.getShaderInfoLog(shader)).find((said) => said?.trim()) ?? gl.getProgramInfoLog(program);
6207
+ const lost = gl.isContextLost();
6208
+ free();
6209
+ refused(lost ? "the WebGL2 context was lost as it was made" : `the shader did not compile or link: ${firstLine(log, "no reason given")}`, null);
5593
6210
  return null;
5594
- const { canvas, pen } = drawn;
5595
- pen.fillStyle = color;
5596
- pen.fillRect(0, 0, canvas.width, canvas.height);
5597
- pen.setTransform(scale, 0, 0, scale, at.x, at.y);
5598
- pen.drawImage(image, 0, 0, width, height);
5599
- if (over) {
5600
- pen.setTransform(1, 0, 0, 1, 0, 0);
5601
- pen.drawImage(over.canvas, 0, 0);
5602
- spend(over.canvas);
5603
6211
  }
5604
- return canvas;
6212
+ gl.useProgram(program);
6213
+ gl.bindBuffer(gl.ARRAY_BUFFER, corners);
6214
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
6215
+ const corner = gl.getAttribLocation(program, "corner");
6216
+ gl.enableVertexAttribArray(corner);
6217
+ gl.vertexAttribPointer(corner, 2, gl.FLOAT, false, 0, 0);
6218
+ const at = (name) => gl.getUniformLocation(program, name);
6219
+ const { stage } = place2;
6220
+ gl.uniform4f(at("view"), rect.x, rect.y, rect.width, rect.height);
6221
+ gl.uniform2f(at("stage"), stage.width, stage.height);
6222
+ gl.uniform2f(at("along"), place2.across ? 0 : 1, place2.across ? 1 : 0);
6223
+ gl.uniform3f(at("line"), ...hingeLine(place2.pane, place2.across, place2.part));
6224
+ gl.uniform1f(at("px"), canvas.width > 0 ? rect.width / canvas.width : 1);
6225
+ gl.uniform1i(at("page"), 0);
6226
+ const wipe = WIPE[place2.pane];
6227
+ gl.uniform2f(at("run"), uvOf(place2.pane, 0), uvOf(place2.pane, 1) - uvOf(place2.pane, 0));
6228
+ gl.uniform3f(at("wiped"), wipe.at, wipe.shade[0], wipe.shade[1]);
6229
+ gl.uniform2f(at("soften"), wipe.blur[0], wipe.blur[1]);
6230
+ const uniforms = { peak: at("peak"), edge: at("edge"), free: at("free"), dark: at("dark"), shape: at("shape"), rimmed: at("rimmed"), band: at("band"), lit: at("lit"), grain: at("grain") };
6231
+ gl.bindTexture(gl.TEXTURE_2D, texture);
6232
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
6233
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
6234
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
6235
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
6236
+ gl.viewport(0, 0, canvas.width, canvas.height);
6237
+ const widest = gl.getParameter(gl.MAX_TEXTURE_SIZE) || 2048;
6238
+ let shot = null;
6239
+ let look = null;
6240
+ let gone = false;
6241
+ const draw = (next) => {
6242
+ look = next;
6243
+ if (gone || !shot)
6244
+ return;
6245
+ gl.uniform1f(uniforms.peak, next.peak);
6246
+ gl.uniform2f(uniforms.edge, ...next.edge);
6247
+ gl.uniform1f(uniforms.free, next.free);
6248
+ gl.uniform1f(uniforms.dark, next.dark);
6249
+ gl.uniform2f(uniforms.shape, tune.blurHinge, tune.blurRise);
6250
+ gl.uniform2f(uniforms.rimmed, tune.edgeReach, tune.blurSpread);
6251
+ gl.uniform3f(uniforms.band, tune.darkFrom, tune.darkBand, tune.darkBroad);
6252
+ gl.uniform3f(uniforms.lit, ...next.lit);
6253
+ gl.uniform1f(uniforms.grain, tune.grain);
6254
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
6255
+ };
6256
+ canvas.addEventListener("webglcontextlost", () => {
6257
+ if (gone)
6258
+ return;
6259
+ gone = true;
6260
+ canvas.remove();
6261
+ refused("the WebGL2 context was lost", shot);
6262
+ });
6263
+ const refuse = (why, next) => {
6264
+ if (!gone)
6265
+ free();
6266
+ gone = true;
6267
+ refused(why, next);
6268
+ };
6269
+ return {
6270
+ canvas,
6271
+ paint(next) {
6272
+ if (gone)
6273
+ return refuse("the WebGL2 context is gone", next);
6274
+ if (Math.max(next.width, next.height) > widest) {
6275
+ return refuse(`the picture, ${next.width} by ${next.height} px, is larger than MAX_TEXTURE_SIZE, ${widest}`, next);
6276
+ }
6277
+ gl.getError();
6278
+ try {
6279
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, next);
6280
+ } catch (error) {
6281
+ return refuse(uploadWhy(error), next);
6282
+ }
6283
+ const failed = gl.getError();
6284
+ if (failed !== gl.NO_ERROR)
6285
+ return refuse(`the picture could not be uploaded: WebGL2 error 0x${failed.toString(16)}`, next);
6286
+ gl.generateMipmap(gl.TEXTURE_2D);
6287
+ shot = next;
6288
+ if (look)
6289
+ draw(look);
6290
+ },
6291
+ draw,
6292
+ release() {
6293
+ if (gone)
6294
+ return;
6295
+ gone = true;
6296
+ free();
6297
+ }
6298
+ };
5605
6299
  }
5606
6300
 
5607
6301
  // src/engine/barshot.ts
@@ -5689,6 +6383,7 @@ var EDGE = "#48484a";
5689
6383
  var RIM2 = "#2a2a2c";
5690
6384
  var BAND = 2.5;
5691
6385
  var UNDER = 2;
6386
+ var CONTINUOUS = { extent: 1.363, shape: 1.52 };
5692
6387
  var MOCK_CSS = `
5693
6388
  /* Clips the frame to the screen's corners in a mock, in the body's color so
5694
6389
  no blue shows at the seam. */
@@ -5697,6 +6392,14 @@ var MOCK_CSS = `
5697
6392
  overflow: hidden;
5698
6393
  background: ${BODY};
5699
6394
  }
6395
+ /* A phone with an island: its continuous corners where the browser draws
6396
+ them, over the round radius set on it, which the mat still reads. */
6397
+ @supports (corner-shape: superellipse(2)) {
6398
+ .glass.continuous {
6399
+ border-radius: var(--continuous) !important;
6400
+ corner-shape: superellipse(${CONTINUOUS.shape});
6401
+ }
6402
+ }
5700
6403
  /* Over the frame, and never in the way of a pointer. */
5701
6404
  .mock {
5702
6405
  position: absolute;
@@ -5720,28 +6423,42 @@ function corners(radius, by = 0) {
5720
6423
  function roundRect(rect, radius) {
5721
6424
  const { x, y, width, height } = rect;
5722
6425
  const [a, b, c, d] = corners(radius).map((r) => Math.max(0, Math.min(r, width / 2, height / 2)));
5723
- const arc = (r = 0) => `A${r} ${r} 0 0 1`;
6426
+ const arc2 = (r = 0) => `A${r} ${r} 0 0 1`;
5724
6427
  return [
5725
- `M${x + a} ${y}H${x + width - b}${arc(b)} ${x + width} ${y + b}`,
5726
- `V${y + height - c}${arc(c)} ${x + width - c} ${y + height}`,
5727
- `H${x + d}${arc(d)} ${x} ${y + height - d}`,
5728
- `V${y + a}${arc(a)} ${x + a} ${y}Z`
6428
+ `M${x + a} ${y}H${x + width - b}${arc2(b)} ${x + width} ${y + b}`,
6429
+ `V${y + height - c}${arc2(c)} ${x + width - c} ${y + height}`,
6430
+ `H${x + d}${arc2(d)} ${x} ${y + height - d}`,
6431
+ `V${y + a}${arc2(a)} ${x + a} ${y}Z`
5729
6432
  ].join("");
5730
6433
  }
6434
+ function continuousRect(rect, radius) {
6435
+ const { x, y, width, height } = rect;
6436
+ const power = 2 / 2 ** CONTINUOUS.shape;
6437
+ const most = Math.min(width, height) / 2;
6438
+ const lengths = corners(radius).map((r) => Math.max(0, Math.min(r * CONTINUOUS.extent, most)));
6439
+ const ends = [
6440
+ [x, y, 1, 1],
6441
+ [x + width, y, -1, 1],
6442
+ [x + width, y + height, -1, -1],
6443
+ [x, y + height, 1, -1]
6444
+ ];
6445
+ const points = ends.flatMap(([cx, cy, sx, sy], at) => {
6446
+ const length = lengths[at] ?? 0;
6447
+ return Array.from({ length: 17 }, (_, step) => {
6448
+ const t = (at % 2 === 0 ? step : 16 - step) / 16 * (Math.PI / 2);
6449
+ const px = cx + sx * length * (1 - Math.cos(t) ** power);
6450
+ const py = cy + sy * length * (1 - Math.sin(t) ** power);
6451
+ return `${px.toFixed(2)} ${py.toFixed(2)}`;
6452
+ });
6453
+ });
6454
+ return `M${points.join("L")}Z`;
6455
+ }
5731
6456
  function drawMock(mock, screenSize, href) {
5732
6457
  const svg = svgNode("svg", {
5733
6458
  class: "mock",
5734
6459
  viewBox: `0 0 ${mock.width} ${mock.height}`,
5735
6460
  "aria-hidden": "true"
5736
6461
  });
5737
- if (mock.image && href) {
5738
- const { x: x2, y: y2, width: width2, height: height2, turn: turn2 } = mock.image;
5739
- const image = svgNode("image", { href, x: x2, y: y2, width: width2, height: height2 });
5740
- if (turn2 !== null)
5741
- image.setAttribute("transform", `matrix(0 -1 1 0 0 ${turn2})`);
5742
- svg.append(image);
5743
- return svg;
5744
- }
5745
6462
  const part = (shape) => svgNode("rect", {
5746
6463
  class: shape.kind,
5747
6464
  x: shape.x,
@@ -5750,11 +6467,22 @@ function drawMock(mock, screenSize, href) {
5750
6467
  height: shape.height,
5751
6468
  rx: shape.radius
5752
6469
  });
6470
+ if (mock.image && href) {
6471
+ const { x: x2, y: y2, width: width2, height: height2, turn: turn2, clockwise, over: over2 } = mock.image;
6472
+ const image = svgNode("image", { href, x: x2, y: y2, width: width2, height: height2 });
6473
+ if (turn2 !== null) {
6474
+ image.setAttribute("transform", clockwise ? `matrix(0 1 -1 0 ${turn2} 0)` : `matrix(0 -1 1 0 0 ${turn2})`);
6475
+ } else if (over2)
6476
+ image.setAttribute("transform", `matrix(-1 0 0 -1 ${mock.width} ${mock.height})`);
6477
+ svg.append(image, ...mock.parts.map(part));
6478
+ return svg;
6479
+ }
5753
6480
  const opening = { x: mock.inset.left, y: mock.inset.top, ...screenSize };
5754
6481
  const { x, y, width, height } = mock.body;
6482
+ const screen = mock.continuous ? continuousRect : roundRect;
5755
6483
  const front = { x: x + BAND, y: y + BAND, width: width - 2 * BAND, height: height - 2 * BAND };
5756
6484
  const inside = roundRect(front, corners(mock.bodyRadius, -BAND));
5757
- svg.append(...mock.parts.filter((shape) => shape.kind === "button").map(part), svgNode("path", { class: "band", d: roundRect(mock.body, mock.bodyRadius) + inside }), svgNode("path", { class: "body", d: inside + roundRect(opening, mock.screenRadius) }), ...mock.parts.filter((shape) => shape.kind !== "button").map(part));
6485
+ svg.append(...mock.parts.filter((shape) => shape.kind === "button").map(part), svgNode("path", { class: "band", d: roundRect(mock.body, mock.bodyRadius) + inside }), svgNode("path", { class: "body", d: inside + screen(opening, mock.screenRadius) }), ...mock.parts.filter((shape) => shape.kind !== "button").map(part));
5758
6486
  return svg;
5759
6487
  }
5760
6488
 
@@ -5764,7 +6492,7 @@ function div(className) {
5764
6492
  node.className = className;
5765
6493
  return node;
5766
6494
  }
5767
- function round(radii) {
6495
+ function round2(radii) {
5768
6496
  return radii.map((radius) => `${radius}px`).join(" ");
5769
6497
  }
5770
6498
  function fill(node) {
@@ -5842,7 +6570,7 @@ function roughOf(frame2, glass, value, size, color) {
5842
6570
  const { device, posture, orientation, browser, edgeToEdge } = value;
5843
6571
  return shootPage(frame2, glass, size, color, [device, posture, orientation, browser, edgeToEdge].join(" "));
5844
6572
  }
5845
- function pictureOf(frame2, glass, value, size, color, copy) {
6573
+ function pictureOf2(frame2, glass, value, size, color, copy) {
5846
6574
  const shown2 = glass.querySelector(":scope > .browser");
5847
6575
  const bars = shown2 ? document.importNode(shown2, true) : null;
5848
6576
  if (bars)
@@ -6050,8 +6778,8 @@ function pose(turning, layout, open, shown2, still2) {
6050
6778
  const fade = (value) => value >= 1 ? "" : String(Math.round(Math.max(0, value) * 1000) / 1000);
6051
6779
  model.style.opacity = fade(shown2);
6052
6780
  turning.still.canvas.style.opacity = fade(still2);
6053
- const over = [turning.inner.stage.lastElementChild, turning.outer.stage.lastElementChild];
6054
- const by = [turning.inner.gl, turning.inner.pictures, turning.outer.gl, turning.outer.pictures, 0, ...over];
6781
+ const over2 = [turning.inner.stage.lastElementChild, turning.outer.stage.lastElementChild];
6782
+ const by = [turning.inner.gl, turning.inner.pictures, turning.outer.gl, turning.outer.pictures, 0, ...over2];
6055
6783
  const { lit } = turning;
6056
6784
  if (lit && lit.shot === shot && lit.by.every((one, index) => one === by[index]))
6057
6785
  return;
@@ -6191,9 +6919,9 @@ function turnTo(turn2, to, done) {
6191
6919
  if (spin)
6192
6920
  window.cancelAnimationFrame(spin.frame);
6193
6921
  const time = MORPH_TIME.turn * Math.abs(to.angle - from.angle) / 90;
6194
- const over = cover?.share ?? 0;
6922
+ const over2 = cover?.share ?? 0;
6195
6923
  const across = to.angle === 0 ? 0 : 1;
6196
- coverTo(turn2.cover, over);
6924
+ coverTo(turn2.cover, over2);
6197
6925
  const going = { spin: turn2, pose: from, frame: 0, done };
6198
6926
  spin = going;
6199
6927
  let begin = null;
@@ -6202,7 +6930,7 @@ function turnTo(turn2, to, done) {
6202
6930
  const elapsed = now - begin;
6203
6931
  going.pose = poseAt(from, to, elapsed, time);
6204
6932
  stand(turn2, going.pose);
6205
- coverTo(turn2.cover, coverAt(over, across, elapsed, time));
6933
+ coverTo(turn2.cover, coverAt(over2, across, elapsed, time));
6206
6934
  if (elapsed < time) {
6207
6935
  going.frame = window.requestAnimationFrame(step);
6208
6936
  return;
@@ -6292,7 +7020,7 @@ function leafOf(side, picture, turning2, across) {
6292
7020
  const { rect } = turning2;
6293
7021
  const screen = placeAt(div(""), whole);
6294
7022
  screen.style.background = "#000";
6295
- screen.style.borderRadius = round(radii);
7023
+ screen.style.borderRadius = round2(radii);
6296
7024
  if (href)
6297
7025
  screen.style.boxShadow = `0 0 0 ${UNDER}px #000`;
6298
7026
  node.append(screen);
@@ -6308,7 +7036,7 @@ function leafOf(side, picture, turning2, across) {
6308
7036
  dark.style.inset = "-100%";
6309
7037
  dark.style.background = "#000";
6310
7038
  const stage = placeAt(div(""), { ...whole, x: whole.x - rect.x, y: whole.y - rect.y });
6311
- stage.style.borderRadius = round(radii);
7039
+ stage.style.borderRadius = round2(radii);
6312
7040
  stage.style.overflow = "hidden";
6313
7041
  if (picture.bars)
6314
7042
  stage.append(picture.bars);
@@ -6322,9 +7050,9 @@ function leafOf(side, picture, turning2, across) {
6322
7050
  veil.style.width = node.style.width;
6323
7051
  veil.style.height = node.style.height;
6324
7052
  const shade = placeAt(div(""), rect);
6325
- shade.style.borderRadius = round(turning2.radii);
7053
+ shade.style.borderRadius = round2(turning2.radii);
6326
7054
  const freeEdge = placeAt(div(""), rect);
6327
- freeEdge.style.borderRadius = round(turning2.radii);
7055
+ freeEdge.style.borderRadius = round2(turning2.radii);
6328
7056
  veil.append(shade, freeEdge);
6329
7057
  const leaf = {
6330
7058
  pane: turning2.pane,
@@ -6378,8 +7106,10 @@ function copiesOf(layout, open, closed, pictures) {
6378
7106
  inner.screen.style.clipPath = layout.across ? `inset(${-far}px ${short(whole.x + whole.width - layout.hinge)}px ${-far}px ${-far}px)` : `inset(${short(layout.hinge - whole.y)}px ${-far}px ${-far}px ${-far}px)`;
6379
7107
  return { inner, outer };
6380
7108
  }
6381
- function build(scene, layout, open, closed, pictures, found) {
7109
+ function build(scene, layout, open, closed, pictures, found, flip) {
6382
7110
  const layer = div("fold");
7111
+ if (flip)
7112
+ layer.style.transform = "rotate(180deg)";
6383
7113
  const place2 = div("");
6384
7114
  let turning2;
6385
7115
  const shots2 = found && shotsOf(layout, open, closed, pictures, found);
@@ -6422,9 +7152,11 @@ function retake(going) {
6422
7152
  const { size } = going.faces.open;
6423
7153
  const color = scene.background();
6424
7154
  const last = going.pictures.open;
6425
- if (roughOf(scene.frame, scene.glass, values.open, size, color) === last.shot)
7155
+ const rough = roughOf(scene.frame, scene.glass, values.open, size, color);
7156
+ if ((going.flip && rough ? flipPicture({ shot: rough, painted: null, bars: null }, size).shot : rough) === last.shot)
6426
7157
  return;
6427
- const next = pictureOf(scene.frame, scene.glass, values.open, size, color, copyPage(scene.frame));
7158
+ const taken = pictureOf2(scene.frame, scene.glass, values.open, size, color, copyPage(scene.frame));
7159
+ const next = going.flip ? flipPicture(taken, size) : taken;
6428
7160
  going.pictures = { ...going.pictures, open: next };
6429
7161
  const put = (shot) => {
6430
7162
  if (fold !== going || going.pictures.open !== next)
@@ -6435,18 +7167,18 @@ function retake(going) {
6435
7167
  else
6436
7168
  paintLeaf(turning2.inner, shot);
6437
7169
  };
6438
- const rough = () => {
7170
+ const roughly = () => {
6439
7171
  if (next.shot)
6440
7172
  put(next.shot);
6441
7173
  };
6442
7174
  if (!next.painted)
6443
- rough();
7175
+ roughly();
6444
7176
  else {
6445
7177
  next.painted.then((drawn) => {
6446
7178
  if (drawn)
6447
7179
  paintDrawn(next, drawn, put);
6448
7180
  else
6449
- rough();
7181
+ roughly();
6450
7182
  });
6451
7183
  }
6452
7184
  }
@@ -6490,7 +7222,7 @@ function show(going) {
6490
7222
  going.waiting = false;
6491
7223
  const { open: open2, closed } = going.faces;
6492
7224
  drop(going.parts);
6493
- going.parts = build(going.scene, going.layout, open2, closed, going.pictures, found);
7225
+ going.parts = build(going.scene, going.layout, open2, closed, going.pictures, found, going.flip);
6494
7226
  going.drawn = "";
6495
7227
  }
6496
7228
  const { layout, parts } = going;
@@ -6523,8 +7255,14 @@ function show(going) {
6523
7255
  const opened = unit.posture === "open";
6524
7256
  const own = opened ? layout.unfolded.scale : layout.folded.scale;
6525
7257
  const drift = shots2 ? shotsDrift(shots2.shots, layout, shots2.inside, shots2.outside, open, unit.posture) : { wide: 1, tall: 1, x: 0, y: 0 };
6526
- const body = opened ? { x: 0, y: 0 } : layout.shut;
6527
- const to = { x: x + (drift.wide * body.x + drift.x) * scale, y: y + (drift.tall * body.y + drift.y) * scale };
7258
+ const body = opened ? { x: 0, y: 0, ...layout.open } : layout.shut;
7259
+ const laid = {
7260
+ x: x + (drift.wide * body.x + drift.x) * scale,
7261
+ y: y + (drift.tall * body.y + drift.y) * scale,
7262
+ width: body.width * drift.wide * scale,
7263
+ height: body.height * drift.tall * scale
7264
+ };
7265
+ const to = going.flip ? flipRect(laid, going.flip) : laid;
6528
7266
  const by = { x: to.x - unit.corner.x, y: to.y - unit.corner.y };
6529
7267
  const size = unit.base * scale / own;
6530
7268
  scene.unit.style.transform = `translate(${by.x}px, ${by.y}px) scale(${size * drift.wide}, ${size * drift.tall})`;
@@ -6542,7 +7280,9 @@ function stillClip(going, shots2, inside, own) {
6542
7280
  const under = inside ? 1 + 2 * (shots2?.inner.over ?? 0) : 0;
6543
7281
  const hinge = at(layout.hinge + (layout.across ? -under : under));
6544
7282
  const far = 1e5;
6545
- const points = (corners2) => `polygon(${corners2.map(([px, py]) => `${px}px ${py}px`).join(", ")})`;
7283
+ const { width, height } = layout.open;
7284
+ const placed = ([px, py]) => going.flip ? [at(width) - px, at(height) - py] : [px, py];
7285
+ const points = (corners2) => `polygon(${corners2.map(placed).map(([px, py]) => `${px}px ${py}px`).join(", ")})`;
6546
7286
  if (!shots2 || going.still < 1) {
6547
7287
  return layout.across ? points([[hinge, -far], [far, -far], [far, far], [hinge, far]]) : points([[-far, -far], [far, -far], [far, hinge], [-far, hinge]]);
6548
7288
  }
@@ -6709,14 +7449,18 @@ function foldDevice(from, value, scene, draw, held = false) {
6709
7449
  coverTo(scene.cover, 0);
6710
7450
  scene.glass.append(scene.cover);
6711
7451
  const color = scene.background();
6712
- const now = sideOf(scene, from, scene.screenRect());
6713
- const next = sideOf(scene, value, to);
6714
7452
  const opening = value.posture === "open";
6715
7453
  const across = (opening ? value : from).orientation === "landscape";
7454
+ const { letterbox } = scene;
7455
+ const flip = !across && formOf(from.device, "closed")?.clockwise === true ? { width: letterbox.clientWidth, height: letterbox.clientHeight } : null;
7456
+ const turn2 = (face) => flip ? flipFace(face, flip) : face;
7457
+ const now = turn2(sideOf(scene, from, scene.screenRect()));
7458
+ const next = turn2(sideOf(scene, value, to));
6716
7459
  const copy = copyPage(scene.frame);
6717
- const before = pictureOf(scene.frame, scene.glass, from, now.size, color, copy);
7460
+ const turnPicture = (picture, size) => flip ? flipPicture(picture, size) : picture;
7461
+ const before = turnPicture(pictureOf2(scene.frame, scene.glass, from, now.size, color, copy), now.size);
6718
7462
  draw(value);
6719
- const after = pictureOf(scene.frame, scene.glass, value, next.size, color, copy);
7463
+ const after = turnPicture(pictureOf2(scene.frame, scene.glass, value, next.size, color, copy), next.size);
6720
7464
  draw(from);
6721
7465
  const closed = opening ? now : next;
6722
7466
  const open = opening ? next : now;
@@ -6728,7 +7472,7 @@ function foldDevice(from, value, scene, draw, held = false) {
6728
7472
  const target = openOf((held ? from : value).posture);
6729
7473
  if (duo)
6730
7474
  decodeFoldShots(start, Math.sign(start - target));
6731
- const parts = build(scene, layout, open, closed, pictures, duo ? foldShots() : null);
7475
+ const parts = build(scene, layout, open, closed, pictures, duo ? foldShots() : null, flip);
6732
7476
  const wait = held ? null : { since: null, painted: !before.painted && !after.painted };
6733
7477
  if (wait && !wait.painted) {
6734
7478
  Promise.all([before.painted, after.painted]).then(() => {
@@ -6756,6 +7500,7 @@ function foldDevice(from, value, scene, draw, held = false) {
6756
7500
  wait,
6757
7501
  parts,
6758
7502
  unit: measure2(scene, from.posture),
7503
+ flip,
6759
7504
  fresh: null,
6760
7505
  still: 0,
6761
7506
  out: 1,
@@ -7167,7 +7912,7 @@ function rimsAt(splash, plan2, time) {
7167
7912
  }
7168
7913
  return rims;
7169
7914
  }
7170
- function round2(value) {
7915
+ function round3(value) {
7171
7916
  return Math.round(value * 10) / 10;
7172
7917
  }
7173
7918
  function pathOf(rims) {
@@ -7176,8 +7921,8 @@ function pathOf(rims) {
7176
7921
  const [first] = curve;
7177
7922
  if (!first)
7178
7923
  return "";
7179
- const start2 = `M${round2(first[0].x)} ${round2(first[0].y)}`;
7180
- const rest3 = curve.map(([, c1, c2, end]) => `C${round2(c1.x)} ${round2(c1.y)} ${round2(c2.x)} ${round2(c2.y)} ${round2(end.x)} ${round2(end.y)}`);
7924
+ const start2 = `M${round3(first[0].x)} ${round3(first[0].y)}`;
7925
+ const rest3 = curve.map(([, c1, c2, end]) => `C${round3(c1.x)} ${round3(c1.y)} ${round3(c2.x)} ${round3(c2.y)} ${round3(end.x)} ${round3(end.y)}`);
7181
7926
  return `${start2}${rest3.join("")}Z`;
7182
7927
  }).join("");
7183
7928
  }
@@ -7799,7 +8544,7 @@ function visionFilter(value) {
7799
8544
  }
7800
8545
 
7801
8546
  // src/engine/width.ts
7802
- var NAME2 = "width";
8547
+ var NAME = "width";
7803
8548
  var RIDE_SLOW = 50;
7804
8549
  var FRAME_API_WAIT = 1500;
7805
8550
  var ZOOM_SETTLE = 200;
@@ -8136,13 +8881,16 @@ function showMock(mock, place2) {
8136
8881
  mockDrawing = mock ? drawMock(mock, place2, href) : null;
8137
8882
  if (mockDrawing)
8138
8883
  screen.append(mockDrawing);
8139
- glass.className = mock ? "glass mocked" : "glass";
8884
+ glass.className = mock ? `glass mocked${mock.continuous ? " continuous" : ""}` : "glass";
8140
8885
  }
8141
8886
  const zoom = place2.zoom;
8142
8887
  glass.style.left = mock ? `${mock.inset.left * zoom}px` : "";
8143
8888
  glass.style.top = mock ? `${mock.inset.top * zoom}px` : "";
8144
- const round3 = mock ? corners(mock.screenRadius).map((radius) => `${radius * zoom}px`) : [];
8145
- glass.style.borderRadius = round3.join(" ");
8889
+ const round4 = mock ? corners(mock.screenRadius).map((radius) => `${radius * zoom}px`) : [];
8890
+ glass.style.borderRadius = round4.join(" ");
8891
+ const [corner = 0] = mock ? corners(mock.screenRadius) : [];
8892
+ const continuous = mock?.continuous ? `${corner * CONTINUOUS.extent * zoom}px` : "";
8893
+ glass.style.setProperty("--continuous", continuous);
8146
8894
  glass.style.boxShadow = href ? `0 0 0 ${UNDER * zoom}px #000` : "";
8147
8895
  if (mock && mockDrawing) {
8148
8896
  mockDrawing.style.width = `${mock.width * zoom}px`;
@@ -8185,8 +8933,10 @@ function showMat(size) {
8185
8933
  mat = next;
8186
8934
  }
8187
8935
  function bodyFor(value) {
8188
- return bodyOf(value, resize);
8936
+ const body = bodyOf(value, resize);
8937
+ return body && over2 && openUpright(shapeOf(value)) ? flipMock(body) : body;
8189
8938
  }
8939
+ var over2 = false;
8190
8940
  function resize() {
8191
8941
  if (!frame3 || !letterbox || !stage || !drawing || !screen || !readout || !caption)
8192
8942
  return;
@@ -8380,6 +9130,7 @@ foldableShown(() => {
8380
9130
  return scene && { scene, value: current };
8381
9131
  });
8382
9132
  function foldDevice2(value, held2 = false) {
9133
+ over2 = caseOver(shapeOf(current), shapeOf(value), over2);
8383
9134
  landGlide();
8384
9135
  touchDot?.rest();
8385
9136
  return foldDevice(current, value, foldScene(), draw, held2);
@@ -8390,7 +9141,7 @@ function hidePage() {
8390
9141
  return;
8391
9142
  covered = true;
8392
9143
  cover2(body);
8393
- const style = ensureStyle(NAME2);
9144
+ const style = ensureStyle(NAME);
8394
9145
  style.textContent = "html{overflow:hidden!important}:popover-open:not([data-devknobs]){display:none!important}";
8395
9146
  const node = styleNode(style);
8396
9147
  if (node)
@@ -8403,7 +9154,7 @@ function showPage() {
8403
9154
  stopKeepingStyle?.();
8404
9155
  stopKeepingStyle = null;
8405
9156
  uncover2();
8406
- removeStyle(NAME2);
9157
+ removeStyle(NAME);
8407
9158
  }
8408
9159
  function remounted() {
8409
9160
  if (covered) {
@@ -8707,9 +9458,10 @@ function close(follow5) {
8707
9458
  else
8708
9459
  window.scrollTo({ left: scroll.x, top: scroll.y, behavior: "instant" });
8709
9460
  }
8710
- function apply2(value) {
9461
+ function apply3(value) {
8711
9462
  const shape = shapeOf(value);
8712
9463
  const from = heading;
9464
+ over2 = caseOver(from, shape, over2);
8713
9465
  heading = shape;
8714
9466
  const first = !settled;
8715
9467
  settled = true;
@@ -8811,6 +9563,7 @@ function apply2(value) {
8811
9563
  function reset() {
8812
9564
  close(false);
8813
9565
  heading = "closed";
9566
+ over2 = false;
8814
9567
  settled = false;
8815
9568
  }
8816
9569
  // src/engine/foldhand.ts