1import { useShortcut } from "@opendesk/shared/shortcuts";
2import { router } from "@/router";
3import { createResource } from "frappe-ui";
4import { ref } from "vue";
5
6export const currentTicketIndex = ref(0);
7
8export const ticketsToNavigate = createResource({
9 url: "opendesk.opendesk.doctype.od_ticket.api.get_navigation_tickets",
10 cache: ["ticketsToNavigate"],
11});
12
13// Module scope, not inside the composable: the command palette needs these too,
14// and calling the composable a second time would register duplicate shortcuts.
15
16export function goToNextTicket() {
17 const nextTicketId = getNextTicket();
18 if (!nextTicketId) return null;
19 currentTicketIndex.value += 1;
20 navigateToTicket(nextTicketId);
21 return nextTicketId;
22}
23
24export function goToPreviousTicket() {
25 const prevTicketId = getPreviousTicket();
26 if (!prevTicketId) return null;
27 currentTicketIndex.value -= 1;
28 navigateToTicket(prevTicketId);
29 return prevTicketId;
30}
31
32export function getCurrentTicket() {
33 return ticketsToNavigate.data[currentTicketIndex.value];
34}
35
36export function getNextTicket() {
37 if (!ticketsToNavigate.data) return null;
38 if (currentTicketIndex.value < ticketsToNavigate.data.length - 1) {
39 return ticketsToNavigate.data[currentTicketIndex.value + 1];
40 }
41 return null;
42}
43
44export function getPreviousTicket() {
45 if (!ticketsToNavigate.data) return null;
46 if (currentTicketIndex.value > 0) {
47 return ticketsToNavigate.data[currentTicketIndex.value - 1];
48 }
49 return null;
50}
51
52export function navigateToTicket(ticketId: string) {
53 const view = router.currentRoute.value.query.view as string;
54 const routeToNavigate: any = {
55 name: "TicketAgent",
56 params: { ticketId },
57 hash: "",
58 };
59 if (view) {
60 routeToNavigate["query"] = { view };
61 }
62 router.push(routeToNavigate);
63}
64
65/** True once the view has more than one ticket to move between. */
66export function canNavigateTickets() {
67 return !ticketsToNavigate.loading && ticketsToNavigate.data?.length > 1;
68}
69
70/**
71 * Shift + < / > to move through the current view's tickets. Listeners are
72 * registered per caller, so call this once per page (the ticket page).
73 */
74export function useTicketNavigation() {
75 useShortcut(
76 { key: ">", shift: true },
77 () => canNavigateTickets() && goToNextTicket()
78 );
79 useShortcut(
80 { key: "<", shift: true },
81 () => canNavigateTickets() && goToPreviousTicket()
82 );
83}
84