All files / components/toggle-switch ToggleSwitch.vue

100% Statements 47/47
90.9% Branches 30/33
100% Functions 9/9
100% Lines 46/46

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    1x 6x       1x     1x 1x 1x 1x 1x 1x 1x       1x                                                                                                                               8x 8x 8x 8x   8x   8x 8x 8x 8x         8x 8x 8x 8x 8x     8x       8x   1x   8x                         1x 1x 1x 1x 1x 1x       8x 8x             1x                       1x 1x 1x   1x                                 4x               2x                     1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
<template>
	<span
		class="cdx-toggle-switch"
		:class="rootClasses"
		:style="rootStyle"
	>
		<input
			:id="inputId"
			ref="input"
			v-model="wrappedModel"
			class="cdx-toggle-switch__input"
			type="checkbox"
			role="switch"
			:aria-describedby="( $slots.description &&
				$slots.description().length > 0 ) ? descriptionId : undefined"
			:value="inputValue"
			:disabled="computedDisabled"
			v-bind="otherAttrs"
			@keydown.prevent.enter="clickInput"
		>
 
		<span class="cdx-toggle-switch__switch">
			<span class="cdx-toggle-switch__switch__grip" />
		</span>
 
		<!-- Only render a Label component if label text has been provided. This component can also
			supply a description to the input if content is provided in the description slot. -->
		<cdx-label
			v-if="$slots.default && $slots.default().length"
			class="cdx-toggle-switch__label"
			:input-id="inputId"
			:description-id="( $slots.description &&
				$slots.description().length > 0 ) ? descriptionId : undefined"
			:visually-hidden="hideLabel"
			:disabled="computedDisabled"
		>
			<!-- @slot Label text. -->
			<slot />
			<template v-if="$slots.description && $slots.description().length > 0" #description>
				<!-- @slot Short description text. -->
				<slot name="description" />
			</template>
		</cdx-label>
	</span>
</template>
 
<script lang="ts">
import { defineComponent, PropType, ref, toRef, computed } from 'vue';
import CdxLabel from '../label/Label.vue';
import useLabelChecker from '../../composables/useLabelChecker';
import useModelWrapper from '../../composables/useModelWrapper';
import useGeneratedId from '../../composables/useGeneratedId';
import useSplitAttributes from '../../composables/useSplitAttributes';
import useFieldData from '../../composables/useFieldData';
 
/**
 * A switch that allows the user to toggle between on and off states.
 */
export default defineComponent( {
	name: 'CdxToggleSwitch',
	components: { CdxLabel },
	/**
	 * The input element will inherit attributes, not the root element.
	 */
	inheritAttrs: false,
	props: {
		/**
		 * Current value of the toggle switch or toggle switch group.
		 *
		 * Provided by `v-model` binding in the parent component.
		 */
		modelValue: {
			type: [ Boolean, Array ] as PropType<boolean | string[] | number[]>,
			default: false
		},
		/**
		 * HTML "value" attribute to assign to the input element.
		 *
		 * Required for groups of ToggleSwitches. Can be omitted for single true/false switches.
		 */
		inputValue: {
			type: [ String, Number, Boolean ],
			default: false
		},
		/**
		 * Whether to align the switch to the end of the container.
		 *
		 * Useful for ToggleSwitch groups, where each switch should be aligned regardless of
		 * label length.
		 */
		alignSwitch: {
			type: Boolean,
			default: false
		},
		/**
		 * Whether the label should be visually hidden.
		 *
		 * Note that this will also hide the description.
		 */
		hideLabel: {
			type: Boolean,
			default: false
		},
		/**
		 * Whether the disabled attribute should be added to the input.
		 */
		disabled: {
			type: Boolean,
			default: false
		}
	},
	emits: [
		/**
		 * Emitted when modelValue changes.
		 *
		 * @property {boolean} modelValue The new model value
		 */
		'update:modelValue'
	],
	setup( props, { emit, slots, attrs } ) {
		useLabelChecker( slots.default?.(), attrs, 'CdxToggleSwitch' );
 
		// Declare template refs.
		const input = ref<HTMLInputElement>();
 
		// Input needs an ID so we can connect it and the label element.
		const inputId = useGeneratedId( 'toggle-switch' );
		const descriptionId = useGeneratedId( 'description' );
 
		const internalClasses = computed( (): Record<string, boolean> => {
			return {
				'cdx-toggle-switch--align-switch': props.alignSwitch
			};
		} );
 
		// Get helpers from useSplitAttributes.
		const {
			rootClasses,
			rootStyle,
			otherAttrs
		} = useSplitAttributes( attrs, internalClasses );
 
		const { computedDisabled } = useFieldData( toRef( props, 'disabled' ) );
 
		// Take the modelValue provided by the parent component via v-model and generate a wrapped
		// model that we can use for the input element in this component.
		const wrappedModel = useModelWrapper( toRef( props, 'modelValue' ), emit );
 
		/**
		 * Click the input to toggle its state.
		 */
		const clickInput = (): void => {
			// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
			input.value!.click();
		};
 
		return {
			input,
			inputId,
			descriptionId,
			rootClasses,
			rootStyle,
			otherAttrs,
			computedDisabled,
			wrappedModel,
			clickInput
		};
	}
} );
</script>
 
