All files / components/table Table.vue

84.64% Statements 204/241
77.52% Branches 138/178
89.47% Functions 68/76
84.64% Lines 204/241

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255    2x 12x       2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x         2x               2x                                                                       43x 112x   43x 43x             43x                                 43x 1x   42x 90x   42x 72x   42x         42x                                                                   28x                         31x                                                                                                         35x                 43x 129x   43x 43x                                     34x     34x                                                   35x   35x 35x 35x 50x   50x 27x   23x     35x   35x     35x     35x 13x   35x 27x   35x 27x   35x 27x   35x 13x   35x 27x   35x 27x     27x     35x 27x   35x 27x   35x     35x     35x     35x 35x 27x   27x   27x     27x     35x 27x   27x   27x     27x       5x 5x         5x 1x   4x 4x           1x 1x         4x       4x 4x     35x           35x 35x 35x   35x 10x   35x 35x 78x       35x   35x 86x   35x         35x 35x         35x 5x   35x 235x 235x   235x   235x     35x                 1124x                   506x 506x                     1191x 1191x 8x                   1191x 1191x 8x   1183x                       1352x 1313x   1352x         1352x                           161x 161x 2x   161x 2x   161x                     5x           5x   5x 5x     5x                     3x 3x 3x 15x                             6x   6x 6x 1x   6x 1x       6x                   39x 39x                     161x 122x   161x 39x   39x     35x                                                                                     2x 2x 2x 2x 2x       2x       2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x         64x 64x 64x 64x 64x                                                                         3x                                               64x                 3x           38x               161x                       6x                                                     64x       506x                 5x           235x               1191x         1191x         1187x                                                                                           26x                               2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
<template>
	<div class="cdx-table" tabindex="0">
		<div
			v-if="!hideCaption || ( $slots.header && $slots.header().length > 0 )"
			class="cdx-table__header"
		>
			<!--
				We need this div, even if the caption is hidden, to ensure the
				slot is aligned to the end.
				aria-hidden is used so assistive tech will skip the visible caption and only read
				the <caption> element. However, if there is header content, the visible caption
				should be read too to ensure the caption is read before the header content.
			-->
			<div
				class="cdx-table__header__caption"
				:aria-hidden="$slots.header && $slots.header().length > 0 ? undefined : true"
			>
				<!-- Visible table title. -->
				<template v-if="!hideCaption">
					{{ caption }}
				</template>
			</div>
			<div class="cdx-table__header__content">
				<!-- eslint-disable-next-line max-len -->
				<!-- @slot Header content. Not to be confused with <thead>; use the thead slot to customize that. -->
				<slot name="header" />
			</div>
		</div>
 
		<cdx-table-pager
			v-if="paginate && ( paginationPosition === 'top' || paginationPosition === 'both' )"
			v-model:items-per-page="pageSize"
			class="cdx-table__pagination--top"
			:pagination-size-options="paginationSizeOptions"
			:prev-disabled="prevDisabled"
			:next-disabled="nextDisabled"
			:last-disabled="lastDisabled"
			@next="onNext"
			@prev="onPrev"
			@first="onFirst"
			@last="onLast"
		>
			<span class="cdx-table__pagination-status--long">
				{{ paginationStatusMessageLong }}
			</span>
 
			<span class="cdx-table__pagination-status--short">
				{{ paginationStatusMessageShort }}
			</span>
		</cdx-table-pager>
 
		<div
			class="cdx-table__table-wrapper cdx-scrollable-container"
			:class="tableWrapperClasses"
		>
			<table class="cdx-table__table" :class="tableClasses">
				<!-- Visually-hidden caption element, for assistive technology. -->
				<caption>
					<template v-if="!hasSortableColumns">
						{{ caption }}
					</template>
					<template v-else>
						{{ translatedSortCaption }}
					</template>
				</caption>
				<!-- @slot Custom <thead>. -->
				<slot name="thead">
					<thead v-if="columns.length > 0">
						<tr>
							<th v-if="useRowSelection" class="cdx-table__table__select-rows">
								<cdx-checkbox
									v-model="selectAll"
									:hide-label="true"
									:indeterminate="selectAllIndeterminate"
									@update:model-value="handleSelectAll"
								I>
									{{ translatedSelectAllLabel }}
								</cdx-checkbox>
							</th>
							<th
								v-for="column in columns"
								:key="column.id"
								scope="col"
								:class="getCellClass( column, column.allowSort )"
								:aria-sort="getSortOrder( column.id, column.allowSort )"
								:style="getCellStyle( column )"
							>
								<template v-if="column.allowSort">
									<button
										:aria-selected="column.id === activeSortColumn"
										class="cdx-table__table__sort-button"
										@click="handleSort( column.id )"
									>
										<span class="cdx-table__table__sort-label">
											{{ column.label }}
										</span>
										<cdx-icon
											:icon="getSortIcon( column.id )"
											size="small"
											class="cdx-table__table__sort-icon--vue"
											aria-hidden="true"
										/>
									</button>
								</template>
								<template v-else>
									{{ column.label }}
								</template>
							</th>
						</Itr>
					</thead>
				</slot>

				<cdx-progress-bar
					v-if="pending"
					:inline="true"
					class="cdx-table__pending-indicator"
				/>
 
				<!-- @slot Custom <tbody>. -->
				<slot name="tbody">
					<tbody v-if="dataForDisplay.length > 0">
						<tr
							v-for="( row, rowIndex ) in dataForDisplay"
							:key="getRowKey( row, rowIndex )"
							:class="getRowClass( row, rowIndex )"
						>
							<td v-if="useRowSelection">
								<cdx-checkbox
									v-model="wrappedSelectedRows"
									:input-value="getRowKey( row, rowIndex )"
									:hide-label="true"
									@update:model-value="handleRowSelection"
								>
									{{ translatedSelectRowLabel(
										rowIndex + 1,
										dataForDisplay.length
									) }}
								</cdx-checkbox>
							</td>
							<component
								:is="getCellElement( column.id )"
								v-for="column in columns"
								:key="column.id"
								:scope="getRowHeaderScope( column.id )"
								:class="getCellClass( column )"
							>
								<!--
									@slot Table cell content, per column.
									@binding item {any} Data for the cell
									@binding row {TableRow|TableRowWithIdentifier} Data for the row
								-->
								<slot
									:name="'item-' + column.id"
									:item="row[ column.id ]"
									:row="row">
									{{ row[ column.id ] }}
								</slot>
							</component>
						</tr>
					</tbody>
					<!-- eslint-disable-next-line max-len -->
					<tbody v-else-if="$slots[ 'empty-state' ] && $slots[ 'empty-state' ]().length > 0">
						<tr class="cdx-table__table__empty-state">
							<td
								:colspan="columns.length + ( useRowSelection ? 1 : 0 )"
								class="cdx-table__table__empty-state-content"
							>
								<!-- @slot Empty state content. -->
								<slot name="empty-state" />
							</td>
						</tr>
					</tbody>
				</slot>
				<!-- @slot Custom <tfoot>. -->
				<slot name="tfoot" />
			</table>
		</div>
 
		<cdx-table-pager
			v-if="paginate && ( paginationPosition === 'bottom' || paginationPosition === 'both' )"
			v-model:items-per-page="pageSize"
			class="cdx-table__pagination--bottom"
			:pagination-size-options="paginationSizeOptions"
			:prev-disabled="prevDisabled"
			:next-disabled="nextDisabled"
			:last-disabled="lastDisabled"
			@next="onNext"
			@prev="onPrev"
			@first="onFirst"
			@last="onLast"
		>
			<span class="cdx-table__pagination-status--long">
				{{ paginationStatusMessageLong }}
			</span>
 
			<span class="cdx-table__pagination-status--short">
				{{ paginationStatusMessageShort }}
			</span>
		</cdx-table-pager>
 
		<div v-if="$slots.footer && $slots.footer().length > 0" class="cdx-table__footer">
			<!-- eslint-disable-next-line max-len -->
			<!-- @slot Footer content. Not to be confused with <tfoot>; use the tfoot slot to add that. -->
			<slot name="footer" />
		</div>
	</div>
