v-sistec-features 1.27.2 → 1.29.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "v-sistec-features",
3
3
  "private": false,
4
- "version": "1.27.2",
4
+ "version": "1.29.0",
5
5
  "author": "Márlon Bento Azevedo (https://github.com/marlon-bento)",
6
6
  "repository": {
7
7
  "type": "git",
@@ -54,7 +54,6 @@ interface SearchProps {
54
54
  placeholder_search?: string;
55
55
  deactivate_search_on_clear?: boolean;
56
56
  deactivate_search_empty?: boolean;
57
-
58
57
  }
59
58
  const props = withDefaults(defineProps<SearchProps>(), {
60
59
  filter: "",
@@ -245,7 +245,7 @@
245
245
 
246
246
  <script setup lang="ts" generic="T extends Record<string, any>">
247
247
  import type { VDataTableProps, ExposedFunctions, PaginationObject } from '../types/v-data-table.ts';
248
- import { readonly, ref, provide, computed, watch, nextTick, onMounted } from 'vue';
248
+ import { readonly, ref, provide, computed, nextTick, onMounted } from 'vue';
249
249
  import PaginationDatatable from '@/Pagination/Pagination.vue';
250
250
  import Search from './SearchDatatable.vue';
251
251
  import VColumnManager from './VColumnManager.vue';
@@ -291,7 +291,7 @@ const emit = defineEmits(['tradePage', 'beforeFetch', 'afterFetch', 'clickedClea
291
291
 
292
292
  const orderings_state = ref<Record<string, 'none' | 'increasing' | 'decreasing'>>({});
293
293
  const columns = ref<ColumnConfiguration[]>([]);
294
- const totalItems = ref<number>(0);
294
+
295
295
 
296
296
 
297
297
 
@@ -322,10 +322,10 @@ const {
322
322
  );
323
323
 
324
324
  const {
325
- items, error, response, attempt, default_params,
325
+ items, error, attempt, default_params,
326
326
  fetchDataWithDelay, reSearch,
327
327
  showLoadingState, first_fetch
328
- } = useDataTableFetch<T>(options.value, pagination, columns, orderings_state, emit, close_all_expanded_items);
328
+ } = useDataTableFetch<T>(options, pagination, columns, orderings_state, emit, close_all_expanded_items);
329
329
 
330
330
 
331
331
  const {
@@ -492,16 +492,7 @@ const hasItems = computed(() => {
492
492
 
493
493
 
494
494
 
495
- watch(response, (newResponse: any) => {
496
- if (newResponse) {
497
- items.value = newResponse[options.value.data_key] || [];
498
- totalItems.value = newResponse[options.value.total_key] || 0;
499
- pagination.value.count = totalItems.value;
500
- } else {
501
- items.value = [];
502
- totalItems.value = 0;
503
- }
504
- }, { immediate: true });
495
+
505
496
 
506
497
 
507
498
  // =======================================================
@@ -677,33 +668,8 @@ onMounted(() => {
677
668
  });
678
669
  });
679
670
 
680
- watch(
681
- () => {
682
- const params = typeof options.value.add_params === 'function'
683
- ? options.value.add_params()
684
- : options.value.add_params;
685
- return JSON.stringify(params);
686
- },
687
- (newVal, oldVal) => {
688
- if (newVal !== oldVal && oldVal !== undefined) {
689
- reSearch();
690
- }
691
- }
692
- );
693
- /*
694
- ========
695
- Observa mudanças no endpoint.
696
- Caso a rota da API mude dinamicamente, ele reseta a tabela para a página inicial com segurança.
697
- ========
698
- */
699
- watch(
700
- () => options.value.endpoint,
701
- (newVal, oldVal) => {
702
- if (newVal !== oldVal && oldVal !== undefined) {
703
- pagination.value.current_page = options.value.page_starts_at;
704
- }
705
- }
706
- );
671
+
672
+
707
673
  </script>
708
674
 
709
675
  <style lang="scss" scoped>
@@ -1,10 +1,11 @@
1
- import { ref, computed, type Ref } from 'vue';
1
+ import { ref, computed, type Ref, watch, unref } from 'vue';
2
2
  import type { PaginationObject, DataTablePropsWithDefaults } from '../types/v-data-table'; // Ajuste o caminho conforme necessário
3
3
  import { type ColumnConfiguration } from '../keys';
4
4
 
5
5
 
6
- export function useDataTableFetch<T>(
7
- props: DataTablePropsWithDefaults,
6
+ export function useDataTableFetch<T extends Record<string, any>>(
7
+ /* para manter a reatividade a prop agora precisa usar unref*/
8
+ props: Ref<DataTablePropsWithDefaults>,
8
9
  pagination: Ref<PaginationObject>,
9
10
  columns: Ref<ColumnConfiguration[]>,
10
11
  orderings_state: Ref<Record<string, 'none' | 'increasing' | 'decreasing'>>,
@@ -12,17 +13,21 @@ export function useDataTableFetch<T>(
12
13
  close_all_expanded_items: () => void
13
14
 
14
15
  ) {
15
- const items = ref<T[]>([]) as Ref<T[]>;
16
+ // Estado para armazenar o retorno bruto da API
17
+ const raw_items = ref<T[]>([]) as Ref<T[]>;
16
18
 
19
+
20
+ const propsValue = computed(() => unref(props));
17
21
  const urlReativa = computed(() => {
18
- return props.endpoint;
22
+ return propsValue.value.endpoint;
19
23
  });
20
-
24
+
25
+
21
26
  const default_params = computed<Record<string, any>>(() => ({
22
- [props.page_param_name]: pagination.value.current_page + 1,
23
- [props.page_size_param_name]: pagination.value.limit_per_page,
24
- [props.search_param_name]: pagination.value.search || "",
25
- [props.filter_param_name]: pagination.value.filter || "",
27
+ [propsValue.value.page_param_name]: pagination.value.current_page + 1,
28
+ [propsValue.value.page_size_param_name]: pagination.value.limit_per_page,
29
+ [propsValue.value.search_param_name]: pagination.value.search || "",
30
+ [propsValue.value.filter_param_name]: pagination.value.filter || "",
26
31
  }));
27
32
 
28
33
  const params_ordering = computed(() => {
@@ -33,53 +38,130 @@ export function useDataTableFetch<T>(
33
38
  objectOrdering[col.param_ordering] = col.increasing_value || 'increasing';
34
39
  } else if (orderings_state.value[col.id] === 'decreasing') {
35
40
  objectOrdering[col.param_ordering] = col.decreasing_value || 'decreasing';
36
- }
37
- }
41
+ }
42
+ }
38
43
  }
39
44
 
40
45
  return objectOrdering;
41
46
  });
42
- const { data: response, pending, error, execute, attempt } = props.fetch(urlReativa, {
43
- disable_request: () => props.disable_request,
47
+ const { data: response, pending, error, execute, attempt } = propsValue.value.fetch(urlReativa, {
48
+ disable_request: () => propsValue.value.disable_request,
44
49
  params: () => {
45
- const isFunction = typeof props.add_params === 'function';
46
- let extraParams = {};
50
+ /*add_params*/
51
+ const addParamsIsFunction = typeof propsValue.value.add_params === 'function';
52
+ let extraAddParams = {};
53
+ /*silent_params*/
54
+ const silentParamsIsFunction = typeof propsValue.value.silent_params === 'function';
55
+ let extraSilentParams = {};
56
+ /*add_params_keep_page*/
57
+ const addParamsKeepPageIsFunction = typeof propsValue.value.add_params_keep_page === 'function';
58
+ let extraAddParamsKeepPage = {};
59
+
60
+
61
+
47
62
 
48
- if (isFunction) {
49
- const getParams = props.add_params as () => Record<string, any>;
50
- extraParams = getParams();
63
+ if (addParamsIsFunction) {
64
+ const getParams = propsValue.value.add_params as () => Record<string, any>;
65
+ extraAddParams = getParams();
51
66
  } else {
52
- extraParams = props.add_params || {};
67
+ extraAddParams = propsValue.value.add_params || {};
53
68
  }
54
- if (props.deactivate_default_params) {
69
+
70
+ if (silentParamsIsFunction) {
71
+ const getParams = propsValue.value.silent_params as () => Record<string, any>;
72
+ extraSilentParams = getParams();
73
+ } else {
74
+ extraSilentParams = propsValue.value.silent_params || {};
75
+ }
76
+
77
+ if (addParamsKeepPageIsFunction) {
78
+ const getParams = propsValue.value.add_params_keep_page as () => Record<string, any>;
79
+ extraAddParamsKeepPage = getParams();
80
+ } else {
81
+ extraAddParamsKeepPage = propsValue.value.add_params_keep_page || {};
82
+ }
83
+
84
+
85
+ if (propsValue.value.deactivate_default_params) {
55
86
  return {
56
- ...extraParams,
87
+ ...extraAddParams,
88
+ ...extraSilentParams,
89
+ ...extraAddParamsKeepPage,
57
90
  ...params_ordering.value
58
91
  };
59
92
  }
60
93
  return {
61
94
  ...default_params.value,
62
- ...props.add_params,
95
+ ...extraAddParams,
96
+ ...extraSilentParams,
97
+ ...extraAddParamsKeepPage,
63
98
  ...params_ordering.value
64
99
  };
65
100
  },
66
- retry: props.retry_attempts,
67
- retryDelay: props.retry_delay,
101
+ retry: propsValue.value.retry_attempts,
102
+ retryDelay: propsValue.value.retry_delay,
68
103
  paramsReactives: false,
69
104
  immediate: false,
70
- }, props.fetch_name);
105
+ }, propsValue.value.fetch_name);
106
+
107
+ const filtered_items = computed<T[]>(() => {
108
+ if (!propsValue.value.frontend_pagination) {
109
+ return raw_items.value;
110
+ }
111
+
112
+ let filtered = raw_items.value;
113
+ const customFilterFn = propsValue.value.custom_frontend_filter;
114
+
115
+ if (customFilterFn && typeof customFilterFn === 'function') {
116
+ filtered = filtered.filter(item =>
117
+ customFilterFn(item, pagination.value.search, pagination.value.filter)
118
+ );
119
+ } else if (pagination.value.search) {
120
+ const searchLower = pagination.value.search.toLowerCase();
121
+ filtered = filtered.filter(item => {
122
+ return Object.values(item).some(val =>
123
+ val !== null && val !== undefined && String(val).toLowerCase().includes(searchLower)
124
+ );
125
+ });
126
+ }
127
+
128
+ return filtered;
129
+ });
130
+
131
+ watch(filtered_items, (newVal) => {
132
+ if (propsValue.value.frontend_pagination) {
133
+ pagination.value.count = newVal.length;
134
+
135
+ const maxPage = Math.ceil(newVal.length / pagination.value.limit_per_page) - 1;
136
+ if (pagination.value.current_page > maxPage && maxPage >= 0) {
137
+ pagination.value.current_page = maxPage;
138
+ }
139
+ }
140
+ }, { immediate: true });
141
+
142
+ const items = computed<T[]>(() => {
143
+ if (!propsValue.value.frontend_pagination) {
144
+ return raw_items.value;
145
+ }
146
+
147
+ const start = pagination.value.current_page * pagination.value.limit_per_page;
148
+ const end = start + pagination.value.limit_per_page;
149
+
150
+ return filtered_items.value.slice(start, end);
151
+ });
71
152
 
72
153
  const isDelaying = ref<boolean>(false);
73
154
  const delayTimer = ref<ReturnType<typeof setTimeout> | null>(null);
74
155
  const first_fetch = ref<boolean>(false);
75
156
  // para controlar a exibição do loading
76
157
  const showLoadingState = computed<boolean>(() => {
77
- return (pending.value || isDelaying.value)
158
+ return (pending.value || isDelaying.value)
78
159
  });
79
160
  // Função que gerencia o delay e a chamada da API
80
161
  async function fetchDataWithDelay(): Promise<void> {
81
162
  // agora já fez pelo menos a primeira busca então marca como true
82
163
  if (!first_fetch.value) first_fetch.value = true;
164
+
83
165
  // Limpa timer anterior, se houver
84
166
  if (delayTimer.value) clearTimeout(delayTimer.value);
85
167
 
@@ -87,17 +169,89 @@ export function useDataTableFetch<T>(
87
169
 
88
170
  delayTimer.value = setTimeout(() => {
89
171
  isDelaying.value = false;
90
- }, props.min_loading_delay);
172
+ }, propsValue.value.min_loading_delay);
173
+
91
174
  close_all_expanded_items();
92
175
  emit('beforeFetch');
93
- await execute(); // Executa a busca de dados original do useApiFetch
176
+ if (!propsValue.value.frontend_pagination || raw_items.value.length === 0) {
177
+ await execute(); // Executa a busca de dados original do useApiFetch
178
+ }
179
+
94
180
  emit('afterFetch');
95
181
  }
96
182
 
97
183
  function reSearch(): void {
98
- pagination.value.current_page = props.page_starts_at;
184
+ pagination.value.current_page = propsValue.value.page_starts_at;
185
+
99
186
  fetchDataWithDelay();
100
187
  }
188
+
189
+
190
+ watch(response, (newResponse: any) => {
191
+ if (newResponse) {
192
+ let fetchedData = [];
193
+
194
+ // Aceitação de dados direto da raiz do objeto quando data_key for string vazia
195
+ if (!propsValue.value.data_key) {
196
+ fetchedData = Array.isArray(newResponse) ? newResponse : [newResponse];
197
+ } else {
198
+ fetchedData = newResponse[propsValue.value.data_key] || [];
199
+ }
200
+
201
+ raw_items.value = fetchedData;
202
+
203
+ // O count é operado pelo frontend se a prop estiver ativa
204
+ if (!propsValue.value.frontend_pagination) {
205
+ pagination.value.count = newResponse[propsValue.value.total_key] || 0;
206
+ }
207
+
208
+ } else {
209
+ raw_items.value = [];
210
+ pagination.value.count = 0;
211
+ }
212
+ }, { immediate: true });
213
+
214
+ watch(
215
+ () => {
216
+ const params = typeof propsValue.value.add_params === 'function'
217
+ ? propsValue.value.add_params()
218
+ : propsValue.value.add_params;
219
+ return JSON.stringify(params);
220
+ },
221
+ (newVal, oldVal) => {
222
+ if (newVal !== oldVal && oldVal !== undefined) {
223
+ reSearch();
224
+ }
225
+ }
226
+ );
227
+ watch(
228
+ () => {
229
+ const params = typeof propsValue.value.add_params_keep_page === 'function'
230
+ ? propsValue.value.add_params_keep_page()
231
+ : propsValue.value.add_params_keep_page;
232
+ return JSON.stringify(params);
233
+ },
234
+ (newVal, oldVal) => {
235
+ if (newVal !== oldVal && oldVal !== undefined) {
236
+ fetchDataWithDelay();
237
+ }
238
+ }
239
+ );
240
+
241
+ /*
242
+ ========
243
+ Observa mudanças no endpoint.
244
+ Caso a rota da API mude dinamicamente, ele reseta a tabela para a página inicial com segurança.
245
+ ========
246
+ */
247
+ watch(
248
+ () => propsValue.value.endpoint,
249
+ (newVal, oldVal) => {
250
+ if (newVal !== oldVal && oldVal !== undefined) {
251
+ pagination.value.current_page = propsValue.value.page_starts_at;
252
+ }
253
+ }
254
+ );
101
255
  return {
102
256
  items,
103
257
  pending,
@@ -11,8 +11,11 @@ export const defaultDataTableConfig: DataTableGlobalConfig = {
11
11
  fetch_name: '',
12
12
  custom_loading: null,
13
13
  deactivate_default_params: false,
14
-
14
+ frontend_pagination: false,
15
15
  add_params: {},
16
+ add_params_keep_page: {},
17
+ silent_params: {},
18
+
16
19
  list_filter: [],
17
20
 
18
21
  use_checkbox: false,
@@ -72,4 +75,6 @@ export const defaultDataTableConfig: DataTableGlobalConfig = {
72
75
  show_header_when_empty: false,
73
76
  storage_id: '',
74
77
  use_column_manager: false,
78
+
79
+ custom_frontend_filter: null,
75
80
  };
@@ -21,7 +21,23 @@ export interface ApiProps {
21
21
  search_param_name?: string;
22
22
  page_param_name?: string;
23
23
  page_size_param_name?: string;
24
+ /*
25
+ Parâmetros reativos: dispara um novo fetch e reseta a tabela para a página 1 sempre que sofrer mutação.
26
+ Ideal para buscas e filtros primários.
27
+ */
24
28
  add_params?: Record<string, any> | (() => Record<string, any>);
29
+
30
+ /*
31
+ Parâmetros de recarregamento suave: dispara um novo fetch quando alterados, mas NÃO reseta a página atual.
32
+ Ideal para ordenação externa ou filtros que não devem interromper a navegação.
33
+ */
34
+ add_params_keep_page?: Record<string, any> | (() => Record<string, any>);
35
+
36
+ /*
37
+ Parâmetros silenciosos: injeta dados na requisição sem disparar um fetch automático.
38
+ Ideal para injeção de paginação manual ou tokens.
39
+ */
40
+ silent_params?: Record<string, any> | (() => Record<string, any>);
25
41
  /* retira os params default da requisição */
26
42
  deactivate_default_params?: boolean;
27
43
  disable_request?: MaybeRefOrGetter<boolean>;
@@ -70,6 +86,7 @@ Tipagem para o comportamento principal.
70
86
  Por que é usada: Controla limites, tempos de carregamento, armazenamento de estado e identificadores.
71
87
  */
72
88
  export interface BehaviorProps {
89
+ frontend_pagination?: boolean;
73
90
  limit_per_page?: number;
74
91
  page_starts_at?: number;
75
92
  /*
@@ -108,6 +125,7 @@ export interface SearchProps {
108
125
  disable_search?: boolean;
109
126
  deactivate_search_empty?: boolean;
110
127
  deactivate_search_on_clear?: boolean;
128
+ custom_frontend_filter?: ((item: any, search: string, filter: string) => boolean) | null;
111
129
  }
112
130
  /*
113
131
  Tipagem para regras de paginação.
@@ -163,6 +181,8 @@ Tipagem consolidada de propriedades do VDataTable com valores padrão.
163
181
  Por que é usada: Fornece uma interface completa para o Vue, incluindo todas as propriedades obrigatórias e opcionais, com valores padrão definidos.
164
182
  */
165
183
  export type DataTablePropsWithDefaults = VDataTableProps & {
184
+ custom_frontend_filter: ((item: any, search: string, filter: string) => boolean) | null;
185
+ frontend_pagination: boolean;
166
186
  // Strings
167
187
  fetch_name: string;
168
188
  type_loading: string;