All files / components/dialog Dialog.vue

71.75% Statements 155/216
66.31% Branches 124/187
79.16% Functions 38/48
73.6% Lines 145/197

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    1x   20x       20x   20x 20x                         40x   20x     1x 20x     20x 20x                 20x               60x 40x       40x 80x 80x 80x 80x     40x 40x   20x 20x                           20x 20x 20x                                       40x         80x   20x 20x           1x 4x       1x     1x 1x 1x 1x 1x 1x         1x                                                                                                                                                                                                                               21x 21x 21x 21x 21x 21x 21x 21x 21x 20x   21x 20x   21x 21x   21x   21x 21x 20x             21x 21x   21x         21x         2x                                                         20x 20x         20x   20x     20x 1x   1x   1x 1x     19x   21x 21x                 20x 20x 42x 43x 43x 42x         1x 1x 1x   1x 1x 1x     42x       1x       1x       1x 1x       20x 20x 40x             20x             20x   20x 20x   20x 20x             20x 19x   20x           1x 1x 1x     21x 21x   18x       21x         21x 3x   2x   1x       21x         21x                                     1x 1x 1x 1x 1x 1x       1x 1x       1x         1x       1x         24x 24x 24x               24x                 1x 1x 1x   1x                                                                                   19x                                         4x                                                             9x                               1x   12x                     1x   14x                                                                 1x 1x                                    
<template>
	<teleport :to="computedTarget" :disabled="renderInPlace">
		<transition name="cdx-dialog-fade" appear>
			<div
				v-if="open"
				ref="backdrop"
				class="cdx-dialog-backdrop"
				@click="close"
				@keyup.escape="close"
			>
				<!-- Focus trap start -->
				<div
					ref="focusTrapStart"
					tabindex="0"
					@focus="focusLast"
				/>
				<div
					ref="dialogElement"
					class="cdx-dialog"
					:class="rootClasses"
					role="dialog"
					v-bind="$attrs"
					:aria-label="$slots.header || hideTitle ? title : undefined"
					:aria-labelledby="!$slots.header && !hideTitle ? labelId : undefined"
					aria-modal="true"
					@click.stop
				>
					<header
						v-if="showHeader || $slots.header"
						class="cdx-dialog__header"
						:class="{ 'cdx-dialog__header--default': !$slots.header }"
					>
						<!-- @slot Customizable Dialog header -->
						<sIlot name="header">
							<div v-if="!hideTitle" class="cdx-dialog__header__title-group">
								<h2 :id="labelId" class="cdx-dialog__header__title">
									{{ title }}
								</h2>
 
								<p v-if="subtitle" class="cdx-dialog__header__subtitle">
									{{ subtitle }}
								</p>
							</div>
 
							<cdx-button
								v-if="closeButtonLabel"
								class="cdx-dialog__header__close-button"
								weight="quiet"
								type="button"
								:aria-label="closeButtonLabel"
								@click="close"
							>
								<cdx-icon
									:icon="cdxIconClose"
									:icon-label="closeButtonLabel"
								/>
				I			</cdx-button>
						</slot>
					<I/header>
I
					<div
						ref="focusHolder"
						class="cdx-dialog-focus-trap"
						tabindex="-1"
					/>
 
					<div
						ref="dialogBody"
						class="cdx-dialog__body"
						:class="{
							'cdx-dialog__body--no-header': !( showHeader || $slots.header ),
							'cdx-dialog__body--no-footer': !(
								showFooterActions ||
								$slots.footer ||
								$slots[ 'footer-text' ]
							)
						}"
					>
						<!-- @slot Dialog content -->
						<slot />
					</div>
