Merge remote-tracking branch 'upstream/master' into history-fieldset-virtualscroll

# Conflicts:
#	pages/index.vue
This commit is contained in:
izerozlu
2019-08-28 12:48:31 +03:00
7 changed files with 668 additions and 475 deletions

View File

@@ -1,6 +1,5 @@
<template>
<div class="page">
<pw-section class="blue" label="Request" ref="request">
<ul>
<li>
@@ -22,12 +21,11 @@
<input id="path" v-model="path" v-on:keyup.enter="sendRequest">
</li>
<li>
<label for="action">&nbsp;</label>
<label for="action" class="hide-on-small-screen">&nbsp;</label>
<button id="action" name="action" @click="sendRequest" :disabled="!isValidURL">Send</button>
</li>
</ul>
</pw-section>
<pw-section class="blue-dark" label="Request Body" v-if="method === 'POST' || method === 'PUT'">
<ul>
<li>
@@ -53,7 +51,7 @@
<input :name="'bvalue'+index" v-model="param.value">
</li>
<li>
<label for="request">&nbsp;</label>
<label for="request" class="hide-on-small-screen">&nbsp;</label>
<button name="request" @click="removeRequestBodyParam(index)">Remove</button>
</li>
</ol>
@@ -69,11 +67,11 @@
<textarea name="request" rows="1" readonly>{{rawRequestBody || '(add at least one parameter)'}}</textarea>
</li>
</ul>
</div><div v-else>
</div>
<div v-else>
<textarea v-model="rawParams" style="font-family: monospace;" rows="16" @keydown="formatRawParams"></textarea>
</div>
</pw-section>
<pw-section class="green" label="Authentication" collapsed>
<ul>
<li>
@@ -102,7 +100,34 @@
</li>
</ul>
</pw-section>
<pw-section class="orange" label="Headers" collapsed>
<ol v-for="(header, index) in headers">
<li>
<label :for="'header'+index">Key {{index + 1}}</label>
<input :name="'header'+index" v-model="header.key">
</li>
<li>
<label :for="'value'+index">Value {{index + 1}}</label>
<input :name="'value'+index" v-model="header.value">
</li>
<li>
<label for="header" class="hide-on-small-screen">&nbsp;</label>
<button name="header" @click="removeRequestHeader(index)">Remove</button>
</li>
</ol>
<ul>
<li>
<label for="add">Action</label>
<button name="add" @click="addRequestHeader">Add</button>
</li>
</ul>
<ul>
<li>
<label for="request">Header List</label>
<textarea name="request" rows="1" readonly>{{headerString || '(add at least one header)'}}</textarea>
</li>
</ul>
</pw-section>
<pw-section class="cyan" label="Parameters" collapsed>
<ol v-for="(param, index) in params">
<li>
@@ -114,7 +139,7 @@
<input :name="'value'+index" v-model="param.value">
</li>
<li>
<label for="param">&nbsp;</label>
<label for="param" class="hide-on-small-screen">&nbsp;</label>
<button name="param" @click="removeRequestParam(index)">Remove</button>
</li>
</ol>
@@ -131,7 +156,6 @@
</li>
</ul>
</pw-section>
<pw-section class="purple" label="Response" id="response" ref="response">
<ul>
<li>
@@ -147,15 +171,20 @@
</ul>
<ul>
<li>
<div class="flex-wrap">
<label for="body">response</label>
<button v-if="response.body" name="action" class="btn-copy" @click="copyResponse">Copy Response</button>
</div>
<textarea name="body" rows="10" id="response-details" readonly>{{response.body || '(waiting to send request)'}}</textarea>
<div class="flex-wrap">
<label for="body">response</label>
<button v-if="response.body" name="action" @click="copyResponse">Copy Response</button>
</div>
<div id="response-details-wrapper">
<textarea name="body" rows="16" id="response-details" readonly>{{response.body || '(waiting to send request)'}}</textarea>
<iframe src="about:blank" class="covers-response" ref="previewFrame" :class="{hidden: !previewEnabled}"></iframe>
</div>
<div v-if="response.body && responseType === 'text/html'" class="align-right">
<button @click.prevent="togglePreview">{{ previewEnabled ? 'Hide Preview' : 'Preview HTML' }}</button>
</div>
</li>
</ul>
</pw-section>
<pw-section class="gray" label="History">
<ul>
<li>
@@ -183,33 +212,54 @@
<input name="path" type="text" readonly :value="entry.path">
</li>
<li>
<label for="delete">&nbsp;</label>
<label for="delete"class="hide-on-small-screen">&nbsp;</label>
<button name="delete" @click="deleteHistory(entry)">Delete</button>
</li>
<li>
<label for="use">&nbsp;</label>
<label for="use"class="hide-on-small-screen">&nbsp;</label>
<button name="use" @click="useHistory(entry)">Use</button>
</li>
</ul>
</virtual-list>
</pw-section>
</div>
</template>
<script>
import VirtualList from 'vue-virtual-scroll-list'
import section from "../components/section";
const statusCategories = [
{name: 'informational', statusCodeRegex: new RegExp(/[1][0-9]+/), className: 'info-response'},
{name: 'successful', statusCodeRegex: new RegExp(/[2][0-9]+/), className: 'success-response'},
{name: 'redirection', statusCodeRegex: new RegExp(/[3][0-9]+/), className: 'redir-response'},
{name: 'client error', statusCodeRegex: new RegExp(/[4][0-9]+/), className: 'cl-error-response'},
{name: 'server error', statusCodeRegex: new RegExp(/[5][0-9]+/), className: 'sv-error-response'},
const statusCategories = [{
name: 'informational',
statusCodeRegex: new RegExp(/[1][0-9]+/),
className: 'info-response'
},
{
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 = {};
@@ -220,8 +270,8 @@
headerMap[header] = value
});
return headerMap
};
};
const findStatusGroup = responseStatus => statusCategories.find(status => status.statusCodeRegex.test(responseStatus));
export default {
@@ -237,74 +287,87 @@
path: '/api/users',
httpUser: '',
httpPassword: '',
bearerToken: '',
params: [],
bodyParams: [],
rawParams: '',
rawInput: false,
contentType: 'application/json',
response: {
status: '',
headers: '',
body: ''
},
history: window.localStorage.getItem('history') ? JSON.parse(window.localStorage.getItem('history')) : []
}
bearerToken: '',headers: [],
params: [],
bodyParams: [],
rawParams: '',
rawInput: false,
contentType: 'application/json',
response: {
status: '',
headers: '',
body: ''
},
history: window.localStorage.getItem('history') ? JSON.parse(window.localStorage.getItem('history')) : [],
previewEnabled: false
}
},
computed: {
statusCategory() {
return findStatusGroup(this.response.status);
},
computed: {
statusCategory(){
return findStatusGroup(this.response.status);
},
noHistoryToClear() {
return this.history.length === 0;
},
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);
},
rawRequestBody() {
const {
bodyParams
} = this
if (this.contentType === 'application/json') {
try {
const obj = JSON.parse(`{${bodyParams.filter(({ key }) => !!key).map(({ key, value }) => `
noHistoryToClear() {
return this.history.length === 0;
},
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);
},
rawRequestBody() {
const {
bodyParams
} = this
if (this.contentType === 'application/json') {
try {
const obj = JSON.parse(`{${bodyParams.filter(({ key }) => !!key).map(({ key, value }) => `
"${key}": "${value}"
`).join()}}`)
return JSON.stringify(obj)
} catch (ex) {
return 'invalid'
}
} else {
return bodyParams
.filter(({
key
}) => !!key)
.map(({
key,
value
}) => `${key}=${encodeURIComponent(value)}`).join('&')
}
},
queryString() {
const result = this.params
.filter(({
key
}) => !!key)
.map(({
key,
value
}) => `${key}=${encodeURIComponent(value)}`).join('&')
return result === '' ? '' : `?${result}`
return JSON.stringify(obj)
} catch (ex) {
return 'invalid'
}
} else {
return bodyParams
.filter(({
key
}) => !!key)
.map(({
key,
value
}) => `${key}=${encodeURIComponent(value)}`).join('&')
}
},
methods: {
findEntryStatus(entry){
let foundStatusGroup = findStatusGroup(entry.status);
headerString() {
const result = this.headers
.filter(({
key
}) => !!key)
.map(({
key,
value
}) => `${key}: ${value}`).join(',\n')
return result == '' ? '' : `${result}`
},
queryString() {
const result = this.params
.filter(({
key
}) => !!key)
.map(({
key,
value
}) => `${key}=${encodeURIComponent(value)}`).join('&')
return result === '' ? '' : `?${result}`
},
responseType() {
return (this.response.headers['content-type'] || '').split(';')[0].toLowerCase();
}
},
methods: {
findEntryStatus(entry) {
let foundStatusGroup = findStatusGroup(entry.status);
return foundStatusGroup || {className: ''};
},
deleteHistory(entry) {
@@ -328,107 +391,138 @@
})
},
sendRequest() {
if (this.$refs.response.$el.classList.contains('hidden')) {
if (!this.isValidURL) {
alert('Please check the formatting of the URL');
return
} if (this.$refs.response.$el.classList.contains('hidden')) {
this.$refs.response.$el.classList.toggle('hidden')
}
this.$refs.response.$el.scrollIntoView({
behavior: 'smooth'
})
this.response.status = 'Fetching...'
this.response.body = 'Loading...'
const xhr = new XMLHttpRequest()
const user = this.auth === 'Basic' ? this.httpUser : null
const pswd = this.auth === 'Basic' ? this.httpPassword : null
xhr.open(this.method, this.url + this.path + this.queryString, true, user, pswd)
if (this.auth === 'Bearer Token') {
xhr.setRequestHeader('Authorization', 'Bearer ' + this.bearerToken);
}
if (this.method === 'POST' || this.method === 'PUT') {
});
this.previewEnabled = false;
this.response.status = 'Fetching...';
this.response.body = 'Loading...';
const xhr = new XMLHttpRequest();
const user = this.auth === 'Basic' ? this.httpUser : null;
const password = this.auth === 'Basic' ? this.httpPassword : null;
xhr.open(this.method, this.url + this.path + this.queryString, true, user, password);
if (this.auth === 'Bearer Token')
xhr.setRequestHeader('Authorization', 'Bearer ' + this.bearerToken
);
if (this.headers) {
this.headers.forEach(function(element) {
xhr.setRequestHeader(element.key, element.value)
})
}
if (this.method === 'POST' || this.method === 'PUT') {
const requestBody = this.rawInput ? this.rawParams : this.rawRequestBody;
xhr.setRequestHeader('Content-Length', requestBody.length)
xhr.setRequestHeader('Content-Type', `${this.contentType}; charset=utf-8`)
xhr.send(requestBody)
xhr.setRequestHeader('Content-Length', requestBody.length);
xhr.setRequestHeader('Content-Type', `${this.contentType}; charset=utf-8`);
xhr.send(requestBody);
} else {
xhr.send()
xhr.send();
}
xhr.onload = e => {
this.response.status = xhr.status
const headers = this.response.headers = parseHeaders(xhr)
this.response.status = xhr.status;
const headers = this.response.headers = parseHeaders(xhr);
this.response.body = xhr.responseText;
if ((headers['content-type'] || '').startsWith('application/json')) {
this.response.body = JSON.stringify(JSON.parse(xhr.responseText), null, 2)
} else {
this.response.body = xhr.responseText
this.response.body = JSON.stringify(JSON.parse(
this.response.body ), null, 2);
}
if (!this.isValidURL) {
alert('Please check the formatting of the URL');
return
}
const n = new Date().toLocaleTimeString()
const n = new Date().toLocaleTimeString();
this.history = [{
status: xhr.status,
time: n,
method: this.method,
url: this.url,
path: this.path
}, ...this.history]
window.localStorage.setItem('history', JSON.stringify(this.history))
}
}, ...this.history];
window.localStorage.setItem('history', JSON.stringify(this.history));
};
xhr.onerror = e => {
this.response.status = xhr.status
this.response.body = xhr.statusText
this.response.status = xhr.status;
this.response.body = xhr.statusText;
}
},
addRequestParam() {
this.params.push({
key: '',
value: ''
})
return false
},
removeRequestParam(index) {
this.params.splice(index, 1)
},
addRequestBodyParam() {
this.bodyParams.push({
key: '',
value: ''
})
return false
},
removeRequestBodyParam(index) {
this.bodyParams.splice(index, 1)
},
formatRawParams(event) {
if ((event.which !== 13 && event.which !== 9)) {
addRequestHeader() {
this.headers.push({
key: '',
value: ''
});
return false
},
removeRequestHeader(index) {
this.headers.splice(index, 1)
},
addRequestParam() {
this.params.push({
key: '',
value: ''
})
return false
},
removeRequestParam(index) {
this.params.splice(index, 1)
},
addRequestBodyParam() {
this.bodyParams.push({
key: '',
value: ''
})
return false
},
removeRequestBodyParam(index) {
this.bodyParams.splice(index, 1)
},
formatRawParams(event) {
if ((event.which !== 13 && event.which !== 9)) {
return;
}
const textBody = event.target.value;
const textBeforeCursor = textBody.substring(0, event.target.selectionStart);
const textAfterCursor = textBody.substring(event.target.selectionEnd);
if (event.which === 13) {
event.preventDefault();
const oldSelectionStart = event.target.selectionStart;
const lastLine = textBeforeCursor.split('\n').slice(-1)[0];
const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";
event.target.value = textBeforeCursor + '\n' + rightPadding + textAfterCursor;
setTimeout(() => event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + rightPadding.length + 1, 1);
} else if (event.which === 9) {
event.preventDefault();
const oldSelectionStart = event.target.selectionStart;
event.target.value = textBeforeCursor + '\xa0\xa0' + textAfterCursor;
event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + 2;
return false;
}
},
copyResponse() {
var copyText = document.getElementById("response-details");
copyText.select();
document.execCommand("copy");
},
togglePreview() {
this.previewEnabled = !this.previewEnabled;
if (this.previewEnabled) {
// If you want to add 'preview' support for other response types,
// just add them here.
if (this.responseType === "text/html") {
// If the preview already has that URL loaded, let's not bother re-loading it all.
if (this.$refs.previewFrame.getAttribute('data-previewing-url') === this.url)
return;
}
const textBody = event.target.value;
const textBeforeCursor = textBody.substring(0, event.target.selectionStart);
const textAfterCursor = textBody.substring(event.target.selectionEnd);
if (event.which === 13) {
event.preventDefault();
const oldSelectionStart = event.target.selectionStart;
const lastLine = textBeforeCursor.split('\n').slice(-1)[0];
const rightPadding = lastLine.match(/([\s\t]*).*/)[1] || "";
event.target.value = textBeforeCursor + '\n' + rightPadding + textAfterCursor;
setTimeout(() => event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + rightPadding.length + 1, 1);
}
else if (event.which === 9) {
event.preventDefault();
const oldSelectionStart = event.target.selectionStart;
event.target.value = textBeforeCursor + '\xa0\xa0' + textAfterCursor;
event.target.selectionStart = event.target.selectionEnd = oldSelectionStart + 2;
return false;
}
},
copyResponse() {
var copyText = document.getElementById("response-details");
copyText.select();
document.execCommand("copy");
// 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);
}
}
}
}
}
</script>