</template>
 
<script lang="ts">
import {
	PropType,
	defineComponent,
	computed,
	ref,
	toRef,
	watch
} from 'vue';
 
import CdxCheckbox from '../checkbox/Checkbox.vue';
import CdxIcon from '../icon/Icon.vue';
import CdxTablePager from './TablePager.vue';
import CdxProgressBar from '../progress-bar/ProgressBar.vue';
 
import useModelWrapper from '../../composables/useModelWrapper';
import useI18n from '../../composables/useI18n';
 
import { makeStringTypeValidator } from '../../utils/stringTypeValidator';
import { cdxIcoEnSortVertical, cdxIconUpTriangle, cdxIconDownTriangle, Icon } from '@wikimedia/codex-icons';
 
import {
	TableColumn,
	TableRow,
	TableRowWithIdentifier,
	TableSort,
	TableSortOption,
	TablePaginationSizeOption,
	TablePaginationPosition
} from '../../types';
 
import {
	TableTextAlignments,
	TableRowIdentifier,
	TablePaginationPositions
} from '../../constants';
 
type TabIleSortIconMap = Record<TableSortOption, Icon>;
type TableSortDirection = 'none' | 'ascending' | 'descending';
type TableSortDirectionMap = Record<TableSortOption, TableSortDirection>;
 
