feat: rebuild group rule schema and add IDE-style problems panel

This commit is contained in:
2026-02-27 19:47:44 +08:00
parent 4259c46f65
commit f5ae91df43
10 changed files with 696 additions and 107 deletions

View File

@@ -72,10 +72,29 @@
步骤: 步骤:
- 在画布上创建多个节点。 - 在画布上创建多个节点。
- 创建动态分组Dynamic Group将节点加入/移出分组。 - 创建动态分组Dynamic Group将节点加入/移出分组。
- 仅选中 Dynamic Group 执行 `Ctrl+C` / `Ctrl+V`,观察粘贴结果。
预期: 预期:
- 分组操作成功。 - 分组操作成功。
- 分组信息能写入节点 meta用于规则检查 - 分组信息能写入节点 meta用于规则检查
- 复制分组时会自动携带组内节点(官方行为),新旧分组互不串联拖拽。
排查点:
- `src/components/flow/FlowEditor.vue` 使用 LogicFlow 默认快捷键复制粘贴(`shortcut.js -> lf.addElements`)。
## 11. 导出图片时隐藏 Dynamic Group视觉优化
步骤:
- 在画布创建 Dynamic Group并放入若干子节点。
- 点击“准备截图”并下载图片。
预期:
- 导出的图片中不显示 Dynamic Group 容器边框。
- 组内节点与其他节点正常显示。
- 导出完成后,编辑器画布中的 Dynamic Group 仍可见(只在导出瞬间隐藏)。
排查点:
- `src/components/Toolbar.vue``captureLogicFlowSnapshot` 及临时隐藏/恢复逻辑。
## 6. 规则静态检查(分组内) ## 6. 规则静态检查(分组内)
@@ -149,30 +168,32 @@
- [x] 基础启动与构建通过(`npm install` / `npm run dev` / `npm run build`)。 - [x] 基础启动与构建通过(`npm install` / `npm run dev` / `npm run build`)。
- [ ] 资产基路径与引用一致性通过(`/assets/...` 在宿主子路径下可正确解析)。 - [ ] 资产基路径与引用一致性通过(`/assets/...` 在宿主子路径下可正确解析)。
- [ ] 用户素材上传与使用通过(我的素材可新增并可用于节点)。 - [x] 用户素材上传与使用通过(我的素材可新增并可用于节点)。
- [ ] 用户素材删除与持久化通过(删除后刷新不复活)。 - [x] 用户素材删除与持久化通过(删除后刷新不复活)。
- [ ] 缺失资产降级策略通过(不阻断导出/渲染)。 - [ ] 缺失资产降级策略通过(不阻断导出/渲染)。
- [ ] Dynamic Group 分组基础行为通过(分组信息写入 `meta.groupId`)。 - [x] Dynamic Group 分组基础行为通过(分组信息写入 `meta.groupId`,复制分组会携带组内节点)。
- [ ] 分组规则静态检查通过(冲突与供火提示正确且可实时更新)。 - [ ] 分组规则静态检查通过(冲突与供火提示正确且可实时更新)。
- [ ] 矢量节点快速缩放性能回归通过(无明显卡顿/卡死)。 - [ ] 矢量节点快速缩放性能回归通过(无明显卡顿/卡死)。
- [ ] 导出到 wiki 数据兼容通过wiki 侧可 normalize 与预览)。 - [ ] 导出到 wiki 数据兼容通过wiki 侧可 normalize 与预览)。
- [ ] 跨项目素材互通通过(同 origin 可复用素材,跨 origin 不互通)。 - [ ] 跨项目素材互通通过(同 origin 可复用素材,跨 origin 不互通)。
- [ ] 跨项目规则互通方案确认(共享配置源定义、两侧读取一致)。 - [ ] 跨项目规则互通方案确认(共享配置源定义、两侧读取一致)。
- [x] 导出图片时隐藏 Dynamic Group 通过(导出前隐藏,导出后恢复)。
当前状态2026-02-27 当前状态2026-02-27
- 已通过:1 项(基础启动与构建)。 - 已通过:5 项(基础启动与构建、用户素材上传与使用、用户素材删除与持久化、Dynamic Group 分组基础行为、导出图片时隐藏 Dynamic Group)。
- 部分通过:3 项(用户素材上传与使用、用户素材删除与持久化、跨项目规则互通方案确认)。 - 部分通过:1 项(跨项目规则互通方案确认)。
- 未通过/待验证:7 项(其余项待完整手测或跨仓联调)。 - 未通过/待验证:6 项(其余项待完整手测或跨仓联调)。
逐项状态: 逐项状态:
- 基础启动与构建:已通过 - 基础启动与构建:已通过
- 资产基路径与引用一致性:未通过(待手测) - 资产基路径与引用一致性:未通过(待手测)
- 用户素材上传与使用:部分通过(实现已就绪,待手测) - 用户素材上传与使用:已通过
- 用户素材删除与持久化:部分通过(实现已修复,待手测) - 用户素材删除与持久化:已通过
- 缺失资产降级策略:未通过(待手测) - 缺失资产降级策略:未通过(待手测)
- Dynamic Group 分组基础行为:通过(待手测) - Dynamic Group 分组基础行为:通过
- 分组规则静态检查:未通过(待手测) - 分组规则静态检查:未通过(待手测)
- 矢量节点快速缩放性能回归:未通过(待手测) - 矢量节点快速缩放性能回归:未通过(待手测)
- 导出到 wiki 数据兼容:未通过(待跨仓联测) - 导出到 wiki 数据兼容:未通过(待跨仓联测)
- 跨项目素材互通:未通过(待同 origin 联测) - 跨项目素材互通:未通过(待同 origin 联测)
- 跨项目规则互通方案确认部分通过yys-editor 已落地wiki 待读取同源配置) - 跨项目规则互通方案确认部分通过yys-editor 已落地wiki 待读取同源配置)
- 导出图片时隐藏 Dynamic Group已通过

