Debian Codegraph @

skins/Vector/includes/SkinVector22.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Skins\Vector;
4
5 use MediaWiki\Html\Html;
6 use MediaWiki\Languages\LanguageConverterFactory;
7 use MediaWiki\MediaWikiServices;
8 use MediaWiki\Registration\ExtensionRegistry;
9 use MediaWiki\Skins\Vector\Components\VectorComponentAppearance;
10 use MediaWiki\Skins\Vector\Components\VectorComponentButton;
11 use MediaWiki\Skins\Vector\Components\VectorComponentDropdown;
12 use MediaWiki\Skins\Vector\Components\VectorComponentLanguageDropdown;
13 use MediaWiki\Skins\Vector\Components\VectorComponentMainMenu;
14 use MediaWiki\Skins\Vector\Components\VectorComponentPageTools;
15 use MediaWiki\Skins\Vector\Components\VectorComponentPinnableContainer;
16 use MediaWiki\Skins\Vector\Components\VectorComponentSearchBox;
17 use MediaWiki\Skins\Vector\Components\VectorComponentStickyHeader;
18 use MediaWiki\Skins\Vector\Components\VectorComponentTableOfContents;
19 use MediaWiki\Skins\Vector\Components\VectorComponentUserLinks;
20 use MediaWiki\Skins\Vector\Components\VectorComponentVariants;
21 use MediaWiki\Skins\Vector\FeatureManagement\FeatureManager;
22 use MediaWiki\Skins\Vector\FeatureManagement\FeatureManagerFactory;
23 use RuntimeException;
24 use SkinMustache;
25 use SkinTemplate;
26
27 /**
28 * @ingroup Skins
29 * @package Vector
30 * @internal
31 */
32 class SkinVector22 extends SkinMustache {
33 private const STICKY_HEADER_ENABLED_CLASS = 'vector-sticky-header-enabled';
34 /** @var null|array for caching purposes */
35 private $languages;
36
37 private LanguageConverterFactory $languageConverterFactory;
38 private FeatureManagerFactory $featureManagerFactory;
39 private ?FeatureManager $featureManager = null;
40
41 public function __construct(
42 LanguageConverterFactory $languageConverterFactory,
43 FeatureManagerFactory $featureManagerFactory,
44 array $options
45 ) {
46 parent::__construct( $options );
47 $this->languageConverterFactory = $languageConverterFactory;
48 // Cannot use the context in the constructor, setContext is called after construction
49 $this->featureManagerFactory = $featureManagerFactory;
50 }
51
52 /**
53 * @inheritDoc
54 */
55 protected function runOnSkinTemplateNavigationHooks( SkinTemplate $skin, &$content_navigation ) {
56 parent::runOnSkinTemplateNavigationHooks( $skin, $content_navigation );
57 Hooks::onSkinTemplateNavigation( $skin, $content_navigation );
58 }
59
60 /**
61 * @inheritDoc
62 */
63 public function isResponsive() {
64 // Check it's enabled by user preference and configuration
65 $responsive = parent::isResponsive() && $this->getConfig()->get( 'VectorResponsive' );
66 // For historic reasons, the viewport is added when Vector is loaded on the mobile
67 // domain. This is only possible for 3rd parties or by useskin parameter as there is
68 // no preference for changing mobile skin. Only need to check if $responsive is falsey.
69 if ( !$responsive && ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) ) {
70 $mobFrontContext = MediaWikiServices::getInstance()->getService( 'MobileFrontend.Context' );
71 if ( $mobFrontContext->shouldDisplayMobileView() ) {
72 return true;
73 }
74 }
75 return $responsive;
76 }
77
78 /**
79 * Whether or not toc data is available
80 *
81 * @param array $parentData Template data
82 * @return bool
83 */
84 private function isTocAvailable( array $parentData ): bool {
85 return !empty( $parentData['data-toc'][ 'array-sections' ] );
86 }
87
88 /**
89 * This should be upstreamed to the Skin class in core once the logic is finalized.
90 * Returns false if the page is a special page without any languages, or if an action
91 * other than view is being used.
92 *
93 * @return bool
94 */
95 private function canHaveLanguages(): bool {
96 $action = $this->getActionName();
97
98 // FIXME: This logic should be moved into the ULS extension or core given the button is hidden,
99 // it should not be rendered, short term fix for T328996.
100 if ( $action === 'history' ) {
101 return false;
102 }
103
104 $title = $this->getTitle();
105 return !$title || !$title->isSpecialPage()
106 // Defensive programming - if a special page has added languages explicitly, best to show it.
107 || $this->getLanguagesCached();
108 }
109
110 /**
111 * Remove the add topic button from data-views if present
112 *
113 * @param array &$parentData Template data
114 * @return bool An add topic button was removed
115 */
116 private function removeAddTopicButton( array &$parentData ): bool {
117 $views = $parentData['data-portlets']['data-views']['array-items'];
118 $hasAddTopicButton = false;
119 $html = '';
120 foreach ( $views as $i => $view ) {
121 if ( $view['id'] === 'ca-addsection' ) {
122 array_splice( $views, $i, 1 );
123 $hasAddTopicButton = true;
124 continue;
125 }
126 $html .= $view['html-item'];
127 }
128 $parentData['data-portlets']['data-views']['array-items'] = $views;
129 $parentData['data-portlets']['data-views']['html-items'] = $html;
130 return $hasAddTopicButton;
131 }
132
133 private function getFeatureManager(): FeatureManager {
134 if ( $this->featureManager === null ) {
135 $this->featureManager = $this->featureManagerFactory->createFeatureManager( $this->getContext() );
136 }
137 return $this->featureManager;
138 }
139
140 /**
141 * @param string $location Either 'top' or 'bottom' is accepted.
142 * @return bool
143 */
144 protected function isLanguagesInContentAt( string $location ): bool {
145 if ( !$this->canHaveLanguages() ) {
146 return false;
147 }
148 $featureManager = $this->getFeatureManager();
149 $inContent = $featureManager->isFeatureEnabled(
150 Constants::FEATURE_LANGUAGE_IN_HEADER
151 );
152 $title = $this->getTitle();
153 $isMainPage = $title ? $title->isMainPage() : false;
154
155 switch ( $location ) {
156 case 'top':
157 return $isMainPage ? $inContent && $featureManager->isFeatureEnabled(
158 Constants::FEATURE_LANGUAGE_IN_MAIN_PAGE_HEADER
159 ) : $inContent;
160 case 'bottom':
161 return $inContent && $isMainPage && !$featureManager->isFeatureEnabled(
162 Constants::FEATURE_LANGUAGE_IN_MAIN_PAGE_HEADER
163 );
164 default:
165 throw new RuntimeException( 'unknown language button location' );
166 }
167 }
168
169 /**
170 * Whether or not the languages are out of the sidebar and in the content either at
171 * the top or the bottom.
172 *
173 * @return bool
174 */
175 final protected function isLanguagesInContent(): bool {
176 return $this->isLanguagesInContentAt( 'top' ) || $this->isLanguagesInContentAt( 'bottom' );
177 }
178
179 /**
180 * Calls getLanguages with caching.
181 *
182 * @return array
183 */
184 protected function getLanguagesCached(): array {
185 if ( $this->languages === null ) {
186 $this->languages = $this->getLanguages();
187 }
188 return $this->languages;
189 }
190
191 /**
192 * Check whether ULS is enabled
193 *
194 * @return bool
195 */
196 final protected function isULSExtensionEnabled(): bool {
197 return ExtensionRegistry::getInstance()->isLoaded( 'UniversalLanguageSelector' );
198 }
199
200 /**
201 * Check whether Visual Editor Tab Position is first
202 *
203 * @param array $dataViews
204 * @return bool
205 */
206 final protected function isVisualEditorTabPositionFirst( $dataViews ): bool {
207 $names = [ 've-edit', 'edit' ];
208 // find if under key 'name' 've-edit' or 'edit' is the before item in the array
209 for ( $i = 0; $i < count( $dataViews[ 'array-items' ] ); $i++ ) {
210 if ( in_array( $dataViews[ 'array-items' ][ $i ][ 'name' ], $names ) ) {
211 return $dataViews[ 'array-items' ][ $i ][ 'name' ] === $names[ 0 ];
212 }
213 }
214 return false;
215 }
216
217 /**
218 * Show the ULS button if it's modern Vector, languages in header is enabled,
219 * the ULS extension is enabled, and we are on a subect page. Hide it otherwise.
220 * There is no point in showing the language button if ULS extension is unavailable
221 * as there is no ways to add languages without it.
222 * @return bool
223 */
224 protected function shouldHideLanguages(): bool {
225 $title = $this->getTitle();
226 $isSubjectPage = $title && $title->exists() && !$title->isTalkPage();
227 return !$this->isLanguagesInContent() || !$this->isULSExtensionEnabled() || !$isSubjectPage;
228 }
229
230 /**
231 * Merges the `view-overflow` menu into the `action` menu.
232 * This ensures that the previous state of the menu e.g. emptyPortlet class
233 * is preserved.
234 *
235 * @param array $data
236 * @return array
237 */
238 private function mergeViewOverflowIntoActions( array $data ): array {
239 $portlets = $data['data-portlets'];
240 $actions = $portlets['data-actions'];
241 $overflow = $portlets['data-views-overflow'];
242 // if the views overflow menu is not empty, then signal that the more menu despite
243 // being initially empty now has collapsible items.
244 if ( !$overflow['is-empty'] ) {
245 $data['data-portlets']['data-actions']['class'] .= ' vector-has-collapsible-items';
246 }
247 $data['data-portlets']['data-actions']['html-items'] = $overflow['html-items'] . $actions['html-items'];
248 return $data;
249 }
250
251 /**
252 * @inheritDoc
253 */
254 public function getHtmlElementAttributes() {
255 $original = parent::getHtmlElementAttributes();
256 $featureManager = $this->getFeatureManager();
257 $original['class'] .= ' ' . implode( ' ', $featureManager->getFeatureBodyClass() );
258
259 if ( $featureManager->isFeatureEnabled( Constants::FEATURE_STICKY_HEADER ) ) {
260 // T290518: Add scroll padding to root element when the sticky header is
261 // enabled. This class needs to be server rendered instead of added from
262 // JS in order to correctly handle situations where the sticky header
263 // isn't visible yet but we still need scroll padding applied (e.g. when
264 // the user navigates to a page with a hash fragment in the URI). For this
265 // reason, we can't rely on the `vector-sticky-header-visible` class as it
266 // is added too late.
267 //
268 // Please note that this class applies scroll padding which does not work
269 // when applied to the body tag in Chrome, Safari, and Firefox (and
270 // possibly others). It must instead be applied to the html tag.
271 $original['class'] = implode( ' ', [ $original['class'] ?? '', self::STICKY_HEADER_ENABLED_CLASS ] );
272 }
273 $original['class'] = trim( $original['class'] );
274
275 return $original;
276 }
277
278 /**
279 * Pulls the page tools menu out of $sidebar into $pageToolsMenu
280 *
281 * @param array &$sidebar
282 * @param array &$pageToolsMenu
283 */
284 private static function extractPageToolsFromSidebar( array &$sidebar, array &$pageToolsMenu ) {
285 $restPortlets = $sidebar[ 'array-portlets-rest' ] ?? [];
286 $toolboxMenuIndex = array_search(
287 VectorComponentPageTools::TOOLBOX_ID,
288 array_column(
289 $restPortlets,
290 'id'
291 )
292 );
293
294 if ( $toolboxMenuIndex !== false ) {
295 // Splice removes the toolbox menu from the $restPortlets array
296 // and current returns the first value of array_splice, i.e. the $toolbox menu data.
297 $pageToolsMenu = array_splice( $restPortlets, $toolboxMenuIndex );
298 $sidebar['array-portlets-rest'] = $restPortlets;
299 }
300 }
301
302 /**
303 * Get the ULS button label, accounting for the number of available
304 * languages.
305 *
306 * @return array
307 */
308 final protected function getULSLabels(): array {
309 $numLanguages = count( $this->getLanguagesCached() );
310
311 if ( $numLanguages === 0 ) {
312 return [
313 'label' => $this->msg( 'vector-no-language-button-label' )->text(),
314 'aria-label' => $this->msg( 'vector-no-language-button-aria-label' )->text()
315 ];
316 } else {
317 return [
318 'label' => $this->msg( 'vector-language-button-label' )->numParams( $numLanguages )->text(),
319 'aria-label' => $this->msg( 'vector-language-button-aria-label' )->numParams( $numLanguages )->text()
320 ];
321 }
322 }
323
324 /**
325 * @return array
326 */
327 public function getTemplateData(): array {
328 $parentData = parent::getTemplateData();
329 $parentData = $this->mergeViewOverflowIntoActions( $parentData );
330 $portlets = $parentData['data-portlets'];
331
332 $langData = $portlets['data-languages'] ?? null;
333 $config = $this->getConfig();
334 $featureManager = $this->getFeatureManager();
335
336 $sidebar = $parentData[ 'data-portlets-sidebar' ];
337 $pageToolsMenu = [];
338 self::extractPageToolsFromSidebar( $sidebar, $pageToolsMenu );
339
340 $hasAddTopicButton = $config->get( 'VectorPromoteAddTopic' ) &&
341 $this->removeAddTopicButton( $parentData );
342
343 $langButtonClass = $langData['class'] ?? '';
344 $ulsLabels = $this->getULSLabels();
345 $user = $this->getUser();
346 $localizer = $this->getContext();
347 $title = $this->getTitle();
348
349 // If the table of contents has no items, we won't output it.
350 // empty array is interpreted by Mustache as falsey.
351 $tocComponents = [];
352 if ( $this->isTocAvailable( $parentData ) ) {
353 // @phan-suppress-next-line SecurityCheck-XSS
354 $dataToc = new VectorComponentTableOfContents(
355 $parentData['data-toc'],
356 $localizer,
357 $config,
358 $featureManager
359 );
360 $isPinned = $dataToc->isPinned();
361 $tocComponents = [
362 'data-toc' => $dataToc,
363 'data-toc-pinnable-container' => new VectorComponentPinnableContainer(
364 VectorComponentTableOfContents::ID,
365 $isPinned
366 ),
367 'data-page-titlebar-toc-dropdown' => new VectorComponentDropdown(
368 'vector-page-titlebar-toc',
369 // label
370 $this->msg( 'vector-toc-collapsible-button-label' ),
371 // class
372 'vector-page-titlebar-toc vector-button-flush-left',
373 // icon
374 'listBullet',
375 ),
376 'data-page-titlebar-toc-pinnable-container' => new VectorComponentPinnableContainer(
377 'vector-page-titlebar-toc',
378 $isPinned
379 ),
380 'data-sticky-header-toc-dropdown' => new VectorComponentDropdown(
381 'vector-sticky-header-toc',
382 // label
383 $this->msg( 'vector-toc-collapsible-button-label' ),
384 // class
385 'mw-portlet mw-portlet-sticky-header-toc vector-sticky-header-toc vector-button-flush-left',
386 // icon
387 'listBullet'
388 ),
389 'data-sticky-header-toc-pinnable-container' => new VectorComponentPinnableContainer(
390 'vector-sticky-header-toc',
391 $isPinned
392 ),
393 ];
394 $this->getOutput()->addHtmlClasses( 'vector-toc-available' );
395 } else {
396 $this->getOutput()->addHtmlClasses( 'vector-toc-not-available' );
397 }
398
399 $isRegistered = $user->isRegistered();
400 $userPage = $isRegistered ? $this->buildPersonalPageItem() : [];
401
402 $components = $tocComponents + [
403 'data-add-topic-button' => $hasAddTopicButton ? new VectorComponentButton(
404 $this->msg( [ 'vector-2022-action-addsection', 'skin-action-addsection' ] )->text(),
405 'speechBubbleAdd-progressive',
406 'ca-addsection',
407 '',
408 [ 'data-event-name' => 'addsection-header' ],
409 'quiet',
410 'progressive',
411 false,
412 $title->getLocalURL( [ 'action' => 'edit', 'section' => 'new' ] )
413 ) : null,
414 'data-variants' => new VectorComponentVariants(
415 $this->languageConverterFactory,
416 $portlets['data-variants'],
417 $title->getPageLanguage(),
418 $this->msg( 'vector-language-variant-switcher-label' )
419 ),
420 'data-vector-user-links' => new VectorComponentUserLinks(
421 $localizer,
422 $user,
423 $portlets,
424 $this->getOptions()['link'],
425 $userPage[ 'icon' ] ?? ''
426 ),
427 'data-lang-dropdown' => $langData ? new VectorComponentLanguageDropdown(
428 $ulsLabels['label'],
429 $ulsLabels['aria-label'],
430 $langButtonClass,
431 count( $this->getLanguagesCached() ),
432 $langData['html-items'] ?? '',
433 $langData['html-before-portal'] ?? '',
434 $langData['html-after-portal'] ?? '',
435 $title
436 ) : null,
437 'data-search-box' => new VectorComponentSearchBox(
438 $parentData['data-search-box'],
439 true,
440 // is primary mode of search
441 true,
442 'searchform',
443 true,
444 $config,
445 Constants::SEARCH_BOX_INPUT_LOCATION_MOVED,
446 $localizer
447 ),
448 'data-main-menu' => new VectorComponentMainMenu(
449 $sidebar,
450 $portlets['data-languages'] ?? [],
451 $localizer,
452 $user,
453 $featureManager,
454 $this,
455 ),
456 'data-main-menu-dropdown' => new VectorComponentDropdown(
457 VectorComponentMainMenu::ID . '-dropdown',
458 $this->msg( VectorComponentMainMenu::ID . '-label' )->text(),
459 VectorComponentMainMenu::ID . '-dropdown' . ' vector-button-flush-left vector-button-flush-right',
460 'menu'
461 ),
462 'data-page-tools' => new VectorComponentPageTools(
463 array_merge( [ $portlets['data-actions'] ?? [] ], $pageToolsMenu ),
464 $localizer,
465 $featureManager
466 ),
467 'data-page-tools-dropdown' => new VectorComponentDropdown(
468 VectorComponentPageTools::ID . '-dropdown',
469 $this->msg( 'toolbox' )->text(),
470 VectorComponentPageTools::ID . '-dropdown',
471 ),
472 'data-appearance' => new VectorComponentAppearance( $localizer, $featureManager ),
473 'data-appearance-dropdown' => new VectorComponentDropdown(
474 'vector-appearance-dropdown',
475 $this->msg( 'vector-appearance-label' )->text(),
476 '',
477 'appearance',
478 Html::expandAttributes( [
479 'title' => $this->msg( 'vector-appearance-tooltip' ),
480 ] )
481 ),
482 'data-vector-sticky-header' => $featureManager->isFeatureEnabled(
483 Constants::FEATURE_STICKY_HEADER
484 ) ? new VectorComponentStickyHeader(
485 $localizer,
486 new VectorComponentSearchBox(
487 $parentData['data-search-box'],
488 // Collapse inside search box is disabled.
489 false,
490 false,
491 'vector-sticky-search-form',
492 false,
493 $config,
494 Constants::SEARCH_BOX_INPUT_LOCATION_MOVED,
495 $localizer
496 ),
497 // Show sticky ULS if the ULS extension is enabled and the ULS in header is not hidden
498 $this->isULSExtensionEnabled() && !$this->shouldHideLanguages() ?
499 new VectorComponentButton(
500 $ulsLabels[ 'label' ],
501 'wikimedia-language',
502 'p-lang-btn-sticky-header',
503 'mw-interlanguage-selector',
504 [
505 'tabindex' => '-1',
506 'data-event-name' => 'ui.dropdown-p-lang-btn-sticky-header'
507 ],
508 'quiet',
509 ) : null,
510 $this->isVisualEditorTabPositionFirst( $portlets[ 'data-views' ] )
511 ) : null,
512 ];
513
514 foreach ( $components as $key => $component ) {
515 // Array of components or null values.
516 if ( $component ) {
517 $parentData[$key] = $component->getTemplateData();
518 }
519 }
520
521 return array_merge( $parentData, [
522 'is-language-in-content' => $this->isLanguagesInContent(),
523 'has-buttons-in-content-top' => $this->isLanguagesInContentAt( 'top' ) || $hasAddTopicButton,
524 'is-language-in-content-bottom' => $this->isLanguagesInContentAt( 'bottom' ),
525 // Cast empty string to null
526 'html-subtitle' => $parentData['html-subtitle'] === '' ? null : $parentData['html-subtitle'],
527 ] );
528 }
529 }