import { CategoryKey } from '../../../../common/category' ; import { map } from '../../../../common/iterables' ; import { LegendItem } from '../../../../common/legend' ; import { LegendPositionConfig } from '../../../../specs/settings' ; import { isHierarchicalLegend } from '../../../../utils/legend' ; import { Layer } from '../../specs' ; import { PartitionLayout } from '../types/config_types' ; import { QuadViewModel } from '../types/viewmodel_types' ; function makeKey ( ... keyParts ) { return keyParts . join ( '---' ) ; } function compareTreePaths ( { index : oiA , innerIndex : iiA , path : a } , { index : oiB , innerIndex : iiB , path : b } ) { if ( oiA !== oiB ) return oiA - oiB ; if ( iiA !== iiB ) return iiA - iiB ; for ( let i = 0 ; i < Math . min ( a . length , b . length ) ; i ++ ) { const diff = a [ i ] . index - b [ i ] . index ; if ( diff ) { return diff ; } } return a . length - b . length ; } internal export function getLegendItems ( id , layers , flatLegend , legendMaxDepth , legendPosition , quadViewModel , partitionLayout ) { const uniqueNames = new Set ( map ( ( { dataName , fillColor } ) => makeKey ( dataName , fillColor ) , quadViewModel ) ) ; const useHierarchicalLegend = isHierarchicalLegend ( flatLegend , legendPosition ) ; const formattedLabel = ( { dataName , depth } ) => { const formatter = layers [ depth - 1 ] ?. nodeLabel ; return formatter ? formatter ( dataName ) : dataName ; } ; function compareNames ( aItem , bItem ) { const a = formattedLabel ( aItem ) ; const b = formattedLabel ( bItem ) ; return a < b ? - 1 : a > b ? 1 : 0 ; } function descendingValues ( aItem , bItem ) { return aItem . depth - bItem . depth || bItem . value - aItem . value ; } const excluded = new Set ( ) ; const items = quadViewModel . filter ( ( { depth , dataName , fillColor } ) => { if ( legendMaxDepth !== null && depth > legendMaxDepth ) { return false ; } if ( ! useHierarchicalLegend ) { const key = makeKey ( dataName , fillColor ) ; if ( uniqueNames . has ( key ) && excluded . has ( key ) ) { return false ; } excluded . add ( key ) ; } return true ; } ) ; items . sort ( partitionLayout === PartitionLayout . waffle ? descendingValues : flatLegend ? compareNames : compareTreePaths ) ; return items . map < LegendItem > ( ( item ) => { const { dataName , fillColor , depth , path } = item ; return { color : fillColor , label : formattedLabel ( item ) , childId : dataName , depth : useHierarchicalLegend ? depth - 1 : 0 , path , seriesIdentifiers : [ { key : dataName , specId : id } ] , keys : [ ] , } ; } ) ; }