const appendFileToHead = function (i, s, o, g, r, a, m) {
a = s.createElement(o), m = s.getElementsByTagName(o)[0];
a.type = g.blob.type.split(';')[0].trim();
a.appendChild(s.createTextNode(g.text));
a.onload = r(g);
m ? m.parentNode.insertBefore(a, m) : s.head.appendChild(a);
};
function fetchInject(inputs, promise) {
if (!(inputs && Array.isArray(inputs))) return Promise.reject(new Error('`inputs` must be an array'));
if (promise && !(promise instanceof Promise)) return Promise.reject(new Error('`promise` must be a promise'));
const resources = [];
const deferreds = promise ? [].concat(promise) : [];
const thenables = [];
inputs.forEach(input => deferreds.push(window.fetch(input).then(res => {
return [res.clone().text(), res.blob()];
}).then(promises => {
return Promise.all(promises).then(resolved => {
resources.push({
text: resolved[0],
blob: resolved[1]
});
});
})));
return Promise.all(deferreds).then(() => {
resources.forEach(resource => {
thenables.push({
then: resolve => {
resource.blob.type.split(';')[0].trim() === 'text/css' ? appendFileToHead(window, document, 'style', resource, resolve) : appendFileToHead(window, document, 'script', resource, resolve);
}
});
});
return Promise.all(thenables);
});
}
function loadScript(url) {
return new Promise((resolve, reject) => {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.addEventListener('load', () => resolve(script), false);
script.addEventListener('error', () => reject(script), false);
document.body.appendChild(script);
});
}
window.customElements.define('loess-3d-model', class extends HTMLElement {
async connectedCallback() {
await fetchInject([window.LoessTheme.styles.modelViewerUiStyles]);
Shopify.loadFeatures([{
name: 'shopify-xr',
version: '1.0',
onLoad: this.setupShopifyXR.bind(this)
}, {
name: 'model-viewer-ui',
version: '1.0',
onLoad: () => {
this.modelViewerUI = new Shopify.ModelViewerUI(this.querySelector('model-viewer'));
}
}]);
}
disconnectedCallback() {
var _this$modelViewerUI;
(_this$modelViewerUI = this.modelViewerUI) === null || _this$modelViewerUI === void 0 ? void 0 : _this$modelViewerUI.destroy();
}
setupShopifyXR(errors) {
if (errors) return;
if (!window.ShopifyXR) {
document.addEventListener('shopify_xr_initialized', () => this.setupShopifyXR());
return;
}
document.querySelectorAll('[id^="ProductJSON-"]').forEach(modelJSON => {
window.ShopifyXR.addModels(JSON.parse(modelJSON.textContent));
modelJSON.remove();
});
window.ShopifyXR.setupXRElements();
}
play() {
var _this$modelViewerUI2;
(_this$modelViewerUI2 = this.modelViewerUI) === null || _this$modelViewerUI2 === void 0 ? void 0 : _this$modelViewerUI2.play();
}
pause() {
var _this$modelViewerUI3;
(_this$modelViewerUI3 = this.modelViewerUI) === null || _this$modelViewerUI3 === void 0 ? void 0 : _this$modelViewerUI3.pause();
}
});
class Button extends HTMLButtonElement {
constructor() {
super();
this.addEventListener('click', this._onClick.bind(this));
}
static get observedAttributes() {
return ['aria-expanded'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === 'false' && newValue === 'true') {
this.target.open = true;
} else if (oldValue === 'true' && newValue === 'false') {
this.target.open = false;
}
}
connectedCallback() {
this.handleState = this._handleState.bind(this);
document.addEventListener('expandable-html-element:open', this.handleState);
document.addEventListener('expandable-html-element:close', this.handleState);
}
disconnectedCallback() {
document.removeEventListener('expandable-html-element:open', this.handleState);
document.removeEventListener('expandable-html-element:close', this.handleState);
}
_handleState(event) {
if (this.target !== event.target) return;
event.stopPropagation();
if (event.type == 'expandable-html-element:open') {
this.expanded = true;
if (this.targetFocus) this.targetFocus.focus();
} else {
this.expanded = false;
}
}
get expanded() {
return this.getAttribute('aria-expanded') === 'true';
}
set expanded(value) {
this.setAttribute('aria-expanded', String(value));
}
get target() {
return document.getElementById(this.getAttribute('aria-controls'));
}
get targetFocus() {
return document.getElementById(this.getAttribute('target-focus'));
}
_onClick() {
this.expanded = !this.expanded;
}
}
window.customElements.define('loess-button', Button, {
extends: 'button'
});
function debounce(func, timeout = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
}
function fetchConfig(type = 'json') {
return {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': `application/${type}`
}
};
}
customElements.define('loess-cart-notes', class extends HTMLTextAreaElement {
constructor() {
super();
this.addEventListener('input', debounce(event => {
const body = JSON.stringify({
note: event.target.value
});
fetch(`${window.LoessTheme.routes.cart_update_url}`, {
...fetchConfig(),
...{
body
}
});
}));
}
}, {
extends: 'textarea'
});
customElements.define('loess-cart-remove-button', class extends HTMLElement {
constructor() {
super();
this.addEventListener('click', event => {
event.preventDefault();
const cartItems = this.closest('loess-cart-items') || this.closest('loess-cart-drawer-items');
cartItems.updateQuantity(this.dataset.index, 0);
}, {
once: true
});
}
});
const CartItems = class extends HTMLElement {
constructor() {
super();
this.currentItemCount = Array.from(this.querySelectorAll('[name="updates[]"]')).reduce((total, quantityInput) => total + parseInt(quantityInput.value), 0);
this.debouncedOnChange = debounce(event => {
if (event.target.name === 'note') return;
this.onChange(event);
});
this.addEventListener('change', this.debouncedOnChange.bind(this));
}
onChange(event) {
console.log(event);
this.updateQuantity(event.target.dataset.index, event.target.value, document.activeElement.getAttribute('name'));
}
getSectionsToRender() {
return [{
id: 'MainCartItems',
section: document.getElementById('MainCartItems').dataset.id,
selector: '.cart-items'
}, {
id: 'MainCartItems',
section: document.getElementById('MainCartItems').dataset.id,
selector: '.cart-payment-terms'
}, {
id: 'CartTotalPrice',
section: 'cart-total-price',
selector: '.shopify-section'
}, {
id: 'HeaderCartIcon',
section: 'header-cart-icon',
selector: '.shopify-section'
}, {
id: 'FreeShippingTextMobile',
section: 'free-shipping-text',
selector: '.shopify-section'
}, {
id: 'FreeShippingTextLarge',
section: 'free-shipping-text',
selector: '.shopify-section'
}];
}
updateQuantity(line, quantity, name) {
const lineNumber = Number(line);
const requestedQuantity = Number(quantity);
const previousRow = this.querySelector(`#CartItem-${lineNumber}`);
const productLink = previousRow && previousRow.querySelector('.cart-item__details a');
const productName = productLink ? productLink.textContent.trim() : 'Item';
const activeControl = document.activeElement;
const restoreFocus = previousRow && previousRow.contains(activeControl);
const controlName = restoreFocus ? activeControl.getAttribute('name') : name;
// Register the live region before the response arrives. Keep it outside the replaced table.
const status = this.ensureCartUpdateStatus();
clearTimeout(this.cartAnnouncementTimer);
status.textContent = '';
this.enableLoading(line);
const errorHost = this.closest('#CartDrawer') || this;
const errorBox = errorHost.querySelector('.cart-errors');
if (errorBox) errorBox.classList.remove('cart-errors--visible');
const body = JSON.stringify({
line,
quantity,
sections: this.getSectionsToRender().map(section => section.section),
sections_url: window.location.pathname
});
return fetch(`${window.LoessTheme.routes.cart_change_url}`, {
...fetchConfig(),
body
}).then(async response => {
const state = await response.json();
if (!response.ok || state.errors || (state.status && Number(state.status) >= 400)) {
const detail = state.description || state.errors || state.message;
throw new Error(typeof detail === 'string' ? detail : window.LoessTheme.cartStrings.error);
}
if (!Array.isArray(state.items) || typeof state.total_price !== 'number') {
throw new Error(window.LoessTheme.cartStrings.error);
}
return state;
}).then(state => {
const mayRestoreFocus = restoreFocus &&
(document.activeElement === activeControl || document.activeElement === document.body);
this.renderCartItems(state);
this.disableLoading();
this.currentItemCount = state.item_count;
this.restoreCartQuantityFocus(lineNumber, controlName, activeControl, mayRestoreFocus);
const confirmedItem = requestedQuantity > 0 ? state.items[lineNumber - 1] : null;
const currency = state.currency || 'USD';
let message;
if (requestedQuantity === 0) {
message = `${productName} removed from cart.`;
} else if (confirmedItem) {
const title = confirmedItem.product_title || confirmedItem.title || productName;
if (Number(confirmedItem.quantity) === requestedQuantity) {
message = `Quantity for ${title} updated to ${confirmedItem.quantity}.`;
} else {
message = `Quantity for ${title} is ${confirmedItem.quantity}. The requested quantity ${requestedQuantity} could not be applied.`;
}
if (typeof confirmedItem.final_line_price === 'number') {
message += ` Item total ${this.formatCartAnnouncementMoney(confirmedItem.final_line_price, currency)}.`;
}
} else {
message = 'Cart updated. Please review the items in your cart.';
}
message += state.item_count === 0 ? ' Your cart is empty.' :
` Cart total ${this.formatCartAnnouncementMoney(state.total_price, currency)}.`;
this.announceCartUpdate(message);
}).catch(error => {
this.disableLoading();
const message = error.message || window.LoessTheme.cartStrings.error;
this.querySelectorAll('.loading-overlay').forEach(overlay => overlay.classList.add('hidden'));
const rowError = previousRow && previousRow.querySelector('p.allMyERROR');
if (rowError && rowError.isConnected) rowError.textContent = message;
const errorText = errorHost.querySelector('.cart-product-error') ||
(errorBox && errorBox.querySelector('span'));
if (errorText) errorText.textContent = message;
if (errorBox) errorBox.classList.add('cart-errors--visible');
this.restoreCartQuantityFocus(lineNumber, controlName, activeControl, restoreFocus);
this.announceCartUpdate(`Cart could not be updated. ${message}`);
});
}
ensureCartUpdateStatus() {
let status = this.querySelector('[data-cart-update-status]');
if (!status) {
status = document.createElement('div');
status.setAttribute('data-cart-update-status', '');
status.setAttribute('role', 'status');
status.setAttribute('aria-live', 'polite');
status.setAttribute('aria-atomic', 'true');
status.style.cssText = 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;';
this.appendChild(status);
}
return status;
}
announceCartUpdate(message) {
const status = this.ensureCartUpdateStatus();
status.textContent = '';
clearTimeout(this.cartAnnouncementTimer);
this.cartAnnouncementTimer = setTimeout(() => {
if (status.isConnected) status.textContent = message;
}, 100);
}
async announceAddedCartItem(addedState) {
const status = this.ensureCartUpdateStatus();
clearTimeout(this.cartAnnouncementTimer);
status.textContent = '';
const sequence = (this.cartAddAnnouncementSequence || 0) + 1;
this.cartAddAnnouncementSequence = sequence;
let message = '';
try {
const cartURL = (window.LoessTheme.routes.cart_url || '/cart').replace(/\/$/, '') + '.js';
const response = await fetch(cartURL, { headers: { Accept: 'application/json' }, cache: 'no-store' });
if (!response.ok) throw new Error('Unable to read updated cart');
const cart = await response.json();
const addedItems = Array.isArray(addedState.items) ? addedState.items : [addedState];
const confirmedItems = addedItems.map(added => {
if (added.key) return cart.items.find(item => item.key === added.key);
// Only use a variant ID if it identifies exactly one cart line.
const matches = cart.items.filter(item => String(item.id) === String(added.id));
return matches.length === 1 ? matches[0] : null;
});
if (!confirmedItems.length || confirmedItems.some(item => !item)) {
throw new Error('Unable to identify added cart line');
}
message = confirmedItems.map(item => {
let text = `${item.product_title || item.title || 'Item'} added to cart. Quantity ${item.quantity}.`;
if (typeof item.final_line_price === 'number') {
text += ` Item total ${this.formatCartAnnouncementMoney(item.final_line_price, cart.currency || 'USD')}.`;
}
return text;
}).join(' ');
if (typeof cart.total_price === 'number') {
message += ` Cart total ${this.formatCartAnnouncementMoney(cart.total_price, cart.currency || 'USD')}.`;
}
} catch (error) {
// The add succeeded even if the subsequent read failed. Do not report add failure.
message = 'Item added to cart. Please review the quantity and totals in your cart.';
}
// Let the drawer's own opening/focus announcement happen first.
setTimeout(() => {
if (sequence !== this.cartAddAnnouncementSequence || !status.isConnected) return;
const drawer = this.closest('loess-drawer');
if (drawer && !drawer.open) return;
this.announceCartUpdate(message);
}, 350);
}
formatCartAnnouncementMoney(cents, currency) {
try {
return new Intl.NumberFormat(document.documentElement.lang || 'en', {
style: 'currency', currency
}).format(cents / 100);
} catch (error) {
return `${(cents / 100).toFixed(2)} ${currency}`;
}
}
restoreCartQuantityFocus(line, name, previousControl, shouldRestore) {
// Do not pull focus back if the shopper moved to another control while waiting.
if (!shouldRestore || (document.activeElement !== document.body &&
document.activeElement !== previousControl)) return;
const row = this.querySelector(`#CartItem-${line}`);
let target = row && name && Array.from(row.querySelectorAll('button, input, a')).find(element =>
element.getAttribute('name') === name && !element.disabled);
if (!target) target = row && row.querySelector('.quantity__input');
if (!target) {
const inputs = this.querySelectorAll('.quantity__input');
target = inputs[inputs.length - 1];
}
if (!target) target = this.querySelector('.cart-empty [close]');
if (target) target.focus({ preventScroll: true });
}
renderCartItems(state) {
var _this$parentElement$n;
const parsedState = state;
this.classList.toggle('is-empty', parsedState.item_count === 0);
(_this$parentElement$n = this.parentElement.nextElementSibling) === null || _this$parentElement$n === void 0 ? void 0 : _this$parentElement$n.classList.toggle('hide', parsedState.item_count === 0);
this.renderHTML(parsedState);
this.dispatchCartUpdatedEvent(parsedState);
}
renderHTML(parsedState) {
this.getSectionsToRender().forEach(section => {
var _document$getElementB;
const elementToReplace = ((_document$getElementB = document.getElementById(section.id)) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.querySelector(section.selector)) || document.getElementById(section.id);
if (!elementToReplace) return;
const parsedHTML = new DOMParser().parseFromString(parsedState.sections[section.section], 'text/html').querySelector(section.selector);
if (!parsedHTML) return;
elementToReplace.innerHTML = parsedHTML.innerHTML;
});
}
dispatchCartUpdatedEvent(parsedState) {
document.documentElement.dispatchEvent(new CustomEvent('cart:updated', {
bubbles: true,
detail: {
cart: parsedState
}
}));
}
updateLiveRegions(line, itemCount) {
if (this.currentItemCount === itemCount) {
document.getElementById(`Line-item-error-${line}`).querySelector('.cart-item__error-text').innerHTML = window.LoessTheme.cartStrings.quantityError.replace('[quantity]', document.getElementById(`Quantity-${line}`).value);
}
this.currentItemCount = itemCount;
const cartStatus = document.getElementById('cart-live-region-text');
cartStatus.setAttribute('aria-hidden', false);
setTimeout(() => {
cartStatus.setAttribute('aria-hidden', true);
}, 1000);
}
enableLoading(line) {
document.getElementById('MainCartItems').classList.add('cart__items--disabled');
this.querySelectorAll(`#CartItem-${line} .loading-overlay`).forEach(overlay => overlay.classList.remove('hidden'));
}
disableLoading() {
document.getElementById('MainCartItems').classList.remove('cart__items--disabled');
}
};
customElements.define('loess-cart-items', CartItems);
const CartDrawerItems = class extends CartItems {
getSectionsToRender() {
return [{
id: 'MainCartItems',
section: 'cart-drawer-items',
selector: '.cart-items'
}, {
id: 'HeaderCartIcon',
section: 'header-cart-icon',
selector: '.shopify-section'
}, {
id: 'FreeShippingText',
section: 'free-shipping-text',
selector: '.shopify-section'
}, {
id: 'CartDrawerTotalPrice',
section: 'cart-total-price',
selector: '.shopify-section'
}];
}
};
customElements.define('loess-cart-drawer-items', CartDrawerItems);
const CartNotification = class extends CartItems {
renderCartItems(state) {
this.cartItemKey = state.key;
this.renderHTML(state);
this.dispatchCartUpdatedEvent(state);
}
getSectionsToRender() {
return [{
id: 'HeaderCartIcon',
section: 'header-cart-icon',
selector: '.shopify-section'
}, {
id: 'CartNotificationButton',
section: 'cart-notification-button',
selector: '.shopify-section'
}, {
id: 'CartNotificationProduct',
section: 'cart-notification-product',
selector: `[id="CartNotificationProduct-${this.cartItemKey}"]`
}, {
id: 'FreeShippingText',
section: 'free-shipping-text',
selector: '.shopify-section'
}];
}
};
customElements.define('loess-cart-notification', CartNotification);
window.customElements.define('loess-cart-drawer-checkout', class extends HTMLElement {
constructor() {
super();
this.parentElement.addEventListener('click', this.redirect.bind(this));
}
redirect() {
this.parentElement.nextElementSibling.classList.remove('hide');
this.parentElement.remove();
}
});
window.customElements.define('loess-cart-recommendations', class extends HTMLElement {
constructor() {
super();
if (!this.productId) return;
this.initProductRecommendations();
}
connectedCallback() {
document.documentElement.addEventListener('cart:updated', event => {
this.updateProductId(event);
this.initProductRecommendations();
});
}
async initProductRecommendations() {
const response = await fetch(this.buildQueryString());
const text = await response.text();
this.injectHTMLResponse(text);
}
updateProductId(event) {
var _event$detail$cart$it;
this.setAttribute('product-id', event.detail.cart.product_id || ((_event$detail$cart$it = event.detail.cart.items[0]) === null || _event$detail$cart$it === void 0 ? void 0 : _event$detail$cart$it.product_id) || this.productId);
}
buildQueryString() {
return `${window.LoessTheme.routes.product_recommendations_url}?section_id=cart-drawer-recommendations&product_id=${this.productId}&limit=${this.limit}`;
}
injectHTMLResponse(text) {
const div = document.createElement('div');
div.innerHTML = text;
const productRecommendations = div.querySelector('.shopify-section');
if (productRecommendations && productRecommendations.innerHTML.trim().length) {
var _this$querySelector;
(_this$querySelector = this.querySelector('ul')) === null || _this$querySelector === void 0 ? void 0 : _this$querySelector.remove();
this.insertAdjacentHTML('beforeend', productRecommendations.innerHTML);
}
}
get productId() {
return this.getAttribute('product-id');
}
get limit() {
return this.getAttribute('limit');
}
});
const StickyScrollMixin = {
setupStickyScroll(element) {
this.getInitialValues(element);
this.checkPosition = this.checkPosition.bind(this);
window.addEventListener('scroll', this.checkPosition);
},
destroyStickyScroll() {
window.removeEventListener('scroll', this.checkPosition);
},
getInitialValues(element) {
this.element = element;
this.lastKnownY = window.scrollY;
this.currentTop = 0;
this.pendingRaf = false;
this.stickyHeaderOffset = this.getStickyHeaderOffset();
},
checkPosition() {
if (this.pendingRaf) return;
this.pendingRaf = true;
requestAnimationFrame(() => {
const {
top
} = this.element.getBoundingClientRect();
const maxTop = top + window.scrollY - this.element.offsetTop + this.getTopOffset();
const minTop = this.element.clientHeight - window.innerHeight + 30;
if (window.scrollY < this.lastKnownY) {
this.currentTop -= window.scrollY - this.lastKnownY;
} else {
this.currentTop += this.lastKnownY - window.scrollY;
}
this.lastKnownY = window.scrollY;
this.currentTop = Math.min(Math.max(this.currentTop, -minTop), maxTop, this.getTopOffset());
this.element.style.top = `${this.currentTop}px`;
this.pendingRaf = false;
});
},
getTopOffset() {
return this.stickyHeaderOffset + 30;
},
getStickyHeaderOffset() {
const documentStyles = getComputedStyle(document.documentElement);
return parseInt(documentStyles.getPropertyValue('--header-height') || 0) * parseInt(documentStyles.getPropertyValue('--enable-sticky-header') || 0);
}
};
const LoessCartBlocks = class extends HTMLElement {
constructor() {
super();
this.setupStickyScroll(this);
}
};
Object.assign(LoessCartBlocks.prototype, StickyScrollMixin);
window.customElements.define('loess-cart-blocks', LoessCartBlocks);
/*!
* tabbable 5.3.3
* @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
*/
var candidateSelectors = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]:not(slot)', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable="false"])', 'details>summary:first-of-type', 'details'];
var candidateSelector = /* #__PURE__ */candidateSelectors.join(',');
var NoElement = typeof Element === 'undefined';
var matches = NoElement ? function () {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
var getRootNode = !NoElement && Element.prototype.getRootNode ? function (element) {
return element.getRootNode();
} : function (element) {
return element.ownerDocument;
};
/**
* @param {Element} el container to check in
* @param {boolean} includeContainer add container to check
* @param {(node: Element) => boolean} filter filter candidates
* @returns {Element[]}
*/
var getCandidates = function getCandidates(el, includeContainer, filter) {
var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));
if (includeContainer && matches.call(el, candidateSelector)) {
candidates.unshift(el);
}
candidates = candidates.filter(filter);
return candidates;
};
/**
* @callback GetShadowRoot
* @param {Element} element to check for shadow root
* @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available.
*/
/**
* @callback ShadowRootFilter
* @param {Element} shadowHostNode the element which contains shadow content
* @returns {boolean} true if a shadow root could potentially contain valid candidates.
*/
/**
* @typedef {Object} CandidatesScope
* @property {Element} scope contains inner candidates
* @property {Element[]} candidates
*/
/**
* @typedef {Object} IterativeOptions
* @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not;
* if a function, implies shadow support is enabled and either returns the shadow root of an element
* or a boolean stating if it has an undisclosed shadow root
* @property {(node: Element) => boolean} filter filter candidates
* @property {boolean} flatten if true then result will flatten any CandidatesScope into the returned list
* @property {ShadowRootFilter} shadowRootFilter filter shadow roots;
*/
/**
* @param {Element[]} elements list of element containers to match candidates from
* @param {boolean} includeContainer add container list to check
* @param {IterativeOptions} options
* @returns {Array.}
*/
var getCandidatesIteratively = function getCandidatesIteratively(elements, includeContainer, options) {
var candidates = [];
var elementsToCheck = Array.from(elements);
while (elementsToCheck.length) {
var element = elementsToCheck.shift();
if (element.tagName === 'SLOT') {
// add shadow dom slot scope (slot itself cannot be focusable)
var assigned = element.assignedElements();
var content = assigned.length ? assigned : element.children;
var nestedCandidates = getCandidatesIteratively(content, true, options);
if (options.flatten) {
candidates.push.apply(candidates, nestedCandidates);
} else {
candidates.push({
scope: element,
candidates: nestedCandidates
});
}
} else {
// check candidate element
var validCandidate = matches.call(element, candidateSelector);
if (validCandidate && options.filter(element) && (includeContainer || !elements.includes(element))) {
candidates.push(element);
} // iterate over shadow content if possible
var shadowRoot = element.shadowRoot || // check for an undisclosed shadow
typeof options.getShadowRoot === 'function' && options.getShadowRoot(element);
var validShadowRoot = !options.shadowRootFilter || options.shadowRootFilter(element);
if (shadowRoot && validShadowRoot) {
// add shadow dom scope IIF a shadow root node was given; otherwise, an undisclosed
// shadow exists, so look at light dom children as fallback BUT create a scope for any
// child candidates found because they're likely slotted elements (elements that are
// children of the web component element (which has the shadow), in the light dom, but
// slotted somewhere _inside_ the undisclosed shadow) -- the scope is created below,
// _after_ we return from this recursive call
var _nestedCandidates = getCandidatesIteratively(shadowRoot === true ? element.children : shadowRoot.children, true, options);
if (options.flatten) {
candidates.push.apply(candidates, _nestedCandidates);
} else {
candidates.push({
scope: element,
candidates: _nestedCandidates
});
}
} else {
// there's not shadow so just dig into the element's (light dom) children
// __without__ giving the element special scope treatment
elementsToCheck.unshift.apply(elementsToCheck, element.children);
}
}
}
return candidates;
};
var getTabindex = function getTabindex(node, isScope) {
if (node.tabIndex < 0) {
// in Chrome, , and elements get a default
// `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
// yet they are still part of the regular tab order; in FF, they get a default
// `tabIndex` of 0; since Chrome still puts those elements in the regular tab
// order, consider their tab index to be 0.
// Also browsers do not return `tabIndex` correctly for contentEditable nodes;
// so if they don't have a tabindex attribute specifically set, assume it's 0.
//
// isScope is positive for custom element with shadow root or slot that by default
// have tabIndex -1, but need to be sorted by document order in order for their
// content to be inserted in the correct position
if ((isScope || /^(AUDIO|VIDEO|DETAILS)$/.test(node.tagName) || node.isContentEditable) && isNaN(parseInt(node.getAttribute('tabindex'), 10))) {
return 0;
}
}
return node.tabIndex;
};
var sortOrderedTabbables = function sortOrderedTabbables(a, b) {
return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex;
};
var isInput = function isInput(node) {
return node.tagName === 'INPUT';
};
var isHiddenInput = function isHiddenInput(node) {
return isInput(node) && node.type === 'hidden';
};
var isDetailsWithSummary = function isDetailsWithSummary(node) {
var r = node.tagName === 'DETAILS' && Array.prototype.slice.apply(node.children).some(function (child) {
return child.tagName === 'SUMMARY';
});
return r;
};
var getCheckedRadio = function getCheckedRadio(nodes, form) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked && nodes[i].form === form) {
return nodes[i];
}
}
};
var isTabbableRadio = function isTabbableRadio(node) {
if (!node.name) {
return true;
}
var radioScope = node.form || getRootNode(node);
var queryRadios = function queryRadios(name) {
return radioScope.querySelectorAll('input[type="radio"][name="' + name + '"]');
};
var radioSet;
if (typeof window !== 'undefined' && typeof window.CSS !== 'undefined' && typeof window.CSS.escape === 'function') {
radioSet = queryRadios(window.CSS.escape(node.name));
} else {
try {
radioSet = queryRadios(node.name);
} catch (err) {
// eslint-disable-next-line no-console
console.error('Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s', err.message);
return false;
}
}
var checked = getCheckedRadio(radioSet, node.form);
return !checked || checked === node;
};
var isRadio = function isRadio(node) {
return isInput(node) && node.type === 'radio';
};
var isNonTabbableRadio = function isNonTabbableRadio(node) {
return isRadio(node) && !isTabbableRadio(node);
};
var isZeroArea = function isZeroArea(node) {
var _node$getBoundingClie = node.getBoundingClientRect(),
width = _node$getBoundingClie.width,
height = _node$getBoundingClie.height;
return width === 0 && height === 0;
};
var isHidden = function isHidden(node, _ref) {
var displayCheck = _ref.displayCheck,
getShadowRoot = _ref.getShadowRoot;
// NOTE: visibility will be `undefined` if node is detached from the document
// (see notes about this further down), which means we will consider it visible
// (this is legacy behavior from a very long way back)
// NOTE: we check this regardless of `displayCheck="none"` because this is a
// _visibility_ check, not a _display_ check
if (getComputedStyle(node).visibility === 'hidden') {
return true;
}
var isDirectSummary = matches.call(node, 'details>summary:first-of-type');
var nodeUnderDetails = isDirectSummary ? node.parentElement : node;
if (matches.call(nodeUnderDetails, 'details:not([open]) *')) {
return true;
} // The root node is the shadow root if the node is in a shadow DOM; some document otherwise
// (but NOT _the_ document; see second 'If' comment below for more).
// If rootNode is shadow root, it'll have a host, which is the element to which the shadow
// is attached, and the one we need to check if it's in the document or not (because the
// shadow, and all nodes it contains, is never considered in the document since shadows
// behave like self-contained DOMs; but if the shadow's HOST, which is part of the document,
// is hidden, or is not in the document itself but is detached, it will affect the shadow's
// visibility, including all the nodes it contains). The host could be any normal node,
// or a custom element (i.e. web component). Either way, that's the one that is considered
// part of the document, not the shadow root, nor any of its children (i.e. the node being
// tested).
// If rootNode is not a shadow root, it won't have a host, and so rootNode should be the
// document (per the docs) and while it's a Document-type object, that document does not
// appear to be the same as the node's `ownerDocument` for some reason, so it's safer
// to ignore the rootNode at this point, and use `node.ownerDocument`. Otherwise,
// using `rootNode.contains(node)` will _always_ be true we'll get false-positives when
// node is actually detached.
var nodeRootHost = getRootNode(node).host;
var nodeIsAttached = (nodeRootHost === null || nodeRootHost === void 0 ? void 0 : nodeRootHost.ownerDocument.contains(nodeRootHost)) || node.ownerDocument.contains(node);
if (!displayCheck || displayCheck === 'full') {
if (typeof getShadowRoot === 'function') {
// figure out if we should consider the node to be in an undisclosed shadow and use the
// 'non-zero-area' fallback
var originalNode = node;
while (node) {
var parentElement = node.parentElement;
var rootNode = getRootNode(node);
if (parentElement && !parentElement.shadowRoot && getShadowRoot(parentElement) === true // check if there's an undisclosed shadow
) {
// node has an undisclosed shadow which means we can only treat it as a black box, so we
// fall back to a non-zero-area test
return isZeroArea(node);
} else if (node.assignedSlot) {
// iterate up slot
node = node.assignedSlot;
} else if (!parentElement && rootNode !== node.ownerDocument) {
// cross shadow boundary
node = rootNode.host;
} else {
// iterate up normal dom
node = parentElement;
}
}
node = originalNode;
} // else, `getShadowRoot` might be true, but all that does is enable shadow DOM support
// (i.e. it does not also presume that all nodes might have undisclosed shadows); or
// it might be a falsy value, which means shadow DOM support is disabled
// Since we didn't find it sitting in an undisclosed shadow (or shadows are disabled)
// now we can just test to see if it would normally be visible or not, provided it's
// attached to the main document.
// NOTE: We must consider case where node is inside a shadow DOM and given directly to
// `isTabbable()` or `isFocusable()` -- regardless of `getShadowRoot` option setting.
if (nodeIsAttached) {
// this works wherever the node is: if there's at least one client rect, it's
// somehow displayed; it also covers the CSS 'display: contents' case where the
// node itself is hidden in place of its contents; and there's no need to search
// up the hierarchy either
return !node.getClientRects().length;
} // Else, the node isn't attached to the document, which means the `getClientRects()`
// API will __always__ return zero rects (this can happen, for example, if React
// is used to render nodes onto a detached tree, as confirmed in this thread:
// https://github.com/facebook/react/issues/9117#issuecomment-284228870)
//
// It also means that even window.getComputedStyle(node).display will return `undefined`
// because styles are only computed for nodes that are in the document.
//
// NOTE: THIS HAS BEEN THE CASE FOR YEARS. It is not new, nor is it caused by tabbable
// somehow. Though it was never stated officially, anyone who has ever used tabbable
// APIs on nodes in detached containers has actually implicitly used tabbable in what
// was later (as of v5.2.0 on Apr 9, 2021) called `displayCheck="none"` mode -- essentially
// considering __everything__ to be visible because of the innability to determine styles.
} else if (displayCheck === 'non-zero-area') {
// NOTE: Even though this tests that the node's client rect is non-zero to determine
// whether it's displayed, and that a detached node will __always__ have a zero-area
// client rect, we don't special-case for whether the node is attached or not. In
// this mode, we do want to consider nodes that have a zero area to be hidden at all
// times, and that includes attached or not.
return isZeroArea(node);
} // visible, as far as we can tell, or per current `displayCheck` mode
return false;
}; // form fields (nested) inside a disabled fieldset are not focusable/tabbable
// unless they are in the _first_
Please Note: All Measurements Were Taken By Hand And Are Approximate; Slight Variations May Occur.
Hailed For Its Beautifully-Crafted Cashmere Pieces, Brunello Cucinelli Was Named Gq's Designer Of The Year In 2021. With Attention To Craftsmanship And Sustainability, The Company Exemplifies Italian Luxury.
Our Products Are 100% Genuine. In Some Cases We Purchase Merchandise From Trusted Independent Suppliers And Not Directly From The Brand Owner. In All Cases We Stand By The Authenticity Of Every Product Sold On Our Site.