forked from trampgeek/moodle-qtype_coderunner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestionbrowser.php
More file actions
1612 lines (1368 loc) · 52.8 KB
/
questionbrowser.php
File metadata and controls
1612 lines (1368 loc) · 52.8 KB
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of CodeRunner - http://coderunner.org.nz
//
// CodeRunner 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.
//
// CodeRunner 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 CodeRunner. If not, see <http://www.gnu.org/licenses/>.
/**
* Simplified Question Browser that generates data inline.
* Enhanced with advanced filter builder.
*
* @package qtype_coderunner
* @copyright 2025 Richard Lobb, The University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace qtype_coderunner;
use html_writer;
define('NO_OUTPUT_BUFFERING', true);
require_once(__DIR__ . '/../../../config.php');
require_once($CFG->libdir . '/questionlib.php');
require_once(__DIR__ . '/classes/bulk_tester.php');
// Get the parameter from the URL.
$contextid = required_param('contextid', PARAM_INT);
// Login and check permissions.
require_login();
$context = \context::instance_by_id($contextid);
require_capability('moodle/question:editall', $context);
// Get course name for display.
$coursename = '';
if ($context->contextlevel == CONTEXT_COURSE) {
$course = $DB->get_record('course', ['id' => $context->instanceid], 'fullname');
$coursename = $course ? $course->fullname : 'Unknown Course (' . $contextid . ')';
} else if ($context->contextlevel == CONTEXT_MODULE) {
$cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
$course = $DB->get_record('course', ['id' => $cm->course], 'fullname');
$coursename = $course ? $course->fullname : 'Unknown Course (' . $contextid . ')';
} else {
$coursename = $context->get_context_name() . ' (' . $contextid . ')';
}
// Generate questions data directly.
$generator = new questions_json_generator($context);
$questions = $generator->generate_questions_data();
$questionsjson = json_encode($questions, JSON_UNESCAPED_UNICODE);
// Get the correct Moodle base URL for JavaScript.
global $CFG;
$moodlebaseurl = $CFG->wwwroot;
$urlparams = ['contextid' => $context->id];
$PAGE->set_url('/question/type/coderunner/questionbrowser.php', $urlparams);
$PAGE->set_context($context);
$PAGE->set_title("Question browser");
if ($context->contextlevel == CONTEXT_MODULE) {
$cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
$PAGE->set_cm($cm, $DB->get_record('course', ['id' => $cm->course], '*', MUST_EXIST));
}
/**
* Class to generate questions.json from database.
*/
class questions_json_generator {
private $context;
private $usagemap;
public function __construct($context) {
$this->context = $context;
}
/**
* Generate the complete questions data array.
*/
public function generate_questions_data() {
$questions = bulk_tester::get_all_coderunner_questions_in_context($this->context->id, false);
// Fetch quiz usage for all questions in one bulk query.
$this->usagemap = $this->fetch_quiz_usage_bulk($questions);
$enhancedquestions = [];
foreach ($questions as $question) {
$enhanced = $this->enhance_question_metadata($question);
$enhancedquestions[] = $enhanced;
}
return $enhancedquestions;
}
/**
* Fetch quiz usage for all questions in a single query.
*/
private function fetch_quiz_usage_bulk($questions) {
global $DB;
if (empty($questions)) {
return [];
}
$questionids = array_column($questions, 'id');
if (empty($questionids)) {
return [];
}
// Build the query to get quiz usage for all questions.
// This combines question_references (direct usage) and question_attempts (random question usage).
[$insql, $params] = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
$sql = "SELECT CONCAT(qv.questionid, '-', qz.id) as uniqueid,
qv.questionid, qz.id as quizid, qz.name as quizname
FROM {question_versions} qv
JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
JOIN {question_references} qr ON qr.questionbankentryid = qbe.id
JOIN {quiz_slots} slot ON slot.id = qr.itemid
JOIN {quiz} qz ON qz.id = slot.quizid
WHERE qv.questionid $insql
AND qr.component = 'mod_quiz'
AND qr.questionarea = 'slot'
GROUP BY qv.questionid, qz.id, qz.name
ORDER BY qv.questionid, qz.name";
$usages = $DB->get_records_sql($sql, $params);
// Build lookup map: questionid => array of quiz names.
$usagemap = [];
foreach ($usages as $usage) {
if (!isset($usagemap[$usage->questionid])) {
$usagemap[$usage->questionid] = [];
}
$usagemap[$usage->questionid][] = $usage->quizname;
}
return $usagemap;
}
/**
* Enhance a single question with metadata analysis.
*/
private function enhance_question_metadata($question) {
$courseid = $this->get_course_id_from_context();
$answer = $this->extract_answer($question->answer ?? '');
$tags = $this->get_question_tags($question->id);
$usedin = $this->usagemap[$question->id] ?? [];
// Get question bank URL parameters (handles Moodle 5's cmid vs courseid).
$qbankparams = \qtype_coderunner_util::make_question_bank_url_params($question);
$enhanced = [
'type' => 'coderunner',
'id' => (string)$question->id,
'name' => $question->name,
'questiontext' => $question->questiontext,
'answer' => $answer,
'coderunnertype' => $question->coderunnertype,
'category' => bulk_tester::get_category_path($question->category),
'categoryid' => (string)$question->category,
'contextid' => (string)$question->contextid,
'version' => (int)$question->version,
'courseid' => (string)$courseid,
'tags' => $tags,
'usedin' => $usedin,
'qbankparams' => $qbankparams,
];
$enhanced['lines_of_code'] = $this->count_lines_of_code($answer);
return $enhanced;
}
private function extract_answer($answer) {
if (empty(trim($answer))) {
return '';
}
$decoded = json_decode($answer, true);
if (
json_last_error() === JSON_ERROR_NONE &&
is_array($decoded) &&
array_key_exists('answer_code', $decoded)
) {
$answercode = $decoded['answer_code'];
if (is_array($answercode)) {
return implode("\n", $answercode);
}
return $answercode;
}
return $answer;
}
private function get_course_id_from_context() {
if ($this->context->contextlevel == CONTEXT_COURSE) {
return $this->context->instanceid;
} else if ($this->context->contextlevel == CONTEXT_MODULE) {
$cm = get_coursemodule_from_id(false, $this->context->instanceid, 0, false, MUST_EXIST);
return $cm->course;
}
return '0';
}
private function count_lines_of_code($code) {
if (empty(trim($code))) {
return 0;
}
$lines = explode("\n", $code);
$count = 0;
foreach ($lines as $line) {
$trimmed = trim($line);
if (!empty($trimmed) && !preg_match('/^\s*#/', $trimmed)) {
$count++;
}
}
return $count;
}
private function get_question_tags($questionid) {
$tagobjects = \core_tag_tag::get_item_tags('core_question', 'question', $questionid);
$tags = [];
foreach ($tagobjects as $tag) {
$tags[] = $tag->name;
}
return $tags;
}
}
// Set up page using Moodle's layout system.
$PAGE->set_title('Question Browser - ' . $coursename);
$PAGE->set_heading('Question Browser - ' . $coursename);
$PAGE->set_pagelayout('incourse');
if ($context->contextlevel == CONTEXT_COURSE) {
$PAGE->set_course($DB->get_record('course', ['id' => $context->instanceid]));
} else if ($context->contextlevel == CONTEXT_MODULE) {
$cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
$course = $DB->get_record('course', ['id' => $cm->course], '*', MUST_EXIST);
$PAGE->set_course($course);
$PAGE->set_cm($cm);
}
$PAGE->navbar->add('Question Browser');
echo $OUTPUT->header();
?>
<style>
/* Reduce excessive white space */
#page-header, .page-header-headings {
margin-top: 0;
padding-top: 0.5rem;
}
/* Highlight active buttons when panels are open */
.qbrowser-btn-active {
background-color: #0066cc !important;
border-color: #0066cc !important;
color: white !important;
}
/* Minimal custom styles to work with Moodle theme */
.qbrowser-filters .form-group {
margin-bottom: 1rem;
}
.qbrowser-grid2 {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.5rem;
}
.qbrowser-list {
max-height: 75vh;
overflow-y: auto;
}
.qbrowser-list table {
margin-bottom: 0;
}
.qbrowser-detail {
margin: 0.5rem 0;
padding: 1rem;
border-left: 4px solid #dee2e6;
background-color: var(--bs-light, #f8f9fa);
}
.qbrowser-detail.code-content {
white-space: pre-wrap;
font-family: monospace;
font-size: 0.875rem;
}
.qbrowser-detail.html-content {
font-family: inherit;
}
.qbrowser-controls .btn {
margin-right: 0.25rem;
margin-bottom: 0.25rem;
}
/* Advanced filter styles */
.advanced-section {
margin-top: 1rem;
border-top: 2px solid #dee2e6;
padding-top: 1rem;
}
.advanced-toggle {
cursor: pointer;
user-select: none;
display: flex;
align-items: center;
gap: 0.5rem;
color: #0066cc;
font-weight: 500;
}
.advanced-toggle:hover {
color: #0052a3;
}
.advanced-toggle-icon {
transition: transform 0.2s;
display: inline-block;
}
.advanced-toggle-icon.expanded {
transform: rotate(90deg);
}
.advanced-content {
display: none;
margin-top: 1rem;
}
.advanced-content.show {
display: block;
}
.filter-rule {
display: grid;
grid-template-columns: 2fr 1.5fr 2fr auto;
gap: 0.5rem;
align-items: center;
margin-bottom: 0.5rem;
padding: 0.5rem;
background-color: #f8f9fa;
border-radius: 0.25rem;
}
.filter-rule select,
.filter-rule input {
font-size: 0.875rem;
}
.filter-connector {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0.25rem 0;
padding-left: 0.5rem;
}
.filter-connector-select {
width: auto;
font-size: 0.75rem;
padding: 0.125rem 0.5rem;
font-weight: 600;
}
.filter-chips {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 0.5rem;
}
.filter-chip {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.25rem 0.75rem;
background-color: #e3f2fd;
border: 1px solid #90caf9;
border-radius: 1rem;
font-size: 0.875rem;
color: #1976d2;
}
.filter-chip-remove {
cursor: pointer;
font-weight: bold;
color: #1976d2;
border: none;
background: none;
padding: 0;
font-size: 1rem;
line-height: 1;
}
.filter-chip-remove:hover {
color: #d32f2f;
}
@media (min-width: 992px) {
.qbrowser-main {
display: grid;
grid-template-columns: 350px 1fr;
gap: 1.5rem;
position: relative;
}
.qbrowser-main-resizer {
position: absolute;
left: calc(350px + 0.75rem); /* Center in the gap */
top: 0;
bottom: 0;
width: 8px;
margin-left: -4px; /* Center the handle */
cursor: col-resize;
z-index: 10;
background-color: #dee2e6;
border-radius: 4px;
transition: background-color 0.2s;
}
.qbrowser-main-resizer:hover {
background-color: #0066cc;
}
.qbrowser-main-resizer::before {
content: '⋮';
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 16px;
line-height: 1;
text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
}
/* Resizable table columns */
.qbrowser-list table th {
position: relative;
overflow: visible;
}
.column-resizer {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 10px;
cursor: col-resize;
user-select: none;
z-index: 10;
}
.column-resizer:hover {
background-color: rgba(255, 255, 255, 0.3);
}
.column-resizer::after {
content: '';
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
width: 2px;
height: 60%;
background-color: rgba(255, 255, 255, 0.5);
}
.resizing {
cursor: col-resize !important;
user-select: none !important;
}
.resizing * {
cursor: col-resize !important;
user-select: none !important;
}
</style>
<div class="container-fluid qbrowser-main" id="qbrowserMain">
<!-- LEFT: FILTERS -->
<div class="card" id="filterPanel">
<div class="card-header">
<h5 class="mb-0">Filters</h5>
</div>
<div class="card-body qbrowser-filters">
<div class="form-group">
<h6>Data</h6>
<div id="loadStatus" class="text-muted small">Loaded <?php echo count($questions); ?> questions</div>
</div>
<hr>
<div class="form-group">
<h6>Text filter</h6>
<div class="row">
<div class="col-md-6">
<label for="kw" class="form-label small">Search</label>
<input type="text" id="kw" class="form-control form-control-sm" placeholder="substring or regex" />
</div>
<div class="col-md-6">
<label for="kwMode" class="form-label small">Mode</label>
<select id="kwMode" class="form-control form-control-sm">
<option>Include</option>
<option>Exclude</option>
</select>
</div>
</div>
<div class="row mt-2">
<div class="col-md-6">
<label for="kwField" class="form-label small">Field</label>
<select id="kwField" class="form-control form-control-sm">
<option>Any</option>
</select>
</div>
<div class="col-md-6">
<label for="kwType" class="form-label small">Type</label>
<select id="kwType" class="form-control form-control-sm">
<option>Text</option>
<option>Regex</option>
</select>
</div>
</div>
<div class="mt-1">
<small class="text-muted">Regex uses JavaScript syntax</small>
</div>
</div>
<hr>
<div class="form-group">
<h6>Lines of code</h6>
<div id="numericFilters"></div>
</div>
<hr>
<div class="form-group">
<h6>CodeRunner type</h6>
<div id="categoricalFilters"></div>
</div>
<!-- Advanced Filters Section -->
<div class="advanced-section">
<div class="advanced-toggle" id="advancedToggle">
<span class="advanced-toggle-icon">▶</span>
<h6 class="mb-0">Advanced Filters</h6>
</div>
<div class="advanced-content" id="advancedContent">
<div class="mb-2">
<small class="text-muted">Build complex filter rules with AND/OR logic</small>
</div>
<div id="filterRules"></div>
<button class="btn btn-sm btn-outline-primary mt-2" id="addRule">+ Add Rule</button>
<div id="activeFiltersChips" class="filter-chips"></div>
</div>
</div>
<hr>
<div class="d-flex gap-2 flex-wrap">
<button class="btn btn-primary btn-sm" id="apply">Apply Filters</button>
<button class="btn btn-secondary btn-sm" id="clear">Clear</button>
</div>
<div class="mt-2">
<small class="text-muted">Tip: All filters combine with AND logic. Advanced filters provide OR options.</small>
</div>
</div>
</div>
<!-- Resizer for main columns -->
<div class="qbrowser-main-resizer" id="mainResizer"></div>
<!-- RIGHT: RESULTS -->
<div class="card" id="resultsPanel">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div class="d-flex align-items-center">
<h5 class="mb-0">Results</h5>
<span class="text-muted small ml-3" id="count">No data</span>
</div>
<div class="d-flex">
<button id="exportJson" class="btn btn-success btn-sm mr-2" disabled>Export JSON</button>
<button id="exportCsv" class="btn btn-success btn-sm" disabled>Export CSV</button>
</div>
</div>
</div>
<div class="card-body p-0">
<div id="list" class="qbrowser-list">
<!-- Content will be built dynamically -->
</div>
</div>
</div>
</div>
<script>
(() => {
const rawData = <?php echo $questionsjson; ?>;
let viewData = rawData.slice();
const moodleBaseUrl = '<?php echo $moodlebaseurl; ?>';
const COMMON_CATS = [];
let currentSort = {field: null, direction: 'asc'};
let currentlyOpenDetails = null;
let advancedRules = [];
let ruleIdCounter = 0;
let columnWidths = {
name: null,
actions: 280,
category: null,
tags: 200,
usedin: 200
};
// Elements.
const kw = document.getElementById('kw');
const kwMode = document.getElementById('kwMode');
const kwField = document.getElementById('kwField');
const kwType = document.getElementById('kwType');
const numericFilters = document.getElementById('numericFilters');
const categoricalFilters = document.getElementById('categoricalFilters');
const applyBtn = document.getElementById('apply');
const clearBtn = document.getElementById('clear');
const listEl = document.getElementById('list');
const countEl = document.getElementById('count');
const exportJsonBtn = document.getElementById('exportJson');
const exportCsvBtn = document.getElementById('exportCsv');
const advancedToggle = document.getElementById('advancedToggle');
const advancedContent = document.getElementById('advancedContent');
const filterRulesEl = document.getElementById('filterRules');
const addRuleBtn = document.getElementById('addRule');
const activeFiltersChips = document.getElementById('activeFiltersChips');
const qbrowserMain = document.getElementById('qbrowserMain');
const filterPanel = document.getElementById('filterPanel');
const mainResizer = document.getElementById('mainResizer');
// Helpers.
function isNumber(x){ return typeof x === 'number' && Number.isFinite(x); }
function buildHeader() {
const table = document.createElement('table');
table.className = 'table table-striped table-hover table-sm';
table.style.tableLayout = 'fixed';
table.style.width = '100%';
const colgroup = document.createElement('colgroup');
const nameColDef = document.createElement('col');
const actionsColDef = document.createElement('col');
const categoryColDef = document.createElement('col');
const tagsColDef = document.createElement('col');
const usedinColDef = document.createElement('col');
if (columnWidths.name) nameColDef.style.width = columnWidths.name + 'px';
actionsColDef.style.width = columnWidths.actions + 'px';
if (columnWidths.category) categoryColDef.style.width = columnWidths.category + 'px';
if (columnWidths.tags) tagsColDef.style.width = columnWidths.tags + 'px';
if (columnWidths.usedin) usedinColDef.style.width = columnWidths.usedin + 'px';
colgroup.append(nameColDef, actionsColDef, categoryColDef, tagsColDef, usedinColDef);
table.appendChild(colgroup);
const thead = document.createElement('thead');
thead.className = 'table-dark sticky-top';
const headerRow = document.createElement('tr');
const nameCol = document.createElement('th');
nameCol.id = 'sortName';
nameCol.style.cursor = 'pointer';
nameCol.className = 'user-select-none';
nameCol.style.position = 'relative';
const nameText = document.createElement('span');
nameText.textContent = 'Name ↕';
nameCol.appendChild(nameText);
const actionsCol = document.createElement('th');
actionsCol.style.position = 'relative';
const actionsText = document.createElement('span');
actionsText.textContent = 'Actions';
actionsCol.appendChild(actionsText);
const categoryCol = document.createElement('th');
categoryCol.id = 'sortCategory';
categoryCol.style.cursor = 'pointer';
categoryCol.className = 'user-select-none';
categoryCol.style.position = 'relative';
const categoryText = document.createElement('span');
categoryText.textContent = 'Category ↕';
categoryCol.appendChild(categoryText);
const tagsCol = document.createElement('th');
tagsCol.id = 'sortTags';
tagsCol.style.cursor = 'pointer';
tagsCol.className = 'user-select-none';
tagsCol.style.position = 'relative';
const tagsText = document.createElement('span');
tagsText.textContent = 'Tags ↕';
tagsCol.appendChild(tagsText);
const usedinCol = document.createElement('th');
usedinCol.id = 'sortUsedIn';
usedinCol.style.cursor = 'pointer';
usedinCol.className = 'user-select-none';
usedinCol.style.position = 'relative';
const usedinText = document.createElement('span');
usedinText.textContent = 'Used In ↕';
usedinCol.appendChild(usedinText);
// Add resizers to all columns except the last
[nameCol, actionsCol, categoryCol, tagsCol].forEach((col, idx) => {
const resizer = document.createElement('div');
resizer.className = 'column-resizer';
resizer.dataset.columnIndex = idx;
// Stop propagation to prevent triggering sort on parent <th>
resizer.addEventListener('click', (e) => {
e.stopPropagation();
});
col.appendChild(resizer);
});
headerRow.appendChild(nameCol);
headerRow.appendChild(actionsCol);
headerRow.appendChild(categoryCol);
headerRow.appendChild(tagsCol);
headerRow.appendChild(usedinCol);
thead.appendChild(headerRow);
table.appendChild(thead);
const tbody = document.createElement('tbody');
table.appendChild(tbody);
return table;
}
function toCSV(arr) {
if (!arr.length) return "";
const headers = Object.keys(arr[0]);
const esc = v => {
if (v === null || v === undefined) return "";
const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
return /[",\n]/.test(s) ? `"${s.replace(/"/g,'""')}"` : s;
};
return [headers.join(',')].concat(arr.map(o => headers.map(h => esc(o[h])).join(','))).join('\n');
}
function download(filename, content, mime) {
const blob = new Blob([content], {type: mime});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
}
function summarizeRow(q, idx, tbody){
const row = document.createElement('tr');
const nameCell = document.createElement('td');
nameCell.textContent = q.name ?? '';
nameCell.className = 'text-truncate';
nameCell.style.maxWidth = '300px';
const actionsCell = document.createElement('td');
actionsCell.className = 'qbrowser-controls';
const questionBtn = document.createElement('button');
questionBtn.className = 'btn btn-outline-secondary';
questionBtn.style.cssText = 'padding: 2px 5px; font-size: 10px; margin-right: 1px; line-height: 1.2;';
questionBtn.textContent = 'Question';
questionBtn.title = 'View Question';
const answerBtn = document.createElement('button');
answerBtn.className = 'btn btn-outline-secondary';
answerBtn.style.cssText = 'padding: 2px 5px; font-size: 10px; margin-right: 1px; line-height: 1.2;';
answerBtn.textContent = 'Answer';
answerBtn.title = 'View Answer';
const previewBtn = document.createElement('button');
previewBtn.className = 'btn btn-outline-secondary';
previewBtn.style.cssText = 'padding: 2px 5px; font-size: 10px; margin-right: 1px; line-height: 1.2;';
previewBtn.textContent = 'Preview';
previewBtn.title = 'Preview Question';
const bankBtn = document.createElement('button');
bankBtn.className = 'btn btn-outline-secondary';
bankBtn.style.cssText = 'padding: 2px 5px; font-size: 10px; margin-right: 1px; line-height: 1.2;';
bankBtn.textContent = 'Bank';
bankBtn.title = 'View in Question Bank';
const jsonBtn = document.createElement('button');
jsonBtn.className = 'btn btn-outline-secondary';
jsonBtn.style.cssText = 'padding: 2px 5px; font-size: 10px; line-height: 1.2;';
jsonBtn.textContent = 'JSON';
jsonBtn.title = 'View JSON';
actionsCell.append(questionBtn, answerBtn, previewBtn, bankBtn, jsonBtn);
const categoryCell = document.createElement('td');
categoryCell.textContent = q.category ?? '';
categoryCell.className = 'text-muted small text-truncate';
categoryCell.style.maxWidth = '200px';
const tagsCell = document.createElement('td');
const tagText = Array.isArray(q.tags) && q.tags.length > 0 ? q.tags.join(', ') : '';
tagsCell.textContent = tagText;
tagsCell.className = 'text-muted small text-truncate';
tagsCell.style.maxWidth = '200px';
tagsCell.title = tagText;
const usedinCell = document.createElement('td');
const usedinArray = Array.isArray(q.usedin) ? q.usedin : [];
usedinCell.className = 'text-muted small';
usedinCell.style.maxWidth = '200px';
// Create one div per quiz name, each with its own truncation
if (usedinArray.length > 0) {
usedinArray.forEach(quizname => {
const quizDiv = document.createElement('div');
quizDiv.textContent = quizname;
quizDiv.className = 'text-truncate';
quizDiv.title = quizname;
usedinCell.appendChild(quizDiv);
});
}
// Tooltip shows full list
const usedinText = usedinArray.join('\n');
usedinCell.title = usedinText;
row.appendChild(nameCell);
row.appendChild(actionsCell);
row.appendChild(categoryCell);
row.appendChild(tagsCell);
row.appendChild(usedinCell);
let openType = null;
let detailRow = null;
function closeDetails() {
openType = null;
questionBtn.textContent = 'Question';
answerBtn.textContent = 'Answer';
jsonBtn.textContent = 'JSON';
questionBtn.classList.remove('qbrowser-btn-active');
answerBtn.classList.remove('qbrowser-btn-active');
jsonBtn.classList.remove('qbrowser-btn-active');
if (detailRow) {
detailRow.remove();
detailRow = null;
}
if (currentlyOpenDetails === closeDetails) {
currentlyOpenDetails = null;
}
}
function toggleDisplay(type, content, isHTML = false) {
if (openType === type) {
closeDetails();
} else {
if (currentlyOpenDetails && currentlyOpenDetails !== closeDetails) {
currentlyOpenDetails();
}
if (detailRow) {
detailRow.remove();
}
openType = type;
questionBtn.textContent = type === 'question' ? 'Close' : 'Question';
answerBtn.textContent = type === 'answer' ? 'Close' : 'Answer';
jsonBtn.textContent = type === 'json' ? 'Close' : 'JSON';
questionBtn.classList.remove('qbrowser-btn-active');
answerBtn.classList.remove('qbrowser-btn-active');
jsonBtn.classList.remove('qbrowser-btn-active');
if (type === 'question') questionBtn.classList.add('qbrowser-btn-active');
else if (type === 'answer') answerBtn.classList.add('qbrowser-btn-active');
else if (type === 'json') jsonBtn.classList.add('qbrowser-btn-active');
detailRow = document.createElement('tr');
const detailCell = document.createElement('td');
detailCell.colSpan = 5;
const detail = document.createElement('div');
detail.className = isHTML ? 'qbrowser-detail html-content' : 'qbrowser-detail code-content';
if (isHTML) detail.innerHTML = content;
else detail.textContent = content;
detailCell.appendChild(detail);
detailRow.appendChild(detailCell);
row.insertAdjacentElement('afterend', detailRow);
currentlyOpenDetails = closeDetails;
}
}
jsonBtn.addEventListener('click', () => toggleDisplay('json', JSON.stringify(q, null, 2)));
questionBtn.addEventListener('click', () => toggleDisplay('question', q.questiontext || 'No question text available', true));
answerBtn.addEventListener('click', () => toggleDisplay('answer', q.answer || 'No answer available'));
previewBtn.addEventListener('click', () => {
if (q.id) {
const previewUrl = `${moodleBaseUrl}/question/bank/previewquestion/preview.php?id=${q.id}`;
window.open(previewUrl, '_blank');
} else {
alert('No question ID available for preview');
}
});
bankBtn.addEventListener('click', () => {
if (q.qbankparams) {
const params = new URLSearchParams(q.qbankparams);
const bankUrl = `${moodleBaseUrl}/question/edit.php?${params.toString()}`;
window.open(bankUrl, '_blank');
} else {
alert('Missing question bank parameters');
}
});
return row;
}
function sortBy(field) {
if (currentSort.field === field) {
currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
} else {
currentSort.field = field;
currentSort.direction = 'asc';
}
viewData.sort((a, b) => {
let aVal, bVal;
if (field === 'tags' || field === 'usedin') {
aVal = (Array.isArray(a[field]) ? a[field].join(', ') : '').toLowerCase();
bVal = (Array.isArray(b[field]) ? b[field].join(', ') : '').toLowerCase();
} else {
aVal = (a[field] || '').toString().toLowerCase();
bVal = (b[field] || '').toString().toLowerCase();
}
if (currentSort.direction === 'asc') {
return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
} else {
return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
}
});
renderList(viewData);
updateHeaderSortIndicators();
}
function updateHeaderSortIndicators() {
const sortName = document.getElementById('sortName');
const sortCategory = document.getElementById('sortCategory');
const sortTags = document.getElementById('sortTags');
const sortUsedIn = document.getElementById('sortUsedIn');
[sortName, sortCategory, sortTags, sortUsedIn].forEach(header => {
if (!header) return;
let field;
if (header.id === 'sortName') field = 'name';
else if (header.id === 'sortCategory') field = 'category';
else if (header.id === 'sortTags') field = 'tags';
else if (header.id === 'sortUsedIn') field = 'usedin';