@elastic/eui
Version:
Elastic UI Component Library
231 lines (225 loc) • 11.8 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ContainerQueryListChangeEvent = exports.ContainerQueryList = void 0;
exports.matchContainer = matchContainer;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _uuid = require("uuid");
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 = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(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}
*/
/**
* 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
*/
function matchContainer(element, containerQueryString) {
return new ContainerQueryList(element, containerQueryString);
}
/**
* `change` event dispatched by instances of {@link ContainerQueryList}
* whenever the value of `matches` changes
*/
var ContainerQueryListChangeEvent = exports.ContainerQueryListChangeEvent = /*#__PURE__*/function (_Event) {
function ContainerQueryListChangeEvent(matches, container) {
var _this;
(0, _classCallCheck2.default)(this, ContainerQueryListChangeEvent);
_this = _callSuper(this, ContainerQueryListChangeEvent, ['change']);
/** Whether the container query matches */
(0, _defineProperty2.default)(_this, "matches", void 0);
/** A string representation of the container query list e.g. "(width > 1000px)" */
(0, _defineProperty2.default)(_this, "container", void 0);
_this.matches = matches;
_this.container = container;
return _this;
}
(0, _inherits2.default)(ContainerQueryListChangeEvent, _Event);
return (0, _createClass2.default)(ContainerQueryListChangeEvent);
}( /*#__PURE__*/(0, _wrapNativeSuper2.default)(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();
var ContainerQueryList = exports.ContainerQueryList = /*#__PURE__*/function (_EventTarget) {
function ContainerQueryList(element, containerQueryString) {
var _this2;
(0, _classCallCheck2.default)(this, ContainerQueryList);
_this2 = _callSuper(this, ContainerQueryList);
(0, _defineProperty2.default)(_this2, "element", null);
(0, _defineProperty2.default)(_this2, "styleSheet", null);
(0, _defineProperty2.default)(_this2, "markerAttributeName", '');
(0, _defineProperty2.default)(_this2, "sentinelPropertyName", '');
(0, _defineProperty2.default)(_this2, "computedStyle", null);
(0, _defineProperty2.default)(_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}
* */
(0, _defineProperty2.default)(_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((0, _uuid.v1)());
_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.
*/
(0, _inherits2.default)(ContainerQueryList, _EventTarget);
return (0, _createClass2.default)(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((0, _toConsumableArray2.default)(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__*/(0, _wrapNativeSuper2.default)(EventTarget));