Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"@radix-ui/react-tooltip": "^1.2.8",
"@solvro/next-view-transitions": "^0.4.3",
"@t3-oss/env-nextjs": "^0.13.11",
"@tanstack/react-query": "^5.90.5",
"@tanstack/react-query": "^5.101.2",
"@tiptap/extension-code-block-lowlight": "~3.8.0",
"@tiptap/extension-color": "~3.8.0",
"@tiptap/extension-horizontal-rule": "~3.8.0",
Expand Down
3 changes: 3 additions & 0 deletions src/components/presentation/logout-button.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";

import { useQueryClient } from "@tanstack/react-query";
import { LogOut } from "lucide-react";
import { toast } from "sonner";

Expand All @@ -12,6 +13,7 @@ import { getToastMessages } from "@/lib/get-toast-messages";

export function LogoutButton() {
const { logout, clearAuthState } = useAuthentication();
const queryClient = useQueryClient();
const router = useRouter();

const { mutateAsync, isPending } = useMutationWrapper<
Expand All @@ -28,6 +30,7 @@ export function LogoutButton() {
router.push("/login", {
onSnapshotTaken: () => {
clearAuthState();
queryClient.clear();
},
});
},
Expand Down
32 changes: 24 additions & 8 deletions src/components/providers/root-providers.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
"use client";

import { ViewTransitions } from "@solvro/next-view-transitions";
import { QueryClient } from "@tanstack/react-query";
import { QueryClient, environmentManager } from "@tanstack/react-query";
Comment thread
michalges marked this conversation as resolved.

import { globalStore } from "@/stores/global";
import type { WrapperProps } from "@/types/components";

import { InternalProviders } from "./internal-providers";

const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24,
// https://tanstack.com/query/latest/docs/framework/react/guides/advanced-ssr

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Jedynie się obawiam czy te zmiany z query klientem mogą coś jeszcze namieszać? Z tego co przeklikałem to wszystko (na razie) działa.

function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
gcTime: 1000 * 60 * 60 * 24,
},
},
},
});
});
}

let browserQueryClient: QueryClient | undefined;

function getQueryClient() {
if (environmentManager.isServer()) {
return makeQueryClient();
} else {
browserQueryClient ??= makeQueryClient();
return browserQueryClient;
}
}
Comment thread
michalges marked this conversation as resolved.

