UNPKG

@wordpress/components

Version:
194 lines (193 loc) • 13.1 kB
import { TabList as TabList$1, useStoreState } from "@ariakit/react"; import clsx from "clsx"; import warning from "@wordpress/warning"; import { forwardRef, useLayoutEffect, useState } from "@wordpress/element"; import { useMergeRefs } from "@wordpress/compose"; import { useTabsContext } from "./context.mjs"; import { useTrackElementOffsetRect } from "../utils/element-rect.mjs"; import { useTrackOverflow } from "./use-track-overflow.mjs"; import { useAnimatedOffsetRect } from "../utils/hooks/use-animated-offset-rect.mjs"; import { jsx } from "react/jsx-runtime"; // packages/style-runtime/src/index.ts const STYLE_HASH_ATTRIBUTE = "data-wp-hash"; /** * Returns the shared style runtime registry. * * The registry is stored on `globalThis` so separately bundled copies of this * package can coordinate through the same document and style maps. * * @return The shared runtime registry. */ function getRuntime() { const globalScope = globalThis; if (globalScope.__wpStyleRuntime) return globalScope.__wpStyleRuntime; globalScope.__wpStyleRuntime = { documents: /* @__PURE__ */ new Map(), styles: /* @__PURE__ */ new Map(), injectedStyles: /* @__PURE__ */ new WeakMap() }; if (typeof document !== "undefined") registerDocument(document); return globalScope.__wpStyleRuntime; } /** * Checks whether a document already contains a style tag for a hash. * * @param targetDocument Document to inspect. * @param hash Stable hash for the transformed CSS. * * @return Whether the style hash already exists in the document. */ function documentContainsStyleHash(targetDocument, hash) { if (!targetDocument.head) return false; for (const style of targetDocument.head.querySelectorAll(`style[${STYLE_HASH_ATTRIBUTE}]`)) if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) return true; return false; } /** * Injects a registered style into a document, unless that document already * contains a style tag for the same hash. * * @param targetDocument Document to inject the style into. * @param hash Stable hash for the transformed CSS. * @param css CSS text to inject. */ function injectStyle(targetDocument, hash, css) { if (!targetDocument.head) return; const runtime = getRuntime(); let injectedStyles = runtime.injectedStyles.get(targetDocument); if (!injectedStyles) { injectedStyles = /* @__PURE__ */ new Set(); runtime.injectedStyles.set(targetDocument, injectedStyles); } if (injectedStyles.has(hash)) return; if (documentContainsStyleHash(targetDocument, hash)) { injectedStyles.add(hash); return; } const style = targetDocument.createElement("style"); style.setAttribute(STYLE_HASH_ATTRIBUTE, hash); style.appendChild(targetDocument.createTextNode(css)); targetDocument.head.appendChild(style); injectedStyles.add(hash); } /** * Registers a document as a style injection target. * * Existing registered styles are replayed into the document immediately. * Documents are reference-counted so multiple providers can safely register the * same document without one cleanup removing it while another registration is * still active. * * @param targetDocument Document to receive registered styles. * @return Cleanup function that unregisters this document registration. */ function registerDocument(targetDocument) { const runtime = getRuntime(); runtime.documents.set(targetDocument, (runtime.documents.get(targetDocument) ?? 0) + 1); for (const [hash, css] of runtime.styles) injectStyle(targetDocument, hash, css); return () => { const count = runtime.documents.get(targetDocument); if (count === void 0) return; if (count <= 1) { runtime.documents.delete(targetDocument); return; } runtime.documents.set(targetDocument, count - 1); }; } /** * Registers a style and injects it into all registered documents. * * The hash is used as the deduplication key, so calling this repeatedly with * the same hash will not add duplicate style tags to a document. * Registered styles are retained for the lifetime of the page so they can be * replayed into documents that are registered later. * * @param hash Stable hash for the transformed CSS. * @param css CSS text to inject. */ function registerStyle(hash, css) { const runtime = getRuntime(); runtime.styles.set(hash, css); for (const targetDocument of runtime.documents.keys()) injectStyle(targetDocument, hash, css); } // packages/components/src/tabs/style.module.scss if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("28b24e1597", ".aedb7ed7e3ceb3b8__tab-list{align-items:stretch;display:flex;overflow-x:auto}.aedb7ed7e3ceb3b8__tab-list[aria-orientation=vertical]{flex-direction:column}.aedb7ed7e3ceb3b8__tab-list:where([aria-orientation=horizontal]){width:fit-content}.aedb7ed7e3ceb3b8__tab-list{--direction-factor:1;--direction-start:left;--direction-end:right;--selected-start:var(--selected-left,0)}.aedb7ed7e3ceb3b8__tab-list:dir(rtl){--direction-factor:-1;--direction-start:right;--direction-end:left;--selected-start:var(--selected-right,0)}@media not (prefers-reduced-motion){.aedb7ed7e3ceb3b8__tab-list[data-indicator-animated]:before{transition-duration:.2s;transition-property:transform;transition-timing-function:ease-out}}.aedb7ed7e3ceb3b8__tab-list{position:relative}.aedb7ed7e3ceb3b8__tab-list:before{color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);content:\"\";outline:2px solid transparent;outline-offset:-1px;pointer-events:none;position:absolute;transform-origin:var(--direction-start) top}.aedb7ed7e3ceb3b8__tab-list{--antialiasing-factor:100}.aedb7ed7e3ceb3b8__tab-list[aria-orientation=horizontal]{--fade-width:64px;--fade-gradient-base:transparent 0%,#000 var(--fade-width);--fade-gradient-composed:var(--fade-gradient-base),#000 60%,transparent 50%}.aedb7ed7e3ceb3b8__tab-list[aria-orientation=horizontal].is-overflowing-first{mask-image:linear-gradient(to var(--direction-end),var(--fade-gradient-base))}.aedb7ed7e3ceb3b8__tab-list[aria-orientation=horizontal].is-overflowing-last{mask-image:linear-gradient(to var(--direction-start),var(--fade-gradient-base))}.aedb7ed7e3ceb3b8__tab-list[aria-orientation=horizontal].is-overflowing-first.is-overflowing-last{mask-image:linear-gradient(to right,var(--fade-gradient-composed)),linear-gradient(to left,var(--fade-gradient-composed))}.aedb7ed7e3ceb3b8__tab-list[aria-orientation=horizontal]:before{border-bottom:var(--wp-admin-border-width-focus) solid;bottom:0;height:0;transform:translateX(calc(var(--selected-start)*var(--direction-factor)*1px)) scaleX(calc(var(--selected-width, 0)/var(--antialiasing-factor)));width:calc(var(--antialiasing-factor)*1px)}.aedb7ed7e3ceb3b8__tab-list:has([aria-selected=true]:not([aria-disabled=true])[data-focus-visible]):before{color:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e)}@media not (prefers-reduced-motion){.aedb7ed7e3ceb3b8__tab-list[aria-orientation=vertical][data-indicator-animated]:before{transition-property:transform,height}}.aedb7ed7e3ceb3b8__tab-list[aria-orientation=vertical]:before{background-color:currentColor;height:max(0px,var(--selected-height,0) * 1px - 2 * var(--wpds-dimension-padding-md,12px));inset-inline-start:0;top:var(--wpds-dimension-padding-md,12px);transform:translateY(calc(var(--selected-top, 0)*1px));width:var(--wp-admin-border-width-focus);z-index:1}.d392328761fe616c__tab{align-items:center;background:transparent;border:none;border-radius:0;box-shadow:none;color:var(--wpds-color-foreground-interactive-neutral,#1e1e1e);cursor:pointer;display:flex;flex:1 0 auto;font-family:var(--wpds-typography-font-family-body,-apple-system,system-ui,\"Segoe UI\",\"Roboto\",\"Oxygen-Sans\",\"Ubuntu\",\"Cantarell\",\"Helvetica Neue\",sans-serif);font-size:13px;font-weight:400;line-height:1.2;white-space:nowrap}.d392328761fe616c__tab:is([aria-selected=true],[aria-disabled=true]){cursor:default}.d392328761fe616c__tab[aria-disabled=true]{color:var(--wpds-color-foreground-interactive-neutral-disabled,#8b8b8b)}.d392328761fe616c__tab:not([aria-disabled=true]):is(:not([aria-selected=true]):hover,:not([aria-selected=true]):active,[data-focus-visible]){color:var(--wpds-color-foreground-interactive-neutral-active,#1e1e1e)}.d392328761fe616c__tab:not([aria-disabled=true]):is(:not([aria-selected=true]):hover,:not([aria-selected=true]):active,[data-focus-visible]):after{background-color:var(--wpds-color-background-interactive-neutral-weak-active,#ececec);opacity:1}.d392328761fe616c__tab:focus:not(:disabled){box-shadow:none;outline:none}.d392328761fe616c__tab{isolation:isolate;position:relative}.d392328761fe616c__tab:after{border-radius:2px;opacity:0;outline:var(--wp-admin-border-width-focus) solid transparent;pointer-events:none;position:absolute;z-index:-1}@media not (prefers-reduced-motion){.d392328761fe616c__tab:after{transition:opacity .1s linear}}.d392328761fe616c__tab[data-focus-visible]:after{opacity:1;outline-color:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9))}[aria-orientation=horizontal] .d392328761fe616c__tab{height:48px;padding-inline:16px;scroll-margin:24px}[aria-orientation=horizontal] .d392328761fe616c__tab:after{content:\"\";inset:var(--wpds-dimension-padding-md,12px)}[aria-orientation=vertical] .d392328761fe616c__tab{min-height:var(--wpds-dimension-size-lg,40px);padding:var(--wpds-dimension-padding-md,12px)}[aria-orientation=vertical] .d392328761fe616c__tab:after{content:\"\";inset:0;outline-offset:calc(var(--wp-admin-border-width-focus)*-1)}.d9b72f97a5e9d4a2__tab-children{align-items:center;display:flex;flex-grow:1}[aria-orientation=horizontal] .d9b72f97a5e9d4a2__tab-children{justify-content:center}[aria-orientation=vertical] .d9b72f97a5e9d4a2__tab-children{justify-content:start}._6327f0cce5ff83f2__tab-panel:focus{outline:none}._6327f0cce5ff83f2__tab-panel[data-focus-visible]{outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--focus-color,var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9)));outline-offset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px));outline-offset:0}"); var style_module_default = { "tab-list": "aedb7ed7e3ceb3b8__tab-list", "tab": "d392328761fe616c__tab", "tab-children": "d9b72f97a5e9d4a2__tab-children", "tab-panel": "_6327f0cce5ff83f2__tab-panel" }; // packages/components/src/tabs/tablist.tsx const DEFAULT_SCROLL_MARGIN = 24; /** * Scrolls a given parent element so that a given rect is visible. * * The scroll is updated initially and whenever the rect changes. */ function useScrollRectIntoView(parent, rect, { margin = DEFAULT_SCROLL_MARGIN } = {}) { useLayoutEffect(() => { if (!parent || !rect) return; const { scrollLeft: parentScroll } = parent; const parentWidth = parent.getBoundingClientRect().width; const { left: childLeft, width: childWidth } = rect; const parentRightEdge = parentScroll + parentWidth; const rightOverflow = childLeft + childWidth + margin - parentRightEdge; const leftOverflow = parentScroll - (childLeft - margin); let scrollLeft = null; if (leftOverflow > 0) scrollLeft = parentScroll - leftOverflow; else if (rightOverflow > 0) scrollLeft = parentScroll + rightOverflow; if (scrollLeft !== null) /** * The optional chaining is used here to avoid unit test failures. * It can be removed when JSDOM supports `Element` scroll methods. * See: https://github.com/WordPress/gutenberg/pull/66498#issuecomment-2441146096 */ parent.scroll?.({ left: scrollLeft }); }, [ margin, parent, rect ]); } const TabList = forwardRef(function UnforwardedTabList({ children, ...otherProps }, ref) { const { store } = useTabsContext() ?? {}; const selectedId = useStoreState(store, "selectedId"); const selectOnMove = useStoreState(store, "selectOnMove"); const items = useStoreState(store, "items"); const [parent, setParent] = useState(); const refs = useMergeRefs([ref, setParent]); const selectedItem = store?.item(selectedId); const renderedItems = useStoreState(store, "renderedItems"); const selectedItemIndex = renderedItems && selectedItem ? renderedItems.indexOf(selectedItem) : -1; const selectedRect = useTrackElementOffsetRect(selectedItem?.element, [selectedItemIndex]); const overflow = useTrackOverflow(parent, { first: items?.at(0)?.element, last: items?.at(-1)?.element }); useAnimatedOffsetRect(parent, selectedRect, { prefix: "selected", dataAttribute: "indicator-animated", transitionEndFilter: (event) => event.pseudoElement === "::before", roundRect: true }); useScrollRectIntoView(parent, selectedRect); if (!store) { warning("`Tabs.TabList` must be wrapped in a `Tabs` component."); return null; } return /* @__PURE__ */ jsx(TabList$1, { ref: refs, store, render: (props) => /* @__PURE__ */ jsx("div", { ...props, tabIndex: props.tabIndex ?? -1 }), "data-select-on-move": selectOnMove ? "true" : "false", ...otherProps, className: clsx(style_module_default["tab-list"], overflow.first && "is-overflowing-first", overflow.last && "is-overflowing-last", otherProps.className), children }); }); export { TabList }; //# sourceMappingURL=tablist.mjs.map