forked from icza/gowut
-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.go
419 lines (360 loc) · 11.7 KB
/
editor.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
// Copyright (C) 2013 Andras Belicza. All rights reserved.
//
// 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 3 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, see <http://www.gnu.org/licenses/>.
// Defines the Editor component.
package gwu
import (
"net/http"
"fmt"
// "strconv"
)
// Editor interface defines a component for text input purpose.
//
// Suggested event type to handle actions: ETypeChange
//
// By default the value of the TextBox is synchronized with the server
// on ETypeChange event which is when the TextBox loses focus
// or when the ENTER key is pressed.
// If you want a TextBox to synchronize values during editing
// (while you type in characters), add the ETypeKeyUp event type
// to the events on which synchronization happens by calling:
// AddSyncOnETypes(ETypeKeyUp)
//
// Default style class: "gwu-TextBox"
type Editor interface {
// Editor is a component.
Comp
// Editor has text.
HasText
// Editor can be enabled/disabled.
HasEnabled
// ReadOnly returns if the editor is read-only.
ReadOnly() bool
// SetReadOnly sets if the text box is read-only.
SetReadOnly(readOnly bool)
// Rows returns the number of displayed rows.
Rows() int
// SetRows sets the number of displayed rows.
// rows=1 will make this a simple, one-line input text box,
// rows>1 will make this a text area.
SetRows(rows int)
// Cols returns the number of displayed columns.
Cols() int
// SetCols sets the number of displayed columns.
SetCols(cols int)
// MaxLength returns the maximum number of characters
// allowed in the text box.
// -1 is returned if there is no maximum length set.
MaxLength() int
// SetMaxLength sets the maximum number of characters
// allowed in the text box.
// Pass -1 to not limit the maximum length.
SetMaxLength(maxLength int)
}
// TextBox implementation.
type editorImpl struct {
compImpl // Component implementation
hasTextImpl // Has text implementation
hasEnabledImpl // Has enabled implementation
rows, cols int // Number of displayed rows and columns.
isInline bool
}
var (
// strEncURIThisV = []byte("encodeURIComponent(this.value)") // "encodeURIComponent(this.value)"
)
// NewEditor creates a new Editor
func NewEditor(text string) *editorImpl {
c := newEditorImpl(strEncURIThisV, text, false)
c.Style().AddClass("gwu-Editor")
return &c
}
// NewEditor creates a new Editor
func NewInlineEditor(text string) *editorImpl {
c := newEditorImpl(strEncURIThisV, text, true)
c.Style().AddClass("gwu-Editor")
return &c
}
// newTextBoxImpl creates a new textBoxImpl.
func newEditorImpl(valueProviderJs []byte, text string, isInline bool) editorImpl {
c := editorImpl{newCompImpl(valueProviderJs), newHasTextImpl(text), newHasEnabledImpl(), 1, 20, isInline}
c.AddSyncOnETypes(ETypeChange)
return c
}
func (c *editorImpl) ReadOnly() bool {
ro := c.Attr("readonly")
return len(ro) > 0
}
func (c *editorImpl) SetReadOnly(readOnly bool) {
if readOnly {
c.SetAttr("readonly", "readonly")
} else {
c.SetAttr("readonly", "")
}
}
func (c *editorImpl) Rows() int {
return c.rows
}
func (c *editorImpl) SetRows(rows int) {
c.rows = rows
}
func (c *editorImpl) Cols() int {
return c.cols
}
func (c *editorImpl) SetCols(cols int) {
c.cols = cols
}
func (c *editorImpl) preprocessEvent(event Event, r *http.Request) {
// Empty string for text box is a valid value.
// So we have to check whether it is supplied, not just whether its len() > 0
value := r.FormValue(paramCompValue)
//fmt.Printf("Getting value %+v\n", value)
if len(value) > 0 {
c.text = value
} else {
// Empty string might be a valid value, if the component value param is present:
values, present := r.Form[paramCompValue] // Form is surely parsed (we called FormValue())
if present && len(values) > 0 {
c.text = values[0]
}
}
}
var (
strDivOp = []byte("<div") // "<div"
//strRows = []byte(` rows="`) // ` rows="`
//strCols = []byte(`" cols="`) // `" cols="`
strDivOpCl = []byte("\">\n") // "\">\n"
strDivCl = []byte("</div>") // "</textarea>"
)
func (c *editorImpl) Render(w Writer) {
if c.isInline {
c.RenderInline(w)
} else {
c.RenderTextArea(w)
}
}
// renderTextArea renders the component as an textarea HTML tag.
func (c *editorImpl) RenderInline(w Writer) {
w.Write(strDivOp)
c.renderAttrsAndStyle(w)
c.renderEnabled(w)
c.renderEHandlers(w)
w.Write(strDivOpCl)
w.Writes(c.text)
w.Write(strDivCl)
w.Write([]byte(fmt.Sprintf(`<script>
/**
* This code is based on <https://github.com/pourquoi/ckeditor5-simple-upload>
* and will be implemented by <https://github.com/mecha-cms/extend.c-k-editor> in the future!
*/
// The upload adapter
var Adapter = function(loader, urlOrObject, t) {
var $ = this;
$.loader = loader;
$.urlOrObject = urlOrObject;
$.t = t;
$.upload = function() {
return new Promise(function(resolve, reject) {
$._initRequest();
$._initListeners(resolve, reject);
$._sendRequest();
});
};
$.abort = function() {
$.xhr && $.xhr.abort();
};
$._initRequest = function() {
$.xhr = new XMLHttpRequest();
var url = $.urlOrObject,
headers;
if (typeof url === "object") {
url = url.url;
headers = url.headers;
}
$.xhr.withCredentials = true;
$.xhr.open('POST', url, true);
if (headers) {
for (var key in headers) {
if (typeof headers[key] === "function") {
$.xhr.setRequestHeader(key, headers[key]());
} else {
$.xhr.setRequestHeader(key, headers[key]);
}
}
}
$.xhr.responseType = 'json';
};
$._initListeners = function(resolve, reject) {
var xhr = $.xhr,
loader = $.loader,
t = $.t,
genericError = t('Cannot upload file:') + ' ' + loader.file.name;
xhr.addEventListener('error', function() {
reject(genericError);
});
xhr.addEventListener('abort', reject);
xhr.addEventListener('load', function() {
var response = xhr.response;
if (!response || !response.uploaded) {
return reject(response && response.error && response.error.message ? response.error.message : genericError);
}
resolve({
'default': response.url
});
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
});
}
}
$._sendRequest = function() {
var data = new FormData();
data.append('upload', $.loader.file);
$.xhr.send(data);
};
};
let editor%d;
InlineEditor
.create( document.getElementById( '%d' ) )
.then( newEditor => {
editor%d = newEditor;
editor%d.model.document.on( 'change:data', () => {
value = editor%d.getData()
console.log("The data has changed!" + value );
//se(null,11,%d,encodeURIComponent(value))
se2(null,11,%d,value)
} );
editor%d.plugins.get('FileRepository').createUploadAdapter = function(loader) {
return new Adapter(loader, _pathUploadCK, editor%d.t);
};
})
.catch( error => {
console.error( error );
});
</script>`, c.id, c.id, c.id, c.id, c.id, c.id, c.id, c.id, c.id)))
}
// renderTextArea renders the component as an textarea HTML tag.
func (c *editorImpl) RenderTextArea(w Writer) {
w.Write(strTextareaOp)
c.renderAttrsAndStyle(w)
c.renderEnabled(w)
c.renderEHandlers(w)
// New line char after the <textarea> tag is ignored.
// So we must render a newline after textarea, else if text value
// starts with a new line, it will be omitted!
w.Write(strRows)
w.Writev(c.rows)
w.Write(strCols)
w.Writev(c.cols)
w.Write(strTextAreaOpCl)
c.renderText(w)
w.Write(strTextAreaCl)
w.Write([]byte(fmt.Sprintf(`<script>
/**
* This code is based on <https://github.com/pourquoi/ckeditor5-simple-upload>
* and will be implemented by <https://github.com/mecha-cms/extend.c-k-editor> in the future!
*/
// The upload adapter
var Adapter = function(loader, urlOrObject, t) {
var $ = this;
$.loader = loader;
$.urlOrObject = urlOrObject;
$.t = t;
$.upload = function() {
return new Promise(function(resolve, reject) {
$._initRequest();
$._initListeners(resolve, reject);
$._sendRequest();
});
};
$.abort = function() {
$.xhr && $.xhr.abort();
};
$._initRequest = function() {
$.xhr = new XMLHttpRequest();
var url = $.urlOrObject,
headers;
if (typeof url === "object") {
url = url.url;
headers = url.headers;
}
$.xhr.withCredentials = true;
$.xhr.open('POST', url, true);
if (headers) {
for (var key in headers) {
if (typeof headers[key] === "function") {
$.xhr.setRequestHeader(key, headers[key]());
} else {
$.xhr.setRequestHeader(key, headers[key]);
}
}
}
$.xhr.responseType = 'json';
};
$._initListeners = function(resolve, reject) {
var xhr = $.xhr,
loader = $.loader,
t = $.t,
genericError = t('Cannot upload file:') + ' ' + loader.file.name;
xhr.addEventListener('error', function() {
reject(genericError);
});
xhr.addEventListener('abort', reject);
xhr.addEventListener('load', function() {
var response = xhr.response;
if (!response || !response.uploaded) {
return reject(response && response.error && response.error.message ? response.error.message : genericError);
}
resolve({
'default': response.url
});
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
});
}
}
$._sendRequest = function() {
var data = new FormData();
data.append('upload', $.loader.file);
$.xhr.send(data);
};
};
let editor%d;
ClassicEditor
.create( document.getElementById( '%d' ) )
.then( newEditor => {
editor%d = newEditor;
editor%d.model.document.on( 'change:data', () => {
value = editor%d.getData()
console.log("The data has changed!" + value );
//se(null,11,%d,encodeURIComponent(value))
se2(null,11,%d,value)
} );
editor%d.plugins.get('FileRepository').createUploadAdapter = function(loader) {
return new Adapter(loader, _pathUploadCK, editor%d.t);
};
})
.catch( error => {
console.error( error );
});
</script>`, c.id, c.id, c.id, c.id, c.id, c.id, c.id, c.id, c.id)))
}