Compare commits

...

4 Commits

9 changed files with 1040 additions and 25 deletions
+4 -4
View File
@@ -90,8 +90,8 @@ export function registerIpcHandlers() {
// ==================== 主题管理 ====================
ipcMain.handle('mqtt:add-topic', (_, serverId, topic, qos) => {
return mqttManager.addTopic(serverId, topic, qos);
ipcMain.handle('mqtt:add-topic', (_, serverId, topic, qos, comment) => {
return mqttManager.addTopic(serverId, topic, qos, comment);
});
ipcMain.handle('mqtt:remove-topic', (_, serverId, topic) => {
@@ -110,8 +110,8 @@ export function registerIpcHandlers() {
return mqttManager.subscribeAll(serverId);
});
ipcMain.handle('mqtt:update-topic', (_, serverId, topicId, topic, qos) => {
return mqttManager.updateTopic(serverId, topicId, topic, qos);
ipcMain.handle('mqtt:update-topic', (_, serverId, topicId, topic, qos, comment) => {
return mqttManager.updateTopic(serverId, topicId, topic, qos, comment);
});
// ==================== 消息发布 ====================
+12 -5
View File
@@ -82,6 +82,7 @@ class MqttManager {
s.topics = (s.topics || []).map((t) => ({
...t,
id: t.id || 'topic_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
comment: t.comment ?? '',
subscribed: false,
}));
this.servers.set(s.id, s);
@@ -154,8 +155,8 @@ class MqttManager {
reconnectInterval: 5000,
status: 'disconnected',
topics: [
{ id: 'topic_default_001', topic: 'sensor/+/temperature', qos: 1, subscribed: false },
{ id: 'topic_default_002', topic: 'device/status', qos: 2, subscribed: false },
{ id: 'topic_default_001', topic: 'sensor/+/temperature', qos: 1, comment: '', subscribed: false },
{ id: 'topic_default_002', topic: 'device/status', qos: 2, comment: '', subscribed: false },
],
},
];
@@ -272,6 +273,7 @@ class MqttManager {
id: t.id || 'topic_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
topic: t.topic,
qos: t.qos ?? 1,
comment: t.comment ?? '',
subscribed: false,
};
}
@@ -361,6 +363,7 @@ class MqttManager {
id: t.id,
topic: t.topic,
qos: t.qos,
comment: t.comment ?? '',
};
}
@@ -575,9 +578,10 @@ class MqttManager {
* @param {string} serverId - 服务器 id
* @param {string} topic - 主题名称
* @param {MqttQoS} qos - QoS 等级
* @param {string} comment - 主题备注
* @returns {MqttTopic | null} 添加后的主题对象或 null
*/
addTopic(serverId, topic, qos = 1) {
addTopic(serverId, topic, qos = 1, comment = '') {
let server = this.servers.get(serverId);
if (!server) {
return null;
@@ -588,7 +592,7 @@ class MqttManager {
let topicId = 'topic_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6);
let newTopic = { id: topicId, topic, qos, subscribed: false };
let newTopic = { id: topicId, topic, qos, comment, subscribed: false };
server.topics.push(newTopic);
this.saveData();
@@ -686,9 +690,10 @@ class MqttManager {
* @param {string} topicId - 主题 id
* @param {string} newTopic - 新的主题名称
* @param {number} newQos - 新的 QoS 等级
* @param {string} comment - 新的主题备注
* @returns {boolean} 是否更新成功
*/
updateTopic(serverId, topicId, newTopic, newQos) {
updateTopic(serverId, topicId, newTopic, newQos, comment = '') {
let server = this.servers.get(serverId);
@@ -721,6 +726,7 @@ class MqttManager {
t.topic = newTopic;
t.qos = newQos;
t.comment = comment;
// 如果已连接且此前已订阅,重新订阅新主题
if (server.status === 'connected' && wasSubscribed) {
@@ -733,6 +739,7 @@ class MqttManager {
topic: newTopic,
subscribed: t.subscribed,
topicId,
comment: t.comment,
});
return true;
+4 -3
View File
@@ -20,13 +20,14 @@ const api = {
disconnect: (id) => ipcRenderer.invoke('mqtt:disconnect', id),
// 主题管理
addTopic: (serverId, topic, qos) => ipcRenderer.invoke('mqtt:add-topic', serverId, topic, qos),
addTopic: (serverId, topic, qos, comment) =>
ipcRenderer.invoke('mqtt:add-topic', serverId, topic, qos, comment),
removeTopic: (serverId, topic) => ipcRenderer.invoke('mqtt:remove-topic', serverId, topic),
subscribe: (serverId, topic) => ipcRenderer.invoke('mqtt:subscribe', serverId, topic),
unsubscribe: (serverId, topic) => ipcRenderer.invoke('mqtt:unsubscribe', serverId, topic),
subscribeAll: (serverId) => ipcRenderer.invoke('mqtt:subscribe-all', serverId),
updateTopic: (serverId, topicId, topic, qos) =>
ipcRenderer.invoke('mqtt:update-topic', serverId, topicId, topic, qos),
updateTopic: (serverId, topicId, topic, qos, comment) =>
ipcRenderer.invoke('mqtt:update-topic', serverId, topicId, topic, qos, comment),
// 消息发布
publish: (serverId, topic, payload, opts) =>
+9
View File
@@ -9,6 +9,7 @@ import Dashboard from './views/Dashboard.vue';
import Subscribe from './views/Subscribe.vue';
import Publish from './views/Publish.vue';
import Messages from './views/Messages.vue';
import QuickSend from './views/QuickSend.vue';
// 全局状态
const store = useMqttStore();
@@ -148,6 +149,14 @@ function handleSwitchTab(tab) {
</div>
</div>
</n-tab-pane>
<n-tab-pane
name="quick-send"
tab="快速发送"
>
<div class="tab-content">
<QuickSend />
</div>
</n-tab-pane>
</n-tabs>
</n-layout>
+28 -6
View File
@@ -33,6 +33,7 @@ import { ref, computed } from 'vue';
* @property {string} serverId 所属服务器 id
* @property {string} topic 主题名称
* @property {string} [topicId] 主题 id
* @property {string} [comment] 主题备注
* @property {boolean} subscribed 是否已订阅
*/
@@ -57,12 +58,12 @@ import { ref, computed } from 'vue';
* @property {(serverList: ServerConfig[]) => Promise<MqttServer[]>} importServers 导入服务器配置
* @property {(id: string) => Promise<boolean>} connectServer 连接服务器
* @property {(id: string) => Promise<void>} disconnectServer 断开服务器
* @property {(serverId: string, topic: string, qos: MqttQoS) => Promise<MqttTopic | null>} addTopic 添加主题
* @property {(serverId: string, topic: string, qos: MqttQoS, comment: string) => Promise<MqttTopic | null>} addTopic 添加主题
* @property {(serverId: string, topic: string) => Promise<void>} removeTopic 移除主题
* @property {(serverId: string, topic: string) => Promise<boolean>} subscribeTopic 订阅主题
* @property {(serverId: string, topic: string) => Promise<boolean>} unsubscribeTopic 取消订阅主题
* @property {(serverId: string) => Promise<boolean>} subscribeAllTopics 批量订阅所有主题
* @property {(serverId: string, topicId: string, topic: string, qos: MqttQoS) => Promise<boolean>} updateTopic 更新主题
* @property {(serverId: string, topicId: string, topic: string, qos: MqttQoS, comment: string) => Promise<boolean>} updateTopic 更新主题
* @property {(serverId: string, topic: string, payload: string, opts: PublishOptions) => Promise<boolean>} publishMessage 发布消息
* @property {() => Promise<void>} refreshMessages 刷新消息列表
* @property {() => Promise<void>} refreshPublishHistory 刷新发布历史
@@ -108,6 +109,17 @@ const loading = ref(false);
*/
let cleanupFns = [];
/**
* 对指定服务器的主题列表按主题名称升序排序
* @param {MqttServer} server - 服务器对象
* @returns {void}
*/
function sortTopics(server) {
if (server && server.topics) {
server.topics.sort((a, b) => a.topic.localeCompare(b.topic));
}
}
/**
* 设置主进程事件监听器
* 包括状态变化、消息接收、订阅变化等事件
@@ -170,8 +182,12 @@ function setupListeners() {
if (t) {
t.subscribed = data.subscribed;
if (typeof data.comment === 'string') {
t.comment = data.comment;
}
if (data.topic && data.topic !== t.topic) {
t.topic = data.topic;
sortTopics(srv);
}
}
@@ -252,6 +268,7 @@ export function useMqttStore() {
servers.value = data;
sortServers();
servers.value.forEach((srv) => sortTopics(srv));
setupListeners();
} catch (e) {
@@ -355,6 +372,7 @@ export function useMqttStore() {
let data = await window.api.importServers(serverList);
servers.value = data;
sortServers();
servers.value.forEach((srv) => sortTopics(srv));
if (servers.value.length > 0 && !activeServerId.value) {
activeServerId.value = servers.value[0].id;
}
@@ -386,16 +404,18 @@ export function useMqttStore() {
* @param {string} serverId - 服务器 id
* @param {string} topic - 主题名称
* @param {MqttQoS} qos - QoS 等级
* @param {string} comment - 主题备注
* @returns {Promise<MqttTopic | null>} 添加后的主题对象或 null
*/
async function addTopic(serverId, topic, qos) {
async function addTopic(serverId, topic, qos, comment) {
let result = await window.api.addTopic(serverId, topic, qos);
let result = await window.api.addTopic(serverId, topic, qos, comment);
if (result) {
let srv = servers.value.find((s) => s.id === serverId);
if (srv) {
srv.topics.push(result);
sortTopics(srv);
}
}
@@ -417,6 +437,7 @@ export function useMqttStore() {
if (srv) {
srv.topics = srv.topics.filter((t) => t.topic !== topic);
sortTopics(srv);
}
}
@@ -456,10 +477,11 @@ export function useMqttStore() {
* @param {string} topicId - 主题 id
* @param {string} topic - 新的主题名称
* @param {MqttQoS} qos - 新的 QoS 等级
* @param {string} comment - 新的主题备注
* @returns {Promise<boolean>} 是否更新成功
*/
async function updateTopic(serverId, topicId, topic, qos) {
return await window.api.updateTopic(serverId, topicId, topic, qos);
async function updateTopic(serverId, topicId, topic, qos, comment) {
return await window.api.updateTopic(serverId, topicId, topic, qos, comment);
}
// ==================== 消息发布 ====================
+839
View File
@@ -0,0 +1,839 @@
<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { useMqttStore } from '../stores/mqtt.js';
import { NCard, NSpace, NFormItem, NInput, NSelect, NSwitch, NButton, NEmpty, NModal, NForm, NGrid, NGridItem, NCheckbox, useMessage, useDialog } from 'naive-ui';
// 全局状态与消息 API
const store = useMqttStore();
const msg = useMessage();
const dialog = useDialog();
// localStorage 持久化 key
const storageKey = 'mqtt-client.quick-send-list';
/**
* @typedef {Object} QuickSendItem
* @property {string} id
* @property {string} topic
* @property {string} payload
* @property {0|1|2} qos
* @property {boolean} retain
*/
// 快速发送列表
/** @type {import('vue').Ref<QuickSendItem[]>} */
const quickList = ref([]);
// 表单弹窗显隐
const showModal = ref(false);
const isEdit = ref(false);
// 表单数据
const formId = ref('');
const formTopic = ref('');
const formPayload = ref('');
const formQos = ref(1);
const formRetain = ref(false);
// 从 localStorage 恢复列表
try {
let saved = JSON.parse(localStorage.getItem(storageKey) || '[]');
if (Array.isArray(saved)) {
quickList.value = saved.filter((item) => {
return item && typeof item.id === 'string' && typeof item.topic === 'string';
});
}
} catch {
localStorage.removeItem(storageKey);
}
// 列表变化时持久化
watch(
quickList,
() => {
localStorage.setItem(storageKey, JSON.stringify(quickList.value));
},
{ deep: true }
);
// QoS 下拉选项
const qosOptions = [
{ label: 'QoS 0 - 最多一次', value: 0 },
{ label: 'QoS 1 - 至少一次', value: 1 },
{ label: 'QoS 2 - 恰好一次', value: 2 },
];
// 当前是否有选中的服务器
const hasActiveServer = computed(() => Boolean(store.activeServer.value));
// 拖拽排序状态
/** @type {import('vue').Ref<number>} */
const dragIndex = ref(-1);
/** @type {import('vue').Ref<QuickSendItem | null>} */
const dragItem = ref(null);
// 列表容器引用与响应式布局
/** @type {import('vue').Ref<HTMLElement | null>} */
const containerRef = ref(null);
const columnCount = ref(1);
/** @type {ResizeObserver | null} */
let resizeObserver = null;
// 批量操作状态
/** @type {import('vue').Ref<string[]>} */
const selectedIds = ref([]);
/** @type {import('vue').Ref<HTMLInputElement | null>} */
const fileInput = ref(null);
// 是否已全选
const isAllSelected = computed(() => {
return quickList.value.length > 0 && selectedIds.value.length === quickList.value.length;
});
// 是否有选中项
const hasSelected = computed(() => selectedIds.value.length > 0);
/**
* 生成唯一 id
* @returns {string}
*/
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
}
/**
* 打开新增弹窗
*/
function handleAdd() {
isEdit.value = false;
formId.value = '';
formTopic.value = '';
formPayload.value = '';
formQos.value = 1;
formRetain.value = false;
showModal.value = true;
}
/**
* 打开编辑弹窗
* @param {QuickSendItem} item
*/
function handleEdit(item) {
isEdit.value = true;
formId.value = item.id;
formTopic.value = item.topic;
formPayload.value = item.payload;
formQos.value = item.qos;
formRetain.value = item.retain;
showModal.value = true;
}
/**
* 保存快速发送项
*/
function handleSave() {
let topic = formTopic.value.trim();
if (!topic) {
msg.warning('请输入目标主题');
return;
}
let payload = formPayload.value;
let qos = formQos.value;
let retain = formRetain.value;
if (isEdit.value) {
let idx = quickList.value.findIndex((item) => item.id === formId.value);
if (idx !== -1) {
quickList.value[idx] = {
...quickList.value[idx],
topic,
payload,
qos,
retain,
};
}
} else {
quickList.value.push({
id: generateId(),
topic,
payload,
qos,
retain,
});
}
showModal.value = false;
}
/**
* 删除快速发送项
* @param {QuickSendItem} item
*/
function handleDelete(item) {
dialog.warning({
title: '确认删除',
content: `确定要删除主题 "${item.topic}" 的快速消息吗?`,
positiveText: '删除',
negativeText: '取消',
onPositiveClick: () => {
quickList.value = quickList.value.filter((i) => i.id !== item.id);
},
});
}
/**
* 开始拖拽
* @param {DragEvent} e
* @param {QuickSendItem} item
* @param {number} index
*/
function handleDragStart(e, item, index) {
dragIndex.value = index;
dragItem.value = item;
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', item.id);
}
}
/**
* 拖拽经过目标项
* @param {DragEvent} e
* @param {number} index
*/
function handleDragOver(e, index) {
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = 'move';
}
if (dragIndex.value === -1 || dragIndex.value === index) {
return;
}
}
/**
* 放置拖拽项
* @param {DragEvent} e
* @param {number} index
*/
function handleDrop(e, index) {
e.preventDefault();
if (dragIndex.value === -1 || dragIndex.value === index) {
return;
}
let item = quickList.value[dragIndex.value];
quickList.value.splice(dragIndex.value, 1);
quickList.value.splice(index, 0, item);
}
/**
* 拖拽结束
*/
function handleDragEnd() {
dragIndex.value = -1;
dragItem.value = null;
}
/**
* 发送消息到当前服务器
* @param {QuickSendItem} item
*/
async function handleSend(item) {
let srv = store.activeServer.value;
if (!srv) {
msg.warning('请先在左侧选择一个 MQTT 服务器');
return;
}
if (srv.status !== 'connected') {
msg.warning('请先连接服务器');
return;
}
let result = await store.publishMessage(srv.id, item.topic, item.payload, {
qos: item.qos,
retain: item.retain,
});
if (result) {
msg.success('消息已发布到: ' + item.topic);
}
}
/**
* 复制主题到剪贴板
* @param {string} topic
*/
async function copyTopic(topic) {
try {
await navigator.clipboard.writeText(topic);
msg.success('主题已复制');
} catch {
msg.error('复制失败');
}
}
/**
* 格式化消息内容为 JSON
*/
function handleFormatJson() {
try {
let obj = JSON.parse(formPayload.value);
formPayload.value = JSON.stringify(obj, null, 2);
msg.info('JSON 已格式化');
} catch {
msg.warning('无效的 JSON 格式');
}
}
/**
* 选中或取消选中单个快速消息
* @param {string} id
* @param {boolean} checked
*/
function handleSelectItem(id, checked) {
if (checked) {
selectedIds.value.push(id);
} else {
selectedIds.value = selectedIds.value.filter((i) => i !== id);
}
}
/**
* 切换全选状态
*/
function handleToggleSelectAll() {
if (isAllSelected.value) {
selectedIds.value = [];
} else {
selectedIds.value = quickList.value.map((item) => item.id);
}
}
/**
* 批量删除选中的快速消息
*/
function handleBatchDelete() {
if (!hasSelected.value) {
return;
}
dialog.warning({
title: '确认批量删除',
content: `确定要删除选中的 ${selectedIds.value.length} 条快速消息吗?`,
positiveText: '删除',
negativeText: '取消',
onPositiveClick: () => {
quickList.value = quickList.value.filter((item) => !selectedIds.value.includes(item.id));
selectedIds.value = [];
},
});
}
/**
* 导出快速消息列表为 JSON 文件
*/
function handleExport() {
let data = quickList.value;
let blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
let url = URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = `frost-mqtt-quick-send-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);
msg.success('快速消息已导出');
}
/**
* 触发文件导入点击
*/
function handleImportClick() {
fileInput.value?.click();
}
/**
* 处理导入的 JSON 文件
* @param {Event} event
*/
function handleImportFile(event) {
let file = event.target.files?.[0];
if (!file) {
return;
}
let reader = new FileReader();
reader.onload = (e) => {
try {
let data = JSON.parse(String(e.target?.result || ''));
if (!Array.isArray(data)) {
msg.error('导入失败: 文件内容不是数组');
return;
}
let validItems = data.filter((item) => {
return item && typeof item.id === 'string' && typeof item.topic === 'string';
});
if (validItems.length === 0) {
msg.warning('未找到有效的快速消息');
return;
}
dialog.create({
title: '选择导入方式',
content: `检测到 ${validItems.length} 条快速消息,请选择导入方式:`,
positiveText: '追加',
negativeText: '覆盖',
class: 'quick-send-dialog',
onPositiveClick: () => {
let existingIds = new Set(quickList.value.map((item) => item.id));
let itemsToAdd = validItems.map((item) => {
if (existingIds.has(item.id)) {
return { ...item, id: generateId() };
}
return item;
});
quickList.value.push(...itemsToAdd);
selectedIds.value = [];
msg.success(`已追加 ${itemsToAdd.length} 条快速消息`);
},
onNegativeClick: () => {
quickList.value = validItems;
selectedIds.value = [];
msg.success(`已覆盖为导入的 ${validItems.length} 条快速消息`);
},
});
} catch (err) {
msg.error('导入失败: ' + (err.message || '未知错误'));
}
};
reader.onerror = () => {
msg.error('读取文件失败');
};
reader.readAsText(file);
event.target.value = '';
}
function updateColumnCount(width) {
if (width >= 1520) {
columnCount.value = 3;
} else if (width >= 720) {
columnCount.value = 2;
} else {
columnCount.value = 1;
}
}
onMounted(() => {
resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
updateColumnCount(entry.contentRect.width);
}
});
if (containerRef.value) {
resizeObserver.observe(containerRef.value);
updateColumnCount(containerRef.value.clientWidth);
}
});
onUnmounted(() => {
if (resizeObserver) {
resizeObserver.disconnect();
resizeObserver = null;
}
});
</script>
<template>
<div
ref="containerRef"
class="quick-send-view"
>
<n-card
size="small"
:content-style="{
display: 'flex',
flexDirection: 'column',
minHeight: 0,
overflow: 'hidden',
}"
>
<n-space
style="margin-bottom: 12px"
align="center"
>
<n-button
type="primary"
@click="handleAdd"
>新增快速消息</n-button>
<n-button
size="small"
:disabled="quickList.length === 0"
@click="handleToggleSelectAll"
>{{ isAllSelected ? '取消全选' : '全选' }}</n-button>
<n-button
size="small"
type="error"
ghost
:disabled="!hasSelected"
@click="handleBatchDelete"
>批量删除</n-button>
<n-button
size="small"
@click="handleImportClick"
>导入</n-button>
<n-button
size="small"
@click="handleExport"
>导出</n-button>
</n-space>
<n-empty
v-if="quickList.length === 0"
description="暂无快速发送消息,点击上方按钮添加"
/>
<div
v-else
class="quick-list"
:class="`columns-${columnCount}`"
>
<div
v-for="(item, index) in quickList"
:key="item.id"
class="quick-item"
:class="{ dragging: dragIndex === index }"
draggable="true"
@dragstart="handleDragStart($event, item, index)"
@dragover.prevent="handleDragOver($event, index)"
@drop.prevent="handleDrop($event, index)"
@dragend="handleDragEnd"
>
<div class="quick-header">
<n-checkbox
class="quick-checkbox"
:checked="selectedIds.includes(item.id)"
@update:checked="(checked) => handleSelectItem(item.id, checked)"
@click.stop
/>
<div class="quick-topic-wrap">
<span class="quick-dir pub">PUB</span>
<span
class="quick-topic"
:title="item.topic"
@click="copyTopic(item.topic)"
>{{ item.topic }}</span>
<span class="quick-meta">QoS{{ item.qos }}{{ item.retain ? ' R' : '' }}</span>
</div>
<n-space>
<n-button
size="tiny"
:disabled="!hasActiveServer"
type="primary"
@click="handleSend(item)"
>发送</n-button>
<n-button
size="tiny"
@click="handleEdit(item)"
>编辑</n-button>
<n-button
size="tiny"
type="error"
ghost
@click="handleDelete(item)"
>删除</n-button>
</n-space>
</div>
<pre
v-if="item.payload"
class="quick-payload"
>{{ item.payload }}</pre>
</div>
</div>
<input
ref="fileInput"
type="file"
accept=".json,application/json"
style="display: none"
@change="handleImportFile"
>
</n-card>
<n-modal
v-model:show="showModal"
class="quick-send-modal"
:title="isEdit ? '编辑快速消息' : '新增快速消息'"
preset="card"
style="width: 520px; max-width: 90vw"
:bordered="false"
:segmented="{ content: true }"
>
<n-form
label-placement="top"
:show-feedback="false"
>
<n-form-item label="目标主题">
<n-input
v-model:value="formTopic"
placeholder="例如: sensor/device01/temperature"
/>
</n-form-item>
<n-grid
cols="2"
x-gap="12"
>
<n-grid-item>
<n-form-item label="QoS">
<n-select
v-model:value="formQos"
:options="qosOptions"
/>
</n-form-item>
</n-grid-item>
<n-grid-item>
<n-form-item label="保留消息">
<n-switch v-model:value="formRetain" />
</n-form-item>
</n-grid-item>
</n-grid>
<n-form-item label="消息内容">
<div class="payload-field">
<n-input
v-model:value="formPayload"
type="textarea"
:resizable="false"
:rows="6"
placeholder="输入要发送的消息内容"
/>
<n-button
size="small"
@click="handleFormatJson"
>格式化 JSON</n-button>
</div>
</n-form-item>
</n-form>
<template #footer>
<n-space justify="end">
<n-button @click="showModal = false">取消</n-button>
<n-button
type="primary"
@click="handleSave"
>保存</n-button>
</n-space>
</template>
</n-modal>
</div>
</template>
<style scoped>
.quick-send-view {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
}
.quick-send-view :deep(.n-card) {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.quick-send-view :deep(.n-card__content) {
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
}
.quick-list {
flex: 1;
min-height: 0;
overflow-y: auto;
display: grid;
grid-template-columns: 1fr;
gap: 12px;
padding-right: 4px;
align-content: start;
}
.quick-list.columns-1 {
grid-template-columns: 1fr;
}
.quick-list.columns-2 {
grid-template-columns: repeat(2, 1fr);
}
.quick-list.columns-3 {
grid-template-columns: repeat(3, 1fr);
}
.payload-field {
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
}
.payload-field :deep(.n-input) {
width: 100%;
}
.payload-field .n-button {
align-self: flex-end;
}
.quick-item {
border: 1px solid rgba(0, 0, 0, 0.08);
border-radius: 6px;
padding: 12px;
background: #fafafa;
cursor: grab;
transition: box-shadow 0.2s, opacity 0.2s;
}
.quick-item.dragging {
opacity: 0.6;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
cursor: grabbing;
}
.quick-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
min-width: 0;
}
.quick-checkbox {
flex-shrink: 0;
margin-top: 2px;
}
.quick-checkbox :deep(.n-checkbox-box) {
width: 16px;
height: 16px;
}
.quick-topic-wrap {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
flex: 1;
flex-wrap: wrap;
}
.quick-dir {
flex-shrink: 0;
font-weight: 700;
width: 28px;
font-size: 12px;
}
.quick-dir.pub {
color: #3b82f6;
}
.quick-topic {
color: #d25a00;
min-width: 0;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
font-family: monospace;
font-size: 13px;
}
.quick-topic:hover {
text-decoration: underline;
}
.quick-meta {
color: #999;
font-size: 11px;
flex-shrink: 0;
font-family: monospace;
}
.quick-payload {
margin: 10px 0 0;
padding: 8px 10px;
border-radius: 4px;
background: rgba(0, 0, 0, 0.04);
color: #333;
font: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-family: monospace;
font-size: 12px;
line-height: 1.6;
max-height: 120px;
overflow-y: auto;
}
.quick-send-modal .n-form-item {
margin-bottom: 20px;
}
.quick-send-modal .n-form-item__label {
margin-bottom: 8px;
}
.quick-send-modal .n-form-item:last-child {
margin-bottom: 0;
}
.quick-send-modal .n-grid {
margin-bottom: 20px;
}
.quick-send-dialog .n-dialog__icon {
color: #0ea5a0;
}
</style>
+91 -7
View File
@@ -1,7 +1,7 @@
<script setup>
import { ref, watch } from 'vue';
import { useMqttStore } from '../stores/mqtt.js';
import { NCard, NSpace, NFormItem, NInput, NSelect, NButton, NEmpty, NList, NListItem, NTag, NEllipsis, useMessage } from 'naive-ui';
import { NCard, NSpace, NFormItem, NInput, NSelect, NButton, NEmpty, NList, NListItem, NTag, useMessage } from 'naive-ui';
// 全局状态与消息 API
const store = useMqttStore();
@@ -10,11 +10,13 @@ const msg = useMessage();
// 主题输入与 QoS 选择
const topicInput = ref('');
const qos = ref(2);
const comment = ref('');
// 编辑状态
const editingTopicId = ref(null);
const editingTopic = ref('');
const editingQos = ref(2);
const editingComment = ref('');
// QoS 下拉选项
const qosOptions = [
@@ -84,11 +86,12 @@ async function handleAddTopic() {
return;
}
let result = await store.addTopic(srv.id, topic, qos.value);
let result = await store.addTopic(srv.id, topic, qos.value, comment.value.trim());
if (result) {
msg.success('主题已添加' + (srv.status === 'connected' ? '并已订阅' : ''));
topicInput.value = '';
comment.value = '';
}
}
@@ -173,6 +176,7 @@ function startEdit(t) {
editingTopicId.value = t.id || t.topic;
editingTopic.value = t.topic;
editingQos.value = t.qos ?? 2;
editingComment.value = t.comment ?? '';
}
/**
@@ -182,6 +186,7 @@ function cancelEdit() {
editingTopicId.value = null;
editingTopic.value = '';
editingQos.value = 2;
editingComment.value = '';
}
/**
@@ -213,7 +218,13 @@ async function handleEditSave(t) {
}
let topicId = t.id || t.topic;
let result = await store.updateTopic(srv.id, topicId, topicName, editingQos.value);
let result = await store.updateTopic(
srv.id,
topicId,
topicName,
editingQos.value,
editingComment.value.trim()
);
if (result) {
msg.success('主题已更新');
@@ -258,6 +269,16 @@ async function handleEditSave(t) {
:options="qosOptions"
/>
</n-form-item>
<n-form-item
class="comment-field"
label="备注"
>
<n-input
v-model:value="comment"
placeholder="可选备注"
@keydown.enter="handleAddTopic"
/>
</n-form-item>
<n-button
class="topic-submit"
type="primary"
@@ -329,6 +350,11 @@ async function handleEditSave(t) {
:options="qosOptions"
style="width: 160px; flex-shrink: 0"
/>
<n-input
v-model:value="editingComment"
size="small"
placeholder="备注"
/>
<n-space
:size="4"
:wrap="false"
@@ -352,7 +378,20 @@ async function handleEditSave(t) {
v-else
class="topic-name"
>
<n-ellipsis>{{ t.topic }}</n-ellipsis>
<span
class="topic-label"
:title="t.topic"
>{{ t.topic }}</span>
<div
v-if="t.comment"
class="topic-comment"
>
<span class="topic-comment-prefix">备注</span>
<span
class="topic-comment-text"
:title="t.comment"
>{{ t.comment }}</span>
</div>
</div>
<template #suffix>
<n-space
@@ -443,12 +482,18 @@ async function handleEditSave(t) {
width: 160px;
}
.comment-field {
flex: 1 1 180px;
width: auto;
}
.topic-submit {
flex: 0 0 auto;
}
.topic-field :deep(.n-form-item-blank),
.qos-field :deep(.n-form-item-blank) {
.qos-field :deep(.n-form-item-blank),
.comment-field :deep(.n-form-item-blank) {
width: 100%;
}
@@ -460,12 +505,51 @@ async function handleEditSave(t) {
}
.topic-name {
min-width: 0;
display: flex;
flex: 1;
font-family: monospace;
flex-direction: column;
align-items: stretch;
min-width: 0;
gap: 5px;
font-size: 13px;
}
.topic-label {
min-width: 0;
overflow: hidden;
font-family: monospace;
text-overflow: ellipsis;
white-space: nowrap;
}
.topic-comment {
display: flex;
align-items: center;
min-width: 0;
max-width: 100%;
padding: 2px 6px;
gap: 5px;
border: 1px solid rgba(14, 165, 160, 0.16);
border-radius: 4px;
background: rgba(20, 184, 166, 0.06);
color: var(--n-text-color-3);
font-size: 12px;
line-height: 18px;
}
.topic-comment-prefix {
flex-shrink: 0;
color: #0f766e;
}
.topic-comment-text {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.topic-actions {
flex-shrink: 0;
}
+4
View File
@@ -17,6 +17,8 @@ export interface MqttTopic {
topic: string;
/** 订阅 QoS 等级 */
qos: MqttQoS;
/** 主题备注,空字符串表示未备注 */
comment: string;
/** 当前是否已订阅 */
subscribed: boolean;
}
@@ -29,6 +31,8 @@ export interface TopicConfig {
topic: string;
/** 订阅 QoS 等级,默认 1 */
qos?: MqttQoS;
/** 主题备注,默认空字符串 */
comment?: string;
}
/** MQTT 服务器配置(不含运行时状态) */
+49
View File
@@ -0,0 +1,49 @@
# 代码风格
## 基础格式
- 使用 UTF-8、LF 换行、2 个空格缩进;文件末尾保留换行,删除行尾空白。
- JavaScript、Vue SFC 使用分号结尾。
- 字符串通常使用单引号;模板属性和值使用双引号。
- 对象、数组尾项保留逗号。
- 复杂函数的函数体内常使用空行分隔初始化、分支和返回逻辑;保持与所在文件一致即可。
## JavaScript
- 使用 ES Module`import` / `export`
- 导入顺序通常为:框架或第三方依赖、项目内部模块、资源文件;不同分组之间空一行。
- 变量优先使用 `const`;需要重新赋值的局部变量使用 `let`;不使用 `var`
- 函数以具名 `function` 声明为主;回调和简单映射使用箭头函数。
- 命名使用 camelCase:变量、函数、方法和参数均使用英文语义名称;布尔值常以 `is``show``has` 等开头。
- 常量或配置集合也多使用 camelCase,例如 `protocolOptions``themeOverrides`
- 错误处理使用 `try...catch`,错误信息通过中文 `console.error` 或界面消息反馈。
## 注释与类型
- 注释、JSDoc 说明和面向用户的提示文案使用简体中文。
- 按职责使用 `// ==================== 模块名 ====================` 分隔较长的文件。
- 公开方法、重要状态和较复杂逻辑使用 JSDoc 描述用途、参数和返回值。
- JavaScript 项目通过 JSDoc 引入或声明类型,例如 `@typedef``@param``@returns`,公共 MQTT 类型集中引用 `types/jsdoc.d.ts`
- 简单实现可配合单行中文注释说明意图,避免重复描述显而易见的代码。
## Vue 组件
- 单文件组件按 `<script setup>``<template>``<style>` 的顺序组织。
- 组件文件使用 PascalCase,例如 `ServerModal.vue`;组件在模板中同样使用 PascalCase。
- `script setup` 中通常依次放置:导入、Props/Emits、响应式状态、静态配置、侦听或生命周期、事件处理函数。
- 事件处理函数以 `handle` 开头,例如 `handleSave`;模板事件名采用 kebab-case,例如 `@edit-server`
- Naive UI 组件使用 `NButton` 等 PascalCase 导入,在模板中写为 `n-button`
- 模板属性一行较长时换行,每个属性单独一行,并保持 2 空格缩进。
- 样式采用普通 CSS;类名使用 kebab-case;布局和组件私有样式就近放在对应组件中。
## Electron 分层
- `src/main` 处理窗口、IPC 与 MQTT 等主进程逻辑。
- `src/preload` 统一封装并暴露 `window.api`,渲染进程不直接使用 Electron IPC。
- `src/renderer` 放置 Vue 页面、组件和状态管理;通过 `window.api` 调用主进程能力。
## ESLint
- 使用 `@electron-toolkit/eslint-config` 与 Vue 推荐规则作为基础。
- Vue 组件允许单词名称;未强制默认 Prop;模板单行或多行内容换行规则已关闭。
- 提交前执行 `pnpm lint`,并修复实际报告的问题。