@vinena/knobs 0.5.1 → 0.5.3

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 (65) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +7 -0
  3. package/dist/early.global.js +6 -6
  4. package/dist/{elementsview-tf4qzmtw.js → elementsview-1wsxcdtj.js} +4 -4
  5. package/dist/{elementsview-jnkbhzkj.js → elementsview-3kv34jfx.js} +4 -4
  6. package/dist/engine/browserdraw.d.ts +29 -2
  7. package/dist/engine/browserkit.d.ts +20 -1
  8. package/dist/engine/browserui.d.ts +162 -22
  9. package/dist/engine/devices.d.ts +3 -2
  10. package/dist/engine/devicon.d.ts +59 -0
  11. package/dist/engine/fit.d.ts +4 -3
  12. package/dist/engine/foldflip.d.ts +40 -0
  13. package/dist/engine/frames.d.ts +1 -0
  14. package/dist/engine/identity.d.ts +12 -5
  15. package/dist/engine/index.d.ts +2 -0
  16. package/dist/engine/mock.d.ts +14 -0
  17. package/dist/engine/mockdata.d.ts +5 -1
  18. package/dist/engine/morphrun.d.ts +4 -0
  19. package/dist/engine/native.d.ts +31 -3
  20. package/dist/engine/notice.d.ts +1 -2
  21. package/dist/engine/pageshot.d.ts +5 -2
  22. package/dist/engine/safaridraw.d.ts +162 -10
  23. package/dist/engine/screen.d.ts +24 -0
  24. package/dist/engine/store.d.ts +2 -1
  25. package/dist/engine/tabicon.d.ts +43 -0
  26. package/dist/engine/toplayer.d.ts +62 -0
  27. package/dist/engine/touchpointer.d.ts +0 -21
  28. package/dist/engine/underbar.d.ts +61 -0
  29. package/dist/engine/width.d.ts +3 -0
  30. package/dist/{framekit-3n7p79ht.js → framekit-cjz0e4y8.js} +2492 -1587
  31. package/dist/{framekit-g96t6nmq.js → framekit-yk1jxjv7.js} +2492 -1587
  32. package/dist/host.d.ts +51 -0
  33. package/dist/{index-33x9hxe3.js → index-6wbgqkdz.js} +626 -189
  34. package/dist/{index-2d6wvs8h.js → index-9jhatmky.js} +4 -4
  35. package/dist/{index-zvze25nf.js → index-begsqdm0.js} +1 -1
  36. package/dist/{index-peh33xjv.js → index-j1h13ahg.js} +1 -1
  37. package/dist/{index-5baxvd3v.js → index-p57fdttx.js} +307 -129
  38. package/dist/{index-dvr4x91q.js → index-prjpx67p.js} +20 -8
  39. package/dist/{index-d0cjxjsm.js → index-q73py563.js} +1 -1
  40. package/dist/{index-ke6v7919.js → index-sn2y6j09.js} +20 -8
  41. package/dist/{index-0casarhy.js → index-vgfn2n1h.js} +1 -1
  42. package/dist/{index-k015tb6c.js → index-zt3rheck.js} +4 -4
  43. package/dist/index.d.ts +26 -1
  44. package/dist/index.global.js +299 -176
  45. package/dist/index.js +424 -124
  46. package/dist/instance.d.ts +23 -4
  47. package/dist/{react-qv0nykcv.js → react-3rhdj2k1.js} +623 -186
  48. package/dist/{react-carf84xv.js → react-6tss0r9f.js} +307 -129
  49. package/dist/{react-eygws6cx.js → react-7vjfsh40.js} +4 -4
  50. package/dist/{react-71a9ypex.js → react-806qmkyz.js} +4 -4
  51. package/dist/{react-65tgdbs8.js → react-gefkdkdz.js} +1 -1
  52. package/dist/{react-sq9pkw4k.js → react-mmq2zya3.js} +1 -1
  53. package/dist/{react-xxfpfddf.js → react-qfpg79hs.js} +1 -1
  54. package/dist/{react-pdvseef0.js → react-qgz9afa2.js} +1 -1
  55. package/dist/react.js +420 -123
  56. package/dist/{storageview-sb23henh.js → storageview-7cv0vpdm.js} +4 -4
  57. package/dist/{storageview-vf8v8q8j.js → storageview-dyhpgt8f.js} +4 -4
  58. package/dist/types.d.ts +14 -0
  59. package/dist/ui/footer.d.ts +9 -2
  60. package/dist/ui/panel.d.ts +16 -2
  61. package/dist/ui/settings.d.ts +25 -1
  62. package/dist/version.d.ts +2 -0
  63. package/package.json +3 -2
  64. package/skills/devknobs/SKILL.md +1 -1
  65. package/dist/engine/endroom.d.ts +0 -21
@@ -28,12 +28,12 @@ import {
28
28
  turnOf,
29
29
  turnedPose,
30
30
  windowRect
31
- } from "./index-peh33xjv.js";
31
+ } from "./index-j1h13ahg.js";
32
32
  import {
33
33
  hush,
34
34
  hushOnce,
35
35
  quietFetch
36
- } from "./index-d0cjxjsm.js";
36
+ } from "./index-q73py563.js";
37
37
  import {
38
38
  copyText
39
39
  } from "./index-ztnjefrh.js";
