-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodesh.php
More file actions
1367 lines (1174 loc) · 46.3 KB
/
codesh.php
File metadata and controls
1367 lines (1174 loc) · 46.3 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
namespace Grav\Plugin;
use Composer\Autoload\ClassLoader;
use Grav\Common\Plugin;
use Grav\Common\Utils;
use Grav\Plugin\Codesh\GrammarManager;
use Grav\Plugin\Codesh\PrismDefenseTransformer;
use Grav\Plugin\Codesh\ThemeManager;
use Phiki\Phiki;
use Phiki\Transformers\Decorations\PreDecoration;
use RocketTheme\Toolbox\Event\Event;
use Symfony\Component\HttpFoundation\Response;
class CodeshPlugin extends Plugin
{
protected ?Phiki $phiki = null;
protected ?ThemeManager $themeManager = null;
protected ?GrammarManager $grammarManager = null;
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
'onPluginsInitialized' => [
['autoload', 100001],
['onPluginsInitialized', 0]
],
// Editor Pro integration events
'registerEditorProPlugin' => [
['registerEditorProPlugin', 0],
],
'onEditorProShortcodeRegister' => [
['onEditorProShortcodeRegister', 0],
]
];
}
/**
* Composer autoload
*
* @return ClassLoader
*/
public function autoload(): ClassLoader
{
return require __DIR__ . '/vendor/autoload.php';
}
/**
* Initialize the plugin
*/
public function onPluginsInitialized(): void
{
if ($this->isAdmin()) {
$this->enable([
'onAdminTwigTemplatePaths' => ['onAdminTwigTemplatePaths', 1000], // High priority to run early
'onTwigLoader' => ['onTwigLoader', 0], // Add paths directly to Twig loader
'onAssetsInitialized' => ['onAssetsInitialized', 0],
// High priority to intercept AJAX requests before admin routing
'onPagesInitialized' => ['onAdminPagesInitialized', 100000],
]);
return;
}
$this->enable([
'onShortcodeHandlers' => ['onShortcodeHandlers', 0],
'onTwigInitialized' => ['onTwigInitialized', 0],
'onTwigSiteVariables' => ['onTwigSiteVariables', 0],
'onOutputGenerated' => ['onOutputGenerated', 0],
]);
}
/**
* Get Theme Manager instance
*/
public function getThemeManager(): ThemeManager
{
if ($this->themeManager === null) {
$this->themeManager = new ThemeManager($this->grav);
}
return $this->themeManager;
}
/**
* Get Grammar Manager instance
*/
public function getGrammarManager(): GrammarManager
{
if ($this->grammarManager === null) {
$this->grammarManager = new GrammarManager($this->grav);
}
return $this->grammarManager;
}
/**
* Add admin template paths for custom form field types
*/
public function onAdminTwigTemplatePaths(Event $e): void
{
if (!$this->isAdmin()) {
return;
}
$currentPaths = $e['paths'];
array_unshift($currentPaths, __DIR__ . '/templates');
$e['paths'] = $currentPaths;
}
/**
* Add paths directly to Twig loader for custom form field templates
*/
public function onTwigLoader(): void
{
if (!$this->isAdmin()) {
return;
}
/** @var \Grav\Common\Twig\Twig $twig */
$twig = $this->grav['twig'];
// Prepend paths for form field templates
$twig->prependPath(__DIR__ . '/templates');
}
/**
* Register assets for custom field types (theme picker, grammar list)
*/
public function onAssetsInitialized(): void
{
$assets = $this->grav['assets'];
// Theme picker field
$assets->addCss('plugin://codesh/admin/css/codeshtheme-field.css', ['priority' => 10]);
$assets->addJs('plugin://codesh/admin/js/codeshtheme-field.js', [
'group' => 'bottom',
'loading' => 'defer',
'priority' => 120
]);
// Grammar list field
$assets->addCss('plugin://codesh/admin/css/codeshgrammarlist-field.css', ['priority' => 10]);
$assets->addJs('plugin://codesh/admin/js/codeshgrammarlist-field.js', [
'group' => 'bottom',
'loading' => 'defer',
'priority' => 120
]);
}
/**
* Handle admin routes for theme editor and grammar API
*/
public function onAdminPagesInitialized(): void
{
// For AJAX requests, check URI path directly and handle early
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
$uri = $this->grav['uri'];
$path = $uri->path();
if (strpos($path, 'codesh-themes') !== false) {
// Clean output buffers and handle AJAX
while (ob_get_level()) {
ob_end_clean();
}
// Check if this is a grammar request (under codesh-themes/grammars/*)
if (strpos($path, 'codesh-themes/grammars') !== false) {
$this->handleGrammarApiRoutes();
} else {
$this->handleThemeEditorRoutes();
}
exit;
}
}
}
/**
* Handle theme API routes (AJAX only)
*/
protected function handleThemeEditorRoutes(): void
{
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
// Parse action from URI
$uri = $this->grav['uri'];
$path = $uri->path();
$action = 'list';
$param = null;
// Extract action from path like /grav-helios/admin/codesh-themes/list
if (preg_match('/codesh-themes\/([^\/\?]+)(?:\/([^\/\?]+))?/', $path, $matches)) {
$action = $matches[1] ?? 'list';
$param = $matches[2] ?? null;
}
if ($method === 'GET' && $action === 'list') {
$this->handleAjaxList();
} elseif ($method === 'POST') {
$this->handleAjaxRequest($action);
} elseif ($method === 'DELETE') {
$this->handleAjaxDelete($param ?? $action);
}
}
/**
* Handle AJAX requests
*/
protected function handleAjaxRequest(string $action): void
{
// Clean any output buffers
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
// Validate nonce
$nonce = $_POST['admin-nonce'] ?? $_SERVER['HTTP_X_ADMIN_NONCE'] ?? '';
if (!Utils::verifyNonce($nonce, 'admin-form')) {
echo json_encode(['error' => 'Invalid security token']);
return;
}
$themeManager = $this->getThemeManager();
switch ($action) {
case 'preview':
$this->handlePreview($themeManager);
break;
case 'save':
$this->handleSave($themeManager);
break;
case 'copy':
$this->handleCopy($themeManager);
break;
case 'import':
$this->handleImport($themeManager);
break;
case 'list':
$this->handleList($themeManager);
break;
default:
echo json_encode(['error' => 'Unknown action']);
}
}
/**
* Handle preview generation
*/
protected function handlePreview(ThemeManager $themeManager): void
{
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['colors'])) {
echo json_encode(['error' => 'Invalid request']);
return;
}
$colors = $input['colors'];
$language = $input['language'] ?? 'php';
$variant = $input['variant'] ?? 'dark';
// Validate colors
foreach ($colors as $key => $value) {
if (!preg_match('/^#[0-9A-Fa-f]{6}$/i', $value)) {
echo json_encode(['error' => 'Invalid color format: ' . $key]);
return;
}
}
// Generate theme from colors
$theme = $themeManager->generateFromCoreColors($colors, $variant);
// Generate preview
$html = $themeManager->generatePreviewFromData($theme, $language);
echo json_encode(['html' => $html]);
}
/**
* Handle theme save
*/
protected function handleSave(ThemeManager $themeManager): void
{
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['name']) || !isset($input['colors'])) {
echo json_encode(['error' => 'Invalid request']);
return;
}
$name = $input['name'];
$colors = $input['colors'];
$variant = $input['variant'] ?? 'dark';
$displayName = $input['displayName'] ?? null;
// Validate name
if (!preg_match('/^[a-z0-9-_]+$/i', $name)) {
echo json_encode(['error' => 'Invalid theme name']);
return;
}
try {
// Generate full theme from colors
$theme = $themeManager->generateFromCoreColors($colors, $variant);
// Set name and display name
$theme['name'] = $name;
if ($displayName) {
$theme['displayName'] = $displayName;
}
// Save theme
$success = $themeManager->saveTheme($name, $theme);
echo json_encode([
'success' => $success,
'message' => $success ? 'Theme saved successfully' : 'Failed to save theme'
]);
} catch (\Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
}
/**
* Handle theme copy
*/
protected function handleCopy(ThemeManager $themeManager): void
{
$input = json_decode(file_get_contents('php://input'), true);
$source = $input['source'] ?? '';
$newName = $input['name'] ?? '';
if (empty($source) || empty($newName)) {
echo json_encode(['error' => 'Source and new name are required']);
return;
}
try {
$success = $themeManager->copyTheme($source, $newName);
$admin = $this->grav['admin'];
echo json_encode([
'success' => $success,
'message' => $success ? 'Theme copied successfully' : 'Failed to copy theme',
'redirect' => $admin->adminUrl('codesh-themes?theme=' . $newName)
]);
} catch (\Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
}
/**
* Handle theme import
*/
protected function handleImport(ThemeManager $themeManager): void
{
if (!isset($_FILES['theme_file']) || $_FILES['theme_file']['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['error' => 'No file uploaded or upload error']);
return;
}
$file = $_FILES['theme_file'];
// Validate file type
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($extension !== 'json') {
echo json_encode(['error' => 'Only JSON files are allowed']);
return;
}
// Validate file size (max 1MB)
if ($file['size'] > 1048576) {
echo json_encode(['error' => 'File too large (max 1MB)']);
return;
}
try {
$themeName = $themeManager->importTheme($file['tmp_name']);
$admin = $this->grav['admin'];
echo json_encode([
'success' => true,
'message' => 'Theme imported successfully',
'theme' => $themeName,
'redirect' => $admin->adminUrl('codesh-themes?theme=' . $themeName)
]);
} catch (\Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
}
/**
* Handle theme list (POST AJAX)
*/
protected function handleList(ThemeManager $themeManager): void
{
echo json_encode([
'builtin' => $themeManager->listBuiltinThemes(),
'custom' => $themeManager->listCustomThemes()
]);
}
/**
* Handle AJAX GET request for theme list
*/
protected function handleAjaxList(): void
{
// Clean any output buffers
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
// Note: No nonce validation for read-only list endpoint
$themeManager = $this->getThemeManager();
echo json_encode([
'builtin' => $themeManager->listBuiltinThemes(),
'custom' => $themeManager->listCustomThemes()
]);
}
/**
* Handle AJAX DELETE request for theme deletion
*/
protected function handleAjaxDelete(string $name): void
{
// Clean any output buffers
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
// Validate nonce from header
$nonce = $_SERVER['HTTP_X_GRAV_NONCE'] ?? '';
if (!Utils::verifyNonce($nonce, 'admin-form')) {
http_response_code(403);
echo json_encode(['error' => 'Invalid security token']);
return;
}
if (empty($name)) {
http_response_code(400);
echo json_encode(['error' => 'Theme name is required']);
return;
}
$themeManager = $this->getThemeManager();
// Only allow deleting custom themes
if (!$themeManager->customThemeExists($name)) {
http_response_code(400);
echo json_encode(['error' => 'Can only delete custom themes']);
return;
}
$success = $themeManager->deleteTheme($name);
if ($success) {
echo json_encode([
'success' => true,
'message' => 'Theme deleted successfully'
]);
} else {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Failed to delete theme'
]);
}
}
/**
* Handle grammar API routes (AJAX only)
*/
protected function handleGrammarApiRoutes(): void
{
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
// Parse action from URI
$uri = $this->grav['uri'];
$path = $uri->path();
$action = 'list';
$param = null;
// Extract action from path like /grav-helios/admin/codesh-themes/grammars/list
if (preg_match('/codesh-themes\/grammars\/([^\/\?]+)(?:\/([^\/\?]+))?/', $path, $matches)) {
$action = $matches[1] ?? 'list';
$param = $matches[2] ?? null;
}
// Handle AJAX requests (GET, POST, or DELETE)
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
if ($method === 'GET' && $action === 'list') {
$this->handleGrammarList();
exit;
}
if ($method === 'POST' && $action === 'import') {
$this->handleGrammarImport();
exit;
}
if ($method === 'DELETE') {
$this->handleGrammarDelete($param ?? $action);
exit;
}
}
}
/**
* Handle AJAX GET request for grammar list
*/
protected function handleGrammarList(): void
{
// Clean any output buffers
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
// Note: No nonce validation for read-only list endpoint
$grammarManager = $this->getGrammarManager();
echo json_encode([
'custom' => $grammarManager->listCustomGrammars(),
'builtin' => $grammarManager->listBuiltinGrammars()
]);
}
/**
* Handle AJAX GET request for single grammar
*/
protected function handleGrammarGet(string $slug): void
{
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
$grammarManager = $this->getGrammarManager();
$grammar = $grammarManager->getGrammar($slug);
if ($grammar) {
echo json_encode(['success' => true, 'grammar' => $grammar]);
} else {
http_response_code(404);
echo json_encode(['error' => 'Grammar not found']);
}
}
/**
* Handle AJAX POST request for grammar import
*/
protected function handleGrammarImport(): void
{
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
// Validate nonce
$nonce = $_SERVER['HTTP_X_GRAV_NONCE'] ?? '';
if (!Utils::verifyNonce($nonce, 'admin-form')) {
http_response_code(403);
echo json_encode(['error' => 'Invalid security token']);
return;
}
if (!isset($_FILES['grammar_file']) || $_FILES['grammar_file']['error'] !== UPLOAD_ERR_OK) {
http_response_code(400);
echo json_encode(['error' => 'No file uploaded or upload error']);
return;
}
$file = $_FILES['grammar_file'];
// Validate file type
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($extension !== 'json') {
http_response_code(400);
echo json_encode(['error' => 'Only JSON files are allowed']);
return;
}
// Validate file size (max 1MB)
if ($file['size'] > 1048576) {
http_response_code(400);
echo json_encode(['error' => 'File too large (max 1MB)']);
return;
}
try {
$grammarManager = $this->getGrammarManager();
$slug = $grammarManager->importGrammar($file);
echo json_encode([
'success' => true,
'message' => 'Grammar imported successfully',
'slug' => $slug
]);
} catch (\Exception $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
}
}
/**
* Handle AJAX DELETE request for grammar deletion
*/
protected function handleGrammarDelete(string $slug): void
{
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
// Validate nonce
$nonce = $_SERVER['HTTP_X_GRAV_NONCE'] ?? '';
if (!Utils::verifyNonce($nonce, 'admin-form')) {
http_response_code(403);
echo json_encode(['error' => 'Invalid security token']);
return;
}
if (empty($slug)) {
http_response_code(400);
echo json_encode(['error' => 'Grammar slug is required']);
return;
}
$grammarManager = $this->getGrammarManager();
// Only allow deleting custom grammars
if (!$grammarManager->customGrammarExists($slug)) {
http_response_code(400);
echo json_encode(['error' => 'Can only delete custom grammars']);
return;
}
$success = $grammarManager->deleteGrammar($slug);
if ($success) {
echo json_encode([
'success' => true,
'message' => 'Grammar deleted successfully'
]);
} else {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Failed to delete grammar'
]);
}
}
/**
* Register shortcode handlers
*/
public function onShortcodeHandlers(Event $e): void
{
$this->grav['shortcode']->registerAllShortcodes(__DIR__ . '/classes/shortcodes');
}
/**
* Register Editor Pro plugin assets
*/
public function registerEditorProPlugin(Event $event): Event
{
$plugins = $event['plugins'];
// Add Codesh Editor Pro integration CSS
$plugins['css'][] = 'plugin://codesh/editor-pro/codesh-integration.css';
$event['plugins'] = $plugins;
return $event;
}
/**
* Register Codesh shortcodes for Editor Pro
*/
public function onEditorProShortcodeRegister(Event $event): Event
{
$shortcodes = $event['shortcodes'];
// Codesh shortcodes
$codeshShortcodes = [
// Codesh - syntax highlighted code block
[
'name' => 'codesh',
'title' => 'Codesh',
'description' => 'Server-side syntax highlighted code block with 200+ languages',
'type' => 'block',
'plugin' => 'codesh',
'category' => 'code',
'group' => 'Codesh',
'icon' => '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>',
'bbcodeAttribute' => 'lang', // BBCode value [codesh=xxx] maps to this attribute
'attributes' => [
'lang' => [
'type' => 'text',
'title' => 'Language',
'default' => 'javascript',
'required' => true,
'placeholder' => 'e.g., javascript, php, python'
],
'title' => [
'type' => 'text',
'title' => 'Title/Filename',
'default' => '',
'placeholder' => 'e.g., example.js'
],
'line-numbers' => [
'type' => 'checkbox',
'title' => 'Show Line Numbers',
'default' => false
],
'start' => [
'type' => 'number',
'title' => 'Starting Line',
'placeholder' => '1',
'min' => 1
],
'highlight' => [
'type' => 'text',
'title' => 'Highlight Lines',
'default' => '',
'placeholder' => 'e.g., 1,3-5,8'
],
'focus' => [
'type' => 'text',
'title' => 'Focus Lines',
'default' => '',
'placeholder' => 'e.g., 2-4'
],
'theme' => [
'type' => 'text',
'title' => 'Theme Override',
'default' => '',
'placeholder' => 'e.g., dracula, nord'
],
'hide-header' => [
'type' => 'checkbox',
'title' => 'Hide Header',
'default' => false
],
'hide-lang' => [
'type' => 'checkbox',
'title' => 'Hide Language',
'default' => false
],
'diff' => [
'type' => 'checkbox',
'title' => 'Diff Mode',
'default' => false
],
'wrap' => [
'type' => 'select',
'title' => 'Line Wrapping',
'default' => '',
'options' => [
'' => 'Use Global Setting',
'true' => 'Enabled',
'false' => 'Disabled'
]
]
],
'titleBarAttributes' => ['title', 'lang', 'theme', 'highlight', 'focus', 'line-numbers', 'diff', 'hide-header', 'hide-lang', 'wrap'],
'hasContent' => true,
'contentType' => 'code', // Treat content as raw code (uses CodeMirror editor)
'language' => 'javascript', // Default language for CodeMirror
'defaultContent' => 'console.log("Hello, World!");'
],
// Codesh Group - tabbed code blocks
[
'name' => 'codesh-group',
'title' => 'Codesh Group',
'description' => 'Tabbed interface for multiple code examples with optional sync',
'type' => 'block',
'plugin' => 'codesh',
'category' => 'code',
'group' => 'Codesh',
'icon' => '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="3" y1="9" x2="21" y2="9"></line><line x1="9" y1="21" x2="9" y2="9"></line></svg>',
'attributes' => [
'sync' => [
'type' => 'text',
'title' => 'Sync Key',
'default' => '',
'placeholder' => 'e.g., lang (syncs tabs across groups)'
]
],
'titleBarAttributes' => ['sync'],
'hasContent' => true,
'allowedChildren' => ['codesh'], // Nested codesh blocks allowed
'defaultContent' => '[codesh lang="javascript" title="JavaScript"]\nconsole.log("Hello!");\n[/codesh]\n[codesh lang="python" title="Python"]\nprint("Hello!")\n[/codesh]'
]
];
// Add all Codesh shortcodes to the registry
foreach ($codeshShortcodes as $shortcode) {
$shortcodes[] = $shortcode;
}
$event['shortcodes'] = $shortcodes;
return $event;
}
/**
* Add Twig filter (must be done before Twig extensions are frozen)
*/
public function onTwigInitialized(): void
{
$twig = $this->grav['twig']->twig();
$twig->addFilter(new \Twig\TwigFilter('codesh', [$this, 'codeshFilter'], ['is_safe' => ['html']]));
}
/**
* Add CSS and JS assets
*/
public function onTwigSiteVariables(): void
{
$this->grav['assets']->addCss('plugin://codesh/css/codesh.css');
$this->grav['assets']->addJs('plugin://codesh/js/codesh.js', ['group' => 'bottom', 'defer' => true]);
}
/**
* Twig filter to highlight code using codesh
*
* Usage in templates:
* {{ code_string|codesh('json') }}
* {{ code_string|codesh('php', {title: 'example.php', 'line-numbers': true}) }}
*
* @param string $content The code to highlight
* @param string $lang The language (default: 'txt')
* @param array $options Options: theme, line-numbers, start, highlight, focus, class, hide-lang, title, hide-header
* @return string The highlighted HTML
*/
public function codeshFilter(string $content, string $lang = 'txt', array $options = []): string
{
$mergedOptions = array_merge([
'theme' => $options['theme'] ?? null,
'line-numbers' => $options['line-numbers'] ?? false,
'start' => $options['start'] ?? 1,
'highlight' => $options['highlight'] ?? '',
'focus' => $options['focus'] ?? '',
'class' => $options['class'] ?? '',
'hide-lang' => $options['hide-lang'] ?? false,
'title' => $options['title'] ?? '',
'hide-header' => $options['hide-header'] ?? false,
], $options);
// Generate cache key based on content, language, options, and theme
$themeConfig = $this->config->get('themes.helios.appearance.theme', 'system');
$cacheKey = 'codesh_' . md5($content . $lang . serialize($mergedOptions) . $themeConfig);
// Try to get from cache
$cache = $this->grav['cache'];
$cached = $cache->fetch($cacheKey);
if ($cached !== false) {
return $cached;
}
// Generate highlighted code
$result = $this->highlightCodeFull($content, $lang, $mergedOptions);
// Cache the result (1 hour TTL)
$cache->save($cacheKey, $result, 3600);
return $result;
}
/**
* Highlight code using Phiki (shared implementation for filter and page processing)
*/
protected function highlightCodeFull(string $code, string $lang, array $options): string
{
$config = $this->config->get('plugins.codesh');
// Detect theme mode from Helios theme config
$themeConfig = $this->config->get('themes.helios.appearance.theme', 'system');
// Use custom helios themes by default (with diff backgrounds)
$themeDark = $config['theme_dark'] ?? 'helios-dark';
$themeLight = $config['theme_light'] ?? 'helios-light';
// Get theme - explicit theme parameter overrides mode-based themes
$explicitTheme = $options['theme'] ?? null;
if ($explicitTheme) {
$theme = $explicitTheme;
} elseif ($themeConfig === 'system') {
$theme = [
'light' => $themeLight,
'dark' => $themeDark,
];
} else {
$theme = ($themeConfig === 'dark') ? $themeDark : $themeLight;
}
$lineNumbers = $this->toBool($options['line-numbers'] ?? $config['show_line_numbers'] ?? false);
$startLine = (int) ($options['start'] ?? 1);
$highlight = $options['highlight'] ?? '';
$focus = $options['focus'] ?? '';
$class = $options['class'] ?? '';
$showLang = !$this->toBool($options['hide-lang'] ?? false);
$title = $options['title'] ?? '';
$showHeader = !$this->toBool($options['hide-header'] ?? false);
// Clean up the content
$code = html_entity_decode($code, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$code = trim($code, "\n\r");
$code = $this->dedent($code);
if (empty(trim($code))) {
return '';
}
try {
$phiki = $this->getPhiki();
$output = $phiki->codeToHtml($code, strtolower($lang), $theme);
// Rename language-* classes to lang-* to prevent Prism.js re-highlighting
$output = $output->transformer(new PrismDefenseTransformer());
// Add 'no-highlight' class as additional defense
$output = $output->decoration(
PreDecoration::make()->class('no-highlight')
);
// Add line numbers if enabled
if ($lineNumbers) {
$output = $output->withGutter();
if ($startLine !== 1) {
$output = $output->startingLine($startLine);
}
}
// Add line decorations for highlighting
if (!empty($highlight)) {
$highlightLines = $this->parseLineSpec($highlight);
foreach ($highlightLines as $line) {
$output = $output->decoration(
\Phiki\Transformers\Decorations\LineDecoration::forLine($line - 1)->class('highlight')
);
}
}
// Add line decorations for focus
if (!empty($focus)) {
$focusLines = $this->parseLineSpec($focus);
foreach ($focusLines as $line) {
$output = $output->decoration(
\Phiki\Transformers\Decorations\LineDecoration::forLine($line - 1)->class('focus')
);
}
}
$html = $output->toString();
// Wrap in container with optional class
$classes = ['codesh-block'];
if (is_array($theme)) {
$classes[] = 'codesh-dual-theme';
}
if (!empty($class)) {
$classes[] = htmlspecialchars($class);
}
if (!empty($highlight)) {
$classes[] = 'has-highlights';
}
if (!empty($focus)) {
$classes[] = 'has-focus';
}
if (!$showHeader) {
$classes[] = 'no-header';
}
// Handle wrap option - shortcode can override global setting
$wrapOption = $options['wrap'] ?? null;