Socketio.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 flex p-4 top-0 z-10 sticky">
  18. <div class="space-x-2 flex-1 inline-flex">
  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 border-divider rounded-l cursor-pointer flex font-semibold text-secondaryDark py-2 px-4 w-26 hover:border-dividerDark focus-visible:bg-transparent focus-visible:border-dividerDark"
  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 border-divider flex flex-1 text-secondaryDark w-full py-2 px-4 hover:border-dividerDark focus-visible:bg-transparent focus-visible:border-dividerDark"
  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 border-divider rounded-r flex flex-1 text-secondaryDark w-full py-2 px-4 hover:border-dividerDark focus-visible:bg-transparent focus-visible:border-dividerDark"
  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="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 flex-col flex-1 p-4 inline-flex">
  105. <label for="events" class="font-semibold text-secondaryLight">
  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 flex-1 p-4 items-center justify-between">
  122. <label class="font-semibold text-secondaryLight">
  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. @click.native="addCommunicationInput"
  131. />
  132. </div>
  133. </div>
  134. <div class="flex flex-col space-y-2 px-4 pb-4">
  135. <div
  136. v-for="(input, index) of communication.inputs"
  137. :key="`input-${index}`"
  138. >
  139. <div class="flex space-x-2">
  140. <input
  141. v-model="communication.inputs[index]"
  142. class="input"
  143. name="message"
  144. :placeholder="$t('count.message', { count: index + 1 })"
  145. type="text"
  146. autocomplete="off"
  147. :disabled="!connectionState"
  148. @keyup.enter="connectionState ? sendMessage() : null"
  149. />
  150. <ButtonSecondary
  151. v-if="index + 1 !== communication.inputs.length"
  152. v-tippy="{ theme: 'tooltip' }"
  153. :title="$t('action.remove')"
  154. svg="trash"
  155. color="red"
  156. outline
  157. @click.native="removeCommunicationInput({ index })"
  158. />
  159. <ButtonPrimary
  160. v-if="index + 1 === communication.inputs.length"
  161. id="send"
  162. name="send"
  163. :disabled="!connectionState"
  164. :label="$t('action.send')"
  165. @click.native="sendMessage"
  166. />
  167. </div>
  168. </div>
  169. </div>
  170. </AppSection>
  171. </Pane>
  172. </Splitpanes>
  173. </template>
  174. <script>
  175. import { defineComponent } from "@nuxtjs/composition-api"
  176. import { Splitpanes, Pane } from "splitpanes"
  177. import "splitpanes/dist/splitpanes.css"
  178. // All Socket.IO client version imports
  179. import ClientV2 from "socket.io-client-v2"
  180. import { io as ClientV3 } from "socket.io-client-v3"
  181. import { io as ClientV4 } from "socket.io-client-v4"
  182. import wildcard from "socketio-wildcard"
  183. import debounce from "lodash/debounce"
  184. import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
  185. import { useSetting } from "~/newstore/settings"
  186. import useWindowSize from "~/helpers/utils/useWindowSize"
  187. import {
  188. SIOEndpoint$,
  189. setSIOEndpoint,
  190. SIOVersion$,
  191. setSIOVersion,
  192. SIOPath$,
  193. setSIOPath,
  194. SIOConnectionState$,
  195. SIOConnectingState$,
  196. setSIOConnectionState,
  197. setSIOConnectingState,
  198. SIOSocket$,
  199. setSIOSocket,
  200. SIOLog$,
  201. setSIOLog,
  202. addSIOLogLine,
  203. } from "~/newstore/SocketIOSession"
  204. import { useStream } from "~/helpers/utils/composables"
  205. const socketIoClients = {
  206. v4: ClientV4,
  207. v3: ClientV3,
  208. v2: ClientV2,
  209. }
  210. export default defineComponent({
  211. components: { Splitpanes, Pane },
  212. setup() {
  213. return {
  214. windowInnerWidth: useWindowSize(),
  215. SIDEBAR: useSetting("SIDEBAR"),
  216. COLUMN_LAYOUT: useSetting("COLUMN_LAYOUT"),
  217. SIDEBAR_ON_LEFT: useSetting("SIDEBAR_ON_LEFT"),
  218. socketIoClients,
  219. url: useStream(SIOEndpoint$, "", setSIOEndpoint),
  220. clientVersion: useStream(SIOVersion$, "", setSIOVersion),
  221. path: useStream(SIOPath$, "", setSIOPath),
  222. connectingState: useStream(
  223. SIOConnectingState$,
  224. false,
  225. setSIOConnectingState
  226. ),
  227. connectionState: useStream(
  228. SIOConnectionState$,
  229. false,
  230. setSIOConnectionState
  231. ),
  232. io: useStream(SIOSocket$, null, setSIOSocket),
  233. log: useStream(SIOLog$, [], setSIOLog),
  234. }
  235. },
  236. data() {
  237. return {
  238. isUrlValid: true,
  239. communication: {
  240. eventName: "",
  241. inputs: [""],
  242. },
  243. }
  244. },
  245. computed: {
  246. urlValid() {
  247. return this.isUrlValid
  248. },
  249. },
  250. watch: {
  251. url() {
  252. this.debouncer()
  253. },
  254. connectionState(connected) {
  255. if (connected) this.$refs.versionOptions.tippy().disable()
  256. else this.$refs.versionOptions.tippy().enable()
  257. },
  258. },
  259. created() {
  260. if (process.browser) {
  261. this.worker = this.$worker.createRejexWorker()
  262. this.worker.addEventListener("message", this.workerResponseHandler)
  263. }
  264. },
  265. destroyed() {
  266. this.worker.terminate()
  267. },
  268. methods: {
  269. debouncer: debounce(function () {
  270. this.worker.postMessage({ type: "socketio", url: this.url })
  271. }, 1000),
  272. workerResponseHandler({ data }) {
  273. if (data.url === this.url) this.isUrlValid = data.result
  274. },
  275. removeCommunicationInput({ index }) {
  276. this.$delete(this.communication.inputs, index)
  277. },
  278. addCommunicationInput() {
  279. this.communication.inputs.push("")
  280. },
  281. toggleConnection() {
  282. // If it is connecting:
  283. if (!this.connectionState) return this.connect()
  284. // Otherwise, it's disconnecting.
  285. else return this.disconnect()
  286. },
  287. connect() {
  288. this.connectingState = true
  289. this.log = [
  290. {
  291. payload: this.$t("state.connecting_to", { name: this.url }),
  292. source: "info",
  293. color: "var(--accent-color)",
  294. },
  295. ]
  296. try {
  297. if (!this.path) {
  298. this.path = "/socket.io"
  299. }
  300. const Client = socketIoClients[this.clientVersion]
  301. this.io = new Client(this.url, { path: this.path })
  302. // Add ability to listen to all events
  303. wildcard(Client.Manager)(this.io)
  304. this.io.on("connect", () => {
  305. this.connectingState = false
  306. this.connectionState = true
  307. this.log = [
  308. {
  309. payload: this.$t("state.connected_to", { name: this.url }),
  310. source: "info",
  311. color: "var(--accent-color)",
  312. ts: new Date().toLocaleTimeString(),
  313. },
  314. ]
  315. this.$toast.success(this.$t("state.connected"))
  316. })
  317. this.io.on("*", ({ data }) => {
  318. const [eventName, message] = data
  319. addSIOLogLine({
  320. payload: `[${eventName}] ${message ? JSON.stringify(message) : ""}`,
  321. source: "server",
  322. ts: new Date().toLocaleTimeString(),
  323. })
  324. })
  325. this.io.on("connect_error", (error) => {
  326. this.handleError(error)
  327. })
  328. this.io.on("reconnect_error", (error) => {
  329. this.handleError(error)
  330. })
  331. this.io.on("error", () => {
  332. this.handleError()
  333. })
  334. this.io.on("disconnect", () => {
  335. this.connectingState = false
  336. this.connectionState = false
  337. addSIOLogLine({
  338. payload: this.$t("state.disconnected_from", { name: this.url }),
  339. source: "info",
  340. color: "#ff5555",
  341. ts: new Date().toLocaleTimeString(),
  342. })
  343. this.$toast.error(this.$t("state.disconnected"))
  344. })
  345. } catch (e) {
  346. this.handleError(e)
  347. this.$toast.error(this.$t("error.something_went_wrong"))
  348. }
  349. logHoppRequestRunToAnalytics({
  350. platform: "socketio",
  351. })
  352. },
  353. disconnect() {
  354. this.io.close()
  355. },
  356. handleError(error) {
  357. this.disconnect()
  358. this.connectingState = false
  359. this.connectionState = false
  360. addSIOLogLine({
  361. payload: this.$t("error.something_went_wrong"),
  362. source: "info",
  363. color: "#ff5555",
  364. ts: new Date().toLocaleTimeString(),
  365. })
  366. if (error !== null)
  367. addSIOLogLine({
  368. payload: error,
  369. source: "info",
  370. color: "#ff5555",
  371. ts: new Date().toLocaleTimeString(),
  372. })
  373. },
  374. sendMessage() {
  375. const eventName = this.communication.eventName
  376. const messages = (this.communication.inputs || [])
  377. .map((input) => {
  378. try {
  379. return JSON.parse(input)
  380. } catch (e) {
  381. return input
  382. }
  383. })
  384. .filter((message) => !!message)
  385. if (this.io) {
  386. this.io.emit(eventName, ...messages, (data) => {
  387. // receive response from server
  388. addSIOLogLine({
  389. payload: `[${eventName}] ${JSON.stringify(data)}`,
  390. source: "server",
  391. ts: new Date().toLocaleTimeString(),
  392. })
  393. })
  394. addSIOLogLine({
  395. payload: `[${eventName}] ${JSON.stringify(messages)}`,
  396. source: "client",
  397. ts: new Date().toLocaleTimeString(),
  398. })
  399. this.communication.inputs = [""]
  400. }
  401. },
  402. onSelectVersion(version) {
  403. this.clientVersion = version
  404. this.$refs.versionOptions.tippy().hide()
  405. },
  406. },
  407. })
  408. </script>