feat: team environments (#2512)

Co-authored-by: amk-dev <akash.k.mohan98@gmail.com>
Co-authored-by: liyasthomas <liyascthomas@gmail.com>
Co-authored-by: islamzeki <islamzeki@users.noreply.github.com>
Co-authored-by: Jesvin Jose <aitchnyu@users.noreply.github.com>
Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
This commit is contained in:
Nivedin
2022-10-07 22:05:39 +05:30
committed by GitHub
parent c35a85db12
commit a568610c28
28 changed files with 1886 additions and 227 deletions

View File

@@ -122,6 +122,7 @@ a {
.cm-tooltip {
.tippy-box {
@apply fixed;
@apply inline-flex;
@apply -mt-6;
}
}
@@ -135,6 +136,7 @@ a {
@apply truncate;
@apply shadow;
@apply leading-body;
@apply items-center;
font-size: 86%;
kbd {
@@ -152,6 +154,13 @@ a {
.tippy-svg-arrow svg {
@apply fill-tooltip;
}
.env-icon {
@apply inline-flex;
@apply items-center;
@apply mr-1;
@apply text-accentDark;
}
}
.tippy-box[data-theme="popover"] {

View File

@@ -184,11 +184,13 @@
"deleted": "Environment deletion",
"edit": "Edit Environment",
"invalid_name": "Please provide a name for the environment",
"my_environments":"My Environments",
"nested_overflow": "nested environment variables are limited to 10 levels",
"new": "New Environment",
"no_environment": "No environment",
"no_environment_description": "No environments were selected. Choose what to do with the following variables.",
"select": "Select environment",
"team_environments": "Team Environments",
"title": "Environments",
"updated": "Environment updated",
"variable_list": "Variable List"
@@ -653,6 +655,11 @@
"we_sent_invite_link": "We sent an invite link to all invitees!",
"we_sent_invite_link_description": "Ask all invitees to check their inbox. Click on the link to join the team."
},
"team_environment": {
"deleted": "Environment Deleted",
"duplicate": "Environment Duplicated",
"not_found": "Environment not found."
},
"test": {
"failed": "test failed",
"javascript_code": "JavaScript Code",

View File

@@ -55,9 +55,14 @@ declare module '@vue/runtime-core' {
CollectionsTeamsFolder: typeof import('./components/collections/teams/Folder.vue')['default']
CollectionsTeamsRequest: typeof import('./components/collections/teams/Request.vue')['default']
Environments: typeof import('./components/environments/index.vue')['default']
EnvironmentsDetails: typeof import('./components/environments/Details.vue')['default']
EnvironmentsEnvironment: typeof import('./components/environments/Environment.vue')['default']
EnvironmentsChooseType: typeof import('./components/environments/ChooseType.vue')['default']
EnvironmentsImportExport: typeof import('./components/environments/ImportExport.vue')['default']
EnvironmentsMy: typeof import('./components/environments/my/index.vue')['default']
EnvironmentsMyDetails: typeof import('./components/environments/my/Details.vue')['default']
EnvironmentsMyEnvironment: typeof import('./components/environments/my/Environment.vue')['default']
EnvironmentsTeams: typeof import('./components/environments/teams/index.vue')['default']
EnvironmentsTeamsDetails: typeof import('./components/environments/teams/Details.vue')['default']
EnvironmentsTeamsEnvironment: typeof import('./components/environments/teams/Environment.vue')['default']
FirebaseLogin: typeof import('./components/firebase/Login.vue')['default']
FirebaseLogout: typeof import('./components/firebase/Logout.vue')['default']
GraphqlAuthorization: typeof import('./components/graphql/Authorization.vue')['default']
@@ -104,7 +109,6 @@ declare module '@vue/runtime-core' {
IconLucideSearch: typeof import('~icons/lucide/search')['default']
IconLucideUser: typeof import('~icons/lucide/user')['default']
IconLucideUsers: typeof import('~icons/lucide/users')['default']
IconLucideVerified: typeof import('~icons/lucide/verified')['default']
LensesHeadersRenderer: typeof import('./components/lenses/HeadersRenderer.vue')['default']
LensesHeadersRendererEntry: typeof import('./components/lenses/HeadersRendererEntry.vue')['default']
LensesRenderersHTMLLensRenderer: typeof import('./components/lenses/renderers/HTMLLensRenderer.vue')['default']

View File

@@ -0,0 +1,149 @@
<template>
<div v-show="show">
<SmartTabs
:id="'environments_tab'"
v-model="selectedEnvironmentTab"
render-inactive-tabs
>
<SmartTab
:id="'my-environments'"
:label="`${t('environment.my_environments')}`"
/>
<SmartTab
v-if="currentUser"
:id="'team-environments'"
:label="`${t('environment.team_environments')}`"
>
<SmartIntersection @intersecting="onTeamSelectIntersect">
<tippy
interactive
trigger="click"
theme="popover"
arrow
placement="bottom"
>
<span
v-tippy="{ theme: 'tooltip' }"
:title="`${t('collection.select_team')}`"
class="bg-transparent border-t border-dividerLight select-wrapper"
>
<ButtonSecondary
v-if="environmentType.selectedTeam"
:icon="IconUsers"
:label="environmentType.selectedTeam.name"
class="flex-1 !justify-start pr-8 rounded-none"
/>
<ButtonSecondary
v-else
:label="`${t('collection.select_team')}`"
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
v-for="(team, index) in myTeams"
:key="`team-${index}`"
:label="team.name"
:info-icon="
team.id === environmentType.selectedTeam?.id
? IconDone
: undefined
"
:active-info-icon="
team.id === environmentType.selectedTeam?.id
"
:icon="IconUsers"
@click="
() => {
updateSelectedTeam(team)
hide()
}
"
/>
</div>
</template>
</tippy>
</SmartIntersection>
</SmartTab>
</SmartTabs>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue"
import { Team } from "~/helpers/backend/graphql"
import { onLoggedIn } from "@composables/auth"
import { currentUserInfo$ } from "~/helpers/teams/BackendUserInfo"
import TeamListAdapter from "~/helpers/teams/TeamListAdapter"
import { useReadonlyStream } from "@composables/stream"
import { useLocalState } from "~/newstore/localstate"
import { useI18n } from "@composables/i18n"
import IconDone from "~icons/lucide/check"
import IconUsers from "~icons/lucide/users"
const t = useI18n()
type SelectedTeam = Team | undefined
type EnvironmentTabs = "my-environments" | "team-environments"
const selectedEnvironmentTab = ref<EnvironmentTabs>("my-environments")
defineProps<{
show: boolean
environmentType: {
type: "my-environments" | "team-environments"
selectedTeam: SelectedTeam
}
}>()
const emit = defineEmits<{
(e: "update-environment-type", tabID: EnvironmentTabs): void
(e: "update-selected-team", team: SelectedTeam): void
}>()
const currentUser = useReadonlyStream(currentUserInfo$, null)
const adapter = new TeamListAdapter(true)
const myTeams = useReadonlyStream(adapter.teamList$, null)
const REMEMBERED_TEAM_ID = useLocalState("REMEMBERED_TEAM_ID")
let teamListFetched = false
watch(myTeams, (teams) => {
if (teams && !teamListFetched) {
teamListFetched = true
if (REMEMBERED_TEAM_ID.value && currentUser.value) {
const team = teams.find((t) => t.id === REMEMBERED_TEAM_ID.value)
if (team) updateSelectedTeam(team)
}
}
})
onLoggedIn(() => {
adapter.initialize()
})
const onTeamSelectIntersect = () => {
// Load team data as soon as intersection
adapter.fetchList()
}
const updateEnvironmentType = (tabID: EnvironmentTabs) => {
emit("update-environment-type", tabID)
}
const updateSelectedTeam = (team: SelectedTeam) => {
REMEMBERED_TEAM_ID.value = team?.id
emit("update-selected-team", team)
}
watch(selectedEnvironmentTab, (newValue: EnvironmentTabs) => {
updateEnvironmentType(newValue)
})
</script>

View File

@@ -12,7 +12,7 @@
interactive
trigger="click"
theme="popover"
:on-shown="() => tippyActions.focus()"
:on-shown="() => tippyActions!.focus()"
>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
@@ -70,7 +70,11 @@
</span>
</template>
<template #body>
<div class="flex flex-col space-y-2">
<div v-if="loading" class="flex flex-col items-center justify-center p-4">
<SmartSpinner class="my-4" />
<span class="text-secondaryLight">{{ t("state.loading") }}</span>
</div>
<div v-else class="flex flex-col space-y-2">
<SmartItem
:icon="IconFolderPlus"
:label="t('import.from_json')"
@@ -112,10 +116,19 @@ import {
environments$,
replaceEnvironments,
appendEnvironments,
getSelectedEnvironmentType,
} from "~/newstore/environments"
import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"
import * as TE from "fp-ts/TaskEither"
import { pipe } from "fp-ts/function"
import { createTeamEnvironment } from "~/helpers/backend/mutations/TeamEnvironment"
import { GQLError } from "~/helpers/backend/GQLClient"
import { TippyComponent } from "vue-tippy"
defineProps<{
const props = defineProps<{
show: boolean
teamEnvironments?: TeamEnvironment[]
teamId?: string | undefined
}>()
const emit = defineEmits<{
@@ -124,15 +137,38 @@ const emit = defineEmits<{
const toast = useToast()
const t = useI18n()
const environments = useReadonlyStream(environments$, [])
const loading = ref(false)
const myEnvironments = useReadonlyStream(environments$, [])
const currentUser = useReadonlyStream(currentUser$, null)
const selectedEnvType = getSelectedEnvironmentType()
const currentSelectedEnvionmentType = computed(() => {
if (selectedEnvType === "MY_ENV" || props.teamEnvironments === undefined) {
return "MY_ENV"
} else {
return "TEAM_ENV"
}
})
// Template refs
const tippyActions = ref<any | null>(null)
const tippyActions = ref<TippyComponent | null>(null)
const inputChooseFileToImportFrom = ref<HTMLInputElement>()
const environmentJson = computed(() => {
return JSON.stringify(environments.value, null, 2)
if (
currentSelectedEnvionmentType.value === "TEAM_ENV" &&
props.teamEnvironments !== undefined
) {
const teamEnvironments = props.teamEnvironments.map(
(x) => x.environment as Environment
)
return JSON.stringify(teamEnvironments, null, 2)
} else {
return JSON.stringify(myEnvironments.value, null, 2)
}
})
const createEnvironmentGist = async () => {
@@ -196,8 +232,13 @@ const readEnvironmentGist = async () => {
}
}
const environments = JSON.parse(Object.values(files)[0].content)
replaceEnvironments(environments)
fileImported()
if (currentSelectedEnvionmentType.value === "MY_ENV") {
replaceEnvironments(environments)
fileImported()
} else {
importToTeams(environments)
}
} catch (e) {
failedImport()
console.error(e)
@@ -213,6 +254,34 @@ const openDialogChooseFileToImportFrom = () => {
inputChooseFileToImportFrom.value.click()
}
const importToTeams = async (content: Environment[]) => {
loading.value = true
for (const [i, env] of content.entries()) {
if (i === content.length - 1) {
loading.value = false
hideModal()
fileImported()
} else {
await pipe(
createTeamEnvironment(
JSON.stringify(env.variables),
props.teamId as string,
env.name
),
TE.match(
(err: GQLError<string>) => {
console.error(err)
toast.error(`${getErrorMessage(err)}`)
},
() => {
// wait for all the environments to be created then fire the toast
}
)
)()
}
}
}
const importFromJSON = () => {
if (!inputChooseFileToImportFrom.value) return
@@ -235,6 +304,7 @@ const importFromJSON = () => {
}
const environments = JSON.parse(content)
if (
environments._postman_variable_scope === "environment" ||
environments._postman_variable_scope === "globals"
@@ -256,8 +326,12 @@ const importFromJSON = () => {
}
const importFromHoppscotch = (environments: Environment[]) => {
appendEnvironments(environments)
fileImported()
if (currentSelectedEnvionmentType.value === "MY_ENV") {
appendEnvironments(environments)
fileImported()
} else {
importToTeams(environments)
}
}
const importFromPostman = ({
@@ -290,4 +364,17 @@ const exportJSON = () => {
URL.revokeObjectURL(url)
}, 1000)
}
const getErrorMessage = (err: GQLError<string>) => {
if (err.type === "network_error") {
return t("error.network_error")
} else {
switch (err.error) {
case "team_environment/not_found":
return t("team_environment.not_found")
default:
return t("error.something_went_wrong")
}
}
}
</script>

View File

@@ -2,19 +2,23 @@
<div>
<div class="sticky top-0 z-10 flex flex-col rounded-t bg-primary">
<tippy
v-if="environmentType.type === 'my-environments'"
interactive
trigger="click"
theme="popover"
:on-shown="() => tippyActions.focus()"
arrow
:on-shown="() => tippyActions!.focus()"
>
<span
v-tippy="{ theme: 'tooltip' }"
:title="`${t('environment.select')}`"
class="flex-1 bg-transparent border-b border-dividerLight select-wrapper"
class="bg-transparent border-b border-dividerLight select-wrapper"
>
<ButtonSecondary
v-if="selectedEnvironmentIndex !== -1"
:label="environments[selectedEnvironmentIndex].name"
v-if="
selectedEnv.type === 'MY_ENV' && selectedEnv.index !== undefined
"
:label="myEnvironments[selectedEnv.index].name"
class="flex-1 !justify-start pr-8 rounded-none"
/>
<ButtonSecondary
@@ -26,31 +30,36 @@
<template #content="{ hide }">
<div
ref="tippyActions"
role="menu"
class="flex flex-col focus:outline-none"
tabindex="0"
@keyup.escape="hide()"
>
<SmartItem
:label="`${t('environment.no_environment')}`"
:info-icon="selectedEnvironmentIndex === -1 ? IconDone : null"
:active-info-icon="selectedEnvironmentIndex === -1"
:info-icon="
selectedEnvironmentIndex.type !== 'MY_ENV'
? IconCheck
: undefined
"
:active-info-icon="selectedEnvironmentIndex.type !== 'MY_ENV'"
@click="
() => {
selectedEnvironmentIndex = -1
selectedEnvironmentIndex = { type: 'NO_ENV_SELECTED' }
hide()
}
"
/>
<hr v-if="environments.length > 0" />
<hr v-if="myEnvironments.length > 0" />
<SmartItem
v-for="(gen, index) in environments"
v-for="(gen, index) in myEnvironments"
:key="`gen-${index}`"
:label="gen.name"
:info-icon="index === selectedEnvironmentIndex ? IconDone : null"
:active-info-icon="index === selectedEnvironmentIndex"
:info-icon="index === selectedEnv.index ? IconCheck : undefined"
:active-info-icon="index === selectedEnv.index"
@click="
() => {
selectedEnvironmentIndex = index
selectedEnvironmentIndex = { type: 'MY_ENV', index: index }
hide()
}
"
@@ -58,140 +67,258 @@
</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">
<tippy v-else interactive trigger="click" theme="popover" arrow>
<span
v-tippy="{ theme: 'tooltip' }"
:title="`${t('environment.select')}`"
class="bg-transparent border-b border-dividerLight select-wrapper"
>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
to="https://docs.hoppscotch.io/features/environments"
blank
:title="t('app.wiki')"
:icon="IconHelpCircle"
v-if="selectedEnv.name"
:label="selectedEnv.name"
class="flex-1 !justify-start pr-8 rounded-none"
/>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:icon="IconArchive"
:title="t('modal.import_export')"
@click="displayModalImportExport(true)"
v-else
:label="`${t('environment.select')}`"
class="flex-1 !justify-start pr-8 rounded-none"
/>
</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)"
</span>
<template #content="{ hide }">
<div
class="flex flex-col"
role="menu"
tabindex="0"
@keyup.escape="hide()"
>
<SmartItem
:label="`${t('environment.no_environment')}`"
:info-icon="
selectedEnvironmentIndex.type !== 'TEAM_ENV'
? IconCheck
: undefined
"
:active-info-icon="selectedEnvironmentIndex.type !== 'TEAM_ENV'"
@click="
() => {
selectedEnvironmentIndex = { type: 'NO_ENV_SELECTED' }
hide()
}
"
/>
<div
v-if="loading"
class="flex flex-col items-center justify-center p-4"
>
<SmartSpinner class="my-4" />
<span class="text-secondaryLight">{{ t("state.loading") }}</span>
</div>
<hr v-if="teamEnvironmentList.length > 0" />
<div
v-if="environmentType.selectedTeam !== undefined"
class="flex flex-col"
>
<SmartItem
v-for="(gen, index) in teamEnvironmentList"
:key="`gen-team-${index}`"
:label="gen.environment.name"
:info-icon="
gen.id === selectedEnv.teamEnvID ? IconCheck : undefined
"
:active-info-icon="gen.id === selectedEnv.teamEnvID"
@click="
() => {
selectedEnvironmentIndex = {
type: 'TEAM_ENV',
teamEnvID: gen.id,
teamID: gen.teamID,
environment: gen.environment,
}
hide()
}
"
/>
</div>
<div
v-if="!loading && adapterError"
class="flex flex-col items-center py-4"
>
<i class="mb-4 material-icons">help_outline</i>
{{ getErrorMessage(adapterError) }}
</div>
</div>
</template>
</tippy>
<EnvironmentsChooseType
:environment-type="environmentType"
:show="showTeamEnvironment"
@update-environment-type="updateEnvironmentType"
@update-selected-team="updateSelectedTeam"
/>
</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"
outline
@click="displayModalAdd(true)"
/>
</div>
<EnvironmentsDetails
:show="showModalDetails"
:action="action"
:editing-environment-index="editingEnvironmentIndex"
@hide-modal="displayModalEdit(false)"
/>
<EnvironmentsImportExport
:show="showModalImportExport"
@hide-modal="displayModalImportExport(false)"
<EnvironmentsMy v-if="environmentType.type === 'my-environments'" />
<EnvironmentsTeams
v-else
:team="environmentType.selectedTeam"
:team-environments="teamEnvironmentList"
:loading="loading"
:adapter-error="adapterError"
/>
</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 { computed, ref, watch } from "vue"
import { isEqual } from "lodash-es"
import { currentUser$ } from "~/helpers/fb/auth"
import { Team } from "~/helpers/backend/graphql"
import { useReadonlyStream, useStream } from "@composables/stream"
import { useI18n } from "@composables/i18n"
import { useColorMode } from "@composables/theming"
import { useI18n } from "~/composables/i18n"
import {
environments$,
setCurrentEnvironment,
selectedEnvIndex$,
globalEnv$,
selectedEnvironmentIndex$,
setSelectedEnvironmentIndex,
} from "~/newstore/environments"
import TeamEnvironmentAdapter from "~/helpers/teams/TeamEnvironmentAdapter"
import { GQLError } from "~/helpers/backend/GQLClient"
import IconCheck from "~icons/lucide/check"
import { TippyComponent } from "vue-tippy"
const t = useI18n()
const colorMode = useColorMode()
type EnvironmentType = "my-environments" | "team-environments"
const globalEnv = useReadonlyStream(globalEnv$, [])
type SelectedTeam = Team | undefined
const globalEnvironment = computed(() => ({
name: "Global",
variables: globalEnv.value,
}))
type EnvironmentsChooseType = {
type: EnvironmentType
selectedTeam: SelectedTeam
}
const environments = useReadonlyStream(environments$, [])
const environmentType = ref<EnvironmentsChooseType>({
type: "my-environments",
selectedTeam: undefined,
})
const selectedEnvironmentIndex = useStream(
selectedEnvIndex$,
-1,
setCurrentEnvironment
const currentUser = useReadonlyStream(currentUser$, null)
const showTeamEnvironment = computed(() => {
if (currentUser.value == null) {
return false
}
return true
})
const updateSelectedTeam = (newSelectedTeam: SelectedTeam) => {
environmentType.value.selectedTeam = newSelectedTeam
}
const updateEnvironmentType = (newEnvironmentType: EnvironmentType) => {
environmentType.value.type = newEnvironmentType
}
const adapter = new TeamEnvironmentAdapter(undefined)
const adapterLoading = useReadonlyStream(adapter.loading$, false)
const adapterError = useReadonlyStream(adapter.error$, null)
const teamEnvironmentList = useReadonlyStream(adapter.teamEnvironmentList$, [])
const loading = computed(
() => adapterLoading.value && teamEnvironmentList.value.length === 0
)
watch(
() => environmentType.value.selectedTeam?.id,
(newTeamID) => {
adapter.changeTeamID(newTeamID)
}
)
const myEnvironments = useReadonlyStream(environments$, [])
const selectedEnvironmentIndex = useStream(
selectedEnvironmentIndex$,
{ type: "NO_ENV_SELECTED" },
setSelectedEnvironmentIndex
)
/* Checking if there are any changes in the selected team environment when there are any updates
in the selected team environment list */
watch(
() => teamEnvironmentList.value,
(newTeamEnvironmentList) => {
if (
newTeamEnvironmentList.length > 0 &&
selectedEnvironmentIndex.value.type === "TEAM_ENV"
) {
const selectedEnv = newTeamEnvironmentList.find(
(env) =>
env.id ===
(selectedEnvironmentIndex.value.type === "TEAM_ENV" &&
selectedEnvironmentIndex.value.teamEnvID)
)
if (selectedEnv) {
// Checking if the currently selected environment is still the same after the new list is loaded
const isChange = !isEqual(
selectedEnvironmentIndex.value.environment,
selectedEnv.environment
)
if (isChange) {
selectedEnvironmentIndex.value = {
type: "TEAM_ENV",
teamEnvID: selectedEnv.id,
teamID: selectedEnv.teamID,
environment: selectedEnv.environment,
}
}
}
}
},
{ deep: true }
)
const selectedEnv = computed(() => {
if (selectedEnvironmentIndex.value.type === "MY_ENV") {
return {
type: "MY_ENV",
index: selectedEnvironmentIndex.value.index,
}
} else if (selectedEnvironmentIndex.value.type === "TEAM_ENV") {
const teamEnv = teamEnvironmentList.value.find(
(env) =>
env.id ===
(selectedEnvironmentIndex.value.type === "TEAM_ENV" &&
selectedEnvironmentIndex.value.teamEnvID)
)
if (teamEnv) {
return {
type: "TEAM_ENV",
name: teamEnv.environment.name,
teamEnvID: selectedEnvironmentIndex.value.teamEnvID,
}
} else {
selectedEnvironmentIndex.value = { type: "NO_ENV_SELECTED" }
return { type: "NO_ENV_SELECTED" }
}
} else {
selectedEnvironmentIndex.value = { type: "NO_ENV_SELECTED" }
return { type: "NO_ENV_SELECTED" }
}
})
const getErrorMessage = (err: GQLError<string>) => {
if (err.type === "network_error") {
return t("error.network_error")
} else {
switch (err.error) {
case "team_environment/not_found":
return t("team_environment.not_found")
default:
return t("error.something_went_wrong")
}
}
}
// Template refs
const tippyActions = ref<any | null>(null)
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
}
const tippyActions = ref<TippyComponent | null>(null)
</script>

View File

@@ -101,18 +101,12 @@
</div>
</template>
<template #footer>
<span class="flex space-x-2">
<span class="flex">
<ButtonPrimary
:label="`${t('action.save')}`"
outline
@click="saveEnvironment"
/>
<ButtonSecondary
:label="`${t('action.cancel')}`"
outline
filled
@click="hideModal"
/>
<ButtonSecondary :label="`${t('action.cancel')}`" @click="hideModal" />
</span>
</template>
</SmartModal>
@@ -120,7 +114,7 @@
<script setup lang="ts">
import IconTrash2 from "~icons/lucide/trash-2"
import IconCheck from "~icons/lucide/check"
import IconDone from "~icons/lucide/check"
import IconPlus from "~icons/lucide/plus"
import IconTrash from "~icons/lucide/trash"
import { clone } from "lodash-es"
@@ -137,8 +131,8 @@ import {
getEnvironment,
getGlobalVariables,
globalEnv$,
setCurrentEnvironment,
setGlobalEnvVariables,
setSelectedEnvironmentIndex,
updateEnvironment,
} from "~/newstore/environments"
import { useI18n } from "@composables/i18n"
@@ -184,7 +178,7 @@ const vars = ref<EnvironmentVariable[]>([
{ id: idTicker.value++, env: { key: "", value: "" } },
])
const clearIcon = refAutoReset<typeof IconTrash2 | typeof IconCheck>(
const clearIcon = refAutoReset<typeof IconTrash2 | typeof IconDone>(
IconTrash2,
1000
)
@@ -203,7 +197,10 @@ const workingEnv = computed(() => {
variables: props.envVars(),
}
} else if (props.editingEnvironmentIndex !== null) {
return getEnvironment(props.editingEnvironmentIndex)
return getEnvironment({
type: "MY_ENV",
index: props.editingEnvironmentIndex,
})
} else {
return null
}
@@ -229,10 +226,10 @@ const liveEnvs = computed(() => {
}
if (props.editingEnvironmentIndex === "Global") {
return [...vars.value.map((x) => ({ ...x, source: name.value! }))]
return [...vars.value.map((x) => ({ ...x.env, source: name.value! }))]
} else {
return [
...vars.value.map((x) => ({ ...x, source: name.value! })),
...vars.value.map((x) => ({ ...x.env, source: name.value! })),
...globalVars.value.map((x) => ({ ...x, source: "Global" })),
]
}
@@ -255,16 +252,8 @@ watch(
)
const clearContent = () => {
vars.value = [
{
id: idTicker.value++,
env: {
key: "",
value: "",
},
},
]
clearIcon.value = IconCheck
vars.value = []
clearIcon.value = IconDone
toast.success(`${t("state.cleared")}`)
}
@@ -307,7 +296,10 @@ const saveEnvironment = () => {
// Creating a new environment
createEnvironment(name.value)
updateEnvironment(envList.value.length - 1, environmentUpdated)
setCurrentEnvironment(envList.value.length - 1)
setSelectedEnvironmentIndex({
type: "MY_ENV",
index: envList.value.length - 1,
})
toast.success(`${t("environment.created")}`)
} else if (props.editingEnvironmentIndex === "Global") {
// Editing the Global environment

View File

@@ -1,7 +1,7 @@
<template>
<div
class="flex items-stretch group"
@contextmenu.prevent="options.tippy.show()"
@contextmenu.prevent="options!.tippy.show()"
>
<span
class="flex items-center justify-center px-4 cursor-pointer"
@@ -23,7 +23,7 @@
interactive
trigger="click"
theme="popover"
:on-shown="() => tippyActions.focus()"
:on-shown="() => tippyActions!.focus()"
>
<ButtonSecondary
v-tippy="{ theme: 'tooltip' }"
@@ -35,10 +35,13 @@
ref="tippyActions"
class="flex flex-col focus:outline-none"
tabindex="0"
@keyup.e="edit.$el.click()"
@keyup.d="duplicate.$el.click()"
role="menu"
@keyup.e="edit!.$el.click()"
@keyup.d="duplicate!.$el.click()"
@keyup.delete="
!(environmentIndex === 'Global') ? deleteAction.$el.click() : null
!(environmentIndex === 'Global')
? deleteAction!.$el.click()
: null
"
@keyup.escape="hide()"
>
@@ -110,6 +113,8 @@ import {
} from "~/newstore/environments"
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import { TippyComponent } from "vue-tippy"
import SmartItem from "@components/smart/Item.vue"
const t = useI18n()
const toast = useToast()
@@ -125,12 +130,11 @@ const emit = defineEmits<{
const confirmRemove = ref(false)
// Template refs
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 tippyActions = ref<TippyComponent | null>(null)
const options = ref<TippyComponent | null>(null)
const edit = ref<typeof SmartItem | null>(null)
const duplicate = ref<typeof SmartItem | null>(null)
const deleteAction = ref<typeof SmartItem | null>(null)
const removeEnvironment = () => {
if (props.environmentIndex === null) return

View File

@@ -0,0 +1,121 @@
<template>
<div>
<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>
<EnvironmentsMyEnvironment
environment-index="Global"
:environment="globalEnvironment"
class="border-b border-dashed border-dividerLight"
@edit-environment="editEnvironment('Global')"
/>
<EnvironmentsMyEnvironment
v-for="(environment, index) in environments"
:key="`environment-${index}`"
:environment-index="index"
:environment="environment"
@edit-environment="editEnvironment(index)"
/>
<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>
<EnvironmentsMyDetails
: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 { computed, ref } from "vue"
import { environments$, globalEnv$ } from "~/newstore/environments"
import { useColorMode } from "~/composables/theming"
import { useReadonlyStream } from "@composables/stream"
import { useI18n } from "~/composables/i18n"
import IconArchive from "~icons/lucide/archive"
import IconPlus from "~icons/lucide/plus"
import IconHelpCircle from "~icons/lucide/help-circle"
const t = useI18n()
const colorMode = useColorMode()
const globalEnv = useReadonlyStream(globalEnv$, [])
const globalEnvironment = computed(() => ({
name: "Global",
variables: globalEnv.value,
}))
const environments = useReadonlyStream(environments$, [])
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>

View File

@@ -0,0 +1,340 @@
<template>
<SmartModal
v-if="show"
dialog
:title="t(`environment.${action}`)"
@close="hideModal"
>
<template #body>
<div class="flex flex-col px-2">
<div class="relative flex">
<input
id="selectLabelEnvEdit"
v-model="name"
v-focus
class="input floating-input"
:class="isViewer && 'opacity-25'"
placeholder=""
type="text"
autocomplete="off"
:disabled="isViewer"
@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 v-if="!isViewer" 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"
:class="isViewer && 'opacity-25'"
:placeholder="`${t('count.variable', { count: index + 1 })}`"
:name="'param' + index"
:disabled="isViewer"
/>
<SmartEnvInput
v-model="env.value"
:placeholder="`${t('count.value', { count: index + 1 })}`"
:envs="liveEnvs"
:name="'value' + index"
:readonly="isViewer"
/>
<div v-if="!isViewer" 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
v-if="isViewer"
disabled
:label="`${t('add.new')}`"
filled
class="mb-4"
/>
<ButtonSecondary
v-else
:label="`${t('add.new')}`"
filled
class="mb-4"
@click="addEnvironmentVariable"
/>
</div>
</div>
</div>
</template>
<template v-if="!isViewer" #footer>
<span>
<ButtonPrimary
:label="`${t('action.save')}`"
:loading="isLoading"
@click="saveEnvironment"
/>
<ButtonSecondary :label="`${t('action.cancel')}`" @click="hideModal" />
</span>
</template>
</SmartModal>
</template>
<script setup lang="ts">
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 * as TE from "fp-ts/TaskEither"
import { flow, pipe } from "fp-ts/function"
import { parseTemplateStringE } from "@hoppscotch/data"
import { refAutoReset } from "@vueuse/core"
import { clone } from "lodash-es"
import { useToast } from "@composables/toast"
import { useI18n } from "~/composables/i18n"
import {
createTeamEnvironment,
updateTeamEnvironment,
} from "~/helpers/backend/mutations/TeamEnvironment"
import { GQLError } from "~/helpers/backend/GQLClient"
import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"
import { useColorMode } from "~/composables/theming"
import IconTrash from "~icons/lucide/trash"
import IconTrash2 from "~icons/lucide/trash-2"
import IconDone from "~icons/lucide/check"
import IconPlus from "~icons/lucide/plus"
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"
editingEnvironment: TeamEnvironment | null
editingTeamId: string | undefined
isViewer: boolean
}>(),
{
show: false,
action: "edit",
editingEnvironment: null,
editingTeamId: "",
}
)
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 IconDone>(
IconTrash2,
1000
)
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 []
} else {
return [...vars.value.map((x) => ({ ...x.env, source: name.value! }))]
}
})
watch(
() => props.show,
(show) => {
if (show) {
if (props.editingEnvironment === null) {
name.value = null
vars.value = []
} else {
name.value = props.editingEnvironment.environment.name ?? null
vars.value = pipe(
props.editingEnvironment.environment.variables ?? [],
A.map((e: { key: string; value: string }) => ({
id: idTicker.value++,
env: clone(e),
}))
)
}
}
}
)
const clearContent = () => {
vars.value = []
clearIcon.value = IconDone
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 isLoading = ref(false)
const saveEnvironment = async () => {
isLoading.value = true
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)
)
)
)
if (props.action === "new") {
await pipe(
createTeamEnvironment(
JSON.stringify(filterdVariables),
props.editingTeamId,
name.value
),
TE.match(
(err: GQLError<string>) => {
console.error(err)
toast.error(`${getErrorMessage(err)}`)
},
() => {
hideModal()
toast.success(`${t("environment.created")}`)
}
)
)()
} else {
if (!props.editingEnvironment) {
console.error("No Environment Found")
return
}
await pipe(
updateTeamEnvironment(
JSON.stringify(filterdVariables),
props.editingEnvironment.id,
name.value
),
TE.match(
(err: GQLError<string>) => {
console.error(err)
toast.error(`${getErrorMessage(err)}`)
},
() => {
hideModal()
toast.success(`${t("environment.updated")}`)
}
)
)()
}
isLoading.value = false
}
const hideModal = () => {
name.value = null
emit("hide-modal")
}
const getErrorMessage = (err: GQLError<string>) => {
if (err.type === "network_error") {
return t("error.network_error")
} else {
switch (err.error) {
case "team_environment/not_found":
return t("team_environment.not_found")
default:
return t("error.something_went_wrong")
}
}
}
</script>

View File

@@ -0,0 +1,176 @@
<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.environment.name }}
</span>
</span>
<span>
<tippy
v-if="!isViewer"
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="deleteAction!.$el.click()"
@keyup.escape="options!.tippy().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
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 { ref } from "vue"
import { pipe } from "fp-ts/function"
import * as TE from "fp-ts/TaskEither"
import { useToast } from "@composables/toast"
import { useI18n } from "~/composables/i18n"
import {
deleteTeamEnvironment,
createDuplicateEnvironment as duplicateEnvironment,
} from "~/helpers/backend/mutations/TeamEnvironment"
import { GQLError } from "~/helpers/backend/GQLClient"
import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"
import IconEdit from "~icons/lucide/edit"
import IconCopy from "~icons/lucide/copy"
import IconTrash2 from "~icons/lucide/trash-2"
import IconMoreVertical from "~icons/lucide/more-vertical"
import { TippyComponent } from "vue-tippy"
import SmartItem from "@components/smart/Item.vue"
const t = useI18n()
const toast = useToast()
const props = defineProps<{
environment: TeamEnvironment
isViewer: boolean
}>()
const emit = defineEmits<{
(e: "edit-environment"): void
}>()
const confirmRemove = ref(false)
const tippyActions = ref<TippyComponent | null>(null)
const options = ref<TippyComponent | null>(null)
const edit = ref<typeof SmartItem | null>(null)
const duplicate = ref<typeof SmartItem | null>(null)
const deleteAction = ref<typeof SmartItem | null>(null)
const removeEnvironment = () => {
pipe(
deleteTeamEnvironment(props.environment.id),
TE.match(
(err: GQLError<string>) => {
console.error(err)
toast.error(`${getErrorMessage(err)}`)
},
() => {
toast.success(`${t("team_environment.deleted")}`)
}
)
)()
}
const duplicateEnvironments = () => {
pipe(
duplicateEnvironment(props.environment.id),
TE.match(
(err: GQLError<string>) => {
console.error(err)
toast.error(`${getErrorMessage(err)}`)
},
() => {
toast.success(`${t("team_environment.duplicate")}`)
}
)
)()
}
const getErrorMessage = (err: GQLError<string>) => {
if (err.type === "network_error") {
return t("error.network_error")
} else {
switch (err.error) {
case "team_environment/not_found":
return t("team_environment.not_found")
default:
return t("error.something_went_wrong")
}
}
}
</script>

View File

@@ -0,0 +1,177 @@
<template>
<div>
<div class="flex justify-between flex-1 border-y border-dividerLight">
<ButtonSecondary
v-if="team === undefined || team.myRole === 'VIEWER'"
v-tippy="{ theme: 'tooltip' }"
disabled
class="!rounded-none"
:icon="IconPlus"
:title="t('team.no_access')"
:label="t('action.new')"
/>
<ButtonSecondary
v-else
: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-if="team !== undefined && team.myRole === 'VIEWER'"
v-tippy="{ theme: 'tooltip' }"
disabled
:icon="IconArchive"
:title="t('modal.import_export')"
/>
<ButtonSecondary
v-else
v-tippy="{ theme: 'tooltip' }"
:icon="IconArchive"
:title="t('modal.import_export')"
@click="displayModalImportExport(true)"
/>
</div>
</div>
<div
v-if="!loading && teamEnvironments.length === 0 && !adapterError"
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
v-if="team === undefined || team.myRole === 'VIEWER'"
v-tippy="{ theme: 'tooltip' }"
disabled
filled
class="mb-4"
:icon="IconPlus"
:title="t('team.no_access')"
:label="t('action.new')"
/>
<ButtonSecondary
v-else
:label="`${t('add.new')}`"
filled
class="mb-4"
@click="displayModalAdd(true)"
/>
</div>
<div v-else-if="!loading">
<EnvironmentsTeamsEnvironment
v-for="(environment, index) in JSON.parse(
JSON.stringify(teamEnvironments)
)"
:key="`environment-${index}`"
:environment="environment"
:is-viewer="team?.myRole === 'VIEWER'"
@edit-environment="editEnvironment(environment)"
/>
</div>
<div v-if="loading" class="flex flex-col items-center justify-center p-4">
<SmartSpinner class="my-4" />
<span class="text-secondaryLight">{{ t("state.loading") }}</span>
</div>
<div
v-if="!loading && adapterError"
class="flex flex-col items-center py-4"
>
<i class="mb-4 material-icons">help_outline</i>
{{ getErrorMessage(adapterError) }}
</div>
<EnvironmentsTeamsDetails
:show="showModalDetails"
:action="action"
:editing-environment="editingEnvironment"
:editing-team-id="team?.id"
:is-viewer="team?.myRole === 'VIEWER'"
@hide-modal="displayModalEdit(false)"
/>
<EnvironmentsImportExport
:show="showModalImportExport"
:team-environments="teamEnvironments"
:team-id="team?.id"
@hide-modal="displayModalImportExport(false)"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue"
import { GQLError } from "~/helpers/backend/GQLClient"
import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"
import { useI18n } from "~/composables/i18n"
import { useColorMode } from "~/composables/theming"
import IconPlus from "~icons/lucide/plus"
import IconArchive from "~icons/lucide/archive"
import IconHelpCircle from "~icons/lucide/help-circle"
import { Team } from "~/helpers/backend/graphql"
const t = useI18n()
const colorMode = useColorMode()
type SelectedTeam = Team | undefined
defineProps<{
team: SelectedTeam
teamEnvironments: TeamEnvironment[]
adapterError: GQLError<string> | null
loading: boolean
}>()
const showModalImportExport = ref(false)
const showModalDetails = ref(false)
const action = ref<"new" | "edit">("edit")
const editingEnvironment = ref<TeamEnvironment | 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 = (environment: TeamEnvironment | null) => {
editingEnvironment.value = environment
action.value = "edit"
displayModalEdit(true)
}
const resetSelectedData = () => {
editingEnvironment.value = null
}
const getErrorMessage = (err: GQLError<string>) => {
if (err.type === "network_error") {
return t("error.network_error")
} else {
switch (err.error) {
case "team_environment/not_found":
return t("team_environment.not_found")
default:
return t("error.something_went_wrong")
}
}
}
</script>

View File

@@ -194,7 +194,7 @@
class="my-4"
/>
</div>
<EnvironmentsDetails
<EnvironmentsMyDetails
:show="showModalDetails"
action="new"
:env-vars="getAdditionVars"
@@ -210,9 +210,9 @@ import { useReadonlyStream, useStream } from "@composables/stream"
import { useI18n } from "@composables/i18n"
import {
globalEnv$,
selectedEnvIndex$,
setCurrentEnvironment,
selectedEnvironmentIndex$,
setGlobalEnvVariables,
setSelectedEnvironmentIndex,
} from "~/newstore/environments"
import { restTestResults$, setRESTTestResults } from "~/newstore/RESTSession"
import { HoppTestResult } from "~/helpers/types/HoppTestResult"
@@ -263,9 +263,9 @@ const haveEnvVariables = computed(() => {
})
const selectedEnvironmentIndex = useStream(
selectedEnvIndex$,
-1,
setCurrentEnvironment
selectedEnvironmentIndex$,
{ type: "NO_ENV_SELECTED" },
setSelectedEnvironmentIndex
)
const globalEnvVars = useReadonlyStream(globalEnv$, []) as Ref<
@@ -275,7 +275,9 @@ const globalEnvVars = useReadonlyStream(globalEnv$, []) as Ref<
}>
>
const noEnvSelected = computed(() => selectedEnvironmentIndex.value === -1)
const noEnvSelected = computed(
() => selectedEnvironmentIndex.value.type === "NO_ENV_SELECTED"
)
const globalHasAdditions = computed(() => {
if (!testResults.value?.envDiff.selected.additions) return false

View File

@@ -21,6 +21,7 @@ import { HoppRESTResponse } from "./types/HoppRESTResponse"
import { createRESTNetworkRequestStream } from "./network"
import { HoppTestData, HoppTestResult } from "./types/HoppTestResult"
import { isJSONContentType } from "./utils/contenttypes"
import { updateTeamEnvironment } from "./backend/mutations/TeamEnvironment"
import { getRESTRequest, setRESTTestResults } from "~/newstore/RESTSession"
import {
environmentsStore,
@@ -96,17 +97,35 @@ export const runRESTRequest$ = (): TaskEither<
setGlobalEnvVariables(runResult.right.envs.global)
if (environmentsStore.value.currentEnvironmentIndex !== -1) {
const env = getEnvironment(
environmentsStore.value.currentEnvironmentIndex
)
if (
environmentsStore.value.selectedEnvironmentIndex.type ===
"MY_ENV"
) {
const env = getEnvironment({
type: "MY_ENV",
index: environmentsStore.value.selectedEnvironmentIndex.index,
})
updateEnvironment(
environmentsStore.value.currentEnvironmentIndex,
environmentsStore.value.selectedEnvironmentIndex.index,
{
name: env.name,
variables: runResult.right.envs.selected,
}
)
} else if (
environmentsStore.value.selectedEnvironmentIndex.type ===
"TEAM_ENV"
) {
const env = getEnvironment({
type: "TEAM_ENV",
})
pipe(
updateTeamEnvironment(
JSON.stringify(runResult.right.envs.selected),
environmentsStore.value.selectedEnvironmentIndex.teamEnvID,
env.name
)
)()
}
} else {
setRESTTestResults({
@@ -188,7 +207,7 @@ function translateToSandboxTestResults(
}
const globals = cloneDeep(getGlobalVariables())
const env = cloneDeep(getCurrentEnvironment())
const env = getCurrentEnvironment()
return {
description: "",

View File

@@ -0,0 +1,8 @@
mutation CreateDuplicateEnvironment($id: ID!){
createDuplicateEnvironment (id: $id ){
id
teamID
name
variables
}
}

View File

@@ -0,0 +1,7 @@
mutation CreateTeamEnvironment($variables: String!,$teamID: ID!,$name: String!){
createTeamEnvironment( variables: $variables ,teamID: $teamID ,name: $name){
variables
name
teamID
}
}

View File

@@ -0,0 +1,3 @@
mutation DeleteTeamEnvironment($id: ID!){
deleteTeamEnvironment (id: $id )
}

View File

@@ -0,0 +1,7 @@
mutation UpdateTeamEnvironment($variables: String!,$id: ID!,$name: String!){
updateTeamEnvironment( variables: $variables ,id: $id ,name: $name){
variables
name
id
}
}

View File

@@ -0,0 +1,10 @@
query GetTeamEnvironments($teamID: ID!){
team(teamID: $teamID){
teamEnvironments{
id
name
variables
teamID
}
}
}

View File

@@ -0,0 +1,8 @@
subscription TeamEnvironmentCreated ($teamID: ID!) {
teamEnvironmentCreated(teamID: $teamID) {
id
teamID
name
variables
}
}

View File

@@ -0,0 +1,5 @@
subscription TeamEnvironmentDeleted ($teamID: ID!) {
teamEnvironmentDeleted(teamID: $teamID) {
id
}
}

View File

@@ -0,0 +1,8 @@
subscription TeamEnvironmentUpdated ($teamID: ID!) {
teamEnvironmentUpdated(teamID: $teamID) {
id
teamID
name
variables
}
}

View File

@@ -0,0 +1,69 @@
import { runMutation } from "../GQLClient"
import {
CreateDuplicateEnvironmentDocument,
CreateDuplicateEnvironmentMutation,
CreateDuplicateEnvironmentMutationVariables,
CreateTeamEnvironmentDocument,
CreateTeamEnvironmentMutation,
CreateTeamEnvironmentMutationVariables,
DeleteTeamEnvironmentDocument,
DeleteTeamEnvironmentMutation,
DeleteTeamEnvironmentMutationVariables,
UpdateTeamEnvironmentDocument,
UpdateTeamEnvironmentMutation,
UpdateTeamEnvironmentMutationVariables,
} from "../graphql"
type DeleteTeamEnvironmentError = "team_environment/not_found"
type UpdateTeamEnvironmentError = "team_environment/not_found"
type DuplicateTeamEnvironmentError = "team_environment/not_found"
export const createTeamEnvironment = (
variables: string,
teamID: string,
name: string
) =>
runMutation<
CreateTeamEnvironmentMutation,
CreateTeamEnvironmentMutationVariables,
""
>(CreateTeamEnvironmentDocument, {
variables,
teamID,
name,
})
export const deleteTeamEnvironment = (id: string) =>
runMutation<
DeleteTeamEnvironmentMutation,
DeleteTeamEnvironmentMutationVariables,
DeleteTeamEnvironmentError
>(DeleteTeamEnvironmentDocument, {
id,
})
export const updateTeamEnvironment = (
variables: string,
id: string,
name: string
) =>
runMutation<
UpdateTeamEnvironmentMutation,
UpdateTeamEnvironmentMutationVariables,
UpdateTeamEnvironmentError
>(UpdateTeamEnvironmentDocument, {
variables,
id,
name,
})
export const createDuplicateEnvironment = (id: string) =>
runMutation<
CreateDuplicateEnvironmentMutation,
CreateDuplicateEnvironmentMutationVariables,
DuplicateTeamEnvironmentError
>(CreateDuplicateEnvironmentDocument, {
id,
})

View File

@@ -14,6 +14,7 @@ import {
AggregateEnvironment,
aggregateEnvs$,
getAggregateEnvs,
getSelectedEnvironmentType,
} from "~/newstore/environments"
const HOPP_ENVIRONMENT_REGEX = /(<<[a-zA-Z0-9-_]+>>)/g
@@ -73,6 +74,11 @@ const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>
const finalEnv = E.isLeft(result) ? "error" : result.right
const selectedEnvType = getSelectedEnvironmentType()
const envTypeIcon = `<i class="material-icons inline-flex items-center">${
selectedEnvType === "TEAM_ENV" ? "people" : "person"
}</i>`
return {
pos: start,
end: to,
@@ -81,11 +87,15 @@ const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>
create() {
const dom = document.createElement("span")
const kbd = document.createElement("kbd")
const icon = document.createElement("span")
icon.innerHTML = envTypeIcon
kbd.textContent = finalEnv
dom.appendChild(icon)
dom.appendChild(document.createTextNode(`${envName} `))
dom.appendChild(kbd)
dom.className = "tippy-box"
dom.dataset.theme = "tooltip"
icon.className = "env-icon"
return { dom }
},
}

View File

@@ -0,0 +1,10 @@
import { Environment } from "@hoppscotch/data"
/**
* Defines how a Team Environment is represented in the TeamEnvironmentAdapter
*/
export interface TeamEnvironment {
id: string
teamID: string
environment: Environment
}

View File

@@ -0,0 +1,238 @@
import * as E from "fp-ts/Either"
import { BehaviorSubject, Subscription } from "rxjs"
import { Subscription as WSubscription } from "wonka"
import { pipe } from "fp-ts/function"
import { GQLError, runGQLQuery, runGQLSubscription } from "../backend/GQLClient"
import {
GetTeamEnvironmentsDocument,
TeamEnvironmentCreatedDocument,
TeamEnvironmentDeletedDocument,
TeamEnvironmentUpdatedDocument,
} from "../backend/graphql"
import { TeamEnvironment } from "./TeamEnvironment"
export default class TeamEnvironmentAdapter {
error$: BehaviorSubject<GQLError<string> | null>
loading$: BehaviorSubject<boolean>
teamEnvironmentList$: BehaviorSubject<TeamEnvironment[]>
private isDispose: boolean
private teamEnvironmentCreated$: Subscription | null
private teamEnvironmentUpdated$: Subscription | null
private teamEnvironmentDeleted$: Subscription | null
private teamEnvironmentCreatedSub: WSubscription | null
private teamEnvironmentUpdatedSub: WSubscription | null
private teamEnvironmentDeletedSub: WSubscription | null
constructor(private teamID: string | undefined) {
this.error$ = new BehaviorSubject<GQLError<string> | null>(null)
this.loading$ = new BehaviorSubject<boolean>(false)
this.teamEnvironmentList$ = new BehaviorSubject<TeamEnvironment[]>([])
this.isDispose = true
this.teamEnvironmentCreated$ = null
this.teamEnvironmentDeleted$ = null
this.teamEnvironmentUpdated$ = null
this.teamEnvironmentCreatedSub = null
this.teamEnvironmentDeletedSub = null
this.teamEnvironmentUpdatedSub = null
if (teamID) this.initialize()
}
unsubscribeSubscriptions() {
this.teamEnvironmentCreated$?.unsubscribe()
this.teamEnvironmentDeleted$?.unsubscribe()
this.teamEnvironmentUpdated$?.unsubscribe()
this.teamEnvironmentCreatedSub?.unsubscribe()
this.teamEnvironmentDeletedSub?.unsubscribe()
this.teamEnvironmentUpdatedSub?.unsubscribe()
}
changeTeamID(newTeamID: string | undefined) {
this.teamID = newTeamID
this.teamEnvironmentList$.next([])
this.loading$.next(false)
this.unsubscribeSubscriptions()
if (this.teamID) this.initialize()
}
async initialize() {
if (!this.isDispose) throw new Error(`Adapter is already initialized`)
await this.fetchList()
this.registerSubscriptions()
}
public dispose() {
if (this.isDispose) throw new Error(`Adapter has been disposed`)
this.isDispose = true
this.unsubscribeSubscriptions()
}
async fetchList() {
if (this.teamID === undefined) throw new Error("Team ID is null")
this.loading$.next(true)
const results: TeamEnvironment[] = []
const result = await runGQLQuery({
query: GetTeamEnvironmentsDocument,
variables: {
teamID: this.teamID,
},
})
if (E.isLeft(result)) {
this.error$.next(result.left)
this.loading$.next(false)
console.error(result.left)
throw new Error(`Failed fetching team environments: ${result.left}`)
}
if (result.right.team !== undefined && result.right.team !== null) {
results.push(
...result.right.team.teamEnvironments.map(
(x) =>
<TeamEnvironment>{
id: x.id,
teamID: x.teamID,
environment: {
name: x.name,
variables: JSON.parse(x.variables),
},
}
)
)
}
this.teamEnvironmentList$.next(results)
this.loading$.next(false)
}
private createNewTeamEnvironment(newEnvironment: TeamEnvironment) {
const teamEnvironments = this.teamEnvironmentList$.value
teamEnvironments.push(newEnvironment)
this.teamEnvironmentList$.next(teamEnvironments)
}
private deleteTeamEnvironment(envId: string) {
const teamEnvironments = this.teamEnvironmentList$.value.filter(
({ id }) => id !== envId
)
this.teamEnvironmentList$.next(teamEnvironments)
}
private updateTeamEnvironment(updatedEnvironment: TeamEnvironment) {
const teamEnvironments = this.teamEnvironmentList$.value
const environmentFound = teamEnvironments.find(
({ id }) => id === updatedEnvironment.id
)
if (!environmentFound) return
Object.assign(environmentFound, updatedEnvironment)
this.teamEnvironmentList$.next(teamEnvironments)
}
private registerSubscriptions() {
if (this.teamID === undefined) return
const [teamEnvironmentCreated$, teamEnvironmentCreatedSub] =
runGQLSubscription({
query: TeamEnvironmentCreatedDocument,
variables: {
teamID: this.teamID,
},
})
this.teamEnvironmentCreatedSub = teamEnvironmentCreatedSub
this.teamEnvironmentCreated$ = teamEnvironmentCreated$.subscribe(
(result) => {
if (E.isLeft(result)) {
console.error(result.left)
throw new Error(`Team Environment Create Error ${result.left}`)
}
this.createNewTeamEnvironment(
pipe(
result.right.teamEnvironmentCreated,
(x) =>
<TeamEnvironment>{
id: x.id,
teamID: x.teamID,
environment: {
name: x.name,
variables: JSON.parse(x.variables),
},
}
)
)
}
)
const [teamEnvironmentDeleted$, teamEnvironmentDeletedSub] =
runGQLSubscription({
query: TeamEnvironmentDeletedDocument,
variables: {
teamID: this.teamID,
},
})
this.teamEnvironmentDeletedSub = teamEnvironmentDeletedSub
this.teamEnvironmentDeleted$ = teamEnvironmentDeleted$.subscribe(
(result) => {
if (E.isLeft(result)) {
console.error(result.left)
throw new Error(`Team Environment Delete Error ${result.left}`)
}
this.deleteTeamEnvironment(result.right.teamEnvironmentDeleted.id)
}
)
const [teamEnvironmentUpdated$, teamEnvironmentUpdatedSub] =
runGQLSubscription({
query: TeamEnvironmentUpdatedDocument,
variables: {
teamID: this.teamID,
},
})
this.teamEnvironmentUpdatedSub = teamEnvironmentUpdatedSub
this.teamEnvironmentUpdated$ = teamEnvironmentUpdated$.subscribe(
(result) => {
if (E.isLeft(result)) {
console.error(result.left)
throw new Error(`Team Environment Update Error ${result.left}`)
}
this.updateTeamEnvironment(
pipe(
result.right.teamEnvironmentUpdated,
(x) =>
<TeamEnvironment>{
id: x.id,
teamID: x.teamID,
environment: {
name: x.name,
variables: JSON.parse(x.variables),
},
}
)
)
}
)
}
}

View File

@@ -6,6 +6,16 @@ import DispatchingStore, {
defineDispatchers,
} from "~/newstore/DispatchingStore"
type SelectedEnvironmentIndex =
| { type: "NO_ENV_SELECTED" }
| { type: "MY_ENV"; index: number }
| {
type: "TEAM_ENV"
teamID: string
teamEnvID: string
environment: Environment
}
const defaultEnvironmentsState = {
environments: [
{
@@ -16,27 +26,22 @@ const defaultEnvironmentsState = {
globals: [] as Environment["variables"],
// Current environment index specifies the index
// -1 means no environments are selected
currentEnvironmentIndex: -1,
selectedEnvironmentIndex: {
type: "NO_ENV_SELECTED",
} as SelectedEnvironmentIndex,
}
type EnvironmentStore = typeof defaultEnvironmentsState
const dispatchers = defineDispatchers({
setCurrentEnviromentIndex(
{ environments }: EnvironmentStore,
{ newIndex }: { newIndex: number }
setSelectedEnvironmentIndex(
_: EnvironmentStore,
{
selectedEnvironmentIndex,
}: { selectedEnvironmentIndex: SelectedEnvironmentIndex }
) {
if (newIndex >= environments.length || newIndex <= -2) {
// console.log(
// `Ignoring possibly invalid current environment index assignment (value: ${newIndex})`
// )
return {}
}
return {
currentEnvironmentIndex: newIndex,
selectedEnvironmentIndex,
}
},
appendEnvironments(
@@ -90,22 +95,36 @@ const dispatchers = defineDispatchers({
}
},
deleteEnvironment(
{ environments, currentEnvironmentIndex }: EnvironmentStore,
{
environments,
// currentEnvironmentIndex,
selectedEnvironmentIndex,
}: EnvironmentStore,
{ envIndex }: { envIndex: number }
) {
let newCurrEnvIndex = currentEnvironmentIndex
let newCurrEnvIndex = selectedEnvironmentIndex
// Scenario 1: Currently Selected Env is removed -> Set currently selected to none
if (envIndex === currentEnvironmentIndex) newCurrEnvIndex = -1
if (
selectedEnvironmentIndex.type === "MY_ENV" &&
envIndex === selectedEnvironmentIndex.index
)
newCurrEnvIndex = { type: "NO_ENV_SELECTED" }
// Scenario 2: Currently Selected Env Index > Deletion Index -> Current Selection Index Shifts One Position to the left -> Correct Env Index by moving back 1 index
if (envIndex < currentEnvironmentIndex)
newCurrEnvIndex = currentEnvironmentIndex - 1
if (
selectedEnvironmentIndex.type === "MY_ENV" &&
envIndex < selectedEnvironmentIndex.index
)
newCurrEnvIndex = {
type: "MY_ENV",
index: selectedEnvironmentIndex.index - 1,
}
// Scenario 3: Currently Selected Env Index < Deletion Index -> No change happens at selection position -> Noop
return {
environments: environments.filter((_, index) => index !== envIndex),
currentEnvironmentIndex: newCurrEnvIndex,
selectedEnvironmentIndex: newCurrEnvIndex,
}
},
renameEnvironment(
@@ -263,22 +282,23 @@ export const globalEnv$ = environmentsStore.subject$.pipe(
distinctUntilChanged()
)
export const selectedEnvIndex$ = environmentsStore.subject$.pipe(
pluck("currentEnvironmentIndex"),
export const selectedEnvironmentIndex$ = environmentsStore.subject$.pipe(
pluck("selectedEnvironmentIndex"),
distinctUntilChanged()
)
export const currentEnvironment$ = environmentsStore.subject$.pipe(
map(({ currentEnvironmentIndex, environments }) => {
if (currentEnvironmentIndex === -1) {
map(({ environments, selectedEnvironmentIndex }) => {
if (selectedEnvironmentIndex.type === "NO_ENV_SELECTED") {
const env: Environment = {
name: "No environment",
variables: [],
}
return env
} else if (selectedEnvironmentIndex.type === "MY_ENV") {
return environments[selectedEnvironmentIndex.index]
} else {
return environments[currentEnvironmentIndex]
return selectedEnvironmentIndex.environment
}
})
)
@@ -336,23 +356,35 @@ export function getAggregateEnvs() {
}
export function getCurrentEnvironment(): Environment {
if (environmentsStore.value.currentEnvironmentIndex === -1) {
if (
environmentsStore.value.selectedEnvironmentIndex.type === "NO_ENV_SELECTED"
) {
return {
name: "No environment",
variables: [],
}
} else if (
environmentsStore.value.selectedEnvironmentIndex.type === "MY_ENV"
) {
return environmentsStore.value.environments[
environmentsStore.value.selectedEnvironmentIndex.index
]
} else {
return environmentsStore.value.selectedEnvironmentIndex.environment
}
return environmentsStore.value.environments[
environmentsStore.value.currentEnvironmentIndex
]
}
export function setCurrentEnvironment(newEnvIndex: number) {
export function getSelectedEnvironmentType() {
return environmentsStore.value.selectedEnvironmentIndex.type
}
export function setSelectedEnvironmentIndex(
selectedEnvironmentIndex: SelectedEnvironmentIndex
) {
environmentsStore.dispatch({
dispatcher: "setCurrentEnviromentIndex",
dispatcher: "setSelectedEnvironmentIndex",
payload: {
newIndex: newEnvIndex,
selectedEnvironmentIndex,
},
})
}
@@ -539,6 +571,23 @@ export function updateEnvironmentVariable(
})
}
export function getEnvironment(index: number) {
return environmentsStore.value.environments[index]
type SelectedEnv =
| { type: "NO_ENV_SELECTED" }
| { type: "MY_ENV"; index: number }
| { type: "TEAM_ENV" }
export function getEnvironment(selectedEnv: SelectedEnv) {
if (selectedEnv.type === "MY_ENV") {
return environmentsStore.value.environments[selectedEnv.index]
} else if (
selectedEnv.type === "TEAM_ENV" &&
environmentsStore.value.selectedEnvironmentIndex.type === "TEAM_ENV"
) {
return environmentsStore.value.selectedEnvironmentIndex.environment
} else {
return {
name: "N0_ENV",
variables: [],
}
}
}

View File

@@ -38,8 +38,8 @@ import {
addGlobalEnvVariable,
setGlobalEnvVariables,
globalEnv$,
selectedEnvIndex$,
setCurrentEnvironment,
setSelectedEnvironmentIndex,
selectedEnvironmentIndex$,
} from "./environments"
import {
getDefaultRESTRequest,
@@ -224,11 +224,24 @@ function setupSelectedEnvPersistence() {
),
O.getOrElse(() => -1) // If all the above conditions pass, we are good, else set default value (-1)
)
// Check if current environment index is -1 ie. no environment is selected
if (selectedEnvIndex === -1) {
setSelectedEnvironmentIndex({
type: "NO_ENV_SELECTED",
})
} else {
setSelectedEnvironmentIndex({
type: "MY_ENV",
index: selectedEnvIndex,
})
}
setCurrentEnvironment(selectedEnvIndex)
selectedEnvIndex$.subscribe((index) => {
window.localStorage.setItem("selectedEnvIndex", index.toString())
selectedEnvironmentIndex$.subscribe((envIndex) => {
if (envIndex.type === "MY_ENV") {
window.localStorage.setItem("selectedEnvIndex", envIndex.index.toString())
} else {
window.localStorage.setItem("selectedEnvIndex", "-1")
}
})
}