Skip to content

Catch up #355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 14, 2025
Merged
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
2 changes: 2 additions & 0 deletions app/Http/Middleware/HandleInertiaRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Middleware;
use Tighten\Ziggy\Ziggy;

Expand Down Expand Up @@ -53,6 +54,7 @@ public function share(Request $request): array
'error' => fn () => $request->session()->get('flash_error'),
'message' => fn () => $request->session()->get('flash_message'),
],
'queryParams' => Inertia::always($request->query()),
];
}
}
2 changes: 0 additions & 2 deletions package-lock.json

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

2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"@primevue/auto-import-resolver": "^4.3.3",
"@tailwindcss/vite": "^4.0.17",
"@types/lodash-es": "^4.17.12",
"@types/qs": "^6.9.18",
"@vitejs/plugin-vue": "^5.2.3",
"@vue/server-renderer": "^3.5.14",
"@vueuse/core": "^13.0.0",
Expand All @@ -22,7 +21,6 @@
"lodash-es": "^4.17.21",
"lucide-vue-next": "^0.485.0",
"primevue": "^4.3.3",
"qs": "^6.14.0",
"tailwind-merge": "^3.2.0",
"tailwindcss": "^4.0.17",
"tailwindcss-primeui": "^0.6.1",
Expand Down
101 changes: 41 additions & 60 deletions resources/js/composables/usePaginatedData.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { ref, computed, onMounted, toRaw } from 'vue';
import { router } from '@inertiajs/vue3';
import { router, usePage } from '@inertiajs/vue3';
import type { Page, PageProps } from '@inertiajs/core';
import { FilterMatchMode } from '@primevue/core/api';
import { PageState, DataTablePageEvent } from 'primevue';
import debounce from 'lodash-es/debounce';
import qs from 'qs';
import type { PrimeVueDataFilters, InertiaRouterFetchCallbacks } from '@/types';
import type { AppPageProps, PrimeVueDataFilters, InertiaRouterFetchCallbacks } from '@/types';

