-
Notifications
You must be signed in to change notification settings - Fork 1
/
TuiEditor.php
82 lines (73 loc) · 2.13 KB
/
TuiEditor.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
81
82
<?php
namespace h0rseduck\tuieditor;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Inflector;
use yii\helpers\Json;
use yii\web\JsExpression;
use yii\widgets\InputWidget;
/**
* Class AutoloadExample
* @package h0rseduck\tuieditor
*/
class TuiEditor extends InputWidget
{
/**
* @var array markdown options
*/
public $editorOptions = [];
/**
* @var null|string
*/
protected $varName = null;
/**
* @return string|void
*/
public function run()
{
if ($this->hasModel()) {
echo Html::activeTextarea($this->model, $this->attribute,
ArrayHelper::merge($this->options, ['style' => 'display: none;']));
} else {
echo Html::textarea($this->attribute, $this->value,
ArrayHelper::merge($this->options, ['style' => 'display: none;']));
}
echo Html::tag('div', null, [
'id' => "editor_{$this->id}"
]);
$this->registerAssets();
}
/**
* @return string|null
*/
protected function getVarName()
{
if (is_null($this->varName)) {
$this->varName = Inflector::variablize('editor_' . $this->id);
}
return $this->varName;
}
/**
* Register client assets
*/
protected function registerAssets()
{
$view = $this->getView();
TuiEditorAsset::register($view);
$script = "var {$this->getVarName()} = new tui.Editor(" . $this->getEditorOptions() . ');';
$view->registerJs($script);
}
/**
* Return editor options in json format
* @return string
*/
protected function getEditorOptions()
{
$this->editorOptions['el'] = new JsExpression('document.getElementById("editor_' . $this->id . '")');
$this->editorOptions['events']['change'] = new JsExpression('function() {$("#' . $this->options['id'] . '").val(' . $this->getVarName() . '.getValue())}');
$this->editorOptions['initialValue'] = $this->hasModel()
? $this->model->{$this->attribute}
: $this->value;
return Json::encode($this->editorOptions);
}
}