1010use cebe \markdown \GithubMarkdown ;
1111use yii \apidoc \models \TypeDoc ;
1212use yii \apidoc \renderers \BaseRenderer ;
13+ use yii \helpers \Html ;
1314use yii \helpers \Inflector ;
1415use yii \helpers \Markdown ;
1516
@@ -30,6 +31,39 @@ class ApiMarkdown extends GithubMarkdown
3031
3132 protected $ renderingContext ;
3233
34+ protected $ headings = [];
35+
36+ /**
37+ * @inheritDoc
38+ */
39+ protected function prepare ()
40+ {
41+ parent ::prepare ();
42+ $ this ->headings = [];
43+ }
44+
45+ public function parse ($ text )
46+ {
47+ $ markup = parent ::parse ($ text );
48+ $ markup = $ this ->applyToc ($ markup );
49+ return $ markup ;
50+ }
51+
52+ protected function applyToc ($ content )
53+ {
54+ // generate TOC
55+ if (!empty ($ this ->headings )) {
56+ $ toc = [];
57+ foreach ($ this ->headings as $ heading )
58+ $ toc [] = '<li> ' . Html::a ($ heading ['title ' ], '# ' . $ heading ['id ' ]) . '</li> ' ;
59+ $ toc = '<div class="toc"><ol> ' . implode ("\n" , $ toc ) . "</ol></div> \n" ;
60+ if (strpos ($ content , '</h1> ' ) !== false )
61+ $ content = str_replace ('</h1> ' , "</h1> \n" . $ toc , $ content );
62+ else
63+ $ content = $ toc . $ content ;
64+ }
65+ return $ content ;
66+ }
3367
3468 /**
3569 * @inheritdoc
@@ -80,8 +114,20 @@ public static function highlight($code, $language)
80114 protected function renderHeadline ($ block )
81115 {
82116 $ content = $ this ->renderAbsy ($ block ['content ' ]);
83- $ hash = Inflector::slug (strip_tags ($ content ));
84- $ hashLink = "<a href= \"# $ hash \" id= \"$ hash \" class= \"hashlink \">¶</a> " ;
117+ if (preg_match ('~<span id="(.*?)"></span>~ ' , $ content , $ matches )) {
118+ $ hash = $ matches [1 ];
119+ $ content = preg_replace ('~<span id=".*?"></span>~ ' , '' , $ content );
120+ } else {
121+ $ hash = Inflector::slug (strip_tags ($ content ));
122+ }
123+ $ hashLink = "<span id= \"$ hash \"></span><a href= \"# $ hash \" class= \"hashlink \">¶</a> " ;
124+
125+ if ($ block ['level ' ] == 2 ) {
126+ $ this ->headings [] = [
127+ 'title ' => trim ($ content ),
128+ 'id ' => $ hash ,
129+ ];
130+ }
85131
86132 $ tag = 'h ' . $ block ['level ' ];
87133 return "< $ tag> $ content $ hashLink</ $ tag> " ;
0 commit comments