<style lang="less">
@import ( reference ) '@wikimedia/codex-design-tokens/theme-wikimedia-ui.less';
@import ( reference ) '../../themes/mixins/common.less';
 
.cdx-toggle-switch {
	display: inline-flex;
	align-items: center;
	justify-content: flex-start;
	position: relative;
	// Visually hidden `<input>` will be absolutely positioned relative to this element.
	// Create a stacking context by `position: relative` and `z-index` other than `auto`.
	z-index: @z-index-stacking-0;
	margin-bottom: @spacing-75;
 
	&--align-switch {
		display: flex;
		justify-content: space-between;
	}
 
	&:last-child {
		margin-bottom: 0;
	}

	// DEPRECATED: Support CSS-only components that don't set the `cdx-label` class on the
	// label (T353885)
	&__label,
	&__label.cdx-label {
		// Put the label first. It needs to come after the input in the markup so we can apply
		// styles based on the state of the input.
		order: -1;
 
		&:not( :empty ) {
			padding-right: @spacing-35;
		}
	}
 
	// Special overrides for the Label component.
	& &__label.cdx-label {
		padding-bottom: 0;
 
		.cdx-label__label__text {
			font-weight: @font-weight-normal;
		}
	}
 
	// The visible switch.
	&__switch {
		.force-gpu-composite-layer();
		background-color: @background-color-interactive-subtle;
		display: inline-block;
		flex-shrink: 0;
		// Grip will be positioned absolutely relative to the switch.
		position: relative;
		box-sizing: @box-sizing-base;
		min-width: @min-width-toggle-switch;
		min-height: @min-size-interactive-pointer;
		width: @size-300;
		height: @size-200;
		border-width: @border-width-base;
		border-style: @border-style-base;
		border-color: @border-color-input-binary;
		border-radius: @border-radius-pill;
		overflow: hidden;
		transition-property: @transition-property-base;
		transition-duration: @transition-duration-medium;
 
		// Inner focus outline, set visible when toggled on further down.
		&::before {
			content: '';
			display: block;
			position: absolute;
			top: @size-absolute-1;
			right: @size-absolute-1;
			bottom: @size-absolute-1;
			left: @size-absolute-1;
			z-index: @z-index-stacking-1;
			border: @border-width-base @border-style-base @border-color-transparent;
			border-radius: @border-radius-pill;
			transition-property: @transition-property-base;
			transition-duration: @transition-duration-medium;
		}
 
		// The moving element of the switch.
		&__grip {
			position: absolute;
			// Position vertically centered with help of `transform` further down.
			top: @size-half;
			box-sizing: @box-sizing-base;
			min-width: @min-size-toggle-switch-grip;
			min-height: @min-size-toggle-switch-grip;
			width: @size-125;
			height: @size-125;
			border: @border-width-base @border-style-base @border-color-input-binary;
			border-radius: @border-radius-circle;
			// Set starting position with `transform` and add 1px equivalent to x position.
			// Divide height by 50% to center the grip vertically.
			transform: translateX( ( @size-25 + @size-6 ) ) translateY( -@size-half );
			transition-property: @transition-property-toggle-switch-grip;
			// As ToggleSwitch background is a big area transition, let's use the slower duration
			// for it.
 
			/* stylelint-disable stylistic/declaration-colon-newline-after,
				stylistic/value-list-comma-newline-after */
			transition-duration: @transition-duration-medium,
				@transition-duration-base,
				@transition-duration-base;
			/* stylelint-enable stylistic/declaration-colon-newline-after,
				stylistic/value-list-comma-newline-after */
		}
	}
 
	// Hidden `<input type="checkbox">` element.
	&__input {
		// Visually hide the actual `<input>`.
		opacity: 0;
		position: absolute;
		right: 0;
		// Render “on top of” the `span`, so that it's still clickable.
		z-index: @z-index-stacking-2;
		min-width: @min-width-toggle-switch;
		min-height: @min-size-interactive-pointer;
		width: @size-300;
		height: @size-200;
		margin: 0;
		font-size: inherit;
 
		// Checked (on) state whether or not the input is enabled or disabled.
		&:checked ~ .cdx-toggle-switch__switch {
			.cdx-toggle-switch__switch__grip {
				background-color: @background-color-base;
				border-color: @border-color-inverted;
				// Move the grip to the right and add 1px equivalent to x position.
				// Continue to divide height by 50% to center the grip.
				transform: translateX( calc( @size-full + @size-6 ) ) translateY( -@size-half );
			}
		}
 
		&:enabled {
			// Add hover cursor to switch and label.
			// DEPRECATED: The line with the :not() selector is meant to support CSS-only usage of
			// a simple label element with class `.cdx-toggle-switch__label`, rather than use of
			// the Label component (this usage is deprecated, see T353885).
			&:hover,
			& ~ .cdx-label .cdx-label__label:hover,
			& ~ .cdx-toggle-switch__label:not( .cdx-label ):hover {
				cursor: @cursor-base--hover;
			}
 
			& ~ .cdx-toggle-switch__switch .cdx-toggle-switch__switch__grip {
				background-color: @background-color-base-fixed;
			}
 
			&:hover ~ .cdx-toggle-switch__switch {
				background-color: @background-color-base;
				border-color: @border-color-progressive--hover;
 
				.cdx-toggle-switch__switch__grip {
					background-color: @background-color-base-fixed;
					border-color: @border-color-progressive--hover;
				}
			}
 
			&:active ~ .cdx-toggle-switch__switch {
				background-color: @background-color-progressive--active;
				border-color: @border-color-progressive--active;
 
				&::before {
					border-color: @border-color-progressive--active;
				}
 
				.cdx-toggle-switch__switch__grip {
					border-color: @border-color-inverted;
				}
			}
 
			&:focus:not( :active ) ~ .cdx-toggle-switch__switch {
				border-color: @border-color-progressive;
				box-shadow: @box-shadow-inset-small @box-shadow-color-progressive--focus;
				outline: @outline-base--focus;
 
				.cdx-toggle-switch__switch__grip {
					border-color: @border-color-progressive;
				}
			}
 
			// Checked state.
			/* stylelint-disable no-descending-specificity */
			&:checked {
				& ~ .cdx-toggle-switch__switch {
					background-color: @background-color-input-binary--checked;
					border-color: @border-color-input-binary--checked;
 
					.cdx-toggle-switch__switch__grip {
						border-color: @background-color-base;
					}
				}
 
				&:hover ~ .cdx-toggle-switch__switch {
					background-color: @background-color-progressive--hover;
					border-color: @border-color-progressive--hover;
				}
 
				&:active ~ .cdx-toggle-switch__switch {
					background-color: @background-color-progressive--active;
					border-color: @border-color-progressive--active;
					box-shadow: @box-shadow-inset-small @box-shadow-color-progressive--active;
 
					&::before {
						border-color: @border-color-progressive--active;
					}
 
					.cdx-toggle-switch__switch__grip {
						background-color: @background-color-base-fixed;
						border-color: @border-color-inverted;
					}
				}
 
				&:focus:not( :active ) ~ .cdx-toggle-switch__switch {
					border-color: @border-color-input-binary--checked;
 
					&::before,
					.cdx-toggle-switch__switch__grip {
						border-color: @border-color-inverted;
					}
				}
			}
			/* stylelint-enable no-descending-specificity */
		}
 
		/* stylelint-disable no-descending-specificity */
		&:disabled {
			cursor: @cursor-base--disabled;
 
			& ~ .cdx-toggle-switch__switch {
				background-color: @background-color-disabled;
				border-color: @border-color-disabled;
 
				.cdx-toggle-switch__switch__grip {
					border-color: @border-color-inverted;
					box-shadow: @box-shadow-inset-small @box-shadow-color-inverted;
				}
			}
 
			&:checked ~ .cdx-toggle-switch__switch {
				.cdx-toggle-switch__switch__grip {
					background-color: @background-color-base;
				}
			}
		}
		/* stylelint-enable no-descending-specificity */
	}
}
</style>