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 "encoding/json"
5 "errors"
6 "sort"
7 "strconv"
8 "strings"
9
10 "gorm.io/gorm"
11 "gorm.io/gorm/clause"
12
13 "amadan.net/oficina/sheets/internal/sheets/store"
14)
15
16// ViewSpec is how a tab is sorted and filtered.
17//
18// **Non-destructive, and that is a constraint rather than a
19// preference.** calc's dependency graph is keyed on POSITION —
20// store/handle.go's cellKey builds CellKey{rowPos+1, colPos+1} — so
21// physically reordering rows changes what every existing formula
22// points at, silently. Plan 1's review flagged exactly this ("valid
23// only until rows move"). Sorting therefore reorders what is DISPLAYED
24// and never what is stored; the graph, and every reference in it, is
25// untouched.
26//
27// A destructive sort is a real thing to want and is not built. Its
28// trigger is written into the spec's deferred table: it needs calc's
29// key space rebuilt on stable ids first, which is a subsystem, not a
30// feature.
31type ViewSpec struct {
32 // SortCol is a zero-based column, or -1 for no sort.
33 SortCol int `json:"sortCol"`
34 SortDsc bool `json:"sortDesc"`
35
36 // FilterCol is a zero-based column, or -1 for no filter.
37 FilterCol int `json:"filterCol"`
38 FilterOp string `json:"filterOp"`
39 FilterVal string `json:"filterVal"`
40}
41
42// emptyView is what a tab has before anybody sorts it.
43func emptyView() ViewSpec { return ViewSpec{SortCol: -1, FilterCol: -1} }
44
45// Active reports whether this view does anything.
46func (v ViewSpec) Active() bool { return v.SortCol >= 0 || v.FilterCol >= 0 }
47
48// filterOps are the comparisons a filter may use.
49//
50// A small, closed set. Each is a thing somebody can hold in their head,
51// and a closed set is what lets the criteria be validated on the way in
52// rather than interpreted on the way out.
53var filterOps = []string{"contains", "equals", "gt", "lt", "nonempty"}
54
55func filterOpValid(op string) bool {
56 for _, ok := range filterOps {
57 if op == ok {
58 return true
59 }
60 }
61 return false
62}
63
64// Validate bounds a spec before it is stored.
65func (v ViewSpec) Validate() error {
66 if v.SortCol < -1 || v.SortCol >= tableCols {
67 return errors.New("sheets: sort column out of range")
68 }
69 if v.FilterCol < -1 || v.FilterCol >= tableCols {
70 return errors.New("sheets: filter column out of range")
71 }
72 if v.FilterCol >= 0 && !filterOpValid(v.FilterOp) {
73 return errors.New("sheets: unknown filter comparison")
74 }
75 if len(v.FilterVal) > maxRawBytes {
76 return errors.New("sheets: filter value too long")
77 }
78 return nil
79}
80
81// loadView reads a tab's view, or the empty one.
82func (a *App) loadView(tabID uint64) ViewSpec {
83 if a.db == nil || a.sealer == nil {
84 return emptyView()
85 }
86 var row TabView
87 if err := a.db.Where("tab_id = ?", tabID).First(&row).Error; err != nil {
88 return emptyView()
89 }
90 body, err := a.sealer.Open("tab.view", row.SpecSealed)
91 if err != nil {
92 return emptyView()
93 }
94 spec := emptyView()
95 if err := json.Unmarshal(body, &spec); err != nil {
96 return emptyView()
97 }
98 if spec.Validate() != nil {
99 // A stored spec this build cannot make sense of shows the tab
100 // unsorted rather than refusing to render it.
101 return emptyView()
102 }
103 return spec
104}
105
106// saveView stores a tab's view, sealed.
107func (a *App) saveView(g store.Guard, tabID uint64, spec ViewSpec, by Member) error {
108 if a.db == nil {
109 return errNoDB
110 }
111 if a.sealer == nil {
112 return errNoSealer
113 }
114 if err := spec.Validate(); err != nil {
115 return err
116 }
117 body, err := json.Marshal(spec)
118 if err != nil {
119 return err
120 }
121 sealed, err := a.sealer.Seal("tab.view", body)
122 if err != nil {
123 return err
124 }
125 return a.guarded(g, func(db *gorm.DB) error {
126 return db.Clauses(clause.OnConflict{
127 Columns: []clause.Column{{Name: "tab_id"}},
128 DoUpdates: clause.AssignmentColumns([]string{"spec_sealed", "updated_by", "updated_at"}),
129 }).Create(&TabView{TabID: tabID, SpecSealed: sealed, UpdatedBy: by.ID}).Error
130 })
131}
132
133// applyView turns a stored spec into the order rows should be shown in.
134//
135// It returns display positions: the row position to render at each
136// place. Cells keep their real coordinates everywhere else in the app,
137// so nothing downstream has to know a view is in effect — and a write
138// still addresses the row it was always addressing.
139func applyView(h *store.Handle, spec ViewSpec, first, count int) []int {
140 rows := make([]int, 0, count)
141 for _, r := range h.GridRows() {
142 rows = append(rows, r.Pos)
143 }
144 if len(rows) == 0 {
145 // Nothing stored yet: show the plain window, so an empty sheet
146 // still has rows to type into.
147 for i := 0; i < count; i++ {
148 rows = append(rows, first+i)
149 }
150 return rows
151 }
152
153 idx := newPosIndex(h)
154 if spec.FilterCol >= 0 {
155 kept := rows[:0:0]
156 for _, rp := range rows {
157 if matches(h, idx, rp, spec) {
158 kept = append(kept, rp)
159 }
160 }
161 rows = kept
162 }
163 if spec.SortCol >= 0 {
164 sort.SliceStable(rows, func(i, j int) bool {
165 a := cellText(h, idx, rows[i], spec.SortCol)
166 b := cellText(h, idx, rows[j], spec.SortCol)
167 if spec.SortDsc {
168 return less(b, a)
169 }
170 return less(a, b)
171 })
172 }
173
174 // Page after ordering, not before: paging first would sort one
175 // page at a time, which looks like sorting and is not.
176 if first >= len(rows) {
177 return nil
178 }
179 end := first + count
180 if end > len(rows) {
181 end = len(rows)
182 }
183 return rows[first:end]
184}
185
186// cellText reads a cell's displayed string at a position.
187func cellText(h *store.Handle, idx posIndex, rowPos, colPos int) string {
188 rowID, ok := idx.rowID[rowPos]
189 if !ok {
190 return ""
191 }
192 colID, ok := idx.colID[colPos]
193 if !ok {
194 return ""
195 }
196 return display(h.Value(rowID, colID), h.Format(rowID, colID))
197}
198
199// matches applies a filter to one row.
200func matches(h *store.Handle, idx posIndex, rowPos int, spec ViewSpec) bool {
201 got := cellText(h, idx, rowPos, spec.FilterCol)
202 want := spec.FilterVal
203 switch spec.FilterOp {
204 case "nonempty":
205 return strings.TrimSpace(got) != ""
206 case "equals":
207 return strings.EqualFold(strings.TrimSpace(got), strings.TrimSpace(want))
208 case "contains":
209 return strings.Contains(strings.ToLower(got), strings.ToLower(want))
210 case "gt", "lt":
211 g, err1 := strconv.ParseFloat(strings.TrimSpace(got), 64)
212 wv, err2 := strconv.ParseFloat(strings.TrimSpace(want), 64)
213 if err1 != nil || err2 != nil {
214 // A numeric comparison against something that is not a
215 // number excludes the row rather than guessing an order.
216 return false
217 }
218 if spec.FilterOp == "gt" {
219 return g > wv
220 }
221 return g < wv
222 }
223 return true
224}
225
226// less orders two displayed strings, numbers before text.
227//
228// Numbers compare numerically, so 9 sorts before 10 — string order
229// would put 10 first, which is the single most obvious way a
230// spreadsheet sort can be wrong. Everything else compares
231// case-insensitively, and empties sort last so a sorted column does not
232// open with a screen of blanks.
233func less(a, b string) bool {
234 af, aNum := parseNum(a)
235 bf, bNum := parseNum(b)
236 switch {
237 case a == "" && b == "":
238 return false
239 case a == "":
240 return false
241 case b == "":
242 return true
243 case aNum && bNum:
244 return af < bf
245 case aNum != bNum:
246 return aNum
247 }
248 return strings.ToLower(a) < strings.ToLower(b)
249}
250
251func parseNum(s string) (float64, bool) {
252 f, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
253 return f, err == nil
254}
255