summaryrefslogtreecommitdiff
path: root/src/ThemeEditor.php
blob: 0b62264a74eb7ea68d26fe15d5aefd0ce26876ac (plain)
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
<?php

namespace TimberEditor;

class ThemeEditor
{
    /**
     * ThemeEditor constructor.
     */
    public function __construct()
    {
        add_filter('wp_theme_editor_filetypes', [$this, 'editableExtensions']);
        add_filter('editable_extensions', [$this, 'editableExtensions']);
        add_filter('wp_code_editor_settings', [$this, 'codeEditorSettings'], 10, 2);
        add_action('wp_enqueue_code_editor', [$this, 'enqueueCodeEditor']);
    }

    /**
     * wp_theme_editor_filetypes and editable_extensions filter callback
     * Adds twig extension support
     *
     * @param $types
     *
     * @return array
     */
    public function editableExtensions($types)
    {
        $types[] = 'twig';

        return $types;
    }

    /**
     * wp_code_editor_settings filter callback
     * Adds twig support and sets theme
     *
     * @param $settings
     * @param $args
     *
     * @return array
     */
    public function codeEditorSettings($settings, $args) {
        if (strpos($args['file'], '.twig') !== false) {
            $settings['codemirror']['mode'] = ['name' => 'twig', 'base' => 'text/html'];
        }

        $settings['codemirror']['theme'] = Settings::getCodeMirrorTheme();

        return $settings;
    }

    /**
     * wp_enqueue_code_editor action callback
     * Adds twig and custom mode support
     * Adds selected theme css
     *
     * @param $settings
     */
    public function enqueueCodeEditor($settings) {
        if (isset($settings['codemirror']['mode']['name']) && $settings['codemirror']['mode']['name'] == 'twig') {
            wp_add_inline_script( # fix as described here: https://make.wordpress.org/core/2017/10/22/code-editing-improvements-in-wordpress-4-9/
                'wp-codemirror',
                'window.CodeMirror = wp.CodeMirror;'
            );
            wp_enqueue_script('mode-twig', 'https://unpkg.com/codemirror@5/mode/twig/twig.js', ['wp-codemirror']);
        }

        $theme = $settings['codemirror']['theme'];
        if ($theme != 'default') {
            wp_enqueue_style('codemirror-theme', "https://unpkg.com/codemirror@5/theme/$theme.css", ['wp-codemirror']);
        }
    }
}