summaryrefslogtreecommitdiff
path: root/vendor/oojs/oojs-ui/php/elements/TabIndexedElement.php
blob: 223b537165fcf14474679343918bbb82634eda1e (plain)
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
83
84
85
86
87
88
<?php

namespace OOUI;

/**
 * Element supporting "sequential focus navigation" using the 'tabindex' attribute.
 *
 * @abstract
 */
class TabIndexedElement extends ElementMixin {
	/**
	 * Tab index value.
	 *
	 * @var number|null
	 */
	protected $tabIndex = null;

	public static $targetPropertyName = 'tabIndexed';

	/**
	 * @param Element $element Element being mixed into
	 * @param array $config Configuration options
	 * @param number|null $config['tabIndex'] Tab index value. Use 0 to use default ordering, use -1 to
	 *   prevent tab focusing, use null to suppress the `tabindex` attribute. (default: 0)
	 */
	public function __construct( Element $element, array $config = array() ) {
		// Parent constructor
		$target = isset( $config['tabIndexed'] ) ? $config['tabIndexed'] : $element;
		parent::__construct( $element, $target, $config );

		// Initialization
		$this->setTabIndex( isset( $config['tabIndex'] ) ? $config['tabIndex'] : 0 );
	}

	/**
	 * Set tab index value.
	 *
	 * @param number|null $tabIndex Tab index value or null for no tab index
	 * @chainable
	 */
	public function setTabIndex( $tabIndex ) {
		$tabIndex = is_numeric( $tabIndex ) ? $tabIndex : null;

		if ( $this->tabIndex !== $tabIndex ) {
			$this->tabIndex = $tabIndex;
			$this->updateTabIndex();
		}

		return $this;
	}

	/**
	 * Update the tabIndex attribute, in case of changes to tabIndex or disabled
	 * state.
	 *
	 * @chainable
	 */
	public function updateTabIndex() {
		$disabled = $this->element->isDisabled();
		if ( $this->tabIndex !== null ) {
			$this->target->setAttributes( array(
				// Do not index over disabled elements
				'tabindex' => $disabled ? -1 : $this->tabIndex,
				// ChromeVox and NVDA do not seem to inherit this from parent elements
				'aria-disabled' => ( $disabled ? 'true' : 'false' )
			) );
		} else {
			$this->target->removeAttributes( array( 'tabindex', 'aria-disabled' ) );
		}
		return $this;
	}

	/**
	 * Get tab index value.
	 *
	 * @return number|null Tab index value
	 */
	public function getTabIndex() {
		return $this->tabIndex;
	}

	public function getConfig( &$config ) {
		if ( $this->tabIndex !== 0 ) {
			$config['tabIndex'] = $this->tabIndex;
		}
		return parent::getConfig( $config );
	}
}