-
Notifications
You must be signed in to change notification settings - Fork 0
/
useLimboSearch.js
915 lines (851 loc) · 26.3 KB
/
useLimboSearch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
export const useLimboSearch = async (options = {}) => {
/*
Options
we repeat this way of getting variables in every function, computed
value or watcher in which they are used as to keep reactivity, though
we have left them in commented for the sake of clarity.
Except the searchKey, which should not be replaced post initiation!
*/
const {
searchKey = "",
// searchFilters,
// config = {},
// extraParameters = {},
// parameterOverwrites = {},
} = toValue(options || {});
// Default methods and values
const defaultDataMergerMethod = (newData, oldData) => {
if (
newData &&
oldData &&
Array.isArray(newData) &&
Array.isArray(oldData)
) {
return [...oldData, ...newData];
}
return newData;
};
const defaultGroupedDataMergerMethod = (newData, oldData) => {
const compiledGroups = [];
if (
newData?.groups &&
oldData?.groups &&
Array.isArray(newData.groups) &&
Array.isArray(oldData.groups)
) {
oldData.groups.forEach((group) => {
const newGroup = newData.groups.find((newGroup) => {
return newGroup.id === group.id;
});
if (newGroup) {
newGroup.items = [...group.items, ...newGroup.items];
compiledGroups.push(newGroup);
} else {
compiledGroups.push(group);
}
});
return { ...newData, groups: compiledGroups };
}
return newData || JSON.parse(JSON.stringify(oldData));
};
const defaultLimit = 12;
const defaultConfig = {
callMethod: "GET", // { string } The method to use for the call
enableLiveSearch: false, // { boolean|array } Can be an array of particular parameters triggering a live search or simply true or false
immediateSearch: {
useUrlQuery: true,
ssr: true, // ssr: true will make the search run on the server side
}, // { boolean|object } Can also be set to boolean value
clearRouterHashOnSearch: false, // { boolean|object } Whether to clear the hash on search. If an object is used, the property "includeInitialSearch" to also clear for the first search, else that will be left out
limit: { initial: defaultLimit, value: defaultLimit }, // { number|object } If a numeric limit is set, it will be used for both values - grouped paginations should be set with their ids (fx. limit: { 1: { initial: 18, value: 12 }, 2: { initial: 15, value: 6 } }).
enableGroupedSearch: false, // { boolean } Make use of grouped pagination (l1, o1, l2, o2, (ie. l{id}, o{id}) etc.) instead of simply "limit" and "offset".
groupParameter: "groups", // { string } When needing to "fetch more / all" we need a parameter to filter that.
updateUrlQueryOnSearch: true, // { boolean } Allow the page's url to reflect the search
updateVueRouteOnSearch: false, // { boolean|object } Allow the vue router to reflect the search - may cause issues if the page is keyed based off the query. /* NOT FULLY DONE YET (DON'T CURRENTLY RE-SEARCH): If an object is used, set "pushHistory" to make each individual search part of the browser history. */
clearSearchDataOnError: true, // { boolean } When toggled to false, the data from the previous search will persist on error
allowSearchFiltersMutation: false, // { boolean } Needs to be explicitly turned on!
updateSearchFiltersOnBindingChange: true, // { boolean } Whether a change in the bound search filters should trigger a change in the internally used data
persistentParameters: ["contextId"], // { array } Parameters that should always be present in a search (empty or not)
hiddenParameters: ["siteId", "contextId", "pageId", "cultureId"], // { array } Parameters that should not be shown in the url.
defaultParameterValues: {}, // { object } Default values for parameters - parameters will not be shown in the url if they have the same value as the default value
searchDelay: 0, // { number } Delay in ms before the search is triggered
urlFilterMapping: {}, // { object } Mapping for filters to url parameters, NOT FULLY IMPLEMENTED YET
// Data transformation methods
searchResponseTransformerMethod: (val) => val, // { function } Method to transform the response data
searchBodyTransformerMethod: (val) => val, // { function } Method to transform the searchBody data, ONLY used when callMethod is POST
dataMergerMethod: defaultDataMergerMethod, // { function } Method to merge new data with old data
dataOutputTransformerMethod: (val) => val, // { function } Method to transform the output data. Note that this method doesn't change the internally stored data, but only the data place in the bindings.
// Hooks
onInit: () => {}, // { function } Hook for when the search is initiated. The reactive Limbo search object is passed as the first argument.
};
onBeforeUnmount(() => {
clearNuxtState([`searchData${searchKey}`, `searchState${searchKey}`]);
});
const defaultSearchData = {
data: null,
facets: null,
pagination: null,
meta: null,
misc: null,
error: null,
};
const reservedParameters = ["limit", "offset", "total"];
const lastRequestedUrl = ref(null);
const searchData = useState(`searchData${searchKey}`, () =>
JSON.parse(JSON.stringify(defaultSearchData))
);
const searchFilters = computed(() => {
const { searchFilters } = toValue(options || {});
if (searchFilters && isRef(searchFilters)) {
return searchFilters.value;
}
return searchFilters;
});
const internalSearchFilters = ref(
removeReservedParameters(searchFilters.value)
);
const searchFiltersClone = ref(
removeReservedParameters(
JSON.parse(JSON.stringify(searchFilters.value))
)
);
const internalExtraParameters = ref({});
const internalPagination = ref({});
const requestTimeout = ref(null);
const state = useState(`searchState${searchKey}`, () => ({
isInitiated: false,
isLoading: false,
hasFetchedOnce: false,
hasMoreItems: undefined,
isAppend: false,
}));
const query = ref({
parameters: null,
});
const latestResponse = ref(null);
const compConfig = computed(() => {
const { config = {} } = toValue(options || {});
const _return = { ...defaultConfig, ...config };
if (
_return.dataMergerMethod === defaultDataMergerMethod &&
_return.enableGroupedSearch
) {
_return.dataMergerMethod = defaultGroupedDataMergerMethod;
}
return _return;
});
const filters = computed(() => {
if (compConfig.value.allowSearchFiltersMutation) {
return internalSearchFilters.value;
}
return searchFiltersClone.value;
});
const endpointUrl = computed(() => {
return filters.value?.endpointUrl;
});
const fields = computed(() => {
return filters.value?.fields;
});
const searchFilterParameters = computed(() => {
const fieldParameters =
fields.value?.reduce((reducer, field) => {
if (field.name) {
if (Array.isArray(field.value)) {
const item = field.value.find((item) => item.checked);
if (item) {
reducer[field.name] = item.value;
}
} else {
reducer[field.name] = field.value;
}
}
return reducer;
}, {}) ?? {};
return fieldParameters;
});
const pagination = computed(() => {
if (compConfig.value.enableGroupedSearch) {
return convertToParameterStyledPagination(internalPagination.value);
}
const pagination = { limit: 0, offset: 0 };
const { limit, offset } = internalPagination.value ?? {};
if (typeof limit !== "undefined") {
pagination.limit = limit;
}
if (typeof offset !== "undefined") {
pagination.offset = offset;
}
return pagination;
});
const watchedParameters = computed(() => {
const { extraParameters = {}, parameterOverwrites = {} } = toValue(
options || {}
);
const parameters = {
...extraParameters,
...searchFilterParameters.value,
};
for (const key in parameterOverwrites) {
parameters[key] = parameterOverwrites[key];
}
return parameters;
});
const parameters = computed(() => {
const { extraParameters = {}, parameterOverwrites = {} } = toValue(
options || {}
);
const parameters = {
...extraParameters,
...internalExtraParameters.value,
...searchFilterParameters.value,
...pagination.value,
...parameterOverwrites,
};
for (const name in parameters) {
const value = parameters[name];
if (
value == null &&
!compConfig.value.persistentParameters?.includes?.(name)
) {
delete parameters[name];
}
}
return parameters;
});
const hideGroupsParameter = computed(() => {
const { parameterOverwrites = {} } = toValue(options || {});
if (
compConfig.value.enableGroupedSearch &&
typeof internalExtraParameters.value[
compConfig.value.groupParameter
] !== "undefined"
) {
const parameters = {
...searchFilterParameters.value,
...pagination.value,
...parameterOverwrites,
};
for (const name in parameters) {
const value = parameters[name];
if (
name === compConfig.value.groupParameter &&
(value ||
compConfig.value.persistentParameters?.includes?.(name))
) {
return false;
}
}
return true;
}
return false;
});
watch(
searchFilters,
(newFilters) => {
if (compConfig.value.updateSearchFiltersOnBindingChange) {
internalSearchFilters.value =
removeReservedParameters(newFilters);
searchFiltersClone.value = removeReservedParameters(
JSON.parse(JSON.stringify(newFilters))
);
}
},
{ deep: true }
);
watch(
watchedParameters,
(newParams, oldParams) => {
const { enableLiveSearch } = compConfig.value;
if (enableLiveSearch) {
if (!Array.isArray(enableLiveSearch)) {
if (
state.value.hasFetchedOnce &&
JSON.stringify(newParams) !== JSON.stringify(oldParams)
) {
submit();
}
} else if (state.value.hasFetchedOnce) {
for (let i = 0; i < enableLiveSearch.length; i++) {
const key = enableLiveSearch[i];
if (newParams[key] !== oldParams[key]) {
submit();
break;
}
}
}
}
},
{ deep: true }
);
const route = useRoute();
function submit() {
internalExtraParameters.value = {};
resetPagination();
requestSearch();
}
function fetchMore(amount) {
// Set a default amount if none is provided
amount ??=
(compConfig.value.limit?.value ??
parseInt(compConfig.value.limit)) ||
defaultLimit;
amount = +amount;
// Cancel out if we are already loading or there are no more items
if (state.value.isLoading || !state.value.hasMoreItems) {
return;
}
// Set new internal pagination
internalPagination.value.offset += internalPagination.value.limit ?? 0;
internalPagination.value.limit =
amount ?? internalPagination.value.limit;
// Request the search
requestSearch({ append: true });
}
function fetchMoreGroup(id, amount) {
if (!searchData?.value?.error && state.value.hasMoreItems?.[id]) {
// Make sure that we don't fetch the other groups as well
internalExtraParameters.value[compConfig.value.groupParameter] = id;
// Set a default amount if none is provided
amount ??=
(compConfig.value.limit[id]?.value ??
parseInt(compConfig.value.limit[id])) ||
defaultLimit;
amount = +amount;
// Set new internal pagination
const internal = internalPagination.value[id] || {};
internal.offset =
+searchData?.value?.pagination?.[id]?.offset +
+searchData?.value?.pagination?.[id]?.limit;
internal.limit = +amount;
internalPagination.value[id] = internal;
// Request the search
requestSearch({ append: true });
}
}
function fetchAll() {
if (!searchData?.value?.error && state.value.hasMoreItems) {
internalPagination.value.offset =
+searchData?.value?.pagination?.offset +
+searchData?.value?.pagination?.limit;
internalPagination.value.limit =
+searchData?.value?.pagination?.total -
internalPagination.value.offset;
requestSearch({ append: true });
}
}
function fetchAllGroup(id) {
if (!searchData?.value?.error && state.value.hasMoreItems?.[id]) {
// Make sure that we don't fetch the other groups as well
internalExtraParameters.value[compConfig.value.groupParameter] = id;
// Fetch
const internal = internalPagination.value[id] || {};
internal.offset =
+searchData?.value?.pagination?.[id]?.offset +
+searchData?.value?.pagination?.[id]?.limit;
internal.limit =
+searchData?.value?.pagination?.[id]?.total - internal.offset;
internalPagination.value[id] = internal;
requestSearch({ append: true });
}
}
async function requestSearch(options) {
const { delay, append } = {
delay: compConfig.value.searchDelay,
append: false,
...options,
};
let clearHash = false;
if (
!append &&
route.hash &&
compConfig.value.clearRouterHashOnSearch &&
(!compConfig.value.immediateSearch ||
state.value.hasFetchedOnce ||
compConfig.value.clearRouterHashOnSearch?.includeInitialSearch)
) {
clearHash = true;
}
state.value.isInitiated = true;
state.value.isLoading = true;
// The search requesting
const searchRequest = async () => {
const params = {
...(append
? {
...query.value.parameters,
...internalExtraParameters.value,
...convertToParameterStyledPagination(
internalPagination.value
),
}
: parameters.value),
};
const serializedParams = getSerializedParams(params);
if (
compConfig.value.updateUrlQueryOnSearch ||
compConfig.value.updateVueRouteOnSearch
) {
setUrlQuery(serializedParams, clearHash);
}
requestTimeout.value = null;
lastRequestedUrl.value = `${endpointUrl.value}?${serializedParams}`;
if (compConfig.value.callMethod === "POST") {
lastRequestedUrl.value = endpointUrl.value;
}
state.value.isAppend = !!append;
const currentlyRequestedUrl = lastRequestedUrl.value;
const data = await $fetch(lastRequestedUrl.value, {
method: compConfig.value.callMethod,
body:
compConfig.value.callMethod === "POST"
? compConfig.value.searchBodyTransformerMethod(params)
: null,
onResponseError({ response }) {
if (!requestTimeout.value) {
searchData.value = {
...defaultSearchData,
...searchData.value,
};
state.value.hasFetchedOnce = import.meta.client;
if (compConfig.value.clearSearchDataOnError) {
state.value.hasMoreItems = null;
Object.assign(searchData.value, defaultSearchData);
latestResponse.value = null;
} else {
if (compConfig.value.enableGroupedSearch) {
for (const key in state.value.hasMoreItems) {
state.value.hasMoreItems[key] = false;
}
} else {
state.value.hasMoreItems = false;
}
}
searchData.value.error = response._data;
state.value.isLoading = false;
console.error(response._data);
}
},
});
if (lastRequestedUrl.value != currentlyRequestedUrl) {
return;
}
if (!requestTimeout.value) {
state.value.hasFetchedOnce = import.meta.client;
let response =
compConfig.value.searchResponseTransformerMethod?.(data) ??
data;
latestResponse.value = data; // save for later
// On append, merge the paginations
if (append && searchData.value.pagination && response) {
if (response.pagination) {
response.pagination = {
...searchData.value.pagination,
...response.pagination,
};
} else {
response.pagination = {
...searchData.value.pagination,
};
}
} // Should probably merge facets and misc as well... A thing for the future?
// Set the everything
searchData.value = {
...defaultSearchData,
...searchData.value,
};
searchData.value.error = null;
const newData = compConfig.value.enableGroupedSearch
? response
: response?.data;
searchData.value.data = append // Data is getting merged
? compConfig.value.dataMergerMethod?.(
newData,
JSON.parse(JSON.stringify(searchData.value.data))
) ?? newData
: newData;
searchData.value.facets = response?.facets;
searchData.value.meta = response?.meta;
searchData.value.misc = response?.misc;
query.value.parameters = {
...parameters.value,
};
if (compConfig.value.enableGroupedSearch) {
// Group pagination
state.value.hasMoreItems = {};
searchData.value.pagination = response?.pagination;
if (!searchData.value.pagination) {
searchData.value.pagination = {};
}
response?.groups?.forEach((group) => {
if ("id" in group) {
searchData.value.pagination[group.id] = {
limit: group.limit || 0,
offset: group.offset || 0,
total: group.total || 0,
};
}
});
for (const key in searchData.value.pagination) {
const value = Object.assign(
{ limit: 0, offset: 0, total: 0 },
searchData.value.pagination[key]
);
searchData.value.pagination[key] = value;
internalPagination.value[key] = {
...value,
};
state.value.hasMoreItems[key] =
value.limit + value.offset < value.total;
}
} else {
// Ordinary pagination
searchData.value.pagination = Object.assign(
{ limit: 0, offset: 0, total: 0 },
response?.pagination
);
internalPagination.value.limit =
searchData.value.pagination.limit;
internalPagination.value.offset =
searchData.value.pagination.offset;
state.value.hasMoreItems =
searchData.value.pagination.limit +
searchData.value.pagination.offset <
searchData.value.pagination.total;
}
state.value.isLoading = false;
}
};
// Run on client or server
if (typeof window !== "undefined" && delay > 0) {
await new Promise((resolve) => {
window.clearTimeout(requestTimeout.value);
requestTimeout.value = window.setTimeout(resolve, delay);
});
}
await searchRequest();
compConfig.value.onAfterSearch?.(
JSON.parse(JSON.stringify(searchData.value)),
JSON.parse(JSON.stringify(state.value))
);
}
function getSerializedParams(parameters = parameters.value) {
const array = [];
for (const key in parameters) {
const value = parameters[key];
const isPersistent =
compConfig.value?.persistentParameters?.includes?.(key);
if (Array.isArray(value)) {
const item = parameters?.find?.((item) => item.value === value);
if ((item && item.value) || isPersistent) {
array.push(`${key}=${item?.value}`);
}
} else if (
value ||
/* eslint-disable-next-line */
(key in (compConfig.value.defaultParameterValues || {}) &&
value != compConfig.value.defaultParameterValues?.[key]) ||
isPersistent
) {
array.push(`${key}=${value ?? ""}`);
}
}
return array.join("&");
}
function resetPagination() {
if (!internalPagination.value) {
internalPagination.value = {};
}
if (compConfig.value.enableGroupedSearch) {
// Grouped pagination
for (const key in compConfig.value.limit) {
if (key === String(parseInt(key))) {
const value = internalPagination.value[key] || {};
internalPagination.value[key] = value;
}
}
for (const key in internalPagination.value) {
const value = internalPagination.value[key];
value.limit =
(compConfig.value.limit[key]?.initial ??
compConfig.value.limit[key]?.value ??
compConfig.value.limit[key]) ||
defaultLimit;
value.offset = 0;
}
} else {
// Ordinary pagination
internalPagination.value.limit =
(compConfig.value.limit?.initial ??
compConfig.value.limit?.value ??
compConfig.value.limit) ||
defaultLimit;
internalPagination.value.offset = 0;
}
}
const router = useRouter();
function setUrlQuery(query = getSerializedParams(), clearHash = false) {
const array = query.split("&").filter((item) => {
const key = item.split("=").shift();
let value = item.split("=").pop();
// TODO: implement urlFilterMapping
if (
key === compConfig.value.groupParameter &&
hideGroupsParameter.value
) {
return false;
}
const initialLimit =
(compConfig.value.limit?.initial ??
compConfig.value.limit?.value ??
compConfig.value.limit) ||
defaultLimit;
const defaultParameterValues = {
limit: initialLimit,
offset: 0,
...compConfig.value.defaultParameterValues,
};
if (!(key in defaultParameterValues)) {
if (key === `l${String(parseInt(key.substring(1)))}`) {
const id = key.substring(1);
defaultParameterValues[`l${id}`] =
(compConfig.value.limit[id]?.initial ??
compConfig.value.limit[id]?.value ??
compConfig.value.limit[id]) ||
defaultLimit;
}
if (key === `o${String(parseInt(key.substring(1)))}`) {
defaultParameterValues[key] = 0;
}
}
if (
key in defaultParameterValues &&
String(defaultParameterValues[key]) === (value ?? "")
) {
return false;
}
return !compConfig.value.hiddenParameters?.includes?.(key);
});
const transformedArray = array.map((item) => {
const key = item.split("=").shift();
let value = item.split("=").pop();
if (key in compConfig.value.urlFilterMapping) {
const mappedKey = compConfig.value.urlFilterMapping[key];
if (value in mappedKey) {
value = mappedKey[value];
}
}
return `${key}=${value}`;
});
const url =
[route.path, transformedArray.join("&")].filter(Boolean).join("?") +
(clearHash
? ""
: typeof window !== "undefined"
? window.location.hash
: route.hash);
const oldUrl =
typeof window === "undefined"
? route.fullPath
: [
window.location.pathname,
window.location.search,
window.location.hash,
]
.filter(Boolean)
.join("");
typeof window !== "undefined" &&
compConfig.value.updateUrlQueryOnSearch &&
window.history.replaceState(window.history.state, "", url);
if (
compConfig.value.updateVueRouteOnSearch &&
decodeURIComponent(route.fullPath) !== decodeURIComponent(url)
) {
compConfig.value.updateVueRouteOnSearch?.pushHistory
? router.push(url)
: router.replace(url);
}
// Edge case, but might as well handle it
if (
typeof window !== "undefined" &&
compConfig.value.updateVueRouteOnSearch &&
compConfig.value.updateUrlQueryOnSearch
) {
window.history.replaceState(window.history.state, "", oldUrl);
}
}
// Check if initiated
if (!compConfig.value.immediateSearch) {
resetPagination();
state.value.isInitiated = true;
}
if (
compConfig.value.immediateSearch &&
(compConfig.value.immediateSearch?.ssr ||
typeof compConfig.value.immediateSearch === "boolean")
) {
resetPagination();
if (
compConfig.value.immediateSearch?.useUrlQuery ||
typeof compConfig.value.immediateSearch === "boolean"
) {
mixParametersFromUrl();
if (compConfig.value.enableGroupedSearch) {
// Grouped pagination
for (const key in internalPagination.value) {
const value = internalPagination.value[key];
if (value.limit) {
value.limit = +value.limit;
}
if (value.offset) {
value.limit = +value.limit + +value.offset;
value.offset = 0;
}
}
} else {
// Ordinary pagination
if (internalPagination.value.limit) {
internalPagination.value.limit =
+internalPagination.value.limit;
}
if (internalPagination.value.offset) {
internalPagination.value.limit =
+internalPagination.value.limit +
+internalPagination.value.offset;
internalPagination.value.offset = 0;
}
}
}
await requestSearch({ delay: 0 });
}
const limboSearch = reactive({
// Data
searchData,
compConfig,
state,
query,
lastRequestedUrl,
latestResponse,
watchedParameters,
// Methods
requestSearch,
fetchMore: compConfig.value.enableGroupedSearch
? fetchMoreGroup
: fetchMore,
fetchAll: compConfig.value.enableGroupedSearch
? fetchAllGroup
: fetchAll,
submit,
setUrlQuery,
resetPagination,
getSerializedParams,
});
compConfig.value.onInit?.(limboSearch);
return limboSearch;
// Internal helper functions
function removeReservedParameters(filters) {
const newFilters = { ...(filters || {}) };
if (filters?.fields && Array.isArray(filters.fields)) {
newFilters.fields = filters.fields.filter(
(field) =>
!reservedParameters.includes(field.name.toLowerCase())
);
}
return newFilters;
}
function convertToParameterStyledPagination(pagination) {
if (compConfig.value.enableGroupedSearch) {
const newPagination = {};
for (const key in pagination) {
const value = pagination[key];
if (typeof value?.limit !== "undefined") {
newPagination[`l${key}`] = value.limit;
}
if (typeof value?.offset !== "undefined") {
newPagination[`o${key}`] = value.offset;
}
}
return newPagination;
}
return pagination;
}
function setSearchFilterField(key, value) {
const { fields = [] } = filters.value || {};
const field = fields.find((field) => {
return field.name === key;
});
if (field) {
if (Array.isArray(field.value)) {
if (field.value.find((item) => item.value === value)) {
field.value.forEach((item) => {
item.checked = item.value === value;
});
}
} else {
field.value = value ?? "";
}
return true;
}
return false; // Return false if the field does not exist
}
function mixParametersFromUrl() {
const { query } = route;
for (const key in query) {
const value = query[key];
// Set key as pagination
if (compConfig.value.enableGroupedSearch) {
const array = key.toLowerCase().split("");
const firstLetter = array.shift();
const remainder = array.join("");
if (
(firstLetter === "o" || firstLetter === "l") &&
remainder === String(parseInt(remainder))
) {
const object = Object.assign(
{ limit: 0, offset: 0 },
internalPagination?.value?.[remainder]
);
if (firstLetter === "o") {
object.offset = parseInt(value);
}
if (firstLetter === "l") {
object.limit = parseInt(value);
}
internalPagination.value = Object.assign(
internalPagination.value,
{
[remainder]: object,
}
);
continue;
}
} else {
if (key.toLowerCase() === "limit") {
if (!internalPagination.value) {
internalPagination.value = {
limit: parseInt(value),
offset: 0,
};
continue;
}
internalPagination.value.limit = parseInt(value);
continue;
} else if (key.toLowerCase() === "offset") {
if (!internalPagination.value) {
internalPagination.value = {
limit: 0,
offset: parseInt(value),
};
continue;
}
internalPagination.value.offset = parseInt(value);
continue;
}
}
// Set key as search filter field
if (!setSearchFilterField(key, value)) {
// Set key as extra parameter
internalExtraParameters.value[key] = value;
}
}
}
};