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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
|
/** NOTE:
* depricated code for tag-system is commented-out and kept in the source-code
* as case-study; the code is operational;
*/
// Globals
// -----------------------------------------------------------------------------
// NOTE:
// Variable `entity_id` is defined before evaluating this script
// id (int) : the id of edited post (or 0 if new post)
var lesson;
var id = (entity_id == 0) ? false : entity_id;
var categories = [
// Nope! root can not be a post's category ... { id: 0 , label: 'Ρίζα (root)' }
];
var privileges = [
{ id: 0, label: '_Δημόσιο_'}
];
var files = []; // array of { id:.., title:.., type:.., path:.. } records
// TODO: support tags
// var tags = []; // array of integers
// an alternative--id when a lesson_id not exists (needed for file-upload)
// ... consist of a 6-digit date string + random number up to 999
const yymmdd = new Date().toISOString().slice(2, 10).replaceAll('-','');
var rnd999 = Math.floor(Math.random() * 1000);
var altID = (id == 0) ? ( yymmdd +'-'+ rnd999.toString() ) : id;
// Supplamentary functions
// -----------------------------------------------------------------------------
// function for sorting an array by 'label' attribute
// --- -- -- - - -
function compare_label (a,b) {
if ( a.label < b.label ) { return -1; }
if ( a.label > b.label ) { return 1; }
return 0;
}
// return course record by course-id
// --- -- -- - - -
function course_record(id) {
var record = 0;
categories.forEach(el => { if (el.id == id) record = el; });
return record;
}
// Modal HTML Creators
// -----------------------------------------------------------------------------
const modal_header = (title) => {
return [
'<div class="modal-header">',
'<h4 class="modal-title" id="myModalLabel">',
title,
'</h4>',
'<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">',
'<span aria-hidden="true"></span>',
'</button>',
'</div>'
].join('\n');
}
const upload_file_form = () => {
return [
'<form method="POST" id="file_upload_form" name="upload_file_form">',
'<div class="modal-body">',
'<input type="hidden" name="folder" value="'+ altID +'">',
'<div class="form-group">',
'<label for="title">Τίτλος/Περιγραφή για το Αρχείο</label>',
'<input type="text" class="form-control " value="" name="title" id="title" placeholder="Τίτλος για το Αρχείο" required="">',
'</div>',
'<div class="form-group">',
'<label class="control-label" for="file">Εισαγωγή Αρχείου</label>',
'<input class="form-control" type="file" id="file" name="file" required="">',
'</div>',
'</div>',
'<div class="modal-footer">',
'<div class="row" style="width: 50%;">',
'<div class="form-actions">',
'<div class="col col-4">',
'<buton type="button" class="btn btn-default js-modal-close col-12" data-bs-dismiss="modal">',
'Κλείσιμο',
'</button>',
'</div>',
'<div class="col-8">',
'<button class="btn btn-success col-12" type="submit">Καταχώριση</button>',
'</div>',
'</div>',
'</div>',
'</div>',
'</form>'
].join('\n');
}
const preview_article = (title, intro, body) => {
return [
'<div class="modal-body">',
'<div class="post">',
'<h2>'+ title +'</h2>',
((intro == '') ? '' : ('<div class="intro">'+ intro +'</div>')),
'<div class="article-body">',
marked.parse(body, { sanitize: true }),
'</div>',
'</div>',
'</div>',
'<div class="modal-footer">',
'<div class="row" style="width: 50%;">',
'<div class="form-actions">',
'<div class="col-md-4 col-md-offset-4 col-6 col-offset-3">',
'<buton type="button" class="btn btn-default js-modal-close col-12" data-bs-dismiss="modal">',
'Κλείσιμο',
'</button>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('\n');
}
$(document).ready(function() {
// When document is ready
// -------------------------------------------------------------------------
// inti category (select2)
// ...
$("#course_id").select2({
placeholder: 'Κεφάλαιο',
width: '100%'
});
// inti category (select2)
// ...
$("#privilege_id").select2({
placeholder: 'Επίπεδο Πρόσβασης',
width: '100%'
});
/** DEPRICATED: (tag system)
*
* // init tags (select2)
* // ...
* $('#tags').select2({
* placeholder: 'Ετικέτες (tags/keywords)',
* width: '100%',
* tags: true
* });
*/
/** DEPRICATED:
*
* // TINY-MCE EDITOR
* init editor (tiny MCE)
* tinymce.init({
* selector: 'form textarea[name=body]',
* language: 'el',
* menubar: true
* });
*/
/** preload content
* --- -- -- - - -
* get post
* get categories
* get tags
* update content (form-elements)
*/
if (id) { // if an `id` is given, load post .. then init_form
$.getJSON( "/admin/api/lesson/" + id )
.done( function (data) {
lesson = data; // keep post
// update fields' values
$('input[name=id]').val(lesson.id); // id
$('input[name=title]').val(lesson.title); // title
$('textarea[name=intro]').val(lesson.intro); // intro
$('textarea[name=body]').val(lesson.body); // body
$('select[name=status]').val(
(lesson.status == 0) ? '0' : "one"
).trigger('change');
// $('input[name=status]').prop( // status
// 'checked',
// ((lesson.status==1)? true : false))
// .trigger('change');
// $('#post-info').html('Δημιουργία: '+post.creation_date+'<br>Τελευταία Ενημέρωση: '+ post.update_date);
// parse media files; then draw
if (lesson.medias_json != null) {
files = JSON.parse(lesson.medias_json);
}
draw_files_list(); // then draw the files list
init_form_values(); // init all (other) values
});
} else { // else ... just init_form
init_form_values();
}
/**
* load categories and tags;
* if not a new post (id!=0) update form elemnts with post's values
*/
function init_form_values() {
$.when( // when loaded posts and categories
$.getJSON( "/admin/api/categories" ),
$.getJSON( "/admin/api/privileges" )
).done( function( categories_response, privileges_response ) {
// construct categories data
// ---
Object.keys(categories_response[0]).forEach( key => {
cat = categories_response[0][key];
categories.push({
id: cat.rec.id,
label: cat.breadcrumb.replaceAll('\t', ' / ')
});
});
categories.sort( compare_label ); // sort categories by breadcrumb
/** DEPRICATED: (tag system)
*
* // construct tags data
* // ---
* Object.keys(tags_response[0]).forEach( key => {
* tag = tags_response[0][key];
* tags.push({
* id: tag.id,
* label: tag.name
* });
* });
*/
// construct provileges data
// ---
Object.keys(privileges_response[0]).forEach( key => {
priv = privileges_response[0][key];
privileges.push({
id: priv.id,
label: priv.label
});
});
privileges.sort( compare_label ); // sort categories by breadcrumb
// pass categories and tags options onto select2 elements
// --- -- -- - - -
if (id == 0) {
set_parent_options( $('#course_id'), categories );
set_parent_options( $('#privilege_id'), privileges );
} else {
// setup category_id options; select post's chosen category-id
set_parent_options( $('#course_id'), categories, lesson.course_id );
/*** DEPRICATED: (tag system)
*
* // parse selected tags
* // ---
* var selected_tag_ids = [];
* if (post.tags_json != null) {
* var selected_tags = JSON.parse(post.tags_json);
* selected_tags.forEach( itag => { selected_tag_ids.push(itag.id); })
* }
*/
// setup tags options; select post's chosen tags
set_parent_options( $('#privilege_id'), privileges, lesson.privilege_id );
// DEPRICATED: ALSO: if tags selectd, show tags field
// if (selected_tag_ids.length != 0) { $('.optional label[for=tags]').addClass('show'); }
}
});
}
/** set_parent_options()
*
* -> create options for parents <select>
* -> choose selected parent
*
* NOTE:
* the targer <select> should be a select2 control
*
* @param parents (array): array of parents
* @param selected (int): selected parent
*/
function set_parent_options(selector, list, selected_value = false) {
list.forEach( li => { // attach options into <select> control
selector.append(`<option value="${li.id}">${li.label}</option>`);
});
if (selected_value !== false) { // mark selected option(s)
selector.val(selected_value).trigger('change');
}
else { selector.val(null).trigger('change'); }
}
/** draw_files_list
* --- -- -- - - -
*/
function draw_files_list() {
var li_list = [];
var ref_icon, ref_class;
files.forEach( item => {
var copy = [ // copy button
'<button type="button" class="btn btn-xs btn-default js-copy"',
' data-url="' + item.path +'"',
' data-type="' + item.type + '"',
'>',
'<i class="far fa-clone"></i>',
'</button>'
].join('');
var del = [ // delete button
'<button type="button" class="btn btn-xs btn-danger js-delete"',
'data-id="' + item.id + '">',
'<i class="fas fa-trash-alt"></i>',
'</button>'
].join('');
var option = [ // li html
'<li>',
'<div class="text">' + item.label + '</div>',
'<div class="actions">',
copy, ' ', del,
'</div>',
'</li>'
].join('');
li_list.push(option); // push to li_list
});
$('#files_list').html( li_list.join('\n') );
}
// When form's action-buttons are clicked
// -------------------------------------------------------------------------
// form submit
// --- -- -- - - -
$('.edit-post form').submit( event => {
event.preventDefault();
/** DEPRICATED:
*
### TAG SYSTEM
# // rearrange tags to old and new ones
# // ---
# var old_tags = [];
# var new_tags = [];
# var tags = $('#tags').select2('data');
# tags.forEach( t => {
# if (!parseInt(t.id)) {
# new_tags.push(t.text);
# } else { old_tags.push(t.id); }
# })
*/
var attachments = [];
// attachments (array) of "`media_id`;`reference`" strings
files.forEach( f => { attachments.push( f.id ) });
// prepare data to POST
// ---
var data = {
id: parseInt($('.edit-post form input[name=id]').val()),
title: $('.edit-post form input[name=title]').val(),
course_id: parseInt($('#course_id').select2('data')[0].id),
intro: $('.edit-post form textarea[name=intro]').val(),
body: $('.edit-post form textarea[name=body]').val(),
status: ( ($('select[name=status]').val() == "0") ? 0 : 1 ),
privilege_id: parseInt($('#privilege_id').select2('data')[0].id),
// tags: old_tags,
// new_tags: new_tags,
media: attachments
};
// select action url (add or update)
// ---
var request = '/admin/api/lesson/' + ((data.id == 0) ? 'add' : 'update');
// send POST (ajax) request
$.post(request, data)
.done(function( data ) {
// console.log(data);
window.location.href = '/admin/lessons'; // seems ok; bach to articles
});
});
// go-back (to lessons)
// --- -- -- - - -
$('#go-back').click( event => {
if (confirm('Θέλετε να ακυρώσετε τις όποιες αλλαγές και να φύγτε από τη σελίδα;')) {
window.location.href = '/admin/lessons';
}
});
// copy url button
// --- -- -- - - -
$('.admin-container').on('click', 'button.js-copy', function (e) {
var copytext = ''; // default: copy nothing
if ($(this).data('id') !== undefined) {
copytext = window.location.origin +'/lesson/' + $(this).data('id');
}
if ($(this).data('url') !== undefined) {
copytext = window.location.origin + '/serve/file/' + $(this).data('url') + '?type=' + $(this).data('type');
}
navigator.clipboard
.writeText(copytext)
.then(() => { // notify the copy event
$(this).addClass('copied');
setTimeout( () => { $(this).removeClass('copied'); }, 700);
console.log(copytext, ' copied!');
})
.catch(() => {
console.log("error on coping text");
});
});
// delete (remove) file button
// --- -- -- - - -
$('.admin-container').on('click', 'button.js-delete', function (e) {
console.log('delete!');
var media_id = $(this).data('id');
// remove from files array the one with id == media_id
// ---
var temp = [];
files.forEach( it => { if (it.id != media_id) temp.push(it); });
files = temp; // re-define files
draw_files_list(); // then re-draw files list
});
/** DEPRICATED:
*
# // show|hide file as referece button
# // --- -- -- - - -
# $('.admin-container').on('click', 'button.js-reference', function (e) {
# var id = $(this).data('id');
#
# // toggle reference attribute of item with `id` = id
# // ---
# var temp = [];
# files.forEach( it => {
# if (it.id == id) {
# it.reference = (it.reference==0) ? 1 : 0;
# }
# temp.push(it)
# });
#
# files = temp; // re-define files
# draw_files_list(); // then re-draw files list
# });
*/
/** When modal show-up
* -------------------------------------------------------------------------
* ... prepare the manage-category form
* ... update select2 with possible parents
*/
$('#editorModal').on('show.bs.modal', event => {
let button = $(event.relatedTarget); // Button that triggered the modal
let action = button.data('action'); // action
// var modal = $(this); // modal object
// update modal literature
switch (action) {
case 'upload_file':
$("#editorModal .modal-content").html(
modal_header('Εισαγωγή Αρχείου') + upload_file_form()
);
break;
case 'preview':
let preview = preview_article(
$('.edit-post form input[name=title]').val(),
$('.edit-post form textarea[name=intro]').val(),
$('.edit-post form textarea[name=body]').val()
);
$("#editorModal .modal-content").html( modal_header('Προεπισκόπηση') + preview);
break;
default:
// do nothing
}
});
/** submit upload file event
* -------------------------------------------------------------------------
*/
$('#editorModal').on('submit', 'form[name=upload_file_form]', function (event) {
event.preventDefault();
// create the FormData object
// --- -- -- - - -
var fd = new FormData(document.getElementById('file_upload_form'));
// post the form (via ajax)
$.ajax({
url: '/admin/api/file_upload',
type: 'POST',
data: fd,
contentType: false,
processData: false,
dataType: 'json',
success: function(response) { // on success
if (response.success) {
files.push({ // ... update files array
id: response.id,
label: response.title,
path: response.path,
type: response.type
});
draw_files_list();
$('#editorModal').modal('hide');
} else {
console.log('File not uploaded');
}
}
});
});
// TODO:
// disable links while previewing the article
// OR add a target="_blank"
});
|