oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calendar
2
3import (
4 "amadan.net/oficina/estilo.git/chrome"
5 "amadan.net/oficina/estilo.git/credits"
6 "amadan.net/oficina/estilo.git/menu"
7 "amadan.net/oficina/home/connect"
8 "bytes"
9 "embed"
10 "html/template"
11 "net/http"
12
13 "amadan.net/rastrillo/rastrillo"
14 "amadan.net/rastrillo/rastrillo/sessions"
15 "amadan.net/rastrillo/rastrillo/ui"
16
17 "amadan.net/oficina/calendar/internal/calendar/icons"
18)
19
20// all:, not a bare pattern. The default embed pattern SKIPS files whose
21// names begin with "_" or "." — so templates/_chip.html, the partial
22// every view shares, silently did not exist in the embedded filesystem
23// and the app panicked at init with "pattern matches no files". The
24// prefix is what makes the underscore convention safe here.
25//
26//go:embed all:templates all:static
27var appFS embed.FS
28
29// assets fingerprints static/: {{asset "static/tokens.css"}} in a
30// template returns a content-hashed URL, served immutable-cacheable by
31// the handler New mounts.
32var assets = rastrillo.NewAssets(appFS)
33
34// pageNames is every page this app renders. Kept as a list rather than
35// discovered from the filesystem so a template that is never rendered
36// is a compile-time-visible mistake rather than dead weight nobody
37// notices.
38var pageNames = []string{
39 "home", "signin", "errors", "credits", "day", "week", "month", "agenda",
40 "event", "event_form", "event_delete", "calendars", "share",
41 "import", "import_done", "settings", "reminders",
42 "booking_pages", "booking_page_form",
43 "book_page", "book_sent", "book_hold", "book_manage", "book_gone",
44}
45
46// pages is one *template.Template per page, each combining layout.html
47// with that page's own file — separate trees so every page can define a
48// template named "content" without colliding with the others.
49var pages = map[string]*template.Template{}
50
51func init() {
52 for _, name := range pageNames {
53 // ui's partials and their helpers first, so every page can
54 // call one without registering anything. WithIcons points
55 // ui's two icon seams at the app's own set — both of them,
56 // always: passing only icon would leave iconAssets on the
57 // framework default and silently break cdn and js delivery.
58 t := template.Must(template.New("layout").
59 Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))).
60 Funcs(template.FuncMap{"asset": assets.Path}).
61 Funcs(appFuncs).
62 ParseFS(ui.Templates(), "*.html"))
63 // estilo's menu and chrome: the bar, the account menu, the error
64 // page and the sign-in door. chrome's templates call ui's field and
65 // callout partials, already in the tree, and name menu's.
66 t = template.Must(t.ParseFS(menu.Templates(), "templates/*.html"))
67 t = template.Must(t.ParseFS(chrome.Templates(), "templates/*.html"))
68 t = template.Must(t.ParseFS(appFS, "templates/layout.html", "templates/_chip.html",
69 "templates/_quickadd.html", "templates/_quickpane.html", "templates/_bookingpane.html",
70 "templates/"+name+".html"))
71 // home_link for the account pages. The Keymail continuation is
72 // the door's own state now (estilo-signin-screen draws its meta
73 // refresh), so connect's oauth page is not parsed.
74 t = template.Must(t.ParseFS(connect.Templates(), "templates/home_link.html"))
75 pages[name] = template.Must(t.ParseFS(credits.Templates(), "templates/*.html"))
76 }
77}
78
79// fragments is the partials on their own, with no layout around them.
80//
81// It exists for the panes that are fetched and swapped into a page that
82// is already open — quick add's, and the booking form's. Rendering one
83// through pages[...] would wrap it in the whole shell — a second <html>
84// inside the one on screen.
85var fragments = template.Must(
86 template.Must(template.New("fragments").
87 Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))).
88 Funcs(template.FuncMap{"asset": assets.Path}).
89 Funcs(appFuncs).
90 ParseFS(ui.Templates(), "*.html")).
91 ParseFS(appFS, "templates/_quickpane.html", "templates/_bookingpane.html"))
92
93// renderFragment writes one partial, with no shell.
94func renderFragment(w http.ResponseWriter, name string, data any) {
95 var buf bytes.Buffer
96 if err := fragments.ExecuteTemplate(&buf, name, data); err != nil {
97 http.Error(w, "Something went wrong.", http.StatusInternalServerError)
98 return
99 }
100 w.Header().Set("Content-Type", "text/html; charset=utf-8")
101 buf.WriteTo(w)
102}
103
104// PageData is the shell every page renders inside. Data is NAMED
105// rather than embedded, so a template always says ".Data.Events" and
106// can never accidentally resolve a page field where it meant a shell
107// one, or the reverse.
108type PageData struct {
109 // Title is the <title>, and usually the page's own <h1>.
110 Title string
111
112 // WholeTitle, when set, is the whole <title>: the door's is rastrillo's,
113 // which names Calendar already ("Sign in to Calendar").
114 WholeTitle string
115
116 // ThemeAttr is the value of <html data-theme>, or "" for auto —
117 // which the layout renders as no attribute at all. See theme.go:
118 // this is the light/dark SCHEME, never rastrillo's theme NAME.
119 ThemeAttr string
120
121 // Mode is the stored preference behind ThemeAttr ("auto", "light",
122 // "dark"), so the switcher can mark its current choice.
123 Mode string
124
125 // Chrome is the suite-owned 52px bar. It is built in page so error
126 // pages and ordinary pages cannot accidentally grow different chrome.
127 Chrome chrome.Bar
128
129 // Path is the current request path, so a form that posts elsewhere
130 // and redirects back — the mode switcher — can name where "back" is.
131 Path string
132
133 // SignedIn and Address describe the viewer. Address is shown in the
134 // account menu and nowhere else.
135 HomeEnabled bool
136 SignedIn bool
137 Address string
138 Partial bool // team mode's partial view (team_answers.go)
139
140 // QuickPane is the quick-add box's first paint. It is on the SHELL
141 // rather than on each page's own data because the box is in the
142 // shell: a page that forgot to build one would render an empty
143 // pane and look like a broken feature rather than a missing field.
144 QuickPane QuickPaneView
145
146 Data any
147}
148
149// page builds the shell for a request. One place decides how the theme,
150// the viewer and the return path are read, so no handler can forget one
151// and render a page whose switcher silently does nothing.
152func (h *handlers) page(r *http.Request, title string, data any) PageData {
153 mode := chrome.Appearance(r)
154 pd := PageData{
155 Title: title,
156 HomeEnabled: h.homeEnabled,
157 ThemeAttr: chrome.ThemeAttr(mode),
158 Mode: string(mode),
159 Path: r.URL.Path,
160 QuickPane: emptyPane(),
161 Data: data,
162 Partial: h.team != nil && requestUnknown(r),
163 }
164 // Every door (each state, the confirm step and refusal on /auth/*,
165 // signed out) is drawn signed out: the brand alone. Never from the
166 // viewer: a session the door just refused is still on the context.
167 _, door := data.(signinView)
168 door = door || r.URL.Path == "/signin" || r.URL.Path == "/signin/local" || r.URL.Path == "/signed-out"
169 if id, ok := h.viewer(r); ok && !door {
170 pd.SignedIn = true
171 pd.Address = id.Address
172 }
173 pd.Chrome = calendarChrome(r, pd.SignedIn, pd.Address, mode, title, h.directory)
174 if pd.Chrome.Account != nil && h.offerHomeConnect(r) {
175 pd.Chrome.Account.Items = append(pd.Chrome.Account.Items, menu.Item{Href: "/account/home", Label: connect.English["menu_action"]})
176 }
177 if door {
178 pd.Chrome.Account, pd.Chrome.SignIn = nil, nil
179 }
180 h.addReminderLink(r, &pd.Chrome) // in-app reminders (handlers_reminders.go)
181 return pd
182}
183
184// render executes a page into a buffer before anything touches the
185// wire: a template error becomes a clean 500 instead of garbage
186// appended to a half-written page, and headers stay settable until the
187// status line is written.
188//
189// The error string is fixed and says nothing about what failed.
190// html/template's own errors quote the data being rendered, so passing
191// one through to the browser would be a way to read a stranger's
192// calendar back out of an error page.
193func render(w http.ResponseWriter, name string, data any) {
194 var buf bytes.Buffer
195 if err := pages[name].ExecuteTemplate(&buf, "layout", data); err != nil {
196 http.Error(w, "Something went wrong.", http.StatusInternalServerError)
197 return
198 }
199 buf.WriteTo(w)
200}
201
202// renderStatus is render answering with status, written only once the
203// page has rendered, so a template error is still a clean 500.
204func renderStatus(w http.ResponseWriter, name string, status int, data any) {
205 var buf bytes.Buffer
206 if err := pages[name].ExecuteTemplate(&buf, "layout", data); err != nil {
207 http.Error(w, "Something went wrong.", http.StatusInternalServerError)
208 return
209 }
210 w.Header().Set("Content-Type", "text/html; charset=utf-8")
211 w.WriteHeader(status)
212 buf.WriteTo(w)
213}
214
215// ErrorPage renders the shared error page for status, with ref being
216// rastrillo's own request reference or empty when there is none. It is
217// the rastrillo.ErrorPageFunc cmd/calendar/main.go points
218// Options.ErrorPage at, so a panic gets the same page a handled failure
219// would.
220func ErrorPage(w http.ResponseWriter, r *http.Request, status int, ref string) {
221 id, ok := viewer(r)
222 _, session := sessions.Current(r)
223 renderError(w, r, status, ref, id.Address, ok || session, "")
224}
225
226// errorPage is ErrorPage for a request the app is serving: the viewer is
227// resolved the way every other page resolves it (h.viewer, which knows a
228// Home session's person), so the error page carries the same chrome. A
229// live session whose person cannot be resolved still gets the account
230// menu, to sign out from, with no identity in it.
231func (h *handlers) errorPage(w http.ResponseWriter, r *http.Request, status int, ref string) {
232 if status == http.StatusNotFound && requestUnknown(r) {
233 h.teamUnavailable(w, r) // team mode: retry, never "not found"
234 return
235 }
236 id, ok := h.viewer(r)
237 _, session := sessions.Current(r)
238 if !ok {
239 id.Address = ""
240 }
241 renderError(w, r, status, ref, id.Address, ok || session, h.directory)
242}
243
244func renderError(w http.ResponseWriter, r *http.Request, status int, ref, address string, signed bool, directory string) {
245 mode := chrome.Appearance(r)
246 title, errPage := errorData(r, status, ref)
247 w.WriteHeader(status)
248 render(w, "errors", PageData{
249 Title: title,
250 ThemeAttr: chrome.ThemeAttr(mode),
251 Mode: string(mode),
252 Path: r.URL.Path,
253 SignedIn: signed,
254 Address: address,
255 Chrome: calendarChrome(r, signed, address, mode, title, directory),
256 Data: errPage,
257 })
258}
259
260// errorData is the shared-chrome spec's §3.2 table: the tab title, then the
261// page's h1, body and primary way back. A 404 never says whether the thing
262// exists (not shared and deleted read the same). A 500 or 503 on a GET
263// offers the same URL again; any other method goes to Calendar, because
264// re-sending a POST from a link is not possible and not wanted.
265func errorData(r *http.Request, status int, ref string) (string, chrome.ErrorPage) {
266 home := chrome.Link{Href: "/", Label: "Go to Calendar"}
267 again := home
268 if r.Method == http.MethodGet {
269 again = chrome.Link{Href: r.URL.RequestURI(), Label: "Try again"}
270 }
271 title, h1, body, cta := "Something went wrong", "Something went wrong", "Try again in a moment. If it keeps happening, quote the reference below.", again
272 switch status {
273 case http.StatusNotFound:
274 title, h1, body, cta = "Page not found", "We can’t find that page", "The link may be out of date, or the page may have moved.", home
275 case http.StatusForbidden:
276 title, h1, body, cta = "No access", "You don’t have access to this page", "Ask whoever runs this team if you think you should.", home
277 case http.StatusServiceUnavailable:
278 title, h1, body, cta = "Calendar is unavailable", "Calendar is unavailable right now", "Try again in a few minutes.", again
279 case http.StatusBadRequest:
280 // Not in the table: a malformed request is the person's link or
281 // form, not our failure, so it reads as the 404's way back.
282 title, h1, body, cta = "Something went wrong", "That request didn’t work", "The link or form may be out of date. Go back and try again.", home
283 }
284 return title, chrome.ErrorPage{Status: status, Title: h1, Body: body, Home: cta, Ref: ref, RefLabel: "Reference:"}
285}
286
287// notFound has an HTML page only for navigation. API/feed clients retain the
288// ordinary compact 404, which is both the useful representation and prevents
289// an HTML error page from being mistaken for a successful feed response.
290func (h *handlers) notFound(w http.ResponseWriter, r *http.Request) {
291 if !containsHTML(r.Header.Get("Accept")) {
292 http.NotFound(w, r)
293 return
294 }
295 w.WriteHeader(http.StatusNotFound)
296 title, page := errorData(r, http.StatusNotFound, "")
297 render(w, "errors", h.page(r, title, page))
298}
299