View File

@@ -1,126 +1,133 @@
<template>
<div class="page">
<pw-section class="blue" label="Theme">
<ul>
<li>
<h3>Background</h3>
<div class="backgrounds">
<span v-for="theme in themes" :key="theme.class" @click="applyTheme(theme.class)">
<swatch :color="theme.color" :name="theme.name" :class="{ vibrant: theme.vibrant }" :active="settings.THEME_CLASS === theme.class"></swatch>
</span>
</div>
</li>
</ul>
<br><br>
<ul>
<li>
<h3>Color</h3>
<div class="colors">
<span v-for="entry in colors" :key="entry.color"
@click.prevent="setActiveColor(entry.color, entry.vibrant)">
<swatch
:color="entry.color"
:name="entry.name"
:class="{ vibrant: entry.vibrant }"
:active="settings.THEME_COLOR === entry.color.toUpperCase()" />
</span>
</div>
<p>
<input id="disableFrameColors" type="checkbox"
:checked="!settings.DISABLE_FRAME_COLORS"
@change="toggleSetting('DISABLE_FRAME_COLORS')">
<label for="disableFrameColors">Enable multi-colored frames</label>
</p>
</li>
</ul>
</pw-section>
</div>
<div class="page">
<pw-section class="blue" label="Theme">
<ul>
<li>
<h3 class="title">Background</h3>
<div class="backgrounds">
<span v-for="theme in themes" :key="theme.class" @click="applyTheme(theme.class)">
<swatch :color="theme.color" :name="theme.name" :class="{ vibrant: theme.vibrant }" :active="settings.THEME_CLASS === theme.class"></swatch>
</span>
</div>
</li>
</ul>
<ul>
<li>
<h3 class="title">Color</h3>
<div class="colors">
<span v-for="entry in colors" :key="entry.color" @click.prevent="setActiveColor(entry.color, entry.vibrant)">
<swatch :color="entry.color" :name="entry.name" :class="{ vibrant: entry.vibrant }" :active="settings.THEME_COLOR === entry.color.toUpperCase()" />
</span>
</div>
</li>
</ul>
<ul>
<li>
<h3 class="title">Frames</h3>
<input id="disableFrameColors" type="checkbox" :checked="!settings.DISABLE_FRAME_COLORS" @change="toggleSetting('DISABLE_FRAME_COLORS')">
<label for="disableFrameColors">Enable multi-color</label>
</li>
</ul>
</pw-section>
</div>
</template>
<script>
import section from "../components/section";
import swatch from "../components/settings/swatch";
export default {
data () {
return {
// NOTE:: You need to first set the CSS for your theme in /assets/css/themes.scss
// You should copy the existing light theme as a template and then just
// set the relevant values.
themes: [
{ "color": "#121212", "name": "Dark (Default)", "class": "" },
{ "color": "#DFDFDF", "name": "Light", "vibrant": true, "class": "light" }
],
// 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": "#51ff0d", "name":"Lime (Default)", "vibrant": true },
{ "color": "#FFC107", "name":"Yellow", "vibrant": true },
{ "color": "#E91E63", "name":"Pink", "vibrant": false },
{ "color": "#e74c3c", "name":"Red", "vibrant": false },
{ "color": "#9b59b6", "name":"Purple", "vibrant": false },
{ "color": "#2980b9", "name":"Blue", "vibrant": false },
],
settings: {
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
}
}
},
components: {
'pw-section': section,
'swatch': swatch
},
methods: {
applyTheme (name) {
this.applySetting('THEME_CLASS', name);
document.documentElement.className = name;
},
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 ? '#121212' : '#fff');
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()}`;
},
applySetting (key, value) {
this.settings[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]]);
}
},
beforeMount () {
this.settings.THEME_COLOR = this.getActiveColor();
import section from "../components/section";
import swatch from "../components/settings/swatch";
export default {
data() {
return {
// NOTE:: You need to first set the CSS for your theme in /assets/css/themes.scss
// You should copy the existing light theme as a template and then just
// set the relevant values.
themes: [{
"color": "#121212",
"name": "Dark (Default)",
"class": ""
},
{
"color": "#DFDFDF",
"name": "Light",
"vibrant": true,
"class": "light"
}
],
// 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": "#51ff0d",
"name": "Lime (Default)",
"vibrant": true
},
{
"color": "#FFC107",
"name": "Yellow",
"vibrant": true
},
{
"color": "#E91E63",
"name": "Pink",
"vibrant": false
},
{
"color": "#e74c3c",
"name": "Red",
"vibrant": false
},
{
"color": "#9b59b6",
"name": "Purple",
"vibrant": false
},
{
"color": "#2980b9",
"name": "Blue",
"vibrant": false
},
],
settings: {
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
}
}
},
components: {
'pw-section': section,
'swatch': swatch
},
methods: {
applyTheme(name) {
this.applySetting('THEME_CLASS', name);
document.documentElement.className = name;
},
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 ? '#121212' : '#fff');
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()}`;
},
applySetting(key, value) {
this.settings[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]]);
}
},
beforeMount() {
this.settings.THEME_COLOR = this.getActiveColor();
}
</script>
}
</script>

