Sync up with Parsoid parserTests.txt
[mediawiki.git] / includes / pager / TablePager.php
blob487c85813d8236a0fc9d12e67c6a3c732e57488b
1 <?php
2 /**
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
18 * @file
21 use MediaWiki\Linker\LinkRenderer;
23 /**
24 * Table-based display with a user-selectable sort order
26 * @stable to extend
27 * @ingroup Pager
29 abstract class TablePager extends IndexPager {
30 /** @var string */
31 protected $mSort;
33 /** @var stdClass */
34 protected $mCurrentRow;
36 /**
37 * @stable to call
39 * @param IContextSource|null $context
40 * @param LinkRenderer|null $linkRenderer
42 public function __construct( IContextSource $context = null, LinkRenderer $linkRenderer = null ) {
43 if ( $context ) {
44 $this->setContext( $context );
47 $this->mSort = $this->getRequest()->getText( 'sort' );
48 if ( !array_key_exists( $this->mSort, $this->getFieldNames() )
49 || !$this->isFieldSortable( $this->mSort )
50 ) {
51 $this->mSort = $this->getDefaultSort();
53 if ( $this->getRequest()->getBool( 'asc' ) ) {
54 $this->mDefaultDirection = IndexPager::DIR_ASCENDING;
55 } elseif ( $this->getRequest()->getBool( 'desc' ) ) {
56 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
57 } /* Else leave it at whatever the class default is */
59 // Parent constructor needs mSort set, so we call it last
60 parent::__construct( null, $linkRenderer );
63 /**
64 * Get the formatted result list. Calls getStartBody(), formatRow() and getEndBody(), concatenates
65 * the results and returns them.
67 * Also adds the required styles to our OutputPage object (this means that if context wasn't
68 * passed to constructor or otherwise set up, you will get a pager with missing styles).
70 * This method has been made 'final' in 1.24. There's no reason to override it, and if there exist
71 * any subclasses that do, the style loading hack is probably broken in them. Let's fail fast
72 * rather than mysteriously render things wrong.
74 * @deprecated since 1.24, use getBodyOutput() or getFullOutput() instead
75 * @return string
77 final public function getBody() {
78 return parent::getBody();
81 /**
82 * Get the formatted result list.
84 * Calls getBody() and getModuleStyles() and builds a ParserOutput object. (This is a bit hacky
85 * but works well.)
87 * @since 1.24
88 * @return ParserOutput
90 public function getBodyOutput() {
91 $body = parent::getBody();
93 $pout = new ParserOutput;
94 $pout->setText( $body );
95 return $pout;
98 /**
99 * Get the formatted result list, with navigation bars.
101 * Calls getBody(), getNavigationBar() and getModuleStyles() and
102 * builds a ParserOutput object. (This is a bit hacky but works well.)
104 * @since 1.24
105 * @return ParserOutput
107 public function getFullOutput() {
108 $navigation = $this->getNavigationBar();
109 $body = parent::getBody();
111 $pout = new ParserOutput;
112 $pout->setText( $navigation . $body . $navigation );
113 $pout->addModuleStyles( $this->getModuleStyles() );
114 return $pout;
118 * @stable to override
119 * @return string
121 protected function getStartBody() {
122 $sortClass = $this->getSortHeaderClass();
124 $s = '';
125 $fields = $this->getFieldNames();
127 // Make table header
128 foreach ( $fields as $field => $name ) {
129 if ( strval( $name ) == '' ) {
130 $s .= Html::rawElement( 'th', [], "\u{00A0}" ) . "\n";
131 } elseif ( $this->isFieldSortable( $field ) ) {
132 $query = [ 'sort' => $field, 'limit' => $this->mLimit ];
133 $linkType = null;
134 $class = null;
136 if ( $this->mSort == $field ) {
137 // The table is sorted by this field already, make a link to sort in the other direction
138 // We don't actually know in which direction other fields will be sorted by default…
139 if ( $this->mDefaultDirection == IndexPager::DIR_DESCENDING ) {
140 $linkType = 'asc';
141 $class = "$sortClass mw-datatable-is-sorted mw-datatable-is-descending";
142 $query['asc'] = '1';
143 $query['desc'] = '';
144 } else {
145 $linkType = 'desc';
146 $class = "$sortClass mw-datatable-is-sorted mw-datatable-is-ascending";
147 $query['asc'] = '';
148 $query['desc'] = '1';
152 $link = $this->makeLink( htmlspecialchars( $name ), $query, $linkType );
153 $s .= Html::rawElement( 'th', [ 'class' => $class ], $link ) . "\n";
154 } else {
155 $s .= Html::element( 'th', [], $name ) . "\n";
159 $ret = Html::openElement( 'table', [
160 'class' => $this->getTableClass() ]
162 $ret .= Html::rawElement( 'thead', [], Html::rawElement( 'tr', [], "\n" . $s . "\n" ) );
163 $ret .= Html::openElement( 'tbody' ) . "\n";
165 return $ret;
169 * @stable to override
170 * @return string
172 protected function getEndBody() {
173 return "</tbody></table>\n";
177 * @return string
179 protected function getEmptyBody() {
180 $colspan = count( $this->getFieldNames() );
181 $msgEmpty = $this->msg( 'table_pager_empty' )->text();
182 return Html::rawElement( 'tr', [],
183 Html::element( 'td', [ 'colspan' => $colspan ], $msgEmpty ) );
187 * @stable to override
188 * @param stdClass $row
189 * @return string HTML
191 public function formatRow( $row ) {
192 $this->mCurrentRow = $row; // In case formatValue etc need to know
193 $s = Html::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n";
194 $fieldNames = $this->getFieldNames();
196 foreach ( $fieldNames as $field => $name ) {
197 $value = $row->$field ?? null;
198 $formatted = strval( $this->formatValue( $field, $value ) );
200 if ( $formatted == '' ) {
201 $formatted = "\u{00A0}";
204 $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n";
207 $s .= Html::closeElement( 'tr' ) . "\n";
209 return $s;
213 * Get a class name to be applied to the given row.
215 * @stable to override
217 * @param stdClass $row The database result row
218 * @return string
220 protected function getRowClass( $row ) {
221 return '';
225 * Get attributes to be applied to the given row.
227 * @stable to override
229 * @param stdClass $row The database result row
230 * @return array Array of attribute => value
232 protected function getRowAttrs( $row ) {
233 return [ 'class' => $this->getRowClass( $row ) ];
237 * @return stdClass
239 protected function getCurrentRow() {
240 return $this->mCurrentRow;
244 * Get any extra attributes to be applied to the given cell. Don't
245 * take this as an excuse to hardcode styles; use classes and
246 * CSS instead. Row context is available in $this->mCurrentRow
248 * @stable to override
250 * @param string $field The column
251 * @param string $value The cell contents
252 * @return array Array of attr => value
254 protected function getCellAttrs( $field, $value ) {
255 return [ 'class' => 'TablePager_col_' . $field ];
259 * @inheritDoc
260 * @stable to override
262 public function getIndexField() {
263 return $this->mSort;
267 * TablePager relies on `mw-datatable` for styling, see T214208
269 * @stable to override
270 * @return string
272 protected function getTableClass() {
273 return 'mw-datatable';
277 * @stable to override
278 * @return string
280 protected function getNavClass() {
281 return 'TablePager_nav';
285 * @stable to override
286 * @return string
288 protected function getSortHeaderClass() {
289 return 'TablePager_sort';
293 * A navigation bar with images
295 * @stable to override
296 * @return string HTML
298 public function getNavigationBar() {
299 if ( !$this->isNavigationBarShown() ) {
300 return '';
303 $this->getOutput()->enableOOUI();
305 $types = [ 'first', 'prev', 'next', 'last' ];
307 $queries = $this->getPagingQueries();
309 $buttons = [];
311 $title = $this->getTitle();
313 foreach ( $types as $type ) {
314 $buttons[] = new \OOUI\ButtonWidget( [
315 // Messages used here:
316 // * table_pager_first
317 // * table_pager_prev
318 // * table_pager_next
319 // * table_pager_last
320 'classes' => [ 'TablePager-button-' . $type ],
321 'flags' => [ 'progressive' ],
322 'framed' => false,
323 'label' => $this->msg( 'table_pager_' . $type )->text(),
324 'href' => $queries[ $type ] ?
325 $title->getLinkURL( $queries[ $type ] + $this->getDefaultQuery() ) :
326 null,
327 'icon' => $type === 'prev' ? 'previous' : $type,
328 'disabled' => $queries[ $type ] === false
329 ] );
331 return new \OOUI\ButtonGroupWidget( [
332 'classes' => [ $this->getNavClass() ],
333 'items' => $buttons,
334 ] );
338 * @inheritDoc
340 public function getModuleStyles() {
341 return array_merge(
342 parent::getModuleStyles(), [ 'oojs-ui.styles.icons-movement' ]
347 * Get a "<select>" element which has options for each of the allowed limits
349 * @param string[] $attribs Extra attributes to set
350 * @return string HTML fragment
352 public function getLimitSelect( $attribs = [] ) {
353 $select = new XmlSelect( 'limit', false, $this->mLimit );
354 $select->addOptions( $this->getLimitSelectList() );
355 foreach ( $attribs as $name => $value ) {
356 $select->setAttribute( $name, $value );
358 return $select->getHTML();
362 * Get a list of items to show in a "<select>" element of limits.
363 * This can be passed directly to XmlSelect::addOptions().
365 * @since 1.22
366 * @return array
368 public function getLimitSelectList() {
369 # Add the current limit from the query string
370 # to avoid that the limit is lost after clicking Go next time
371 if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) {
372 $this->mLimitsShown[] = $this->mLimit;
373 sort( $this->mLimitsShown );
375 $ret = [];
376 foreach ( $this->mLimitsShown as $key => $value ) {
377 # The pair is either $index => $limit, in which case the $value
378 # will be numeric, or $limit => $text, in which case the $value
379 # will be a string.
380 if ( is_int( $value ) ) {
381 $limit = $value;
382 $text = $this->getLanguage()->formatNum( $limit );
383 } else {
384 $limit = $key;
385 $text = $value;
387 $ret[$text] = $limit;
389 return $ret;
393 * Get \<input type="hidden"\> elements for use in a method="get" form.
394 * Resubmits all defined elements of the query string, except for a
395 * exclusion list, passed in the $noResubmit parameter.
397 * @param array $noResubmit Parameters from the request query which should not be resubmitted
398 * @return string HTML fragment
400 public function getHiddenFields( $noResubmit = [] ) {
401 $noResubmit = (array)$noResubmit;
402 $query = $this->getRequest()->getQueryValues();
403 foreach ( $noResubmit as $name ) {
404 unset( $query[$name] );
406 $s = '';
407 foreach ( $query as $name => $value ) {
408 $s .= Html::hidden( $name, $value ) . "\n";
410 return $s;
414 * Get a form containing a limit selection dropdown
416 * @return string HTML fragment
418 public function getLimitForm() {
419 return Html::rawElement(
420 'form',
422 'method' => 'get',
423 'action' => wfScript(),
425 "\n" . $this->getLimitDropdown()
426 ) . "\n";
430 * Gets a limit selection dropdown
432 * @return string
434 private function getLimitDropdown() {
435 # Make the select with some explanatory text
436 $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped();
438 return $this->msg( 'table_pager_limit' )
439 ->rawParams( $this->getLimitSelect() )->escaped() .
440 "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" .
441 $this->getHiddenFields( [ 'limit' ] );
445 * Return true if the named field should be sortable by the UI, false
446 * otherwise
448 * @param string $field
449 * @return bool
451 abstract protected function isFieldSortable( $field );
454 * Format a table cell. The return value should be HTML, but use an empty
455 * string not &#160; for empty cells. Do not include the <td> and </td>.
457 * The current result row is available as $this->mCurrentRow, in case you
458 * need more context.
460 * @param string $name The database field name
461 * @param string|null $value The value retrieved from the database, or null if
462 * the row doesn't contain this field
464 abstract public function formatValue( $name, $value );
467 * The database field name used as a default sort order.
469 * Note that this field will only be sorted on if isFieldSortable returns
470 * true for this field. If not (e.g. paginating on multiple columns), this
471 * should return empty string, and getIndexField should be overridden.
473 * @return string
475 abstract public function getDefaultSort();
478 * An array mapping database field names to a textual description of the
479 * field name, for use in the table header. The description should be plain
480 * text, it will be HTML-escaped later.
482 * @return string[]
484 abstract protected function getFieldNames();