-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.go
391 lines (344 loc) · 10.2 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// susen.go - a web-based Sudoku game and teaching tool.
// Copyright (C) 2015 Daniel C. Brotsky.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// Licensed under the LGPL v3. See the LICENSE file for details
package client
import (
"bytes"
"fmt"
"github.com/ancientHacker/susen.go/puzzle"
"html/template"
"os"
"path/filepath"
)
/*
solver pages
*/
// The solverPageTemplate contains the template for a solver
// page. It's initialized when needed; see the definition of
// findSolverPageTemplate for template location details.
var solverPageTemplate *template.Template
// A templateSolverPage contains the values to fill the solver
// page template.
type templateSolverPage struct {
SessionID, PuzzleID string
Title, TopHead string
IconFile, CssFile, JsFile string
Puzzle templatePuzzle
ApplicationFooter string
}
// templatePuzzle is the structure expected by the puzzle grid
// section of the solver page template.
type templatePuzzle [][]templatePuzzleCell
// A templatePuzzleCell contains the cell's index, value, and CSS
// styling classes as expected by the puzzle grid section of the
// solver page template.
type templatePuzzleCell struct {
Index int
Value template.HTML
Shade, HBorder, VBorder string
}
// add solver statics to the static list
func init() {
staticResourcePaths["/solver.js"] = filepath.Join("solver", "puzzle.js")
staticResourcePaths["/solver.css"] = filepath.Join("solver", "puzzle.css")
}
// SolverPage executes the solver page template over the passed
// session and puzzle info, and returns the solver page content as a
// string.
func SolverPage(sessionID string, puzzleID string, summary *puzzle.Summary) string {
var tp templatePuzzle
var err error
if summary.Geometry == puzzle.SudokuGeometryName {
tp, err = sudokuTemplatePuzzle(summary.Values)
} else if summary.Geometry == puzzle.DudokuGeometryName {
tp, err = dudokuTemplatePuzzle(summary.Values)
} else {
err = fmt.Errorf("Can't generate puzzle grid for geometry %q", summary.Geometry)
}
if err != nil {
return ErrorPage(err)
}
tsp := templateSolverPage{
SessionID: sessionID,
PuzzleID: puzzleID,
Title: fmt.Sprintf("%s: Solver", brandName),
TopHead: fmt.Sprintf("Puzzle Solver"),
IconFile: iconPath,
CssFile: "/solver.css",
JsFile: "/solver.js",
Puzzle: tp,
ApplicationFooter: applicationFooter(),
}
tmpl, err := loadPageTemplate("solver")
if err != nil {
return ErrorPage(fmt.Errorf("Couldn't load the %q template: %v", "solver", err))
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, tsp)
if err != nil {
return ErrorPage(err)
}
return buf.String()
}
/*
Sudoku puzzle templates
*/
// sudokuTemplatePuzzle takes the values of a puzzle and returns
// the appropriate templatePuzzle. Errors mean the given values
// have the wrong shape to be a sudokuPuzzle.
func sudokuTemplatePuzzle(vals []int) (templatePuzzle, error) {
slen, ok := findIntSquareRoot(len(vals))
if !ok {
return nil, fmt.Errorf("Puzzle square count is %v: not a square.", len(vals))
}
tlen, ok := findIntSquareRoot(slen)
if !ok {
return nil, fmt.Errorf("Puzzle side length is %v: not a square.", slen)
}
rows := make(templatePuzzle, slen)
for i := 0; i < slen; i++ {
rows[i] = make([]templatePuzzleCell, slen)
// is this top, bottom, or middle row of quad
hborder := "middle"
if i%tlen == 0 {
hborder = "top"
} else if i%tlen == tlen-1 {
hborder = "bottom"
}
for j := 0; j < slen; j++ {
index := i*slen + j
value := template.HTML(" ")
if val := vals[index]; val > 0 {
value = template.HTML(fmt.Sprint(val))
}
quad := i/tlen + j/tlen
// even quad or odd quad shading
shade := "lighter"
if quad%2 == 0 {
shade = "darker"
}
// is this left, center, or right column of quad
vborder := "center"
if j%tlen == 0 {
vborder = "left"
} else if j%tlen == tlen-1 {
vborder = "right"
}
rows[i][j] = templatePuzzleCell{
Index: index + 1,
Value: value,
Shade: shade,
HBorder: hborder,
VBorder: vborder,
}
}
}
return rows, nil
}
// Find the integer square root of val, if it exists.
func findIntSquareRoot(val int) (int, bool) {
var i int
for i = 1; i*i <= val; i++ {
if i*i == val {
return i, true
}
}
return i - 1, false
}
/*
Dudoku puzzle templates
*/
// dudokuTemplatePuzzle takes the values of a puzzle and returns
// the appropriate templatePuzzle. Errors mean the given values
// have the wrong shape to be a dudokuPuzzle.
func dudokuTemplatePuzzle(vals []int) (templatePuzzle, error) {
slen, ok := findIntSquareRoot(len(vals))
if !ok {
return nil, fmt.Errorf("Puzzle square count is %v: not a square.", len(vals))
}
htlen, vtlen, ok := findDivisors(slen)
if !ok {
return nil, fmt.Errorf("Puzzle side length is %v: not the product of consecutive integers.", slen)
}
rows := make(templatePuzzle, slen)
for i := 0; i < slen; i++ {
rows[i] = make([]templatePuzzleCell, slen)
// is this top, bottom, or middle row of quad
hborder := "middle"
if i%vtlen == 0 {
hborder = "top"
} else if i%vtlen == vtlen-1 {
hborder = "bottom"
}
for j := 0; j < slen; j++ {
index := i*slen + j
value := template.HTML(" ")
if val := vals[index]; val > 0 {
value = template.HTML(fmt.Sprint(val))
}
quad := i/vtlen + j/htlen
// even quad or odd quad shading
shade := "lighter"
if quad%2 == 0 {
shade = "darker"
}
// is this left, center, or right column of quad
vborder := "center"
if j%htlen == 0 {
vborder = "left"
} else if j%htlen == htlen-1 {
vborder = "right"
}
rows[i][j] = templatePuzzleCell{
Index: index + 1,
Value: value,
Shade: shade,
HBorder: hborder,
VBorder: vborder,
}
}
}
return rows, nil
}
// findDivisors: find consecutive ints that multiply to give an
// int, if they exist
func findDivisors(val int) (int, int, bool) {
var low, high int
for low, high = 1, 2; low*high <= val; low, high = high, high+1 {
if low*high == val {
return low, high, true
}
}
return low - 1, low, false
}
/*
error pages
*/
// A templateErrorPage contains the values to fill the error page
// template.
type templateErrorPage struct {
Title, TopHead, Message string
IconFile, ReportBugPage string
ApplicationFooter string
}
// return error page content
func ErrorPage(e error) string {
tep := templateErrorPage{
Title: fmt.Sprintf("%s: Error", brandName),
TopHead: fmt.Sprintf("Unexpected Server Error"),
Message: e.Error(),
IconFile: iconPath,
ReportBugPage: reportBugPath,
ApplicationFooter: applicationFooter(),
}
tmpl, err := loadPageTemplate("error")
if err != nil {
return fmt.Sprintf("Couldn't load the %q template: %v", "error", err)
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, tep)
if err != nil {
return fmt.Sprintf("A templating error has occurred: %v", err)
}
return buf.String()
}
/*
home page
*/
// The homePageTemplate contains the template for a home
// page. It's initialized when needed; see the definition of
// findHomePageTemplate for template location details.
var homePageTemplate *template.Template
// A templateHomePage contains the values to file the home
// page template.
type templateHomePage struct {
SessionID, PuzzleID string
Title, TopHead string
IconFile, CssFile, JsFile string
PuzzleIDs []string
ApplicationFooter string
}
// add home statics to the static list
func init() {
staticResourcePaths["/home.js"] = filepath.Join("home", "home.js")
staticResourcePaths["/home.css"] = filepath.Join("home", "home.css")
}
// HomePage executes the home page template over the passed
// session and puzzle info, and returns the home page content as
// a string. If there is an error, what's returned is the error
// page content as a string.
func HomePage(sessionID string, puzzleID string, puzzleIDs []string) string {
tsp := templateHomePage{
SessionID: sessionID,
PuzzleID: puzzleID,
Title: fmt.Sprintf("%s: Home", brandName),
TopHead: fmt.Sprintf("%s", brandName),
IconFile: iconPath,
CssFile: "/home.css",
JsFile: "/home.js",
PuzzleIDs: puzzleIDs,
ApplicationFooter: applicationFooter(),
}
tmpl, err := loadPageTemplate("home")
if err != nil {
return ErrorPage(fmt.Errorf("Couldn't load the %q template: %v", "home", err))
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, tsp)
if err != nil {
return ErrorPage(err)
}
return buf.String()
}
/*
application footer
*/
// applicationFooter - the application footer that shows at the
// bottom of all pages.
func applicationFooter() string {
appName := os.Getenv(applicationNameEnvVar)
appEnv := os.Getenv(applicationEnvEnvVar)
appVersion := os.Getenv(applicationVersionEnvVar)
appInstance := os.Getenv(applicationInstanceEnvVar)
appBuild := os.Getenv(applicationBuildEnvVar)
if appName == "" {
appName = brandName
}
if appEnv == "" {
appEnv = "local"
}
if appVersion != "" {
appVersion = " " + appVersion
}
if len(appBuild) >= 7 {
appBuild = appBuild[:7]
}
if appInstance != "" {
appInstance = " (dyno " + appInstance + ")"
}
switch appEnv {
case "local":
return "[" + appName + " local]"
case "dev":
return "[" + appName + " CI/CD]"
case "stg":
return "[" + appName + appVersion + " <" + appBuild + ">]"
case "prd":
return "[" + appName + appVersion + " <" + appBuild + ">" + appInstance + "]"
}
return "[" + appName + " <??>]"
}