oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1import SwiftUI
2
3/// The sky behind everything (P9): the web's atmosphere, drawn as it is in
4/// internal/look/static/app.css. The sky's gradient (`body`), two beams of
5/// warm light that sway and breathe (`.light`, `.light::after`), and four
6/// banks of coloured fog on their own slow paths whose colours drift
7/// (`.fog`, `.fog i`), on the same keyframes, periods and delays.
8///
9/// - Drawn by a `Canvas` under a `TimelineView` at 30 fps, paused while the
10/// scene isn't active (a hidden window, a backgrounded app).
11/// - Reduce Motion holds it at the stylesheet's reduced-motion pose: no
12/// animation, the beam at `skewX(-14deg)`. Snapshots draw that pose too
13/// (`.skyFrozen()`).
14public struct Sky: View {
15 @Environment(\.colorScheme) private var scheme
16 @Environment(\.accessibilityReduceMotion) private var reduceMotion
17 @Environment(\.skyFrozen) private var frozen
18 @Environment(\.scenePhase) private var phase
19
20 public init() {}
21
22 public var body: some View {
23 let palette = Palette(scheme)
24 Group {
25 if reduceMotion || frozen {
26 Canvas { context, size in SkyPainter(palette: palette, time: nil).paint(&context, size) }
27 } else {
28 TimelineView(.animation(minimumInterval: 1.0 / 30, paused: phase != .active)) { timeline in
29 Canvas { context, size in
30 SkyPainter(palette: palette, time: timeline.date.timeIntervalSinceReferenceDate).paint(&context, size)
31 }
32 }
33 }
34 }
35 .ignoresSafeArea()
36 .accessibilityHidden(true)
37 .allowsHitTesting(false)
38 }
39}
40
41public extension EnvironmentValues {
42 /// Draws the sky still, at its reduced-motion pose (snapshots, and any
43 /// screen that must not move).
44 @Entry var skyFrozen: Bool = false
45}
46
47public extension View {
48 func skyFrozen(_ frozen: Bool = true) -> some View { environment(\.skyFrozen, frozen) }
49}
50
51/// One frame of the sky. `time` nil is the reduced-motion pose.
52struct SkyPainter {
53 let palette: Palette
54 let time: TimeInterval?
55
56 func paint(_ context: inout GraphicsContext, _ size: CGSize) {
57 let rect = CGRect(origin: .zero, size: size)
58 let p = palette
59 // html { background: var(--sky) } under body's gradient, 165°:
60 // --sky-1 0%, --sky-2 at --sky-stop, --sky-3 100%.
61 context.fill(Path(rect), with: .color(p[.sky]))
62 let (start, end) = Self.cssLine(degrees: 165, in: rect)
63 context.fill(Path(rect), with: .linearGradient(
64 Gradient(stops: [.init(color: p[.sky1], location: 0), .init(color: p[.sky2], location: p.skyStop), .init(color: p[.sky3], location: 1)]),
65 startPoint: start, endPoint: end))
66 // .light sits before .fog in the page: the fog is drawn over it.
67 drawLight(&context, size)
68 drawFog(&context, size)
69 }
70
71 // MARK: The light
72
73 /// `.light`: top -30%, left 18%, 46% × 120% of the page, a gradient from
74 /// --beam-1 through --beam-2 (45%) to --beam-3 (78%), blurred 40px,
75 /// swaying from its top centre (`sway` 9s) and breathing (`breathe`
76 /// 6s). Its `::after` (left 95%, 45% × 85% of the beam, --shine-1 into
77 /// --shine-2 at 80%) sways on its own (13s, -4s, alternate-reverse)
78 /// inside it, under the same blur and breath.
79 func drawLight(_ context: inout GraphicsContext, _ size: CGSize) {
80 let p = palette
81 let beam = CGRect(x: size.width * 0.18, y: -size.height * 0.30, width: size.width * 0.46, height: size.height * 1.2)
82 let shine = CGRect(x: beam.minX + beam.width * 0.95, y: beam.minY, width: beam.width * 0.45, height: beam.height * 0.85)
83 let parent: CGAffineTransform, child: CGAffineTransform, opacity: Double
84 if let time {
85 let sway = Self.easeInOut(Self.progress(time, period: 9, delay: 0, reverse: false))
86 parent = Self.skewTranslate(beam, skew: Self.mix(-24, -4, sway), translate: Self.mix(-0.18, 0.22, sway))
87 let swayAfter = Self.easeInOut(Self.progress(time, period: 13, delay: -4, reverse: true))
88 child = Self.skewTranslate(shine, skew: Self.mix(-24, -4, swayAfter), translate: Self.mix(-0.18, 0.22, swayAfter))
89 opacity = Self.mix(0.45, 1, Self.easeInOut(Self.progress(time, period: 6, delay: 0, reverse: false)))
90 } else {
91 // @media (prefers-reduced-motion): .light { transform: skewX(-14deg) }
92 parent = Self.skewTranslate(beam, skew: -14, translate: 0)
93 child = .identity
94 opacity = 1
95 }
96 context.drawLayer { layer in
97 layer.addFilter(.blur(radius: 40))
98 layer.opacity = opacity
99 var beamLayer = layer
100 beamLayer.concatenate(parent)
101 beamLayer.fill(Path(beam), with: .linearGradient(
102 Gradient(stops: [.init(color: p[.beam1], location: 0), .init(color: p[.beam2], location: 0.45), .init(color: p[.beam3], location: 0.78)]),
103 startPoint: CGPoint(x: beam.midX, y: beam.minY), endPoint: CGPoint(x: beam.midX, y: beam.maxY)))
104 var shineLayer = layer
105 shineLayer.concatenate(child.concatenating(parent))
106 shineLayer.fill(Path(shine), with: .linearGradient(
107 Gradient(stops: [.init(color: p[.shine1], location: 0), .init(color: p[.shine2], location: 0.8)]),
108 startPoint: CGPoint(x: shine.midX, y: shine.minY), endPoint: CGPoint(x: shine.midX, y: shine.maxY)))
109 }
110 }
111
112 // MARK: The fog
113
114 struct Bank {
115 let token: Palette.Token
116 let width: Double, height: Double
117 /// left (or, with `fromRight`, right) and bottom, in % of the fog's box.
118 let x: Double, bottom: Double
119 let fromRight: Bool
120 let path: [(tx: Double, ty: Double, scale: Double)]
121 let period: Double, delay: Double
122 let reverse: Bool
123 }
124
125 static let pathA: [(tx: Double, ty: Double, scale: Double)] = [(-0.18, 0.06, 0.9), (0.14, -0.28, 1.25), (0.36, 0.04, 1)]
126 static let pathB: [(tx: Double, ty: Double, scale: Double)] = [(0.16, -0.04, 1.1), (-0.20, 0.22, 0.85), (-0.38, -0.14, 1.2)]
127 static let pathC: [(tx: Double, ty: Double, scale: Double)] = [(0.10, 0.10, 0.8), (-0.32, -0.40, 1.3), (0.28, -0.18, 1)]
128
129 /// `.fog i:nth-child(1…4)`.
130 static let banks: [Bank] = [
131 Bank(token: .lagoon, width: 0.62, height: 0.34, x: -0.04, bottom: 0.10, fromRight: false, path: pathA, period: 12, delay: 0, reverse: false),
132 Bank(token: .orchid, width: 0.58, height: 0.36, x: -0.06, bottom: 0.20, fromRight: true, path: pathB, period: 15, delay: -5, reverse: false),
133 Bank(token: .rose, width: 0.36, height: 0.22, x: 0.40, bottom: 0.02, fromRight: false, path: pathC, period: 10, delay: -3, reverse: false),
134 Bank(token: .fog4, width: 0.70, height: 0.18, x: 0.10, bottom: 0.30, fromRight: false, path: pathB, period: 17, delay: -9, reverse: true),
135 ]
136
137 /// `.fog`: inset -20% of the page, its colours turning (`tint`, 18s,
138 /// hue-rotate -20° to 28°); each bank an ellipse blurred 56px.
139 func drawFog(_ context: inout GraphicsContext, _ size: CGSize) {
140 let box = CGRect(x: -size.width * 0.2, y: -size.height * 0.2, width: size.width * 1.4, height: size.height * 1.4)
141 let opacities = palette.fogOpacity
142 context.drawLayer { fog in
143 if let time {
144 let tint = Self.easeInOut(Self.progress(time, period: 18, delay: 0, reverse: false))
145 fog.addFilter(.hueRotation(.degrees(Self.mix(-20, 28, tint))))
146 }
147 for (index, bank) in Self.banks.enumerated() {
148 let w = box.width * bank.width, h = box.height * bank.height
149 let x = bank.fromRight ? box.maxX - box.width * bank.x - w : box.minX + box.width * bank.x
150 let y = box.maxY - box.height * bank.bottom - h
151 var frame = CGRect(x: x, y: y, width: w, height: h)
152 if let time {
153 let t = Self.progress(time, period: bank.period, delay: bank.delay, reverse: bank.reverse)
154 let pose = Self.keyframe(bank.path, t)
155 // translate(tx%, ty%) of its own box, then scale about its centre.
156 let centre = CGPoint(x: frame.midX + w * pose.tx, y: frame.midY + h * pose.ty)
157 frame = CGRect(x: centre.x - w * pose.scale / 2, y: centre.y - h * pose.scale / 2, width: w * pose.scale, height: h * pose.scale)
158 }
159 fog.drawLayer { bankLayer in
160 bankLayer.addFilter(.blur(radius: 56))
161 bankLayer.opacity = opacities[index]
162 bankLayer.fill(Path(ellipseIn: frame), with: .color(palette[bank.token]))
163 }
164 }
165 }
166 }
167
168 // MARK: CSS animation, as a browser runs it
169
170 /// Where an `ease-in-out infinite` animation is within its keyframes at
171 /// `time`: 0…1, running `alternate` (or `alternate-reverse`), `delay`
172 /// seconds in (negative: started that long before).
173 static func progress(_ time: TimeInterval, period: Double, delay: Double, reverse: Bool) -> Double {
174 let elapsed = time - delay
175 let cycles = elapsed / period
176 let iteration = floor(cycles)
177 var p = cycles - iteration
178 let backwards = (Int(iteration) % 2 != 0) != reverse
179 if backwards { p = 1 - p }
180 return p
181 }
182
183 /// A three-keyframe path (0%, 50%, 100%) at progress `t`, each half
184 /// eased (`ease-in-out`).
185 static func keyframe(_ path: [(tx: Double, ty: Double, scale: Double)], _ t: Double) -> (tx: Double, ty: Double, scale: Double) {
186 let (a, b, local) = t < 0.5 ? (path[0], path[1], t / 0.5) : (path[1], path[2], (t - 0.5) / 0.5)
187 let e = easeInOut(local)
188 return (mix(a.tx, b.tx, e), mix(a.ty, b.ty, e), mix(a.scale, b.scale, e))
189 }
190
191 /// Between two keyframes' values (`from`, `to`) at eased progress t.
192 static func mix(_ a: Double, _ b: Double, _ t: Double) -> Double { a + (b - a) * t }
193
194 /// `skewX(deg) translateX(t × width)` about the box's top centre
195 /// (`transform-origin: 50% 0`).
196 static func skewTranslate(_ box: CGRect, skew degrees: Double, translate: Double) -> CGAffineTransform {
197 let origin = CGPoint(x: box.midX, y: box.minY)
198 let skew = CGAffineTransform(a: 1, b: 0, c: CGFloat(tan(degrees * .pi / 180)), d: 1, tx: 0, ty: 0)
199 return CGAffineTransform(translationX: -origin.x + box.width * translate, y: -origin.y)
200 .concatenating(skew)
201 .concatenating(CGAffineTransform(translationX: origin.x, y: origin.y))
202 }
203
204 /// `cubic-bezier(.42, 0, .58, 1)` at x.
205 static func easeInOut(_ x: Double) -> Double { cubicBezier(x, 0.42, 0, 0.58, 1) }
206
207 static func cubicBezier(_ x: Double, _ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double) -> Double {
208 if x <= 0 { return 0 }
209 if x >= 1 { return 1 }
210 func sample(_ t: Double, _ a1: Double, _ a2: Double) -> Double {
211 let u = 1 - t
212 return 3 * u * u * t * a1 + 3 * u * t * t * a2 + t * t * t
213 }
214 var lo = 0.0, hi = 1.0, t = x
215 for _ in 0..<30 {
216 let v = sample(t, x1, x2)
217 if abs(v - x) < 1e-6 { break }
218 if v < x { lo = t } else { hi = t }
219 t = (lo + hi) / 2
220 }
221 return sample(t, y1, y2)
222 }
223
224 /// A CSS linear-gradient's line for `degrees` (0° up, clockwise) over
225 /// `rect`: through its centre, as long as the box's projection on it.
226 static func cssLine(degrees: Double, in rect: CGRect) -> (CGPoint, CGPoint) {
227 let a = degrees * .pi / 180
228 let dx = sin(a), dy = -cos(a)
229 let half = (abs(rect.width * dx) + abs(rect.height * dy)) / 2
230 let c = CGPoint(x: rect.midX, y: rect.midY)
231 // Screen y runs down, as CSS's does: (sin, -cos) is already the line.
232 return (CGPoint(x: c.x - dx * half, y: c.y - dy * half), CGPoint(x: c.x + dx * half, y: c.y + dy * half))
233 }
234}
235