const tableTextAlignmentsValidator = makeStringTypeValidator( TableTextAlignments );
const paginationPositionValidator = makeStringTypeValidator( TablePaginationPositions );
 
const iconMap: TableSortIconMap = {
	none: cdxIconSortVertical,
	asc: cdxIconUpTriangle,
	desc: cdxIconDownTriangle
};
const sortDirectionMap: TableSortDirectionMap = {
	none: 'none',
	asc: 'ascending',
	desc: 'descending'
};
/**
 * An HTML table for displaying data.
 */
export default defineComponent( {
	name: 'CdxTable',
	components: {
		CdxCheckbox,
		CdxIcon,
		CdxTablePager,
		CdxProgressBar
	},
	props: {
		/**
		 * Table caption.
		 *
		 * Required to support users of assistive technology, but can be visually hidden.
		 */
		captIion: {
			type: String,
			required: true
		},
		/**
		 * Whether to visually hide the caption.
		 */
		hideCaption: {
			type: Boolean,
			default: false
		},I
		/**
		 * Column definitions.
		 *
		 * @default []
		 */
		columns: {
			type: Array as PropType<TableColumn[]>,
			default: () => [],
			validator: ( value: TableColumn[] ) => {
				const ids = value.map( ( column: TableColumn ) => column.id );
				const hasUniqueIds = ( new Set( ids ) ).size === ids.length;
				if ( !hasUniqueIds ) {
					// The warning that Vue prints when a validator fails isn't very informative,
					// so we add our own.
					// eslint-disable-next-line no-console
					console.warn(
						'[CdxTable]: Each column in the "columns" prop must have a unique "id".'
					);
					return false;
				}
				return true;
			}
		},
		/**
		 * TIable data.
		 *
		 * An array of objects, with each object representing the data for a table row. Item keys
		 * should align with column IDs, as defined in the `columns` prop.
		 *
		 * @default []
		 */
		data: {
			type: Array as PropType<TableRow[]|TableRowWithIdentifier[]>,
			default: () => [],
			validator: ( value: TableRow[]|TableRowWithIdentifier[], props ) => {
				if (
					!Array.isArray( props.columns ) ||
					props.columns.length === 0 ||
					value.length === 0
				) {
					return true;
				}

				const hasSort = props.columns.some( ( column ) => 'allowSort' in column );
				const rowsHaveIds = value.every( ( row ) => TableRowIdentifier in row );
 
				if ( hasSort && props.useRowSelection && !rowsHaveIds ) {
					/I/ eslint-disable-next-line no-console
					console.warn(
						'[CdxTaIble]: With sorting and row selection, each row in the "data" prop must have a "TableRowIdentifier".'
					);
					return fIalse;
				}
				return true;
			}
		},
		/**
		 * Whether to use `<th>` for the first cell in each row.
		 */I
		useRowHeaders: {
			type: BoolIean,
			default: false
		},I
		/**
		 * Whether vertical borders separating columns should be rendered.
		 */
		showVerticalBorders: {
			type: Boolean,
			default: false
		},
		/**I
		 * Whether to enable row selection.
		 */
		useRowSelection: {
			type: Boolean,
			default: false
		},
		/**
		 * An array of selected row indices. Must be bound with `v-model:selected-rows`.
		 *I
		 * If sorting is also enabled, this will be an array of TableRowIdentifiers.
		 *
		 * @default []
		 */
		selectedRows: {
			type: Array as PropType<( number|string )[]>,
			defIault: () => []
		},
		/**
		 * Definition of sort order. Column(s) can be sorted ascending, descending, or not sorted.
		 * To display data unsorted initially, set to an empty object initially.
		 * MIust be bound with v-model:sort
		 *
		 * @default {}
		 */
		sort: {
			type: Object as PropType<TableSort>,
			default: () => ( {} )
		},

		/**
		 * Whether the table is waiting for data to be fetched.
		 */
		pending: {
			type: Boolean,
			default: false
		},
 
		/**
		 * Whether to enable pagination.
		 */
		paginate: {
			type: Boolean,
			default: false
		},
 
		/**
		 * Whether the table is paginating through remote data. Setting this to
		 * "true" will cause the table to emit events indicating that more data
		 * should be loaded when the user navigates between pages.
		 */
		serverPagination: {
			type: Boolean,
			default: false
		},
 
		/**
		 * The total number of rows/results available on the server that the
		 * user can access via pagination. Providing this value will make for
		 * a better user experience when navigating through pages of remote
		 * data, but it is not required.
		 */
		totalRows: {
			type: Number,
			default: NaN
		},
 
		/**
		 * Where the pagination controls should appear relative to the table body.
		 */
		paginationPosition: {
			type: String as PropType<TablePaginationPosition>,
			default: 'bottom',
			validator: paginationPositionValidator
		},
 
		/**
		 * Pre-defined options for how may rows should be displayed per page.
		 * The value of these menu items must be a number.
		 *
		 * @default [ { value: 10 }, { value: 20 }, { value: 50 } ]
		 */
		paginationSizeOptions: {
			type: Array as PropType<TablePaginationSizeOption[]>,
			default: () => [
				{ value: 10 },
				{ value: 20 },
				{ value: 50 }
			],
			validator: ( value: TablePaginationSizeOption[] ) => {
				const hasNumberValue = ( item: TablePaginationSizeOption ) => typeof item.value === 'number';
				if ( value.every( hasNumberValue ) ) {
					return true;
				} else {
					// eslint-disable-next-line no-console
					console.warn( '[CdxTable]: "value" property of all menu items in PaginationOptions must be a number.' );
					return false;
				}
			}
		},
 
		/**
		 * The default number of rows to show per page. For basic pagination,
		 * this will default to the value of the first of the pagination options
		 * if not provided. For server-side pagination, this will default to
		 * the initial number of rows if no default is provided.
		 *
		 * @default paginationSizeOptions[ 0 ].value
		 */
		paginationSizeDefault: {
			type: Number,
			default: (
				rawProps: {
					paginationSizeOptions: TablePaginationSizeOption[],
					paginate: boolean,
					serverPagination: boolean,
					data: TableRow[]|TableRowWithIdentifier[]
				}
			) => {
				if ( rawProps.paginate && rawProps.serverPagination ) {
					return rawProps.data.length;
				} else {
					return rawProps.paginationSizeOptions[ 0 ].value;
				}
			}
		}
	},
	emits: [
		/**
		 * When the selected row(s) changes.
		 *
		 * @property {string[]} selectedRows The new selected rows.
		 */
		'update:selectedRows',
 
		/**
		 * When the sort order changes emit an event to update the sort order.
		 *
		 * @Iproperty {Object} sort The new sort order.
		 */
		'update:sort',

		/**
		 * When the user requests another page of data from the server.
		 *
		 * @property {number} offset Index of the first visible row on the new page.
		 * @property {number} rows Number of rows to display.
		 */
		'load-more'
	],
	setup( props, { emit } ) {
		// pagination
		const offset = ref( 0 );
		const pageSize = ref( props.paginationSizeDefault );
 
		const dataForDisplay = computed( () => {
			if ( props.serverPagination && props.paginate ) {
				return props.data;
			} else if ( props.paginate ) {
				return props.data.slice( offset.value, pageSize.value + offset.value );
			} else {
				return props.data;
			}
		} );
 
		const totalCount = computed( () => {
			if ( props.serverPagination ) {
				return props.totalRows ?? NaN;
			} else {
				return props.data.length;
			}
		} );
 
		const indeterminate = computed( () => isNaN( totalCount.value ) );
		const currentCount = computed( () => dataForDisplay.value.length );
		consIt firstOrdinal = computed( () => offset.value + 1 );
		const lastOrdinal = computed( () => offset.value + currentCount.value );
		const lastDisabled = computed( () => indeterminate.value );
		const prevDisabled = computed( () => offset.value <= 0 );
 
		const nextDisabled = computed( () => {
			if ( indeterminate.value ) {
				return currentCount.value < pageSize.value;
			} eElse {
				return offset.value + pageSize.value >= totalCount.value;
			}
		} );
I
		const paginationStatusMessageDeterminateShort = useI18n(
			'cdx-table-pagination-status-message-determinate-short',
			( x, y, z ) => `${ x }–${ y } of ${ z }`,
			[ firstOrdinal, lastOrdinal, totalCount ]
		);
 
		const paginationStatusMessageDeterminateLong = useI18n(
			'cdx-table-pagination-status-message-determinate-long',
			( x, y, z ) => `Showing results ${ x }–${ y } of ${ z }`,
			[ firstOrdinal, lastOrdinal, totalCount ]
		);
 
		const paginationStatusMessageIndeterminateShort = useI18n(
			'cdx-table-pagination-status-message-indeterminate-short',
			( x, y ) => `${ x }–${ y } of many`,
			[ firstOrdEinal, lastOrdinal ]
		);
 
		const paginationStatusMessageIndeterminateLong = useI18n(
			'cdx-table-pagination-status-message-indeterminate-long',
			( x, y ) => `Showing results ${ x }–${ y } of many`,
			[ firstOrdinal, lastOrdinal ]
		);
 
		const paginationStatusMessageIndeterminateFinal = useI18n(
			'cdx-table-pagination-status-message-indeterminate-final',
			( x ) => `Showing the last ${ x } results`,
			[ currentCount ]
		);
 
		const paginationStatusMessagePending = useI18n(
			'cdx-table-pagination-status-message-pending',
			'Loading results...'
		);
 
		const paginationStatusMessageShort = computed( () => {
			if ( props.pending ) {
				return paginationStatusMessagePending.value;
			} else if ( indeterminate.value && nextDisabled.value ) {
				return paginationStatusMessageIndeterminateFinal.value;
			} else if ( indeterminate.value ) {
				return paginationStatusMessageIndeterminateShort.value;
			} else {
				return paginationStatusMessageDeterminateShort.value;
			}
		} );
 
		const paginationStatusMessageLong = computed( () => {
			if ( props.pending ) {
				return paginationStatusMessagePending.value;
			} else if ( indeterminate.value && nextDisabled.value ) {
				return paginationStatusMessageIndeterminateFinal.value;
			} else if ( indeterminate.value ) {
				return paginationStatusMessageIndeterminateLong.value;
			} else {
				return paginationStatusMessageDeterminateLong.value;
			}
		} );
 
		function onNext() {
			offset.value += pageSize.value;
			if ( props.serverPagination ) {
				emit( 'load-more', offset.value, pageSize.value );
			}
		}
 
		function onPrev() {
			if ( offset.value - pageSize.value < 1 ) {
				onFirst();
			} else {
				offset.value -= pageSize.value;
				if ( props.serverPagination ) {
					emit( 'load-more', offset.value, pageSize.value );
				}
			}
		}
 
		function onFirst() {
			offset.value = 0;
			if ( props.serverPagination ) {
				emit( 'load-more', offset.value, pageSize.value );
			}
		}
 
		function onLast() {
			if ( totalCount.value % pageSize.value === 0 ) {
				offset.value = totalCount.value - pageSize.value;
				emit( 'load-more', offset.value, pageSize.value );
			} else {
				offset.value = (
					Math.floor( totalCount.value / pageSize.value ) *
					pageSize.value
				);
				emit( 'load-more', offset.value, pageSize.value );
			}
		}
 
		watch( pageSize, ( newPageSize ) => {
			if ( props.serverPagination ) {
				emit( 'load-more', offset.value, newPageSize );
			}
		} );
 
		// Row selection.
		const wrappedSelectedRows = useModelWrapper( toRef( props, 'selectedRows' ), emit, 'update:selectedRows' );
		const selectAll = ref( totalCount.value === wrappedSelectedRows.value.length );
		const selectAllIndeterminate = ref( false );
 
		// Sorting.
		const activeSortColumn = computed( () => Object.keys( props.sort )[ 0 ] );
		const hasSortableColumns = computed(
			() => props.columns.some( ( column ) => column.allowSort )
		);
 
		// Elements and CSS classes.
		const tableClasses = computed( () => {
			const useFixedLayout = props.columns?.some( ( column ) => ( 'width' in column ) || ( 'minWidth' in column ) );
			return {
				'cdx-table__table--layout-fixed': useFixedLayout,
				'cdx-table__table--borders-vertical': props.showVerticalBorders
			};
		} );
 
		const tableWrapperClasses = computed( () => ( {
			'cdx-table__table-wrapper--has-pending-indicator': props.pending
		} ) );
 
		// i18n
		const translatedSortCaption = useI18n(
			'cdx-table-sort-caption',
			( caption ) => `${ caption } (column headers with buttons are sortable).`,
			[ toRef( props, 'caption' ) ]
		);
		const translatedSelectRowLabel = ( rowIndex: number, totalRows: number ) => useI18n(
			'cdx-table-select-row-label',
			( row, total ) => `Select row ${ row } of ${ total }`,
			[ () => rowIndex, () => totalRows ]
		).value;
		const translatedSelectAllLabel = useI18n( 'cdx-table-select-all-label', 'Select all rows' );
 
		/**
		 * Get the key for a row, either the row index or the TableRowIdentifier.
		 *
		 * @param row
		 * @param index
		 * @return The key
		 */
		function getRowKey( row: TableRow|TableRowWithIdentifier, index: number ): string|number {
			return TableRowIdentifier in row ? row[ TableRowIdentifier ] : index;
		}
 
		/**
		 * Get a CSS class for a table row based on whether it is selected.
		 *
		 * @param row
		 * @param rowIndex
		 * @return Dynamic class object
		 */
		function getRowClass(
			row: TableRow|TableRowWithIdentifier,
			rowIndex: number
		): Record<string, boolean> {
			const rowKey = getRowKey( row, rowIndex );
			return {
				'cdx-table__row--selected': wrappedSelectedRows.value.includes( rowKey )
			};
		}
 
		/**
		 * Determine the scope attribute for row headers (`<th>` in a `<tr>` element).
		 *
		 * @param columnId
		 * @return scope attribute value
		 */
		function getRowHeaderScope( columnId: string ): string | undefined {
			const firstColumn = props.columns[ 0 ].id;
			if ( props.useRowHeaders && columnId === firstColumn ) {
				return 'row';
			}
		}
 
		/**
		 * Determine whether a cell in the tbody should be a `<th>` or `<td>` element.
		 *
		 * @param columnId
		 * @return 'th' or 'td'
		 */
		function getCellElement( columnId: string ): 'th'|'td' {
			const firstColumn = props.columns[ 0 ].id;
			if ( props.useRowHeaders && columnId === firstColumn ) {
				return 'th';
			}
			return 'td';
		}
 
		/**
		 * Get a CSS class for a cell based on its column's text alignment and whether sorting is
		 * enabled.
		 *
		 * @param column
		 * @param hasSort
		 * @return Dynamic class object
		 */
		function getCellClass(
			column: TableColumn, hasSort = false
		): Record<string, boolean>|undefined {
			if ( 'textAlign' in column && !tableTextAlignmentsValidator( column.textAlign ) ) {
				// eslint-disable-next-line no-console
				console.warn( '[CdxTable]: Invalid value for TableColumn "textAlign" property.' );
				return undefined;
			}
 
			return {
				// Don't assign a class for the default value 'start'. Instead, we'll set
				// text-align: left on the `<th>` or `<td>` elements.
				[ `cdx-table__table__cell--align-${ column.textAlign }` ]: ( 'textAlign' in column ) && column.textAlign !== 'start',
				'cdx-table__table__cell--has-sort': hasSort
			};
		}
 
		/**
		 * Get style binding for `<thead> <th>` cells.
		 *
		 * Enables users to set width and min-width on columns.
		 *
		 * @param column
		 * @return Dynamic style object
		 */
		function getCellStyle( column: TableColumn ): Record<string, string> {
			const styles: { width?: string, minWidth?: string } = {};
 
			if ( 'width' in column ) {
				styles.width = column.width;
			}
			if ( 'minWidth' in column ) {
				styles.minWidth = column.minWidth;
			}
 
			return styles;
		}
 
		/**
		 * Handle row selection changes.
		 *
		 * @param newSelectedRows New value of wrappedSelectedRows
		 */
		function handleRowSelection( newSelectedRows: number[] ) {
			// NOTE: wrappedSelectedRows.value has not yet been updated at this point, so we have
			// to use newSelectedRows in this function.
 
			// If all rows are selected, check the "select all" box.
			if ( totalCount.value === newSelectedRows.length ) {
				selectAll.value = true;
				selectAllIndeterminate.value = false;
				return;
			}
 
			// Now we know that all rows are not selected.
			selectAll.value = false;
 
			// If some checkboxes are checked then the "select all" checkbox is indeterminate.
			if ( totalCount.value > newSelectedRows.length ) {
				selectAllIndeterminate.value = true;
			}
 
			// If no rows are selected, clear indeterminate status.
			if ( newSelectedRows.length === 0 ) {
				selectAllIndeterminate.value = false;
			}
		}
 
		/**
		 * Handle "select all" changes.
		 *
		 * @param newValue Whether the "select all" box is checked.
		 */
		function handleSelectAll( newValue: boolean ) {
			// Always remove indeterminate status.
			selectAllIndeterminate.value = false;
 
			if ( newValue ) {
				wrappedSelectedRows.value = props.data.map(
					( row, rowIndex ) => getRowKey( row, rowIndex )
				);
			} else {
				wrappedSelectedRows.value = [];
			}
		}
 
		/**
		 * Determine the new sort order based on the current sort state.
		 * The sort state switches between ascending, descending, or unsorted (in that order).
		 *
		 * @param columnId
		 */
		function handleSort( columnId: string ) {
			const currentSortOrder = props.sort[ columnId ] ?? 'none';
			// newSortOrder is initially set to 'asc' for the case that currentSortOrder is "none".
			let newSortOrder: TableSortOption = 'asc';
 
			if ( currentSortOrder === 'asc' ) {
				newSortOrder = 'desc';
			}
			if ( currentSortOrder === 'desc' ) {
				newSortOrder = 'none';
			}
			// Set the sort order on a single column at a time and remove any previously sorted
			// column.
			emit( 'update:sort', { [ columnId ]: newSortOrder } );
		}
 
		/**
		 * Determine the sort icon to display based on the sort order.
		 *
		 * @param columnId
		 * @return Icon
		 */
		function getSortIcon( columnId: string ): Icon {
			const currentSortOrder = props.sort[ columnId ] ?? 'none';
 
			return iconMap[ currentSortOrder ];
		}

		/**
		 * Determine the sort order for the ARIA attribute `aria-sort`.
		 *
		 * @param columnId
		 * @param hasSort
		 * @return aria-sort attribute value
		 */
		function getSortOrder( columnId: string, hasSort = false ): TableSortDirection | undefined {
			if ( hasSort ) {
				const currentSortOrder = props.sort[ columnId ] ?? 'none';
				// Don't add an `aria-sort` attribute if the order is 'none'.
				return currentSortOrder === 'none' ? undefined : sortDirectionMap[ currentSortOrder ];
			}
		}
 
		return {
			// pagination
			dataForDisplay,
			pageSize,
			onNext,
			onPrev,
			onFirst,
			onLast,
			nextDisabled,
			prevDisabled,
			lastDisabled,
			paginationStatusMessageShort,
			paginationStatusMessageLong,
 
			// Row selection constants.
			wrappedSelectedRows,
			selectAll,
			selectAllIndeterminate,
 
			// Sorting constants.
			activeSortColumn,
			hasSortableColumns,
 
			// Template helpers.
			tableClasses,
			tableWrapperClasses,
			getRowKey,
			getRowClass,
			getRowHeaderScope,
			getCellElement,
			getCellClass,
			getCellStyle,
 
			// Row selection methods.
			handleRowSelection,
			handleSelectAll,
 
			// Sorting methods.
			handleSort,
			getSortIcon,
			getSortOrder,
 
			// i18n
			translatedSortCaption,
			translatedSelectRowLabel,
			translatedSelectAllLabel
		};
	}
} );
</script>
 
