1+ import { Ref , ref , watch } from 'vue'
2+ import { PivotData } from '@/helper/utilities.js'
3+
4+ export interface UseMaterializeInputOptions {
5+ derivedAttributes : Ref < Record < string , ( record : Record < string , any > ) => any > >
6+ }
7+
8+ export interface UseMaterializeInputReturn {
9+ rawData : Ref < any >
10+ allFilters : Ref < Record < string , Record < string , number > > >
11+ materializedInput : Ref < any [ ] >
12+ processData : ( data : any ) => { AllFilters : Record < string , Record < string , number > > ; materializedInput : any [ ] } | void
13+ }
14+
15+ export function useMaterializeInput (
16+ dataSource : Ref < any > ,
17+ options : UseMaterializeInputOptions
18+ ) : UseMaterializeInputReturn {
19+ const rawData = ref < any > ( null )
20+ const allFilters = ref < Record < string , Record < string , number > > > ( { } )
21+ const materializedInput = ref < any [ ] > ( [ ] )
22+
23+ function processData ( data : any ) {
24+ if ( ! data || rawData . value === data ) return
25+
26+ rawData . value = data
27+ const newAllFilters : Record < string , Record < string , number > > = { }
28+ const newMaterializedInput : any [ ] = [ ]
29+
30+ let recordsProcessed = 0
31+
32+ PivotData . forEachRecord (
33+ data ,
34+ options . derivedAttributes . value ,
35+ function ( record : Record < string , any > ) {
36+ newMaterializedInput . push ( record )
37+
38+ for ( const attr of Object . keys ( record ) ) {
39+ if ( ! ( attr in newAllFilters ) ) {
40+ newAllFilters [ attr ] = { }
41+ if ( recordsProcessed > 0 ) {
42+ newAllFilters [ attr ] . null = recordsProcessed
43+ }
44+ }
45+ }
46+
47+ for ( const attr in newAllFilters ) {
48+ const value = attr in record ? record [ attr ] : 'null'
49+ if ( ! ( value in newAllFilters [ attr ] ) ) {
50+ newAllFilters [ attr ] [ value ] = 0
51+ }
52+ newAllFilters [ attr ] [ value ] ++
53+ }
54+
55+ recordsProcessed ++
56+ }
57+ )
58+
59+ allFilters . value = newAllFilters
60+ materializedInput . value = newMaterializedInput
61+
62+ return {
63+ AllFilters : newAllFilters ,
64+ materializedInput : newMaterializedInput
65+ }
66+ }
67+
68+ watch ( ( ) => dataSource . value , processData , { immediate : true } )
69+
70+ watch (
71+ ( ) => options . derivedAttributes . value ,
72+ ( ) => {
73+ processData ( dataSource . value )
74+ }
75+ )
76+
77+ return {
78+ rawData,
79+ allFilters,
80+ materializedInput,
81+ processData
82+ }
83+ }
0 commit comments