forked from iJackUA/yii2-lepture-markdown-editor-widget
/
Markdowneditor.php
80 lines (70 loc) · 1.84 KB
/
Markdowneditor.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
/**
* Lepture Markdown Editor class file
*
* @author Evgeniy Kuzminov
* @license MIT License
* http://stdout.in
*/
namespace ijackua\lepture;
use yii\helpers\Html;
use yii\helpers\Inflector;
use Yii;
use yii\helpers\Json;
use yii\web\JsExpression;
use yii\widgets\InputWidget;
class Markdowneditor extends InputWidget
{
/**
* Markdown options you want to override
* See https://github.com/lepture/editor
*
* @var array
*/
public $leptureOptions = [];
/**
* Marked options (markdown parser used by EpicEditor)
* See details https://github.com/chjj/marked
*
* @var array
*/
public $markedOptions = [];
/**
* ID of Textarea where editor will be placed
*
* @var string
*/
protected $id;
public function init()
{
parent::init();
if (empty($this->id)) {
$this->id = $this->hasModel() ? Html::getInputId($this->model, $this->attribute) : $this->getId();
}
if (empty($this->leptureOptions['element'])) {
$this->leptureOptions['element'] = new JsExpression('$("#' . $this->id . '")[0]');
}
$jsonOptionsMarked = Json::encode($this->markedOptions);
$script = 'marked.setOptions(' . $jsonOptionsMarked . ');';
$this->view->registerJs($script);
}
public function run()
{
MarkdowneditorAssets::register($this->view);
$this->registerScripts();
$this->options['id'] = $this->id;
if ($this->hasModel()) {
$textarea = Html::activeTextArea($this->model, $this->attribute, $this->options);
} else {
$textarea = Html::textArea($this->name, $this->value, $this->options);
}
echo '<div class="lepture">' . $textarea . '</div>';
}
public function registerScripts()
{
$jsonOptions = Json::encode($this->leptureOptions);
$varName = Inflector::classify('editor' . $this->id);
$script = "var {$varName} = new Editor(" . $jsonOptions . "); {$varName}.render();";
$this->view->registerJs($script);
}
}