Socketio.vue 13 KB

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