View File

@@ -1,6 +1,5 @@
<template>
<div class="page">
<pw-section class="blue" label="Request" ref="request">
<ul>
<li>
@@ -8,41 +7,36 @@
<input id="url" type="url" :class="{ error: !urlValid }" v-model="url" @keyup.enter="toggleConnection">
</li>
<li>
<label>&nbsp;</label>
<label for="action" class="hide-on-small-screen">&nbsp;</label>
<button :class="{ disabled: !urlValid }" name="action" @click="toggleConnection">{{ toggleConnectionVerb }}</button>
</li>
</ul>
</pw-section>
<pw-section class="purple" 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 in communication.log" :style="{ color: logEntry.color }">{{ getSourcePrefix(logEntry.source) }} {{ logEntry.payload }}</span>
</span>
<span v-if="communication.log">
<span v-for="logEntry in communication.log" :style="{ color: logEntry.color }">{{ getSourcePrefix(logEntry.source) }} {{ logEntry.payload }}</span>
</span>
<span v-else>(Waiting for connection...)</span>
</div>
</li>
</ul>
<ul>
<li>
<label for="message">Message</label>
<input id="message" name="message" type="text" v-model="communication.input" :readonly="!connectionState" @keyup.enter="sendMessage">
</li>
<li>
<label>&nbsp;</label>
<label for="send" class="hide-on-small-screen">&nbsp;</label>
<button name="send" :class="{ disabled: !connectionState }" @click="sendMessage">Send</button>
</li>
</ul>
</pw-section>
</div>
</template>
<style lang="scss">
div.log {
margin: 4px;
@@ -54,7 +48,8 @@
height: 256px;
overflow: auto;
&, span {
&,
span {
font-weight: 700;
font-size: 18px;
font-family: monospace;
@@ -65,142 +60,116 @@
white-space: pre-wrap;
}
}
</style>
</style>
<script>
import section from "../components/section";
export default {
components: {
'pw-section': section
},
data () {
data() {
return {
connectionState: false,
url: "wss://echo.websocket.org",
socket: null,
communication: {
log: null,
input: ""
}
}
},
computed: {
toggleConnectionVerb () {
return !this.connectionState ? "Connect" : "Disconnect";
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');
return pattern.test(this.url);
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');
return pattern.test(this.url);
}
},
methods: {
toggleConnection () {
toggleConnection() {
// If it is connecting:
if(!this.connectionState) return this.connect();
if (!this.connectionState) return this.connect();
// Otherwise, it's disconnecting.
else return this.disconnect();
},
connect () {
this.communication.log = [
{
payload: `Connecting to ${this.url}...`,
source: 'info',
color: 'lime'
}
];
connect() {
this.communication.log = [{
payload: `Connecting to ${this.url}...`,
source: 'info',
color: 'lime'
}];
try {
this.socket = new WebSocket(this.url);
this.socket.onopen = (event) => {
this.connectionState = true;
this.communication.log = [
{
payload: `Connected to ${this.url}.`,
source: 'info',
color: 'lime'
}
];
};
this.socket.onerror = (event) => {
this.handleError();
};
this.socket.onclose = (event) => {
this.connectionState = false;
this.communication.log.push({
payload: `Disconnected from ${this.url}.`,
source: 'info',
color: 'red'
});
};
this.socket.onmessage = (event) => {
this.communication.log.push({
payload: event.data,
source: 'server'
});
}
}catch(ex){
this.handleError(ex);
this.socket = new WebSocket(this.url);
this.socket.onopen = (event) => {
this.connectionState = true;
this.communication.log = [{
payload: `Connected to ${this.url}.`,
source: 'info',
color: 'lime'
}];
};
this.socket.onerror = (event) => {
this.handleError();
};
this.socket.onclose = (event) => {
this.connectionState = false;
this.communication.log.push({
payload: `Disconnected from ${this.url}.`,
source: 'info',
color: 'red'
});
};
this.socket.onmessage = (event) => {
this.communication.log.push({
payload: event.data,
source: 'server'
});
}
} catch (ex) {
this.handleError(ex);
}
},
disconnect () {
if(this.socket != null) this.socket.close();
disconnect() {
if (this.socket != null) this.socket.close();
},
handleError (error) {
this.disconnect();
this.connectionState = false;
this.communication.log.push({
payload: `An error has occurred.`,
source: 'info',
color: 'red'
});
if(error != null) this.communication.log.push({
payload: error,
source: 'info',
color: 'red'
});
handleError(error) {
this.disconnect();
this.connectionState = false;
this.communication.log.push({
payload: `An error has occurred.`,
source: 'info',
color: 'red'
});
if (error != null) this.communication.log.push({
payload: error,
source: 'info',
color: 'red'
});
},
sendMessage () {
sendMessage() {
const message = this.communication.input;
this.socket.send(message);
this.communication.log.push({
payload: message,
source: 'client'
payload: message,
source: 'client'
});
this.communication.input = "";
},
collapse({target}) {
collapse({
target
}) {
const el = target.parentNode.className;
document.getElementsByClassName(el)[0].classList.toggle('hidden');
},
getSourcePrefix(source){
getSourcePrefix(source) {
const sourceEmojis = {
// Source used for info messages.
'info': ' [INFO]:\t',
@@ -209,11 +178,10 @@
// Source used for server to client messages.
'server': '📥 [RECEIVED]:\t'
};
if (Object.keys(sourceEmojis).includes(source)) return sourceEmojis[source];
return '';
}
}
}
</script>