@@ -48,13 +48,16 @@ import {
48
48
  MAT_COLOR_NAMES,
49
49
  SAFARI_TEXT,
50
50
  UNFRAMED,
51
+ ZOOM_MAX,
51
52
  ZOOM_PRESETS,
52
53
  Z_INDEX,
53
54
  __export,
54
55
  addStyle,
55
56
  adoptEarly,
57
+ alphaAt,
56
58
  anchorScroll,
57
59
  apply3 as apply,
60
+ apply4 as apply2,
58
61
  barsOf,
59
62
  barsStep,
60
63
  baseMatchMedia,
@@ -63,11 +66,9 @@ import {
63
66
  coarse,
64
67
  deviceOf,
65
68
  dropEarly,
66
- endRoom,
67
69
  ensureStyle,
68
70
  equip,
69
71
  equip1 as equip2,
70
- findStyle,
71
72
  follow,
72
73
  formId,
73
74
  formOf,
@@ -75,6 +76,7 @@ import {
75
76
  handing,
76
77
  handsSchemeDown,
77
78
  hasTouch,
79
+ islandOf,
78
80
  keep,
79
81
  keepDrawing,
80
82
  layoutOf,
@@ -88,6 +90,7 @@ import {
88
90
  openOf,
89
91
  ownReload,
90
92
  parseColor,
93
+ parseHex,
91
94
  percent,
92
95
  placeIn,
93
96
  plainFrame,
@@ -97,7 +100,10 @@ import {
97
100
  readMessage,
98
101
  readSnapshot,
99
102
  removeStyle,
103
+ round,
104
+ runsUnderBars,
100
105
  screenOf,
106
+ screenSizeOf,
101
107
  settles,
102
108
  snapshotKey,
103
109
  stepZoom,
@@ -106,12 +112,13 @@ import {
106
112
  styleNode,
107
113
  turn,
108
114
  turnRadius,
115
+ turnRect,
109
116
  turnSides,
110
117
  uaPreset,
111
118
  userAgentOf,
112
119
  viewportOf,
113
120
  wheelZoom
114
- } from "./index-5baxvd3v.js";
121
+ } from "./index-p57fdttx.js";
115
122
 
116
123
  // src/engine/width.ts
117
124
  var exports_width = {};
@@ -123,6 +130,7 @@ __export(exports_width, {
123
130
  origin: () => origin,
124
131
  onZoom: () => onZoom,
125
132
  onRefused: () => onRefused,
133
+ onLoader: () => onLoader,
126
134
  onFramed: () => onFramed,
127
135
  onExit: () => onExit,
128
136
  label: () => label,
@@ -130,19 +138,20 @@ __export(exports_width, {
130
138
  frameWindow: () => frameWindow,
131
139
  foldDevice: () => foldDevice2,
132
140
  fit: () => fit,
133
- apply: () => apply2,
141
+ apply: () => apply3,
134
142
  STRIP: () => STRIP,
135
143
  RIDE_SLOW: () => RIDE_SLOW,
136
- FRAME_API_WAIT: () => FRAME_API_WAIT
144
+ FRAME_API_WAIT: () => FRAME_API_WAIT,
145
+ COVER_CAP: () => COVER_CAP
137
146
  });
138
147
 
139
148
  // src/engine/identity.ts
140
149
  function identityOf(state) {
141
150
  const agent = uaPreset(state.ua.preset) ? state.ua.preset : userAgentOf(state.ua);
142
- return { agent, touch: hasTouch(state.device), dpr: state.dpr };
151
+ return { agent, touch: hasTouch(state.device), dpr: state.dpr, ...state.panel?.realPhone ? { served: true } : {} };
143
152
  }
144
153
  function stale(loaded, next) {
145
- return loaded !== null && (loaded.agent !== next.agent || loaded.touch !== next.touch || loaded.dpr !== next.dpr);
154
+ return loaded !== null && (loaded.agent !== next.agent || loaded.touch !== next.touch || loaded.dpr !== next.dpr || (loaded.served ?? false) !== (next.served ?? false));
146
155
  }
147
156
  var PATCHED = Symbol.for("devknobs.identity");
148
157
  function isIdentity(value) {
@@ -159,6 +168,7 @@ function patchWindow(view, state) {
159
168
  const identity = identityOf(state);
160
169
  Reflect.set(view, PATCHED, identity);
161
170
  apply(state.ua, view);
171
+ apply2(screenSizeOf(state), view);
162
172
  if (identity.touch) {
163
173
  equip2(view, uaPreset(state.ua.preset) === undefined);
164
174
  coarse(view);
@@ -2970,7 +2980,7 @@ var BEZELS = {
2970
2980
  opening: [60, 72, 1260, 2736],
2971
2981
  body: [6, 26, 1375, 2854],
2972
2982
  cutout: [503.25, 133.05, 373.76, 107.91],
2973
- radius: PRO
2983
+ radius: 65
2974
2984
  }
2975
2985
  },
2976
2986
  "iphone-17": {
@@ -3155,6 +3165,7 @@ function bezelMock(id, orientation) {
3155
3165
  const own = orientation === "landscape" ? found.landscape : undefined;
3156
3166
  const bezel = own ?? found.portrait;
3157
3167
  const turned = orientation === "landscape" && !own;
3168
+ const clockwise = turned && device.clockwise === true;
3158
3169
  const screen = turn(device, own ? "landscape" : "portrait");
3159
3170
  const scale = density(screen, bezel);
3160
3171
  const [x, y, w, h] = bezel.opening;
@@ -3171,22 +3182,26 @@ function bezelMock(id, orientation) {
3171
3182
  };
3172
3183
  const width = (right - left) / scale;
3173
3184
  const height = (bottom - top) / scale;
3174
- const sides = turned ? turnSides(inset) : inset;
3185
+ const sides = turned ? turnSides(inset, clockwise) : inset;
3175
3186
  const size = turned ? { width: height, height: width } : { width, height };
3187
+ const island = islandOf(id);
3188
+ const flat = island && round("sensor", { ...island, x: inset.left + island.x, y: inset.top + island.y });
3189
+ const parts = flat ? [turned ? turnRect(flat, width, height, clockwise) : flat] : [];
3176
3190
  return {
3177
3191
  ...size,
3178
3192
  inset: sides,
3179
3193
  body: { x: 0, y: 0, ...size },
3180
- screenRadius: turned ? turnRadius(bezel.radius) : bezel.radius,
3194
+ screenRadius: turned ? turnRadius(bezel.radius, clockwise) : bezel.radius,
3181
3195
  bodyRadius: 0,
3182
- parts: [],
3196
+ parts,
3183
3197
  image: {
3184
3198
  file: bezel.file,
3185
3199
  x: -left / scale,
3186
3200
  y: -top / scale,
3187
3201
  width: bezel.size[0] / scale,
3188
3202
  height: bezel.size[1] / scale,
3189
- turn: turned ? width : null
3203
+ turn: turned ? clockwise ? height : width : null,
3204
+ ...clockwise ? { clockwise } : {}
3190
3205
  }
3191
3206
  };
3192
3207
  }
@@ -3559,8 +3574,7 @@ var GLYPHS = {
3559
3574
  bookmarks: () => [],
3560
3575
  tabs: () => [],
3561
3576
  reload: () => [],
3562
- page: () => [],
3563
- more: () => []
3577
+ page: () => []
3564
3578
  };
3565
3579
  function box(className, rect) {
3566
3580
  const node = el("div", className);
@@ -3646,32 +3660,8 @@ function buildChrome(full, mini, look) {
3646
3660
  };
3647
3661
  }
3648
3662
 
3649
- // src/engine/endroom.ts
3650
- var NAME = "endroom";
3651
- var VARIABLE = "--devknobs-end-room";
3652
- var CSS = `:root{${VARIABLE}:0px}html{margin-bottom:var(${VARIABLE})!important}`;
3653
- function holder(style) {
3654
- const rule = style.sheet?.cssRules[0];
3655
- return rule?.style ?? null;
3656
- }
3657
- function give(doc, room) {
3658
- const existing = findStyle(NAME, doc);
3659
- const held = existing ? holder(existing) : null;
3660
- const had = Number.parseFloat(held?.getPropertyValue(VARIABLE) ?? "") || 0;
3661
- if (room <= 0) {
3662
- existing?.remove();
3663
- return had;
3664
- }
3665
- if (had === room)
3666
- return had;
3667
- const style = existing ?? ensureStyle(NAME, doc);
3668
- if (!existing)
3669
- style.textContent = CSS;
3670
- holder(style)?.setProperty(VARIABLE, `${room}px`);
3671
- return had;
3672
- }
3673
-
3674
3663
  // src/engine/safaridraw.ts
3664
+ var DOMAIN_WEIGHT = 500;
3675
3665
  var SAFARI_CSS = `
3676
3666
  .safari {
3677
3667
  color: #000;
@@ -3693,27 +3683,37 @@ var SAFARI_CSS = `
3693
3683
  }
3694
3684
  .safari.dark { color: #f3f3f8; }
3695
3685
  .safari .surface > *, .safari .side > *, .safari .field > * { position: absolute; }
3696
- /* Glass over the page: a fill the page shows faintly through, blurred. */
3697
- .safari .capsule, .safari .card, .safari .surface {
3698
- background: rgba(255, 255, 255, 0.78);
3699
- box-shadow: 0 8px 28px rgba(0, 0, 0, 0.1), 0 0 0 0.5px rgba(0, 0, 0, 0.06);
3700
- -webkit-backdrop-filter: blur(10px) saturate(1.8);
3701
- backdrop-filter: blur(10px) saturate(1.8);
3702
- }
3703
- .safari .card, .safari[data-state="max"] .surface.from-card {
3704
- background: rgba(250, 250, 250, 0.82);
3705
- }
3706
- .safari .field { background: rgba(0, 0, 0, 0.05); }
3707
- /* Sampled from a real iPhone over a dark page. */
3708
- .safari.dark .capsule, .safari.dark .surface {
3709
- background: rgba(40, 40, 42, 0.75);
3710
- box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.13);
3711
- }
3712
- .safari.dark .card, .safari.dark[data-state="max"] .surface.from-card {
3713
- background: rgba(46, 46, 48, 0.8);
3714
- box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.12);
3715
- }
3716
- .safari.dark .field { background: rgba(0, 0, 0, 0.14); }
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); }
3717
3717
  .safari .glyph {
3718
3718
  fill: none;
3719
3719
  stroke: currentColor;
@@ -3721,13 +3721,13 @@ var SAFARI_CSS = `
3721
3721
  stroke-linecap: round;
3722
3722
  stroke-linejoin: round;
3723
3723
  }
3724
- .safari .glyph .solid { fill: currentColor; stroke: none; }
3725
3724
  /* Reload and stop are a shade lighter than the other glyphs and thinner, as measured. */
3726
3725
  .safari .glyph .reload { stroke-width: 1.6; }
3727
3726
  .safari .glyph .stop { stroke-width: 1.82; }
3728
- .safari.light .glyph .reload, .safari.light .glyph .stop { stroke: #191919; }
3729
- .safari .glyph.off { color: #babac7; }
3730
- .safari.dark .glyph.off { color: #58585b; }
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; }
3731
3731
  .safari .domain {
3732
3732
  left: 50%;
3733
3733
  white-space: nowrap;
@@ -3735,14 +3735,14 @@ var SAFARI_CSS = `
3735
3735
  text-overflow: ellipsis;
3736
3736
  text-align: center;
3737
3737
  font-size: ${SAFARI_TEXT.field}px;
3738
- font-weight: 400;
3739
- letter-spacing: -0.2px;
3738
+ font-weight: ${DOMAIN_WEIGHT};
3740
3739
  transform: translate(-50%, -50%);
3741
3740
  }
3742
- .safari .time { font-weight: 600; letter-spacing: -0.3px; transform: translate(-50%, -50%); }
3741
+ .safari .time { font-weight: 600; transform: translate(-50%, -50%); }
3743
3742
  .safari .status { fill: currentColor; }
3744
- .safari .level { fill: #fff; font-size: 9.5px; font-weight: 600; letter-spacing: -0.3px; }
3745
- .safari.dark .level { fill: #000; }
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; }
3746
3746
  /* One surface morphs: its box, corners and color, and the domain glides in it. */
3747
3747
  .safari .surface {
3748
3748
  overflow: hidden;
@@ -3755,7 +3755,10 @@ var SAFARI_CSS = `
3755
3755
  background-color var(--main) ${MORPH.ease},
3756
3756
  box-shadow var(--main) ${MORPH.ease};
3757
3757
  }
3758
- .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 {
3759
3762
  transition:
3760
3763
  top var(--main) ${MORPH.ease},
3761
3764
  height var(--main) ${MORPH.ease},
@@ -3830,11 +3833,7 @@ var GLYPHS2 = {
3830
3833
  path2("M6.66 0.92A6.59 6.59 0 1 1 2.93 -5.02", "reload"),
3831
3834
  path2("M-0.15 -8.89L3.26 -5.33L-0.16 -1.93", "reload")
3832
3835
  ],
3833
- page: () => [
3834
- svgNode("rect", { x: -6.8, y: -8.1, width: 13.6, height: 8.6, rx: 2.4 }),
3835
- path2("M-6.8 4.2H6.8M-6.8 8.1H2.6")
3836
- ],
3837
- more: () => [-7.8, 0, 7.8].map((x) => svgNode("circle", { cx: x, cy: 0, r: 2, class: "solid" })),
3836
+ page: () => [path2("M-6.3 -5.1H8M-6.3 0H8M-6.3 5.1H3", "page")],
3838
3837
  plus: () => [path2("M0 -8.5V8.5M-8.5 0H8.5")],
3839
3838
  home: () => [],
3840
3839
  tune: () => [],
@@ -3844,65 +3843,183 @@ var GLYPHS2 = {
3844
3843
  function stopGlyph() {
3845
3844
  return [path2("M-5.66 -5.54L5.88 6M5.88 -5.54L-5.66 6", "stop")];
3846
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
+ };
3847
3876
  function fan(from, to, angle) {
3848
3877
  const rad = angle * Math.PI / 180;
3849
3878
  const at = (r, side) => `${(side * r * Math.sin(rad)).toFixed(2)} ${(-r * Math.cos(rad)).toFixed(2)}`;
3850
3879
  const inner = from > 0 ? `L${at(from, 1)}A${from} ${from} 0 0 0 ${at(from, -1)}Z` : "L0 0Z";
3851
3880
  return `M${at(to, -1)}A${to} ${to} 0 0 1 ${at(to, 1)}${inner}`;
3852
3881
  }
3853
- function wifi(x, y) {
3854
- const svg = svgNode("svg", { class: "status", viewBox: "-8.5 -12.3 17 12.3" });
3855
- place(svg, x, y - 6.15, 17, 12.3);
3856
- svg.append(...[fan(0, 3.6, 46), fan(5.5, 8.2, 46), fan(9.9, 12.3, 46)].map((d) => {
3857
- const round = { "stroke-linejoin": "round", stroke: "currentColor", "stroke-width": 0.6 };
3858
- return svgNode("path", { d, ...round });
3859
- }));
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 })));
3860
3890
  return svg;
3861
3891
  }
3862
- function signal(x, y) {
3863
- const svg = svgNode("svg", { class: "status", viewBox: "0 0 18 12" });
3864
- place(svg, x, y - 6, 18, 12);
3865
- svg.append(...[4.4, 6.8, 9.2, 12].map((height, at) => svgNode("rect", { x: at * 4.93, y: 12 - height, width: 3.2, height, rx: 1 })));
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 })));
3866
3899
  return svg;
3867
3900
  }
3868
- function battery(x, y) {
3869
- const svg = svgNode("svg", { class: "status", viewBox: "0 0 27.3 13" });
3870
- place(svg, x, y - 6.5, 27.3, 13);
3871
- const level = svgNode("text", {
3872
- class: "level",
3873
- x: 12.6,
3874
- y: 6.9,
3875
- "text-anchor": "middle",
3876
- "dominant-baseline": "middle"
3877
- });
3878
- level.textContent = String(CHARGE);
3879
- const edge = (25.2 * CHARGE / 100).toFixed(2);
3880
- svg.append(svgNode("rect", { x: 0, y: 0, width: 25.2, height: 13, rx: 4.2, "fill-opacity": 0.4 }), svgNode("path", { d: `M4.2 0H${edge}V13H4.2A4.2 4.2 0 0 1 0 8.8V4.2A4.2 4.2 0 0 1 4.2 0Z` }), level, svgNode("path", {
3881
- d: "M26.1 4.6a1.2 1.2 0 0 1 1.2 1.2v1.4a1.2 1.2 0 0 1-1.2 1.2Z",
3882
- "fill-opacity": 0.4
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"
3883
3939
  }));
3884
3940
  return svg;
3885
3941
  }
3886
3942
  function statusBar(status) {
3943
+ const glyphs = status.large ? STATUS_GLYPHS.large : STATUS_GLYPHS.regular;
3887
3944
  const time = el("div", "time", "04:20");
3888
3945
  time.style.left = `${status.time.x}px`;
3889
- time.style.top = `${status.time.y}px`;
3946
+ time.style.top = `${status.time.y + glyphs.time.drop}px`;
3890
3947
  time.style.fontSize = `${status.time.size}px`;
3948
+ time.style.letterSpacing = `${glyphs.time.spacing}px`;
3891
3949
  const { icons } = status;
3950
+ const { signal: bars, wifi: air, battery: cell } = glyphs;
3892
3951
  if (icons.align === "start") {
3893
3952
  const end = status.battery ?? { x: icons.x, y: icons.y };
3953
+ const bottom = icons.y + Math.max(...bars.heights) / 2;
3894
3954
  const nodes = [
3895
- signal(icons.x, icons.y),
3896
- wifi(icons.x + 23, icons.y),
3897
- 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)
3898
3958
  ];
3899
3959
  for (const node of nodes)
3900
3960
  node.style.transform = "scale(0.85)";
3901
3961
  return [time, ...nodes];
3902
3962
  }
3903
- const cell = icons.x - 27.3;
3904
- const air = cell - 7.3 - 17;
3905
- return [time, signal(air - 6 - 18, icons.y), wifi(air, icons.y), battery(cell, icons.y)];
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
+ ];
3906
4023
  }
3907
4024
  function pressOf(glyph, actions) {
3908
4025
  if (glyph === "back")
@@ -3919,33 +4036,135 @@ function glyphIn(mark, origin, className, actions) {
3919
4036
  svg.style.top = `${mark.y - origin.y - 15}px`;
3920
4037
  return svg;
3921
4038
  }
4039
+ function domainOf(host) {
4040
+ return host.replace(/:\d+$/, "");
4041
+ }
3922
4042
  function pillBox(pill, host) {
3923
- 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);
3924
4045
  return { x: pill.x - width / 2, y: pill.y, width, height: pill.height };
3925
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
+ }
3926
4131
  function placeBox(node, box2, radius) {
3927
4132
  place(node, box2.x, box2.y, box2.width, box2.height);
3928
4133
  node.style.borderRadius = `${radius}px`;
3929
4134
  }
3930
- function placeFade(node, fade, look) {
3931
- node.hidden = fade === null;
3932
- if (!fade)
3933
- return;
3934
- node.style.top = `${fade.y}px`;
3935
- node.style.height = `${fade.height}px`;
3936
- const color = (alpha) => look.background.replace(/^rgb\((.*)\)$/, `rgba($1, ${alpha})`);
3937
- const stops = fade.stops.map(({ at, alpha }) => `${color(alpha)} ${at}px`);
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`);
3938
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));
3939
4158
  }
3940
4159
  function buildSafari(full, mini, look, actions) {
3941
4160
  const root = el("div", "safari");
3942
4161
  root.style.inset = "0";
3943
- const fade = el("div", "fade");
3944
- fade.style.left = "0";
3945
- fade.style.right = "0";
3946
- root.append(fade);
4162
+ const scrim = el("div", "scrim");
4163
+ root.append(scrim);
3947
4164
  if (full.status)
3948
4165
  root.append(...statusBar(full.status));
4166
+ const column = full.column ? statusColumn(full.column) : [];
4167
+ root.append(...column);
3949
4168
  const pill = mini.shapes.find((shape) => shape.kind === "pill") ?? null;
3950
4169
  const main = pill ? full.shapes.find((shape) => shape.kind === "card") ?? full.shapes.find((shape) => shape.text !== undefined) ?? null : null;
3951
4170
  let surface = null;
@@ -3995,11 +4214,13 @@ function buildSafari(full, mini, look, actions) {
3995
4214
  progress.hidden = true;
3996
4215
  surface?.append(progress);
3997
4216
  let loads3 = 0;
4217
+ const sides = [];
3998
4218
  for (const shape of full.shapes) {
3999
4219
  if (shape === main || shape.kind === "field")
4000
4220
  continue;
4001
4221
  const side = el("div", "side capsule");
4002
4222
  placeBox(side, shape, shape.radius);
4223
+ sides.push({ node: side, box: shape });
4003
4224
  const middle = shape.x + shape.width / 2;
4004
4225
  const across = full.orientation === "landscape";
4005
4226
  const toward = main ? main.x + main.width / 2 : middle;
@@ -4021,11 +4242,18 @@ function buildSafari(full, mini, look, actions) {
4021
4242
  root,
4022
4243
  apply(minimized, sight) {
4023
4244
  root.dataset.state = minimized ? "min" : "max";
4024
- root.className = sight.dark ? "safari dark" : "safari light";
4025
- 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" : "";
4026
4252
  for (const text of Array.from(root.querySelectorAll(".domain"))) {
4027
- text.textContent = sight.host;
4253
+ text.textContent = domainOf(sight.host);
4028
4254
  }
4255
+ for (const { node, box: box2 } of sides)
4256
+ tintGlass(node, box2, sight);
4029
4257
  for (const { node, glyph } of glyphs) {
4030
4258
  const off = glyph === "back" && !sight.canBack || glyph === "forward" && !sight.canForward;
4031
4259
  node.classList.toggle("off", off);
@@ -4034,9 +4262,10 @@ function buildSafari(full, mini, look, actions) {
4034
4262
  if (surface && domain && main && pill) {
4035
4263
  const box2 = minimized ? pillBox(pill, sight.host) : main;
4036
4264
  placeBox(surface, box2, minimized ? pill.radius : main.radius);
4265
+ tintGlass(surface, box2, sight);
4037
4266
  const top = minimized ? pill.height / 2 : Number(domain.dataset.top);
4038
4267
  domain.style.top = `${top}px`;
4039
- const scale = minimized ? SAFARI_TEXT.pill / SAFARI_TEXT.field : 1;
4268
+ const scale = minimized ? (pill.text?.size ?? SAFARI_TEXT.pill) / SAFARI_TEXT.field : 1;
4040
4269
  domain.style.transform = `translate(-50%, -50%) scale(${scale})`;
4041
4270
  }
4042
4271
  },
@@ -4074,1534 +4303,2044 @@ function buildSafari(full, mini, look, actions) {
4074
4303
  duration: PROGRESS.finish,
4075
4304
  easing: "ease-out"
4076
4305
  });
4077
- const fade2 = progress.animate([{ opacity: 1 }, { opacity: 0 }], {
4306
+ const fade = progress.animate([{ opacity: 1 }, { opacity: 0 }], {
4078
4307
  delay: PROGRESS.finish,
4079
4308
  duration: PROGRESS.fade,
4080
4309
  easing: "ease-out",
4081
4310
  fill: "forwards"
4082
4311
  });
4083
- fade2.finished.then(() => {
4312
+ fade.finished.then(() => {
4084
4313
  if (load !== loads3)
4085
4314
  return;
4086
4315
  progress.hidden = true;
4087
- fade2.cancel();
4316
+ fade.cancel();
4088
4317
  }, () => {});
4089
4318
  }
4090
4319
  };
4091
4320
  }
4092
4321
 
4093
- // src/engine/browserdraw.ts
4094
- var BARS_CSS = `
4095
- .browser {
4096
- position: absolute;
4097
- top: 0;
4098
- left: 0;
4099
- overflow: hidden;
4100
- transform-origin: 0 0;
4101
- pointer-events: none;
4102
- cursor: default;
4103
- user-select: none;
4104
- -webkit-user-select: none;
4105
- font-family: ${FONT};
4106
- font-weight: 400;
4107
- -webkit-font-smoothing: antialiased;
4108
- line-height: 1;
4109
- }
4110
- .browser > *,
4111
- .browser > * > *,
4112
- .browser .group > * {
4113
- position: absolute;
4114
- box-sizing: border-box;
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;
4115
4343
  }
4116
- .browser svg { overflow: visible; }
4117
- .browser .press { pointer-events: auto; cursor: default; }
4118
- ${SAFARI_CSS}
4119
- ${CHROME_CSS}
4120
- `;
4121
- var BUILDERS = { safari: buildSafari, chrome: buildChrome };
4122
- function toRgb(color) {
4123
- const parsed = parseColor(color);
4124
- if (parsed)
4125
- return parsed;
4126
- try {
4127
- const canvas = document.createElement("canvas");
4128
- canvas.width = 1;
4129
- canvas.height = 1;
4130
- const context = canvas.getContext("2d", { willReadFrequently: true });
4131
- if (!context)
4132
- return null;
4133
- context.fillStyle = color;
4134
- context.fillRect(0, 0, 1, 1);
4135
- const [r = 0, g = 0, b = 0, a = 0] = context.getImageData(0, 0, 1, 1).data;
4136
- return { red: r, green: g, blue: b, alpha: a / 255 };
4137
- } catch {
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))
4138
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;
4139
4355
  }
4356
+ return offset;
4140
4357
  }
4141
- function backgroundOf(doc, view, dark) {
4142
- const root = view.getComputedStyle(doc.documentElement);
4143
- const schemes = root.colorScheme ?? "";
4144
- const canvasDark = schemes.includes("dark") && (dark || !schemes.includes("light"));
4145
- let base = canvasDark ? [18, 18, 18] : [255, 255, 255];
4146
- const layers = [doc.body, doc.documentElement].filter((node) => !!node);
4147
- for (const node of layers) {
4148
- const color = toRgb(view.getComputedStyle(node).backgroundColor);
4149
- if (!color || color.alpha === 0)
4150
- continue;
4151
- const { red, green, blue, alpha } = color;
4152
- const [r, g, b] = base;
4153
- const over = (top, under) => Math.round(top * alpha + under * (1 - alpha));
4154
- base = [over(red, r), over(green, g), over(blue, b)];
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
+ }
4155
4387
  }
4156
- 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];
4157
4395
  }
4158
- function readLook(frame2) {
4159
- const fallback = {
4160
- background: "rgb(255, 255, 255)",
4161
- dark: false,
4162
- scheme: "light",
4163
- host: "",
4164
- canBack: false,
4165
- canForward: false
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
4166
4428
  };
4167
- try {
4168
- const view = frame2.contentWindow;
4169
- const doc = frame2.contentDocument;
4170
- if (!view || !doc?.documentElement)
4171
- return fallback;
4172
- const scheme = view.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
4173
- const [r, g, b] = backgroundOf(doc, view, scheme === "dark");
4174
- const navigation = navigationOf(view);
4175
- const can = (key) => {
4176
- const value = navigation && Reflect.get(navigation, key);
4177
- return typeof value === "boolean" ? value : null;
4178
- };
4179
- return {
4180
- background: `rgb(${r}, ${g}, ${b})`,
4181
- dark: luminance(r, g, b) < 0.4,
4182
- scheme,
4183
- host: view.location.host,
4184
- canBack: can("canGoBack") ?? view.history.length > 1,
4185
- canForward: can("canGoForward") ?? false
4186
- };
4187
- } catch {
4188
- return fallback;
4189
- }
4190
4429
  }
4191
- function reaches(frame2) {
4192
- try {
4193
- return !!frame2.contentDocument?.documentElement;
4194
- } catch {
4195
- 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
+ }
4196
4457
  }
4458
+ parts.push(text.slice(from));
4459
+ return parts;
4197
4460
  }
4198
- var RESTYLE = 120;
4199
- var LOAD_WAIT = 5000;
4200
- function same(a, b) {
4201
- 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("|");
4202
4467
  }
4203
- function createBrowser(glass, frame2, onChange, onReload = () => {}, ready = () => true) {
4204
- const blank = el("div", "screenblank");
4205
- blank.hidden = true;
4206
- glass.append(blank);
4207
- const layer = el("div", "browser");
4208
- layer.setAttribute("aria-hidden", "true");
4209
- let view = null;
4210
- let look = null;
4211
- let painted = null;
4212
- let built = "";
4213
- let applied = null;
4214
- let shrinking = 0;
4215
- let later = 0;
4216
- let query = null;
4217
- let watched = null;
4218
- let href = "";
4219
- let motion = BARS_START;
4220
- let busy = false;
4221
- let loadWait = 0;
4222
- const still2 = () => baseMatchMedia("(prefers-reduced-motion: reduce)").matches;
4223
- const step = (event) => {
4224
- const before = motion.minimized;
4225
- motion = barsStep(motion, event);
4226
- if (motion.minimized !== before)
4227
- queueMicrotask(onChange);
4228
- };
4229
- const onScroll = () => {
4230
- const page = frame2.contentWindow;
4231
- if (page)
4232
- step({ type: "scroll", y: page.scrollY, time: performance.now() });
4233
- };
4234
- const actions = {
4235
- back: () => frame2.contentWindow?.history.back(),
4236
- forward: () => frame2.contentWindow?.history.forward(),
4237
- reload: () => {
4238
- if (busy) {
4239
- frame2.contentWindow?.stop();
4240
- stopLoading();
4241
- return;
4242
- }
4243
- onReload();
4244
- keep(frame2.contentWindow, "frame");
4245
- frame2.contentWindow?.location.reload();
4246
- },
4247
- expand: () => step({ type: "tap" })
4248
- };
4249
- const roomFrame = () => {
4250
- const bars = view?.bars ?? null;
4251
- try {
4252
- const page = frame2.contentWindow;
4253
- const doc = frame2.contentDocument;
4254
- if (!page || !doc?.documentElement)
4255
- return;
4256
- const room = bars ? endRoom(bars.screen, bars.orientation, bars.layout, bars.minimized, bars.edge) : 0;
4257
- const had = give(doc, room);
4258
- if (had === room)
4259
- return;
4260
- step({ type: "resize", time: performance.now() });
4261
- const end = doc.documentElement.scrollHeight - page.innerHeight;
4262
- if (room < had || page.scrollY <= 1 || page.scrollY < end - (room - had) - 1)
4263
- return;
4264
- page.scrollTo({ top: end, behavior: still2() ? "instant" : "smooth" });
4265
- } catch {}
4266
- };
4267
- const sizeFrame = () => {
4268
- if (!view)
4269
- return;
4270
- view.sizeFrame();
4271
- if (!same(view.page, applied))
4272
- step({ type: "resize", time: performance.now() });
4273
- applied = view.page;
4274
- roomFrame();
4275
- };
4276
- const placeFrame = (instant) => {
4277
- const page = view?.page ?? null;
4278
- const shrinks = !instant && page && applied && page.height < applied.height;
4279
- clearTimeout(shrinking);
4280
- if (!shrinks) {
4281
- sizeFrame();
4282
- return;
4283
- }
4284
- shrinking = window.setTimeout(() => {
4285
- if (same(view?.page ?? null, page))
4286
- sizeFrame();
4287
- }, MORPH.expand);
4288
- };
4289
- const back = () => {
4290
- frame2.style.background = reaches(frame2) ? (look ??= readLook(frame2)).background : "";
4291
- };
4292
- const draw = () => {
4293
- const bars = view?.bars ?? null;
4294
- if (!view || !bars) {
4295
- clearTimeout(shrinking);
4296
- layer.replaceChildren();
4297
- glass.style.background = "";
4298
- back();
4299
- painted = null;
4300
- built = "";
4301
- if (view)
4302
- sizeFrame();
4303
- return;
4304
- }
4305
- look ??= readLook(frame2);
4306
- glass.style.background = look.background;
4307
- back();
4308
- const { platform, layout, screen, orientation, edge } = bars;
4309
- const base = JSON.stringify([platform, layout, screen, orientation, edge, view.follow]);
4310
- const fresh2 = base !== built || !painted;
4311
- const instant = fresh2 || still2();
4312
- if (fresh2) {
4313
- const other = barsOf(screen, orientation, layout, !bars.minimized, edge);
4314
- const full = bars.minimized ? other : bars;
4315
- const mini = bars.minimized ? bars : other;
4316
- const shown2 = { ...actions, expand: view.follow ? actions.expand : undefined };
4317
- if (!full || !mini)
4318
- return;
4319
- painted = BUILDERS[bars.platform](full, mini, look, shown2);
4320
- layer.replaceChildren(painted.root);
4321
- built = base;
4322
- if (busy)
4323
- painted.loading?.(true, true);
4324
- }
4325
- if (instant)
4326
- layer.setAttribute("data-instant", "");
4327
- painted?.apply(bars.minimized, look);
4328
- if (instant) {
4329
- layer.offsetWidth;
4330
- layer.removeAttribute("data-instant");
4331
- }
4332
- placeFrame(instant);
4333
- };
4334
- const pageOf = () => {
4335
- try {
4336
- return frame2.contentDocument;
4337
- } catch {
4338
- return null;
4339
- }
4340
- };
4341
- const showLoading = (on, seed) => {
4342
- busy = on;
4343
- if (seed) {
4344
- look = seed;
4345
- draw();
4346
- }
4347
- painted?.loading?.(on, still2());
4348
- if (!on)
4349
- browser.refresh();
4350
- };
4351
- const stopLoading = () => {
4352
- if (loadWait)
4353
- window.cancelAnimationFrame(loadWait);
4354
- loadWait = 0;
4355
- if (!busy)
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)
4356
4478
  return;
4357
- blank.hidden = true;
4358
- showLoading(false, null);
4359
- };
4360
- const startLoading = (seed) => {
4361
- blank.style.background = (seed ?? look ?? readLook(frame2)).background;
4362
- blank.hidden = false;
4363
- showLoading(true, seed);
4364
- if (loadWait)
4365
- window.cancelAnimationFrame(loadWait);
4366
- const end = performance.now() + LOAD_WAIT;
4367
- const gone = pageOf();
4368
- const check = () => {
4369
- loadWait = 0;
4370
- const next = gone === null || pageOf() !== gone;
4371
- if (next && ready() || performance.now() >= end)
4372
- stopLoading();
4373
- else
4374
- loadWait = window.requestAnimationFrame(check);
4375
- };
4376
- loadWait = window.requestAnimationFrame(check);
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() : "";
4377
4493
  };
4378
- const read = () => {
4379
- try {
4380
- const page = frame2.contentWindow;
4381
- const doc = frame2.contentDocument;
4382
- if (page && doc && doc !== watched) {
4383
- query?.removeEventListener("change", read);
4384
- query = page.matchMedia("(prefers-color-scheme: dark)");
4385
- query.addEventListener("change", read);
4386
- page.addEventListener("scroll", onScroll, { passive: true });
4387
- watched = doc;
4388
- }
4389
- const now = page?.location.href ?? "";
4390
- if (now !== href) {
4391
- href = now;
4392
- step({ type: "navigate" });
4393
- }
4394
- } catch {
4395
- query = null;
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));
4396
4546
  }
4397
- if (!busy || !look)
4398
- look = readLook(frame2);
4399
- draw();
4400
- };
4401
- const browser = {
4402
- show(next) {
4403
- view = next;
4404
- if (next.bars && !layer.isConnected)
4405
- glass.append(layer);
4406
- if (!next.bars)
4407
- layer.remove();
4408
- place(layer, 0, 0, next.size.width, next.size.height);
4409
- layer.style.transform = next.zoom === 1 ? "" : `scale(${next.zoom})`;
4410
- draw();
4411
- },
4412
- refresh() {
4413
- if (!view)
4414
- return;
4415
- const again = view.bars ? read : () => {
4416
- if (!busy || !look)
4417
- look = readLook(frame2);
4418
- back();
4419
- };
4420
- again();
4421
- clearTimeout(later);
4422
- later = window.setTimeout(again, RESTYLE);
4423
- },
4424
- minimized: () => motion.minimized,
4425
- page: () => applied,
4426
- startLoading,
4427
- stopLoading,
4428
- look: () => look,
4429
- remove() {
4430
- clearTimeout(later);
4431
- if (loadWait)
4432
- window.cancelAnimationFrame(loadWait);
4433
- loadWait = 0;
4434
- clearTimeout(shrinking);
4435
- query?.removeEventListener("change", read);
4436
- try {
4437
- frame2.contentWindow?.removeEventListener("scroll", onScroll);
4438
- } catch {}
4439
- query = null;
4440
- watched = null;
4441
- layer.remove();
4442
- blank.remove();
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;
4443
4555
  }
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);
4560
+ }
4561
+ return css;
4444
4562
  };
4445
- 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;
4446
4581
  }
4447
4582
 
4448
- // src/engine/fit.ts
4449
- var STRIP_TOP = 8;
4450
- var STRIP = 24 + STRIP_TOP;
4451
- var MARGIN = 24;
4452
- var BARE = { top: 0, right: 0, bottom: 0, left: 0 };
4453
- function hasStrip(knobs2) {
4454
- const sized = typeof knobs2.width === "number" || typeof knobs2.height === "number";
4455
- return sized || knobs2.zoom !== "fit";
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;
4456
4594
  }
4457
- function margin(size) {
4458
- return Math.min(MARGIN, size / 4);
4595
+ function clear(color) {
4596
+ return color === "" || color === "transparent" || /^rgba\(.*,\s*0\)$/.test(color);
4459
4597
  }
4460
- function fit(knobs2, size, options = {}) {
4461
- const { frameZoom = 1, aside = 0, side = "right", mock = BARE } = options;
4462
- const room = {
4463
- width: size.width,
4464
- height: Math.max(0, size.height - (hasStrip(knobs2) ? STRIP : 0))
4465
- };
4466
- const sized = typeof knobs2.width === "number";
4467
- const width = typeof knobs2.width === "number" ? knobs2.width : room.width;
4468
- const x = sized ? margin(room.width) : 0;
4469
- const y = typeof knobs2.height === "number" ? margin(room.height) : 0;
4470
- const sides = { width: mock.left + mock.right, height: mock.top + mock.bottom };
4471
- const across = width > 0 && room.width > 0 ? (room.width - 2 * x) / (width + sides.width) : 1;
4472
- const tall = typeof knobs2.height === "number" && knobs2.height > 0 && room.height > 0;
4473
- const upright = (room.height - 2 * y) / (Number(knobs2.height) + sides.height);
4474
- const whole = Math.min(1, across, tall ? upright : 1);
4475
- const height = typeof knobs2.height === "number" ? knobs2.height : room.height / whole;
4476
- const outer = { width: width + sides.width, height: height + sides.height };
4477
- const covered = sized && aside > 0 && aside <= room.width / 2 && (room.width + outer.width * whole) / 2 + x > room.width - aside;
4478
- const fitted = covered ? Math.min(whole, (room.width - aside - 2 * x) / outer.width) : whole;
4479
- const scale = knobs2.zoom === "fit" ? fitted : knobs2.zoom;
4480
- const beside = knobs2.zoom === "fit" && covered ? aside : 0;
4481
- const before = side === "left" ? beside : 0;
4482
- return {
4483
- width,
4484
- height,
4485
- zoom: frameZoom,
4486
- scale,
4487
- fit: fitted,
4488
- transform: scale / frameZoom,
4489
- box: { width: outer.width * scale + 2 * x + beside, height: outer.height * scale + 2 * y },
4490
- left: x + mock.left * scale + before,
4491
- top: y + mock.top * scale
4492
- };
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;
4493
4609
  }
4494
- function origin(place2, room) {
4495
- return {
4496
- x: Math.max(0, (room.width - place2.box.width) / 2) + place2.left,
4497
- y: Math.max(0, (room.height - place2.box.height) / 2) + place2.top
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) };
4498
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();
4499
4646
  }
4500
- function label(place2, knobs2, page = place2) {
4501
- const name = formOf(knobs2.device, knobs2.posture)?.label;
4502
- let text = name ? `${name} · ${page.width}` : String(page.width);
4503
- if (typeof knobs2.height === "number")
4504
- text += ` × ${page.height}`;
4505
- if (typeof knobs2.dpr === "number")
4506
- text += ` · ${knobs2.dpr}x`;
4507
- return text;
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);
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;
4508
4762
  }
4509
-
4510
- // src/engine/mat.ts
4511
- function colorRules() {
4512
- return MAT_COLOR_NAMES.map((name) => {
4513
- const paint = MAT_COLORS[name];
4514
- return `[data-mat="${name}"] { --mat: ${matGradient(paint.srgb)}; --mat-p3: ${matGradient(paint.p3)}; --mat-line: ${paint.line}; }`;
4515
- }).join(`
4516
- `);
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();
4517
4770
  }
