tempest-react-sdk 0.48.0 → 0.49.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/dist/audio/sfx-pool.cjs +1 -1
- package/dist/audio/sfx-pool.cjs.map +1 -1
- package/dist/audio/sfx-pool.js +16 -7
- package/dist/audio/sfx-pool.js.map +1 -1
- package/dist/audio/use-sfx-pool.cjs +1 -1
- package/dist/audio/use-sfx-pool.cjs.map +1 -1
- package/dist/audio/use-sfx-pool.js +3 -8
- package/dist/audio/use-sfx-pool.js.map +1 -1
- package/dist/auth/passkey.cjs +1 -1
- package/dist/auth/passkey.cjs.map +1 -1
- package/dist/auth/passkey.js +79 -81
- package/dist/auth/passkey.js.map +1 -1
- package/dist/charts.cjs +1 -1
- package/dist/charts.js +4 -4
- package/dist/components/BarList/BarList.cjs +1 -1
- package/dist/components/BarList/BarList.cjs.map +1 -1
- package/dist/components/BarList/BarList.js +31 -24
- package/dist/components/BarList/BarList.js.map +1 -1
- package/dist/components/BarList/bar-list-model.cjs +1 -1
- package/dist/components/BarList/bar-list-model.cjs.map +1 -1
- package/dist/components/BarList/bar-list-model.js +5 -5
- package/dist/components/BarList/bar-list-model.js.map +1 -1
- package/dist/components/ClickOutside/ClickOutside.cjs +1 -1
- package/dist/components/ClickOutside/ClickOutside.cjs.map +1 -1
- package/dist/components/ClickOutside/ClickOutside.js +13 -14
- package/dist/components/ClickOutside/ClickOutside.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +124 -122
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/FilterBar/filter-apply.cjs +1 -1
- package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
- package/dist/components/FilterBar/filter-apply.js +35 -38
- package/dist/components/FilterBar/filter-apply.js.map +1 -1
- package/dist/components/FilterBar/filter-query.cjs +1 -1
- package/dist/components/FilterBar/filter-query.cjs.map +1 -1
- package/dist/components/FilterBar/filter-query.js +16 -13
- package/dist/components/FilterBar/filter-query.js.map +1 -1
- package/dist/geo/use-position-tracker.cjs +1 -1
- package/dist/geo/use-position-tracker.cjs.map +1 -1
- package/dist/geo/use-position-tracker.js +25 -26
- package/dist/geo/use-position-tracker.js.map +1 -1
- package/dist/hooks/use-async.cjs +1 -1
- package/dist/hooks/use-async.cjs.map +1 -1
- package/dist/hooks/use-async.js +27 -30
- package/dist/hooks/use-async.js.map +1 -1
- package/dist/hooks/use-click-outside.cjs +1 -1
- package/dist/hooks/use-click-outside.cjs.map +1 -1
- package/dist/hooks/use-click-outside.js +8 -9
- package/dist/hooks/use-click-outside.js.map +1 -1
- package/dist/hooks/use-countdown.cjs +1 -1
- package/dist/hooks/use-countdown.cjs.map +1 -1
- package/dist/hooks/use-countdown.js +8 -13
- package/dist/hooks/use-countdown.js.map +1 -1
- package/dist/hooks/use-event-listener.cjs +1 -1
- package/dist/hooks/use-event-listener.cjs.map +1 -1
- package/dist/hooks/use-event-listener.js +6 -6
- package/dist/hooks/use-event-listener.js.map +1 -1
- package/dist/hooks/use-interval.cjs +1 -1
- package/dist/hooks/use-interval.cjs.map +1 -1
- package/dist/hooks/use-interval.js +5 -6
- package/dist/hooks/use-interval.js.map +1 -1
- package/dist/hooks/use-latest-ref.cjs.map +1 -1
- package/dist/hooks/use-latest-ref.js.map +1 -1
- package/dist/hooks/use-long-press-handlers.cjs +1 -1
- package/dist/hooks/use-long-press-handlers.cjs.map +1 -1
- package/dist/hooks/use-long-press-handlers.js +8 -10
- package/dist/hooks/use-long-press-handlers.js.map +1 -1
- package/dist/hooks/use-long-press.cjs +1 -1
- package/dist/hooks/use-long-press.cjs.map +1 -1
- package/dist/hooks/use-long-press.js +6 -6
- package/dist/hooks/use-long-press.js.map +1 -1
- package/dist/hooks/use-online.cjs +1 -1
- package/dist/hooks/use-online.cjs.map +1 -1
- package/dist/hooks/use-online.js +10 -10
- package/dist/hooks/use-online.js.map +1 -1
- package/dist/hooks/use-service-worker-update.cjs +1 -1
- package/dist/hooks/use-service-worker-update.cjs.map +1 -1
- package/dist/hooks/use-service-worker-update.js +24 -25
- package/dist/hooks/use-service-worker-update.js.map +1 -1
- package/dist/hooks/use-stable-callback.cjs +1 -1
- package/dist/hooks/use-stable-callback.cjs.map +1 -1
- package/dist/hooks/use-stable-callback.js +4 -3
- package/dist/hooks/use-stable-callback.js.map +1 -1
- package/dist/hooks/use-timeout.cjs +1 -1
- package/dist/hooks/use-timeout.cjs.map +1 -1
- package/dist/hooks/use-timeout.js +5 -6
- package/dist/hooks/use-timeout.js.map +1 -1
- package/dist/hooks/use-typewriter.cjs +1 -1
- package/dist/hooks/use-typewriter.cjs.map +1 -1
- package/dist/hooks/use-typewriter.js +9 -18
- package/dist/hooks/use-typewriter.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +11 -16
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/describe-api-error.cjs +1 -1
- package/dist/http/describe-api-error.cjs.map +1 -1
- package/dist/http/describe-api-error.js +12 -15
- package/dist/http/describe-api-error.js.map +1 -1
- package/dist/http/errors.cjs +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js +18 -6
- package/dist/http/errors.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +60 -61
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +20 -16
- package/dist/http/retry.js.map +1 -1
- package/dist/http/use-describe-api-error.cjs +1 -1
- package/dist/http/use-describe-api-error.cjs.map +1 -1
- package/dist/http/use-describe-api-error.js +2 -2
- package/dist/http/use-describe-api-error.js.map +1 -1
- package/dist/i18n/create-i18n.cjs +1 -1
- package/dist/i18n/create-i18n.cjs.map +1 -1
- package/dist/i18n/create-i18n.js +6 -6
- package/dist/i18n/create-i18n.js.map +1 -1
- package/dist/icons/material-symbols.cjs +1 -1
- package/dist/icons/material-symbols.cjs.map +1 -1
- package/dist/icons/material-symbols.js +136 -5
- package/dist/icons/material-symbols.js.map +1 -1
- package/dist/icons.d.ts +17 -5
- package/dist/offline/create-offline-sync.cjs +1 -1
- package/dist/offline/create-offline-sync.cjs.map +1 -1
- package/dist/offline/create-offline-sync.js +17 -9
- package/dist/offline/create-offline-sync.js.map +1 -1
- package/dist/offline/use-offline-sync.cjs +1 -1
- package/dist/offline/use-offline-sync.cjs.map +1 -1
- package/dist/offline/use-offline-sync.js +7 -8
- package/dist/offline/use-offline-sync.js.map +1 -1
- package/dist/push/use-push-subscription.cjs +1 -1
- package/dist/push/use-push-subscription.cjs.map +1 -1
- package/dist/push/use-push-subscription.js +13 -12
- package/dist/push/use-push-subscription.js.map +1 -1
- package/dist/query/retry-policy.cjs +1 -1
- package/dist/query/retry-policy.cjs.map +1 -1
- package/dist/query/retry-policy.js +3 -3
- package/dist/query/retry-policy.js.map +1 -1
- package/dist/sse/use-event-stream.cjs +1 -1
- package/dist/sse/use-event-stream.cjs.map +1 -1
- package/dist/sse/use-event-stream.js +19 -20
- package/dist/sse/use-event-stream.js.map +1 -1
- package/dist/tabular/use-tabular-predictor.cjs +1 -1
- package/dist/tabular/use-tabular-predictor.cjs.map +1 -1
- package/dist/tabular/use-tabular-predictor.js +20 -17
- package/dist/tabular/use-tabular-predictor.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +363 -149
- package/dist/tempest-react-sdk.js +143 -143
- package/dist/theme/ThemeProvider.cjs +1 -1
- package/dist/theme/ThemeProvider.cjs.map +1 -1
- package/dist/theme/ThemeProvider.js +12 -17
- package/dist/theme/ThemeProvider.js.map +1 -1
- package/dist/utils/base64.cjs +2 -0
- package/dist/utils/base64.cjs.map +1 -0
- package/dist/utils/base64.js +16 -0
- package/dist/utils/base64.js.map +1 -0
- package/dist/utils/compare-values.cjs +1 -1
- package/dist/utils/compare-values.cjs.map +1 -1
- package/dist/utils/compare-values.js +4 -3
- package/dist/utils/compare-values.js.map +1 -1
- package/dist/utils/compressed-storage.cjs +1 -1
- package/dist/utils/compressed-storage.cjs.map +1 -1
- package/dist/utils/compressed-storage.js +16 -46
- package/dist/utils/compressed-storage.js.map +1 -1
- package/dist/utils/storage.cjs +1 -1
- package/dist/utils/storage.cjs.map +1 -1
- package/dist/utils/storage.js +37 -17
- package/dist/utils/storage.js.map +1 -1
- package/dist/vision/use-camera-stream.cjs +1 -1
- package/dist/vision/use-camera-stream.cjs.map +1 -1
- package/dist/vision/use-camera-stream.js +34 -33
- package/dist/vision/use-camera-stream.js.map +1 -1
- package/dist/vite/base-url.cjs +2 -0
- package/dist/vite/base-url.cjs.map +1 -0
- package/dist/vite/base-url.js +8 -0
- package/dist/vite/base-url.js.map +1 -0
- package/dist/vite/tempest-pwa-dev-sw.cjs +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.js +54 -29
- package/dist/vite/tempest-pwa-dev-sw.js.map +1 -1
- package/dist/vite/tempest-pwa-manifest.cjs +2 -2
- package/dist/vite/tempest-pwa-manifest.cjs.map +1 -1
- package/dist/vite/tempest-pwa-manifest.js +15 -14
- package/dist/vite/tempest-pwa-manifest.js.map +1 -1
- package/dist/vite.d.ts +2 -2
- package/dist/ws/use-web-socket.cjs +1 -1
- package/dist/ws/use-web-socket.cjs.map +1 -1
- package/dist/ws/use-web-socket.js +40 -42
- package/dist/ws/use-web-socket.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,17 +1,14 @@
|
|
|
1
|
-
import { isComplete as e
|
|
1
|
+
import { isComplete as e } from "./filter-model.js";
|
|
2
|
+
import { formatDateForInput as t } from "../../utils/format.js";
|
|
2
3
|
//#region src/components/FilterBar/filter-apply.ts
|
|
3
|
-
var n = /^\d{4}-\d{2}-\d{2}
|
|
4
|
-
function
|
|
4
|
+
var n = /^\d{4}-\d{2}-\d{2}$/, r = new Intl.Collator(void 0, { numeric: !0 });
|
|
5
|
+
function i(e, t) {
|
|
5
6
|
if (!(typeof e != "object" || !e)) return e[t];
|
|
6
7
|
}
|
|
7
|
-
function
|
|
8
|
-
|
|
9
|
-
let t = e instanceof Date ? e : typeof e == "string" && e.trim() !== "" ? new Date(e) : null;
|
|
10
|
-
if (t === null || Number.isNaN(t.getTime())) return null;
|
|
11
|
-
let r = `${t.getMonth() + 1}`.padStart(2, "0"), i = `${t.getDate()}`.padStart(2, "0");
|
|
12
|
-
return `${t.getFullYear()}-${r}-${i}`;
|
|
8
|
+
function a(e) {
|
|
9
|
+
return e instanceof Date ? t(e) || null : typeof e != "string" || e.trim() === "" ? null : t(e) || null;
|
|
13
10
|
}
|
|
14
|
-
function
|
|
11
|
+
function o(e, t) {
|
|
15
12
|
if (e == null) return null;
|
|
16
13
|
if (typeof e == "number") {
|
|
17
14
|
let n = Number(t);
|
|
@@ -22,55 +19,55 @@ function a(e, t) {
|
|
|
22
19
|
return n === null ? null : Number(e) - Number(n);
|
|
23
20
|
}
|
|
24
21
|
if (n.test(t)) {
|
|
25
|
-
let n =
|
|
22
|
+
let n = a(e);
|
|
26
23
|
return n === null ? null : n.localeCompare(t);
|
|
27
24
|
}
|
|
28
|
-
return String(e)
|
|
25
|
+
return r.compare(String(e), t);
|
|
29
26
|
}
|
|
30
|
-
function
|
|
31
|
-
|
|
27
|
+
function s(e, t) {
|
|
28
|
+
if (e === t) return !0;
|
|
29
|
+
let n = o(e, t);
|
|
32
30
|
return n === null ? String(e ?? "") === t : n === 0;
|
|
33
31
|
}
|
|
34
|
-
function
|
|
32
|
+
function c(e) {
|
|
35
33
|
return e == null ? !0 : typeof e == "string" ? e.trim() === "" : Array.isArray(e) ? e.length === 0 : !1;
|
|
36
34
|
}
|
|
37
|
-
function
|
|
35
|
+
function l(e) {
|
|
38
36
|
return e.value === void 0 ? [] : Array.isArray(e.value) ? [...e.value] : [String(e.value)];
|
|
39
37
|
}
|
|
40
|
-
function
|
|
38
|
+
function u(e, t, n) {
|
|
41
39
|
switch (e) {
|
|
42
|
-
case "empty": return
|
|
43
|
-
case "notEmpty": return !
|
|
44
|
-
case "eq": return
|
|
45
|
-
case "ne": return !
|
|
40
|
+
case "empty": return c(t);
|
|
41
|
+
case "notEmpty": return !c(t);
|
|
42
|
+
case "eq": return s(t, n[0] ?? "");
|
|
43
|
+
case "ne": return !s(t, n[0] ?? "");
|
|
46
44
|
case "contains": return String(t ?? "").toLowerCase().includes((n[0] ?? "").toLowerCase());
|
|
47
|
-
case "in": return n.some((e) =>
|
|
45
|
+
case "in": return n.some((e) => s(t, e));
|
|
48
46
|
case "between": {
|
|
49
|
-
let [e = "", r = ""] = n, i =
|
|
50
|
-
return i === null ||
|
|
47
|
+
let [e = "", r = ""] = n, i = o(t, e), a = o(t, r);
|
|
48
|
+
return i === null || a === null ? !1 : i >= 0 && a <= 0;
|
|
51
49
|
}
|
|
52
50
|
default: {
|
|
53
|
-
let r =
|
|
51
|
+
let r = o(t, n[0] ?? "");
|
|
54
52
|
return r === null ? !1 : e === "gt" ? r > 0 : e === "gte" ? r >= 0 : e === "lt" ? r < 0 : r <= 0;
|
|
55
53
|
}
|
|
56
54
|
}
|
|
57
55
|
}
|
|
58
|
-
function
|
|
59
|
-
let [t = "",
|
|
60
|
-
if (n.test(t) && n.test(
|
|
61
|
-
let
|
|
62
|
-
return !Number.isNaN(
|
|
56
|
+
function d(e) {
|
|
57
|
+
let [t = "", i = ""] = e;
|
|
58
|
+
if (n.test(t) && n.test(i)) return t <= i ? [t, i] : [i, t];
|
|
59
|
+
let a = Number(t), o = Number(i);
|
|
60
|
+
return !Number.isNaN(a) && !Number.isNaN(o) ? a <= o ? [t, i] : [i, t] : r.compare(t, i) <= 0 ? [t, i] : [i, t];
|
|
63
61
|
}
|
|
64
|
-
function
|
|
65
|
-
let
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
let a = n.operator === "between" ? u(c(n)) : c(n);
|
|
70
|
-
return l(n.operator, i, a);
|
|
62
|
+
function f(t, n) {
|
|
63
|
+
let r = n.filter(e).map((e) => ({
|
|
64
|
+
field: e.field,
|
|
65
|
+
operator: e.operator,
|
|
66
|
+
values: e.operator === "between" ? d(l(e)) : l(e)
|
|
71
67
|
}));
|
|
68
|
+
return r.length === 0 ? [...t] : t.filter((e) => r.every(({ field: t, operator: n, values: r }) => u(n, i(e, t), r)));
|
|
72
69
|
}
|
|
73
70
|
//#endregion
|
|
74
|
-
export {
|
|
71
|
+
export { f as applyFilters, d as orderRange };
|
|
75
72
|
|
|
76
73
|
//# sourceMappingURL=filter-apply.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"filter-apply.js","names":[],"sources":["../../../src/components/FilterBar/filter-apply.ts"],"sourcesContent":["// The other half of the filter model: evaluating a `Filter[]` instead of only\n// describing it. `FilterBar` produces filters, `applyFilters` runs them over an\n// in-memory list, and `filtersToQueryParams` (filter-query.ts) hands the same set\n// to a paginated backend. Without these two the model stops one step short of\n// useful and every app writes the eleven operator branches again.\n\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete, isValueless } from \"./filter-model\";\n\n/** Matches a plain `yyyy-mm-dd`, the shape `<input type=\"date\">` produces. */\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * Read a property off a row without asserting the row's shape.\n *\n * `Filter.field` is a string chosen by the app's field list, so it cannot be a\n * `keyof T`; the lookup goes through an index signature and a missing property\n * yields `undefined`, which the operators treat as an empty value.\n *\n * @param item - The row being tested.\n * @param field - Property name from the filter.\n * @returns The property value, or `undefined` when the row has no such key.\n */\nfunction readField(item: unknown, field: string): unknown {\n if (item == null || typeof item !== \"object\") return undefined;\n return (item as Record<string, unknown>)[field];\n}\n\n/**\n * Local `yyyy-mm-dd` for a value that represents a date, or `null`.\n *\n * Built from the local calendar parts rather than `toISOString`, which converts\n * to UTC first and therefore reports the next day for anything after 21:00 in\n * UTC-3. A `yyyy-mm-dd` string is returned untouched, so a filter value and a\n * row value that already agree never round-trip through `Date` at all.\n *\n * @param value - A `Date`, a date-ish string, or anything else.\n * @returns The day key, or `null` when the value does not denote a date.\n */\nfunction dayKey(value: unknown): string | null {\n if (typeof value === \"string\" && DATE_ONLY.test(value)) return value;\n\n const date =\n value instanceof Date\n ? value\n : typeof value === \"string\" && value.trim() !== \"\"\n ? new Date(value)\n : null;\n if (date === null || Number.isNaN(date.getTime())) return null;\n\n const month = `${date.getMonth() + 1}`.padStart(2, \"0\");\n const day = `${date.getDate()}`.padStart(2, \"0\");\n return `${date.getFullYear()}-${month}-${day}`;\n}\n\n/**\n * Compare a row value against a filter value, in the row value's own type.\n *\n * The filter always carries strings — it comes from form inputs and from the\n * URL — while the row carries whatever the API returned. Comparing them as text\n * gets the two common cases wrong: `10` would sort before `9`, and a date would\n * be compared by however it happens to be formatted. So the row value picks the\n * comparison, and the filter value is coerced into it.\n *\n * Dates compare by **day**, not by instant: a row stamped `2026-03-05T13:00:00Z`\n * is `>= 2026-03-05`, which is what the person picking a date in the UI means.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Negative, zero or positive, or `null` when the two cannot be compared.\n */\nfunction compare(left: unknown, right: string): number | null {\n if (left == null) return null;\n\n if (typeof left === \"number\") {\n const parsed = Number(right);\n return Number.isNaN(parsed) ? null : left - parsed;\n }\n\n if (typeof left === \"boolean\") {\n const parsed = right === \"true\" ? true : right === \"false\" ? false : null;\n return parsed === null ? null : Number(left) - Number(parsed);\n }\n\n if (DATE_ONLY.test(right)) {\n const key = dayKey(left);\n return key === null ? null : key.localeCompare(right);\n }\n\n return String(left).localeCompare(right, undefined, { numeric: true });\n}\n\n/**\n * Equality in the row value's type, falling back to exact text.\n *\n * Case-sensitive on purpose: `eq` maps to a plain `WHERE column = value` on the\n * server side, so a case-insensitive client would quietly disagree with the\n * backend for the same filter. `contains` is the case-insensitive operator, and\n * it is also the default one for text fields, so the friendly behaviour is what\n * people get without asking.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Whether the two are equal.\n */\nfunction equals(left: unknown, right: string): boolean {\n const result = compare(left, right);\n if (result !== null) return result === 0;\n return String(left ?? \"\") === right;\n}\n\n/**\n * Is this row value empty?\n *\n * Empty means absent, blank text or an empty list — never falsy. `0` and `false`\n * are values somebody chose, and a filter that hid them would be reporting the\n * wrong count on every dashboard that tracks zeroes.\n *\n * @param value - The row value.\n * @returns Whether the value counts as empty.\n */\nfunction isEmptyValue(value: unknown): boolean {\n if (value == null) return true;\n if (typeof value === \"string\") return value.trim() === \"\";\n if (Array.isArray(value)) return value.length === 0;\n return false;\n}\n\n/**\n * The filter's value as a list, whatever arity the operator uses.\n *\n * @param filter - The filter to read.\n * @returns Its values, trimmed of nothing — a leading space may be meaningful text.\n */\nfunction valuesOf(filter: Filter): string[] {\n if (filter.value === undefined) return [];\n return Array.isArray(filter.value) ? [...filter.value] : [String(filter.value)];\n}\n\n/**\n * Evaluate one operator against one row value.\n *\n * @param operator - The comparison to make.\n * @param left - The row value.\n * @param values - The filter values (one, two for `between`, many for `in`).\n * @returns Whether the row value satisfies the operator.\n */\nfunction matchesOperator(operator: FilterOperator, left: unknown, values: string[]): boolean {\n switch (operator) {\n case \"empty\":\n return isEmptyValue(left);\n case \"notEmpty\":\n return !isEmptyValue(left);\n case \"eq\":\n return equals(left, values[0] ?? \"\");\n case \"ne\":\n return !equals(left, values[0] ?? \"\");\n case \"contains\":\n return String(left ?? \"\")\n .toLowerCase()\n .includes((values[0] ?? \"\").toLowerCase());\n case \"in\":\n return values.some((value) => equals(left, value));\n case \"between\": {\n const [first = \"\", second = \"\"] = values;\n const low = compare(left, first);\n const high = compare(left, second);\n if (low === null || high === null) return false;\n return low >= 0 && high <= 0;\n }\n default: {\n const result = compare(left, values[0] ?? \"\");\n if (result === null) return false;\n if (operator === \"gt\") return result > 0;\n if (operator === \"gte\") return result >= 0;\n if (operator === \"lt\") return result < 0;\n return result <= 0;\n }\n }\n}\n\n/**\n * Order the two values of a `between` so the range is never empty by accident.\n *\n * A person who picks the later date first means the range between the two dates,\n * not \"no rows\". The server-side `BETWEEN` needs `(lo, hi)` in order too, which\n * is why the normalisation lives here and is shared by `filtersToQueryParams`.\n *\n * @param values - The raw pair.\n * @returns The pair, ascending.\n */\nexport function orderRange(values: readonly string[]): string[] {\n const [first = \"\", second = \"\"] = values;\n if (DATE_ONLY.test(first) && DATE_ONLY.test(second)) {\n return first <= second ? [first, second] : [second, first];\n }\n const low = Number(first);\n const high = Number(second);\n if (!Number.isNaN(low) && !Number.isNaN(high)) {\n return low <= high ? [first, second] : [second, first];\n }\n return first.localeCompare(second, undefined, { numeric: true }) <= 0\n ? [first, second]\n : [second, first];\n}\n\n/**\n * Run a filter set over an in-memory list.\n *\n * Closes the loop `FilterBar` opens: the bar produces `Filter[]`, this applies\n * them. Filters combine with `AND`, matching the flat model the bar builds, and\n * an incomplete filter is skipped rather than treated as a match of nothing — a\n * half-filled form should not empty the table underneath it.\n *\n * Comparison follows the row's type, not the filter's: numbers compare\n * numerically, dates compare by day, and everything else compares as text with\n * `numeric: true` so `\"item 2\"` lands before `\"item 10\"`.\n *\n * A few behaviours differ from the SQL the server-side twin produces, and the\n * difference is deliberate rather than accidental:\n *\n * - `ne` matches rows whose value is absent. In SQL, `column <> 'x'` is `NULL`\n * for a `NULL` column and the row drops out. Here \"is not paid\" shows the rows\n * with no status at all, which is what the chip claims.\n * - `empty` matches `NULL`, blank text and empty lists; `__isnull` on the server\n * only matches `NULL`. A column that stores `\"\"` instead of `NULL` is where\n * the two disagree.\n *\n * @example\n * const visible = applyFilters(orders, filters);\n *\n * @param items - The full list.\n * @param filters - Applied filters; incomplete ones are ignored.\n * @returns A new array with the rows that satisfy every complete filter.\n */\nexport function applyFilters<T>(items: readonly T[], filters: readonly Filter[]): T[] {\n const active = filters.filter(isComplete);\n if (active.length === 0) return [...items];\n\n return items.filter((item) =>\n active.every((filter) => {\n const left = readField(item, filter.field);\n if (isValueless(filter.operator)) {\n return matchesOperator(filter.operator, left, []);\n }\n const values =\n filter.operator === \"between\" ? orderRange(valuesOf(filter)) : valuesOf(filter);\n return matchesOperator(filter.operator, left, values);\n }),\n );\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"filter-apply.js","names":[],"sources":["../../../src/components/FilterBar/filter-apply.ts"],"sourcesContent":["// The other half of the filter model: evaluating a `Filter[]` instead of only\n// describing it. `FilterBar` produces filters, `applyFilters` runs them over an\n// in-memory list, and `filtersToQueryParams` (filter-query.ts) hands the same set\n// to a paginated backend. Without these two the model stops one step short of\n// useful and every app writes the eleven operator branches again.\n\nimport { formatDateForInput } from \"@/utils/format\";\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete } from \"./filter-model\";\n\n/** Matches a plain `yyyy-mm-dd`, the shape `<input type=\"date\">` produces. */\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * One collator for every text comparison in this module.\n *\n * `localeCompare(value, undefined, { numeric: true })` builds a collator on each\n * call — passing an options bag opts out of the engine's cached-default fast\n * path — and this comparison runs once per row per filter. Measured at 200k\n * comparisons: 453 ms through `localeCompare` against 25 ms through a hoisted\n * collator, i.e. ~23 ms of main thread per keystroke on a 10k-row list.\n */\nconst TEXT_COLLATOR = new Intl.Collator(undefined, { numeric: true });\n\n/**\n * Read a property off a row without asserting the row's shape.\n *\n * `Filter.field` is a string chosen by the app's field list, so it cannot be a\n * `keyof T`; the lookup goes through an index signature and a missing property\n * yields `undefined`, which the operators treat as an empty value.\n *\n * @param item - The row being tested.\n * @param field - Property name from the filter.\n * @returns The property value, or `undefined` when the row has no such key.\n */\nfunction readField(item: unknown, field: string): unknown {\n if (item == null || typeof item !== \"object\") return undefined;\n return (item as Record<string, unknown>)[field];\n}\n\n/**\n * Local `yyyy-mm-dd` for a value that represents a date, or `null`.\n *\n * Delegates the formatting to {@link formatDateForInput}, which owns the rule\n * that the key is built from the local calendar parts rather than `toISOString`.\n * This adds only the narrowing from `unknown` and maps \"not a date\" to `null`\n * instead of to the empty string a date input wants.\n *\n * @param value - A `Date`, a date-ish string, or anything else.\n * @returns The day key, or `null` when the value does not denote a date.\n */\nfunction dayKey(value: unknown): string | null {\n if (value instanceof Date) return formatDateForInput(value) || null;\n if (typeof value !== \"string\" || value.trim() === \"\") return null;\n return formatDateForInput(value) || null;\n}\n\n/**\n * Compare a row value against a filter value, in the row value's own type.\n *\n * The filter always carries strings — it comes from form inputs and from the\n * URL — while the row carries whatever the API returned. Comparing them as text\n * gets the two common cases wrong: `10` would sort before `9`, and a date would\n * be compared by however it happens to be formatted. So the row value picks the\n * comparison, and the filter value is coerced into it.\n *\n * Dates compare by **day**, not by instant: a row stamped `2026-03-05T13:00:00Z`\n * is `>= 2026-03-05`, which is what the person picking a date in the UI means.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Negative, zero or positive, or `null` when the two cannot be compared.\n */\nfunction compare(left: unknown, right: string): number | null {\n if (left == null) return null;\n\n if (typeof left === \"number\") {\n const parsed = Number(right);\n return Number.isNaN(parsed) ? null : left - parsed;\n }\n\n if (typeof left === \"boolean\") {\n const parsed = right === \"true\" ? true : right === \"false\" ? false : null;\n return parsed === null ? null : Number(left) - Number(parsed);\n }\n\n if (DATE_ONLY.test(right)) {\n const key = dayKey(left);\n return key === null ? null : key.localeCompare(right);\n }\n\n return TEXT_COLLATOR.compare(String(left), right);\n}\n\n/**\n * Equality in the row value's type, falling back to exact text.\n *\n * Case-sensitive on purpose: `eq` maps to a plain `WHERE column = value` on the\n * server side, so a case-insensitive client would quietly disagree with the\n * backend for the same filter. `contains` is the case-insensitive operator, and\n * it is also the default one for text fields, so the friendly behaviour is what\n * people get without asking.\n *\n * Identical strings take a fast path out, since the row value is text in the\n * common case and the collator is the expensive part.\n *\n * @param left - The row value.\n * @param right - The raw filter value.\n * @returns Whether the two are equal.\n */\nfunction equals(left: unknown, right: string): boolean {\n if (left === right) return true;\n const result = compare(left, right);\n if (result !== null) return result === 0;\n return String(left ?? \"\") === right;\n}\n\n/**\n * Is this row value empty?\n *\n * Empty means absent, blank text or an empty list — never falsy. `0` and `false`\n * are values somebody chose, and a filter that hid them would be reporting the\n * wrong count on every dashboard that tracks zeroes.\n *\n * @param value - The row value.\n * @returns Whether the value counts as empty.\n */\nfunction isEmptyValue(value: unknown): boolean {\n if (value == null) return true;\n if (typeof value === \"string\") return value.trim() === \"\";\n if (Array.isArray(value)) return value.length === 0;\n return false;\n}\n\n/**\n * The filter's value as a list, whatever arity the operator uses.\n *\n * @param filter - The filter to read.\n * @returns Its values, trimmed of nothing — a leading space may be meaningful text.\n */\nfunction valuesOf(filter: Filter): string[] {\n if (filter.value === undefined) return [];\n return Array.isArray(filter.value) ? [...filter.value] : [String(filter.value)];\n}\n\n/**\n * Evaluate one operator against one row value.\n *\n * @param operator - The comparison to make.\n * @param left - The row value.\n * @param values - The filter values (one, two for `between`, many for `in`).\n * @returns Whether the row value satisfies the operator.\n */\nfunction matchesOperator(operator: FilterOperator, left: unknown, values: string[]): boolean {\n switch (operator) {\n case \"empty\":\n return isEmptyValue(left);\n case \"notEmpty\":\n return !isEmptyValue(left);\n case \"eq\":\n return equals(left, values[0] ?? \"\");\n case \"ne\":\n return !equals(left, values[0] ?? \"\");\n case \"contains\":\n return String(left ?? \"\")\n .toLowerCase()\n .includes((values[0] ?? \"\").toLowerCase());\n case \"in\":\n return values.some((value) => equals(left, value));\n case \"between\": {\n const [first = \"\", second = \"\"] = values;\n const low = compare(left, first);\n const high = compare(left, second);\n if (low === null || high === null) return false;\n return low >= 0 && high <= 0;\n }\n default: {\n const result = compare(left, values[0] ?? \"\");\n if (result === null) return false;\n if (operator === \"gt\") return result > 0;\n if (operator === \"gte\") return result >= 0;\n if (operator === \"lt\") return result < 0;\n return result <= 0;\n }\n }\n}\n\n/**\n * Order the two values of a `between` so the range is never empty by accident.\n *\n * A person who picks the later date first means the range between the two dates,\n * not \"no rows\". The server-side `BETWEEN` needs `(lo, hi)` in order too, which\n * is why the normalisation lives here and is shared by `filtersToQueryParams`.\n *\n * @param values - The raw pair.\n * @returns The pair, ascending.\n */\nexport function orderRange(values: readonly string[]): string[] {\n const [first = \"\", second = \"\"] = values;\n if (DATE_ONLY.test(first) && DATE_ONLY.test(second)) {\n return first <= second ? [first, second] : [second, first];\n }\n const low = Number(first);\n const high = Number(second);\n if (!Number.isNaN(low) && !Number.isNaN(high)) {\n return low <= high ? [first, second] : [second, first];\n }\n return TEXT_COLLATOR.compare(first, second) <= 0 ? [first, second] : [second, first];\n}\n\n/**\n * Run a filter set over an in-memory list.\n *\n * Closes the loop `FilterBar` opens: the bar produces `Filter[]`, this applies\n * them. Filters combine with `AND`, matching the flat model the bar builds, and\n * an incomplete filter is skipped rather than treated as a match of nothing — a\n * half-filled form should not empty the table underneath it.\n *\n * Comparison follows the row's type, not the filter's: numbers compare\n * numerically, dates compare by day, and everything else compares as text with\n * `numeric: true` so `\"item 2\"` lands before `\"item 10\"`.\n *\n * A few behaviours differ from the SQL the server-side twin produces, and the\n * difference is deliberate rather than accidental:\n *\n * - `ne` matches rows whose value is absent. In SQL, `column <> 'x'` is `NULL`\n * for a `NULL` column and the row drops out. Here \"is not paid\" shows the rows\n * with no status at all, which is what the chip claims.\n * - `empty` matches `NULL`, blank text and empty lists; `__isnull` on the server\n * only matches `NULL`. A column that stores `\"\"` instead of `NULL` is where\n * the two disagree.\n *\n * @example\n * const visible = applyFilters(orders, filters);\n *\n * Each filter's values are normalised once, before the scan, rather than inside\n * the per-row predicate: the arity, the `between` ordering and the value array\n * depend only on the filter, so deriving them per row multiplied that work by\n * the row count. `empty`/`notEmpty` ignore their values entirely, which is why\n * the prepared shape does not need to distinguish them.\n *\n * @param items - The full list.\n * @param filters - Applied filters; incomplete ones are ignored.\n * @returns A new array with the rows that satisfy every complete filter.\n */\nexport function applyFilters<T>(items: readonly T[], filters: readonly Filter[]): T[] {\n const active = filters.filter(isComplete).map((filter) => ({\n field: filter.field,\n operator: filter.operator,\n values: filter.operator === \"between\" ? orderRange(valuesOf(filter)) : valuesOf(filter),\n }));\n if (active.length === 0) return [...items];\n\n return items.filter((item) =>\n active.every(({ field, operator, values }) =>\n matchesOperator(operator, readField(item, field), values),\n ),\n );\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./filter-model.cjs"),t=require("./filter-apply.cjs");var n={eq:``,ne:`__ne`,contains:`__icontains`,gt:`__gt`,gte:`__gte`,lt:`__lt`,lte:`__lte`,between:`__between`,in:`__in`,empty:`__isnull`,notEmpty:`__isnull`},r
|
|
1
|
+
const e=require("./filter-model.cjs"),t=require("./filter-apply.cjs");var n={eq:``,ne:`__ne`,contains:`__icontains`,gt:`__gt`,gte:`__gte`,lt:`__lt`,lte:`__lte`,between:`__between`,in:`__in`,empty:`__isnull`,notEmpty:`__isnull`},r=new Set([`name`]);function i(i,a={}){let o=a.operatorSuffix?{...n,...a.operatorSuffix}:n,s=a.substringColumns?new Set(a.substringColumns):r,c=new URLSearchParams;for(let n of i){if(!e.isComplete(n))continue;let r=o[n.operator],i=n.operator===`eq`&&s.has(n.field)?`${n.field}__iexact`:`${n.field}${r}`;if(n.operator===`empty`||n.operator===`notEmpty`){c.append(i,n.operator===`empty`?`true`:`false`);continue}let a=Array.isArray(n.value)?[...n.value]:[String(n.value??``)];if(n.operator===`between`){for(let e of t.orderRange(a))c.append(i,e);continue}for(let e of a)c.append(i,e)}return c}exports.filtersToQueryParams=i;
|
|
2
2
|
//# sourceMappingURL=filter-query.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"filter-query.cjs","names":[],"sources":["../../../src/components/FilterBar/filter-query.ts"],"sourcesContent":["// Server-side half of the filter model: the same `Filter[]` the bar produces,\n// encoded the way a paginated backend expects to read it. Kept apart from\n// `filtersToSearchParams` (filter-model.ts) because the two answer different\n// questions — that one round-trips the UI state through the URL, this one talks\n// to an API and its shape is the API's, not ours.\n\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete } from \"./filter-model\";\nimport { orderRange } from \"./filter-apply\";\n\n/**\n * Operator suffix per filter operator, following the `<column>__<op>` convention\n * of `tempest-fastapi-sdk`.\n *\n * Ported from `build_filter_condition` in\n * `tempest_fastapi_sdk/db/expressions.py`, which is what `BaseRepository`\n * dict filters and `Q` both resolve through. An empty suffix means the bare\n * column name, which that function resolves to plain equality.\n *\n * `contains` maps to `icontains` (case-insensitive, and the backend escapes the\n * `LIKE` wildcards) and both emptiness operators map to `isnull`, whose value\n * carries the direction.\n */\nconst
|
|
1
|
+
{"version":3,"file":"filter-query.cjs","names":[],"sources":["../../../src/components/FilterBar/filter-query.ts"],"sourcesContent":["// Server-side half of the filter model: the same `Filter[]` the bar produces,\n// encoded the way a paginated backend expects to read it. Kept apart from\n// `filtersToSearchParams` (filter-model.ts) because the two answer different\n// questions — that one round-trips the UI state through the URL, this one talks\n// to an API and its shape is the API's, not ours.\n\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete } from \"./filter-model\";\nimport { orderRange } from \"./filter-apply\";\n\n/**\n * Operator suffix per filter operator, following the `<column>__<op>` convention\n * of `tempest-fastapi-sdk`.\n *\n * Ported from `build_filter_condition` in\n * `tempest_fastapi_sdk/db/expressions.py`, which is what `BaseRepository`\n * dict filters and `Q` both resolve through. An empty suffix means the bare\n * column name, which that function resolves to plain equality.\n *\n * `contains` maps to `icontains` (case-insensitive, and the backend escapes the\n * `LIKE` wildcards) and both emptiness operators map to `isnull`, whose value\n * carries the direction.\n */\nconst DEFAULT_OPERATOR_SUFFIX: Record<FilterOperator, string> = {\n eq: \"\",\n ne: \"__ne\",\n contains: \"__icontains\",\n gt: \"__gt\",\n gte: \"__gte\",\n lt: \"__lt\",\n lte: \"__lte\",\n between: \"__between\",\n in: \"__in\",\n empty: \"__isnull\",\n notEmpty: \"__isnull\",\n};\n\n/**\n * Columns the backend treats as a substring search when they carry no operator\n * suffix.\n *\n * Ported from `build_filter_condition`, which special-cases a string `name` into\n * `ILIKE %value%`. Sending a bare `name=` for an `eq` filter would therefore ask\n * for \"contains\" while the chip says \"is\", so `eq` on such a column is emitted as\n * `name__iexact` instead.\n */\nconst DEFAULT_SUBSTRING_COLUMNS: ReadonlySet<string> = new Set([\"name\"]);\n\n/** Overrides for the backend dialect {@link filtersToQueryParams} encodes into. */\nexport interface FiltersToQueryParamsOptions {\n /**\n * Columns whose `eq` is emitted as `<column>__iexact` rather than as the bare\n * column name. Default `[\"name\"]`, which is what `build_filter_condition`\n * special-cases.\n *\n * Pass the columns **your** backend treats that way — `nome`, `titulo`,\n * `razao_social` — or `[]` when it treats none of them specially and a bare\n * `eq` should stay bare.\n */\n substringColumns?: readonly string[];\n /**\n * Operator suffixes, merged over the `tempest-fastapi-sdk` dialect, so an\n * override names only the operators that differ.\n *\n * @example\n * // A DRF-style backend\n * filtersToQueryParams(filters, {\n * substringColumns: [],\n * operatorSuffix: { contains: \"__icontains\", ne: \"__exclude\" },\n * });\n */\n operatorSuffix?: Partial<Record<FilterOperator, string>>;\n}\n\n/**\n * Encode filters as query params for a paginated backend.\n *\n * The counterpart of {@link applyFilters}: same filter set, evaluated by the\n * database instead of by the browser, which is the only option once the list is\n * paginated on the server and the page in memory is not the whole result.\n *\n * The encoding is the `<column>__<op>` convention `tempest-fastapi-sdk` already\n * reads (`BaseRepository._apply_filters` → `build_filter_condition`):\n *\n * | Operator | Param |\n * | --- | --- |\n * | `eq` | `field` (or `field__iexact` for the `name` column) |\n * | `ne` | `field__ne` |\n * | `contains` | `field__icontains` |\n * | `gt` `gte` `lt` `lte` | `field__gt` … `field__lte` |\n * | `between` | `field__between` twice, low value first |\n * | `in` | `field__in` once per value |\n * | `empty` / `notEmpty` | `field__isnull=true` / `=false` |\n *\n * Returns `URLSearchParams` rather than a plain object because `between` carries\n * a pair and `in` carries a list: an object would keep only the last value of\n * each, silently narrowing the filter. Repeated params are also how FastAPI\n * receives a `list[str]` declared with `Query`.\n *\n * Two things the backend has to hold up its end of, or the filter fails quietly:\n *\n * - **Every key must be declared.** `BasePaginationFilterSchema.get_conditions()`\n * only forwards fields the subclass declares, so a `status__ne` the schema\n * never mentions is dropped by FastAPI before the repository sees it — no\n * error, no filtering.\n * - **`isnull` matches `NULL` only.** A column that stores `\"\"` for \"no value\"\n * will not answer an `empty` filter, while {@link applyFilters} treats blank\n * text as empty.\n *\n * The defaults are that dialect, not a universal truth. A backend that names its\n * substring column something other than `name`, or that spells its operators\n * differently, passes `options` — the alternative was an encoder whose special\n * cases were a wall for anyone not on the Tempest stack.\n *\n * @example\n * const params = filtersToQueryParams(filters);\n * params.set(\"page\", String(page));\n * const data = await api.get(`/orders?${params}`);\n *\n * @example\n * // A backend whose searchable column is `razao_social` and that spells `ne`\n * // the Django way.\n * const params = filtersToQueryParams(filters, {\n * substringColumns: [\"razao_social\"],\n * operatorSuffix: { ne: \"__exclude\" },\n * });\n *\n * @param filters - Applied filters; incomplete ones are ignored.\n * @param options - Dialect overrides. Defaults to the `tempest-fastapi-sdk` one.\n * @returns Params ready to append to a request URL.\n */\nexport function filtersToQueryParams(\n filters: readonly Filter[],\n options: FiltersToQueryParamsOptions = {},\n): URLSearchParams {\n const suffixes = options.operatorSuffix\n ? { ...DEFAULT_OPERATOR_SUFFIX, ...options.operatorSuffix }\n : DEFAULT_OPERATOR_SUFFIX;\n const substringColumns = options.substringColumns\n ? new Set(options.substringColumns)\n : DEFAULT_SUBSTRING_COLUMNS;\n\n const params = new URLSearchParams();\n\n for (const filter of filters) {\n if (!isComplete(filter)) continue;\n\n const suffix = suffixes[filter.operator];\n const key =\n filter.operator === \"eq\" && substringColumns.has(filter.field)\n ? `${filter.field}__iexact`\n : `${filter.field}${suffix}`;\n\n if (filter.operator === \"empty\" || filter.operator === \"notEmpty\") {\n params.append(key, filter.operator === \"empty\" ? \"true\" : \"false\");\n continue;\n }\n\n const values = Array.isArray(filter.value)\n ? [...filter.value]\n : [String(filter.value ?? \"\")];\n\n if (filter.operator === \"between\") {\n for (const value of orderRange(values)) params.append(key, value);\n continue;\n }\n\n for (const value of values) params.append(key, value);\n }\n\n return params;\n}\n"],"mappings":"sEAuBA,IAAM,EAA0D,CAC5D,GAAI,GACJ,GAAI,OACJ,SAAU,cACV,GAAI,OACJ,IAAK,QACL,GAAI,OACJ,IAAK,QACL,QAAS,YACT,GAAI,OACJ,MAAO,WACP,SAAU,UACd,EAWM,EAAiD,IAAI,IAAI,CAAC,MAAM,CAAC,EAqFvE,SAAgB,EACZ,EACA,EAAuC,CAAC,EACzB,CACf,IAAM,EAAW,EAAQ,eACnB,CAAE,GAAG,EAAyB,GAAG,EAAQ,cAAe,EACxD,EACA,EAAmB,EAAQ,iBAC3B,IAAI,IAAI,EAAQ,gBAAgB,EAChC,EAEA,EAAS,IAAI,gBAEnB,IAAK,IAAM,KAAU,EAAS,CAC1B,GAAI,CAAC,EAAA,WAAW,CAAM,EAAG,SAEzB,IAAM,EAAS,EAAS,EAAO,UACzB,EACF,EAAO,WAAa,MAAQ,EAAiB,IAAI,EAAO,KAAK,EACvD,GAAG,EAAO,MAAM,UAChB,GAAG,EAAO,QAAQ,IAE5B,GAAI,EAAO,WAAa,SAAW,EAAO,WAAa,WAAY,CAC/D,EAAO,OAAO,EAAK,EAAO,WAAa,QAAU,OAAS,OAAO,EACjE,QACJ,CAEA,IAAM,EAAS,MAAM,QAAQ,EAAO,KAAK,EACnC,CAAC,GAAG,EAAO,KAAK,EAChB,CAAC,OAAO,EAAO,OAAS,EAAE,CAAC,EAEjC,GAAI,EAAO,WAAa,UAAW,CAC/B,IAAK,IAAM,KAAS,EAAA,WAAW,CAAM,EAAG,EAAO,OAAO,EAAK,CAAK,EAChE,QACJ,CAEA,IAAK,IAAM,KAAS,EAAQ,EAAO,OAAO,EAAK,CAAK,CACxD,CAEA,OAAO,CACX"}
|
|
@@ -13,24 +13,27 @@ var n = {
|
|
|
13
13
|
in: "__in",
|
|
14
14
|
empty: "__isnull",
|
|
15
15
|
notEmpty: "__isnull"
|
|
16
|
-
}, r = "name";
|
|
17
|
-
function i(i) {
|
|
18
|
-
let
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
}, r = /* @__PURE__ */ new Set(["name"]);
|
|
17
|
+
function i(i, a = {}) {
|
|
18
|
+
let o = a.operatorSuffix ? {
|
|
19
|
+
...n,
|
|
20
|
+
...a.operatorSuffix
|
|
21
|
+
} : n, s = a.substringColumns ? new Set(a.substringColumns) : r, c = new URLSearchParams();
|
|
22
|
+
for (let n of i) {
|
|
23
|
+
if (!e(n)) continue;
|
|
24
|
+
let r = o[n.operator], i = n.operator === "eq" && s.has(n.field) ? `${n.field}__iexact` : `${n.field}${r}`;
|
|
25
|
+
if (n.operator === "empty" || n.operator === "notEmpty") {
|
|
26
|
+
c.append(i, n.operator === "empty" ? "true" : "false");
|
|
24
27
|
continue;
|
|
25
28
|
}
|
|
26
|
-
let
|
|
27
|
-
if (
|
|
28
|
-
for (let e of t(
|
|
29
|
+
let a = Array.isArray(n.value) ? [...n.value] : [String(n.value ?? "")];
|
|
30
|
+
if (n.operator === "between") {
|
|
31
|
+
for (let e of t(a)) c.append(i, e);
|
|
29
32
|
continue;
|
|
30
33
|
}
|
|
31
|
-
for (let e of
|
|
34
|
+
for (let e of a) c.append(i, e);
|
|
32
35
|
}
|
|
33
|
-
return
|
|
36
|
+
return c;
|
|
34
37
|
}
|
|
35
38
|
//#endregion
|
|
36
39
|
export { i as filtersToQueryParams };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"filter-query.js","names":[],"sources":["../../../src/components/FilterBar/filter-query.ts"],"sourcesContent":["// Server-side half of the filter model: the same `Filter[]` the bar produces,\n// encoded the way a paginated backend expects to read it. Kept apart from\n// `filtersToSearchParams` (filter-model.ts) because the two answer different\n// questions — that one round-trips the UI state through the URL, this one talks\n// to an API and its shape is the API's, not ours.\n\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete } from \"./filter-model\";\nimport { orderRange } from \"./filter-apply\";\n\n/**\n * Operator suffix per filter operator, following the `<column>__<op>` convention\n * of `tempest-fastapi-sdk`.\n *\n * Ported from `build_filter_condition` in\n * `tempest_fastapi_sdk/db/expressions.py`, which is what `BaseRepository`\n * dict filters and `Q` both resolve through. An empty suffix means the bare\n * column name, which that function resolves to plain equality.\n *\n * `contains` maps to `icontains` (case-insensitive, and the backend escapes the\n * `LIKE` wildcards) and both emptiness operators map to `isnull`, whose value\n * carries the direction.\n */\nconst
|
|
1
|
+
{"version":3,"file":"filter-query.js","names":[],"sources":["../../../src/components/FilterBar/filter-query.ts"],"sourcesContent":["// Server-side half of the filter model: the same `Filter[]` the bar produces,\n// encoded the way a paginated backend expects to read it. Kept apart from\n// `filtersToSearchParams` (filter-model.ts) because the two answer different\n// questions — that one round-trips the UI state through the URL, this one talks\n// to an API and its shape is the API's, not ours.\n\nimport type { Filter, FilterOperator } from \"./filter-model\";\nimport { isComplete } from \"./filter-model\";\nimport { orderRange } from \"./filter-apply\";\n\n/**\n * Operator suffix per filter operator, following the `<column>__<op>` convention\n * of `tempest-fastapi-sdk`.\n *\n * Ported from `build_filter_condition` in\n * `tempest_fastapi_sdk/db/expressions.py`, which is what `BaseRepository`\n * dict filters and `Q` both resolve through. An empty suffix means the bare\n * column name, which that function resolves to plain equality.\n *\n * `contains` maps to `icontains` (case-insensitive, and the backend escapes the\n * `LIKE` wildcards) and both emptiness operators map to `isnull`, whose value\n * carries the direction.\n */\nconst DEFAULT_OPERATOR_SUFFIX: Record<FilterOperator, string> = {\n eq: \"\",\n ne: \"__ne\",\n contains: \"__icontains\",\n gt: \"__gt\",\n gte: \"__gte\",\n lt: \"__lt\",\n lte: \"__lte\",\n between: \"__between\",\n in: \"__in\",\n empty: \"__isnull\",\n notEmpty: \"__isnull\",\n};\n\n/**\n * Columns the backend treats as a substring search when they carry no operator\n * suffix.\n *\n * Ported from `build_filter_condition`, which special-cases a string `name` into\n * `ILIKE %value%`. Sending a bare `name=` for an `eq` filter would therefore ask\n * for \"contains\" while the chip says \"is\", so `eq` on such a column is emitted as\n * `name__iexact` instead.\n */\nconst DEFAULT_SUBSTRING_COLUMNS: ReadonlySet<string> = new Set([\"name\"]);\n\n/** Overrides for the backend dialect {@link filtersToQueryParams} encodes into. */\nexport interface FiltersToQueryParamsOptions {\n /**\n * Columns whose `eq` is emitted as `<column>__iexact` rather than as the bare\n * column name. Default `[\"name\"]`, which is what `build_filter_condition`\n * special-cases.\n *\n * Pass the columns **your** backend treats that way — `nome`, `titulo`,\n * `razao_social` — or `[]` when it treats none of them specially and a bare\n * `eq` should stay bare.\n */\n substringColumns?: readonly string[];\n /**\n * Operator suffixes, merged over the `tempest-fastapi-sdk` dialect, so an\n * override names only the operators that differ.\n *\n * @example\n * // A DRF-style backend\n * filtersToQueryParams(filters, {\n * substringColumns: [],\n * operatorSuffix: { contains: \"__icontains\", ne: \"__exclude\" },\n * });\n */\n operatorSuffix?: Partial<Record<FilterOperator, string>>;\n}\n\n/**\n * Encode filters as query params for a paginated backend.\n *\n * The counterpart of {@link applyFilters}: same filter set, evaluated by the\n * database instead of by the browser, which is the only option once the list is\n * paginated on the server and the page in memory is not the whole result.\n *\n * The encoding is the `<column>__<op>` convention `tempest-fastapi-sdk` already\n * reads (`BaseRepository._apply_filters` → `build_filter_condition`):\n *\n * | Operator | Param |\n * | --- | --- |\n * | `eq` | `field` (or `field__iexact` for the `name` column) |\n * | `ne` | `field__ne` |\n * | `contains` | `field__icontains` |\n * | `gt` `gte` `lt` `lte` | `field__gt` … `field__lte` |\n * | `between` | `field__between` twice, low value first |\n * | `in` | `field__in` once per value |\n * | `empty` / `notEmpty` | `field__isnull=true` / `=false` |\n *\n * Returns `URLSearchParams` rather than a plain object because `between` carries\n * a pair and `in` carries a list: an object would keep only the last value of\n * each, silently narrowing the filter. Repeated params are also how FastAPI\n * receives a `list[str]` declared with `Query`.\n *\n * Two things the backend has to hold up its end of, or the filter fails quietly:\n *\n * - **Every key must be declared.** `BasePaginationFilterSchema.get_conditions()`\n * only forwards fields the subclass declares, so a `status__ne` the schema\n * never mentions is dropped by FastAPI before the repository sees it — no\n * error, no filtering.\n * - **`isnull` matches `NULL` only.** A column that stores `\"\"` for \"no value\"\n * will not answer an `empty` filter, while {@link applyFilters} treats blank\n * text as empty.\n *\n * The defaults are that dialect, not a universal truth. A backend that names its\n * substring column something other than `name`, or that spells its operators\n * differently, passes `options` — the alternative was an encoder whose special\n * cases were a wall for anyone not on the Tempest stack.\n *\n * @example\n * const params = filtersToQueryParams(filters);\n * params.set(\"page\", String(page));\n * const data = await api.get(`/orders?${params}`);\n *\n * @example\n * // A backend whose searchable column is `razao_social` and that spells `ne`\n * // the Django way.\n * const params = filtersToQueryParams(filters, {\n * substringColumns: [\"razao_social\"],\n * operatorSuffix: { ne: \"__exclude\" },\n * });\n *\n * @param filters - Applied filters; incomplete ones are ignored.\n * @param options - Dialect overrides. Defaults to the `tempest-fastapi-sdk` one.\n * @returns Params ready to append to a request URL.\n */\nexport function filtersToQueryParams(\n filters: readonly Filter[],\n options: FiltersToQueryParamsOptions = {},\n): URLSearchParams {\n const suffixes = options.operatorSuffix\n ? { ...DEFAULT_OPERATOR_SUFFIX, ...options.operatorSuffix }\n : DEFAULT_OPERATOR_SUFFIX;\n const substringColumns = options.substringColumns\n ? new Set(options.substringColumns)\n : DEFAULT_SUBSTRING_COLUMNS;\n\n const params = new URLSearchParams();\n\n for (const filter of filters) {\n if (!isComplete(filter)) continue;\n\n const suffix = suffixes[filter.operator];\n const key =\n filter.operator === \"eq\" && substringColumns.has(filter.field)\n ? `${filter.field}__iexact`\n : `${filter.field}${suffix}`;\n\n if (filter.operator === \"empty\" || filter.operator === \"notEmpty\") {\n params.append(key, filter.operator === \"empty\" ? \"true\" : \"false\");\n continue;\n }\n\n const values = Array.isArray(filter.value)\n ? [...filter.value]\n : [String(filter.value ?? \"\")];\n\n if (filter.operator === \"between\") {\n for (const value of orderRange(values)) params.append(key, value);\n continue;\n }\n\n for (const value of values) params.append(key, value);\n }\n\n return params;\n}\n"],"mappings":";;;AAuBA,IAAM,IAA0D;CAC5D,IAAI;CACJ,IAAI;CACJ,UAAU;CACV,IAAI;CACJ,KAAK;CACL,IAAI;CACJ,KAAK;CACL,SAAS;CACT,IAAI;CACJ,OAAO;CACP,UAAU;AACd,GAWM,oBAAiD,IAAI,IAAI,CAAC,MAAM,CAAC;AAqFvE,SAAgB,EACZ,GACA,IAAuC,CAAC,GACzB;CACf,IAAM,IAAW,EAAQ,iBACnB;EAAE,GAAG;EAAyB,GAAG,EAAQ;CAAe,IACxD,GACA,IAAmB,EAAQ,mBAC3B,IAAI,IAAI,EAAQ,gBAAgB,IAChC,GAEA,IAAS,IAAI,gBAAgB;CAEnC,KAAK,IAAM,KAAU,GAAS;EAC1B,IAAI,CAAC,EAAW,CAAM,GAAG;EAEzB,IAAM,IAAS,EAAS,EAAO,WACzB,IACF,EAAO,aAAa,QAAQ,EAAiB,IAAI,EAAO,KAAK,IACvD,GAAG,EAAO,MAAM,YAChB,GAAG,EAAO,QAAQ;EAE5B,IAAI,EAAO,aAAa,WAAW,EAAO,aAAa,YAAY;GAC/D,EAAO,OAAO,GAAK,EAAO,aAAa,UAAU,SAAS,OAAO;GACjE;EACJ;EAEA,IAAM,IAAS,MAAM,QAAQ,EAAO,KAAK,IACnC,CAAC,GAAG,EAAO,KAAK,IAChB,CAAC,OAAO,EAAO,SAAS,EAAE,CAAC;EAEjC,IAAI,EAAO,aAAa,WAAW;GAC/B,KAAK,IAAM,KAAS,EAAW,CAAM,GAAG,EAAO,OAAO,GAAK,CAAK;GAChE;EACJ;EAEA,KAAK,IAAM,KAAS,GAAQ,EAAO,OAAO,GAAK,CAAK;CACxD;CAEA,OAAO;AACX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./create-position-tracker.cjs");let
|
|
1
|
+
const e=require("../hooks/use-latest-ref.cjs"),t=require("./create-position-tracker.cjs");let n=require("react");function r(r={}){let{autoStart:i=!1,onError:a,...o}=r,[s,c]=(0,n.useState)([]),[l,u]=(0,n.useState)(0),[d,f]=(0,n.useState)(`idle`),p=(0,n.useRef)(null),m=e.useLatestRef(a);(0,n.useEffect)(()=>{let e=t.createPositionTracker({...o,onUpdate:t=>{c([...t]),u(e.distanceKm)},onStatusChange:f,onError:e=>m.current?.(e)});return p.current=e,i&&e.start(),()=>{e.stop(),p.current=null}},[]);let h=(0,n.useCallback)(()=>p.current?.start(),[]),g=(0,n.useCallback)(()=>p.current?.stop(),[]),_=(0,n.useCallback)(()=>{p.current?.clear(),u(0)},[]);return{points:s,lastPoint:s.length>0?s[s.length-1]:null,distanceKm:l,status:d,isTracking:d===`tracking`,start:h,stop:g,clear:_}}exports.usePositionTracker=r;
|
|
2
2
|
//# sourceMappingURL=use-position-tracker.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-position-tracker.cjs","names":[],"sources":["../../src/geo/use-position-tracker.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n createPositionTracker,\n type CreatePositionTrackerOptions,\n type PositionTracker,\n type TrackerStatus,\n} from \"./create-position-tracker\";\nimport type { TrackPoint } from \"./types\";\n\nexport interface UsePositionTrackerOptions extends Omit<\n CreatePositionTrackerOptions,\n \"onUpdate\" | \"onStatusChange\"\n> {\n /** Start tracking automatically on mount. Default: `false`. */\n autoStart?: boolean;\n}\n\nexport interface UsePositionTrackerResult {\n /** Recorded trajectory (newest last). */\n points: readonly TrackPoint[];\n /** Most recent point, or `null` before the first fix. */\n lastPoint: TrackPoint | null;\n /** Total distance of the trajectory in kilometers. */\n distanceKm: number;\n /** Current tracker status. */\n status: TrackerStatus;\n /** True while `status === \"tracking\"`. */\n isTracking: boolean;\n /** Begin watching position. */\n start: () => void;\n /** Stop watching, keeping the trajectory. */\n stop: () => void;\n /** Stop and discard the trajectory. */\n clear: () => void;\n}\n\n/**\n * React hook wrapping {@link createPositionTracker}. Records a live GPS\n * trajectory tied to the component lifecycle — the watch is torn down on\n * unmount. Fully browser-side; no external service.\n *\n * @example\n * const { points, distanceKm, isTracking, start, stop } = usePositionTracker({\n * minDistanceKm: 0.01,\n * });\n * return (\n * <>\n * <button onClick={isTracking ? stop : start}>{isTracking ? \"Parar\" : \"Rastrear\"}</button>\n * <TrajectoryMap points={points} />\n * <span>{distanceKm.toFixed(2)} km</span>\n * </>\n * );\n */\nexport function usePositionTracker(\n options: UsePositionTrackerOptions = {},\n): UsePositionTrackerResult {\n const { autoStart = false, onError, ...trackerOptions } = options;\n\n const [points, setPoints] = useState<readonly TrackPoint[]>([]);\n const [distanceKm, setDistanceKm] = useState<number>(0);\n const [status, setStatus] = useState<TrackerStatus>(\"idle\");\n\n const trackerRef = useRef<PositionTracker | null>(null);\n const onErrorRef =
|
|
1
|
+
{"version":3,"file":"use-position-tracker.cjs","names":[],"sources":["../../src/geo/use-position-tracker.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createPositionTracker,\n type CreatePositionTrackerOptions,\n type PositionTracker,\n type TrackerStatus,\n} from \"./create-position-tracker\";\nimport type { TrackPoint } from \"./types\";\n\nexport interface UsePositionTrackerOptions extends Omit<\n CreatePositionTrackerOptions,\n \"onUpdate\" | \"onStatusChange\"\n> {\n /** Start tracking automatically on mount. Default: `false`. */\n autoStart?: boolean;\n}\n\nexport interface UsePositionTrackerResult {\n /** Recorded trajectory (newest last). */\n points: readonly TrackPoint[];\n /** Most recent point, or `null` before the first fix. */\n lastPoint: TrackPoint | null;\n /** Total distance of the trajectory in kilometers. */\n distanceKm: number;\n /** Current tracker status. */\n status: TrackerStatus;\n /** True while `status === \"tracking\"`. */\n isTracking: boolean;\n /** Begin watching position. */\n start: () => void;\n /** Stop watching, keeping the trajectory. */\n stop: () => void;\n /** Stop and discard the trajectory. */\n clear: () => void;\n}\n\n/**\n * React hook wrapping {@link createPositionTracker}. Records a live GPS\n * trajectory tied to the component lifecycle — the watch is torn down on\n * unmount. Fully browser-side; no external service.\n *\n * @example\n * const { points, distanceKm, isTracking, start, stop } = usePositionTracker({\n * minDistanceKm: 0.01,\n * });\n * return (\n * <>\n * <button onClick={isTracking ? stop : start}>{isTracking ? \"Parar\" : \"Rastrear\"}</button>\n * <TrajectoryMap points={points} />\n * <span>{distanceKm.toFixed(2)} km</span>\n * </>\n * );\n */\nexport function usePositionTracker(\n options: UsePositionTrackerOptions = {},\n): UsePositionTrackerResult {\n const { autoStart = false, onError, ...trackerOptions } = options;\n\n const [points, setPoints] = useState<readonly TrackPoint[]>([]);\n const [distanceKm, setDistanceKm] = useState<number>(0);\n const [status, setStatus] = useState<TrackerStatus>(\"idle\");\n\n const trackerRef = useRef<PositionTracker | null>(null);\n const onErrorRef = useLatestRef(onError);\n\n useEffect(() => {\n const tracker = createPositionTracker({\n ...trackerOptions,\n onUpdate: (next) => {\n setPoints([...next]);\n setDistanceKm(tracker.distanceKm);\n },\n onStatusChange: setStatus,\n onError: (error) => onErrorRef.current?.(error),\n });\n trackerRef.current = tracker;\n if (autoStart) tracker.start();\n\n return () => {\n tracker.stop();\n trackerRef.current = null;\n };\n // Tracker options are read once at creation; changing them mid-track\n // would drop the recorded trajectory, so they are intentionally omitted.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const start = useCallback((): void => trackerRef.current?.start(), []);\n const stop = useCallback((): void => trackerRef.current?.stop(), []);\n const clear = useCallback((): void => {\n trackerRef.current?.clear();\n setDistanceKm(0);\n }, []);\n\n return {\n points,\n lastPoint: points.length > 0 ? points[points.length - 1] : null,\n distanceKm,\n status,\n isTracking: status === \"tracking\",\n start,\n stop,\n clear,\n };\n}\n"],"mappings":"iHAsDA,SAAgB,EACZ,EAAqC,CAAC,EACd,CACxB,GAAM,CAAE,YAAY,GAAO,UAAS,GAAG,GAAmB,EAEpD,CAAC,EAAQ,IAAA,EAAa,EAAA,SAAA,CAAgC,CAAC,CAAC,EACxD,CAAC,EAAY,IAAA,EAAiB,EAAA,SAAA,CAAiB,CAAC,EAChD,CAAC,EAAQ,IAAA,EAAa,EAAA,SAAA,CAAwB,MAAM,EAEpD,GAAA,EAAa,EAAA,OAAA,CAA+B,IAAI,EAChD,EAAa,EAAA,aAAa,CAAO,GAEvC,EAAA,EAAA,UAAA,KAAgB,CACZ,IAAM,EAAU,EAAA,sBAAsB,CAClC,GAAG,EACH,SAAW,GAAS,CAChB,EAAU,CAAC,GAAG,CAAI,CAAC,EACnB,EAAc,EAAQ,UAAU,CACpC,EACA,eAAgB,EAChB,QAAU,GAAU,EAAW,UAAU,CAAK,CAClD,CAAC,EAID,MAHA,GAAW,QAAU,EACjB,GAAW,EAAQ,MAAM,MAEhB,CACT,EAAQ,KAAK,EACb,EAAW,QAAU,IACzB,CAIJ,EAAG,CAAC,CAAC,EAEL,IAAM,GAAA,EAAQ,EAAA,YAAA,KAAwB,EAAW,SAAS,MAAM,EAAG,CAAC,CAAC,EAC/D,GAAA,EAAO,EAAA,YAAA,KAAwB,EAAW,SAAS,KAAK,EAAG,CAAC,CAAC,EAC7D,GAAA,EAAQ,EAAA,YAAA,KAAwB,CAClC,EAAW,SAAS,MAAM,EAC1B,EAAc,CAAC,CACnB,EAAG,CAAC,CAAC,EAEL,MAAO,CACH,SACA,UAAW,EAAO,OAAS,EAAI,EAAO,EAAO,OAAS,GAAK,KAC3D,aACA,SACA,WAAY,IAAW,WACvB,QACA,OACA,OACJ,CACJ"}
|
|
@@ -1,38 +1,37 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { useLatestRef as e } from "../hooks/use-latest-ref.js";
|
|
2
|
+
import { createPositionTracker as t } from "./create-position-tracker.js";
|
|
3
|
+
import { useCallback as n, useEffect as r, useRef as i, useState as a } from "react";
|
|
3
4
|
//#region src/geo/use-position-tracker.ts
|
|
4
|
-
function
|
|
5
|
-
let { autoStart:
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
onUpdate: (e) => {
|
|
12
|
-
u([...e]), f(t.distanceKm);
|
|
5
|
+
function o(o = {}) {
|
|
6
|
+
let { autoStart: s = !1, onError: c, ...l } = o, [u, d] = a([]), [f, p] = a(0), [m, h] = a("idle"), g = i(null), _ = e(c);
|
|
7
|
+
r(() => {
|
|
8
|
+
let e = t({
|
|
9
|
+
...l,
|
|
10
|
+
onUpdate: (t) => {
|
|
11
|
+
d([...t]), p(e.distanceKm);
|
|
13
12
|
},
|
|
14
|
-
onStatusChange:
|
|
15
|
-
onError: (e) =>
|
|
13
|
+
onStatusChange: h,
|
|
14
|
+
onError: (e) => _.current?.(e)
|
|
16
15
|
});
|
|
17
|
-
return
|
|
18
|
-
|
|
16
|
+
return g.current = e, s && e.start(), () => {
|
|
17
|
+
e.stop(), g.current = null;
|
|
19
18
|
};
|
|
20
19
|
}, []);
|
|
21
|
-
let
|
|
22
|
-
|
|
20
|
+
let v = n(() => g.current?.start(), []), y = n(() => g.current?.stop(), []), b = n(() => {
|
|
21
|
+
g.current?.clear(), p(0);
|
|
23
22
|
}, []);
|
|
24
23
|
return {
|
|
25
|
-
points:
|
|
26
|
-
lastPoint:
|
|
27
|
-
distanceKm:
|
|
28
|
-
status:
|
|
29
|
-
isTracking:
|
|
30
|
-
start:
|
|
31
|
-
stop:
|
|
32
|
-
clear:
|
|
24
|
+
points: u,
|
|
25
|
+
lastPoint: u.length > 0 ? u[u.length - 1] : null,
|
|
26
|
+
distanceKm: f,
|
|
27
|
+
status: m,
|
|
28
|
+
isTracking: m === "tracking",
|
|
29
|
+
start: v,
|
|
30
|
+
stop: y,
|
|
31
|
+
clear: b
|
|
33
32
|
};
|
|
34
33
|
}
|
|
35
34
|
//#endregion
|
|
36
|
-
export {
|
|
35
|
+
export { o as usePositionTracker };
|
|
37
36
|
|
|
38
37
|
//# sourceMappingURL=use-position-tracker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-position-tracker.js","names":[],"sources":["../../src/geo/use-position-tracker.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n createPositionTracker,\n type CreatePositionTrackerOptions,\n type PositionTracker,\n type TrackerStatus,\n} from \"./create-position-tracker\";\nimport type { TrackPoint } from \"./types\";\n\nexport interface UsePositionTrackerOptions extends Omit<\n CreatePositionTrackerOptions,\n \"onUpdate\" | \"onStatusChange\"\n> {\n /** Start tracking automatically on mount. Default: `false`. */\n autoStart?: boolean;\n}\n\nexport interface UsePositionTrackerResult {\n /** Recorded trajectory (newest last). */\n points: readonly TrackPoint[];\n /** Most recent point, or `null` before the first fix. */\n lastPoint: TrackPoint | null;\n /** Total distance of the trajectory in kilometers. */\n distanceKm: number;\n /** Current tracker status. */\n status: TrackerStatus;\n /** True while `status === \"tracking\"`. */\n isTracking: boolean;\n /** Begin watching position. */\n start: () => void;\n /** Stop watching, keeping the trajectory. */\n stop: () => void;\n /** Stop and discard the trajectory. */\n clear: () => void;\n}\n\n/**\n * React hook wrapping {@link createPositionTracker}. Records a live GPS\n * trajectory tied to the component lifecycle — the watch is torn down on\n * unmount. Fully browser-side; no external service.\n *\n * @example\n * const { points, distanceKm, isTracking, start, stop } = usePositionTracker({\n * minDistanceKm: 0.01,\n * });\n * return (\n * <>\n * <button onClick={isTracking ? stop : start}>{isTracking ? \"Parar\" : \"Rastrear\"}</button>\n * <TrajectoryMap points={points} />\n * <span>{distanceKm.toFixed(2)} km</span>\n * </>\n * );\n */\nexport function usePositionTracker(\n options: UsePositionTrackerOptions = {},\n): UsePositionTrackerResult {\n const { autoStart = false, onError, ...trackerOptions } = options;\n\n const [points, setPoints] = useState<readonly TrackPoint[]>([]);\n const [distanceKm, setDistanceKm] = useState<number>(0);\n const [status, setStatus] = useState<TrackerStatus>(\"idle\");\n\n const trackerRef = useRef<PositionTracker | null>(null);\n const onErrorRef =
|
|
1
|
+
{"version":3,"file":"use-position-tracker.js","names":[],"sources":["../../src/geo/use-position-tracker.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createPositionTracker,\n type CreatePositionTrackerOptions,\n type PositionTracker,\n type TrackerStatus,\n} from \"./create-position-tracker\";\nimport type { TrackPoint } from \"./types\";\n\nexport interface UsePositionTrackerOptions extends Omit<\n CreatePositionTrackerOptions,\n \"onUpdate\" | \"onStatusChange\"\n> {\n /** Start tracking automatically on mount. Default: `false`. */\n autoStart?: boolean;\n}\n\nexport interface UsePositionTrackerResult {\n /** Recorded trajectory (newest last). */\n points: readonly TrackPoint[];\n /** Most recent point, or `null` before the first fix. */\n lastPoint: TrackPoint | null;\n /** Total distance of the trajectory in kilometers. */\n distanceKm: number;\n /** Current tracker status. */\n status: TrackerStatus;\n /** True while `status === \"tracking\"`. */\n isTracking: boolean;\n /** Begin watching position. */\n start: () => void;\n /** Stop watching, keeping the trajectory. */\n stop: () => void;\n /** Stop and discard the trajectory. */\n clear: () => void;\n}\n\n/**\n * React hook wrapping {@link createPositionTracker}. Records a live GPS\n * trajectory tied to the component lifecycle — the watch is torn down on\n * unmount. Fully browser-side; no external service.\n *\n * @example\n * const { points, distanceKm, isTracking, start, stop } = usePositionTracker({\n * minDistanceKm: 0.01,\n * });\n * return (\n * <>\n * <button onClick={isTracking ? stop : start}>{isTracking ? \"Parar\" : \"Rastrear\"}</button>\n * <TrajectoryMap points={points} />\n * <span>{distanceKm.toFixed(2)} km</span>\n * </>\n * );\n */\nexport function usePositionTracker(\n options: UsePositionTrackerOptions = {},\n): UsePositionTrackerResult {\n const { autoStart = false, onError, ...trackerOptions } = options;\n\n const [points, setPoints] = useState<readonly TrackPoint[]>([]);\n const [distanceKm, setDistanceKm] = useState<number>(0);\n const [status, setStatus] = useState<TrackerStatus>(\"idle\");\n\n const trackerRef = useRef<PositionTracker | null>(null);\n const onErrorRef = useLatestRef(onError);\n\n useEffect(() => {\n const tracker = createPositionTracker({\n ...trackerOptions,\n onUpdate: (next) => {\n setPoints([...next]);\n setDistanceKm(tracker.distanceKm);\n },\n onStatusChange: setStatus,\n onError: (error) => onErrorRef.current?.(error),\n });\n trackerRef.current = tracker;\n if (autoStart) tracker.start();\n\n return () => {\n tracker.stop();\n trackerRef.current = null;\n };\n // Tracker options are read once at creation; changing them mid-track\n // would drop the recorded trajectory, so they are intentionally omitted.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const start = useCallback((): void => trackerRef.current?.start(), []);\n const stop = useCallback((): void => trackerRef.current?.stop(), []);\n const clear = useCallback((): void => {\n trackerRef.current?.clear();\n setDistanceKm(0);\n }, []);\n\n return {\n points,\n lastPoint: points.length > 0 ? points[points.length - 1] : null,\n distanceKm,\n status,\n isTracking: status === \"tracking\",\n start,\n stop,\n clear,\n };\n}\n"],"mappings":";;;;AAsDA,SAAgB,EACZ,IAAqC,CAAC,GACd;CACxB,IAAM,EAAE,eAAY,IAAO,YAAS,GAAG,MAAmB,GAEpD,CAAC,GAAQ,KAAa,EAAgC,CAAC,CAAC,GACxD,CAAC,GAAY,KAAiB,EAAiB,CAAC,GAChD,CAAC,GAAQ,KAAa,EAAwB,MAAM,GAEpD,IAAa,EAA+B,IAAI,GAChD,IAAa,EAAa,CAAO;CAEvC,QAAgB;EACZ,IAAM,IAAU,EAAsB;GAClC,GAAG;GACH,WAAW,MAAS;IAEhB,AADA,EAAU,CAAC,GAAG,CAAI,CAAC,GACnB,EAAc,EAAQ,UAAU;GACpC;GACA,gBAAgB;GAChB,UAAU,MAAU,EAAW,UAAU,CAAK;EAClD,CAAC;EAID,OAHA,EAAW,UAAU,GACjB,KAAW,EAAQ,MAAM,SAEhB;GAET,AADA,EAAQ,KAAK,GACb,EAAW,UAAU;EACzB;CAIJ,GAAG,CAAC,CAAC;CAEL,IAAM,IAAQ,QAAwB,EAAW,SAAS,MAAM,GAAG,CAAC,CAAC,GAC/D,IAAO,QAAwB,EAAW,SAAS,KAAK,GAAG,CAAC,CAAC,GAC7D,IAAQ,QAAwB;EAElC,AADA,EAAW,SAAS,MAAM,GAC1B,EAAc,CAAC;CACnB,GAAG,CAAC,CAAC;CAEL,OAAO;EACH;EACA,WAAW,EAAO,SAAS,IAAI,EAAO,EAAO,SAAS,KAAK;EAC3D;EACA;EACA,YAAY,MAAW;EACvB;EACA;EACA;CACJ;AACJ"}
|
package/dist/hooks/use-async.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
const e=require("./use-latest-ref.cjs");let t=require("react");function n(n,r=[],i={}){let{immediate:a=!1}=i,[o,s]=(0,t.useState)({status:`idle`,data:void 0,error:void 0}),c=e.useLatestRef(n),l=(0,t.useRef)(0),u=(0,t.useRef)(!0);(0,t.useEffect)(()=>(u.current=!0,()=>{u.current=!1}),[]);let d=(0,t.useCallback)(async()=>{let e=++l.current;s(e=>({...e,status:`pending`,error:void 0}));try{let t=await c.current();return u.current&&l.current===e&&s({status:`success`,data:t,error:void 0}),t}catch(t){throw u.current&&l.current===e&&s({status:`error`,data:void 0,error:t}),t}},[c]),f=(0,t.useCallback)(()=>{l.current++,s({status:`idle`,data:void 0,error:void 0})},[]);return(0,t.useEffect)(()=>{a&&d().catch(()=>{})},[a,...r]),{status:o.status,data:o.data,error:o.error,isPending:o.status===`pending`,isSuccess:o.status===`success`,isError:o.status===`error`,run:d,reset:f}}exports.useAsync=n;
|
|
2
2
|
//# sourceMappingURL=use-async.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-async.cjs","names":[],"sources":["../../src/hooks/use-async.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport type AsyncStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport interface UseAsyncResult<T> {\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n isPending: boolean;\n isSuccess: boolean;\n isError: boolean;\n /** Trigger the async function. Resolves with the new data or rejects. */\n run: () => Promise<T>;\n /** Reset state back to idle. */\n reset: () => void;\n}\n\n/**\n * Run an async function and track its `idle/pending/success/error` state.\n *\n * - Discards results from stale runs (race-condition safe).\n * - `immediate` (default `false`) triggers the function on mount and when\n * `deps` change. With `false`, call `run()` manually.\n * - Returns a stable object so callers can destructure or pass around safely.\n *\n * For server data with caching, prefer React Query — `useAsync` is the\n * minimal one-shot primitive without dependencies.\n */\nexport function useAsync<T>(\n asyncFn: () => Promise<T>,\n deps: ReadonlyArray<unknown> = [],\n options: { immediate?: boolean } = {},\n): UseAsyncResult<T> {\n const { immediate = false } = options;\n const [state, setState] = useState<{\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n }>({ status: \"idle\", data: undefined, error: undefined });\n\n const fnRef =
|
|
1
|
+
{"version":3,"file":"use-async.cjs","names":[],"sources":["../../src/hooks/use-async.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"./use-latest-ref\";\n\nexport type AsyncStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport interface UseAsyncResult<T> {\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n isPending: boolean;\n isSuccess: boolean;\n isError: boolean;\n /** Trigger the async function. Resolves with the new data or rejects. */\n run: () => Promise<T>;\n /** Reset state back to idle. */\n reset: () => void;\n}\n\n/**\n * Run an async function and track its `idle/pending/success/error` state.\n *\n * - Discards results from stale runs (race-condition safe).\n * - `immediate` (default `false`) triggers the function on mount and when\n * `deps` change. With `false`, call `run()` manually.\n * - Returns a stable object so callers can destructure or pass around safely.\n *\n * For server data with caching, prefer React Query — `useAsync` is the\n * minimal one-shot primitive without dependencies.\n */\nexport function useAsync<T>(\n asyncFn: () => Promise<T>,\n deps: ReadonlyArray<unknown> = [],\n options: { immediate?: boolean } = {},\n): UseAsyncResult<T> {\n const { immediate = false } = options;\n const [state, setState] = useState<{\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n }>({ status: \"idle\", data: undefined, error: undefined });\n\n const fnRef = useLatestRef(asyncFn);\n const callIdRef = useRef<number>(0);\n const mountedRef = useRef<boolean>(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n const run = useCallback(async (): Promise<T> => {\n const callId = ++callIdRef.current;\n setState((current) => ({ ...current, status: \"pending\", error: undefined }));\n try {\n const data = await fnRef.current();\n if (mountedRef.current && callIdRef.current === callId) {\n setState({ status: \"success\", data, error: undefined });\n }\n return data;\n } catch (error) {\n if (mountedRef.current && callIdRef.current === callId) {\n setState({ status: \"error\", data: undefined, error });\n }\n throw error;\n }\n }, [fnRef]);\n\n const reset = useCallback((): void => {\n callIdRef.current++;\n setState({ status: \"idle\", data: undefined, error: undefined });\n }, []);\n\n useEffect(() => {\n if (!immediate) return;\n run().catch(() => {\n /* error already captured in state */\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [immediate, ...deps]);\n\n return {\n status: state.status,\n data: state.data,\n error: state.error,\n isPending: state.status === \"pending\",\n isSuccess: state.status === \"success\",\n isError: state.status === \"error\",\n run,\n reset,\n };\n}\n"],"mappings":"+DA6BA,SAAgB,EACZ,EACA,EAA+B,CAAC,EAChC,EAAmC,CAAC,EACnB,CACjB,GAAM,CAAE,YAAY,IAAU,EACxB,CAAC,EAAO,IAAA,EAAY,EAAA,SAAA,CAIvB,CAAE,OAAQ,OAAQ,KAAM,IAAA,GAAW,MAAO,IAAA,EAAU,CAAC,EAElD,EAAQ,EAAA,aAAa,CAAO,EAC5B,GAAA,EAAY,EAAA,OAAA,CAAe,CAAC,EAC5B,GAAA,EAAa,EAAA,OAAA,CAAgB,EAAI,GAEvC,EAAA,EAAA,UAAA,MACI,EAAW,QAAU,OACR,CACT,EAAW,QAAU,EACzB,GACD,CAAC,CAAC,EAEL,IAAM,GAAA,EAAM,EAAA,YAAA,CAAY,SAAwB,CAC5C,IAAM,EAAS,EAAE,EAAU,QAC3B,EAAU,IAAa,CAAE,GAAG,EAAS,OAAQ,UAAW,MAAO,IAAA,EAAU,EAAE,EAC3E,GAAI,CACA,IAAM,EAAO,MAAM,EAAM,QAAQ,EAIjC,OAHI,EAAW,SAAW,EAAU,UAAY,GAC5C,EAAS,CAAE,OAAQ,UAAW,OAAM,MAAO,IAAA,EAAU,CAAC,EAEnD,CACX,OAAS,EAAO,CAIZ,MAHI,EAAW,SAAW,EAAU,UAAY,GAC5C,EAAS,CAAE,OAAQ,QAAS,KAAM,IAAA,GAAW,OAAM,CAAC,EAElD,CACV,CACJ,EAAG,CAAC,CAAK,CAAC,EAEJ,GAAA,EAAQ,EAAA,YAAA,KAAwB,CAClC,EAAU,UACV,EAAS,CAAE,OAAQ,OAAQ,KAAM,IAAA,GAAW,MAAO,IAAA,EAAU,CAAC,CAClE,EAAG,CAAC,CAAC,EAUL,OARA,EAAA,EAAA,UAAA,KAAgB,CACP,GACL,EAAI,CAAC,CAAC,UAAY,CAElB,CAAC,CAEL,EAAG,CAAC,EAAW,GAAG,CAAI,CAAC,EAEhB,CACH,OAAQ,EAAM,OACd,KAAM,EAAM,KACZ,MAAO,EAAM,MACb,UAAW,EAAM,SAAW,UAC5B,UAAW,EAAM,SAAW,UAC5B,QAAS,EAAM,SAAW,QAC1B,MACA,OACJ,CACJ"}
|
package/dist/hooks/use-async.js
CHANGED
|
@@ -1,60 +1,57 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { useLatestRef as e } from "./use-latest-ref.js";
|
|
2
|
+
import { useCallback as t, useEffect as n, useRef as r, useState as i } from "react";
|
|
2
3
|
//#region src/hooks/use-async.ts
|
|
3
|
-
function
|
|
4
|
-
let { immediate:
|
|
4
|
+
function a(a, o = [], s = {}) {
|
|
5
|
+
let { immediate: c = !1 } = s, [l, u] = i({
|
|
5
6
|
status: "idle",
|
|
6
7
|
data: void 0,
|
|
7
8
|
error: void 0
|
|
8
|
-
}),
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}, [i]);
|
|
12
|
-
let d = n(0), f = n(!0);
|
|
13
|
-
t(() => (f.current = !0, () => {
|
|
14
|
-
f.current = !1;
|
|
9
|
+
}), d = e(a), f = r(0), p = r(!0);
|
|
10
|
+
n(() => (p.current = !0, () => {
|
|
11
|
+
p.current = !1;
|
|
15
12
|
}), []);
|
|
16
|
-
let
|
|
17
|
-
let e = ++
|
|
18
|
-
|
|
13
|
+
let m = t(async () => {
|
|
14
|
+
let e = ++f.current;
|
|
15
|
+
u((e) => ({
|
|
19
16
|
...e,
|
|
20
17
|
status: "pending",
|
|
21
18
|
error: void 0
|
|
22
19
|
}));
|
|
23
20
|
try {
|
|
24
|
-
let t = await
|
|
25
|
-
return
|
|
21
|
+
let t = await d.current();
|
|
22
|
+
return p.current && f.current === e && u({
|
|
26
23
|
status: "success",
|
|
27
24
|
data: t,
|
|
28
25
|
error: void 0
|
|
29
26
|
}), t;
|
|
30
27
|
} catch (t) {
|
|
31
|
-
throw
|
|
28
|
+
throw p.current && f.current === e && u({
|
|
32
29
|
status: "error",
|
|
33
30
|
data: void 0,
|
|
34
31
|
error: t
|
|
35
32
|
}), t;
|
|
36
33
|
}
|
|
37
|
-
}, []),
|
|
38
|
-
|
|
34
|
+
}, [d]), h = t(() => {
|
|
35
|
+
f.current++, u({
|
|
39
36
|
status: "idle",
|
|
40
37
|
data: void 0,
|
|
41
38
|
error: void 0
|
|
42
39
|
});
|
|
43
40
|
}, []);
|
|
44
|
-
return
|
|
45
|
-
|
|
46
|
-
}, [
|
|
47
|
-
status:
|
|
48
|
-
data:
|
|
49
|
-
error:
|
|
50
|
-
isPending:
|
|
51
|
-
isSuccess:
|
|
52
|
-
isError:
|
|
53
|
-
run:
|
|
54
|
-
reset:
|
|
41
|
+
return n(() => {
|
|
42
|
+
c && m().catch(() => {});
|
|
43
|
+
}, [c, ...o]), {
|
|
44
|
+
status: l.status,
|
|
45
|
+
data: l.data,
|
|
46
|
+
error: l.error,
|
|
47
|
+
isPending: l.status === "pending",
|
|
48
|
+
isSuccess: l.status === "success",
|
|
49
|
+
isError: l.status === "error",
|
|
50
|
+
run: m,
|
|
51
|
+
reset: h
|
|
55
52
|
};
|
|
56
53
|
}
|
|
57
54
|
//#endregion
|
|
58
|
-
export {
|
|
55
|
+
export { a as useAsync };
|
|
59
56
|
|
|
60
57
|
//# sourceMappingURL=use-async.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-async.js","names":[],"sources":["../../src/hooks/use-async.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport type AsyncStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport interface UseAsyncResult<T> {\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n isPending: boolean;\n isSuccess: boolean;\n isError: boolean;\n /** Trigger the async function. Resolves with the new data or rejects. */\n run: () => Promise<T>;\n /** Reset state back to idle. */\n reset: () => void;\n}\n\n/**\n * Run an async function and track its `idle/pending/success/error` state.\n *\n * - Discards results from stale runs (race-condition safe).\n * - `immediate` (default `false`) triggers the function on mount and when\n * `deps` change. With `false`, call `run()` manually.\n * - Returns a stable object so callers can destructure or pass around safely.\n *\n * For server data with caching, prefer React Query — `useAsync` is the\n * minimal one-shot primitive without dependencies.\n */\nexport function useAsync<T>(\n asyncFn: () => Promise<T>,\n deps: ReadonlyArray<unknown> = [],\n options: { immediate?: boolean } = {},\n): UseAsyncResult<T> {\n const { immediate = false } = options;\n const [state, setState] = useState<{\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n }>({ status: \"idle\", data: undefined, error: undefined });\n\n const fnRef =
|
|
1
|
+
{"version":3,"file":"use-async.js","names":[],"sources":["../../src/hooks/use-async.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"./use-latest-ref\";\n\nexport type AsyncStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport interface UseAsyncResult<T> {\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n isPending: boolean;\n isSuccess: boolean;\n isError: boolean;\n /** Trigger the async function. Resolves with the new data or rejects. */\n run: () => Promise<T>;\n /** Reset state back to idle. */\n reset: () => void;\n}\n\n/**\n * Run an async function and track its `idle/pending/success/error` state.\n *\n * - Discards results from stale runs (race-condition safe).\n * - `immediate` (default `false`) triggers the function on mount and when\n * `deps` change. With `false`, call `run()` manually.\n * - Returns a stable object so callers can destructure or pass around safely.\n *\n * For server data with caching, prefer React Query — `useAsync` is the\n * minimal one-shot primitive without dependencies.\n */\nexport function useAsync<T>(\n asyncFn: () => Promise<T>,\n deps: ReadonlyArray<unknown> = [],\n options: { immediate?: boolean } = {},\n): UseAsyncResult<T> {\n const { immediate = false } = options;\n const [state, setState] = useState<{\n status: AsyncStatus;\n data: T | undefined;\n error: unknown;\n }>({ status: \"idle\", data: undefined, error: undefined });\n\n const fnRef = useLatestRef(asyncFn);\n const callIdRef = useRef<number>(0);\n const mountedRef = useRef<boolean>(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n const run = useCallback(async (): Promise<T> => {\n const callId = ++callIdRef.current;\n setState((current) => ({ ...current, status: \"pending\", error: undefined }));\n try {\n const data = await fnRef.current();\n if (mountedRef.current && callIdRef.current === callId) {\n setState({ status: \"success\", data, error: undefined });\n }\n return data;\n } catch (error) {\n if (mountedRef.current && callIdRef.current === callId) {\n setState({ status: \"error\", data: undefined, error });\n }\n throw error;\n }\n }, [fnRef]);\n\n const reset = useCallback((): void => {\n callIdRef.current++;\n setState({ status: \"idle\", data: undefined, error: undefined });\n }, []);\n\n useEffect(() => {\n if (!immediate) return;\n run().catch(() => {\n /* error already captured in state */\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [immediate, ...deps]);\n\n return {\n status: state.status,\n data: state.data,\n error: state.error,\n isPending: state.status === \"pending\",\n isSuccess: state.status === \"success\",\n isError: state.status === \"error\",\n run,\n reset,\n };\n}\n"],"mappings":";;;AA6BA,SAAgB,EACZ,GACA,IAA+B,CAAC,GAChC,IAAmC,CAAC,GACnB;CACjB,IAAM,EAAE,eAAY,OAAU,GACxB,CAAC,GAAO,KAAY,EAIvB;EAAE,QAAQ;EAAQ,MAAM,KAAA;EAAW,OAAO,KAAA;CAAU,CAAC,GAElD,IAAQ,EAAa,CAAO,GAC5B,IAAY,EAAe,CAAC,GAC5B,IAAa,EAAgB,EAAI;CAEvC,SACI,EAAW,UAAU,UACR;EACT,EAAW,UAAU;CACzB,IACD,CAAC,CAAC;CAEL,IAAM,IAAM,EAAY,YAAwB;EAC5C,IAAM,IAAS,EAAE,EAAU;EAC3B,GAAU,OAAa;GAAE,GAAG;GAAS,QAAQ;GAAW,OAAO,KAAA;EAAU,EAAE;EAC3E,IAAI;GACA,IAAM,IAAO,MAAM,EAAM,QAAQ;GAIjC,OAHI,EAAW,WAAW,EAAU,YAAY,KAC5C,EAAS;IAAE,QAAQ;IAAW;IAAM,OAAO,KAAA;GAAU,CAAC,GAEnD;EACX,SAAS,GAAO;GAIZ,MAHI,EAAW,WAAW,EAAU,YAAY,KAC5C,EAAS;IAAE,QAAQ;IAAS,MAAM,KAAA;IAAW;GAAM,CAAC,GAElD;EACV;CACJ,GAAG,CAAC,CAAK,CAAC,GAEJ,IAAQ,QAAwB;EAElC,AADA,EAAU,WACV,EAAS;GAAE,QAAQ;GAAQ,MAAM,KAAA;GAAW,OAAO,KAAA;EAAU,CAAC;CAClE,GAAG,CAAC,CAAC;CAUL,OARA,QAAgB;EACP,KACL,EAAI,CAAC,CAAC,YAAY,CAElB,CAAC;CAEL,GAAG,CAAC,GAAW,GAAG,CAAI,CAAC,GAEhB;EACH,QAAQ,EAAM;EACd,MAAM,EAAM;EACZ,OAAO,EAAM;EACb,WAAW,EAAM,WAAW;EAC5B,WAAW,EAAM,WAAW;EAC5B,SAAS,EAAM,WAAW;EAC1B;EACA;CACJ;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
const e=require("./use-latest-ref.cjs");let t=require("react");function n(n){let r=(0,t.useRef)(null),i=e.useLatestRef(n);return(0,t.useEffect)(()=>{if(typeof document>`u`)return;let e=e=>{let t=e.target;!r.current||t&&r.current.contains(t)||i.current()};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e)}},[i]),r}exports.useClickOutside=n;
|
|
2
2
|
//# sourceMappingURL=use-click-outside.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-click-outside.cjs","names":[],"sources":["../../src/hooks/use-click-outside.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport type { RefObject } from \"react\";\n\n/**\n * Call `handler` when a `mousedown` / `touchstart` occurs outside the returned\n * ref's element. SSR-safe — listeners are only attached in the browser.\n *\n * @typeParam T - element type to attach the ref to.\n * @param handler - invoked on an outside interaction.\n * @returns A ref to attach to the element treated as \"inside\".\n */\nexport function useClickOutside<T extends HTMLElement = HTMLElement>(\n handler: () => void,\n): RefObject<T | null> {\n const ref = useRef<T>(null);\n const handlerRef =
|
|
1
|
+
{"version":3,"file":"use-click-outside.cjs","names":[],"sources":["../../src/hooks/use-click-outside.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { useLatestRef } from \"./use-latest-ref\";\nimport type { RefObject } from \"react\";\n\n/**\n * Call `handler` when a `mousedown` / `touchstart` occurs outside the returned\n * ref's element. SSR-safe — listeners are only attached in the browser.\n *\n * @typeParam T - element type to attach the ref to.\n * @param handler - invoked on an outside interaction.\n * @returns A ref to attach to the element treated as \"inside\".\n */\nexport function useClickOutside<T extends HTMLElement = HTMLElement>(\n handler: () => void,\n): RefObject<T | null> {\n const ref = useRef<T>(null);\n const handlerRef = useLatestRef(handler);\n\n useEffect(() => {\n if (typeof document === \"undefined\") return;\n\n const listener = (event: MouseEvent | TouchEvent): void => {\n const target = event.target as Node | null;\n if (!ref.current || (target && ref.current.contains(target))) return;\n handlerRef.current();\n };\n\n document.addEventListener(\"mousedown\", listener);\n document.addEventListener(\"touchstart\", listener);\n return () => {\n document.removeEventListener(\"mousedown\", listener);\n document.removeEventListener(\"touchstart\", listener);\n };\n }, [handlerRef]);\n\n return ref;\n}\n"],"mappings":"+DAYA,SAAgB,EACZ,EACmB,CACnB,IAAM,GAAA,EAAM,EAAA,OAAA,CAAU,IAAI,EACpB,EAAa,EAAA,aAAa,CAAO,EAmBvC,OAjBA,EAAA,EAAA,UAAA,KAAgB,CACZ,GAAI,OAAO,SAAa,IAAa,OAErC,IAAM,EAAY,GAAyC,CACvD,IAAM,EAAS,EAAM,OACjB,CAAC,EAAI,SAAY,GAAU,EAAI,QAAQ,SAAS,CAAM,GAC1D,EAAW,QAAQ,CACvB,EAIA,OAFA,SAAS,iBAAiB,YAAa,CAAQ,EAC/C,SAAS,iBAAiB,aAAc,CAAQ,MACnC,CACT,SAAS,oBAAoB,YAAa,CAAQ,EAClD,SAAS,oBAAoB,aAAc,CAAQ,CACvD,CACJ,EAAG,CAAC,CAAU,CAAC,EAER,CACX"}
|