forked from ponzu-cms/ponzu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elements.go
521 lines (454 loc) · 15.2 KB
/
elements.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package editor
import (
"bytes"
"html"
"strings"
)
// Input returns the []byte of an <input> HTML element with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
// type Person struct {
// item.Item
// editor editor.Editor
//
// Name string `json:"name"`
// //...
// }
//
// func (p *Person) MarshalEditor() ([]byte, error) {
// view, err := editor.Form(p,
// editor.Field{
// View: editor.Input("Name", p, map[string]string{
// "label": "Name",
// "type": "text",
// "placeholder": "Enter the Name here",
// }),
// }
// )
// }
func Input(fieldName string, p interface{}, attrs map[string]string) []byte {
e := NewElement("input", attrs["label"], fieldName, p, attrs)
return DOMElementSelfClose(e)
}
// Textarea returns the []byte of a <textarea> HTML element with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func Textarea(fieldName string, p interface{}, attrs map[string]string) []byte {
// add materialize css class to make UI correct
className := "materialize-textarea"
if _, ok := attrs["class"]; ok {
class := attrs["class"]
attrs["class"] = class + " " + className
} else {
attrs["class"] = className
}
e := NewElement("textarea", attrs["label"], fieldName, p, attrs)
return DOMElement(e)
}
// Timestamp returns the []byte of an <input> HTML element with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func Timestamp(fieldName string, p interface{}, attrs map[string]string) []byte {
var data string
val := ValueFromStructField(fieldName, p)
if val == "0" {
data = ""
} else {
data = val
}
e := &Element{
TagName: "input",
Attrs: attrs,
Name: TagNameFromStructField(fieldName, p),
Label: attrs["label"],
Data: data,
ViewBuf: &bytes.Buffer{},
}
return DOMElementSelfClose(e)
}
// File returns the []byte of a <input type="file"> HTML element with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func File(fieldName string, p interface{}, attrs map[string]string) []byte {
name := TagNameFromStructField(fieldName, p)
value := ValueFromStructField(fieldName, p)
tmpl :=
`<div class="file-input ` + name + ` input-field col s12">
<label class="active">` + attrs["label"] + `</label>
<div class="file-field input-field">
<div class="btn">
<span>Upload</span>
<input class="upload" type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" placeholder="` + attrs["label"] + `" type="text">
</div>
</div>
<div class="preview"><div class="img-clip"></div></div>
<input class="store ` + name + `" type="hidden" name="` + name + `" value="` + value + `" />
</div>`
script :=
`<script>
$(function() {
var $file = $('.file-input.` + name + `'),
upload = $file.find('input.upload'),
store = $file.find('input.store'),
preview = $file.find('.preview'),
clip = preview.find('.img-clip'),
reset = document.createElement('div'),
img = document.createElement('img'),
video = document.createElement('video'),
unknown = document.createElement('div'),
viewLink = document.createElement('a'),
viewLinkText = document.createTextNode('Download / View '),
iconLaunch = document.createElement('i'),
iconLaunchText = document.createTextNode('launch'),
uploadSrc = store.val();
video.setAttribute
preview.hide();
viewLink.setAttribute('href', '` + value + `');
viewLink.setAttribute('target', '_blank');
viewLink.appendChild(viewLinkText);
viewLink.style.display = 'block';
viewLink.style.marginRight = '10px';
viewLink.style.textAlign = 'right';
iconLaunch.className = 'material-icons tiny';
iconLaunch.style.position = 'relative';
iconLaunch.style.top = '3px';
iconLaunch.appendChild(iconLaunchText);
viewLink.appendChild(iconLaunch);
preview.append(viewLink);
// when ` + name + ` input changes (file is selected), remove
// the 'name' and 'value' attrs from the hidden store input.
// add the 'name' attr to ` + name + ` input
upload.on('change', function(e) {
resetImage();
});
if (uploadSrc.length > 0) {
var ext = uploadSrc.substring(uploadSrc.lastIndexOf('.'));
ext = ext.toLowerCase();
switch (ext) {
case '.jpg':
case '.jpeg':
case '.webp':
case '.gif':
case '.png':
$(img).attr('src', store.val());
clip.append(img);
break;
case '.mp4':
case '.webm':
$(video)
.attr('src', store.val())
.attr('type', 'video/'+ext.substring(1))
.attr('controls', true)
.css('width', '100%');
clip.append(video);
break;
default:
$(img).attr('src', '/admin/static/dashboard/img/ponzu-file.png');
$(unknown)
.css({
position: 'absolute',
top: '10px',
left: '10px',
border: 'solid 1px #ddd',
padding: '7px 7px 5px 12px',
fontWeight: 'bold',
background: '#888',
color: '#fff',
textTransform: 'uppercase',
letterSpacing: '2px'
})
.text(ext);
clip.append(img);
clip.append(unknown);
clip.css('maxWidth', '200px');
}
preview.show();
$(reset).addClass('reset ` + name + ` btn waves-effect waves-light grey');
$(reset).html('<i class="material-icons tiny">clear<i>');
$(reset).on('click', function(e) {
e.preventDefault();
preview.animate({"opacity": 0.1}, 200, function() {
preview.slideUp(250, function() {
resetImage();
});
})
});
clip.append(reset);
}
function resetImage() {
store.val('');
store.attr('name', '');
upload.attr('name', '` + name + `');
clip.empty();
}
});
</script>`
return []byte(tmpl + script)
}
// Richtext returns the []byte of a rich text editor (provided by http://summernote.org/) with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func Richtext(fieldName string, p interface{}, attrs map[string]string) []byte {
// create wrapper for richtext editor, which isolates the editor's css
iso := []byte(`<div class="iso-texteditor input-field col s12"><label>` + attrs["label"] + `</label>`)
isoClose := []byte(`</div>`)
if _, ok := attrs["class"]; ok {
attrs["class"] += "richtext " + fieldName
} else {
attrs["class"] = "richtext " + fieldName
}
if _, ok := attrs["id"]; ok {
attrs["id"] += "richtext-" + fieldName
} else {
attrs["id"] = "richtext-" + fieldName
}
// create the target element for the editor to attach itself
div := &Element{
TagName: "div",
Attrs: attrs,
Name: "",
Label: "",
Data: "",
ViewBuf: &bytes.Buffer{},
}
// create a hidden input to store the value from the struct
val := ValueFromStructField(fieldName, p)
name := TagNameFromStructField(fieldName, p)
input := `<input type="hidden" name="` + name + `" class="richtext-value ` + fieldName + `" value="` + html.EscapeString(val) + `"/>`
// build the dom tree for the entire richtext component
iso = append(iso, DOMElement(div)...)
iso = append(iso, []byte(input)...)
iso = append(iso, isoClose...)
script := `
<script>
$(function() {
var _editor = $('.richtext.` + fieldName + `');
var hidden = $('.richtext-value.` + fieldName + `');
_editor.materialnote({
height: 250,
placeholder: '` + attrs["placeholder"] + `',
toolbar: [
['style', ['style']],
['font', ['bold', 'italic', 'underline', 'clear', 'strikethrough', 'superscript', 'subscript']],
['fontsize', ['fontsize']],
['color', ['color']],
['insert', ['link', 'picture', 'video', 'hr']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['height', ['height']],
['misc', ['codeview']]
],
// intercept file insertion, upload and insert img with new src
onImageUpload: function(files) {
var data = new FormData();
data.append("file", files[0]);
$.ajax({
data: data,
type: 'PUT',
url: '/admin/edit/upload',
cache: false,
contentType: false,
processData: false,
success: function(resp) {
var img = document.createElement('img');
img.setAttribute('src', resp.data[0].url);
_editor.materialnote('insertNode', img);
},
error: function(xhr, status, err) {
console.log(status, err);
}
})
}
});
// inject content into editor
if (hidden.val() !== "") {
_editor.code(hidden.val());
}
// update hidden input with encoded value on different events
_editor.on('materialnote.change', function(e, content, $editable) {
hidden.val(replaceBadChars(content));
});
_editor.on('materialnote.paste', function(e) {
hidden.val(replaceBadChars(_editor.code()));
});
// bit of a hack to stop the editor buttons from causing a refresh when clicked
$('.note-toolbar').find('button, i, a').on('click', function(e) { e.preventDefault(); });
});
</script>`
return append(iso, []byte(script)...)
}
// Select returns the []byte of a <select> HTML element plus internal <options> with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func Select(fieldName string, p interface{}, attrs, options map[string]string) []byte {
// options are the value attr and the display value, i.e.
// <option value="{map key}">{map value}</option>
// find the field value in p to determine if an option is pre-selected
fieldVal := ValueFromStructField(fieldName, p)
if _, ok := attrs["class"]; ok {
attrs["class"] += " browser-default"
} else {
attrs["class"] = "browser-default"
}
sel := NewElement("select", attrs["label"], fieldName, p, attrs)
var opts []*Element
// provide a call to action for the select element
cta := &Element{
TagName: "option",
Attrs: map[string]string{"disabled": "true", "selected": "true"},
Data: "Select an option...",
ViewBuf: &bytes.Buffer{},
}
// provide a selection reset (will store empty string in db)
reset := &Element{
TagName: "option",
Attrs: map[string]string{"value": ""},
Data: "None",
ViewBuf: &bytes.Buffer{},
}
opts = append(opts, cta, reset)
for k, v := range options {
optAttrs := map[string]string{"value": k}
if k == fieldVal {
optAttrs["selected"] = "true"
}
opt := &Element{
TagName: "option",
Attrs: optAttrs,
Data: v,
ViewBuf: &bytes.Buffer{},
}
opts = append(opts, opt)
}
return DOMElementWithChildrenSelect(sel, opts)
}
// Checkbox returns the []byte of a set of <input type="checkbox"> HTML elements
// wrapped in a <div> with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func Checkbox(fieldName string, p interface{}, attrs, options map[string]string) []byte {
if _, ok := attrs["class"]; ok {
attrs["class"] += "input-field col s12"
} else {
attrs["class"] = "input-field col s12"
}
div := NewElement("div", attrs["label"], fieldName, p, attrs)
var opts []*Element
// get the pre-checked options if this is already an existing post
checkedVals := ValueFromStructField(fieldName, p)
checked := strings.Split(checkedVals, "__ponzu")
i := 0
for k, v := range options {
inputAttrs := map[string]string{
"type": "checkbox",
"value": k,
"id": strings.Join(strings.Split(v, " "), "-"),
}
// check if k is in the pre-checked values and set to checked
for _, x := range checked {
if k == x {
inputAttrs["checked"] = "checked"
}
}
// create a *element manually using the modified TagNameFromStructFieldMulti
// func since this is for a multi-value name
input := &Element{
TagName: "input",
Attrs: inputAttrs,
Name: TagNameFromStructFieldMulti(fieldName, i, p),
Label: v,
Data: "",
ViewBuf: &bytes.Buffer{},
}
opts = append(opts, input)
i++
}
return DOMElementWithChildrenCheckbox(div, opts)
}
// Tags returns the []byte of a tag input (in the style of Materialze 'Chips') with a label.
// IMPORTANT:
// The `fieldName` argument will cause a panic if it is not exactly the string
// form of the struct field that this editor input is representing
func Tags(fieldName string, p interface{}, attrs map[string]string) []byte {
name := TagNameFromStructField(fieldName, p)
// get the saved tags if this is already an existing post
values := ValueFromStructField(fieldName, p)
var tags []string
if strings.Contains(values, "__ponzu") {
tags = strings.Split(values, "__ponzu")
}
// case where there is only one tag stored, thus has no separator
if len(values) > 0 && !strings.Contains(values, "__ponzu") {
tags = append(tags, values)
}
html := `
<div class="col s12 __ponzu-tags ` + name + `">
<label class="active">` + attrs["label"] + ` (Type and press "Enter")</label>
<div class="chips ` + name + `"></div>
`
var initial []string
i := 0
for _, tag := range tags {
tagName := TagNameFromStructFieldMulti(fieldName, i, p)
html += `<input type="hidden" class="__ponzu-tag ` + tag + `" name=` + tagName + ` value="` + tag + `"/>`
initial = append(initial, `{tag: '`+tag+`'}`)
i++
}
script := `
<script>
$(function() {
var tags = $('.__ponzu-tags.` + name + `');
$('.chips.` + name + `').material_chip({
data: [` + strings.Join(initial, ",") + `],
secondaryPlaceholder: '+` + name + `'
});
// handle events specific to tags
var chips = tags.find('.chips');
chips.on('chip.add', function(e, chip) {
chips.parent().find('.empty-tag').remove();
var input = $('<input>');
input.attr({
class: '__ponzu-tag '+chip.tag.split(' ').join('__'),
name: '` + name + `.'+String(tags.find('input[type=hidden]').length),
value: chip.tag,
type: 'hidden'
});
tags.append(input);
});
chips.on('chip.delete', function(e, chip) {
// convert tag string to class-like selector "some tag" -> ".some.tag"
var sel = '.__ponzu-tag.' + chip.tag.split(' ').join('__');
chips.parent().find(sel).remove();
// iterate through all hidden tag inputs to re-name them with the correct ` + name + `.index
var hidden = chips.parent().find('input[type=hidden]');
// if there are no tags, set a blank
if (hidden.length === 0) {
var input = $('<input>');
input.attr({
class: 'empty-tag',
name: '` + name + `',
type: 'hidden'
});
tags.append(input);
}
// re-name hidden storage elements in necessary format
for (var i = 0; i < hidden.length; i++) {
$(hidden[i]).attr('name', '` + name + `.'+String(i));
}
});
});
</script>
`
html += `</div>`
return []byte(html + script)
}