-
Notifications
You must be signed in to change notification settings - Fork 14
/
CodemirrorWidget.php
80 lines (69 loc) · 2.21 KB
/
CodemirrorWidget.php
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
<?php
/**
* @link https://github.com/borodulin/yii2-codemirror
* @copyright Copyright (c) 2015 Andrey Borodulin
* @license https://github.com/borodulin/yii2-codemirror/blob/master/LICENSE.md
*/
namespace conquer\codemirror;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use conquer\helpers\Json;
/**
* @author Andrey Borodulin
*/
class CodemirrorWidget extends \yii\widgets\InputWidget
{
public $presetsDir;
public $assets = [];
public $settings = [];
/**
* Preset name. php|javascript etc.
* @var string
*/
public $preset;
/**
* @inheritdoc
*/
public function run()
{
if ($this->hasModel()) {
echo Html::activeTextarea($this->model, $this->attribute, $this->options);
} else {
echo Html::textarea($this->name, $this->value, $this->options);
}
$this->registerAssets();
}
/**
* Registers Assets
*/
public function registerAssets()
{
$view = $this->getView();
$id = $this->options['id'];
$settings = $this->settings;
$assets = $this->assets;
if ($this->preset) {
$preset = $this->getPreset($this->preset);
if (isset($preset['settings'])) {
$settings = ArrayHelper::merge($preset['settings'], $settings);
}
if (isset($preset['assets'])) {
$assets = ArrayHelper::merge($preset['assets'], $assets);
}
}
$settings = Json::encode($settings);
$instanceName = 'CM_'.preg_replace('/[^\w\d]/ius', '', $id);
$js = "CodeMirror.fromTextArea(document.getElementById('$id'), $settings);";
$view->registerJs($js, $view::POS_READY);
CodemirrorAsset::register($this->view, $assets);
}
public function getPreset($name)
{
if ($this->presetsDir) {
$filename = $this->presetsDir . DIRECTORY_SEPARATOR . ucfirst($name) . 'Preset.php';
} else {
$filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'presets' . DIRECTORY_SEPARATOR . ucfirst($name) . 'Preset.php';
}
return require $filename;
}
}