oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// editor.go is the browser editor's own surface (spec §3.1): the page
2// the bundle enhances, and the slide HTML its stage and strip fetch.
3//
4// The page is server-rendered whole — the strip with every thumbnail,
5// the stage with the current slide, the notes under it — so the first
6// paint is right before a byte of script has run, and so the one thing
7// the bundle adds is editing. What the bundle needs to know (the deck,
8// the log's seq, the current slide, who this person is) rides on data
9// attributes; every visible string it will ever show is rendered into
10// one too, from the catalog, so the bundle carries no English.
11package slides
12
13import (
14 "context"
15 "encoding/json"
16 "fmt"
17 "html/template"
18 "net/http"
19 "strconv"
20 "strings"
21
22 "github.com/go-chi/chi/v5"
23
24 estilomenu "amadan.net/oficina/estilo.git/menu"
25 "amadan.net/rastrillo/rastrillo"
26
27 "amadan.net/oficina/slides/internal/slides/assist"
28 "amadan.net/oficina/slides/internal/slides/deck"
29 slidehtml "amadan.net/oficina/slides/internal/slides/render"
30)
31
32// stripItem is one slide in the strip: the address of the server's
33// picture of it, its number (1-based; fixtures/strip.mjs renumbers
34// after every change), its label, and whether it is the one on stage.
35//
36// A URL and not markup. The strip used to carry nine whole renderings
37// of the deck scaled down by CSS; each is now one <img> of the SVG
38// thumbs.go draws, which is smaller to send, cheaper to paint, and the
39// same picture the export is (thumbs.go says why at length).
40//
41// Presses and Talk are drawn by the server too (steps and presenter
42// spec §4), so the strip's first paint is its final one: the count of a
43// slide's presses in its picture's corner, and whether it is in the
44// talk ("" for in it, "full" for the full version only, "parked").
45type stripItem struct {
46 ID string
47 Number int
48 Label string
49 Thumb string
50 Current bool
51 Presses int
52 Talk string
53}
54
55// PressesLabel is a slide's count of presses as the strip and the
56// stage's control say it ("1 press", "3 presses"; fixtures/play-through.mjs's
57// pressesWords), "" for none.
58func (p editorPage) PressesLabel(n int) string {
59 switch {
60 case n <= 0:
61 return ""
62 case n == 1:
63 return p.L("presses.one")
64 }
65 return strings.Replace(p.L("presses.many"), "{n}", strconv.Itoa(n), 1)
66}
67
68// TalkLabel is what a strip item says after its title about its place
69// in the talk: "Full version only", "Parked", or "" for in the talk.
70func (p editorPage) TalkLabel(talk string) string {
71 switch talk {
72 case "full":
73 return p.L("talk.full.label")
74 case "parked":
75 return p.L("talk.parked.label")
76 }
77 return ""
78}
79
80// editorPage is the whole editor screen. The Text* fields are the
81// strings the bundle shows at run time — the status line's three
82// states, the link dialog — rendered into data attributes rather than
83// into the DOM, because the bundle decides WHEN to show them and the
84// catalog decides WHAT they say.
85type editorPage struct {
86 shell
87 Title string
88 DeckSqid string
89 Seq int64
90 SlideID string
91 ClientName string
92 ClientColour string
93 BundleSrc string
94
95 NewSlideLabel string
96 DuplicateLabel string
97 UndoLabel string
98 RedoLabel string
99 PresentAction string
100 PresentLabel string
101
102 StripLabel string
103 CurrentLabel string
104 // SlideLabel is the "Slide {n}" template itself, placeholder and
105 // all, for the strip to label a slide with no heading by its
106 // number after the order changes (strip.mjs's labelFor).
107 SlideLabel string
108 Strip []stripItem
109
110 StageLabel string
111 HasSlides bool
112 Stage template.HTML
113 // SlideLayout and SlideBackground are the painted slide's layout
114 // ("flow" or "canvas") and background kind ("theme", "color",
115 // "image"): the card's slide options are rendered as the bundle
116 // fills them for that slide (which fields show, which choice is
117 // made), so the card's first paint is its final size.
118 SlideLayout string
119 SlideBackground string
120 // SlideLit is the layout picture the painted slide lights (spec
121 // §3.1): "free" on a canvas slide, else its template, as
122 // fixtures/layout-pick.mjs's litFor.
123 SlideLit string
124 // SlideTalk is the painted slide's place in the talk, for the Slide
125 // menu's two checkbox rows ("full", "parked" or "").
126 SlideTalk string
127 // SlidePresses is the painted slide's count of presses, for the
128 // stage's presses control at the first paint (0: not drawn).
129 SlidePresses int
130 EmptyTitle string
131 EmptyBody string
132
133 Notes template.HTML
134 // NotesWords is how many words the painted slide's notes hold,
135 // len(strings.Fields(Plain())): the closed notes' tab says so from
136 // the first paint (NotesTab); fixtures/notes-card.mjs's countWords
137 // counts every slide after the same way.
138 NotesWords int
139
140 // InspectorState is the card's data-state, "open" or "closed"
141 // (inspectorState); InspectorExpanded is the same as the Format
142 // button's aria-expanded and the View row's aria-pressed.
143 InspectorState string
144 InspectorExpanded string
145
146 // NotesState is the notes card's data-state, "open" or "closed",
147 // and NotesPressed the View row's aria-pressed (notesState);
148 // NotesHeight its height in px, 0 for the stylesheet's default
149 // (notesHeight).
150 NotesState string
151 NotesPressed string
152 NotesHeight int
153
154 StatusLabel string
155 TextSaved string
156 TextSaving string
157 TextOffline string
158 TextFailed string
159 LinkTitle string
160 LinkURLLabel string
161 LinkInsert string
162 LinkRemove string
163 LinkCancel string
164 NoScriptBody string
165 NoScriptLink string
166 // NoScriptSettings names the settings form (decks.go): the title
167 // and theme without the inspector, for somebody with scripts off.
168 // Shown with SettingsHref, which is the only link to that page.
169 NoScriptSettings string
170
171 // Themes is the deck section's theme picker, the settings screen's
172 // own list with the deck's theme selected.
173 Themes []selectOption
174 // ThemeAccents is each theme's own accent colour as JSON, id to hex:
175 // what the accent field shows once an undo takes a custom accent
176 // away, before the stage has been redrawn to say it.
177 ThemeAccents string
178 // YourFonts is the person's own library families for the deck's two
179 // font fields (deckfonts.go's yourFonts): the CSS name as the value,
180 // the family's name as the label. Another person's library is never
181 // offered, though the deck serves whatever its editors added.
182 // FontsHref is the library, opened beside the editor to upload one;
183 // empty with no object store, where there is no library.
184 YourFonts []selectOption
185 FontsHref string
186 // HasStore says whether this deployment has an object store bound
187 // (Config.Blobs). False disables the image block's file input and
188 // puts the "no store" line in its place — the page says so rather
189 // than the bundle discovering it from a 503 after somebody has
190 // already chosen a file.
191 HasStore bool
192 // AcceptTypes is the file input's accept attribute: §2.7's four
193 // types, from the same map the upload endpoint validates against
194 // (assets.go), so the picker and the gate cannot drift.
195 AcceptTypes string
196 // HasScenes says whether the deck has a scene, so Insert → Scene is
197 // enabled at first paint (the bundle keeps it so as scenes come and
198 // go). SceneAuthors names the actors a scene's author line may show
199 // (scenes and clips spec §5): the deck's scene authors and this
200 // person, actor to label, as JSON. RefusedScene and RefusedSceneBig
201 // are a saved code's refusals ({name} the scene's); SceneLoadFailed
202 // and SceneAgain say the code did not load, and ask for it again.
203 HasScenes bool
204 SceneAuthors string
205 RefusedScene, RefusedSceneBig string
206 SceneLoadFailed, SceneAgain string
207 // RefusedClip and RefusedClipBig are a clip's refusals ({name} the
208 // file's); ClipTypes is the clip picker's accept list (clips.go).
209 RefusedClip, RefusedClipBig string
210 ClipTypes string
211 // The header (I2, after Docs' editor): the deck's own links, each
212 // empty when this person may not use it, so the File menu lists
213 // only what works for them. ViewHref is the viewer (its first
214 // slide: the deck's bare address opens this page); NewDeckAction
215 // where File → New deck posts; CreditsHref Help's Open source.
216 // SettingsHref is the scriptless title-and-theme form, linked from
217 // the <noscript> alone: with scripts on the inspector's Deck section
218 // is those settings, and who can open the deck is Share's.
219 ViewHref, SettingsHref, ShareHref, ExportHref, NotesPageHref string
220 DeleteHref, NewDeckAction, CreditsHref string
221 // QRLinkAction is where a follow-along code asks for its audience
222 // link (qrlink.go): empty when this person may not share the deck,
223 // and then the card has no button and a new code is added empty.
224 QRLinkAction string
225 // Keys are the menus' shortcuts, formatted for this request's
226 // platform by estilo (menu.Shortcut), keyed by command.
227 Keys map[string]string
228 // Layouts is the New slide picker's list (fixtures/slide-layouts.mjs
229 // holds what each one puts on a slide; this is the name and label).
230 Layouts []layoutChoice
231
232 // Assist is the assistant's panel (assist.go), nil with SLIDES_AI
233 // off, and then the header has no Assistant button at all.
234 Assist *assistPanel
235
236 // S holds every other string the inspector, the strip's menu, the
237 // switcher and the canvas overlay show, keyed by the tail of its
238 // catalog key (slides.editor.<key>). The inspector has some ninety
239 // labels; one named field each would be a page type nobody could
240 // read, and the template reads them through L.
241 S map[string]string
242}
243
244// assistPanel is what the assistant's panel offers: where a change
245// applies (this slide, the whole deck) and which model makes it. The
246// model ids are configuration (SLIDES_AI_MODELS), shown as they are:
247// data, like a deck title, not copy.
248type assistPanel struct {
249 Scopes []selectOption
250 Models []selectOption
251}
252
253// modelLabels names each model id in the picker by what follows its
254// vendor ("deepseek/deepseek-v4-flash-0731" is "deepseek-v4-flash-0731"),
255// which is what fits a narrow panel, unless two ids would then read the
256// same, when every one keeps its whole id.
257func modelLabels(ids []string) []string {
258 out := make([]string, len(ids))
259 seen := map[string]bool{}
260 for i, id := range ids {
261 out[i] = id[strings.LastIndexByte(id, '/')+1:]
262 if out[i] == "" || seen[out[i]] {
263 return append([]string(nil), ids...)
264 }
265 seen[out[i]] = true
266 }
267 return out
268}
269
270// layoutChoice is one entry in the New slide picker.
271type layoutChoice struct{ Name, Label string }
272
273// layoutNames is fixtures/slide-layouts.mjs's LAYOUT_NAMES, in its
274// order; TestEditorLayoutsMatchTheBundle holds the two together.
275var layoutNames = []string{"title", "title-text", "title-list", "two-column", "section", "picture", "quote", "blank"}
276
277// L is the template's way to a string in S: {{.L "deck.theme"}}.
278func (p editorPage) L(key string) string { return p.S[key] }
279
280// NotesTab is the closed notes' tab's text (the quieter editor, spec
281// §6.2): notes.tab with no words, else notes.tab.words with {n} the
282// count, as fixtures/notes-card.mjs's refresh writes it.
283func (p editorPage) NotesTab() string {
284 if p.NotesWords > 0 {
285 return strings.Replace(p.L("notes.tab.words"), "{n}", strconv.Itoa(p.NotesWords), 1)
286 }
287 return p.L("notes.tab")
288}
289
290// editorStrings is every key the template reads through L. The list
291// is here, once, so a missing key is a missing label on the page
292// (rastrillo.T's own fallback) rather than a template failure.
293var editorStrings = []string{
294 "strip.actions", "strip.reorder",
295 "view", "view.desktop", "view.phone", "view.both", "view.both.title", "view.phone.readonly", "phone.editing",
296 "group.style", "group.image", "group.description", "group.slide",
297 "deck.settings", "deck.theme", "deck.accent", "deck.accent.reset", "deck.font.heading", "deck.font.body",
298 "font.theme", "font.system", "font.serif", "font.mono", "font.yours", "font.upload",
299 "layout.free", "layout.leave.confirm", "layout.leave", "layout.leave.cancel",
300 "template.title", "template.title-body", "template.two-column", "template.section",
301 "template.image-full", "template.quote", "template.blank",
302 "slide.background", "background.theme", "background.color", "slide.background.color",
303 "slide.transition", "transition.none", "transition.fade",
304 "slide.phone", "slide.phone.inherit", "slide.phone.reflow",
305 "placeholder.notes", "notes.tab", "notes.tab.words", "notes.close", "notes.resize",
306 "slide.add", "slide.move.up", "slide.move.down", "slide.delete", "slide.delete.confirm", "slide.delete.cancel",
307 "type.heading", "type.text", "type.list", "type.quote", "type.image", "type.columns",
308 "type.code", "type.shape", "type.table", "type.divider", "type.spacer", "type.qr",
309 "qr.link", "qr.make",
310 "block.level", "level.1", "level.2", "level.3", "block.size", "size.s", "size.m", "size.l",
311 "block.align", "align.start", "align.center", "align.end",
312 "block.style", "style.bullet", "style.number", "block.cite",
313 "block.fit", "fit.cover", "fit.contain", "block.alt", "block.decorative", "block.radius",
314 "block.image.file", "block.image.hint", "block.image.nostore", "block.image.uploading",
315 "block.image.checking", "block.image.done", "block.image.failed", "block.image.toolarge",
316 "block.image.type", "block.image.altfirst",
317 "assets.unused", "assets.unused.none", "assets.remove",
318 "block.count", "block.language",
319 "block.kind", "kind.rect", "kind.ellipse", "kind.line", "kind.arrow",
320 "block.fill", "block.stroke", "block.strokeWidth", "block.label",
321 "block.rows", "block.cols", "block.header",
322 "region.heading", "region.body", "region.aside", "region.media",
323 "block.box", "box.x", "box.y", "box.w", "box.h", "place.title",
324 "block.forward", "block.back", "block.move.up", "block.move.down",
325 "box.more", "box.place", "box.region", "box.delete",
326 "appears", "appears.slide", "appears.press", "appears.each", "appears.after", "appears.after.press",
327 "presses.one", "presses.many", "presses.exit",
328 "talk.full", "talk.parked", "talk.full.label", "talk.parked.label",
329 "arrive", "arrive.appear", "arrive.fade", "arrive.rise",
330 "block.phone", "block.phone.hidden", "block.phone.order", "block.phone.size", "block.phone.same",
331 "block.phone.override", "block.phone.reset",
332 "canvas.selected",
333 "presence.slide", "presence.block", "presence.more", "presence.joined", "presence.left",
334 "status.error",
335 "head.title", "head.menus", "head.history", "head.format", "head.share", "head.newslide", "head.layouts",
336 "menu.file", "menu.edit", "menu.insert", "menu.slide", "menu.view", "menu.help",
337 "file.newdeck", "file.view", "file.notes", "file.export", "file.deck", "file.delete",
338 "insert.slide", "insert.block", "view.notes", "view.inspector", "view.outline", "outline.none", "help.keys", "help.credits",
339 "keys.title", "keys.close", "keys.newslide", "keys.duplicate", "keys.present", "keys.undo", "keys.redo",
340 "keys.link", "keys.bold", "keys.italic", "keys.reorder", "keys.delete", "keys.code", "keys.highlight",
341 "keys.box.forward", "keys.box.back", "keys.box.up", "keys.box.down", "keys.box.delete", "keys.box.menu",
342 "format.label", "format.b", "format.i", "format.c", "format.h", "format.link",
343 "assist.open", "assist.title", "assist.close", "assist.prompt", "assist.prompt.hint",
344 "assist.scope", "assist.scope.slide", "assist.scope.deck", "assist.model", "assist.ask",
345 "assist.privacy", "assist.working", "assist.applied", "assist.nothing", "assist.undo", "assist.undone",
346 "assist.undo.later", "assist.error.prompt", "assist.error.busy", "assist.error.rate", "assist.error.gone",
347 "assist.error.toolarge", "assist.error.unavailable", "assist.error.timeout", "assist.error.refused",
348 "assist.error.changed", "assist.error.fonts", "assist.error.generic", "assist.error.noslide",
349 "block.scene", "scene.from", "scene.to", "scene.words", "scene.stale", "scene.stale.ask",
350 "scene.missing", "scene.missing.one", "scene.data", "scene.data.table", "scene.data.json",
351 "scene.data.add", "scene.data.remove", "scene.data.invalid", "scene.data.big", "scene.missing.list",
352 "scene.code", "scene.code.preview", "scene.code.save", "scene.code.author",
353 "block.clip", "clip.play", "clip.press", "clip.loop", "clip.once",
354}
355
356// The inspector card's open or closed state (spec §2, §4: Format). A
357// cookie, as Docs' docs-inspector is, so the server renders the state
358// and the first paint is final; localStorage, which it replaces, was
359// only applied after the editor mounted. Written by fixtures/head.mjs.
360const (
361 inspectorOpen = "open"
362 inspectorClosed = "closed"
363 inspectorCookie = "slides-inspector"
364)
365
366// inspectorState reads it, defaulting to open: only exactly "closed" is
367// closed, and the value is compared, never printed.
368func inspectorState(r *http.Request) string {
369 c, err := r.Cookie(inspectorCookie)
370 if err != nil || c.Value != inspectorClosed {
371 return inspectorOpen
372 }
373 return inspectorClosed
374}
375
376// The notes card's open or closed state and its height (spec §5;
377// ruling R21: "never a flash" over §5's "remembered where the switch's
378// state is today"). Cookies, as the inspector's state is, so the server
379// renders both and the first paint is final; localStorage, which they
380// replace, was only applied after the editor mounted, and the card
381// visibly closed or changed height under a slow bundle. Written by
382// fixtures/notes-card.mjs.
383const (
384 notesOpen = "open"
385 notesClosed = "closed"
386 notesCookie = "slides-notes"
387 notesHeightCookie = "slides-notes-height"
388 // The bounds the server holds a remembered height to. The least is
389 // notes-card.mjs's own: the card less its body (HEAD_PX, 26) and two
390 // lines of the notes' 15px at 1.55 (46.5), rounded up. The most is a
391 // sanity bound only; the bundle still holds the card to half the
392 // desk it has.
393 notesMinHeight = 73
394 notesMaxHeight = 2000
395)
396
397// notesState reads the notes' state, defaulting to open: only exactly
398// "closed" is closed, and the value is compared, never printed.
399func notesState(r *http.Request) string {
400 c, err := r.Cookie(notesCookie)
401 if err != nil || c.Value != notesClosed {
402 return notesOpen
403 }
404 return notesClosed
405}
406
407// notesHeight reads the notes' remembered height: a whole number of px
408// (an optional minus sign and up to six digits, nothing else), clamped
409// to [notesMinHeight, notesMaxHeight]. Anything else, or no cookie, is
410// 0: no height, and the stylesheet's default. What is printed is the
411// clamped integer, never the cookie's text.
412func notesHeight(r *http.Request) int {
413 c, err := r.Cookie(notesHeightCookie)
414 if err != nil || c.Value == "" || len(c.Value) > 7 {
415 return 0
416 }
417 n, err := strconv.Atoi(c.Value)
418 if err != nil {
419 return 0
420 }
421 return min(max(n, notesMinHeight), notesMaxHeight)
422}
423
424// editorPlaceholders is what an empty text block says on the stage,
425// by block type (render.Options.Placeholders): the catalog's
426// slides.editor.placeholder.<type>. A new slide's blocks start empty,
427// and without these a fresh slide is a blank rectangle with nowhere to
428// click — the blocks are there, one empty line each, and invisible.
429func editorPlaceholders(r *http.Request) map[string]string {
430 out := map[string]string{}
431 for _, t := range []string{"heading", "text", "list", "quote", "code"} {
432 out[t] = rastrillo.T(r, "slides.editor.placeholder."+t)
433 }
434 return out
435}
436
437// blockTypes is §2.4's vocabulary in the order the add menu lists it
438// (InsertTypes says who is offered which).
439var blockTypes = []string{"heading", "text", "list", "quote", "image", "columns", "code", "shape", "table", "divider", "spacer", "qr"}
440
441// BlockTypes is every kind, for the type labels the bundle reads (a
442// box somebody else added is still named).
443func (p editorPage) BlockTypes() []string { return blockTypes }
444
445// InsertTypes is the Insert menu's list: every kind, less a
446// follow-along code for somebody who may not share the deck, since
447// its link is a share link (qrlink.go) and they could not make one.
448func (p editorPage) InsertTypes() []string {
449 if p.QRLinkAction != "" {
450 return blockTypes
451 }
452 out := make([]string, 0, len(blockTypes))
453 for _, t := range blockTypes {
454 if t != "qr" {
455 out = append(out, t)
456 }
457 }
458 return out
459}
460
461// --- GET /d/{sqid}/edit ---
462
463// deckEditor serves the editor page to deckFor's audience — the owner
464// and, on a team deck, every member. A team deck is edited by the team
465// (live.go's rule for the write endpoints, which this page is the
466// front of), so there is no owner-only branch here.
467func (a *app) deckEditor(w http.ResponseWriter, r *http.Request) {
468 u, ok := a.viewer(w, r)
469 if !ok {
470 return
471 }
472 d, ok := a.deckFor(w, r, u)
473 if !ok {
474 return
475 }
476 h, view, err := a.openDeck(r.Context(), d)
477 if err != nil {
478 a.fail(w, r, "open a deck to edit", err)
479 return
480 }
481 defer h.Close(r.Context())
482
483 base := "/d/" + d.Sqid
484 person := u.viewerLabel()
485 mayShare := a.mayShareDeck(r.Context(), u, d)
486 mayRetitle := a.mayRetitleDeck(r.Context(), u, d)
487 mayDelete := a.mayDeleteDeck(r.Context(), u, d)
488 sh := a.shellFor(r, u, titled(view.Meta.Title))
489 sh.Fonts = newFontGate(r, view, base)
490 keys := map[string]string{}
491 for cmd, chord := range map[string]string{
492 "new-slide": "Mod+Enter", "duplicate-slide": "Mod+D", "present": "Mod+Shift+F",
493 "undo": "Mod+Z", "redo": "Mod+Shift+Z", "link": "Mod+K", "bold": "Mod+B", "italic": "Mod+I", "code": "Mod+E", "highlight": "Mod+Shift+H",
494 "reorder": "Alt+↑", "delete": "Delete",
495 // The selected box's (the quieter editor, spec §4.2; fixtures/box-menu.mjs).
496 "block-forward": "Mod+]", "block-back": "Mod+[", "block-move-up": "Mod+Shift+↑", "block-move-down": "Mod+Shift+↓",
497 "block-menu": "Shift+F10", "block-delete": "Delete",
498 } {
499 keys[cmd] = estilomenu.Shortcut(r, chord)
500 }
501 w.Header().Add("Vary", "User-Agent")
502 layouts := make([]layoutChoice, len(layoutNames))
503 for i, n := range layoutNames {
504 layouts[i] = layoutChoice{Name: n, Label: rastrillo.T(r, "slides.editor.layout."+n)}
505 }
506 page := editorPage{
507 shell: sh,
508 ViewHref: viewerStart(d.Sqid),
509 NotesPageHref: base + "/notes",
510 ExportHref: base + "/export",
511 CreditsHref: "/help/open-source",
512 Keys: keys,
513 Layouts: layouts,
514 Title: view.Meta.Title,
515 DeckSqid: d.Sqid,
516 Seq: d.Seq,
517 ClientName: person,
518 ClientColour: u.Colour,
519 BundleSrc: editorBundlePath(),
520
521 NewSlideLabel: rastrillo.T(r, "slides.editor.slide.new"),
522 DuplicateLabel: rastrillo.T(r, "slides.editor.slide.duplicate"),
523 UndoLabel: rastrillo.T(r, "slides.editor.undo"),
524 RedoLabel: rastrillo.T(r, "slides.editor.redo"),
525 PresentAction: base + "/present",
526 PresentLabel: rastrillo.T(r, "slides.viewer.present"),
527
528 StripLabel: rastrillo.T(r, "slides.editor.strip"),
529 CurrentLabel: rastrillo.T(r, "slides.editor.strip.current"),
530 SlideLabel: rastrillo.T(r, "slides.deck.slide"),
531 StageLabel: rastrillo.T(r, "slides.editor.stage"),
532 EmptyTitle: rastrillo.T(r, "slides.viewer.empty.title"),
533 EmptyBody: rastrillo.T(r, "slides.editor.empty.body"),
534
535 InspectorState: inspectorState(r),
536 InspectorExpanded: strconv.FormatBool(inspectorState(r) == inspectorOpen),
537
538 NotesState: notesState(r),
539 NotesPressed: strconv.FormatBool(notesState(r) == notesOpen),
540 NotesHeight: notesHeight(r),
541
542 StatusLabel: rastrillo.T(r, "slides.editor.status"),
543 TextSaved: rastrillo.T(r, "slides.editor.status.saved"),
544 TextSaving: rastrillo.T(r, "slides.editor.status.saving"),
545 TextOffline: rastrillo.T(r, "slides.editor.status.offline"),
546 TextFailed: rastrillo.T(r, "slides.editor.status.failed"),
547 LinkTitle: rastrillo.T(r, "slides.editor.link.title"),
548 LinkURLLabel: rastrillo.T(r, "slides.editor.link.url"),
549 LinkInsert: rastrillo.T(r, "slides.editor.link.insert"),
550 LinkRemove: rastrillo.T(r, "slides.editor.link.remove"),
551 LinkCancel: rastrillo.T(r, "slides.editor.link.cancel"),
552 NoScriptBody: rastrillo.T(r, "slides.editor.noscript"),
553 NoScriptLink: rastrillo.T(r, "slides.editor.noscript.link"),
554
555 NoScriptSettings: rastrillo.T(r, "slides.editor.noscript.settings"),
556
557 Themes: themeOptions(r, view.Meta.Theme),
558 ThemeAccents: themeAccents(),
559 HasStore: a.cfg.Blobs != nil,
560 AcceptTypes: acceptTypes(),
561
562 HasScenes: len(view.Scenes) > 0,
563 SceneAuthors: a.sceneAuthors(r.Context(), u, view),
564 RefusedScene: rastrillo.T(r, "slides.refused.scene"),
565 RefusedSceneBig: rastrillo.T(r, "slides.refused.scene.big"),
566 RefusedClip: rastrillo.T(r, "slides.refused.clip"),
567 RefusedClipBig: rastrillo.T(r, "slides.refused.clip.big"),
568 ClipTypes: clipTypes(),
569 SceneLoadFailed: rastrillo.T(r, "slides.error.422.heading"),
570 SceneAgain: rastrillo.T(r, "slides.error.again"),
571 S: make(map[string]string, len(editorStrings)),
572 }
573 if a.cfg.Blobs != nil {
574 yours, err := a.yourFonts(r.Context(), u)
575 if err != nil {
576 a.fail(w, r, "list a person's fonts", err)
577 return
578 }
579 page.YourFonts, page.FontsHref = yours, "/fonts"
580 }
581 for _, k := range editorStrings {
582 page.S[k] = rastrillo.T(r, "slides.editor."+k)
583 }
584 if a.assist != nil {
585 page.Assist = &assistPanel{
586 Scopes: []selectOption{
587 {Value: "slide", Label: page.S["assist.scope.slide"], Selected: len(view.Slides) > 0},
588 {Value: "deck", Label: page.S["assist.scope.deck"], Selected: len(view.Slides) == 0},
589 },
590 }
591 page.S["assist.privacy"] = strings.ReplaceAll(page.S["assist.privacy"], "{provider}", assist.Name)
592 labels := modelLabels(a.assist.models)
593 for i, m := range a.assist.models {
594 page.Assist.Models = append(page.Assist.Models, selectOption{Value: m, Label: labels[i], Selected: i == 0})
595 }
596 }
597 if mayShare {
598 page.ShareHref = base + "/share"
599 page.QRLinkAction = base + "/qr-link"
600 }
601 if mayRetitle {
602 page.SettingsHref = base + "/settings"
603 }
604 if mayDelete {
605 page.DeleteHref = base + "/delete"
606 }
607 // New deck only for somebody who may make one (the list's own rule,
608 // decks.go's CanCreate): in team mode a non-member would get a 403.
609 if a.member(u) {
610 page.NewDeckAction = "/decks"
611 }
612
613 if len(view.Slides) == 0 {
614 render(w, "editor", page)
615 return
616 }
617
618 // The page opens on the first slide. Which slide the URL hash
619 // names is the bundle's business — the hash never reaches the
620 // server — and the bundle moves the stage if it says otherwise.
621 page.HasSlides = true
622 page.SlideID = view.Slides[0].ID
623 page.SlideLayout = view.Slides[0].Layout
624 page.SlideBackground = view.Slides[0].Background.Kind
625 page.SlideTalk = view.Slides[0].Talk
626 page.SlidePresses = len(deck.Presses(view.Slides[0], view.Scenes))
627 page.SlideLit = view.Slides[0].Template
628 if page.SlideLayout == "canvas" {
629 page.SlideLit = "free"
630 }
631 // Drawn as the editor will draw it (render/editing.go): when the
632 // editor binds late, to a slide already shown, nothing moves.
633 opt := slidehtml.Options{AssetBase: assetBaseFor(base), Editing: true, Placeholders: editorPlaceholders(r), QRAlt: qrAlt(r), QR: a.followCodes(r.Context(), d, view, base)}
634 stage, err := slidehtml.SlideWith(view, 0, slidehtml.Desktop, opt)
635 if err != nil {
636 a.fail(w, r, "render the stage", err)
637 return
638 }
639 page.Stage = stage
640 page.Notes = slidehtml.Notes(view.Slides[0].Notes)
641 page.NotesWords = len(strings.Fields(view.Slides[0].Notes.Plain()))
642
643 page.Strip = make([]stripItem, 0, len(view.Slides))
644 for i, s := range view.Slides {
645 // The deck's seq is on the URL so the browser asks again when
646 // the deck has changed and reads its own cache when it has
647 // not. The route revalidates on an ETag either way; this is
648 // what keeps a returning tab from showing yesterday's slide
649 // out of the disk cache before the first flush.
650 page.Strip = append(page.Strip, stripItem{
651 ID: s.ID,
652 Number: i + 1,
653 Label: slideLabel(r, s, i+1),
654 Thumb: fmt.Sprintf("%s/slides/%s.svg?seq=%d", base, s.ID, d.Seq),
655 Current: i == 0,
656 Presses: len(deck.Presses(s, view.Scenes)),
657 Talk: s.Talk,
658 })
659 }
660 render(w, "editor", page)
661}
662
663// sceneAuthors is the JSON map of actor to label the code panel's author
664// line reads (fixtures/scene-code.mjs): every scene's author, labelled as
665// the deck list labels a last editor (actorLabels: a person's name or
666// address, an agent's mark and principal), and this person, who is the
667// author of a hand edit. An author that resolves to nothing is left out
668// and the line says nothing.
669func (a *app) sceneAuthors(ctx context.Context, u User, view *deck.Deck) string {
670 actors := make([]string, 0, len(view.Scenes))
671 for _, s := range view.Scenes {
672 if s.Author != "" {
673 actors = append(actors, s.Author)
674 }
675 }
676 labels := map[string]string{}
677 if len(actors) > 0 {
678 labels = a.actorLabels(ctx, actors)
679 }
680 labels[actorFor(u)] = u.viewerLabel()
681 b, err := json.Marshal(labels)
682 if err != nil {
683 return "{}"
684 }
685 return string(b)
686}
687
688// --- GET /d/{sqid}/scene-authors ---
689
690// deckSceneAuthors answers sceneAuthors for the deck now, for the code
691// panel's author line when a scene's author arrives that the page did
692// not name (fixtures/scene-code.mjs): a person or an agent who changed
693// the code while the editor was open. The deck's readers only.
694func (a *app) deckSceneAuthors(w http.ResponseWriter, r *http.Request) {
695 u, ok := a.viewer(w, r)
696 if !ok {
697 return
698 }
699 d, ok := a.deckFor(w, r, u)
700 if !ok {
701 return
702 }
703 h, view, err := a.openDeck(r.Context(), d)
704 if err != nil {
705 a.fail(w, r, "open a deck to name its scene authors", err)
706 return
707 }
708 h.Close(r.Context())
709 w.Header().Set("Content-Type", "application/json")
710 w.Header().Set("Cache-Control", "no-store")
711 fmt.Fprint(w, a.sceneAuthors(r.Context(), u, view))
712}
713
714// --- GET /d/{sqid}/slides/{id}.html ---
715
716// deckSlide renders one slide as the section the viewer would show it
717// in — the session-cookie twin of the API's apiSlide, for the editor's
718// stage and its thumbnail strip.
719//
720// Two surfaces rather than one shared route because the two are
721// authenticated differently and nothing else about them differs: the
722// API's caller carries a bearer token and the API's own 404 shape, this
723// one carries a session cookie and this app's. The rendering is
724// literally the same call into the same package, which is the invariant
725// that matters (AGENTS.md: render.Slide is the only place slide HTML is
726// produced).
727//
728// It is the SECTION, never a page: the stage swaps this into the DOM,
729// so a layout around it would be a page nested inside a page.
730//
731// vp names the viewport: `phone` reflows (spec §2.5), `desktop` and
732// `thumb` both render desktop. A thumbnail is a desktop slide scaled by
733// CSS rather than a third rendering — the one rule this app has is that
734// a slide is one block tree rendered many ways, and "many ways" is two
735// viewports, not one per place a slide is drawn.
736func (a *app) deckSlide(w http.ResponseWriter, r *http.Request) {
737 u, ok := a.viewer(w, r)
738 if !ok {
739 return
740 }
741 d, ok := a.deckFor(w, r, u)
742 if !ok {
743 return
744 }
745 // The picture twin, on the same route because the two are the same
746 // slide behind the same capability and differ only in what a
747 // caller wants back (thumbs.go).
748 if strings.HasSuffix(chi.URLParam(r, "file"), ".svg") {
749 a.serveThumb(w, r, d, "/d/"+d.Sqid, func() { a.notFound(w, r) })
750 return
751 }
752
753 slideID, ok := strings.CutSuffix(chi.URLParam(r, "file"), ".html")
754 if !ok || slideID == "" {
755 a.notFound(w, r)
756 return
757 }
758 vp := editorViewport(r.URL.Query().Get("vp"))
759
760 // Seq, slide and viewport: the three things that change what these
761 // bytes are. The stage re-fetches after every structural change,
762 // and the browser sends the tag back; a match answers 304 before
763 // the document is opened, which is what makes the fetch that
764 // changed nothing cheap. The slide id is in the tag so a stale
765 // slide's tag never matches a live one at the same seq — though a
766 // removed slide is a 404 below either way.
767 //
768 // The header goes on the two responses that ARE this
769 // representation — the 304 here and the 200 below — and never on
770 // the 404: a tag on "there is no such slide" invites a cache to
771 // treat the absence as the thing.
772 // And the share links, which decide which follow-along codes are
773 // drawn (followCodes): revoking one changes no seq.
774 etag := strconv.Quote(strconv.FormatInt(d.Seq, 10) + a.linksStamp(r.Context(), d) + "-" + slideID + "-" + vp.String())
775 if matchesETag(r.Header.Get("If-None-Match"), etag) {
776 w.Header().Set("ETag", etag)
777 w.WriteHeader(http.StatusNotModified)
778 return
779 }
780
781 h, view, err := a.openDeck(r.Context(), d)
782 if err != nil {
783 a.fail(w, r, "open a deck to render a slide", err)
784 return
785 }
786 defer h.Close(r.Context())
787
788 index := -1
789 for i, s := range view.Slides {
790 if s.ID == slideID {
791 index = i
792 break
793 }
794 }
795 if index < 0 {
796 a.notFound(w, r)
797 return
798 }
799
800 // The editor's stage is the only caller, so the section is drawn as
801 // the editor will draw it (render/editing.go): the views it binds to
802 // it replace that markup with their own and nothing moves.
803 section, err := slidehtml.SlideWith(view, index, vp,
804 slidehtml.Options{AssetBase: assetBaseFor("/d/" + d.Sqid), Editing: true, Placeholders: editorPlaceholders(r), QRAlt: qrAlt(r),
805 QR: a.followCodes(r.Context(), d, view, "/d/"+d.Sqid)})
806 if err != nil {
807 a.fail(w, r, "render a slide for the editor", err)
808 return
809 }
810 w.Header().Set("ETag", etag)
811 w.Header().Set("Content-Type", "text/html; charset=utf-8")
812 w.WriteHeader(http.StatusOK)
813 fmt.Fprint(w, section)
814}
815
816// editorViewport maps the ?vp= value onto a rendering. Anything
817// unrecognised is desktop rather than a 400: this is a rendering hint
818// on a read, and a stage that got a typo should show the slide.
819func editorViewport(vp string) slidehtml.Viewport {
820 if vp == "phone" {
821 return slidehtml.Phone
822 }
823 return slidehtml.Desktop
824}
825
826// themeAccents is every theme's own accent as a JSON object (id to hex),
827// for the accent field to show without asking the stage.
828func themeAccents() string {
829 out := make(map[string]string, len(themeIDs))
830 for _, id := range themeIDs {
831 if vars, ok := slidehtml.ThemeVars(id); ok {
832 out[id] = vars["--slides-accent"]
833 }
834 }
835 b, _ := json.Marshal(out)
836 return string(b)
837}
838