@data-slot/core

中文文档
1.1.3发布于 2026/11/05MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 2.7万

Shared utilities for data-slot headless UI components.

原始使用文档
文档目录12 节
  1. Installation
  2. API
  3. DOM Utilities
  4. Focus Utilities
  5. ARIA Utilities
  6. Event Utilities
  7. Modal and Dismissal Utilities
  8. Swipe Gesture
  9. Usage in Components
  10. Terminal lifecycle
  11. License
  12. Retaining closed overlay content

@data-slot/core

Shared utilities for data-slot headless UI components.

Installation

npm install @data-slot/core

API

DOM Utilities

getPart(root, slot)

Query a single part/slot within a component root.

const trigger = getPart<HTMLButtonElement>(root, "dialog-trigger");

getParts(root, slot)

Query all parts/slots within a component root.

const items = getParts<HTMLElement>(root, "accordion-item");

getRoots(scope, slot)

Find all component roots within a scope by data-slot value.

const dialogs = getRoots(document, "dialog");

Focus Utilities

isFocusable(element) checks whether an individual element can receive programmatic focus, using the same eligibility rules as descendant discovery.

getFocusable(container) returns programmatically focusable descendants in DOM order, including elements with a negative tabindex. getTabbables(container) returns the subset eligible for Tab navigation, accounting for checked radio groups. It also returns DOM order rather than sorting positive tabindex values.

getAutofocusOrFirstFocusable(container) selects an eligible [autofocus] descendant, otherwise the first focusable descendant, or undefined if none exist.

Each call reads current DOM state. Hidden, inert, and natively disabled controls are excluded. aria-disabled and data-disabled alone do not remove native focus eligibility. Queries exclude the container itself and do not cross into nested shadow roots; pass a shadow root directly to query its descendants.

ARIA Utilities

ensureId(element, prefix)

Ensure an element has an id, generating one if needed.

const id = ensureId(content, "dialog-content");
// Returns existing id or generates "dialog-content-1"

setAria(element, name, value)

Set or remove an ARIA attribute. Boolean values are converted to strings.

setAria(trigger, "expanded", true);  // aria-expanded="true"
setAria(trigger, "expanded", null);  // removes aria-expanded

linkLabelledBy(content, title, description)

Link content element to its label and description via ARIA.

linkLabelledBy(dialogContent, titleElement, descriptionElement);
// Sets aria-labelledby and aria-describedby

Event Utilities

on(element, type, handler, options?)

Add an event listener and return a cleanup function.

const cleanup = on(button, "click", () => console.log("clicked"));
// Later: cleanup() to remove listener

onRoot(root, type, handler)

Listen for events dispatched directly on a component root. Events bubbling from descendants are ignored by this handler and continue to propagate. Returns a cleanup function, like on.

Use this for inbound component commands so nested instances cannot change their parent's state:

const cleanup = onRoot(root, "tabs:set", handleSet);

emit(element, name, detail?)

Dispatch a bubbling custom event with optional detail. Outbound component events can be observed on ancestors; check event.target to identify the source root.

emit(root, "tabs:change", { value: "tab-2" });

composeHandlers(...handlers)

Compose multiple event handlers into one. Stops if event.defaultPrevented.

const handler = composeHandlers(onClickProp, internalHandler);

Modal and Dismissal Utilities

createModalStackItem(options)

Register a surface with the document's modal stack. The controller provides open(), close(), destroy(), and a readonly isTopmost property. Use isTopmost for interaction ownership rather than reading the styling attributes.

Set isolateOutside: true to keep background content inert and hidden from assistive technology while that item is open. Isolation follows the topmost stack item, including a dialog opened above a drawer, and permits its owned portals. Closing or destroying items restores the previous isolation and authored attributes. Items that do not request isolation retain their existing behavior when no isolating item is open.

createDismissLayer(options)

Coordinate outside presses, Escape, and focus moving into an outside iframe. onDismiss(details) receives the triggering originalEvent and its reason: "outside-press", "escape-key", or "focus-out". Touch dismissal reports the activation click; iframe dismissal reports the window blur event. Callbacks that do not need these details can continue to take no arguments.

Swipe Gesture

createSwipeGesture(options)

Track one pointer or touch swipe at a time from a press on element. Nothing is reported until movement passes lockThreshold (default 8px) on one of the allowed axes; a drag dominated by another axis, or one the lock callback refuses (for example when a scroll container owns it), is left to the page. start(event, target) resolves what a press would swipe or returns null to ignore it. Once locked, the pointer is captured on the element capture returns, move receives raw deltas, and release adds the press duration for velocity. reset runs when a locked gesture ends without a release. The click that follows a released swipe is swallowed. The controller offers cancel(), optionally for one target, and destroy().

