| 1 | //go:build browser |
| 2 | |
| 3 | package calendartest |
| 4 | |
| 5 | // Steps the browser tests share, on chromedp v0.21's generic API (rastrillo |
| 6 | // v0.30): what v0.14's builder calls did, in one place. |
| 7 | |
| 8 | import ( |
| 9 | "context" |
| 10 | "net/http" |
| 11 | |
| 12 | "github.com/chromedp/cdproto/cdp" |
| 13 | "github.com/chromedp/cdproto/emulation" |
| 14 | "github.com/chromedp/cdproto/network" |
| 15 | "github.com/chromedp/chromedp" |
| 16 | ) |
| 17 | |
| 18 | // evalInto is a step that evaluates js and decodes the result into out. A |
| 19 | // script that returns null or undefined leaves out as it was, as chromedp |
| 20 | // v0.14's Evaluate did; v0.21's fails on null for a type that cannot be |
| 21 | // nil, so the result is read through a pointer. A nil out drops it. |
| 22 | func evalInto[T any](out *T, js string, opts ...chromedp.EvaluateOption) chromedp.Action[chromedp.Void] { |
| 23 | return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { |
| 24 | v, err := chromedp.Evaluate[*T](js, opts...)(ctx, t) |
| 25 | if err != nil { |
| 26 | return err |
| 27 | } |
| 28 | if v != nil && out != nil { |
| 29 | *out = *v |
| 30 | } |
| 31 | return nil |
| 32 | }) |
| 33 | } |
| 34 | |
| 35 | // evalOnly is a step that evaluates js for its effect alone. |
| 36 | func evalOnly(js string) chromedp.Action[chromedp.Void] { |
| 37 | return evalInto[any](nil, js) |
| 38 | } |
| 39 | |
| 40 | // command is a step that sends one protocol command and drops its result. |
| 41 | func command[P, R any](c cdp.Command[P, R], params P) chromedp.Action[chromedp.Void] { |
| 42 | return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { |
| 43 | _, err := cdp.Call(ctx, t, c, params) |
| 44 | return err |
| 45 | }) |
| 46 | } |
| 47 | |
| 48 | // setCookie is a step that sets a sign-in cookie for the rig's origin. |
| 49 | func setCookie(origin string, c *http.Cookie) chromedp.Action[chromedp.Void] { |
| 50 | return command(network.SetCookie, network.SetCookieParams{ |
| 51 | Name: c.Name, Value: c.Value, URL: origin + "/", |
| 52 | HTTPOnly: &c.HttpOnly, SameSite: network.CookieSameSiteLax, |
| 53 | }) |
| 54 | } |
| 55 | |
| 56 | // deviceMetrics is a step that sets a mobile viewport width × height at 1x. |
| 57 | func deviceMetrics(width, height int64) chromedp.Action[chromedp.Void] { |
| 58 | return command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{ |
| 59 | Width: width, Height: height, DeviceScaleFactor: 1, Mobile: true, |
| 60 | }) |
| 61 | } |
| 62 | |
| 63 | // forceLight is a step that puts the page in the light scheme, whatever the |
| 64 | // machine's (this Mac is dark). |
| 65 | func forceLight() chromedp.Action[chromedp.Void] { |
| 66 | return command(emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{ |
| 67 | Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: "light"}}, |
| 68 | }) |
| 69 | } |
| 70 | |