import { computed, reactive } from "vue";
import type { DialogInstance, QueueKind } from "@/dialogs/types";
interface DialogQueue {
active: DialogInstance | null;
pending: DialogInstance[];
}
const dialogQueues = reactive(new Map<string, DialogQueue>());
function ensureQueue(label: string): DialogQueue {
const existing = dialogQueues.get(label);
if (existing) {
return existing;
}
const created = reactive<DialogQueue>({
active: null,
pending: [],
});
dialogQueues.set(label, created);
return created;
}
function initStats() {
return {
question: 0,
confirm: 0,
};
}
function bump(stats: ReturnType<typeof initStats>, kind: QueueKind) {
switch (kind) {
case "question":
stats.question += 1;
break;
case "confirm":
stats.confirm += 1;
break;
default:
break;
}
}
/**
* UI 对话框统一管理(按窗口 label 分队列)。
*/
export function useUiDialog(windowLabel: string) {
const queue = ensureQueue(windowLabel);
const activeDialog = computed(() => queue.active);
const queueSize = computed(() => queue.pending.length);
const queueStatsByKind = computed(() => {
const stats = initStats();
for (const item of queue.pending) {
bump(stats, item.queueKind);
}
return stats;
});
function enqueue(dialog: DialogInstance) {
if (!queue.active) {
queue.active = dialog;
} else {
queue.pending.push(dialog);
}
}
function advance() {
if (queue.pending.length > 0) {
queue.active = queue.pending.shift() ?? null;
} else {
queue.active = null;
}
}
function clearQueue() {
queue.active = null;
queue.pending = [];
}
const isIdle = computed(() => !queue.active && queue.pending.length === 0);
return {
activeDialog,
queueSize,
queueStatsByKind,
isIdle,
enqueue,
advance,
clearQueue,
};
}