oficina / estilo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package chrome is the suite's shared page chrome: the top bar
2// (estilo-bar, with an optional editable title), the account menu, the
3// app switcher, the error page body and the sign-in pages, plus the
4// per-app Appearance preference behind the account menu.
5//
6// Docs is the first consumer and Sheets the second; until Sheets has
7// adopted it this is a home, not an agreed interface (AGENTS.md, the one
8// rule).
9//
10// Templates carry no strings: callers supply every label in their own
11// locale. Parse Templates() together with menu.Templates() and, for the
12// sign-in form, rastrillo's ui.Templates() with ui.Funcs().
13//
14// Script line: everything works with scripts off. Every trigger is a
15// <details> in the one top-level group name="estilo-menus", and every
16// action is a link or a form POST. With scripts off an open panel closes
17// only when its own summary is clicked again (the same stated cost as
18// rastrillo's dropdown); JS() adds Escape and outside-click close, and
19// Escape in the editable title restores it.
20package chrome
21
22import (
23 "embed"
24 "html/template"
25 "net/http"
26 "strings"
27 "time"
28 "unicode"
29
30 "golang.org/x/text/width"
31
32 "amadan.net/oficina/estilo.git/menu"
33 "amadan.net/oficina/estilo.git/sky"
34 "github.com/carlosframework/rastrillo/sessions"
35)
36
37//go:embed chrome.css
38var css []byte
39
40// built is chrome.css as CSS() serves it: the file, with a compact bar's
41// 704px band (buildCSS) after the stacked header's block.
42var built = buildCSS(string(css))
43
44//go:embed chrome.js
45var js []byte
46
47//go:embed templates/*.html
48var templateFS embed.FS
49
50// CSS returns chrome.css, with a compact bar's 704px band in place. Link
51// it after menu.css.
52func CSS() []byte { return append([]byte(nil), built...) }
53
54// The stacked header's 56px block, which every stacked bar takes from
55// 800px, opens after this comment. A compact bar takes the same block from
56// 704px (Paul, 2026-11-28: the desktop header for an iPad in portrait),
57// and nothing else moves: Mapa and Fichas stack too, and their own layouts
58// change at 800px (Fable on c56314e). A media query cannot ask which bar
59// it is, so the band is a copy of the block, made here rather than kept
60// by hand, with every selector scoped to a compact bar.
61const (
62 wideOpens = "/* From 800px, the 56px stacked header:"
63 wideQuery = "@media (min-width: 800px) {"
64 bandQuery = "@media (min-width: 704px) and (max-width: 799.98px) and (not ((max-height: 480px) and (pointer: coarse)))"
65)
66
67func buildCSS(src string) []byte {
68 start, end := wideBounds(src)
69 band := bandQuery + " {\n" + scopeRules(stripComments(src[start:end])) + "}\n"
70 return []byte(src[:end+2] + band + src[end+2:])
71}
72
73// wideBounds is the stacked header block's body: from after its opening
74// brace to its closing brace.
75func wideBounds(src string) (int, int) {
76 at := strings.Index(src, wideOpens)
77 if at < 0 {
78 panic("chrome.css lost the stacked header's block")
79 }
80 open := strings.Index(src[at:], wideQuery)
81 if open < 0 {
82 panic("chrome.css: the stacked header's block is not " + wideQuery)
83 }
84 start := at + open + len(wideQuery)
85 depth := 1
86 for i := start; i < len(src); i++ {
87 switch src[i] {
88 case '{':
89 depth++
90 case '}':
91 depth--
92 if depth == 0 {
93 return start, i
94 }
95 }
96 }
97 panic("chrome.css: the stacked header's block never closes")
98}
99
100// wideBlock is the stacked header block's body, as chrome.css has it.
101func wideBlock(src string) string {
102 start, end := wideBounds(src)
103 return src[start:end]
104}
105
106func stripComments(s string) string {
107 var b strings.Builder
108 for {
109 i := strings.Index(s, "/*")
110 if i < 0 {
111 return b.String() + s
112 }
113 b.WriteString(s[:i])
114 j := strings.Index(s[i:], "*/")
115 if j < 0 {
116 return b.String()
117 }
118 s = s[i+j+2:]
119 }
120}
121
122// scopeRules copies a block's rules, nested @media blocks included, with
123// every selector scoped to a compact bar and every declaration as it was.
124func scopeRules(body string) string {
125 var b strings.Builder
126 for {
127 open := strings.IndexByte(body, '{')
128 if open < 0 {
129 return b.String()
130 }
131 prelude := strings.TrimSpace(body[:open])
132 depth, close := 1, open+1
133 for ; depth > 0; close++ {
134 switch body[close] {
135 case '{':
136 depth++
137 case '}':
138 depth--
139 }
140 }
141 inner := body[open+1 : close-1]
142 if strings.HasPrefix(prelude, "@") {
143 b.WriteString(prelude + " {\n" + scopeRules(inner) + "}\n")
144 } else {
145 sels := splitSelectors(prelude)
146 for i, sel := range sels {
147 sels[i] = scopeSelector(sel)
148 }
149 b.WriteString(strings.Join(sels, ",\n") + " {" + inner + "}\n")
150 }
151 body = body[close:]
152 }
153}
154
155// scopeSelector limits sel to a compact bar: the bar itself or anything
156// inside one. The scope is :where(), so the copy keeps each rule's own
157// specificity and the cascade around it is the original's: the
158// forced-colors border after the block still outweighs the controls'
159// border: 0 (Fable, on 4757ccc). A pseudo-element stays outside :is(),
160// where it is valid; the root's rule asks for a stacked bar that is also
161// compact.
162func scopeSelector(sel string) string {
163 sel = strings.Join(strings.Fields(sel), " ")
164 if strings.HasPrefix(sel, ":root") {
165 return strings.Replace(sel, `[estilo-bar~="stacked"]`, `[estilo-bar~="stacked"][estilo-bar~="compact"]`, 1)
166 }
167 pseudo := ""
168 if i := strings.LastIndex(sel, "::"); i >= 0 && !strings.ContainsAny(sel[i:], "()[] ") {
169 sel, pseudo = sel[:i], sel[i:]
170 }
171 return ":is(" + sel + `):where([estilo-bar~="compact"], [estilo-bar~="compact"] *)` + pseudo
172}
173
174// splitSelectors splits a selector list at its top-level commas, leaving
175// those inside :is(), :has() and the like.
176func splitSelectors(list string) []string {
177 var out []string
178 depth, start := 0, 0
179 for i, r := range list {
180 switch r {
181 case '(':
182 depth++
183 case ')':
184 depth--
185 case ',':
186 if depth == 0 {
187 out = append(out, strings.TrimSpace(list[start:i]))
188 start = i + 1
189 }
190 }
191 }
192 return append(out, strings.TrimSpace(list[start:]))
193}
194
195// JS returns chrome.js, an optional classic script (defer) that closes an
196// open bar panel on Escape or an outside click, restores the editable
197// title on Escape, fits a stacked bar's title field to its title, and
198// switches Appearance in place (saving it with a background POST).
199// Nothing depends on it: without it the title keeps its server-rendered
200// size and Appearance posts and redirects.
201func JS() []byte { return append([]byte(nil), js...) }
202
203// Templates holds estilo-bar, estilo-bar-title, estilo-bar-title-fit,
204// estilo-bar-actions, estilo-bar-action, estilo-account, estilo-switcher, estilo-error, estilo-signin,
205// estilo-signin-screen, estilo-signin-screen-title, estilo-signin-sent,
206// estilo-signed-out and the bar's icons.
207func Templates() embed.FS { return templateFS }
208
209// Link is a labelled destination. Current marks the page being shown.
210type Link struct {
211 Href, Label string
212 Current bool
213}
214
215// App names the app the bar belongs to. Home is the brand's link, the
216// app root; leave it empty on a public read-only page and the brand is
217// plain text. Icon is the brand image URL.
218type App struct {
219 Name, Slug, Home, Icon string
220}
221
222// TitleEdit is the bar's editable title: a form posting Name=Value to
223// Action. Set it only when the person may rename; leave it nil and the
224// read-only Context shows instead.
225type TitleEdit struct {
226 Action, Name, Value string
227 // Label is the input's accessible name ("Document title"); Submit the
228 // button that appears while the field has focus ("Rename").
229 Label, Submit string
230}
231
232// Size is the title field's size attribute in a stacked bar
233// (Bar.Menubar set), where the field is as wide as its title rather than
234// the bar's room. It is the first paint's guess, before any script runs,
235// and with scripts off the only width the field gets, so it errs wide: a
236// field too wide only puts its (unpainted) edge further out, and one too
237// narrow cuts the title off. A size unit is about one average Latin
238// character, so the title is counted in columns: an East Asian wide or
239// fullwidth character (CJK, kana, Hangul, most emoji) is two, a capital
240// one and a half (20 Ws need 1.7 each), anything else one; then a
241// quarter more, rounded up, and never under 4, so an empty or one-letter
242// title still leaves something to click. chrome.js then measures the
243// field and corrects its width; nothing after the title on its row moves
244// when it does.
245func (t TitleEdit) Size() int {
246 halves := 0 // half-columns, so a capital's one and a half stays whole
247 for _, r := range t.Value {
248 switch k := width.LookupRune(r).Kind(); {
249 case k == width.EastAsianWide || k == width.EastAsianFullwidth:
250 halves += 4
251 case unicode.IsUpper(r):
252 halves += 3
253 default:
254 halves += 2
255 }
256 }
257 return max(4, (halves*5+7)/8) // halves/2 columns, times 5/4, rounded up
258}
259
260// Action is one page action. Its Item says what activating it does (a
261// link, a POST, a dialog or a toggle; see menu.Item), so the bar's button
262// and the Menu sheet's row are the same element kind and cannot disagree.
263// Primary marks the page's main action, drawn as the primary button.
264//
265// Docs' actions were all links (chrome.Link). Sheets' Create is a POST,
266// and a link in the sheet would be a GET to the list that creates
267// nothing, so the action carries the item instead.
268type Action struct {
269 menu.Item
270 Primary bool
271 // WideOnly is an action that only means something on a wide screen
272 // (Docs' Format, which toggles an inspector that exists only from
273 // 64rem): the bar hides it below 64rem (estilo-bar-wide) and the
274 // narrow Menu sheet leaves it out.
275 WideOnly bool
276 // Icon is an optional decorative glyph drawn before the label in the
277 // bar (not in the sheet): the app's own inline <svg aria-hidden="true">,
278 // trusted markup the app renders itself. The label still names it.
279 Icon template.HTML
280 // IconOnly draws the action in the bar as its Icon alone (Mapa's and
281 // Fichas' Search, 2026-11-18). Label is then its accessible name
282 // (aria-label) and, followed by Key when there is one, its tooltip on
283 // hover and focus: rastrillo's rst-tip, so "Search ⌘K". The Menu
284 // sheet's row is unchanged, label and key. Without an Icon it is
285 // ignored and the label shows.
286 IconOnly bool
287 // KeyShortcuts is the bar control's aria-keyshortcuts, in ARIA's own
288 // spelling ("Meta+K Control+K"): Key is the shortcut people read,
289 // this the one assistive technology does. Optional.
290 KeyShortcuts string
291}
292
293// BarLabels are the bar's own strings: the skip link (rendered by the
294// app's layout) and the narrow Menu trigger.
295type BarLabels struct {
296 Skip, Menu string
297}
298
299// Bar is estilo-bar's data.
300type Bar struct {
301 App App
302 // Context is the open object's title, read-only. ContextEdit, when
303 // set, replaces it with the editable title.
304 Context string
305 ContextEdit *TitleEdit
306 // Nav is the app's section links; NavLabel their accessible name.
307 Nav []Link
308 NavLabel string
309 // Actions are page actions ("Share…", "Create"): buttons at wide
310 // widths, rows in the Menu sheet below 800px.
311 Actions []Action
312 // Switcher is optional; nil drops it with nothing else to change.
313 Switcher *Switcher
314 // Account is set when someone is signed in. Otherwise SignIn is the
315 // corner's "Sign in" link, and nil leaves the corner empty (on the
316 // sign-in pages themselves).
317 Account *Account
318 SignIn *Link
319 // Sticky pins the bar to the top of the viewport.
320 Sticky bool
321 Labels BarLabels
322 // Menubar is the app's menu bar ([estilo-menubar] markup it rendered
323 // itself, File, Edit...). Set, it makes the bar stacked
324 // (estilo-bar~="stacked"): from 800px the 56px header with the title
325 // over the menus beside a 32px icon, and below 800px the one-row bar
326 // with the menus as a full-width second row under it. The bar's height
327 // is published as --estilo-bar-block-size either way. Trusted markup:
328 // the app's own template output, never user input.
329 Menubar template.HTML
330 // Lead is app markup drawn at the start of the end group, before the
331 // actions, at every width (Docs' undo/redo pair). It never goes into
332 // the Menu sheet, and the bar never hides it, so the app MUST hide it
333 // on narrow screens (Docs hides it below 800px): the end group does
334 // not shrink, and at 320px a lead squeezes the title to nothing.
335 // Trusted markup, like Menubar.
336 //
337 // A bar with Menubar or Lead set draws its end group as one set of
338 // controls (28px pills, the avatar as a circle, a divider before the
339 // account); a bar with neither is unchanged.
340 Lead template.HTML
341 // Compact, set, makes the bar the phone's one row below 704px
342 // (estilo-bar~="compact"; the phone web design, Paul 2026-11-28),
343 // and a stacked compact bar the 56px header from 704px rather than
344 // 800px, with its actions in the bar. The Menu sheet is drawn only for
345 // Nav, and shown in the compact row: Trail is the app's own overflow
346 // for everything else, the actions included.
347 Compact *Compact
348}
349
350// Compact is a compact bar's two slots (Bar.Compact). Below 704px, or on
351// a phone held sideways (a coarse pointer under 30rem tall), the bar is
352// one 52px row: the brand as Back (a chevron and the app's name, to
353// App.Home), the title, the Lead, then Trail. The menubar, the actions,
354// the switcher and the account are not shown there; the app's Trail and
355// its other screens carry them (Docs: the switcher and the account stay
356// on the library, as native's D4 has it). A Nav stays reachable in the
357// Menu sheet, drawn before the Trail. The Lead stays, so an app that
358// sets both draws its lead for the phone itself.
359//
360// Both are trusted markup, the app's own template output. Controls in
361// them may take [estilo-bar-tool], a 44px round control in the accent,
362// and a <details name="estilo-menus"> in the Trail with an [estilo-menu]
363// panel is a drop-down from the bar's inline end, with 44px rows and no
364// shortcut hints (Paul's answer 3: a drop-down, not a sheet).
365type Compact struct {
366 // Trail is drawn at the inline end below 704px (Docs' Aa and •••).
367 Trail template.HTML
368 // Title, when set, replaces the bar's own title below 704px (Docs'
369 // inline title): the page has a large title of its own, and the bar
370 // shows this only once the app's script marks the header folded with
371 // the estilo-bar-folded attribute (when the large title has scrolled
372 // away). Folded, Back is its chevron alone, the app's name kept as its
373 // accessible name, and the bar's hairline appears. Without script the
374 // bar never folds. Left empty, the bar's Context or ContextEdit stays,
375 // one line that fills the room and ends in an ellipsis.
376 Title template.HTML
377}
378
379// Kind is estilo-bar's value: "sticky", "stacked" and "compact", in that
380// order, for whichever apply; empty for none.
381func (b Bar) Kind() string {
382 var k []string
383 if b.Sticky {
384 k = append(k, "sticky")
385 }
386 if b.Menubar != "" {
387 k = append(k, "stacked")
388 }
389 if b.Compact != nil {
390 k = append(k, "compact")
391 }
392 return strings.Join(k, " ")
393}
394
395// AccountLabels are the account menu's headings.
396type AccountLabels struct {
397 SignedInAs, Appearance, Help string
398}
399
400// Account is estilo-account's data.
401type Account struct {
402 // TriggerLabel is the trigger's accessible name ("Account:
403 // paul@example.com"). Initials fills the avatar; empty shows the
404 // person glyph (a hub that cannot read the address).
405 TriggerLabel, Initials string
406 // Name and Address identify who is signed in; either may be empty.
407 Name, Address string
408 Labels AccountLabels
409 // Items are the app's account-scoped pages, after the identity row.
410 Items []menu.Item
411 // Appearance is the Light / Dark / System group; nil omits it.
412 Appearance *AppearanceMenu
413 // Help items come last before Sign out ("Open source" last of all).
414 Help []menu.Item
415 SignOut SignOut
416 // Rail draws the account at the foot of a sidebar rail rather than at
417 // the bar's inline end, for an app whose chrome is a rail (Fichas).
418 // The trigger becomes a row that says who is signed in beside the
419 // avatar, and the panel hangs from the rail's inline start and opens
420 // upward where the rail is the viewport's height (from 800px, the
421 // shell breakpoint). Below that the rail is an in-flow disclosure at
422 // the top of the page, so the panel opens downward like every other.
423 // The menu, its group and its one Sign out are unchanged.
424 Rail bool
425}
426
427// SignOut is the account menu's one Sign out: a POST to Action.
428type SignOut struct {
429 Action, Label string
430}
431
432// AppearanceMenu is the account menu's Appearance form, posting mode and
433// return_to to Action (HandleAppearance).
434type AppearanceMenu struct {
435 Action, Return string
436 Options []AppearanceOption
437}
438
439// AppearanceOption is one button in the Appearance group.
440type AppearanceOption struct {
441 Value Mode
442 Label string
443 Current bool
444}
445
446// Switcher is estilo-switcher's data. Apps are the tiles, in the suite's
447// fixed order; AllApps is the hub directory. Label is the trigger's
448// accessible name and CurrentLabel the hidden "(this app)" on the
449// current tile.
450type Switcher struct {
451 Label, CurrentLabel string
452 Apps []SwitcherApp
453 AllApps menu.Item
454}
455
456// SwitcherApp is one tile.
457type SwitcherApp struct {
458 Name, Href, Icon string
459 Current bool
460}
461
462// ErrorPage is estilo-error's data. Back is shown only for a Referer the
463// app has checked is same-origin; Ref only for a 500, prefixed by
464// RefLabel ("Reference:").
465type ErrorPage struct {
466 Status int
467 Title, Body string
468 Home Link
469 Back *Link
470 Ref, RefLabel string
471}
472
473// Hidden is one hidden form field.
474type Hidden struct {
475 Name, Value string
476}
477
478// SignIn is estilo-signin's data. Error is shown in a negative callout
479// above the form; AddressError in the field's own error slot.
480//
481// The door's words are its own (DoorCopy): the app passes its name, mark,
482// sky and destinations, and Copy only for a locale other than English.
483type SignIn struct {
484 Icon, Lede string
485 // App is the product's name, beside its mark at the head of the card
486 // ("Calendar"); Sky is the sky behind it, sky.For(<the instance's
487 // host>). Both optional. A Sky needs sky.css linked, sky.Handler
488 // mounted at sky.Prefix and img-src data: allowed (the template).
489 App string
490 Sky sky.View
491 Error string
492 Action, Return string
493 Hidden []Hidden
494 Address, AddressError string
495 // Copy replaces the door's English (nil) with another locale's set.
496 Copy *DoorCopy
497}
498
499// SignInScreen is estilo-signin-screen's data: rastrillo's sign-in screen
500// (its ui "signin" partial) drawn as the Oficina door, with the sky behind
501// and the app's mark and name at the card's head (smart-door spec,
502// home docs/superpowers/specs/2026-11-19-smart-door.md, step 2).
503//
504// Duck-typed, because estilo pins the old rastrillo module path and
505// cannot import the release that has the partial: the template reads
506// State.Unavailable and hands State, L and Preview on to the partial by
507// name. So the app must parse its own rastrillo's ui.Templates() with
508// ui.Funcs() alongside this package, or the call to "signin" fails.
509type SignInScreen struct {
510 // Icon is the app's mark at the card's head, and App its name beside
511 // it, which is also the partial's Brand.Name ("Sign in to Docs"), so
512 // it is required. Sky is the sky behind, as for SignIn.
513 Icon, App string
514 Sky sky.View
515 // State is the request's auth.SigninState (or a pointer to one), after
516 // PrepareSigninResponse. With State.Unavailable set, or a nil State,
517 // the template draws nothing at all, not even the door.
518 State any
519 // L is the request's *ui.Localizer, handed to the partial as its L.
520 L any
521 // Preview is the partial's gallery mode; false on a real page.
522 Preview bool
523}
524
525// OficinaGlyph is the Oficina ID glyph, the mark's two fanned cards alone,
526// in currentColor: the icon of "Continue with Oficina ID". Pass it as
527// rastrillo auth's FederatedDoor.Icon. It is never the full-colour app
528// icon, whose gradient tile fights the button's fill (smart-door spec,
529// "How the buttons look"). Inline, so the door makes no request for it and
530// draws no late icon; hidden from assistive technology, because the
531// button's words say what it is. The width and height are only the size
532// with no stylesheet: rastrillo's door sizes it.
533const OficinaGlyph template.HTML = `<svg viewBox="18 20 62 60" width="20" height="20" aria-hidden="true" focusable="false">` +
534 `<rect x="30.62" y="23.78" width="45.60" height="36.48" rx="7.98" fill="currentColor" opacity=".55"/>` +
535 `<rect x="22.64" y="36.32" width="50.16" height="38.76" rx="7.98" fill="currentColor"/></svg>`
536
537// ForgetForm is the signed-out page's "Forget me on this device": a POST
538// to Action, rastrillo auth's Forget (Config.ForgetPath), which forgets
539// how this browser last signed in. Return is posted as return_to when
540// set, and Hidden as written (a CSRF token, for an app whose Forget wants
541// one). Build it with SignInNotice.Forgetting, which supplies the label.
542type ForgetForm struct {
543 Action, Return, Label string
544 Hidden []Hidden
545}
546
547// Text is the button's words: Label, or English's when a copy set left it
548// empty, so the button is never drawn without a name.
549func (f ForgetForm) Text() string {
550 if f.Label == "" {
551 return English.Forget
552 }
553 return f.Label
554}
555
556// SignInNotice is the data of estilo-signin-sent and estilo-signed-out,
557// and of any other notice drawn as the door (the Keymail hand-off, the
558// hub's account pages). For the door's own two, build it with Sent or
559// SignedOut, which supply the heading, body and link label; set Heading,
560// Body and Link directly only for a notice of the app's own.
561type SignInNotice struct {
562 Icon, Heading, Body string
563 App string
564 Sky sky.View
565 Link *Link
566 // Forget is the signed-out page's quiet "Forget me on this device"
567 // form, under its Sign in; nil draws none.
568 Forget *ForgetForm
569 // Copy replaces the door's English (nil) with another locale's set.
570 Copy *DoorCopy
571 // page is the tab title's page, set by Sent and SignedOut.
572 page string
573}
574
575// Initials is the avatar's text: the first letter of name, or else of
576// the address's local part, upper-cased. Empty when neither has a
577// letter or digit, and the account trigger then shows the person glyph.
578func Initials(name, address string) string {
579 source := strings.TrimSpace(name)
580 if source == "" {
581 source, _, _ = strings.Cut(strings.TrimSpace(address), "@")
582 }
583 for _, r := range source {
584 if unicode.IsLetter(r) || unicode.IsDigit(r) {
585 return strings.ToUpper(string(r))
586 }
587 }
588 return ""
589}
590
591// Mode is an Appearance preference.
592type Mode string
593
594const (
595 Light Mode = "light"
596 Dark Mode = "dark"
597 System Mode = "system"
598)
599
600// AppearanceCookie is the host-only cookie holding the preference. It is
601// per app on purpose: each origin remembers its own.
602const AppearanceCookie = "estilo_appearance"
603
604func validMode(v string) (Mode, bool) {
605 switch Mode(v) {
606 case Light, Dark, System:
607 return Mode(v), true
608 }
609 return System, false
610}
611
612// Appearance reads the request's preference. Anything that is not
613// exactly light, dark or system is System.
614func Appearance(r *http.Request) Mode {
615 c, err := r.Cookie(AppearanceCookie)
616 if err != nil {
617 return System
618 }
619 m, _ := validMode(c.Value)
620 return m
621}
622
623// ThemeAttr is the value for <html data-theme>: "light" or "dark", and
624// empty for System, when the layout omits the attribute and the theme follows
625// the operating system.
626func ThemeAttr(m Mode) string {
627 switch m {
628 case Light, Dark:
629 return string(m)
630 }
631 return ""
632}
633
634// AppearanceOptions builds the three buttons in the fixed order Light,
635// Dark, System, with current pressed.
636func AppearanceOptions(current Mode, light, dark, system string) []AppearanceOption {
637 return []AppearanceOption{
638 {Value: Light, Label: light, Current: current == Light},
639 {Value: Dark, Label: dark, Current: current == Dark},
640 {Value: System, Label: system, Current: current == System},
641 }
642}
643
644// HandleAppearance serves the Appearance form's POST: it validates mode
645// against the three values, sets AppearanceCookie for a year and answers
646// 303 to return_to, validated by rastrillo's sessions.SafeReturn (falling
647// back to "/"). Mount it inside the app's CSRF protection and outside its
648// session guard, so a session that expired mid-page cannot turn the click
649// into a sign-in loop. Anything but POST is 405; an unknown mode is 400.
650func HandleAppearance(w http.ResponseWriter, r *http.Request) {
651 if r.Method != http.MethodPost {
652 w.Header().Set("Allow", http.MethodPost)
653 http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
654 return
655 }
656 r.Body = http.MaxBytesReader(w, r.Body, 4096)
657 mode, ok := validMode(r.PostFormValue("mode"))
658 if !ok {
659 http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
660 return
661 }
662 http.SetCookie(w, &http.Cookie{
663 Name: AppearanceCookie,
664 Value: string(mode),
665 Path: "/",
666 MaxAge: int((365 * 24 * time.Hour).Seconds()),
667 Secure: true,
668 HttpOnly: true,
669 SameSite: http.SameSiteLaxMode,
670 })
671 w.Header().Set("Cache-Control", "no-store")
672 http.Redirect(w, r, sessions.SafeReturn(r, "/"), http.StatusSeeOther)
673}
674