move common logic to a helper functions for WebUI

This commit is contained in:
arabcoders
2025-04-11 21:21:49 +03:00
parent 3ed2c9b9d7
commit 859b56ab86
8 changed files with 164 additions and 82 deletions

View File

@@ -152,7 +152,14 @@
</template> </template>
<script setup> <script setup>
import {copyText, notification, parse_api_response, TOOLTIP_DATE_FORMAT} from '~/utils/index' import {
copyText,
disableOpacity,
enableOpacity,
notification,
parse_api_response,
TOOLTIP_DATE_FORMAT
} from '~/utils/index'
import request from '~/utils/request' import request from '~/utils/request'
import moment from 'moment' import moment from 'moment'
import {getStatusClass, makeName} from '~/utils/events/helpers' import {getStatusClass, makeName} from '~/utils/events/helpers'
@@ -188,9 +195,7 @@ const filteredRows = computed(() => {
}); });
onMounted(async () => { onMounted(async () => {
if (bg_enable.value) { disableOpacity()
document.querySelector('body').setAttribute("style", "opacity: 1");
}
if (!props.id) { if (!props.id) {
throw createError({ throw createError({
statusCode: 404, statusCode: 404,
@@ -200,11 +205,7 @@ onMounted(async () => {
return await loadContent() return await loadContent()
}) })
onUnmounted(async () => { onUnmounted(async () => enableOpacity())
if (bg_enable.value && bg_opacity.value) {
document.querySelector('body').setAttribute("style", `opacity: ${bg_opacity.value}`)
}
})
const loadContent = async () => { const loadContent = async () => {
try { try {

View File

@@ -6,6 +6,7 @@
import {useStorage} from '@vueuse/core' import {useStorage} from '@vueuse/core'
import {marked} from 'marked' import {marked} from 'marked'
import {baseUrl} from 'marked-base-url' import {baseUrl} from 'marked-base-url'
import {disableOpacity, enableOpacity} from "~/utils/index.js";
const props = defineProps({ const props = defineProps({
file: { file: {
@@ -18,6 +19,8 @@ const content = ref('')
const api_url = useStorage('api_url', '') const api_url = useStorage('api_url', '')
onMounted(async () => { onMounted(async () => {
disableOpacity()
const response = await fetch(`${api_url.value}${props.file}?_=${Date.now()}`) const response = await fetch(`${api_url.value}${props.file}?_=${Date.now()}`)
const text = await response.text() const text = await response.text()
@@ -50,4 +53,6 @@ onMounted(async () => {
content.value = marked.parse(text) content.value = marked.parse(text)
}); });
onUnmounted(() => enableOpacity())
</script> </script>

View File

@@ -189,7 +189,7 @@
- -
<NuxtLink @click="loadFile = '/NEWS.md'" v-text="'News'"/> <NuxtLink @click="loadFile = '/NEWS.md'" v-text="'News'"/>
- -
<NuxtLink :to="changelog_url" v-text="'ChangeLog'"/> <NuxtLink :to="changelog_url" v-text="'CHANGELOG'"/>
</div> </div>
<div class="column is-6 is-4-mobile has-text-right"> <div class="column is-6 is-4-mobile has-text-right">
{{ api_version }} - <a href="https://github.com/arabcoders/watchstate" target="_blank">WatchState</a> {{ api_version }} - <a href="https://github.com/arabcoders/watchstate" target="_blank">WatchState</a>

View File

@@ -232,7 +232,7 @@ const usefulCommands = {
}, },
metadata_only: { metadata_only: {
id: 5, id: 5,
title: "Import this backend metadata.", title: "Run metadata import from this backend.",
command: "state:import -v --metadata-only -u {user} -s {name}", command: "state:import -v --metadata-only -u {user} -s {name}",
}, },
import_debug: { import_debug: {
@@ -245,6 +245,11 @@ const usefulCommands = {
title: "Run export and save debug log.", title: "Run export and save debug log.",
command: "state:export -v --debug -u {user} -s {name} --logfile '/config/{user}@{name}.export.txt'", command: "state:export -v --debug -u {user} -s {name} --logfile '/config/{user}@{name}.export.txt'",
}, },
force_import: {
id: 8,
title: "Force import local play state from this backend.",
command: "state:import -f -v -u {user} -s {name}",
},
} }
const forwardCommand = async backend => { const forwardCommand = async backend => {

View File

@@ -4,80 +4,147 @@
<div class="column is-12 is-clearfix is-unselectable"> <div class="column is-12 is-clearfix is-unselectable">
<span id="env_page_title" class="title is-4"> <span id="env_page_title" class="title is-4">
<span class="icon"><i class="fas fa-cogs"></i></span> <span class="icon"><i class="fas fa-cogs"></i></span>
Change logs CHANGELOG
</span> </span>
<div class="is-pulled-right" v-if="!isLoading">
<div class="field is-grouped">
<div class="control has-icons-left" v-if="toggleFilter">
<input type="search" v-model.lazy="query" class="input" id="filter" placeholder="Filter">
<span class="icon is-left"><i class="fas fa-filter"/></span>
</div>
<div class="control">
<button class="button is-danger is-light" v-tooltip.bottom="'Filter log lines.'"
@click="toggleFilter = !toggleFilter">
<span class="icon"><i class="fas fa-filter"/></span>
</button>
</div>
</div>
</div>
<div class="is-hidden-mobile"> <div class="is-hidden-mobile">
<span class="subtitle">This page displays the application change logs.</span> <span class="subtitle">This page displays all the application change logs.</span>
</div> </div>
</div> </div>
</div> </div>
<div class="column is-12" v-for="(log, index) in logs" :key="log.tag">
<div class="content"> <div class="columns is-multiline" v-if="isLoading">
<h1 class="is-4"> <div class="column is-12">
<span class="icon-text"> <Message message_class="has-background-info-90 has-text-dark" title="Loading"
<span class="icon"><i class="fas fa-code-branch"></i></span> icon="fas fa-spinner fa-spin" message="Loading data. Please wait..."/>
<span>
{{ log.tag }} <span class="tag has-text-success" v-if="isInstalled(log.tag)">Installed</span>
</span>
</span>
</h1>
<hr>
<ul>
<li v-for="commit in log.commits" :key="commit.sha">
<strong>{{ ucFirst(commit.message).replace(/\.$/, "") }}.</strong> -
<small>
<NuxtLink :to="`https://github.com/arabcoders/watchstate/commit/${commit.sha}`" target="_blank">
<span class="has-tooltip" v-tooltip="`SHA: ${commit.sha} - Date: ${commit.date}`">
{{ moment(commit.date).fromNow() }}
</span>
</NuxtLink>
</small>
</li>
</ul>
<hr v-if="index < logs.length - 1">
</div> </div>
</div> </div>
<template v-if="!isLoading">
<div class="logs-container">
<div class="columns is-multiline">
<div class="column is-12" v-for="(log, index) in logs" :key="log.tag">
<div class="content">
<h1 class="is-4">
<span class="icon"><i class="fas fa-code-branch"/></span>
{{ formatTag(log.tag) }} <span class="tag has-text-success" v-if="isInstalled(log.tag)">Installed</span>
</h1>
<hr>
<ul>
<li v-for="commit in log.commits" :key="commit.sha">
<strong>{{ ucFirst(commit.message).replace(/\.$/, "") }}.</strong> -
<small>
<NuxtLink :to="`https://github.com/arabcoders/watchstate/commit/${commit.sha}`" target="_blank">
<span class="has-tooltip" v-tooltip="`SHA: ${commit.sha} - Date: ${commit.date}`">
{{ moment(commit.date).fromNow() }}
</span>
</NuxtLink>
</small>
</li>
</ul>
<hr v-if="index < logs.length - 1">
</div>
</div>
</div>
</div>
</template>
</div> </div>
</template> </template>
<script setup> <script setup>
import {notification} from '~/utils/index' import {disableOpacity, enableOpacity, notification} from '~/utils/index'
import moment from 'moment' import moment from 'moment'
import {NuxtLink} from '#components'; import {NuxtLink} from '#components';
import Message from "~/components/Message.vue";
useHead({title: 'Change log'}) useHead({title: 'CHANGELOG'})
const REPO_URL = "https://arabcoders.github.io/watchstate/CHANGELOG-{branch}.json?version={version}"; const REPO_URL = "https://arabcoders.github.io/watchstate/CHANGELOG-{branch}.json?version={version}";
const logs = ref([]); const logs = ref([]);
const api_version = ref('master'); const api_version = ref('master');
const isLoading = ref(false);
const branch = computed(() => { const branch = computed(() => {
const branch = String(api_version.value).split('-')[0] ?? 'master'; const branch = String(api_version.value).split('-')[0] ?? 'master';
return ['master', 'dev'].includes(branch) ? branch : 'master'; return ['master', 'dev'].includes(branch) ? branch : 'master';
}); });
const loadContent = async () => { const toggleFilter = ref(false)
try { const query = ref()
const response = await request('/system/version');
const json = await response.json();
api_version.value = json.version;
} catch (e) {
console.error(e);
notification('error', 'Error', `Failed to fetch version. ${e.message}`);
}
const loadContent = async () => {
isLoading.value = true;
try { try {
const changes = await fetch(r(REPO_URL, {branch: branch.value, version: api_version.value})); try {
logs.value = await changes.json(); const response = await request('/system/version');
} catch (e) { const json = await response.json();
console.error(e); api_version.value = json.version;
notification('error', 'Error', `Failed to fetch changelog. ${e.message}`); } catch (e) {
console.error(e);
notification('error', 'Error', `Failed to fetch version. ${e.message}`);
}
try {
const changes = await fetch(r(REPO_URL, {branch: branch.value, version: api_version.value}));
logs.value = await changes.json();
} catch (e) {
console.error(e);
notification('error', 'Error', `Failed to fetch changelog. ${e.message}`);
}
} finally {
isLoading.value = false;
} }
} }
const formatTag = tag => {
const parts = tag.split('-');
if (parts.length < 3) {
return tag;
}
const branch = parts[0];
const date = parts[1];
const shortSha = parts[2].substring(0, 7);
return `${ucFirst(branch)}: ${moment(date, 'YYYYMMDD').format('YYYY-MM-DD')} - ${shortSha}`;
}
const isInstalled = tag => { const isInstalled = tag => {
const installed = String(api_version.value).split('-').pop(); const installed = String(api_version.value).split('-').pop();
return tag.endsWith(installed); return tag.endsWith(installed);
} }
onMounted(() => loadContent()); onMounted(async () => {
disableOpacity()
await loadContent()
});
onUnmounted(() => enableOpacity())
</script> </script>
<style scoped>
.logs-container {
padding: 1rem;
min-width: 100%;
max-height: 73vh;
overflow-y: auto;
overflow-x: auto;
}
hr {
border-bottom: 1px solid #b2d1ff;
}
</style>

View File

@@ -107,7 +107,8 @@
</div> </div>
</div> </div>
</template> </template>
<style>
<style scoped>
.xterm { .xterm {
padding: 0.50rem !important; padding: 0.50rem !important;
@@ -116,7 +117,6 @@
.xterm-viewport { .xterm-viewport {
background-color: #1f2229 !important; background-color: #1f2229 !important;
} }
</style> </style>
<script setup> <script setup>
@@ -124,7 +124,7 @@ import "@xterm/xterm/css/xterm.css"
import {Terminal} from "@xterm/xterm" import {Terminal} from "@xterm/xterm"
import {FitAddon} from "@xterm/addon-fit" import {FitAddon} from "@xterm/addon-fit"
import {useStorage} from '@vueuse/core' import {useStorage} from '@vueuse/core'
import {notification} from '~/utils/index' import {disableOpacity, enableOpacity, notification} from '~/utils/index'
import Message from '~/components/Message' import Message from '~/components/Message'
import request from "~/utils/request.js"; import request from "~/utils/request.js";
@@ -144,9 +144,6 @@ const commandInput = ref()
const executedCommands = useStorage('executedCommands', []) const executedCommands = useStorage('executedCommands', [])
const exitCode = ref(0) const exitCode = ref(0)
const bg_enable = useStorage('bg_enable', true)
const bg_opacity = useStorage('bg_opacity', 0.95)
const hasPrefix = computed(() => command.value.startsWith('console') || command.value.startsWith('docker')) const hasPrefix = computed(() => command.value.startsWith('console') || command.value.startsWith('docker'))
const hasPlaceholder = computed(() => command.value && command.value.match(/\[.*]/)) const hasPlaceholder = computed(() => command.value && command.value.match(/\[.*]/))
const show_page_tips = useStorage('show_page_tips', true) const show_page_tips = useStorage('show_page_tips', true)
@@ -167,7 +164,7 @@ const RunCommand = async () => {
} }
// use regex to check if command contains [...] // use regex to check if command contains [...]
if (userCommand.match(/\[.*\]/)) { if (userCommand.match(/\[.*]/)) {
if (!confirm(`The command contains placeholders '[...]'. Are you sure you want to run as it is?`)) { if (!confirm(`The command contains placeholders '[...]'. Are you sure you want to run as it is?`)) {
return return
} }
@@ -290,16 +287,11 @@ onUnmounted(() => {
if (sse) { if (sse) {
sse.close() sse.close()
} }
enableOpacity()
if (bg_enable.value && bg_opacity.value) {
document.querySelector('body').setAttribute("style", `opacity: ${bg_opacity.value}`)
}
}) })
onMounted(async () => { onMounted(async () => {
if (bg_enable.value) { disableOpacity()
document.querySelector('body').setAttribute("style", "opacity: 1");
}
window.addEventListener("resize", reSizeTerminal); window.addEventListener("resize", reSizeTerminal);
commandInput.value.focus() commandInput.value.focus()

View File

@@ -3,7 +3,7 @@
<div class="columns is-multiline"> <div class="columns is-multiline">
<div class="column is-12 is-clearfix is-unselectable"> <div class="column is-12 is-clearfix is-unselectable">
<span class="title is-4"> <span class="title is-4">
<span class="icon"><i class="fas fa-globe" :class="{'fa-spin': isLoading || isTodayLog}"/>&nbsp;</span> <span class="icon"><i class="fas fa-globe" :class="{'fa-spin': isLoading }"/>&nbsp;</span>
<NuxtLink to="/logs">Logs</NuxtLink> <NuxtLink to="/logs">Logs</NuxtLink>
: {{ filename }} : {{ filename }}
</span> </span>
@@ -57,7 +57,10 @@
</div> </div>
</div> </div>
<div class="is-hidden-mobile"> <div class="is-hidden-mobile">
<span class="subtitle">Scroll-up to load older logs.</span> <span class="subtitle">
<template v-if="isTodayLog">The logs are being streamed in real-time.</template>
Scroll-up to load older logs.
</span>
</div> </div>
</div> </div>
@@ -141,7 +144,7 @@ div.logbox pre {
import Message from '~/components/Message' import Message from '~/components/Message'
import moment from 'moment' import moment from 'moment'
import {useStorage} from '@vueuse/core' import {useStorage} from '@vueuse/core'
import {goto_history_item, notification, parse_api_response} from '~/utils/index' import {disableOpacity, enableOpacity, goto_history_item, notification, parse_api_response} from '~/utils/index'
import request from '~/utils/request' import request from '~/utils/request'
const router = useRouter() const router = useRouter()
@@ -278,22 +281,14 @@ const scrollToBottom = () => {
onMounted(async () => { onMounted(async () => {
await loadContent() await loadContent()
await nextTick(() => { await nextTick(() => disableOpacity())
if (bg_enable.value) {
document.querySelector('body').setAttribute("style", `opacity: 1.0`)
}
})
}); });
onBeforeUnmount(() => closeStream()); onBeforeUnmount(() => closeStream());
onUnmounted(async () => { onUnmounted(async () => {
closeStream() closeStream()
await nextTick(() => { await nextTick(() => enableOpacity())
if (bg_enable.value) {
document.querySelector('body').setAttribute("style", `opacity: ${bg_opacity.value}`)
}
})
}); });
const watchLog = () => { const watchLog = () => {

View File

@@ -531,6 +531,21 @@ const queue_event = async (event, event_data = {}, delay = 0, opts = {}) => {
return resp.status return resp.status
} }
const enableOpacity = () => {
const bg_enable = useStorage('bg_enable', true)
const bg_opacity = useStorage('bg_opacity', 0.95)
if (bg_enable.value && bg_opacity.value) {
document.querySelector('body').setAttribute("style", `opacity: ${bg_opacity.value}`)
}
}
const disableOpacity = () => {
const bg_enable = useStorage('bg_enable', true)
if (bg_enable.value) {
document.querySelector('body').setAttribute("style", "opacity: 1");
}
}
export { export {
r, r,
ag_set, ag_set,
@@ -554,5 +569,7 @@ export {
basename, basename,
parse_api_response, parse_api_response,
goto_history_item, goto_history_item,
queue_event queue_event,
enableOpacity,
disableOpacity,
} }