View File

@@ -36,6 +36,13 @@ const componentGroups = [
description: '可折叠的动态分组容器', description: '可折叠的动态分组容器',
data: { data: {
children: [], children: [],
groupMeta: {
version: 1,
groupKind: 'team',
groupName: '',
ruleEnabled: true,
ruleScope: ['shikigami-yuhun', 'shikigami-shikigami']
},
collapsible: true, collapsible: true,
isCollapsed: false, isCollapsed: false,
width: 420, width: 420,

View File

@@ -55,17 +55,43 @@
</button> </button>
</div> </div>
</div> </div>
<div v-if="groupRuleWarnings.length" class="control-row rule-row">
<div class="control-label">规则检查</div>
<div class="rule-list">
<div v-for="(warning, index) in groupRuleWarnings" :key="`${warning.groupId}-${warning.code}-${index}`" class="rule-item">
[{{ warning.groupId }}] {{ warning.message }}
</div>
</div>
</div>
</template> </template>
</div> </div>
<div class="container" ref="containerRef" :style="{ height: '100%' }"></div> <div class="container" ref="containerRef" :style="{ height: '100%' }"></div>
<div class="problems-dock" :class="{ 'problems-dock--open': problemsPanelOpen }">
<div class="problems-dock-bar">
<button class="problems-tab" type="button" @click="problemsPanelOpen = !problemsPanelOpen">
Problems
<span class="problems-badge">{{ groupRuleWarnings.length }}</span>
</button>
</div>
<div v-if="problemsPanelOpen" class="problems-panel">
<div class="problems-header">
<span>规则告警</span>
<span>{{ groupRuleWarnings.length }} </span>
</div>
<div v-if="!groupRuleWarnings.length" class="problems-empty">
当前没有告警
</div>
<div v-else class="problems-list">
<div
v-for="(warning, index) in groupRuleWarnings"
:key="warning.id || `${warning.groupId}-${warning.code}-${index}`"
class="problem-item"
role="button"
tabindex="0"
@click="locateProblemNode(warning)"
@keydown.enter.prevent="locateProblemNode(warning)"
>
<div class="problem-severity">{{ warning.severity.toUpperCase() }}</div>
<div class="problem-content">
<div class="problem-message">{{ warning.message }}</div>
<div class="problem-meta">{{ warning.groupName || warning.groupId }} · {{ warning.ruleId }}</div>
</div>
</div>
</div>
</div>
</div>
</div> </div>
<!-- 右侧属性面板 --> <!-- 右侧属性面板 -->
<PropertyPanel :height="height" :node="selectedNode" :lf="lf" /> <PropertyPanel :height="height" :node="selectedNode" :lf="lf" />
@@ -137,6 +163,7 @@ const { showMessage } = useGlobalMessage();
const selectedNode = ref<any>(null); const selectedNode = ref<any>(null);
const groupRuleWarnings = ref<GroupRuleWarning[]>([]); const groupRuleWarnings = ref<GroupRuleWarning[]>([]);
const flowControlsCollapsed = ref(true); const flowControlsCollapsed = ref(true);
const problemsPanelOpen = ref(false);
let containerResizeObserver: ResizeObserver | null = null; let containerResizeObserver: ResizeObserver | null = null;
let groupRuleValidationTimer: ReturnType<typeof setTimeout> | null = null; let groupRuleValidationTimer: ReturnType<typeof setTimeout> | null = null;
let unsubscribeSharedGroupRules: (() => void) | null = null; let unsubscribeSharedGroupRules: (() => void) | null = null;
@@ -701,6 +728,31 @@ function scheduleGroupRuleValidation(delay = 120) {
}, delay); }, delay);
} }
function locateProblemNode(warning: GroupRuleWarning) {
const lfInstance = lf.value as any;
if (!lfInstance) return;
const candidateIds = [...(warning.nodeIds || []), warning.groupId].filter((id) => !!id);
const targetId = candidateIds.find((id) => !!lfInstance.getNodeModelById(id));
if (!targetId) {
showMessage('warning', '未找到告警对应节点,可能已被删除');
return;
}
try {
lfInstance.clearSelectElements?.();
lfInstance.selectElementById?.(targetId, false, false);
lfInstance.focusOn?.(targetId);
const nodeData = lfInstance.getNodeDataById?.(targetId);
if (nodeData) {
selectedNode.value = nodeData;
}
} catch (error) {
console.error('定位告警节点失败:', error);
showMessage('error', '定位节点失败');
}
}
function applySelectionSelect(enabled: boolean) { function applySelectionSelect(enabled: boolean) {
const lfInstance = lf.value as any; const lfInstance = lf.value as any;
if (!lfInstance) return; if (!lfInstance) return;
@@ -1256,23 +1308,6 @@ onBeforeUnmount(() => {
.control-row:last-child { .control-row:last-child {
margin-bottom: 0; margin-bottom: 0;
} }
.rule-row {
align-items: flex-start;
}
.rule-list {
display: flex;
flex-direction: column;
gap: 4px;
max-width: 360px;
}
.rule-item {
color: #9a3412;
background: #fff7ed;
border: 1px solid #fed7aa;
border-radius: 6px;
padding: 4px 6px;
line-height: 1.4;
}
.control-label { .control-label {
font-weight: 600; font-weight: 600;
color: #303133; color: #303133;
@@ -1307,6 +1342,126 @@ onBeforeUnmount(() => {
.control-hint { .control-hint {
color: #909399; color: #909399;
} }
.problems-dock {
position: absolute;
left: 0;
right: 0;
bottom: 0;
z-index: 11;
pointer-events: none;
}
.problems-dock-bar {
display: flex;
align-items: center;
gap: 8px;
height: 32px;
padding: 0 10px;
background: rgba(250, 250, 250, 0.98);
border-top: 1px solid #dcdfe6;
pointer-events: auto;
}
.problems-tab {
display: inline-flex;
align-items: center;
gap: 6px;
border: 1px solid #dcdfe6;
background: #fff;
border-radius: 4px;
padding: 2px 10px;
height: 24px;
font-size: 12px;
cursor: pointer;
color: #303133;
}
.problems-tab:hover {
background: #f5f7fa;
}
.problems-badge {
min-width: 18px;
height: 18px;
border-radius: 10px;
background: #fde68a;
color: #92400e;
font-size: 11px;
font-weight: 600;
line-height: 18px;
text-align: center;
padding: 0 4px;
box-sizing: border-box;
}
.problems-panel {
height: 220px;
background: rgba(255, 255, 255, 0.98);
border-top: 1px solid #dcdfe6;
box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.08);
display: flex;
flex-direction: column;
pointer-events: auto;
}
.problems-header {
height: 32px;
padding: 0 12px;
border-bottom: 1px solid #ebeef5;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: #606266;
}
.problems-empty {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
color: #909399;
font-size: 13px;
}
.problems-list {
flex: 1;
overflow-y: auto;
}
.problem-item {
display: flex;
gap: 10px;
padding: 8px 12px;
border-bottom: 1px solid #f2f3f5;
cursor: pointer;
}
.problem-item:hover {
background: #f8fafc;
}
.problem-item:focus {
outline: none;
box-shadow: inset 0 0 0 1px #93c5fd;
background: #eff6ff;
}
.problem-severity {
width: 56px;
height: 20px;
border-radius: 10px;
background: #fff7ed;
border: 1px solid #fed7aa;
color: #9a3412;
font-size: 11px;
line-height: 18px;
text-align: center;
flex-shrink: 0;
}
.problem-content {
min-width: 0;
}
.problem-message {
color: #303133;
font-size: 13px;
line-height: 1.4;
}
.problem-meta {
margin-top: 2px;
color: #909399;
font-size: 12px;
line-height: 1.3;
word-break: break-all;
}
.context-menu { .context-menu {
position: fixed; position: fixed;
background: white; background: white;

View File

@@ -6,6 +6,7 @@ import TextPanel from './panels/TextPanel.vue';
import StylePanel from './panels/StylePanel.vue'; import StylePanel from './panels/StylePanel.vue';
import AssetSelectorPanel from './panels/AssetSelectorPanel.vue'; import AssetSelectorPanel from './panels/AssetSelectorPanel.vue';
import VectorPanel from './panels/VectorPanel.vue'; import VectorPanel from './panels/VectorPanel.vue';
import DynamicGroupPanel from './panels/DynamicGroupPanel.vue';
import { ASSET_LIBRARIES } from '@/types/nodeTypes'; import { ASSET_LIBRARIES } from '@/types/nodeTypes';
import { getLogicFlowInstance } from '@/ts/useLogicFlow'; import { getLogicFlowInstance } from '@/ts/useLogicFlow';
@@ -35,7 +36,8 @@ const panelMap: Record<string, any> = {
imageNode: ImagePanel, imageNode: ImagePanel,
textNode: TextPanel, textNode: TextPanel,
assetSelector: AssetSelectorPanel, assetSelector: AssetSelectorPanel,
vectorNode: VectorPanel vectorNode: VectorPanel,
'dynamic-group': DynamicGroupPanel
}; };
const panelComponent = computed(() => panelMap[nodeType.value] || null); const panelComponent = computed(() => panelMap[nodeType.value] || null);

View File

@@ -6,6 +6,7 @@ import { SELECTOR_PRESETS } from '@/configs/selectorPresets';
import type { SelectorConfig } from '@/types/selector'; import type { SelectorConfig } from '@/types/selector';
import { resolveAssetUrl, resolveAssetUrlsInDataSource } from '@/utils/assetUrl'; import { resolveAssetUrl, resolveAssetUrlsInDataSource } from '@/utils/assetUrl';
import { deleteCustomAsset, listCustomAssets } from '@/utils/customAssets'; import { deleteCustomAsset, listCustomAssets } from '@/utils/customAssets';
import { normalizeSelectedAssetRecord } from '@/utils/graphSchema';
const props = defineProps<{ const props = defineProps<{
node: any; node: any;
@@ -34,12 +35,13 @@ const handleOpenSelector = () => {
const imageField = preset.itemRender.imageField; const imageField = preset.itemRender.imageField;
const selectedAsset = node.properties?.selectedAsset || null; const selectedAsset = node.properties?.selectedAsset || null;
const normalizedSelectedAsset = selectedAsset && typeof selectedAsset === 'object' const normalizedSelectedAssetRecord = normalizeSelectedAssetRecord(selectedAsset, library);
const normalizedSelectedAsset = normalizedSelectedAssetRecord
? { ? {
...selectedAsset, ...normalizedSelectedAssetRecord,
[imageField]: resolveAssetUrl(selectedAsset?.[imageField]) [imageField]: resolveAssetUrl((selectedAsset as any)?.[imageField])
} }
: selectedAsset; : null;
const customAssets = listCustomAssets(library); const customAssets = listCustomAssets(library);
const mergedDataSource = [ const mergedDataSource = [
@@ -67,12 +69,13 @@ const handleOpenSelector = () => {
}; };
openGenericSelector(config, (selectedItem) => { openGenericSelector(config, (selectedItem) => {
const normalizedSelected = selectedItem && typeof selectedItem === 'object' const normalizedSelectedRecord = normalizeSelectedAssetRecord(selectedItem, library);
const normalizedSelected = normalizedSelectedRecord
? { ? {
...selectedItem, ...normalizedSelectedRecord,
[imageField]: resolveAssetUrl(selectedItem?.[imageField]) [imageField]: resolveAssetUrl((selectedItem as any)?.[imageField])
} }
: selectedItem; : null;
lf.setProperties(node.id, { lf.setProperties(node.id, {
...node.properties, ...node.properties,

View File

@@ -0,0 +1,138 @@
<script setup lang="ts">
import { reactive, watch } from 'vue';
import { getLogicFlowInstance } from '@/ts/useLogicFlow';
import {
DEFAULT_GROUP_RULE_SCOPE,
GROUP_META_VERSION,
normalizeDynamicGroupMeta
} from '@/utils/graphSchema';
const props = defineProps<{
node: any;
}>();
type DynamicGroupMeta = {
groupKind: 'team' | 'shikigami';
groupName: string;
ruleEnabled: boolean;
ruleScope: string[];
};
const DEFAULT_SCOPE_OPTIONS = [
{ value: 'shikigami-yuhun', label: '式神-御魂关系' },
{ value: 'shikigami-shikigami', label: '式神-式神关系' }
];
const form = reactive<DynamicGroupMeta>({
groupKind: 'team',
groupName: '',
ruleEnabled: true,
ruleScope: [...DEFAULT_GROUP_RULE_SCOPE]
});
const normalizeRuleScope = (value: unknown): string[] => {
if (!Array.isArray(value)) {
return [...DEFAULT_GROUP_RULE_SCOPE];
}
const normalized = value
.map((item) => (typeof item === 'string' ? item.trim() : ''))
.filter((item) => !!item);
return normalized.length ? normalized : [...DEFAULT_GROUP_RULE_SCOPE];
};
const syncFromNode = (node?: any) => {
if (!node) return;
const groupMeta = normalizeDynamicGroupMeta(node.properties?.groupMeta);
form.groupKind = groupMeta.groupKind;
form.groupName = groupMeta.groupName;
form.ruleEnabled = groupMeta.ruleEnabled;
form.ruleScope = normalizeRuleScope(groupMeta.ruleScope);
};
watch(
() => props.node,
(node) => {
if (node) {
syncFromNode(node);
}
},
{ immediate: true, deep: true }
);
const applyGroupMeta = () => {
const lf = getLogicFlowInstance();
const node = props.node;
if (!lf || !node) return;
lf.setProperties(node.id, {
...(node.properties || {}),
groupMeta: {
version: GROUP_META_VERSION,
groupKind: form.groupKind,
groupName: form.groupName.trim(),
ruleEnabled: form.ruleEnabled,
ruleScope: normalizeRuleScope(form.ruleScope)
}
});
};
</script>
<template>
<div class="property-section">
<div class="section-header">分组规则属性</div>
<div class="property-item">
<div class="property-label">分组类型</div>
<el-select v-model="form.groupKind" style="width: 100%" @change="applyGroupMeta">
<el-option label="队伍组team" value="team" />
<el-option label="式神组shikigami" value="shikigami" />
</el-select>
</div>
<div class="property-item">
<div class="property-label">分组名称</div>
<el-input
v-model="form.groupName"
placeholder="例如队伍1、PVP阵容A"
clearable
@change="applyGroupMeta"
/>
</div>
<div class="property-item">
<div class="property-label">启用规则检查</div>
<el-switch v-model="form.ruleEnabled" @change="applyGroupMeta" />
</div>
<div class="property-item">
<div class="property-label">规则范围</div>
<el-select
v-model="form.ruleScope"
multiple
filterable
allow-create
default-first-option
style="width: 100%"
placeholder="选择或输入规则范围"
@change="applyGroupMeta"
>
<el-option
v-for="option in DEFAULT_SCOPE_OPTIONS"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
<div class="property-tip">可扩展后续新增规则域时可直接添加 scope</div>
</div>
</div>
</template>
<style scoped>
.property-tip {
margin-top: 8px;
font-size: 12px;
color: #909399;
line-height: 1.4;
}
</style>

View File

@@ -56,6 +56,22 @@ export interface NodeMeta {
export interface NodeProperties { export interface NodeProperties {
style: NodeStyle; style: NodeStyle;
meta?: NodeMeta; meta?: NodeMeta;
children?: string[];
groupMeta?: {
version: number;
groupKind: 'team' | 'shikigami';
groupName: string;
ruleEnabled: boolean;
ruleScope: string[];
};
assetLibrary?: string;
selectedAsset?: {
assetId: string;
library: string;
name?: string;
avatar?: string;
[key: string]: any;
} | null;
image?: { url: string; fit?: 'fill'|'contain'|'cover' }; image?: { url: string; fit?: 'fill'|'contain'|'cover' };
text?: { content: string; rich?: boolean }; text?: { content: string; rich?: boolean };
vector?: { vector?: {
@@ -81,6 +97,7 @@ export interface GraphNode {
y?: number; y?: number;
width?: number; width?: number;
height?: number; height?: number;
children?: string[];
properties: NodeProperties; properties: NodeProperties;
} }

View File

@@ -5,6 +5,7 @@ import {ElMessageBox} from "element-plus";
import {useGlobalMessage} from "./useGlobalMessage"; import {useGlobalMessage} from "./useGlobalMessage";
import {getLogicFlowInstance} from "./useLogicFlow"; import {getLogicFlowInstance} from "./useLogicFlow";
import {CURRENT_SCHEMA_VERSION, migrateToV1, RootDocument} from "./schema"; import {CURRENT_SCHEMA_VERSION, migrateToV1, RootDocument} from "./schema";
import { normalizeGraphRawDataSchema } from '@/utils/graphSchema';
const {showMessage} = useGlobalMessage(); const {showMessage} = useGlobalMessage();
@@ -117,7 +118,7 @@ export const useFilesStore = defineStore('files', () => {
name: f?.name ?? f?.label ?? `File ${i + 1}`, name: f?.name ?? f?.label ?? `File ${i + 1}`,
visible: f?.visible ?? true, visible: f?.visible ?? true,
type: f?.type ?? 'FLOW', type: f?.type ?? 'FLOW',
graphRawData: (f?.graphRawData && typeof f.graphRawData === 'object') ? f.graphRawData : { nodes: [], edges: [] }, graphRawData: normalizeGraphRawDataSchema(f?.graphRawData),
transform: f?.transform ?? { transform: f?.transform ?? {
SCALE_X: 1, SCALE_X: 1,
SCALE_Y: 1, SCALE_Y: 1,
@@ -333,11 +334,12 @@ export const useFilesStore = defineStore('files', () => {
}; };
}) })
}; };
const normalizedGraphData = normalizeGraphRawDataSchema(enrichedGraphData);
// 直接保存原始数据到 GraphRawData // 直接保存原始数据到 GraphRawData
const file = findById(targetId); const file = findById(targetId);
if (file) { if (file) {
file.graphRawData = enrichedGraphData; file.graphRawData = normalizedGraphData;
file.transform = transform; file.transform = transform;
} }
} }

155
src/utils/graphSchema.ts Normal file
View File

@@ -0,0 +1,155 @@
export const GROUP_META_VERSION = 1
export const DEFAULT_GROUP_RULE_SCOPE = ['shikigami-yuhun', 'shikigami-shikigami']
export type GroupKind = 'team' | 'shikigami'
export type DynamicGroupMeta = {
version: number
groupKind: GroupKind
groupName: string
ruleEnabled: boolean
ruleScope: string[]
}
const normalizeText = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
const normalizeLibrary = (value: unknown): string => normalizeText(value).toLowerCase()
const inferLibraryFromAvatar = (avatar: string): string => {
if (!avatar) return ''
if (avatar.includes('/Yuhun/')) return 'yuhun'
if (avatar.includes('/Shikigami/')) return 'shikigami'
if (avatar.includes('/hero_')) return 'onmyoji'
return ''
}
const createStableHash = (seed: string): string => {
let hash = 0
for (let index = 0; index < seed.length; index += 1) {
hash = ((hash << 5) - hash) + seed.charCodeAt(index)
hash |= 0
}
return Math.abs(hash).toString(36)
}
const normalizeStringList = (value: unknown, fallback: string[]): string[] => {
if (!Array.isArray(value)) {
return [...fallback]
}
const normalized = value
.map((item) => normalizeText(item))
.filter((item) => !!item)
return normalized.length ? Array.from(new Set(normalized)) : [...fallback]
}
export const normalizeDynamicGroupMeta = (input: unknown, fallbackKind: GroupKind = 'team'): DynamicGroupMeta => {
const raw = input && typeof input === 'object' ? input as Record<string, unknown> : {}
const versionCandidate = Number(raw.version)
const version = Number.isFinite(versionCandidate) && versionCandidate > 0
? Math.trunc(versionCandidate)
: GROUP_META_VERSION
const groupKind: GroupKind = raw.groupKind === 'shikigami' ? 'shikigami' : fallbackKind
const groupName = normalizeText(raw.groupName)
const ruleEnabled = raw.ruleEnabled !== false
const ruleScope = normalizeStringList(raw.ruleScope, DEFAULT_GROUP_RULE_SCOPE)
return {
version,
groupKind,
groupName,
ruleEnabled,
ruleScope
}
}
const normalizeChildren = (value: unknown): string[] => {
if (!Array.isArray(value)) {
return []
}
return Array.from(
new Set(
value
.map((item) => normalizeText(item))
.filter((item) => !!item)
)
)
}
export const getDynamicGroupChildIds = (node: any): string[] => {
const nodeChildren = normalizeChildren(node?.children)
const propertyChildren = normalizeChildren(node?.properties?.children)
return nodeChildren.length ? nodeChildren : propertyChildren
}
export const normalizeSelectedAssetRecord = (input: unknown, preferredLibrary = ''): Record<string, unknown> | null => {
if (!input || typeof input !== 'object') {
return null
}
const raw = input as Record<string, unknown>
const name = normalizeText(raw.name)
const avatar = normalizeText(raw.avatar)
const library = normalizeLibrary(raw.library) || normalizeLibrary(preferredLibrary) || inferLibraryFromAvatar(avatar)
const sourceId = normalizeText(raw.assetId)
|| normalizeText(raw.id)
|| normalizeText(raw.skillId)
|| normalizeText(raw.onmyojiId)
const identitySeed = sourceId || `${name}|${avatar}|${library}`
const assetId = sourceId
? `${library || 'asset'}:${sourceId}`
: `asset_${createStableHash(identitySeed || String(Date.now()))}`
return {
...raw,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
library: library || 'shikigami',
assetId
}
}
export const normalizeGraphRawDataSchema = (graphData: any): { nodes: any[]; edges: any[] } => {
const rawNodes = Array.isArray(graphData?.nodes) ? graphData.nodes : []
const rawEdges = Array.isArray(graphData?.edges) ? graphData.edges : []
const nodes = rawNodes.map((node: any) => {
const properties = node?.properties && typeof node.properties === 'object'
? { ...node.properties }
: {}
if (node?.type === 'dynamic-group') {
const children = getDynamicGroupChildIds(node)
return {
...node,
children,
properties: {
...properties,
children,
groupMeta: normalizeDynamicGroupMeta(properties.groupMeta)
}
}
}
if (node?.type === 'assetSelector') {
const currentLibrary = normalizeLibrary(properties.assetLibrary) || 'shikigami'
const selectedAsset = normalizeSelectedAssetRecord(properties.selectedAsset, currentLibrary)
return {
...node,
properties: {
...properties,
assetLibrary: selectedAsset?.library || currentLibrary,
selectedAsset
}
}
}
return {
...node,
properties
}
})
return {
nodes,
edges: rawEdges
}
}

View File

@@ -1,21 +1,34 @@
import type { GroupRulesConfig } from '@/configs/groupRules' import type { GroupRulesConfig } from '@/configs/groupRules'
import { readSharedGroupRulesConfig } from '@/utils/groupRulesConfigSource' import { readSharedGroupRulesConfig } from '@/utils/groupRulesConfigSource'
import { getDynamicGroupChildIds, normalizeGraphRawDataSchema } from '@/utils/graphSchema'
type GraphData = { type GraphData = {
nodes: any[] nodes: any[]
edges: any[] edges: any[]
} }
type GroupAssetSnapshot = { type TeamAsset = {
nodeId: string
assetId: string
name: string
library: string
}
type TeamAssetSnapshot = {
groupId: string groupId: string
groupName: string
nodeIds: string[] nodeIds: string[]
shikigamiNames: string[] shikigamiAssets: TeamAsset[]
yuhunNames: string[] yuhunAssets: TeamAsset[]
} }
export type GroupRuleWarning = { export type GroupRuleWarning = {
id: string
ruleId: string
code: 'SHIKIGAMI_YUHUN_BLACKLIST' | 'SHIKIGAMI_CONFLICT' | 'MISSING_FIRE_SHIKIGAMI' code: 'SHIKIGAMI_YUHUN_BLACKLIST' | 'SHIKIGAMI_CONFLICT' | 'MISSING_FIRE_SHIKIGAMI'
severity: 'warning' | 'error' | 'info'
groupId: string groupId: string
groupName?: string
message: string message: string
nodeIds: string[] nodeIds: string[]
} }
@@ -31,13 +44,17 @@ const isAssetSelectorNode = (node: any): boolean => {
return !!node && node.type === 'assetSelector' return !!node && node.type === 'assetSelector'
} }
const isDynamicGroupNode = (node: any): boolean => {
return !!node && node.type === 'dynamic-group'
}
const inferLibrary = (node: any): string => { const inferLibrary = (node: any): string => {
const assetLibrary = normalizeText(node?.properties?.assetLibrary) const assetLibrary = normalizeText(node?.properties?.assetLibrary).toLowerCase()
if (assetLibrary) { if (assetLibrary) {
return assetLibrary return assetLibrary
} }
const selectedLibrary = normalizeText(node?.properties?.selectedAsset?.library) const selectedLibrary = normalizeText(node?.properties?.selectedAsset?.library).toLowerCase()
if (selectedLibrary) { if (selectedLibrary) {
return selectedLibrary return selectedLibrary
} }
@@ -52,94 +69,166 @@ const inferLibrary = (node: any): string => {
return '' return ''
} }
const collectGroupAssets = (graphData: GraphData): GroupAssetSnapshot[] => {
const groupMap = new Map<string, GroupAssetSnapshot>()
const nodes = Array.isArray(graphData?.nodes) ? graphData.nodes : []
nodes.forEach((node) => {
if (!isAssetSelectorNode(node)) {
return
}
const groupId = normalizeText(node?.properties?.meta?.groupId)
if (!groupId) {
return
}
const assetName = normalizeText(node?.properties?.selectedAsset?.name)
if (!assetName) {
return
}
if (!groupMap.has(groupId)) {
groupMap.set(groupId, {
groupId,
nodeIds: [],
shikigamiNames: [],
yuhunNames: []
})
}
const group = groupMap.get(groupId)!
group.nodeIds.push(node.id)
const library = inferLibrary(node)
if (library === 'shikigami') {
group.shikigamiNames.push(assetName)
return
}
if (library === 'yuhun') {
group.yuhunNames.push(assetName)
}
})
return Array.from(groupMap.values())
}
const includesName = (list: string[], target: string): boolean => { const includesName = (list: string[], target: string): boolean => {
return list.some((item) => item === target) return list.some((item) => item === target)
} }
const dedupeNodeIds = (ids: string[]): string[] => Array.from(new Set(ids))
const collectTeamAssetSnapshots = (graphData: GraphData): TeamAssetSnapshot[] => {
const nodes = Array.isArray(graphData?.nodes) ? graphData.nodes : []
const nodeMap = new Map<string, any>()
nodes.forEach((node) => {
const nodeId = normalizeText(node?.id)
if (!nodeId) return
nodeMap.set(nodeId, node)
})
const teamGroups = nodes.filter((node) => {
if (!isDynamicGroupNode(node)) return false
const groupKind = normalizeText(node?.properties?.groupMeta?.groupKind)
const ruleEnabled = node?.properties?.groupMeta?.ruleEnabled !== false
return groupKind === 'team' && ruleEnabled
})
return teamGroups.map((teamNode) => {
const teamId = normalizeText(teamNode?.id) || 'unknown-team'
const teamName = normalizeText(teamNode?.properties?.groupMeta?.groupName)
const queue = [...getDynamicGroupChildIds(teamNode)]
const visited = new Set<string>()
const shikigamiAssets: TeamAsset[] = []
const yuhunAssets: TeamAsset[] = []
while (queue.length > 0) {
const currentId = queue.shift() as string
if (!currentId || visited.has(currentId)) {
continue
}
visited.add(currentId)
const node = nodeMap.get(currentId)
if (!node) {
continue
}
if (isDynamicGroupNode(node)) {
const childKind = normalizeText(node?.properties?.groupMeta?.groupKind)
// 嵌套 team 视为独立边界,不纳入当前队伍聚合
if (childKind === 'team') {
continue
}
queue.push(...getDynamicGroupChildIds(node))
continue
}
if (!isAssetSelectorNode(node)) {
continue
}
const library = inferLibrary(node)
const name = normalizeText(node?.properties?.selectedAsset?.name)
const assetId = normalizeText(node?.properties?.selectedAsset?.assetId)
if (!name) {
continue
}
const asset: TeamAsset = {
nodeId: normalizeText(node?.id),
assetId,
name,
library
}
if (library === 'shikigami') {
shikigamiAssets.push(asset)
} else if (library === 'yuhun') {
yuhunAssets.push(asset)
}
}
return {
groupId: teamId,
groupName: teamName,
nodeIds: dedupeNodeIds([
...shikigamiAssets.map((item) => item.nodeId),
...yuhunAssets.map((item) => item.nodeId)
]),
shikigamiAssets,
yuhunAssets
}
})
}
const createWarningId = (groupId: string, ruleId: string): string => `${groupId}::${ruleId}`
export const validateGraphGroupRules = ( export const validateGraphGroupRules = (
graphData: GraphData, graphData: GraphData,
config?: GroupRulesConfig config?: GroupRulesConfig
): GroupRuleWarning[] => { ): GroupRuleWarning[] => {
const effectiveConfig = config || readSharedGroupRulesConfig() const effectiveConfig = config || readSharedGroupRulesConfig()
const groups = collectGroupAssets(graphData) const normalizedGraphData = normalizeGraphRawDataSchema(graphData)
const teams = collectTeamAssetSnapshots(normalizedGraphData)
const warnings: GroupRuleWarning[] = [] const warnings: GroupRuleWarning[] = []
groups.forEach((group) => { teams.forEach((team) => {
const shikigamiNames = team.shikigamiAssets.map((item) => item.name)
const yuhunNames = team.yuhunAssets.map((item) => item.name)
effectiveConfig.shikigamiYuhunBlacklist.forEach((rule) => { effectiveConfig.shikigamiYuhunBlacklist.forEach((rule) => {
if (includesName(group.shikigamiNames, rule.shikigami) && includesName(group.yuhunNames, rule.yuhun)) { if (includesName(shikigamiNames, rule.shikigami) && includesName(yuhunNames, rule.yuhun)) {
const ruleId = `blacklist:${rule.shikigami}:${rule.yuhun}`
const nodeIds = dedupeNodeIds([
...team.shikigamiAssets.filter((item) => item.name === rule.shikigami).map((item) => item.nodeId),
...team.yuhunAssets.filter((item) => item.name === rule.yuhun).map((item) => item.nodeId)
])
warnings.push({ warnings.push({
id: createWarningId(team.groupId, ruleId),
ruleId,
code: 'SHIKIGAMI_YUHUN_BLACKLIST', code: 'SHIKIGAMI_YUHUN_BLACKLIST',
groupId: group.groupId, severity: 'warning',
nodeIds: group.nodeIds, groupId: team.groupId,
groupName: team.groupName || undefined,
nodeIds,
message: rule.message || `规则冲突:${rule.shikigami} 不建议携带 ${rule.yuhun}` message: rule.message || `规则冲突:${rule.shikigami} 不建议携带 ${rule.yuhun}`
}) })
} }
}) })
effectiveConfig.shikigamiConflictPairs.forEach((rule) => { effectiveConfig.shikigamiConflictPairs.forEach((rule) => {
if (includesName(group.shikigamiNames, rule.left) && includesName(group.shikigamiNames, rule.right)) { if (includesName(shikigamiNames, rule.left) && includesName(shikigamiNames, rule.right)) {
const ruleId = `conflict:${rule.left}:${rule.right}`
const nodeIds = dedupeNodeIds([
...team.shikigamiAssets.filter((item) => item.name === rule.left).map((item) => item.nodeId),
...team.shikigamiAssets.filter((item) => item.name === rule.right).map((item) => item.nodeId)
])
warnings.push({ warnings.push({
id: createWarningId(team.groupId, ruleId),
ruleId,
code: 'SHIKIGAMI_CONFLICT', code: 'SHIKIGAMI_CONFLICT',
groupId: group.groupId, severity: 'warning',
nodeIds: group.nodeIds, groupId: team.groupId,
groupName: team.groupName || undefined,
nodeIds,
message: rule.message || `规则冲突:${rule.left}${rule.right} 不建议同队。` message: rule.message || `规则冲突:${rule.left}${rule.right} 不建议同队。`
}) })
} }
}) })
const hasShikigami = group.shikigamiNames.length > 0 const hasShikigami = shikigamiNames.length > 0
if (hasShikigami) { if (hasShikigami) {
const hasFireShikigami = group.shikigamiNames.some((name) => effectiveConfig.fireShikigamiWhitelist.includes(name)) const hasFireShikigami = shikigamiNames.some((name) => effectiveConfig.fireShikigamiWhitelist.includes(name))
if (!hasFireShikigami) { if (!hasFireShikigami) {
const ruleId = 'missing-fire-shikigami'
warnings.push({ warnings.push({
id: createWarningId(team.groupId, ruleId),
ruleId,
code: 'MISSING_FIRE_SHIKIGAMI', code: 'MISSING_FIRE_SHIKIGAMI',
groupId: group.groupId, severity: 'warning',
nodeIds: group.nodeIds, groupId: team.groupId,
message: '规则提示:当前分组未检测到鬼火式神,建议补充供火位。' groupName: team.groupName || undefined,
nodeIds: dedupeNodeIds(team.shikigamiAssets.map((item) => item.nodeId)),
message: '规则提示:当前队伍未检测到鬼火式神,建议补充供火位。'
}) })
} }
} }