@cloudwick/astral-ui-cli 2.1.0 → 2.2.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,145 @@
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useRef,
5
+ useState,
6
+ type ChangeEvent,
7
+ type FocusEvent,
8
+ type KeyboardEvent
9
+ } from "react";
10
+
11
+ import { keyboardKeys } from "@constants";
12
+ import { useDebouncedCallback } from "./useDebouncedCallback";
13
+
14
+ interface IUseFilterQueryArgs {
15
+ /** Seeds/re-syncs the search box on change; not fully controlled — pair with onFilterChange. */
16
+ filterValue?: string;
17
+ /** Server-side filter handler; its presence is the client/server mode switch. */
18
+ onFilterChange?: ( query: string ) => void;
19
+ /** Debounce delay in ms for `onFilterChange`. */
20
+ filterDebounceMs: number;
21
+ }
22
+
23
+ interface IUseFilterQueryResult {
24
+ /** Current search text. */
25
+ filterQuery: string;
26
+ /** Change handler for the search input. */
27
+ handleFilterInput: ( e: ChangeEvent<HTMLInputElement> ) => void;
28
+ /** The same path as `handleFilterInput` for surfaces that report their search as a plain string. */
29
+ setFilterQuery: ( query: string ) => void;
30
+ /** Marks Backspace/Delete held so debounce waits for release (see handleFilterKeyUp). */
31
+ handleFilterKeyDown: ( e: KeyboardEvent<HTMLInputElement> ) => void;
32
+ /** On Backspace/Delete release, starts the deferred debounce. */
33
+ handleFilterKeyUp: ( e: KeyboardEvent<HTMLInputElement> ) => void;
34
+ /** On blur during a Backspace/Delete hold, release and start the deferred debounce. */
35
+ handleFilterBlur: ( e: FocusEvent<HTMLInputElement> ) => void;
36
+ /** Clear the query, drop any pending debounce, and notify a server-side consumer. */
37
+ resetFilter: () => void;
38
+ }
39
+
40
+ const isDeleteKey = ( key: string ): boolean =>
41
+ key === keyboardKeys.backspace || key === keyboardKeys.delete;
42
+
43
+ /** Owns a search query and the debounced bridge to a server-side `onFilterChange`. */
44
+ export function useFilterQuery({
45
+ filterValue,
46
+ onFilterChange,
47
+ filterDebounceMs
48
+ }: IUseFilterQueryArgs ): IUseFilterQueryResult {
49
+ const [ filterQuery, setQueryState ] = useState( filterValue ?? "" );
50
+
51
+ // Refs keep resetFilter stable for outside-click deps (avoid re-subscribing each render).
52
+ const filterQueryRef = useRef( filterQuery );
53
+ filterQueryRef.current = filterQuery;
54
+ const onFilterChangeRef = useRef( onFilterChange );
55
+ onFilterChangeRef.current = onFilterChange;
56
+
57
+ // Defer debounce while Backspace/Delete is held (OS key-repeat gap exceeds filterDebounceMs).
58
+ const isDeleteKeyHeldRef = useRef( false );
59
+ // True only when an onChange was suppressed during the hold (skips no-op empty Backspace).
60
+ const deferredDuringDeleteRef = useRef( false );
61
+
62
+ // filterDebounceMs=0 fires synchronously; pending timer is cancelled on unmount.
63
+ const { call: debouncedFilterChange, cancel: cancelFilterChange } = useDebouncedCallback(
64
+ ( query: string ) => onFilterChangeRef.current?.( query ),
65
+ filterDebounceMs
66
+ );
67
+
68
+ const releaseDeleteKeyAndFlush = useCallback(() => {
69
+ if ( !isDeleteKeyHeldRef.current ) {
70
+ return;
71
+ }
72
+ isDeleteKeyHeldRef.current = false;
73
+ if ( !deferredDuringDeleteRef.current ) {
74
+ return;
75
+ }
76
+ deferredDuringDeleteRef.current = false;
77
+ debouncedFilterChange( filterQueryRef.current );
78
+ }, [debouncedFilterChange]);
79
+
80
+ // Sync filterValue from parent; cancel pending debounce so stale queries don't fire.
81
+ useEffect(() => {
82
+ if ( filterValue !== undefined ) {
83
+ isDeleteKeyHeldRef.current = false;
84
+ deferredDuringDeleteRef.current = false;
85
+ cancelFilterChange();
86
+ setQueryState( filterValue );
87
+ }
88
+ }, [ filterValue, cancelFilterChange ]);
89
+
90
+ const handleFilterKeyDown = useCallback(( e: KeyboardEvent<HTMLInputElement> ) => {
91
+ if ( isDeleteKey( e.key )) {
92
+ isDeleteKeyHeldRef.current = true;
93
+ }
94
+ }, []);
95
+
96
+ const handleFilterKeyUp = useCallback(( e: KeyboardEvent<HTMLInputElement> ) => {
97
+ if ( isDeleteKey( e.key )) {
98
+ releaseDeleteKeyAndFlush();
99
+ }
100
+ }, [releaseDeleteKeyAndFlush]);
101
+
102
+ const handleFilterBlur = useCallback(() => {
103
+ releaseDeleteKeyAndFlush();
104
+ }, [releaseDeleteKeyAndFlush]);
105
+
106
+ const setFilterQuery = useCallback(
107
+ ( query: string ) => {
108
+ setQueryState( query );
109
+ if ( isDeleteKeyHeldRef.current ) {
110
+ // Wait for keyup/blur to schedule debounce with the final query.
111
+ cancelFilterChange();
112
+ deferredDuringDeleteRef.current = true;
113
+ return;
114
+ }
115
+ debouncedFilterChange( query );
116
+ },
117
+ [ debouncedFilterChange, cancelFilterChange ]
118
+ );
119
+
120
+ const handleFilterInput = useCallback(
121
+ ( e: ChangeEvent<HTMLInputElement> ) => setFilterQuery( e.target.value ),
122
+ [setFilterQuery]
123
+ );
124
+
125
+ const resetFilter = useCallback(() => {
126
+ isDeleteKeyHeldRef.current = false;
127
+ deferredDuringDeleteRef.current = false;
128
+ cancelFilterChange();
129
+ setQueryState( "" );
130
+ // Notify immediately on clear so a pending keystroke can't overtake the reset.
131
+ if ( filterQueryRef.current !== "" ) {
132
+ onFilterChangeRef.current?.( "" );
133
+ }
134
+ }, [cancelFilterChange]);
135
+
136
+ return {
137
+ filterQuery,
138
+ handleFilterInput,
139
+ setFilterQuery,
140
+ handleFilterKeyDown,
141
+ handleFilterKeyUp,
142
+ handleFilterBlur,
143
+ resetFilter
144
+ };
145
+ }
@@ -0,0 +1,17 @@
1
+ import { useEffect, useRef } from "react";
2
+
3
+ import { devWarn } from "@utils";
4
+
5
+ /**
6
+ * Warns once per instance while `active`. Raised from an effect, not the render body, so StrictMode's
7
+ * double render doesn't print it twice.
8
+ */
9
+ export function useIgnoredPropWarning( active: boolean, message: string ): void {
10
+ const warnedRef = useRef( false );
11
+ useEffect(() => {
12
+ if ( active && !warnedRef.current ) {
13
+ warnedRef.current = true;
14
+ devWarn( message );
15
+ }
16
+ }, [ active, message ]);
17
+ }
@@ -1,4 +1,7 @@
1
- import { useEffect, useRef } from "react";
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ /** Callback ref for the sentinel element. Assign it with `ref={...}`; it takes no `.current`. */
4
+ export type TSentinelRef<T extends HTMLElement = HTMLDivElement> = ( node: T | null ) => void;
2
5
 
