@elastic/eui
Version:
Elastic UI Component Library
243 lines (237 loc) • 15.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ContainerQueryListChangeEvent = exports.ContainerQueryList = void 0;
exports.matchContainer = matchContainer;
var _uuid = require("uuid");
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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 _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }
function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(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;
_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();
var ContainerQueryList = exports.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((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.
*/
_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));