Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/entities/state_selectors.ts

raw
1 import type { CreateSelectorFunction, Selector } from 'reselect'
2 import { createDraftSafeSelector } from '../createDraftSafeSelector'
3 import type { EntityId, EntitySelectors, EntityState } from './models'
4
5 type AnyFunction = (...args: any) => any
6 type AnyCreateSelectorFunction = CreateSelectorFunction<
7 <F extends AnyFunction>(f: F) => F,
8 <F extends AnyFunction>(f: F) => F
9 >
10
11 export type GetSelectorsOptions = {
12 createSelector?: AnyCreateSelectorFunction
13 }
14
15 export function createSelectorsFactory<T, Id extends EntityId>() {
16 function getSelectors(
17 selectState?: undefined,
18 options?: GetSelectorsOptions,
19 ): EntitySelectors<T, EntityState<T, Id>, Id>
20 function getSelectors<V>(
21 selectState: (state: V) => EntityState<T, Id>,
22 options?: GetSelectorsOptions,
23 ): EntitySelectors<T, V, Id>
24 function getSelectors<V>(
25 selectState?: (state: V) => EntityState<T, Id>,
26 options: GetSelectorsOptions = {},
27 ): EntitySelectors<T, any, Id> {
28 const {
29 createSelector = createDraftSafeSelector as AnyCreateSelectorFunction,
30 } = options
31
32 const selectIds = (state: EntityState<T, Id>) => state.ids
33
34 const selectEntities = (state: EntityState<T, Id>) => state.entities
35
36 const selectAll = createSelector(
37 selectIds,
38 selectEntities,
39 (ids, entities): T[] => ids.map((id) => entities[id]!),
40 )
41
42 const selectId = (_: unknown, id: Id) => id
43
44 const selectById = (entities: Record<Id, T>, id: Id) => entities[id]
45
46 const selectTotal = createSelector(selectIds, (ids) => ids.length)
47
48 if (!selectState) {
49 return {
50 selectIds,
51 selectEntities,
52 selectAll,
53 selectTotal,
54 selectById: createSelector(selectEntities, selectId, selectById),
55 }
56 }
57
58 const selectGlobalizedEntities = createSelector(
59 selectState as Selector<V, EntityState<T, Id>>,
60 selectEntities,
61 )
62
63 return {
64 selectIds: createSelector(selectState, selectIds),
65 selectEntities: selectGlobalizedEntities,
66 selectAll: createSelector(selectState, selectAll),
67 selectTotal: createSelector(selectState, selectTotal),
68 selectById: createSelector(
69 selectGlobalizedEntities,
70 selectId,
71 selectById,
72 ),
73 }
74 }
75
76 return { getSelectors }
77 }