| 1 |
<?php |
| 2 |
|
| 3 |
namespace OOUI; |
| 4 |
|
| 5 |
/** |
| 6 |
* OptionWidgets are special elements that can be selected and configured with data. The |
| 7 |
* data is often unique for each option, but it does not have to be. |
| 8 |
* |
| 9 |
* OptionWidgets are used SelectWidget to create a selection of mutually exclusive options. |
| 10 |
*/ |
| 11 |
class OptionWidget extends Widget { |
| 12 |
|
| 13 |
use LabelElement; |
| 14 |
use FlaggedElement; |
| 15 |
use AccessKeyedElement; |
| 16 |
use TitledElement; |
| 17 |
|
| 18 |
/** |
| 19 |
* @var bool |
| 20 |
*/ |
| 21 |
protected $selected; |
| 22 |
|
| 23 |
/** |
| 24 |
* @param array $config Configuration options |
| 25 |
* - bool $config['selected'] Whether to mark the option as selected |
| 26 |
*/ |
| 27 |
public function __construct( array $config = [] ) { |
| 28 |
parent::__construct( $config ); |
| 29 |
|
| 30 |
$this->initializeFlaggedElement( $config ); |
| 31 |
$this->initializeTitledElement( array_merge( [ 'titled' => $this ], $config ) ); |
| 32 |
$this->initializeAccessKeyedElement( array_merge( [ 'accessKeyed' => $this ], $config ) ); |
| 33 |
$this->initializeLabelElement( $config ); |
| 34 |
|
| 35 |
$this->appendContent( $this->label ); |
| 36 |
|
| 37 |
$this->setSelected( $config['selected'] ?? false ); |
| 38 |
|
| 39 |
$this->addClasses( [ 'oo-ui-optionWidget' ] ); |
| 40 |
$this->setAttributes( [ |
| 41 |
'role' => 'option' |
| 42 |
] ); |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Set the selected state of the option |
| 47 |
* |
| 48 |
* @param bool $selected The options is selected |
| 49 |
* @return $this |
| 50 |
*/ |
| 51 |
public function setSelected( bool $selected ) { |
| 52 |
$this->selected = $selected; |
| 53 |
$this->toggleClasses( [ 'oo-ui-optionWidget-selected' ], $selected ); |
| 54 |
$this->setAttributes( [ |
| 55 |
// 'selected' is not a config option, so set aria-selected false by default (same as js) |
| 56 |
'aria-selected' => $selected ? 'true' : 'false', |
| 57 |
] ); |
| 58 |
return $this; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* @return bool |
| 63 |
*/ |
| 64 |
public function isSelected() { |
| 65 |
return $this->selected; |
| 66 |
} |
| 67 |
|
| 68 |
/** @inheritDoc */ |
| 69 |
public function getConfig( &$config ) { |
| 70 |
if ( $this->selected ) { |
| 71 |
$config['selected'] = $this->selected; |
| 72 |
} |
| 73 |
return parent::getConfig( $config ); |
| 74 |
} |
| 75 |
} |