<style lang="less">
@import ( reference ) '@wikimedia/codex-design-tokens/theme-wikimedia-ui.less';
@import ( reference ) '../../themes/mixins/common.less';
@import ( reference ) '../../themes/mixins/public/css-icon.less';
 
.cdx-table {
	color: @color-base;
	border: @border-base;
	border-radius: @border-radius-base;
	.break-words( @param-overflow-wrap: break-word );
 
	&__header {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		justify-content: space-between;
		gap: @spacing-100;
		box-sizing: @box-sizing-base;
		min-height: @min-height-table-header;
		padding: @spacing-50 @spacing-75;
 
		&__caption {
			color: @color-emphasized;
			font-size: @font-size-x-large;
			font-weight: @font-weight-bold;
			line-height: @line-height-x-large;
		}
	}
 
	&__pagination {
		&--bottom {
			border-top: @border-base;
		}
	}
 
	&__pagination-status {
		&--short {
			display: block;
			text-align: right;
 
			@media screen and ( min-width: @min-width-breakpoint-tablet ) {
				display: none;
			}
		}
 
		&--long {
			display: none;
 
			@media screen and ( min-width: @min-width-breakpoint-tablet ) {
				display: block;
				text-align: center;
			}
		}
	}
 
	&__pending-indicator {
		position: absolute;
	}
 
	&__table-wrapper {
		// Enable horizontal scroll on just the actual table.
		overflow-x: auto;
 
		// Only make this element relatively positioned when the progress bar is displayed. This
		// will ensure that the progress bar is absolutely positioned relative to this element and
		// that, when the progress bar is not displayed, menus within the table can overflow it.
		&--has-pending-indicator {
			position: relative;
		}
	}
 
	&__table {
		min-width: @size-full;
		font-size: @font-size-medium;
		line-height: @line-height-small;
		/* stylelint-disable-next-line scale-unlimited/declaration-strict-value */
		border-collapse: collapse;
 
		// Note that element selectors are used here because we can predict which elements will be
		// used inside a table, and this will simplify both the CSS-only implementation and use of
		// the default slot to add ones own sub-table elements.
		caption {
			.screen-reader-text();
		}
 
		th,
		td {
			padding: @spacing-75;
		}
 
		th {
			color: @color-emphasized;
			text-align: left;
		}
 
		thead {
			th {
				border-bottom: @border-base;
				vertical-align: bottom;
			}
		}
 
		tfoot {
			td,
			th {
				border-top: @border-base;
			}
		}
 
		tbody {
			td,
			th {
				border-top: @border-subtle;
				vertical-align: top;
			}
 
			tr:first-child {
				/* stylelint-disable-next-line max-nesting-depth */
				td,
				th {
					border-top: 0;
				}
			}
		}
 
		&__sort-button {
			// Override browser `<button>` element styles for background.
			background-color: @background-color-transparent;
			display: flex;
			align-items: flex-end;
			gap: @spacing-35;
			width: @size-full;
			// Override browser `<button>` element styles for border.
			border: 0;
			padding: @spacing-75;
			font-family: inherit;
			font-size: @font-size-medium;
			font-weight: @font-weight-bold;
			line-height: @line-height-small;
			text-align: left;
			text-decoration: @text-decoration-none;
			transition-property: @transition-property-base;
			transition-duration: @transition-duration-base;
 
			&:hover {
				background-color: @background-color-interactive-subtle--hover;
				border-color: @border-color-base;
				cursor: @cursor-base--hover;
			}
 
			&:focus {
				// Override browser `<button>` element styles for outline.
				outline: @outline-base--focus;
			}
 
			&:active {
				background-color: @background-color-interactive-subtle--active;
				border-color: @border-color-base;
			}
 
			&:focus:not( :active ) {
				background-color: @background-color-base;
				box-shadow: @box-shadow-inset-medium @box-shadow-color-progressive--focus;
			}
		}
 
		// CSS-only sort icons.
		&__sort-icon {
			&--unsorted {
				.cdx-mixin-css-icon( @cdx-icon-sort-vertical, @param-size-icon: @size-icon-small );
			}
 
			&--asc {
				.cdx-mixin-css-icon( @cdx-icon-up-triangle, @param-size-icon: @size-icon-small );
			}
 
			&--desc {
				.cdx-mixin-css-icon( @cdx-icon-down-triangle, @param-size-icon: @size-icon-small );
			}
		}
 
		// Common styles for Vue and CSS-only sort icons. This needs to come after the application
		// of the CSS icon mixin above so the height set here will override the height set in the
		// CSS icon mixin.
		&__sort-icon--vue,
		&__sort-icon {
			color: @color-subtle;
			flex-shrink: 0;
			// Setting the height of the icon to the line-height of the accompanying text
			// to ensure centering of the icon to text
			height: @line-height-small;
		}
 
		// Modifiers for table cells (th and td). Note that the extra class selector is needed to
		// override styles placed on .cdx-table__table th/td above.
		.cdx-table__table__cell {
			&--align-center {
				text-align: center;
				// Note that other styles for the sort button and icon are not included here
				// because they should behave just like with the default start alignment.
			}
 
			&--align-end {
				text-align: right;
 
				/* stylelint-disable-next-line max-nesting-depth */
				.cdx-table__table__sort-button {
					flex-direction: row-reverse;
					// Override text-align: left style above.
					text-align: right;
				}
			}
 
			// Numbers should be aligned right in both reading directionalities.
			&--align-number {
				// Trick postcss-rtlcss into setting text-align to right in both LTR and RTL. We
				// can't just use the rtl:ignore directive, because in bidirectional mode, we need
				// the [dir] selector to be added to match the specificity of the text-align rule
				// applied to all `<th>` and `<td>` elements. Hat-tip to Roan for this one.
				text-align: right /* rtl:right */;
 
				/* stylelint-disable-next-line max-nesting-depth */
				.cdx-table__table__sort-button {
					// Only reverse flex direction in LTR. In RTL, this will happen automatically.
					flex-direction: row-reverse /* rtl: row */;
					// This can be rtl-ignored because it's already set by flipping the text-align
					// style on .cdx-table__table__sort-button above, and it's more specific than
					// that rule.
					text-align: right /* rtl:ignore */;
				}
			}
 
			// Remove padding on `<th>` elements if sorting is enabled, since padding will be added
			// to the sort button instead.
			&--has-sort {
				padding: 0;
			}
		}
 
		// Column of row selection checkboxes.
		&__select-rows {
			// Make this column as narrow as possible.
			width: @size-absolute-1;
		}
 
		&__row {
			&--selected {
				background-color: @background-color-progressive-subtle;
			}
		}
 
		&--layout-fixed {
			/* stylelint-disable-next-line scale-unlimited/declaration-strict-value */
			table-layout: fixed;
		}
 
		&--borders-vertical {
			th,
			td {
				border-right: @border-subtle;
			}
 
			th:last-child,
			td:last-child {
				border-right: 0;
			}
 
			thead {
				/* stylelint-disable-next-line max-nesting-depth */
				tr:not( :first-child ) {
					/* stylelint-disable-next-line max-nesting-depth */
					th {
						// Border styles for `<th>` elements that are not in the first `<tr>`
						// element of the `<thead>`.
						border-top: @border-base;
					}
				}
			}
 
			.cdx-table__header + .cdx-table__table-wrapper & thead th {
				// Set border-top style when table header is present.
				border-top: @border-base;
			}
		}
 
		&__empty-state {
			border-top: @border-base;
 
			// Remove border if there's a thead, which has a border-bottom.
			thead + tbody & {
				border-top: 0;
			}
 
			// Extra specificity is needed to override the vertical-align: top
			// style that is applied to normal `<td>` elements in CdxTable.
			tbody td&-content {
				color: @color-subtle;
				height: @min-height-table-footer - @spacing-150;
				text-align: center;
				vertical-align: middle;
			}
		}
	}
 
	&__footer {
		display: flex;
		align-items: center;
		gap: @spacing-100;
		box-sizing: @box-sizing-base;
		min-height: @min-height-table-footer;
		border-top: @border-base;
		padding: @spacing-75;
		font-size: @font-size-medium;
		line-height: @line-height-small;
	}
}
</style>