@sincpro/criteria-react 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.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # @sincpro/criteria-react
2
+
3
+ React hooks over [`@sincpro/criteria`](https://github.com/Sincpro-SRL/sincpro_criteria)'s
4
+ `Reading`/`Buckets`, and a query-key helper for a consumer that already has its own cache. A
5
+ separate package from the core on purpose — see `docs/DESIGN.md` at the repo root for why —
6
+ because it needs `react` as a real dependency, and that must never leak into installing the
7
+ core for `Criteria`/`Source` alone.
8
+
9
+ There are two ways to use this, and picking between them is one question: **does your app
10
+ already have a query cache (react-query, SWR, …)?**
11
+
12
+ ## No cache of your own: `useReading` / `useBuckets`
13
+
14
+ `Reading` and `Buckets` are already `useSyncExternalStore`-shaped stores. These hooks own the
15
+ lifecycle a store by itself cannot: create one per `(resource, criteria)` pair, load it once,
16
+ clean it up on unmount.
17
+
18
+ ```tsx
19
+ import { useReading } from "@sincpro/criteria-react";
20
+ import { criteria } from "@sincpro/criteria";
21
+
22
+ function DatasetList({ resource, where }: Props) {
23
+ const { rows, status, hasMore, more } = useReading(
24
+ resource,
25
+ criteria<Dataset>().where(where).limit(50),
26
+ );
27
+
28
+ if (status === "loading") return <Spinner />;
29
+ return <List rows={rows} onEndReached={more} hasMore={hasMore} />;
30
+ }
31
+ ```
32
+
33
+ `useBuckets` is the grouping counterpart:
34
+
35
+ ```tsx
36
+ import { useBuckets } from "@sincpro/criteria-react";
37
+
38
+ function EncodingBreakdown({ resource }: Props) {
39
+ const { buckets, status } = useBuckets(resource, criteria<Dataset>().groupBy("encoding"));
40
+ return <BarChart data={buckets} />;
41
+ }
42
+ ```
43
+
44
+ Both are keyed by `pack(criteria)`, not by object identity — a `criteria` literal built fresh
45
+ on every render does not restart the reading.
46
+
47
+ ## Already have a cache: `queryKeyFor`
48
+
49
+ Reusing `Reading` here would be a second cache fighting the one you already trust.
50
+ `queryKeyFor` is the one line that was missing — a stable key from a criteria, so two requests
51
+ that ask the same question hit the same cache entry:
52
+
53
+ ```tsx
54
+ import { useQuery } from "@tanstack/react-query";
55
+ import { queryKeyFor } from "@sincpro/criteria-react";
56
+
57
+ function useDatasets(criteria: Criteria<Dataset>) {
58
+ return useQuery({
59
+ queryKey: queryKeyFor(["catalog", "datasets"], criteria),
60
+ queryFn: ({ signal }) => datasets.page(criteria, signal),
61
+ });
62
+ }
63
+ ```
64
+
65
+ This package never imports `react-query`, `SWR`, or anything like them — `queryKeyFor` returns
66
+ a plain array, so it works with whichever cache you already have.
67
+
68
+ ## Combining a permission with what the user typed
69
+
70
+ Merging is `@sincpro/criteria`'s job (`merge`, plain functions, no React in it) — this package
71
+ adds nothing to that law, it just gives you a place to call it once instead of at every call
72
+ site. A small custom hook is the natural shape, not a HOC — nothing here needs to wrap a
73
+ component to do this:
74
+
75
+ ```tsx
76
+ import { criteria, merge, plain, where } from "@sincpro/criteria";
77
+ import { useReading } from "@sincpro/criteria-react";
78
+
79
+ function usePermissionedAccounts(resource: Resource<Account>, typed: Expression<Account>) {
80
+ const permission = criteria<Account>().where(
81
+ where.any(["region", "=", "north"], ["owner", "=", useCurrentUser()]),
82
+ );
83
+ const asked = merge(plain(permission), plain(criteria<Account>().where(typed)));
84
+ return useReading(resource, asked);
85
+ }
86
+ ```
87
+
88
+ `asked` is what actually reaches the network — the user's filter narrows the permission, it
89
+ can never widen past it, because `where` always merges by AND. See the core README's "The law
90
+ for merging two of them" for what merge does with the rest of a criteria (order, pagination,
91
+ grouping), not just `where`.
92
+
93
+ ## Development
94
+
95
+ ```bash
96
+ make init # from the repo root — installs the whole workspace
97
+ make test # node --test over these hooks, react-test-renderer, no DOM needed
98
+ make typecheck
99
+ make build
100
+ ```
@@ -0,0 +1,78 @@
1
+ import type { Bucket, BucketsState, CriteriaFor, Reading, Resource } from "@sincpro/criteria";
2
+ /** A level of buckets' state, plus the methods that drive it and open what it found. */
3
+ export interface UseBucketsResult<T> extends BucketsState<T> {
4
+ /** The buckets of this level. */
5
+ load(): Promise<void>;
6
+ /** The same levels over another reading. */
7
+ refine(criteria: CriteriaFor<T>): Promise<void>;
8
+ /** The rows of one bucket, as a `Reading` of its own — pass this to {@link useReading}. */
9
+ open(bucket: Bucket<T>): Reading<T>;
10
+ }
11
+ /**
12
+ * A live level of buckets over a resource, re-rendering this component when it changes.
13
+ *
14
+ * Same identity rule as {@link useReading}: the level is keyed by `pack(criteria)`, not by
15
+ * object identity, so an inline `criteria` literal does not restart it on every render.
16
+ *
17
+ * @example
18
+ * // simple
19
+ * function EncodingBreakdown({ resource }: Props) {
20
+ * const { buckets, status } = useBuckets(resource, criteria<Dataset>().groupBy("encoding"));
21
+ * return <BarChart data={buckets} />;
22
+ * }
23
+ *
24
+ * @example
25
+ * // medium: a measure, and opening a clicked bucket's rows with useReading
26
+ * import { measure } from "@sincpro/criteria";
27
+ * import { useReading } from "./index.js";
28
+ *
29
+ * function EncodingTotals({ resource }: Props) {
30
+ * const tree = useBuckets(
31
+ * resource,
32
+ * criteria<Dataset>().groupBy("encoding").measures({ rows: measure.sum("row_count") }),
33
+ * );
34
+ * const [opened, setOpened] = useState<Bucket<Dataset>>();
35
+ * const rows = useReading(resource, opened ? opened.criteria : {});
36
+ * return (
37
+ * <>
38
+ * <BarChart data={tree.buckets} onBarClick={setOpened} />
39
+ * {opened && <List rows={rows.rows} />}
40
+ * </>
41
+ * );
42
+ * }
43
+ *
44
+ * @example
45
+ * // complex: two grouping levels, two measures, a filter over the groups themselves,
46
+ * // group-count paging AND row-count paging, and following one bucket's own cursor further.
47
+ * import { resumingFrom, where } from "@sincpro/criteria";
48
+ *
49
+ * function HighVolumeProducers({ resource }: Props) {
50
+ * const tree = useBuckets(
51
+ * resource,
52
+ * criteria<Dataset>()
53
+ * .where(
54
+ * ["row_count", ">", 50],
55
+ * where.any(
56
+ * where.all(["tags", "contains", "raw"], ["producer_id", "!=", null]),
57
+ * ["registered_at", ">=", "2026-03-01T00:00:00.000Z"],
58
+ * ),
59
+ * where.negate(["name", "like", "draft"]),
60
+ * )
61
+ * .groupBy("encoding", "producer_id")
62
+ * .measures({ total_rows: measure.sum("row_count") })
63
+ * .whereMeasures(["total_rows", ">", 200])
64
+ * .orderGroups("-total_rows")
65
+ * .limitGroups(2) // at most 2 top-level groups
66
+ * .limit(2), // at most 2 row ids per surviving group
67
+ * );
68
+ *
69
+ * async function loadMoreOf(bucket: Bucket<Dataset>) {
70
+ * if (bucket.cursor === null) return;
71
+ * const next = await resource.page(resumingFrom(bucket.criteria, bucket.cursor));
72
+ * // next.rows -> the next page of ids INSIDE that one bucket, not the whole catalog
73
+ * }
74
+ *
75
+ * return <Tree buckets={tree.buckets} onLoadMore={loadMoreOf} />;
76
+ * }
77
+ */
78
+ export declare function useBuckets<T>(resource: Resource<T>, criteria?: CriteriaFor<T>): UseBucketsResult<T>;
@@ -0,0 +1,85 @@
1
+ import { pack, plain } from "@sincpro/criteria";
2
+ import { useEffect, useMemo, useSyncExternalStore } from "react";
3
+ /**
4
+ * A live level of buckets over a resource, re-rendering this component when it changes.
5
+ *
6
+ * Same identity rule as {@link useReading}: the level is keyed by `pack(criteria)`, not by
7
+ * object identity, so an inline `criteria` literal does not restart it on every render.
8
+ *
9
+ * @example
10
+ * // simple
11
+ * function EncodingBreakdown({ resource }: Props) {
12
+ * const { buckets, status } = useBuckets(resource, criteria<Dataset>().groupBy("encoding"));
13
+ * return <BarChart data={buckets} />;
14
+ * }
15
+ *
16
+ * @example
17
+ * // medium: a measure, and opening a clicked bucket's rows with useReading
18
+ * import { measure } from "@sincpro/criteria";
19
+ * import { useReading } from "./index.js";
20
+ *
21
+ * function EncodingTotals({ resource }: Props) {
22
+ * const tree = useBuckets(
23
+ * resource,
24
+ * criteria<Dataset>().groupBy("encoding").measures({ rows: measure.sum("row_count") }),
25
+ * );
26
+ * const [opened, setOpened] = useState<Bucket<Dataset>>();
27
+ * const rows = useReading(resource, opened ? opened.criteria : {});
28
+ * return (
29
+ * <>
30
+ * <BarChart data={tree.buckets} onBarClick={setOpened} />
31
+ * {opened && <List rows={rows.rows} />}
32
+ * </>
33
+ * );
34
+ * }
35
+ *
36
+ * @example
37
+ * // complex: two grouping levels, two measures, a filter over the groups themselves,
38
+ * // group-count paging AND row-count paging, and following one bucket's own cursor further.
39
+ * import { resumingFrom, where } from "@sincpro/criteria";
40
+ *
41
+ * function HighVolumeProducers({ resource }: Props) {
42
+ * const tree = useBuckets(
43
+ * resource,
44
+ * criteria<Dataset>()
45
+ * .where(
46
+ * ["row_count", ">", 50],
47
+ * where.any(
48
+ * where.all(["tags", "contains", "raw"], ["producer_id", "!=", null]),
49
+ * ["registered_at", ">=", "2026-03-01T00:00:00.000Z"],
50
+ * ),
51
+ * where.negate(["name", "like", "draft"]),
52
+ * )
53
+ * .groupBy("encoding", "producer_id")
54
+ * .measures({ total_rows: measure.sum("row_count") })
55
+ * .whereMeasures(["total_rows", ">", 200])
56
+ * .orderGroups("-total_rows")
57
+ * .limitGroups(2) // at most 2 top-level groups
58
+ * .limit(2), // at most 2 row ids per surviving group
59
+ * );
60
+ *
61
+ * async function loadMoreOf(bucket: Bucket<Dataset>) {
62
+ * if (bucket.cursor === null) return;
63
+ * const next = await resource.page(resumingFrom(bucket.criteria, bucket.cursor));
64
+ * // next.rows -> the next page of ids INSIDE that one bucket, not the whole catalog
65
+ * }
66
+ *
67
+ * return <Tree buckets={tree.buckets} onLoadMore={loadMoreOf} />;
68
+ * }
69
+ */
70
+ export function useBuckets(resource, criteria = {}) {
71
+ const key = pack(plain(criteria));
72
+ const buckets = useMemo(() => resource.group(criteria), [resource, key]);
73
+ useEffect(() => {
74
+ void buckets.load();
75
+ // `Buckets` has no `reset()` — an in-flight request left over from an unmounted component
76
+ // resolves into a `write()` on a store nobody is subscribed to any more, which is a no-op.
77
+ }, [buckets]);
78
+ const state = useSyncExternalStore((onChange) => buckets.subscribe(onChange), () => buckets.snapshot());
79
+ return useMemo(() => ({
80
+ ...state,
81
+ load: () => buckets.load(),
82
+ refine: (next) => buckets.refine(next),
83
+ open: (bucket) => buckets.open(bucket),
84
+ }), [state, buckets]);
85
+ }
@@ -0,0 +1,5 @@
1
+ export type { UseBucketsResult } from "./buckets.js";
2
+ export { useBuckets } from "./buckets.js";
3
+ export { queryKeyFor } from "./query-key.js";
4
+ export type { UseReadingResult } from "./reading.js";
5
+ export { useReading } from "./reading.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { useBuckets } from "./buckets.js";
2
+ export { queryKeyFor } from "./query-key.js";
3
+ export { useReading } from "./reading.js";
@@ -0,0 +1,15 @@
1
+ import type { CriteriaFor } from "@sincpro/criteria";
2
+ /**
3
+ * A cache key for a criteria, under a prefix of the caller's choosing.
4
+ *
5
+ * Two criteria that ask the same question pack to the same string regardless of key order or
6
+ * object identity, so this is safe to use as a `queryKey`/`SWRKey` directly: the same filter
7
+ * built twice hits the same cache entry, and a different one is a different entry.
8
+ *
9
+ * @example
10
+ * useQuery({
11
+ * queryKey: queryKeyFor(["catalog", "datasets"], criteria),
12
+ * queryFn: ({ signal }) => datasets.page(criteria, signal),
13
+ * });
14
+ */
15
+ export declare function queryKeyFor<T>(prefix: readonly unknown[], criteria?: CriteriaFor<T>): readonly [...unknown[], string];
@@ -0,0 +1,17 @@
1
+ import { pack, plain } from "@sincpro/criteria";
2
+ /**
3
+ * A cache key for a criteria, under a prefix of the caller's choosing.
4
+ *
5
+ * Two criteria that ask the same question pack to the same string regardless of key order or
6
+ * object identity, so this is safe to use as a `queryKey`/`SWRKey` directly: the same filter
7
+ * built twice hits the same cache entry, and a different one is a different entry.
8
+ *
9
+ * @example
10
+ * useQuery({
11
+ * queryKey: queryKeyFor(["catalog", "datasets"], criteria),
12
+ * queryFn: ({ signal }) => datasets.page(criteria, signal),
13
+ * });
14
+ */
15
+ export function queryKeyFor(prefix, criteria = {}) {
16
+ return [...prefix, pack(plain(criteria))];
17
+ }
@@ -0,0 +1,70 @@
1
+ import type { CriteriaFor, ReadingState, Resource } from "@sincpro/criteria";
2
+ /**
3
+ * A reading's state, plus the four methods that drive it, bound and ready to call.
4
+ *
5
+ * `more` is renamed to {@link hasMore} here: `ReadingState.more` is the boolean "is there a
6
+ * next page", and the class's own action method is also called `more()` — two different
7
+ * namespaces on the class, but one flat object here, so one of them has to give.
8
+ */
9
+ export interface UseReadingResult<T> extends Omit<ReadingState<T>, "more"> {
10
+ /** Whether there is another page to ask for. */
11
+ hasMore: boolean;
12
+ /** The first page. Calling it again is a reload. */
13
+ load(): Promise<void>;
14
+ /** The next page, appended. A no-op while one is already on its way, or there is none. */
15
+ more(): Promise<void>;
16
+ /** Another reading, from the first page — for a search box or a filter change. */
17
+ refine(criteria: CriteriaFor<T>): Promise<void>;
18
+ /** The same reading, read again from the first page. */
19
+ reload(): Promise<void>;
20
+ }
21
+ /**
22
+ * A live `Reading` over a resource, re-rendering this component when it changes.
23
+ *
24
+ * The reading is created once per distinct `(resource, criteria)` pair — a fresh-but-equal
25
+ * `criteria` object literal built inline on every render does not restart it, because the
26
+ * identity compared is `pack(criteria)`, not the object. `load()` runs once, when that pair
27
+ * first appears, and the reading is reset (its in-flight request aborted) when the component
28
+ * unmounts or the pair changes.
29
+ *
30
+ * @example
31
+ * // simple
32
+ * function DatasetList({ resource }: Props) {
33
+ * const { rows, status, hasMore, more } = useReading(
34
+ * resource,
35
+ * criteria<Dataset>().where(["encoding", "=", "utf-8"]).limit(50),
36
+ * );
37
+ * if (status === "loading") return <Spinner />;
38
+ * return <List rows={rows} onEndReached={more} hasMore={hasMore} />;
39
+ * }
40
+ *
41
+ * @example
42
+ * // medium: a saved permission merged with what the user typed, refined on every keystroke
43
+ * import { merge, plain, where } from "@sincpro/criteria";
44
+ *
45
+ * function DatasetSearch({ resource, typed }: Props) {
46
+ * const permission = criteria<Dataset>().where(where.any(["region", "=", "north"]));
47
+ * const asked = merge(plain(permission), plain(criteria<Dataset>().where(typed)));
48
+ * const { rows, refine } = useReading(resource, asked);
49
+ * // call refine(nextCriteria) again whenever `typed` changes
50
+ * return <List rows={rows} />;
51
+ * }
52
+ *
53
+ * @example
54
+ * // complex: AND(A, B, OR(AND(C, D), E), NOT(F)) — three real levels of nesting. useReading
55
+ * // only needs the finished criteria; grouping is {@link useBuckets}'s job, not this one's.
56
+ * function RecentRawUploads({ resource }: Props) {
57
+ * const q = criteria<Dataset>().where(
58
+ * ["row_count", ">", 50],
59
+ * ["encoding", "!=", "latin-1"],
60
+ * where.any(
61
+ * where.all(["tags", "contains", "raw"], ["producer_id", "!=", null]),
62
+ * ["registered_at", ">=", "2026-03-01T00:00:00.000Z"],
63
+ * ),
64
+ * where.negate(["name", "like", "draft"]),
65
+ * );
66
+ * const { rows } = useReading(resource, q);
67
+ * return <List rows={rows} />;
68
+ * }
69
+ */
70
+ export declare function useReading<T>(resource: Resource<T>, criteria?: CriteriaFor<T>): UseReadingResult<T>;
@@ -0,0 +1,78 @@
1
+ import { pack, plain } from "@sincpro/criteria";
2
+ import { useEffect, useMemo, useSyncExternalStore } from "react";
3
+ /**
4
+ * A live `Reading` over a resource, re-rendering this component when it changes.
5
+ *
6
+ * The reading is created once per distinct `(resource, criteria)` pair — a fresh-but-equal
7
+ * `criteria` object literal built inline on every render does not restart it, because the
8
+ * identity compared is `pack(criteria)`, not the object. `load()` runs once, when that pair
9
+ * first appears, and the reading is reset (its in-flight request aborted) when the component
10
+ * unmounts or the pair changes.
11
+ *
12
+ * @example
13
+ * // simple
14
+ * function DatasetList({ resource }: Props) {
15
+ * const { rows, status, hasMore, more } = useReading(
16
+ * resource,
17
+ * criteria<Dataset>().where(["encoding", "=", "utf-8"]).limit(50),
18
+ * );
19
+ * if (status === "loading") return <Spinner />;
20
+ * return <List rows={rows} onEndReached={more} hasMore={hasMore} />;
21
+ * }
22
+ *
23
+ * @example
24
+ * // medium: a saved permission merged with what the user typed, refined on every keystroke
25
+ * import { merge, plain, where } from "@sincpro/criteria";
26
+ *
27
+ * function DatasetSearch({ resource, typed }: Props) {
28
+ * const permission = criteria<Dataset>().where(where.any(["region", "=", "north"]));
29
+ * const asked = merge(plain(permission), plain(criteria<Dataset>().where(typed)));
30
+ * const { rows, refine } = useReading(resource, asked);
31
+ * // call refine(nextCriteria) again whenever `typed` changes
32
+ * return <List rows={rows} />;
33
+ * }
34
+ *
35
+ * @example
36
+ * // complex: AND(A, B, OR(AND(C, D), E), NOT(F)) — three real levels of nesting. useReading
37
+ * // only needs the finished criteria; grouping is {@link useBuckets}'s job, not this one's.
38
+ * function RecentRawUploads({ resource }: Props) {
39
+ * const q = criteria<Dataset>().where(
40
+ * ["row_count", ">", 50],
41
+ * ["encoding", "!=", "latin-1"],
42
+ * where.any(
43
+ * where.all(["tags", "contains", "raw"], ["producer_id", "!=", null]),
44
+ * ["registered_at", ">=", "2026-03-01T00:00:00.000Z"],
45
+ * ),
46
+ * where.negate(["name", "like", "draft"]),
47
+ * );
48
+ * const { rows } = useReading(resource, q);
49
+ * return <List rows={rows} />;
50
+ * }
51
+ */
52
+ export function useReading(resource, criteria = {}) {
53
+ // `key` and not `criteria` itself in the dependency list: a criteria built inline is a new
54
+ // object on every render, and `pack` is the identity that already means "the same reading"
55
+ // everywhere else in this package (query keys, URLs).
56
+ const key = pack(plain(criteria));
57
+ const reading = useMemo(() => resource.read(criteria), [resource, key]);
58
+ useEffect(() => {
59
+ void reading.load();
60
+ return () => reading.reset();
61
+ }, [reading]);
62
+ const state = useSyncExternalStore((onChange) => reading.subscribe(onChange), () => reading.snapshot());
63
+ return useMemo(() => ({
64
+ criteria: state.criteria,
65
+ rows: state.rows,
66
+ cursor: state.cursor,
67
+ count: state.count,
68
+ meta: state.meta,
69
+ dropped: state.dropped,
70
+ status: state.status,
71
+ error: state.error,
72
+ hasMore: state.more,
73
+ load: () => reading.load(),
74
+ more: () => reading.more(),
75
+ refine: (next) => reading.refine(next),
76
+ reload: () => reading.reload(),
77
+ }), [state, reading]);
78
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@sincpro/criteria-react",
3
+ "version": "0.1.0",
4
+ "description": "React hooks over @sincpro/criteria's Reading and Buckets, plus a query-key helper for wiring a resource into an existing cache (react-query, …). See docs/DESIGN.md at the repo root for why this is a separate package.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
21
+ "sideEffects": false,
22
+ "peerDependencies": {
23
+ "@sincpro/criteria": "^0.1.0",
24
+ "react": ">=18"
25
+ },
26
+ "devDependencies": {
27
+ "@sincpro/criteria": "*",
28
+ "@types/react": "^18.3.0",
29
+ "@types/react-test-renderer": "^18.3.0",
30
+ "react": "^18.3.0",
31
+ "react-test-renderer": "^18.3.0"
32
+ },
33
+ "keywords": [
34
+ "criteria",
35
+ "react",
36
+ "hooks",
37
+ "sincpro"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/Sincpro-SRL/sincpro_criteria.git",
42
+ "directory": "packages/criteria-react"
43
+ },
44
+ "author": "Gutierrez, Andres <andres.gutierrez@sincpro.com.bo>",
45
+ "license": "MIT",
46
+ "engines": {
47
+ "node": ">=22"
48
+ }
49
+ }