@rcarls/rc-common 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,76 @@
1
+ import { PartInfo, ElementPart } from 'lit/directive.js';
2
+ import { AsyncDirective } from 'lit/async-directive.js';
3
+ export type KeyboardNavigationAction = 'next' | 'prev' | 'start' | 'end' | 'open-to-first' | 'open-to-last' | 'escape' | 'activate' | 'toggle';
4
+ /**
5
+ * Options for the keyNavigation directive.
6
+ */
7
+ export interface KeyNavigationOptions {
8
+ /**
9
+ * Set data-interaction-mode attribute for keyboard vs mouse styling.
10
+ * @default true
11
+ */
12
+ useInteractionModeAttr?: boolean;
13
+ /**
14
+ * Dispatch 'escape' action on Escape key.
15
+ * @default false
16
+ */
17
+ handleEscape?: boolean;
18
+ /**
19
+ * Dispatch 'activate' action on Enter/Space.
20
+ * When enabled, Enter/Space will dispatch 'activate' instead of 'toggle'.
21
+ * @default false
22
+ */
23
+ handleActivate?: boolean;
24
+ /**
25
+ * Explicitly set the navigation axis, overriding role-based auto-detection.
26
+ * The navigation axis determines which arrow keys map to 'next'/'prev'.
27
+ * Required when the element has no ARIA role (e.g. a menu-button trigger wrapper).
28
+ */
29
+ navigationAxis?: 'horizontal' | 'vertical';
30
+ /**
31
+ * Handle navigation-axis arrow keys ('next'/'prev') and Home/End ('start'/'end').
32
+ * Set to false for elements that don't navigate items themselves (e.g. menu buttons
33
+ * that let the parent menubar handle navigation).
34
+ * @default true
35
+ */
36
+ handleNavAxis?: boolean;
37
+ /**
38
+ * Handle open-axis arrow keys (perpendicular to the navigation axis).
39
+ * Dispatches 'open-to-first' and 'open-to-last' actions.
40
+ * For horizontal navigation axis: ArrowDown → 'open-to-first', ArrowUp → 'open-to-last'.
41
+ * For vertical navigation axis: ArrowRight → 'open-to-first', ArrowLeft → 'open-to-last'.
42
+ * @default false
43
+ */
44
+ handleOpenAxis?: boolean;
45
+ }
46
+ declare class KeyboardNavigationDirective extends AsyncDirective {
47
+ private _element?;
48
+ private _keyDownHandle;
49
+ private _mouseClickHandle;
50
+ private _callback;
51
+ private _options;
52
+ /**
53
+ * The navigation axis determines which arrow keys map to 'next'/'prev'.
54
+ * Checks the explicit `navigationAxis` option first, then auto-detects
55
+ * from the element's ARIA role and aria-orientation attribute.
56
+ */
57
+ protected get navigationAxis(): 'horizontal' | 'vertical';
58
+ constructor(partInfo: PartInfo);
59
+ private _normalizeKey;
60
+ protected _onKeydown(e: KeyboardEvent): void;
61
+ protected _onMouseClick(_e: MouseEvent): void;
62
+ protected _init(): void;
63
+ /**
64
+ * @param _cb - Callback function invoked with the navigation action
65
+ * @param _options - Options object or deprecated boolean for useInteractionModeAttr
66
+ * @deprecated Passing a boolean as the second parameter is deprecated.
67
+ * Use an options object instead: `{ useInteractionModeAttr: true }`
68
+ */
69
+ render(_cb: (action: KeyboardNavigationAction) => void, _options?: KeyNavigationOptions | boolean): symbol;
70
+ update(part: ElementPart, [cb, optionsOrBoolean]: Parameters<this['render']>): void;
71
+ disconnected(): void;
72
+ reconnected(): void;
73
+ }
74
+ export declare const keyNavigation: (_cb: (action: KeyboardNavigationAction) => void, _options?: boolean | KeyNavigationOptions | undefined) => import('lit/directive.js').DirectiveResult<typeof KeyboardNavigationDirective>;
75
+ export type { KeyboardNavigationDirective };
76
+ export default keyNavigation;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,42 @@
1
+ import { PartInfo, ElementPart } from 'lit/directive.js';
2
+ import { AsyncDirective } from 'lit/async-directive.js';
3
+ /**
4
+ * Lit element directive that invokes a callback during an active pointer drag.
5
+ *
6
+ * The exported name remains `mouseMove` for compatibility, but the directive
7
+ * listens to Pointer Events so mouse, touch, and pen input share the same path.
8
+ */
9
+ declare class MouseMoveDirective extends AsyncDirective {
10
+ private _element?;
11
+ private readonly _pointerDownHandle;
12
+ private readonly _pointerMoveHandle;
13
+ private readonly _pointerEndHandle;
14
+ private _callback;
15
+ private _activePointerId;
16
+ constructor(partInfo: PartInfo);
17
+ /** Start a pointer drag cycle on the directive-decorated element. */
18
+ protected _onPointerDown(evt: PointerEvent): void;
19
+ /** Forward pointer movement during an active drag cycle. */
20
+ protected _onPointerMove(evt: PointerEvent): void;
21
+ /** Finish the active pointer drag cycle and remove temporary listeners. */
22
+ protected _onPointerEnd(evt: PointerEvent): void;
23
+ /** Attach the permanent pointerdown listener to the current element. */
24
+ protected _init(): void;
25
+ /** Remove all listeners associated with the active drag cycle. */
26
+ private _removePointerCycleListeners;
27
+ private _capturePointer;
28
+ private _releasePointer;
29
+ /** Render no DOM; this directive only wires pointer listeners. */
30
+ render(_cb: (e: MouseEvent) => void): symbol;
31
+ update(part: ElementPart, [cb]: Parameters<this['render']>): void;
32
+ disconnected(): void;
33
+ reconnected(): void;
34
+ }
35
+ /**
36
+ * Wire pointer-drag movement to an element without rendering DOM.
37
+ *
38
+ * The callback receives the `PointerEvent` as a `MouseEvent`-compatible object.
39
+ */
40
+ export declare const mouseMove: (_cb: (e: MouseEvent) => void) => import('lit/directive.js').DirectiveResult<typeof MouseMoveDirective>;
41
+ export type { MouseMoveDirective };
42
+ export default mouseMove;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,78 @@
1
+ import { ReactiveController, ReactiveControllerHost } from 'lit';
2
+ export type ResizeDirection = 'none' | 'both' | 'horizontal' | 'vertical';
3
+ export interface ResizeOptions {
4
+ /** The element to resize. Its `width` / `height` (and `left` / `top` for opposite edges) styles are updated. */
5
+ target: Element;
6
+ /** Which edges are resizable, mirroring CSS `resize` values. Defaults to `'none'`. */
7
+ direction?: ResizeDirection;
8
+ /** Custom resize handle element. If omitted, edge detection on `target` is used. */
9
+ handle?: Element | null;
10
+ /** Edge hit-test thickness in px (straddles the edge, inside + outside). Defaults to `8`. */
11
+ threshold?: number;
12
+ /** Bounds constraint. Defaults to `'viewport'`. */
13
+ bounds?: 'viewport' | 'parent' | Element;
14
+ minWidth?: number;
15
+ maxWidth?: number;
16
+ minHeight?: number;
17
+ maxHeight?: number;
18
+ /** Keyboard arrow-key step in px. Shift multiplies by 10. Defaults to `4`. */
19
+ step?: number;
20
+ disabled?: boolean;
21
+ }
22
+ /**
23
+ * Makes an element resizable via pointer (edge detection) and keyboard.
24
+ *
25
+ * Supports all 8 resize handles (n, s, e, w, ne, nw, se, sw) depending on
26
+ * the configured `direction`. Opposite-edge resizes (w / n / nw / ne / sw)
27
+ * anchor the far corner and mutate `left` / `top` accordingly, mirroring
28
+ * OS-windowed resize semantics.
29
+ *
30
+ * On resize start the element's position and size are pinned as explicit
31
+ * `border-box` pixel values so UA centering styles (e.g. `inset:0; margin:auto`
32
+ * on `<dialog>`) cannot fight the resize calculations.
33
+ */
34
+ export declare class ResizeController implements ReactiveController {
35
+ private _opts;
36
+ private _resizing;
37
+ private _startX;
38
+ private _startY;
39
+ private _startW;
40
+ private _startH;
41
+ private _startLeft;
42
+ private _startTop;
43
+ private _effectiveMinW;
44
+ private _effectiveMinH;
45
+ private _cornerBtn;
46
+ private readonly _onPointerMove;
47
+ private readonly _onPointerDown;
48
+ private readonly _onPointerUp;
49
+ private readonly _onPointerLeave;
50
+ private readonly _onKeyDown;
51
+ constructor(host: ReactiveControllerHost, options: ResizeOptions);
52
+ setOptions(next: Partial<ResizeOptions>): void;
53
+ hostConnected(): void;
54
+ hostDisconnected(): void;
55
+ private _target;
56
+ private _injectCornerButton;
57
+ private _removeCornerButton;
58
+ private _cornerCursor;
59
+ private _edgeCursor;
60
+ private _detectEdge;
61
+ /**
62
+ * Pins position and size as explicit border-box pixel values.
63
+ *
64
+ * Required before any resize so that:
65
+ * - UA centering styles (`inset:0; margin:auto` on `<dialog>`) don't fight
66
+ * explicit left/top changes on n/w edges.
67
+ * - Changing width/height alone doesn't redistribute auto-margins and shift
68
+ * the element for e/s edges.
69
+ * - box-sizing is known, so `style.width = rect.width` is a no-op visually.
70
+ */
71
+ private _pinPosition;
72
+ private _handlePointerDown;
73
+ private _handlePointerMove;
74
+ private _handlePointerUp;
75
+ private _handlePointerLeave;
76
+ private _handleKeyDown;
77
+ private _boundsRect;
78
+ }
@@ -0,0 +1,58 @@
1
+ import { LitElement } from 'lit';
2
+ import { FocusableElement } from './isFocusable';
3
+ type Constructor<T = object> = new (...args: any[]) => T;
4
+ /**
5
+ * Ambient class declaration exposing the public + protected shape added by
6
+ * RovingTabIndexMixin. The `declare class` form (rather than an interface) is
7
+ * required so TypeScript can express protected members — subclasses need access
8
+ * to `_lastFocused` and the hook methods inside their own `_initItems` overrides.
9
+ */
10
+ export declare class RovingTabIndexMixinBase {
11
+ protected _lastFocused: FocusableElement | undefined;
12
+ get items(): FocusableElement[];
13
+ get firstItem(): FocusableElement | undefined;
14
+ get lastItem(): FocusableElement | undefined;
15
+ get nextItem(): FocusableElement | undefined;
16
+ get previousItem(): FocusableElement | undefined;
17
+ focusItem(item?: FocusableElement | null): void;
18
+ focusItemAt(index: number): void;
19
+ focusFirst(): void;
20
+ focusLast(): void;
21
+ /**
22
+ * Returns the elements to register from a slot. The default collects ALL
23
+ * direct assigned elements; focusability is checked dynamically by the
24
+ * `items` getter so that elements toggling `disabled` are included or
25
+ * excluded without requiring a new `slotchange`.
26
+ */
27
+ protected _collectItems(slot: HTMLSlotElement): Element[];
28
+ protected _handleItemFocus(e: FocusEvent): void;
29
+ protected _onSlotChange(e: Event): void;
30
+ protected _initItems(): void;
31
+ }
32
+ /**
33
+ * Mixin that adds WAI-ARIA roving-tabindex focus management to a LitElement.
34
+ *
35
+ * Provides item registration from a named slot, focus navigation helpers,
36
+ * tabindex synchronisation on focusin, and hook methods for subclass-specific
37
+ * item configuration (setting roles, collecting items from group containers, etc.).
38
+ *
39
+ * Wire the two event handlers in the subclass `render()`:
40
+ *
41
+ * ```ts
42
+ * html`
43
+ * <div id="slot-wrap" @focusin=${this._handleItemFocus}>
44
+ * <slot @slotchange=${this._onSlotChange}></slot>
45
+ * </div>
46
+ * `
47
+ * ```
48
+ *
49
+ * @example
50
+ * class MyList extends RovingTabIndexMixin(LitElement) {
51
+ * protected override _initItems() {
52
+ * super._initItems(); // sets tabindex
53
+ * this.items.forEach(el => el.setAttribute('role', 'option'));
54
+ * }
55
+ * }
56
+ */
57
+ export declare function RovingTabIndexMixin<T extends Constructor<LitElement>>(Base: T): T & Constructor<RovingTabIndexMixinBase>;
58
+ export {};
@@ -0,0 +1,61 @@
1
+ import { ReactiveController, ReactiveControllerHost } from 'lit';
2
+ export type ScrollObserverTarget = Element | Document | Window;
3
+ /**
4
+ * @callback ScrollObserverChangeCB
5
+ * @param scrolled - whether the target is scrolled past the threshold
6
+ * @param scrollTop - the scroll offset read on the last evaluated frame
7
+ */
8
+ export type ScrollObserverChangeCB = (scrolled: boolean, scrollTop: number) => void;
9
+ /**
10
+ * @callback ScrollObserverScrollCB
11
+ * @param scrollTop - current scroll offset
12
+ * @param delta - change from the previously evaluated scroll offset
13
+ */
14
+ export type ScrollObserverScrollCB = (scrollTop: number, delta: number) => void;
15
+ export interface ScrollObserverOptions {
16
+ /** The scroll container to observe. Accepts an element reference or getter. */
17
+ target: ScrollObserverTarget | (() => ScrollObserverTarget | null) | null;
18
+ /** Scroll offset in px past which `scrolled` becomes true (strict `>`). Defaults to `4`. */
19
+ threshold?: number;
20
+ /** Invoked only when the boolean state crosses the threshold. */
21
+ onChange?: ScrollObserverChangeCB;
22
+ /** Invoked on every evaluated scroll event, including the initial attach. */
23
+ onScroll?: ScrollObserverScrollCB;
24
+ /** When true, detaches the listener entirely (e.g. host-controlled state). */
25
+ disabled?: boolean;
26
+ }
27
+ /**
28
+ * Observes a scroll container and tracks whether it is scrolled past a
29
+ * threshold, for scroll-driven UI state such as app-bar elevation.
30
+ *
31
+ * Uses a single passive scroll listener evaluated synchronously per event;
32
+ * browsers already coalesce scroll events to one per frame per target, and
33
+ * the evaluation is a scroll-offset read plus a boolean compare. `onChange`
34
+ * fires only when the boolean state flips, including immediately on attach
35
+ * when the target mounts already scrolled (bfcache restore, fragment
36
+ * navigation).
37
+ *
38
+ * A null or missing target is silently inert; the controller never throws.
39
+ */
40
+ export declare class ScrollObserverController implements ReactiveController {
41
+ private _host;
42
+ private _opts;
43
+ /** Target resolved at attach time, so detach unsubscribes the right node. */
44
+ private _attached;
45
+ private _scrolled;
46
+ private _lastScrollTop;
47
+ private readonly _onScroll;
48
+ constructor(host: ReactiveControllerHost, options: ScrollObserverOptions);
49
+ /** Whether the observed target is currently scrolled past the threshold. */
50
+ get scrolled(): boolean;
51
+ /** Reconfigure the controller: detaches, merges options, and reattaches. */
52
+ setOptions(next: Partial<ScrollObserverOptions>): void;
53
+ hostConnected(): void;
54
+ hostDisconnected(): void;
55
+ private _resolveTarget;
56
+ private _attach;
57
+ private _detach;
58
+ private _scrollTop;
59
+ private _evaluate;
60
+ }
61
+ export default ScrollObserverController;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ export * from './ActiveDescendantController';
2
+ export * from './KeyboardNavigationDirective';
3
+ export * from './MouseMoveDirective';
4
+ export * from './DragController';
5
+ export * from './ResizeController';
6
+ export * from './AnchorController';
7
+ export * from './ScrollObserverController';
8
+ export * from './isFocusable';
9
+ export * from './RovingTabIndexMixin';
10
+ export * from './sliderUtils';
@@ -0,0 +1,10 @@
1
+ export type FocusableElement = HTMLAnchorElement | HTMLAreaElement | HTMLButtonElement | HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
2
+ /**
3
+ * Returns true if `el` is a natively focusable element or a custom element
4
+ * that opts in to keyboard navigation via `tabindex`.
5
+ *
6
+ * Note: does not check `tabindex >= 0` because rc-common components mutate
7
+ * tabindex values during roving-tabindex management — any `tabindex` attribute
8
+ * presence is sufficient signal.
9
+ */
10
+ export declare function isFocusable(el?: Element | null): el is FocusableElement;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Clamps `value` to [min, max] and rounds to the nearest `step` boundary.
3
+ *
4
+ * A step of 0 or less disables snapping and returns the clamped value as-is.
5
+ */
6
+ export declare function snapToStep(value: number, min: number, max: number, step: number): number;
7
+ /**
8
+ * Returns `value`'s position within [min, max] as a fraction in [0, 1].
9
+ *
10
+ * Returns 0 when min === max to avoid division by zero.
11
+ */
12
+ export declare function valueToPercent(value: number, min: number, max: number): number;
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@rcarls/rc-common",
3
+ "publishConfig": {
4
+ "access": "public"
5
+ },
6
+ "version": "0.1.0",
7
+ "description": "Shared reactive controllers and directives for @rcarls Lit web components",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/richardcarls/rc-webcomponents.git",
11
+ "directory": "packages/rc-common"
12
+ },
13
+ "homepage": "https://github.com/richardcarls/rc-webcomponents#readme",
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "main": "./dist/rc-common.umd.cjs",
20
+ "module": "./dist/rc-common.js",
21
+ "exports": {
22
+ ".": {
23
+ "import": {
24
+ "types": "./dist/types/index.d.ts",
25
+ "default": "./dist/rc-common.js"
26
+ },
27
+ "require": {
28
+ "types": "./dist/types/index.d.ts",
29
+ "default": "./dist/rc-common.umd.cjs"
30
+ }
31
+ }
32
+ },
33
+ "types": "./dist/types/index.d.ts",
34
+ "sideEffects": false,
35
+ "scripts": {
36
+ "dev": "vite",
37
+ "build": "tsc && vite build",
38
+ "preview": "vite preview",
39
+ "test:browser": "vitest",
40
+ "test:browser:chrome": "vitest --project=chromium",
41
+ "test:browser:firefox": "vitest --project=firefox",
42
+ "yalc:publish": "yalc publish --push"
43
+ },
44
+ "dependencies": {
45
+ "@oddbird/css-anchor-positioning": "^0.7.0"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^25.6.0",
49
+ "@vitest/browser-playwright": "4.1.5",
50
+ "lit": "^3.0.0",
51
+ "playwright": "^1.56.0",
52
+ "rollup": "^4.60.2",
53
+ "typescript": "~5.9.3",
54
+ "vite": "^7.1.7",
55
+ "vite-plugin-dts": "^4.5.4",
56
+ "vitest": "^4.0.6",
57
+ "vitest-browser-lit": "^1.0.1"
58
+ },
59
+ "peerDependencies": {
60
+ "lit": "^3.0.0"
61
+ }
62
+ }