UNPKG

@elastic/eui

Version:

Elastic UI Component Library

229 lines (220 loc) 11 kB
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import _createClass from "@babel/runtime/helpers/createClass"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf"; import _inherits from "@babel/runtime/helpers/inherits"; import _wrapNativeSuper from "@babel/runtime/helpers/wrapNativeSuper"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); } function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); } function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; } function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); } function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ /** * @license MIT License * * Copyright (c) 2025 Martin Winkler * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @see {@link https://github.com/teetotum/match-container/blob/main/matchContainer.js} */ import { v1 as uuid } from 'uuid'; /** * Listen for changes on a container query. * Just like `window.matchMedia`. * * @example * ```js * const cql = matchContainer(element, '(width > 42rem)'); * cql.addEventListener('change', ({ matches }) { * // .. * }) * ``` * * @param element * @param containerQueryString e.g. (width > 42rem) * @returns ContainerQueryList */ export function matchContainer(element, containerQueryString) { return new ContainerQueryList(element, containerQueryString); } /** * `change` event dispatched by instances of {@link ContainerQueryList} * whenever the value of `matches` changes */ export var ContainerQueryListChangeEvent = /*#__PURE__*/function (_Event) { function ContainerQueryListChangeEvent(matches, container) { var _this; _classCallCheck(this, ContainerQueryListChangeEvent); _this = _callSuper(this, ContainerQueryListChangeEvent, ['change']); /** Whether the container query matches */ _defineProperty(_this, "matches", void 0); /** A string representation of the container query list e.g. "(width > 1000px)" */ _defineProperty(_this, "container", void 0); _this.matches = matches; _this.container = container; return _this; } _inherits(ContainerQueryListChangeEvent, _Event); return _createClass(ContainerQueryListChangeEvent); }( /*#__PURE__*/_wrapNativeSuper(Event)); /** * A hacky implementation of a possible native `ContainerQueryList` * based on the teetotum/match-container polyfill: * - based on a API proposal in W3C CSS WG {@link https://github.com/w3c/csswg-drafts/issues/6205}) * - mimicking MediaQueryList {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList} * * Not meant to be used directly, but rather call `matchContainer`. * * It works by listening on a `transitionrun` event on the element, * that gets triggered by a container query changing a custom property. * Setting `transition-behavior: allow-discrete` is what makes it possible * to have a CSS `transition` for a custom property. * @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/transition-behavior} */ var _matches = /*#__PURE__*/new WeakMap(); export var ContainerQueryList = /*#__PURE__*/function (_EventTarget) { function ContainerQueryList(element, containerQueryString) { var _this2; _classCallCheck(this, ContainerQueryList); _this2 = _callSuper(this, ContainerQueryList); _defineProperty(_this2, "element", null); _defineProperty(_this2, "styleSheet", null); _defineProperty(_this2, "markerAttributeName", ''); _defineProperty(_this2, "sentinelPropertyName", ''); _defineProperty(_this2, "computedStyle", null); _defineProperty(_this2, "transitionRunListener", null); _classPrivateFieldInitSpec(_this2, _matches, false); /** * A string representation of the container query list e.g. "(width > 1000px)" * (the name is weird but it is so for consistency with mediaQueryList.media) * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/media} * */ _defineProperty(_this2, "container", void 0); _this2.container = containerQueryString; _this2.element = element; // we call this only once to try to avoid any impact on performance _this2.computedStyle = getComputedStyle(_this2.element); var uniqueName = "container-query-observer-".concat(uuid()); _this2.markerAttributeName = "data-".concat(uniqueName); _this2.sentinelPropertyName = "--".concat(uniqueName); // order is important (as in life) _this2.applyMarkerAttribute(); _this2.createStyleSheet(); _classPrivateFieldSet(_matches, _this2, _this2.computedStyle.getPropertyValue(_this2.sentinelPropertyName) === '--true'); _this2.setupTransitionListener(); return _this2; } /** * The marker attribute is `data-container-query-observer-{UUID}`, * it will be used as a selector in the container query, * in the global CSS that's being added below. */ _inherits(ContainerQueryList, _EventTarget); return _createClass(ContainerQueryList, [{ key: "matches", get: /** Whether the container query matches */ function get() { return _classPrivateFieldGet(_matches, this); } }, { key: "applyMarkerAttribute", value: function applyMarkerAttribute() { this.element.setAttribute(this.markerAttributeName, ''); } /** * Create a CSS custom property with values either `--true` or `--false`, * and add container query targetting the element. * Whenever the container query matches, the custom property will be `--true`. * This styles are added globaly via `document.adoptedStyleSheets`. */ }, { key: "createStyleSheet", value: function createStyleSheet() { var css = "\n @property ".concat(this.sentinelPropertyName, " {\n syntax: '<custom-ident>';\n inherits: false;\n initial-value: --false;\n }\n @container ").concat(this.container, " {\n [").concat(this.markerAttributeName, "] {\n ").concat(this.sentinelPropertyName, ": --true;\n }\n }\n "); var styleSheet = new CSSStyleSheet(); styleSheet.replaceSync(css); document.adoptedStyleSheets = [].concat(_toConsumableArray(document.adoptedStyleSheets), [styleSheet]); this.styleSheet = styleSheet; } /** * This is the key to the hack: * - a `transition` style is added for the custom property * - the `transitionrun` event will fire whenever the custom property value changes * because of the container query * - we get the value from computed styles * - the `matches` value is updated and * - a ContainerQueryListChangeEvent event is dispatched */ }, { key: "setupTransitionListener", value: function setupTransitionListener() { var _this3 = this; var element = this.element, computedStyle = this.computedStyle, sentinelPropertyName = this.sentinelPropertyName; if (!element) return; var currentValue = computedStyle.getPropertyValue(sentinelPropertyName); element.style.setProperty('transition', "".concat(sentinelPropertyName, " 0.001ms step-start")); element.style.setProperty('transition-behavior', 'allow-discrete'); this.transitionRunListener = function (event) { if (event.target !== element) return; var nextValue = computedStyle.getPropertyValue(sentinelPropertyName); if (nextValue === currentValue) return; currentValue = nextValue; _classPrivateFieldSet(_matches, _this3, nextValue === '--true'); _this3.dispatchEvent(new ContainerQueryListChangeEvent(_classPrivateFieldGet(_matches, _this3), _this3.container)); }; element.addEventListener('transitionrun', this.transitionRunListener); } }, { key: "dispose", value: function dispose() { var _this4 = this; // remove the stylesheet from adoptedStyleSheets if (this.styleSheet) { document.adoptedStyleSheets = document.adoptedStyleSheets.filter(function (sheet) { return sheet !== _this4.styleSheet; }); } if (!this.element) return; if (this.transitionRunListener) { this.element.removeEventListener('transitionrun', this.transitionRunListener); } this.element.removeAttribute(this.markerAttributeName); this.element.style.removeProperty('transition'); this.element.style.removeProperty('transition-behavior'); this.element = null; this.styleSheet = null; this.computedStyle = null; this.transitionRunListener = null; } }]); }( /*#__PURE__*/_wrapNativeSuper(EventTarget));