3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 namespace MediaWiki\Skin
;
21 use MediaWiki\Output\OutputPage
;
22 use MediaWiki\Parser\ParserOutputFlags
;
25 * @internal for use inside Skin and SkinTemplate classes only
28 class SkinComponentTableOfContents
implements SkinComponent
{
29 /** @var OutputPage */
32 public function __construct( OutputPage
$output ) {
33 $this->output
= $output;
37 * Nests child sections within their parent sections.
39 * @param array $sections
40 * @param int $toclevel
43 private function getSectionsDataInternal( array $sections, int $toclevel = 1 ): array {
45 foreach ( $sections as $i => $section ) {
46 // Child section belongs to a higher parent.
47 if ( $section->tocLevel
< $toclevel ) {
51 // Set all the parent sections at the current top level.
52 if ( $section->tocLevel
=== $toclevel ) {
53 $childSections = $this->getSectionsDataInternal(
54 array_slice( $sections, $i +
1 ),
57 $data[] = $section->toLegacy() +
[
58 'array-sections' => $childSections,
59 'is-top-level-section' => $toclevel === 1,
60 'is-parent-section' => $childSections !== []
68 * Get table of contents template data
70 * Enriches section data by nesting child elements within parent elements
71 * such that the table of contents can be rendered in Mustache.
73 * For an example of how to render the data, see TableOfContents.mustache in
76 private function getTOCDataInternal(): array {
77 $tocData = $this->output
->getTOCData();
78 // Return data only if TOC present T298796.
79 if ( $tocData === null ) {
83 if ( $this->output
->getOutputFlag( ParserOutputFlags
::NO_TOC
) ) {
87 $outputSections = $tocData->getSections();
89 return count( $outputSections ) > 0 ?
[
90 'number-section-count' => count( $outputSections ),
91 'array-sections' => $this->getSectionsDataInternal( $outputSections, 1 ),
98 public function getTemplateData(): array {
99 return $this->getTOCDataInternal();