-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsray.php
More file actions
1609 lines (1416 loc) · 47.2 KB
/
Copy pathjsray.php
File metadata and controls
1609 lines (1416 loc) · 47.2 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
/**
* Plugin Name: JSRay
* Plugin URI: https://jsray.org
* Description: JSRay Core rendering for WordPress code blocks.
* Version: 0.0.2-beta
* Author: Jie
* Author URI: https://jsray.org
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: jsray
* Domain Path: /languages
* Requires at least: 6.0
* Requires PHP: 7.4
*
* @package JSRay
*
* JSRay for WordPress
* Copyright (C) 2026 JSRay
*
* 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 2 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 <https://www.gnu.org/licenses/gpl-2.0.html>.
*
* Bundled JSRay Core stays MIT — see LICENSE-THIRD-PARTY.
*/
if (! defined('ABSPATH')) {
exit;
}
define('JSRAY_WP_VERSION', '0.0.2-beta');
define('JSRAY_WP_FILE', __FILE__);
define('JSRAY_WP_DIR', plugin_dir_path(__FILE__));
define('JSRAY_WP_URL', plugin_dir_url(__FILE__));
/*
* Translations load themselves.
*
* `load_plugin_textdomain()` used to be required and has been discouraged since
* WordPress 4.6: for a plugin on WordPress.org the translations arrive from
* translate.wordpress.org without it, and since the just-in-time loader landed,
* a `.mo` sitting in the plugin's own languages/ directory is picked up too. The
* minimum supported version here is 6.0, so both paths are always available and
* the call had nothing left to do — it loaded no file, because only a .pot ships
* today. Plugin Check flags it, and a call that does nothing is not worth a
* review round.
*
* Text Domain and Domain Path stay in the plugin header, which is what both
* loaders actually read.
*/
/**
* Return plugin defaults.
*
* @return array<string, string>
*/
function jsray_wp_default_options() {
return array(
'theme' => 'dark',
'palette' => 'default',
'custom_palette' => '',
'fallback_language' => '',
'enqueue_assets' => '1',
'scan_all_code' => '1',
);
}
/**
* Palettes bundled with the plugin.
*
* Each key maps to assets/css/themes/<key>.css, synced from Core. Every
* palette carries its own dark and light variant, so this is independent of
* the theme-mode setting.
*
* @return array<string, string>
*/
function jsray_wp_palettes() {
$palettes = array(
'default' => __('Default — the signature JSRay palette', 'jsray'),
'aurora' => __('Aurora — polar night, glacial blue with mint and violet', 'jsray'),
'ember' => __('Ember — warm forge, flame keywords with patina mint', 'jsray'),
'fjord' => __('Fjord — Nordic low-chroma, calm for long reading', 'jsray'),
);
/**
* Filter the palettes offered by the JSRay WordPress integration.
*
* A renderer adapter that ships its own stylesheets can add entries here;
* register a style handle named `jsray-theme-<key>` to go with each one.
*
* @param array<string, string> $palettes Palette key to label map.
*/
return apply_filters('jsray_wp_palettes', $palettes);
}
/**
* Read a bundled JSON data file shipped with the plugin.
*
* @param string $relative_path Path relative to plugin root.
* @return array<string, mixed>
*/
function jsray_wp_read_json($relative_path) {
$path = JSRAY_WP_DIR . ltrim($relative_path, '/');
if (! file_exists($path)) {
return array();
}
$decoded = json_decode((string) file_get_contents($path), true); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
return is_array($decoded) ? $decoded : array();
}
/**
* Verify the bundled JSRay Core snapshot against its official digests.
*
* The plugin ships a copy of Core rather than depending on it, so the file that
* renders a visitor's code lives on disk where a host, a theme, or an attacker
* can replace it. This hashes each bundled asset and compares it to the digest
* Core published for that release.
*
* Result is cached against the manifest's own modification time, so the hashing
* happens once per release rather than once per page load.
*
* @param bool $force Skip the cache.
* @return array{status: string, version: string, mismatched: string[], checked: int}
*/
function jsray_wp_core_integrity($force = false) {
$manifest_path = JSRAY_WP_DIR . 'core-integrity.json';
$cache_key = 'jsray_wp_core_integrity';
if (! $force) {
$cached = get_transient($cache_key);
if (is_array($cached) && isset($cached['fingerprint'])
&& $cached['fingerprint'] === (file_exists($manifest_path) ? (string) filemtime($manifest_path) : '')) {
return $cached['result'];
}
}
$manifest = jsray_wp_read_json('core-integrity.json');
$result = array(
'status' => 'unknown',
'version' => isset($manifest['version']) ? (string) $manifest['version'] : '',
'mismatched' => array(),
'checked' => 0,
);
if (empty($manifest['files']) || ! is_array($manifest['files'])) {
return $result;
}
foreach ($manifest['files'] as $relative => $expected) {
$path = JSRAY_WP_DIR . ltrim((string) $relative, '/');
if (! file_exists($path)) {
$result['mismatched'][] = (string) $relative;
continue;
}
$actual = 'sha256-' . base64_encode((string) hash_file('sha256', $path, true));
$result['checked']++;
// hash_equals keeps the comparison constant-time; these are public
// digests, but there is no reason to leak timing on a security check.
if (! hash_equals((string) $expected, $actual)) {
$result['mismatched'][] = (string) $relative;
}
}
$result['status'] = empty($result['mismatched']) ? 'official' : 'modified';
set_transient(
$cache_key,
array(
'fingerprint' => file_exists($manifest_path) ? (string) filemtime($manifest_path) : '',
'result' => $result,
),
DAY_IN_SECONDS
);
return $result;
}
/**
* Warn in the admin when the bundled Core no longer matches its official build.
*
* @return void
*/
function jsray_wp_core_integrity_notice() {
if (! current_user_can('manage_options')) {
return;
}
$integrity = jsray_wp_core_integrity();
if ('modified' !== $integrity['status']) {
return;
}
?>
<div class="notice notice-error">
<p>
<strong><?php esc_html_e('JSRay: the bundled rendering core has been modified.', 'jsray'); ?></strong>
</p>
<p>
<?php
echo esc_html(
sprintf(
/* translators: %s: comma-separated list of file paths. */
__('These files no longer match the official JSRay Core %1$s build: %2$s', 'jsray'),
$integrity['version'],
implode(', ', $integrity['mismatched'])
)
);
?>
</p>
<p>
<?php esc_html_e('Reinstall the plugin to restore the official core. If you replaced the renderer on purpose, use the renderer adapter hooks instead — they let you swap the engine without editing bundled files.', 'jsray'); ?>
</p>
</div>
<?php
}
add_action('admin_notices', 'jsray_wp_core_integrity_notice');
/**
* The JSRay token vocabulary bundled with this Core snapshot.
*
* Maps a palette key (`function.declaration`) to its CSS variable and runtime
* class suffix (`fn-decl`). Custom palettes are validated against this, so the
* accepted vocabulary always describes the Core actually shipping here.
*
* @return array{tokens: array<string, string>, surfaces: array<string, string>}
*/
function jsray_wp_vocabulary() {
static $vocabulary = null;
if (null === $vocabulary) {
$data = jsray_wp_read_json('vocabulary.json');
$vocabulary = array(
'tokens' => isset($data['tokens']) && is_array($data['tokens']) ? $data['tokens'] : array(),
'surfaces' => isset($data['surfaces']) && is_array($data['surfaces']) ? $data['surfaces'] : array(),
);
}
return $vocabulary;
}
/**
* Resolve the active palette key, falling back to the default when a stored
* value no longer exists (for example after a filter stops offering it).
*
* @return string
*/
function jsray_wp_active_palette() {
$options = jsray_wp_get_options();
$palettes = jsray_wp_palettes();
$palette = isset($options['palette']) ? (string) $options['palette'] : 'default';
return isset($palettes[$palette]) ? $palette : 'default';
}
/**
* Read merged plugin options.
*
* @return array<string, string>
*/
function jsray_wp_get_options() {
$options = get_option('jsray_wp_options', array());
if (! is_array($options)) {
$options = array();
}
return wp_parse_args($options, jsray_wp_default_options());
}
/**
* Sanitize a JSRay language identifier.
*
* @param string $language Raw language identifier.
* @return string
*/
function jsray_wp_sanitize_language($language) {
$language = strtolower((string) $language);
$language = preg_replace('/[^a-z0-9_-]/', '', $language);
return is_string($language) ? $language : '';
}
/**
* Supported language labels exposed to the block editor.
*
* @return array<string, string>
*/
function jsray_wp_supported_languages() {
$languages = array(
'js' => __('JavaScript', 'jsray'),
'ts' => __('TypeScript', 'jsray'),
'jsx' => __('JSX', 'jsray'),
'tsx' => __('TSX', 'jsray'),
'python' => __('Python', 'jsray'),
'php' => __('PHP', 'jsray'),
'go' => __('Go', 'jsray'),
'swift' => __('Swift', 'jsray'),
'kotlin' => __('Kotlin', 'jsray'),
'dart' => __('Dart', 'jsray'),
'lua' => __('Lua', 'jsray'),
'java' => __('Java', 'jsray'),
'c' => __('C', 'jsray'),
'cpp' => __('C++', 'jsray'),
'csharp' => __('C#', 'jsray'),
'ruby' => __('Ruby', 'jsray'),
'rust' => __('Rust', 'jsray'),
'html' => __('HTML', 'jsray'),
'xml' => __('XML', 'jsray'),
'svg' => __('SVG', 'jsray'),
'vue' => __('Vue', 'jsray'),
'css' => __('CSS', 'jsray'),
'scss' => __('SCSS', 'jsray'),
'sass' => __('Sass', 'jsray'),
'less' => __('Less', 'jsray'),
'json' => __('JSON', 'jsray'),
'jsonc' => __('JSONC', 'jsray'),
'bash' => __('Bash', 'jsray'),
'shell' => __('Shell', 'jsray'),
'zsh' => __('Zsh', 'jsray'),
'markdown' => __('Markdown', 'jsray'),
'sql' => __('SQL', 'jsray'),
'yaml' => __('YAML', 'jsray'),
'scala' => __('Scala', 'jsray'),
'objectivec' => __('Objective-C', 'jsray'),
'r' => __('R', 'jsray'),
'perl' => __('Perl', 'jsray'),
'powershell' => __('PowerShell', 'jsray'),
'elixir' => __('Elixir', 'jsray'),
'haskell' => __('Haskell', 'jsray'),
'graphql' => __('GraphQL', 'jsray'),
'toml' => __('TOML', 'jsray'),
'ini' => __('INI', 'jsray'),
'dockerfile' => __('Dockerfile', 'jsray'),
'makefile' => __('Makefile', 'jsray'),
'diff' => __('Diff', 'jsray'),
);
/**
* Filter language labels exposed by the JSRay WordPress integration.
*
* Renderer adapters can use this to add, remove, or relabel languages
* without replacing the block UI.
*
* @param array<string, string> $languages Language identifier to label map.
*/
return apply_filters('jsray_wp_supported_languages', $languages);
}
/**
* Resolve a human-readable language label.
*
* @param string $language JSRay language identifier.
* @return string
*/
function jsray_wp_language_label($language) {
$languages = jsray_wp_supported_languages();
$language = jsray_wp_sanitize_language($language);
if ('' === $language) {
return __('Auto detect', 'jsray');
}
return isset($languages[$language]) ? $languages[$language] : strtoupper($language);
}
/**
* Validate a CSS color value.
*
* Deliberately narrow: hex, rgb(), rgba(), hsl(), hsla(), and the CSS-wide
* keywords. Anything else — url(), var(), expression(), a stray semicolon —
* is refused, because these values are written straight into a style block.
*
* @param mixed $value Raw color.
* @return string Empty string when the value is not an acceptable color.
*/
function jsray_wp_sanitize_color($value) {
$value = trim((string) $value);
if ('' === $value || strlen($value) > 64) {
return '';
}
if (preg_match('/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $value)) {
return $value;
}
if (preg_match('/^(?:rgb|rgba|hsl|hsla)\(\s*[0-9a-zA-Z.,%\/\s+-]+\s*\)$/', $value)) {
return $value;
}
if (in_array(strtolower($value), array('transparent', 'currentcolor', 'inherit'), true)) {
return $value;
}
return '';
}
/**
* Validate a custom palette against the bundled token vocabulary.
*
* Accepts the palette shape JSRay Core uses everywhere else — the same JSON the
* Theme Studio at jsray.org exports — so a palette authored once works on every
* JSRay surface. Unknown keys and unusable values are dropped rather than
* rejected wholesale, which keeps a palette written for a newer Core usable on
* an older one.
*
* @param mixed $input Raw palette (JSON string or decoded array).
* @return array{themes: array<string, array<string, mixed>>, errors: string[]}
*/
function jsray_wp_validate_palette($input) {
$errors = array();
if (is_string($input)) {
$input = trim($input);
if ('' === $input) {
return array('themes' => array(), 'errors' => array());
}
$decoded = json_decode($input, true);
if (! is_array($decoded)) {
return array(
'themes' => array(),
'errors' => array(__('The palette is not valid JSON.', 'jsray')),
);
}
$input = $decoded;
}
if (! is_array($input)) {
return array('themes' => array(), 'errors' => array(__('The palette is not valid JSON.', 'jsray')));
}
// Accept both a full palette file and a bare { dark: …, light: … } map.
$themes = isset($input['themes']) && is_array($input['themes']) ? $input['themes'] : $input;
$vocabulary = jsray_wp_vocabulary();
$valid = array();
foreach (array('dark', 'light') as $mode) {
if (! isset($themes[$mode]) || ! is_array($themes[$mode])) {
continue;
}
$source = $themes[$mode];
$output = array('tokens' => array());
foreach ($vocabulary['surfaces'] as $key => $suffix) {
if (! isset($source[$key])) {
continue;
}
$color = jsray_wp_sanitize_color($source[$key]);
if ('' === $color) {
/* translators: 1: palette key, 2: theme mode. */
$errors[] = sprintf(__('Ignored an unusable color for "%1$s" in the %2$s theme.', 'jsray'), $key, $mode);
continue;
}
$output[$key] = $color;
unset($suffix);
}
$tokens = isset($source['tokens']) && is_array($source['tokens']) ? $source['tokens'] : array();
foreach ($tokens as $key => $token) {
if (! isset($vocabulary['tokens'][$key])) {
/* translators: %s: palette token key. */
$errors[] = sprintf(__('Ignored "%s" — not a JSRay token in this Core version.', 'jsray'), (string) $key);
continue;
}
$color = jsray_wp_sanitize_color(is_array($token) ? ($token['color'] ?? '') : $token);
if ('' === $color) {
/* translators: 1: palette key, 2: theme mode. */
$errors[] = sprintf(__('Ignored an unusable color for "%1$s" in the %2$s theme.', 'jsray'), (string) $key, $mode);
continue;
}
$entry = array('color' => $color);
if (is_array($token) && isset($token['fontStyle'])) {
$style = strtolower(trim((string) $token['fontStyle']));
if (in_array($style, array('bold', 'italic', 'bold italic', 'normal'), true)) {
$entry['fontStyle'] = $style;
}
}
$output['tokens'][$key] = $entry;
}
if (! empty($output['tokens']) || count($output) > 1) {
$valid[$mode] = $output;
}
}
if (empty($valid) && empty($errors)) {
$errors[] = __('The palette contains no recognizable dark or light theme.', 'jsray');
}
return array('themes' => $valid, 'errors' => $errors);
}
/**
* Build the CSS for a validated custom palette.
*
* Emitted as an inline stylesheet after the palette stylesheet, so it overrides
* only the variables the user actually defined and inherits the rest.
*
* @param array<string, array<string, mixed>> $themes Validated themes.
* @return string
*/
function jsray_wp_palette_css($themes) {
$vocabulary = jsray_wp_vocabulary();
$css = '';
foreach ($themes as $mode => $theme) {
$variables = array();
$rules = '';
foreach ($vocabulary['surfaces'] as $key => $suffix) {
if (isset($theme[$key])) {
$variables[] = sprintf('--jr-%s:%s', $suffix, $theme[$key]);
}
}
foreach ($theme['tokens'] as $key => $token) {
$suffix = $vocabulary['tokens'][$key];
$variables[] = sprintf('--jr-%s:%s', $suffix, $token['color']);
// Colors are variable-driven, but weight and slant are declared on
// the .tk-* classes in the core stylesheet — so overriding them
// takes a real rule, not a custom property.
if (isset($token['fontStyle'])) {
$rules .= sprintf(
'[data-theme="%1$s"] .tk-%2$s{font-weight:%3$s;font-style:%4$s}',
$mode,
$suffix,
false !== strpos($token['fontStyle'], 'bold') ? '700' : '400',
false !== strpos($token['fontStyle'], 'italic') ? 'italic' : 'normal'
);
}
}
if ($variables) {
$css .= sprintf('[data-theme="%s"]{%s;}', $mode, implode(';', $variables));
}
$css .= $rules;
}
return $css;
}
/**
* Sanitize plugin settings.
*
* @param mixed $input Raw option payload.
* @return array<string, string>
*/
function jsray_wp_sanitize_options($input) {
$defaults = jsray_wp_default_options();
$output = $defaults;
if (! is_array($input)) {
return $output;
}
$theme = isset($input['theme']) ? sanitize_key((string) $input['theme']) : $defaults['theme'];
if (! in_array($theme, array('dark', 'light', 'inherit'), true)) {
$theme = $defaults['theme'];
}
$palette = isset($input['palette']) ? sanitize_key((string) $input['palette']) : $defaults['palette'];
if (! array_key_exists($palette, jsray_wp_palettes())) {
$palette = $defaults['palette'];
}
// The custom palette is stored as the user typed it so the textarea can
// round-trip, but it is validated here and again before any CSS is emitted.
$custom = isset($input['custom_palette']) ? (string) $input['custom_palette'] : '';
if ('' !== trim($custom)) {
$validated = jsray_wp_validate_palette($custom);
foreach ($validated['errors'] as $message) {
add_settings_error('jsray_wp_options', 'jsray_wp_palette', $message, 'warning');
}
if (empty($validated['themes'])) {
$custom = '';
} else {
add_settings_error(
'jsray_wp_options',
'jsray_wp_palette_ok',
sprintf(
/* translators: %s: comma-separated theme modes. */
__('Custom palette accepted for: %s.', 'jsray'),
implode(', ', array_keys($validated['themes']))
),
'success'
);
}
}
$output['theme'] = $theme;
$output['palette'] = $palette;
$output['custom_palette'] = $custom;
$output['fallback_language'] = isset($input['fallback_language'])
? jsray_wp_sanitize_language((string) $input['fallback_language'])
: $defaults['fallback_language'];
$output['enqueue_assets'] = empty($input['enqueue_assets']) ? '0' : '1';
$output['scan_all_code'] = empty($input['scan_all_code']) ? '0' : '1';
return $output;
}
/**
* Build a cache-busting asset version.
*
* @param string $relative_path Path relative to plugin root.
* @return string
*/
function jsray_wp_asset_version($relative_path) {
$path = JSRAY_WP_DIR . ltrim($relative_path, '/');
return file_exists($path) ? (string) filemtime($path) : JSRAY_WP_VERSION;
}
/**
* Register shared front-end and editor assets.
*
* @return void
*/
function jsray_wp_register_assets() {
// One handle per bundled palette. Exactly one is enqueued at a time; the
// core stylesheet deliberately does not depend on any of them, so a
// renderer adapter can supply its own palette instead.
foreach (array_keys(jsray_wp_palettes()) as $palette) {
$relative = 'assets/css/themes/' . $palette . '.css';
if (! file_exists(JSRAY_WP_DIR . $relative)) {
continue;
}
wp_register_style(
'jsray-theme-' . $palette,
JSRAY_WP_URL . $relative,
array(),
jsray_wp_asset_version($relative)
);
}
wp_register_style(
'jsray-core',
JSRAY_WP_URL . 'assets/css/jsray.css',
array(),
jsray_wp_asset_version('assets/css/jsray.css')
);
wp_register_style(
'jsray-block-frontend',
JSRAY_WP_URL . 'assets/css/jsray-block.css',
array('jsray-core'),
jsray_wp_asset_version('assets/css/jsray-block.css')
);
wp_register_style(
'jsray-block-editor',
JSRAY_WP_URL . 'assets/css/jsray-block-editor.css',
array('jsray-block-frontend'),
jsray_wp_asset_version('assets/css/jsray-block-editor.css')
);
wp_register_script(
'jsray-core',
JSRAY_WP_URL . 'assets/js/jsray.js',
array(),
jsray_wp_asset_version('assets/js/jsray.js'),
true
);
/**
* Filter script dependencies for the front-end loader.
*
* Renderer adapters that provide their own runtime can replace the default
* `jsray-core` dependency with their own registered script handle.
*
* @param string[] $dependencies Script handles required by the loader.
*/
$loader_dependencies = apply_filters('jsray_wp_loader_dependencies', array('jsray-core'));
wp_register_script(
'jsray-loader',
JSRAY_WP_URL . 'assets/js/jsray-loader.js',
$loader_dependencies,
jsray_wp_asset_version('assets/js/jsray-loader.js'),
true
);
wp_register_script(
'jsray-block-editor',
JSRAY_WP_URL . 'assets/js/jsray-block.js',
array(
'wp-blocks',
'wp-block-editor',
'wp-components',
'wp-element',
'wp-i18n',
'jsray-core',
),
jsray_wp_asset_version('assets/js/jsray-block.js'),
true
);
// block.json is the single source of truth for the block's name, attributes,
// and supports. The editor script reads it from here instead of repeating it.
$metadata = array();
$metadata_path = JSRAY_WP_DIR . 'block.json';
if (file_exists($metadata_path)) {
$decoded = json_decode((string) file_get_contents($metadata_path), true); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
if (is_array($decoded)) {
$metadata = $decoded;
}
}
wp_add_inline_script(
'jsray-block-editor',
'window.JSRayBlockSettings = ' . wp_json_encode(
array(
'languages' => jsray_wp_supported_languages(),
'metadata' => $metadata,
)
) . ';',
'before'
);
if (function_exists('wp_set_script_translations')) {
wp_set_script_translations('jsray-block-editor', 'jsray', JSRAY_WP_DIR . 'languages');
wp_set_script_translations('jsray-loader', 'jsray', JSRAY_WP_DIR . 'languages');
}
}
add_action('init', 'jsray_wp_register_assets', 5);
/**
* Register the JSRay Gutenberg block.
*
* @return void
*/
function jsray_wp_register_block() {
// Attributes, supports, and asset handles all come from block.json, so the
// PHP and JS sides cannot drift apart.
register_block_type(
JSRAY_WP_DIR . 'block.json',
array(
'render_callback' => 'jsray_wp_render_code_block',
)
);
}
add_action('init', 'jsray_wp_register_block', 20);
/**
* Register the plugin settings UI.
*
* @return void
*/
function jsray_wp_register_settings() {
register_setting(
'jsray_wp',
'jsray_wp_options',
array(
'type' => 'array',
'sanitize_callback' => 'jsray_wp_sanitize_options',
'default' => jsray_wp_default_options(),
)
);
add_settings_section(
'jsray_wp_rendering',
__('Rendering', 'jsray'),
'__return_false',
'jsray_wp'
);
add_settings_field(
'jsray_wp_palette',
__('Palette', 'jsray'),
'jsray_wp_render_palette_field',
'jsray_wp',
'jsray_wp_rendering'
);
add_settings_field(
'jsray_wp_custom_palette',
__('Custom colors', 'jsray'),
'jsray_wp_render_custom_palette_field',
'jsray_wp',
'jsray_wp_rendering'
);
add_settings_field(
'jsray_wp_theme',
__('Theme mode', 'jsray'),
'jsray_wp_render_theme_field',
'jsray_wp',
'jsray_wp_rendering'
);
add_settings_field(
'jsray_wp_fallback_language',
__('Fallback language', 'jsray'),
'jsray_wp_render_fallback_language_field',
'jsray_wp',
'jsray_wp_rendering'
);
add_settings_field(
'jsray_wp_enqueue_assets',
__('Front-end assets', 'jsray'),
'jsray_wp_render_enqueue_assets_field',
'jsray_wp',
'jsray_wp_rendering'
);
add_settings_field(
'jsray_wp_scan_all_code',
__('Code block coverage', 'jsray'),
'jsray_wp_render_scan_all_code_field',
'jsray_wp',
'jsray_wp_rendering'
);
}
/**
* Add a Settings link on the Plugins screen.
*
* @param string[] $links Existing action links.
* @return string[]
*/
function jsray_wp_plugin_action_links($links) {
$settings = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(admin_url('options-general.php?page=jsray')),
esc_html__('Settings', 'jsray')
);
array_unshift($links, $settings);
return $links;
}
add_filter('plugin_action_links_' . plugin_basename(JSRAY_WP_FILE), 'jsray_wp_plugin_action_links');
add_action('admin_init', 'jsray_wp_register_settings');
/**
* Add the settings page.
*
* @return void
*/
function jsray_wp_add_settings_page() {
add_options_page(
__('JSRay', 'jsray'),
__('JSRay', 'jsray'),
'manage_options',
'jsray',
'jsray_wp_render_settings_page'
);
}
add_action('admin_menu', 'jsray_wp_add_settings_page');
/**
* Render palette field.
*
* @return void
*/
function jsray_wp_render_palette_field() {
$active = jsray_wp_active_palette();
$palettes = jsray_wp_palettes();
?>
<select id="jsray-wp-palette" name="jsray_wp_options[palette]">
<?php foreach ($palettes as $key => $label) : ?>
<option value="<?php echo esc_attr($key); ?>" <?php selected($active, $key); ?>>
<?php echo esc_html($label); ?>
</option>
<?php endforeach; ?>
</select>
<p class="description"><?php esc_html_e('Every palette ships both a dark and a light variant, so this is independent of the theme mode below.', 'jsray'); ?></p>
<?php
// A custom palette silently outranks this setting. Without saying so, the
// palette picker looks broken to anyone who pasted a palette and forgot.
$overrides = jsray_wp_custom_palette_keys();
if ($overrides) {
?>
<p class="description" style="color:#996800;">
<strong><?php esc_html_e('Note:', 'jsray'); ?></strong>
<?php
echo esc_html(
sprintf(
/* translators: 1: number of overridden values, 2: comma-separated list. */
_n(
'Custom colors below override %1$d value on top of this palette, so it will not change: %2$s',
'Custom colors below override %1$d values on top of this palette, so they will not change: %2$s',
count($overrides),
'jsray'
),
count($overrides),
implode(', ', $overrides)
)
);
?>
</p>
<?php
}
}
/**
* List the values a stored custom palette overrides.
*
* @return string[] Human-readable "mode: key" labels.
*/
function jsray_wp_custom_palette_keys() {
$options = jsray_wp_get_options();
if ('' === trim((string) $options['custom_palette'])) {
return array();
}
$validated = jsray_wp_validate_palette($options['custom_palette']);
$keys = array();
foreach ($validated['themes'] as $mode => $theme) {
foreach (array_keys($theme) as $key) {
if ('tokens' !== $key) {
$keys[] = $mode . ': ' . $key;
}
}
foreach (array_keys($theme['tokens']) as $key) {
$keys[] = $mode . ': ' . $key;
}
}
return $keys;
}
/**
* Render the custom palette field.
*
* @return void
*/
function jsray_wp_render_custom_palette_field() {
$options = jsray_wp_get_options();
$count = count(jsray_wp_vocabulary()['tokens']);
?>
<textarea
id="jsray-wp-custom-palette"
name="jsray_wp_options[custom_palette]"
rows="8"
class="large-text code"
spellcheck="false"
placeholder='{"themes":{"dark":{"background":"#101014","tokens":{"keyword":{"color":"#FF6B9D","fontStyle":"bold"}}}}}'
><?php echo esc_textarea($options['custom_palette']); ?></textarea>
<p class="description">
<?php
echo esc_html(
sprintf(
/* translators: %d: number of token classes. */
__('Optional. Overrides individual colors on top of the palette above — anything you leave out keeps the palette\'s value. Accepts the same JSON the JSRay Theme Studio exports, covering all %d token classes.', 'jsray'),
$count
)
);
?>
<br>
<a href="https://jsray.org/studio.html" target="_blank" rel="noopener noreferrer">
<?php esc_html_e('Design a palette in the Theme Studio', 'jsray'); ?>
</a>
</p>
<?php
}