3
6
  interface IUseInfiniteScrollArgs {
4
7
  /** Whether more items can be loaded. The observer is inert when false. */
@@ -13,7 +16,14 @@ interface IUseInfiniteScrollArgs {
13
16
 
14
17
  /**
15
18
  * Attaches an IntersectionObserver to a sentinel element and fires `onLoadMore` when it
16
- * scrolls into view. Returns the ref to spread onto the sentinel element.
19
+ * scrolls into view. Returns the callback ref to put on the sentinel element.
20
+ *
21
+ * A **callback ref backed by state**, not a `RefObject`, because the sentinel's identity has to be
22
+ * one of the effect's dependencies. The surfaces here unmount the rows — and the sentinel with them —
23
+ * while a search fetch replaces the list, and none of the other dependencies change across that round
24
+ * trip: the observer would stay bound to the detached node and paging would be silently dead for
25
+ * every search result set. A callback ref re-runs the effect on each detach/attach, so the observer
26
+ * always watches the node that is actually in the document.
17
27
  *
18
28
  * `onLoadMore` is read through a ref so passing a fresh inline callback each render doesn't tear
19
29
  * the observer down and recreate it. `isLoading`, by contrast, IS a dependency: no observer exists
@@ -28,15 +38,16 @@ export function useInfiniteScroll<T extends HTMLElement = HTMLDivElement>({
28
38
  isLoading = false,
29
39
  onLoadMore,
30
40
  enabled = true
31
- }: IUseInfiniteScrollArgs ) {
32
- const sentinelRef = useRef<T>( null );
41
+ }: IUseInfiniteScrollArgs ): TSentinelRef<T> {
42
+ // `useState`'s setter is permanently stable, so React never re-invokes the ref for a re-render —
43
+ // only for a genuine detach (null) or attach (node).
44
+ const [ sentinel, setSentinel ] = useState<T | null>( null );
33
45
 
34
46
  const onLoadMoreRef = useRef( onLoadMore );
35
47
  onLoadMoreRef.current = onLoadMore;
36
48
 
37
49
  useEffect(() => {
38
- const el = sentinelRef.current;
39
- if ( !el || !hasMore || !enabled || isLoading ) {
50
+ if ( !sentinel || !hasMore || !enabled || isLoading ) {
40
51
  return undefined;
41
52
  }
42
53
  const observer = new IntersectionObserver(([entry]) => {
@@ -44,9 +55,9 @@ export function useInfiniteScroll<T extends HTMLElement = HTMLDivElement>({
44
55
  onLoadMoreRef.current?.();
45
56
  }
46
57
  });
47
- observer.observe( el );
58
+ observer.observe( sentinel );
48
59
  return () => observer.disconnect();
49
- }, [ hasMore, enabled, isLoading ]);
60
+ }, [ sentinel, hasMore, enabled, isLoading ]);
50
61
 
51
- return sentinelRef;
62
+ return setSentinel;
52
63
  }
@@ -0,0 +1,17 @@
1
+ import { useEffect, useRef } from "react";
2
+
3
+ /**
4
+ * Runs `onChange` when `value` CHANGES, never on mount. The ref comparison is the whole point: a
5
+ * plain effect on `[value]` also fires on paint, and the callers here route the change into a reset
6
+ * path that would clobber consumer-seeded state if it ran before the user had touched anything.
7
+ */
8
+ export function useOnValueChange<TValue>( value: TValue, onChange: () => void ): void {
9
+ const previousRef = useRef( value );
10
+ useEffect(() => {
11
+ if ( previousRef.current === value ) {
12
+ return;
13
+ }
14
+ previousRef.current = value;
15
+ onChange();
16
+ }, [ value, onChange ]);
17
+ }
@@ -0,0 +1,38 @@
1
+ import { useEffect } from "react";
2
+
3
+ import type { TPrefetch } from "./useAsyncOptions";
4
+
5
+ interface IUsePrefetchBaselineArgs {
6
+ /** Which trigger arms the baseline fetch. A surface with no open/close narrows the union. */
7
+ prefetch: TPrefetch;
8
+ /** Whether the surface is currently open. Omit on a surface that is always visible. */
9
+ isOpen?: boolean;
10
+ /** Identity of the option set — a change re-arms an already-armed prefetch. */
11
+ optionsKey?: string | number;
12
+ /** `useAsyncOptions().ensureDefaults`. Idempotent and latch-guarded. */
13
+ ensureDefaults: () => void;
14
+ }
15
+
16
+ /**
17
+ * Translates a `prefetch` trigger into the one effect that calls `ensureDefaults`. Shared so the
18
+ * three option surfaces cannot answer "when is the baseline fetched" differently.
19
+ *
20
+ * `armed` — not the raw flags — is the dependency, which is what keeps `"mount"` from re-firing when
21
+ * the surface opens (it is already true) while still letting `"open"` fire on the false→true edge.
22
+ * `optionsKey` is a dependency (and only a dependency) so a dependent surface whose parent changes
23
+ * while armed repopulates immediately.
24
+ */
25
+ export function usePrefetchBaseline({
26
+ prefetch,
27
+ isOpen = false,
28
+ optionsKey,
29
+ ensureDefaults
30
+ }: IUsePrefetchBaselineArgs ): void {
31
+ const armed = prefetch === "mount" || ( prefetch === "open" && isOpen );
32
+
33
+ useEffect(() => {
34
+ if ( armed ) {
35
+ ensureDefaults();
36
+ }
37
+ }, [ armed, optionsKey, ensureDefaults ]);
38
+ }
@@ -32,6 +32,9 @@
32
32
  },
33
33
  "constants": {
34
34
  "type": "string"
35
+ },
36
+ "hooks": {
37
+ "type": "string"
35
38
  }
36
39
  },