4518
- var MAT_CSS = `
4519
- ${colorRules()}
4520
- .mat {
4521
- position: absolute;
4522
- top: 0;
4523
- left: 0;
4524
- width: 100%;
4525
- height: 100%;
4526
- pointer-events: none;
4527
- fill: var(--mat-line);
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;
4528
4777
  }
4529
- .mat .cell { opacity: 0.07; }
4530
- .mat .major { opacity: 0.14; }
4531
- .mat .span { opacity: 0.26; }
4532
- .mat .angle { fill: none; stroke: var(--mat-line); }
4533
- .mat .mark, .mat .tick { opacity: 0.55; }
4534
- .mat text {
4535
- font: 9px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
4536
- font-variant-numeric: tabular-nums;
4537
- opacity: 0.5;
4538
- }`;
4539
- var CELL = 10;
4540
- var MAJOR = 50;
4541
- var SPAN = 100;
4542
- var TICK = { cell: 3, major: 5, span: 9 };
4543
- var ANGLES = [15, 30, 45, 60, 75];
4544
- var GUIDE = { line: 0.15, half: 0.22 };
4545
- var ARC = 40;
4546
- var LABEL = { radius: 240, off: 3, top: 40, room: 24 };
4547
- var FOOT = 30;
4548
- var NUMBER = 24;
4549
- function ticks(length) {
4550
- const out = [];
4551
- for (let at = CELL;at < length; at += CELL) {
4552
- const size = at % SPAN === 0 ? TICK.span : at % MAJOR === 0 ? TICK.major : TICK.cell;
4553
- out.push({ at, size });
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 };
4554
4792
  }
4555
- return out;
4793
+ const kept3 = shots.get(doc) ?? new Map;
4794
+ kept3.set(key, canvas);
4795
+ shots.set(doc, kept3);
4556
4796
  }
4557
- function numbers(length, avoid) {
4558
- const out = [];
4559
- for (let at = SPAN;at + NUMBER <= length; at += SPAN) {
4560
- if (avoid && at + NUMBER > avoid.from && at < avoid.to)
4561
- continue;
4562
- out.push(at);
4563
- }
4564
- return out;
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
+ });
4565
4814
  }
4566
- function lines(across, length, hair) {
4567
- return across.map((at) => `M${at} 0h${hair}v${length}h${-hair}ZM0 ${at}h${length}v${hair}h${-length}Z`).join("");
4815
+ function blurMargin(coarse2) {
4816
+ return Math.ceil(2 * coarse2);
4568
4817
  }
4569
- function vertex(height) {
4570
- const y = Math.floor((height - FOOT) / SPAN) * SPAN;
4571
- 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) };
4572
4821
  }
4573
- function direction(angle) {
4574
- const turn2 = angle * Math.PI / 180;
4575
- return { x: Math.cos(turn2), y: -Math.sin(turn2) };
4822
+ function spend(canvas) {
4823
+ canvas.width = 0;
4824
+ canvas.height = 0;
4576
4825
  }
4577
- function exit(from, angle, size) {
4578
- const step = direction(angle);
4579
- const toTop = step.y < 0 ? from.y / -step.y : Infinity;
4580
- const toRight = step.x > 0 ? (size.width - from.x) / step.x : Infinity;
4581
- if (toTop <= toRight)
4582
- return { x: from.x + toTop * step.x, y: 0 };
4583
- return { x: size.width, y: from.y + toRight * step.y };
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;
4584
4853
  }
4585
- function along(from, angle, radius, off = 0) {
4586
- const step = direction(angle);
4587
- return { x: from.x + radius * step.x + off * step.y, y: from.y + radius * step.y - off * step.x };
4854
+ function blankUrl(width, height) {
4855
+ return svgUrl(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"/>`);
4588
4856
  }
4589
- function drawMat(size, hair, avoid, bleed = { left: 0, right: 0 }) {
4590
- const svg = svgNode("svg", { class: "mat", "aria-hidden": "true" });
4591
- const sheet = svgNode("g", { transform: `translate(${bleed.left} 0)` });
4592
- const half = SPAN / 2;
4593
- const minor = [];
4594
- for (let at = CELL;at < SPAN; at += CELL)
4595
- if (at !== half)
4596
- minor.push(at);
4597
- const arm = 6;
4598
- const pattern = svgNode("pattern", {
4599
- id: "mat-grid",
4600
- x: -half,
4601
- y: -half,
4602
- width: SPAN,
4603
- height: SPAN,
4604
- patternUnits: "userSpaceOnUse"
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));
4605
4870
  });
4606
- pattern.append(svgNode("path", { class: "cell", d: lines(minor, SPAN, hair) }), svgNode("path", { class: "major", d: lines([0], SPAN, hair) }), svgNode("path", { class: "span", d: lines([half], SPAN, hair) }), svgNode("path", {
4607
- class: "mark",
4608
- d: `M${half - arm} ${half}h${2 * arm + hair}v${hair}h${-2 * arm - hair}Z` + `M${half} ${half - arm}h${hair}v${2 * arm + hair}h${-hair}Z`
4609
- }));
4610
- const defs = svgNode("defs", {});
4611
- defs.append(pattern);
4612
- const top = ticks(size.width).map((tick) => `M${tick.at} 0h${hair}v${tick.size}h${-hair}Z`).join("");
4613
- const left = ticks(size.height).map((tick) => `M0 ${tick.at}h${tick.size}v${hair}h${-tick.size}Z`).join("");
4614
- sheet.append(svgNode("rect", {
4615
- x: -bleed.left,
4616
- width: bleed.left + size.width + bleed.right,
4617
- height: "100%",
4618
- fill: "url(#mat-grid)"
4619
- }), svgNode("path", { class: "tick", d: top + left }));
4620
- svg.append(defs, sheet);
4621
- const origin2 = vertex(size.height);
4622
- if (origin2) {
4623
- const base = along(origin2, 0, ARC);
4624
- const rim = { x: origin2.x, y: origin2.y - ARC };
4625
- const arc = svgNode("path", {
4626
- class: "angle",
4627
- d: `M${base.x} ${base.y}A${ARC} ${ARC} 0 0 0 ${rim.x} ${rim.y}`,
4628
- "stroke-width": hair
4629
- });
4630
- arc.style.opacity = String(GUIDE.line);
4631
- sheet.append(arc);
4632
- for (const angle of ANGLES) {
4633
- const start = along(origin2, angle, ARC);
4634
- const end = exit(origin2, angle, size);
4635
- const line = svgNode("path", {
4636
- class: "angle",
4637
- d: `M${start.x} ${start.y}L${end.x} ${end.y}`,
4638
- "stroke-width": hair
4639
- });
4640
- line.style.opacity = String(angle === 45 ? GUIDE.half : GUIDE.line);
4641
- sheet.append(line);
4642
- const reach = Math.hypot(end.x - origin2.x, end.y - origin2.y);
4643
- const at = along(origin2, angle, LABEL.radius, LABEL.off);
4644
- if (reach < LABEL.radius + LABEL.room || at.y < LABEL.top)
4645
- continue;
4646
- const text = svgNode("text", {
4647
- x: at.x,
4648
- y: at.y,
4649
- transform: `rotate(${-angle} ${at.x} ${at.y})`
4650
- });
4651
- text.textContent = `${angle}°`;
4652
- sheet.append(text);
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", "");
4893
+ }
4894
+ }
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);
4653
4933
  }
4934
+ try {
4935
+ if (over2)
4936
+ drawMedia(over2.pen, media, rect, view.getComputedStyle(node));
4937
+ } catch {}
4654
4938
  }
4655
- for (const at of numbers(size.width, avoid)) {
4656
- const text = svgNode("text", { x: at + 3, y: TICK.span + 1 });
4657
- text.textContent = String(at);
4658
- sheet.append(text);
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;
4659
4953
  }
4660
- for (const at of numbers(size.height)) {
4661
- const text = svgNode("text", { x: TICK.span + 2, y: at, "dominant-baseline": "middle" });
4662
- text.textContent = String(at);
4663
- sheet.append(text);
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);
4664
4966
  }
4665
- return svg;
4967
+ return canvas;
4666
4968
  }
4667
4969
 
4668
- // src/engine/foldgl.ts
4669
- function screenLook(open, wedge, free = 1, shaded = null, pane = shaded ?? "inner") {
4670
- const blurred = blurOn();
4671
- const [, wipe, area, far] = shaded ? shadeOf(shaded, open, free) : [1, 0, 0, 0];
4672
- return {
4673
- peak: blurred ? turnBlur(open, pane) : 0,
4674
- edge: blurred ? [tune.edgeHinge * wedge, tune.edgeFree * wedge] : [0, 0],
4675
- free,
4676
- dark: shadesOn() ? freeDepth(open) : 0,
4677
- lit: [wipe, area, far]
4678
- };
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;
4679
4977
  }
4680
- var WEIGHTS = [0.375, 0.25, 0.0625];
4681
- function wedgeOf(window2, pane, picture, span) {
4682
- const { top, bottom } = darkAt(window2, pane, picture);
4683
- return picture.height > 0 ? Math.max(top, bottom) * span / picture.height : 0;
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;
4684
4985
  }
4685
- function freeOf(window2, pane, picture) {
4686
- if (picture.width <= 0)
4687
- return 1;
4688
- const [a, b, c, d] = window2;
4689
- const seen = pane === "inner" ? picture.x + picture.width - (a[0] + d[0]) / 2 : (b[0] + c[0]) / 2 - picture.x;
4690
- return Math.min(1, Math.max(0, seen / picture.width));
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;
4691
4995
  }