interface PaginatedFilteredSortedQueryParams {
interface QueryParams {
filters?: PrimeVueDataFilters;
page?: string;
rows?: string;
sortField?: string;
sortOrder?: string;
[key: string]: any;
}
interface PaginationState {
page: number;
Expand All @@ -22,13 +22,16 @@ interface SortState {
field: string;
order: number;
}
type InertiaPageProps = PageProps & Omit<AppPageProps, 'queryParams'> & {
queryParams: QueryParams
}

export function usePaginatedData(
propDataToFetch: string | string[],
initialFilters: PrimeVueDataFilters = {},
initialRows: number = 20
) {
const urlParams = ref<PaginatedFilteredSortedQueryParams>({});
const page = usePage<InertiaPageProps>();
const processing = ref<boolean>(false);
const filters = ref<PrimeVueDataFilters>(structuredClone(toRaw(initialFilters)));
const sorting = ref<SortState>({
Expand All @@ -43,9 +46,10 @@ export function usePaginatedData(
const firstDatasetIndex = computed(() => {
return (pagination.value.page - 1) * pagination.value.rows;
});

const filteredOrSorted = computed(() => {
const paramsFilters = urlParams.value?.filters || {};
const sortField = urlParams.value?.sortField || null;
const paramsFilters = page.props.queryParams?.filters || {};
const sortField = page.props.queryParams?.sortField || null;
const isFiltering = Object.values(paramsFilters).some(
(filter) => filter.value !== null && filter.value !== ''
);
Expand All @@ -58,21 +62,6 @@ export function usePaginatedData(
filterCallback();
}, 300);

function setUrlParams(): void {
const queryString = window.location.search;
const params = qs.parse(queryString, {
ignoreQueryPrefix: true,
strictNullHandling: true,
decoder: function (str, defaultDecoder) {
// set empty string values to null to match Laravel backend behavior
const value = defaultDecoder(str);
return value === '' ? null : value;
},
}) as PaginatedFilteredSortedQueryParams;

urlParams.value = { ...params };
}

function scrollToTop(): void {
window.scrollTo({
top: 0,
Expand All @@ -85,7 +74,6 @@ export function usePaginatedData(

return new Promise((resolve, reject) => {
processing.value = true;

router.visit(window.location.pathname, {
method: 'get',
data: {
Expand All @@ -98,7 +86,9 @@ export function usePaginatedData(
preserveUrl: false,
showProgress: true,
replace: true,
only: Array.isArray(propDataToFetch) ? propDataToFetch : [propDataToFetch],
only: Array.isArray(propDataToFetch)
? [...propDataToFetch, 'queryParams']
: [propDataToFetch, 'queryParams'],
onSuccess: (page) => {
onSuccess?.(page);
resolve(page);
Expand All @@ -108,7 +98,6 @@ export function usePaginatedData(
reject(errors);
},
onFinish: () => {
setUrlParams();
processing.value = false;
onFinish?.();
},
Expand All @@ -122,7 +111,6 @@ export function usePaginatedData(
} else {
pagination.value.page = event.page + 1;
}

pagination.value.rows = event.rows;

return fetchData({
Expand All @@ -134,8 +122,8 @@ export function usePaginatedData(

function filter(options: InertiaRouterFetchCallbacks = {}): Promise<Page<PageProps>> {
const { onFinish: onFinishCallback, onSuccess, onError } = options;

pagination.value.page = 1;

return fetchData({
onSuccess,
onError,
Expand All @@ -162,22 +150,23 @@ export function usePaginatedData(

return new Promise((resolve, reject) => {
processing.value = true;

router.visit(window.location.pathname, {
method: 'get',
preserveUrl: false,
showProgress: true,
replace: true,
only: Array.isArray(propDataToFetch) ? propDataToFetch : [propDataToFetch],
onSuccess(page) {
only: Array.isArray(propDataToFetch)
? [...propDataToFetch, 'queryParams']
: [propDataToFetch, 'queryParams'],
onSuccess: (page) => {
onSuccess?.(page);
resolve(page);
},
onError(errors) {
onError: (errors) => {
onError?.(errors);
reject(errors);
},
onFinish() {
onFinish: () => {
processing.value = false;
onFinish?.();
},
Expand All @@ -188,19 +177,17 @@ export function usePaginatedData(
function parseUrlFilterValues(): void {
Object.keys(filters.value).forEach((key) => {
const filter = filters.value[key];

if (!filter?.value || !filter?.matchMode) {
return;
}

if (
filter.matchMode == FilterMatchMode.DATE_IS ||
filter.matchMode == FilterMatchMode.DATE_IS_NOT ||
filter.matchMode == FilterMatchMode.DATE_BEFORE ||
filter.matchMode == FilterMatchMode.DATE_AFTER
) {
if ([
FilterMatchMode.DATE_IS,
FilterMatchMode.DATE_IS_NOT,
FilterMatchMode.DATE_BEFORE,
FilterMatchMode.DATE_AFTER,
].includes(filter.matchMode)) {
filters.value[key].value = new Date(filter.value as string);
} else if (filter.matchMode == FilterMatchMode.BETWEEN) {
} else if (filter.matchMode === FilterMatchMode.BETWEEN) {
filter.value.forEach((value: any, index: number) => {
if (typeof value === 'string') {
filter.value[index] = new Date(value);
Expand All @@ -214,15 +201,14 @@ export function usePaginatedData(
filters.value[key].value = Number(filter.value);
} else if (
Array.isArray(filter.value) ||
filter.matchMode == FilterMatchMode.IN
filter.matchMode === FilterMatchMode.IN
) {
if (filter.value.length === 0) {
// empty arrays cause filtering issues, set to null instead
filters.value[key].value = null;
} else {
// Unique array values
const unique = [...new Set(filter.value)];

filter.value = unique;
filter.value.forEach((value: any, index: number) => {
if (typeof value === 'string' && !isNaN(Number(value))) {
Expand All @@ -234,34 +220,29 @@ export function usePaginatedData(
});
}

function parseUrlParams(urlParamsObj: PaginatedFilteredSortedQueryParams): void {
function parseUrlParams(): void {
const queryParams = page.props.queryParams || {};
filters.value = {
...structuredClone(toRaw(initialFilters)),
...urlParamsObj?.filters,
...queryParams.filters,
};

parseUrlFilterValues();

if (urlParamsObj?.sortField) {
sorting.value.field = urlParamsObj.sortField;
if (queryParams.sortField) {
sorting.value.field = queryParams.sortField;
}

if (urlParamsObj?.sortOrder) {
sorting.value.order = parseInt(urlParamsObj.sortOrder);
if (queryParams.sortOrder) {
sorting.value.order = parseInt(queryParams.sortOrder);
}

if (urlParamsObj?.page) {
pagination.value.page = parseInt(urlParamsObj.page);
if (queryParams.page) {
pagination.value.page = parseInt(queryParams.page);
}

if (urlParamsObj?.rows) {
pagination.value.rows = parseInt(urlParamsObj.rows);
if (queryParams.rows) {
pagination.value.rows = parseInt(queryParams.rows);
}
}

onMounted(() => {
setUrlParams();
parseUrlParams(urlParams.value);
parseUrlParams();
});

return {
Expand Down
2 changes: 1 addition & 1 deletion resources/js/types/global.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { PageProps as InertiaPageProps } from '@inertiajs/core';
import { AxiosInstance } from 'axios';
import { route as ziggyRoute } from 'ziggy-js';
import { PageProps as AppPageProps } from './';
import { AppPageProps } from './';

declare global {
interface Window {
Expand Down
27 changes: 22 additions & 5 deletions resources/js/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
import type { DataTableFilterMetaData } from 'primevue';
import type { Page, PageProps, Errors } from '@inertiajs/core';
import type { Page, Errors } from '@inertiajs/core';
import type { MenuItem as PrimeVueMenuItem } from 'primevue/menuitem';
import type { LucideIcon } from 'lucide-vue-next';
import type { Config } from 'ziggy-js';

export interface User {
id: number;
name: string;
email: string;
email_verified_at?: string;
email_verified_at: string | null;
}

export type PageProps<
T extends Record<string, unknown> = Record<string, unknown>
> = T;
export interface AuthProps {
user: User | null;
}

export interface FlashProps {
success?: string | null;
info?: string | null;
warn?: string | null;
error?: string | null;
message?: string | null;
}

export type AppPageProps<T extends Record<string, unknown> = Record<string, unknown>> = T & {
colorScheme: 'auto' | 'light' | 'dark';
ziggy: Config & { location: string };
auth: AuthProps;
flash: FlashProps;
queryParams: Record<string, string | string[]>;
};

export type PrimeVueDataFilters = {
[key: string]: DataTableFilterMetaData;
Expand Down