refactor: monorepo+pnpm (removed husky)

This commit is contained in:
Andrew Bastin
2021-09-10 00:28:28 +05:30
parent 917550ff4d
commit b28f82a881
445 changed files with 81301 additions and 63752 deletions

View File

@@ -0,0 +1,79 @@
<template>
<div class="flex flex-col">
<div
class="
bg-primary
border-b border-dividerLight
flex flex-1
pl-4
top-0
z-10
sticky
items-center
justify-between
"
>
<label for="log" class="font-semibold text-secondaryLight py-2">
{{ title }}
</label>
</div>
<div ref="log" name="log" class="realtime-log">
<span v-if="log" class="space-y-2">
<span
v-for="(entry, index) in log"
:key="`entry-${index}`"
:style="{ color: entry.color }"
>{{ entry.ts }}{{ getSourcePrefix(entry.source)
}}{{ entry.payload }}</span
>
</span>
<span v-else>{{ $t("response.waiting_for_connection") }}</span>
</div>
</div>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import { getSourcePrefix } from "~/helpers/utils/string"
export default defineComponent({
props: {
log: { type: Array, default: () => [] },
title: {
type: String,
default: "",
},
},
updated() {
this.$nextTick(function () {
if (this.$refs.log) {
this.$refs.log.scrollBy(0, this.$refs.log.scrollHeight + 100)
}
})
},
methods: {
getSourcePrefix,
},
})
</script>
<style scoped lang="scss">
.realtime-log {
@apply p-4;
@apply bg-transparent;
@apply text-secondary;
@apply overflow-auto;
height: 256px;
&,
span {
@apply select-text;
}
span {
@apply block;
@apply break-words break-all;
}
}
</style>

View File