4692
- function reachOf(shots, pane) {
4693
- let most = 0;
4694
- for (const shot of shots.frames) {
4695
- if (shotPane(shots, shot) !== pane)
4696
- continue;
4697
- const quad = shotQuad(shot, pane);
4698
- const picture = shotPicture(shots, pane, quad);
4699
- most = Math.max(most, wedgeOf(shotWindow(quad, pane, picture), pane, picture, 1));
4700
- }
4701
- return most;
4996
+ function showsBand(bars, look) {
4997
+ if (!bars || bars.platform !== "safari" || !bars.status && !bars.column)
4998
+ return false;
4999
+ return !!look && !look.footer;
4702
5000
  }
4703
- function canvasRect(place2) {
4704
- const { across, part, stage, margin: margin2 } = place2;
4705
- return across ? { x: part.x, y: -margin2, width: part.width, height: stage.height + 2 * margin2 } : { x: -margin2, y: part.y, width: stage.width + 2 * margin2, height: part.height };
5001
+ function bandShift(scrollY, innerHeight, scale) {
5002
+ return -(scrollY + innerHeight) * scale;
4706
5003
  }
4707
- function hingeLine(pane, across, part) {
4708
- const { x, y, width, height } = part;
4709
- if (across)
4710
- return pane === "inner" ? [-1 / width, 0, (x + width) / width] : [1 / width, 0, -x / width];
4711
- return pane === "inner" ? [0, 1 / height, -y / height] : [0, -1 / height, (y + height) / height];
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`);
4712
5007
  }
4713
- function contextOf(canvas) {
4714
- 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)
4715
5012
  return null;
4716
- const gl = canvas.getContext("webgl2", {
4717
- alpha: false,
4718
- antialias: false,
4719
- depth: false,
4720
- stencil: false,
4721
- premultipliedAlpha: false,
4722
- powerPreference: "low-power"
4723
- });
4724
- return gl instanceof WebGL2RenderingContext ? gl : null;
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
+ };
4725
5174
  }
4726
- var VERTEX = `#version 300 es
4727
- in vec2 corner;
4728
- uniform vec4 view;
4729
- out vec2 pos;
4730
- void main() {
4731
- pos = view.xy + corner * view.zw;
4732
- gl_Position = vec4(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0, 0.0, 1.0);
4733
- }`;
4734
- var FRAGMENT = `#version 300 es
4735
- precision highp float;
4736
- uniform sampler2D page;
4737
- uniform vec2 stage;
4738
- uniform vec2 along;
4739
- uniform vec3 line;
4740
- uniform float peak;
4741
- uniform vec2 edge;
4742
- uniform float free;
4743
- uniform float dark;
4744
- uniform vec2 shape;
4745
- uniform vec2 rimmed;
4746
- uniform vec3 band;
4747
- uniform vec3 lit;
4748
- uniform vec2 run;
4749
- uniform vec3 wiped;
4750
- uniform vec2 soften;
4751
- uniform float grain;
4752
- uniform float px;
4753
- in vec2 pos;
4754
- out vec4 color;
4755
- const float WEIGHTS[3] = float[3](${WEIGHTS.join(", ")});
4756
- float cover(float at, float span, float soft) {
4757
- return smoothstep(-soft, soft, at) * (1.0 - smoothstep(span - soft, span + soft, at));
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;
4758
5192
  }
4759
- float shadow(float t) {
4760
- if (dark <= 0.0) return 1.0;
4761
- float across = t / max(free, 0.001);
4762
- float deep = band.z * smoothstep(band.x, 1.0, across) + (1.0 - band.z) * smoothstep(1.0 - band.y, 1.0, across);
4763
- return 1.0 - dark * deep;
5193
+ .browser > *,
5194
+ .browser > * > *,
5195
+ .browser .group > * {
5196
+ position: absolute;
5197
+ box-sizing: border-box;
4764
5198
  }
4765
- float shade(float t) {
4766
- if (lit.x + lit.y + lit.z <= 0.0) return 1.0;
4767
- float uv = run.x + run.y * t;
4768
- float off = abs(uv - wiped.x);
4769
- float wipe = 1.0 - clamp(smoothstep(wiped.y, wiped.z, off) * lit.x, 0.0, 1.0);
4770
- float soft = 1.0 - smoothstep(0.9, 1.3, clamp((off - soften.x) / (soften.y - soften.x) * lit.y, 0.0, 4.0 / 3.0));
4771
- float away = mix(1.0, smoothstep(0.05, 0.5, uv), lit.z);
4772
- return pow(clamp(wipe * soft * soft * away, 0.0, 1.0), 1.0 / 2.2);
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
+ }
4773
5224
  }
4774
- vec4 shaded(vec3 rgb, float t) {
4775
- float speck = 0.0;
4776
- if (grain > 0.0 && dark + lit.x + lit.y + lit.z > 0.0) {
4777
- speck = (fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5) * grain / 255.0;
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)];
4778
5239
  }
4779
- return vec4(rgb * shadow(t) * shade(min(t, free)) + speck, 1.0);
5240
+ return base;
4780
5241
  }
4781
- float seen(vec2 at, float soft) {
4782
- float reach = soft * length(line.xy);
4783
- return cover(dot(along, at), dot(along, stage), soft) * (1.0 - smoothstep(free - reach, free + reach, dot(line.xy, at) + line.z));
5242
+ function rgbOf(color) {
5243
+ return `rgb(${Math.round(color.red)}, ${Math.round(color.green)}, ${Math.round(color.blue)})`;
4784
5244
  }
4785
- void main() {
4786
- vec2 texels = vec2(textureSize(page, 0)) / stage;
4787
- vec2 right = dFdx(pos) * texels;
4788
- vec2 down = dFdy(pos) * texels;
4789
- float sharp = 0.5 * log2(max(1.0, max(dot(right, right), dot(down, down))));
4790
- float t = clamp(dot(line.xy, pos) + line.z, 0.0, 1.0);
4791
- float span = dot(along, stage);
4792
- float at = dot(along, pos);
4793
- float across = free > 0.0 ? min(1.0, t / free) : 1.0;
4794
- float wide = peak * (shape.x + (1.0 - shape.x) * pow(across, shape.y));
4795
- float rim = mix(edge.x, edge.y, t);
4796
- if (rim > 0.0) wide = max(wide, rim * (1.0 - smoothstep(0.0, rimmed.x * rim, min(at, span - at))));
4797
- float gap = rimmed.y * wide;
4798
- float soft = max(0.5 * px, 0.75 * gap);
4799
- float lod = max(sharp, log2(max(1.0, gap * max(texels.x, texels.y))));
4800
- vec3 sum = vec3(0.0);
4801
- if (peak + edge.x + edge.y <= 0.0) {
4802
- sum = textureLod(page, pos / stage, lod).rgb * seen(pos, soft);
4803
- } else {
4804
- for (int y = -2; y <= 2; y++) {
4805
- for (int x = -2; x <= 2; x++) {
4806
- vec2 tap = pos + vec2(float(x), float(y)) * gap;
4807
- float weight = WEIGHTS[abs(x)] * WEIGHTS[abs(y)];
4808
- sum += textureLod(page, tap / stage, lod).rgb * seen(tap, soft) * weight;
4809
- }
4810
- }
4811
- }
4812
- color = shaded(sum, t);
4813
- }`;
4814
- function compile(gl, kind, source) {
4815
- const shader = gl.createShader(kind);
4816
- if (!shader)
4817
- return null;
4818
- gl.shaderSource(shader, source);
4819
- gl.compileShader(shader);
4820
- return shader;
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)];
4821
5248
  }
4822
- function firstLine(log, otherwise) {
4823
- return log?.trim().split(`
4824
- `)[0]?.trim() || otherwise;
5249
+ function rgbText([r, g, b]) {
5250
+ return `rgb(${r}, ${g}, ${b})`;
4825
5251
  }
4826
- function uploadWhy(error) {
4827
- const name = error instanceof Error ? error.name : String(error);
4828
- const tainted = "the browser holds the picture as another origin's, as one with a picture, video or canvas from another origin drawn in, or a drawing of the page this browser does not trust";
4829
- return `the picture could not be uploaded: ${name}${name === "SecurityError" ? `, ${tainted}` : ""}`;
5252
+ function paintOf(view, node) {
5253
+ const color = toRgb(view.getComputedStyle(node).backgroundColor);
5254
+ return color && color.alpha > 0 ? color : null;
4830
5255
  }
4831
- function screenGl(place2, refused) {
4832
- const canvas = document.createElement("canvas");
4833
- const gl = contextOf(canvas);
4834
- if (!gl) {
4835
- refused(typeof WebGL2RenderingContext === "undefined" ? "this browser has no WebGL2" : "the canvas gave no WebGL2 context", null);
4836
- return null;
5256
+ function solidOf(view, node) {
5257
+ const color = paintOf(view, node);
5258
+ return color && color.alpha >= 0.5 ? color : null;
5259
+ }
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;
4837
5272
  }
4838
- const rect = canvasRect(place2);
4839
- const most = Math.max(1, gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) || 4096);
4840
- const density2 = Math.min(place2.density, most / rect.width, most / rect.height);
4841
- canvas.width = Math.max(1, Math.round(rect.width * density2));
4842
- canvas.height = Math.max(1, Math.round(rect.height * density2));
4843
- canvas.style.position = "absolute";
4844
- canvas.style.display = "block";
4845
- canvas.style.left = `${rect.x}px`;
4846
- canvas.style.top = `${rect.y}px`;
4847
- canvas.style.width = `${rect.width}px`;
4848
- canvas.style.height = `${rect.height}px`;
4849
- const vertex2 = compile(gl, gl.VERTEX_SHADER, VERTEX);
4850
- const fragment = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);
4851
- const program = gl.createProgram();
4852
- const corners = gl.createBuffer();
4853
- const texture = gl.createTexture();
4854
- const free = () => {
4855
- gl.deleteTexture(texture);
4856
- gl.deleteBuffer(corners);
4857
- gl.deleteProgram(program);
4858
- gl.deleteShader(vertex2);
4859
- gl.deleteShader(fragment);
4860
- gl.getExtension("WEBGL_lose_context")?.loseContext();
4861
- canvas.remove();
4862
- };
4863
- if (!vertex2 || !fragment || !program || !corners || !texture) {
4864
- const why = gl.isContextLost() ? "the WebGL2 context was lost as it was made" : "WebGL2 made no shader, program, buffer or texture";
4865
- free();
4866
- refused(why, null);
4867
- return null;
5273
+ return null;
5274
+ }
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;
4868
5293
  }
4869
- gl.attachShader(program, vertex2);
4870
- gl.attachShader(program, fragment);
4871
- gl.linkProgram(program);
4872
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
4873
- const log = [vertex2, fragment].map((shader) => gl.getShaderInfoLog(shader)).find((said) => said?.trim()) ?? gl.getProgramInfoLog(program);
4874
- const lost = gl.isContextLost();
4875
- free();
4876
- refused(lost ? "the WebGL2 context was lost as it was made" : `the shader did not compile or link: ${firstLine(log, "no reason given")}`, null);
5294
+ if (layers.length === 0)
4877
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
+ header: false,
5305
+ footer: false,
5306
+ under: [],
5307
+ dark: false,
5308
+ scheme: "light",
5309
+ host: "",
5310
+ canBack: false,
5311
+ canForward: false
5312
+ };
5313
+ try {
5314
+ const view = frame2.contentWindow;
5315
+ const doc = frame2.contentDocument;
5316
+ if (!view || !doc?.documentElement)
5317
+ return fallback;
5318
+ const scheme = view.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
5319
+ const base = backgroundOf(doc, view, scheme === "dark");
5320
+ const [r, g, b] = base;
5321
+ const background = rgbText(base);
5322
+ const header = edgeBar(doc, view, "top", base);
5323
+ const top = header ?? background;
5324
+ const last = () => colorAt(doc, view, view.innerWidth / 2, view.innerHeight - 1, base);
5325
+ const footer = edgeBar(doc, view, "bottom", base);
5326
+ const bottom = footer ?? last() ?? background;
5327
+ const under = (probe?.points ?? []).map(({ x, y }) => {
5328
+ const { page } = probe ?? { page: { x: 0, y: 0, width: 0, height: 0 } };
5329
+ const inside = { x: x - page.x, y: y - page.y };
5330
+ if (inside.y < 0)
5331
+ return { x, y, color: top };
5332
+ if (inside.x < 0 || inside.x >= page.width)
5333
+ return { x, y, color: background };
5334
+ if (inside.y >= page.height)
5335
+ return { x, y, color: bottom };
5336
+ const across = Math.min(Math.max(inside.x, 0), page.width - 1);
5337
+ return { x, y, color: colorAt(doc, view, across, inside.y, base) ?? background };
5338
+ });
5339
+ const navigation = navigationOf(view);
5340
+ const can = (key) => {
5341
+ const value = navigation && Reflect.get(navigation, key);
5342
+ return typeof value === "boolean" ? value : null;
5343
+ };
5344
+ return {
5345
+ background,
5346
+ top,
5347
+ bottom,
5348
+ header: header !== null,
5349
+ footer: footer !== null,
5350
+ under,
5351
+ dark: luminance(r, g, b) < 0.4,
5352
+ scheme,
5353
+ host: view.location.host,
5354
+ canBack: can("canGoBack") ?? view.history.length > 1,
5355
+ canForward: can("canGoForward") ?? false
5356
+ };
5357
+ } catch {
5358
+ return fallback;
4878
5359
  }
4879
- gl.useProgram(program);
4880
- gl.bindBuffer(gl.ARRAY_BUFFER, corners);
4881
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
4882
- const corner = gl.getAttribLocation(program, "corner");
4883
- gl.enableVertexAttribArray(corner);
4884
- gl.vertexAttribPointer(corner, 2, gl.FLOAT, false, 0, 0);
4885
- const at = (name) => gl.getUniformLocation(program, name);
4886
- const { stage } = place2;
4887
- gl.uniform4f(at("view"), rect.x, rect.y, rect.width, rect.height);
4888
- gl.uniform2f(at("stage"), stage.width, stage.height);
4889
- gl.uniform2f(at("along"), place2.across ? 0 : 1, place2.across ? 1 : 0);
4890
- gl.uniform3f(at("line"), ...hingeLine(place2.pane, place2.across, place2.part));
4891
- gl.uniform1f(at("px"), canvas.width > 0 ? rect.width / canvas.width : 1);
4892
- gl.uniform1i(at("page"), 0);
4893
- const wipe = WIPE[place2.pane];
4894
- gl.uniform2f(at("run"), uvOf(place2.pane, 0), uvOf(place2.pane, 1) - uvOf(place2.pane, 0));
4895
- gl.uniform3f(at("wiped"), wipe.at, wipe.shade[0], wipe.shade[1]);
4896
- gl.uniform2f(at("soften"), wipe.blur[0], wipe.blur[1]);
4897
- const uniforms = { peak: at("peak"), edge: at("edge"), free: at("free"), dark: at("dark"), shape: at("shape"), rimmed: at("rimmed"), band: at("band"), lit: at("lit"), grain: at("grain") };
4898
- gl.bindTexture(gl.TEXTURE_2D, texture);
4899
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
4900
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
4901
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
4902
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
4903
- gl.viewport(0, 0, canvas.width, canvas.height);
4904
- const widest = gl.getParameter(gl.MAX_TEXTURE_SIZE) || 2048;
4905
- let shot = null;
5360
+ }
5361
+ function screenFill(look, bars, page, height) {
5362
+ const strip = bars.status || bars.column || !runsUnderBars(bars.screen.id);
5363
+ if (bars.platform !== "safari" || !strip || !page)
5364
+ return look.background;
5365
+ const held = look.top !== look.background;
5366
+ const top = bars.scrim && !held ? rgbOf(underAt(look, bars.scrim.at.x, bars.scrim.at.y)) : look.top;
5367
+ if (top === look.background && look.bottom === look.background)
5368
+ return look.background;
5369
+ const start = page.y / height * 100;
5370
+ const end = (page.y + page.height) / height * 100;
5371
+ const { background: middle, bottom } = look;
5372
+ const strips = `linear-gradient(to bottom, ${top} ${start}%, ${middle} ${start}%, ${middle} ${end}%, ${bottom} ${end}%)`;
5373
+ const W = turn(bars.screen, bars.orientation).width;
5374
+ const [left, right] = [page.x / W * 100, (page.x + page.width) / W * 100];
5375
+ if (left <= 0 && right >= 100)
5376
+ return strips;
5377
+ const column = `linear-gradient(to right, ${middle} ${left}%, transparent ${left}%, transparent ${right}%, ${middle} ${right}%)`;
5378
+ return `${column}, ${strips}`;
5379
+ }
5380
+ function reaches(frame2) {
5381
+ try {
5382
+ return !!frame2.contentDocument?.documentElement;
5383
+ } catch {
5384
+ return false;
5385
+ }
5386
+ }
5387
+ var RESTYLE = 120;
5388
+ var LOAD_WAIT = 5000;
5389
+ function same(a, b) {
5390
+ return JSON.stringify(a) === JSON.stringify(b);
5391
+ }
5392
+ function createBrowser(glass, frame2, onChange, onReload = () => {}, ready = () => true) {
5393
+ const blank = el("div", "screenblank");
5394
+ blank.hidden = true;
5395
+ glass.append(blank);
5396
+ const band = createUnderbar(glass, frame2);
5397
+ const layer = el("div", "browser");
5398
+ layer.setAttribute("aria-hidden", "true");
5399
+ const seams = [el("div", "seam"), el("div", "seam")];
5400
+ for (const seam of seams) {
5401
+ seam.setAttribute("aria-hidden", "true");
5402
+ seam.style.cssText = "position:absolute;pointer-events:none";
5403
+ seam.hidden = true;
5404
+ }
5405
+ let view = null;
4906
5406
  let look = null;
4907
- let gone = false;
4908
- const draw = (next) => {
5407
+ let painted = null;
5408
+ let built = "";
5409
+ let applied = null;
5410
+ let shrinking = 0;
5411
+ let shrinkTo = null;
5412
+ let later = 0;
5413
+ let query = null;
5414
+ let watched2 = null;
5415
+ let href = "";
5416
+ let motion = BARS_START;
5417
+ let landed = false;
5418
+ let busy = false;
5419
+ let loadWait = 0;
5420
+ let sampling = 0;
5421
+ const still2 = () => baseMatchMedia("(prefers-reduced-motion: reduce)").matches;
5422
+ const step = (event) => {
5423
+ const before = motion.minimized;
5424
+ motion = barsStep(motion, event);
5425
+ if (motion.minimized !== before)
5426
+ queueMicrotask(onChange);
5427
+ };
5428
+ const probe = () => {
5429
+ const bars = view?.bars ?? null;
5430
+ if (!view || !bars || bars.platform !== "safari")
5431
+ return null;
5432
+ const { screen, orientation, layout, minimized, edge } = bars;
5433
+ const other = barsOf(screen, orientation, layout, !minimized, edge);
5434
+ const shapes = [...bars.shapes, ...other?.shapes ?? []];
5435
+ const points = shapes.map((shape) => ({
5436
+ x: shape.x + shape.width / 2,
5437
+ y: shape.y + shape.height / 2
5438
+ }));
5439
+ const scrim = bars.scrim ?? other?.scrim;
5440
+ if (scrim)
5441
+ points.push(scrim.at);
5442
+ return { page: view.page ?? { x: 0, y: 0, ...view.size }, points };
5443
+ };
5444
+ const lookNow = () => readLook(frame2, probe());
5445
+ const placeBand = () => {
5446
+ const bars = view?.bars ?? null;
5447
+ const shown2 = view && showsBand(bars, look) && reaches(frame2) ? bandRect(applied, view.size.height) : null;
5448
+ band.show(shown2, view?.zoom ?? 1, look);
5449
+ placeSeams();
5450
+ };
5451
+ const placeSeams = () => {
5452
+ const ratio = glass.offsetWidth > 0 ? glass.getBoundingClientRect().width / glass.offsetWidth : 1;
5453
+ const unit = 1 / ((window.devicePixelRatio || 1) * (ratio || 1));
5454
+ const rects = look && reaches(frame2) ? seamRects(applied, view?.zoom ?? 1, unit, look) : { top: null, bottom: null };
5455
+ const colors = [look?.top ?? "", look?.bottom ?? ""];
5456
+ [rects.top, rects.bottom].forEach((rect, index) => {
5457
+ const seam = seams[index];
5458
+ if (!seam)
5459
+ return;
5460
+ seam.hidden = rect === null;
5461
+ if (!rect)
5462
+ return;
5463
+ if (!seam.isConnected)
5464
+ glass.insertBefore(seam, layer.isConnected ? layer : null);
5465
+ place(seam, rect.x, rect.y, rect.width, rect.height);
5466
+ seam.style.background = colors[index] ?? "";
5467
+ });
5468
+ };
5469
+ const resample = () => {
5470
+ sampling = 0;
5471
+ const bars = view?.bars;
5472
+ if (busy || !look || !view || !bars || bars.platform !== "safari")
5473
+ return;
5474
+ const next = lookNow();
5475
+ if (JSON.stringify(next) === JSON.stringify(look))
5476
+ return;
4909
5477
  look = next;
4910
- if (gone || !shot)
5478
+ glass.style.background = screenFill(look, bars, view.page, view.size.height);
5479
+ back();
5480
+ placeBand();
5481
+ painted?.apply(bars.minimized, look);
5482
+ };
5483
+ const growth = () => {
5484
+ const bars = view?.bars;
5485
+ if (!bars)
5486
+ return { room: 0, grow: 0 };
5487
+ const { screen, orientation, layout, edge } = bars;
5488
+ const [full, mini] = [false, true].map((minimized) => viewportOf(screen, orientation, layout, minimized, edge));
5489
+ if (!full || !mini)
5490
+ return { room: 0, grow: 0 };
5491
+ return { room: Math.max(0, full.y - mini.y), grow: Math.max(0, mini.height - full.height) };
5492
+ };
5493
+ const onScroll = () => {
5494
+ band.move();
5495
+ landed = false;
5496
+ const page = frame2.contentWindow;
5497
+ if (page) {
5498
+ const { room, grow } = growth();
5499
+ const tall = frame2.contentDocument?.documentElement?.scrollHeight;
5500
+ const rest = typeof tall === "number" ? tall - page.innerHeight - grow : Number.POSITIVE_INFINITY;
5501
+ step({ type: "scroll", y: page.scrollY, time: performance.now(), room, rest });
5502
+ }
5503
+ if (!sampling)
5504
+ sampling = window.requestAnimationFrame(resample);
5505
+ };
5506
+ const actions = {
5507
+ back: () => frame2.contentWindow?.history.back(),
5508
+ forward: () => frame2.contentWindow?.history.forward(),
5509
+ reload: () => {
5510
+ if (busy) {
5511
+ frame2.contentWindow?.stop();
5512
+ stopLoading();
5513
+ return;
5514
+ }
5515
+ onReload();
5516
+ keep(frame2.contentWindow, "frame");
5517
+ frame2.contentWindow?.location.reload();
5518
+ },
5519
+ expand: () => step({ type: "tap" })
5520
+ };
5521
+ const sizeFrame = () => {
5522
+ if (!view)
5523
+ return;
5524
+ const before = applied;
5525
+ view.sizeFrame();
5526
+ const page = view.page;
5527
+ if (!same(page, applied))
5528
+ step({ type: "resize", time: performance.now() });
5529
+ applied = page;
5530
+ const moved2 = before && page && before.y !== page.y && before.x === page.x && before.width === page.width;
5531
+ if (moved2) {
5532
+ const fresh2 = landed;
5533
+ landed = false;
5534
+ try {
5535
+ if (!fresh2)
5536
+ frame2.contentWindow?.scrollBy({ top: page.y - before.y, behavior: "instant" });
5537
+ } catch {}
5538
+ }
5539
+ placeBand();
5540
+ };
5541
+ const stopShrink = () => {
5542
+ clearTimeout(shrinking);
5543
+ shrinking = 0;
5544
+ shrinkTo = null;
5545
+ };
5546
+ const placeFrame = (instant) => {
5547
+ const page = view?.page ?? null;
5548
+ const shrinks = !instant && page && applied && page.height < applied.height && page.y === applied.y;
5549
+ if (shrinks && shrinking && same(page, shrinkTo))
5550
+ return;
5551
+ stopShrink();
5552
+ if (!shrinks) {
5553
+ sizeFrame();
5554
+ return;
5555
+ }
5556
+ shrinkTo = page;
5557
+ shrinking = window.setTimeout(() => {
5558
+ shrinking = 0;
5559
+ shrinkTo = null;
5560
+ if (same(view?.page ?? null, page))
5561
+ sizeFrame();
5562
+ }, MORPH.expand);
5563
+ };
5564
+ const back = () => {
5565
+ frame2.style.background = reaches(frame2) ? (look ??= lookNow()).background : "";
5566
+ };
5567
+ const draw = () => {
5568
+ const bars = view?.bars ?? null;
5569
+ if (!view || !bars) {
5570
+ stopShrink();
5571
+ layer.replaceChildren();
5572
+ glass.style.background = "";
5573
+ back();
5574
+ painted = null;
5575
+ built = "";
5576
+ if (view)
5577
+ sizeFrame();
5578
+ placeBand();
4911
5579
  return;
4912
- gl.uniform1f(uniforms.peak, next.peak);
4913
- gl.uniform2f(uniforms.edge, ...next.edge);
4914
- gl.uniform1f(uniforms.free, next.free);
4915
- gl.uniform1f(uniforms.dark, next.dark);
4916
- gl.uniform2f(uniforms.shape, tune.blurHinge, tune.blurRise);
4917
- gl.uniform2f(uniforms.rimmed, tune.edgeReach, tune.blurSpread);
4918
- gl.uniform3f(uniforms.band, tune.darkFrom, tune.darkBand, tune.darkBroad);
4919
- gl.uniform3f(uniforms.lit, ...next.lit);
4920
- gl.uniform1f(uniforms.grain, tune.grain);
4921
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
5580
+ }
5581
+ look ??= lookNow();
5582
+ glass.style.background = screenFill(look, bars, view.page, view.size.height);
5583
+ back();
5584
+ placeBand();
5585
+ const { platform, layout, screen, orientation, edge } = bars;
5586
+ const base = JSON.stringify([platform, layout, screen, orientation, edge, view.follow]);
5587
+ const fresh2 = base !== built || !painted;
5588
+ const instant = fresh2 || still2();
5589
+ if (fresh2) {
5590
+ const other = barsOf(screen, orientation, layout, !bars.minimized, edge);
5591
+ const full = bars.minimized ? other : bars;
5592
+ const mini = bars.minimized ? bars : other;
5593
+ const shown2 = { ...actions, expand: view.follow ? actions.expand : undefined };
5594
+ if (!full || !mini)
5595
+ return;
5596
+ painted = BUILDERS[bars.platform](full, mini, look, shown2);
5597
+ layer.replaceChildren(painted.root);
5598
+ built = base;
5599
+ if (busy)
5600
+ painted.loading?.(true, true);
5601
+ }
5602
+ if (instant)
5603
+ layer.setAttribute("data-instant", "");
5604
+ painted?.apply(bars.minimized, look);
5605
+ if (instant) {
5606
+ layer.offsetWidth;
5607
+ layer.removeAttribute("data-instant");
5608
+ }
5609
+ placeFrame(instant);
4922
5610
  };
4923
- canvas.addEventListener("webglcontextlost", () => {
4924
- if (gone)
5611
+ const pageOf = () => {
5612
+ try {
5613
+ return frame2.contentDocument;
5614
+ } catch {
5615
+ return null;
5616
+ }
5617
+ };
5618
+ const showLoading = (on, seed) => {
5619
+ busy = on;
5620
+ if (seed) {
5621
+ look = seed;
5622
+ draw();
5623
+ }
5624
+ painted?.loading?.(on, still2());
5625
+ if (!on)
5626
+ browser.refresh();
5627
+ };
5628
+ const stopLoading = () => {
5629
+ if (loadWait)
5630
+ window.cancelAnimationFrame(loadWait);
5631
+ loadWait = 0;
5632
+ if (!busy)
4925
5633
  return;
4926
- gone = true;
4927
- canvas.remove();
4928
- refused("the WebGL2 context was lost", shot);
4929
- });
4930
- const refuse = (why, next) => {
4931
- if (!gone)
4932
- free();
4933
- gone = true;
4934
- refused(why, next);
5634
+ blank.hidden = true;
5635
+ showLoading(false, null);
4935
5636
  };
4936
- return {
4937
- canvas,
4938
- paint(next) {
4939
- if (gone)
4940
- return refuse("the WebGL2 context is gone", next);
4941
- if (Math.max(next.width, next.height) > widest) {
4942
- return refuse(`the picture, ${next.width} by ${next.height} px, is larger than MAX_TEXTURE_SIZE, ${widest}`, next);
5637
+ const startLoading = (seed) => {
5638
+ blank.style.background = (seed ?? look ?? lookNow()).background;
5639
+ blank.hidden = false;
5640
+ showLoading(true, seed);
5641
+ if (loadWait)
5642
+ window.cancelAnimationFrame(loadWait);
5643
+ const end = performance.now() + LOAD_WAIT;
5644
+ const gone = pageOf();
5645
+ const check = () => {
5646
+ loadWait = 0;
5647
+ const next = gone === null || pageOf() !== gone;
5648
+ if (next && ready() || performance.now() >= end)
5649
+ stopLoading();
5650
+ else
5651
+ loadWait = window.requestAnimationFrame(check);
5652
+ };
5653
+ loadWait = window.requestAnimationFrame(check);
5654
+ };
5655
+ const read = () => {
5656
+ try {
5657
+ const page = frame2.contentWindow;
5658
+ const doc = frame2.contentDocument;
5659
+ const arrived = doc !== watched2;
5660
+ if (page && doc && doc !== watched2) {
5661
+ query?.removeEventListener("change", read);
5662
+ query = page.matchMedia("(prefers-color-scheme: dark)");
5663
+ query.addEventListener("change", read);
5664
+ page.addEventListener("scroll", onScroll, { passive: true });
5665
+ watched2 = doc;
4943
5666
  }
4944
- gl.getError();
4945
- try {
4946
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, next);
4947
- } catch (error) {
4948
- return refuse(uploadWhy(error), next);
5667
+ const now = page?.location.href ?? "";
5668
+ if (now !== href) {
5669
+ href = now;
5670
+ landed = arrived;
5671
+ step({ type: "navigate" });
4949
5672
  }
4950
- const failed = gl.getError();
4951
- if (failed !== gl.NO_ERROR)
4952
- return refuse(`the picture could not be uploaded: WebGL2 error 0x${failed.toString(16)}`, next);
4953
- gl.generateMipmap(gl.TEXTURE_2D);
4954
- shot = next;
4955
- if (look)
4956
- draw(look);
4957
- },
4958
- draw,
4959
- release() {
4960
- if (gone)
4961
- return;
4962
- gone = true;
4963
- free();
5673
+ } catch {
5674
+ query = null;
4964
5675
  }
5676
+ if (!busy || !look)
5677
+ look = lookNow();
5678
+ draw();
4965
5679
  };
4966
- }
4967
-
4968
- // src/engine/objectfit.ts
4969
- var MIDDLE = { share: 0.5, px: 0 };
4970
- function words(text) {
4971
- const parts = [];
4972
- let depth = 0;
4973
- let word = "";
4974
- for (const char of text.trim()) {
4975
- if (char === "(")
4976
- depth++;
4977
- if (char === ")")
4978
- depth--;
4979
- if (/\s/.test(char) && depth === 0) {
4980
- if (word)
4981
- parts.push(word);
4982
- word = "";
4983
- } else
4984
- word += char;
4985
- }
4986
- if (word)
4987
- parts.push(word);
4988
- return parts;
4989
- }
4990
- function offsetOf(word) {
4991
- const terms = Array.from(word.matchAll(/([+-])?\s*(\d*\.?\d+(?:e[+-]?\d+)?)(%|px)?/gi));
4992
- if (terms.length === 0 || !/^(calc\(.*\)|[+-]?[\d.]+(e[+-]?\d+)?(%|px)?)$/i.test(word))
4993
- return null;
4994
- const offset = { share: 0, px: 0 };
4995
- for (const [, sign, digits = "0", unit] of terms) {
4996
- const value = Number(digits) * (sign === "-" ? -1 : 1);
4997
- if (unit === "%")
4998
- offset.share += value / 100;
4999
- else
5000
- offset.px += value;
5001
- }
5002
- return offset;
5003
- }
5004
- function fromFar(offset) {
5005
- return { share: 1 - offset.share, px: 0 - offset.px };
5006
- }
5007
- function objectPosition(position) {
5008
- let x = null;
5009
- let y = null;
5010
- const plain = [];
5011
- const list = words(position.toLowerCase());
5012
- const counted = list.length > 2;
5013
- for (let at = 0;at < list.length; at++) {
5014
- const word = list[at] ?? "";
5015
- const next = offsetOf(list[at + 1] ?? "");
5016
- if (word === "left" || word === "right" || word === "top" || word === "bottom") {
5017
- const far = word === "right" || word === "bottom";
5018
- const edge = counted && next || { share: 0, px: 0 };
5019
- if (counted && next)
5020
- at++;
5021
- const offset = far ? fromFar(edge) : edge;
5022
- if (word === "left" || word === "right")
5023
- x = offset;
5024
- else
5025
- y = offset;
5026
- } else if (word === "center")
5027
- plain.push(MIDDLE);
5028
- else {
5029
- const offset = offsetOf(word);
5030
- if (offset)
5031
- plain.push(offset);
5032
- }
5033
- }
5034
- for (const offset of plain) {
5035
- if (!x)
5036
- x = offset;
5037
- else if (!y)
5038
- y = offset;
5039
- }
5040
- return [x ?? MIDDLE, y ?? MIDDLE];
5041
- }
5042
- function objectPlace(fit2, position, natural, box2) {
5043
- if (!(natural.width > 0 && natural.height > 0 && box2.width > 0 && box2.height > 0))
5044
- return null;
5045
- const across = box2.width / natural.width;
5046
- const down = box2.height / natural.height;
5047
- const whole = Math.min(across, down);
5048
- let size = { width: box2.width, height: box2.height };
5049
- const scaled = (scale) => ({ width: natural.width * scale, height: natural.height * scale });
5050
- if (fit2 === "contain")
5051
- size = scaled(whole);
5052
- else if (fit2 === "cover")
5053
- size = scaled(Math.max(across, down));
5054
- else if (fit2 === "none")
5055
- size = scaled(1);
5056
- else if (fit2 === "scale-down")
5057
- size = scaled(Math.min(1, whole));
5058
- const [x, y] = objectPosition(position);
5059
- const left = box2.x + (box2.width - size.width) * x.share + x.px;
5060
- const top = box2.y + (box2.height - size.height) * y.share + y.px;
5061
- const to = {
5062
- x: Math.max(left, box2.x),
5063
- y: Math.max(top, box2.y),
5064
- width: Math.min(left + size.width, box2.x + box2.width) - Math.max(left, box2.x),
5065
- height: Math.min(top + size.height, box2.y + box2.height) - Math.max(top, box2.y)
5680
+ const browser = {
5681
+ show(next) {
5682
+ view = next;
5683
+ if (next.bars && !layer.isConnected)
5684
+ glass.append(layer);
5685
+ for (const seam of seams)
5686
+ if (seam.isConnected)
5687
+ glass.insertBefore(seam, layer.isConnected ? layer : null);
5688
+ if (!next.bars)
5689
+ layer.remove();
5690
+ place(layer, 0, 0, next.size.width, next.size.height);
5691
+ layer.style.transform = next.zoom === 1 ? "" : `scale(${next.zoom})`;
5692
+ draw();
5693
+ },
5694
+ refresh() {
5695
+ if (!view)
5696
+ return;
5697
+ const again = view.bars ? read : () => {
5698
+ if (!busy || !look)
5699
+ look = lookNow();
5700
+ back();
5701
+ };
5702
+ again();
5703
+ band.refresh();
5704
+ clearTimeout(later);
5705
+ later = window.setTimeout(again, RESTYLE);
5706
+ },
5707
+ minimized: () => motion.minimized,
5708
+ page: () => applied,
5709
+ startLoading,
5710
+ stopLoading,
5711
+ look: () => look,
5712
+ remove() {
5713
+ clearTimeout(later);
5714
+ if (sampling)
5715
+ window.cancelAnimationFrame(sampling);
5716
+ sampling = 0;
5717
+ if (loadWait)
5718
+ window.cancelAnimationFrame(loadWait);
5719
+ loadWait = 0;
5720
+ stopShrink();
5721
+ query?.removeEventListener("change", read);
5722
+ try {
5723
+ frame2.contentWindow?.removeEventListener("scroll", onScroll);
5724
+ } catch {}
5725
+ query = null;
5726
+ watched2 = null;
5727
+ layer.remove();
5728
+ for (const seam of seams)
5729
+ seam.remove();
5730
+ blank.remove();
5731
+ band.remove();
5732
+ }
5066
5733
  };
5067
- if (!(to.width > 0 && to.height > 0))
5068
- return null;
5069
- const wide = natural.width / size.width;
5070
- const tall = natural.height / size.height;
5734
+ return browser;
5735
+ }
5736
+ function seamRects(page, zoom, unit, look) {
5737
+ if (!page)
5738
+ return { top: null, bottom: null };
5739
+ const x = page.x * zoom;
5740
+ const width = page.width * zoom;
5741
+ const edge = (y) => ({ x, y: y - 2 * unit, width, height: 4 * unit });
5071
5742
  return {
5072
- from: { x: (to.x - left) * wide, y: (to.y - top) * tall, width: to.width * wide, height: to.height * tall },
5073
- to
5743
+ top: look.header ? edge(page.y * zoom) : null,
5744
+ bottom: look.footer ? edge((page.y + page.height) * zoom) : null
5074
5745
  };
5075
5746
  }
5076
5747
 
5077
- // src/engine/pagefonts.ts
5078
- var kept2 = null;
5079
- var READ = /^(woff2?|truetype|opentype|collection)(-variations)?$/;
5080
- var URL_OF = /^url\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^)]*))\s*\)/i;
5081
- var CHUNK = 32768;
5082
- function cut(text, mark) {
5083
- const parts = [];
5084
- let depth = 0;
5085
- let quote = "";
5086
- let from = 0;
5087
- for (let at = 0;at < text.length; at++) {
5088
- const char = text[at];
5089
- if (char === "\\")
5090
- at++;
5091
- else if (quote)
5092
- quote = char === quote ? "" : quote;
5093
- else if (char === '"' || char === "'")
5094
- quote = char;
5095
- else if (char === "(")
5096
- depth++;
5097
- else if (char === ")")
5098
- depth--;
5099
- else if (char === mark && depth === 0) {
5100
- parts.push(text.slice(from, at));
5101
- from = at + 1;
5102
- }
5103
- }
5104
- parts.push(text.slice(from));
5105
- return parts;
5106
- }
5107
- function faceKey(family, weight, style, range) {
5108
- const name = family.trim().replace(/^(["'])(.*)\1$/, "$2").toLowerCase();
5109
- const plain = (value) => value.trim().toLowerCase().replace(/\s+/g, " ") || "normal";
5110
- const heavy = plain(weight).replace(/\bnormal\b/g, "400").replace(/\bbold\b/g, "700");
5111
- const chars = (range.trim() || "U+0-10FFFF").toLowerCase().split(",").map((part) => part.trim().replace(/^u\+/, "").split("-").map((end) => end.replace(/^0+(?=.)/, "")).join("-")).join(",");
5112
- return [name, heavy, plain(style), chars].join("|");
5113
- }
5114
- function base64(bytes) {
5115
- let text = "";
5116
- for (let at = 0;at < bytes.length; at += CHUNK)
5117
- text += String.fromCharCode(...bytes.subarray(at, at + CHUNK));
5118
- return btoa(text);
5748
+ // src/engine/fit.ts
5749
+ var STRIP_TOP = 8;
5750
+ var STRIP = 24 + STRIP_TOP;
5751
+ var MARGIN = 24;
5752
+ var BARE = { top: 0, right: 0, bottom: 0, left: 0 };
5753
+ function hasStrip(knobs2) {
5754
+ const sized = typeof knobs2.width === "number" || typeof knobs2.height === "number";
5755
+ return sized || knobs2.zoom !== "fit";
5119
5756
  }
5120
- function fetchFont(url, fonts) {
5121
- fonts.set(url, null);
5122
- quietFetch(url).then(async (response) => {
5123
- if (!response.ok)
5124
- return;
5125
- const type = /^[\w.+-]+\/[\w.+-]+/.exec(response.headers.get("content-type") ?? "")?.[0];
5126
- const bytes = new Uint8Array(await response.arrayBuffer());
5127
- fonts.set(url, `data:${type ?? "application/octet-stream"};base64,${base64(bytes)}`);
5128
- }).catch(() => {});
5757
+ function margin(size) {
5758
+ return Math.min(MARGIN, size / 4);
5129
5759
  }
5130
- function faceWith(css, base, used, fonts) {
5131
- const open = css.indexOf("{");
5132
- const close = css.lastIndexOf("}");
5133
- if (open < 0 || close < open)
5134
- return css;
5135
- const parts = cut(css.slice(open + 1, close), ";");
5136
- const named = (name) => {
5137
- const part = parts.find((part2) => part2.split(":")[0]?.trim().toLowerCase() === name);
5138
- return part ? part.slice(part.indexOf(":") + 1).trim() : "";
5760
+ function fit(knobs2, size, options = {}) {
5761
+ const { frameZoom = 1, aside = 0, side = "right", mock = BARE } = options;
5762
+ const room = {
5763
+ width: size.width,
5764
+ height: Math.max(0, size.height - (hasStrip(knobs2) ? STRIP : 0))
5139
5765
  };
5140
- if (!used.has(faceKey(named("font-family"), named("font-weight"), named("font-style"), named("unicode-range")))) {
5141
- return css;
5142
- }
5143
- const sources = cut(named("src"), ",").map((source2) => source2.trim());
5144
- const at = sources.findIndex((source2) => {
5145
- const format = /format\(\s*["']?([\w-]+)["']?\s*\)/i.exec(source2)?.[1];
5146
- return URL_OF.test(source2) && (!format || READ.test(format.toLowerCase()));
5147
- });
5148
- const source = sources[at];
5149
- const found = source ? URL_OF.exec(source) : null;
5150
- if (!source || !found)
5151
- return css;
5152
- const address = (found[1] ?? found[2] ?? found[3] ?? "").trim().replace(/\\(.)/g, "$1");
5153
- if (/^data:/i.test(address))
5154
- return css;
5155
- let url;
5156
- try {
5157
- url = new URL(address, base).href;
5158
- } catch {
5159
- return css;
5160
- }
5161
- const data = fonts.get(url);
5162
- if (data === undefined)
5163
- fetchFont(url, fonts);
5164
- if (!data)
5165
- return css;
5166
- const locals = sources.slice(0, at).filter((source2) => /^local\(/i.test(source2));
5167
- const src = [...locals, `url("${data}")${source.slice(found[0].length)}`].join(", ");
5168
- const next = parts.map((part) => part.split(":")[0]?.trim().toLowerCase() === "src" ? ` src: ${src}` : part);
5169
- return `${css.slice(0, open + 1)}${next.join(";")}${css.slice(close)}`;
5170
- }
5171
- function holdsRules(rule) {
5172
- return "cssRules" in rule;
5173
- }
5174
- function keptFor(doc) {
5175
- if (kept2?.doc === doc)
5176
- return kept2.fonts;
5177
- forgetFonts();
5178
- const set = doc.fonts;
5179
- const again = () => fetchFonts(doc);
5180
- set?.addEventListener("loadingdone", again);
5181
- kept2 = { doc, fonts: new Map, stop: () => set?.removeEventListener("loadingdone", again) };
5182
- return kept2.fonts;
5183
- }
5184
- function embedFonts(doc) {
5185
- const fonts = keptFor(doc);
5186
- const used = new Set;
5187
- const set = doc.fonts;
5188
- if (set) {
5189
- for (const face of set) {
5190
- if (face.status === "loaded")
5191
- used.add(faceKey(face.family, face.weight, face.style, face.unicodeRange));
5192
- }
5193
- }
5194
- const embed = (rule) => {
5195
- let css = rule.cssText;
5196
- if (used.size === 0 || !css.includes("@font-face"))
5197
- return css;
5198
- if (!holdsRules(rule)) {
5199
- const base = rule.parentStyleSheet?.href ?? doc.baseURI;
5200
- return css.startsWith("@font-face") ? faceWith(css, base, used, fonts) : css;
5201
- }
5202
- for (const inner of rule.cssRules) {
5203
- const next = embed(inner);
5204
- if (next !== inner.cssText)
5205
- css = css.split(inner.cssText).join(next);
5206
- }
5207
- return css;
5766
+ const sized = typeof knobs2.width === "number";
5767
+ const width = typeof knobs2.width === "number" ? knobs2.width : room.width;
5768
+ const x = sized ? margin(room.width) : 0;
5769
+ const y = typeof knobs2.height === "number" ? margin(room.height) : 0;
5770
+ const sides = { width: mock.left + mock.right, height: mock.top + mock.bottom };
5771
+ const across = width > 0 && room.width > 0 ? (room.width - 2 * x) / (width + sides.width) : 1;
5772
+ const tall = typeof knobs2.height === "number" && knobs2.height > 0 && room.height > 0;
5773
+ const upright = (room.height - 2 * y) / (Number(knobs2.height) + sides.height);
5774
+ const whole = Math.min(sized && tall ? ZOOM_MAX : 1, across, tall ? upright : 1);
5775
+ const height = typeof knobs2.height === "number" ? knobs2.height : room.height / whole;
5776
+ const outer = { width: width + sides.width, height: height + sides.height };
5777
+ const covered = sized && aside > 0 && aside <= room.width / 2 && (room.width + outer.width * whole) / 2 + x > room.width - aside;
5778
+ const fitted = covered ? Math.min(whole, (room.width - aside - 2 * x) / outer.width) : whole;
5779
+ const scale = knobs2.zoom === "fit" ? fitted : knobs2.zoom;
5780
+ const beside = knobs2.zoom === "fit" && covered ? aside : 0;
5781
+ const before = side === "left" ? beside : 0;
5782
+ return {
5783
+ width,
5784
+ height,
5785
+ zoom: frameZoom,
5786
+ scale,
5787
+ fit: fitted,
5788
+ transform: scale / frameZoom,
5789
+ box: { width: outer.width * scale + 2 * x + beside, height: outer.height * scale + 2 * y },
5790
+ left: x + mock.left * scale + before,
5791
+ top: y + mock.top * scale
5208
5792
  };
5209
- return embed;
5210
- }
5211
- function fetchFonts(doc) {
5212
- const embed = embedFonts(doc);
5213
- for (const sheet of doc.styleSheets) {
5214
- try {
5215
- for (const rule of sheet.cssRules)
5216
- embed(rule);
5217
- } catch {}
5218
- }
5219
5793
  }
5220
- function warmFonts(doc) {
5221
- if (kept2?.doc !== doc)
5222
- fetchFonts(doc);
5794
+ function origin(place2, room) {
5795
+ return {
5796
+ x: Math.max(0, (room.width - place2.box.width) / 2) + place2.left,
5797
+ y: Math.max(0, (room.height - place2.box.height) / 2) + place2.top
5798
+ };
5223
5799
  }
5224
- function forgetFonts() {
5225
- kept2?.stop();
5226
- kept2 = null;
5800
+ function label(place2, knobs2, page = place2) {
5801
+ const name = formOf(knobs2.device, knobs2.posture)?.label;
5802
+ let text = name ? `${name} · ${page.width}` : String(page.width);
5803
+ if (typeof knobs2.height === "number")
5804
+ text += ` × ${page.height}`;
5805
+ if (typeof knobs2.dpr === "number")
5806
+ text += ` · ${knobs2.dpr}x`;
5807
+ return text;
5227
5808
  }
5228
5809
 
5229
- // src/engine/pageshot.ts
5230
- var RES = 0.25;
5231
- var MOST = 1500;
5232
- var BUDGET = 6;
5233
- var INK = 0.4;
5234
- function canvasOf(width, height) {
5235
- const canvas = document.createElement("canvas");
5236
- canvas.width = Math.max(1, Math.round(width));
5237
- canvas.height = Math.max(1, Math.round(height));
5238
- const pen = canvas.getContext("2d");
5239
- return pen ? { canvas, pen } : null;
5810
+ // src/engine/mat.ts
5811
+ function colorRules() {
5812
+ return MAT_COLOR_NAMES.map((name) => {
5813
+ const paint = MAT_COLORS[name];
5814
+ return `[data-mat="${name}"] { --mat: ${matGradient(paint.srgb)}; --mat-p3: ${matGradient(paint.p3)}; --mat-line: ${paint.line}; }`;
5815
+ }).join(`
5816
+ `);
5240
5817
  }
5241
- function clear(color) {
5242
- return color === "" || color === "transparent" || /^rgba\(.*,\s*0\)$/.test(color);
5818
+ var MAT_CSS = `
5819
+ ${colorRules()}
5820
+ .mat {
5821
+ position: absolute;
5822
+ top: 0;
5823
+ left: 0;
5824
+ width: 100%;
5825
+ height: 100%;
5826
+ pointer-events: none;
5827
+ fill: var(--mat-line);
5243
5828
  }
5244
- var MEDIA = "img, video, canvas";
5245
- function mediaOf(node) {
5246
- if ("naturalWidth" in node) {
5247
- const loaded = node.complete && node.naturalWidth > 0 && node.naturalHeight > 0;
5248
- return loaded ? { source: node, width: node.naturalWidth, height: node.naturalHeight } : null;
5829
+ .mat .cell { opacity: 0.07; }
5830
+ .mat .major { opacity: 0.14; }
5831
+ .mat .span { opacity: 0.26; }
5832
+ .mat .angle { fill: none; stroke: var(--mat-line); }
5833
+ .mat .mark, .mat .tick { opacity: 0.55; }
5834
+ .mat text {
5835
+ font: 9px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
5836
+ font-variant-numeric: tabular-nums;
5837
+ opacity: 0.5;
5838
+ }`;
5839
+ var CELL = 10;
5840
+ var MAJOR = 50;
5841
+ var SPAN = 100;
5842
+ var TICK = { cell: 3, major: 5, span: 9 };
5843
+ var ANGLES = [15, 30, 45, 60, 75];
5844
+ var GUIDE = { line: 0.15, half: 0.22 };
5845
+ var ARC = 40;
5846
+ var LABEL = { radius: 240, off: 3, top: 40, room: 24 };
5847
+ var FOOT = 30;
5848
+ var NUMBER = 24;
5849
+ function ticks(length) {
5850
+ const out = [];
5851
+ for (let at = CELL;at < length; at += CELL) {
5852
+ const size = at % SPAN === 0 ? TICK.span : at % MAJOR === 0 ? TICK.major : TICK.cell;
5853
+ out.push({ at, size });
5249
5854
  }
5250
- if ("videoWidth" in node) {
5251
- const playing = node.readyState >= 2 && node.videoWidth > 0 && node.videoHeight > 0;
5252
- return playing ? { source: node, width: node.videoWidth, height: node.videoHeight } : null;
5855
+ return out;
5856
+ }
5857
+ function numbers(length, avoid) {
5858
+ const out = [];
5859
+ for (let at = SPAN;at + NUMBER <= length; at += SPAN) {
5860
+ if (avoid && at + NUMBER > avoid.from && at < avoid.to)
5861
+ continue;
5862
+ out.push(at);
5253
5863
  }
5254
- return node.width > 0 && node.height > 0 ? { source: node, width: node.width, height: node.height } : null;
5864
+ return out;
5255
5865
  }
5256
- function radiusOf(value, wide, tall) {
5257
- const [across = "0", down = across] = value.trim().split(/\s+/);
5258
- const px = (text, of) => (text.endsWith("%") ? Number.parseFloat(text) / 100 * of : Number.parseFloat(text)) || 0;
5259
- return { x: px(across, wide), y: px(down, tall) };
5866
+ function lines(across, length, hair) {
5867
+ return across.map((at) => `M${at} 0h${hair}v${length}h${-hair}ZM0 ${at}h${length}v${hair}h${-length}Z`).join("");
5260
5868
  }
5261
- function drawMedia(pen, media, rect, style) {
5262
- const px = (value) => Number.parseFloat(value) || 0;
5263
- const left = px(style.borderLeftWidth) + px(style.paddingLeft);
5264
- const right = px(style.borderRightWidth) + px(style.paddingRight);
5265
- const top = px(style.borderTopWidth) + px(style.paddingTop);
5266
- const bottom = px(style.borderBottomWidth) + px(style.paddingBottom);
5267
- const box2 = { x: rect.left + left, y: rect.top + top, width: rect.width - left - right, height: rect.height - top - bottom };
5268
- const placed = objectPlace(style.objectFit, style.objectPosition, media, box2);
5269
- if (!placed)
5270
- return;
5271
- const corner = (value, across, down) => {
5272
- const radius = radiusOf(value, rect.width, rect.height);
5273
- return { x: Math.max(0, radius.x - across), y: Math.max(0, radius.y - down) };
5274
- };
5275
- const corners = [
5276
- corner(style.borderTopLeftRadius, left, top),
5277
- corner(style.borderTopRightRadius, right, top),
5278
- corner(style.borderBottomRightRadius, right, bottom),
5279
- corner(style.borderBottomLeftRadius, left, bottom)
5280
- ];
5281
- const { from, to } = placed;
5282
- pen.save();
5283
- if (corners.some((radius) => radius.x > 0 && radius.y > 0)) {
5284
- pen.beginPath();
5285
- pen.roundRect(box2.x, box2.y, box2.width, box2.height, corners);
5286
- pen.clip();
5287
- }
5288
- if (style.imageRendering === "pixelated" || style.imageRendering === "crisp-edges")
5289
- pen.imageSmoothingEnabled = false;
5290
- pen.drawImage(media.source, from.x, from.y, from.width, from.height, to.x, to.y, to.width, to.height);
5291
- pen.restore();
5869
+ function vertex(height) {
5870
+ const y = Math.floor((height - FOOT) / SPAN) * SPAN;
5871
+ return y > 0 ? { x: 0, y } : null;
5292
5872
  }
5293
- function picturesKey(doc) {
5294
- const parts = [];
5295
- for (const node of doc.querySelectorAll(MEDIA)) {
5296
- if (!("naturalWidth" in node))
5297
- return null;
5298
- const address = node.currentSrc;
5299
- parts.push(`${address.length}:${address.slice(-64)}@${node.naturalWidth}x${node.naturalHeight}`);
5300
- }
5301
- return parts.join(" ");
5873
+ function direction(angle) {
5874
+ const turn2 = angle * Math.PI / 180;
5875
+ return { x: Math.cos(turn2), y: -Math.sin(turn2) };
5302
5876
  }
5303
- function shotKey(at) {
5304
- const { size, frame: frame2, view, scroll } = at;
5305
- return JSON.stringify([
5306
- [size.width, size.height, at.color, at.layout],
5307
- [frame2.x, frame2.y, frame2.width],
5308
- [view.width, view.height, scroll.x, scroll.y],
5309
- [at.dpr, at.text, at.pictures]
5310
- ]);
5877
+ function exit(from, angle, size) {
5878
+ const step = direction(angle);
5879
+ const toTop = step.y < 0 ? from.y / -step.y : Infinity;
5880
+ const toRight = step.x > 0 ? (size.width - from.x) / step.x : Infinity;
5881
+ if (toTop <= toRight)
5882
+ return { x: from.x + toTop * step.x, y: 0 };
5883
+ return { x: size.width, y: from.y + toRight * step.y };
5311
5884
  }
5312
- function shootPage(frame2, glass, size, color, layout = "") {
5313
- const doc = frame2.contentDocument;
5314
- const view = frame2.contentWindow;
5315
- const screen = glass.getBoundingClientRect();
5316
- const box2 = frame2.getBoundingClientRect();
5317
- if (!doc?.body || !view || screen.width <= 0 || view.innerWidth <= 0)
5318
- return null;
5319
- const shown2 = picturesKey(doc);
5320
- const css = size.width / screen.width;
5321
- const near = (value) => Math.round(value * css * 1000) / 1000;
5322
- const key = shotKey({
5323
- size,
5324
- color,
5325
- layout,
5326
- frame: { x: near(box2.left - screen.left), y: near(box2.top - screen.top), width: near(box2.width) },
5327
- view: { width: view.innerWidth, height: view.innerHeight },
5328
- scroll: { x: view.scrollX, y: view.scrollY },
5329
- dpr: view.devicePixelRatio,
5330
- text: view.getComputedStyle(doc.documentElement).fontSize,
5331
- pictures: shown2 ?? ""
5885
+ function along(from, angle, radius, off = 0) {
5886
+ const step = direction(angle);
5887
+ return { x: from.x + radius * step.x + off * step.y, y: from.y + radius * step.y - off * step.x };
5888
+ }
5889
+ function drawMat(size, hair, avoid, bleed = { left: 0, right: 0 }) {
5890
+ const svg = svgNode("svg", { class: "mat", "aria-hidden": "true" });
5891
+ const sheet = svgNode("g", { transform: `translate(${bleed.left} 0)` });
5892
+ const half = SPAN / 2;
5893
+ const minor = [];
5894
+ for (let at = CELL;at < SPAN; at += CELL)
5895
+ if (at !== half)
5896
+ minor.push(at);
5897
+ const arm = 6;
5898
+ const pattern = svgNode("pattern", {
5899
+ id: "mat-grid",
5900
+ x: -half,
5901
+ y: -half,
5902
+ width: SPAN,
5903
+ height: SPAN,
5904
+ patternUnits: "userSpaceOnUse"
5332
5905
  });
5333
- const kept3 = shown2 === null || !unchanged(doc) ? null : shots.get(doc)?.get(key);
5334
- if (kept3)
5335
- return kept3;
5336
- const drawn = canvasOf(size.width * RES, size.height * RES);
5337
- if (!drawn)
5338
- return null;
5339
- const { canvas, pen } = drawn;
5340
- pen.fillStyle = color;
5341
- pen.fillRect(0, 0, canvas.width, canvas.height);
5342
- const scale = box2.width * css / view.innerWidth;
5343
- pen.setTransform(RES * scale, 0, 0, RES * scale, RES * (box2.left - screen.left) * css, RES * (box2.top - screen.top) * css);
5344
- pen.beginPath();
5345
- pen.rect(0, 0, view.innerWidth, view.innerHeight);
5346
- pen.clip();
5347
- const pictures = new Map;
5348
- for (const node of doc.querySelectorAll(MEDIA)) {
5349
- const media = mediaOf(node);
5350
- if (media)
5351
- pictures.set(node, media);
5352
- }
5353
- const range = doc.createRange();
5354
- const tall = view.innerHeight;
5355
- let seen = 0;
5356
- const pinned = [];
5357
- const deadline = performance.now() + BUDGET;
5358
- const draw = (node, alpha, lifted) => {
5359
- if (seen++ > MOST || seen % 50 === 0 && performance.now() > deadline)
5360
- return;
5361
- if (node.hasAttribute("data-devknobs"))
5362
- return;
5363
- const style = view.getComputedStyle(node);
5364
- if (style.display === "none")
5365
- return;
5366
- if (!lifted && (style.position === "fixed" || style.position === "sticky")) {
5367
- pinned.push([node, alpha]);
5368
- return;
5369
- }
5370
- const rect = node.getBoundingClientRect();
5371
- const area = rect.width > 0 && rect.height > 0;
5372
- if (area && (rect.bottom < 0 || rect.top > tall))
5373
- return;
5374
- const shown3 = alpha * (Number.parseFloat(style.opacity) || 0);
5375
- if (shown3 <= 0)
5376
- return;
5377
- if (area && style.visibility !== "hidden") {
5378
- pen.globalAlpha = shown3;
5379
- if (!clear(style.backgroundColor)) {
5380
- pen.fillStyle = style.backgroundColor;
5381
- pen.beginPath();
5382
- pen.roundRect(rect.left, rect.top, rect.width, rect.height, Number.parseFloat(style.borderTopLeftRadius) || 0);
5383
- pen.fill();
5384
- }
5385
- const picture = pictures.get(node);
5386
- if (picture)
5387
- drawMedia(pen, picture, rect, style);
5388
- pen.fillStyle = style.color;
5389
- pen.globalAlpha = shown3 * INK;
5390
- for (const text of node.childNodes) {
5391
- if (text.nodeType !== Node.TEXT_NODE || !text.textContent?.trim())
5392
- continue;
5393
- range.selectNodeContents(text);
5394
- for (const line of range.getClientRects())
5395
- pen.fillRect(line.left, line.top, line.width, line.height);
5396
- }
5906
+ 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", {
5907
+ class: "mark",
5908
+ 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`
5909
+ }));
5910
+ const defs = svgNode("defs", {});
5911
+ defs.append(pattern);
5912
+ const top = ticks(size.width).map((tick) => `M${tick.at} 0h${hair}v${tick.size}h${-hair}Z`).join("");
5913
+ const left = ticks(size.height).map((tick) => `M0 ${tick.at}h${tick.size}v${hair}h${-tick.size}Z`).join("");
5914
+ sheet.append(svgNode("rect", {
5915
+ x: -bleed.left,
5916
+ width: bleed.left + size.width + bleed.right,
5917
+ height: "100%",
5918
+ fill: "url(#mat-grid)"
5919
+ }), svgNode("path", { class: "tick", d: top + left }));
5920
+ svg.append(defs, sheet);
5921
+ const origin2 = vertex(size.height);
5922
+ if (origin2) {
5923
+ const base = along(origin2, 0, ARC);
5924
+ const rim = { x: origin2.x, y: origin2.y - ARC };
5925
+ const arc2 = svgNode("path", {
5926
+ class: "angle",
5927
+ d: `M${base.x} ${base.y}A${ARC} ${ARC} 0 0 0 ${rim.x} ${rim.y}`,
5928
+ "stroke-width": hair
5929
+ });
5930
+ arc2.style.opacity = String(GUIDE.line);
5931
+ sheet.append(arc2);
5932
+ for (const angle of ANGLES) {
5933
+ const start = along(origin2, angle, ARC);
5934
+ const end = exit(origin2, angle, size);
5935
+ const line = svgNode("path", {
5936
+ class: "angle",
5937
+ d: `M${start.x} ${start.y}L${end.x} ${end.y}`,
5938
+ "stroke-width": hair
5939
+ });
5940
+ line.style.opacity = String(angle === 45 ? GUIDE.half : GUIDE.line);
5941
+ sheet.append(line);
5942
+ const reach = Math.hypot(end.x - origin2.x, end.y - origin2.y);
5943
+ const at = along(origin2, angle, LABEL.radius, LABEL.off);
5944
+ if (reach < LABEL.radius + LABEL.room || at.y < LABEL.top)
5945
+ continue;
5946
+ const text = svgNode("text", {
5947
+ x: at.x,
5948
+ y: at.y,
5949
+ transform: `rotate(${-angle} ${at.x} ${at.y})`
5950
+ });
5951
+ text.textContent = `${angle}°`;
5952
+ sheet.append(text);
5397
5953
  }
5398
- for (const child of node.children)
5399
- draw(child, shown3, lifted);
5954
+ }
5955
+ for (const at of numbers(size.width, avoid)) {
5956
+ const text = svgNode("text", { x: at + 3, y: TICK.span + 1 });
5957
+ text.textContent = String(at);
5958
+ sheet.append(text);
5959
+ }
5960
+ for (const at of numbers(size.height)) {
5961
+ const text = svgNode("text", { x: TICK.span + 2, y: at, "dominant-baseline": "middle" });
5962
+ text.textContent = String(at);
5963
+ sheet.append(text);
5964
+ }
5965
+ return svg;
5966
+ }
5967
+
5968
+ // src/engine/foldflip.ts
5969
+ function flipRect(rect, room) {
5970
+ return { ...rect, x: room.width - rect.x - rect.width, y: room.height - rect.y - rect.height };
5971
+ }
5972
+ function flipRadius(radius) {
5973
+ if (typeof radius === "number")
5974
+ return radius;
5975
+ const [topLeft, topRight, bottomRight, bottomLeft] = radius;
5976
+ return [bottomRight, bottomLeft, topLeft, topRight];
5977
+ }
5978
+ function flipMock(mock) {
5979
+ const room = { width: mock.width, height: mock.height };
5980
+ const { top, right, bottom, left } = mock.inset;
5981
+ const flipped = {
5982
+ ...mock,
5983
+ inset: { top: bottom, right: left, bottom: top, left: right },
5984
+ body: flipRect(mock.body, room),
5985
+ screenRadius: flipRadius(mock.screenRadius),
5986
+ bodyRadius: flipRadius(mock.bodyRadius),
5987
+ parts: mock.parts.map((part) => flipRect(part, room))
5400
5988
  };
5401
- for (const child of doc.body.children)
5402
- draw(child, 1, false);
5403
- for (const [node, alpha] of pinned)
5404
- draw(node, alpha, true);
5405
- if (shown2 !== null)
5406
- keepShot(doc, key, canvas);
5407
- return canvas;
5989
+ if (!mock.image)
5990
+ return flipped;
5991
+ if (mock.image.turn === null) {
5992
+ const { over: over2, ...still2 } = mock.image;
5993
+ return { ...flipped, image: over2 ? still2 : { ...still2, over: true } };
5994
+ }
5995
+ const { clockwise, ...image } = mock.image;
5996
+ return { ...flipped, image: clockwise ? { ...image, turn: mock.height } : { ...image, turn: mock.width, clockwise: true } };
5408
5997
  }
