| 1 | package todo |
| 2 | |
| 3 | import "strconv" |
| 4 | |
| 5 | // filter is which slice of the list a page shows. Its name is what forms |
| 6 | // post back as `filter`; its path is where the 303 goes. |
| 7 | type filter string |
| 8 | |
| 9 | const ( |
| 10 | filterAll filter = "all" |
| 11 | filterActive filter = "active" |
| 12 | filterCompleted filter = "completed" |
| 13 | ) |
| 14 | |
| 15 | // parseFilter reads a posted filter. Missing or unknown is "all". |
| 16 | func parseFilter(s string) filter { |
| 17 | switch f := filter(s); f { |
| 18 | case filterActive, filterCompleted: |
| 19 | return f |
| 20 | } |
| 21 | return filterAll |
| 22 | } |
| 23 | |
| 24 | func (f filter) path() string { |
| 25 | if f == filterAll { |
| 26 | return "/" |
| 27 | } |
| 28 | return "/" + string(f) |
| 29 | } |
| 30 | |
| 31 | func (f filter) shows(t Todo) bool { |
| 32 | switch f { |
| 33 | case filterActive: |
| 34 | return !t.Completed |
| 35 | case filterCompleted: |
| 36 | return t.Completed |
| 37 | } |
| 38 | return true |
| 39 | } |
| 40 | |
| 41 | // view is everything the page template draws. |
| 42 | type view struct { |
| 43 | Filter filter |
| 44 | Items []item |
| 45 | Total int |
| 46 | Left int |
| 47 | Completed int |
| 48 | Editing bool |
| 49 | } |
| 50 | |
| 51 | type item struct { |
| 52 | ID int64 |
| 53 | Title string |
| 54 | Completed bool |
| 55 | Editing bool |
| 56 | EditHref string |
| 57 | } |
| 58 | |
| 59 | // newView sorts the list into what the page shows. Counts cover the |
| 60 | // whole list whichever filter is on; editing is the item whose editor is |
| 61 | // open, or 0. |
| 62 | func newView(todos []Todo, f filter, editing int64) view { |
| 63 | v := view{Filter: f, Total: len(todos)} |
| 64 | for _, t := range todos { |
| 65 | if t.Completed { |
| 66 | v.Completed++ |
| 67 | } else { |
| 68 | v.Left++ |
| 69 | } |
| 70 | if !f.shows(t) { |
| 71 | continue |
| 72 | } |
| 73 | it := item{ID: t.ID, Title: t.Title, Completed: t.Completed, |
| 74 | Editing: t.ID == editing, |
| 75 | EditHref: f.path() + "?edit=" + strconv.FormatInt(t.ID, 10)} |
| 76 | v.Editing = v.Editing || it.Editing |
| 77 | v.Items = append(v.Items, it) |
| 78 | } |
| 79 | return v |
| 80 | } |
| 81 | |
| 82 | // Class is the li's class attribute: completed, editing, both or none. |
| 83 | func (it item) Class() string { |
| 84 | switch { |
| 85 | case it.Completed && it.Editing: |
| 86 | return "completed editing" |
| 87 | case it.Completed: |
| 88 | return "completed" |
| 89 | case it.Editing: |
| 90 | return "editing" |
| 91 | } |
| 92 | return "" |
| 93 | } |
| 94 | |
| 95 | // AllCompleted is toggle-all's checked state. |
| 96 | func (v view) AllCompleted() bool { return v.Total > 0 && v.Left == 0 } |
| 97 | |