@@ -0,0 +1,374 @@
<template>
<Splitpanes
class="smart-splitter"
:dbl-click-splitter="false"
:horizontal="!(windowInnerWidth.x.value >= 768)"
>
<Pane class="hide-scrollbar !overflow-auto">
<Splitpanes class="smart-splitter" :dbl-click-splitter="false" horizontal>
<Pane class="hide-scrollbar !overflow-auto">
<AppSection label="request">
<div class="bg-primary flex p-4 top-0 z-10 sticky">
<div class="space-x-2 flex-1 inline-flex">
<input
id="mqtt-url"
v-model="url"
v-focus
type="url"
autocomplete="off"
spellcheck="false"
class="
bg-primaryLight
border border-divider
rounded
text-secondaryDark
w-full
py-2
px-4
hover:border-dividerDark
focus-visible:bg-transparent
focus-visible:border-dividerDark
"
:placeholder="$t('mqtt.url')"
/>
<ButtonPrimary
id="connect"
:disabled="!validUrl"
class="w-32"
:label="
connectionState
? $t('action.disconnect')
: $t('action.connect')
"
:loading="connectingState"
@click.native="toggleConnection"
/>
</div>
</div>
</AppSection>
</Pane>
<Pane class="hide-scrollbar !overflow-auto">
<AppSection label="response">
<RealtimeLog :title="$t('mqtt.log')" :log="log" />
</AppSection>
</Pane>
</Splitpanes>
</Pane>
<Pane
v-if="RIGHT_SIDEBAR"
max-size="35"
size="25"
min-size="20"
class="hide-scrollbar !overflow-auto"
>
<AppSection label="messages">
<div class="flex flex-col flex-1 p-4 inline-flex">
<label for="pub_topic" class="font-semibold text-secondaryLight">
{{ $t("mqtt.topic") }}
</label>
</div>
<div class="flex px-4">
<input
id="pub_topic"
v-model="pub_topic"
class="input"
:placeholder="$t('mqtt.topic_name')"
type="text"
autocomplete="off"
spellcheck="false"
/>
</div>
<div class="flex flex-1 p-4 items-center justify-between">
<label for="mqtt-message" class="font-semibold text-secondaryLight">
{{ $t("mqtt.communication") }}
</label>
</div>
<div class="flex space-x-2 px-4">
<input
id="mqtt-message"
v-model="msg"
class="input"
type="text"
autocomplete="off"
:placeholder="$t('mqtt.message')"
spellcheck="false"
/>
<ButtonPrimary
id="publish"
name="get"
:disabled="!canpublish"
:label="$t('mqtt.publish')"
@click.native="publish"
/>
</div>
<div
class="
border-t border-dividerLight
flex flex-col flex-1
mt-4
p-4
inline-flex
"
>
<label for="sub_topic" class="font-semibold text-secondaryLight">
{{ $t("mqtt.topic") }}
</label>
</div>
<div class="flex space-x-2 px-4">
<input
id="sub_topic"
v-model="sub_topic"
type="text"
autocomplete="off"
:placeholder="$t('mqtt.topic_name')"
spellcheck="false"
class="input"
/>
<ButtonPrimary
id="subscribe"
name="get"
:disabled="!cansubscribe"
:label="
subscriptionState ? $t('mqtt.unsubscribe') : $t('mqtt.subscribe')
"
reverse
@click.native="toggleSubscription"
/>
</div>
</AppSection>
</Pane>
</Splitpanes>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import Paho from "paho-mqtt"
import debounce from "~/helpers/utils/debounce"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import { useSetting } from "~/newstore/settings"
import useWindowSize from "~/helpers/utils/useWindowSize"
export default defineComponent({
components: { Splitpanes, Pane },
setup() {
return {
windowInnerWidth: useWindowSize(),
RIGHT_SIDEBAR: useSetting("RIGHT_SIDEBAR"),
}
},
data() {
return {
url: "wss://test.mosquitto.org:8081",
isUrlValid: true,
client: null,
pub_topic: "",
sub_topic: "",
msg: "",
connectionState: false,
connectingState: false,
log: null,
manualDisconnect: false,
subscriptionState: false,
}
},
computed: {
validUrl() {
return this.isUrlValid
},
canpublish() {
return this.pub_topic !== "" && this.msg !== "" && this.connectionState
},
cansubscribe() {
return this.sub_topic !== "" && this.connectionState
},
},
watch: {
url() {
this.debouncer()
},
},
mounted() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
debouncer: debounce(function () {
this.worker.postMessage({ type: "ws", url: this.url })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
connect() {
this.connectingState = true
this.log = [
{
payload: this.$t("state.connecting_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
const parseUrl = new URL(this.url)
this.client = new Paho.Client(
parseUrl.hostname,
parseUrl.port !== "" ? Number(parseUrl.port) : 8081,
"hoppscotch"
)
this.client.connect({
onSuccess: this.onConnectionSuccess,
onFailure: this.onConnectionFailure,
useSSL: true,
})
this.client.onConnectionLost = this.onConnectionLost
this.client.onMessageArrived = this.onMessageArrived
logHoppRequestRunToAnalytics({
platform: "mqtt",
})
},
onConnectionFailure() {
this.connectingState = false
this.connectionState = false
this.log.push({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
onConnectionSuccess() {
this.connectingState = false
this.connectionState = true
this.log.push({
payload: this.$t("state.connected_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
})
this.$toast.success(this.$t("state.connected"), {
icon: "sync",
})
},
onMessageArrived({ payloadString, destinationName }) {
this.log.push({
payload: `Message: ${payloadString} arrived on topic: ${destinationName}`,
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
})
},
toggleConnection() {
if (this.connectionState) {
this.disconnect()
} else {
this.connect()
}
},
disconnect() {
this.manualDisconnect = true
this.client.disconnect()
this.log.push({
payload: this.$t("state.disconnected_from", { name: this.url }),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
onConnectionLost() {
this.connectingState = false
this.connectionState = false
if (this.manualDisconnect) {
this.$toast.error(this.$t("state.disconnected"), {
icon: "sync_disabled",
})
} else {
this.$toast.error(this.$t("error.something_went_wrong"), {
icon: "error_outline",
})
}
this.manualDisconnect = false
this.subscriptionState = false
},
publish() {
try {
this.client.publish(this.pub_topic, this.msg, 0, false)
this.log.push({
payload: `Published message: ${this.msg} to topic: ${this.pub_topic}`,
ts: new Date().toLocaleTimeString(),
source: "info",
color: "var(--accent-color)",
})
} catch (e) {
this.log.push({
payload:
this.$t("error.something_went_wrong") +
`while publishing msg: ${this.msg} to topic: ${this.pub_topic}`,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
}
},
toggleSubscription() {
if (this.subscriptionState) {
this.unsubscribe()
} else {
this.subscribe()
}
},
subscribe() {
try {
this.client.subscribe(this.sub_topic, {
onSuccess: this.usubSuccess,
onFailure: this.usubFailure,
})
} catch (e) {
this.log.push({
payload:
this.$t("error.something_went_wrong") +
`while subscribing to topic: ${this.sub_topic}`,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
}
},
usubSuccess() {
this.subscriptionState = !this.subscriptionState
this.log.push({
payload:
`Successfully ` +
(this.subscriptionState ? "subscribed" : "unsubscribed") +
` to topic: ${this.sub_topic}`,
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
})
},
usubFailure() {
this.log.push({
payload:
`Failed to ` +
(this.subscriptionState ? "unsubscribe" : "subscribe") +
` to topic: ${this.sub_topic}`,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
unsubscribe() {
this.client.unsubscribe(this.sub_topic, {
onSuccess: this.usubSuccess,
onFailure: this.usubFailure,
})
},
},
})
</script>

View File

@@ -0,0 +1,362 @@
<template>
<Splitpanes
class="smart-splitter"
:dbl-click-splitter="false"
:horizontal="!(windowInnerWidth.x.value >= 768)"
>
<Pane class="hide-scrollbar !overflow-auto">
<Splitpanes class="smart-splitter" :dbl-click-splitter="false" horizontal>
<Pane class="hide-scrollbar !overflow-auto">
<AppSection label="request">
<div class="bg-primary flex p-4 top-0 z-10 sticky">
<div class="space-x-2 flex-1 inline-flex">
<div class="flex flex-1">
<input
id="socketio-url"
v-model="url"
v-focus
type="url"
autocomplete="off"
spellcheck="false"
:class="{ error: !urlValid }"
class="
bg-primaryLight
border border-divider
rounded-l
flex flex-1
text-secondaryDark
w-full
py-2
px-4
hover:border-dividerDark
focus-visible:bg-transparent
focus-visible:border-dividerDark
"
:placeholder="$t('socketio.url')"
@keyup.enter="urlValid ? toggleConnection() : null"
/>
<input
id="socketio-path"
v-model="path"
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
"
spellcheck="false"
/>
</div>
<ButtonPrimary
id="connect"
:disabled="!urlValid"
name="connect"
class="w-32"
:label="
!connectionState
? $t('action.connect')
: $t('action.disconnect')
"
:loading="connectingState"
@click.native="toggleConnection"
/>
</div>
</div>
</AppSection>
</Pane>
<Pane class="hide-scrollbar !overflow-auto">
<AppSection label="response">
<RealtimeLog :title="$t('socketio.log')" :log="communication.log" />
</AppSection>
</Pane>
</Splitpanes>
</Pane>
<Pane
v-if="RIGHT_SIDEBAR"
max-size="35"
size="25"
min-size="20"
class="hide-scrollbar !overflow-auto"
>
<AppSection label="messages">
<div class="flex flex-col flex-1 p-4 inline-flex">
<label for="events" class="font-semibold text-secondaryLight">
{{ $t("socketio.events") }}
</label>
</div>
<div class="flex px-4">
<input
id="event_name"
v-model="communication.eventName"
class="input"
name="event_name"
:placeholder="$t('socketio.event_name')"
type="text"
autocomplete="off"
:disabled="!connectionState"
/>
</div>
<div class="flex flex-1 p-4 items-center justify-between">
<label class="font-semibold text-secondaryLight">
{{ $t("socketio.communication") }}
</label>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('add.new')"
svg="plus"
class="rounded"
@click.native="addCommunicationInput"
/>
</div>
</div>
<div class="flex flex-col space-y-2 px-4">
<div
v-for="(input, index) of communication.inputs"
:key="`input-${index}`"
>
<div class="flex space-x-2">
<input
v-model="communication.inputs[index]"
class="input"
name="message"
:placeholder="$t('count.message', { count: index + 1 })"
type="text"
autocomplete="off"
:disabled="!connectionState"
@keyup.enter="connectionState ? sendMessage() : null"
/>
<ButtonSecondary
v-if="index + 1 !== communication.inputs.length"
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.remove')"
svg="trash"
class="rounded"
color="red"
outline
@click.native="removeCommunicationInput({ index })"
/>
<ButtonPrimary
v-if="index + 1 === communication.inputs.length"
id="send"
name="send"
:disabled="!connectionState"
:label="$t('action.send')"
@click.native="sendMessage"
/>
</div>
</div>
</div>
</AppSection>
</Pane>
</Splitpanes>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { io as Client } from "socket.io-client"
import wildcard from "socketio-wildcard"
import debounce from "~/helpers/utils/debounce"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import { useSetting } from "~/newstore/settings"
import useWindowSize from "~/helpers/utils/useWindowSize"
export default defineComponent({
components: { Splitpanes, Pane },
setup() {
return {
windowInnerWidth: useWindowSize(),
RIGHT_SIDEBAR: useSetting("RIGHT_SIDEBAR"),
}
},
data() {
return {
url: "wss://main-daxrc78qyb411dls-gtw.qovery.io",
path: "/socket.io",
isUrlValid: true,
connectingState: false,
connectionState: false,
io: null,
communication: {
log: null,
eventName: "",
inputs: [""],
},
}
},
computed: {
urlValid() {
return this.isUrlValid
},
},
watch: {
url() {
this.debouncer()
},
},
mounted() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
debouncer: debounce(function () {
this.worker.postMessage({ type: "socketio", url: this.url })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
removeCommunicationInput({ index }) {
this.$delete(this.communication.inputs, index)
},
addCommunicationInput() {
this.communication.inputs.push("")
},
toggleConnection() {
// If it is connecting:
if (!this.connectionState) return this.connect()
// Otherwise, it's disconnecting.
else return this.disconnect()
},
connect() {
this.connectingState = true
this.communication.log = [
{
payload: this.$t("state.connecting_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
},
]
try {
if (!this.path) {
this.path = "/socket.io"
}
this.io = new Client(this.url, {
path: this.path,
})
// Add ability to listen to all events
wildcard(Client.Manager)(this.io)
this.io.on("connect", () => {
this.connectingState = false
this.connectionState = true
this.communication.log = [
{
payload: this.$t("state.connected_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
this.$toast.success(this.$t("state.connected"), {
icon: "sync",
})
})
this.io.on("*", ({ data }) => {
const [eventName, message] = data
this.communication.log.push({
payload: `[${eventName}] ${message ? JSON.stringify(message) : ""}`,
source: "server",
ts: new Date().toLocaleTimeString(),
})
})
this.io.on("connect_error", (error) => {
this.handleError(error)
})
this.io.on("reconnect_error", (error) => {
this.handleError(error)
})
this.io.on("error", () => {
this.handleError()
})
this.io.on("disconnect", () => {
this.connectingState = false
this.connectionState = false
this.communication.log.push({
payload: this.$t("state.disconnected_from", { name: this.url }),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
this.$toast.error(this.$t("state.disconnected"), {
icon: "sync_disabled",
})
})
} catch (e) {
this.handleError(e)
this.$toast.error(this.$t("error.something_went_wrong"), {
icon: "error_outline",
})
}
logHoppRequestRunToAnalytics({
platform: "socketio",
})
},
disconnect() {
this.io.close()
},
handleError(error) {
this.disconnect()
this.connectingState = false
this.connectionState = false
this.communication.log.push({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
if (error !== null)
this.communication.log.push({
payload: error,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
sendMessage() {
const eventName = this.communication.eventName
const messages = (this.communication.inputs || [])
.map((input) => {
try {
return JSON.parse(input)
} catch (e) {
return input
}
})
.filter((message) => !!message)
if (this.io) {
this.io.emit(eventName, ...messages, (data) => {
// receive response from server
this.communication.log.push({
payload: `[${eventName}] ${JSON.stringify(data)}`,
source: "server",
ts: new Date().toLocaleTimeString(),
})
})
this.communication.log.push({
payload: `[${eventName}] ${JSON.stringify(messages)}`,
source: "client",
ts: new Date().toLocaleTimeString(),
})
this.communication.inputs = [""]
}
},
},
})
</script>

View File

@@ -0,0 +1,238 @@
<template>
<Splitpanes class="smart-splitter" :dbl-click-splitter="false" horizontal>
<Pane class="hide-scrollbar !overflow-auto">
<div class="bg-primary flex p-4 top-0 z-10 sticky">
<div class="space-x-2 flex-1 inline-flex">
<div class="flex flex-1">
<input
id="server"
v-model="server"
v-focus
type="url"
autocomplete="off"
:class="{ error: !serverValid }"
class="
bg-primaryLight
border border-divider
rounded-l
flex flex-1
text-secondaryDark
w-full
py-2
px-4
hover:border-dividerDark
focus-visible:bg-transparent focus-visible:border-dividerDark
"
:placeholder="$t('sse.url')"
@keyup.enter="serverValid ? toggleSSEConnection() : null"
/>
<label
for="url"
class="
bg-primaryLight
border-t border-b border-divider
font-semibold
text-secondaryLight
py-2
px-4
truncate
"
>
{{ $t("sse.event_type") }}
</label>
<input
id="event-type"
v-model="eventType"
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
"
spellcheck="false"
/>
</div>
<ButtonPrimary
id="start"
:disabled="!serverValid"
name="start"
class="w-32"
:label="
!connectionSSEState ? $t('action.start') : $t('action.stop')
"
:loading="connectingState"
@click.native="toggleSSEConnection"
/>
</div>
</div>
</Pane>
<Pane class="hide-scrollbar !overflow-auto">
<AppSection label="response">
<ul>
<li>
<RealtimeLog :title="$t('sse.log')" :log="events.log" />
<div id="result"></div>
</li>
</ul>
</AppSection>
</Pane>
</Splitpanes>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import debounce from "~/helpers/utils/debounce"
export default defineComponent({
components: { Splitpanes, Pane },
data() {
return {
connectionSSEState: false,
connectingState: false,
server: "https://express-eventsource.herokuapp.com/events",
isUrlValid: true,
sse: null,
events: {
log: null,
input: "",
},
eventType: "data",
}
},
computed: {
serverValid() {
return this.isUrlValid
},
},
watch: {
server() {
this.debouncer()
},
},
mounted() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
debouncer: debounce(function () {
this.worker.postMessage({ type: "sse", url: this.server })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
toggleSSEConnection() {
// If it is connecting:
if (!this.connectionSSEState) return this.start()
// Otherwise, it's disconnecting.
else return this.stop()
},
start() {
this.connectingState = true
this.events.log = [
{
payload: this.$t("state.connecting_to", { name: this.server }),
source: "info",
color: "var(--accent-color)",
},
]
if (typeof EventSource !== "undefined") {
try {
this.sse = new EventSource(this.server)
this.sse.onopen = () => {
this.connectingState = false
this.connectionSSEState = true
this.events.log = [
{
payload: this.$t("state.connected_to", { name: this.server }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
this.$toast.success(this.$t("state.connected"), {
icon: "sync",
})
}
this.sse.onerror = () => {
this.handleSSEError()
}
this.sse.onclose = () => {
this.connectionSSEState = false
this.events.log.push({
payload: this.$t("state.disconnected_from", {
name: this.server,
}),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
this.$toast.error(this.$t("state.disconnected"), {
icon: "sync_disabled",
})
}
this.sse.addEventListener(this.eventType, ({ data }) => {
this.events.log.push({
payload: data,
source: "server",
ts: new Date().toLocaleTimeString(),
})
})
} catch (e) {
this.handleSSEError(e)
this.$toast.error(this.$t("error.something_went_wrong"), {
icon: "error_outline",
})
}
} else {
this.events.log = [
{
payload: this.$t("error.browser_support_sse"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
},
]
}
logHoppRequestRunToAnalytics({
platform: "sse",
})
},
handleSSEError(error) {
this.stop()
this.connectionSSEState = false
this.events.log.push({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
if (error !== null)
this.events.log.push({
payload: error,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
stop() {
this.sse.close()
this.sse.onclose()
},
},
})
</script>

View File

@@ -0,0 +1,433 @@
<template>
<Splitpanes
class="smart-splitter"
:dbl-click-splitter="false"
:horizontal="!(windowInnerWidth.x.value >= 768)"
>
<Pane class="hide-scrollbar !overflow-auto">
<Splitpanes class="smart-splitter" :dbl-click-splitter="false" horizontal>
<Pane class="hide-scrollbar !overflow-auto">
<AppSection label="request">
<div class="bg-primary flex p-4 top-0 z-10 sticky">
<div class="space-x-2 flex-1 inline-flex">
<input
id="websocket-url"
v-model="url"
v-focus
class="
bg-primaryLight
border border-divider
rounded
text-secondaryDark
w-full
py-2
px-4
hover:border-dividerDark
focus-visible:bg-transparent
focus-visible:border-dividerDark
"
type="url"
autocomplete="off"
spellcheck="false"
:class="{ error: !urlValid }"
:placeholder="$t('websocket.url')"
@keyup.enter="urlValid ? toggleConnection() : null"
/>
<ButtonPrimary
id="connect"
:disabled="!urlValid"
class="w-32"
name="connect"
:label="
!connectionState
? $t('action.connect')
: $t('action.disconnect')
"
:loading="connectingState"
@click.native="toggleConnection"
/>
</div>
</div>
<div
class="
bg-primary
border-b border-dividerLight
flex flex-1
top-upperPrimaryStickyFold
pl-4
z-10
sticky
items-center
justify-between
"
>
<label class="font-semibold text-secondaryLight">
{{ $t("websocket.protocols") }}
</label>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.clear_all')"
svg="trash-2"
@click.native="clearContent"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('add.new')"
svg="plus"
@click.native="addProtocol"
/>
</div>
</div>
<div
v-for="(protocol, index) of protocols"
:key="`protocol-${index}`"
class="
divide-x divide-dividerLight
border-b border-dividerLight
flex
"
>
<input
v-model="protocol.value"
class="bg-transparent flex flex-1 py-2 px-4"
:placeholder="$t('count.protocol', { count: index + 1 })"
name="message"
type="text"
autocomplete="off"
/>
<span>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="
protocol.hasOwnProperty('active')
? protocol.active
? $t('action.turn_off')
: $t('action.turn_on')
: $t('action.turn_off')
"
:svg="
protocol.hasOwnProperty('active')
? protocol.active
? 'check-circle'
: 'circle'
: 'check-circle'
"
color="green"
@click.native="
protocol.active = protocol.hasOwnProperty('active')
? !protocol.active
: false
"
/>
</span>
<span>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="$t('action.remove')"
svg="trash"
color="red"
@click.native="deleteProtocol({ index })"
/>
</span>
</div>
<div
v-if="protocols.length === 0"
class="
flex flex-col
text-secondaryLight
p-4
items-center
justify-center
"
>
<i class="opacity-75 pb-2 material-icons">topic</i>
<span class="text-center">
{{ $t("empty.protocols") }}
</span>
</div>
</AppSection>
</Pane>
<Pane class="hide-scrollbar !overflow-auto">
<AppSection label="response">
<RealtimeLog
:title="$t('websocket.log')"
:log="communication.log"
/>
</AppSection>
</Pane>
</Splitpanes>
</Pane>
<Pane
v-if="RIGHT_SIDEBAR"
max-size="35"
size="25"
min-size="20"
class="hide-scrollbar !overflow-auto"
>
<AppSection label="messages">
<div class="flex flex-col flex-1 p-4 inline-flex">
<label
for="websocket-message"
class="font-semibold text-secondaryLight"
>
{{ $t("websocket.communication") }}
</label>
</div>
<div class="flex space-x-2 px-4">
<input
id="websocket-message"
v-model="communication.input"
name="message"
type="text"
autocomplete="off"
:disabled="!connectionState"
:placeholder="$t('websocket.message')"
class="input"
@keyup.enter="connectionState ? sendMessage() : null"
@keyup.up="connectionState ? walkHistory('up') : null"
@keyup.down="connectionState ? walkHistory('down') : null"
/>
<ButtonPrimary
id="send"
name="send"
:disabled="!connectionState"
:label="$t('action.send')"
@click.native="sendMessage"
/>
</div>
</AppSection>
</Pane>
</Splitpanes>
</template>
<script>
import { defineComponent } from "@nuxtjs/composition-api"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
import debounce from "~/helpers/utils/debounce"
import useWindowSize from "~/helpers/utils/useWindowSize"
import { useSetting } from "~/newstore/settings"
export default defineComponent({
components: { Splitpanes, Pane },
setup() {
return {
windowInnerWidth: useWindowSize(),
RIGHT_SIDEBAR: useSetting("RIGHT_SIDEBAR"),
}
},
data() {
return {
connectionState: false,
connectingState: false,
url: "wss://echo.websocket.org",
isUrlValid: true,
socket: null,
communication: {
log: null,
input: "",
},
currentIndex: -1, // index of the message log array to put in input box
protocols: [],
activeProtocols: [],
}
},
computed: {
urlValid() {
return this.isUrlValid
},
},
watch: {
url() {
this.debouncer()
},
protocols: {
handler(newVal) {
this.activeProtocols = newVal
.filter((item) =>
Object.prototype.hasOwnProperty.call(item, "active")
? item.active === true
: true
)
.map(({ value }) => value)
},
deep: true,
},
},
mounted() {
if (process.browser) {
this.worker = this.$worker.createRejexWorker()
this.worker.addEventListener("message", this.workerResponseHandler)
}
},
destroyed() {
this.worker.terminate()
},
methods: {
clearContent() {
this.protocols = []
},
debouncer: debounce(function () {
this.worker.postMessage({ type: "ws", url: this.url })
}, 1000),
workerResponseHandler({ data }) {
if (data.url === this.url) this.isUrlValid = data.result
},
toggleConnection() {
// If it is connecting:
if (!this.connectionState) return this.connect()
// Otherwise, it's disconnecting.
else return this.disconnect()
},
connect() {
this.communication.log = [
{
payload: this.$t("state.connecting_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
},
]
try {
this.connectingState = true
this.socket = new WebSocket(this.url, this.activeProtocols)
this.socket.onopen = () => {
this.connectingState = false
this.connectionState = true
this.communication.log = [
{
payload: this.$t("state.connected_to", { name: this.url }),
source: "info",
color: "var(--accent-color)",
ts: new Date().toLocaleTimeString(),
},
]
this.$toast.success(this.$t("state.connected"), {
icon: "sync",
})
}
this.socket.onerror = () => {
this.handleError()
}
this.socket.onclose = () => {
this.connectionState = false
this.communication.log.push({
payload: this.$t("state.disconnected_from", { name: this.url }),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
this.$toast.error(this.$t("state.disconnected"), {
icon: "sync_disabled",
})
}
this.socket.onmessage = ({ data }) => {
this.communication.log.push({
payload: data,
source: "server",
ts: new Date().toLocaleTimeString(),
})
}
} catch (e) {
this.handleError(e)
this.$toast.error(this.$t("error.something_went_wrong"), {
icon: "error_outline",
})
}
logHoppRequestRunToAnalytics({
platform: "wss",
})
},
disconnect() {
if (this.socket) {
this.socket.close()
this.connectionState = false
this.connectingState = false
}
},
handleError(error) {
this.disconnect()
this.connectionState = false
this.communication.log.push({
payload: this.$t("error.something_went_wrong"),
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
if (error !== null)
this.communication.log.push({
payload: error,
source: "info",
color: "#ff5555",
ts: new Date().toLocaleTimeString(),
})
},
sendMessage() {
const message = this.communication.input
this.socket.send(message)
this.communication.log.push({
payload: message,
source: "client",
ts: new Date().toLocaleTimeString(),
})
this.communication.input = ""
},
walkHistory(direction) {
const clientMessages = this.communication.log.filter(
({ source }) => source === "client"
)
const length = clientMessages.length
switch (direction) {
case "up":
if (length > 0 && this.currentIndex !== 0) {
// does nothing if message log is empty or the currentIndex is 0 when up arrow is pressed
if (this.currentIndex === -1) {
this.currentIndex = length - 1
this.communication.input =
clientMessages[this.currentIndex].payload
} else if (this.currentIndex === 0) {
this.communication.input = clientMessages[0].payload
} else if (this.currentIndex > 0) {
this.currentIndex = this.currentIndex - 1
this.communication.input =
clientMessages[this.currentIndex].payload
}
}
break
case "down":
if (length > 0 && this.currentIndex > -1) {
if (this.currentIndex === length - 1) {
this.currentIndex = -1
this.communication.input = ""
} else if (this.currentIndex < length - 1) {
this.currentIndex = this.currentIndex + 1
this.communication.input =
clientMessages[this.currentIndex].payload
}
}
break
}
},
addProtocol() {
this.protocols.push({ value: "", active: true })
},
deleteProtocol({ index }) {
const oldProtocols = this.protocols.slice()
this.$delete(this.protocols, index)
this.$toast.success(this.$t("state.deleted"), {
icon: "delete",
action: {
text: this.$t("action.undo"),
duration: 4000,
onClick: (_, toastObject) => {
this.protocols = oldProtocols
toastObject.remove()
},
},
})
},
},
})
</script>