actions.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. type BoundActionList = {
  29. // eslint-disable-next-line no-unused-vars
  30. [_ in HoppAction]?: Array<() => void>
  31. }
  32. const boundActions: BoundActionList = {}
  33. export const activeActions$ = new BehaviorSubject<HoppAction[]>([])
  34. export function bindAction(action: HoppAction, handler: () => void) {
  35. if (boundActions[action]) {
  36. boundActions[action]?.push(handler)
  37. } else {
  38. boundActions[action] = [handler]
  39. }
  40. activeActions$.next(Object.keys(boundActions) as HoppAction[])
  41. }
  42. export function invokeAction(action: HoppAction) {
  43. boundActions[action]?.forEach((handler) => handler())
  44. }
  45. export function unbindAction(action: HoppAction, handler: () => void) {
  46. boundActions[action] = boundActions[action]?.filter((x) => x !== handler)
  47. if (boundActions[action]?.length === 0) {
  48. delete boundActions[action]
  49. }
  50. activeActions$.next(Object.keys(boundActions) as HoppAction[])
  51. }
  52. export function defineActionHandler(action: HoppAction, handler: () => void) {
  53. onMounted(() => {
  54. bindAction(action, handler)
  55. })
  56. onBeforeUnmount(() => {
  57. unbindAction(action, handler)
  58. })
  59. }