oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "errors"
5 "html/template"
6 "net/http"
7 "strconv"
8
9 "amadan.net/oficina/estilo.git/chrome"
10 estilomenu "amadan.net/oficina/estilo.git/menu"
11 "github.com/go-chi/chi/v5"
12 "gorm.io/gorm"
13)
14
15// sheetRow is one line of the sheet list: a summary plus its
16// thumbnail, rendered here rather than in the template because the
17// template cannot call a method that needs the app.
18type sheetRow struct {
19 SheetSummary
20 Preview template.HTML
21}
22
23// sheetListView is the sheet list's payload.
24//
25// It carried an ImportError until the import form moved off this page
26// to /sheets/import. The reasoning for keeping a refusal on the same
27// page as its form was right and still is — it needs no flash, no
28// cookie and no redirect — which is why the field moved with the form
29// rather than being dropped: it is importPageView.Error now.
30type sheetListView struct {
31 Sheets []sheetRow
32 // Partial is team mode with standing Unknown: Sheets holds the
33 // viewer's shares only, and the page says so (teamPartial).
34 Partial bool
35}
36
37// sheetPageView is the grid page's payload.
38//
39// Rows and Cols are the window's dimensions, sent to the client so the
40// grid builds the right shape before it has fetched a single cell —
41// otherwise the page reflows the moment the first response lands.
42type sheetPageView struct {
43 Sheet SheetSummary
44 Rows int
45 Cols int
46 // Truncated is set when the sheet reaches past the widest window
47 // the grid can paint. It is rendered as an attribute the page can
48 // read rather than as prose in Go, so the wording lives with the
49 // rest of the copy.
50 Truncated bool
51 ImportReport bool // offers the File menu's "Import report" item
52 // MayShare drives whether the page offers a Share link. The route
53 // checks again — this only decides what to render, and a button
54 // that 404s is worse than no button.
55 MayShare bool
56 // MayWrite decides whether the editing chrome is rendered at all.
57 //
58 // Without it a viewer gets a toolbar and a Format menu whose every
59 // control 404s — the route checks again, correctly, and the person
60 // is left pressing buttons that silently do nothing. A control you
61 // are not allowed to use should be absent, not broken.
62 MayWrite bool
63 // MayComment decides whether Insert offers the comment link. A
64 // commenter may not edit a cell but may say something about one,
65 // which is a different question from MayWrite and has to be asked
66 // separately.
67 MayComment bool
68 // FillSwatches and InkSwatches are the palettes the toolbar's two
69 // colour menus render. They come from the page view rather than a
70 // template func so there is exactly one list, defined in Go, that
71 // both the buttons and the write endpoint's validation read.
72 FillSwatches []swatch
73 InkSwatches []swatch
74 // NumberFormats is the same list the write endpoint validates
75 // against, so a button the UI renders is a pattern the route
76 // accepts — by construction rather than by both being edited.
77 NumberFormats []numberFormat
78 // Warned lists cells whose IMPORTED fill and ink fail WCAG AA.
79 // Spec §11.1 ruled that such a pair is rendered as authored and
80 // that the obligation is surfacing, not overriding — so this is a
81 // notice on the page, never a correction to the cell.
82 Warned []string
83}
84
85// handleSheetList renders the sheets the viewer may see.
86func (a *App) handleSheetList(w http.ResponseWriter, r *http.Request) {
87 a.renderSheetList(w, r, http.StatusOK)
88}
89
90// renderSheetList draws the list.
91//
92// It used to take a refused upload's explanation and a status to go
93// with it, because the import form lived on this page and a refusal
94// belongs beside the form that caused it. The form moved to
95// /sheets/import and the refusal went with it — renderImportPage keeps
96// both the parameter and the reasoning. What is left here has one
97// caller and one status, so it no longer takes either.
98func (a *App) renderSheetList(w http.ResponseWriter, r *http.Request, status int) {
99 viewer, ok := a.actor(r)
100 if !ok {
101 a.forbidden(w, r)
102 return
103 }
104 list, err := a.listSheets(viewer)
105 if err != nil {
106 a.fail(w, r, err)
107 return
108 }
109 // Team mode with standing Unknown: the list above holds the shares
110 // only, and is shown as partial, with a notice, rather than as a 503
111 // (Paul, 2026-10-28). Asked after listing, of the same Access the list
112 // was built with, because a lease can lapse during it.
113 partial := a.teamPartial(viewer)
114 if wantsNative(r) {
115 // Reuse the web preview's shape-only query; never decrypt cells or
116 // return HTML to a native renderer.
117 type nativeSheetRow struct {
118 SheetSummary
119 Preview preview
120 }
121 rows := make([]nativeSheetRow, 0, len(list))
122 for _, sheet := range list {
123 rows = append(rows, nativeSheetRow{SheetSummary: sheet, Preview: a.buildPreview(sheet.TabID)})
124 }
125 body := map[string]any{"Sheets": rows}
126 if partial {
127 body["Partial"] = true
128 }
129 nativeJSON(w, status, body)
130 return
131 }
132 rows := make([]sheetRow, 0, len(list))
133 for _, s := range list {
134 rows = append(rows, sheetRow{SheetSummary: s, Preview: a.previewFor(s)})
135 }
136 // Import and Create are the list's page actions: buttons in the bar
137 // at wide widths, rows in its Menu sheet below 800px. Create is a
138 // POST in both places (estilo's chrome.Action): it makes a sheet
139 // called "Untitled sheet" in one click and 303s into it.
140 f := frame{actions: []chrome.Action{
141 {Item: estilomenu.Item{Href: "/sheets/import", Label: "Import"}},
142 {Item: estilomenu.Item{Action: "/sheets", Label: "Create"}, Primary: true},
143 }}
144 a.render(w, r, "sheets", f, status, sheetListView{Sheets: rows, Partial: partial})
145}
146
147// handleSheetCreate makes a sheet and sends you to it.
148//
149// The title is read field by field with r.FormValue into an explicit
150// struct — never bound onto a GORM model (AGENTS.md / Mechanical
151// rules), which would let a form field set CreatedBy, or DeletedAt, or
152// an id.
153//
154// It answers 303 rather than rendering: a POST that renders is a POST
155// that resubmits on reload, and the second submission makes a second
156// sheet.
157func (a *App) handleSheetCreate(w http.ResponseWriter, r *http.Request) {
158 actor, ok := a.actor(r)
159 if !ok {
160 a.forbidden(w, r)
161 return
162 }
163 if !a.teamMemberOnly(w, r) {
164 return
165 }
166 title := r.FormValue("title")
167 if title == "" {
168 title = "Untitled sheet"
169 }
170 s, err := a.createSheet(a.memberGuard(r.Context()), title, actor)
171 if a.guardRefused(w, r, err) {
172 return
173 }
174 if err != nil {
175 a.fail(w, r, err)
176 return
177 }
178 if wantsNative(r) {
179 nativeJSON(w, 201, s)
180 return
181 }
182 http.Redirect(w, r, "/sheets/"+strconv.FormatUint(s.ID, 10), http.StatusSeeOther)
183}
184
185// handleSheetPage renders the grid.
186func (a *App) handleSheetPage(w http.ResponseWriter, r *http.Request) {
187 s, ok := a.sheetFromURL(w, r)
188 if !ok {
189 return
190 }
191 view := sheetPageView{
192 Sheet: s, Rows: defaultWindowRows, Cols: defaultWindowCols,
193 FillSwatches: fillSwatches, InkSwatches: inkSwatches,
194 NumberFormats: numberFormats,
195 ImportReport: a.hasImportReport(s.ID),
196 }
197 if viewer, ok := a.actor(r); ok {
198 view.MayShare = a.mayShare(s.ID, viewer)
199 view.MayWrite = a.mayWrite(s.ID, viewer)
200 view.MayComment = a.mayComment(s.ID, viewer)
201 }
202 // Best effort: a sheet whose handle will not open still renders its
203 // page, and the grid's own fetch reports the failure properly.
204 if h, err := a.openTabFor(s); err == nil {
205 idx := newPosIndex(h)
206 // The window is sized to the sheet rather than to a constant.
207 // clamp's floor keeps a one-cell sheet opening a grid somebody
208 // can type into, and its ceiling is what the cells route would
209 // clamp the request to anyway — asking for more than the server
210 // will serve renders empty rows the grid can scroll to and never
211 // fill, which is a different lie in the same place.
212 eRows, eCols := extent(h, idx)
213 view.Rows = windowFor(eRows, defaultWindowRows, maxWindowRows)
214 view.Cols = windowFor(eCols, defaultWindowCols, maxWindowCols)
215 // Past the ceiling the honest answer is words, not a wider grid.
216 // The page says so and clipboard.js's status line reads it out;
217 // silently painting the first 500 rows of a longer sheet is the
218 // same class of quiet as the constant window was.
219 view.Truncated = eRows > maxWindowRows || eCols > maxWindowCols
220 view.Warned = warnedCells(h, idx, view.Rows, view.Cols)
221 h.Release()
222 }
223 f := onSheet(s, "")
224 f.fill = true
225 if view.MayWrite {
226 // The rename is the bar's editable title (estilo's TitleEdit),
227 // posting to the same route it always has.
228 f.edit = &chrome.TitleEdit{
229 Action: "/sheets/" + strconv.FormatUint(s.ID, 10) + "/rename",
230 Name: "title", Value: s.Title,
231 Label: "Sheet title", Submit: "Rename",
232 }
233 }
234 a.render(w, r, "sheet", f, http.StatusOK, view)
235}
236
237// windowGrowRoom is the empty space kept below and to the right of a
238// sheet's furthest cell.
239//
240// Without it the window ends exactly where the content does, and the
241// row under the last one you typed in is not on the screen — a grid you
242// cannot add a row to is a worse bug than the one this fixes. A
243// screenful is the right size: enough to keep typing into, not so much
244// that the scrollbar claims a sheet far longer than it is.
245const windowGrowRoom = 20
246
247// windowFor sizes one axis of the grid's window.
248//
249// clamp is deliberately not used, and the difference is the whole point:
250// clamp's `def` is what you get for a request of ZERO, so a sheet with a
251// single cell in A1 asked for a one-row grid and clamp handed back one
252// row. def here is a FLOOR — a nearly empty sheet still opens a grid
253// somebody can work in.
254//
255// The ceiling is what the cells route would clamp a request to anyway.
256// Opening a window wider than the server will serve paints rows that can
257// be scrolled to and never filled, which is a different lie in the same
258// place.
259func windowFor(reach, floor, ceiling int) int {
260 want := reach + windowGrowRoom
261 if want < floor {
262 want = floor
263 }
264 if want > ceiling {
265 want = ceiling
266 }
267 return want
268}
269
270// sheetFromURL reads {sheetID} and loads it, answering 404 itself if it
271// is not there. The bool is whether the caller should carry on.
272//
273// A sheet that is not there — or an id that was never a number — is a
274// 404, never a 403 (AGENTS.md). A 403 tells whoever asked that the row
275// exists, which is a fact about somebody else's data.
276func (a *App) sheetFromURL(w http.ResponseWriter, r *http.Request) (SheetSummary, bool) {
277 viewer, ok := a.actor(r)
278 if !ok {
279 a.notFound(w, r)
280 return SheetSummary{}, false
281 }
282 id, err := strconv.ParseUint(chi.URLParam(r, "sheetID"), 10, 64)
283 if err != nil || id == 0 {
284 a.notFound(w, r)
285 return SheetSummary{}, false
286 }
287 s, err := a.sheetSummary(id, viewer)
288 if err != nil {
289 // No grant and no such sheet are the same answer. See
290 // sheetSummary for why, and the two-user isolation suite for
291 // the proof that they stay the same.
292 if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, errNoAccess) {
293 a.notFound(w, r)
294 return SheetSummary{}, false
295 }
296 a.fail(w, r, err)
297 return SheetSummary{}, false
298 }
299 return s, true
300}
301