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

View File

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