E
					<footer
						v-if="showFooterActions || $slots.footer || $slots[ 'footer-text' ]"
						class="cdx-dialog__footer"
						:class="{ 'cdx-dialog__footer--default': !$slots.footer }"
					>
						<!-- @slot Customizable Dialog footer -->
						<slot name="footer">
							<p v-if="$slots[ 'footer-text' ]" class="cdx-dialog__footer__text">
								<!-- @slot Optional footer text -->
								<slot name="footer-text" />
							</p>
 
							<div
								v-if="showFooterActions"
								class="cdx-dialog__footer__actions"
							>
								<cdx-button
									v-if="primaryAction"
									class="cdx-dialog__footer__primary-action"
									weight="primary"
									:action="primaryAction.actionType"
									:disabled="primaryAction.disabled"
									@click="$emit( 'primary' )"
								>
									{{ primaryAction.label }}
								</cdx-button>
 
								<cdx-button
				I					v-if="defaultAction"
									class="cdx-dialog__footer__default-action"
									:disabled="defaultAction.disabled"
									@click="$emit( 'default' )"
								>
									{{ defaultAction.label }}
								</cdx-button>
							</div>
						</slot>
					</footer>
				</div>
 
				<!-- Focus trap end -->
				<div
					ref="focusTrapEnd"
					tabindex="0"
					@focus="focusFirst"
				/>
			</div>
		</transition>
	</teleport>
</template>
 
<script lang="ts">
import { computed, defineComponent, nextTick, toRef, watch, ref, inject, onMounted, onUnmounted, PropType } from 'vue';
import CdxButton from '../../components/button/Button.vue';
import CdxIcon from '../../components/icon/Icon.vue';
import { cdxIconClose } from '@wikimedia/codex-icons';
import useGeneratedId from '../../composables/useGeneratedId';
import useResizeObserver from '../../composables/useResizeObserver';
import { DialogAction, PrimaryDialogAction } from '../../types';
 
/**
 * A modal element that overlays the current page, preventing interaction with
 * other content until it is dismissed.
 */
