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