refactor: params should respect the data model

This commit is contained in:
Andrew Bastin
2021-12-31 21:35:09 +05:30
parent da5e7fdde5
commit 5f0d1ae52f
2 changed files with 138 additions and 75 deletions

View File

@@ -39,7 +39,7 @@
<div v-if="bulkMode" ref="bulkEditor"></div>
<div v-else>
<div
v-for="(param, index) in params$"
v-for="(param, index) in workingParams"
:key="`param-${index}`"
class="flex border-b divide-x divide-dividerLight border-dividerLight"
>
@@ -117,7 +117,7 @@
</span>
</div>
<div
v-if="params$.length === 0"
v-if="workingParams.length === 0"
class="flex flex-col items-center justify-center p-4 text-secondaryLight"
>
<img
@@ -142,22 +142,13 @@
</template>
<script setup lang="ts">
import { ref, watch, onBeforeUpdate } from "@nuxtjs/composition-api"
import { ref, watch } from "@nuxtjs/composition-api"
import { HoppRESTParam } from "@hoppscotch/data"
import isEqual from "lodash/isEqual"
import clone from "lodash/clone"
import { useCodemirror } from "~/helpers/editor/codemirror"
import {
useReadonlyStream,
useI18n,
useToast,
} from "~/helpers/utils/composables"
import {
restParams$,
addRESTParam,
updateRESTParam,
deleteRESTParam,
deleteAllRESTParams,
setRESTParams,
} from "~/newstore/RESTSession"
import { useI18n, useToast, useStream } from "~/helpers/utils/composables"
import { restParams$, setRESTParams } from "~/newstore/RESTSession"
const t = useI18n()
@@ -166,19 +157,7 @@ const toast = useToast()
const bulkMode = ref(false)
const bulkParams = ref("")
watch(bulkParams, () => {
try {
const transformation = bulkParams.value.split("\n").map((item) => ({
key: item.substring(0, item.indexOf(":")).trim().replace(/^#/, ""),
value: item.substring(item.indexOf(":") + 1).trim(),
active: !item.trim().startsWith("#"),
}))
setRESTParams(transformation as HoppRESTParam[])
} catch (e) {
toast.error(`${t("error.something_went_wrong")}`)
console.error(e)
}
})
const deletionToast = ref<{ goAway: (delay: number) => void } | null>(null)
const bulkEditor = ref<any | null>(null)
@@ -192,78 +171,162 @@ useCodemirror(bulkEditor, bulkParams, {
environmentHighlights: true,
})
const params$ = useReadonlyStream(restParams$, [])
// The functional parameters list (the parameters actually applied to the session)
const params = useStream(restParams$, [], setRESTParams)
watch(
params$,
(newValue) => {
if (!bulkMode.value)
if (
(newValue[newValue.length - 1]?.key !== "" ||
newValue[newValue.length - 1]?.value !== "") &&
newValue.length
)
addParam()
// The UI representation of the parameters list (has the empty end param)
const workingParams = ref<HoppRESTParam[]>([
{
key: "",
value: "",
active: true,
},
{ deep: true }
])
// Rule: Working Params always have last element is always an empty param
watch(workingParams, (paramsList) => {
if (paramsList.length > 0 && paramsList[paramsList.length - 1].key !== "") {
workingParams.value.push({
key: "",
value: "",
active: true,
})
}
})
// Sync logic between params and working params
watch(
params,
(newParamsList) => {
// Sync should overwrite working params
const filteredWorkingParams = workingParams.value.filter(
(e) => e.key !== ""
)
if (!isEqual(newParamsList, filteredWorkingParams)) {
workingParams.value = newParamsList
}
},
{ immediate: true }
)
onBeforeUpdate(() => editBulkParamsLine(-1, null))
watch(workingParams, (newWorkingParams) => {
const fixedParams = newWorkingParams.filter((e) => e.key !== "")
if (!isEqual(params.value, fixedParams)) {
params.value = fixedParams
}
})
const editBulkParamsLine = (index: number, item?: HoppRESTParam | null) => {
bulkParams.value = params$.value
.reduce((all, param, pIndex) => {
const current =
index === pIndex && item != null
? `${item.active ? "" : "#"}${item.key}: ${item.value}`
: `${param.active ? "" : "#"}${param.key}: ${param.value}`
return [...all, current]
}, [])
.join("\n")
}
// Bulk Editor Syncing with Working Params
watch(bulkParams, () => {
try {
const transformation = bulkParams.value
.split("\n")
.filter((x) => x.trim().length > 0 && x.includes(":"))
.map((item) => ({
key: item
.substring(0, item.indexOf(":"))
.trimLeft()
.replace(/^\/\//, ""),
value: item.substring(item.indexOf(":") + 1).trimLeft(),
active: !item.trim().startsWith("//"),
}))
const clearBulkEditor = () => {
bulkParams.value = ""
}
const filteredParams = workingParams.value.filter((x) => x.key !== "")
if (!isEqual(filteredParams, transformation)) {
workingParams.value = transformation
}
} catch (e) {
toast.error(`${t("error.something_went_wrong")}`)
console.error(e)
}
})
watch(workingParams, (newParamsList) => {
// If we are in bulk mode, don't apply direct changes
if (bulkMode.value) return
try {
const currentBulkParams = bulkParams.value.split("\n").map((item) => ({
key: item.substring(0, item.indexOf(":")).trimLeft().replace(/^\/\//, ""),
value: item.substring(item.indexOf(":") + 1).trimLeft(),
active: !item.trim().startsWith("//"),
}))
const filteredParams = newParamsList.filter((x) => x.key !== "")
if (!isEqual(currentBulkParams, filteredParams)) {
bulkParams.value = filteredParams
.map((param) => {
return `${param.active ? "" : "//"}${param.key}: ${param.value}`
})
.join("\n")
}
} catch (e) {
toast.error(`${t("error.something_went_wrong")}`)
console.error(e)
}
})
const addParam = () => {
const empty = { key: "", value: "", active: true }
const index = params$.value.length
addRESTParam(empty)
editBulkParamsLine(index, empty)
workingParams.value.push({
key: "",
value: "",
active: true,
})
}
const updateParam = (index: number, item: HoppRESTParam) => {
updateRESTParam(index, item)
editBulkParamsLine(index, item)
const updateParam = (index: number, param: HoppRESTParam) => {
workingParams.value = workingParams.value.map((h, i) =>
i === index ? param : h
)
}
const deleteParam = (index: number) => {
const parametersBeforeDeletion = params$.value
const paramsBeforeDeletion = clone(workingParams.value)
deleteRESTParam(index)
editBulkParamsLine(index, null)
if (
!(
paramsBeforeDeletion.length > 0 &&
index === paramsBeforeDeletion.length - 1
)
) {
if (deletionToast.value) {
deletionToast.value.goAway(0)
deletionToast.value = null
}
const deletedItem = parametersBeforeDeletion[index]
if (deletedItem.key || deletedItem.value) {
toast.success(`${t("state.deleted")}`, {
deletionToast.value = toast.success(`${t("state.deleted")}`, {
action: [
{
text: `${t("action.undo")}`,
onClick: (_, toastObject) => {
setRESTParams(parametersBeforeDeletion as HoppRESTParam[])
editBulkParamsLine(index, deletedItem)
workingParams.value = paramsBeforeDeletion
toastObject.goAway(0)
deletionToast.value = null
},
},
],
onComplete: () => {
deletionToast.value = null
},
})
}
workingParams.value.splice(index, 1)
}
const clearContent = () => {
deleteAllRESTParams()
clearBulkEditor()
// set params list to the initial state
workingParams.value = [
{
key: "",
value: "",
active: true,
},
]
bulkParams.value = ""
}
</script>

View File

@@ -27,7 +27,7 @@ export const defaultRESTRequest: HoppRESTRequest = {
v: RESTReqSchemaVersion,
endpoint: "https://echo.hoppscotch.io",
name: "Untitled request",
params: [{ key: "", value: "", active: true }],
params: [],
headers: [],
method: "GET",
auth: {