| 123 | } |
| 124 | |
| 125 | function reducer<T, C>(data: AsyncListState<T, C>, action: Action<T, C>): AsyncListState<T, C> { |
| 126 | let selectedKeys; |
| 127 | switch (data.state) { |
| 128 | case 'idle': |
| 129 | case 'error': |
| 130 | switch (action.type) { |
| 131 | case 'loading': |
| 132 | case 'loadingMore': |
| 133 | case 'sorting': |
| 134 | case 'filtering': |
| 135 | return { |
| 136 | ...data, |
| 137 | filterText: action.filterText ?? data.filterText, |
| 138 | state: action.type, |
| 139 | // Reset items to an empty list if loading, but not when sorting. |
| 140 | items: action.type === 'loading' ? [] : data.items, |
| 141 | sortDescriptor: action.sortDescriptor ?? data.sortDescriptor, |
| 142 | abortController: action.abortController |
| 143 | }; |
| 144 | case 'update': |
| 145 | return { |
| 146 | ...data, |
| 147 | ...action.updater?.(data) |
| 148 | }; |
| 149 | case 'success': |
| 150 | case 'error': |
| 151 | return data; |
| 152 | default: |
| 153 | throw new Error(`Invalid action "${action.type}" in state "${data.state}"`); |
| 154 | } |
| 155 | case 'loading': |
| 156 | case 'sorting': |
| 157 | case 'filtering': |
| 158 | switch (action.type) { |
| 159 | case 'success': |
| 160 | // Ignore if there is a newer abortcontroller in state. |
| 161 | // This means that multiple requests were going at once. |
| 162 | // We want to take only the latest result. |
| 163 | if (action.abortController !== data.abortController) { |
| 164 | return data; |
| 165 | } |
| 166 | |
| 167 | selectedKeys = action.selectedKeys ?? data.selectedKeys; |
| 168 | return { |
| 169 | ...data, |
| 170 | filterText: action.filterText ?? data.filterText, |
| 171 | state: 'idle', |
| 172 | items: [...(action.items ?? [])], |
| 173 | selectedKeys: selectedKeys === 'all' ? 'all' : new Set(selectedKeys), |
| 174 | sortDescriptor: action.sortDescriptor ?? data.sortDescriptor, |
| 175 | abortController: undefined, |
| 176 | cursor: action.cursor |
| 177 | }; |
| 178 | case 'error': |
| 179 | if (action.abortController !== data.abortController) { |
| 180 | return data; |
| 181 | } |
| 182 | |