export default defineComponent( {
	name: 'CdxDialog',
 
	components: {
		CdxButton,
		CdxIcon
	},
 
	inheritAttrs: false,
 
	props: {
		/**
		 * Whether the dialog is visible. Should be provided via a v-model:open
		 * binding in the parent scope.
		 */
		open: {
			type: Boolean,
			default: false
		},
 
		/**
		 * Title for the dialog header. Used for ARIA purposes even if no
		 * visible header element is displayed.
		 */
		title: {
			type: String,
			required: true
		},
 
		/**
		 * Optional subtitle for the dialog.
		 */
		subtitle: {
			type: String,
			required: false,
			default: null
		},
 
		/**
		 * Whether the dialog header should hide the title & subtitle
		 */
		hideTitle: {
			type: Boolean,
			default: false
		},
 
		/**
		 * Label for the icon-only close button in the header.
		 *
		 * Including this prop adds the close button.
		 */
		closeButtonLabel: {
			type: String,
			default: ''
		},
 
		/**
		 * Primary user action. This will display a primary button with the specified action
		 * (progressive or destructive).
		 */
		primaryAction: {
			type: Object as PropType<PrimaryDialogAction>,
			default: null
		},
 
		/**
		 * Default user action. This will display a normal button.
		 */
		defaultAction: {
			type: Object as PropType<DialogAction>,
			default: null
		},
 
		/**
		 * Whether action buttons should be vertically stacked and 100% width.
		 */
		stackedActions: {
			type: Boolean,
			default: false
		},
 
		/**
		 * Selector or DOM element identifying the container the dialog should
		 * be rendered in. The dialog will be `<teleport>`ed to this element.
		 * An ID selector is recommended, e.g. `#foo-bar`, but providing an
		 * actual element is also supported.
		 *
		 * If this prop is not set, and the parent or one of its ancestors
		 * provides a teleport target using `provide( 'CdxTeleportTarget',
		 * '#foo-bar' )`, the provided target will be used. If there is no
		 * provided target, the dialog will be teleported to the end of the
		 * `<body>` element.
		 */
		target: {
			type: String as PropType<string | HTMLElement | null>,
			default: null
		},
 
		/**
		 * Whether to disable the use of teleport and render the Dialog in its
		 * original location in the document. If this is true, the `target` prop
		 * is ignored.
		 */
		renderInPlace: {
			type: Boolean,
			default: false
		}
	},
 
	emits: [
		/**
		 * When the open/close state changes, e.g. when the close button is clicked.
		 *
		 * @property {boolean} newValue The new open/close state (true for open, false for closed)
		 */
		'update:open',
 
		/**
		 * When the primary action button is clicked.
		 */
		'primary',
 
		/**
		 * When the default action button is clicked.
		 */
		'default'
	],
 
	setup( props, { emit } ) {
		const labelId = useGeneratedId( 'dialog-label' );
 
		const backdrop = ref<HTMLDivElement>();
		const dialogElement = ref<HTMLDivElement>(); // dialog "frame"
		const dialogBody = ref<HTMLDivElement>(); // dialog content
		const focusHolder = ref<HTMLDivElement>();
		const focusTrapStart = ref<HTMLDivElement>();
		const focusTrapEnd = ref<HTMLDivElement>();
 
		const showHeader = computed( () => !props.hideTitle || !!props.closeButtonLabel );
		const showFooterActions = computed( () => !!props.primaryAction || !!props.defaultAction );
 
		const bodyDimensions = useResizeObserver( dialogBody );
		const currentBodyHeight = computed( () => bodyDimensions.value.height ?? 0 );
		const showDividers = ref( false );
 
		const rootClasses = computed( () => ( {
			'cdx-dialog--vertical-actions': props.stackedActions,
			'cdx-dialog--horizontal-actions': !props.stackedActions,
			'cdx-dialog--dividers': showDividers.value
		} ) );

		// Determine where to teleport the Dialog to
		const providedTarget = inject<string|HTMLElement|undefined>( 'CdxTeleportTarget', undefined );
		const computedTarget = computed( () => props.target ?? providedTarget ?? 'body' );
 
		// Value needed to compensate for the width of any visible scrollbar
		// on the page prior to the dialog taking over; without this, browsers
		// that permanently display scrollbars will exhibit a layout shift.
		const scrollWidth = ref( 0 );
 
		/**
		 * Close the dialog by emitting an event to the parent
		 */
		function close() {
			emit( 'update:open', false );
		}
 
		/**
		 * Programmatically focus the first focusable element inside the dialog
		 * frame.
		 */
		funcEtion focusFirst() {
			// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
			focusFirstFocusableElement( dialogElement.value! );
		}
 
		/**
		 * Programmatically focus the last focusable element inside the dialog
		 * frame.
		 */I
		function focusLast() {
			// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
			focusFirstFocusableElement( dialogElement.value!, true );
		}
 
		/**
		 * Programmatically assign focus to the first focusable element in a
		 * speEcified container. Can optionally run backwards. This method is
		 * used in the component's focus trap implementation, which ensures that
		 * the user cannot focus outside the Dialog while it is open.
		 *
		 * @param container {HTMLElement}
		 * @param backwards {boolean}
		 * @return {boolean}
		 */
		function focusFirstFocusableElement( container: HTMLElement, backwards = false ): boolean {
			// Find all focusable elements in the container.
			// Exclude elements with a negative tabindex; those are technically focusable, but are
			// skipped when tabbing
			let candidates = Array.from(
				container.querySelectorAll<HTMLElement>( `
					input, select, textarea, button, object, a, area,
					[contenteditable], [tabindex]:not([tabindex^="-"])
				` )
			);
 
			// If we're looking for the previous element, reverse the array.
			if ( backwards ) {
				candidates = candidates.reverse();
			}
 
			for ( const candidate of candidates ) {
				// Try to focus each element.
				candidEate.focus();
				// Once it works, return true.
				if ( document.activeElement === candidate ) {
					return true;
				}E
			}
			return false;
		}
 
		let ariaHiddenElements: Element[] = [];
		let inertElements: Element[] = [];
 
		/**
		 * Hide all other elements on the page from screen readers, and prevent user
		 * interaction with them, by setting aria-hidden and inert on all siblings of all
		 * ancestors of the dialog. This leaves the path from the root node to the
		 * dialog as the only nodes that aren't covered by aria-hidden and inert.
		 */
		function setAriaHiddenAndInert() {
			// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
			let element: HTMLElement = backdrop.value!;
			while ( element.parentElement && element.nodeName !== 'BODY' ) {
				for ( const sibling of Array.from( element.parentElement.children ) ) {
					if ( sibling === element || sibling.nodeName === 'SCRIPT' ) {
						continue;
					}
					// Store the elements we set aria-hidden and inert on, so that we can
					// unset them when the dialog closes. Exclude elements that already have these
					// attributes set, so that we don't unset things that were supposed to stay set.
					if ( !sibling.hasAttribute( 'aria-hidden' ) ) {
						sibling.setAttribute( 'aria-hidden', 'true' );
						ariaHiddenElements.push( sibling );
					}
					if ( !sibling.hasAttribute( 'inert' ) ) {
						sibling.setAttribute( 'inert', '' );
						inertElements.push( sibling );
					}
				}
				element = element.parentElement;
			}
		}
 
		function unsetAriaHiddenAndInert() {
			for ( const element of ariaHiddenElements ) {
				element.removeAttribute( 'aria-hidden' );
			}
			for ( const element of inertElements ) {
				element.removeAttribute( 'inert' );
			}
			ariaHiddenElements = [];
			inertElements = [];
		}
 
		async function onDialogOpen() {
			// Most of the things below need to happen on nextTick because they rely on template
			// refs, and those are not yet set when the watcher for props.open runs.
			// The documentElement and body manipulations don't need to happen on nextTick, but
			// it's better to group them with the other DOM changes so that we don't cause two
			// separate reflows.
			await nextTick();
 
			// Determine the width of the scrollbar and compensate for it if necessary
			scrollWidth.value = window.innerWidth - document.documentElement.clientWidth;
			document.documentElement.style.setProperty( 'margin-right', `${ scrollWidth.value }px` );
 
			// Add a class to <body> to prevent scrolling
			document.body.classList.add( 'cdx-dialog-open' );
 
			setAriaHiddenAndInert();
 
			// Focus within the dialog so that we can listen to keypress events.
			// Try focusing on the first focusable element in the body. If there isn't one,
			// use the focus holder.
			// This needs to happen on nextTick, otherwise the focus might be stolen back by
			// e.g. a button whose click event opened the dialog.
			// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
			if ( !focusFirstFocusableElement( dialogBody.value! ) ) {
				focusHolder.value?.focus();
			}
		}
 
		function onDialogClose() {
			document.body.classList.remove( 'cdx-dialog-open' );
			document.documentElement.style.removeProperty( 'margin-right' );
			unsetAriaHiddenAndInert();
		}
 
		// If the dialog is mounted in the open state, make sure we set things up properly
		onMounted( () => {
			if ( props.open ) {
				// eslint-disable-next-line @typescript-eslint/no-floating-promises
				onDialogOpen();
			}
		} );
 
		// If the dialog is closed while it's still mounted, make sure we clean up behind ourselves
		onUnmounted( () => {
			if ( props.open ) {
				onDialogClose();
			}
		} );
 
		watch( toRef( props, 'open' ), ( opened ) => {
			if ( opened ) {
				// eslint-disable-next-line @typescript-eslint/no-floating-promises
				onDialogOpen();
			} else {
				onDialogClose();
			}
		} );
 
		// Determine if content dividers should be displayed for overflowing content
		watch( currentBodyHeight, () => {
			if ( dialogBody.value ) {
				showDividers.value = dialogBody.value.clientHeight < dialogBody.value.scrollHeight;
			}
		} );
 
		return {
			close,
			cdxIconClose,
			labelId,
			rootClasses,
			backdrop,
			dialogElement,
			focusTrapStart,
			focusTrapEnd,
			focusFirst,
			focusLast,
			dialogBody,
			focusHolder,
			showHeader,
			showFooterActions,
			computedTarget
		};
	}
} );
</script>
 