Usage in Components

This package is used internally by all @data-slot/* component packages. You typically don't need to import it directly unless building custom components.

import { getPart, setAria, on } from "@data-slot/core";

function createCustomComponent(root: Element) {
  const trigger = getPart(root, "custom-trigger");
  const content = getPart(root, "custom-content");
  
  const cleanup = on(trigger, "click", () => {
    const isOpen = content.hidden;
    content.hidden = !isOpen;
    setAria(trigger, "expanded", isOpen);
  });
  
  return { destroy: cleanup };
}

Terminal lifecycle

createTerminalLifecycle() manages work that must stop permanently when a controller is destroyed. It returns a TerminalLifecycleController:

MemberBehavior
isDestroyedBecomes true after the before-destroy hooks and before resource cleanup.
trackRaf(callback)Schedules an animation frame; returns its handle or null once destruction starts.
trackTimeout(callback, delay)Schedules a timeout; returns its handle or null once destruction starts.
cancelRaf(handle) / cancelTimeout(handle)Cancel tracked work and immediately release its handle. Null, finished, or already-canceled handles are ignored. Use these methods instead of native cancellation for tracked work.
onBeforeDestroy(callback)Registers synchronous preparation after ordinary pending work is canceled, before resource cleanup.
trackFinalRaf(callback)Schedules a final frame only from a before-destroy hook. This frame deliberately survives destruction, for example to finish an already-pending focus restoration. Returns null outside that phase.
onDestroy(callback)Registers synchronous resource cleanup, or runs it immediately if already destroyed.
destroy()Cancels pending work and runs hooks once. Returns true for the first destruction, false for repeated or reentrant calls.
import { createTerminalLifecycle } from "@data-slot/core";

const lifecycle = createTerminalLifecycle();
const frame = lifecycle.trackRaf(() => updatePosition());
lifecycle.cancelRaf(frame);
lifecycle.onDestroy(() => observer.disconnect());
lifecycle.destroy();

registerFloatingTerminalResources(lifecycle, resources) registers cleanup for positionSync, presence, portal, a cleanups array, and an unbind callback, in that order. The resources use the exported FloatingTerminalResources type. The component remains responsible for its closed state and focus policy.

registerModalTerminalResources(lifecycle, resources) optionally registers a beforeDestroy hook, then disposes modalStack, each entry in the presence array, calls reset, releaseScrollLock, and cleanup, cleans up the nullable portal, drains listener cleanups, and calls unbind, in that order. ModalTerminalResources describes these callbacks and resources. Focus policy and interaction events remain the component's responsibility.

drainCleanups(cleanups) removes the current callbacks from an array and invokes them in order. Repeating the call on the emptied array does nothing. Cleanup callbacks should complete synchronously without throwing.

License

MIT

Retaining closed overlay content

createContentMount({ root, target, strategy: "lazy" }) retains the same authored nodes outside the connected document. Pass the outer authored portal/positioner as target when present. strategy: "eager" leaves content connected.

  • Call mount() before portal mounting, positioning, ARIA references, or focus.
  • Call unmount() after the presence exit completes and the portal is restored.
  • Call cleanup() after portal cleanup to restore authored placement and remove the placeholder. Cleanup is terminal and idempotent.

The helper only owns placement. Components own visibility, animation, focus, ARIA, and open state. getRoots(scope, slot) includes nested component roots in retained content owned by roots within that scope; regular DOM queries do not. Detachment reduces live DOM after initialization, not server-rendered HTML bytes.

版本与发布记录

@data-slot/core 共发布 165 个版本,首次发布于 2026/01/09;过去 12 个月发布了 165 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.3latest2026/11/056 天前
1.1.22026/10/1428 天前
1.1.12026/10/051 个月前
1.1.02026/10/021 个月前
1.0.22026/09/271 个月前
1.0.12026/09/261 个月前

关于 @data-slot/core 的常见问题

@data-slot/core 是什么?

Shared utilities for data-slot headless UI components.

如何安装 @data-slot/core?

在项目目录运行 npm install @data-slot/core,或使用 pnpm add / yarn add / bun add。

@data-slot/core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@data-slot/core 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@data-slot/core 可以商用吗?

@data-slot/core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@data-slot/core 的下载量有多少?

根据 npm 官方下载统计,@data-slot/core 在 2026/10/12 – 2026/11/10 这 30 天内被下载 27,414 次,日均约 914 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@data-slot/core 还在维护吗?

最新版本 1.1.3 发布于 2026/11/05(6 天前);至今共发布 165 个版本,其中过去 12 个月发布了 165 个;首次发布于 2026/01/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。