37
40
  "required": [
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Dev-only warning shim. The `typeof process` guard keeps unbundled ESM consumers safe — the Rollup
3
+ * build has no `@rollup/plugin-replace`, so `process.env.NODE_ENV` is not substituted at build time.
4
+ */
5
+ export function devWarn( message: string ): void {
6
+ if ( typeof process !== "undefined" && process.env.NODE_ENV !== "production" ) {
7
+ console.warn( message );
8
+ }
9
+ }
@@ -4,3 +4,7 @@ export * from "./findParentAttribute";
4
4
  export * from "./elementUtils";
5
5
  export * from "./debounce";
6
6
  export * from "./matchesQuery";
7
+ export * from "./mergeUnique";
8
+ export * from "./devWarn";
9
+ export * from "./resolveLoadErrors";
10
+ export * from "./resolveReloadControls";
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Concatenates `sources` in order, keeping the first occurrence of each key and dropping anything in
3
+ * `excluded`. Iterating the sources directly rather than spreading them into one array matters here:
4
+ * the callers re-run this on every landed page, over the whole pool.
5
+ */
6
+ export function mergeUnique<TItem, TKey>(
7
+ sources: readonly Iterable<TItem>[],
8
+ getKey: ( item: TItem ) => TKey,
9
+ excluded?: ReadonlySet<TKey>
10
+ ): TItem[] {
11
+ const seen = new Set<TKey>();
12
+ const merged: TItem[] = [];
13
+ for ( const source of sources ) {
14
+ for ( const item of source ) {
15
+ const key = getKey( item );
16
+ if ( seen.has( key ) || excluded?.has( key ) === true ) {
17
+ continue;
18
+ }
19
+ seen.add( key );
20
+ merged.push( item );
21
+ }
22
+ }
23
+ return merged;
24
+ }
@@ -0,0 +1,40 @@
1
+ import type { ReactNode } from "react";
2
+
3
+ // Type-only, so it is erased at compile time — no runtime import edge back into `hooks`.
4
+ import type { TAsyncRequest } from "../hooks/useAsyncOptions";
5
+
6
+ // The three surfaces render the same two failures, so the wording lives here rather than in each of
7
+ // them — a default that differs per component is a difference nobody chose.
8
+ const DEFAULT_LOAD_ERROR = "Couldn't load options.";
9
+ const DEFAULT_LOAD_MORE_ERROR = "Couldn't load more.";
10
+
11
+ interface IResolveLoadErrorsArgs {
12
+ /** `null` means no failure — the only thing that decides whether either slot is filled. */
13
+ errorKind: TAsyncRequest | null;
14
+ loadErrorMessage?: ReactNode;
15
+ loadMoreErrorMessage?: ReactNode;
16
+ }
17
+
18
+ interface IResolvedLoadErrors {
19
+ /** Set when the whole list failed. Mutually exclusive with `loadMoreError`. */
20
+ loadError?: ReactNode;
21
+ /** Set when a page append failed. The rows the user was reading stay on screen. */
22
+ loadMoreError?: ReactNode;
23
+ }
24
+
25
+ /**
26
+ * Splits one failure into the two slots a surface renders. The `errorKind === "more"` branch is the
27
+ * line that keeps a failed page append from blanking a list the user was already reading.
28
+ */
29
+ export function resolveLoadErrors({
30
+ errorKind,
31
+ loadErrorMessage,
32
+ loadMoreErrorMessage
33
+ }: IResolveLoadErrorsArgs ): IResolvedLoadErrors {
34
+ if ( errorKind === null ) {
35
+ return {};
36
+ }
37
+ return errorKind === "more"
38
+ ? { loadMoreError: loadMoreErrorMessage ?? DEFAULT_LOAD_MORE_ERROR }
39
+ : { loadError: loadErrorMessage ?? DEFAULT_LOAD_ERROR };
40
+ }
@@ -0,0 +1,31 @@
1
+ interface IResolveReloadControlsArgs {
2
+ isAsync: boolean;
3
+ /** The async source's own reload trio. */
4
+ source: { errorKind: string | null; isReloading: boolean; reload: () => void };
5
+ /** Consumer overrides. Each wins outright — a consumer driving their own refresh keeps it. */
6
+ onReload?: () => void;
7
+ isReloading?: boolean;
8
+ showReloadButton?: boolean;
9
+ }
10
+
11
+ interface IResolvedReloadControls {
12
+ onReload?: () => void;
13
+ isReloading?: boolean;
14
+ }
15
+
16
+ /**
17
+ * Decides whether the surface gets a reload affordance at all. Off by default so async mode doesn't
18
+ * grow UI nobody asked for, and auto-shown while an error is displayed — where it is the only retry.
19
+ */
20
+ export function resolveReloadControls({
21
+ isAsync,
22
+ source,
23
+ onReload,
24
+ isReloading,
25
+ showReloadButton = false
26
+ }: IResolveReloadControlsArgs ): IResolvedReloadControls {
27
+ return {
28
+ onReload: onReload ?? ( isAsync && ( showReloadButton || source.errorKind !== null ) ? source.reload : undefined ),
29
+ isReloading: isReloading ?? ( isAsync ? source.isReloading : undefined )
30
+ };
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudwick/astral-ui-cli",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "CLI for installing Astral UI components in any codebase",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -1,32 +0,0 @@
1
- import { matchesQuery } from "./matchesQuery";
2
-
3
- describe( "matchesQuery", () => {
4
- test( "empty query matches everything", () => {
5
- expect( matchesQuery({ label: "Anything", value: "x" }, "" )).toBe( true );
6
- });
7
-
8
- test( "matches a string label case-insensitively", () => {
9
- expect( matchesQuery({ label: "Chocolate", value: "c" }, "choc" )).toBe( true );
10
- expect( matchesQuery({ label: "Chocolate", value: "c" }, "vanilla" )).toBe( false );
11
- });
12
-
13
- test( "falls back to the stringified value when label is not a string", () => {
14
- expect( matchesQuery({ label: <span>Icon</span>, value: "banana" }, "ban" )).toBe( true );
15
- expect( matchesQuery({ label: <span>Icon</span>, value: "banana" }, "icon" )).toBe( false );
16
- });
17
-
18
- test( "matches searchValue when provided", () => {
19
- expect( matchesQuery({ label: <span>Icon</span>, value: "u1", searchValue: "Manage Users" }, "users" )).toBe( true );
20
- expect( matchesQuery({ label: <span>Icon</span>, value: "u1", searchValue: "Manage Users" }, "sync" )).toBe( false );
21
- });
22
-
23
- test( "searchValue takes precedence over label and value", () => {
24
- // Query matches the label but not searchValue -> no match (searchValue wins).
25
- expect( matchesQuery({ label: "Chocolate", value: "choc", searchValue: "Dessert" }, "choc" )).toBe( false );
26
- expect( matchesQuery({ label: "Chocolate", value: "choc", searchValue: "Dessert" }, "dess" )).toBe( true );
27
- });
28
-
29
- test( "an empty-string searchValue is ignored (falls back to label/value)", () => {
30
- expect( matchesQuery({ label: "Chocolate", value: "choc", searchValue: "" }, "choc" )).toBe( true );
31
- });
32
- });