5409
- var shots = new WeakMap;
5410
- var watched = null;
5411
- function forgetShots() {
5412
- watched?.observer.disconnect();
5413
- watched = null;
5414
- shots = new WeakMap;
5415
- forgetFonts();
5998
+ function coverAcross(shape) {
5999
+ const [device = "", held, posture] = shape.split("|");
6000
+ return held === "landscape" && posture === "closed" && formOf(device, "closed")?.clockwise === true;
5416
6001
  }
5417
- function unchanged(doc) {
5418
- if (watched?.doc !== doc)
5419
- return false;
5420
- if (watched.observer.takeRecords().length > 0)
5421
- watched.changed = true;
5422
- return !watched.changed;
6002
+ function openUpright(shape) {
6003
+ const [device = "", held, posture] = shape.split("|");
6004
+ return held === "portrait" && posture === "open" && formOf(device, "closed")?.clockwise === true;
5423
6005
  }
5424
- function keepShot(doc, key, canvas) {
5425
- if (!unchanged(doc)) {
5426
- watched?.observer.disconnect();
5427
- shots = new WeakMap;
5428
- const Observer = doc.defaultView?.MutationObserver;
5429
- if (!Observer)
5430
- return;
5431
- const observer = new Observer(() => {
5432
- if (watched?.observer === observer)
5433
- watched.changed = true;
5434
- observer.disconnect();
5435
- });
5436
- observer.observe(doc, { subtree: true, childList: true, attributes: true, characterData: true });
5437
- watched = { doc, changed: false, observer };
6006
+ function caseOver(from, to, over2) {
6007
+ if (coverAcross(to))
6008
+ return true;
6009
+ if (!openUpright(to))
6010
+ return false;
6011
+ return coverAcross(from) || from === to && over2;
6012
+ }
6013
+ function flipFace(face, room) {
6014
+ return { ...face, body: face.body && flipMock(face.body), screen: flipRect(face.screen, room) };
6015
+ }
6016
+ var turnedOver = new WeakMap;
6017
+ function flipCanvas(canvas) {
6018
+ const known = turnedOver.get(canvas);
6019
+ if (known)
6020
+ return known;
6021
+ const turned = document.createElement("canvas");
6022
+ turned.width = canvas.width;
6023
+ turned.height = canvas.height;
6024
+ const pen = turned.getContext("2d");
6025
+ if (pen) {
6026
+ pen.translate(canvas.width, canvas.height);
6027
+ pen.rotate(Math.PI);
6028
+ pen.drawImage(canvas, 0, 0);
6029
+ }
6030
+ turnedOver.set(canvas, turned);
6031
+ return turned;
6032
+ }
6033
+ function flipPicture(picture, size) {
6034
+ const { bars } = picture;
6035
+ if (bars) {
6036
+ bars.style.transformOrigin = "0 0";
6037
+ bars.style.transform = `translate(${size.width}px, ${size.height}px) rotate(180deg)`;
5438
6038
  }
5439
- const kept3 = shots.get(doc) ?? new Map;
5440
- kept3.set(key, canvas);
5441
- shots.set(doc, kept3);
6039
+ return {
6040
+ shot: picture.shot && flipCanvas(picture.shot),
6041
+ painted: picture.painted?.then((drawn) => drawn && { ...drawn, shot: flipCanvas(drawn.shot) }) ?? null,
6042
+ bars
6043
+ };
5442
6044
  }
5443
- var KEPT = 8;
5444
- function blurPictures(shot, width, across, widths = blurWidths().slice(1)) {
5445
- const length = across ? shot.height : shot.width;
5446
- return widths.map((wide) => {
5447
- const coarse2 = Math.max(1, wide * shot.width / width);
5448
- const margin2 = blurMargin(coarse2);
5449
- const padded = canvasOf(shot.width + (across ? 0 : 2 * margin2), shot.height + (across ? 2 * margin2 : 0));
5450
- if (!padded)
5451
- return { canvas: blurPicture(shot, coarse2), long: length };
5452
- padded.pen.fillStyle = "#000";
5453
- padded.pen.fillRect(0, 0, padded.canvas.width, padded.canvas.height);
5454
- padded.pen.drawImage(shot, across ? 0 : margin2, across ? margin2 : 0);
5455
- const canvas = blurPicture(padded.canvas, coarse2);
5456
- if (canvas !== padded.canvas)
5457
- spend(padded.canvas);
5458
- return { canvas, long: length + 2 * margin2 };
5459
- });
6045
+
6046
+ // src/engine/foldgl.ts
6047
+ function screenLook(open, wedge, free = 1, shaded = null, pane = shaded ?? "inner") {
6048
+ const blurred = blurOn();
6049
+ const [, wipe, area, far] = shaded ? shadeOf(shaded, open, free) : [1, 0, 0, 0];
6050
+ return {
6051
+ peak: blurred ? turnBlur(open, pane) : 0,
6052
+ edge: blurred ? [tune.edgeHinge * wedge, tune.edgeFree * wedge] : [0, 0],
6053
+ free,
6054
+ dark: shadesOn() ? freeDepth(open) : 0,
6055
+ lit: [wipe, area, far]
6056
+ };
5460
6057
  }
5461
- function blurMargin(coarse2) {
5462
- return Math.ceil(2 * coarse2);
6058
+ var WEIGHTS = [0.375, 0.25, 0.0625];
6059
+ function wedgeOf(window2, pane, picture, span) {
6060
+ const { top, bottom } = darkAt(window2, pane, picture);
6061
+ return picture.height > 0 ? Math.max(top, bottom) * span / picture.height : 0;
5463
6062
  }
5464
- function marginPlace(shot, padded) {
5465
- const exact = (value) => Math.round(value * 1e4) / 1e4;
5466
- return { start: exact((shot - padded) / 2 / shot * 100), size: exact(padded / shot * 100) };
6063
+ function freeOf(window2, pane, picture) {
6064
+ if (picture.width <= 0)
6065
+ return 1;
6066
+ const [a, b, c, d] = window2;
6067
+ const seen = pane === "inner" ? picture.x + picture.width - (a[0] + d[0]) / 2 : (b[0] + c[0]) / 2 - picture.x;
6068
+ return Math.min(1, Math.max(0, seen / picture.width));
5467
6069
  }
5468
- function spend(canvas) {
5469
- canvas.width = 0;
5470
- canvas.height = 0;
6070
+ function reachOf(shots2, pane) {
6071
+ let most = 0;
6072
+ for (const shot of shots2.frames) {
6073
+ if (shotPane(shots2, shot) !== pane)
6074
+ continue;
6075
+ const quad = shotQuad(shot, pane);
6076
+ const picture = shotPicture(shots2, pane, quad);
6077
+ most = Math.max(most, wedgeOf(shotWindow(quad, pane, picture), pane, picture, 1));
6078
+ }
6079
+ return most;
5471
6080
  }
5472
- function blurPicture(shot, coarse2) {
5473
- const halvings = Math.ceil(Math.log2(coarse2) - 0.000000001);
5474
- const { width, height } = shot;
5475
- const sized = (level) => {
5476
- const scale = Math.min(1, 2 ** level / coarse2);
5477
- return canvasOf(width * scale, height * scale);
5478
- };
5479
- let at = shot;
5480
- const step = (level, smooth) => {
5481
- const next = sized(level);
5482
- if (!next)
5483
- return false;
5484
- if (smooth)
5485
- next.pen.imageSmoothingQuality = "high";
5486
- next.pen.drawImage(at, 0, 0, next.canvas.width, next.canvas.height);
5487
- if (at !== shot)
5488
- spend(at);
5489
- at = next.canvas;
5490
- return true;
5491
- };
5492
- for (let level = halvings - 1;level >= 0; level--)
5493
- if (!step(level, false))
5494
- return at;
5495
- for (let level = 1;level <= Math.min(Math.log2(KEPT), halvings); level++)
5496
- if (!step(level, true))
5497
- return at;
5498
- return at;
6081
+ function canvasRect(place2) {
6082
+ const { across, part, stage, margin: margin2 } = place2;
6083
+ return across ? { x: part.x, y: -margin2, width: part.width, height: stage.height + 2 * margin2 } : { x: -margin2, y: part.y, width: stage.width + 2 * margin2, height: part.height };
5499
6084
  }
5500
- function blankUrl(width, height) {
5501
- return svgUrl(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"/>`);
6085
+ function hingeLine(pane, across, part) {
6086
+ const { x, y, width, height } = part;
6087
+ if (across)
6088
+ return pane === "inner" ? [-1 / width, 0, (x + width) / width] : [1 / width, 0, -x / width];
6089
+ return pane === "inner" ? [0, 1 / height, -y / height] : [0, -1 / height, (y + height) / height];
5502
6090
  }
5503
- function blankPictures(live, copy) {
5504
- const shown2 = live.querySelectorAll("img");
5505
- copy.querySelectorAll("img").forEach((image, index) => {
5506
- const from = shown2[index];
5507
- if (!from || !from.complete || !(from.naturalWidth > 0 && from.naturalHeight > 0))
5508
- return;
5509
- for (const name of ["srcset", "sizes", "loading"])
5510
- image.removeAttribute(name);
5511
- const holder2 = image.parentElement;
5512
- if (holder2?.localName === "picture")
5513
- for (const source of holder2.querySelectorAll("source"))
5514
- source.remove();
5515
- image.setAttribute("src", blankUrl(from.naturalWidth, from.naturalHeight));
6091
+ function contextOf(canvas) {
6092
+ if (typeof WebGL2RenderingContext === "undefined")
6093
+ return null;
6094
+ const gl = canvas.getContext("webgl2", {
6095
+ alpha: false,
6096
+ antialias: false,
6097
+ depth: false,
6098
+ stencil: false,
6099
+ premultipliedAlpha: false,
6100
+ powerPreference: "low-power"
5516
6101
  });
6102
+ return gl instanceof WebGL2RenderingContext ? gl : null;
5517
6103
  }
5518
- function copyPage(frame2) {
5519
- const doc = frame2.contentDocument;
5520
- if (!doc?.documentElement)
5521
- return null;
5522
- const rules = [];
5523
- const written2 = embedFonts(doc);
5524
- for (const sheet of [...doc.styleSheets, ...doc.adoptedStyleSheets ?? []]) {
5525
- try {
5526
- for (const rule of sheet.cssRules)
5527
- rules.push(written2(rule));
5528
- } catch {}
6104
+ var VERTEX = `#version 300 es
6105
+ in vec2 corner;
6106
+ uniform vec4 view;
6107
+ out vec2 pos;
6108
+ void main() {
6109
+ pos = view.xy + corner * view.zw;
6110
+ gl_Position = vec4(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0, 0.0, 1.0);
6111
+ }`;
6112
+ var FRAGMENT = `#version 300 es
6113
+ precision highp float;
6114
+ uniform sampler2D page;
6115
+ uniform vec2 stage;
6116
+ uniform vec2 along;
6117
+ uniform vec3 line;
6118
+ uniform float peak;
6119
+ uniform vec2 edge;
6120
+ uniform float free;
6121
+ uniform float dark;
6122
+ uniform vec2 shape;
6123
+ uniform vec2 rimmed;
6124
+ uniform vec3 band;
6125
+ uniform vec3 lit;
6126
+ uniform vec2 run;
6127
+ uniform vec3 wiped;
6128
+ uniform vec2 soften;
6129
+ uniform float grain;
6130
+ uniform float px;
6131
+ in vec2 pos;
6132
+ out vec4 color;
6133
+ const float WEIGHTS[3] = float[3](${WEIGHTS.join(", ")});
6134
+ float cover(float at, float span, float soft) {
6135
+ return smoothstep(-soft, soft, at) * (1.0 - smoothstep(span - soft, span + soft, at));
6136
+ }
6137
+ float shadow(float t) {
6138
+ if (dark <= 0.0) return 1.0;
6139
+ float across = t / max(free, 0.001);
6140
+ float deep = band.z * smoothstep(band.x, 1.0, across) + (1.0 - band.z) * smoothstep(1.0 - band.y, 1.0, across);
6141
+ return 1.0 - dark * deep;
6142
+ }
6143
+ float shade(float t) {
6144
+ if (lit.x + lit.y + lit.z <= 0.0) return 1.0;
6145
+ float uv = run.x + run.y * t;
6146
+ float off = abs(uv - wiped.x);
6147
+ float wipe = 1.0 - clamp(smoothstep(wiped.y, wiped.z, off) * lit.x, 0.0, 1.0);
6148
+ 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));
6149
+ float away = mix(1.0, smoothstep(0.05, 0.5, uv), lit.z);
6150
+ return pow(clamp(wipe * soft * soft * away, 0.0, 1.0), 1.0 / 2.2);
6151
+ }
6152
+ vec4 shaded(vec3 rgb, float t) {
6153
+ float speck = 0.0;
6154
+ if (grain > 0.0 && dark + lit.x + lit.y + lit.z > 0.0) {
6155
+ speck = (fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5) * grain / 255.0;
6156
+ }
6157
+ return vec4(rgb * shadow(t) * shade(min(t, free)) + speck, 1.0);
6158
+ }
6159
+ float seen(vec2 at, float soft) {
6160
+ float reach = soft * length(line.xy);
6161
+ return cover(dot(along, at), dot(along, stage), soft) * (1.0 - smoothstep(free - reach, free + reach, dot(line.xy, at) + line.z));
6162
+ }
6163
+ void main() {
6164
+ vec2 texels = vec2(textureSize(page, 0)) / stage;
6165
+ vec2 right = dFdx(pos) * texels;
6166
+ vec2 down = dFdy(pos) * texels;
6167
+ float sharp = 0.5 * log2(max(1.0, max(dot(right, right), dot(down, down))));
6168
+ float t = clamp(dot(line.xy, pos) + line.z, 0.0, 1.0);
6169
+ float span = dot(along, stage);
6170
+ float at = dot(along, pos);
6171
+ float across = free > 0.0 ? min(1.0, t / free) : 1.0;
6172
+ float wide = peak * (shape.x + (1.0 - shape.x) * pow(across, shape.y));
6173
+ float rim = mix(edge.x, edge.y, t);
6174
+ if (rim > 0.0) wide = max(wide, rim * (1.0 - smoothstep(0.0, rimmed.x * rim, min(at, span - at))));
6175
+ float gap = rimmed.y * wide;
6176
+ float soft = max(0.5 * px, 0.75 * gap);
6177
+ float lod = max(sharp, log2(max(1.0, gap * max(texels.x, texels.y))));
6178
+ vec3 sum = vec3(0.0);
6179
+ if (peak + edge.x + edge.y <= 0.0) {
6180
+ sum = textureLod(page, pos / stage, lod).rgb * seen(pos, soft);
6181
+ } else {
6182
+ for (int y = -2; y <= 2; y++) {
6183
+ for (int x = -2; x <= 2; x++) {
6184
+ vec2 tap = pos + vec2(float(x), float(y)) * gap;
6185
+ float weight = WEIGHTS[abs(x)] * WEIGHTS[abs(y)];
6186
+ sum += textureLod(page, tap / stage, lod).rgb * seen(tap, soft) * weight;
6187
+ }
6188
+ }
5529
6189
  }
5530
- const inert = doc.implementation.createHTMLDocument("");
5531
- const root = inert.importNode(doc.documentElement, true);
5532
- blankPictures(doc.documentElement, root);
5533
- for (const node of root.querySelectorAll("script, link, style, noscript, [data-devknobs]"))
5534
- node.remove();
5535
- const style = inert.createElement("style");
5536
- style.textContent = rules.join(`
5537
- `);
5538
- (root.querySelector("head") ?? root).append(style);
5539
- return root;
6190
+ color = shaded(sum, t);
6191
+ }`;
6192
+ function compile(gl, kind, source) {
6193
+ const shader = gl.createShader(kind);
6194
+ if (!shader)
6195
+ return null;
6196
+ gl.shaderSource(shader, source);
6197
+ gl.compileShader(shader);
6198
+ return shader;
5540
6199
  }
5541
- var LONE_HALF = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
5542
- function svgUrl(svg) {
5543
- const whole = typeof svg.toWellFormed === "function" ? svg.toWellFormed() : svg.replace(LONE_HALF, "�");
5544
- return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(whole)}`;
6200
+ function firstLine(log, otherwise) {
6201
+ return log?.trim().split(`
6202
+ `)[0]?.trim() || otherwise;
5545
6203
  }
5546
- function rootSize(doc, view) {
5547
- const size = view.getComputedStyle(doc.documentElement).fontSize;
5548
- return size ? `font-size:${size} !important` : "";
6204
+ function uploadWhy(error) {
6205
+ const name = error instanceof Error ? error.name : String(error);
6206
+ 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";
6207
+ return `the picture could not be uploaded: ${name}${name === "SecurityError" ? `, ${tainted}` : ""}`;
5549
6208
  }
5550
- async function paintPage(frame2, glass, size, color, copy) {
5551
- const doc = frame2.contentDocument;
5552
- const view = frame2.contentWindow;
5553
- const screen = glass.getBoundingClientRect();
5554
- const box2 = frame2.getBoundingClientRect();
5555
- if (!doc || !view || screen.width <= 0 || view.innerWidth <= 0)
6209
+ function screenGl(place2, refused) {
6210
+ const canvas = document.createElement("canvas");
6211
+ const gl = contextOf(canvas);
6212
+ if (!gl) {
6213
+ refused(typeof WebGL2RenderingContext === "undefined" ? "this browser has no WebGL2" : "the canvas gave no WebGL2 context", null);
5556
6214
  return null;
5557
- const { innerWidth: width, innerHeight: height, scrollX, scrollY } = view;
5558
- const css = size.width / screen.width;
5559
- const scale = box2.width * css / width;
5560
- const at = { x: (box2.left - screen.left) * css, y: (box2.top - screen.top) * css };
5561
- let over = null;
5562
- for (const node of doc.querySelectorAll(MEDIA)) {
5563
- const media = node.closest("[data-devknobs]") ? null : mediaOf(node);
5564
- const rect = node.getBoundingClientRect();
5565
- if (!media || rect.bottom <= 0 || rect.top >= height || rect.width <= 0)
5566
- continue;
5567
- if (!over) {
5568
- over = canvasOf(size.width, size.height);
5569
- over?.pen.setTransform(scale, 0, 0, scale, at.x, at.y);
5570
- }
5571
- try {
5572
- if (over)
5573
- drawMedia(over.pen, media, rect, view.getComputedStyle(node));
5574
- } catch {}
5575
6215
  }
5576
- const root = copy.cloneNode(true);
5577
- const scrolled = `position:relative;left:${-scrollX}px;top:${-scrollY}px`;
5578
- const sized = rootSize(doc, view);
5579
- root.setAttribute("style", `${root.getAttribute("style") ?? ""};${sized};${scrolled}`);
5580
- const markup = new XMLSerializer().serializeToString(root);
5581
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" style="${sized}">` + `<foreignObject width="100%" height="100%">${markup}</foreignObject></svg>`;
5582
- const image = new Image;
5583
- try {
5584
- image.src = svgUrl(svg);
5585
- await image.decode();
5586
- } catch {
5587
- if (over)
5588
- spend(over.canvas);
6216
+ const rect = canvasRect(place2);
6217
+ const most = Math.max(1, gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) || 4096);
6218
+ const density2 = Math.min(place2.density, most / rect.width, most / rect.height);
6219
+ canvas.width = Math.max(1, Math.round(rect.width * density2));
6220
+ canvas.height = Math.max(1, Math.round(rect.height * density2));
6221
+ canvas.style.position = "absolute";
6222
+ canvas.style.display = "block";
6223
+ canvas.style.left = `${rect.x}px`;
6224
+ canvas.style.top = `${rect.y}px`;
6225
+ canvas.style.width = `${rect.width}px`;
6226
+ canvas.style.height = `${rect.height}px`;
6227
+ const vertex2 = compile(gl, gl.VERTEX_SHADER, VERTEX);
6228
+ const fragment = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);
6229
+ const program = gl.createProgram();
6230
+ const corners = gl.createBuffer();
6231
+ const texture = gl.createTexture();
6232
+ const free = () => {
6233
+ gl.deleteTexture(texture);
6234
+ gl.deleteBuffer(corners);
6235
+ gl.deleteProgram(program);
6236
+ gl.deleteShader(vertex2);
6237
+ gl.deleteShader(fragment);
6238
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
6239
+ canvas.remove();
6240
+ };
6241
+ if (!vertex2 || !fragment || !program || !corners || !texture) {
6242
+ const why = gl.isContextLost() ? "the WebGL2 context was lost as it was made" : "WebGL2 made no shader, program, buffer or texture";
6243
+ free();
6244
+ refused(why, null);
5589
6245
  return null;
5590
6246
  }
5591
- const drawn = canvasOf(size.width, size.height);
5592
- if (!drawn)
6247
+ gl.attachShader(program, vertex2);
6248
+ gl.attachShader(program, fragment);
6249
+ gl.linkProgram(program);
6250
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
6251
+ const log = [vertex2, fragment].map((shader) => gl.getShaderInfoLog(shader)).find((said) => said?.trim()) ?? gl.getProgramInfoLog(program);
6252
+ const lost = gl.isContextLost();
6253
+ free();
6254
+ refused(lost ? "the WebGL2 context was lost as it was made" : `the shader did not compile or link: ${firstLine(log, "no reason given")}`, null);
5593
6255
  return null;
5594
- const { canvas, pen } = drawn;
5595
- pen.fillStyle = color;
5596
- pen.fillRect(0, 0, canvas.width, canvas.height);
5597
- pen.setTransform(scale, 0, 0, scale, at.x, at.y);
5598
- pen.drawImage(image, 0, 0, width, height);
5599
- if (over) {
5600
- pen.setTransform(1, 0, 0, 1, 0, 0);
5601
- pen.drawImage(over.canvas, 0, 0);
5602
- spend(over.canvas);
5603
6256
  }
5604
- return canvas;
6257
+ gl.useProgram(program);
6258
+ gl.bindBuffer(gl.ARRAY_BUFFER, corners);
6259
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
6260
+ const corner = gl.getAttribLocation(program, "corner");
6261
+ gl.enableVertexAttribArray(corner);
6262
+ gl.vertexAttribPointer(corner, 2, gl.FLOAT, false, 0, 0);
6263
+ const at = (name) => gl.getUniformLocation(program, name);
6264
+ const { stage } = place2;
6265
+ gl.uniform4f(at("view"), rect.x, rect.y, rect.width, rect.height);
6266
+ gl.uniform2f(at("stage"), stage.width, stage.height);
6267
+ gl.uniform2f(at("along"), place2.across ? 0 : 1, place2.across ? 1 : 0);
6268
+ gl.uniform3f(at("line"), ...hingeLine(place2.pane, place2.across, place2.part));
6269
+ gl.uniform1f(at("px"), canvas.width > 0 ? rect.width / canvas.width : 1);
6270
+ gl.uniform1i(at("page"), 0);
6271
+ const wipe = WIPE[place2.pane];
6272
+ gl.uniform2f(at("run"), uvOf(place2.pane, 0), uvOf(place2.pane, 1) - uvOf(place2.pane, 0));
6273
+ gl.uniform3f(at("wiped"), wipe.at, wipe.shade[0], wipe.shade[1]);
6274
+ gl.uniform2f(at("soften"), wipe.blur[0], wipe.blur[1]);
6275
+ 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") };
6276
+ gl.bindTexture(gl.TEXTURE_2D, texture);
6277
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
6278
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
6279
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
6280
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
6281
+ gl.viewport(0, 0, canvas.width, canvas.height);
6282
+ const widest = gl.getParameter(gl.MAX_TEXTURE_SIZE) || 2048;
6283
+ let shot = null;
6284
+ let look = null;
6285
+ let gone = false;
6286
+ const draw = (next) => {
6287
+ look = next;
6288
+ if (gone || !shot)
6289
+ return;
6290
+ gl.uniform1f(uniforms.peak, next.peak);
6291
+ gl.uniform2f(uniforms.edge, ...next.edge);
6292
+ gl.uniform1f(uniforms.free, next.free);
6293
+ gl.uniform1f(uniforms.dark, next.dark);
6294
+ gl.uniform2f(uniforms.shape, tune.blurHinge, tune.blurRise);
6295
+ gl.uniform2f(uniforms.rimmed, tune.edgeReach, tune.blurSpread);
6296
+ gl.uniform3f(uniforms.band, tune.darkFrom, tune.darkBand, tune.darkBroad);
6297
+ gl.uniform3f(uniforms.lit, ...next.lit);
6298
+ gl.uniform1f(uniforms.grain, tune.grain);
6299
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
6300
+ };
6301
+ canvas.addEventListener("webglcontextlost", () => {
6302
+ if (gone)
6303
+ return;
6304
+ gone = true;
6305
+ canvas.remove();
6306
+ refused("the WebGL2 context was lost", shot);
6307
+ });
6308
+ const refuse = (why, next) => {
6309
+ if (!gone)
6310
+ free();
6311
+ gone = true;
6312
+ refused(why, next);
6313
+ };
6314
+ return {
6315
+ canvas,
6316
+ paint(next) {
6317
+ if (gone)
6318
+ return refuse("the WebGL2 context is gone", next);
6319
+ if (Math.max(next.width, next.height) > widest) {
6320
+ return refuse(`the picture, ${next.width} by ${next.height} px, is larger than MAX_TEXTURE_SIZE, ${widest}`, next);
6321
+ }
6322
+ gl.getError();
6323
+ try {
6324
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, next);
6325
+ } catch (error) {
6326
+ return refuse(uploadWhy(error), next);
6327
+ }
6328
+ const failed = gl.getError();
6329
+ if (failed !== gl.NO_ERROR)
6330
+ return refuse(`the picture could not be uploaded: WebGL2 error 0x${failed.toString(16)}`, next);
6331
+ gl.generateMipmap(gl.TEXTURE_2D);
6332
+ shot = next;
6333
+ if (look)
6334
+ draw(look);
6335
+ },
6336
+ draw,
6337
+ release() {
6338
+ if (gone)
6339
+ return;
6340
+ gone = true;
6341
+ free();
6342
+ }
6343
+ };
5605
6344
  }
5606
6345
 
5607
6346
  // src/engine/barshot.ts
@@ -5720,12 +6459,12 @@ function corners(radius, by = 0) {
5720
6459
  function roundRect(rect, radius) {
5721
6460
  const { x, y, width, height } = rect;
5722
6461
  const [a, b, c, d] = corners(radius).map((r) => Math.max(0, Math.min(r, width / 2, height / 2)));
5723
- const arc = (r = 0) => `A${r} ${r} 0 0 1`;
6462
+ const arc2 = (r = 0) => `A${r} ${r} 0 0 1`;
5724
6463
  return [
5725
- `M${x + a} ${y}H${x + width - b}${arc(b)} ${x + width} ${y + b}`,
5726
- `V${y + height - c}${arc(c)} ${x + width - c} ${y + height}`,
5727
- `H${x + d}${arc(d)} ${x} ${y + height - d}`,
5728
- `V${y + a}${arc(a)} ${x + a} ${y}Z`
6464
+ `M${x + a} ${y}H${x + width - b}${arc2(b)} ${x + width} ${y + b}`,
6465
+ `V${y + height - c}${arc2(c)} ${x + width - c} ${y + height}`,
6466
+ `H${x + d}${arc2(d)} ${x} ${y + height - d}`,
6467
+ `V${y + a}${arc2(a)} ${x + a} ${y}Z`
5729
6468
  ].join("");
5730
6469
  }
5731
6470
  function drawMock(mock, screenSize, href) {
@@ -5734,14 +6473,6 @@ function drawMock(mock, screenSize, href) {
5734
6473
  viewBox: `0 0 ${mock.width} ${mock.height}`,
5735
6474
  "aria-hidden": "true"
5736
6475
  });
5737
- if (mock.image && href) {
5738
- const { x: x2, y: y2, width: width2, height: height2, turn: turn2 } = mock.image;
5739
- const image = svgNode("image", { href, x: x2, y: y2, width: width2, height: height2 });
5740
- if (turn2 !== null)
5741
- image.setAttribute("transform", `matrix(0 -1 1 0 0 ${turn2})`);
5742
- svg.append(image);
5743
- return svg;
5744
- }
5745
6476
  const part = (shape) => svgNode("rect", {
5746
6477
  class: shape.kind,
5747
6478
  x: shape.x,
@@ -5750,6 +6481,16 @@ function drawMock(mock, screenSize, href) {
5750
6481
  height: shape.height,
5751
6482
  rx: shape.radius
5752
6483
  });
6484
+ if (mock.image && href) {
6485
+ const { x: x2, y: y2, width: width2, height: height2, turn: turn2, clockwise, over: over2 } = mock.image;
6486
+ const image = svgNode("image", { href, x: x2, y: y2, width: width2, height: height2 });
6487
+ if (turn2 !== null) {
6488
+ image.setAttribute("transform", clockwise ? `matrix(0 1 -1 0 ${turn2} 0)` : `matrix(0 -1 1 0 0 ${turn2})`);
6489
+ } else if (over2)
6490
+ image.setAttribute("transform", `matrix(-1 0 0 -1 ${mock.width} ${mock.height})`);
6491
+ svg.append(image, ...mock.parts.map(part));
6492
+ return svg;
6493
+ }
5753
6494
  const opening = { x: mock.inset.left, y: mock.inset.top, ...screenSize };
5754
6495
  const { x, y, width, height } = mock.body;
5755
6496
  const front = { x: x + BAND, y: y + BAND, width: width - 2 * BAND, height: height - 2 * BAND };
@@ -5764,7 +6505,7 @@ function div(className) {
5764
6505
  node.className = className;
5765
6506
  return node;
5766
6507
  }
5767
- function round(radii) {
6508
+ function round2(radii) {
5768
6509
  return radii.map((radius) => `${radius}px`).join(" ");
5769
6510
  }
5770
6511
  function fill(node) {
@@ -5842,7 +6583,7 @@ function roughOf(frame2, glass, value, size, color) {
5842
6583
  const { device, posture, orientation, browser, edgeToEdge } = value;
5843
6584
  return shootPage(frame2, glass, size, color, [device, posture, orientation, browser, edgeToEdge].join(" "));
5844
6585
  }
5845
- function pictureOf(frame2, glass, value, size, color, copy) {
6586
+ function pictureOf2(frame2, glass, value, size, color, copy) {
5846
6587
  const shown2 = glass.querySelector(":scope > .browser");
5847
6588
  const bars = shown2 ? document.importNode(shown2, true) : null;
5848
6589
  if (bars)
@@ -6050,8 +6791,8 @@ function pose(turning, layout, open, shown2, still2) {
6050
6791
  const fade = (value) => value >= 1 ? "" : String(Math.round(Math.max(0, value) * 1000) / 1000);
6051
6792
  model.style.opacity = fade(shown2);
6052
6793
  turning.still.canvas.style.opacity = fade(still2);
6053
- const over = [turning.inner.stage.lastElementChild, turning.outer.stage.lastElementChild];
6054
- const by = [turning.inner.gl, turning.inner.pictures, turning.outer.gl, turning.outer.pictures, 0, ...over];
6794
+ const over2 = [turning.inner.stage.lastElementChild, turning.outer.stage.lastElementChild];
6795
+ const by = [turning.inner.gl, turning.inner.pictures, turning.outer.gl, turning.outer.pictures, 0, ...over2];
6055
6796
  const { lit } = turning;
6056
6797
  if (lit && lit.shot === shot && lit.by.every((one, index) => one === by[index]))
6057
6798
  return;
@@ -6191,9 +6932,9 @@ function turnTo(turn2, to, done) {
6191
6932
  if (spin)
6192
6933
  window.cancelAnimationFrame(spin.frame);
6193
6934
  const time = MORPH_TIME.turn * Math.abs(to.angle - from.angle) / 90;
6194
- const over = cover?.share ?? 0;
6935
+ const over2 = cover?.share ?? 0;
6195
6936
  const across = to.angle === 0 ? 0 : 1;
6196
- coverTo(turn2.cover, over);
6937
+ coverTo(turn2.cover, over2);
6197
6938
  const going = { spin: turn2, pose: from, frame: 0, done };
6198
6939
  spin = going;
6199
6940
  let begin = null;
@@ -6202,7 +6943,7 @@ function turnTo(turn2, to, done) {
6202
6943
  const elapsed = now - begin;
6203
6944
  going.pose = poseAt(from, to, elapsed, time);
6204
6945
  stand(turn2, going.pose);
6205
- coverTo(turn2.cover, coverAt(over, across, elapsed, time));
6946
+ coverTo(turn2.cover, coverAt(over2, across, elapsed, time));
6206
6947
  if (elapsed < time) {
6207
6948
  going.frame = window.requestAnimationFrame(step);
6208
6949
  return;
@@ -6292,7 +7033,7 @@ function leafOf(side, picture, turning2, across) {
6292
7033
  const { rect } = turning2;
6293
7034
  const screen = placeAt(div(""), whole);
6294
7035
  screen.style.background = "#000";
6295
- screen.style.borderRadius = round(radii);
7036
+ screen.style.borderRadius = round2(radii);
6296
7037
  if (href)
6297
7038
  screen.style.boxShadow = `0 0 0 ${UNDER}px #000`;
6298
7039
  node.append(screen);
@@ -6308,7 +7049,7 @@ function leafOf(side, picture, turning2, across) {
6308
7049
  dark.style.inset = "-100%";
6309
7050
  dark.style.background = "#000";
6310
7051
  const stage = placeAt(div(""), { ...whole, x: whole.x - rect.x, y: whole.y - rect.y });
6311
- stage.style.borderRadius = round(radii);
7052
+ stage.style.borderRadius = round2(radii);
6312
7053
  stage.style.overflow = "hidden";
6313
7054
  if (picture.bars)
6314
7055
  stage.append(picture.bars);
@@ -6322,9 +7063,9 @@ function leafOf(side, picture, turning2, across) {
6322
7063
  veil.style.width = node.style.width;
6323
7064
  veil.style.height = node.style.height;
6324
7065
  const shade = placeAt(div(""), rect);
6325
- shade.style.borderRadius = round(turning2.radii);
7066
+ shade.style.borderRadius = round2(turning2.radii);
6326
7067
  const freeEdge = placeAt(div(""), rect);
6327
- freeEdge.style.borderRadius = round(turning2.radii);
7068
+ freeEdge.style.borderRadius = round2(turning2.radii);
6328
7069
  veil.append(shade, freeEdge);
6329
7070
  const leaf = {
6330
7071
  pane: turning2.pane,
@@ -6378,8 +7119,10 @@ function copiesOf(layout, open, closed, pictures) {
6378
7119
  inner.screen.style.clipPath = layout.across ? `inset(${-far}px ${short(whole.x + whole.width - layout.hinge)}px ${-far}px ${-far}px)` : `inset(${short(layout.hinge - whole.y)}px ${-far}px ${-far}px ${-far}px)`;
6379
7120
  return { inner, outer };
6380
7121
  }
6381
- function build(scene, layout, open, closed, pictures, found) {
7122
+ function build(scene, layout, open, closed, pictures, found, flip) {
6382
7123
  const layer = div("fold");
7124
+ if (flip)
7125
+ layer.style.transform = "rotate(180deg)";
6383
7126
  const place2 = div("");
6384
7127
  let turning2;
6385
7128
  const shots2 = found && shotsOf(layout, open, closed, pictures, found);
@@ -6422,9 +7165,11 @@ function retake(going) {
6422
7165
  const { size } = going.faces.open;
6423
7166
  const color = scene.background();
6424
7167
  const last = going.pictures.open;
6425
- if (roughOf(scene.frame, scene.glass, values.open, size, color) === last.shot)
7168
+ const rough = roughOf(scene.frame, scene.glass, values.open, size, color);
7169
+ if ((going.flip && rough ? flipPicture({ shot: rough, painted: null, bars: null }, size).shot : rough) === last.shot)
6426
7170
  return;
6427
- const next = pictureOf(scene.frame, scene.glass, values.open, size, color, copyPage(scene.frame));
7171
+ const taken = pictureOf2(scene.frame, scene.glass, values.open, size, color, copyPage(scene.frame));
7172
+ const next = going.flip ? flipPicture(taken, size) : taken;
6428
7173
  going.pictures = { ...going.pictures, open: next };
6429
7174
  const put = (shot) => {
6430
7175
  if (fold !== going || going.pictures.open !== next)
@@ -6435,18 +7180,18 @@ function retake(going) {
6435
7180
  else
6436
7181
  paintLeaf(turning2.inner, shot);
6437
7182
  };
6438
- const rough = () => {
7183
+ const roughly = () => {
6439
7184
  if (next.shot)
6440
7185
  put(next.shot);
6441
7186
  };
6442
7187
  if (!next.painted)
6443
- rough();
7188
+ roughly();
6444
7189
  else {
6445
7190
  next.painted.then((drawn) => {
6446
7191
  if (drawn)
6447
7192
  paintDrawn(next, drawn, put);
6448
7193
  else
6449
- rough();
7194
+ roughly();
6450
7195
  });
6451
7196
  }
6452
7197
  }
@@ -6490,7 +7235,7 @@ function show(going) {
6490
7235
  going.waiting = false;
6491
7236
  const { open: open2, closed } = going.faces;
6492
7237
  drop(going.parts);
6493
- going.parts = build(going.scene, going.layout, open2, closed, going.pictures, found);
7238
+ going.parts = build(going.scene, going.layout, open2, closed, going.pictures, found, going.flip);
6494
7239
  going.drawn = "";
6495
7240
  }
6496
7241
  const { layout, parts } = going;
@@ -6523,8 +7268,14 @@ function show(going) {
6523
7268
  const opened = unit.posture === "open";
6524
7269
  const own = opened ? layout.unfolded.scale : layout.folded.scale;
6525
7270
  const drift = shots2 ? shotsDrift(shots2.shots, layout, shots2.inside, shots2.outside, open, unit.posture) : { wide: 1, tall: 1, x: 0, y: 0 };
6526
- const body = opened ? { x: 0, y: 0 } : layout.shut;
6527
- const to = { x: x + (drift.wide * body.x + drift.x) * scale, y: y + (drift.tall * body.y + drift.y) * scale };
7271
+ const body = opened ? { x: 0, y: 0, ...layout.open } : layout.shut;
7272
+ const laid = {
7273
+ x: x + (drift.wide * body.x + drift.x) * scale,
7274
+ y: y + (drift.tall * body.y + drift.y) * scale,
7275
+ width: body.width * drift.wide * scale,
7276
+ height: body.height * drift.tall * scale
7277
+ };
7278
+ const to = going.flip ? flipRect(laid, going.flip) : laid;
6528
7279
  const by = { x: to.x - unit.corner.x, y: to.y - unit.corner.y };
6529
7280
  const size = unit.base * scale / own;
6530
7281
  scene.unit.style.transform = `translate(${by.x}px, ${by.y}px) scale(${size * drift.wide}, ${size * drift.tall})`;
@@ -6542,7 +7293,9 @@ function stillClip(going, shots2, inside, own) {
6542
7293
  const under = inside ? 1 + 2 * (shots2?.inner.over ?? 0) : 0;
6543
7294
  const hinge = at(layout.hinge + (layout.across ? -under : under));
6544
7295
  const far = 1e5;
6545
- const points = (corners2) => `polygon(${corners2.map(([px, py]) => `${px}px ${py}px`).join(", ")})`;
7296
+ const { width, height } = layout.open;
7297
+ const placed = ([px, py]) => going.flip ? [at(width) - px, at(height) - py] : [px, py];
7298
+ const points = (corners2) => `polygon(${corners2.map(placed).map(([px, py]) => `${px}px ${py}px`).join(", ")})`;
6546
7299
  if (!shots2 || going.still < 1) {
6547
7300
  return layout.across ? points([[hinge, -far], [far, -far], [far, far], [hinge, far]]) : points([[-far, -far], [far, -far], [far, hinge], [-far, hinge]]);
6548
7301
  }
@@ -6709,14 +7462,18 @@ function foldDevice(from, value, scene, draw, held = false) {
6709
7462
  coverTo(scene.cover, 0);
6710
7463
  scene.glass.append(scene.cover);
6711
7464
  const color = scene.background();
6712
- const now = sideOf(scene, from, scene.screenRect());
6713
- const next = sideOf(scene, value, to);
6714
7465
  const opening = value.posture === "open";
6715
7466
  const across = (opening ? value : from).orientation === "landscape";
7467
+ const { letterbox } = scene;
7468
+ const flip = !across && formOf(from.device, "closed")?.clockwise === true ? { width: letterbox.clientWidth, height: letterbox.clientHeight } : null;
7469
+ const turn2 = (face) => flip ? flipFace(face, flip) : face;
7470
+ const now = turn2(sideOf(scene, from, scene.screenRect()));
7471
+ const next = turn2(sideOf(scene, value, to));
6716
7472
  const copy = copyPage(scene.frame);
6717
- const before = pictureOf(scene.frame, scene.glass, from, now.size, color, copy);
7473
+ const turnPicture = (picture, size) => flip ? flipPicture(picture, size) : picture;
7474
+ const before = turnPicture(pictureOf2(scene.frame, scene.glass, from, now.size, color, copy), now.size);
6718
7475
  draw(value);
6719
- const after = pictureOf(scene.frame, scene.glass, value, next.size, color, copy);
7476
+ const after = turnPicture(pictureOf2(scene.frame, scene.glass, value, next.size, color, copy), next.size);
6720
7477
  draw(from);
6721
7478
  const closed = opening ? now : next;
6722
7479
  const open = opening ? next : now;
@@ -6728,7 +7485,7 @@ function foldDevice(from, value, scene, draw, held = false) {
6728
7485
  const target = openOf((held ? from : value).posture);
6729
7486
  if (duo)
6730
7487
  decodeFoldShots(start, Math.sign(start - target));
6731
- const parts = build(scene, layout, open, closed, pictures, duo ? foldShots() : null);
7488
+ const parts = build(scene, layout, open, closed, pictures, duo ? foldShots() : null, flip);
6732
7489
  const wait = held ? null : { since: null, painted: !before.painted && !after.painted };
6733
7490
  if (wait && !wait.painted) {
6734
7491
  Promise.all([before.painted, after.painted]).then(() => {
@@ -6756,6 +7513,7 @@ function foldDevice(from, value, scene, draw, held = false) {
6756
7513
  wait,
6757
7514
  parts,
6758
7515
  unit: measure2(scene, from.posture),
7516
+ flip,
6759
7517
  fresh: null,
6760
7518
  still: 0,
6761
7519
  out: 1,
@@ -6870,12 +7628,22 @@ function clear3(color) {
6870
7628
  return color === "" || color === "transparent" || /[,/]\s*0\)$/.test(color);
6871
7629
  }
6872
7630
  function paintVeil(veil) {
7631
+ veil.className = "veil";
6873
7632
  const root = getComputedStyle(document.documentElement);
6874
7633
  const body = document.body ? getComputedStyle(document.body).backgroundColor : "";
6875
7634
  const color = [root.backgroundColor, body].find((value) => !clear3(value));
6876
7635
  veil.style.background = color ?? "Canvas";
6877
7636
  veil.style.colorScheme = root.colorScheme || "normal";
6878
7637
  }
7638
+ function paintCover(scene) {
7639
+ scene.veil.className = "veil loading";
7640
+ scene.veil.style.background = "";
7641
+ scene.veil.style.colorScheme = scene.scheme();
7642
+ }
7643
+ function evenHole(hole) {
7644
+ const round3 = Math.max(...hole.radius);
7645
+ return { ...hole, radius: [round3, round3, round3, round3] };
7646
+ }
6879
7647
  function openVeiled(scene, share) {
6880
7648
  seen = { veil: share, content: 0, hole: scene.fullRect() };
6881
7649
  paintVeil(scene.veil);
@@ -6957,6 +7725,8 @@ function moveHole(scene, to, time) {
6957
7725
  }
6958
7726
  function placeHole(scene, hole) {
6959
7727
  seen.hole = hole;
7728
+ scene.veil.style.setProperty("--dot-x", `${hole.x + hole.width / 2}px`);
7729
+ scene.veil.style.setProperty("--dot-y", `${hole.y + hole.height / 2}px`);
6960
7730
  const path3 = holePath(hole);
6961
7731
  if (path3 === cut2)
6962
7732
  return;
@@ -6968,7 +7738,7 @@ function track2(scene) {
6968
7738
  const step = () => {
6969
7739
  if (tracking !== frame2)
6970
7740
  return;
6971
- placeHole(scene, scene.screenRect());
7741
+ placeHole(scene, evenHole(scene.screenRect()));
6972
7742
  frame2 = window.requestAnimationFrame(step);
6973
7743
  tracking = frame2;
6974
7744
  };
@@ -7018,7 +7788,7 @@ async function perform(scene, step, target, instant) {
7018
7788
  } else if (step.kind === "layout") {
7019
7789
  scene.layout();
7020
7790
  } else if (step.kind === "mat") {
7021
- const to = step.to === "screen" ? scene.screenRect : step.to === "round" ? () => rounded(scene.fullRect()) : scene.fullRect;
7791
+ const to = step.to === "screen" ? () => evenHole(scene.screenRect()) : step.to === "round" ? () => rounded(scene.fullRect()) : scene.fullRect;
7022
7792
  const going = run;
7023
7793
  await moveHole(scene, to, instant ? 0 : step.time);
7024
7794
  if (step.to === "screen" && !instant && going?.live())
@@ -7035,13 +7805,16 @@ async function perform(scene, step, target, instant) {
7035
7805
  }
7036
7806
  function start(scene, target) {
7037
7807
  if (!clipped) {
7038
- seen = { veil: 1, content: 1, hole: scene.screenRect() };
7039
- paintVeil(scene.veil);
7808
+ seen = { veil: 1, content: 1, hole: evenHole(scene.screenRect()) };
7809
+ if (target === "closed")
7810
+ paintVeil(scene.veil);
7040
7811
  scene.veil.style.opacity = "1";
7041
7812
  cut2 = "";
7042
7813
  placeHole(scene, seen.hole);
7043
7814
  clipped = true;
7044
7815
  }
7816
+ if (target === "open")
7817
+ paintCover(scene);
7045
7818
  const shown3 = { ...seen, covered: scene.covered(), open: sameHole(seen.hole, scene.fullRect()) };
7046
7819
  const next = sequence(plan(shown3, target), target);
7047
7820
  run = next;
@@ -7167,7 +7940,7 @@ function rimsAt(splash, plan2, time) {
7167
7940
  }
7168
7941
  return rims;
7169
7942
  }
7170
- function round2(value) {
7943
+ function round3(value) {
7171
7944
  return Math.round(value * 10) / 10;
7172
7945
  }
7173
7946
  function pathOf(rims) {
@@ -7176,8 +7949,8 @@ function pathOf(rims) {
7176
7949
  const [first] = curve;
7177
7950
  if (!first)
7178
7951
  return "";
7179
- const start2 = `M${round2(first[0].x)} ${round2(first[0].y)}`;
7180
- const rest3 = curve.map(([, c1, c2, end]) => `C${round2(c1.x)} ${round2(c1.y)} ${round2(c2.x)} ${round2(c2.y)} ${round2(end.x)} ${round2(end.y)}`);
7952
+ const start2 = `M${round3(first[0].x)} ${round3(first[0].y)}`;
7953
+ const rest3 = curve.map(([, c1, c2, end]) => `C${round3(c1.x)} ${round3(c1.y)} ${round3(c2.x)} ${round3(c2.y)} ${round3(end.x)} ${round3(end.y)}`);
7181
7954
  return `${start2}${rest3.join("")}Z`;
7182
7955
  }).join("");
7183
7956
  }
@@ -7319,8 +8092,6 @@ function explain(box2, refusal, again) {
7319
8092
  };
7320
8093
  button.addEventListener("click", run2);
7321
8094
  why.append(button);
7322
- if (retry.now)
7323
- run2();
7324
8095
  }
7325
8096
  }
7326
8097
 
@@ -7711,8 +8482,45 @@ var VIEWPORT_CSS = `
7711
8482
  top: 0;
7712
8483
  left: 0;
7713
8484
  }
8485
+ /* Holds the cover over the frame. */
8486
+ .page { position: relative; }
7714
8487
  /* Where a phone's browser leaves the page in its screen. */
7715
8488
  .page.placed { position: absolute; }
8489
+ /* Over the frame while its page loads or a host loads it again, so a browser's
8490
+ error page never flashes: the frame's own canvas, a dot that breathes. */
8491
+ .loading {
8492
+ position: absolute;
8493
+ inset: 0;
8494
+ display: flex;
8495
+ align-items: center;
8496
+ justify-content: center;
8497
+ background: Canvas;
8498
+ color: CanvasText;
8499
+ /* The user's own scheme, unless the knob forces one. */
8500
+ color-scheme: light dark;
8501
+ pointer-events: none;
8502
+ }
8503
+ .loading[hidden] { display: none; }
8504
+ /* The veil wears the cover between two devices, its dot in the mat's opening. */
8505
+ .veil.loading::after {
8506
+ position: absolute;
8507
+ left: var(--dot-x, 50%);
8508
+ top: var(--dot-y, 50%);
8509
+ translate: -50% -50%;
8510
+ }
8511
+ .loading::after {
8512
+ content: "";
8513
+ width: 6px;
8514
+ height: 6px;
8515
+ border-radius: 50%;
8516
+ background: currentColor;
8517
+ opacity: 0.25;
8518
+ animation: devknobs-breathe 1.2s ease-in-out infinite alternate;
8519
+ }
8520
+ @keyframes devknobs-breathe { to { opacity: 0.08; } }
8521
+ @media (prefers-reduced-motion: reduce) {
8522
+ .loading::after { animation: none; }
8523
+ }
7716
8524
  iframe {
7717
8525
  display: block;
7718
8526
  border: 0;
@@ -7799,7 +8607,7 @@ function visionFilter(value) {
7799
8607
  }
7800
8608
 
7801
8609
  // src/engine/width.ts
7802
- var NAME2 = "width";
8610
+ var NAME = "width";
7803
8611
  var RIDE_SLOW = 50;
7804
8612
  var FRAME_API_WAIT = 1500;
7805
8613
  var ZOOM_SETTLE = 200;
@@ -7848,7 +8656,14 @@ var notice = null;
7848
8656
  var exit2 = null;
7849
8657
  var askWhy = null;
7850
8658
  var framed = null;
8659
+ var loader = null;
8660
+ var ANSWER_WAIT = 6000;
7851
8661
  var refusals = 0;
8662
+ var loadCover = null;
8663
+ var coverPoll = 0;
8664
+ var coverCap = 0;
8665
+ var COVER_POLL = 50;
8666
+ var COVER_CAP = ANSWER_WAIT + 2000;
7852
8667
  var current = {
7853
8668
  ...UNFRAMED,
7854
8669
  scheme: "system",
@@ -7907,16 +8722,78 @@ function onRefused(handler) {
7907
8722
  function onFramed(handler) {
7908
8723
  framed = handler;
7909
8724
  }
8725
+ function onLoader(handler) {
8726
+ loader = handler;
8727
+ }
8728
+ function navigate(target, url) {
8729
+ if (!loader?.(target, url))
8730
+ target.src = url;
8731
+ }
7910
8732
  function whyRefused() {
7911
8733
  const box2 = notice;
7912
8734
  const turn2 = ++refusals;
7913
8735
  if (!box2)
7914
8736
  return;
7915
8737
  explain(box2, null, loadAgain);
7916
- askWhy?.(frameUrl).then((refusal) => {
7917
- if (turn2 === refusals && notice === box2 && !box2.hidden)
7918
- explain(box2, refusal, loadAgain);
7919
- }, () => {});
8738
+ if (!askWhy) {
8739
+ hideCover();
8740
+ box2.hidden = false;
8741
+ return;
8742
+ }
8743
+ showCover();
8744
+ const still2 = () => turn2 === refusals && notice === box2;
8745
+ let answered = false;
8746
+ const show2 = (refusal) => {
8747
+ if (!still2())
8748
+ return;
8749
+ hideCover();
8750
+ box2.hidden = false;
8751
+ explain(box2, refusal, loadAgain);
8752
+ };
8753
+ window.setTimeout(() => {
8754
+ if (!answered)
8755
+ show2(null);
8756
+ }, ANSWER_WAIT);
8757
+ askWhy(frameUrl).then((refusal) => {
8758
+ answered = true;
8759
+ const retry = refusal?.retry;
8760
+ if (!retry?.now) {
8761
+ show2(refusal);
8762
+ return;
8763
+ }
8764
+ retry.run().then(() => {
8765
+ if (still2())
8766
+ loadAgain();
8767
+ }, (error) => show2({ why: error instanceof Error ? error.message : String(error) }));
8768
+ }, () => {
8769
+ answered = true;
8770
+ show2(null);
8771
+ });
8772
+ }
8773
+ function readable() {
8774
+ const doc = frameDocument();
8775
+ return doc !== null && doc.URL !== "about:blank" && doc.readyState !== "loading";
8776
+ }
8777
+ function showCover() {
8778
+ if (!loadCover)
8779
+ return;
8780
+ clearTimeout(coverPoll);
8781
+ clearTimeout(coverCap);
8782
+ loadCover.hidden = false;
8783
+ const look = () => {
8784
+ if (readable())
8785
+ hideCover();
8786
+ else
8787
+ coverPoll = window.setTimeout(look, COVER_POLL);
8788
+ };
8789
+ coverPoll = window.setTimeout(look, COVER_POLL);
8790
+ coverCap = window.setTimeout(hideCover, COVER_CAP);
8791
+ }
8792
+ function hideCover() {
8793
+ clearTimeout(coverPoll);
8794
+ clearTimeout(coverCap);
8795
+ if (loadCover)
8796
+ loadCover.hidden = true;
7920
8797
  }
7921
8798
  function loadAgain() {
7922
8799
  if (!frame3)
@@ -7926,7 +8803,8 @@ function loadAgain() {
7926
8803
  refusals += 1;
7927
8804
  if (notice)
7928
8805
  notice.hidden = true;
7929
- frame3.src = frameUrl;
8806
+ showCover();
8807
+ navigate(frame3, frameUrl);
7930
8808
  }
7931
8809
  function onZoom(handler) {
7932
8810
  zoomTo = handler;
@@ -7948,9 +8826,13 @@ function onLoad() {
7948
8826
  loadedAt = performance.now();
7949
8827
  const doc = frameDocument();
7950
8828
  if (notice)
7951
- notice.hidden = doc !== null;
8829
+ notice.hidden = true;
7952
8830
  if (doc === null)
7953
8831
  whyRefused();
8832
+ else {
8833
+ refusals += 1;
8834
+ hideCover();
8835
+ }
7954
8836
  locate();
7955
8837
  const view = frameWindow();
7956
8838
  if (view && doc) {
@@ -8141,8 +9023,8 @@ function showMock(mock, place2) {
8141
9023
  const zoom = place2.zoom;
8142
9024
  glass.style.left = mock ? `${mock.inset.left * zoom}px` : "";
8143
9025
  glass.style.top = mock ? `${mock.inset.top * zoom}px` : "";
8144
- const round3 = mock ? corners(mock.screenRadius).map((radius) => `${radius * zoom}px`) : [];
8145
- glass.style.borderRadius = round3.join(" ");
9026
+ const round4 = mock ? corners(mock.screenRadius).map((radius) => `${radius * zoom}px`) : [];
9027
+ glass.style.borderRadius = round4.join(" ");
8146
9028
  glass.style.boxShadow = href ? `0 0 0 ${UNDER * zoom}px #000` : "";
8147
9029
  if (mock && mockDrawing) {
8148
9030
  mockDrawing.style.width = `${mock.width * zoom}px`;
@@ -8185,8 +9067,10 @@ function showMat(size) {
8185
9067
  mat = next;
8186
9068
  }
8187
9069
  function bodyFor(value) {
8188
- return bodyOf(value, resize);
9070
+ const body = bodyOf(value, resize);
9071
+ return body && over2 && openUpright(shapeOf(value)) ? flipMock(body) : body;
8189
9072
  }
9073
+ var over2 = false;
8190
9074
  function resize() {
8191
9075
  if (!frame3 || !letterbox || !stage || !drawing || !screen || !readout || !caption)
8192
9076
  return;
@@ -8232,6 +9116,10 @@ function resize() {
8232
9116
  frame3.style.colorScheme = current.scheme;
8233
9117
  else
8234
9118
  frame3.style.removeProperty("color-scheme");
9119
+ if (loadCover)
9120
+ loadCover.style.colorScheme = coverScheme();
9121
+ if (veil?.className === "veil loading")
9122
+ veil.style.colorScheme = coverScheme();
8235
9123
  frame3.style.filter = visionFilter(current.vision);
8236
9124
  checkZoom();
8237
9125
  warmFold();
@@ -8380,6 +9268,7 @@ foldableShown(() => {
8380
9268
  return scene && { scene, value: current };
8381
9269
  });
8382
9270
  function foldDevice2(value, held2 = false) {
9271
+ over2 = caseOver(shapeOf(current), shapeOf(value), over2);
8383
9272
  landGlide();
8384
9273
  touchDot?.rest();
8385
9274
  return foldDevice(current, value, foldScene(), draw, held2);
@@ -8390,7 +9279,7 @@ function hidePage() {
8390
9279
  return;
8391
9280
  covered = true;
8392
9281
  cover2(body);
8393
- const style = ensureStyle(NAME2);
9282
+ const style = ensureStyle(NAME);
8394
9283
  style.textContent = "html{overflow:hidden!important}:popover-open:not([data-devknobs]){display:none!important}";
8395
9284
  const node = styleNode(style);
8396
9285
  if (node)
@@ -8403,7 +9292,7 @@ function showPage() {
8403
9292
  stopKeepingStyle?.();
8404
9293
  stopKeepingStyle = null;
8405
9294
  uncover2();
8406
- removeStyle(NAME2);
9295
+ removeStyle(NAME);
8407
9296
  }
8408
9297
  function remounted() {
8409
9298
  if (covered) {
@@ -8463,6 +9352,9 @@ function handBack() {
8463
9352
  showPage();
8464
9353
  window.scrollTo({ left: scroll.x, top: scroll.y, behavior: "instant" });
8465
9354
  }
9355
+ function coverScheme() {
9356
+ return current.scheme === "system" ? "" : current.scheme;
9357
+ }
8466
9358
  function scene() {
8467
9359
  if (!host || !back || !veil)
8468
9360
  return null;
@@ -8472,6 +9364,7 @@ function scene() {
8472
9364
  content: contentNodes,
8473
9365
  screenRect,
8474
9366
  fullRect,
9367
+ scheme: coverScheme,
8475
9368
  covered: () => covered,
8476
9369
  hidePage,
8477
9370
  painted,
@@ -8562,12 +9455,12 @@ function open(veiled, first) {
8562
9455
  waiting2.then(() => {
8563
9456
  if (frame3 !== opened)
8564
9457
  return;
8565
- opened.src = frameUrl;
8566
9458
  opened.addEventListener("load", onLoad);
9459
+ navigate(opened, frameUrl);
8567
9460
  });
8568
- } else {
8569
- frame3.src = frameUrl;
9461
+ } else if (!loader) {
8570
9462
  frame3.addEventListener("load", onLoad);
9463
+ navigate(frame3, frameUrl);
8571
9464
  }
8572
9465
  track({
8573
9466
  view: frameWindow,
@@ -8578,7 +9471,11 @@ function open(veiled, first) {
8578
9471
  notice = createNotice(() => exit2?.());
8579
9472
  pageBox = document.createElement("div");
8580
9473
  pageBox.className = "page";
8581
- pageBox.append(frame3);
9474
+ loadCover = document.createElement("div");
9475
+ loadCover.className = "loading";
9476
+ loadCover.setAttribute("aria-hidden", "true");
9477
+ pageBox.append(frame3, loadCover);
9478
+ showCover();
8582
9479
  glass.append(pageBox);
8583
9480
  browser = createBrowser(glass, frame3, resize, onReloading, painted);
8584
9481
  touchDot = createTouchDot({
@@ -8603,6 +9500,10 @@ function open(veiled, first) {
8603
9500
  window.addEventListener("resize", resize);
8604
9501
  window.addEventListener("pagehide", keep2);
8605
9502
  body.append(host);
9503
+ if (!waiting2 && loader) {
9504
+ frame3.addEventListener("load", onLoad);
9505
+ navigate(frame3, frameUrl);
9506
+ }
8606
9507
  stopKeeping = keepMounted(host, { restored: remounted });
8607
9508
  const now = scene();
8608
9509
  if (veiled !== null && now)
@@ -8665,6 +9566,8 @@ function teardown() {
8665
9566
  mockDrawing = null;
8666
9567
  mockKey = "";
8667
9568
  frame3 = null;
9569
+ hideCover();
9570
+ loadCover = null;
8668
9571
  notice = null;
8669
9572
  readout = null;
8670
9573
  caption = null;
@@ -8707,9 +9610,10 @@ function close(follow5) {
8707
9610
  else
8708
9611
  window.scrollTo({ left: scroll.x, top: scroll.y, behavior: "instant" });
8709
9612
  }
8710
- function apply2(value) {
9613
+ function apply3(value) {
8711
9614
  const shape = shapeOf(value);
8712
9615
  const from = heading;
9616
+ over2 = caseOver(from, shape, over2);
8713
9617
  heading = shape;
8714
9618
  const first = !settled;
8715
9619
  settled = true;
@@ -8811,6 +9715,7 @@ function apply2(value) {
8811
9715
  function reset() {
8812
9716
  close(false);
8813
9717
  heading = "closed";
9718
+ over2 = false;
8814
9719
  settled = false;
8815
9720
  }
8816
9721
  // src/engine/foldhand.ts