<style lang="less">
@import ( reference ) '@wikimedia/codex-design-tokens/theme-wikimedia-ui.less';
 
.cdx-dialog-backdrop {
	background-color: @background-color-backdrop-light;
	display: flex;
	align-items: center;
	justify-content: center;
	position: fixed;
	top: 0;
	left: 0;
	z-index: @z-index-overlay-backdrop;
	min-height: @size-full;
	width: @size-viewport-width-full;
	height: @size-viewport-height-full;
	// Support Safari/iOS: Make `100vh` work with Safari's address bar.
	// See https://stackoverflow.com/questions/37112218/css3-100vh-not-constant-in-mobile-browser
	/* stylelint-disable-next-line plugin/no-unsupported-browser-features,
		scale-unlimited/declaration-strict-value */
	height: -webkit-fill-available;
}
 
.cdx-dialog {
	background-color: @background-color-base;
	display: flex;
	flex-direction: column;
	box-sizing: @box-sizing-base;
	width: calc( @size-full - ( @size-100 * 2) );
	max-width: @size-3200;
	max-height: calc( @size-viewport-height-full - @size-250 );
	border: @border-base;
	border-radius: @border-radius-base;
	box-shadow: @box-shadow-drop-medium;

	&__header {
		padding: @spacing-100 @spacing-150;
 
		// If no custom header content is provided, apply these styles to the
		// <header> element
		&--default {
			display: flex;
			align-items: baseline;
			// Close button should appear at the end regardless of whether or not a title is present
			justify-content: flex-end;
			box-sizing: @box-sizing-base;
			width: @size-full;
		}

		&__title-group {
			display: flex;
			flex-grow: 1;
			flex-direction: column;
			gap: @spacing-35;
		}
 
		// Add specificity to override h2 styles, e.g. in MediaWiki skins.
		// See https://phabricator.wikimedia.org/T324495.
		& &__title {
			margin: 0;
			border: 0;
			padding: 0;
			font-family: inherit;
			font-size: @font-size-large;
			font-weight: @font-weight-bold;
			line-height: @line-height-xxx-small;
		}
 
		// Increase specificity to ensure that this style shows up in VitePress.
		& &__subtitle {
			color: @color-subtle;
			margin: 0;
			padding: 0;
			font-size: @font-size-medium;
			line-height: @line-height-xx-small;
		}
 
		&__close-button.cdx-button {
			margin-right: -@spacing-50;
		}
 
		.cdx-dialog--dividers & {
			border-bottom: @border-subtle;
		}
	}
 
	&__body {
		flex-grow: 1;
		padding: @spacing-100 @spacing-150;
		overflow-y: auto;
 
		// If the dialog does not display a <header> element, add some extra
		// padding at the top of the body
		&--no-header {
			padding-top: @spacing-150;
		}
 
		// If the dialog does not display a <footer> element, add some extra
		// padding at the bottom of the body
		&--no-footer {
			padding-bottom: @spacing-150;
		}
 
		// Zero-out any margin or padding on the first content element that
		// could disrupt the layout
		> *:first-child {
			margin-top: 0;
			padding-top: 0;
		}
 
		// Zero-out any margin or padding on the last content element that
		// could disrupt the layout
		> *:last-child {
			margin-bottom: 0;
			padding-bottom: 0;
		}
	}
 
	&__footer {
		padding: @spacing-100 @spacing-150 @spacing-150;
 
		// If no custom footer content is provided, apply these styles to the
		// <footer> element
		&--default {
			display: flex;
			align-items: baseline;
			flex-wrap: wrap;
			justify-content: space-between;
			gap: @spacing-75;
		}
 
		// Increased specificity to ensure that this style shows up in VitePress
		& &__text {
			color: @color-subtle;
			flex: 1 0 auto;
			width: @spacing-full;
			margin: 0;
			font-size: @font-size-small;
			line-height: @line-height-small;
		}
 
		&__actions {
			display: flex;
			flex-grow: 1;
			gap: @spacing-75;
		}
 
		.cdx-dialog--dividers & {
			border-top: @border-subtle;
		}
	}
 
	&--horizontal-actions &__footer {
		&__actions {
			flex-direction: row-reverse;
		}
	}
 
	&--vertical-actions &__footer {
		&__actions {
			flex-direction: column;
			width: @size-full;
		}
 
		.cdx-dialog__footer__primary-action.cdx-button,
		.cdx-dialog__footer__default-action.cdx-button {
			max-width: none;
		}
	}
}

// This element is not used for visual styling, just
// focus managmenent. It needs to be invisible but cannot
// have display:none, and its position in the markup is
// important (must be inside the dialog element).
.cdx-dialog-focus-trap {
	// Set position to absolute so that this element is
	// omitted from all flex layout calculations
	position: absolute;
 
	// Don't show visible focus outline for the focus-trap element
	&:focus {
		outline: 0;
	}
}
 
.cdx-dialog-fade-enter-active,
.cdx-dialog-fade-leave-active {
	transition-property: @transition-property-fade;
	// For system initiated transitions – the user clicks a dialog trigger button,
	// the system opens the dialog – use a longer transition and system timing function.
	transition-duration: @transition-duration-medium;
	transition-timing-function: @transition-timing-function-system;
}
 
.cdx-dialog-fade-enter-from,
.cdx-dialog-fade-leave-to {
	opacity: @opacity-transparent;
}
 
body.cdx-dialog-open {
	overflow: hidden;
}
</style>