Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
<template>
<div
class="sticky top-upperSecondaryStickyFold z-10 flex items-center justify-between border-y border-dividerLight bg-primary pl-4"
>
<label class="font-semibold text-secondaryLight">
{{ t("request.query") }}
</label>
<div class="flex">
<HoppButtonSecondary
v-if="showRunActions && subscriptionState === 'SUBSCRIBED'"
v-tippy="{
theme: 'tooltip',
delay: [500, 20],
allowHTML: true,
}"
:title="`${t('request.stop')}`"
:label="`${t('request.stop')}`"
:icon="IconStop"
class="!hover:text-accentDark rounded-none !text-accent"
@click="stopQuery()"
/>
<HoppButtonSecondary
v-if="showRunActions && subscriptionState !== 'SUBSCRIBED'"
v-tippy="{
theme: 'tooltip',
delay: [500, 20],
allowHTML: true,
}"
:title="`${t('request.run')} <kbd>${getSpecialKey()}</kbd><kbd>↩</kbd>`"
:label="`${selectedOperation?.name?.value ?? t('request.run')}`"
:icon="IconPlay"
class="!hover:text-accentDark rounded-none !text-accent"
@click="runQuery(selectedOperation)"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"
:title="`${t(
'request.save'
)} <kbd>${getSpecialKey()}</kbd><kbd>S</kbd>`"
:label="`${t('request.save')}`"
:icon="IconSave"
class="rounded-none"
@click="saveRequest"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('app.wiki')"
to="https://docs.hoppscotch.io/documentation/features/graphql-api-testing"
blank
:icon="IconHelpCircle"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.clear_all')"
:icon="IconTrash2"
@click="clearGQLQuery()"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('state.linewrap')"
:class="{ '!text-accent': WRAP_LINES }"
:icon="IconWrapText"
@click.prevent="toggleNestedSetting('WRAP_LINES', 'graphqlQuery')"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.prettify')"
:icon="prettifyQueryIcon"
@click="prettifyQuery"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.copy')"
:icon="copyQueryIcon"
@click="copyQuery"
/>
</div>
</div>
<div class="h-full relative flex flex-col flex-1">
<div ref="queryEditor" class="absolute inset-0"></div>
</div>
</template>
<script setup lang="ts">
import IconPlay from "~icons/lucide/play"
import IconStop from "~icons/lucide/stop-circle"
import IconSave from "~icons/lucide/save"
import IconHelpCircle from "~icons/lucide/help-circle"
import IconTrash2 from "~icons/lucide/trash-2"
import IconCopy from "~icons/lucide/copy"
import IconCheck from "~icons/lucide/check"
import IconInfo from "~icons/lucide/info"
import IconWand from "~icons/lucide/wand"
import IconWrapText from "~icons/lucide/wrap-text"
import {
onBeforeUnmount,
onMounted,
reactive,
ref,
markRaw,
watch,
nextTick,
computed,
} from "vue"
import { copyToClipboard } from "@helpers/utils/clipboard"
import { useCodemirror } from "@composables/codemirror"
import { useI18n } from "@composables/i18n"
import { refAutoReset, useVModel } from "@vueuse/core"
import { useToast } from "~/composables/toast"
import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"
import { OperationDefinitionNode, parse, print } from "graphql"
import { createGQLQueryLinter } from "~/helpers/editor/linting/gqlQuery"
import queryCompleter from "~/helpers/editor/completion/gqlQuery"
import { selectedGQLOpHighlight } from "~/helpers/editor/gql/operation"
import { debounce } from "lodash-es"
import { ViewUpdate } from "@codemirror/view"
import { defineActionHandler } from "~/helpers/actions"
import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"
import { useNestedSetting } from "~/composables/settings"
import { toggleNestedSetting } from "~/newstore/settings"
import { useService } from "dioc/vue"
import { GQLQueryBuilderService } from "~/services/gql-query-builder.service"
import type { SubscriptionState } from "~/helpers/graphql/connection"
import type { AggregateEnvironment } from "~/newstore/environments"
// Template refs
const queryEditor = ref<any | null>(null)
const t = useI18n()
const toast = useToast()
const props = withDefaults(
defineProps<{
modelValue: string
showRunActions?: boolean
subscriptionState?: SubscriptionState
// Embed-only env scope for `<<var>>` highlights
envs?: AggregateEnvironment[]
// Workspace tab this editor shows; scopes requested cursor moves
tabId?: string
}>(),
{
showRunActions: true,
subscriptionState: undefined,
envs: undefined,
tabId: undefined,
}
)
const emit = defineEmits<{
(e: "save-request"): void
(e: "update:modelValue", val: string): void
(e: "cursor-position", val: number): void
(e: "run-query", definition: OperationDefinitionNode | null): void
(e: "stop-query"): void
}>()
const copyQueryIcon = refAutoReset<typeof IconCopy | typeof IconCheck>(
IconCopy,
1000
)
const prettifyQueryIcon = refAutoReset<
typeof IconWand | typeof IconCheck | typeof IconInfo
>(IconWand, 1000)
const WRAP_LINES = useNestedSetting("WRAP_LINES", "graphqlQuery")
const selectedOperation = ref<OperationDefinitionNode | null>(null)
const gqlQueryString = useVModel(props, "modelValue", emit)
// Unified workspace's schema-explorer → editor insertion runs through
// `GQLQueryBuilderService` — not the legacy `useQuery()` composable that
// backs `graphql/Query.vue`. The service owns its own `updatedQuery`,
// `cursorPosition`, and `operations` refs.
const queryBuilder = useService(GQLQueryBuilderService)
const updatedQuery = queryBuilder.updatedQuery
const cursorPosition = queryBuilder.cursorPosition
const operationDefinitions = queryBuilder.operations
// Active tab's schema — not the legacy /graphql page singleton, which the
// unified workspace never writes.
const gqlTabConn = useService(GQLTabConnectionService)
const schema = gqlTabConn.activeTabSchema
const debouncedOnUpdateQueryState = debounce((update: ViewUpdate) => {
const selectedPos = update.state.selection.main.head
emit("cursor-position", selectedPos)
selectedOperation.value = null
const queryString = update.state.doc.toJSON().join(update.state.lineBreak)
try {
const ast = parse(queryString)
operationDefinitions.value = ast.definitions.filter(
(def) => def.kind === "OperationDefinition"
) as OperationDefinitionNode[]
if (ast.definitions.length === 1) {
selectedOperation.value = ast.definitions[0] as OperationDefinitionNode
return
}
selectedOperation.value =
(ast.definitions.find((def) => {
if (def.kind !== "OperationDefinition") return false
const { start, end } = def.loc!
return selectedPos >= start && selectedPos <= end
}) as OperationDefinitionNode) ?? null
} catch (_error) {
if (queryString.trim() === "") {
operationDefinitions.value = []
}
}
}, 100)
// A pending update from a closing tab must not overwrite the shared
// query-builder service refs after another tab's Query.vue has mounted
// (mirrors Argument.vue's cancel-on-unmount)
onBeforeUnmount(() => {
debouncedOnUpdateQueryState.cancel()
})
onMounted(() => {
try {
const ast = parse(gqlQueryString.value)
operationDefinitions.value = ast.definitions.filter(
(def) => def.kind === "OperationDefinition"
) as OperationDefinitionNode[]
if (ast.definitions.length) {
selectedOperation.value = ast.definitions[0] as OperationDefinitionNode
return
}
} catch (_error) {}
})
const cmQueryEditor = useCodemirror(
queryEditor,
gqlQueryString,
reactive({
extendedEditorConfig: {
mode: "graphql",
placeholder: `${t("request.query")}`,
lineWrapping: WRAP_LINES,
},
linter: createGQLQueryLinter(schema),
completer: queryCompleter(schema),
environmentHighlights: true,
envs: computed(() => props.envs),
predefinedVariablesHighlights: true,
additionalExts: [markRaw(selectedGQLOpHighlight)],
onUpdate: debouncedOnUpdateQueryState,
})
)
watch(updatedQuery, async (newQuery) => {
if (newQuery) {
gqlQueryString.value = newQuery
await nextTick()
if (cursorPosition.value) {
cmQueryEditor.cursor.value = cursorPosition.value
}
}
})
// Cursor-only moves requested by non-editor surfaces (e.g. the AI chat
// pointing at the operation it runs or just wrote) — the `updatedQuery`
// watcher above only fires when the query text itself changes.
const applyRequestedCursor = async (
req: NonNullable<typeof queryBuilder.requestedCursor.value>
) => {
// Let a same-tick query update land in the editor first so the position
// exists in the document being addressed.
await nextTick()
// A newer request superseded this one while waiting.
if (queryBuilder.requestedCursor.value !== req) return
// The editor focuses itself when its cursor is set; a move requested by
// another surface (the chat) must not pull focus away from it.
const previouslyFocused = document.activeElement
cmQueryEditor.cursor.value = { line: req.line, ch: req.ch }
queryBuilder.requestedCursor.value = null
await nextTick()
if (
previouslyFocused instanceof HTMLElement &&
previouslyFocused !== document.activeElement &&
previouslyFocused.isConnected
) {
previouslyFocused.focus({ preventScroll: true })
}
}
watch(
() => queryBuilder.requestedCursor.value,
(req) => {
// A move for another tab was computed from that tab's document.
if (req && (!req.tabId || req.tabId === props.tabId))
applyRequestedCursor(req)
}
)
// Picks up a move requested for this tab while its editor was unmounted.
onMounted(() => {
const req = queryBuilder.requestedCursor.value
if (req?.tabId && req.tabId === props.tabId) applyRequestedCursor(req)
})
const prettifyQuery = () => {
try {
gqlQueryString.value = print(
parse(gqlQueryString.value, {
allowLegacyFragmentVariables: true,
})
)
prettifyQueryIcon.value = IconCheck
} catch (_e) {
toast.error(`${t("error.gql_prettify_invalid_query")}`)
prettifyQueryIcon.value = IconInfo
}
}
const copyQuery = () => {
copyToClipboard(gqlQueryString.value)
copyQueryIcon.value = IconCheck
toast.success(`${t("state.copied_to_clipboard")}`)
}
const clearGQLQuery = () => {
gqlQueryString.value = ""
}
const runQuery = (definition: OperationDefinitionNode | null = null) => {
emit("run-query", definition)
}
const stopQuery = () => {
emit("stop-query")
}
const saveRequest = () => {
emit("save-request")
}
defineActionHandler("editor.format", prettifyQuery)
</script>