actions.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* An `action` is a unique verb that is associated with certain thing that can be done on Hoppscotch.
  2. * For example, sending a request.
  3. */
  4. import { onBeforeUnmount, onMounted } from "@nuxtjs/composition-api"
  5. import { BehaviorSubject } from "rxjs"
  6. export type HoppAction =
  7. | "request.send-cancel" // Send/Cancel a Hoppscotch Request
  8. | "request.reset" // Clear request data
  9. | "request.copy-link" // Copy Request Link
  10. | "request.save" // Save to Collections
  11. | "request.save-as" // Save As
  12. | "request.method.next" // Select Next Method
  13. | "request.method.prev" // Select Previous Method
  14. | "request.method.get" // Select GET Method
  15. | "request.method.head" // Select HEAD Method
  16. | "request.method.post" // Select POST Method
  17. | "request.method.put" // Select PUT Method
  18. | "request.method.delete" // Select DELETE Method
  19. | "flyouts.keybinds.toggle" // Shows the keybinds flyout
  20. | "modals.search.toggle" // Shows the search modal
  21. | "modals.support.toggle" // Shows the support modal
  22. | "modals.share.toggle" // Shows the share modal
  23. | "navigation.jump.rest" // Jump to REST page
  24. | "navigation.jump.graphql" // Jump to GraphQL page
  25. | "navigation.jump.realtime" // Jump to realtime page
  26. | "navigation.jump.documentation" // Jump to documentation page
  27. | "navigation.jump.settings" // Jump to settings page
  28. | "navigation.jump.back" // Jump to previous page
  29. | "navigation.jump.forward" // Jump to next page
  30. type BoundActionList = {
  31. // eslint-disable-next-line no-unused-vars
  32. [_ in HoppAction]?: Array<() => void>
  33. }
  34. const boundActions: BoundActionList = {}
  35. export const activeActions$ = new BehaviorSubject<HoppAction[]>([])
  36. export function bindAction(action: HoppAction, handler: () => void) {
  37. if (boundActions[action]) {
  38. boundActions[action]?.push(handler)
  39. } else {
  40. boundActions[action] = [handler]
  41. }
  42. activeActions$.next(Object.keys(boundActions) as HoppAction[])
  43. }
  44. export function invokeAction(action: HoppAction) {
  45. boundActions[action]?.forEach((handler) => handler())
  46. }
  47. export function unbindAction(action: HoppAction, handler: () => void) {
  48. boundActions[action] = boundActions[action]?.filter((x) => x !== handler)
  49. if (boundActions[action]?.length === 0) {
  50. delete boundActions[action]
  51. }
  52. activeActions$.next(Object.keys(boundActions) as HoppAction[])
  53. }
  54. export function defineActionHandler(action: HoppAction, handler: () => void) {
  55. onMounted(() => {
  56. bindAction(action, handler)
  57. })
  58. onBeforeUnmount(() => {
  59. unbindAction(action, handler)
  60. })
  61. }