export function RootProviders({ children }: WrapperProps) {
const queryClient = getQueryClient();

return (
<ViewTransitions>
<InternalProviders queryClient={queryClient} jotaiStore={globalStore}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ReactNode } from "react";
import { get } from "react-hook-form";
import type { Control } from "react-hook-form";
import { toast } from "sonner";
Expand Down Expand Up @@ -36,11 +37,13 @@ import { sanitizeId, toTitleCase } from "@/utils";
import { useArfRelation } from "../hooks/use-arf-relation";
import { useArfRelationMutation } from "../hooks/use-arf-relation-mutation";
import { useArfSheet } from "../hooks/use-arf-sheet";
import { getItemPivotOrder } from "../utils/get-item-pivot-order";
import { getMutationConfig } from "../utils/get-mutation-config";
import { isExistingItem } from "../utils/is-existing-item";
import { ArfInput } from "./arf-input";
import { ArfPivotData } from "./arf-pivot-data";
import { OrderableMultiSelect } from "./orderable-multi-select";
import { OrderablePivotMultiSelect } from "./orderable-pivot-multi-select";

export function ArfRelationInput<
T extends Resource,
Expand Down Expand Up @@ -142,12 +145,26 @@ export function ArfRelationInput<
);
}
const queriedRelations = unsafeQueriedRelations ?? [];
const isRelationOrderable = isOrderableResource(resourceRelation);
const isRelationOrderable =
isOrderableResource(resourceRelation) &&
relationDefinition.type !== RelationType.ManyToMany;
const isPivotOrderable =
relationDefinition.type === RelationType.ManyToMany &&
relationDefinition.orderable === true;
const sortedQueriedRelations = isRelationOrderable
? [...queriedRelations].toSorted((a, b) =>
"order" in a && "order" in b ? a.order - b.order : 1,
)
: queriedRelations;
: isPivotOrderable
? [...queriedRelations].toSorted((a, b) => {
const orderA = getItemPivotOrder(a);
const orderB = getItemPivotOrder(b);
if (orderA !== undefined && orderB !== undefined) {
return orderA - orderB;
}
return 1;
})
: queriedRelations;
const selectedValues = sortedQueriedRelations.flatMap((item) => {
const value = get(item, primaryKeyField, null) as ResourcePk | null;
return value == null ? [] : String(value);
Expand Down Expand Up @@ -262,16 +279,29 @@ export function ArfRelationInput<
defaultValue: [...new Set(selectedValues)],
} satisfies React.ComponentProps<typeof MultiSelect>;

const multiselect = isRelationOrderable ? (
<OrderableMultiSelect
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- type guard doesn't narrow generics
resourceRelation={resourceRelation as OrderableResource}
items={sortedQueriedRelations as ResourceDataType<OrderableResource>[]}
multiSelectProps={multiSelectProps}
/>
) : (
<MultiSelect {...multiSelectProps} />
);
let multiselect: ReactNode;
if (isRelationOrderable) {
multiselect = (
<OrderableMultiSelect
resourceRelation={resourceRelation as OrderableResource}
items={sortedQueriedRelations as ResourceDataType<OrderableResource>[]}
multiSelectProps={multiSelectProps}
/>
);
} else if (isPivotOrderable && relationDefinition.pivotData != null) {
multiselect = (
<OrderablePivotMultiSelect
resource={resource}
resourceRelation={resourceRelation}
endpoint={endpoint}
pivotData={relationDefinition.pivotData}
items={sortedQueriedRelations}
multiSelectProps={multiSelectProps}
/>
);
} else {
multiselect = <MultiSelect {...multiSelectProps} />;
}
return relationDefinition.type === RelationType.ManyToMany ? (
// TODO: allow m:n relation inputs to be immutable
<Label className="flex-col items-start">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import { useRef } from "react";
import { arrayMove } from "@dnd-kit/sortable";
import { useEffect, useRef } from "react";

import { MultiSelect } from "@/components/ui/multi-select";
import { calculateNewSortValue } from "@/features/abstract-resource-list";
Expand All @@ -23,7 +24,10 @@ export function OrderableMultiSelect<T extends OrderableResource>({
multiSelectProps,
}: OrderableMultiSelectProps<T>) {
const itemsRef = useRef(items);
itemsRef.current = items;

useEffect(() => {
itemsRef.current = items;
}, [items]);

const { mutateOrder } = useRelationOrderMutation({ resourceRelation });

Expand All @@ -33,6 +37,9 @@ export function OrderableMultiSelect<T extends OrderableResource>({
oldIndex,
newIndex,
);

itemsRef.current = arrayMove(itemsRef.current, oldIndex, newIndex);

void mutateOrder(id, order);
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"use client";

import { arrayMove } from "@dnd-kit/sortable";
import { useEffect, useRef } from "react";
import type { ComponentProps } from "react";

import { MultiSelect } from "@/components/ui/multi-select";
import { calculateNewSortValue } from "@/features/abstract-resource-list";
import type { Resource } from "@/features/resources";
import type {
OrderableResource,
PivotDataDefinition,
ResourceDataType,
ResourcePk,
ResourceRelation,
} from "@/features/resources/types";

import { usePivotRelationOrderMutation } from "../hooks/use-pivot-relation-order-mutation";
import { getItemPivotOrder, hasMeta } from "../utils/get-item-pivot-order";

export function OrderablePivotMultiSelect<
T extends Resource,
L extends ResourceRelation<T>,
>({
resource,
resourceRelation,
endpoint,
pivotData,
items,
multiSelectProps,
}: {
resource: T;
resourceRelation: L;
endpoint: string;
pivotData: PivotDataDefinition;
items: ResourceDataType<L>[];
multiSelectProps: ComponentProps<typeof MultiSelect>;
}) {
const itemsRef = useRef(items);

useEffect(() => {
itemsRef.current = items;
}, [items]);

const { mutateOrder } = usePivotRelationOrderMutation({
resource,
resourceRelation,
endpoint,
});

const handleReorder = (id: string, oldIndex: number, newIndex: number) => {
const mappedItems = itemsRef.current.map((item) => ({
...item,
order: getItemPivotOrder(item) ?? 0,
})) as ResourceDataType<OrderableResource>[];

const order = calculateNewSortValue(mappedItems, oldIndex, newIndex);

const originalItem = itemsRef.current.find(
(item) => String(item.id) === id,
);
if (originalItem == null) {
return;
}

const meta = hasMeta(originalItem) ? originalItem.meta : undefined;
const pivotKey = `pivot_${pivotData.field}`;
const pivotValue = meta?.[pivotKey];

if (pivotValue == null) {
return;
}

const reorderedItems = arrayMove(itemsRef.current, oldIndex, newIndex);

itemsRef.current = reorderedItems.map((item) => {
if (String(item.id) === id) {
return {
...item,
meta: {
...(hasMeta(item) ? item.meta : {}),
pivot_order: order,
},
};
}
return item;
});

void mutateOrder(id as ResourcePk, order, {
[pivotData.field]: pivotValue,
});
};

return <MultiSelect {...multiSelectProps} onReorder={handleReorder} />;
}
Loading
Loading