aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files/src/store/active.ts
blob: 1303a157b081e4a7e705710742439dd891180485 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
 * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

import type { FileAction, View, Node, Folder } from '@nextcloud/files'

import { subscribe } from '@nextcloud/event-bus'
import { getNavigation } from '@nextcloud/files'
import { defineStore } from 'pinia'
import { ref } from 'vue'

import logger from '../logger.ts'

export const useActiveStore = defineStore('active', () => {
	/**
	 * The currently active action
	 */
	const activeAction = ref<FileAction>()

	/**
	 * The currently active folder
	 */
	const activeFolder = ref<Folder>()

	/**
	 * The current active node within the folder
	 */
	const activeNode = ref<Node>()

	/**
	 * The current active view
	 */
	const activeView = ref<View>()

	initialize()

	/**
	 * Unset the active node if deleted
	 *
	 * @param node - The node thats deleted
	 * @private
	 */
	function onDeletedNode(node: Node) {
		if (activeNode.value && activeNode.value.source === node.source) {
			activeNode.value = undefined
		}
	}

	/**
	 * Callback to update the current active view
	 *
	 * @param view - The new active view
	 * @private
	 */
	function onChangedView(view: View|null = null) {
		logger.debug('Setting active view', { view })
		activeView.value = view ?? undefined
		activeNode.value = undefined
	}

	/**
	 * Initalize the store - connect all event listeners.
	 * @private
	 */
	function initialize() {
		const navigation = getNavigation()

		// Make sure we only register the listeners once
		subscribe('files:node:deleted', onDeletedNode)

		onChangedView(navigation.active)

		// Or you can react to changes of the current active view
		navigation.addEventListener('updateActive', (event) => {
			onChangedView(event.detail)
		})
	}

	return {
		activeAction,
		activeFolder,
		activeNode,
		activeView,
	}
})