feat(mqtt): optimize console and subscription sync

This commit is contained in:
jinmo authored and GitHub committed 2026-08-08 11:56:32 +08:00
1 parent e49d86b101
commit bad7f6b472
22 files changed
+1814 -229

No files matched your search

@@ -1,9 +1,10 @@
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useI18n } from "vue-i18n";
import { mqttGetBrokerInfo, mqttListTopics, mqttGetTopicTree, mqttGetMessages, mqttSubscribe, mqttUnsubscribe, mqttClearMessages } from "@/lib/backend/api";
import type { MqttBrokerInfo, MqttTopicNode, MqttMessage } from "@/types/mqtt";
import { mqttGetBrokerInfo, mqttListTopics, mqttListSavedTopicConfigs, mqttGetMessages, mqttSubscribe, mqttUnsubscribe, mqttSaveTopicConfig, mqttDeleteTopicConfig, mqttClearMessages } from "@/lib/backend/api";
import type { MqttBrokerInfo, MqttSavedTopic, MqttTopicNode, MqttMessage, MqttQoS } from "@/types/mqtt";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import TopicTreeNode from "./TopicTreeNode.vue";
import MqttPublishPanel from "./MqttPublishDialog.vue";
import { decodePayload, PAYLOAD_ENCODINGS, PAYLOAD_ENCODING_LABELS, type PayloadEncoding } from "@/lib/mqtt/mqttPayloadCodec";
@@ -15,35 +16,65 @@ interface Props {
const props = defineProps<Props>();
const { t } = useI18n();
/* ========== State ========== */
const brokerInfo = ref<MqttBrokerInfo | null>(null);
const topicTree = ref<MqttTopicNode | null>(null);
const messages = ref<MqttMessage[]>([]);
const savedTopics = ref<MqttSavedTopic[]>([]);
const subscribedTopics = ref<[string, string][]>([]);
const messages = ref<MqttMessage[]>([]);
const noLocalSubscribe = ref(false);
const selectedTopic = ref<string>(props.initialTopic ?? "");
const loading = ref(true);
const error = ref<string | null>(null);
const pollingTimer = ref<ReturnType<typeof setInterval> | null>(null);
/* Payload 显示编码格式 */
const displayEncoding = ref<PayloadEncoding>("plaintext");
const topicSearch = ref("");
const showSubscriptionDialog = ref(false);
const savingSubscription = ref(false);
const formTopic = ref("");
const formQos = ref<MqttQoS>("atmostonce");
const formNoLocal = ref(false);
const formEnabled = ref(true);
const editingTopic = ref<string | null>(null);
/* ========== Computed ========== */
const connected = computed(() => brokerInfo.value?.connected ?? false);
const mqtt5 = computed(() => brokerInfo.value?.protocolVersion?.includes("5") ?? false);
function buildTopicTree(topics: MqttSavedTopic[]): MqttTopicNode {
const root: MqttTopicNode = { name: "root", fullPath: "", children: [], isLeaf: false };
for (const config of topics) {
const segments = config.topic.split("/");
let current = root;
for (let index = 0; index < segments.length; index += 1) {
const fullPath = segments.slice(0, index + 1).join("/");
let child = current.children.find((candidate) => candidate.name === segments[index]);
if (!child) {
child = { name: segments[index], fullPath, children: [], isLeaf: false };
current.children.push(child);
}
if (index === segments.length - 1) child.isLeaf = true;
current = child;
}
}
const sort = (node: MqttTopicNode) => {
node.children.sort((left, right) => left.name.localeCompare(right.name));
node.children.forEach(sort);
};
sort(root);
return root;
}
const topicTree = computed(() => buildTopicTree(savedTopics.value));
/* ========== 数据刷新 ========== */
async function refreshData() {
try {
const [info, topics, tree, msgs] = await Promise.all([
const [info, active, configs, msgs] = await Promise.all([
mqttGetBrokerInfo(props.connectionId) as Promise<MqttBrokerInfo>,
mqttListTopics(props.connectionId) as Promise<[string, string][]>,
mqttGetTopicTree(props.connectionId) as Promise<MqttTopicNode>,
mqttListSavedTopicConfigs(props.connectionId) as Promise<MqttSavedTopic[]>,
mqttGetMessages(props.connectionId, selectedTopic.value || undefined, 50) as Promise<MqttMessage[]>,
]);
brokerInfo.value = info;
subscribedTopics.value = topics;
topicTree.value = tree;
subscribedTopics.value = active;
savedTopics.value = configs.map((config) => ({ ...config, enabled: config.enabled !== false, noLocal: config.noLocal === true }));
messages.value = msgs;
error.value = null;
} catch (e) {
@@ -53,49 +84,117 @@ async function refreshData() {
}
}
async function handleSubscribe(topic: string, noLocal = noLocalSubscribe.value) {
async function handleSubscribe(topic: string, qos: MqttQoS = "atmostonce", noLocal = noLocalSubscribe.value) {
try {
await mqttSubscribe(props.connectionId, topic, "atmostonce", noLocal);
await mqttSubscribe(props.connectionId, topic, qos, noLocal);
selectedTopic.value = topic;
await refreshData();
} catch (e) {
error.value = String(e);
}
}
async function handleUnsubscribe(topics: string[]) {
const subscribed = new Set(subscribedTopics.value.map(([topic]) => topic));
const targets = [...new Set(topics)].filter((topic) => subscribed.has(topic));
if (targets.length === 0) {
error.value = t("connection.mqttUnsubscribeMissing");
async function handleToggleEnabled(config: MqttSavedTopic) {
try {
if (subscribedTopics.value.some(([topic]) => topic === config.topic)) {
await mqttUnsubscribe(props.connectionId, config.topic);
} else {
await handleSubscribe(config.topic, config.qos, config.noLocal === true);
return;
}
await refreshData();
} catch (e) {
error.value = String(e);
}
}
async function handleDelete(config: MqttSavedTopic) {
if (!window.confirm(t("connection.mqttDeleteSubscriptionConfirm", { topic: config.topic }))) return;
try {
if (subscribedTopics.value.some(([topic]) => topic === config.topic)) await mqttUnsubscribe(props.connectionId, config.topic);
await mqttDeleteTopicConfig(props.connectionId, config.topic);
if (selectedTopic.value === config.topic) selectedTopic.value = "";
await refreshData();
} catch (e) {
error.value = String(e);
}
}
function openSubscriptionDialog() {
editingTopic.value = null;
formTopic.value = "";
formQos.value = "atmostonce";
formNoLocal.value = false;
formEnabled.value = true;
error.value = null;
showSubscriptionDialog.value = true;
}
function editSubscription(config: MqttSavedTopic) {
editingTopic.value = config.topic;
formTopic.value = config.topic;
formQos.value = config.qos;
formNoLocal.value = config.noLocal === true;
formEnabled.value = config.enabled !== false;
error.value = null;
showSubscriptionDialog.value = true;
}
function validTopicFilter(topic: string): boolean {
if (!topic) return false;
const segments = topic.split("/");
return segments.every((segment, index) => {
if (segment === "#") return index === segments.length - 1;
return !segment.includes("#") && (!segment.includes("+") || segment === "+");
});
}
async function saveSubscription() {
const topic = formTopic.value.trim();
if (!validTopicFilter(topic)) {
error.value = t("connection.mqttSubscriptionTopicFilterInvalid");
return;
}
if (savedTopics.value.some((config) => config.topic === topic && config.topic !== editingTopic.value)) {
error.value = t("connection.mqttSubscriptionTopicFilterDuplicate");
return;
}
if (formNoLocal.value && !mqtt5.value) {
error.value = t("connection.mqttSubscriptionNoLocalProtocolError");
return;
}
const prompt = targets.length === 1 ? t("connection.mqttUnsubscribeConfirm", { topic: targets[0] }) : t("connection.mqttUnsubscribeGroupConfirm", { count: targets.length });
if (!window.confirm(prompt)) return;
const failures: string[] = [];
for (const topic of targets) {
try {
await mqttUnsubscribe(props.connectionId, topic);
} catch (e) {
failures.push(`${topic}:${String(e)}`);
}
}
if (targets.includes(selectedTopic.value)) selectedTopic.value = "";
await refreshData();
if (failures.length > 0) {
error.value = t("connection.mqttUnsubscribeFailed", { count: failures.length, errors: failures.join("; ") });
savingSubscription.value = true;
error.value = null;
const previousTopic = editingTopic.value;
const topicChanged = previousTopic != null && previousTopic !== topic;
const previousWasActive = previousTopic != null && subscribedTopics.value.some(([current]) => current === previousTopic);
try {
// Save the new configuration first so a broker failure cannot remove the
// previous configuration or leave the edited topic without a retry path.
await mqttSaveTopicConfig(props.connectionId, topic, formQos.value, formNoLocal.value, formEnabled.value);
if (formEnabled.value) await mqttSubscribe(props.connectionId, topic, formQos.value, formNoLocal.value);
else if (!topicChanged && previousWasActive) await mqttUnsubscribe(props.connectionId, topic);
if (topicChanged && previousWasActive && previousTopic) await mqttUnsubscribe(props.connectionId, previousTopic);
if (topicChanged && previousTopic) await mqttDeleteTopicConfig(props.connectionId, previousTopic);
selectedTopic.value = topic;
showSubscriptionDialog.value = false;
await refreshData();
} catch (e) {
error.value = t("connection.mqttSubscriptionOperationFailed", { error: String(e) });
await refreshData();
} finally {
savingSubscription.value = false;
}
}
function handleTopicClick(topic: string) {
selectedTopic.value = topic;
refreshData();
void refreshData();
}
function handleMessagePublished() {
refreshData();
void refreshData();
}
async function handleClearMessages() {
@@ -107,15 +206,13 @@ async function handleClearMessages() {
}
}
/* ========== 消息轮询 ========== */
function startPolling() {
stopPolling();
pollingTimer.value = setInterval(async () => {
try {
const msgs = (await mqttGetMessages(props.connectionId, selectedTopic.value || undefined, 50)) as MqttMessage[];
messages.value = msgs;
messages.value = (await mqttGetMessages(props.connectionId, selectedTopic.value || undefined, 50)) as MqttMessage[];
} catch {
/* 忽略轮询错误 */
/* ignore polling errors */
}
}, 3000);
}
@@ -127,33 +224,36 @@ function stopPolling() {
}
}
/* ========== 格式化消息 Payload ========== */
function formatMessagePayload(msg: MqttMessage): string {
if (displayEncoding.value === "plaintext" && msg.payloadText != null) {
return msg.payloadText;
}
if (displayEncoding.value === "plaintext" && msg.payloadText != null) return msg.payloadText;
return decodePayload(msg.payloadBase64, displayEncoding.value);
}
/* ========== 生命周期 ========== */
watch(
() => props.initialTopic,
(topic) => {
if (topic !== undefined && topic !== selectedTopic.value) {
selectedTopic.value = topic;
void refreshData();
}
},
);
onMounted(async () => {
await refreshData();
startPolling();
});
onUnmounted(() => {
stopPolling();
});
onUnmounted(stopPolling);
</script>
<template>
<div class="flex flex-col h-full bg-card text-card-foreground">
<!-- Header -->
<div class="flex items-center justify-between px-4 py-2 border-b shrink-0">
<div class="flex h-full flex-col bg-card text-card-foreground">
<div class="flex shrink-0 items-center justify-between border-b px-4 py-2">
<div class="flex items-center gap-3">
<span class="text-lg font-semibold">{{ t("connection.mqttConsoleTitle") }}</span>
<span v-if="brokerInfo" class="text-sm text-muted-foreground">{{ brokerInfo.brokerUrl }}</span>
<span v-if="brokerInfo" class="px-1.5 py-0.5 rounded text-xs font-medium" :class="connected ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'">
<span v-if="brokerInfo" class="rounded px-1.5 py-0.5 text-xs font-medium" :class="connected ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'">
{{ connected ? t("connection.mqttConnected") : t("connection.mqttDisconnected") }}
</span>
</div>
@@ -163,86 +263,129 @@ onUnmounted(() => {
</div>
</div>
<!-- Error banner -->
<div v-if="error" class="px-4 py-2 bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-400 text-sm border-b">
<div v-if="error" class="border-b bg-red-50 px-4 py-2 text-sm text-red-700 dark:bg-red-950/30 dark:text-red-400">
{{ error }}
<button class="ml-2 underline" @click="error = null">{{ t("common.close") }}</button>
</div>
<!-- Body: 双栏布局 -->
<div class="flex-1 flex min-h-0">
<!-- 左侧:主题树 -->
<div class="w-72 border-r flex flex-col shrink-0">
<div class="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase border-b">{{ t("connection.mqttTopics") }}</div>
<div class="flex-1 overflow-auto p-2">
<div v-if="loading" class="text-xs text-muted-foreground p-2">{{ t("common.loading") }}</div>
<div v-else-if="!topicTree?.children?.length" class="text-xs text-muted-foreground p-2">{{ t("connection.mqttNoTopicsHint") }}</div>
<TopicTreeNode v-for="child in topicTree?.children ?? []" :key="child.fullPath" :node="child" :depth="0" :selected-topic="selectedTopic" :subscribed-topics="subscribedTopics" @select="handleTopicClick" @subscribe="handleSubscribe" @unsubscribe="handleUnsubscribe" />
<div class="flex min-h-0 flex-1">
<div class="flex w-[22rem] shrink-0 flex-col border-r">
<div class="flex items-center justify-between border-b px-3 py-2">
<span class="text-xs font-semibold uppercase text-muted-foreground">{{ t("connection.mqttSubscriptionConfig") }}</span>
<div class="flex items-center gap-1">
<Button size="sm" variant="ghost" class="h-7 px-2 text-xs" @click="refreshData">{{ t("connection.mqttRefresh") }}</Button>
<Button size="sm" class="h-7 px-2 text-xs" @click="openSubscriptionDialog">+ {{ t("connection.mqttNewSubscription") }}</Button>
</div>
</div>
<div class="border-b p-2">
<input v-model="topicSearch" class="h-8 w-full rounded border bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring" :placeholder="t('connection.mqttSearchSubscriptionsPlaceholder')" />
</div>
<div class="min-h-0 flex-1 overflow-auto">
<div v-if="loading" class="p-3 text-xs text-muted-foreground">{{ t("common.loading") }}</div>
<div v-else-if="!savedTopics.length" class="p-3 text-xs text-muted-foreground">{{ t("connection.mqttNoSavedSubscriptions") }}</div>
<TopicTreeNode
v-for="child in topicTree.children"
:key="child.fullPath"
:node="child"
:depth="0"
:selected-topic="selectedTopic"
:subscribed-topics="subscribedTopics"
:saved-topics="savedTopics"
:filter="topicSearch"
@select="handleTopicClick"
@toggle-enabled="handleToggleEnabled"
@edit="editSubscription"
@delete="handleDelete"
/>
</div>
<!-- 快速订阅 -->
<div class="border-t p-2">
<form
class="flex gap-1"
@submit.prevent="
(e) => {
const input = (e.target as HTMLFormElement).querySelector('input');
const topic = input?.value.trim();
if (topic && input) {
handleSubscribe(topic);
input.value = '';
}
}
"
>
<input class="flex-1 h-7 px-2 text-xs rounded border bg-transparent" :placeholder="t('connection.mqttSubscribePlaceholder')" />
<label class="flex items-center gap-1 text-[10px] whitespace-nowrap"><input v-model="noLocalSubscribe" type="checkbox" />{{ t("connection.mqttNoLocal") }}</label>
<Button size="sm" variant="ghost" class="h-7 text-xs" type="submit">{{ t("connection.mqttSubscribe") }}</Button>
<form class="flex gap-1" @submit.prevent="handleSubscribe((($event.target as HTMLFormElement).querySelector('input') as HTMLInputElement)?.value.trim() || '')">
<input class="h-7 min-w-0 flex-1 rounded border bg-transparent px-2 text-xs" :placeholder="t('connection.mqttSubscribePlaceholder')" />
<Button size="sm" variant="ghost" class="h-7 px-2 text-xs" type="submit">{{ t("connection.mqttQuickSubscribe") }}</Button>
</form>
<label class="mt-1 flex items-center gap-1 text-[10px] text-muted-foreground"><input v-model="noLocalSubscribe" type="checkbox" :disabled="!mqtt5" />{{ t("connection.mqttNoLocal") }}</label>
</div>
</div>
<!-- 右侧:消息列表 + 发布面板 -->
<div class="flex-1 flex flex-col min-w-0">
<!-- 消息区域 -->
<div class="flex-1 flex flex-col min-h-0">
<div class="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase border-b flex items-center justify-between shrink-0">
<div class="flex min-w-0 flex-1 flex-col">
<div class="flex min-h-0 flex-1 flex-col">
<div class="flex shrink-0 items-center justify-between border-b px-3 py-2 text-xs font-semibold uppercase text-muted-foreground">
<span v-if="selectedTopic">{{ t("connection.mqttMessagesForTopic", { topic: selectedTopic }) }}</span>
<span v-else>{{ t("connection.mqttAllMessages") }}</span>
<div class="flex items-center gap-2">
<span class="font-normal">{{ messages.length }}</span>
<!-- Payload 编码格式选择 -->
<select v-model="displayEncoding" class="h-6 px-1.5 text-[11px] rounded border bg-transparent text-muted-foreground cursor-pointer outline-none">
<option v-for="enc in PAYLOAD_ENCODINGS" :key="enc" :value="enc">
{{ PAYLOAD_ENCODING_LABELS[enc] }}
</option>
<select v-model="displayEncoding" class="h-6 rounded border bg-transparent px-1.5 text-[11px] text-muted-foreground outline-none">
<option v-for="enc in PAYLOAD_ENCODINGS" :key="enc" :value="enc">{{ PAYLOAD_ENCODING_LABELS[enc] }}</option>
</select>
</div>
</div>
<div class="flex-1 overflow-auto flex flex-col">
<div v-if="messages.length === 0" class="text-xs text-muted-foreground p-4 text-center">{{ t("connection.mqttNoMessages") }}</div>
<div class="flex min-h-0 flex-1 flex-col overflow-auto">
<div v-if="messages.length === 0" class="p-4 text-center text-xs text-muted-foreground">{{ t("connection.mqttNoMessages") }}</div>
<div
v-for="(msg, i) in messages"
:key="i"
class="px-3 py-2 border-b last:border-b-0 cursor-pointer text-xs self-start w-full"
:class="msg.direction === 'sent' ? 'bg-emerald-50/60 dark:bg-emerald-950/20 hover:bg-emerald-100/60 dark:hover:bg-emerald-950/40 ml-auto max-w-[85%] rounded-l-md' : 'hover:bg-muted/50 mr-auto max-w-[85%] rounded-r-md'"
class="w-full cursor-pointer border-b px-3 py-2 text-xs"
:class="
msg.direction === 'sent'
? 'ml-auto max-w-[85%] rounded-l-md border-r-2 border-emerald-400 bg-emerald-50/70 hover:bg-emerald-100/70 dark:border-emerald-500 dark:bg-emerald-950/30 dark:hover:bg-emerald-950/50'
: 'mr-auto max-w-[85%] rounded-r-md border-l-2 border-blue-400 bg-blue-50/70 hover:bg-blue-100/70 dark:border-blue-500 dark:bg-blue-950/30 dark:hover:bg-blue-950/50'
"
@click="handleTopicClick(msg.topic)"
>
<div class="flex items-center gap-2 mb-0.5">
<span v-if="msg.direction === 'sent'" class="text-emerald-600 dark:text-emerald-400 text-[10px] font-bold shrink-0">{{ t("connection.mqttSent") }}</span>
<span v-else class="text-blue-600 dark:text-blue-400 text-[10px] font-bold shrink-0">{{ t("connection.mqttReceived") }}</span>
<span class="font-mono text-blue-600 dark:text-blue-400 font-medium truncate">{{ msg.topic }}</span>
<span class="text-muted-foreground/60 shrink-0">QoS{{ msg.qos }}</span>
<span v-if="msg.retain" class="text-amber-600 dark:text-amber-400 text-[10px] font-medium shrink-0">{{ t("connection.mqttRetained") }}</span>
<div class="mb-0.5 flex items-center gap-2">
<span v-if="msg.direction === 'sent'" class="shrink-0 text-[10px] font-bold text-emerald-600 dark:text-emerald-400">{{ t("connection.mqttSent") }}</span>
<span v-else class="shrink-0 text-[10px] font-bold text-blue-600 dark:text-blue-400">{{ t("connection.mqttReceived") }}</span>
<span class="truncate font-mono font-medium text-blue-700 dark:text-blue-300">{{ msg.topic }}</span>
<span class="shrink-0 text-muted-foreground">QoS{{ msg.qos }}</span>
<span v-if="msg.retain" class="shrink-0 text-[10px] font-medium text-amber-600 dark:text-amber-400">{{ t("connection.mqttRetained") }}</span>
</div>
<div class="text-muted-foreground font-mono whitespace-pre-wrap break-all">{{ formatMessagePayload(msg) }}</div>
<div class="text-muted-foreground/50 mt-0.5 text-[10px]">{{ new Date(msg.receivedAtMs).toLocaleTimeString() }}</div>
<div class="break-all whitespace-pre-wrap font-mono text-muted-foreground">{{ formatMessagePayload(msg) }}</div>
<div class="mt-0.5 text-[10px] text-muted-foreground/60">{{ new Date(msg.receivedAtMs).toLocaleTimeString() }}</div>
</div>
</div>
</div>
<!-- 底部:内联发布面板 -->
<MqttPublishPanel v-if="connected" :connection-id="connectionId" :initial-topic="selectedTopic" @published="handleMessagePublished" />
</div>
</div>
<Dialog v-model:open="showSubscriptionDialog">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>{{ editingTopic ? t("connection.mqttEditSubscription") : t("connection.mqttNewSubscription") }}</DialogTitle>
</DialogHeader>
<div class="grid gap-3">
<label class="grid gap-1.5 text-xs font-medium">
<span>{{ t("connection.mqttTopicFilter") }}</span>
<input v-model="formTopic" class="h-8 rounded border bg-transparent px-2 font-mono text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring" :placeholder="t('connection.mqttTopicFilterPlaceholder')" :disabled="savingSubscription" @keydown.enter.prevent="saveSubscription" />
<span class="text-[11px] font-normal text-muted-foreground">{{ t("connection.mqttTopicFilterHint") }}</span>
</label>
<label class="grid gap-1.5 text-xs font-medium">
<span>QoS</span>
<select v-model="formQos" class="h-8 rounded border bg-transparent px-2 text-xs" :disabled="savingSubscription">
<option value="atmostonce">QoS 0 — {{ t("connection.mqttQosAtMostOnce") }}</option>
<option value="atleastonce">QoS 1 — {{ t("connection.mqttQosAtLeastOnce") }}</option>
<option value="exactlyonce">QoS 2 — {{ t("connection.mqttQosExactlyOnce") }}</option>
</select>
</label>
<label class="flex items-center gap-2 text-xs font-medium">
<input v-model="formNoLocal" type="checkbox" :disabled="savingSubscription || !mqtt5" />
<span>{{ t("connection.mqttNoLocal") }}(No Local)</span>
<span v-if="!mqtt5" class="font-normal text-muted-foreground">{{ t("connection.mqttNoLocalMqtt5Only") }}</span>
</label>
<label class="flex items-start gap-2 text-xs font-medium">
<input v-model="formEnabled" type="checkbox" :disabled="savingSubscription" />
<span
><span>{{ t("connection.mqttEnableSubscription") }}</span
><span class="block font-normal text-muted-foreground">{{ t("connection.mqttEnableSubscriptionHint") }}</span></span
>
</label>
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
</div>
<DialogFooter>
<Button variant="ghost" :disabled="savingSubscription" @click="showSubscriptionDialog = false">{{ t("common.cancel") }}</Button>
<Button :disabled="savingSubscription" @click="saveSubscription">{{ savingSubscription ? t("connection.mqttSaving") : t("common.save") }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</template>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import type { MqttTopicNode } from "@/types/mqtt";
import { ChevronRight, ChevronDown, Trash2 } from "@lucide/vue";
import type { MqttSavedTopic, MqttTopicNode } from "@/types/mqtt";
import { ChevronRight, ChevronDown, Pencil, Power, Trash2 } from "@lucide/vue";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
@@ -9,32 +9,28 @@ interface Props {
depth: number;
selectedTopic: string;
subscribedTopics: [string, string][];
savedTopics: MqttSavedTopic[];
filter?: string;
}
const props = defineProps<Props>();
const { t } = useI18n();
const emit = defineEmits<{
select: [topic: string];
subscribe: [topic: string];
unsubscribe: [topics: string[]];
toggleEnabled: [config: MqttSavedTopic];
edit: [config: MqttSavedTopic];
delete: [config: MqttSavedTopic];
}>();
const expanded = ref(props.depth < 2);
function isSubscribed(topic: string): boolean {
return props.subscribedTopics.some(([t]) => t === topic);
}
function collectSubscribedTopics(node: MqttTopicNode): string[] {
const topics = node.isLeaf && isSubscribed(node.fullPath) ? [node.fullPath] : [];
for (const child of node.children ?? []) {
topics.push(...collectSubscribedTopics(child));
}
return topics;
}
const topicsToUnsubscribe = computed(() => collectSubscribedTopics(props.node));
const unsubscribeLabel = computed(() => (topicsToUnsubscribe.value.length === 1 ? t("connection.mqttUnsubscribeTopic", { topic: topicsToUnsubscribe.value[0] }) : t("connection.mqttUnsubscribeGroup", { count: topicsToUnsubscribe.value.length })));
const savedConfig = computed(() => props.savedTopics.find((config) => config.topic === props.node.fullPath));
const active = computed(() => props.subscribedTopics.some(([topic]) => topic === props.node.fullPath));
const visible = computed(() => {
const filter = props.filter?.trim().toLowerCase();
if (!filter) return true;
const matches = (node: MqttTopicNode): boolean => node.fullPath.toLowerCase().includes(filter) || (node.children ?? []).some(matches);
return matches(props.node);
});
function toggle() {
expanded.value = !expanded.value;
@@ -42,39 +38,41 @@ function toggle() {
</script>
<template>
<div>
<div v-if="visible">
<div
class="flex items-center gap-1 py-0.5 pl-2 pr-1 rounded cursor-pointer text-xs group border-l-2 border-transparent"
:class="selectedTopic === node.fullPath ? 'bg-primary/25 text-foreground font-semibold border-l-primary shadow-sm ring-1 ring-primary/20' : 'hover:bg-muted/70 text-muted-foreground'"
:style="{ paddingLeft: `${depth * 12 + 4}px` }"
@click="node.isLeaf ? emit('select', node.fullPath) : toggle()"
class="group flex min-h-8 items-center gap-1 border-b border-border/50 py-1 pr-1 text-[13px] transition-colors"
:class="selectedTopic === node.fullPath ? 'border-l-2 border-l-primary bg-primary/10 pl-1 text-primary' : 'border-l-2 border-l-transparent pl-1 text-foreground/90 hover:bg-muted/60'"
:style="{ paddingLeft: `${depth * 14 + 4}px` }"
>
<!-- Expand/collapse toggle -->
<button v-if="node.children?.length" class="shrink-0 w-4 h-4 flex items-center justify-center text-muted-foreground" @click.stop="toggle">
<ChevronRight v-if="!expanded" class="h-3 w-3" />
<ChevronDown v-else class="h-3 w-3" />
<button v-if="node.children?.length" type="button" class="flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted" @click.stop="toggle">
<ChevronRight v-if="!expanded" class="h-3.5 w-3.5" />
<ChevronDown v-else class="h-3.5 w-3.5" />
</button>
<span v-else class="w-4 shrink-0" />
<span v-else class="w-5 shrink-0" />
<!-- Topic name -->
<span class="truncate flex-1 font-mono" :class="selectedTopic === node.fullPath ? 'text-primary' : node.isLeaf ? 'font-medium text-blue-600 dark:text-blue-400' : ''">
{{ node.name }}
</span>
<button type="button" class="min-w-0 flex-1 truncate text-left font-mono font-medium" :title="node.fullPath" @click="node.isLeaf ? emit('select', node.fullPath) : toggle()">{{ node.name }}<span v-if="!node.isLeaf" class="text-muted-foreground/70">/</span></button>
<!-- 分组节点可一次取消其下全部订阅 -->
<button
v-if="topicsToUnsubscribe.length"
type="button"
class="flex h-5 w-5 shrink-0 items-center justify-center rounded text-red-500 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-100 focus:opacity-100"
:title="unsubscribeLabel"
:aria-label="unsubscribeLabel"
@click.stop="emit('unsubscribe', topicsToUnsubscribe)"
>
<Trash2 class="h-3 w-3" />
</button>
<template v-if="savedConfig">
<span class="shrink-0 rounded border px-1 py-0.5 text-[10px] text-muted-foreground">QoS {{ savedConfig.qos === "atmostonce" ? 0 : savedConfig.qos === "atleastonce" ? 1 : 2 }}</span>
<span v-if="savedConfig.noLocal" class="shrink-0 rounded border border-blue-400/40 px-1 py-0.5 text-[10px] text-blue-600 dark:text-blue-400" :title="t('connection.mqttNoLocalMqtt5Only')">NL</span>
<span class="hidden shrink-0 text-[10px] text-muted-foreground sm:inline">{{ active ? t("connection.mqttSubscriptionStatusActive") : savedConfig.enabled ? t("connection.mqttSubscriptionStatusPending") : t("connection.mqttSubscriptionStatusDisabled") }}</span>
<button
type="button"
class="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"
:title="active ? t('connection.mqttSubscriptionDisable') : t('connection.mqttSubscriptionEnable')"
@click.stop="emit('toggleEnabled', savedConfig)"
>
<Power class="h-3.5 w-3.5" :class="active ? 'text-emerald-600 dark:text-emerald-400' : ''" />
</button>
<button type="button" class="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground" :title="t('connection.mqttSubscriptionEdit')" @click.stop="emit('edit', savedConfig)">
<Pencil class="h-3.5 w-3.5" />
</button>
<button type="button" class="flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-destructive/10 hover:text-destructive" :title="t('connection.mqttSubscriptionDelete')" @click.stop="emit('delete', savedConfig)">
<Trash2 class="h-3.5 w-3.5" />
</button>
</template>
</div>
<!-- Children -->
<TopicTreeNode
v-if="expanded"
v-for="child in node.children"
@@ -83,14 +81,16 @@ function toggle() {
:depth="depth + 1"
:selected-topic="selectedTopic"
:subscribed-topics="subscribedTopics"
:saved-topics="savedTopics"
:filter="filter"
@select="emit('select', $event)"
@subscribe="emit('subscribe', $event)"
@unsubscribe="emit('unsubscribe', $event)"
@toggle-enabled="emit('toggleEnabled', $event)"
@edit="emit('edit', $event)"
@delete="emit('delete', $event)"
/>
</div>
</template>
<script lang="ts">
// Recursive component needs explicit name in non-setup script block
export default { name: "TopicTreeNode" };
</script>