HistoryStoreExample.kt (2313B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 // This is example code for the 'Simplified Example' section of 6 // /docs/architecture-overview.md 7 class HistoryStore( 8 private val initialState: HistoryState, 9 private val middleware: List<Middleware<HistoryState, HistoryAction>> 10 ) : Store<HistoryState, Reducer<HistoryState, HistoryAction>>(initialState, middleware, ::reducer) { 11 init { 12 // This will ensure that middlewares can take any actions they need to during initialization 13 dispatch(HistoryAction.Init) 14 } 15 } 16 17 sealed class HistoryAction { 18 object Init : HistoryAction() 19 data class ItemsChanged(val items: List<History>) : HistoryAction() 20 data class DeleteItems(val items: List<History>) : HistoryAction() 21 data class DeleteFinished() : HistoryAction() 22 data class ToggleItemSelection(val item: History) : HistoryAction() 23 data class OpenItem(val item: History) : HistoryAction() 24 } 25 26 data class HistoryState( 27 val items: List<History>, 28 val selectedItems: List<History>, 29 val itemsBeingDeleted: List<History>, 30 companion object { 31 val initial = HistoryState( 32 items = listOf(), 33 selectedItems = listOf(), 34 itemsBeingDeleted = listOf(), 35 ) 36 } 37 ) { 38 val displayItems = items.filter { item -> 39 item !in itemsBeingDeleted 40 } 41 } 42 43 fun reducer(oldState: HistoryState, action: HistoryAction): HistoryState = when (action) { 44 is HistoryAction.ItemsChanged -> oldState.copy(items = action.items) 45 is HistoryAction.DeleteItems -> oldState.copy(itemsBeingDeleted = action.items) 46 is HistoryAction.DeleteFinished -> oldState.copy( 47 items = oldState.items - oldState.itemsBeingDeleted, 48 itemsBeingDeleted = listOf(), 49 ) 50 is HistoryAction.ToggleItemSelection -> { 51 if (oldState.selectedItems.contains(action.item)) { 52 oldState.copy(selectedItems = oldState.selectedItems - action.item) 53 } else { 54 oldState.copy(selectedItems = oldState.selectedItems + action.item) 55 } 56 } 57 else -> Unit 58 } 59 60 data class History( 61 val id: Int, 62 val title: String, 63 val url: Uri, 64 )