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
: rotating_light: Lint
Liyas Thomasa09d7d76d3a4
diff --git a/README.md b/README.mdindex 1c3b2ccb6..4be62d407 100644--- a/README.md+++ b/README.md@@ -228,6 +228,7 @@ See the [CHANGELOG](CHANGELOG.md) file for details.<td align="center"><a href="https://github.com/nityanandagohain"><img src="https://github.com/nityanandagohain.png?size=100" width="100px;" alt="Nityananda Gohain"/><br /><sub><b>Nityananda Gohain</b></sub></a><br /><a href="https://github.com/liyasthomas/postwoman/commits?author=nityanandagohain" title="Code">💻</a></td><td align="center"><a href="https://github.com/terranblake"><img src="https://github.com/terranblake.png?size=100" width="100px;" alt="Terran Blake"/><br /><sub><b>Terran Blake</b></sub></a><br /><a href="https://github.com/liyasthomas/postwoman/commits?author=terranblake" title="Code">💻</a></td><td align="center"><a href="https://github.com/hosseinnedaee"><img src="https://github.com/hosseinnedaee.png?size=100" width="100px;" alt="Hossein Nedaee"/><br /><sub><b>Hossein Nedaee</b></sub></a><br /><a href="https://github.com/liyasthomas/postwoman/commits?author=hosseinnedaee" title="Code">💻</a></td>+ <td align="center"><a href="https://github.com/vlad0337187"><img src="https://github.com/vlad0337187.png?size=100" width="100px;" alt="Vladislav"/><br /><sub><b>Vladislav</b></sub></a><br /><a href="https://github.com/liyasthomas/postwoman/commits?author=vlad0337187" title="Code">💻</a></td></tr></table>diff --git a/assets/css/fonts.scss b/assets/css/fonts.scssindex e1ef94a7c..e51da7cb5 100644--- a/assets/css/fonts.scss+++ b/assets/css/fonts.scss@@ -1,13 +1,13 @@/* Material Design Icons */@font-face {- font-family: 'Material Icons';+ font-family: "Material Icons";font-style: normal;font-weight: 400;- src: url(~@/assets/fonts/material-icons-v48.woff2) format('woff2');+ src: url(~@/assets/fonts/material-icons-v48.woff2) format("woff2");}.material-icons {- font-family: 'Material Icons';+ font-family: "Material Icons";font-weight: normal;font-style: normal;font-size: 24px;@@ -18,35 +18,42 @@white-space: nowrap;word-wrap: normal;direction: ltr;- -webkit-font-feature-settings: 'liga';+ -webkit-font-feature-settings: "liga";-webkit-font-smoothing: antialiased;}/* Roboto Mono 400 */@font-face {- font-family: 'Roboto Mono';+ font-family: "Roboto Mono";font-style: normal;font-weight: 400;- src: local('Roboto Mono'), local('RobotoMono-Regular'),- url('~@/assets/fonts/roboto-mono-v7-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */- url('~@/assets/fonts/roboto-mono-v7-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */+ src: local("Roboto Mono"), local("RobotoMono-Regular"),+ url("~@/assets/fonts/roboto-mono-v7-latin-regular.woff2") format("woff2"),+ /* Chrome 26+, Opera 23+, Firefox 39+ */+ url("~@/assets/fonts/roboto-mono-v7-latin-regular.woff") format("woff");+ /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */}/* Poppins 500 */@font-face {- font-family: 'Poppins';+ font-family: "Poppins";font-style: normal;font-weight: 500;- src: local('Poppins Medium'), local('Poppins-Medium'),- url('~@/assets/fonts/poppins-v9-latin-500.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */- url('~@/assets/fonts/poppins-v9-latin-500.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */+ src: local("Poppins Medium"), local("Poppins-Medium"),+ url("~@/assets/fonts/poppins-v9-latin-500.woff2") format("woff2"),+ /* Chrome 26+, Opera 23+, Firefox 39+ */+ url("~@/assets/fonts/poppins-v9-latin-500.woff") format("woff");+ /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */}+/* poppins-700 - latin */@font-face {- font-family: 'Poppins';+ font-family: "Poppins";font-style: normal;font-weight: 700;- src: local('Poppins Bold'), local('Poppins-Bold'),- url('~@/assets/fonts/poppins-v9-latin-700.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */- url('~@/assets/fonts/poppins-v9-latin-700.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */+ src: local("Poppins Bold"), local("Poppins-Bold"),+ url("~@/assets/fonts/poppins-v9-latin-700.woff2") format("woff2"),+ /* Chrome 26+, Opera 23+, Firefox 39+ */+ url("~@/assets/fonts/poppins-v9-latin-700.woff") format("woff");+ /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */}diff --git a/assets/css/styles.scss b/assets/css/styles.scssindex 97917b015..f873039c1 100644--- a/assets/css/styles.scss+++ b/assets/css/styles.scss@@ -2,9 +2,11 @@ $responsiveWidth: 720px;// Make theme transition smoother.body.afterLoad {- &, & * {++ &,+ & * {transition: background-color 0.2s ease-in-out,- border 0.2s ease-in-out;+ border 0.2s ease-in-out;}}@@ -180,7 +182,7 @@ h3.title {header,footer {- & > div {+ &>div {display: flex;padding: 16px;width: 100%;@@ -218,7 +220,6 @@ button {transition: all 0.2s ease-in-out;fill: var(--act-color);height: 40px;- box-shadow: 0px 1px 0px rgba(0, 0, 0, 0.02);cursor: pointer;span {@@ -353,7 +354,7 @@ input[type="checkbox"] {display: none;&,- & + label {+ &+label {vertical-align: middle;cursor: pointer;@@ -372,7 +373,7 @@ input[type="checkbox"] {}}- &:checked + label:before {+ &:checked+label:before {background-color: var(--ac-color);border-color: var(--ac-color);color: var(--act-color);@@ -567,7 +568,7 @@ div.tab {display: none;}-input[type="radio"] + label {+input[type="radio"]+label {padding: 8px 16px;border-bottom: 2px solid transparent;cursor: pointer;@@ -578,11 +579,11 @@ input[type="radio"] + label {}}-input[type="radio"]:checked + label {+input[type="radio"]:checked+label {border-color: var(--fg-color);}-input[type="radio"]:checked + label + div.tab {+input[type="radio"]:checked+label+div.tab {display: block;}diff --git a/assets/css/themes.scss b/assets/css/themes.scssindex 69362831b..85228a8eb 100644--- a/assets/css/themes.scss+++ b/assets/css/themes.scss@@ -1,6 +1,5 @@/**Main Themes:-- dark (default)- light- black@@ -33,6 +32,7 @@:root {@include darkTheme;}+@media(prefers-color-scheme: dark) {:root.auto {@include darkTheme;@@ -64,6 +64,7 @@:root.light {@include lightTheme;}+@media(prefers-color-scheme: light) {:root.auto {@include lightTheme;@@ -91,6 +92,7 @@// Active text color--act-color: #000000;}+:root.black {@include blackTheme;}diff --git a/assets/js/curlparser.js b/assets/js/curlparser.jsindex be4386ce1..39aad35a2 100644--- a/assets/js/curlparser.js+++ b/assets/js/curlparser.js@@ -2,222 +2,229 @@ import * as cookie from "cookie";import * as URL from "url";import * as querystring from "querystring";-/*** given this: [ 'msg1=value1', 'msg2=value2' ]* output this: 'msg1=value1&msg2=value2'* @param dataArguments*/function joinDataArguments(dataArguments) {- let data = '';- dataArguments.forEach(function(argument, i) {- if (i === 0) {- data += argument;- } else {- data += '&' + argument;- }- })- return data;+ let data = "";+ dataArguments.forEach(function(argument, i) {+ if (i === 0) {+ data += argument;+ } else {+ data += "&" + argument;+ }+ });+ return data;}function parseCurlCommand(curlCommand) {- let newlineFound = /\r|\n/.exec(curlCommand);- if (newlineFound) {- // remove newlines- curlCommand = curlCommand.replace(/\\\r|\\\n/g, '');- }- // yargs parses -XPOST as separate arguments. just prescreen for it.- curlCommand = curlCommand.replace(/ -XPOST/, ' -X POST');- curlCommand = curlCommand.replace(/ -XGET/, ' -X GET');- curlCommand = curlCommand.replace(/ -XPUT/, ' -X PUT');- curlCommand = curlCommand.replace(/ -XPATCH/, ' -X PATCH');- curlCommand = curlCommand.replace(/ -XDELETE/, ' -X DELETE');- curlCommand = curlCommand.trim();- let parsedArguments = require("yargs-parser")(curlCommand);- let cookieString;- let cookies;- let url = parsedArguments._[1];- if (!url) {- for (let argName in parsedArguments) {- if (typeof parsedArguments[argName] === 'string') {- if (['http', 'www.'].includes(parsedArguments[argName])) {- url = parsedArguments[argName];- }- }- }- }- let headers;-- let parseHeaders = function(headerFieldName) {- if (parsedArguments[headerFieldName]) {- if (!headers) {- headers = {};- }- if (!Array.isArray(parsedArguments[headerFieldName])) {- parsedArguments[headerFieldName] = [parsedArguments[headerFieldName]];- }- parsedArguments[headerFieldName].forEach(function(header) {- if (header.includes('Cookie')) {- // stupid javascript tricks: closure- cookieString = header;- } else {- let colonIndex = header.indexOf(':');- let headerName = header.substring(0, colonIndex);- let headerValue = header.substring(colonIndex + 1).trim();- headers[headerName] = headerValue;- }- })- }- }-- parseHeaders('H');- parseHeaders('header');- if (parsedArguments.A) {- if (!headers) {- headers = [];+ let newlineFound = /\r|\n/.exec(curlCommand);+ if (newlineFound) {+ // remove newlines+ curlCommand = curlCommand.replace(/\\\r|\\\n/g, "");+ }+ // yargs parses -XPOST as separate arguments. just prescreen for it.+ curlCommand = curlCommand.replace(/ -XPOST/, " -X POST");+ curlCommand = curlCommand.replace(/ -XGET/, " -X GET");+ curlCommand = curlCommand.replace(/ -XPUT/, " -X PUT");+ curlCommand = curlCommand.replace(/ -XPATCH/, " -X PATCH");+ curlCommand = curlCommand.replace(/ -XDELETE/, " -X DELETE");+ curlCommand = curlCommand.trim();+ let parsedArguments = require("yargs-parser")(curlCommand);+ let cookieString;+ let cookies;+ let url = parsedArguments._[1];+ if (!url) {+ for (let argName in parsedArguments) {+ if (typeof parsedArguments[argName] === "string") {+ if (["http", "www."].includes(parsedArguments[argName])) {+ url = parsedArguments[argName];}- headers['User-Agent'] = parsedArguments.A;- } else if (parsedArguments['user-agent']) {- if (!headers) {- headers = [];- }- headers['User-Agent'] = parsedArguments['user-agent'];- }-- if (parsedArguments.b) {- cookieString = parsedArguments.b;- }- if (parsedArguments.cookie) {- cookieString = parsedArguments.cookie;- }- let multipartUploads;- if (parsedArguments.F) {- multipartUploads = {};- if (!Array.isArray(parsedArguments.F)) {- parsedArguments.F = [parsedArguments.F];- }- parsedArguments.F.forEach(function(multipartArgument) {- // input looks like key=value. value could be json or a file path prepended with an @- let splitArguments = multipartArgument.split('=', 2);- let key = splitArguments[0];- let value = splitArguments[1];- multipartUploads[key] = value;- })- }- if (cookieString) {- let cookieParseOptions = {- decode: function(s) { return s }- }- // separate out cookie headers into separate data structure- // note: cookie is case insensitive- cookies = cookie.parse(cookieString.replace(/^Cookie: /gi, ''), cookieParseOptions);- }- let method;- if (parsedArguments.X === 'POST') {- method = 'post';- } else if (parsedArguments.X === 'PUT' ||- parsedArguments['T']) {- method = 'put';- } else if (parsedArguments.X === 'PATCH') {- method = 'patch';- } else if (parsedArguments.X === 'DELETE') {- method = 'delete';- } else if (parsedArguments.X === 'OPTIONS') {- method = 'options';- } else if ((parsedArguments['d'] ||- parsedArguments['data'] ||- parsedArguments['data-ascii'] ||- parsedArguments['data-binary'] ||- parsedArguments['F'] ||- parsedArguments['form']) && !((parsedArguments['G'] || parsedArguments['get']))) {- method = 'post';- } else if (parsedArguments['I'] ||- parsedArguments['head']) {- method = 'head';- } else {- method = 'get';- }-- let compressed = !!parsedArguments.compressed;- let urlObject = URL.parse(url); // eslint-disable-line-- // if GET request with data, convert data to query string- // NB: the -G flag does not change the http verb. It just moves the data into the url.- if (parsedArguments['G'] || parsedArguments['get']) {- urlObject.query = urlObject.query ? urlObject.query : '';- let option = 'd' in parsedArguments ? 'd' : 'data' in parsedArguments ? 'data' : null;- if (option) {- let urlQueryString = '';-- if (!url.includes('?')) {- url += '?';- } else {- urlQueryString += '&';- }-- if (typeof(parsedArguments[option]) === 'object') {- urlQueryString += parsedArguments[option].join('&');- } else {- urlQueryString += parsedArguments[option];- }- urlObject.query += urlQueryString;- url += urlQueryString;- delete parsedArguments[option];+ }+ }+ }+ let headers;++ let parseHeaders = function(headerFieldName) {+ if (parsedArguments[headerFieldName]) {+ if (!headers) {+ headers = {};+ }+ if (!Array.isArray(parsedArguments[headerFieldName])) {+ parsedArguments[headerFieldName] = [parsedArguments[headerFieldName]];+ }+ parsedArguments[headerFieldName].forEach(function(header) {+ if (header.includes("Cookie")) {+ // stupid javascript tricks: closure+ cookieString = header;+ } else {+ let colonIndex = header.indexOf(":");+ let headerName = header.substring(0, colonIndex);+ let headerValue = header.substring(colonIndex + 1).trim();+ headers[headerName] = headerValue;}- }- let query = querystring.parse(urlObject.query, null, null, { maxKeys: 10000 });-- urlObject.search = null // Clean out the search/query portion.- let request = {- url: url,- urlWithoutQuery: URL.format(urlObject)- }- if (compressed) {- request['compressed'] = true;- }-- if (Object.keys(query).length > 0) {- request.query = query;- }- if (headers) {- request.headers = headers;- }- request['method'] = method;-- if (cookies) {- request.cookies = cookies;- request.cookieString = cookieString.replace('Cookie: ', '');- }- if (multipartUploads) {- request.multipartUploads = multipartUploads;- }- if (parsedArguments.data) {- request.data = parsedArguments.data;- } else if (parsedArguments['data-binary']) {- request.data = parsedArguments['data-binary']- request.isDataBinary = true;- } else if (parsedArguments['d']) {- request.data = parsedArguments['d'];- } else if (parsedArguments['data-ascii']) {- request.data = parsedArguments['data-ascii'];- }-- if (parsedArguments['u']) {- request.auth = parsedArguments['u'];- }- if (parsedArguments['user']) {- request.auth = parsedArguments['user'];- }- if (Array.isArray(request.data)) {- request.dataArray = request.data- request.data = joinDataArguments(request.data);- }-- if (parsedArguments['k'] || parsedArguments['insecure']) {- request.insecure = true;- }- return request;+ });+ }+ };++ parseHeaders("H");+ parseHeaders("header");+ if (parsedArguments.A) {+ if (!headers) {+ headers = [];+ }+ headers["User-Agent"] = parsedArguments.A;+ } else if (parsedArguments["user-agent"]) {+ if (!headers) {+ headers = [];+ }+ headers["User-Agent"] = parsedArguments["user-agent"];+ }++ if (parsedArguments.b) {+ cookieString = parsedArguments.b;+ }+ if (parsedArguments.cookie) {+ cookieString = parsedArguments.cookie;+ }+ let multipartUploads;+ if (parsedArguments.F) {+ multipartUploads = {};+ if (!Array.isArray(parsedArguments.F)) {+ parsedArguments.F = [parsedArguments.F];+ }+ parsedArguments.F.forEach(function(multipartArgument) {+ // input looks like key=value. value could be json or a file path prepended with an @+ let splitArguments = multipartArgument.split("=", 2);+ let key = splitArguments[0];+ let value = splitArguments[1];+ multipartUploads[key] = value;+ });+ }+ if (cookieString) {+ let cookieParseOptions = {+ decode: function(s) {+ return s;+ }+ };+ // separate out cookie headers into separate data structure+ // note: cookie is case insensitive+ cookies = cookie.parse(+ cookieString.replace(/^Cookie: /gi, ""),+ cookieParseOptions+ );+ }+ let method;+ if (parsedArguments.X === "POST") {+ method = "post";+ } else if (parsedArguments.X === "PUT" || parsedArguments["T"]) {+ method = "put";+ } else if (parsedArguments.X === "PATCH") {+ method = "patch";+ } else if (parsedArguments.X === "DELETE") {+ method = "delete";+ } else if (parsedArguments.X === "OPTIONS") {+ method = "options";+ } else if (+ (parsedArguments["d"] ||+ parsedArguments["data"] ||+ parsedArguments["data-ascii"] ||+ parsedArguments["data-binary"] ||+ parsedArguments["F"] ||+ parsedArguments["form"]) &&+ !(parsedArguments["G"] || parsedArguments["get"])+ ) {+ method = "post";+ } else if (parsedArguments["I"] || parsedArguments["head"]) {+ method = "head";+ } else {+ method = "get";+ }++ let compressed = !!parsedArguments.compressed;+ let urlObject = URL.parse(url); // eslint-disable-line++ // if GET request with data, convert data to query string+ // NB: the -G flag does not change the http verb. It just moves the data into the url.+ if (parsedArguments["G"] || parsedArguments["get"]) {+ urlObject.query = urlObject.query ? urlObject.query : "";+ let option =+ "d" in parsedArguments ? "d" : "data" in parsedArguments ? "data" : null;+ if (option) {+ let urlQueryString = "";++ if (!url.includes("?")) {+ url += "?";+ } else {+ urlQueryString += "&";+ }++ if (typeof parsedArguments[option] === "object") {+ urlQueryString += parsedArguments[option].join("&");+ } else {+ urlQueryString += parsedArguments[option];+ }+ urlObject.query += urlQueryString;+ url += urlQueryString;+ delete parsedArguments[option];+ }+ }+ let query = querystring.parse(urlObject.query, null, null, {+ maxKeys: 10000+ });++ urlObject.search = null; // Clean out the search/query portion.+ let request = {+ url: url,+ urlWithoutQuery: URL.format(urlObject)+ };+ if (compressed) {+ request["compressed"] = true;+ }++ if (Object.keys(query).length > 0) {+ request.query = query;+ }+ if (headers) {+ request.headers = headers;+ }+ request["method"] = method;++ if (cookies) {+ request.cookies = cookies;+ request.cookieString = cookieString.replace("Cookie: ", "");+ }+ if (multipartUploads) {+ request.multipartUploads = multipartUploads;+ }+ if (parsedArguments.data) {+ request.data = parsedArguments.data;+ } else if (parsedArguments["data-binary"]) {+ request.data = parsedArguments["data-binary"];+ request.isDataBinary = true;+ } else if (parsedArguments["d"]) {+ request.data = parsedArguments["d"];+ } else if (parsedArguments["data-ascii"]) {+ request.data = parsedArguments["data-ascii"];+ }++ if (parsedArguments["u"]) {+ request.auth = parsedArguments["u"];+ }+ if (parsedArguments["user"]) {+ request.auth = parsedArguments["user"];+ }+ if (Array.isArray(request.data)) {+ request.dataArray = request.data;+ request.data = joinDataArguments(request.data);+ }++ if (parsedArguments["k"] || parsedArguments["insecure"]) {+ request.insecure = true;+ }+ return request;}-export default parseCurlCommand;diff --git a/assets/js/pwa.js b/assets/js/pwa.jsindex 81adf4306..02ed1b133 100644--- a/assets/js/pwa.js+++ b/assets/js/pwa.js@@ -35,8 +35,6 @@ export default () => {});// When the app is uninstalled, add the prompts back--return async () => {if (deferredPrompt) {deferredPrompt.prompt();diff --git a/build.js b/build.jsindex fec57b032..b2dd9f89f 100644--- a/build.js+++ b/build.js@@ -1,10 +1,12 @@const axios = require("axios");const fs = require("fs");-const { spawnSync } = require("child_process");+const {+ spawnSync+} = require("child_process");const runCommand = (command, args) =>spawnSync(command, args)- .stdout.toString()- .replace(/\n/g, "");+ .stdout.toString()+ .replace(/\n/g, "");const FAIL_ON_ERROR = false;const PW_BUILD_DATA_DIR = "./.postwoman";@@ -27,7 +29,9 @@ try {.get("https://api.github.com/repos/liyasthomas/postwoman/releases")// If we can't get it from GitHub, we'll resort to getting it from package.json.catch(ex => ({- data: [{ tag_name: require("./package.json").version }]+ data: [{+ tag_name: require("./package.json").version+ }]}))).data[0]["tag_name"];}@@ -37,8 +41,8 @@ try {version.variant =process.env.TRAVIS_BRANCH ||runCommand("git", ["branch"])- .split("* ")[1]- .split(" ")[0] + (IS_DEV_MODE ? " - DEV MODE" : "");+ .split("* ")[1]+ .split(" ")[0] + (IS_DEV_MODE ? " - DEV MODE" : "");if (["", "master"].includes(version.variant))delete version.variant;diff --git a/components/autocomplete.vue b/components/autocomplete.vueindex 26359b574..750bf4897 100644--- a/components/autocomplete.vue+++ b/components/autocomplete.vue@@ -29,176 +29,182 @@</template><style lang="scss" scoped>-.autocomplete-wrapper {- position: relative;+ .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: calc(100% - 4px);- margin: 0 4px;- left: 0;- padding: 0;- border-radius: 0 0 4px 4px;- z-index: 9999;- transition: transform 200ms ease-out;-- li {- width: 100%;+ input:focus + ul.suggestions,+ ul.suggestions:hover {display: block;- padding: 8px 16px;- font-size: 18px;- font-family: 'Roboto Mono', monospace;- white-space: pre-wrap;-- &:last-child {- border-radius: 0 0 4px 4px;- }+ }- &:hover,- &.active {- background-color: var(--ac-color);- color: var(--act-color);- cursor: pointer;+ ul.suggestions {+ display: none;+ background-color: var(--atc-color);+ position: absolute;+ top: calc(100% - 4px);+ 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;+ padding: 8px 16px;+ font-size: 18px;+ font-family: "Roboto Mono", monospace;+ white-space: pre-wrap;++ &:last-child {+ border-radius: 0 0 4px 4px;+ }++ &:hover,+ &.active {+ background-color: var(--ac-color);+ color: var(--act-color);+ cursor: pointer;+ }}}}-}</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+ 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+ }},- placeholder: {- type: String,- default: "Start typing...",- required: false+ watch: {+ value() {+ this.$emit("input", this.value);+ }},- source: {- type: Array,- required: true- }- },+ data() {+ return {+ value: "application/json",+ selectionStart: 0,+ suggestionsOffsetLeft: 0,+ currentSuggestionIndex: -1,+ suggestionsVisible: false+ };+ },- watch: {- value() {- this.$emit("input", this.value);- }- },-- data() {- return {- value: "application/json",- 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;+ 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;- return;+ },++ handleKeystroke(event) {+ switch (event.which) {+ case KEY_ARROW_UP:+ event.preventDefault();+ this.currentSuggestionIndex =+ this.currentSuggestionIndex - 1 >= 0+ ? this.currentSuggestionIndex - 1+ : 0;+ break;++ case KEY_ARROW_DOWN:+ event.preventDefault();+ this.currentSuggestionIndex =+ this.currentSuggestionIndex < this.suggestions.length - 1+ ? this.currentSuggestionIndex + 1+ : this.suggestions.length - 1;+ break;++ case 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;+ }+ break;++ default:+ break;+ }}-- // 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;+ 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)+ );+ }},- handleKeystroke(event) {- switch (event.which) {-- case KEY_ARROW_UP:- event.preventDefault();- this.currentSuggestionIndex =this.currentSuggestionIndex - 1 >= 0 ? this.currentSuggestionIndex - 1 : 0;- break;-- case KEY_ARROW_DOWN:- event.preventDefault();- this.currentSuggestionIndex = this.currentSuggestionIndex < this.suggestions.length - 1 ? this.currentSuggestionIndex + 1- : this.suggestions.length - 1;- break;-- case 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;- }- break;-- default:- break;- }+ mounted() {+ this.updateSuggestions({+ target: this.$refs.acInput+ });}- },-- 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/components/collections/addCollection.vue b/components/collections/addCollection.vueindex 1d10775e3..8466f7de7 100644--- a/components/collections/addCollection.vue+++ b/components/collections/addCollection.vue@@ -1,64 +1,64 @@<template>- <div>- <modal v-if="show" @close="hideModal">- <div slot="header">- <ul>- <li>- <div class="flex-wrap">- <h3 class="title">New Collection</h3>- <div>- <button class="icon" @click="hideModal" >- <i class="material-icons">close</i>- </button>- </div>- </div>- </li>- </ul>+ <modal v-if="show" @close="hideModal">+ <div slot="header">+ <ul>+ <li>+ <div class="flex-wrap">+ <h3 class="title">New Collection</h3>+ <div>+ <button class="icon" @click="hideModal">+ <i class="material-icons">close</i>+ </button></div>- <div slot="body">- <ul>- <li>- <input type="text" v-model="name" placeholder="My New Collection" />- </li>- </ul>- </div>- <div slot="footer">- <ul>- <li>- <button class="icon" @click="addNewCollection">- <i class="material-icons">add</i>- <span>Create</span>- </button>- </li>- </ul>- </div>- </modal>+ </div>+ </li>+ </ul>+ </div>+ <div slot="body">+ <ul>+ <li>+ <input type="text" v-model="name" placeholder="My New Collection" />+ </li>+ </ul></div>+ <div slot="footer">+ <ul>+ <li>+ <button class="icon" @click="addNewCollection">+ <i class="material-icons">add</i>+ <span>Create</span>+ </button>+ </li>+ </ul>+ </div>+ </modal></template><script>-import modal from "../../components/modal";+ import modal from "../../components/modal";-export default {+ export default {props: {- show: Boolean,+ show: Boolean},components: {- modal,+ modal},data() {- return {- name: undefined,- }+ return {+ name: undefined+ };},methods: {- addNewCollection() {- this.$store.commit('postwoman/addNewCollection', { name: this.$data.name })- this.$emit('hide-modal')- },- hideModal() {- this.$emit('hide-modal')- },- },-};+ addNewCollection() {+ this.$store.commit("postwoman/addNewCollection", {+ name: this.$data.name+ });+ this.$emit("hide-modal");+ },+ hideModal() {+ this.$emit("hide-modal");+ }+ }+ };</script>diff --git a/components/collections/addFolder.vue b/components/collections/addFolder.vueindex bc70f87d4..1141bc47a 100644--- a/components/collections/addFolder.vue+++ b/components/collections/addFolder.vue@@ -1,64 +1,67 @@<template>- <modal v-if="show" @close="show = false">- <div slot="header">- <ul>- <li>- <div class="flex-wrap">- <h3 class="title">New Folder</h3>- <div>- <button class="icon" @click="hideModal">- <i class="material-icons">close</i>- </button>- </div>- </div>- </li>- </ul>- </div>- <div slot="body">- <ul>- <li>- <input type="text" v-model="name" placeholder="My New Folder" />- </li>- </ul>- </div>- <div slot="footer">- <ul>- <li>- <button class="icon" @click="addNewFolder">- <i class="material-icons">add</i>- <span>Create</span>- </button>- </li>- </ul>- </div>- </modal>+ <modal v-if="show" @close="show = false">+ <div slot="header">+ <ul>+ <li>+ <div class="flex-wrap">+ <h3 class="title">New Folder</h3>+ <div>+ <button class="icon" @click="hideModal">+ <i class="material-icons">close</i>+ </button>+ </div>+ </div>+ </li>+ </ul>+ </div>+ <div slot="body">+ <ul>+ <li>+ <input type="text" v-model="name" placeholder="My New Folder" />+ </li>+ </ul>+ </div>+ <div slot="footer">+ <ul>+ <li>+ <button class="icon" @click="addNewFolder">+ <i class="material-icons">add</i>+ <span>Create</span>+ </button>+ </li>+ </ul>+ </div>+ </modal></template><script>-import modal from "../../components/modal";+ import modal from "../../components/modal";-export default {+ export default {props: {- show : Boolean,- collection : Object,- collectionIndex : Number,+ show: Boolean,+ collection: Object,+ collectionIndex: Number},components: {- modal,+ modal},data() {- return {- name: undefined,- }+ return {+ name: undefined+ };},methods: {- addNewFolder() {- this.$store.commit('postwoman/addNewFolder', { folder: { name: this.$data.name }, collectionIndex: this.$props.collectionIndex })- this.hideModal()- },- hideModal() {- this.$emit('hide-modal')- },- },-};+ addNewFolder() {+ this.$store.commit("postwoman/addNewFolder", {+ folder: { name: this.$data.name },+ collectionIndex: this.$props.collectionIndex+ });+ this.hideModal();+ },+ hideModal() {+ this.$emit("hide-modal");+ }+ }+ };</script>diff --git a/components/collections/collection.vue b/components/collections/collection.vueindex 332d8d8fb..08aeb8bef 100644--- a/components/collections/collection.vue+++ b/components/collections/collection.vue@@ -1,103 +1,103 @@<template>- <div>- <div class="flex-wrap">- <div>- <button class="icon" @click="toggleShowChildren">- <i class="material-icons" v-show='!showChildren'>arrow_right</i>- <i class="material-icons" v-show='showChildren'>arrow_drop_down</i>- <i class="material-icons">folder</i>- <span>{{collection.name}}</span>- </button>- </div>- <div>- <button class="icon" @click="removeCollection" v-tooltip="'Delete collection'">- <i class="material-icons">delete</i>- </button>- <button class="icon" @click="$emit('edit-collection')" v-tooltip="'Edit collection'">- <i class="material-icons">create</i>- </button>- <button class="icon" @click="$emit('add-folder')" v-tooltip="'New Folder'">- <i class="material-icons">create_new_folder</i>- </button>- </div>- </div>+ <div>+ <div class="flex-wrap">+ <div>+ <button class="icon" @click="toggleShowChildren">+ <i class="material-icons" v-show="!showChildren">arrow_right</i>+ <i class="material-icons" v-show="showChildren">arrow_drop_down</i>+ <i class="material-icons">folder</i>+ <span>{{collection.name}}</span>+ </button>+ </div>+ <div>+ <button class="icon" @click="removeCollection" v-tooltip="'Delete collection'">+ <i class="material-icons">delete</i>+ </button>+ <button class="icon" @click="$emit('edit-collection')" v-tooltip="'Edit collection'">+ <i class="material-icons">create</i>+ </button>+ <button class="icon" @click="$emit('add-folder')" v-tooltip="'New Folder'">+ <i class="material-icons">create_new_folder</i>+ </button>+ </div>+ </div>- <div v-show="showChildren">- <ul>- <li v-for="(folder, index) in collection.folders" :key="folder.name">- <folder- v-bind:folder = "folder"- v-bind:folderIndex = "index"- v-bind:collection-index = "collectionIndex"- v-on:edit-folder = "editFolder(collectionIndex, folder, index)"- v-on:edit-request = "$emit('edit-request', $event)"- />- </li>- <li v-if="(collection.folders.length === 0) && (collection.requests.length === 0)">- <label>Collection is empty</label>- </li>- </ul>+ <div v-show="showChildren">+ <ul>+ <li v-for="(folder, index) in collection.folders" :key="folder.name">+ <folder+ v-bind:folder="folder"+ v-bind:folderIndex="index"+ v-bind:collection-index="collectionIndex"+ v-on:edit-folder="editFolder(collectionIndex, folder, index)"+ v-on:edit-request="$emit('edit-request', $event)"+ />+ </li>+ <li v-if="(collection.folders.length === 0) && (collection.requests.length === 0)">+ <label>Collection is empty</label>+ </li>+ </ul>- <ul>- <li v-for="(request, index) in collection.requests" :key="index">- <request- v-bind:request = "request"- v-bind:collection-index = "collectionIndex"- v-bind:folder-index = "-1"- v-bind:request-index = "index"- v-on:edit-request = "$emit('edit-request', { request, collectionIndex, folderIndex: undefined, requestIndex: index })"- ></request>- </li>- </ul>- </div>+ <ul>+ <li v-for="(request, index) in collection.requests" :key="index">+ <request+ v-bind:request="request"+ v-bind:collection-index="collectionIndex"+ v-bind:folder-index="-1"+ v-bind:request-index="index"+ v-on:edit-request="$emit('edit-request', { request, collectionIndex, folderIndex: undefined, requestIndex: index })"+ ></request>+ </li>+ </ul></div>+ </div></template><style scoped>- ul {- display: flex;- flex-direction: column;- }+ ul {+ display: flex;+ flex-direction: column;+ }- ul li {- display: flex;- padding-left: 16px;- border-left: 1px solid var(--brd-color);- }+ ul li {+ display: flex;+ padding-left: 16px;+ border-left: 1px solid var(--brd-color);+ }</style><script>-import folder from './folder';-import request from './request';+ import folder from "./folder";+ import request from "./request";-export default {+ export default {components: {- folder,- request,+ folder,+ request},props: {- collectionIndex : Number,- collection : Object,+ collectionIndex: Number,+ collection: Object},- data () {- return {- showChildren : false,- selectedFolder : {},- };+ data() {+ return {+ showChildren: false,+ selectedFolder: {}+ };},methods: {- toggleShowChildren() {- this.showChildren = !this.showChildren;- },- removeCollection() {- if (!confirm("Are you sure you want to remove this collection?")) return;- this.$store.commit('postwoman/removeCollection', {- collectionIndex: this.collectionIndex,- });- },- editFolder(collectionIndex, folder, folderIndex) {- this.$emit('edit-folder', { collectionIndex, folder, folderIndex })- },+ toggleShowChildren() {+ this.showChildren = !this.showChildren;+ },+ removeCollection() {+ if (!confirm("Are you sure you want to remove this collection?")) return;+ this.$store.commit("postwoman/removeCollection", {+ collectionIndex: this.collectionIndex+ });+ },+ editFolder(collectionIndex, folder, folderIndex) {+ this.$emit("edit-folder", { collectionIndex, folder, folderIndex });+ }}-};+ };</script>diff --git a/components/collections/editCollection.vue b/components/collections/editCollection.vueindex 5cf952a99..6b67049d2 100644--- a/components/collections/editCollection.vue+++ b/components/collections/editCollection.vue@@ -1,67 +1,71 @@<template>- <div>- <modal v-if="show" @close="hideModel">- <div slot='header'>- <ul>- <li>- <div class="flex-wrap">- <h3 class="title">Edit Collection</h3>- <div>- <button class="icon" @click="hideModel" >- <i class="material-icons">close</i>- </button>- </div>- </div>- </li>- </ul>+ <modal v-if="show" @close="hideModel">+ <div slot="header">+ <ul>+ <li>+ <div class="flex-wrap">+ <h3 class="title">Edit Collection</h3>+ <div>+ <button class="icon" @click="hideModel">+ <i class="material-icons">close</i>+ </button></div>- <div slot="body">- <ul>- <li>- <input type="text" v-model="name" v-bind:placeholder="editingCollection.name" />- </li>- </ul>- </div>- <div slot="footer">- <ul>- <li>- <button class="icon" @click="saveCollection">- <i class="material-icons">save</i>- <span>Save</span>- </button>- </li>- </ul>- </div>- </modal>+ </div>+ </li>+ </ul>+ </div>+ <div slot="body">+ <ul>+ <li>+ <input type="text" v-model="name" v-bind:placeholder="editingCollection.name" />+ </li>+ </ul></div>+ <div slot="footer">+ <ul>+ <li>+ <button class="icon" @click="saveCollection">+ <i class="material-icons">save</i>+ <span>Save</span>+ </button>+ </li>+ </ul>+ </div>+ </modal></template><script>-import modal from "../../components/modal";+ import modal from "../../components/modal";-export default {+ export default {props: {- show : Boolean,- editingCollection : Object,- editingCollectionIndex : Number,+ show: Boolean,+ editingCollection: Object,+ editingCollectionIndex: Number},components: {- modal,+ modal},data() {- return {- name: undefined,- }+ return {+ name: undefined+ };},methods: {- saveCollection() {- const collectionUpdated = { ...this.$props.editingCollection, name: this.$data.name }- this.$store.commit('postwoman/editCollection', { collection: collectionUpdated, collectionIndex: this.$props.editingCollectionIndex })- this.$emit('hide-modal');- },- hideModel() {- this.$emit('hide-modal');- },- },-};+ saveCollection() {+ const collectionUpdated = {+ ...this.$props.editingCollection,+ name: this.$data.name+ };+ this.$store.commit("postwoman/editCollection", {+ collection: collectionUpdated,+ collectionIndex: this.$props.editingCollectionIndex+ });+ this.$emit("hide-modal");+ },+ hideModel() {+ this.$emit("hide-modal");+ }+ }+ };</script>diff --git a/components/collections/editFolder.vue b/components/collections/editFolder.vueindex b0b94f2c8..39c1f8244 100644--- a/components/collections/editFolder.vue+++ b/components/collections/editFolder.vue@@ -1,70 +1,70 @@<template>- <modal v-if="show" @close="show = false">- <div slot="header">- <ul>- <li>- <div class="flex-wrap">- <h3 class="title">Edit Folder</h3>- <div>- <button class="icon" @click="hideModal">- <i class="material-icons">close</i>- </button>- </div>- </div>- </li>- </ul>- </div>- <div slot="body">- <ul>- <li>- <input type="text" v-model="name" v-bind:placeholder="folder.name" />- </li>- </ul>- </div>- <div slot="footer">- <ul>- <li>- <button class="icon" @click="editFolder">- <i class="material-icons">add</i>- <span>Save</span>- </button>- </li>- </ul>- </div>- </modal>+ <modal v-if="show" @close="show = false">+ <div slot="header">+ <ul>+ <li>+ <div class="flex-wrap">+ <h3 class="title">Edit Folder</h3>+ <div>+ <button class="icon" @click="hideModal">+ <i class="material-icons">close</i>+ </button>+ </div>+ </div>+ </li>+ </ul>+ </div>+ <div slot="body">+ <ul>+ <li>+ <input type="text" v-model="name" v-bind:placeholder="folder.name" />+ </li>+ </ul>+ </div>+ <div slot="footer">+ <ul>+ <li>+ <button class="icon" @click="editFolder">+ <i class="material-icons">add</i>+ <span>Save</span>+ </button>+ </li>+ </ul>+ </div>+ </modal></template><script>-import modal from "../../components/modal";+ import modal from "../../components/modal";-export default {+ export default {props: {- show : Boolean,- collection : Object,- collectionIndex : Number,- folder : Object,- folderIndex : Number,+ show: Boolean,+ collection: Object,+ collectionIndex: Number,+ folder: Object,+ folderIndex: Number},components: {- modal,+ modal},data() {- return {- name: undefined,- }+ return {+ name: undefined+ };},methods: {- editFolder() {- this.$store.commit('postwoman/editFolder', {- collectionIndex : this.$props.collectionIndex,- folder : { ...this.$props.folder, name: this.$data.name },- folderIndex : this.$props.folderIndex,- })- this.hideModal()- },- hideModal() {- this.$emit('hide-modal')- },- },-};+ editFolder() {+ this.$store.commit("postwoman/editFolder", {+ collectionIndex: this.$props.collectionIndex,+ folder: { ...this.$props.folder, name: this.$data.name },+ folderIndex: this.$props.folderIndex+ });+ this.hideModal();+ },+ hideModal() {+ this.$emit("hide-modal");+ }+ }+ };</script>diff --git a/components/collections/editRequest.vue b/components/collections/editRequest.vueindex cbcb5c35c..3269b2c4b 100644--- a/components/collections/editRequest.vue+++ b/components/collections/editRequest.vue@@ -1,132 +1,122 @@-<!---Made this component to be separate from `saveRequest` as it handles request editing-only related to it's positioning and naming inside of collections.--->-<template>- <div>- <modal v-if="show" @close="hideModal">- <div slot="header">- <ul>- <li>- <div class="flex-wrap">- <h3 class="title">Edit Request</h3>- <div>- <button class="icon" @click="hideModal">- <i class="material-icons">close</i>- </button>- </div>- </div>- </li>- </ul>- </div>- <div slot="body">- <ul>- <li>- <input type="text" v-model="requestUpdateData.name" v-bind:placeholder="request.name" />- <select type="text" v-model="requestUpdateData.collectionIndex" >- <option- v-for="(collection, index) in $store.state.postwoman.collections"- :key = "index"- :value = "index">- {{ collection.name }}- </option>- </select>- <select type="text" v-model="requestUpdateData.folderIndex">- <option- :key = "undefined"- :value = "undefined">- </option>- <option- v-for="(folder, index) in folders"- :key = "index"- :value = "index">- {{ folder.name }}- </option>- </select>- </li>- </ul>+ <modal v-if="show" @close="hideModal">+ <div slot="header">+ <ul>+ <li>+ <div class="flex-wrap">+ <h3 class="title">Edit Request</h3>+ <div>+ <button class="icon" @click="hideModal">+ <i class="material-icons">close</i>+ </button></div>- <div slot="footer">- <ul>- <li>- <button class="icon" @click="saveRequest">- <i class="material-icons">save</i>- <span>Save</span>- </button>- </li>- </ul>- </div>- </modal>+ </div>+ </li>+ </ul>+ </div>+ <div slot="body">+ <ul>+ <li>+ <input type="text" v-model="requestUpdateData.name" v-bind:placeholder="request.name" />+ <select type="text" v-model="requestUpdateData.collectionIndex">+ <option+ v-for="(collection, index) in $store.state.postwoman.collections"+ :key="index"+ :value="index"+ >{{ collection.name }}</option>+ </select>+ <select type="text" v-model="requestUpdateData.folderIndex">+ <option :key="undefined" :value="undefined"></option>+ <option v-for="(folder, index) in folders" :key="index" :value="index">{{ folder.name }}</option>+ </select>+ </li>+ </ul></div>+ <div slot="footer">+ <ul>+ <li>+ <button class="icon" @click="saveRequest">+ <i class="material-icons">save</i>+ <span>Save</span>+ </button>+ </li>+ </ul>+ </div>+ </modal></template><script>-import modal from "../../components/modal";+ import modal from "../../components/modal";-export default {+ export default {props: {- show : Boolean,- collectionIndex : Number,- folderIndex : Number,- request : Object,- requestIndex : Number,+ show: Boolean,+ collectionIndex: Number,+ folderIndex: Number,+ request: Object,+ requestIndex: Number},components: {- modal,+ modal},data() {- return {- requestUpdateData : {- name : undefined,- collectionIndex : undefined,- folderIndex : undefined,- },+ return {+ requestUpdateData: {+ name: undefined,+ collectionIndex: undefined,+ folderIndex: undefined}+ };},watch: {- 'requestUpdateData.collectionIndex': function resetFolderIndex() {+ "requestUpdateData.collectionIndex": function resetFolderIndex() {// if user choosen some folder, than selected other collection, which doesn't have any folders// than `requestUpdateData.folderIndex` won't be reseted- this.$data.requestUpdateData.folderIndex = undefined- },+ this.$data.requestUpdateData.folderIndex = undefined;+ }},computed: {- folders() {- const userSelectedAnyCollection = this.$data.requestUpdateData.collectionIndex !== undefined- if (!userSelectedAnyCollection) return []+ folders() {+ const userSelectedAnyCollection =+ this.$data.requestUpdateData.collectionIndex !== undefined;+ if (!userSelectedAnyCollection) return [];- return this.$store.state.postwoman.collections[this.$data.requestUpdateData.collectionIndex].folders- },+ return this.$store.state.postwoman.collections[+ this.$data.requestUpdateData.collectionIndex+ ].folders;+ }},methods: {- saveRequest() {- const userSelectedAnyCollection = this.$data.requestUpdateData.collectionIndex !== undefined+ saveRequest() {+ const userSelectedAnyCollection =+ this.$data.requestUpdateData.collectionIndex !== undefined;- const requestUpdated = {- ...this.$props.request,- name : this.$data.requestUpdateData.name || this.$props.request.name,- collection : userSelectedAnyCollection ? this.$data.requestUpdateData.collectionIndex : this.$props.collectionIndex,- folder : this.$data.requestUpdateData.folderIndex,- }+ const requestUpdated = {+ ...this.$props.request,+ name: this.$data.requestUpdateData.name || this.$props.request.name,+ collection: userSelectedAnyCollection+ ? this.$data.requestUpdateData.collectionIndex+ : this.$props.collectionIndex,+ folder: this.$data.requestUpdateData.folderIndex+ };- // pass data separately to don't depend on request's collection, folder fields- // probably, they should be deprecated because they don't describe request itself- this.$store.commit('postwoman/editRequest', {- requestOld : this.$props.request,- requestOldCollectionIndex : this.$props.collectionIndex,- requestOldFolderIndex : this.$props.folderIndex,- requestOldIndex : this.$props.requestIndex,- requestNew : requestUpdated,- requestNewCollectionIndex : requestUpdated.collection,- requestNewFolderIndex : requestUpdated.folder,- });+ // pass data separately to don't depend on request's collection, folder fields+ // probably, they should be deprecated because they don't describe request itself+ this.$store.commit("postwoman/editRequest", {+ requestOld: this.$props.request,+ requestOldCollectionIndex: this.$props.collectionIndex,+ requestOldFolderIndex: this.$props.folderIndex,+ requestOldIndex: this.$props.requestIndex,+ requestNew: requestUpdated,+ requestNewCollectionIndex: requestUpdated.collection,+ requestNewFolderIndex: requestUpdated.folder+ });- this.hideModal()- },- hideModal() {- this.$emit('hide-modal')- },- },-};+ this.hideModal();+ },+ hideModal() {+ this.$emit("hide-modal");+ }+ }+ };</script>diff --git a/components/collections/folder.vue b/components/collections/folder.vueindex 4bacf9830..4deb99575 100644--- a/components/collections/folder.vue+++ b/components/collections/folder.vue@@ -1,90 +1,90 @@<template>- <div>- <div class="flex-wrap">- <div>- <button class="icon" @click="toggleShowChildren">- <i class="material-icons" v-show='!showChildren'>arrow_right</i>- <i class="material-icons" v-show='showChildren'>arrow_drop_down</i>- <i class="material-icons">folder_open</i>- <span>{{folder.name}}</span>- </button>- </div>- <div>- <button class="icon" @click="removeFolder" v-tooltip="'Delete folder'">- <i class="material-icons">delete</i>- </button>- <button class="icon" @click="editFolder" v-tooltip="'Edit folder'">- <i class="material-icons">edit</i>- </button>- </div>- </div>+ <div>+ <div class="flex-wrap">+ <div>+ <button class="icon" @click="toggleShowChildren">+ <i class="material-icons" v-show="!showChildren">arrow_right</i>+ <i class="material-icons" v-show="showChildren">arrow_drop_down</i>+ <i class="material-icons">folder_open</i>+ <span>{{folder.name}}</span>+ </button>+ </div>+ <div>+ <button class="icon" @click="removeFolder" v-tooltip="'Delete folder'">+ <i class="material-icons">delete</i>+ </button>+ <button class="icon" @click="editFolder" v-tooltip="'Edit folder'">+ <i class="material-icons">edit</i>+ </button>+ </div>+ </div>- <div v-show="showChildren">- <ul>- <li v-for="(request, index) in folder.requests" :key="index">- <request- v-bind:request = "request"- v-bind:collection-index = "collectionIndex"- v-bind:folder-index = "folderIndex"- v-bind:request-index = "index"- v-on:edit-request = "$emit('edit-request', { request, collectionIndex, folderIndex, requestIndex: index })"- ></request>- </li>- <li v-if="folder.requests.length === 0">- <label>Folder is empty</label>- </li>- </ul>- </div>+ <div v-show="showChildren">+ <ul>+ <li v-for="(request, index) in folder.requests" :key="index">+ <request+ v-bind:request="request"+ v-bind:collection-index="collectionIndex"+ v-bind:folder-index="folderIndex"+ v-bind:request-index="index"+ v-on:edit-request="$emit('edit-request', { request, collectionIndex, folderIndex, requestIndex: index })"+ ></request>+ </li>+ <li v-if="folder.requests.length === 0">+ <label>Folder is empty</label>+ </li>+ </ul></div>+ </div></template><style scoped>- ul {- display: flex;- flex-direction: column;- }+ ul {+ display: flex;+ flex-direction: column;+ }- ul li {- display: flex;- padding-left: 16px;- border-left: 1px solid var(--brd-color);- }+ ul li {+ display: flex;+ padding-left: 16px;+ border-left: 1px solid var(--brd-color);+ }</style><script>-import request from './request';+ import request from "./request";-export default {+ export default {props: {- folder : Object,- collectionIndex : Number,- folderIndex : Number,+ folder: Object,+ collectionIndex: Number,+ folderIndex: Number},components: {- request,+ request},- data () {- return {- showChildren: false,- };+ data() {+ return {+ showChildren: false+ };},methods: {- toggleShowChildren() {- this.showChildren = !this.showChildren;- },- selectRequest(request) {- this.$store.commit('postwoman/selectRequest', { request });- },- removeFolder() {- if (!confirm("Are you sure you want to remove this folder?")) return;- this.$store.commit('postwoman/removeFolder', {- collectionIndex: this.collectionIndex,- folderIndex: this.folderIndex,- });- },- editFolder() {- this.$emit('edit-folder')- },+ toggleShowChildren() {+ this.showChildren = !this.showChildren;+ },+ selectRequest(request) {+ this.$store.commit("postwoman/selectRequest", { request });+ },+ removeFolder() {+ if (!confirm("Are you sure you want to remove this folder?")) return;+ this.$store.commit("postwoman/removeFolder", {+ collectionIndex: this.collectionIndex,+ folderIndex: this.folderIndex+ });+ },+ editFolder() {+ this.$emit("edit-folder");+ }}-};+ };</script>diff --git a/components/collections/importExportCollections.vue b/components/collections/importExportCollections.vueindex 5e57518a7..a7d54f8ad 100644--- a/components/collections/importExportCollections.vue+++ b/components/collections/importExportCollections.vue@@ -1,110 +1,117 @@<template>- <div>- <modal v-if="show" @close="hideModel">- <div slot="header">- <ul>- <li>- <div class="flex-wrap">- <h3 class="title">Import / Export Collections</h3>- <div>- <button class="icon" @click="hideModel">- <i class="material-icons">close</i>- </button>- </div>- </div>- </li>- </ul>+ <modal v-if="show" @close="hideModel">+ <div slot="header">+ <ul>+ <li>+ <div class="flex-wrap">+ <h3 class="title">Import / Export Collections</h3>+ <div>+ <button class="icon" @click="hideModel">+ <i class="material-icons">close</i>+ </button></div>- <div slot="body">- <textarea v-model='collectionJson' rows="8">- </textarea>- </div>- <div slot="footer">- <ul>- <li>- <button class="icon" @click="openDialogChooseFileToReplaceWith">- <i class="material-icons">get_app</i>- <span>Replace with JSON</span>- <input type="file" @change="replaceWithJSON" style="display: none;" ref="inputChooseFileToReplaceWith">- </button>- </li>- <li>- <button class="icon" @click="openDialogChooseFileToImportFrom">- <i class="material-icons">get_app</i>- <span>Import from JSON</span>- <input type="file" @change="importFromJSON" style="display: none;" ref="inputChooseFileToImportFrom">- </button>- </li>- <li>- <button class="icon" @click="exportJSON">- <i class="material-icons">get_app</i>- <span>Export JSON</span>- </button>- </li>- </ul>- </div>- </modal>+ </div>+ </li>+ </ul>+ </div>+ <div slot="body">+ <textarea v-model="collectionJson" rows="8"></textarea></div>+ <div slot="footer">+ <ul>+ <li>+ <button class="icon" @click="openDialogChooseFileToReplaceWith">+ <i class="material-icons">get_app</i>+ <span>Replace with JSON</span>+ <input+ type="file"+ @change="replaceWithJSON"+ style="display: none;"+ ref="inputChooseFileToReplaceWith"+ />+ </button>+ </li>+ <li>+ <button class="icon" @click="openDialogChooseFileToImportFrom">+ <i class="material-icons">get_app</i>+ <span>Import from JSON</span>+ <input+ type="file"+ @change="importFromJSON"+ style="display: none;"+ ref="inputChooseFileToImportFrom"+ />+ </button>+ </li>+ <li>+ <button class="icon" @click="exportJSON">+ <i class="material-icons">get_app</i>+ <span>Export JSON</span>+ </button>+ </li>+ </ul>+ </div>+ </modal></template><script>-import modal from "../../components/modal";+ import modal from "../../components/modal";-export default {+ export default {props: {- show: Boolean,+ show: Boolean},components: {- modal,+ modal},computed: {- collectionJson () {- return JSON.stringify(this.$store.state.postwoman.collections, null, 2);- }+ collectionJson() {+ return JSON.stringify(this.$store.state.postwoman.collections, null, 2);+ }},methods: {- hideModel() {- this.$emit('hide-modal');- },- openDialogChooseFileToReplaceWith() {- this.$refs.inputChooseFileToReplaceWith.click();- },- openDialogChooseFileToImportFrom() {- this.$refs.inputChooseFileToImportFrom.click();- },- replaceWithJSON() {- let reader = new FileReader();- reader.onload = (event) => {- let content = event.target.result;- let collections = JSON.parse(content);- this.$store.commit('postwoman/replaceCollections', collections);- };- reader.readAsText(this.$refs.inputChooseFileToReplaceWith.files[0]);- },- importFromJSON() {- let reader = new FileReader();- reader.onload = (event) => {- let content = event.target.result;- let collections = JSON.parse(content);- this.$store.commit('postwoman/importCollections', collections);- };- reader.readAsText(this.$refs.inputChooseFileToImportFrom.files[0]);- },- exportJSON() {- let text = this.collectionJson;- text = text.replace(/\n/g, '\r\n');- let blob = new Blob([text], {- type: 'text/json'- });- let anchor = document.createElement('a');- anchor.download = 'postwoman-collection.json';- anchor.href = window.URL.createObjectURL(blob);- anchor.target = '_blank';- anchor.style.display = 'none';- document.body.appendChild(anchor);- anchor.click();- document.body.removeChild(anchor);- }- },-};+ hideModel() {+ this.$emit("hide-modal");+ },+ openDialogChooseFileToReplaceWith() {+ this.$refs.inputChooseFileToReplaceWith.click();+ },+ openDialogChooseFileToImportFrom() {+ this.$refs.inputChooseFileToImportFrom.click();+ },+ replaceWithJSON() {+ let reader = new FileReader();+ reader.onload = event => {+ let content = event.target.result;+ let collections = JSON.parse(content);+ this.$store.commit("postwoman/replaceCollections", collections);+ };+ reader.readAsText(this.$refs.inputChooseFileToReplaceWith.files[0]);+ },+ importFromJSON() {+ let reader = new FileReader();+ reader.onload = event => {+ let content = event.target.result;+ let collections = JSON.parse(content);+ this.$store.commit("postwoman/importCollections", collections);+ };+ reader.readAsText(this.$refs.inputChooseFileToImportFrom.files[0]);+ },+ exportJSON() {+ let text = this.collectionJson;+ text = text.replace(/\n/g, "\r\n");+ let blob = new Blob([text], {+ type: "text/json"+ });+ let anchor = document.createElement("a");+ anchor.download = "postwoman-collection.json";+ anchor.href = window.URL.createObjectURL(blob);+ anchor.target = "_blank";+ anchor.style.display = "none";+ document.body.appendChild(anchor);+ anchor.click();+ document.body.removeChild(anchor);+ }+ }+ };</script>diff --git a/components/collections/index.vue b/components/collections/index.vueindex 2e44eba69..4cd7383d8 100644--- a/components/collections/index.vue+++ b/components/collections/index.vue@@ -5,50 +5,41 @@ TODO:<template><div class="collections-wrapper">- <addCollection- v-bind:show = "showModalAdd"- v-on:hide-modal = 'displayModalAdd(false)'- >- </addCollection>+ <addCollection v-bind:show="showModalAdd" v-on:hide-modal="displayModalAdd(false)"></addCollection><editCollection- v-bind:show = "showModalEdit"- v-bind:editingCollection = "editingCollection"- v-bind:editingCollectionIndex = "editingCollectionIndex"- v-on:hide-modal = 'displayModalEdit(false)'- >- </editCollection>+ v-bind:show="showModalEdit"+ v-bind:editingCollection="editingCollection"+ v-bind:editingCollectionIndex="editingCollectionIndex"+ v-on:hide-modal="displayModalEdit(false)"+ ></editCollection><addFolder- v-bind:show = "showModalAddFolder"- v-bind:collection = "editingCollection"- v-bind:collectionIndex = "editingCollectionIndex"- v-on:hide-modal = 'displayModalAddFolder(false)'- >- </addFolder>+ v-bind:show="showModalAddFolder"+ v-bind:collection="editingCollection"+ v-bind:collectionIndex="editingCollectionIndex"+ v-on:hide-modal="displayModalAddFolder(false)"+ ></addFolder><editFolder- v-bind:show = "showModalEditFolder"- v-bind:collection = "editingCollection"- v-bind:collectionIndex = "editingCollectionIndex"- v-bind:folder = "editingFolder"- v-bind:folderIndex = "editingFolderIndex"- v-on:hide-modal = 'displayModalEditFolder(false)'- >- </editFolder>+ v-bind:show="showModalEditFolder"+ v-bind:collection="editingCollection"+ v-bind:collectionIndex="editingCollectionIndex"+ v-bind:folder="editingFolder"+ v-bind:folderIndex="editingFolderIndex"+ v-on:hide-modal="displayModalEditFolder(false)"+ ></editFolder><editRequest- v-bind:show = "showModalEditRequest"- v-bind:collectionIndex = "editingCollectionIndex"- v-bind:folderIndex = "editingFolderIndex"- v-bind:request = "editingRequest"- v-bind:requestIndex = "editingRequestIndex"- v-on:hide-modal = "displayModalEditRequest(false)"- >- </editRequest>+ v-bind:show="showModalEditRequest"+ v-bind:collectionIndex="editingCollectionIndex"+ v-bind:folderIndex="editingFolderIndex"+ v-bind:request="editingRequest"+ v-bind:requestIndex="editingRequestIndex"+ v-on:hide-modal="displayModalEditRequest(false)"+ ></editRequest><importExportCollections- v-bind:show = "showModalImportExport"- v-on:hide-modal = 'displayModalImportExport(false)'- >- </importExportCollections>+ v-bind:show="showModalImportExport"+ v-on:hide-modal="displayModalImportExport(false)"+ ></importExportCollections>- <div class='flex-wrap'>+ <div class="flex-wrap"><div><button class="icon" @click="displayModalAdd(true)"><i class="material-icons">add</i>@@ -66,14 +57,13 @@ TODO:<ul><li v-for="(collection, index) in collections" :key="collection.name"><collection- v-bind:collection-index = "index"- v-bind:collection = "collection"- v-on:edit-collection = "editCollection(collection, index)"- v-on:add-folder = "addFolder(collection, index)"- v-on:edit-folder = "editFolder($event)"- v-on:edit-request = "editRequest($event)"- >- </collection>+ v-bind:collection-index="index"+ v-bind:collection="collection"+ v-on:edit-collection="editCollection(collection, index)"+ v-on:add-folder="addFolder(collection, index)"+ v-on:edit-folder="editFolder($event)"+ v-on:edit-request="editRequest($event)"+ ></collection></li><li v-if="collections.length === 0"><label>Collections are empty</label>@@ -90,12 +80,12 @@ TODO:</style><script>- import addCollection from "./addCollection";- import addFolder from "./addFolder";- import collection from './collection'- import editCollection from "./editCollection";- import editFolder from "./editFolder";- import editRequest from "./editRequest";+ import addCollection from "./addCollection";+ import addFolder from "./addFolder";+ import collection from "./collection";+ import editCollection from "./editCollection";+ import editFolder from "./editFolder";+ import editRequest from "./editRequest";import importExportCollections from "./importExportCollections";export default {@@ -106,96 +96,90 @@ TODO:editCollection,editFolder,editRequest,- importExportCollections,+ importExportCollections},data() {return {- showModalAdd : false,- showModalEdit : false,- showModalImportExport : false,- showModalAddFolder : false,- showModalEditFolder : false,- showModalEditRequest : false,- editingCollection : undefined,- editingCollectionIndex : undefined,- editingFolder : undefined,- editingFolderIndex : undefined,- editingRequest : undefined,- editingRequestIndex : undefined,- }+ showModalAdd: false,+ showModalEdit: false,+ showModalImportExport: false,+ showModalAddFolder: false,+ showModalEditFolder: false,+ showModalEditRequest: false,+ editingCollection: undefined,+ editingCollectionIndex: undefined,+ editingFolder: undefined,+ editingFolderIndex: undefined,+ editingRequest: undefined,+ editingRequestIndex: undefined+ };},computed: {- collections () {- return this.$store.state.postwoman.collections+ collections() {+ return this.$store.state.postwoman.collections;}},methods: {displayModalAdd(shouldDisplay) {- this.showModalAdd = shouldDisplay+ this.showModalAdd = shouldDisplay;},displayModalEdit(shouldDisplay) {- this.showModalEdit = shouldDisplay+ this.showModalEdit = shouldDisplay;- if (!shouldDisplay)- this.resetSelectedData()+ if (!shouldDisplay) this.resetSelectedData();},displayModalImportExport(shouldDisplay) {- this.showModalImportExport = shouldDisplay+ this.showModalImportExport = shouldDisplay;},displayModalAddFolder(shouldDisplay) {- this.showModalAddFolder = shouldDisplay+ this.showModalAddFolder = shouldDisplay;- if (!shouldDisplay)- this.resetSelectedData()+ if (!shouldDisplay) this.resetSelectedData();},displayModalEditFolder(shouldDisplay) {- this.showModalEditFolder = shouldDisplay+ this.showModalEditFolder = shouldDisplay;- if (!shouldDisplay)- this.resetSelectedData()+ if (!shouldDisplay) this.resetSelectedData();},displayModalEditRequest(shouldDisplay) {- this.showModalEditRequest = shouldDisplay+ this.showModalEditRequest = shouldDisplay;- if (!shouldDisplay)- this.resetSelectedData()+ if (!shouldDisplay) this.resetSelectedData();},editCollection(collection, collectionIndex) {- this.$data.editingCollection = collection- this.$data.editingCollectionIndex = collectionIndex- this.displayModalEdit(true)+ this.$data.editingCollection = collection;+ this.$data.editingCollectionIndex = collectionIndex;+ this.displayModalEdit(true);},addFolder(collection, collectionIndex) {- this.$data.editingCollection = collection- this.$data.editingCollectionIndex = collectionIndex- this.displayModalAddFolder(true)+ this.$data.editingCollection = collection;+ this.$data.editingCollectionIndex = collectionIndex;+ this.displayModalAddFolder(true);},editFolder(payload) {- const { collectionIndex, folder, folderIndex } = payload- this.$data.editingCollection = collection- this.$data.editingCollectionIndex = collectionIndex- this.$data.editingFolder = folder- this.$data.editingFolderIndex = folderIndex- this.displayModalEditFolder(true)+ const { collectionIndex, folder, folderIndex } = payload;+ this.$data.editingCollection = collection;+ this.$data.editingCollectionIndex = collectionIndex;+ this.$data.editingFolder = folder;+ this.$data.editingFolderIndex = folderIndex;+ this.displayModalEditFolder(true);},editRequest(payload) {- const { request, collectionIndex, folderIndex, requestIndex } = payload- this.$data.editingCollectionIndex = collectionIndex- this.$data.editingFolderIndex = folderIndex- this.$data.editingRequest = request- this.$data.editingRequestIndex = requestIndex- this.displayModalEditRequest(true)-+ const { request, collectionIndex, folderIndex, requestIndex } = payload;+ this.$data.editingCollectionIndex = collectionIndex;+ this.$data.editingFolderIndex = folderIndex;+ this.$data.editingRequest = request;+ this.$data.editingRequestIndex = requestIndex;+ this.displayModalEditRequest(true);},resetSelectedData() {- this.$data.editingCollection = undefined- this.$data.editingCollectionIndex = undefined- this.$data.editingFolder = undefined- this.$data.editingFolderIndex = undefined- this.$data.editingRequest = undefined- this.$data.editingRequestIndex = undefined- },- },- }-+ this.$data.editingCollection = undefined;+ this.$data.editingCollectionIndex = undefined;+ this.$data.editingFolder = undefined;+ this.$data.editingFolderIndex = undefined;+ this.$data.editingRequest = undefined;+ this.$data.editingRequestIndex = undefined;+ }+ }+ };</script>diff --git a/components/collections/request.vue b/components/collections/request.vueindex 7cb150f5a..4448de5e2 100644--- a/components/collections/request.vue+++ b/components/collections/request.vue@@ -1,55 +1,55 @@<template>- <div class="flex-wrap">- <div>- <button class="icon" @click="selectRequest()" v-tooltip="'Use request'">- <i class="material-icons">insert_drive_file</i>- <span>{{request.name}}</span>- </button>- </div>- <div>- <button class="icon" @click="removeRequest" v-tooltip="'Delete request'">- <i class="material-icons">delete</i>- </button>- <button class="icon" @click="$emit('edit-request')" v-tooltip="'Edit request'">- <i class="material-icons">edit</i>- </button>- </div>+ <div class="flex-wrap">+ <div>+ <button class="icon" @click="selectRequest()" v-tooltip="'Use request'">+ <i class="material-icons">insert_drive_file</i>+ <span>{{request.name}}</span>+ </button></div>+ <div>+ <button class="icon" @click="removeRequest" v-tooltip="'Delete request'">+ <i class="material-icons">delete</i>+ </button>+ <button class="icon" @click="$emit('edit-request')" v-tooltip="'Edit request'">+ <i class="material-icons">edit</i>+ </button>+ </div>+ </div></template><style scoped>- ul {- display: flex;- flex-direction: column;- }+ ul {+ display: flex;+ flex-direction: column;+ }- ul li {- display: flex;- padding-left: 16px;- border-left: 1px solid var(--brd-color);- }+ ul li {+ display: flex;+ padding-left: 16px;+ border-left: 1px solid var(--brd-color);+ }</style><script>-export default {+ export default {props: {- request : Object,- collectionIndex : Number,- folderIndex : Number,- requestIndex : Number,+ request: Object,+ collectionIndex: Number,+ folderIndex: Number,+ requestIndex: Number},methods: {- selectRequest() {- this.$store.commit('postwoman/selectRequest', { request: this.request });- },- removeRequest() {- if (!confirm("Are you sure you want to remove this request?")) return;- this.$store.commit('postwoman/removeRequest', {- collectionIndex : this.collectionIndex,- folderIndex : this.folderIndex,- requestIndex : this.requestIndex,- });- },- },-};+ selectRequest() {+ this.$store.commit("postwoman/selectRequest", { request: this.request });+ },+ removeRequest() {+ if (!confirm("Are you sure you want to remove this request?")) return;+ this.$store.commit("postwoman/removeRequest", {+ collectionIndex: this.collectionIndex,+ folderIndex: this.folderIndex,+ requestIndex: this.requestIndex+ });+ }+ }+ };</script>diff --git a/components/collections/saveRequestAs.vue b/components/collections/saveRequestAs.vueindex de90f8b53..8777f0502 100644--- a/components/collections/saveRequestAs.vue+++ b/components/collections/saveRequestAs.vue@@ -1,158 +1,154 @@<template>- <div>- <modal v-if="show" @close="hideModal">- <div slot="header">- <ul>- <li>- <div class="flex-wrap">- <h3 class="title">Save Request As</h3>- <div>- <button class="icon" @click="hideModal">- <i class="material-icons">close</i>- </button>- </div>- </div>- </li>- </ul>+ <modal v-if="show" @close="hideModal">+ <div slot="header">+ <ul>+ <li>+ <div class="flex-wrap">+ <h3 class="title">Save Request As</h3>+ <div>+ <button class="icon" @click="hideModal">+ <i class="material-icons">close</i>+ </button></div>- <div slot="body">- <ul>- <li>- <input type="text" v-model="requestData.name" v-bind:placeholder="defaultRequestName" />- <select type="text" v-model="requestData.collectionIndex" >- <option- v-for="(collection, index) in $store.state.postwoman.collections"- :key = "index"- :value = "index">- {{ collection.name }}- </option>- </select>- <select type="text" v-model="requestData.folderIndex" >- <option- :key = "undefined"- :value = "undefined">- </option>- <option- v-for="(folder, index) in folders"- :key = "index"- :value = "index">- {{ folder.name }}- </option>- </select>- <select type="text" v-model="requestData.requestIndex" >- <option- :key = "undefined"- :value = "undefined">- </option>- <option- v-for ="(folder, index) in requests"- :key = "index"- :value = "index">- {{ folder.name }}- </option>- </select>- </li>- </ul>- </div>- <div slot="footer">- <ul>- <li>- <button class="icon" @click="saveRequestAs">- <i class="material-icons">save</i>- <span>Save</span>- </button>- </li>- </ul>- </div>- </modal>+ </div>+ </li>+ </ul>+ </div>+ <div slot="body">+ <ul>+ <li>+ <input type="text" v-model="requestData.name" v-bind:placeholder="defaultRequestName" />+ <select type="text" v-model="requestData.collectionIndex">+ <option+ v-for="(collection, index) in $store.state.postwoman.collections"+ :key="index"+ :value="index"+ >{{ collection.name }}</option>+ </select>+ <select type="text" v-model="requestData.folderIndex">+ <option :key="undefined" :value="undefined"></option>+ <option v-for="(folder, index) in folders" :key="index" :value="index">{{ folder.name }}</option>+ </select>+ <select type="text" v-model="requestData.requestIndex">+ <option :key="undefined" :value="undefined"></option>+ <option+ v-for="(folder, index) in requests"+ :key="index"+ :value="index"+ >{{ folder.name }}</option>+ </select>+ </li>+ </ul></div>+ <div slot="footer">+ <ul>+ <li>+ <button class="icon" @click="saveRequestAs">+ <i class="material-icons">save</i>+ <span>Save</span>+ </button>+ </li>+ </ul>+ </div>+ </modal></template><script>-import modal from "../../components/modal";+ import modal from "../../components/modal";-export default {+ export default {props: {- show : Boolean,- editingRequest : Object,+ show: Boolean,+ editingRequest: Object},components: {- modal,+ modal},data() {- return {- defaultRequestName : 'My New Request',- requestData : {- name : undefined,- collectionIndex : undefined,- folderIndex : undefined,- requestIndex : undefined,- },+ return {+ defaultRequestName: "My New Request",+ requestData: {+ name: undefined,+ collectionIndex: undefined,+ folderIndex: undefined,+ requestIndex: undefined}+ };},watch: {- 'requestData.collectionIndex': function resetFolderAndRequestIndex() {- // if user choosen some folder, than selected other collection, which doesn't have any folders- // than `requestUpdateData.folderIndex` won't be reseted- this.$data.requestData.folderIndex = undefined- this.$data.requestData.requestIndex = undefined- },- 'requestData.folderIndex': function resetRequestIndex() {- this.$data.requestData.requestIndex = undefined- },+ "requestData.collectionIndex": function resetFolderAndRequestIndex() {+ // if user choosen some folder, than selected other collection, which doesn't have any folders+ // than `requestUpdateData.folderIndex` won't be reseted+ this.$data.requestData.folderIndex = undefined;+ this.$data.requestData.requestIndex = undefined;+ },+ "requestData.folderIndex": function resetRequestIndex() {+ this.$data.requestData.requestIndex = undefined;+ }},computed: {- folders() {- const userSelectedAnyCollection = this.$data.requestData.collectionIndex !== undefined- if (!userSelectedAnyCollection) return []+ folders() {+ const userSelectedAnyCollection =+ this.$data.requestData.collectionIndex !== undefined;+ if (!userSelectedAnyCollection) return [];- return this.$store.state.postwoman.collections[this.$data.requestData.collectionIndex].folders- },- requests() {- const userSelectedAnyCollection = this.$data.requestData.collectionIndex !== undefined- if (!userSelectedAnyCollection) return []+ return this.$store.state.postwoman.collections[+ this.$data.requestData.collectionIndex+ ].folders;+ },+ requests() {+ const userSelectedAnyCollection =+ this.$data.requestData.collectionIndex !== undefined;+ if (!userSelectedAnyCollection) return [];- const userSelectedAnyFolder = this.$data.requestData.folderIndex !== undefined- if (userSelectedAnyFolder) {- const collection = this.$store.state.postwoman.collections[this.$data.requestData.collectionIndex]- const folder = collection.folders[this.$data.requestData.folderIndex]- const requests = folder.requests- return requests- }- else {- const collection = this.$store.state.postwoman.collections[this.$data.requestData.collectionIndex]- const requests = collection.requests- return requests- }+ const userSelectedAnyFolder =+ this.$data.requestData.folderIndex !== undefined;+ if (userSelectedAnyFolder) {+ const collection = this.$store.state.postwoman.collections[+ this.$data.requestData.collectionIndex+ ];+ const folder = collection.folders[this.$data.requestData.folderIndex];+ const requests = folder.requests;+ return requests;+ } else {+ const collection = this.$store.state.postwoman.collections[+ this.$data.requestData.collectionIndex+ ];+ const requests = collection.requests;+ return requests;}+ }},methods: {- saveRequestAs() {- const userDidntSpecifyCollection = this.$data.requestData.collectionIndex === undefined- if (userDidntSpecifyCollection) {- this.$toast.error('please, specify collection first', { icon: 'error' })- return- }+ saveRequestAs() {+ const userDidntSpecifyCollection =+ this.$data.requestData.collectionIndex === undefined;+ if (userDidntSpecifyCollection) {+ this.$toast.error("please, specify collection first", {+ icon: "error"+ });+ return;+ }- const requestUpdated = {- ...this.$props.editingRequest,- name : this.$data.requestData.name || this.$data.defaultRequestName,- collection : this.$data.requestData.collectionIndex,- }+ const requestUpdated = {+ ...this.$props.editingRequest,+ name: this.$data.requestData.name || this.$data.defaultRequestName,+ collection: this.$data.requestData.collectionIndex+ };- this.$store.commit('postwoman/saveRequestAs', {- request : requestUpdated,- collectionIndex : this.$data.requestData.collectionIndex,- folderIndex : this.$data.requestData.folderIndex,- requestIndex : this.$data.requestData.requestIndex,- });+ this.$store.commit("postwoman/saveRequestAs", {+ request: requestUpdated,+ collectionIndex: this.$data.requestData.collectionIndex,+ folderIndex: this.$data.requestData.folderIndex,+ requestIndex: this.$data.requestData.requestIndex+ });- this.hideModal();- },- hideModal() {- this.$emit('hide-modal');- this.$emit('hide-model'); // for backward compatibility // TODO: use fixed event- },- },-};+ this.hideModal();+ },+ hideModal() {+ this.$emit("hide-modal");+ this.$emit("hide-model"); // for backward compatibility // TODO: use fixed event+ }+ }+ };</script>diff --git a/components/history.vue b/components/history.vueindex 445a9adc5..d32faa513 100644--- a/components/history.vue+++ b/components/history.vue@@ -2,52 +2,107 @@<pw-section class="green" icon="history" label="History"><ul><li id="filter-history">- <input aria-label="Search" type="text" placeholder="search history" :readonly="history.length === 0" v-model="filterText">+ <input+ aria-label="Search"+ type="text"+ placeholder="search history"+ :readonly="history.length === 0"+ v-model="filterText"+ /></li></ul><ul><li @click="sort_by_label()">- <label for="" class="flex-wrap">Label<i class="material-icons">sort</i></label>+ <label class="flex-wrap">+ Label+ <i class="material-icons">unfold_more</i>+ </label></li><li @click="sort_by_time()">- <label for="" class="flex-wrap">Time<i class="material-icons">sort</i></label>+ <label class="flex-wrap">+ Time+ <i class="material-icons">unfold_more</i>+ </label></li><li @click="sort_by_status_code()">- <label for="" class="flex-wrap">Status<i class="material-icons">sort</i></label>+ <label class="flex-wrap">+ Status+ <i class="material-icons">unfold_more</i>+ </label></li><li @click="sort_by_url()">- <label for="" class="flex-wrap">URL<i class="material-icons">sort</i></label>+ <label class="flex-wrap">+ URL+ <i class="material-icons">unfold_more</i>+ </label></li><li @click="sort_by_path()">- <label for="" class="flex-wrap">Path<i class="material-icons">sort</i></label>+ <label class="flex-wrap">+ Path+ <i class="material-icons">unfold_more</i>+ </label></li></ul>- <virtual-list class="virtual-list" :class="{filled: filteredHistory.length}" :size="54" :remain="Math.min(5, filteredHistory.length)">+ <virtual-list+ class="virtual-list"+ :class="{filled: filteredHistory.length}"+ :size="54"+ :remain="Math.min(5, filteredHistory.length)"+ ><ul v-for="(entry, index) in filteredHistory" :key="index" class="entry"><li>- <input aria-label="Label" type="text" readonly :value="entry.label" placeholder="No label">+ <input+ aria-label="Label"+ type="text"+ readonly+ :value="entry.label"+ placeholder="No label"+ /></li><li>- <input aria-label="Time" type="text" readonly :value="entry.time" :title="entry.date">+ <input aria-label="Time" type="text" readonly :value="entry.time" :title="entry.date" /></li><li class="method-list-item">- <input aria-label="Method" type="text" readonly :value="entry.method" :class="findEntryStatus(entry).className" :style="{'--status-code': entry.status}">- <span class="entry-status-code" :class="findEntryStatus(entry).className" :style="{'--status-code': entry.status}">{{entry.status}}</span>+ <input+ aria-label="Method"+ type="text"+ readonly+ :value="entry.method"+ :class="findEntryStatus(entry).className"+ :style="{'--status-code': entry.status}"+ />+ <span+ class="entry-status-code"+ :class="findEntryStatus(entry).className"+ :style="{'--status-code': entry.status}"+ >{{entry.status}}</span></li><li>- <input aria-label="URL" type="text" readonly :value="entry.url">+ <input aria-label="URL" type="text" readonly :value="entry.url" /></li><li>- <input aria-label="Path" type="text" readonly :value="entry.path" placeholder="No path">+ <input aria-label="Path" type="text" readonly :value="entry.path" placeholder="No path" /></li><div class="show-on-small-screen"><li>- <button v-tooltip="'Delete entry'" class="icon" :id="'delete-button#'+index" @click="deleteHistory(entry)" aria-label="Delete">+ <button+ v-tooltip="'Delete entry'"+ class="icon"+ :id="'delete-button#'+index"+ @click="deleteHistory(entry)"+ aria-label="Delete"+ ><i class="material-icons">delete</i></button></li><li>- <button v-tooltip="'Edit entry'" class="icon" :id="'use-button#'+index" @click="useHistory(entry)" aria-label="Edit">+ <button+ v-tooltip="'Edit entry'"+ class="icon"+ :id="'use-button#'+index"+ @click="useHistory(entry)"+ aria-label="Edit"+ ><i class="material-icons">edit</i></button></li>@@ -56,7 +111,7 @@</virtual-list><ul :class="{hidden: filteredHistory.length != 0 || history.length === 0 }"><li>- <label>Nothing found for "{{filterText}}"</label>+ <label>Nothing found "{{filterText}}"</label></li></ul><ul v-if="history.length === 0">@@ -66,7 +121,12 @@</ul><ul v-if="history.length !== 0"><li v-if="!isClearingHistory">- <button class="icon" id="clear-history-button" :disabled="history.length === 0" @click="enableHistoryClearing">+ <button+ class="icon"+ id="clear-history-button"+ :disabled="history.length === 0"+ @click="enableHistoryClearing"+ ><i class="material-icons">clear_all</i><span>Clear All</span></button>@@ -75,36 +135,52 @@<div class="flex-wrap"><label for="clear-history-button">Are you sure?</label><div>- <button class="icon" id="confirm-clear-history-button" @click="clearHistory">- Yes- </button>- <button class="icon" id="reject-clear-history-button" @click="disableHistoryClearing">- No- </button>+ <button class="icon" id="confirm-clear-history-button" @click="clearHistory">Yes</button>+ <button class="icon" id="reject-clear-history-button" @click="disableHistoryClearing">No</button></div></div></li></ul></pw-section></template>++<style scoped lang="scss">+ .virtual-list {+ [readonly] {+ cursor: default;+ }+ }++ .flex-wrap {+ cursor: pointer;+ }++ @media (max-width: 720px) {+ .virtual-list.filled {+ min-height: 200px;+ }+ }+</style>+<script>- import VirtualList from 'vue-virtual-scroll-list'+ import VirtualList from "vue-virtual-scroll-list";import section from "./section";- import {- findStatusGroup- } from "../pages/index";+ import { findStatusGroup } from "../pages/index";- const updateOnLocalStorage = (propertyName, property) => window.localStorage.setItem(propertyName, JSON.stringify(property));+ const updateOnLocalStorage = (propertyName, property) =>+ window.localStorage.setItem(propertyName, JSON.stringify(property));export default {components: {- 'pw-section': section,+ "pw-section": section,VirtualList},data() {- const localStorageHistory = JSON.parse(window.localStorage.getItem('history'));+ const localStorageHistory = JSON.parse(+ window.localStorage.getItem("history")+ );return {history: localStorageHistory || [],- filterText: '',+ filterText: "",showFilter: false,isClearingHistory: false,reverse_sort_label: false,@@ -112,7 +188,7 @@reverse_sort_status_code: false,reverse_sort_url: false,reverse_sort_path: false- }+ };},computed: {filteredHistory() {@@ -120,7 +196,7 @@const filterText = this.filterText.toLowerCase();return Object.keys(entry).some(key => {let value = entry[key];- value = typeof value !== 'string' ? value.toString() : value;+ value = typeof value !== "string" ? value.toString() : value;return value.toLowerCase().includes(filterText);});});@@ -129,35 +205,37 @@methods: {clearHistory() {this.history = [];- this.filterText = '';+ this.filterText = "";this.disableHistoryClearing();- updateOnLocalStorage('history', this.history);- this.$toast.error('History Deleted', {- icon: 'delete'+ updateOnLocalStorage("history", this.history);+ this.$toast.error("History Deleted", {+ icon: "delete"});},useHistory(entry) {- this.$emit('useHistory', entry);+ this.$emit("useHistory", entry);},findEntryStatus(entry) {const foundStatusGroup = findStatusGroup(entry.status);- return foundStatusGroup || {- className: ''- };+ return (+ foundStatusGroup || {+ className: ""+ }+ );},deleteHistory(entry) {this.history.splice(this.history.indexOf(entry), 1);if (this.history.length === 0) {- this.filterText = '';+ this.filterText = "";}- updateOnLocalStorage('history', this.history);- this.$toast.error('Deleted', {- icon: 'delete'+ updateOnLocalStorage("history", this.history);+ this.$toast.error("Deleted", {+ icon: "delete"});},addEntry(entry) {this.history.push(entry);- updateOnLocalStorage('history', this.history);+ updateOnLocalStorage("history", this.history);},enableHistoryClearing() {if (!this.history || !this.history.length) return;@@ -168,80 +246,72 @@},sort_by_time() {let byDate = this.history.slice(0);- byDate.sort((a,b) =>{+ byDate.sort((a, b) => {let date_a = a.date.split("/");let date_b = b.date.split("/");- let time_a = a.time.split(":")- let time_b = b.time.split(":")- let final_a = new Date(date_a[2], date_a[1], date_a[0], time_a[0], time_a[1], time_a[2]);- let final_b = new Date(date_b[2], date_b[1], date_b[0], time_b[0], time_b[1], time_b[2]);- if(this.reverse_sort_time)- return final_b - final_a;- else- return final_a - final_b;- })+ let time_a = a.time.split(":");+ let time_b = b.time.split(":");+ let final_a = new Date(+ date_a[2],+ date_a[1],+ date_a[0],+ time_a[0],+ time_a[1],+ time_a[2]+ );+ let final_b = new Date(+ date_b[2],+ date_b[1],+ date_b[0],+ time_b[0],+ time_b[1],+ time_b[2]+ );+ if (this.reverse_sort_time) return final_b - final_a;+ else return final_a - final_b;+ });this.history = byDate;this.reverse_sort_time = !this.reverse_sort_time;},sort_by_status_code() {let byCode = this.history.slice(0);- byCode.sort((a,b) =>{- if(this.reverse_sort_status_code)- return b.status - a.status;- else- return a.status - b.status;- })+ byCode.sort((a, b) => {+ if (this.reverse_sort_status_code) return b.status - a.status;+ else return a.status - b.status;+ });this.history = byCode;this.reverse_sort_status_code = !this.reverse_sort_status_code;},sort_by_url() {let byUrl = this.history.slice(0);- byUrl.sort((a, b)=>{- if(this.reverse_sort_url)+ byUrl.sort((a, b) => {+ if (this.reverse_sort_url)return a.url == b.url ? 0 : +(a.url < b.url) || -1;- else- return a.url == b.url ? 0 : +(a.url > b.url) || -1;+ else return a.url == b.url ? 0 : +(a.url > b.url) || -1;});this.history = byUrl;this.reverse_sort_url = !this.reverse_sort_url;},sort_by_label() {let byLabel = this.history.slice(0);- byLabel.sort((a, b)=>{- if(this.reverse_sort_label)+ byLabel.sort((a, b) => {+ if (this.reverse_sort_label)return a.label == b.label ? 0 : +(a.label < b.label) || -1;- else- return a.label == b.label ? 0 : +(a.label > b.label) || -1;+ else return a.label == b.label ? 0 : +(a.label > b.label) || -1;});this.history = byLabel;this.reverse_sort_label = !this.reverse_sort_label;},sort_by_path() {let byPath = this.history.slice(0);- byPath.sort((a, b)=>{- if(this.reverse_sort_path)+ byPath.sort((a, b) => {+ if (this.reverse_sort_path)return a.path == b.path ? 0 : +(a.path < b.path) || -1;- else- return a.path == b.path ? 0 : +(a.path > b.path) || -1;+ else return a.path == b.path ? 0 : +(a.path > b.path) || -1;});this.history = byPath;this.reverse_sort_path = !this.reverse_sort_path;}}- }-+ };</script>-<style scoped lang="scss">- .virtual-list {- [readonly] {- cursor: default;- }- }-- @media (max-width: 720px) {- .virtual-list.filled {- min-height: 200px;- }- }--</style>diff --git a/components/logo.vue b/components/logo.vueindex 3e080efe6..46cee36b3 100644--- a/components/logo.vue+++ b/components/logo.vue@@ -1,11 +1,34 @@<template>- <svg version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 612.001 612.001" style="enable-background:new 0 0 612.001 612.001;" xml:space="preserve">+ <svg+ version="1.1"+ id="Capa_1"+ x="0px"+ y="0px"+ viewBox="0 0 612.001 612.001"+ style="enable-background:new 0 0 612.001 612.001;"+ xml:space="preserve"+ ><defs id="defs11" /><g id="g3826" transform="translate(-516.40798,-163.88978)">- <circle :fill="color" transform="scale(1,-1)" style="stroke-width:1.19531453" r="178.70923" cy="-501.55591" cx="822.40845" id="circle3814" />+ <circle+ :fill="color"+ transform="scale(1,-1)"+ style="stroke-width:1.19531453"+ r="178.70923"+ cy="-501.55591"+ cx="822.40845"+ id="circle3814"+ /><g id="g3820" transform="translate(516.40798,163.89028)"><g id="g3818">- <path :fill="color" id="path3816" data-old_color="#121212" class="active-path" data-original="#121212" d="M 64.601,236.822 C 64.601,394.256 192.786,612 306.001,612 412.582,612 547.4,394.256 547.4,236.822 547.4,79.388 439.322,0 306,0 172.678,0 64.601,79.388 64.601,236.822 Z m 304.12,116.415 c 29.475,-29.475 70.598,-40.195 108.552,-32.173 8.021,37.954 -2.698,79.077 -32.173,108.552 -29.475,29.475 -70.598,40.195 -108.552,32.173 -8.022,-37.955 2.698,-79.078 32.173,-108.552 z M 134.727,321.063 c 37.954,-8.021 79.077,2.698 108.552,32.173 29.475,29.475 40.195,70.598 32.173,108.552 -37.954,8.021 -79.077,-2.698 -108.552,-32.173 -29.475,-29.476 -40.194,-70.598 -32.173,-108.552 z" />+ <path+ :fill="color"+ id="path3816"+ data-old_color="#121212"+ class="active-path"+ data-original="#121212"+ d="M 64.601,236.822 C 64.601,394.256 192.786,612 306.001,612 412.582,612 547.4,394.256 547.4,236.822 547.4,79.388 439.322,0 306,0 172.678,0 64.601,79.388 64.601,236.822 Z m 304.12,116.415 c 29.475,-29.475 70.598,-40.195 108.552,-32.173 8.021,37.954 -2.698,79.077 -32.173,108.552 -29.475,29.475 -70.598,40.195 -108.552,32.173 -8.022,-37.955 2.698,-79.078 32.173,-108.552 z M 134.727,321.063 c 37.954,-8.021 79.077,2.698 108.552,32.173 29.475,29.475 40.195,70.598 32.173,108.552 -37.954,8.021 -79.077,-2.698 -108.552,-32.173 -29.475,-29.476 -40.194,-70.598 -32.173,-108.552 z"+ /></g></g></g>@@ -24,9 +47,9 @@<script>export default {props: {- 'color': {+ color: {type: String}}- }+ };</script>diff --git a/components/modal.vue b/components/modal.vueindex 8c5da0d44..b9e74beef 100644--- a/components/modal.vue+++ b/components/modal.vue@@ -53,13 +53,13 @@}/*- * The following styles are auto-applied to elements with- * transition="modal" when their visibility is toggled- * by Vue.js.- *- * You can easily play with the modal transition by editing- * these styles.- */+ * The following styles are auto-applied to elements with+ * transition="modal" when their visibility is toggled+ * by Vue.js.+ *+ * You can easily play with the modal transition by editing+ * these styles.+ */.modal-fade-enter,.modal-fade-leave-active {diff --git a/components/section.vue b/components/section.vueindex f2246f451..d8443e5e5 100644--- a/components/section.vue+++ b/components/section.vue@@ -1,6 +1,11 @@<template><fieldset :id="label.toLowerCase()" :class="{ 'no-colored-frames': noFrameColors }">- <legend @click.prevent="collapse"><i class="material-icons icon">{{ icon }}</i><span>{{ label }}</span><i class="material-icons" v-if="isCollapsed">expand_more</i><i class="material-icons" v-if="!isCollapsed">expand_less</i></legend>+ <legend @click.prevent="collapse">+ <i class="material-icons icon">{{ icon }}</i>+ <span>{{ label }}</span>+ <i class="material-icons" v-if="isCollapsed">expand_more</i>+ <i class="material-icons" v-if="!isCollapsed">expand_less</i>+ </legend><div class="collapsible" :class="{ hidden: collapsed }"><slot /></div>@@ -17,39 +22,39 @@</style><script>-export default {- computed: {- noFrameColors() {- return this.$store.state.postwoman.settings.DISABLE_FRAME_COLORS || false;+ export default {+ computed: {+ noFrameColors() {+ return this.$store.state.postwoman.settings.DISABLE_FRAME_COLORS || false;+ }},- },- data() {- return {- isCollapsed: false- }- },-- props: {- label: {- type: String,- default: "Section"+ data() {+ return {+ isCollapsed: false+ };},- icon: {- type: String,- default: "lens"++ props: {+ label: {+ type: String,+ default: "Section"+ },+ icon: {+ type: String,+ default: "lens"+ },+ collapsed: {+ type: Boolean+ }},- collapsed: {- type: Boolean- }- },- methods: {- collapse({ target }) {- const parent = target.parentNode.parentNode;- parent.querySelector(".collapsible").classList.toggle("hidden");- this.isCollapsed = !this.isCollapsed;+ methods: {+ collapse({ target }) {+ const parent = target.parentNode.parentNode;+ parent.querySelector(".collapsible").classList.toggle("hidden");+ this.isCollapsed = !this.isCollapsed;+ }}- }-};+ };</script>diff --git a/components/toggle.vue b/components/toggle.vueindex 79bbef02a..83cc733bb 100644--- a/components/toggle.vue+++ b/components/toggle.vue@@ -4,7 +4,7 @@<span class="handle"></span></label><label class="caption">- <slot/>+ <slot /></label></div></template>@@ -59,8 +59,8 @@margin: $handleSpacing;background-color: $inactiveHandleColor;- width: #{ $height - ($handleSpacing * 2) };- height: #{ $height - ($handleSpacing * 2) };+ width: #{$height - ($handleSpacing * 2)};+ height: #{$height - ($handleSpacing * 2)};border-radius: 100px;pointer-events: none;@@ -77,14 +77,12 @@}}}-</style><script>export default {-props: {- 'on': {+ on: {type: Boolean,default: false}@@ -93,10 +91,8 @@methods: {toggle() {const containsOnClass = this.$refs.toggle.classList.toggle("on");- this.$emit('change', containsOnClass);+ this.$emit("change", containsOnClass);}}-- }-+ };</script>diff --git a/directives/textareaAutoHeight.js b/directives/textareaAutoHeight.jsindex 10a566ac5..6914d99d3 100644--- a/directives/textareaAutoHeight.js+++ b/directives/textareaAutoHeight.js@@ -1,8 +1,8 @@export default {- name: "textareaAutoHeight",- update(element) {- if (element.scrollHeight !== element.clientHeight) {- element.style.minHeight = `${element.scrollHeight}px`;+ name: "textareaAutoHeight",+ update(element) {+ if (element.scrollHeight !== element.clientHeight) {+ element.style.minHeight = `${element.scrollHeight}px`;+ }}- }}diff --git a/layouts/default.vue b/layouts/default.vueindex dbb10401e..6f9837e7b 100644--- a/layouts/default.vue+++ b/layouts/default.vue@@ -4,7 +4,9 @@<div><div class="slide-in"><nuxt-link to="/">- <h1 class="logo"><logo alt="" style="height: 24px; margin-right: 16px"></logo>Postwoman</h1>+ <h1 class="logo">+ <logo alt style="height: 24px; margin-right: 16px"></logo>Postwoman+ </h1></nuxt-link><h3>API request builder</h3></div>@@ -12,13 +14,20 @@<!--We're using manual checks for linkActive because the query stringseems to mess up the nuxt-link active class.- -->+ --><nuxt-link to="/" :class="linkActive('/')">HTTP</nuxt-link><nuxt-link to="/websocket" :class="linkActive('/websocket')">WebSocket</nuxt-link>- <nuxt-link to="/settings" :class="linkActive('/settings')" v-tooltip="'Settings'" aria-label="Settings">+ <nuxt-link+ to="/settings"+ :class="linkActive('/settings')"+ v-tooltip="'Settings'"+ aria-label="Settings"+ ><!-- Settings cog --><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">- <path d="M24 13.616v-3.232c-1.651-.587-2.694-.752-3.219-2.019v-.001c-.527-1.271.1-2.134.847-3.707l-2.285-2.285c-1.561.742-2.433 1.375-3.707.847h-.001c-1.269-.526-1.435-1.576-2.019-3.219h-3.232c-.582 1.635-.749 2.692-2.019 3.219h-.001c-1.271.528-2.132-.098-3.707-.847l-2.285 2.285c.745 1.568 1.375 2.434.847 3.707-.527 1.271-1.584 1.438-3.219 2.02v3.232c1.632.58 2.692.749 3.219 2.019.53 1.282-.114 2.166-.847 3.707l2.285 2.286c1.562-.743 2.434-1.375 3.707-.847h.001c1.27.526 1.436 1.579 2.019 3.219h3.232c.582-1.636.75-2.69 2.027-3.222h.001c1.262-.524 2.12.101 3.698.851l2.285-2.286c-.744-1.563-1.375-2.433-.848-3.706.527-1.271 1.588-1.44 3.221-2.021zm-12 2.384c-2.209 0-4-1.791-4-4s1.791-4 4-4 4 1.791 4 4-1.791 4-4 4z"/>+ <path+ d="M24 13.616v-3.232c-1.651-.587-2.694-.752-3.219-2.019v-.001c-.527-1.271.1-2.134.847-3.707l-2.285-2.285c-1.561.742-2.433 1.375-3.707.847h-.001c-1.269-.526-1.435-1.576-2.019-3.219h-3.232c-.582 1.635-.749 2.692-2.019 3.219h-.001c-1.271.528-2.132-.098-3.707-.847l-2.285 2.285c.745 1.568 1.375 2.434.847 3.707-.527 1.271-1.584 1.438-3.219 2.02v3.232c1.632.58 2.692.749 3.219 2.019.53 1.282-.114 2.166-.847 3.707l2.285 2.286c1.562-.743 2.434-1.375 3.707-.847h.001c1.27.526 1.436 1.579 2.019 3.219h3.232c.582-1.636.75-2.69 2.027-3.222h.001c1.262-.524 2.12.101 3.698.851l2.285-2.286c-.744-1.563-1.375-2.433-.848-3.706.527-1.271 1.588-1.44 3.221-2.021zm-12 2.384c-2.209 0-4-1.791-4-4s1.791-4 4-4 4 1.791 4 4-1.791 4-4 4z"+ /></svg></nuxt-link></nav>@@ -30,7 +39,7 @@<div class="flex-wrap"><a href="https://github.com/liyasthomas/postwoman" target="_blank" rel="noopener"><button class="icon">- <img id="imgGitHub" src="~static/icons/github.svg" alt="GitHub" :style="logoStyle()">+ <img id="imgGitHub" src="~static/icons/github.svg" alt="GitHub" :style="logoStyle()" /><span>GitHub</span></button></a>@@ -38,9 +47,14 @@<i class="material-icons">add_to_home_screen</i><span>Install PWA</span></button>- <button class="icon" onClick="window.open('https://twitter.com/share?text=👽 Postwoman • API request builder - Helps you create your requests faster, saving you precious time on your development&url=https://postwoman.io&hashtags=postwoman&via=liyasthomas');">+ <button+ class="icon"+ onClick="window.open('https://twitter.com/share?text=👽 Postwoman • API request builder - Helps you create your requests faster, saving you precious time on your development&url=https://postwoman.io&hashtags=postwoman&via=liyasthomas');"+ ><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">- <path d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z"/>+ <path+ d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z"+ /></svg><span>Tweet</span></button>@@ -48,17 +62,29 @@<!-- Bottom section of footer: version/author information --><p class="align-center"><span v-if="version.name">- <a v-bind:href="'https://github.com/liyasthomas/postwoman/releases/tag/' + version.name" target="_blank" rel="noopener">{{version.name}}</a>+ <a+ v-bind:href="'https://github.com/liyasthomas/postwoman/releases/tag/' + version.name"+ target="_blank"+ rel="noopener"+ >{{version.name}}</a><span v-if="version.hash">- - <a v-bind:href="'https://github.com/liyasthomas/postwoman/commit/' + version.hash" target="_blank" rel="noopener">{{version.hash}}</a>+ -+ <a+ v-bind:href="'https://github.com/liyasthomas/postwoman/commit/' + version.hash"+ target="_blank"+ rel="noopener"+ >{{version.hash}}</a></span>- <span v-if="version.variant"> ({{version.variant}})</span>+ <span v-if="version.variant">({{version.variant}})</span>•- </span> by <a href="https://liyasthomas.web.app" target="_blank" rel="noopener">Liyas Thomas 🦄</a> • <a href="https://postwoman.launchaco.com" target="_blank" rel="noopener">Subscribe</a>+ </span> by+ <a href="https://liyasthomas.web.app" target="_blank" rel="noopener">Liyas Thomas 🦄</a> •+ <a href="https://postwoman.launchaco.com" target="_blank" rel="noopener">Subscribe</a></p></footer></div></template>+<style lang="scss">.slide-in {position: relative;@@ -106,7 +132,7 @@&:before {width: 100%;- height: 100%+ height: 100%;}}@@ -139,12 +165,12 @@}}}-</style>+<script>- import intializePwa from '../assets/js/pwa';+ import intializePwa from "../assets/js/pwa";import logo from "../components/logo";- import * as version from '../.postwoman/version.json';+ import * as version from "../.postwoman/version.json";export default {components: {@@ -152,10 +178,10 @@},methods: {- linkActive (path) {+ linkActive(path) {return {- 'nuxt-link-exact-active': this.$route.path === path,- 'nuxt-link-active': this.$route.path === path+ "nuxt-link-exact-active": this.$route.path === path,+ "nuxt-link-active": this.$route.path === path};}},@@ -167,11 +193,15 @@// prompt.showInstallPrompt: null,logoStyle() {- return (((this.$store.state.postwoman.settings.THEME_CLASS || '').includes("light")) ? " filter: invert(100%); -webkit-filter: invert(100%);" : '')+ return (+ this.$store.state.postwoman.settings.THEME_CLASS || ""+ ).includes("light")+ ? " filter: invert(100%); -webkit-filter: invert(100%);"+ : "";},version: {}- }+ };},beforeMount() {@@ -181,36 +211,40 @@// Load theme settings(() => {// Apply theme from settings.- document.documentElement.className = this.$store.state.postwoman.settings.THEME_CLASS || '';+ document.documentElement.className =+ this.$store.state.postwoman.settings.THEME_CLASS || "";// Load theme color data from settings, or use default color.- let color = this.$store.state.postwoman.settings.THEME_COLOR || '#50fa7b';+ let color = this.$store.state.postwoman.settings.THEME_COLOR || "#50fa7b";let vibrant = this.$store.state.postwoman.settings.THEME_COLOR_VIBRANT;if (vibrant == null) vibrant = true;- document.documentElement.style.setProperty('--ac-color', color);- document.documentElement.style.setProperty('--act-color', vibrant ? 'rgb(37, 38, 40)' : '#ffffff');+ document.documentElement.style.setProperty("--ac-color", color);+ document.documentElement.style.setProperty(+ "--act-color",+ vibrant ? "rgb(37, 38, 40)" : "#ffffff"+ );})();},mounted() {- if(process.client){- document.body.classList.add('afterLoad');+ if (process.client) {+ document.body.classList.add("afterLoad");}// Initializes the PWA code - checks if the app is installed,// etc.(async () => {this.showInstallPrompt = await intializePwa();- let cookiesAllowed = localStorage.getItem('cookiesAllowed') === 'yes';- if(!cookiesAllowed) {- this.$toast.show('We use cookies', {- icon: 'info',+ let cookiesAllowed = localStorage.getItem("cookiesAllowed") === "yes";+ if (!cookiesAllowed) {+ this.$toast.show("We use cookies", {+ icon: "info",duration: 5000,- theme: 'toasted-primary',+ theme: "toasted-primary",action: [{- text: 'Dismiss',+ text: "Dismiss",onClick: (e, toastObject) => {- localStorage.setItem('cookiesAllowed', 'yes');+ localStorage.setItem("cookiesAllowed", "yes");toastObject.goAway(0);}}@@ -221,10 +255,9 @@},watch: {- $route () {+ $route() {this.$toast.clear();}}- }-+ };</script>diff --git a/layouts/error.vue b/layouts/error.vueindex f2f332fdd..fc1e912e1 100644--- a/layouts/error.vue+++ b/layouts/error.vue@@ -1,10 +1,16 @@<template><div class="page page-error">- <img src="~static/icons/error.svg" alt="Error" class="error_banner">+ <img src="~static/icons/error.svg" alt="Error" class="error_banner" /><h2>{{ error.statusCode }}</h2><h3>{{ error.message }}</h3>- <p><nuxt-link to="/"><button>Go Home</button></nuxt-link></p>- <p><a href="" @click.prevent="reloadApplication">Reload</a></p>+ <p>+ <nuxt-link to="/">+ <button>Go Home</button>+ </nuxt-link>+ </p>+ <p>+ <a href @click.prevent="reloadApplication">Reload</a>+ </p></div></template>@@ -25,20 +31,20 @@<script>export default {- props: ['error'],+ props: ["error"],- methods: {- reloadApplication () {- this.$router.push('/', () => window.location.reload());- }- },-- head () {- return {- bodyAttrs: {- class: 'sticky-footer'- }- }+ methods: {+ reloadApplication() {+ this.$router.push("/", () => window.location.reload());}- }+ },++ head() {+ return {+ bodyAttrs: {+ class: "sticky-footer"+ }+ };+ }+ };</script>diff --git a/middleware/parsedefaulturl.js b/middleware/parsedefaulturl.jsindex 90fb6cf92..042f21cac 100644--- a/middleware/parsedefaulturl.js+++ b/middleware/parsedefaulturl.js@@ -1,5 +1,8 @@-export default function({ route, redirect }) {- if(route.fullPath !== '/') {+export default function ({+ route,+ redirect+}) {+ if (route.fullPath !== '/') {return redirect('/');}-}\ No newline at end of file+}diff --git a/pages/index.vue b/pages/index.vueindex f92021c01..4a97861a8 100644--- a/pages/index.vue+++ b/pages/index.vue@@ -2,8 +2,8 @@<div class="page"><save-request-asv-bind:show="showRequestModal"- v-on:hide-model='hideRequestModal'- v-bind:editing-request='editRequest'+ v-on:hide-model="hideRequestModal"+ v-bind:editing-request="editRequest"></save-request-as><pw-modal v-if="showModal" @close="showModal = false"><div slot="header">@@ -54,37 +54,62 @@</li><li><label for="url">URL</label>- <input :class="{ error: !isValidURL }" @keyup.enter="isValidURL ? sendRequest() : null" id="url" name="url" type="url" v-model="url">+ <input+ :class="{ error: !isValidURL }"+ @keyup.enter="isValidURL ? sendRequest() : null"+ id="url"+ name="url"+ type="url"+ v-model="url"+ /></li><li><label for="path">Path</label>- <input @keyup.enter="isValidURL ? sendRequest() : null" id="path" name="path" v-model="path" @input="pathInputHandler">+ <input+ @keyup.enter="isValidURL ? sendRequest() : null"+ id="path"+ name="path"+ v-model="path"+ @input="pathInputHandler"+ /></li><li><label for="label">Label</label>- <input id="label" name="label" type="text" v-model="label" placeholder="(optional)">+ <input id="label" name="label" type="text" v-model="label" placeholder="(optional)" /></li><li><label class="hide-on-small-screen" for="send"> </label><button :disabled="!isValidURL" @click="sendRequest" id="send" ref="sendButton">- Send<span id="hidden-message"> Again</span>- <span><i class="material-icons">send</i></span>+ Send+ <span id="hidden-message">Again</span>+ <span>+ <i class="material-icons">send</i>+ </span></button></li></ul>- <div class="blue" label="Request Body" v-if="method === 'POST' || method === 'PUT' || method === 'PATCH'">+ <div+ class="blue"+ label="Request Body"+ v-if="method === 'POST' || method === 'PUT' || method === 'PATCH'"+ ><ul><li><label for="contentType">Content Type</label>- <autocomplete :source="validContentTypes" :spellcheck="false" v-model="contentType">Content Type</autocomplete>+ <autocomplete+ :source="validContentTypes"+ :spellcheck="false"+ v-model="contentType"+ >Content Type</autocomplete></li></ul><ul><li><span>- <pw-toggle :on="rawInput" @change="rawInput = $event">- Raw Input {{ rawInput ? "Enabled" : "Disabled" }}- </pw-toggle>+ <pw-toggle+ :on="rawInput"+ @change="rawInput = $event"+ >Raw Input {{ rawInput ? "Enabled" : "Disabled" }}</pw-toggle></span></li></ul>@@ -92,15 +117,34 @@<ul><li><label for="reqParamList">Parameter List</label>- <textarea id="reqParamList" readonly v-textarea-auto-height="rawRequestBody" v-model="rawRequestBody" placeholder="(add at least one parameter)" rows="1"></textarea>+ <textarea+ id="reqParamList"+ readonly+ v-textarea-auto-height="rawRequestBody"+ v-model="rawRequestBody"+ placeholder="(add at least one parameter)"+ rows="1"+ ></textarea></li></ul><ul v-for="(param, index) in bodyParams" :key="index"><li>- <input :placeholder="'key '+(index+1)" :name="'bparam'+index" v-model="param.key" @keyup.prevent="setRouteQueryState" autofocus>+ <input+ :placeholder="'key '+(index+1)"+ :name="'bparam'+index"+ v-model="param.key"+ @keyup.prevent="setRouteQueryState"+ autofocus+ /></li><li>- <input :placeholder="'value '+(index+1)" :id="'bvalue'+index" :name="'bvalue'+index" v-model="param.value" @keyup.prevent="setRouteQueryState">+ <input+ :placeholder="'value '+(index+1)"+ :id="'bvalue'+index"+ :name="'bvalue'+index"+ v-model="param.value"+ @keyup.prevent="setRouteQueryState"+ /></li><div><li>@@ -123,29 +167,60 @@<ul><li><label for="rawBody">Raw Request Body</label>- <textarea id="rawBody" @keydown="formatRawParams" rows="8" v-model="rawParams" v-textarea-auto-height="rawParams"></textarea>+ <textarea+ id="rawBody"+ @keydown="formatRawParams"+ rows="8"+ v-model="rawParams"+ v-textarea-auto-height="rawParams"+ ></textarea></li></ul></div></div><div class="flex-wrap"><div style="text-align: center;">- <button class="icon" id="show-modal" @click="showModal = true" v-tooltip.bottom='"Import cURL"'>+ <button+ class="icon"+ id="show-modal"+ @click="showModal = true"+ v-tooltip.bottom="'Import cURL'"+ ><i class="material-icons">import_export</i></button>- <button class="icon" id="code" v-on:click="isHidden = !isHidden" :disabled="!isValidURL" v-tooltip.bottom='{ content: isHidden ? "Show Code" : "Hide Code"}'>+ <button+ class="icon"+ id="code"+ v-on:click="isHidden = !isHidden"+ :disabled="!isValidURL"+ v-tooltip.bottom="{ content: isHidden ? 'Show Code' : 'Hide Code'}"+ ><i class="material-icons" v-if="isHidden">visibility</i><i class="material-icons" v-if="!isHidden">visibility_off</i></button></div><div style="text-align: center;">- <button class="icon" @click="copyRequest" id="copyRequest" ref="copyRequest" :disabled="!isValidURL" v-tooltip.bottom='"Sharable request URL"'>+ <button+ class="icon"+ @click="copyRequest"+ id="copyRequest"+ ref="copyRequest"+ :disabled="!isValidURL"+ v-tooltip.bottom="'Sharable request URL'"+ ><i class="material-icons">share</i></button>- <button class="icon" @click="saveRequest" id="saveRequest" ref="saveRequest" :disabled="!isValidURL" v-tooltip.bottom='"Save to Collections"'>+ <button+ class="icon"+ @click="saveRequest"+ id="saveRequest"+ ref="saveRequest"+ :disabled="!isValidURL"+ v-tooltip.bottom="'Save to Collections'"+ ><i class="material-icons">save</i></button>- <button class="icon" @click="clearContent" v-tooltip.bottom='"Clear all"'>+ <button class="icon" @click="clearContent" v-tooltip.bottom="'Clear all'"><i class="material-icons">clear_all</i></button></div>@@ -167,13 +242,24 @@<div class="flex-wrap"><label for="generatedCode">Generated Code</label><div>- <button class="icon" @click="copyRequestCode" id="copyRequestCode" ref="copyRequestCode">+ <button+ class="icon"+ @click="copyRequestCode"+ id="copyRequestCode"+ ref="copyRequestCode"+ ><i class="material-icons">file_copy</i><span>Copy</span></button></div></div>- <textarea id="generatedCode" ref="generatedCode" name="generatedCode" rows="8" v-model="requestCode"></textarea>+ <textarea+ id="generatedCode"+ ref="generatedCode"+ name="generatedCode"+ rows="8"+ v-model="requestCode"+ ></textarea></li></ul></pw-section>@@ -181,13 +267,21 @@<ul><li><label for="status">status</label>- <input :class="statusCategory ? statusCategory.className : ''" :value="response.status || '(waiting to send request)'" ref="status" id="status" name="status" readonly type="text">+ <input+ :class="statusCategory ? statusCategory.className : ''"+ :value="response.status || '(waiting to send request)'"+ ref="status"+ id="status"+ name="status"+ readonly+ type="text"+ /></li></ul><ul v-for="(value, key) in response.headers" :key="key"><li><label :for="key">{{key}}</label>- <input :id="key" :value="value" :name="key" readonly>+ <input :id="key" :value="value" :name="key" readonly /></li></ul><ul v-if="response.body">@@ -202,8 +296,18 @@</div></div><div id="response-details-wrapper">- <pre><code ref="responseBody" id="body" rows="16" placeholder="(waiting to send request)">{{response.body}}</code></pre>- <iframe :class="{hidden: !previewEnabled}" class="covers-response" ref="previewFrame" src="about:blank"></iframe>+ <pre><code+ ref="responseBody"+ id="body"+ rows="16"+ placeholder="(waiting to send request)"+>{{response.body}}</code></pre>+ <iframe+ :class="{hidden: !previewEnabled}"+ class="covers-response"+ ref="previewFrame"+ src="about:blank"+ ></iframe></div><div class="align-right" v-if="response.body && responseType === 'text/html'"><button class="icon" @click.prevent="togglePreview">@@ -216,7 +320,7 @@</ul></pw-section><section>- <input id="tab-one" type="radio" name="grp" checked="checked">+ <input id="tab-one" type="radio" name="grp" checked="checked" /><label for="tab-one">Authentication</label><div class="tab"><pw-section class="cyan" icon="vpn_key" label="Authentication">@@ -240,14 +344,24 @@</ul><ul v-if="auth === 'Basic'"><li>- <input placeholder="User" name="http_basic_user" v-model="httpUser">+ <input placeholder="User" name="http_basic_user" v-model="httpUser" /></li><li>- <input placeholder="Password" name="http_basic_passwd" :type="passwordFieldType" v-model="httpPassword">+ <input+ placeholder="Password"+ name="http_basic_passwd"+ :type="passwordFieldType"+ v-model="httpPassword"+ /></li><div><li>- <button class="icon" id="switchVisibility" ref="switchVisibility" @click="switchVisibility">+ <button+ class="icon"+ id="switchVisibility"+ ref="switchVisibility"+ @click="switchVisibility"+ ><i class="material-icons" v-if="passwordFieldType === 'text'">visibility</i><i class="material-icons" v-if="passwordFieldType !== 'text'">visibility_off</i></button>@@ -256,12 +370,12 @@</ul><ul v-if="auth === 'Bearer Token'"><li>- <input placeholder="Token" name="bearer_token" v-model="bearerToken">+ <input placeholder="Token" name="bearer_token" v-model="bearerToken" /></li></ul></pw-section></div>- <input id="tab-two" type="radio" name="grp">+ <input id="tab-two" type="radio" name="grp" /><label for="tab-two">Headers</label><div class="tab"><pw-section class="orange" icon="toc" label="Headers">@@ -276,15 +390,33 @@</button></div></div>- <textarea id="headerList" readonly v-textarea-auto-height="headerString" v-model="headerString" placeholder="(add at least one header)" rows="1"></textarea>+ <textarea+ id="headerList"+ readonly+ v-textarea-auto-height="headerString"+ v-model="headerString"+ placeholder="(add at least one header)"+ rows="1"+ ></textarea></li></ul><ul v-for="(header, index) in headers" :key="index"><li>- <input :placeholder="'header '+(index+1)" :name="'header'+index" v-model="header.key" @keyup.prevent="setRouteQueryState" autofocus>+ <input+ :placeholder="'header '+(index+1)"+ :name="'header'+index"+ v-model="header.key"+ @keyup.prevent="setRouteQueryState"+ autofocus+ /></li><li>- <input :placeholder="'value '+(index+1)" :name="'value'+index" v-model="header.value" @keyup.prevent="setRouteQueryState">+ <input+ :placeholder="'value '+(index+1)"+ :name="'value'+index"+ v-model="header.value"+ @keyup.prevent="setRouteQueryState"+ /></li><div><li>@@ -304,7 +436,7 @@</ul></pw-section></div>- <input id="tab-three" type="radio" name="grp">+ <input id="tab-three" type="radio" name="grp" /><label for="tab-three">Parameters</label><div class="tab"><pw-section class="pink" icon="input" label="Parameters">@@ -319,15 +451,27 @@</button></div></div>- <textarea id="paramList" readonly v-textarea-auto-height="queryString" v-model="queryString" placeholder="(add at least one parameter)" rows="1"></textarea>+ <textarea+ id="paramList"+ readonly+ v-textarea-auto-height="queryString"+ v-model="queryString"+ placeholder="(add at least one parameter)"+ rows="1"+ ></textarea></li></ul><ul v-for="(param, index) in params" :key="index"><li>- <input :placeholder="'parameter '+(index+1)" :name="'param'+index" v-model="param.key" autofocus>+ <input+ :placeholder="'parameter '+(index+1)"+ :name="'param'+index"+ v-model="param.key"+ autofocus+ /></li><li>- <input :placeholder="'value '+(index+1)" :name="'value'+index" v-model="param.value">+ <input :placeholder="'value '+(index+1)" :name="'value'+index" v-model="param.value" /></li><div><li>@@ -355,841 +499,980 @@</div></template><script>- import url from 'url';- import querystring from "querystring";- 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";- import modal from "../components/modal";- import collections from '../components/collections';- import saveRequestAs from '../components/collections/saveRequestAs';- import parseCurlCommand from '../assets/js/curlparser.js';- import hljs from 'highlight.js';- import 'highlight.js/styles/dracula.css';+import url from "url";+import querystring from "querystring";+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";+import modal from "../components/modal";+import collections from "../components/collections";+import saveRequestAs from "../components/collections/saveRequestAs";+import parseCurlCommand from "../assets/js/curlparser.js";+import hljs from "highlight.js";+import "highlight.js/styles/dracula.css";++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"+ },+ {+ // 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 default {+ directives: {+ textareaAutoHeight+ },++ components: {+ "pw-section": section,+ "pw-toggle": toggle,+ "pw-modal": modal,+ history,+ autocomplete,+ collections,+ saveRequestAs+ },+ data() {+ return {+ label: "",+ showModal: false,+ copyButton: '<i class="material-icons">file_copy</i>',+ copiedButton: '<i class="material-icons">done</i>',+ method: "GET",+ url: "https://reqres.in",+ auth: "None",+ path: "/api/users",+ httpUser: "",+ httpPassword: "",+ passwordFieldType: "password",+ bearerToken: "",+ headers: [],+ params: [],+ bodyParams: [],+ rawParams: "",+ rawInput: false,+ contentType: "application/json",+ requestType: "JavaScript XHR",+ isHidden: true,+ response: {+ status: "",+ headers: "",+ body: ""+ },+ previewEnabled: false,+ paramsWatchEnabled: true,- const statusCategories = [{- name: 'informational',- statusCodeRegex: new RegExp(/[1][0-9]+/),- className: 'info-response'+ /**+ * 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"+ ],+ showRequestModal: false,+ editRequest: {}+ };+ },+ watch: {+ contentType(val) {+ this.rawInput = !this.knownContentTypes.includes(val);},- {- name: 'successful',- statusCodeRegex: new RegExp(/[2][0-9]+/),- className: 'success-response'+ rawInput(status) {+ if (status && this.rawParams === "") this.rawParams = "{}";+ else this.setRouteQueryState();},- {- name: 'redirection',- statusCodeRegex: new RegExp(/[3][0-9]+/),- className: 'redir-response'+ "response.body": function(val) {+ var responseText =+ document.querySelector("div#response-details-wrapper pre code") != null+ ? document.querySelector("div#response-details-wrapper pre code")+ : null;+ if (responseText) {+ if (+ document.querySelector(".hljs") !== null &&+ responseText.innerHTML.indexOf('<span class="hljs') !== -1+ ) {+ responseText.removeAttribute("class");+ responseText.innerHTML = null;+ responseText.innerText = this.response.body;+ } else if (+ responseText &&+ this.response.body !== "(waiting to send request)" &&+ this.response.body !== "Loading..." &&+ this.response.body !== "See JavaScript console (F12) for details."+ ) {+ responseText.innerText =+ this.responseType === "application/json" ||+ this.responseType === "application/hal+json"+ ? JSON.stringify(this.response.body, null, 2)+ : this.response.body;+ hljs.highlightBlock(+ document.querySelector("div#response-details-wrapper pre code")+ );+ } else {+ responseText.innerText = this.response.body;+ }+ }},- {- name: 'client error',- statusCodeRegex: new RegExp(/[4][0-9]+/),- className: 'cl-error-response'+ params: {+ handler: function(newValue) {+ if (!this.paramsWatchEnabled) {+ this.paramsWatchEnabled = true;+ return;+ }+ let path = this.path;+ let queryString = newValue+ .filter(({ key }) => !!key)+ .map(({ key, value }) => `${key}=${value}`)+ .join("&");+ queryString = queryString === "" ? "" : `?${queryString}`;+ if (path.includes("?")) {+ path = path.slice(0, path.indexOf("?")) + queryString;+ } else {+ path = path + queryString;+ }++ this.path = path;+ },+ deep: true},- {- name: 'server error',- statusCodeRegex: new RegExp(/[5][0-9]+/),- className: 'sv-error-response'+ selectedRequest(newValue, oldValue) {+ // @TODO: Convert all variables to single request variable+ if (!newValue) return;+ this.url = newValue.url;+ this.path = newValue.path;+ this.method = newValue.method;+ this.auth = newValue.auth;+ this.httpUser = newValue.httpUser;+ this.httpPassword = newValue.httpPassword;+ this.passwordFieldType = newValue.passwordFieldType;+ this.bearerToken = newValue.bearerToken;+ this.headers = newValue.headers;+ this.params = newValue.params;+ this.bodyParams = newValue.bodyParams;+ this.rawParams = newValue.rawParams;+ this.rawInput = newValue.rawInput;+ this.contentType = newValue.contentType;+ this.requestType = newValue.requestType;},- {- // 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'+ editingRequest(newValue) {+ this.editRequest = newValue;+ this.showRequestModal = true;}- ];- 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 default {- directives: {- textareaAutoHeight+ },+ computed: {+ selectedRequest() {+ return this.$store.state.postwoman.selectedRequest;},-- components: {- 'pw-section': section,- 'pw-toggle': toggle,- 'pw-modal': modal,- history,- autocomplete,- collections,- saveRequestAs,+ editingRequest() {+ return this.$store.state.postwoman.editingRequest;},- data() {- return {- label: '',- showModal: false,- copyButton: '<i class="material-icons">file_copy</i>',- copiedButton: '<i class="material-icons">done</i>',- method: 'GET',- url: 'https://reqres.in',- auth: 'None',- path: '/api/users',- httpUser: '',- httpPassword: '',- passwordFieldType: 'password',- bearerToken: '',- headers: [],- params: [],- bodyParams: [],- rawParams: '',- rawInput: false,- contentType: 'application/json',- requestType: 'JavaScript XHR',- isHidden: true,- response: {- status: '',- headers: '',- body: ''- },- previewEnabled: false,- paramsWatchEnabled: true,-- /**- * 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'- ],- showRequestModal: false,- editRequest: {},- }+ requestName() {+ return this.label;},- watch: {- contentType(val) {- this.rawInput = !this.knownContentTypes.includes(val);- },- rawInput(status) {- if (status && this.rawParams === '') this.rawParams = '{}'- else this.setRouteQueryState()- },- 'response.body': function (val) {- var responseText = document.querySelector("div#response-details-wrapper pre code") != null ? document- .querySelector("div#response-details-wrapper pre code") : null;- if (responseText) {- if (document.querySelector('.hljs') !== null && responseText.innerHTML.indexOf('<span class="hljs') !== -- 1) {- responseText.removeAttribute("class");- responseText.innerHTML = null;- responseText.innerText = this.response.body;- } else if (responseText && this.response.body !== "(waiting to send request)" && this.response.body !==- "Loading..." && this.response.body !== "See JavaScript console (F12) for details.") {- responseText.innerText = this.responseType === 'application/json' || this.responseType === 'application/hal+json' ? JSON.stringify(this.response.body,- null, 2) : this.response.body;- hljs.highlightBlock(document.querySelector("div#response-details-wrapper pre code"));- } else {- responseText.innerText = this.response.body- }+ 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);+ },+ pathName() {+ return this.path.match(/^([^?]*)\??/)[1];+ },+ 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";}- },- params: {- handler: function(newValue) {- if(!this.paramsWatchEnabled) {- this.paramsWatchEnabled = true;- return;- }- let path = this.path;- let queryString = newValue- .filter(({- key- }) => !!key)- .map(({- key,- value- }) => `${key}=${value}`).join('&')- queryString = queryString === '' ? '' : `?${queryString}`- if(path.includes('?')) {- path = path.slice(0, path.indexOf('?')) + queryString;- } else {- path = path + queryString- }-- this.path = path;- },- deep: true- },- selectedRequest (newValue, oldValue) {- // @TODO: Convert all variables to single request variable- if (!newValue) return;- this.url = newValue.url;- this.path = newValue.path;- this.method = newValue.method;- this.auth = newValue.auth;- this.httpUser = newValue.httpUser;- this.httpPassword = newValue.httpPassword;- this.passwordFieldType = newValue.passwordFieldType;- this.bearerToken = newValue.bearerToken;- this.headers = newValue.headers;- this.params = newValue.params;- this.bodyParams = newValue.bodyParams;- this.rawParams = newValue.rawParams;- this.rawInput = newValue.rawInput;- this.contentType = newValue.contentType;- this.requestType = newValue.requestType;- },- editingRequest (newValue) {- this.editRequest = newValue;- this.showRequestModal = true;+ } else {+ return bodyParams+ .filter(({ key }) => !!key)+ .map(({ key, value }) => `${key}=${encodeURIComponent(value)}`)+ .join("&");}},- computed: {- selectedRequest() {- return this.$store.state.postwoman.selectedRequest;- },- editingRequest() {- return this.$store.state.postwoman.editingRequest;- },- requestName() {- return this.label- },- 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])$"+ 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();+ },+ requestCode() {+ if (this.requestType === "JavaScript XHR") {+ var requestString = [];+ requestString.push("const xhr = new XMLHttpRequest()");+ const user = this.auth === "Basic" ? this.httpUser : null;+ const pswd = this.auth === "Basic" ? this.httpPassword : null;+ requestString.push(+ 'xhr.open("' ++ this.method ++ '", "' ++ this.url ++ this.path ++ this.queryString ++ '", true, ' ++ user ++ ", " ++ pswd ++ ")");- return validIP.test(this.url) || validHostname.test(this.url);- },- hasRequestBody() {- return ['POST', 'PUT', 'PATCH'].includes(this.method);- },- pathName() {- return this.path.match(/^([^?]*)\??/)[1]- },- 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'- }+ if (this.auth === "Bearer Token") {+ requestString.push(+ "xhr.setRequestHeader('Authorization', 'Bearer ' + " ++ this.bearerToken ++ ")"+ );+ }+ if (this.headers) {+ this.headers.forEach(function(element) {+ requestString.push(+ "xhr.setRequestHeader(" + element.key + ", " + element.value + ")"+ );+ });+ }+ if (["POST", "PUT", "PATCH"].includes(this.method)) {+ const requestBody = this.rawInput+ ? this.rawParams+ : this.rawRequestBody;+ requestString.push(+ "xhr.setRequestHeader('Content-Length', " + requestBody.length + ")"+ );+ requestString.push(+ "xhr.setRequestHeader('Content-Type', `" ++ this.contentType ++ "; charset=utf-8`)"+ );+ requestString.push("xhr.send(" + requestBody + ")");} else {- return bodyParams- .filter(({- key- }) => !!key)- .map(({- key,- value- }) => `${key}=${encodeURIComponent(value)}`).join('&')+ requestString.push("xhr.send()");}- },- 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();- },- requestCode() {- if (this.requestType === 'JavaScript XHR') {- var requestString = []- requestString.push('const xhr = new XMLHttpRequest()');- const user = this.auth === 'Basic' ? this.httpUser : null- const pswd = this.auth === 'Basic' ? this.httpPassword : null- requestString.push('xhr.open("' + this.method + '", "' + this.url + this.path + this.queryString + '", true, ' +- user + ', ' + pswd + ')');- if (this.auth === 'Bearer Token') {- requestString.push("xhr.setRequestHeader('Authorization', 'Bearer ' + " + this.bearerToken + ")");- }- if (this.headers) {- this.headers.forEach(function (element) {- requestString.push('xhr.setRequestHeader(' + element.key + ', ' + element.value + ')');- })- }- if (['POST', 'PUT', 'PATCH'].includes(this.method)) {- const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;- requestString.push("xhr.setRequestHeader('Content-Length', " + requestBody.length + ")")- requestString.push("xhr.setRequestHeader('Content-Type', `" + this.contentType + "; charset=utf-8`)")- requestString.push("xhr.send(" + requestBody + ")")- } else {- requestString.push('xhr.send()')- }- return requestString.join('\n');- } else if (this.requestType == 'Fetch') {- var requestString = [];- var headers = [];- requestString.push('fetch("' + this.url + this.path + this.queryString + '", {\n')- requestString.push(' method: "' + this.method + '",\n')- if (this.auth === 'Basic') {- var basic = this.httpUser + ':' + this.httpPassword;- headers.push(' "Authorization": "Basic ' + window.btoa(unescape(encodeURIComponent(basic))) + ',\n')- } else if (this.auth === 'Bearer Token') {- headers.push(' "Authorization": "Bearer Token ' + this.bearerToken + ',\n')- }- if (['POST', 'PUT', 'PATCH'].includes(this.method)) {- const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;- requestString.push(' body: ' + requestBody + ',\n')- headers.push(' "Content-Length": ' + requestBody.length + ',\n')- headers.push(' "Content-Type": "' + this.contentType + '; charset=utf-8",\n')- }- if (this.headers) {- this.headers.forEach(function (element) {- headers.push(' "' + element.key + '": "' + element.value + '",\n');- })- }- headers = headers.join('').slice(0, -3);- requestString.push(' headers: {\n' + headers + '\n },\n')- requestString.push(' credentials: "same-origin"\n')- requestString.push(')}).then(function(response) {\n')- requestString.push(' response.status\n')- requestString.push(' response.statusText\n')- requestString.push(' response.headers\n')- requestString.push(' response.url\n\n')- requestString.push(' return response.text()\n')- requestString.push(')}, function(error) {\n')- requestString.push(' error.message\n')- requestString.push(')}')- return requestString.join('');- } else if (this.requestType === 'cURL') {- var requestString = [];- requestString.push('curl -X ' + this.method + ' \\\n')- requestString.push(" '" + this.url + this.path + this.queryString + "' \\\n")- if (this.auth === 'Basic') {- var basic = this.httpUser + ':' + this.httpPassword;- requestString.push(" -H 'Authorization: Basic " + window.btoa(unescape(encodeURIComponent(basic))) +- "' \\\n")- } else if (this.auth === 'Bearer Token') {- requestString.push(" -H 'Authorization: Bearer Token " + this.bearerToken + "' \\\n")- }- if (this.headers) {- this.headers.forEach(function (element) {- requestString.push(" -H '" + element.key + ": " + element.value + "' \\\n");- })- }- if (['POST', 'PUT', 'PATCH'].includes(this.method)) {- const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;- requestString.push(" -H 'Content-Length: " + requestBody.length + "' \\\n")- requestString.push(" -H 'Content-Type: " + this.contentType + "; charset=utf-8' \\\n")- requestString.push(" -d '" + requestBody + "' \\\n")- }- return requestString.join('').slice(0, -3);+ return requestString.join("\n");+ } else if (this.requestType == "Fetch") {+ var requestString = [];+ var headers = [];+ requestString.push(+ 'fetch("' + this.url + this.path + this.queryString + '", {\n'+ );+ requestString.push(' method: "' + this.method + '",\n');+ if (this.auth === "Basic") {+ var basic = this.httpUser + ":" + this.httpPassword;+ headers.push(+ ' "Authorization": "Basic ' ++ window.btoa(unescape(encodeURIComponent(basic))) ++ ",\n"+ );+ } else if (this.auth === "Bearer Token") {+ headers.push(+ ' "Authorization": "Bearer Token ' + this.bearerToken + ",\n"+ );+ }+ if (["POST", "PUT", "PATCH"].includes(this.method)) {+ const requestBody = this.rawInput+ ? this.rawParams+ : this.rawRequestBody;+ requestString.push(" body: " + requestBody + ",\n");+ headers.push(' "Content-Length": ' + requestBody.length + ",\n");+ headers.push(+ ' "Content-Type": "' + this.contentType + '; charset=utf-8",\n'+ );+ }+ if (this.headers) {+ this.headers.forEach(function(element) {+ headers.push(+ ' "' + element.key + '": "' + element.value + '",\n'+ );+ });+ }+ headers = headers.join("").slice(0, -3);+ requestString.push(" headers: {\n" + headers + "\n },\n");+ requestString.push(' credentials: "same-origin"\n');+ requestString.push(")}).then(function(response) {\n");+ requestString.push(" response.status\n");+ requestString.push(" response.statusText\n");+ requestString.push(" response.headers\n");+ requestString.push(" response.url\n\n");+ requestString.push(" return response.text()\n");+ requestString.push(")}, function(error) {\n");+ requestString.push(" error.message\n");+ requestString.push(")}");+ return requestString.join("");+ } else if (this.requestType === "cURL") {+ var requestString = [];+ requestString.push("curl -X " + this.method + " \\\n");+ requestString.push(+ " '" + this.url + this.path + this.queryString + "' \\\n"+ );+ if (this.auth === "Basic") {+ var basic = this.httpUser + ":" + this.httpPassword;+ requestString.push(+ " -H 'Authorization: Basic " ++ window.btoa(unescape(encodeURIComponent(basic))) ++ "' \\\n"+ );+ } else if (this.auth === "Bearer Token") {+ requestString.push(+ " -H 'Authorization: Bearer Token " + this.bearerToken + "' \\\n"+ );+ }+ if (this.headers) {+ this.headers.forEach(function(element) {+ requestString.push(+ " -H '" + element.key + ": " + element.value + "' \\\n"+ );+ });+ }+ if (["POST", "PUT", "PATCH"].includes(this.method)) {+ const requestBody = this.rawInput+ ? this.rawParams+ : this.rawRequestBody;+ requestString.push(+ " -H 'Content-Length: " + requestBody.length + "' \\\n"+ );+ requestString.push(+ " -H 'Content-Type: " + this.contentType + "; charset=utf-8' \\\n"+ );+ requestString.push(" -d '" + requestBody + "' \\\n");}+ return requestString.join("").slice(0, -3);}+ }+ },+ methods: {+ handleUseHistory({ label, method, url, path }) {+ this.label = label;+ this.method = method;+ this.url = url;+ this.path = path;+ this.$refs.request.$el.scrollIntoView({+ behavior: "smooth"+ });},- methods: {- handleUseHistory({- label,- method,- url,- path- }) {- this.label = label;- this.method = method;- this.url = url;- this.path = path;- this.$refs.request.$el.scrollIntoView({- behavior: 'smooth'- });- },- async makeRequest(auth, headers, requestBody) {- const requestOptions = {- method: this.method,- url: this.url + this.pathName + this.queryString,- auth,- headers,- data: requestBody ? requestBody.toString() : null- };+ async makeRequest(auth, headers, requestBody) {+ const requestOptions = {+ method: this.method,+ url: this.url + this.pathName + this.queryString,+ auth,+ headers,+ data: requestBody ? requestBody.toString() : null+ };- const config = this.$store.state.postwoman.settings.PROXY_ENABLED ? {- method: 'POST',+ const config = this.$store.state.postwoman.settings.PROXY_ENABLED+ ? {+ method: "POST",url: `${window.location.protocol}//${window.location.host}/proxy`,data: requestOptions- } : requestOptions;-- const response = await this.$axios(config);- return this.$store.state.postwoman.settings.PROXY_ENABLED ? response.data : response;- },- async sendRequest() {- this.$toast.clear();-- if (!this.isValidURL) {- this.$toast.error('URL is not formatted properly', {- icon: 'error'- });- return;- }+ }+ : requestOptions;- // 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();+ const response = await this.$axios(config);+ return this.$store.state.postwoman.settings.PROXY_ENABLED+ ? response.data+ : response;+ },+ async sendRequest() {+ this.$toast.clear();- if (this.$refs.response.$el.classList.contains('hidden')) {- this.$refs.response.$el.classList.toggle('hidden')- }- this.$refs.response.$el.scrollIntoView({- behavior: 'smooth'+ if (!this.isValidURL) {+ this.$toast.error("URL is not formatted properly", {+ icon: "error"});- this.previewEnabled = false;- this.response.status = 'Fetching...';- this.response.body = 'Loading...';+ return;+ }- const auth = this.auth === 'Basic' ? {- username: this.httpUser,- password: this.httpPassword- } : null;+ // 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();- let headers = {};- let headersObject = {};+ 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...";- Object.keys(headers).forEach(id => {- headersObject[headers[id].key] = headers[id].value- });- headers = headersObject;+ const auth =+ this.auth === "Basic"+ ? {+ username: this.httpUser,+ password: this.httpPassword+ }+ : null;- // If the request has a body, we want to ensure Content-Length and- // Content-Type are sent.- let requestBody;- if (this.hasRequestBody) {- requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;+ let headers = {};+ let headersObject = {};- Object.assign(headers, {- //'Content-Length': requestBody.length,- 'Content-Type': `${this.contentType}; charset=utf-8`- });- }+ Object.keys(headers).forEach(id => {+ headersObject[headers[id].key] = headers[id].value;+ });+ headers = headersObject;- // 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 has a body, we want to ensure Content-Length and+ // Content-Type are sent.+ let requestBody;+ if (this.hasRequestBody) {+ requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;- 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),+ Object.assign(headers, {+ //'Content-Length': requestBody.length,+ "Content-Type": `${this.contentType}; charset=utf-8`+ });+ }- // We make our temporary headers object the source so- // that you can override the added headers if you- // specify them.- headers- );+ // 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}`;- Object.keys(headers).forEach(id => {- headersObject[headers[id].key] = headers[id].value- });- headers = headersObject;+ 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),- try {- const startTime = Date.now();+ // We make our temporary headers object the source so+ // that you can override the added headers if you+ // specify them.+ headers+ );- const payload = await this.makeRequest(auth, headers, requestBody);+ Object.keys(headers).forEach(id => {+ headersObject[headers[id].key] = headers[id].value;+ });+ headers = headersObject;- const duration = Date.now() - startTime;- this.$toast.info(`Finished in ${duration}ms`, {- icon: 'done'- });+ try {+ const startTime = Date.now();- (() => {- const status = this.response.status = payload.status;- const headers = this.response.headers = payload.headers;+ const payload = await this.makeRequest(auth, headers, requestBody);- // We don't need to bother parsing JSON, axios already handles it for us!- const body = this.response.body = payload.data;+ const duration = Date.now() - startTime;+ this.$toast.info(`Finished in ${duration}ms`, {+ icon: "done"+ });- const date = new Date().toLocaleDateString();- const time = new Date().toLocaleTimeString();+ (() => {+ const status = (this.response.status = payload.status);+ const headers = (this.response.headers = payload.headers);- // Addition of an entry to the history component.- const entry = {- label: this.requestName,- status,- date,- time,- method: this.method,- url: this.url,- path: this.path- };- this.$refs.historyComponent.addEntry(entry);- })();- } catch (error) {- console.error(error);- if (error.response) {- this.response.headers = error.response.headers;- this.response.status = error.response.status;- this.response.body = error.response.data;+ // We don't need to bother parsing JSON, axios already handles it for us!+ const body = (this.response.body = payload.data);- // Addition of an entry to the history component.- const entry = {- label: this.requestName,- 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;- } else {- this.response.status = error.message;- this.response.body = "See JavaScript console (F12) for details.";- this.$toast.error(error + ' (F12 for details)', {- icon: 'error'- });- if(!this.$store.state.postwoman.settings.PROXY_ENABLED) {- this.$toast.info('Try enabling Proxy', {- icon: 'help',- duration: 5000,- action: {- text: 'Settings',- onClick: (e, toastObject) => {- this.$router.push({ path: '/settings' });- }- }- });- }- }- }- },- getQueryStringFromPath() {- let queryString,- pathParsed = url.parse(this.path);- return queryString = pathParsed.query ? pathParsed.query : '';- },- queryStringToArray(queryString) {- let queryParsed = querystring.parse(queryString);- return Object.keys(queryParsed).map((key) => ({key: key, value: queryParsed[key]}))- },- pathInputHandler() {- let queryString = this.getQueryStringFromPath(),- params = this.queryStringToArray(queryString);+ const date = new Date().toLocaleDateString();+ const time = new Date().toLocaleTimeString();- this.paramsWatchEnabled = false;- this.params = params;- },- addRequestHeader() {- this.headers.push({- key: '',- value: ''- });- return false- },- removeRequestHeader(index) {- this.headers.splice(index, 1)- this.$toast.error('Deleted', {- icon: 'delete'- });- },- addRequestParam() {- this.params.push({- key: '',- value: ''- })- return false- },- removeRequestParam(index) {- this.params.splice(index, 1)- this.$toast.error('Deleted', {- icon: 'delete'- });- },- addRequestBodyParam() {- this.bodyParams.push({- key: '',- value: ''- })- return false- },- removeRequestBodyParam(index) {- this.bodyParams.splice(index, 1)- this.$toast.error('Deleted', {- icon: 'delete'- });- },- formatRawParams(event) {- if ((event.which !== 13 && event.which !== 9)) {+ // Addition of an entry to the history component.+ const entry = {+ label: this.requestName,+ status,+ date,+ time,+ method: this.method,+ url: this.url,+ path: this.path+ };+ this.$refs.historyComponent.addEntry(entry);+ })();+ } catch (error) {+ console.error(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 = {+ label: this.requestName,+ 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;- }- 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;- }- },- copyRequest() {- if (navigator.share) {- let time = new Date().toLocaleTimeString();- let date = new Date().toLocaleDateString();- navigator.share({- title: `Postwoman`,- text: `Postwoman • API request builder at ${time} on ${date}`,- url: window.location.href- }).then(() => {})- .catch(console.error);} else {- var dummy = document.createElement('input');- document.body.appendChild(dummy);- dummy.value = window.location.href;- dummy.select();- document.execCommand('copy');- document.body.removeChild(dummy);- this.$refs.copyRequest.innerHTML = this.copiedButton;- this.$toast.success('Copied to clipboard', {- icon: 'done'+ this.response.status = error.message;+ this.response.body = "See JavaScript console (F12) for details.";+ this.$toast.error(error + " (F12 for details)", {+ icon: "error"});- setTimeout(() => this.$refs.copyRequest.innerHTML = '<i class="material-icons">share</i>', 1000)+ if (!this.$store.state.postwoman.settings.PROXY_ENABLED) {+ this.$toast.info("Try enabling Proxy", {+ icon: "help",+ duration: 5000,+ action: {+ text: "Settings",+ onClick: (e, toastObject) => {+ this.$router.push({ path: "/settings" });+ }+ }+ });+ }}- },- copyRequestCode() {- this.$refs.copyRequestCode.innerHTML = this.copiedButton + '<span>Copied</span>';- this.$toast.success('Copied to clipboard', {- icon: 'done'- });- this.$refs.generatedCode.select();+ }+ },+ getQueryStringFromPath() {+ let queryString,+ pathParsed = url.parse(this.path);+ return (queryString = pathParsed.query ? pathParsed.query : "");+ },+ queryStringToArray(queryString) {+ let queryParsed = querystring.parse(queryString);+ return Object.keys(queryParsed).map(key => ({+ key: key,+ value: queryParsed[key]+ }));+ },+ pathInputHandler() {+ let queryString = this.getQueryStringFromPath(),+ params = this.queryStringToArray(queryString);++ this.paramsWatchEnabled = false;+ this.params = params;+ },+ addRequestHeader() {+ this.headers.push({+ key: "",+ value: ""+ });+ return false;+ },+ removeRequestHeader(index) {+ this.headers.splice(index, 1);+ this.$toast.error("Deleted", {+ icon: "delete"+ });+ },+ addRequestParam() {+ this.params.push({+ key: "",+ value: ""+ });+ return false;+ },+ removeRequestParam(index) {+ this.params.splice(index, 1);+ this.$toast.error("Deleted", {+ icon: "delete"+ });+ },+ addRequestBodyParam() {+ this.bodyParams.push({+ key: "",+ value: ""+ });+ return false;+ },+ removeRequestBodyParam(index) {+ this.bodyParams.splice(index, 1);+ this.$toast.error("Deleted", {+ icon: "delete"+ });+ },+ 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;+ }+ },+ copyRequest() {+ if (navigator.share) {+ let time = new Date().toLocaleTimeString();+ let date = new Date().toLocaleDateString();+ navigator+ .share({+ title: `Postwoman`,+ text: `Postwoman • API request builder at ${time} on ${date}`,+ url: window.location.href+ })+ .then(() => {})+ .catch(console.error);+ } else {+ var dummy = document.createElement("input");+ document.body.appendChild(dummy);+ dummy.value = window.location.href;+ dummy.select();document.execCommand("copy");- setTimeout(() => this.$refs.copyRequestCode.innerHTML = this.copyButton + '<span>Copy</span>', 1000)- },- copyResponse() {- this.$refs.copyResponse.innerHTML = this.copiedButton + '<span>Copied</span>';- this.$toast.success('Copied to clipboard', {- icon: 'done'+ document.body.removeChild(dummy);+ this.$refs.copyRequest.innerHTML = this.copiedButton;+ this.$toast.success("Copied to clipboard", {+ icon: "done"});- // Creates a textarea element- var aux = document.createElement("textarea");- var copy = this.responseType == 'application/json' ? JSON.stringify(this.response.body) : this.response.body;- // Adds response body to the new textarea- aux.innerText = copy;- // Append the textarea to the body- document.body.appendChild(aux);- // Highlight the content- aux.select();- document.execCommand('copy');- // Remove the input from the body- document.body.removeChild(aux);- setTimeout(() => this.$refs.copyResponse.innerHTML = this.copyButton + '<span>Copy</span>', 1000)- },- 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);- }- }- },- setRouteQueryState() {- const flat = key => this[key] !== '' ? `${key}=${this[key]}&` : ''- const deep = key => {- const haveItems = [...this[key]].length- if (haveItems && this[key]['value'] !== '') {- return `${key}=${JSON.stringify(this[key])}&`- } else return ''+ setTimeout(+ () =>+ (this.$refs.copyRequest.innerHTML =+ '<i class="material-icons">share</i>'),+ 1000+ );+ }+ },+ copyRequestCode() {+ this.$refs.copyRequestCode.innerHTML =+ this.copiedButton + "<span>Copied</span>";+ this.$toast.success("Copied to clipboard", {+ icon: "done"+ });+ this.$refs.generatedCode.select();+ document.execCommand("copy");+ setTimeout(+ () =>+ (this.$refs.copyRequestCode.innerHTML =+ this.copyButton + "<span>Copy</span>"),+ 1000+ );+ },+ copyResponse() {+ this.$refs.copyResponse.innerHTML =+ this.copiedButton + "<span>Copied</span>";+ this.$toast.success("Copied to clipboard", {+ icon: "done"+ });+ // Creates a textarea element+ var aux = document.createElement("textarea");+ var copy =+ this.responseType == "application/json"+ ? JSON.stringify(this.response.body)+ : this.response.body;+ // Adds response body to the new textarea+ aux.innerText = copy;+ // Append the textarea to the body+ document.body.appendChild(aux);+ // Highlight the content+ aux.select();+ document.execCommand("copy");+ // Remove the input from the body+ document.body.removeChild(aux);+ setTimeout(+ () =>+ (this.$refs.copyResponse.innerHTML =+ this.copyButton + "<span>Copy</span>"),+ 1000+ );+ },+ 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);}- let flats = ['method', 'url', 'path', 'auth', 'httpUser', 'httpPassword', 'bearerToken', 'contentType'].map(- item => flat(item))- let deeps = ['headers', 'params'].map(item => deep(item))- let bodyParams = this.rawInput ? [flat('rawParams')] : [deep('bodyParams')];+ }+ },+ setRouteQueryState() {+ const flat = key => (this[key] !== "" ? `${key}=${this[key]}&` : "");+ const deep = key => {+ const haveItems = [...this[key]].length;+ if (haveItems && this[key]["value"] !== "") {+ return `${key}=${JSON.stringify(this[key])}&`;+ } else return "";+ };+ let flats = [+ "method",+ "url",+ "path",+ "auth",+ "httpUser",+ "httpPassword",+ "bearerToken",+ "contentType"+ ].map(item => flat(item));+ let deeps = ["headers", "params"].map(item => deep(item));+ let bodyParams = this.rawInput+ ? [flat("rawParams")]+ : [deep("bodyParams")];- this.$router.replace('/?' + flats.concat(deeps, bodyParams).join('').slice(0, -1))- },- setRouteQueries(queries) {- if (typeof (queries) !== 'object') throw new Error('Route query parameters must be a Object')- for (const key in queries) {- if (['headers', 'params', 'bodyParams'].includes(key)) this[key] = JSON.parse(queries[key])- if (key === 'rawParams') {- this.rawInput = true- this.rawParams = queries['rawParams']- } else if (typeof (this[key]) === 'string') this[key] = queries[key]- }- },- observeRequestButton() {- const requestElement = this.$refs.request.$el;- const sendButtonElement = this.$refs.sendButton;- const observer = new IntersectionObserver((entries, observer) => {+ this.$router.replace(+ "/?" ++ flats+ .concat(deeps, bodyParams)+ .join("")+ .slice(0, -1)+ );+ },+ setRouteQueries(queries) {+ if (typeof queries !== "object")+ throw new Error("Route query parameters must be a Object");+ for (const key in queries) {+ if (["headers", "params", "bodyParams"].includes(key))+ this[key] = JSON.parse(queries[key]);+ if (key === "rawParams") {+ this.rawInput = true;+ this.rawParams = queries["rawParams"];+ } else if (typeof this[key] === "string") 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 => {- if(entry.isIntersecting) sendButtonElement.classList.remove('show');+ if (entry.isIntersecting)+ sendButtonElement.classList.remove("show");// The button should float when it is no longer visible on screen.// This is done by adding the show class to the button.- else sendButtonElement.classList.add('show');+ else sendButtonElement.classList.add("show");});- }, {- rootMargin: '0px',- threshold: [0],- });- observer.observe(requestElement);- },- handleImport() {- let textarea = document.getElementById("import-text")- let text = textarea.value;- try {- let parsedCurl = parseCurlCommand(text);- this.url = parsedCurl.url.replace(/"/g,"").replace(/'/g,"");- this.url = this.url.slice(-1).pop() == '/' ? this.url.slice(0, -1): this.url;- this.path = "";- this.headers = [];- for (const key of Object.keys(parsedCurl.headers)) {- this.headers.push({- key: key,- value: parsedCurl.headers[key]- })- }- this.method = parsedCurl.method.toUpperCase();- if (parsedCurl["data"]){- this.rawInput = true;- this.rawParams = parsedCurl["data"];- }- this.showModal = false;- } catch (error) {- this.showModal = false;- this.$toast.error('cURL is not formatted properly', {- icon: 'error'+ },+ {+ rootMargin: "0px",+ threshold: [0]+ }+ );+ observer.observe(requestElement);+ },+ handleImport() {+ let textarea = document.getElementById("import-text");+ let text = textarea.value;+ try {+ let parsedCurl = parseCurlCommand(text);+ this.url = parsedCurl.url.replace(/"/g, "").replace(/'/g, "");+ this.url =+ this.url.slice(-1).pop() == "/" ? this.url.slice(0, -1) : this.url;+ this.path = "";+ this.headers = [];+ for (const key of Object.keys(parsedCurl.headers)) {+ this.headers.push({+ key: key,+ value: parsedCurl.headers[key]});}- },- toggleModal() {- this.showModal = !this.showModal;- },- switchVisibility() {- this.passwordFieldType = this.passwordFieldType === 'password' ? 'text' : 'password'- },- clearContent(name) {- switch(name) {- case "auth":- this.auth = 'None';- this.httpUser = '';- this.httpPassword = '';- this.bearerToken = '';- break;- case "headers":- this.headers = [];- break;- case "parameters":- this.params = [];- break;- default:- this.label = '',- this.method= 'GET',- this.url = 'https://reqres.in',- this.auth = 'None',- this.path = '/api/users',- this.auth = 'None';- this.httpUser = '';- this.httpPassword = '';- this.bearerToken = '';- this.headers = [];- this.params = [];- this.bodyParams = [];- this.rawParams = '';+ this.method = parsedCurl.method.toUpperCase();+ if (parsedCurl["data"]) {+ this.rawInput = true;+ this.rawParams = parsedCurl["data"];}- this.$toast.info('Cleared', {- icon: 'clear_all'+ this.showModal = false;+ } catch (error) {+ this.showModal = false;+ this.$toast.error("cURL is not formatted properly", {+ icon: "error"});- },- saveRequest() {- this.editRequest = {- url: this.url,- path: this.path,- method: this.method,- auth: this.auth,- httpUser: this.httpUser,- httpPassword: this.httpPassword,- passwordFieldType: this.passwordFieldType,- bearerToken: this.bearerToken,- headers: this.headers,- params: this.params,- bodyParams: this.bodyParams,- rawParams: this.rawParams,- rawInput: this.rawInput,- contentType: this.contentType,- requestType: this.requestType,- };+ }+ },+ toggleModal() {+ this.showModal = !this.showModal;+ },+ switchVisibility() {+ this.passwordFieldType =+ this.passwordFieldType === "password" ? "text" : "password";+ },+ clearContent(name) {+ switch (name) {+ case "auth":+ this.auth = "None";+ this.httpUser = "";+ this.httpPassword = "";+ this.bearerToken = "";+ break;+ case "headers":+ this.headers = [];+ break;+ case "parameters":+ this.params = [];+ break;+ default:+ (this.label = ""),+ (this.method = "GET"),+ (this.url = "https://reqres.in"),+ (this.auth = "None"),+ (this.path = "/api/users"),+ (this.auth = "None");+ this.httpUser = "";+ this.httpPassword = "";+ this.bearerToken = "";+ this.headers = [];+ this.params = [];+ this.bodyParams = [];+ this.rawParams = "";+ }+ this.$toast.info("Cleared", {+ icon: "clear_all"+ });+ },+ saveRequest() {+ this.editRequest = {+ url: this.url,+ path: this.path,+ method: this.method,+ auth: this.auth,+ httpUser: this.httpUser,+ httpPassword: this.httpPassword,+ passwordFieldType: this.passwordFieldType,+ bearerToken: this.bearerToken,+ headers: this.headers,+ params: this.params,+ bodyParams: this.bodyParams,+ rawParams: this.rawParams,+ rawInput: this.rawInput,+ contentType: this.contentType,+ requestType: this.requestType+ };- if (this.selectedRequest.url) {- this.editRequest = Object.assign({}, this.selectedRequest, this.editRequest);- }+ if (this.selectedRequest.url) {+ this.editRequest = Object.assign(+ {},+ this.selectedRequest,+ this.editRequest+ );+ }- this.showRequestModal = true;- },- hideRequestModal() {- this.showRequestModal = false;- this.editRequest = {};- },- },- mounted() {- this.observeRequestButton();+ this.showRequestModal = true;},- created() {- if (Object.keys(this.$route.query).length) this.setRouteQueries(this.$route.query);- this.$watch(vm => [+ hideRequestModal() {+ this.showRequestModal = false;+ this.editRequest = {};+ }+ },+ mounted() {+ this.observeRequestButton();+ },+ created() {+ if (Object.keys(this.$route.query).length)+ this.setRouteQueries(this.$route.query);+ this.$watch(+ vm => [vm.label,vm.method,vm.url,@@ -1203,9 +1486,11 @@vm.bodyParams,vm.contentType,vm.rawParams- ], val => {- this.setRouteQueryState()- })- }+ ],+ val => {+ this.setRouteQueryState();+ }+ );}+};</script>diff --git a/pages/settings.vue b/pages/settings.vueindex 09c51f7c4..06c707969 100644--- a/pages/settings.vue+++ b/pages/settings.vue@@ -6,7 +6,12 @@<h3 class="title">Background</h3><div class="backgrounds"><span :key="theme.class" @click="applyTheme(theme.class)" v-for="theme in themes">- <swatch :active="settings.THEME_CLASS === theme.class" :class="{ vibrant: theme.vibrant }" :color="theme.color" :name="theme.name"></swatch>+ <swatch+ :active="settings.THEME_CLASS === theme.class"+ :class="{ vibrant: theme.vibrant }"+ :color="theme.color"+ :name="theme.name"+ ></swatch></span></div></li>@@ -15,8 +20,17 @@<li><h3 class="title">Color</h3><div class="colors">- <span :key="entry.color" @click.prevent="setActiveColor(entry.color, entry.vibrant)" v-for="entry in colors">- <swatch :active="settings.THEME_COLOR === entry.color.toUpperCase()" :class="{ vibrant: entry.vibrant }" :color="entry.color" :name="entry.name" />+ <span+ :key="entry.color"+ @click.prevent="setActiveColor(entry.color, entry.vibrant)"+ v-for="entry in colors"+ >+ <swatch+ :active="settings.THEME_COLOR === entry.color.toUpperCase()"+ :class="{ vibrant: entry.vibrant }"+ :color="entry.color"+ :name="entry.name"+ /></span></div></li>@@ -25,21 +39,23 @@<li><h3 class="title">Frames</h3><span>- <pw-toggle :on="!settings.DISABLE_FRAME_COLORS" @change="applySetting('DISABLE_FRAME_COLORS', $event)">- Multi-color {{ settings.DISABLE_FRAME_COLORS ? "Disabled" : "Enabled" }}- </pw-toggle>+ <pw-toggle+ :on="!settings.DISABLE_FRAME_COLORS"+ @change="applySetting('DISABLE_FRAME_COLORS', $event)"+ >Multi-color {{ settings.DISABLE_FRAME_COLORS ? "Disabled" : "Enabled" }}</pw-toggle></span></li></ul></pw-section>- <pw-section class="blue" icon="public" label="Proxy">- <ul>- <li>- <pw-toggle :on="settings.PROXY_ENABLED" @change="applySetting('PROXY_ENABLED', $event)">- Proxy {{ settings.PROXY_ENABLED ? "enabled" : "disabled" }}- </pw-toggle>- </li>- </ul>+ <pw-section class="blue" icon="public" label="Proxy">+ <ul>+ <li>+ <pw-toggle+ :on="settings.PROXY_ENABLED"+ @change="applySetting('PROXY_ENABLED', $event)"+ >Proxy {{ settings.PROXY_ENABLED ? "enabled" : "disabled" }}</pw-toggle>+ </li>+ </ul><!--PROXY SETTINGS URL AND KEY--------------@@ -55,10 +71,10 @@</li></ul>-->- </pw-section>-+ </pw-section></div></template>+<script>import section from "../components/section";import swatch from "../components/settings/swatch";@@ -66,9 +82,9 @@export default {components: {- 'pw-section': section,- 'pw-toggle': toggle,- 'swatch': swatch+ "pw-section": section,+ "pw-toggle": toggle,+ swatch: swatch},data() {@@ -78,128 +94,137 @@// set the relevant values.themes: [{- "color": "rgb(37, 38, 40)",- "name": "Kinda Dark",- "class": ""+ color: "rgb(37, 38, 40)",+ name: "Kinda Dark",+ class: ""},{- "color": "#ffffff",- "name": "Clearly White",- "vibrant": true,- "class": "light"+ color: "#ffffff",+ name: "Clearly White",+ vibrant: true,+ class: "light"},{- "color": "#000000",- "name": "Just Black",- "class": "black"+ color: "#000000",+ name: "Just Black",+ class: "black"},{- "color": "var(--bg-color)",- "name": "Auto (system)",- "vibrant": window.matchMedia('(prefers-color-scheme: light)').matches,- "class": "auto"+ color: "var(--bg-color)",+ name: "Auto (system)",+ vibrant: window.matchMedia("(prefers-color-scheme: light)").matches,+ class: "auto"}],// You can define a new color here! It will simply store the color value.colors: [// If the color is vibrant, black is used as the active foreground color.{- "color": "#50fa7b",- "name": "Green",- "vibrant": true+ color: "#50fa7b",+ name: "Green",+ vibrant: true},{- "color": "#f1fa8c",- "name": "Yellow",- "vibrant": true+ color: "#f1fa8c",+ name: "Yellow",+ vibrant: true},{- "color": "#ff79c6",- "name": "Pink",- "vibrant": true+ color: "#ff79c6",+ name: "Pink",+ vibrant: true},{- "color": "#ff5555",- "name": "Red",- "vibrant": false+ color: "#ff5555",+ name: "Red",+ vibrant: false},{- "color": "#bd93f9",- "name": "Purple",- "vibrant": true+ color: "#bd93f9",+ name: "Purple",+ vibrant: true},{- "color": "#ffb86c",- "name": "Orange",- "vibrant": true+ color: "#ffb86c",+ name: "Orange",+ vibrant: true},{- "color": "#8be9fd",- "name": "Cyan",- "vibrant": true+ color: "#8be9fd",+ name: "Cyan",+ vibrant: true},{- "color": "#57b5f9",- "name": "Blue",- "vibrant": false- },+ color: "#57b5f9",+ name: "Blue",+ vibrant: false+ }],settings: {- THEME_CLASS: this.$store.state.postwoman.settings.THEME_CLASS || '',- THEME_COLOR: '',+ THEME_CLASS: this.$store.state.postwoman.settings.THEME_CLASS || "",+ THEME_COLOR: "",THEME_COLOR_VIBRANT: true,- DISABLE_FRAME_COLORS: this.$store.state.postwoman.settings.DISABLE_FRAME_COLORS || false,- PROXY_ENABLED: this.$store.state.postwoman.settings.PROXY_ENABLED || false,- PROXY_URL: this.$store.state.postwoman.settings.PROXY_URL || '',- PROXY_KEY: this.$store.state.postwoman.settings.PROXY_KEY || ''+ DISABLE_FRAME_COLORS:+ this.$store.state.postwoman.settings.DISABLE_FRAME_COLORS || false,+ PROXY_ENABLED:+ this.$store.state.postwoman.settings.PROXY_ENABLED || false,+ PROXY_URL: this.$store.state.postwoman.settings.PROXY_URL || "",+ PROXY_KEY: this.$store.state.postwoman.settings.PROXY_KEY || ""}- }+ };},watch: {proxySettings: {deep: true,handler(value) {- this.applySetting('PROXY_URL', value.url);- this.applySetting('PROXY_KEY', value.key);+ this.applySetting("PROXY_URL", value.url);+ this.applySetting("PROXY_KEY", value.key);}}},methods: {applyTheme(name) {- this.applySetting('THEME_CLASS', name);+ this.applySetting("THEME_CLASS", name);document.documentElement.className = name;let imgGitHub = document.getElementById("imgGitHub");- imgGitHub.style['filter'] = "";- imgGitHub.style['webkit-filter'] = "invert(100%)";+ imgGitHub.style["filter"] = "";+ imgGitHub.style["webkit-filter"] = "invert(100%)";if (name.includes("light")) {- imgGitHub.style['filter'] = "invert(100%)";- imgGitHub.style['webkit-filter'] = "invert(100%)";+ imgGitHub.style["filter"] = "invert(100%)";+ imgGitHub.style["webkit-filter"] = "invert(100%)";}},setActiveColor(color, vibrant) {// By default, the color is vibrant.if (vibrant == null) vibrant = true;- document.documentElement.style.setProperty('--ac-color', color);- document.documentElement.style.setProperty('--act-color', vibrant ? 'rgb(37, 38, 40)' : '#f8f8f2');- this.applySetting('THEME_COLOR', color.toUpperCase());- this.applySetting('THEME_COLOR_VIBRANT', vibrant);+ document.documentElement.style.setProperty("--ac-color", color);+ document.documentElement.style.setProperty(+ "--act-color",+ vibrant ? "rgb(37, 38, 40)" : "#f8f8f2"+ );+ this.applySetting("THEME_COLOR", color.toUpperCase());+ this.applySetting("THEME_COLOR_VIBRANT", vibrant);},getActiveColor() {// This strips extra spaces and # signs from the strings.- const strip = (str) => str.replace(/#/g, '').replace(/ /g, '');- return `#${strip(window.getComputedStyle(document.documentElement).getPropertyValue('--ac-color')).toUpperCase()}`;+ const strip = str => str.replace(/#/g, "").replace(/ /g, "");+ return `#${strip(+ window+ .getComputedStyle(document.documentElement)+ .getPropertyValue("--ac-color")+ ).toUpperCase()}`;},applySetting(key, value) {this.settings[key] = value;- this.$store.commit('postwoman/applySetting', [key, value]);+ this.$store.commit("postwoman/applySetting", [key, value]);},toggleSetting(key) {this.settings[key] = !this.settings[key];- this.$store.commit('postwoman/applySetting', [key, this.settings[key]]);+ this.$store.commit("postwoman/applySetting", [key, this.settings[key]]);}},beforeMount() {@@ -211,9 +236,8 @@return {url: this.settings.PROXY_URL,key: this.settings.PROXY_KEY- }+ };}}- }-+ };</script>diff --git a/pages/websocket.vue b/pages/websocket.vueindex 34d806b63..c70884149 100644--- a/pages/websocket.vue+++ b/pages/websocket.vue@@ -4,7 +4,13 @@<ul><li><label for="url">URL</label>- <input id="url" type="url" :class="{ error: !urlValid }" v-model="url" @keyup.enter="urlValid ? toggleConnection() : null">+ <input+ id="url"+ type="url"+ :class="{ error: !urlValid }"+ v-model="url"+ @keyup.enter="urlValid ? toggleConnection() : null"+ /></li><li><label for="connect" class="hide-on-small-screen"> </label>@@ -18,13 +24,23 @@</li></ul></pw-section>- <pw-section class="purple" icon="cloud_download" label="Communication" id="response" ref="response">+ <pw-section+ class="purple"+ icon="cloud_download"+ label="Communication"+ id="response"+ ref="response"+ ><ul><li><label for="log">Log</label><div id="log" name="log" class="log"><span v-if="communication.log">- <span v-for="(logEntry, index) in communication.log" :style="{ color: logEntry.color }" :key="index">@ {{ logEntry.ts }} {{ getSourcePrefix(logEntry.source) }} {{ logEntry.payload }}</span>+ <span+ v-for="(logEntry, index) in communication.log"+ :style="{ color: logEntry.color }"+ :key="index"+ >@ {{ logEntry.ts }} {{ getSourcePrefix(logEntry.source) }} {{ logEntry.payload }}</span></span><span v-else>(waiting for connection)</span></div>@@ -33,7 +49,14 @@<ul><li><label for="message">Message</label>- <input id="message" name="message" type="text" v-model="communication.input" :readonly="!connectionState" @keyup.enter="connectionState ? sendMessage() : null">+ <input+ id="message"+ name="message"+ type="text"+ v-model="communication.input"+ :readonly="!connectionState"+ @keyup.enter="connectionState ? sendMessage() : null"+ /></li><li><label for="send" class="hide-on-small-screen"> </label>@@ -62,7 +85,7 @@&,span {font-size: 18px;- font-family: 'Roboto Mono', monospace;+ font-family: "Roboto Mono", monospace;}span {@@ -70,13 +93,13 @@white-space: pre-wrap;}}-</style>+<script>import section from "../components/section";export default {components: {- 'pw-section': section+ "pw-section": section},data() {return {@@ -87,19 +110,22 @@log: null,input: ""}- }+ };},computed: {toggleConnectionVerb() {return !this.connectionState ? "Connect" : "Disconnect";},urlValid() {- const pattern = new RegExp('^(wss?:\\/\\/)?' +- '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' +- '((\\d{1,3}\\.){3}\\d{1,3}))' +- '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' +- '(\\?[;&a-z\\d%_.~+=-]*)?' +- '(\\#[-a-z\\d_]*)?$', 'i');+ const pattern = new RegExp(+ "^(wss?:\\/\\/)?" ++ "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" ++ "((\\d{1,3}\\.){3}\\d{1,3}))" ++ "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" ++ "(\\?[;&a-z\\d%_.~+=-]*)?" ++ "(\\#[-a-z\\d_]*)?$",+ "i"+ );return pattern.test(this.url);}},@@ -111,51 +137,55 @@else return this.disconnect();},connect() {- this.communication.log = [{- payload: `Connecting to ${this.url}...`,- source: 'info',- color: 'var(--ac-color)'- }];+ this.communication.log = [+ {+ payload: `Connecting to ${this.url}...`,+ source: "info",+ color: "var(--ac-color)"+ }+ ];try {this.socket = new WebSocket(this.url);- this.socket.onopen = (event) => {+ this.socket.onopen = event => {this.connectionState = true;- this.communication.log = [{- payload: `Connected to ${this.url}.`,- source: 'info',- color: 'var(--ac-color)',- ts: (new Date()).toLocaleTimeString()- }];- this.$toast.success('Connected', {- icon: 'sync'+ this.communication.log = [+ {+ payload: `Connected to ${this.url}.`,+ source: "info",+ color: "var(--ac-color)",+ ts: new Date().toLocaleTimeString()+ }+ ];+ this.$toast.success("Connected", {+ icon: "sync"});};- this.socket.onerror = (event) => {+ this.socket.onerror = event => {this.handleError();};- this.socket.onclose = (event) => {+ this.socket.onclose = event => {this.connectionState = false;this.communication.log.push({payload: `Disconnected from ${this.url}.`,- source: 'info',- color: '#ff5555',- ts: (new Date()).toLocaleTimeString()+ source: "info",+ color: "#ff5555",+ ts: new Date().toLocaleTimeString()});- this.$toast.error('Disconnected', {- icon: 'sync_disabled'+ this.$toast.error("Disconnected", {+ icon: "sync_disabled"});};- this.socket.onmessage = (event) => {+ this.socket.onmessage = event => {this.communication.log.push({payload: event.data,- source: 'server',- ts: (new Date()).toLocaleTimeString()+ source: "server",+ ts: new Date().toLocaleTimeString()});- }+ };} catch (ex) {this.handleError(ex);- this.$toast.error('Something went wrong!', {- icon: 'error'+ this.$toast.error("Something went wrong!", {+ icon: "error"});}},@@ -167,52 +197,51 @@this.connectionState = false;this.communication.log.push({payload: `An error has occurred.`,- source: 'info',- color: '#ff5555',- ts: (new Date()).toLocaleTimeString()- });- if (error != null) this.communication.log.push({- payload: error,- source: 'info',- color: '#ff5555',- ts: (new Date()).toLocaleTimeString()+ source: "info",+ color: "#ff5555",+ ts: new Date().toLocaleTimeString()});+ if (error != null)+ this.communication.log.push({+ payload: error,+ source: "info",+ color: "#ff5555",+ ts: new Date().toLocaleTimeString()+ });},sendMessage() {const message = this.communication.input;this.socket.send(message);this.communication.log.push({payload: message,- source: 'client',- ts: (new Date()).toLocaleTimeString()+ source: "client",+ ts: new Date().toLocaleTimeString()});this.communication.input = "";},- collapse({- target- }) {+ collapse({ target }) {const el = target.parentNode.className;- document.getElementsByClassName(el)[0].classList.toggle('hidden');+ document.getElementsByClassName(el)[0].classList.toggle("hidden");},getSourcePrefix(source) {const sourceEmojis = {// Source used for info messages.- 'info': '\tℹ️ [INFO]:\t',+ info: "\tℹ️ [INFO]:\t",// Source used for client to server messages.- 'client': '\t👽 [SENT]:\t',+ client: "\t👽 [SENT]:\t",// Source used for server to client messages.- 'server': '\t📥 [RECEIVED]:\t'+ server: "\t📥 [RECEIVED]:\t"};- if (Object.keys(sourceEmojis).includes(source)) return sourceEmojis[source];- return '';+ if (Object.keys(sourceEmojis).includes(source))+ return sourceEmojis[source];+ return "";}},- updated: function () {- this.$nextTick(function () {- var divLog = document.getElementById("log")- divLog.scrollBy(0, divLog.scrollHeight + 100)- })+ updated: function() {+ this.$nextTick(function() {+ var divLog = document.getElementById("log");+ divLog.scrollBy(0, divLog.scrollHeight + 100);+ });}- }-+ };</script>diff --git a/plugins/vuex-persist.js b/plugins/vuex-persist.jsindex 09fc9ad02..7dd794b68 100644--- a/plugins/vuex-persist.js+++ b/plugins/vuex-persist.js@@ -1,5 +1,7 @@import VuexPersistence from "vuex-persist";-export default ({ store }) => {- new VuexPersistence().plugin(store);-}\ No newline at end of file+export default ({+ store+}) => {+ new VuexPersistence().plugin(store);+}diff --git a/proxy/index.js b/proxy/index.jsindex 957a87817..847e33514 100644--- a/proxy/index.js+++ b/proxy/index.js@@ -13,7 +13,13 @@ app.use((req, res, next) => {});app.post('/', async (req, res) => {- const {method, url, auth, headers, data} = req.body;+ const {+ method,+ url,+ auth,+ headers,+ data+ } = req.body;try {const payload = await axios({@@ -25,14 +31,14 @@ app.post('/', async (req, res) => {});return await res.json({- data: payload.data,- status: payload.status,- statusText: payload.statusText,- headers: payload.headers,+ data: payload.data,+ status: payload.status,+ statusText: payload.statusText,+ headers: payload.headers,});- } catch(error) {- if(error.response) {+ } catch (error) {+ if (error.response) {const errorResponse = error.response;return await res.json({data: errorResponse.data,diff --git a/store/index.js b/store/index.jsindex 5c933b16b..03048022a 100644--- a/store/index.js+++ b/store/index.js@@ -1,3 +1,3 @@export default {-}\ No newline at end of file+}diff --git a/store/postwoman.js b/store/postwoman.jsindex b8ecb2391..cb6986e4c 100644--- a/store/postwoman.js+++ b/store/postwoman.js@@ -1,241 +1,262 @@import Vue from 'vue'export const SETTINGS_KEYS = [- /**- * The CSS class that should be applied to the root element.- * Essentially, the name of the background theme.- */- "THEME_CLASS",-- /**- * The hex color code for the currently active theme.- */- "THEME_COLOR",-- /**- * Whether or not THEME_COLOR is considered 'vibrant'.- *- * For readability reasons, if the THEME_COLOR is vibrant,- * any text placed on the theme color will have its color- * inverted from white to black.- */- "THEME_COLOR_VIBRANT",-- /**- * Normally, section frames are multicolored in the UI- * to emphasise the different sections.- * This setting allows that to be turned off.- */- "DISABLE_FRAME_COLORS",-- /**- * Whether or not requests should be proxied.- */- "PROXY_ENABLED",-- /**- * The URL of the proxy to connect to for requests.- */- "PROXY_URL",- /**- * The security key of the proxy.- */- "PROXY_KEY"+ /**+ * The CSS class that should be applied to the root element.+ * Essentially, the name of the background theme.+ */+ "THEME_CLASS",++ /**+ * The hex color code for the currently active theme.+ */+ "THEME_COLOR",++ /**+ * Whether or not THEME_COLOR is considered 'vibrant'.+ *+ * For readability reasons, if the THEME_COLOR is vibrant,+ * any text placed on the theme color will have its color+ * inverted from white to black.+ */+ "THEME_COLOR_VIBRANT",++ /**+ * Normally, section frames are multicolored in the UI+ * to emphasise the different sections.+ * This setting allows that to be turned off.+ */+ "DISABLE_FRAME_COLORS",++ /**+ * Whether or not requests should be proxied.+ */+ "PROXY_ENABLED",++ /**+ * The URL of the proxy to connect to for requests.+ */+ "PROXY_URL",+ /**+ * The security key of the proxy.+ */+ "PROXY_KEY"];export const state = () => ({- settings : {},- collections : [{- name : 'My First Collection',- folders : [],- requests : [],- }],- selectedRequest : {},- editingRequest : {},+ settings: {},+ collections: [{+ name: 'My First Collection',+ folders: [],+ requests: [],+ }],+ selectedRequest: {},+ editingRequest: {},});export const mutations = {- applySetting (state, setting) {- if (setting == null || !(setting instanceof Array) || setting.length !== 2)- throw new Error("You must provide a setting (array in the form [key, value])");-- const [key, value] = setting;- // Do not just remove this check.- // Add your settings key to the SETTINGS_KEYS array at the- // top of the file.- // This is to ensure that application settings remain documented.- if (!SETTINGS_KEYS.includes(key)) throw new Error("The settings structure does not include the key " + key);-- state.settings[key] = value;- },-- replaceCollections (state, collections) {- state.collections = collections;- },-- importCollections (state, collections) {- state.collections = [...state.collections, ...collections];-- let index = 0;- for (let collection of collections) {- collection.collectionIndex = index;- index += 1;- }- },-- addNewCollection (state, collection) {- state.collections.push({- name : '',- folders : [],- requests : [],- ...collection,- })- },-- removeCollection (state, payload) {- const { collectionIndex } = payload;- state.collections.splice(collectionIndex, 1)- },-- editCollection (state, payload) {- const { collection, collectionIndex } = payload- state.collections[collectionIndex] = collection- },-- addNewFolder (state, payload) {- const { collectionIndex, folder } = payload;- state.collections[collectionIndex].folders.push({- name : '',- requests : [],- ...folder,- });- },-- editFolder (state, payload) {- const { collectionIndex, folder, folderIndex } = payload;- Vue.set(state.collections[collectionIndex].folders, folderIndex, folder)- },-- removeFolder (state, payload) {- const { collectionIndex, folderIndex } = payload;- state.collections[collectionIndex].folders.splice(folderIndex, 1)- },-- addRequest (state, payload) {- const { request } = payload;-- // Request that is directly attached to collection- if (request.folder === -1) {- state.collections[request.collection].requests.push(request);- return- }-- state.collections[request.collection].folders[request.folder].requests.push(request);- },-- editRequest (state, payload) {- const {- requestOld,- requestOldCollectionIndex,- requestOldFolderIndex,- requestOldIndex,- requestNew,- requestNewCollectionIndex,- requestNewFolderIndex,- } = payload-- const changedCollection = requestOldCollectionIndex !== requestNewCollectionIndex- const changedFolder = requestOldFolderIndex !== requestNewFolderIndex- const changedPlace = changedCollection || changedFolder-- // set new request- if (requestNewFolderIndex !== undefined)- Vue.set(state.collections[requestNewCollectionIndex].folders[requestNewFolderIndex].requests, requestOldIndex, requestNew)- else- Vue.set(state.collections[requestNewCollectionIndex].requests, requestOldIndex, requestNew)-- // remove old request- if (changedPlace) {- if (requestOldFolderIndex !== undefined)- state.collections[requestOldCollectionIndex].folders[requestOldFolderIndex].requests.splice(requestOldIndex, 1)- else- state.collections[requestOldCollectionIndex].requests.splice(requestOldIndex, 1)- }- },-- saveRequestAs (state, payload) {- const {- request,- collectionIndex,- folderIndex,- requestIndex,- } = payload-- const specifiedCollection = collectionIndex !== undefined- const specifiedFolder = folderIndex !== undefined- const specifiedRequest = requestIndex !== undefined-- if (specifiedCollection && specifiedFolder && specifiedRequest)- Vue.set(state.collections[collectionIndex].folders[folderIndex].requests, requestIndex, request)- else if (specifiedCollection && specifiedFolder && !specifiedRequest) {- const requests = state.collections[collectionIndex].folders[folderIndex].requests- const lastRequestIndex = requests.length - 1;- Vue.set(requests, lastRequestIndex + 1, request)- }- else if (specifiedCollection && !specifiedFolder && specifiedRequest) {- const requests = state.collections[collectionIndex].requests- Vue.set(requests,requestIndex, request)- }- else if (specifiedCollection && !specifiedFolder && !specifiedRequest) {- const requests = state.collections[collectionIndex].requests- const lastRequestIndex = requests.length - 1;- Vue.set(requests, lastRequestIndex + 1, request)- }-- },-- saveRequest (state, payload) {- const { request } = payload;-- // Remove the old request from collection- if (request.hasOwnProperty('oldCollection') && request.oldCollection > -1) {- const folder = request.hasOwnProperty('oldFolder') && request.oldFolder >= -1 ? request.oldFolder : request.folder;- if (folder > -1) {- state.collections[request.oldCollection].folders[folder].requests.splice(request.requestIndex, 1)- } else {- state.collections[request.oldCollection].requests.splice(request.requestIndex, 1)- }- } else if (request.hasOwnProperty('oldFolder') && request.oldFolder !== -1) {- state.collections[request.collection].folders[folder].requests.splice(request.requestIndex, 1)- }-- delete request.oldCollection;- delete request.oldFolder;-- // Request that is directly attached to collection- if (request.folder === -1) {- Vue.set(state.collections[request.collection].requests, request.requestIndex, request)- return- }-- Vue.set(state.collections[request.collection].folders[request.folder].requests, request.requestIndex, request)- },-- removeRequest (state, payload) {- const { collectionIndex, folderIndex, requestIndex } = payload;-- // Request that is directly attached to collection- if (folderIndex === -1) {- state.collections[collectionIndex].requests.splice(requestIndex, 1)- return- }-- state.collections[collectionIndex].folders[folderIndex].requests.splice(requestIndex, 1)- },-- selectRequest (state, payload) {- state.selectedRequest = Object.assign({}, payload.request);- },+ applySetting(state, setting) {+ if (setting == null || !(setting instanceof Array) || setting.length !== 2)+ throw new Error("You must provide a setting (array in the form [key, value])");++ const [key, value] = setting;+ // Do not just remove this check.+ // Add your settings key to the SETTINGS_KEYS array at the+ // top of the file.+ // This is to ensure that application settings remain documented.+ if (!SETTINGS_KEYS.includes(key)) throw new Error("The settings structure does not include the key " + key);++ state.settings[key] = value;+ },++ replaceCollections(state, collections) {+ state.collections = collections;+ },++ importCollections(state, collections) {+ state.collections = [...state.collections, ...collections];++ let index = 0;+ for (let collection of collections) {+ collection.collectionIndex = index;+ index += 1;+ }+ },++ addNewCollection(state, collection) {+ state.collections.push({+ name: '',+ folders: [],+ requests: [],+ ...collection,+ })+ },++ removeCollection(state, payload) {+ const {+ collectionIndex+ } = payload;+ state.collections.splice(collectionIndex, 1)+ },++ editCollection(state, payload) {+ const {+ collection,+ collectionIndex+ } = payload+ state.collections[collectionIndex] = collection+ },++ addNewFolder(state, payload) {+ const {+ collectionIndex,+ folder+ } = payload;+ state.collections[collectionIndex].folders.push({+ name: '',+ requests: [],+ ...folder,+ });+ },++ editFolder(state, payload) {+ const {+ collectionIndex,+ folder,+ folderIndex+ } = payload;+ Vue.set(state.collections[collectionIndex].folders, folderIndex, folder)+ },++ removeFolder(state, payload) {+ const {+ collectionIndex,+ folderIndex+ } = payload;+ state.collections[collectionIndex].folders.splice(folderIndex, 1)+ },++ addRequest(state, payload) {+ const {+ request+ } = payload;++ // Request that is directly attached to collection+ if (request.folder === -1) {+ state.collections[request.collection].requests.push(request);+ return+ }++ state.collections[request.collection].folders[request.folder].requests.push(request);+ },++ editRequest(state, payload) {+ const {+ requestOld,+ requestOldCollectionIndex,+ requestOldFolderIndex,+ requestOldIndex,+ requestNew,+ requestNewCollectionIndex,+ requestNewFolderIndex,+ } = payload++ const changedCollection = requestOldCollectionIndex !== requestNewCollectionIndex+ const changedFolder = requestOldFolderIndex !== requestNewFolderIndex+ const changedPlace = changedCollection || changedFolder++ // set new request+ if (requestNewFolderIndex !== undefined)+ Vue.set(state.collections[requestNewCollectionIndex].folders[requestNewFolderIndex].requests, requestOldIndex, requestNew)+ else+ Vue.set(state.collections[requestNewCollectionIndex].requests, requestOldIndex, requestNew)++ // remove old request+ if (changedPlace) {+ if (requestOldFolderIndex !== undefined)+ state.collections[requestOldCollectionIndex].folders[requestOldFolderIndex].requests.splice(requestOldIndex, 1)+ else+ state.collections[requestOldCollectionIndex].requests.splice(requestOldIndex, 1)+ }+ },++ saveRequestAs(state, payload) {+ const {+ request,+ collectionIndex,+ folderIndex,+ requestIndex,+ } = payload++ const specifiedCollection = collectionIndex !== undefined+ const specifiedFolder = folderIndex !== undefined+ const specifiedRequest = requestIndex !== undefined++ if (specifiedCollection && specifiedFolder && specifiedRequest)+ Vue.set(state.collections[collectionIndex].folders[folderIndex].requests, requestIndex, request)+ else if (specifiedCollection && specifiedFolder && !specifiedRequest) {+ const requests = state.collections[collectionIndex].folders[folderIndex].requests+ const lastRequestIndex = requests.length - 1;+ Vue.set(requests, lastRequestIndex + 1, request)+ } else if (specifiedCollection && !specifiedFolder && specifiedRequest) {+ const requests = state.collections[collectionIndex].requests+ Vue.set(requests, requestIndex, request)+ } else if (specifiedCollection && !specifiedFolder && !specifiedRequest) {+ const requests = state.collections[collectionIndex].requests+ const lastRequestIndex = requests.length - 1;+ Vue.set(requests, lastRequestIndex + 1, request)+ }++ },++ saveRequest(state, payload) {+ const {+ request+ } = payload;++ // Remove the old request from collection+ if (request.hasOwnProperty('oldCollection') && request.oldCollection > -1) {+ const folder = request.hasOwnProperty('oldFolder') && request.oldFolder >= -1 ? request.oldFolder : request.folder;+ if (folder > -1) {+ state.collections[request.oldCollection].folders[folder].requests.splice(request.requestIndex, 1)+ } else {+ state.collections[request.oldCollection].requests.splice(request.requestIndex, 1)+ }+ } else if (request.hasOwnProperty('oldFolder') && request.oldFolder !== -1) {+ state.collections[request.collection].folders[folder].requests.splice(request.requestIndex, 1)+ }++ delete request.oldCollection;+ delete request.oldFolder;++ // Request that is directly attached to collection+ if (request.folder === -1) {+ Vue.set(state.collections[request.collection].requests, request.requestIndex, request)+ return+ }++ Vue.set(state.collections[request.collection].folders[request.folder].requests, request.requestIndex, request)+ },++ removeRequest(state, payload) {+ const {+ collectionIndex,+ folderIndex,+ requestIndex+ } = payload;++ // Request that is directly attached to collection+ if (folderIndex === -1) {+ state.collections[collectionIndex].requests.splice(requestIndex, 1)+ return+ }++ state.collections[collectionIndex].folders[folderIndex].requests.splice(requestIndex, 1)+ },++ selectRequest(state, payload) {+ state.selectedRequest = Object.assign({}, payload.request);+ },};