Socketio.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. <template>
  2. <Splitpanes
  3. class="smart-splitter"
  4. :rtl="SIDEBAR_ON_LEFT && windowInnerWidth.x.value >= 768"
  5. :class="{
  6. '!flex-row-reverse': SIDEBAR_ON_LEFT && windowInnerWidth.x.value >= 768,
  7. }"
  8. :horizontal="!(windowInnerWidth.x.value >= 768)"
  9. >
  10. <Pane size="75" min-size="65" class="hide-scrollbar !overflow-auto">
  11. <Splitpanes class="smart-splitter" :horizontal="COLUMN_LAYOUT">
  12. <Pane class="hide-scrollbar !overflow-auto">
  13. <AppSection label="request">
  14. <div class="bg-primary flex p-4 top-0 z-10 sticky">
  15. <div class="space-x-2 flex-1 inline-flex">
  16. <div class="flex flex-1">
  17. <label for="client-version">
  18. <tippy
  19. ref="versionOptions"
  20. interactive
  21. trigger="click"
  22. theme="popover"
  23. arrow
  24. >
  25. <template #trigger>
  26. <span class="select-wrapper">
  27. <input
  28. id="client-version"
  29. v-tippy="{ theme: 'tooltip' }"
  30. title="socket.io-client version"
  31. class="
  32. bg-primaryLight
  33. border border-divider
  34. rounded-l
  35. cursor-pointer
  36. flex
  37. font-semibold
  38. text-secondaryDark
  39. py-2
  40. px-4
  41. w-26
  42. hover:border-dividerDark
  43. focus-visible:bg-transparent
  44. focus-visible:border-dividerDark
  45. "
  46. :value="`Client ${clientVersion}`"
  47. readonly
  48. :disabled="connectionState"
  49. />
  50. </span>
  51. </template>
  52. <SmartItem
  53. v-for="(_, version) in socketIoClients"
  54. :key="`client-${version}`"
  55. :label="`Client ${version}`"
  56. @click.native="onSelectVersion(version)"
  57. />
  58. </tippy>
  59. </label>
  60. <input
  61. id="socketio-url"
  62. v-model="url"
  63. type="url"
  64. autocomplete="off"
  65. spellcheck="false"
  66. :class="{ error: !urlValid }"
  67. class="
  68. bg-primaryLight
  69. border border-divider
  70. flex flex-1
  71. text-secondaryDark
  72. w-full
  73. py-2
  74. px-4
  75. hover:border-dividerDark
  76. focus-visible:bg-transparent
  77. focus-visible:border-dividerDark
  78. "
  79. :placeholder="$t('socketio.url')"
  80. :disabled="connectionState"
  81. @keyup.enter="urlValid ? toggleConnection() : null"
  82. />
  83. <input
  84. id="socketio-path"
  85. v-model="path"
  86. class="
  87. bg-primaryLight
  88. border border-divider
  89. rounded-r
  90. flex flex-1
  91. text-secondaryDark
  92. w-full
  93. py-2
  94. px-4
  95. hover:border-dividerDark
  96. focus-visible:bg-transparent
  97. focus-visible:border-dividerDark
  98. "
  99. spellcheck="false"
  100. :disabled="connectionState"
  101. @keyup.enter="urlValid ? toggleConnection() : null"
  102. />
  103. </div>
  104. <ButtonPrimary
  105. id="connect"
  106. :disabled="!urlValid"
  107. name="connect"
  108. class="w-32"
  109. :label="
  110. !connectionState
  111. ? $t('action.connect')
  112. : $t('action.disconnect')
  113. "
  114. :loading="connectingState"
  115. @click.native="toggleConnection"
  116. />
  117. </div>
  118. </div>
  119. </AppSection>
  120. </Pane>
  121. <Pane class="hide-scrollbar !overflow-auto">
  122. <AppSection label="response">
  123. <RealtimeLog :title="$t('socketio.log')" :log="communication.log" />
  124. </AppSection>
  125. </Pane>
  126. </Splitpanes>
  127. </Pane>
  128. <Pane
  129. v-if="SIDEBAR"
  130. size="25"
  131. min-size="20"
  132. class="hide-scrollbar !overflow-auto"
  133. >
  134. <AppSection label="messages">
  135. <div class="flex flex-col flex-1 p-4 inline-flex">
  136. <label for="events" class="font-semibold text-secondaryLight">
  137. {{ $t("socketio.events") }}
  138. </label>
  139. </div>
  140. <div class="flex px-4">
  141. <input
  142. id="event_name"
  143. v-model="communication.eventName"
  144. class="input"
  145. name="event_name"
  146. :placeholder="$t('socketio.event_name')"
  147. type="text"
  148. autocomplete="off"
  149. :disabled="!connectionState"
  150. />
  151. </div>
  152. <div class="flex flex-1 p-4 items-center justify-between">
  153. <label class="font-semibold text-secondaryLight">
  154. {{ $t("socketio.communication") }}
  155. </label>
  156. <div class="flex">
  157. <ButtonSecondary
  158. v-tippy="{ theme: 'tooltip' }"
  159. :title="$t('add.new')"
  160. svg="plus"
  161. class="rounded"
  162. @click.native="addCommunicationInput"
  163. />
  164. </div>
  165. </div>
  166. <div class="flex flex-col space-y-2 px-4 pb-4">
  167. <div
  168. v-for="(input, index) of communication.inputs"
  169. :key="`input-${index}`"
  170. >
  171. <div class="flex space-x-2">
  172. <input
  173. v-model="communication.inputs[index]"
  174. class="input"
  175. name="message"
  176. :placeholder="$t('count.message', { count: index + 1 })"
  177. type="text"
  178. autocomplete="off"
  179. :disabled="!connectionState"
  180. @keyup.enter="connectionState ? sendMessage() : null"
  181. />
  182. <ButtonSecondary
  183. v-if="index + 1 !== communication.inputs.length"
  184. v-tippy="{ theme: 'tooltip' }"
  185. :title="$t('action.remove')"
  186. svg="trash"
  187. class="rounded"
  188. color="red"
  189. outline
  190. @click.native="removeCommunicationInput({ index })"
  191. />
  192. <ButtonPrimary
  193. v-if="index + 1 === communication.inputs.length"
  194. id="send"
  195. name="send"
  196. :disabled="!connectionState"
  197. :label="$t('action.send')"
  198. @click.native="sendMessage"
  199. />
  200. </div>
  201. </div>
  202. </div>
  203. </AppSection>
  204. </Pane>
  205. </Splitpanes>
  206. </template>
  207. <script>
  208. import { defineComponent } from "@nuxtjs/composition-api"
  209. import { Splitpanes, Pane } from "splitpanes"
  210. import "splitpanes/dist/splitpanes.css"
  211. // All Socket.IO client version imports
  212. import ClientV2 from "socket.io-client-v2"
  213. import { io as ClientV3 } from "socket.io-client-v3"
  214. import { io as ClientV4 } from "socket.io-client-v4"
  215. import wildcard from "socketio-wildcard"
  216. import debounce from "lodash/debounce"
  217. import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
  218. import { useSetting } from "~/newstore/settings"
  219. import useWindowSize from "~/helpers/utils/useWindowSize"
  220. const socketIoClients = {
  221. v4: ClientV4,
  222. v3: ClientV3,
  223. v2: ClientV2,
  224. }
  225. export default defineComponent({
  226. components: { Splitpanes, Pane },
  227. setup() {
  228. return {
  229. windowInnerWidth: useWindowSize(),
  230. SIDEBAR: useSetting("SIDEBAR"),
  231. COLUMN_LAYOUT: useSetting("COLUMN_LAYOUT"),
  232. SIDEBAR_ON_LEFT: useSetting("SIDEBAR_ON_LEFT"),
  233. socketIoClients,
  234. }
  235. },
  236. data() {
  237. return {
  238. // default version is set to v4
  239. clientVersion: "v4",
  240. url: "wss://hoppscotch-socketio.herokuapp.com",
  241. path: "/socket.io",
  242. isUrlValid: true,
  243. connectingState: false,
  244. connectionState: false,
  245. io: null,
  246. communication: {
  247. log: null,
  248. eventName: "",
  249. inputs: [""],
  250. },
  251. }
  252. },
  253. computed: {
  254. urlValid() {
  255. return this.isUrlValid
  256. },
  257. },
  258. watch: {
  259. url() {
  260. this.debouncer()
  261. },
  262. connectionState(connected) {
  263. if (connected) this.$refs.versionOptions.tippy().disable()
  264. else this.$refs.versionOptions.tippy().enable()
  265. },
  266. },
  267. created() {
  268. if (process.browser) {
  269. this.worker = this.$worker.createRejexWorker()
  270. this.worker.addEventListener("message", this.workerResponseHandler)
  271. }
  272. },
  273. destroyed() {
  274. this.worker.terminate()
  275. },
  276. methods: {
  277. debouncer: debounce(function () {
  278. this.worker.postMessage({ type: "socketio", url: this.url })
  279. }, 1000),
  280. workerResponseHandler({ data }) {
  281. if (data.url === this.url) this.isUrlValid = data.result
  282. },
  283. removeCommunicationInput({ index }) {
  284. this.$delete(this.communication.inputs, index)
  285. },
  286. addCommunicationInput() {
  287. this.communication.inputs.push("")
  288. },
  289. toggleConnection() {
  290. // If it is connecting:
  291. if (!this.connectionState) return this.connect()
  292. // Otherwise, it's disconnecting.
  293. else return this.disconnect()
  294. },
  295. connect() {
  296. this.connectingState = true
  297. this.communication.log = [
  298. {
  299. payload: this.$t("state.connecting_to", { name: this.url }),
  300. source: "info",
  301. color: "var(--accent-color)",
  302. },
  303. ]
  304. try {
  305. if (!this.path) {
  306. this.path = "/socket.io"
  307. }
  308. const Client = socketIoClients[this.clientVersion]
  309. this.io = new Client(this.url, { path: this.path })
  310. // Add ability to listen to all events
  311. wildcard(Client.Manager)(this.io)
  312. this.io.on("connect", () => {
  313. this.connectingState = false
  314. this.connectionState = true
  315. this.communication.log = [
  316. {
  317. payload: this.$t("state.connected_to", { name: this.url }),
  318. source: "info",
  319. color: "var(--accent-color)",
  320. ts: new Date().toLocaleTimeString(),
  321. },
  322. ]
  323. this.$toast.success(this.$t("state.connected"), {
  324. icon: "sync",
  325. })
  326. })
  327. this.io.on("*", ({ data }) => {
  328. const [eventName, message] = data
  329. this.communication.log.push({
  330. payload: `[${eventName}] ${message ? JSON.stringify(message) : ""}`,
  331. source: "server",
  332. ts: new Date().toLocaleTimeString(),
  333. })
  334. })
  335. this.io.on("connect_error", (error) => {
  336. this.handleError(error)
  337. })
  338. this.io.on("reconnect_error", (error) => {
  339. this.handleError(error)
  340. })
  341. this.io.on("error", () => {
  342. this.handleError()
  343. })
  344. this.io.on("disconnect", () => {
  345. this.connectingState = false
  346. this.connectionState = false
  347. this.communication.log.push({
  348. payload: this.$t("state.disconnected_from", { name: this.url }),
  349. source: "info",
  350. color: "#ff5555",
  351. ts: new Date().toLocaleTimeString(),
  352. })
  353. this.$toast.error(this.$t("state.disconnected"), {
  354. icon: "sync_disabled",
  355. })
  356. })
  357. } catch (e) {
  358. this.handleError(e)
  359. this.$toast.error(this.$t("error.something_went_wrong"), {
  360. icon: "error_outline",
  361. })
  362. }
  363. logHoppRequestRunToAnalytics({
  364. platform: "socketio",
  365. })
  366. },
  367. disconnect() {
  368. this.io.close()
  369. },
  370. handleError(error) {
  371. this.disconnect()
  372. this.connectingState = false
  373. this.connectionState = false
  374. this.communication.log.push({
  375. payload: this.$t("error.something_went_wrong"),
  376. source: "info",
  377. color: "#ff5555",
  378. ts: new Date().toLocaleTimeString(),
  379. })
  380. if (error !== null)
  381. this.communication.log.push({
  382. payload: error,
  383. source: "info",
  384. color: "#ff5555",
  385. ts: new Date().toLocaleTimeString(),
  386. })
  387. },
  388. sendMessage() {
  389. const eventName = this.communication.eventName
  390. const messages = (this.communication.inputs || [])
  391. .map((input) => {
  392. try {
  393. return JSON.parse(input)
  394. } catch (e) {
  395. return input
  396. }
  397. })
  398. .filter((message) => !!message)
  399. if (this.io) {
  400. this.io.emit(eventName, ...messages, (data) => {
  401. // receive response from server
  402. this.communication.log.push({
  403. payload: `[${eventName}] ${JSON.stringify(data)}`,
  404. source: "server",
  405. ts: new Date().toLocaleTimeString(),
  406. })
  407. })
  408. this.communication.log.push({
  409. payload: `[${eventName}] ${JSON.stringify(messages)}`,
  410. source: "client",
  411. ts: new Date().toLocaleTimeString(),
  412. })
  413. this.communication.inputs = [""]
  414. }
  415. },
  416. onSelectVersion(version) {
  417. this.clientVersion = version
  418. this.$refs.versionOptions.tippy().hide()
  419. },
  420. },
  421. })
  422. </script>