fix useSearch and admin path registration

This commit is contained in:
dswbx
2025-06-09 07:21:32 +02:00
parent 0db052acca
commit 4729203d47
4 changed files with 34 additions and 28 deletions

View File

@@ -1,4 +1,4 @@
import { decodeSearch, encodeSearch, parseDecode } from "core/utils";
import { decodeSearch, encodeSearch, mergeObject, parseDecode } from "core/utils";
import { isEqual, transform } from "lodash-es";
import { useLocation, useSearch as useWouterSearch } from "wouter";
import { type s, parse } from "core/object/schema";
@@ -16,23 +16,16 @@ export function useSearch<Schema extends s.TAnySchema = s.TAnySchema>(
clone: true,
}) as s.StaticCoerced<Schema>;
// @todo: add option to set multiple keys at once
function set<Key extends keyof s.StaticCoerced<Schema>>(
key: Key,
value: s.StaticCoerced<Schema>[Key],
): void {
//console.log("set", key, value);
const update = parse(schema, { ...decodeSearch(searchString), [key]: value });
const search = transform(
update as any,
(result, value, key) => {
if (defaultValue && isEqual(value, defaultValue[key])) return;
result[key] = value;
},
{} as s.StaticCoerced<Schema>,
);
const encoded = encodeSearch(search, { encode: false });
navigate(location + (encoded.length > 0 ? "?" + encoded : ""));
// @ts-ignore
const _defaults = mergeObject(schema.template({ withOptional: true }), defaultValue ?? {});
function set<Update extends Partial<s.StaticCoerced<Schema>>>(update: Update): void {
// @ts-ignore
if (schema.validate(update).valid) {
const search = getWithoutDefaults(mergeObject(value, update), _defaults);
const encoded = encodeSearch(search, { encode: false });
navigate(location + (encoded.length > 0 ? "?" + encoded : ""));
}
}
return {
@@ -40,3 +33,14 @@ export function useSearch<Schema extends s.TAnySchema = s.TAnySchema>(
set,
};
}
function getWithoutDefaults(value: object, defaultValue: object) {
return transform(
value as any,
(result, value, key) => {
if (defaultValue && isEqual(value, defaultValue[key])) return;
result[key] = value;
},
{} as object,
);
}

View File

@@ -23,7 +23,7 @@ const searchSchema = s.partialObject({
perPage: s.number({ default: 10 }).optional(),
});
const PER_PAGE_OPTIONS = [5, 10, 25];
const PER_PAGE_OPTIONS = [5, 10, 25, 50, 100];
export function DataEntityList({ params }) {
const { $data } = useBkndData();
@@ -61,19 +61,18 @@ export function DataEntityList({ params }) {
}
function handleClickPage(page: number) {
search.set("page", page);
search.set({ page });
}
function handleSortClick(name: string) {
const sort = search.value.sort!;
const newSort = { by: name, dir: sort.by === name && sort.dir === "asc" ? "desc" : "asc" };
search.set("sort", newSort as any);
search.set({ sort: newSort as any });
}
function handleClickPerPage(perPage: number) {
// @todo: also reset page to 1
search.set("perPage", perPage);
search.set({ perPage, page: 1 });
}
const isUpdating = $q.isLoading || $q.isValidating;