feat: migrate to vue 3 + vite (#2553)

Co-authored-by: amk-dev <akash.k.mohan98@gmail.com>
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
This commit is contained in:
Andrew Bastin
2022-09-29 10:55:21 +05:30
committed by GitHub
parent 77a561b581
commit 8b300fab5d
685 changed files with 17102 additions and 25942 deletions

View File

@@ -0,0 +1,323 @@
<template>
<SmartModal
v-if="show"
dialog
:title="t(`environment.${action}`)"
@close="hideModal"
>
<template #body>
<div class="flex flex-col">
<div class="relative flex">
<input
id="selectLabelEnvEdit"
v-model="name"
v-focus
class="input floating-input"
placeholder=" "
type="text"
autocomplete="off"
:disabled="editingEnvironmentIndex === 'Global'"
@keyup.enter="saveEnvironment"
/>
<label for="selectLabelEnvEdit">
{{ t("action.label") }}
</label>
</div>
<div class="flex items-center justify-between flex-1">
<label for="variableList" class="p-4">
{{ t("environment.variable_list") }}
</label>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.clear_all')"
:icon="clearIcon"
@click="clearContent()"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:icon="IconPlus"
:title="t('add.new')"
@click="addEnvironmentVariable"
/>
</div>
</div>
<div
v-if="evnExpandError"
class="w-full px-4 py-2 mb-2 overflow-auto font-mono text-red-400 whitespace-normal rounded bg-primaryLight"
>
{{ t("environment.nested_overflow") }}
</div>
<div class="border rounded divide-y divide-dividerLight border-divider">
<div
v-for="({ id, env }, index) in vars"
:key="`variable-${id}-${index}`"
class="flex divide-x divide-dividerLight"
>
<input
v-model="env.key"
class="flex flex-1 px-4 py-2 bg-transparent"
:placeholder="`${t('count.variable', { count: index + 1 })}`"
:name="'param' + index"
/>
<SmartEnvInput
v-model="env.value"
:placeholder="`${t('count.value', { count: index + 1 })}`"
:envs="liveEnvs"
:name="'value' + index"
/>
<div class="flex">
<ButtonSecondary
id="variable"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.remove')"
:icon="IconTrash"
color="red"
@click="removeEnvironmentVariable(index)"
/>
</div>
</div>
<div
v-if="vars.length === 0"
class="flex flex-col items-center justify-center p-4 text-secondaryLight"
>
<img
:src="`/images/states/${colorMode.value}/blockchain.svg`"
loading="lazy"
class="inline-flex flex-col object-contain object-center w-16 h-16 my-4"
:alt="`${t('empty.environments')}`"
/>
<span class="pb-4 text-center">
{{ t("empty.environments") }}
</span>
<ButtonSecondary
:label="`${t('add.new')}`"
filled
class="mb-4"
@click="addEnvironmentVariable"
/>
</div>
</div>
</div>
</template>
<template #footer>
<span class="flex">
<ButtonPrimary
:label="`${t('action.save')}`"
@click="saveEnvironment"
/>
<ButtonSecondary :label="`${t('action.cancel')}`" @click="hideModal" />
</span>
</template>
</SmartModal>
</template>
<script setup lang="ts">
import IconTrash2 from "~icons/lucide/trash-2"
import IconCheck from "~icons/lucide/check"
import IconPlus from "~icons/lucide/plus"
import IconTrash from "~icons/lucide/trash"
import { clone } from "lodash-es"
import { computed, ref, watch } from "vue"
import * as E from "fp-ts/Either"
import * as A from "fp-ts/Array"
import * as O from "fp-ts/Option"
import { pipe, flow } from "fp-ts/function"
import { Environment, parseTemplateStringE } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import {
createEnvironment,
environments$,
getEnvironment,
getGlobalVariables,
globalEnv$,
setCurrentEnvironment,
setGlobalEnvVariables,
updateEnvironment,
} from "~/newstore/environments"
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import { useReadonlyStream } from "@composables/stream"
import { useColorMode } from "@composables/theming"
type EnvironmentVariable = {
id: number
env: {
key: string
value: string
}
}
const t = useI18n()
const toast = useToast()
const colorMode = useColorMode()
const props = withDefaults(
defineProps<{
show: boolean
action: "edit" | "new"
editingEnvironmentIndex: number | "Global" | null
envVars?: () => Environment["variables"]
}>(),
{
show: false,
action: "edit",
editingEnvironmentIndex: null,
envVars: () => [],
}
)
const emit = defineEmits<{
(e: "hide-modal"): void
}>()
const idTicker = ref(0)
const name = ref<string | null>(null)
const vars = ref<EnvironmentVariable[]>([
{ id: idTicker.value++, env: { key: "", value: "" } },
])
const clearIcon = refAutoReset<typeof IconTrash2 | typeof IconCheck>(
IconTrash2,
1000
)
const globalVars = useReadonlyStream(globalEnv$, [])
const workingEnv = computed(() => {
if (props.editingEnvironmentIndex === "Global") {
return {
name: "Global",
variables: getGlobalVariables(),
} as Environment
} else if (props.action === "new") {
return {
name: "",
variables: props.envVars(),
}
} else if (props.editingEnvironmentIndex !== null) {
return getEnvironment(props.editingEnvironmentIndex)
} else {
return null
}
})
const envList = useReadonlyStream(environments$, []) || props.envVars()
const evnExpandError = computed(() => {
const variables = pipe(
vars.value,
A.map((e) => e.env)
)
return pipe(
variables,
A.exists(({ value }) => E.isLeft(parseTemplateStringE(value, variables)))
)
})
const liveEnvs = computed(() => {
if (evnExpandError.value) {
return []
}
if (props.editingEnvironmentIndex === "Global") {
return [...vars.value.map((x) => ({ ...x, source: name.value! }))]
} else {
return [
...vars.value.map((x) => ({ ...x, source: name.value! })),
...globalVars.value.map((x) => ({ ...x, source: "Global" })),
]
}
})
watch(
() => props.show,
(show) => {
if (show) {
name.value = workingEnv.value?.name ?? null
vars.value = pipe(
workingEnv.value?.variables ?? [],
A.map((e) => ({
id: idTicker.value++,
env: clone(e),
}))
)
}
}
)
const clearContent = () => {
vars.value = [
{
id: idTicker.value++,
env: {
key: "",
value: "",
},
},
]
clearIcon.value = IconCheck
toast.success(`${t("state.cleared")}`)
}
const addEnvironmentVariable = () => {
vars.value.push({
id: idTicker.value++,
env: {
key: "",
value: "",
},
})
}
const removeEnvironmentVariable = (index: number) => {
vars.value.splice(index, 1)
}
const saveEnvironment = () => {
if (!name.value) {
toast.error(`${t("environment.invalid_name")}`)
return
}
const filterdVariables = pipe(
vars.value,
A.filterMap(
flow(
O.fromPredicate((e) => e.env.key !== ""),
O.map((e) => e.env)
)
)
)
const environmentUpdated: Environment = {
name: name.value,
variables: filterdVariables,
}
if (props.action === "new") {
// Creating a new environment
createEnvironment(name.value)
updateEnvironment(envList.value.length - 1, environmentUpdated)
setCurrentEnvironment(envList.value.length - 1)
toast.success(`${t("environment.created")}`)
} else if (props.editingEnvironmentIndex === "Global") {
// Editing the Global environment
setGlobalEnvVariables(environmentUpdated.variables)
toast.success(`${t("environment.updated")}`)
} else if (props.editingEnvironmentIndex !== null) {
// Editing an environment
updateEnvironment(props.editingEnvironmentIndex, environmentUpdated)
toast.success(`${t("environment.updated")}`)
}
hideModal()
}
const hideModal = () => {
name.value = null
emit("hide-modal")
}
</script>

View File

@@ -0,0 +1,153 @@
<template>
<div
class="flex items-stretch group"
@contextmenu.prevent="options.tippy.show()"
>
<span
class="flex items-center justify-center px-4 cursor-pointer"
@click="emit('edit-environment')"
>
<icon-lucide-layers class="svg-icons" />
</span>
<span
class="flex flex-1 min-w-0 py-2 pr-2 cursor-pointer transition group-hover:text-secondaryDark"
@click="emit('edit-environment')"
>
<span class="truncate">
{{ environment.name }}
</span>
</span>
<span>
<tippy
ref="options"
interactive
trigger="click"
theme="popover"
arrow
:on-shown="() => tippyActions.focus()"
>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.more')"
:icon="IconMoreVertical"
/>
<template #content="{ hide }">
<div
ref="tippyActions"
class="flex flex-col focus:outline-none"
tabindex="0"
role="menu"
@keyup.e="edit.$el.click()"
@keyup.d="duplicate.$el.click()"
@keyup.delete="
!(environmentIndex === 'Global') ? deleteAction.$el.click() : null
"
@keyup.escape="hide()"
>
<SmartItem
ref="edit"
:icon="IconEdit"
:label="`${t('action.edit')}`"
:shortcut="['E']"
@click="
() => {
emit('edit-environment')
hide()
}
"
/>
<SmartItem
ref="duplicate"
:icon="IconCopy"
:label="`${t('action.duplicate')}`"
:shortcut="['D']"
@click="
() => {
duplicateEnvironments()
hide()
}
"
/>
<SmartItem
v-if="!(environmentIndex === 'Global')"
ref="deleteAction"
:icon="IconTrash2"
:label="`${t('action.delete')}`"
:shortcut="['⌫']"
@click="
() => {
confirmRemove = true
hide()
}
"
/>
</div>
</template>
</tippy>
</span>
<SmartConfirmModal
:show="confirmRemove"
:title="`${t('confirm.remove_environment')}`"
@hide-modal="confirmRemove = false"
@resolve="removeEnvironment"
/>
</div>
</template>
<script setup lang="ts">
import IconMoreVertical from "~icons/lucide/more-vertical"
import IconEdit from "~icons/lucide/edit"
import IconCopy from "~icons/lucide/copy"
import IconTrash2 from "~icons/lucide/trash-2"
import { ref } from "vue"
import { Environment } from "@hoppscotch/data"
import { cloneDeep } from "lodash-es"
import {
deleteEnvironment,
duplicateEnvironment,
createEnvironment,
setEnvironmentVariables,
getGlobalVariables,
environmentsStore,
} from "~/newstore/environments"
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
const t = useI18n()
const toast = useToast()
const props = defineProps<{
environment: Environment
environmentIndex: number | "Global" | null
}>()
const emit = defineEmits<{
(e: "edit-environment"): void
}>()
const confirmRemove = ref(false)
const tippyActions = ref<any | null>(null)
const options = ref<any | null>(null)
const edit = ref<any | null>(null)
const duplicate = ref<any | null>(null)
const deleteAction = ref<any | null>(null)
const removeEnvironment = () => {
if (props.environmentIndex === null) return
if (props.environmentIndex !== "Global")
deleteEnvironment(props.environmentIndex)
toast.success(`${t("state.deleted")}`)
}
const duplicateEnvironments = () => {
if (props.environmentIndex === null) return
if (props.environmentIndex === "Global") {
createEnvironment(`Global - ${t("action.duplicate")}`)
setEnvironmentVariables(
environmentsStore.value.environments.length - 1,
cloneDeep(getGlobalVariables())
)
} else duplicateEnvironment(props.environmentIndex)
}
</script>

View File

@@ -0,0 +1,288 @@
<template>
<SmartModal
v-if="show"
dialog
:title="`${t('environment.title')}`"
max-width="sm:max-w-md"
@close="hideModal"
>
<template #actions>
<span>
<tippy ref="options" interactive trigger="click" theme="popover" arrow>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.more')"
:icon="IconMoreVertical"
/>
<template #content="{ hide }">
<div
class="flex flex-col"
tabindex="0"
role="menu"
@keyup.escape="hide()"
>
<SmartItem
:icon="IconGithub"
:label="t('import.from_gist')"
@click="
() => {
readEnvironmentGist()
hide()
}
"
/>
<span
v-tippy="{ theme: 'tooltip' }"
:title="
!currentUser
? `${t('export.require_github')}`
: currentUser.provider !== 'github.com'
? `${t('export.require_github')}`
: undefined
"
>
<SmartItem
:disabled="
!currentUser
? true
: currentUser.provider !== 'github.com'
? true
: false
"
:icon="IconGithub"
:label="t('export.create_secret_gist')"
@click="
() => {
createEnvironmentGist()
hide()
}
"
/>
</span>
</div>
</template>
</tippy>
</span>
</template>
<template #body>
<div class="flex flex-col space-y-2">
<SmartItem
:icon="IconFolderPlus"
:label="t('import.from_json')"
@click="openDialogChooseFileToImportFrom"
/>
<input
ref="inputChooseFileToImportFrom"
class="input"
type="file"
accept="application/json"
@change="importFromJSON"
/>
<hr />
<SmartItem
v-tippy="{ theme: 'tooltip' }"
:title="t('action.download_file')"
:icon="IconDownload"
:label="t('export.as_json')"
@click="exportJSON"
/>
</div>
</template>
</SmartModal>
</template>
<script setup lang="ts">
import IconMoreVertical from "~icons/lucide/more-vertical"
import IconFolderPlus from "~icons/lucide/folder-plus"
import IconDownload from "~icons/lucide/download"
import IconGithub from "~icons/lucide/github"
import { computed, ref } from "vue"
import { Environment } from "@hoppscotch/data"
import { currentUser$ } from "~/helpers/fb/auth"
import axios from "axios"
import { useI18n } from "@composables/i18n"
import { useReadonlyStream } from "@composables/stream"
import { useToast } from "@composables/toast"
import {
environments$,
replaceEnvironments,
appendEnvironments,
} from "~/newstore/environments"
defineProps<{
show: boolean
}>()
const emit = defineEmits<{
(e: "hide-modal"): void
}>()
const toast = useToast()
const t = useI18n()
const environments = useReadonlyStream(environments$, [])
const currentUser = useReadonlyStream(currentUser$, null)
// Template refs
const options = ref<any>()
const inputChooseFileToImportFrom = ref<HTMLInputElement>()
const environmentJson = computed(() => {
return JSON.stringify(environments.value, null, 2)
})
const createEnvironmentGist = async () => {
if (!currentUser.value) {
toast.error(t("profile.no_permission").toString())
return
}
try {
const res = await axios.post(
"https://api.github.com/gists",
{
files: {
"hoppscotch-environments.json": {
content: environmentJson.value,
},
},
},
{
headers: {
Authorization: `token ${currentUser.value.accessToken}`,
Accept: "application/vnd.github.v3+json",
},
}
)
toast.success(t("export.gist_created").toString())
window.open(res.html_url)
} catch (e) {
toast.error(t("error.something_went_wrong").toString())
console.error(e)
}
}
const fileImported = () => {
toast.success(t("state.file_imported").toString())
}
const failedImport = () => {
toast.error(t("import.failed").toString())
}
const readEnvironmentGist = async () => {
const gist = prompt(t("import.gist_url").toString())
if (!gist) return
try {
const { files } = (await axios.get(
`https://api.github.com/gists/${gist.split("/").pop()}`,
{
headers: {
Accept: "application/vnd.github.v3+json",
},
}
)) as {
files: {
[fileName: string]: {
content: any
}
}
}
const environments = JSON.parse(Object.values(files)[0].content)
replaceEnvironments(environments)
fileImported()
} catch (e) {
failedImport()
console.error(e)
}
}
const hideModal = () => {
emit("hide-modal")
}
const openDialogChooseFileToImportFrom = () => {
if (inputChooseFileToImportFrom.value)
inputChooseFileToImportFrom.value.click()
}
const importFromJSON = () => {
if (!inputChooseFileToImportFrom.value) return
if (
!inputChooseFileToImportFrom.value.files ||
inputChooseFileToImportFrom.value.files.length === 0
) {
toast.show(t("action.choose_file").toString())
return
}
const reader = new FileReader()
reader.onload = ({ target }) => {
const content = target!.result as string | null
if (!content) {
toast.show(t("action.choose_file").toString())
return
}
const environments = JSON.parse(content)
if (
environments._postman_variable_scope === "environment" ||
environments._postman_variable_scope === "globals"
) {
importFromPostman(environments)
} else if (environments[0]) {
const [name, variables] = Object.keys(environments[0])
if (name === "name" && variables === "variables") {
// Do nothing
}
importFromHoppscotch(environments)
} else {
failedImport()
}
}
reader.readAsText(inputChooseFileToImportFrom.value.files[0])
inputChooseFileToImportFrom.value.value = ""
}
const importFromHoppscotch = (environments: Environment[]) => {
appendEnvironments(environments)
fileImported()
}
const importFromPostman = ({
name,
values,
}: {
name: string
values: { key: string; value: string }[]
}) => {
const environment: Environment = { name, variables: [] }
values.forEach(({ key, value }) => environment.variables.push({ key, value }))
const environments = [environment]
importFromHoppscotch(environments)
}
const exportJSON = () => {
const dataToWrite = environmentJson.value
const file = new Blob([dataToWrite], { type: "application/json" })
const a = document.createElement("a")
const url = URL.createObjectURL(file)
a.href = url
// TODO: get uri from meta
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
document.body.appendChild(a)
a.click()
toast.success(t("state.download_started").toString())
setTimeout(() => {
document.body.removeChild(a)
URL.revokeObjectURL(url)
}, 1000)
}
</script>

View File

@@ -0,0 +1,191 @@
<template>
<div>
<div class="sticky top-0 z-10 flex flex-col rounded-t bg-primary">
<tippy ref="options" interactive trigger="click" theme="popover" arrow>
<span
v-tippy="{ theme: 'tooltip' }"
:title="`${t('environment.select')}`"
class="flex-1 bg-transparent border-b border-dividerLight select-wrapper"
>
<ButtonSecondary
v-if="selectedEnvironmentIndex !== -1"
:label="environments[selectedEnvironmentIndex].name"
class="flex-1 !justify-start pr-8 rounded-none"
/>
<ButtonSecondary
v-else
:label="`${t('environment.select')}`"
class="flex-1 !justify-start pr-8 rounded-none"
/>
</span>
<template #content="{ hide }">
<div
class="flex flex-col"
tabindex="0"
role="menu"
@keyup.escape="hide()"
>
<SmartItem
:label="`${t('environment.no_environment')}`"
:info-icon="selectedEnvironmentIndex === -1 ? IconDone : null"
:active-info-icon="selectedEnvironmentIndex === -1"
@click="
() => {
selectedEnvironmentIndex = -1
hide()
}
"
/>
<hr v-if="environments.length > 0" />
<SmartItem
v-for="(gen, index) in environments"
:key="`gen-${index}`"
:label="gen.name"
:info-icon="index === selectedEnvironmentIndex ? IconDone : null"
:active-info-icon="index === selectedEnvironmentIndex"
@click="
() => {
selectedEnvironmentIndex = index
hide()
}
"
/>
</div>
</template>
</tippy>
<div class="flex justify-between flex-1 border-b border-dividerLight">
<ButtonSecondary
:icon="IconPlus"
:label="`${t('action.new')}`"
class="!rounded-none"
@click="displayModalAdd(true)"
/>
<div class="flex">
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
to="https://docs.hoppscotch.io/features/environments"
blank
:title="t('app.wiki')"
:icon="IconHelpCircle"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:icon="IconArchive"
:title="t('modal.import_export')"
@click="displayModalImportExport(true)"
/>
</div>
</div>
</div>
<div class="flex flex-col">
<EnvironmentsEnvironment
environment-index="Global"
:environment="globalEnvironment"
class="border-b border-dashed border-dividerLight"
@edit-environment="editEnvironment('Global')"
/>
<EnvironmentsEnvironment
v-for="(environment, index) in environments"
:key="`environment-${index}`"
:environment-index="index"
:environment="environment"
@edit-environment="editEnvironment(index)"
/>
</div>
<div
v-if="environments.length === 0"
class="flex flex-col items-center justify-center p-4 text-secondaryLight"
>
<img
:src="`/images/states/${colorMode.value}/blockchain.svg`"
loading="lazy"
class="inline-flex flex-col object-contain object-center w-16 h-16 my-4"
:alt="`${t('empty.environments')}`"
/>
<span class="pb-4 text-center">
{{ t("empty.environments") }}
</span>
<ButtonSecondary
:label="`${t('add.new')}`"
filled
class="mb-4"
@click="displayModalAdd(true)"
/>
</div>
<EnvironmentsDetails
:show="showModalDetails"
:action="action"
:editing-environment-index="editingEnvironmentIndex"
@hide-modal="displayModalEdit(false)"
/>
<EnvironmentsImportExport
:show="showModalImportExport"
@hide-modal="displayModalImportExport(false)"
/>
</div>
</template>
<script setup lang="ts">
import IconDone from "~icons/lucide/check"
import IconPlus from "~icons/lucide/plus"
import IconHelpCircle from "~icons/lucide/help-circle"
import IconArchive from "~icons/lucide/archive"
import { computed, ref } from "vue"
import { useReadonlyStream, useStream } from "@composables/stream"
import { useI18n } from "@composables/i18n"
import { useColorMode } from "@composables/theming"
import {
environments$,
setCurrentEnvironment,
selectedEnvIndex$,
globalEnv$,
} from "~/newstore/environments"
const t = useI18n()
const options = ref<any | null>(null)
const colorMode = useColorMode()
const globalEnv = useReadonlyStream(globalEnv$, [])
const globalEnvironment = computed(() => ({
name: "Global",
variables: globalEnv.value,
}))
const environments = useReadonlyStream(environments$, [])
const selectedEnvironmentIndex = useStream(
selectedEnvIndex$,
-1,
setCurrentEnvironment
)
const showModalImportExport = ref(false)
const showModalDetails = ref(false)
const action = ref<"new" | "edit">("edit")
const editingEnvironmentIndex = ref<number | "Global" | null>(null)
const displayModalAdd = (shouldDisplay: boolean) => {
action.value = "new"
showModalDetails.value = shouldDisplay
}
const displayModalEdit = (shouldDisplay: boolean) => {
action.value = "edit"
showModalDetails.value = shouldDisplay
if (!shouldDisplay) resetSelectedData()
}
const displayModalImportExport = (shouldDisplay: boolean) => {
showModalImportExport.value = shouldDisplay
}
const editEnvironment = (environmentIndex: number | "Global") => {
editingEnvironmentIndex.value = environmentIndex
action.value = "edit"
displayModalEdit(true)
}
const resetSelectedData = () => {
editingEnvironmentIndex.value = null
}
</script>