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
⌨️Add autocomplete widget with command line completion
NBTX19a4156b1c86
diff --git a/assets/css/themes.scss b/assets/css/themes.scssindex 11606549b..d611740f3 100644--- a/assets/css/themes.scss+++ b/assets/css/themes.scss@@ -10,6 +10,8 @@--bg-dark-color: #000000;// Background color--bg-color: #121212;+ // Auto-complete color+ --atc-color: #212121;// Text color--fg-color: #FFF;@@ -26,6 +28,8 @@--bg-dark-color: #ffffff;// Background color--bg-color: #F6F8FA;+ // Auto-complete color+ --atc-color: #F1F1F1;// Text color--fg-color: #121212;@@ -36,4 +40,4 @@--ac-color: #51FF0D;// Active text color--act-color: #121212;-}\ No newline at end of file+}diff --git a/components/autocomplete.vue b/components/autocomplete.vuenew file mode 100644index 000000000..0ec662627--- /dev/null+++ b/components/autocomplete.vue@@ -0,0 +1,190 @@+<template>+ <div class="autocomplete-wrapper">+ <label>+ <slot />+ <input type="text"+ :placeholder="placeholder"+ v-model="value"+ @input="updateSuggestions"+ @keyup="updateSuggestions"+ @click="updateSuggestions"+ @keydown="handleKeystroke"+ ref="acInput"+ :spellcheck="spellcheck"+ :autocapitalize="spellcheck"+ :autocorrect="spellcheck">++ <ul class="suggestions" v-if="suggestions.length > 0 && suggestionsVisible" :style="{ transform: `translate(${suggestionsOffsetLeft}px, 0)` }">+ <li v-for="(suggestion, index) in suggestions" @click.prevent="forceSuggestion(suggestion)" :class="{ active: currentSuggestionIndex === index }">{{ suggestion }}</li>+ </ul>+ </label>+ </div>+</template>++<style lang="scss" scoped>+.autocomplete-wrapper {++ position: relative;++ input:focus + ul.suggestions, ul.suggestions:hover {+ display: block;+ }++ ul.suggestions {+ display: none;+ background-color: var(--atc-color);+ position: absolute;+ top: 90%;+ margin: 0 4px;+ left: 0;++ padding: 0;+ border-radius: 0 0 4px 4px;+ z-index: 9999;+ transition: transform 200ms ease-out;++ li {+ width: 100%;+ display: block;+ margin: 5px 0;+ padding: 10px 10px;+ font-weight: 700;+ font-size: 18px;+ font-family: monospace;+ white-space: pre-wrap;++ &:hover, &.active {+ background-color: var(--ac-color);+ }+ }+ }++}+</style>++<script>+ const KEY_TAB = 9;+ const KEY_ESC = 27;++ const KEY_ARROW_UP = 38;+ const KEY_ARROW_DOWN = 40;++ export default {+ props: {+ spellcheck: {+ type: Boolean,+ default: true,+ required: false+ },++ placeholder: {+ type: String,+ default: 'Start typing...',+ required: false+ },++ source: {+ type: Array,+ required: true+ },++ value: {}+ },++ watch: {+ value () {+ this.$emit('input', this.value);+ }+ },++ data () {+ return {+ value: "",++ selectionStart: 0,+ suggestionsOffsetLeft: 0,+ currentSuggestionIndex: -1,+ suggestionsVisible: false+ }+ },++ methods: {+ updateSuggestions (event) {+ // Hide suggestions if ESC pressed.+ if(event.which && event.which === KEY_ESC){+ event.preventDefault();+ this.suggestionsVisible = false;+ this.currentSuggestionIndex = -1;+ return;+ }++ // As suggestions is a reactive property, this implicitly+ // causes suggestions to update.+ this.selectionStart = this.$refs.acInput.selectionStart;+ this.suggestionsOffsetLeft = (12 * this.selectionStart);+ this.suggestionsVisible = true;+ },++ forceSuggestion (text) {+ let input = this.value.substring(0, this.selectionStart);+ this.value = input + text;++ this.selectionStart = this.value.length;+ this.suggestionsVisible = true;+ this.currentSuggestionIndex = -1;+ },++ handleKeystroke (event) {+ if(event.which === KEY_ARROW_UP){+ event.preventDefault();++ this.currentSuggestionIndex = this.currentSuggestionIndex - 1 >= 0+ ? this.currentSuggestionIndex - 1+ : 0;+ }else if(event.which === KEY_ARROW_DOWN){+ event.preventDefault();++ this.currentSuggestionIndex = this.currentSuggestionIndex < this.suggestions.length - 1+ ? this.currentSuggestionIndex + 1+ : this.suggestions.length - 1;+ }++ if(event.which === KEY_TAB){+ event.preventDefault();++ let activeSuggestion = this.suggestions[this.currentSuggestionIndex >= 0 ? this.currentSuggestionIndex : 0];+ if(activeSuggestion){+ let input = this.value.substring(0, this.selectionStart);+ this.value = input + activeSuggestion;+ }+ }+ }+ },++ computed: {+ /**+ * Gets the suggestions list to be displayed under the input box.+ *+ * @returns {default.props.source|{type, required}}+ */+ suggestions () {+ let input = this.value.substring(0, this.selectionStart);++ return this.source.filter((entry) => {+ return entry.toLowerCase().startsWith(input.toLowerCase())+ && input.toLowerCase() !== entry.toLowerCase();+ })+ // Cut off the part that's already been typed.+ .map((entry) => entry.substring(this.selectionStart))+ // We only want the top 3 suggestions.+ .slice(0, 3);+ }+ },++ mounted () {+ this.updateSuggestions({+ target: this.$refs.acInput+ });+ }+ }+</script>diff --git a/package-lock.json b/package-lock.jsonindex 1886a6dc1..fce563864 100644--- a/package-lock.json+++ b/package-lock.json@@ -10121,6 +10121,11 @@"resolved": "https://registry.npmjs.org/vue-virtual-scroll-list/-/vue-virtual-scroll-list-1.4.2.tgz","integrity": "sha512-jcXl1cYDxGZX+aF9vsUauXWnUkXm8oQxnvLTJ8UMTmMxwzbmlHX7vs0xGDdEej91vJpBNrdNNseWPxboTvI+UA=="},+ "vuejs-auto-complete": {+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/vuejs-auto-complete/-/vuejs-auto-complete-0.9.0.tgz",+ "integrity": "sha512-7UV3s9bXdnsbGARhHcOuDAszGUsz7JpsFKBfHQuQvo4rfH0yQIru2Rb/x2bWU+m+VW4fS9DKDSYi6tY511QSIA=="+ },"vuex": {"version": "3.1.1","resolved": "https://registry.npmjs.org/vuex/-/vuex-3.1.1.tgz",diff --git a/package.json b/package.jsonindex 06ba5fa06..4c6dbad63 100644--- a/package.json+++ b/package.json@@ -5,14 +5,12 @@"author": "liyasthomas","private": true,"scripts": {- "predev": "node build.js --dev",+ "predev": "node build.js --dev","dev": "nuxt",-- "prebuild": "node build.js",+ "prebuild": "node build.js","build": "nuxt build","start": "nuxt start",-- "pregenerate": "node build.js",+ "pregenerate": "node build.js","generate": "nuxt generate"},"dependencies": {@@ -20,6 +18,7 @@"@nuxtjs/pwa": "^3.0.0-0","nuxt": "^2.0.0","vue-virtual-scroll-list": "^1.4.2",+ "vuejs-auto-complete": "^0.9.0","vuex-persist": "^2.0.1"},"devDependencies": {diff --git a/pages/index.vue b/pages/index.vueindex d782a9b0b..0e8df6321 100644--- a/pages/index.vue+++ b/pages/index.vue@@ -1,560 +1,589 @@<template>- <div class="page">- <pw-section class="blue" label="Request" ref="request">- <ul>- <li>- <label for="method">Method</label>- <select id="method" v-model="method">- <option>GET</option>- <option>HEAD</option>- <option>POST</option>- <option>PUT</option>- <option>DELETE</option>- <option>OPTIONS</option>- <option>PATCH</option>- </select>- </li>- <li>- <label for="url">URL</label>- <input id="url" type="url" :class="{ error: !isValidURL }" v-model="url" @keyup.enter="isValidURL ? sendRequest() : null">- </li>- <li>- <label for="path">Path</label>- <input id="path" v-model="path" @keyup.enter="isValidURL ? sendRequest() : null">- </li>- <li>- <label for="action" class="hide-on-small-screen"> </label>- <button id="action" class="show" name="action" @click="sendRequest" :disabled="!isValidURL" ref="sendButton">Send <span id="hidden-message">Again</span></button>- </li>- </ul>- </pw-section>- <pw-section class="blue-dark" label="Request Body" v-if="method === 'POST' || method === 'PUT' || method === 'PATCH'">- <ul>- <li>- <label>Content Type</label>- <select v-model="contentType">- <option>application/json</option>- <option>www-form/urlencoded</option>- </select>- <span>- <input v-model="rawInput" style="cursor: pointer;" type="checkbox" id="rawInput">- <label for="rawInput" style="cursor: pointer;">Raw Input</label>+ <div class="page">+ <pw-section class="blue" label="Request" ref="request">+ <ul>+ <li>+ <label for="method">Method</label>+ <select id="method" v-model="method">+ <option>GET</option>+ <option>HEAD</option>+ <option>POST</option>+ <option>PUT</option>+ <option>DELETE</option>+ <option>OPTIONS</option>+ <option>PATCH</option>+ </select>+ </li>+ <li>+ <label for="url">URL</label>+ <input id="url" type="url" :class="{ error: !isValidURL }" v-model="url" @keyup.enter="isValidURL ? sendRequest() : null">+ </li>+ <li>+ <label for="path">Path</label>+ <input id="path" v-model="path" @keyup.enter="isValidURL ? sendRequest() : null">+ </li>+ <li>+ <label for="action" class="hide-on-small-screen"> </label>+ <button id="action" class="show" name="action" @click="sendRequest" :disabled="!isValidURL" ref="sendButton">Send <span id="hidden-message">Again</span></button>+ </li>+ </ul>+ </pw-section>+ <pw-section class="blue-dark" label="Request Body" v-if="method === 'POST' || method === 'PUT' || method === 'PATCH'">+ <ul>+ <li>+ <autocomplete v-model="contentType" :source="validContentTypes" :spellcheck="false">Content Type</autocomplete>++ <span>+ <pw-toggle :on="rawInput" @change="rawInput = !rawInput">+ Raw input {{ rawInput ? "enabled" : "disabled" }}+ </pw-toggle></span>- </li>- </ul>- <div v-if="!rawInput">- <ol v-for="(param, index) in bodyParams">- <li>- <label :for="'bparam'+index">Key {{index + 1}}</label>- <input :name="'bparam'+index" v-model="param.key">- </li>- <li>- <label :for="'bvalue'+index">Value {{index + 1}}</label>- <input :name="'bvalue'+index" v-model="param.value">- </li>- <li>- <label for="request" class="hide-on-small-screen"> </label>- <button name="request" @click="removeRequestBodyParam(index)">Remove</button>- </li>- </ol>- <ul>- <li>- <label for="addrequest">Action</label>- <button name="addrequest" @click="addRequestBodyParam">Add</button>- </li>- </ul>- <ul>- <li>- <label for="request">Parameter List</label>- <textarea name="request" rows="1" v-textarea-auto-height="rawRequestBody" readonly>{{rawRequestBody || '(add at least one parameter)'}}</textarea>- </li>- </ul>- </div>- <div v-else>- <textarea v-model="rawParams" v-textarea-auto-height="rawParams" style="font-family: monospace;" rows="16" @keydown="formatRawParams"></textarea>- </div>- </pw-section>- <pw-section class="green" label="Authentication" collapsed>- <ul>- <li>- <label for="auth">Authentication Type</label>- <select v-model="auth">- <option>None</option>- <option>Basic</option>- <option>Bearer Token</option>- </select>- </li>- </ul>- <ul v-if="auth === 'Basic'">- <li>- <label for="http_basic_user">User</label>- <input v-model="httpUser">- </li>- <li>- <label for="http_basic_passwd">Password</label>- <input v-model="httpPassword" type="password">- </li>- </ul>- <ul v-if="auth === 'Bearer Token'">- <li>- <label for="bearer_token">Token</label>- <input v-model="bearerToken">- </li>- </ul>- </pw-section>- <pw-section class="orange" label="Headers" collapsed>- <ol v-for="(header, index) in headers">- <li>- <label :for="'header'+index">Key {{index + 1}}</label>- <input :name="'header'+index" v-model="header.key">- </li>- <li>- <label :for="'value'+index">Value {{index + 1}}</label>- <input :name="'value'+index" v-model="header.value">- </li>- <li>- <label for="header" class="hide-on-small-screen"> </label>- <button name="header" @click="removeRequestHeader(index)">Remove</button>- </li>- </ol>- <ul>- <li>- <label for="add">Action</label>- <button name="add" @click="addRequestHeader">Add</button>- </li>- </ul>- <ul>- <li>- <label for="request">Header List</label>- <textarea v-textarea-auto-height="headerString" name="request" rows="1" readonly ref="requestTextarea">{{headerString || '(add at least one header)'}}</textarea>- </li>- </ul>- </pw-section>- <pw-section class="cyan" label="Parameters" collapsed>- <ol v-for="(param, index) in params">- <li>- <label :for="'param'+index">Key {{index + 1}}</label>- <input :name="'param'+index" v-model="param.key">- </li>- <li>- <label :for="'value'+index">Value {{index + 1}}</label>- <input :name="'value'+index" v-model="param.value">- </li>- <li>- <label for="param" class="hide-on-small-screen"> </label>- <button name="param" @click="removeRequestParam(index)">Remove</button>- </li>- </ol>- <ul>- <li>- <label for="add">Action</label>- <button name="add" @click="addRequestParam">Add</button>- </li>- </ul>- <ul>- <li>- <label for="request">Parameter List</label>- <textarea name="request" v-textarea-auto-height="queryString" rows="1" readonly>{{queryString || '(add at least one parameter)'}}</textarea>- </li>- </ul>- </pw-section>- <pw-section class="purple" label="Response" id="response" ref="response">- <ul>- <li>- <label for="status">status</label>- <input name="status" type="text" readonly :value="response.status || '(waiting to send request)'" :class="statusCategory ? statusCategory.className : ''">- </li>- </ul>- <ul v-for="(value, key) in response.headers">- <li>- <label for="value">{{key}}</label>- <input name="value" :value="value" readonly>- </li>- </ul>- <ul>- <li>- <div class="flex-wrap">- <label for="body">response</label>- <button v-if="response.body" name="action" @click="copyResponse">Copy Response</button>- </div>- <div id="response-details-wrapper">- <textarea name="body" rows="16" id="response-details" readonly>{{response.body || '(waiting to send request)'}}</textarea>- <iframe src="about:blank" class="covers-response" ref="previewFrame" :class="{hidden: !previewEnabled}"></iframe>- </div>- <div v-if="response.body && responseType === 'text/html'" class="align-right">- <button @click.prevent="togglePreview">{{ previewEnabled ? 'Hide Preview' : 'Preview HTML' }}</button>- </div>- </li>- </ul>- </pw-section>- <history @useHistory="handleUseHistory" ref="historyComponent" />- </div>+ </li>+ </ul>+ <div v-if="!rawInput">+ <ol v-for="(param, index) in bodyParams">+ <li>+ <label :for="'bparam'+index">Key {{index + 1}}</label>+ <input :name="'bparam'+index" v-model="param.key">+ </li>+ <li>+ <label :for="'bvalue'+index">Value {{index + 1}}</label>+ <input :name="'bvalue'+index" v-model="param.value">+ </li>+ <li>+ <label for="request" class="hide-on-small-screen"> </label>+ <button name="request" @click="removeRequestBodyParam(index)">Remove</button>+ </li>+ </ol>+ <ul>+ <li>+ <label for="addrequest">Action</label>+ <button name="addrequest" @click="addRequestBodyParam">Add</button>+ </li>+ </ul>+ <ul>+ <li>+ <label for="request">Parameter List</label>+ <textarea name="request" rows="1" v-textarea-auto-height="rawRequestBody" readonly>{{rawRequestBody || '(add at least one parameter)'}}</textarea>+ </li>+ </ul>+ </div>+ <div v-else>+ <textarea v-model="rawParams" v-textarea-auto-height="rawParams" style="font-family: monospace;" rows="16" @keydown="formatRawParams"></textarea>+ </div>+ </pw-section>+ <pw-section class="green" label="Authentication" collapsed>+ <ul>+ <li>+ <label for="auth">Authentication Type</label>+ <select v-model="auth">+ <option>None</option>+ <option>Basic</option>+ <option>Bearer Token</option>+ </select>+ </li>+ </ul>+ <ul v-if="auth === 'Basic'">+ <li>+ <label for="http_basic_user">User</label>+ <input v-model="httpUser">+ </li>+ <li>+ <label for="http_basic_passwd">Password</label>+ <input v-model="httpPassword" type="password">+ </li>+ </ul>+ <ul v-if="auth === 'Bearer Token'">+ <li>+ <label for="bearer_token">Token</label>+ <input v-model="bearerToken">+ </li>+ </ul>+ </pw-section>+ <pw-section class="orange" label="Headers" collapsed>+ <ol v-for="(header, index) in headers">+ <li>+ <label :for="'header'+index">Key {{index + 1}}</label>+ <input :name="'header'+index" v-model="header.key">+ </li>+ <li>+ <label :for="'value'+index">Value {{index + 1}}</label>+ <input :name="'value'+index" v-model="header.value">+ </li>+ <li>+ <label for="header" class="hide-on-small-screen"> </label>+ <button name="header" @click="removeRequestHeader(index)">Remove</button>+ </li>+ </ol>+ <ul>+ <li>+ <label for="add">Action</label>+ <button name="add" @click="addRequestHeader">Add</button>+ </li>+ </ul>+ <ul>+ <li>+ <label for="request">Header List</label>+ <textarea v-textarea-auto-height="headerString" name="request" rows="1" readonly ref="requestTextarea">{{headerString || '(add at least one header)'}}</textarea>+ </li>+ </ul>+ </pw-section>+ <pw-section class="cyan" label="Parameters" collapsed>+ <ol v-for="(param, index) in params">+ <li>+ <label :for="'param'+index">Key {{index + 1}}</label>+ <input :name="'param'+index" v-model="param.key">+ </li>+ <li>+ <label :for="'value'+index">Value {{index + 1}}</label>+ <input :name="'value'+index" v-model="param.value">+ </li>+ <li>+ <label for="param" class="hide-on-small-screen"> </label>+ <button name="param" @click="removeRequestParam(index)">Remove</button>+ </li>+ </ol>+ <ul>+ <li>+ <label for="add">Action</label>+ <button name="add" @click="addRequestParam">Add</button>+ </li>+ </ul>+ <ul>+ <li>+ <label for="request">Parameter List</label>+ <textarea name="request" v-textarea-auto-height="queryString" rows="1" readonly>{{queryString || '(add at least one parameter)'}}</textarea>+ </li>+ </ul>+ </pw-section>+ <pw-section class="purple" label="Response" id="response" ref="response">+ <ul>+ <li>+ <label for="status">status</label>+ <input name="status" type="text" readonly :value="response.status || '(waiting to send request)'" :class="statusCategory ? statusCategory.className : ''">+ </li>+ </ul>+ <ul v-for="(value, key) in response.headers">+ <li>+ <label for="value">{{key}}</label>+ <input name="value" :value="value" readonly>+ </li>+ </ul>+ <ul>+ <li>+ <div class="flex-wrap">+ <label for="body">response</label>+ <button v-if="response.body" name="action" @click="copyResponse">Copy Response</button>+ </div>+ <div id="response-details-wrapper">+ <textarea name="body" rows="16" id="response-details" readonly>{{response.body || '(waiting to send request)'}}</textarea>+ <iframe src="about:blank" class="covers-response" ref="previewFrame" :class="{hidden: !previewEnabled}"></iframe>+ </div>+ <div v-if="response.body && responseType === 'text/html'" class="align-right">+ <button @click.prevent="togglePreview">{{ previewEnabled ? 'Hide Preview' : 'Preview HTML' }}</button>+ </div>+ </li>+ </ul>+ </pw-section>+ <history @useHistory="handleUseHistory" ref="historyComponent" />+ </div></template><script>- import history from "../components/history";- import section from "../components/section";- import textareaAutoHeight from "../directives/textareaAutoHeight";+ import autocomplete from '../components/autocomplete';+ import history from "../components/history";+ import section from "../components/section";+ import textareaAutoHeight from "../directives/textareaAutoHeight";+ import toggle from "../components/toggle";- const statusCategories = [{- name: 'informational',- statusCodeRegex: new RegExp(/[1][0-9]+/),- className: 'info-response'- },- {- name: 'successful',- statusCodeRegex: new RegExp(/[2][0-9]+/),- className: 'success-response'- },- {- name: 'redirection',- statusCodeRegex: new RegExp(/[3][0-9]+/),- className: 'redir-response'- },- {- name: 'client error',- statusCodeRegex: new RegExp(/[4][0-9]+/),- className: 'cl-error-response'- },- {- name: 'server error',- statusCodeRegex: new RegExp(/[5][0-9]+/),- className: 'sv-error-response'+ const statusCategories = [{+ name: 'informational',+ statusCodeRegex: new RegExp(/[1][0-9]+/),+ className: 'info-response'},- {- // this object is a catch-all for when no other objects match and should always be last- name: 'unknown',- statusCodeRegex: new RegExp(/.*/),- className: 'missing-data-response'- }- ];- const parseHeaders = xhr => {- const headers = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/);- const headerMap = {};- headers.forEach(line => {- const parts = line.split(': ');- const header = parts.shift().toLowerCase();- const value = parts.join(': ');- headerMap[header] = value- });- return headerMap+ {+ name: 'successful',+ statusCodeRegex: new RegExp(/[2][0-9]+/),+ className: 'success-response'+ },+ {+ name: 'redirection',+ statusCodeRegex: new RegExp(/[3][0-9]+/),+ className: 'redir-response'+ },+ {+ name: 'client error',+ statusCodeRegex: new RegExp(/[4][0-9]+/),+ className: 'cl-error-response'+ },+ {+ name: 'server error',+ statusCodeRegex: new RegExp(/[5][0-9]+/),+ className: 'sv-error-response'+ },+ {+ // this object is a catch-all for when no other objects match and should always be last+ name: 'unknown',+ statusCodeRegex: new RegExp(/.*/),+ className: 'missing-data-response'+ }+ ];+ const parseHeaders = xhr => {+ const headers = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/);+ const headerMap = {};+ headers.forEach(line => {+ const parts = line.split(': ');+ const header = parts.shift().toLowerCase();+ const value = parts.join(': ');+ headerMap[header] = value+ });+ return headerMap- };- export const findStatusGroup = responseStatus => statusCategories.find(status => status.statusCodeRegex.test(responseStatus));+ };+ export const findStatusGroup = responseStatus => statusCategories.find(status => status.statusCodeRegex.test(responseStatus));- export default {- directives: {- textareaAutoHeight- },- components: {- 'pw-section': section,- history- },- data() {- return {- method: 'GET',- url: 'https://reqres.in',- auth: 'None',- path: '/api/users',- httpUser: '',- httpPassword: '',- bearerToken: '',- headers: [],- params: [],- bodyParams: [],- rawParams: '',- rawInput: false,- contentType: 'application/json',- response: {- status: '',- headers: '',- body: ''+ export default {+ directives: {+ textareaAutoHeight},- previewEnabled: false- }- },- computed: {- statusCategory() {- return findStatusGroup(this.response.status);- },- isValidURL() {- const protocol = '^(https?:\\/\\/)?';- const validIP = new RegExp(protocol + "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");- const validHostname = new RegExp(protocol + "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");- return validIP.test(this.url) || validHostname.test(this.url);- },- hasRequestBody() {- return ['POST', 'PUT', 'PATCH'].includes(this.method);- },- rawRequestBody() {- const {- bodyParams- } = this- if (this.contentType === 'application/json') {- try {- const obj = JSON.parse(`{${bodyParams.filter(({ key }) => !!key).map(({ key, value }) => `+ components: {+ 'pw-section': section,+ 'pw-toggle': toggle,+ history,+ autocomplete+ },+ data() {+ return {++ method: 'GET',+ url: 'https://reqres.in',+ auth: 'None',+ path: '/api/users',+ httpUser: '',+ httpPassword: '',+ bearerToken: '',+ headers: [],+ params: [],+ bodyParams: [],+ rawParams: '',+ rawInput: false,+ contentType: 'application/json',+ response: {+ status: '',+ headers: '',+ body: ''+ },+ previewEnabled: false,++ /**+ * These are content types that can be automatically+ * serialized by postwoman.+ */+ knownContentTypes: [+ 'application/json',+ 'application/x-www-form-urlencoded'+ ],++ /**+ * These are a list of Content Types known to Postwoman.+ */+ validContentTypes: [+ 'application/json',+ 'application/hal+json',+ 'application/xml',+ 'application/x-www-form-urlencoded',+ 'text/html',+ 'text/plain'+ ]+ }+ },+ watch: {+ contentType (val) {+ this.rawInput = !this.knownContentTypes.includes(val);+ }+ },+ computed: {+ statusCategory() {+ return findStatusGroup(this.response.status);+ },+ isValidURL() {+ const protocol = '^(https?:\\/\\/)?';+ const validIP = new RegExp(protocol + "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");+ const validHostname = new RegExp(protocol + "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");+ return validIP.test(this.url) || validHostname.test(this.url);+ },+ hasRequestBody() {+ return ['POST', 'PUT', 'PATCH'].includes(this.method);+ },+ rawRequestBody() {+ const {+ bodyParams+ } = this+ if (this.contentType === 'application/json') {+ try {+ const obj = JSON.parse(`{${bodyParams.filter(({ key }) => !!key).map(({ key, value }) => `"${key}": "${value}"`).join()}}`)- return JSON.stringify(obj)- } catch (ex) {- return 'invalid'- }- } else {- return bodyParams- .filter(({- key- }) => !!key)- .map(({- key,- value- }) => `${key}=${encodeURIComponent(value)}`).join('&')- }- },- headerString() {- const result = this.headers- .filter(({- key- }) => !!key)- .map(({- key,- value- }) => `${key}: ${value}`).join(',\n')- return result == '' ? '' : `${result}`- },- queryString() {- const result = this.params- .filter(({- key- }) => !!key)- .map(({- key,- value- }) => `${key}=${encodeURIComponent(value)}`).join('&')- return result === '' ? '' : `?${result}`- },- responseType() {- return (this.response.headers['content-type'] || '').split(';')[0].toLowerCase();- }- },- methods: {- handleUseHistory({- method,- url,- path- }) {- this.method = method;- this.url = url;- this.path = path;- this.$refs.request.$el.scrollIntoView({- behavior: 'smooth'- });- },- async sendRequest() {- if (!this.isValidURL) {- alert('Please check the formatting of the URL.');- return;- }+ return JSON.stringify(obj)+ } catch (ex) {+ return 'invalid'+ }+ } else {+ return bodyParams+ .filter(({+ key+ }) => !!key)+ .map(({+ key,+ value+ }) => `${key}=${encodeURIComponent(value)}`).join('&')+ }+ },+ headerString() {+ const result = this.headers+ .filter(({+ key+ }) => !!key)+ .map(({+ key,+ value+ }) => `${key}: ${value}`).join(',\n')+ return result == '' ? '' : `${result}`+ },+ queryString() {+ const result = this.params+ .filter(({+ key+ }) => !!key)+ .map(({+ key,+ value+ }) => `${key}=${encodeURIComponent(value)}`).join('&')+ return result === '' ? '' : `?${result}`+ },+ responseType() {+ return (this.response.headers['content-type'] || '').split(';')[0].toLowerCase();+ }+ },+ methods: {+ handleUseHistory({+ method,+ url,+ path+ }) {+ this.method = method;+ this.url = url;+ this.path = path;+ this.$refs.request.$el.scrollIntoView({+ behavior: 'smooth'+ });+ },+ async sendRequest() {+ if (!this.isValidURL) {+ alert('Please check the formatting of the URL.');+ return;+ }- // Start showing the loading bar as soon as possible.- // The nuxt axios module will hide it when the request is made.- this.$nuxt.$loading.start();+ // Start showing the loading bar as soon as possible.+ // The nuxt axios module will hide it when the request is made.+ this.$nuxt.$loading.start();- if (this.$refs.response.$el.classList.contains('hidden')) {- this.$refs.response.$el.classList.toggle('hidden')- }- this.$refs.response.$el.scrollIntoView({- behavior: 'smooth'- });- this.previewEnabled = false;- this.response.status = 'Fetching...';- this.response.body = 'Loading...';+ if (this.$refs.response.$el.classList.contains('hidden')) {+ this.$refs.response.$el.classList.toggle('hidden')+ }+ this.$refs.response.$el.scrollIntoView({+ behavior: 'smooth'+ });+ this.previewEnabled = false;+ this.response.status = 'Fetching...';+ this.response.body = 'Loading...';- const auth = this.auth === 'Basic' ? {- username: this.httpUser,- password: this.httpPassword- } : null;+ const auth = this.auth === 'Basic' ? {+ username: this.httpUser,+ password: this.httpPassword+ } : null;- let headers = {};+ let headers = {};- // If the request has a request body, we want to ensure Content-Length and- // Content-Type are sent.- let requestBody;- if (this.hasRequestBody) {- requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;+ // If the request has a request body, we want to ensure Content-Length and+ // Content-Type are sent.+ let requestBody;+ if (this.hasRequestBody) {+ requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;- Object.assign(headers, {- 'Content-Length': requestBody.length,- 'Content-Type': `${this.contentType}; charset=utf-8`- });- }+ Object.assign(headers, {+ 'Content-Length': requestBody.length,+ 'Content-Type': `${this.contentType}; charset=utf-8`+ });+ }- // If the request uses a token for auth, we want to make sure it's sent here.- if (this.auth === 'Bearer Token') headers['Authorization'] = `Bearer ${this.bearerToken}`;+ // If the request uses a token for auth, we want to make sure it's sent here.+ if (this.auth === 'Bearer Token') headers['Authorization'] = `Bearer ${this.bearerToken}`;- headers = Object.assign(- // Clone the app headers object first, we don't want to- // mutate it with the request headers added by default.- Object.assign({}, this.headers),+ headers = Object.assign(+ // Clone the app headers object first, we don't want to+ // mutate it with the request headers added by default.+ Object.assign({}, this.headers),- // We make our temporary headers object the source so- // that you can override the added headers if you- // specify them.- headers- );+ // We make our temporary headers object the source so+ // that you can override the added headers if you+ // specify them.+ headers+ );- try {- const payload = await this.$axios({- method: this.method,- url: this.url + this.path + this.queryString,- auth,- headers,- data: requestBody- });+ try {+ const payload = await this.$axios({+ method: this.method,+ url: this.url + this.path + this.queryString,+ auth,+ headers,+ data: requestBody+ });- (() => {- const status = this.response.status = payload.status;- const headers = this.response.headers = payload.headers;+ (() => {+ const status = this.response.status = payload.status;+ const headers = this.response.headers = payload.headers;- // We don't need to bother parsing JSON, axios already handles it for us!- const body = this.response.body = payload.data;+ // We don't need to bother parsing JSON, axios already handles it for us!+ const body = this.response.body = payload.data;- const date = new Date().toLocaleDateString();- const time = new Date().toLocaleTimeString();+ const date = new Date().toLocaleDateString();+ const time = new Date().toLocaleTimeString();- // Addition of an entry to the history component.- const entry = {- status,- date,- time,- method: this.method,- url: this.url,- path: this.path- };- this.$refs.historyComponent.addEntry(entry);- })();- } catch (error) {- if (error.response) {- this.response.headers = error.response.headers;- this.response.status = error.response.status;- this.response.body = error.response.data;+ // Addition of an entry to the history component.+ const entry = {+ status,+ date,+ time,+ method: this.method,+ url: this.url,+ path: this.path+ };+ this.$refs.historyComponent.addEntry(entry);+ })();+ } catch (error) {+ if (error.response) {+ this.response.headers = error.response.headers;+ this.response.status = error.response.status;+ this.response.body = error.response.data;- // Addition of an entry to the history component.- const entry = {- status: this.response.status,- date: new Date().toLocaleDateString(),- time: new Date().toLocaleTimeString(),- method: this.method,- url: this.url,- path: this.path- };- this.$refs.historyComponent.addEntry(entry);- return;- }+ // Addition of an entry to the history component.+ const entry = {+ status: this.response.status,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ method: this.method,+ url: this.url,+ path: this.path+ };+ this.$refs.historyComponent.addEntry(entry);+ return;+ }- this.response.status = error.message;- this.response.body = "See JavaScript console (F12) for details.";- }- },+ this.response.status = error.message;+ this.response.body = "See JavaScript console (F12) for details.";+ }+ },- addRequestHeader() {- this.headers.push({- key: '',- value: ''- });- return false- },- removeRequestHeader(index) {- this.headers.splice(index, 1)- },- addRequestParam() {- this.params.push({- key: '',- value: ''- })- return false- },- removeRequestParam(index) {- this.params.splice(index, 1)- },- addRequestBodyParam() {- this.bodyParams.push({- key: '',- value: ''- })- return false- },- removeRequestBodyParam(index) {- this.bodyParams.splice(index, 1)- },- formatRawParams(event) {- if ((event.which !== 13 && event.which !== 9)) {- return;- }- const textBody = event.target.value;- const textBeforeCursor = textBody.substring(0, event.target.selectionStart);- const textAfterCursor = textBody.substring(event.target.selectionEnd);- if (event.which === 13) {- event.preventDefault();- const oldSelectionStart = event.target.selectionStart;- const lastLine = textBeforeCursor.split('\n').slice(-1)[0];- const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";- event.target.value = textBeforeCursor + '\n' + rightPadding + textAfterCursor;- setTimeout(() => event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + rightPadding.length + 1, 1);- } else if (event.which === 9) {- event.preventDefault();- const oldSelectionStart = event.target.selectionStart;- event.target.value = textBeforeCursor + '\xa0\xa0' + textAfterCursor;- event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + 2;- return false;- }- },- copyResponse() {- var copyText = document.getElementById("response-details");- copyText.select();- document.execCommand("copy");- },- togglePreview() {- this.previewEnabled = !this.previewEnabled;- if (this.previewEnabled) {- // If you want to add 'preview' support for other response types,- // just add them here.- if (this.responseType === "text/html") {- // If the preview already has that URL loaded, let's not bother re-loading it all.- if (this.$refs.previewFrame.getAttribute('data-previewing-url') === this.url)- return;- // Use DOMParser to parse document HTML.- const previewDocument = new DOMParser().parseFromString(this.response.body, this.responseType);- // Inject <base href="..."> tag to head, to fix relative CSS/HTML paths.- previewDocument.head.innerHTML = `<base href="${this.url}">` + previewDocument.head.innerHTML;- // Finally, set the iframe source to the resulting HTML.- this.$refs.previewFrame.srcdoc = previewDocument.documentElement.outerHTML;- this.$refs.previewFrame.setAttribute('data-previewing-url', this.url);- }- }- },- setRouteQueries(queries) {- for (const key in queries) {- if (this[key]) this[key] = queries[key];- }- },- observeRequestButton() {- const requestElement = this.$refs.request.$el;- const sendButtonElement = this.$refs.sendButton;- const observer = new IntersectionObserver((entries, observer) => {- entries.forEach(entry => {- sendButtonElement.classList.toggle('show');- });- }, { threshold: 1 });+ addRequestHeader() {+ this.headers.push({+ key: '',+ value: ''+ });+ return false+ },+ removeRequestHeader(index) {+ this.headers.splice(index, 1)+ },+ addRequestParam() {+ this.params.push({+ key: '',+ value: ''+ })+ return false+ },+ removeRequestParam(index) {+ this.params.splice(index, 1)+ },+ addRequestBodyParam() {+ this.bodyParams.push({+ key: '',+ value: ''+ })+ return false+ },+ removeRequestBodyParam(index) {+ this.bodyParams.splice(index, 1)+ },+ formatRawParams(event) {+ if ((event.which !== 13 && event.which !== 9)) {+ return;+ }+ const textBody = event.target.value;+ const textBeforeCursor = textBody.substring(0, event.target.selectionStart);+ const textAfterCursor = textBody.substring(event.target.selectionEnd);+ if (event.which === 13) {+ event.preventDefault();+ const oldSelectionStart = event.target.selectionStart;+ const lastLine = textBeforeCursor.split('\n').slice(-1)[0];+ const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";+ event.target.value = textBeforeCursor + '\n' + rightPadding + textAfterCursor;+ setTimeout(() => event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + rightPadding.length + 1, 1);+ } else if (event.which === 9) {+ event.preventDefault();+ const oldSelectionStart = event.target.selectionStart;+ event.target.value = textBeforeCursor + '\xa0\xa0' + textAfterCursor;+ event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + 2;+ return false;+ }+ },+ copyResponse() {+ var copyText = document.getElementById("response-details");+ copyText.select();+ document.execCommand("copy");+ },+ togglePreview() {+ this.previewEnabled = !this.previewEnabled;+ if (this.previewEnabled) {+ // If you want to add 'preview' support for other response types,+ // just add them here.+ if (this.responseType === "text/html") {+ // If the preview already has that URL loaded, let's not bother re-loading it all.+ if (this.$refs.previewFrame.getAttribute('data-previewing-url') === this.url)+ return;+ // Use DOMParser to parse document HTML.+ const previewDocument = new DOMParser().parseFromString(this.response.body, this.responseType);+ // Inject <base href="..."> tag to head, to fix relative CSS/HTML paths.+ previewDocument.head.innerHTML = `<base href="${this.url}">` + previewDocument.head.innerHTML;+ // Finally, set the iframe source to the resulting HTML.+ this.$refs.previewFrame.srcdoc = previewDocument.documentElement.outerHTML;+ this.$refs.previewFrame.setAttribute('data-previewing-url', this.url);+ }+ }+ },+ setRouteQueries(queries) {+ for (const key in queries) {+ if (this[key]) this[key] = queries[key];+ }+ },+ observeRequestButton() {+ const requestElement = this.$refs.request.$el;+ const sendButtonElement = this.$refs.sendButton;+ const observer = new IntersectionObserver((entries, observer) => {+ entries.forEach(entry => {+ sendButtonElement.classList.toggle('show');+ });+ }, { threshold: 1 });- observer.observe(requestElement);- }- },- created() {- if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query);- },- mounted() {- this.observeRequestButton();+ observer.observe(requestElement);+ }+ },+ created() {+ if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query);+ },+ mounted() {+ this.observeRequestButton();+ }}- }</script>