Skip to content

World's first open-source enterprise world model.

Classes, properties, attributes and knowledge edit in dialogs; the panel shows (#480)

WaylandYang0fffff4daef8
diff --git a/web/DESIGN.md b/web/DESIGN.md
index 17ff4875..dc67a158 100644
--- a/web/DESIGN.md
+++ b/web/DESIGN.md
@@ -52,6 +52,8 @@ Settings and other read-a-column-of-fields pages are centred and width-limited (
Exempt: the floating panels on Graph and Ontology. Those are `glass-strong` surfaces over a canvas, and their job is to hold the canvas down so they can be read — a different problem from this one.
+A floating panel **shows**; it does not edit. A class, a property, an entity, a fact's interval are read there, and every change — creating, editing, deleting, connecting — opens a `FormDialog`: one title, one form, Cancel and Save at the bottom right, Delete on its own at the bottom left. The pencil beside the panel's close key is the way in. A form inside the panel put half-edited fields next to the definition being read and Save beside Delete; a dialog gives the change its own frame, its own Esc, and leaves the panel to say what the thing is. The dedicated dialogs live in `pages/ontologyDialogs.tsx` and `pages/graphDialogs.tsx`.
+
## How this is enforced
`web/scripts/style-guard.mjs` scans `web/src/**/*.tsx` for the patterns above and fails CI on any hit. It runs first in `pnpm build`. While the pages were being migrated, `web/style-guard.baseline.json` listed the ones not yet done; every page passes now and the file is gone. A new file is checked from its first commit.
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index fbc266e5..48aad6af 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -881,6 +881,11 @@ export const en = {
historicalNote: (n: number) =>
`${n} past fact${n === 1 ? "" : "s"} not shown — see Timeline →`,
undated: "Undated",
+ /* 实体面板的 Relations:两节的标题、组尾的折、行上的证据开关 */
+ fromEntity: (name: string) => `From ${name}`,
+ toEntity: (name: string) => `To ${name}`,
+ past: (n: number) => (n === 1 ? "1 past" : `${n} past`),
+ sources: (n: number) => (n === 1 ? "1 source" : `${n} sources`),
timelineEmpty: "No dated facts yet.",
lastConfirmed: (d: string) => `confirmed ${d}`,
/* 三种来源共用一个标记(引擎接任对账、Review 裁决、有人手改),所以这句
@@ -892,6 +897,7 @@ export const en = {
"The superseded assertion stays in the ledger — see History for who and when.",
/* ---- 人工修正有效区间(302) ---- */
editTime: "Correct the interval",
+ editTitle: "Edit entity",
timeStart: "Start",
timeEnd: "End",
/* 结束端的三态,与账本里的三种写法一一对应(见迁移 0003 的注释) */
@@ -1091,7 +1097,7 @@ export const en = {
tabClasses: "Classes",
tabProperties: "Properties",
newClass: "New class",
- newSubClass: "+ Sub-class",
+ newSubClass: "New sub-class",
newProperty: "New property",
filter: "Filter…",
missesShort: "Unmatched",
@@ -1191,6 +1197,15 @@ export const en = {
attributesHint:
"Literal-valued fields of this class (a person's salary, a contract's amount). Extracted with evidence and history, like any fact.",
newAttribute: "New attribute",
+ /* 编辑弹窗(面板只展示,改动在弹窗里):标题与面板里的入口 */
+ edit: "Edit",
+ editClass: "Edit class",
+ editProperty: "Edit property",
+ editAttribute: "Edit attribute",
+ connectTitle: "Connect a relationship",
+ connectOpen: "Connect an existing relationship…",
+ noDescription: "No description yet.",
+ axiomsNone: "None declared.",
attrDatatype: "Value type",
attrUnit: "Unit",
attrUnitHint: "optional — e.g. CNY, %",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 14682265..12163415 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -791,12 +791,17 @@ export const zh: Strings = {
historyOngoing: "未闭合",
historicalNote: (n: number) => `另有 ${n} 条历史事实未显示——见时间线 →`,
undated: "无日期",
+ fromEntity: (name) => `从 ${name} 出发`,
+ toEntity: (name) => `指向 ${name}`,
+ past: (n) => `${n} 条已结束`,
+ sources: (n) => `${n} 处来源`,
timelineEmpty: "还没有带日期的事实。",
lastConfirmed: (d: string) => `${d} 确认`,
correctedHint:
"这个区间来自一次修正,并非文档里逐字这么写:自动接续、审阅决定,或有人手工改过。" +
"被取代的那条断言仍留在台账里——谁改的、何时改的见「变更」。",
editTime: "修正区间",
+ editTitle: "编辑实体",
timeStart: "起点",
timeEnd: "终点",
timeEndOpen: "仍在持续",
@@ -977,7 +982,7 @@ export const zh: Strings = {
tabClasses: "类",
tabProperties: "属性",
newClass: "新建类",
- newSubClass: "+ 子类",
+ newSubClass: "新建子类",
newProperty: "新建属性",
filter: "筛选…",
missesShort: "未匹配",
@@ -1065,6 +1070,14 @@ export const zh: Strings = {
attributesHint:
"这个类的字面值字段(一个人的薪资、一份合同的金额)。和任何事实一样带证据与历史。",
newAttribute: "新建属性",
+ edit: "编辑",
+ editClass: "编辑类",
+ editProperty: "编辑关系",
+ editAttribute: "编辑属性",
+ connectTitle: "连接一个关系",
+ connectOpen: "用已有的关系连接…",
+ noDescription: "还没有描述。",
+ axiomsNone: "没有声明。",
attrDatatype: "值类型",
attrUnit: "单位",
attrUnitHint: "可选——如 CNY、%",
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index 6e6fb55d..2b4dc270 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from "react";
import {
useCallback,
useEffect,
@@ -38,7 +39,8 @@ import {
TRANSPARENT,
} from "./graphVisuals";
import { EntityHistory } from "./EntityHistory";
-import { fmtTime, parseDateInput } from "../time";
+import { EntityDialog, FactTimeDialog } from "./graphDialogs";
+import { fmtTime } from "../time";
import { NextStep, nextStep, useReadiness } from "./NextStep";
import {
ArrowLeft,
@@ -56,6 +58,7 @@ import {
X,
ZoomIn,
ZoomOut,
+ ChevronRight,
} from "lucide-react";
import {
api,
@@ -72,22 +75,20 @@ import {
Button,
DangerConfirm,
ExpandCard,
- Field,
HOVER_ROW,
IconButton,
Input,
+ LinkButton,
Pill,
- Radio,
REVEAL,
+ ROW_TRAILING,
Row,
Segmented,
ToolButton,
ToolDivider,
ToolTower,
cn,
- localDate,
GroupLabel,
- SearchSelect,
} from "../ui";
import { usePopoverFlip } from "../ui/popoverFlip";
import { useKb, useKbId } from "../kb";
@@ -2657,9 +2658,9 @@ function EntityPanel({
}, [derived, entityId]);
// Relations = 按关系分组(查关系);Timeline = 有效时间轴(事情何时成立);
// History = 记录时间轴(我们何时这么认为、又何时改了主意)
- const [view, setView] = useState<
- "relations" | "timeline" | "history" | "derived"
- >("relations");
+ const [view, setView] = useState<"relations" | "history" | "derived">(
+ "relations",
+ );
useEffect(() => {
const it = intent?.current;
if (!it) return;
@@ -2670,11 +2671,9 @@ function EntityPanel({
const e: GraphNode | undefined = detail.data?.entity;
- // 实体修正:抽取给的是初判,判错此前只能整库重抽
+ // 实体修正(名字、类型)在弹窗里:面板只展示
const qc = useQueryClient();
const [editing, setEditing] = useState(false);
- const [draftName, setDraftName] = useState("");
- const [draftType, setDraftType] = useState("");
// 同名的其他实体:详情接口打开就给。改名之后再用响应里的那份覆盖——
// 改完名可能撞上一批新的同名,那时候的答案比打开时的新
const [renamedPeers, setRenamedPeers] = useState<GraphNode[] | null>(null);
@@ -2701,98 +2700,32 @@ function EntityPanel({
},
onError: (err: Error) => toast.error(err.message),
});
- // 类型下拉要的是全量本体,不是当前视图里出现过的那几个
- const ontology = useQuery({
- queryKey: ["ontology", kbId],
- queryFn: () => api.ontology(kbId),
- enabled: editing,
- });
- const types = ontology.data?.entity_types ?? [];
-
const openEdit = () => {
if (!e) return;
- setDraftName(e.name);
- setDraftType(types.find((t) => t.key === e.type_key)?.id ?? "");
- setSameName([]);
setEditing(true);
};
- // 本体是异步来的:它到齐时把类型下拉对到当前类型上
- useEffect(() => {
- if (editing && !draftType && e)
- setDraftType(types.find((t) => t.key === e.type_key)?.id ?? "");
- }, [editing, draftType, e, types]);
-
- const save = useMutation({
- mutationFn: () => {
- const body: { type_id?: string; canonical_name?: string } = {};
- if (draftName.trim() && draftName.trim() !== e?.name)
- body.canonical_name = draftName.trim();
- const curId = types.find((t) => t.key === e?.type_key)?.id;
- if (draftType && draftType !== curId) body.type_id = draftType;
- return api.updateEntity(kbId, entityId, body);
- },
- onSuccess: (r) => {
- setEditing(false);
- setSameName(r.same_name);
- toast.success(S.graph.editSaved);
- // 改了类型/名字,图谱节点与本体计数都要跟着动
- qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] });
- qc.invalidateQueries({ queryKey: ["graph", kbId] });
- qc.invalidateQueries({ queryKey: ["ontology", kbId] });
- },
- onError: (err: Error) => toast.error(err.message),
- });
- const dirty =
- !!e &&
- (draftName.trim() !== e.name ||
- draftType !== (types.find((t) => t.key === e.type_key)?.id ?? ""));
-
- // Relations = 当下有效的快照(as-of now);已闭合的历史只出现在 Timeline。
- // 按「方向 + 谓词」分组:实体自身名不再逐行重复,谓词只出现在小节标题里
- const { groups, historicalCount } = useMemo(() => {
+ /* Relations 是一张表,不再分「现行」和「年表」两页:**从这个实体出发 / 指向这个实体**
+ 两节,节里一行一条——左边关系名、右边实体名,与本体页那张同一副(不再按谓词
+ 分二级);按关系名、再按起点排。此刻不成立的(0022 的口径按读出来的区间判)折在
+ 节尾的「N past」里——Wikidata 把历史值留在同一列表里靠结束时间区分,是同一个道理 */
+ const sections = useMemo(() => {
const all = detail.data?.facts ?? [];
const nowIso = new Date().toISOString();
- // 「此刻成立」按读出来的区间判(0022):结束了不知哪天的那条不再混进现行里
- const current = all.filter(
- (f) =>
- (!f.holds_from || f.holds_from <= nowIso) &&
- (!f.holds_to || f.holds_to > nowIso),
- );
- const map = new Map<
- string,
- {
- key: string;
- label: string | null;
- inferred: boolean;
- direction: string;
- rows: EntityFact[];
- }
- >();
- for (const f of current) {
- // 谓词为空的事实归到同一组:它们的共同点就是「说不出是什么关系」
- const k = `${f.direction}:${f.predicate_key ?? ""}`;
- if (!map.has(k))
- map.set(k, {
- key: k,
- label: f.predicate_label,
- inferred: f.inferred,
- direction: f.direction,
- rows: [],
- });
- map.get(k)!.rows.push(f);
- }
- const arr = [...map.values()];
- for (const gr of arr)
- gr.rows.sort((a, b) =>
- (a.valid_from ?? "9999") < (b.valid_from ?? "9999") ? -1 : 1,
- );
- arr.sort(
- (a, b) =>
- b.rows.length - a.rows.length ||
- (a.label ?? "").localeCompare(b.label ?? ""),
- );
- return { groups: arr, historicalCount: all.length - current.length };
+ const current = (f: EntityFact) =>
+ (!f.holds_from || f.holds_from <= nowIso) &&
+ (!f.holds_to || f.holds_to > nowIso);
+ const order = (a: EntityFact, b: EntityFact) =>
+ (a.predicate_label ?? "\uffff").localeCompare(b.predicate_label ?? "\uffff") ||
+ ((a.valid_from ?? "9999") < (b.valid_from ?? "9999") ? -1 : 1);
+ const split = (dir: "out" | "in") => {
+ const mine = all.filter((f) => f.direction === dir);
+ return {
+ rows: mine.filter(current).sort(order),
+ past: mine.filter((f) => !current(f)).sort(order),
+ };
+ };
+ return { out: split("out"), in: split("in") };
}, [detail.data]);
return (
@@ -2842,59 +2775,20 @@ function EntityPanel({
</div>
{editing && e && (
- <div className="px-4 py-3 border-b border-line space-y-3">
- <Field label={S.graph.editName} className="mb-2">
- <Input
- size="sm"
- autoFocus
- value={draftName}
- onChange={(ev) => setDraftName(ev.target.value)}
- onKeyDown={(ev) => {
- if (ev.key === "Enter" && dirty && draftName.trim())
- save.mutate();
- if (ev.key === "Escape") setEditing(false);
- }}
- className="w-full"
- />
- </Field>
- <Field label={S.graph.editType} className="mb-2">
- {/* 类可能上千个(schema.org 一装就是 1010 个):这一格要能打字过滤,
- 所以是 SearchSelect 而不是下拉——下拉是给小而有界的枚举的 */}
- <SearchSelect
- size="sm"
- className="w-full"
- value={draftType}
- onChange={setDraftType}
- options={types.map((t) => ({
- value: t.id,
- label: t.label,
- hint: t.key,
- }))}
- />
- </Field>
- <div className="flex items-center gap-2 pt-1">
- <Button
- variant="primary"
- size="sm"
- disabled={!dirty || !draftName.trim() || save.isPending}
- onClick={() => save.mutate()}
- >
- {S.graph.editSave}
- </Button>
- <Button variant="ghost" size="sm" onClick={() => setEditing(false)}>
- {S.graph.editCancel}
- </Button>
- {!draftName.trim() && (
- <span className="text-fine text-danger">
- {S.graph.editEmptyName}
- </span>
- )}
- </div>
- </div>
+ <EntityDialog
+ kbId={kbId}
+ entityId={entityId}
+ entity={e}
+ onClose={() => setEditing(false)}
+ onSaved={(peers) => {
+ setEditing(false);
+ setSameName(peers);
+ }}
+ />
)}
{/* 同名不是错误——两个张伟可以并存。只提示,判定是不是同一个是人的事 */}
- {sameName.length > 0 && !editing && (
+ {sameName.length > 0 && (
<div className="mx-4 mt-3 rounded-panel border border-line bg-surface px-3 py-2">
<div className="flex items-start justify-between gap-2">
<p className="text-fine text-ink-2">
@@ -2960,13 +2854,13 @@ function EntityPanel({
/>
)}
- {/* 视图切换:Relations(分组)| Timeline(年表) */}
+ {/* 视图切换:Relations(一张表,过去的折在组尾)| History(记录轴)| Derived */}
<div className="px-4 pt-3">
<Segmented
size="sm"
value={view}
onChange={setView}
- options={(["relations", "timeline", "history", "derived"] as const)
+ options={(["relations", "history", "derived"] as const)
// 推出来的那一档:**没有派生就不出现**。一个没开推理的库不该看到
// 一个永远是空的标签页。没落地的也算——那正是这一档要说的事
.filter(
@@ -2977,78 +2871,56 @@ function EntityPanel({
label:
v === "relations"
? S.graph.viewRelations
- : v === "timeline"
- ? S.graph.viewTimeline
- : v === "history"
- ? S.graph.viewHistory
- : S.graph.viewDerived,
+ : v === "history"
+ ? S.graph.viewHistory
+ : S.graph.viewDerived,
}))}
/>
</div>
<div className="u-scroll flex-1 overflow-y-auto px-2 py-2">
- {view === "relations" && historicalCount > 0 && (
- <Button
- variant="ghost"
- size="sm"
- className="mx-2 mb-2 mt-1"
- onClick={() => setView("timeline")}
- >
- {S.graph.historicalNote(historicalCount)}
- </Button>
- )}
{view === "relations" &&
- groups.map((gr) => (
- <div key={gr.key} className="mb-3 last:mb-1">
- <GroupLabel
- className="px-2 pb-1 pt-2"
- icon={
- gr.direction === "in" ? (
- <ArrowLeft size={10} />
- ) : (
- <ArrowRight size={10} />
- )
- }
- count={gr.rows.length > 1 ? gr.rows.length : undefined}
+ (["out", "in"] as const).map((dir) => {
+ const { rows, past } = sections[dir];
+ if (rows.length === 0 && past.length === 0) return null;
+ const name = e?.name ?? "";
+ return (
+ <FactSection
+ key={dir}
+ dir={dir}
+ title={dir === "out" ? S.graph.fromEntity(name) : S.graph.toEntity(name)}
+ count={rows.length + past.length}
>
- <span
- className={
- gr.label === null ? "italic text-ink-2" : undefined
- }
- title={
- gr.label && gr.inferred
- ? S.graph.inferredPredicate
- : undefined
- }
- >
- {gr.label ?? S.graph.unknownPredicate}
- </span>
- </GroupLabel>
- <div>
- {gr.rows.map((f) => (
+ {rows.map((f) => (
<FactRow
key={f.id}
kbId={kbId}
+ dir={dir}
fact={f}
open={openFact === f.id}
- onToggle={() =>
- setOpenFact(openFact === f.id ? null : f.id)
- }
+ onToggle={() => setOpenFact(openFact === f.id ? null : f.id)}
onNavigate={onNavigate}
/>
))}
- </div>
- </div>
- ))}
- {view === "timeline" && (
- <TimelineView
- kbId={kbId}
- facts={detail.data?.facts ?? []}
- openFact={openFact}
- onToggle={(id) => setOpenFact(openFact === id ? null : id)}
- onNavigate={onNavigate}
- />
- )}
+ {past.length > 0 && (
+ <PastFold n={past.length}>
+ {past.map((f) => (
+ <FactRow
+ key={f.id}
+ kbId={kbId}
+ dir={dir}
+ fact={f}
+ past
+ open={openFact === f.id}
+ onToggle={() => setOpenFact(openFact === f.id ? null : f.id)}
+ onNavigate={onNavigate}
+ />
+ ))}
+ </PastFold>
+ )}
+ </FactSection>
+ );
+ })}
{view === "history" && (
<EntityHistory kbId={kbId} entityId={entityId} />
)}
@@ -3135,398 +3007,130 @@ function EntityPanel({
);
}
-/** 年表视图:带区间的事实按起点摊开成竖直时间线;无时间的沉到底部 undated。 */
-function TimelineView({
- kbId,
- facts,
- openFact,
- onToggle,
- onNavigate,
-}: {
- kbId: string;
- facts: EntityFact[];
- openFact: string | null;
- onToggle: (id: string) => void;
- onNavigate: (entityId: string) => void;
-}) {
- const dated = facts
- .filter((f) => f.temporal !== "eternal" && (f.valid_from || f.valid_to))
- .sort((a, b) =>
- (a.valid_from ?? a.valid_to ?? "") < (b.valid_from ?? b.valid_to ?? "")
- ? -1
- : 1,
- );
- const undated = facts.filter((f) => !dated.includes(f));
-
- return (
- <div className="pt-1">
- {/* 与 Relations 同一种行:chevron + 两行头(区间在上,谓词和值在下)。
- 年表的次序靠排序和第一行的区间说话,不另画一条线 */}
- <div>
- {dated.map((f) => (
- <TimelineRow
- key={f.id}
- kbId={kbId}
- fact={f}
- open={openFact === f.id}
- onToggle={() => onToggle(f.id)}
- onNavigate={onNavigate}
- />
- ))}
- {dated.length === 0 && (
- <p className="py-2 text-small text-ink-2">
- {S.graph.timelineEmpty}
- </p>
- )}
- </div>
- {undated.length > 0 && (
- <div className="mt-3">
- <GroupLabel className="px-2 pb-1">{S.graph.undated}</GroupLabel>
- {undated.map((f) => (
- <FactRow
- key={f.id}
- kbId={kbId}
- fact={f}
- open={openFact === f.id}
- onToggle={() => onToggle(f.id)}
- onNavigate={onNavigate}
- />
- ))}
- </div>
- )}
- </div>
- );
+/** 字面值宾语的显示:属性 {value,unit} / 问数映射 {summary} / 其他 JSON 兜底。 */
+function fmtObjectValue(v: Record<string, unknown> | null): string | null {
+ if (!v) return null;
+ if (v.value !== undefined) {
+ const val =
+ typeof v.value === "boolean" ? (v.value ? "✓" : "✗") : String(v.value);
+ return typeof v.unit === "string" && v.unit ? `${val} ${v.unit}` : val;
+ }
+ if (typeof v.summary === "string") return v.summary;
+ return JSON.stringify(v);
}
-/** 年表条目:区间 + 闭合方式标记 + 开放事实的最后确认时间;点击展开证据。 */
-function TimelineRow({
- kbId,
- fact,
- open,
- onToggle,
- onNavigate,
+/** 一节(从这个实体出发 / 指向这个实体):可折叠——折叠柄占图标格,正文缩进同样的 24,
+ * 于是每一行的方向箭头正好落在节标题的箭头底下(本体页 Relations 的组同一副) */
+function FactSection({
+ dir,
+ title,
+ count,
+ children,
}: {
- kbId: string;
- fact: EntityFact;
- open: boolean;
- onToggle: () => void;
- onNavigate: (entityId: string) => void;
+ dir: "out" | "in";
+ title: string;
+ count: number;
+ children: ReactNode;
}) {
- const interval = fmtInterval(fact);
- const isOpenEnded = !fact.valid_to;
- const literal = fmtObjectValue(fact.object_value);
- const [editing, setEditing] = useState(false);
+ const [open, setOpen] = useState(true);
return (
- <ExpandCard
- open={open}
- onToggle={onToggle}
- dim={fact.stale}
- title={fact.stale ? S.graph.staleFactHint : undefined}
- header={
- <>
- <div className="flex items-center gap-2 u-num text-fine text-ink-2">
- {interval || "—"}
- {fact.corrected && (
- <span className="text-ink-2" title={S.graph.correctedHint}>
- ⟲
- </span>
- )}
- <span className="ml-auto flex items-center gap-2">
- {isOpenEnded && fact.last_evidence_time && (
- <span className="text-ink-2">
- {S.graph.lastConfirmed(localDate(fact.last_evidence_time))}
- </span>
- )}
- {/* 这一档只有断言事实:派生的区间是算出来的,走 Derived 那条路径,
- 改了下一轮推理也会覆盖(服务端另有 derived_by_rule 的防线) */}
- <span
- role="button"
- tabIndex={0}
- title={S.graph.editTime}
- aria-label={S.graph.editTime}
- onClick={(ev) => {
- ev.stopPropagation();
- setEditing((v) => !v);
- }}
- onKeyDown={(ev) => {
- if (ev.key === "Enter" || ev.key === " ") {
- ev.preventDefault();
- ev.stopPropagation();
- setEditing((v) => !v);
- }
- }}
- className={cn(REVEAL, "cursor-pointer rounded-cell p-1", editing && "is-on")}
- >
- <Pencil size={10} />
- </span>
+ <div className="mb-2">
+ <Row
+ className="mt-1"
+ icon={
+ <span className="flex w-4 justify-center">
+ <ChevronRight size={12} className={cn("u-turn", open && "rotate-90")} />
</span>
- </div>
- <div className="mt-1 flex items-center gap-2 text-body text-ink">
- <span className="text-ink-2 text-small">
- {fact.direction === "in" ? "←" : "→"}{" "}
- <span
- className={
- fact.predicate_label === null
- ? "italic text-ink-2"
- : undefined
- }
- title={
- fact.predicate_label && fact.inferred
- ? S.graph.inferredPredicate
- : undefined
- }
- >
- {fact.predicate_label ?? S.graph.unknownPredicate}
- </span>
- </span>
- {fact.other_id ? (
- <span
- role="link"
- tabIndex={0}
- onClick={(ev) => {
- ev.stopPropagation();
- onNavigate(fact.other_id!);
- }}
- onKeyDown={(ev) => {
- if (ev.key === "Enter") {
- ev.stopPropagation();
- onNavigate(fact.other_id!);
- }
- }}
- className="u-inline-link truncate"
- >
- {fact.other_name ?? "?"}
- </span>
- ) : (
- <span className="truncate">
- {fact.other_name ?? literal ?? "?"}
- </span>
- )}
- {fact.stale && (
- <span className="u-chip u-chip-neutral shrink-0 !text-fine !px-2">
- {S.graph.staleFactChip}
- </span>
- )}
- {fact.contested && (
- <ContestedChip kbId={kbId} c={fact.contested} />
- )}
- </div>
- </>
- }
- >
- {editing && (
- <TimeEditor
- kbId={kbId}
- fact={fact}
- onDone={() => setEditing(false)}
- />
- )}
- {open && <EvidenceList kbId={kbId} fact={fact} />}
- </ExpandCard>
+ }
+ onClick={() => setOpen((v) => !v)}
+ >
+ <span className="flex items-center gap-2 text-small font-medium">
+ {dir === "out" ? <ArrowRight size={10} /> : <ArrowLeft size={10} />}
+ <span className="truncate">{title}</span>
+ <span className="u-num">{count}</span>
+ </span>
+ </Row>
+ {open && <div className="pl-6">{children}</div>}
+ </div>
);
}
-/** 有效区间的人工修正表单(302)。
- *
- * 两端一起提交而不是逐端改:区间的两端互相定义,「清空结束端」与「这次不动
- * 结束端」得能分辨。结束端的三个选项与账本里的三种写法一一对应,所以这里
- * 没有「留空即至今」这种隐含约定——那正是 valid_to IS NULL 一度承载两个意思
- * 的老毛病。 */
-function TimeEditor({
- kbId,
- fact,
- onDone,
-}: {
- kbId: string;
- fact: EntityFact;
- onDone: () => void;
-}) {
- const qc = useQueryClient();
- const [from, setFrom] = useState(
- fmtTime(fact.valid_from, fact.valid_from_precision) ?? "",
- );
- const [to, setTo] = useState(
- fmtTime(fact.valid_to, fact.valid_to_precision) ?? "",
- );
- const [endMode, setEndMode] = useState<"open" | "unknown" | "date">(
- fact.valid_to
- ? "date"
- : fact.valid_to_precision === "unknown"
- ? "unknown"
- : "open",
- );
- const [note, setNote] = useState("");
-
- const save = useMutation({
- mutationFn: () => {
- const f = from.trim() ? parseDateInput(from) : null;
- if (from.trim() && !f) throw new Error(S.graph.timeBadDate);
- const t = endMode === "date" ? parseDateInput(to) : null;
- if (endMode === "date" && !t) throw new Error(S.graph.timeBadDate);
- return api.updateFactTime(kbId, fact.id, {
- valid_from: f?.iso ?? null,
- valid_from_precision: f?.precision ?? null,
- valid_to: t?.iso ?? null,
- valid_to_precision:
- endMode === "date"
- ? (t?.precision ?? null)
- : endMode === "unknown"
- ? "unknown"
- : null,
- note: note.trim() || undefined,
- });
- },
- onSuccess: (r) => {
- // 对账的后果要说出来:改了起点可能顺手闭合了继任者的开放区间,
- // 也可能撞出一条需要人裁的冲突。不说的话图会自己变而没人知道为什么
- if (r.conflicts) toast.success(S.graph.timeSavedConflicts(r.conflicts));
- else if (r.closed) toast.success(S.graph.timeSavedClosed(r.closed));
- else toast.success(S.graph.timeSaved);
- qc.invalidateQueries({ queryKey: ["entity", kbId] });
- qc.invalidateQueries({ queryKey: ["graph"] });
- qc.invalidateQueries({ queryKey: ["review", kbId] });
- onDone();
- },
- onError: (e: Error) => toast.error(e.message),
- });
-
+/** 已结束的留在同一节里,折起来:默认看现行的,要看来路展开它 */
+function PastFold({ n, children }: { n: number; children: ReactNode }) {
+ const [open, setOpen] = useState(false);
return (
- <div
- className="mb-2 rounded-panel border border-line bg-surface p-3"
- onClick={(ev) => ev.stopPropagation()}
- >
- <div className="flex items-center gap-2">
- <label className="w-11 shrink-0 text-small font-medium text-ink-2">
- {S.graph.timeStart}
- </label>
- <Input
- value={from}
- onChange={(e) => setFrom(e.target.value)}
- placeholder={S.graph.timeFormat}
- size="sm"
- className="u-num flex-1"
- />
- </div>
- <div className="mt-2 flex items-start gap-2">
- <label className="w-11 shrink-0 pt-1 text-small font-medium text-ink-2">
- {S.graph.timeEnd}
- </label>
- <div className="flex-1 space-y-1">
- {(
- [
- ["open", S.graph.timeEndOpen],
- ["unknown", S.graph.timeEndUnknown],
- ["date", S.graph.timeEndDate],
- ] as const
- ).map(([mode, label]) => (
- <Radio
- key={mode}
- name={`end-${fact.id}`}
- checked={endMode === mode}
- onChange={() => setEndMode(mode)}
- label={label}
- >
- {mode === "date" && endMode === "date" && (
- <Input
- size="sm"
- value={to}
- onChange={(e) => setTo(e.target.value)}
- placeholder={S.graph.timeFormat}
- className="u-num ml-1 flex-1"
- />
- )}
- </Radio>
- ))}
- </div>
- </div>
- <div className="mt-2 flex items-center gap-2">
- <label className="w-11 shrink-0 text-small font-medium text-ink-2">
- {S.graph.timeNote}
- </label>
- <Input
- value={note}
- onChange={(e) => setNote(e.target.value)}
- placeholder={S.graph.timeNotePlaceholder}
- size="sm"
- className="flex-1"
- />
- </div>
- <div className="mt-2 flex justify-end gap-2">
- <Button size="sm" variant="secondary" onClick={onDone}>
- {S.graph.timeCancel}
- </Button>
- <Button variant="primary"
- size="sm"
- onClick={() => save.mutate()}
- disabled={save.isPending}
- >
- {S.graph.timeSave}
- </Button>
- </div>
- </div>
+ <>
+ <Row
+ icon={
+ <span className="flex w-4 justify-center">
+ <ChevronRight size={12} className={cn("u-turn", open && "rotate-90")} />
+ </span>
+ }
+ onClick={() => setOpen((v) => !v)}
+ >
+ <span className="text-small">{S.graph.past(n)}</span>
+ </Row>
+ {open && <div className="pl-6">{children}</div>}
+ </>
);
}
-/** 字面值宾语的显示:属性 {value,unit} / 问数映射 {summary} / 其他 JSON 兜底。 */
-function fmtObjectValue(v: Record<string, unknown> | null): string | null {
- if (!v) return null;
- if (v.value !== undefined) {
- const val =
- typeof v.value === "boolean" ? (v.value ? "✓" : "✗") : String(v.value);
- return typeof v.unit === "string" && v.unit ? `${val} ${v.unit}` : val;
- }
- if (typeof v.summary === "string") return v.summary;
- return JSON.stringify(v);
-}
-
+/** 一条事实是一行,与本体页 Relations 的行同一副:图标格里是方向箭头,左边关系名
+ * (和 disputed 之类的标记),右边那个实体的名字(区间的小字在名字前);整行点了
+ * 跳到那个实体。指着这一行才露出「N sources」(在行下摊开证据)与铅笔(区间修正
+ * 弹窗)。行首没有折叠柄——折叠柄在这块面板上只属于节与「过去」的折 */
function FactRow({
kbId,
+ dir,
fact,
+ past,
open,
onToggle,
onNavigate,
}: {
kbId: string;
+ dir: "out" | "in";
fact: EntityFact;
+ /** 已结束的那些:压淡 */
+ past?: boolean;
open: boolean;
onToggle: () => void;
onNavigate: (entityId: string) => void;
}) {
+ const [editing, setEditing] = useState(false);
const interval = fmtInterval(fact);
// 与 Review 的低置信口径一致:只有低到需要怀疑才挂 chip,常规置信保持沉默
const lowConfidence = fact.confidence < 0.75;
+ const go = fact.other_id ? () => onNavigate(fact.other_id!) : undefined;
return (
- <ExpandCard
- open={open}
- onToggle={onToggle}
- dim={fact.stale}
+ <div
+ className={cn((fact.stale || past) && "opacity-55")}
title={fact.stale ? S.graph.staleFactHint : undefined}
- header={
- <div className="flex items-center gap-2">
- {fact.other_id ? (
- <span
- role="link"
- tabIndex={0}
- onClick={(ev) => {
- ev.stopPropagation();
- onNavigate(fact.other_id!);
- }}
- onKeyDown={(ev) => {
- if (ev.key === "Enter") {
- ev.stopPropagation();
- onNavigate(fact.other_id!);
- }
- }}
- className="u-inline-link truncate text-body text-ink"
- >
- {fact.other_name ?? "?"}
- </span>
- ) : (
- <span className="truncate text-body text-ink">
- {fact.other_name ?? fmtObjectValue(fact.object_value) ?? "?"}
- </span>
- )}
+ >
+ <div
+ role={go ? "link" : undefined}
+ tabIndex={go ? 0 : undefined}
+ onClick={go}
+ onKeyDown={(ev) => {
+ if (go && ev.key === "Enter") go();
+ }}
+ className={cn(HOVER_ROW, go && "cursor-pointer")}
+ >
+ <span className="shrink-0 text-violet">
+ {dir === "out" ? <ArrowRight size={12} /> : <ArrowLeft size={12} />}
+ </span>
+ <span
+ className={cn(
+ "truncate text-body text-ink",
+ fact.predicate_label === null && "italic text-ink-2",
+ )}
+ title={
+ fact.predicate_label && fact.inferred ? S.graph.inferredPredicate : undefined
+ }
+ >
+ {fact.predicate_label ?? S.graph.unknownPredicate}
+ </span>
{lowConfidence && (
<span className="shrink-0 u-num u-meta-warn text-fine">
{Math.round(fact.confidence * 100)}%
@@ -3538,20 +3142,65 @@ function FactRow({
</span>
)}
{fact.contested && <ContestedChip kbId={kbId} c={fact.contested} />}
- {interval && (
- <span className="ml-auto shrink-0 pl-2 u-num text-fine text-ink-2">
- {interval}
+ {fact.corrected && (
+ <span className="shrink-0 text-fine text-ink-2" title={S.graph.correctedHint}>
+ ⟲
</span>
)}
+ <span className="ml-auto flex min-w-0 shrink-0 items-center gap-2 pl-2">
+ {interval && (
+ <span className="u-num text-fine text-ink-2">{interval}</span>
+ )}
+ <span className={cn(ROW_TRAILING, "max-w-40 truncate")}>
+ {fact.other_name ?? fmtObjectValue(fact.object_value) ?? "?"}
+ </span>
+ {fact.evidence_count > 0 && (
+ <LinkButton
+ className={cn(REVEAL, "text-fine", open && "is-on")}
+ onClick={(ev) => {
+ ev.stopPropagation();
+ onToggle();
+ }}
+ >
+ {S.graph.sources(fact.evidence_count)}
+ </LinkButton>
+ )}
+ {/* 这一档只有断言事实:派生的区间是算出来的,走 Derived 那条路径 */}
+ <span
+ role="button"
+ tabIndex={0}
+ title={S.graph.editTime}
+ aria-label={S.graph.editTime}
+ onClick={(ev) => {
+ ev.stopPropagation();
+ setEditing(true);
+ }}
+ onKeyDown={(ev) => {
+ if (ev.key === "Enter" || ev.key === " ") {
+ ev.preventDefault();
+ ev.stopPropagation();
+ setEditing(true);
+ }
+ }}
+ className={cn(REVEAL, "cursor-pointer rounded-cell p-1 text-ink-2")}
+ >
+ <Pencil size={10} />
+ </span>
+ </span>
+ </div>
+ {open && (
+ <div className="pb-2 pl-2 pr-2">
+ <EvidenceList kbId={kbId} fact={fact} />
</div>
- }
- >
- {open && <EvidenceList kbId={kbId} fact={fact} />}
- </ExpandCard>
+ )}
+ {editing && (
+ <FactTimeDialog kbId={kbId} fact={fact} onClose={() => setEditing(false)} />
+ )}
+ </div>
);
}
-/** 证据展开区(FactRow 与 TimelineRow 共用):quote + 跳原文 + 版本角标 + 置信。 */
+/** 证据展开区(FactRow 在行下摊开):quote + 跳原文 + 版本角标 + 置信。 */
function EvidenceList({ kbId, fact }: { kbId: string; fact: EntityFact }) {
const evidence = useQuery({
queryKey: ["evidence", fact.id],
diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsx
index ef257bdd..73b8d1fe 100644
--- a/web/src/pages/KbSettings.tsx
+++ b/web/src/pages/KbSettings.tsx
@@ -180,8 +180,8 @@ export function KbSettings() {
{ key: "general", label: S.kbset.general, Icon: Settings2 },
{ key: "members", label: S.kbset.members, Icon: Users },
{ key: "activity", label: S.kbset.activity, Icon: HistoryIcon },
- // 默认库不可删除:danger 节整个不出现。入口用警示色:这一条只是去往危险区,
- // 真正删库的那个按钮才是危险色
+ // 默认库不可删除:danger 节整个不出现。入口只把图标染成警示色,文字与别的
+ // 节一样:这一条只是去往危险区,真正删库的那个按钮才是危险色
...(isDefault
? []
: [
@@ -203,8 +203,7 @@ export function KbSettings() {
key={key}
density="nav"
active={section === key}
- tone={tone}
- icon={<Icon size={14} />}
+ icon={<Icon size={14} className={tone === "warn" ? "text-warn" : undefined} />}
onClick={() => setSection(key)}
>
{label}
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index ab0ae083..33b26b11 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -1,6 +1,7 @@
// 本体编辑器:master-detail 双栏(与 Library 的 SourcesRail 同构)。
// 左栏 = filter + Classes/Properties 两小节 + 底部 Unmatched 入口;
-// 右侧 = 选中项的表单 / 未匹配信号面板 / 概览。
+// 右侧 = 选中项的详情面板(只展示;建、改、删、连都在弹窗里,见 ontologyDialogs)
+// / 未匹配信号面板 / 概览。
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate } from "@tanstack/react-router";
@@ -9,8 +10,10 @@ import {
ArrowRight,
ChevronRight,
Inbox,
+ Link2,
Scale,
Network,
+ Pencil,
Plus,
Search,
Split,
@@ -35,28 +38,27 @@ import { useKb } from "../kb";
import { toast } from "../toast";
import { OntologySchemaGraph, type SchemaSelection } from "./OntologySchemaGraph";
import { RulesPanel } from "./RulesPanel";
+import {
+ AttributeDialog,
+ ClassDialog,
+ ConnectDialog,
+ PropertyDialog,
+} from "./ontologyDialogs";
import {
Button,
- Checkbox,
Chip,
- ColorPicker,
- colorForKey,
DangerConfirm,
Disclosure,
- Dropdown,
IconButton,
Input,
Loading,
- MultiSearchSelect,
Pager,
RailItem,
Row,
ROW_TRAILING,
rowClass,
Segmented,
- Textarea,
RAIL_CLS,
- SearchSelect,
cn,
pageSlice,
GroupLabel,
@@ -73,18 +75,15 @@ const RAIL_PAGE_MIXED = 6;
/** 右侧详情区当前展示什么。
*
- * class / relation / new-class / new-relation / schema / null 这一组共享
- * 同一块工作区:模式图常驻做背景,表单(如果有)停靠在右侧——左栏点一个
- * 类名、画布上点一个节点、模式图自己的搜索框选中一个关系,三条路径落到
- * 的是同一个 `sel`,因此也落到同一份表单,不必再各画一遍。
+ * class / relation / schema / null 这一组共享同一块工作区:模式图常驻做
+ * 背景,详情面板停靠在右侧——左栏点一个类名、画布上点一个节点、模式图
+ * 自己的搜索框选中一个关系,三条路径落到的是同一个 `sel`,因此也落到同一
+ * 块面板,不必再各画一遍。面板只展示;改动在 `Edit` 的弹窗里。
* import / refine / misses 仍是独立的整页视图:那三个不是「关于某个类
* 或关系」的事,跟模式图没有共同的背景可言。 */
type Sel =
| { kind: "class"; id: string }
| { kind: "relation"; id: string }
- | { kind: "new-class"; parentId: string | null }
- // 从模式图上一个类发起「新建关系」时带上它的 id,表单里 domain 预填成它
- | { kind: "new-relation"; initialDomain?: string | null }
| { kind: "misses" }
| { kind: "uniqueness" }
// 类型消解:把「大致对」的类换成更具体的那个
@@ -95,18 +94,28 @@ type Sel =
| { kind: "schema" }
| null;
-/** 这次选中会不会在模式图右侧停靠一张表单 */
-const onPanel = (s: Sel) =>
- s?.kind === "class" ||
- s?.kind === "relation" ||
- s?.kind === "new-class" ||
- s?.kind === "new-relation";
+/** 这次选中会不会在模式图右侧停靠一块面板 */
+const onPanel = (s: Sel) => s?.kind === "class" || s?.kind === "relation";
+
+/** 打开着的编辑弹窗。面板只展示;建、改、删、连都在弹窗里发生 */
+type Edit =
+ | { kind: "class"; existing: EntityTypeView | null; parentId: string | null }
+ | {
+ kind: "property";
+ existing: RelationTypeView | null;
+ // 从一个类出发新建关系时带上它的 id,domain 预填成它
+ initialDomain: string | null;
+ }
+ | { kind: "attribute"; typeId: string; existing: RelationTypeView | null }
+ | { kind: "connect"; cls: EntityTypeView }
+ | null;
export function Ontology() {
const { kb } = useKb();
const queryClient = useQueryClient();
const navigate = useNavigate();
const [sel, setSel] = useState<Sel>(null);
+ const [edit, setEdit] = useState<Edit>(null);
const [railTab, setRailTab] = useState<"classes" | "properties">("classes");
// 模式图详情面板停在哪一段。**跨选中保留**:在实例上挨个类看下去,
// 是一种真实的读法,每换一个类就被弹回定义页会打断它
@@ -214,8 +223,6 @@ export function Ontology() {
(r) => r.kind === "attribute" && r.domains.includes(selectedClass.id),
)
: [];
- // 新建的类还没有关系也没有实例,只剩定义这一段
- const classTab = selectedClass ? panelTab : "definition";
return (
<div className="h-full flex">
@@ -269,9 +276,11 @@ export function Ontology() {
className="mb-1"
icon={<Plus size={14} />}
onClick={() =>
- railTab === "classes"
- ? setSel({ kind: "new-class", parentId: null })
- : setSel({ kind: "new-relation" })
+ setEdit(
+ railTab === "classes"
+ ? { kind: "class", existing: null, parentId: null }
+ : { kind: "property", existing: null, initialDomain: null },
+ )
}
>
{railTab === "classes"
@@ -450,169 +459,211 @@ export function Ontology() {
// 退场动画,而点画布正是最常用的那种关法
onSelect={(next) => (next ? setSel(next) : closePanel())}
/>
- {(panelSel?.kind === "new-class" || selectedClass) && (
+ {selectedClass && (
<DockedPanel
onClose={closePanel}
exiting={!onPanel(sel)}
+ actions={
+ <IconButton
+ size="sm"
+ label={S.ontology.editClass}
+ onClick={() =>
+ setEdit({
+ kind: "class",
+ existing: selectedClass,
+ parentId: selectedClass.primary_parent ?? null,
+ })
+ }
+ >
+ <Pencil size={13} />
+ </IconButton>
+ }
header={
<PanelHeader
- color={selectedClass?.color}
- square={selectedClass?.shape === "square"}
- title={selectedClass?.label ?? S.ontology.newClass}
- sub={
- selectedClass
- ? `${selectedClass.key} · ${S.ontology.usage(selectedClass.usage)}`
- : undefined
- }
- builtin={selectedClass?.builtin}
+ color={selectedClass.color}
+ square={selectedClass.shape === "square"}
+ title={selectedClass.label}
+ sub={`${selectedClass.key} · ${S.ontology.usage(selectedClass.usage)}`}
+ builtin={selectedClass.builtin}
/>
}
tabs={
- selectedClass && (
- <Segmented
- fill
- size="sm"
- value={classTab}
- onChange={setPanelTab}
- options={[
- {
- value: "definition",
- label: S.ontology.schemaTabDefinition,
- },
- {
- value: "relations",
- label: S.ontology.schemaTabRelations,
- },
- {
- value: "attributes",
- label: S.ontology.schemaTabAttributes,
- },
- {
- value: "instances",
- label: S.ontology.schemaTabInstances,
- },
- ]}
- />
- )
+ <Segmented
+ fill
+ size="sm"
+ value={panelTab}
+ onChange={setPanelTab}
+ options={[
+ {
+ value: "definition",
+ label: S.ontology.schemaTabDefinition,
+ },
+ {
+ value: "relations",
+ label: S.ontology.schemaTabRelations,
+ },
+ {
+ value: "attributes",
+ label: S.ontology.schemaTabAttributes,
+ },
+ {
+ value: "instances",
+ label: S.ontology.schemaTabInstances,
+ },
+ ]}
+ />
}
>
- {/* 三段用 hidden 藏,不卸载:表单里改了一半的字段、实例列表翻到的
- 第几页,都该在切回来的时候还在 */}
- <div className={classTab === "definition" ? "" : "hidden"}>
- <ClassForm
- key={
- selectedClass?.id ??
- `new-${panelSel?.kind === "new-class" ? panelSel.parentId : "root"}`
- }
- kbId={kb.id}
- existing={selectedClass}
- parentId={
- panelSel?.kind === "new-class"
- ? panelSel.parentId
- : (selectedClass?.primary_parent ?? null)
+ {/* 四段用 hidden 藏,不卸载:实例列表翻到的第几页,切回来的时候还在 */}
+ <div className={panelTab === "definition" ? "" : "hidden"}>
+ <ClassDefinition
+ cls={selectedClass}
+ allTypes={entity_types}
+ onNewSub={() =>
+ setEdit({ kind: "class", existing: null, parentId: selectedClass.id })
}
+ />
+ </div>
+ <div className={panelTab === "relations" ? "" : "hidden"}>
+ <RelationshipsCard
+ cls={selectedClass}
+ relations={relations}
allTypes={entity_types}
- headless
- onNewSub={
- selectedClass
- ? () =>
- setSel({
- kind: "new-class",
- parentId: selectedClass.id,
- })
- : undefined
+ onSelect={(id) => setSel({ kind: "relation", id })}
+ onConnect={() => setEdit({ kind: "connect", cls: selectedClass })}
+ onAddNew={() =>
+ setEdit({
+ kind: "property",
+ existing: null,
+ initialDomain: selectedClass.id,
+ })
}
- onDone={(createdId) => {
- // 新建成功即选中它:立刻能看到、能继续编辑
- if (sel?.kind === "new-class")
- setSel(
- createdId
- ? { kind: "class", id: createdId }
- : { kind: "schema" },
- );
- afterOntologyChange();
- }}
- onError={onError}
/>
</div>
- {selectedClass && (
- <>
- <div className={classTab === "relations" ? "" : "hidden"}>
- <RelationshipsCard
- kbId={kb.id}
- cls={selectedClass}
- relations={relations}
- allTypes={entity_types}
- onChanged={afterOntologyChange}
- onError={onError}
- onSelect={(id) => setSel({ kind: "relation", id })}
- onAddNew={() =>
- setSel({
- kind: "new-relation",
- initialDomain: selectedClass.id,
- })
- }
- />
- </div>
- <div className={classTab === "attributes" ? "" : "hidden"}>
- <AttributesCard
- kbId={kb.id}
- type={selectedClass}
- attributes={classAttributes}
- onChanged={afterOntologyChange}
- onError={onError}
- />
- </div>
- <div className={classTab === "instances" ? "" : "hidden"}>
- <InstancesCard kbId={kb.id} type={selectedClass} />
- </div>
- </>
- )}
+ <div className={panelTab === "attributes" ? "" : "hidden"}>
+ <AttributesCard
+ attributes={classAttributes}
+ onEdit={(a) =>
+ setEdit({ kind: "attribute", typeId: selectedClass.id, existing: a })
+ }
+ onNew={() =>
+ setEdit({ kind: "attribute", typeId: selectedClass.id, existing: null })
+ }
+ />
+ </div>
+ <div className={panelTab === "instances" ? "" : "hidden"}>
+ <InstancesCard kbId={kb.id} type={selectedClass} />
+ </div>
</DockedPanel>
)}
- {(panelSel?.kind === "new-relation" || selectedProp) && (
+ {selectedProp && (
<DockedPanel
onClose={closePanel}
exiting={!onPanel(sel)}
+ actions={
+ <IconButton
+ size="sm"
+ label={S.ontology.editProperty}
+ onClick={() =>
+ setEdit({ kind: "property", existing: selectedProp, initialDomain: null })
+ }
+ >
+ <Pencil size={13} />
+ </IconButton>
+ }
header={
<PanelHeader
- title={selectedProp?.label ?? S.ontology.newProperty}
- sub={
- selectedProp
- ? S.ontology.usage(selectedProp.usage)
- : undefined
- }
- builtin={selectedProp?.builtin}
+ title={selectedProp.label}
+ sub={`${selectedProp.key} · ${S.ontology.usage(selectedProp.usage)}`}
+ builtin={selectedProp.builtin}
/>
}
>
- <div>
- <PropertyForm
- key={selectedProp?.id ?? "new"}
- kbId={kb.id}
- existing={selectedProp}
- allTypes={entity_types}
- allRelations={relations}
- initialDomain={
- panelSel?.kind === "new-relation" ? panelSel.initialDomain : null
- }
- headless
- onDone={(createdId) => {
- if (sel?.kind === "new-relation")
- setSel(
- createdId
- ? { kind: "relation", id: createdId }
- : { kind: "schema" },
- );
- afterOntologyChange();
- }}
- onError={onError}
- />
- </div>
+ <PropertyDefinition
+ rel={selectedProp}
+ allTypes={entity_types}
+ allRelations={relations}
+ />
</DockedPanel>
)}
</div>
)}
+
+ {/* 编辑弹窗:面板只展示,建、改、删、连都在这里发生。建成的立刻选中——
+ 能看到、能接着改;删掉的把面板收起来 */}
+ {edit?.kind === "class" && (
+ <ClassDialog
+ kbId={kb.id}
+ existing={edit.existing}
+ parentId={edit.parentId}
+ allTypes={entity_types}
+ onClose={() => setEdit(null)}
+ onSaved={(createdId) => {
+ setEdit(null);
+ if (createdId) setSel({ kind: "class", id: createdId });
+ afterOntologyChange();
+ }}
+ onDeleted={() => {
+ setEdit(null);
+ closePanel();
+ afterOntologyChange();
+ }}
+ onError={onError}
+ />
+ )}
+ {edit?.kind === "property" && (
+ <PropertyDialog
+ kbId={kb.id}
+ existing={edit.existing}
+ allTypes={entity_types}
+ allRelations={relations}
+ initialDomain={edit.initialDomain}
+ onClose={() => setEdit(null)}
+ onSaved={(createdId) => {
+ setEdit(null);
+ if (createdId) setSel({ kind: "relation", id: createdId });
+ afterOntologyChange();
+ }}
+ onDeleted={() => {
+ setEdit(null);
+ closePanel();
+ afterOntologyChange();
+ }}
+ onError={onError}
+ />
+ )}
+ {edit?.kind === "attribute" && (
+ <AttributeDialog
+ kbId={kb.id}
+ typeId={edit.typeId}
+ existing={edit.existing}
+ onClose={() => setEdit(null)}
+ onSaved={() => {
+ setEdit(null);
+ afterOntologyChange();
+ }}
+ onDeleted={() => {
+ setEdit(null);
+ afterOntologyChange();
+ }}
+ onError={onError}
+ />
+ )}
+ {edit?.kind === "connect" && (
+ <ConnectDialog
+ kbId={kb.id}
+ cls={edit.cls}
+ relations={relations}
+ onClose={() => setEdit(null)}
+ onConnected={(id) => {
+ setEdit(null);
+ afterOntologyChange();
+ // 连完直接跳到那条关系:域/值域改没改、改对了没有,一眼可见
+ setSel({ kind: "relation", id });
+ }}
+ onError={onError}
+ />
+ )}
</div>
);
}
@@ -632,12 +683,15 @@ export function Ontology() {
function DockedPanel({
header,
+ actions,
tabs,
exiting,
onClose,
children,
}: {
header: React.ReactNode;
+ /** 关闭键左边的动作(编辑):面板只展示,改动从这里开弹窗 */
+ actions?: React.ReactNode;
/** 分段控件,跟着标题一起固定在顶上——它要能一直点得到 */
tabs?: React.ReactNode;
/** 正在退场:演动画,期间不再接受点击(u-dock-out 里带了 pointer-events) */
@@ -653,14 +707,12 @@ function DockedPanel({
>
<div className="shrink-0 flex items-start justify-between gap-2 px-4 py-4 border-b border-line">
<div className="min-w-0">{header}</div>
- <IconButton
- size="sm"
- label={S.ontology.schemaClosePanel}
- className="-mr-1 -mt-1"
- onClick={onClose}
- >
- <X size={15} />
- </IconButton>
+ <div className="-mr-1 -mt-1 flex shrink-0 items-center gap-1">
+ {actions}
+ <IconButton size="sm" label={S.ontology.schemaClosePanel} onClick={onClose}>
+ <X size={15} />
+ </IconButton>
+ </div>
</div>
{tabs && <div className="shrink-0 px-4 pt-3 pb-1">{tabs}</div>}
<div className="u-scroll flex-1 min-h-0 overflow-y-auto flex flex-col gap-3 px-4 py-3">
@@ -761,23 +813,20 @@ function InstancesCard({ kbId, type }: { kbId: string; type: EntityTypeView }) {
* 走的是 PropertyForm 保存时同一个 updateRelationType,只是把「打开表单、
* 找到多选框、加一个类」压缩成一步。 */
function RelationshipsCard({
- kbId,
cls,
relations,
allTypes,
- onChanged,
- onError,
onSelect,
+ onConnect,
onAddNew,
}: {
- kbId: string;
cls: EntityTypeView;
/** kind === "relation" 的那些——attribute 的宾语是字面值,谈不上「连着」 */
relations: RelationTypeView[];
allTypes: EntityTypeView[];
- onChanged: () => void;
- onError: (e: unknown) => void;
onSelect: (relationId: string) => void;
+ /** 用一个已有的关系连接这个类:开弹窗 */
+ onConnect: () => void;
onAddNew: () => void;
}) {
const labelOf = (id: string) =>
@@ -786,53 +835,47 @@ function RelationshipsCard({
const outgoing = relations.filter((r) => r.domains.includes(cls.id));
const incoming = relations.filter((r) => r.ranges.includes(cls.id));
- const [connectId, setConnectId] = useState("");
- const [connectSide, setConnectSide] = useState<"domain" | "range">("domain");
- useEffect(() => {
- setConnectId("");
- }, [cls.id]);
-
- const connect = useMutation({
- mutationFn: () => {
- const rel = relations.find((r) => r.id === connectId);
- if (!rel) return Promise.reject(new Error("relation not found"));
- // 只加不减:已经连着的那一侧原样保留,另一侧才可能被追加。
- // Set 去重——挑到已经连过的关系时这是个无害的空操作,不必先禁用按钮
- const domains =
- connectSide === "domain"
- ? [...new Set([...rel.domains, cls.id])]
- : rel.domains;
- const ranges =
- connectSide === "range"
- ? [...new Set([...rel.ranges, cls.id])]
- : rel.ranges;
- return api.updateRelationType(kbId, rel.id, {
- label: rel.label,
- temporal: rel.temporal,
- functional: rel.functional,
- inverse_functional: rel.inverse_functional,
- is_transitive: rel.is_transitive,
- is_symmetric: rel.is_symmetric,
- is_asymmetric: rel.is_asymmetric,
- is_irreflexive: rel.is_irreflexive,
- inverse_of: rel.inverse_of,
- sub_property_of: rel.sub_property_of,
- description: rel.description,
- domains,
- ranges,
- });
- },
- onSuccess: () => {
- const rel = relations.find((r) => r.id === connectId);
- toast.success(S.ontology.schemaConnected(rel?.label ?? ""));
- const id = connectId;
- setConnectId("");
- onChanged();
- // 连完直接跳到那条关系:域/值域改没改、改对了没有,一眼可见
- onSelect(id);
- },
- onError,
- });
+ /** 一组可折叠(#455 的解剖:折叠柄、头、缩进的正文)。缺省展开——
+ * 折起来是为了在长列表里跳过一段,不是为了藏 */
+ const Group = ({
+ dir,
+ rows,
+ }: {
+ dir: "out" | "in";
+ rows: RelationTypeView[];
+ }) => {
+ const [open, setOpen] = useState(true);
+ return (
+ <div>
+ {/* 头是一行 Row:折叠柄占图标格(16 宽),正文缩进同样的 24,
+ 于是下面每一行的方向箭头正好落在组标题的箭头底下 */}
+ <Row
+ className="-mx-2 mt-1"
+ icon={
+ <span className="flex w-4 justify-center">
+ <ChevronRight size={12} className={cn("u-turn", open && "rotate-90")} />
+ </span>
+ }
+ onClick={() => setOpen((v) => !v)}
+ >
+ <span className="flex items-center gap-2 text-small font-medium">
+ {dir === "out" ? <ArrowRight size={10} /> : <ArrowLeft size={10} />}
+ <span className="truncate">
+ {dir === "out" ? S.ontology.schemaOutgoing : S.ontology.schemaIncoming}
+ </span>
+ {rows.length > 1 && <span className="u-num">{rows.length}</span>}
+ </span>
+ </Row>
+ {open && (
+ <div className="pl-6">
+ {rows.map((r) => (
+ <RelationRow key={`${dir}:${r.id}`} r={r} dir={dir} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ };
const RelationRow = ({ r, dir }: { r: RelationTypeView; dir: "out" | "in" }) => (
// 悬停要有底色:这一行整条可点,只把文字提亮半级在深底上几乎看不出来。
@@ -868,349 +911,62 @@ function RelationshipsCard({
</p>
) : (
<div className="mb-2">
- {outgoing.length > 0 && (
- <>
- <GroupLabel
- className="pb-1 pt-2"
- icon={<ArrowRight size={10} />}
- count={outgoing.length > 1 ? outgoing.length : undefined}
- >
- {S.ontology.schemaOutgoing}
- </GroupLabel>
- <div>
- {outgoing.map((r) => (
- <RelationRow key={`out:${r.id}`} r={r} dir="out" />
- ))}
- </div>
- </>
- )}
- {incoming.length > 0 && (
- <>
- <GroupLabel
- className="pb-1 pt-2"
- icon={<ArrowLeft size={10} />}
- count={incoming.length > 1 ? incoming.length : undefined}
- >
- {S.ontology.schemaIncoming}
- </GroupLabel>
- <div>
- {incoming.map((r) => (
- <RelationRow key={`in:${r.id}`} r={r} dir="in" />
- ))}
- </div>
- </>
- )}
+ {outgoing.length > 0 && <Group dir="out" rows={outgoing} />}
+ {incoming.length > 0 && <Group dir="in" rows={incoming} />}
</div>
)}
- <div className="border-t border-line pt-3">
- <p className="text-fine text-ink-2 mb-2">
- {S.ontology.schemaConnectHint}
- </p>
- <div className="flex gap-2 mb-2">
- <SearchSelect
- value={connectId}
- onChange={setConnectId}
- options={relations.map((r) => ({
- value: r.id,
- label: r.label,
- hint: r.key,
- }))}
- size="sm"
- className="flex-1 min-w-0"
- placeholder={S.ontology.schemaConnectPlaceholder}
- />
- </div>
- <div className="flex items-center gap-2 mb-2">
- <span className="text-small font-medium text-ink-2">
- {S.ontology.schemaConnectAs}
- </span>
- <Segmented
- size="sm"
- value={connectSide}
- onChange={setConnectSide}
- options={[
- { value: "domain", label: S.ontology.domainLabel },
- { value: "range", label: S.ontology.rangeLabel },
- ]}
- />
- </div>
- <Button
- size="sm"
- variant="secondary"
- disabled={!connectId || connect.isPending}
- onClick={() => connect.mutate()}
- >
- {S.ontology.schemaConnect}
- </Button>
- </div>
- <div className="mt-2 pt-2 border-t border-line">
- <Button
- variant="ghost"
- size="sm"
- icon={<Plus size={13} />}
- className="-ml-2"
- onClick={onAddNew}
- >
- {S.ontology.schemaAddRelationship}
- </Button>
- </div>
+ {/* 改动开弹窗:连一个已有的关系、或新建一条。面板这一段只展示。
+ 两行与上面的关系行同一副身材 */}
+ <Row className="-mx-2 mt-2" icon={<Link2 size={14} />} onClick={onConnect}>
+ {S.ontology.connectOpen}
+ </Row>
+ <Row className="-mx-2" icon={<Plus size={14} />} onClick={onAddNew}>
+ {S.ontology.schemaAddRelationship}
+ </Row>
</div>
);
}
-/* ---------- 属性卡片:选中类的字面值字段(行内增改删) ---------- */
+/* ---------- 属性卡片:选中类的字面值字段(改动开弹窗) ---------- */
-/** 导出给模式图复用:选中一个类时,检查器里嵌的就是这一张卡片本身,
- * 不是另一份只读摘要——编辑发生在同一处,不必跳回本体主视图 */
-export function AttributesCard({
- kbId,
- type,
+function AttributesCard({
attributes,
- onChanged,
- onError,
+ onEdit,
+ onNew,
}: {
- kbId: string;
- type: EntityTypeView;
attributes: RelationTypeView[];
- onChanged: () => void;
- onError: (e: unknown) => void;
+ onEdit: (attribute: RelationTypeView) => void;
+ onNew: () => void;
}) {
- // 行内编辑:一次只展开一行(属性 id 或 "new")
- const [editing, setEditing] = useState<string | null>(null);
- useEffect(() => setEditing(null), [type.id]);
-
return (
<div>
<p className="mb-2 text-fine text-ink-2">
{S.ontology.attributesHint}
</p>
<div className="divide-y divide-line">
- {attributes.map((a) =>
- editing === a.id ? (
- <AttributeForm
- key={a.id}
- kbId={kbId}
- typeId={type.id}
- existing={a}
- onDone={() => {
- setEditing(null);
- onChanged();
- }}
- onCancel={() => setEditing(null)}
- onError={onError}
- />
- ) : (
- <Row
- key={a.id}
- className="-mx-2"
- trailing={<span className="u-num">{S.ontology.usage(a.usage)}</span>}
- onClick={() => setEditing(a.id)}
- >
- <span className="flex items-center gap-2">
- <span className="truncate">{a.label}</span>
- <Chip tone="neutral">
- {S.ontology.datatypeNames[a.datatype ?? "text"]}
- </Chip>
- {a.unit && (
- <span className="shrink-0 text-small text-ink-2">{a.unit}</span>
- )}
- {a.functional && <Chip tone="info">1:1</Chip>}
- </span>
- </Row>
- ),
- )}
- </div>
- {editing === "new" ? (
- <div className="pt-2">
- <AttributeForm
- kbId={kbId}
- typeId={type.id}
- existing={null}
- onDone={() => {
- setEditing(null);
- onChanged();
- }}
- onCancel={() => setEditing(null)}
- onError={onError}
- />
- </div>
- ) : (
- <Button
- variant="ghost"
- size="sm"
- icon={<Plus size={13} />}
- className="mt-2 -ml-2"
- onClick={() => setEditing("new")}
- >
- {S.ontology.newAttribute}
- </Button>
- )}
- </div>
- );
-}
-
-function AttributeForm({
- kbId,
- typeId,
- existing,
- onDone,
- onCancel,
- onError,
-}: {
- kbId: string;
- typeId: string;
- existing: RelationTypeView | null;
- onDone: () => void;
- onCancel: () => void;
- onError: (e: unknown) => void;
-}) {
- const [key, setKey] = useState(existing?.key ?? "");
- const [label, setLabel] = useState(existing?.label ?? "");
- const [datatype, setDatatype] = useState(existing?.datatype ?? "text");
- const [unit, setUnit] = useState(existing?.unit ?? "");
- // 单值 = functional:新值经时态引擎闭合旧值(属性历史的来源)。多数属性如此,默认开
- const [single, setSingle] = useState(existing?.functional ?? true);
- const [description, setDescription] = useState(existing?.description ?? "");
-
- const save = useMutation({
- mutationFn: async (): Promise<unknown> =>
- existing
- ? api.updateRelationType(kbId, existing.id, {
- label,
- temporal: existing.temporal,
- functional: single,
- inverse_functional: false,
- description,
- datatype,
- unit,
- })
- : api.createRelationType(kbId, {
- key,
- label,
- kind: "attribute",
- domains: [typeId],
- temporal: "state",
- functional: single,
- inverse_functional: false,
- description,
- datatype,
- unit,
- }),
- onSuccess: () => {
- toast.success(existing ? S.toast.saved : S.toast.created);
- onDone();
- },
- onError,
- });
- const remove = useMutation({
- mutationFn: () => api.deleteRelationType(kbId, existing!.id),
- onSuccess: () => {
- toast.success(S.toast.deleted);
- onDone();
- },
- onError,
- });
-
- const lbl = "block text-small font-medium text-ink-2 mb-1";
- return (
- <div className="py-3 space-y-3">
- {!existing && (
- <div className="flex gap-2">
- <div className="flex-1">
- <label className={lbl}>{S.ontology.key}</label>
- <Input
- value={key}
- onChange={(e) => setKey(e.target.value)}
- className="w-full"
- placeholder="salary"
- />
- </div>
- <div className="flex-1">
- <label className={lbl}>{S.ontology.label}</label>
- <Input
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- className="w-full"
- />
- </div>
- </div>
- )}
- {existing && (
- <div>
- <label className={lbl}>{S.ontology.label}</label>
- <Input
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- className="w-full"
- />
- </div>
- )}
- <div className="flex gap-2">
- <div className="flex-1">
- <label className={lbl}>{S.ontology.attrDatatype}</label>
- <Dropdown
- value={datatype}
- onChange={(v) => setDatatype(v as typeof datatype)}
- className="w-full"
- options={(["text", "number", "date", "bool"] as const).map((d) => ({
- value: d,
- label: S.ontology.datatypeNames[d],
- }))}
- />
- </div>
- <div className="flex-1">
- <label className={lbl}>
- {S.ontology.attrUnit}{" "}
- <span className="text-ink-2">
- ({S.ontology.attrUnitHint})
- </span>
- </label>
- <Input
- value={unit}
- onChange={(e) => setUnit(e.target.value)}
- className="w-full"
- />
- </div>
- </div>
- <Checkbox
- checked={single}
- onChange={(e) => setSingle(e.target.checked)}
- label={S.ontology.attrSingle}
- />
- <div>
- <label className={lbl}>{S.ontology.description}</label>
- <Textarea
- className="w-full min-h-24 resize-y"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- />
- </div>
- <div className="flex gap-2">
- <Button variant="primary"
- size="sm"
- onClick={() => save.mutate()}
- disabled={
- save.isPending || !label.trim() || (!existing && !key.trim())
- }
- >
- {S.ontology.save}
- </Button>
- <Button size="sm" variant="secondary" onClick={onCancel}>
- {S.ontology.cancel}
- </Button>
- {existing && (
- <Button
- size="sm"
- variant="secondary"
- className="ml-auto"
- disabled={existing.usage > 0}
- title={existing.usage > 0 ? S.ontology.deleteBlocked : undefined}
- onClick={() => remove.mutate()}
+ {attributes.map((a) => (
+ <Row
+ key={a.id}
+ className="-mx-2"
+ trailing={<span className="u-num">{S.ontology.usage(a.usage)}</span>}
+ onClick={() => onEdit(a)}
>
- {S.ontology.delete}
- </Button>
- )}
+ <span className="flex items-center gap-2">
+ <span className="truncate">{a.label}</span>
+ <Chip tone="neutral">
+ {S.ontology.datatypeNames[a.datatype ?? "text"]}
+ </Chip>
+ {a.unit && (
+ <span className="shrink-0 text-small text-ink-2">{a.unit}</span>
+ )}
+ {a.functional && <Chip tone="info">1:1</Chip>}
+ </span>
+ </Row>
+ ))}
</div>
+ <Row className="-mx-2 mt-2" icon={<Plus size={14} />} onClick={onNew}>
+ {S.ontology.newAttribute}
+ </Row>
</div>
);
}
@@ -1373,652 +1129,120 @@ function PropertyList({
);
}
-/* ---------- 类表单 ---------- */
-
-/** 父类下拉的候选:树序 + 缩进(层级可见),排除自己与全部后代(防成环)。 */
-function parentOptions(
- allTypes: EntityTypeView[],
- selfId: string | undefined,
-): { value: string; label: string; indent: number }[] {
- const excluded = new Set<string>();
- if (selfId) {
- excluded.add(selfId);
- // 收后代:反复扫描直到收敛(类的数量级很小,O(n²) 无所谓)
- let grew = true;
- while (grew) {
- grew = false;
- for (const t of allTypes) {
- if (t.parents.some((p) => excluded.has(p)) && !excluded.has(t.id)) {
- excluded.add(t.id);
- grew = true;
- }
- }
- }
- }
- const children = new Map<string | null, EntityTypeView[]>();
- for (const t of allTypes) {
- const p = t.primary_parent ?? null;
- if (!children.has(p)) children.set(p, []);
- children.get(p)!.push(t);
- }
- const out: { value: string; label: string; indent: number }[] = [];
- const walk = (parent: string | null, depth: number) => {
- for (const t of children.get(parent) ?? []) {
- if (excluded.has(t.id)) continue;
- out.push({ value: t.id, label: t.label, indent: depth });
- walk(t.id, depth + 1);
- }
- };
- walk(null, 0);
- return out;
+/* ---------- 定义(只读):面板展示,改动开弹窗 ---------- */
+
+/** 一行「标签 / 值」;值空着就写占位,不留白 */
+function Def({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="border-b border-line py-2 last:border-0">
+ <div className="text-small text-ink-2">{label}</div>
+ <div className="mt-1 break-words text-body text-ink">{children}</div>
+ </div>
+ );
}
-/** 导出给模式图复用(见 AttributesCard 上的注释) */
-export function ClassForm({
- kbId,
- existing,
- parentId,
+function Description({ text }: { text: string | null | undefined }) {
+ return text?.trim() ? (
+ <span className="whitespace-pre-wrap">{text}</span>
+ ) : (
+ <span className="text-ink-2">{S.ontology.noDescription}</span>
+ );
+}
+
+function ClassDefinition({
+ cls,
allTypes,
onNewSub,
- headless,
- onDone,
- onError,
}: {
- kbId: string;
- existing: EntityTypeView | null;
- parentId: string | null;
+ cls: EntityTypeView;
allTypes: EntityTypeView[];
- /** 编辑已有类时提供:以当前类为父级新建子类 */
- onNewSub?: () => void;
- /** 停靠面板把标题画在自己的固定头里,表单就不再画第二遍 */
- headless?: boolean;
- /** 创建成功时携带新 id,编辑成功时为 undefined */
- onDone: (createdId?: string) => void;
- onError: (e: unknown) => void;
+ /** 以当前类为父级新建子类:开弹窗 */
+ onNewSub: () => void;
}) {
- const [key, setKey] = useState(existing?.key ?? "");
- const [label, setLabel] = useState(existing?.label ?? "");
- // 新建时颜色跟着 key 走(与后端 color_for_key 同一个规则),不是一个固定默认值。
- // 用户当然可以改;但**不改的话,手动建的类和导入建的类配色体系一致**
- const [color, setColor] = useState(
- existing?.color ?? colorForKey(existing?.key ?? ""),
- );
- const [colorTouched, setColorTouched] = useState(Boolean(existing?.color));
- const [shape, setShape] = useState<"circle" | "square">(
- existing?.shape ?? "circle",
- );
- const [parents, setParents] = useState<string[]>(
- existing?.parents ?? (parentId ? [parentId] : []),
- );
- const [description, setDescription] = useState(existing?.description ?? "");
- // 互斥:声明「不可能同时是」。一致性检查据此报不可满足的类(0002)——
- // 一个类继承了两个互斥的祖先,就永远不可能有实例,而它不报错,只是永远空着
- const [disjoint, setDisjoint] = useState<string[]>(existing?.disjoint ?? []);
-
- // 从左栏点"+ 子类"进来时预填那个父。多父下它是第一个,也就是主父
- useEffect(() => setParents(parentId ? [parentId] : []), [parentId]);
-
- const save = useMutation({
- mutationFn: async (): Promise<unknown> =>
- existing
- ? api.updateEntityType(kbId, existing.id, {
- label,
- color,
- shape,
- parents,
- disjoint,
- description,
- })
- : api.createEntityType(kbId, {
- key,
- label,
- color,
- shape,
- parents,
- disjoint,
- description,
- }),
- onSuccess: (res) => {
- toast.success(existing ? S.toast.saved : S.toast.created);
- onDone(existing ? undefined : (res as { id?: string })?.id);
- },
- onError,
- });
- const remove = useMutation({
- mutationFn: () => api.deleteEntityType(kbId, existing!.id),
- onSuccess: () => {
- toast.success(S.toast.deleted);
- onDone();
- },
- onError,
- });
-
- const lbl = "block text-small font-medium text-ink-2 mb-1";
+ const nameOf = (id: string) => allTypes.find((t) => t.id === id)?.label ?? id;
return (
- <div className="space-y-3">
- {!headless && (
- <div className="flex items-center gap-2">
- <span
- className={`h-3 w-3 ${shape === "square" ? "scale-90" : "rounded-full"}`}
- style={{ background: color }}
- />
- <span className="font-semibold text-ink">
- {existing?.label ?? S.ontology.newClass}
- </span>
- {/* key 是纯技术标识:已存在时干脆不展示,只在创建时输入 */}
- {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}
- {existing && (
- <span className="ml-auto text-small text-ink-2">
- {S.ontology.usage(existing.usage)}
- </span>
- )}
- </div>
- )}
- {!existing && (
- <div>
- <label className={lbl}>
- {S.ontology.key}{" "}
- <span className="text-ink-2">({S.ontology.keyHint})</span>
- </label>
- <Input
- value={key}
- onChange={(e) => {
- setKey(e.target.value);
- // 用户没自己挑过色,就让颜色跟着 key 走——与后端同一个规则
- if (!colorTouched) setColor(colorForKey(e.target.value));
- }}
- className="w-full"
- placeholder="contract"
- />
- </div>
- )}
- <div>
- <label className={lbl}>{S.ontology.label}</label>
- <Input
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- className="w-full"
- />
- </div>
- <div>
- <label className={lbl}>{S.ontology.shapeColor}</label>
- <div className="flex items-center gap-2">
- <ColorPicker value={color} onChange={(c: string) => { setColor(c); setColorTouched(true); }} shape={shape} />
- {/* 形状:与图谱节点渲染一一对应(circle=四层圆 / square=四层方) */}
- <Segmented
- size="sm"
- value={shape}
- onChange={setShape}
- options={(["circle", "square"] as const).map((sh) => ({
- value: sh,
- title: sh,
- // 图标占一行正文的高(h-4 = text-fine 的行高):Segmented 的高度由内容撑,
- // 光秃秃的 12px 图标会让它比旁边 32 高的色井矮一截
- label: (
- <span className="flex h-4 items-center">
- <span
- className={`h-3 w-3 border-[1.5px] border-current ${
- sh === "circle" ? "rounded-full" : "scale-90"
- }`}
- />
- </span>
- ),
- }))}
- />
- </div>
- </div>
- {/* 多父:subClassOf 可以有多条。左栏按树画,一个类只能出现一次——
- 所以第一个当主父。界面说明这条,不另加一个"选主父"的控件 */}
- <div>
- <label className={lbl}>{S.ontology.parent}</label>
- <MultiSearchSelect
- values={parents}
- options={parentOptions(allTypes, existing?.id)}
- onToggle={(id) =>
- setParents((v) =>
- v.includes(id) ? v.filter((x) => x !== id) : [...v, id],
- )
- }
- placeholder={S.ontology.searchTypes}
- emptyHint={S.ontology.noParent}
- />
- {parents.length > 1 && (
- <p className="mt-1 text-fine text-ink-2">
- {S.ontology.primaryParentHint}
- </p>
- )}
- </div>
- {/* 互斥:**声明「不可能同时是」**。紧挨着父类,因为两者是同一件事的
- 两面——父类说「也是」,互斥说「不可能同时是」,而一致性检查正是
- 在这两者打架时报出「这个类永远不可能有实例」 */}
- <div>
- <label className={lbl}>{S.ontology.disjoint}</label>
- <p className="text-fine leading-relaxed text-ink-2 mb-2">
- {S.ontology.disjointHint}
- </p>
- <MultiSearchSelect
- values={disjoint}
- options={parentOptions(allTypes, existing?.id)}
- onToggle={(id) =>
- setDisjoint((v) =>
- v.includes(id) ? v.filter((x) => x !== id) : [...v, id],
- )
- }
- placeholder={S.ontology.searchTypes}
- emptyHint={S.ontology.noDisjoint}
- />
- {/* 跟自己的父类互斥 = 这个类永远不可能有实例。当场说,
- 比让人跑一遍一致性检查再发现要快 */}
- {disjoint.some((d) => parents.includes(d)) && (
- <p className="mt-2 text-fine text-danger">
- {S.ontology.disjointWithParent}
- </p>
- )}
- </div>
- <div>
- <label className={lbl}>{S.ontology.description}</label>
- {/* 语义指引:整段注入抽取 prompt,直接影响抽取归类质量 */}
- <Textarea
- className="w-full min-h-36 resize-y"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- />
- <p className="mt-1 text-fine text-ink-2">
- {S.ontology.descriptionHint}
- </p>
- </div>
- <div className="flex gap-2 pt-1">
- <Button variant="primary"
- size="sm"
- onClick={() => save.mutate()}
- disabled={save.isPending || !label.trim()}
- >
- {S.ontology.save}
- </Button>
- {onNewSub && (
- <Button size="sm" variant="secondary" onClick={onNewSub}>
- {S.ontology.newSubClass}
- </Button>
- )}
- {existing && !existing.builtin && (
- <Button
- size="sm"
- variant="secondary"
- disabled={existing.usage > 0}
- title={existing.usage > 0 ? S.ontology.deleteBlocked : undefined}
- onClick={() => remove.mutate()}
- >
- {S.ontology.delete}
- </Button>
- )}
- </div>
+ <div>
+ <Def label={S.ontology.parent}>
+ {cls.parents.length > 0 ? cls.parents.map(nameOf).join(", ") : S.ontology.noParent}
+ </Def>
+ <Def label={S.ontology.disjoint}>
+ {cls.disjoint.length > 0 ? cls.disjoint.map(nameOf).join(", ") : S.ontology.noDisjoint}
+ </Def>
+ <Def label={S.ontology.description}>
+ <Description text={cls.description} />
+ </Def>
+ {/* 新增入口与列表里的行同一副身材(左栏的「New class」也是这样一行):
+ 图标落在文字的左缘上,不再用带内距的按钮去对 */}
+ <Row className="-mx-2 mt-2" icon={<Plus size={14} />} onClick={onNewSub}>
+ {S.ontology.newSubClass}
+ </Row>
</div>
);
}
-/* ---------- 关系表单 ---------- */
-
-/** 导出给模式图复用(见 AttributesCard 上的注释) */
-export function PropertyForm({
- kbId,
- existing,
+function PropertyDefinition({
+ rel,
allTypes,
allRelations,
- initialDomain,
- headless,
- onDone,
- onError,
}: {
- kbId: string;
- existing: RelationTypeView | null;
+ rel: RelationTypeView;
allTypes: EntityTypeView[];
- /** 本库的关系(不含属性)。逆与子属性的下拉从这里取——**属性不在其中**,
- * 它的宾语是字面值,反过来无从谈起 */
allRelations: RelationTypeView[];
- /** 从模式图上一个类出发新建关系时,domain 预填成那个类——**只影响初始值**,
- * 不是约束:下面照旧是个可编辑的 MultiSearchSelect,填错了随手改 */
- initialDomain?: string | null;
- /** 见 `ClassForm.headless` */
- headless?: boolean;
- onDone: (createdId?: string) => void;
- onError: (e: unknown) => void;
}) {
- const [key, setKey] = useState(existing?.key ?? "");
- const [label, setLabel] = useState(existing?.label ?? "");
- const [temporal, setTemporal] = useState(existing?.temporal ?? "state");
- const [functional, setFunctional] = useState(existing?.functional ?? false);
- const [inverseFunctional, setInverseFunctional] = useState(
- existing?.inverse_functional ?? false,
- );
- // 其余四条 OWL 公理。**推理机的判据全在这里**——从前只能靠导入 OWL 带进来,
- // 在界面上手工建本体的人永远开不了那台机器(0002)
- const [transitive, setTransitive] = useState(existing?.is_transitive ?? false);
- const [symmetric, setSymmetric] = useState(existing?.is_symmetric ?? false);
- const [asymmetric, setAsymmetric] = useState(existing?.is_asymmetric ?? false);
- const [irreflexive, setIrreflexive] = useState(
- existing?.is_irreflexive ?? false,
- );
- // 同一族的后两条,形状不同:指向另一个关系。空串 = 没声明
- const [inverseOf, setInverseOf] = useState(existing?.inverse_of ?? "");
- const [subPropertyOf, setSubPropertyOf] = useState(
- existing?.sub_property_of ?? "",
- );
- const [description, setDescription] = useState(existing?.description ?? "");
- const [domains, setDomains] = useState<string[]>(
- existing?.domains ?? (initialDomain ? [initialDomain] : []),
- );
- const [ranges, setRanges] = useState<string[]>(existing?.ranges ?? []);
- // 显示标签,不显示 key。**进提示词的 key 由服务端从库里取**,与界面显示什么无关;
- // 而类树、属性列表也都显示标签,这里没有理由例外——中文库里用户该看到
- // "发票记录" 而不是 invoice_record
- const typeOpts = useMemo(
- () => parentOptions(allTypes, undefined),
- [allTypes],
- );
- // 两个下拉的选项:本库的其它关系。
- //
- // **自己不进列表**,两条都是。子属性指向自己数据库直接拒(那是个环);
- // 逆指向自己在语义上合法——但它等于 `symmetric`,而那个复选框就在上面,
- // 在这里提供第二条路只会让人写出 R0 要报的东西。
- //
- // 唯一的例外是**当前值就是自己**:OWL 导入进来的可以长这样,从列表里漏掉
- // 它就会让下拉显示空白,而空白一保存就把已声明的抹了
- const linkOptions = (current: string) => [
- { value: "", label: S.ontology.noLink },
- // 当前值就是自己时把自己补回列表,否则下拉显示空白,
- // 而空白一保存就把已声明的抹了
- ...(existing && current === existing.id
- ? [{ value: existing.id, label: existing.label, hint: existing.key }]
- : []),
- ...allRelations
- .filter((r) => r.id !== existing?.id)
- .map((r) => ({ value: r.id, label: r.label, hint: r.key })),
- ];
- /** 下拉里选中那条的显示名。找不到就回落到 id——宁可难看,不要空着 */
- const nameOf = (id: string) =>
- allRelations.find((r) => r.id === id)?.label ?? id;
- const toggle = (
- set: React.Dispatch<React.SetStateAction<string[]>>,
- id: string,
- ) => set((v) => (v.includes(id) ? v.filter((x) => x !== id) : [...v, id]));
-
- const save = useMutation({
- mutationFn: async (): Promise<unknown> =>
- existing
- ? api.updateRelationType(kbId, existing.id, {
- label,
- temporal,
- functional,
- inverse_functional: inverseFunctional,
- is_transitive: transitive,
- is_symmetric: symmetric,
- is_asymmetric: asymmetric,
- is_irreflexive: irreflexive,
- // 空串要变成 null 再送——服务端收 `Option<Uuid>`,
- // `""` 解不成 UUID,会是一个 422 而不是「清空」
- inverse_of: inverseOf || null,
- sub_property_of: subPropertyOf || null,
- description,
- domains,
- ranges,
- })
- : api.createRelationType(kbId, {
- key,
- label,
- temporal,
- functional,
- inverse_functional: inverseFunctional,
- is_transitive: transitive,
- is_symmetric: symmetric,
- is_asymmetric: asymmetric,
- is_irreflexive: irreflexive,
- // 空串要变成 null 再送——服务端收 `Option<Uuid>`,
- // `""` 解不成 UUID,会是一个 422 而不是「清空」
- inverse_of: inverseOf || null,
- sub_property_of: subPropertyOf || null,
- description,
- domains,
- ranges,
- }),
- onSuccess: (res) => {
- toast.success(existing ? S.toast.saved : S.toast.created);
- onDone(existing ? undefined : (res as { id?: string })?.id);
- },
- onError,
- });
- const remove = useMutation({
- mutationFn: () => api.deleteRelationType(kbId, existing!.id),
- onSuccess: () => {
- toast.success(S.toast.deleted);
- onDone();
- },
- onError,
- });
-
- const lbl = "block text-small font-medium text-ink-2 mb-1";
+ const typeName = (id: string) => allTypes.find((t) => t.id === id)?.label ?? id;
+ const relName = (id: string) => allRelations.find((r) => r.id === id)?.label ?? id;
+ const temporal =
+ (
+ {
+ state: S.ontology.temporalState,
+ event: S.ontology.temporalEvent,
+ eternal: S.ontology.temporalEternal,
+ } as Record<string, string>
+ )[rel.temporal] ?? rel.temporal;
+ // 勾了的公理才列:没勾的不是信息
+ const axioms = (
+ [
+ [rel.functional, S.ontology.functional],
+ [rel.inverse_functional, S.ontology.inverseFunctional],
+ [rel.is_transitive, S.ontology.transitive],
+ [rel.is_symmetric, S.ontology.symmetric],
+ [rel.is_asymmetric, S.ontology.asymmetric],
+ [rel.is_irreflexive, S.ontology.irreflexive],
+ ] as const
+ )
+ .filter(([on]) => on)
+ .map(([, name]) => name);
return (
- <div className="space-y-3">
- {!headless && (
- <div className="flex items-center gap-2">
- <span className="font-semibold text-ink">
- {existing?.label ?? S.ontology.newProperty}
+ <div>
+ <Def label={S.ontology.domainLabel}>
+ {rel.domains.length > 0 ? rel.domains.map(typeName).join(", ") : S.ontology.anyType}
+ </Def>
+ <Def label={S.ontology.rangeLabel}>
+ {rel.ranges.length > 0 ? rel.ranges.map(typeName).join(", ") : S.ontology.anyType}
+ </Def>
+ <Def label={S.ontology.temporal}>{temporal}</Def>
+ <Def label={S.ontology.axioms}>
+ {axioms.length > 0 ? (
+ <span className="flex flex-wrap gap-1">
+ {axioms.map((a) => (
+ <Chip key={a} tone="info">
+ {a}
+ </Chip>
+ ))}
</span>
- {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}
- {existing && (
- <span className="ml-auto text-small text-ink-2">
- {S.ontology.usage(existing.usage)}
- </span>
- )}
- </div>
+ ) : (
+ <span className="text-ink-2">{S.ontology.axiomsNone}</span>
+ )}
+ </Def>
+ {rel.inverse_of && (
+ <Def label={S.ontology.inverseOf}>{relName(rel.inverse_of)}</Def>
)}
- {!existing && (
- <div>
- <label className={lbl}>
- {S.ontology.key}{" "}
- <span className="text-ink-2">({S.ontology.keyHint})</span>
- </label>
- <Input
- value={key}
- onChange={(e) => setKey(e.target.value)}
- className="w-full"
- placeholder="signed_with"
- />
- </div>
+ {rel.sub_property_of && (
+ <Def label={S.ontology.subPropertyOf}>{relName(rel.sub_property_of)}</Def>
)}
- <div>
- <label className={lbl}>{S.ontology.label}</label>
- <Input
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- className="w-full"
- />
- </div>
- {/* 类型签名。界面显示标签,而进提示词的是 key —— 那一步在服务端,
- 与这里显示什么无关(docs/decisions/0004 定的是提示词里必须用 key) */}
- <div>
- <label className={lbl}>{S.ontology.signature}</label>
- <p className="text-fine leading-relaxed text-ink-2 mb-2">
- {S.ontology.signatureHint}
- </p>
- <div className="grid gap-2 sm:grid-cols-2">
- <div className="min-w-0">
- <div className="mb-1 text-small font-medium text-ink-2">
- {S.ontology.domainLabel}
- </div>
- <MultiSearchSelect
- values={domains}
- options={typeOpts}
- onToggle={(id) => toggle(setDomains, id)}
- placeholder={S.ontology.searchTypes}
- emptyHint={S.ontology.anyType}
- />
- </div>
- <div className="min-w-0">
- <div className="mb-1 text-small font-medium text-ink-2">
- {S.ontology.rangeLabel}
- </div>
- <MultiSearchSelect
- values={ranges}
- options={typeOpts}
- onToggle={(id) => toggle(setRanges, id)}
- placeholder={S.ontology.searchTypes}
- emptyHint={S.ontology.anyType}
- />
- </div>
- </div>
- </div>
- <div>
- <label className={lbl}>{S.ontology.temporal}</label>
- <Dropdown
- value={temporal}
- onChange={setTemporal}
- className="w-full"
- options={[
- { value: "state", label: S.ontology.temporalState },
- { value: "event", label: S.ontology.temporalEvent },
- { value: "eternal", label: S.ontology.temporalEternal },
- ]}
- />
- </div>
- {/* 六条公理并成一组。**它们本来就是同一族**——推理机(0002)拿它们当
- 判据,散在表单各处会让人以为前两条和后四条是两回事。
- 每一条底下写清「勾了会发生什么」:这些开关不是描述,是会改变系统行为的
- 声明——`functional` 让时态引擎自动闭合旧值,`transitive` 让推理机往图里
- 加边。看不出后果的开关,人只会照着直觉乱勾。 */}
- <div>
- <label className={lbl}>{S.ontology.axioms}</label>
- <p className="text-fine leading-relaxed text-ink-2 mb-2">
- {S.ontology.axiomsHint}
- </p>
- <div className="space-y-2">
- {(
- [
- [functional, setFunctional, S.ontology.functional, S.ontology.functionalHint],
- [
- inverseFunctional,
- setInverseFunctional,
- S.ontology.inverseFunctional,
- S.ontology.inverseFunctionalHint,
- ],
- [transitive, setTransitive, S.ontology.transitive, S.ontology.transitiveHint],
- [symmetric, setSymmetric, S.ontology.symmetric, S.ontology.symmetricHint],
- [asymmetric, setAsymmetric, S.ontology.asymmetric, S.ontology.asymmetricHint],
- [
- irreflexive,
- setIrreflexive,
- S.ontology.irreflexive,
- S.ontology.irreflexiveHint,
- ],
- ] as const
- ).map(([on, set, title, hint], i) => (
- <Checkbox
- key={i}
- checked={on}
- onChange={(e) => set(e.target.checked)}
- label={title}
- hint={hint}
- />
- ))}
- </div>
- {/* 对称与反对称同时勾是自相矛盾的(只对空关系成立)。本体自洽性检查
- 会报出来,但在这里当场说一句比让人跑一遍检查再发现要快 */}
- {symmetric && asymmetric && (
- <p className="mt-2 text-fine text-danger">
- {S.ontology.axiomConflict}
- </p>
- )}
- {/* 同一组的后两条,只是形状不同:它们指向**另一个关系**,所以是下拉
- 不是复选框。放在这里而不是单开一节——推理机的四种规则源里,两条是
- 上面的勾,两条是下面的选,分开会让人以为它们是两回事(0002) */}
- <div className="mt-3 space-y-3 border-t border-line pt-3">
- {(
- [
- [
- inverseOf,
- setInverseOf,
- S.ontology.inverseOf,
- S.ontology.inverseOfHint,
- linkOptions(inverseOf),
- ],
- [
- subPropertyOf,
- setSubPropertyOf,
- S.ontology.subPropertyOf,
- S.ontology.subPropertyOfHint,
- linkOptions(subPropertyOf),
- ],
- ] as const
- ).map(([value, set, title, hint, options], i) => (
- <div key={i}>
- <div className="text-body text-ink">{title}</div>
- <p className="text-fine leading-relaxed text-ink-2 mb-1">
- {hint}
- </p>
- <SearchSelect
- value={value}
- onChange={set}
- options={options}
- size="sm"
- className="w-full"
- placeholder={S.ontology.noLink}
- />
- </div>
- ))}
- {/* 选了之后当场把话说全。**这两条推出来的事实主宾未必同向**——
- 逆要对调,子属性不对调,只看名字分不出来,写出来就分得出 */}
- {(inverseOf || subPropertyOf) && (
- <div className="text-fine leading-relaxed text-ink-2 space-y-1">
- {inverseOf && (
- <div>
- {S.ontology.linkMeansInverse(
- label.trim() || key || "?",
- nameOf(inverseOf),
- )}
- </div>
- )}
- {subPropertyOf && (
- <div>
- {S.ontology.linkMeansSuper(
- label.trim() || key || "?",
- nameOf(subPropertyOf),
- )}
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- <div>
- <label className={lbl}>{S.ontology.description}</label>
- <Textarea
- className="w-full min-h-36 resize-y"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- />
- <p className="mt-1 text-fine text-ink-2">
- {S.ontology.descriptionHint}
- </p>
- </div>
- <div className="flex gap-2 pt-1">
- <Button variant="primary"
- size="sm"
- onClick={() => save.mutate()}
- disabled={save.isPending || !label.trim()}
- >
- {S.ontology.save}
- </Button>
- {existing && !existing.builtin && (
- <Button
- size="sm"
- variant="secondary"
- disabled={existing.usage > 0}
- title={existing.usage > 0 ? S.ontology.deleteBlocked : undefined}
- onClick={() => remove.mutate()}
- >
- {S.ontology.delete}
- </Button>
- )}
- </div>
+ <Def label={S.ontology.description}>
+ <Description text={rel.description} />
+ </Def>
</div>
);
}
diff --git a/web/src/pages/OntologySchemaGraph.tsx b/web/src/pages/OntologySchemaGraph.tsx
index bad11038..5e7a05ab 100644
--- a/web/src/pages/OntologySchemaGraph.tsx
+++ b/web/src/pages/OntologySchemaGraph.tsx
@@ -26,7 +26,7 @@ import forceAtlas2 from "graphology-layout-forceatlas2";
import Sigma from "sigma";
import { createNodeBorderProgram } from "@sigma/node-border";
import { EdgeArrowProgram, EdgeLineProgram } from "sigma/rendering";
-import { EdgeCurvedArrowProgram } from "@sigma/edge-curve";
+import EdgeCurveProgram, { EdgeCurvedArrowProgram } from "@sigma/edge-curve";
import { NodeSquareShellProgram } from "./squareShellProgram";
import {
drawHoverCard,
@@ -94,6 +94,7 @@ const DISJOINT_KIND = "disjoint";
const EDGE_TYPE_ARROW = "arrow"; // 直线 + 箭头(EdgeArrowProgram)
const EDGE_TYPE_CURVED_ARROW = "curvedArrow"; // 弧线 + 箭头(EdgeCurvedArrowProgram)
const EDGE_TYPE_LINE = "line"; // 直线,无箭头(EdgeLineProgram)——互斥专用
+const EDGE_TYPE_CURVED_LINE = "curvedLine"; // 弧线,无箭头(EdgeCurveProgram)——互斥与别的边共用一对时
/** 结构边细、关系边粗一档——「语义关系比结构性信息更显眼」不能只靠颜色说,
* 粗细上也要有一档差。这个粗细同时也是点选判定的命中带宽——sigma 的边拾取
@@ -339,37 +340,45 @@ export function buildSchemaGraph(
});
}
- layOutParallelRelations(graph);
+ layOutParallelEdges(graph);
return { graph, unscoped };
}
-/** 同一对类之间的多条关系边(works_at / founded / owns 都连着 Person↔Organization)
- * 各自扇到一条独立的弧上,不叠成一条谁也点不中的线。算法与 Graph.tsx 的
- * layOutParallelEdges 同一个思路(按无向对分组,围绕直线对称铺开),
- * 但这里的边不需要先合并逆关系——本体里 inverse_of 只在关系检查器里说明,
- * 不折进画布,所以少了那一整步。
+/** 同一对类之间的多条边各自扇到一条独立的弧上,不叠成一条谁也点不中的线。
+ * **不分种类**:继承、互斥、关系三种边都可能落在同一对类上(Unit 既是
+ * Organization 的子类又与它互斥;一条关系的主宾恰好是父子),只给关系边扇开
+ * 的话,剩下两种照旧叠在直线上,标签也叠在一起。算法与 Graph.tsx 的
+ * layOutParallelEdges 同一个思路(按无向对分组,围绕直线对称铺开);这里的边
+ * 不需要先合并逆关系——本体里 inverse_of 只在关系检查器里说明,不折进画布。
*
- * 顺带决定每条关系边的渲染类型:**独苗走直线**(EDGE_TYPE_ARROW),
- * 只有真的平行/自环时才切到弧线程序——弧线程序在零弯曲度下也能画,
- * 但没必要为大多数只有一条的关系边多背一层曲线计算 */
-function layOutParallelRelations(graph: Graphology): void {
+ * 顺带决定每条边的渲染程序:**独苗走直线**,只有真的平行/自环时才切到弧线
+ * 程序;有箭头的(继承、关系)用带箭头的弧,互斥用不带箭头的弧 */
+function layOutParallelEdges(graph: Graphology): void {
const groups = new Map<string, string[]>();
- graph.forEachEdge((edge, attrs, source, target) => {
- if (attrs.kind !== RELATION_KIND) return;
+ graph.forEachEdge((edge, _attrs, source, target) => {
const key =
source === target ? `loop:${source}` : [source, target].sort().join("|");
const list = groups.get(key);
if (list) list.push(edge);
else groups.set(key, [edge]);
});
+ const typeFor = (kind: string, curved: boolean) =>
+ kind === DISJOINT_KIND
+ ? curved
+ ? EDGE_TYPE_CURVED_LINE
+ : EDGE_TYPE_LINE
+ : curved
+ ? EDGE_TYPE_CURVED_ARROW
+ : EDGE_TYPE_ARROW;
for (const edges of groups.values()) {
const n = edges.length;
edges.forEach((edge, i) => {
const [source, target] = graph.extremities(edge);
+ const kind = graph.getEdgeAttribute(edge, "kind") as string;
if (source === target) {
graph.mergeEdgeAttributes(edge, {
curvature: SELF_LOOP_BASE_CURVATURE + i * RELATION_CURVATURE_STEP,
- type: EDGE_TYPE_CURVED_ARROW,
+ type: typeFor(kind, true),
});
return;
}
@@ -380,7 +389,7 @@ function layOutParallelRelations(graph: Graphology): void {
const curvature = offset === 0 ? 0 : sign * offset * RELATION_CURVATURE_STEP;
graph.mergeEdgeAttributes(edge, {
curvature,
- type: curvature === 0 ? EDGE_TYPE_ARROW : EDGE_TYPE_CURVED_ARROW,
+ type: typeFor(kind, curvature !== 0),
});
});
}
@@ -677,6 +686,7 @@ export function OntologySchemaGraph({
[EDGE_TYPE_ARROW]: EdgeArrowProgram,
[EDGE_TYPE_LINE]: EdgeLineProgram,
[EDGE_TYPE_CURVED_ARROW]: EdgeCurvedArrowProgram,
+ [EDGE_TYPE_CURVED_LINE]: EdgeCurveProgram,
},
enableEdgeEvents: true,
minEdgeThickness: MIN_EDGE_THICKNESS,
diff --git a/web/src/pages/graphDialogs.tsx b/web/src/pages/graphDialogs.tsx
new file mode 100644
index 00000000..dcb9cff2
--- /dev/null
+++ b/web/src/pages/graphDialogs.tsx
@@ -0,0 +1,225 @@
+// 图谱页的编辑弹窗:实体(名字、类型)与一条事实的有效区间。
+// 实体面板只展示;从前改名的两格嵌在面板头下面、改区间的表单嵌在事实行里,
+// 现在各开一扇窗。字段与提交逻辑原样搬过来。
+import { useEffect, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { api, type EntityFact, type GraphNode } from "../api";
+import { S } from "../i18n";
+import { toast } from "../toast";
+import { fmtTime, parseDateInput } from "../time";
+import { Field, FormDialog, Input, Radio, SearchSelect } from "../ui";
+
+/* ---------- 实体:抽取给的是初判,判错此前只能整库重抽 ---------- */
+
+export function EntityDialog({
+ kbId,
+ entityId,
+ entity,
+ onClose,
+ onSaved,
+}: {
+ kbId: string;
+ entityId: string;
+ entity: GraphNode;
+ onClose: () => void;
+ /** 保存成功:带回同名的其他实体——改完名可能撞上一批新的同名 */
+ onSaved: (sameName: GraphNode[]) => void;
+}) {
+ const qc = useQueryClient();
+ const [name, setName] = useState(entity.name);
+ const [typeId, setTypeId] = useState("");
+ // 类型下拉要的是全量本体,不是当前视图里出现过的那几个
+ const ontology = useQuery({
+ queryKey: ["ontology", kbId],
+ queryFn: () => api.ontology(kbId),
+ });
+ const types = ontology.data?.entity_types ?? [];
+ const currentId = types.find((t) => t.key === entity.type_key)?.id ?? "";
+ // 本体是异步来的:它到齐时把类型下拉对到当前类型上
+ useEffect(() => {
+ if (!typeId && currentId) setTypeId(currentId);
+ }, [typeId, currentId]);
+
+ const dirty = name.trim() !== entity.name || (!!typeId && typeId !== currentId);
+ const save = useMutation({
+ mutationFn: () => {
+ const body: { type_id?: string; canonical_name?: string } = {};
+ if (name.trim() && name.trim() !== entity.name) body.canonical_name = name.trim();
+ if (typeId && typeId !== currentId) body.type_id = typeId;
+ return api.updateEntity(kbId, entityId, body);
+ },
+ onSuccess: (r) => {
+ toast.success(S.graph.editSaved);
+ // 改了类型/名字,图谱节点与本体计数都要跟着动
+ qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] });
+ qc.invalidateQueries({ queryKey: ["graph", kbId] });
+ qc.invalidateQueries({ queryKey: ["ontology", kbId] });
+ onSaved(r.same_name);
+ },
+ onError: (err: Error) => toast.error(err.message),
+ });
+
+ return (
+ <FormDialog
+ title={S.graph.editTitle}
+ closeLabel={S.graph.close}
+ saveLabel={S.graph.editSave}
+ cancelLabel={S.graph.editCancel}
+ canSave={dirty && !!name.trim()}
+ busy={save.isPending}
+ onSave={() => save.mutate()}
+ onCancel={onClose}
+ >
+ <Field
+ label={S.graph.editName}
+ error={!name.trim() ? S.graph.editEmptyName : undefined}
+ >
+ <Input
+ autoFocus
+ className="w-full"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </Field>
+ {/* 类可能上千个(schema.org 一装就是 1010 个):这一格要能打字过滤,
+ 所以是 SearchSelect 而不是下拉——下拉是给小而有界的枚举的 */}
+ <Field label={S.graph.editType} className="mb-0">
+ <SearchSelect
+ className="w-full"
+ value={typeId}
+ onChange={setTypeId}
+ options={types.map((t) => ({ value: t.id, label: t.label, hint: t.key }))}
+ />
+ </Field>
+ </FormDialog>
+ );
+}
+
+/* ---------- 一条事实的有效区间(302) ----------
+ 两端一起提交而不是逐端改:区间的两端互相定义,「清空结束端」与「这次不动
+ 结束端」得能分辨。结束端的三个选项与账本里的三种写法一一对应,所以这里
+ 没有「留空即至今」这种隐含约定——那正是 valid_to IS NULL 一度承载两个意思
+ 的老毛病。 */
+
+export function FactTimeDialog({
+ kbId,
+ fact,
+ onClose,
+}: {
+ kbId: string;
+ fact: EntityFact;
+ onClose: () => void;
+}) {
+ const qc = useQueryClient();
+ const [from, setFrom] = useState(
+ fmtTime(fact.valid_from, fact.valid_from_precision) ?? "",
+ );
+ const [to, setTo] = useState(
+ fmtTime(fact.valid_to, fact.valid_to_precision) ?? "",
+ );
+ const [endMode, setEndMode] = useState<"open" | "unknown" | "date">(
+ fact.valid_to
+ ? "date"
+ : fact.valid_to_precision === "unknown"
+ ? "unknown"
+ : "open",
+ );
+ const [note, setNote] = useState("");
+
+ const save = useMutation({
+ mutationFn: () => {
+ const f = from.trim() ? parseDateInput(from) : null;
+ if (from.trim() && !f) throw new Error(S.graph.timeBadDate);
+ const t = endMode === "date" ? parseDateInput(to) : null;
+ if (endMode === "date" && !t) throw new Error(S.graph.timeBadDate);
+ return api.updateFactTime(kbId, fact.id, {
+ valid_from: f?.iso ?? null,
+ valid_from_precision: f?.precision ?? null,
+ valid_to: t?.iso ?? null,
+ valid_to_precision:
+ endMode === "date"
+ ? (t?.precision ?? null)
+ : endMode === "unknown"
+ ? "unknown"
+ : null,
+ note: note.trim() || undefined,
+ });
+ },
+ onSuccess: (r) => {
+ // 对账的后果要说出来:改了起点可能顺手闭合了继任者的开放区间,
+ // 也可能撞出一条需要人裁的冲突。不说的话图会自己变而没人知道为什么
+ if (r.conflicts) toast.success(S.graph.timeSavedConflicts(r.conflicts));
+ else if (r.closed) toast.success(S.graph.timeSavedClosed(r.closed));
+ else toast.success(S.graph.timeSaved);
+ qc.invalidateQueries({ queryKey: ["entity", kbId] });
+ qc.invalidateQueries({ queryKey: ["graph"] });
+ qc.invalidateQueries({ queryKey: ["review", kbId] });
+ onClose();
+ },
+ onError: (e: Error) => toast.error(e.message),
+ });
+
+ const what = `${fact.predicate_label ?? S.graph.unknownPredicate} → ${
+ fact.other_name ?? "?"
+ }`;
+ return (
+ <FormDialog
+ width="sm"
+ title={S.graph.editTime}
+ description={what}
+ closeLabel={S.graph.close}
+ saveLabel={S.graph.timeSave}
+ cancelLabel={S.graph.timeCancel}
+ busy={save.isPending}
+ onSave={() => save.mutate()}
+ onCancel={onClose}
+ >
+ <Field label={S.graph.timeStart} hint={S.graph.timeFormat}>
+ <Input
+ autoFocus
+ value={from}
+ onChange={(e) => setFrom(e.target.value)}
+ placeholder={S.graph.timeFormat}
+ className="u-num w-full"
+ />
+ </Field>
+ <Field label={S.graph.timeEnd}>
+ <div className="space-y-2">
+ {(
+ [
+ ["open", S.graph.timeEndOpen],
+ ["unknown", S.graph.timeEndUnknown],
+ ["date", S.graph.timeEndDate],
+ ] as const
+ ).map(([mode, label]) => (
+ <Radio
+ key={mode}
+ name={`end-${fact.id}`}
+ checked={endMode === mode}
+ onChange={() => setEndMode(mode)}
+ label={label}
+ >
+ {mode === "date" && endMode === "date" && (
+ <Input
+ size="sm"
+ value={to}
+ onChange={(e) => setTo(e.target.value)}
+ placeholder={S.graph.timeFormat}
+ className="u-num ml-1 flex-1"
+ />
+ )}
+ </Radio>
+ ))}
+ </div>
+ </Field>
+ <Field label={S.graph.timeNote} className="mb-0">
+ <Input
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ placeholder={S.graph.timeNotePlaceholder}
+ className="w-full"
+ />
+ </Field>
+ </FormDialog>
+ );
+}
diff --git a/web/src/pages/graphVisuals.ts b/web/src/pages/graphVisuals.ts
index b2fd2a54..fb4390da 100644
--- a/web/src/pages/graphVisuals.ts
+++ b/web/src/pages/graphVisuals.ts
@@ -132,62 +132,46 @@ export function drawHoverCard(
if (!data.label) return;
ctx.save();
- // 柔光: 半径 max(size*4.8, 16), 类型色 alpha 0.18 → 0
- const glowR = Math.max(data.size * 4.8, 16);
- const [r, g, b] = hexToRgb((data.typeColor as string) ?? "#888888");
- const grad = ctx.createRadialGradient(
- data.x,
- data.y,
- 0,
- data.x,
- data.y,
- glowR,
- );
- grad.addColorStop(0, `rgba(${r},${g},${b},0.18)`);
- grad.addColorStop(1, `rgba(${r},${g},${b},0)`);
- ctx.fillStyle = grad;
- ctx.beginPath();
- ctx.arc(data.x, data.y, glowR, 0, Math.PI * 2);
- ctx.fill();
-
- /* 卡片:标题 body/500、类型行 fine。**类型不再大写**——界面里没有一处
- 大写拉字距的小标题(表格列头除外),画布也不该自成一套 */
- const titleSize = CANVAS_TITLE_SIZE;
- const metaSize = CANVAS_META_SIZE;
- const padX = 10;
- const padY = 7;
- const metaGap = 5;
+ /* 它就是一个 Tooltip,只是画在 canvas 上:皮照抄 `ui/tooltip.tsx` 的那一行——
+ `.u-pop`(近实底 + line-strong 的边)、`rounded-cell`(4)、`px-2 py-1`(8 / 4)、
+ `text-fine`(12)。名字一行、类型一行,名字用正文色加粗一档,类型用第二色。
+ 没有光晕、没有大投影:指着的节点自己已经亮了环,卡片只负责说名字 */
+ const size = CANVAS_META_SIZE;
+ const padX = 8;
+ const padY = 4;
+ const gap = 2;
const meta = String(data.typeLabel ?? "");
ctx.textBaseline = "top";
- ctx.font = `500 ${titleSize}px ${CANVAS_FONT}`;
+ ctx.font = `500 ${size}px ${CANVAS_FONT}`;
const titleW = ctx.measureText(data.label).width;
- ctx.font = `400 ${metaSize}px ${CANVAS_FONT}`;
- const metaW = ctx.measureText(meta).width;
+ ctx.font = `400 ${size}px ${CANVAS_FONT}`;
+ const metaW = meta ? ctx.measureText(meta).width : 0;
const w = Math.max(titleW, metaW) + padX * 2;
- const h = padY * 2 + titleSize + metaGap + metaSize;
+ const h = padY * 2 + size + (meta ? gap + size : 0);
const x = data.x + Math.max(data.size * 0.9, 16);
const y = data.y - Math.max(data.size * 1.1, 16) - h;
- /* 皮与界面上的浮层同一副(`.u-pop`:近实底 + 一条 line-strong 的边)。
- 它就是一个 tooltip——指到才有、指开就没,只是画在 canvas 上,所以数字
- 照抄而不是自己定一套 */
- ctx.shadowColor = "rgba(0,0,0,0.62)";
- ctx.shadowBlur = 15;
+ ctx.shadowColor = "rgba(0,0,0,0.35)";
+ ctx.shadowBlur = 10;
+ ctx.shadowOffsetY = 4;
ctx.beginPath();
- ctx.roundRect(x, y, w, h, 8); // --radius-panel
+ ctx.roundRect(x, y, w, h, 4); // --radius-cell
ctx.fillStyle = POP_BG;
ctx.fill();
ctx.shadowBlur = 0;
+ ctx.shadowOffsetY = 0;
ctx.strokeStyle = PILL_BORDER; // --u-line-strong
ctx.lineWidth = 1;
ctx.stroke();
ctx.fillStyle = CANVAS_TEXT;
- ctx.font = `500 ${titleSize}px ${CANVAS_FONT}`;
+ ctx.font = `500 ${size}px ${CANVAS_FONT}`;
ctx.fillText(data.label, x + padX, y + padY);
- ctx.fillStyle = CANVAS_TEXT_2;
- ctx.font = `400 ${metaSize}px ${CANVAS_FONT}`;
- ctx.fillText(meta, x + padX, y + padY + titleSize + metaGap);
+ if (meta) {
+ ctx.fillStyle = CANVAS_TEXT_2;
+ ctx.font = `400 ${size}px ${CANVAS_FONT}`;
+ ctx.fillText(meta, x + padX, y + padY + size + gap);
+ }
ctx.restore();
}
diff --git a/web/src/pages/ontologyDialogs.tsx b/web/src/pages/ontologyDialogs.tsx
new file mode 100644
index 00000000..20b88a93
--- /dev/null
+++ b/web/src/pages/ontologyDialogs.tsx
@@ -0,0 +1,831 @@
+// 本体的编辑弹窗:类、关系、属性,以及「用一个已有的关系连接这个类」。
+//
+// 右侧面板只展示,改动开一扇窗——从前三张表单嵌在面板里,改到一半的字段
+// 跟正在读的定义挤在同一列,保存与删除也挨在一起。字段一个没变,搬的是壳:
+// 表单里的每一项照旧,只是有了自己的标题、自己的页脚和 Esc。
+import { useMemo, useState } from "react";
+import { useMutation } from "@tanstack/react-query";
+import { api, type EntityTypeView, type RelationTypeView } from "../api";
+import { S } from "../i18n";
+import { toast } from "../toast";
+import {
+ Checkbox,
+ ColorPicker,
+ colorForKey,
+ Dropdown,
+ Field,
+ FormDialog,
+ Input,
+ MultiSearchSelect,
+ SearchSelect,
+ Segmented,
+ Textarea,
+} from "../ui";
+
+/** 父类下拉的候选:树序 + 缩进(层级可见),排除自己与全部后代(防成环)。 */
+export function parentOptions(
+ allTypes: EntityTypeView[],
+ selfId: string | undefined,
+): { value: string; label: string; indent: number }[] {
+ const excluded = new Set<string>();
+ if (selfId) {
+ excluded.add(selfId);
+ // 收后代:反复扫描直到收敛(类的数量级很小,O(n²) 无所谓)
+ let grew = true;
+ while (grew) {
+ grew = false;
+ for (const t of allTypes) {
+ if (t.parents.some((p) => excluded.has(p)) && !excluded.has(t.id)) {
+ excluded.add(t.id);
+ grew = true;
+ }
+ }
+ }
+ }
+ const children = new Map<string | null, EntityTypeView[]>();
+ for (const t of allTypes) {
+ const p = t.primary_parent ?? null;
+ if (!children.has(p)) children.set(p, []);
+ children.get(p)!.push(t);
+ }
+ const out: { value: string; label: string; indent: number }[] = [];
+ const walk = (parent: string | null, depth: number) => {
+ for (const t of children.get(parent) ?? []) {
+ if (excluded.has(t.id)) continue;
+ out.push({ value: t.id, label: t.label, indent: depth });
+ walk(t.id, depth + 1);
+ }
+ };
+ walk(null, 0);
+ return out;
+}
+
+const toggleIn = (
+ set: React.Dispatch<React.SetStateAction<string[]>>,
+ id: string,
+) => set((v) => (v.includes(id) ? v.filter((x) => x !== id) : [...v, id]));
+
+/* ---------- 类 ---------- */
+
+export function ClassDialog({
+ kbId,
+ existing,
+ parentId,
+ allTypes,
+ onClose,
+ onSaved,
+ onDeleted,
+ onError,
+}: {
+ kbId: string;
+ existing: EntityTypeView | null;
+ /** 新建时的父类(从左栏或定义页的「新建子类」进来时预填);多父下它是主父 */
+ parentId: string | null;
+ allTypes: EntityTypeView[];
+ onClose: () => void;
+ /** 创建成功时携带新 id,编辑成功时为 undefined */
+ onSaved: (createdId?: string) => void;
+ onDeleted: () => void;
+ onError: (e: unknown) => void;
+}) {
+ const [key, setKey] = useState(existing?.key ?? "");
+ const [label, setLabel] = useState(existing?.label ?? "");
+ // 新建时颜色跟着 key 走(与后端 color_for_key 同一个规则),不是一个固定默认值。
+ // 用户当然可以改;但**不改的话,手动建的类和导入建的类配色体系一致**
+ const [color, setColor] = useState(
+ existing?.color ?? colorForKey(existing?.key ?? ""),
+ );
+ const [colorTouched, setColorTouched] = useState(Boolean(existing?.color));
+ const [shape, setShape] = useState<"circle" | "square">(
+ existing?.shape ?? "circle",
+ );
+ const [parents, setParents] = useState<string[]>(
+ existing?.parents ?? (parentId ? [parentId] : []),
+ );
+ const [description, setDescription] = useState(existing?.description ?? "");
+ // 互斥:声明「不可能同时是」。一致性检查据此报不可满足的类(0002)——
+ // 一个类继承了两个互斥的祖先,就永远不可能有实例,而它不报错,只是永远空着
+ const [disjoint, setDisjoint] = useState<string[]>(existing?.disjoint ?? []);
+ const options = useMemo(
+ () => parentOptions(allTypes, existing?.id),
+ [allTypes, existing?.id],
+ );
+
+ const save = useMutation({
+ mutationFn: async (): Promise<unknown> =>
+ existing
+ ? api.updateEntityType(kbId, existing.id, {
+ label,
+ color,
+ shape,
+ parents,
+ disjoint,
+ description,
+ })
+ : api.createEntityType(kbId, {
+ key,
+ label,
+ color,
+ shape,
+ parents,
+ disjoint,
+ description,
+ }),
+ onSuccess: (res) => {
+ toast.success(existing ? S.toast.saved : S.toast.created);
+ onSaved(existing ? undefined : (res as { id?: string })?.id);
+ },
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: () => api.deleteEntityType(kbId, existing!.id),
+ onSuccess: () => {
+ toast.success(S.toast.deleted);
+ onDeleted();
+ },
+ onError,
+ });
+
+ return (
+ <FormDialog
+ title={existing ? S.ontology.editClass : S.ontology.newClass}
+ description={
+ existing ? `${existing.key} · ${S.ontology.usage(existing.usage)}` : undefined
+ }
+ closeLabel={S.ui.close}
+ saveLabel={S.ontology.save}
+ cancelLabel={S.ontology.cancel}
+ canSave={!!label.trim() && (!!existing || !!key.trim())}
+ busy={save.isPending}
+ onSave={() => save.mutate()}
+ onCancel={onClose}
+ danger={
+ existing && !existing.builtin
+ ? {
+ label: S.ontology.delete,
+ disabled: existing.usage > 0 || remove.isPending,
+ title: existing.usage > 0 ? S.ontology.deleteBlocked : undefined,
+ onClick: () => remove.mutate(),
+ }
+ : undefined
+ }
+ >
+ {/* key 是纯技术标识:已存在时不展示,只在创建时输入 */}
+ {!existing && (
+ <Field
+ label={
+ <>
+ {S.ontology.key}{" "}
+ <span className="text-ink-2">({S.ontology.keyHint})</span>
+ </>
+ }
+ >
+ <Input
+ autoFocus
+ value={key}
+ onChange={(e) => {
+ setKey(e.target.value);
+ // 用户没自己挑过色,就让颜色跟着 key 走——与后端同一个规则
+ if (!colorTouched) setColor(colorForKey(e.target.value));
+ }}
+ className="w-full"
+ placeholder="contract"
+ />
+ </Field>
+ )}
+ <Field label={S.ontology.label}>
+ <Input
+ autoFocus={!!existing}
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
+ </Field>
+ <Field label={S.ontology.shapeColor}>
+ <div className="flex items-center gap-2">
+ <ColorPicker
+ value={color}
+ onChange={(c: string) => {
+ setColor(c);
+ setColorTouched(true);
+ }}
+ shape={shape}
+ />
+ {/* 形状:与图谱节点渲染一一对应(circle=四层圆 / square=四层方) */}
+ <Segmented
+ size="sm"
+ value={shape}
+ onChange={setShape}
+ options={(["circle", "square"] as const).map((sh) => ({
+ value: sh,
+ title: sh,
+ // 图标占一行正文的高(h-4):Segmented 的高度由内容撑,
+ // 光秃秃的 12px 图标会让它比旁边 32 高的色井矮一截
+ label: (
+ <span className="flex h-4 items-center">
+ <span
+ className={`h-3 w-3 border-[1.5px] border-current ${
+ sh === "circle" ? "rounded-full" : "scale-90"
+ }`}
+ />
+ </span>
+ ),
+ }))}
+ />
+ </div>
+ </Field>
+ {/* 多父:subClassOf 可以有多条。左栏按树画,一个类只能出现一次——
+ 所以第一个当主父。界面说明这条,不另加一个"选主父"的控件 */}
+ <Field
+ label={S.ontology.parent}
+ hint={parents.length > 1 ? S.ontology.primaryParentHint : undefined}
+ >
+ <MultiSearchSelect
+ values={parents}
+ options={options}
+ onToggle={(id) => toggleIn(setParents, id)}
+ placeholder={S.ontology.searchTypes}
+ emptyHint={S.ontology.noParent}
+ />
+ </Field>
+ {/* 互斥:**声明「不可能同时是」**。紧挨着父类,因为两者是同一件事的
+ 两面——父类说「也是」,互斥说「不可能同时是」,而一致性检查正是
+ 在这两者打架时报出「这个类永远不可能有实例」。跟自己的父类互斥当场说,
+ 比让人跑一遍一致性检查再发现要快 */}
+ <Field
+ label={S.ontology.disjoint}
+ hint={S.ontology.disjointHint}
+ error={
+ disjoint.some((d) => parents.includes(d))
+ ? S.ontology.disjointWithParent
+ : undefined
+ }
+ >
+ <MultiSearchSelect
+ values={disjoint}
+ options={options}
+ onToggle={(id) => toggleIn(setDisjoint, id)}
+ placeholder={S.ontology.searchTypes}
+ emptyHint={S.ontology.noDisjoint}
+ />
+ </Field>
+ {/* 语义指引:整段注入抽取 prompt,直接影响抽取归类质量 */}
+ <Field
+ label={S.ontology.description}
+ hint={S.ontology.descriptionHint}
+ className="mb-0"
+ >
+ <Textarea
+ className="w-full min-h-28 resize-y"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </Field>
+ </FormDialog>
+ );
+}
+
+/* ---------- 关系 ---------- */
+
+export function PropertyDialog({
+ kbId,
+ existing,
+ allTypes,
+ allRelations,
+ initialDomain,
+ onClose,
+ onSaved,
+ onDeleted,
+ onError,
+}: {
+ kbId: string;
+ existing: RelationTypeView | null;
+ allTypes: EntityTypeView[];
+ /** 本库的关系(不含属性)。逆与子属性的下拉从这里取——**属性不在其中**,
+ * 它的宾语是字面值,反过来无从谈起 */
+ allRelations: RelationTypeView[];
+ /** 从一个类出发新建关系时,domain 预填成那个类——**只影响初始值**,
+ * 不是约束:下面照旧是个可编辑的 MultiSearchSelect,填错了随手改 */
+ initialDomain: string | null;
+ onClose: () => void;
+ onSaved: (createdId?: string) => void;
+ onDeleted: () => void;
+ onError: (e: unknown) => void;
+}) {
+ const [key, setKey] = useState(existing?.key ?? "");
+ const [label, setLabel] = useState(existing?.label ?? "");
+ const [temporal, setTemporal] = useState(existing?.temporal ?? "state");
+ const [functional, setFunctional] = useState(existing?.functional ?? false);
+ const [inverseFunctional, setInverseFunctional] = useState(
+ existing?.inverse_functional ?? false,
+ );
+ // 其余四条 OWL 公理。**推理机的判据全在这里**——从前只能靠导入 OWL 带进来,
+ // 在界面上手工建本体的人永远开不了那台机器(0002)
+ const [transitive, setTransitive] = useState(existing?.is_transitive ?? false);
+ const [symmetric, setSymmetric] = useState(existing?.is_symmetric ?? false);
+ const [asymmetric, setAsymmetric] = useState(existing?.is_asymmetric ?? false);
+ const [irreflexive, setIrreflexive] = useState(
+ existing?.is_irreflexive ?? false,
+ );
+ // 同一族的后两条,形状不同:指向另一个关系。空串 = 没声明
+ const [inverseOf, setInverseOf] = useState(existing?.inverse_of ?? "");
+ const [subPropertyOf, setSubPropertyOf] = useState(
+ existing?.sub_property_of ?? "",
+ );
+ const [description, setDescription] = useState(existing?.description ?? "");
+ const [domains, setDomains] = useState<string[]>(
+ existing?.domains ?? (initialDomain ? [initialDomain] : []),
+ );
+ const [ranges, setRanges] = useState<string[]>(existing?.ranges ?? []);
+ // 显示标签,不显示 key。**进提示词的 key 由服务端从库里取**,与界面显示什么无关
+ const typeOpts = useMemo(() => parentOptions(allTypes, undefined), [allTypes]);
+ // 两个下拉的选项:本库的其它关系。**自己不进列表**,两条都是:子属性指向自己
+ // 数据库直接拒(那是个环);逆指向自己等于 symmetric,那个复选框就在上面。
+ // 唯一的例外是**当前值就是自己**:OWL 导入进来的可以长这样,从列表里漏掉它
+ // 就会让下拉显示空白,而空白一保存就把已声明的抹了
+ const linkOptions = (current: string) => [
+ { value: "", label: S.ontology.noLink },
+ ...(existing && current === existing.id
+ ? [{ value: existing.id, label: existing.label, hint: existing.key }]
+ : []),
+ ...allRelations
+ .filter((r) => r.id !== existing?.id)
+ .map((r) => ({ value: r.id, label: r.label, hint: r.key })),
+ ];
+ /** 下拉里选中那条的显示名。找不到就回落到 id——宁可难看,不要空着 */
+ const nameOf = (id: string) =>
+ allRelations.find((r) => r.id === id)?.label ?? id;
+
+ const save = useMutation({
+ mutationFn: async (): Promise<unknown> => {
+ const body = {
+ label,
+ temporal,
+ functional,
+ inverse_functional: inverseFunctional,
+ is_transitive: transitive,
+ is_symmetric: symmetric,
+ is_asymmetric: asymmetric,
+ is_irreflexive: irreflexive,
+ // 空串要变成 null 再送——服务端收 `Option<Uuid>`,
+ // `""` 解不成 UUID,会是一个 422 而不是「清空」
+ inverse_of: inverseOf || null,
+ sub_property_of: subPropertyOf || null,
+ description,
+ domains,
+ ranges,
+ };
+ return existing
+ ? api.updateRelationType(kbId, existing.id, body)
+ : api.createRelationType(kbId, { key, ...body });
+ },
+ onSuccess: (res) => {
+ toast.success(existing ? S.toast.saved : S.toast.created);
+ onSaved(existing ? undefined : (res as { id?: string })?.id);
+ },
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: () => api.deleteRelationType(kbId, existing!.id),
+ onSuccess: () => {
+ toast.success(S.toast.deleted);
+ onDeleted();
+ },
+ onError,
+ });
+
+ return (
+ <FormDialog
+ width="lg"
+ title={existing ? S.ontology.editProperty : S.ontology.newProperty}
+ description={
+ existing ? `${existing.key} · ${S.ontology.usage(existing.usage)}` : undefined
+ }
+ closeLabel={S.ui.close}
+ saveLabel={S.ontology.save}
+ cancelLabel={S.ontology.cancel}
+ canSave={!!label.trim() && (!!existing || !!key.trim())}
+ busy={save.isPending}
+ onSave={() => save.mutate()}
+ onCancel={onClose}
+ danger={
+ existing && !existing.builtin
+ ? {
+ label: S.ontology.delete,
+ disabled: existing.usage > 0 || remove.isPending,
+ title: existing.usage > 0 ? S.ontology.deleteBlocked : undefined,
+ onClick: () => remove.mutate(),
+ }
+ : undefined
+ }
+ >
+ {!existing && (
+ <Field
+ label={
+ <>
+ {S.ontology.key}{" "}
+ <span className="text-ink-2">({S.ontology.keyHint})</span>
+ </>
+ }
+ >
+ <Input
+ autoFocus
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ className="w-full"
+ placeholder="signed_with"
+ />
+ </Field>
+ )}
+ <Field label={S.ontology.label}>
+ <Input
+ autoFocus={!!existing}
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
+ </Field>
+ {/* 类型签名。界面显示标签,而进提示词的是 key —— 那一步在服务端(0004) */}
+ <Field label={S.ontology.signature} hint={S.ontology.signatureHint}>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <div className="min-w-0">
+ <div className="mb-1 text-small text-ink-2">{S.ontology.domainLabel}</div>
+ <MultiSearchSelect
+ values={domains}
+ options={typeOpts}
+ onToggle={(id) => toggleIn(setDomains, id)}
+ placeholder={S.ontology.searchTypes}
+ emptyHint={S.ontology.anyType}
+ />
+ </div>
+ <div className="min-w-0">
+ <div className="mb-1 text-small text-ink-2">{S.ontology.rangeLabel}</div>
+ <MultiSearchSelect
+ values={ranges}
+ options={typeOpts}
+ onToggle={(id) => toggleIn(setRanges, id)}
+ placeholder={S.ontology.searchTypes}
+ emptyHint={S.ontology.anyType}
+ />
+ </div>
+ </div>
+ </Field>
+ <Field label={S.ontology.temporal}>
+ <Dropdown
+ value={temporal}
+ onChange={setTemporal}
+ className="w-full"
+ options={[
+ { value: "state", label: S.ontology.temporalState },
+ { value: "event", label: S.ontology.temporalEvent },
+ { value: "eternal", label: S.ontology.temporalEternal },
+ ]}
+ />
+ </Field>
+ {/* 六条公理并成一组。**它们本来就是同一族**——推理机(0002)拿它们当判据。
+ 每一条底下写清「勾了会发生什么」:这些开关不是描述,是会改变系统行为的
+ 声明。对称与反对称同时勾是自相矛盾的(只对空关系成立),当场说一句 */}
+ <Field
+ label={S.ontology.axioms}
+ hint={S.ontology.axiomsHint}
+ error={symmetric && asymmetric ? S.ontology.axiomConflict : undefined}
+ >
+ <div className="space-y-2">
+ {(
+ [
+ [functional, setFunctional, S.ontology.functional, S.ontology.functionalHint],
+ [
+ inverseFunctional,
+ setInverseFunctional,
+ S.ontology.inverseFunctional,
+ S.ontology.inverseFunctionalHint,
+ ],
+ [transitive, setTransitive, S.ontology.transitive, S.ontology.transitiveHint],
+ [symmetric, setSymmetric, S.ontology.symmetric, S.ontology.symmetricHint],
+ [asymmetric, setAsymmetric, S.ontology.asymmetric, S.ontology.asymmetricHint],
+ [
+ irreflexive,
+ setIrreflexive,
+ S.ontology.irreflexive,
+ S.ontology.irreflexiveHint,
+ ],
+ ] as const
+ ).map(([on, set, title, hint], i) => (
+ <Checkbox
+ key={i}
+ checked={on}
+ onChange={(e) => set(e.target.checked)}
+ label={title}
+ hint={hint}
+ />
+ ))}
+ </div>
+ </Field>
+ {/* 同一组的后两条,只是形状不同:它们指向**另一个关系**,所以是下拉不是复选框。
+ 选了之后当场把话说全——**这两条推出来的事实主宾未必同向**,逆要对调,
+ 子属性不对调,只看名字分不出来,写出来就分得出 */}
+ <div className="grid gap-2 sm:grid-cols-2">
+ <Field label={S.ontology.inverseOf} hint={S.ontology.inverseOfHint}>
+ <SearchSelect
+ value={inverseOf}
+ onChange={setInverseOf}
+ options={linkOptions(inverseOf)}
+ size="sm"
+ className="w-full"
+ placeholder={S.ontology.noLink}
+ />
+ </Field>
+ <Field label={S.ontology.subPropertyOf} hint={S.ontology.subPropertyOfHint}>
+ <SearchSelect
+ value={subPropertyOf}
+ onChange={setSubPropertyOf}
+ options={linkOptions(subPropertyOf)}
+ size="sm"
+ className="w-full"
+ placeholder={S.ontology.noLink}
+ />
+ </Field>
+ </div>
+ {(inverseOf || subPropertyOf) && (
+ <div className="mb-4 -mt-2 space-y-1 text-fine leading-relaxed text-ink-2">
+ {inverseOf && (
+ <div>
+ {S.ontology.linkMeansInverse(label.trim() || key || "?", nameOf(inverseOf))}
+ </div>
+ )}
+ {subPropertyOf && (
+ <div>
+ {S.ontology.linkMeansSuper(label.trim() || key || "?", nameOf(subPropertyOf))}
+ </div>
+ )}
+ </div>
+ )}
+ <Field
+ label={S.ontology.description}
+ hint={S.ontology.descriptionHint}
+ className="mb-0"
+ >
+ <Textarea
+ className="w-full min-h-28 resize-y"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </Field>
+ </FormDialog>
+ );
+}
+
+/* ---------- 属性(一个类的字面值字段) ---------- */
+
+export function AttributeDialog({
+ kbId,
+ typeId,
+ existing,
+ onClose,
+ onSaved,
+ onDeleted,
+ onError,
+}: {
+ kbId: string;
+ typeId: string;
+ existing: RelationTypeView | null;
+ onClose: () => void;
+ onSaved: () => void;
+ onDeleted: () => void;
+ onError: (e: unknown) => void;
+}) {
+ const [key, setKey] = useState(existing?.key ?? "");
+ const [label, setLabel] = useState(existing?.label ?? "");
+ const [datatype, setDatatype] = useState(existing?.datatype ?? "text");
+ const [unit, setUnit] = useState(existing?.unit ?? "");
+ // 单值 = functional:新值经时态引擎闭合旧值(属性历史的来源)。多数属性如此,默认开
+ const [single, setSingle] = useState(existing?.functional ?? true);
+ const [description, setDescription] = useState(existing?.description ?? "");
+
+ const save = useMutation({
+ mutationFn: async (): Promise<unknown> =>
+ existing
+ ? api.updateRelationType(kbId, existing.id, {
+ label,
+ temporal: existing.temporal,
+ functional: single,
+ inverse_functional: false,
+ description,
+ datatype,
+ unit,
+ })
+ : api.createRelationType(kbId, {
+ key,
+ label,
+ kind: "attribute",
+ domains: [typeId],
+ temporal: "state",
+ functional: single,
+ inverse_functional: false,
+ description,
+ datatype,
+ unit,
+ }),
+ onSuccess: () => {
+ toast.success(existing ? S.toast.saved : S.toast.created);
+ onSaved();
+ },
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: () => api.deleteRelationType(kbId, existing!.id),
+ onSuccess: () => {
+ toast.success(S.toast.deleted);
+ onDeleted();
+ },
+ onError,
+ });
+
+ return (
+ <FormDialog
+ title={existing ? S.ontology.editAttribute : S.ontology.newAttribute}
+ description={
+ existing ? `${existing.key} · ${S.ontology.usage(existing.usage)}` : undefined
+ }
+ closeLabel={S.ui.close}
+ saveLabel={S.ontology.save}
+ cancelLabel={S.ontology.cancel}
+ canSave={!!label.trim() && (!!existing || !!key.trim())}
+ busy={save.isPending}
+ onSave={() => save.mutate()}
+ onCancel={onClose}
+ danger={
+ existing
+ ? {
+ label: S.ontology.delete,
+ disabled: existing.usage > 0 || remove.isPending,
+ title: existing.usage > 0 ? S.ontology.deleteBlocked : undefined,
+ onClick: () => remove.mutate(),
+ }
+ : undefined
+ }
+ >
+ {existing ? (
+ <Field label={S.ontology.label}>
+ <Input
+ autoFocus
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
+ </Field>
+ ) : (
+ <div className="grid grid-cols-2 gap-4">
+ <Field label={S.ontology.key}>
+ <Input
+ autoFocus
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ className="w-full"
+ placeholder="salary"
+ />
+ </Field>
+ <Field label={S.ontology.label}>
+ <Input
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ className="w-full"
+ />
+ </Field>
+ </div>
+ )}
+ <div className="grid grid-cols-2 gap-4">
+ <Field label={S.ontology.attrDatatype}>
+ <Dropdown
+ value={datatype}
+ onChange={(v) => setDatatype(v as typeof datatype)}
+ className="w-full"
+ options={(["text", "number", "date", "bool"] as const).map((d) => ({
+ value: d,
+ label: S.ontology.datatypeNames[d],
+ }))}
+ />
+ </Field>
+ <Field
+ label={
+ <>
+ {S.ontology.attrUnit}{" "}
+ <span className="text-ink-2">({S.ontology.attrUnitHint})</span>
+ </>
+ }
+ >
+ <Input
+ value={unit}
+ onChange={(e) => setUnit(e.target.value)}
+ className="w-full"
+ />
+ </Field>
+ </div>
+ <div className="mb-4">
+ <Checkbox
+ checked={single}
+ onChange={(e) => setSingle(e.target.checked)}
+ label={S.ontology.attrSingle}
+ />
+ </div>
+ <Field label={S.ontology.description} className="mb-0">
+ <Textarea
+ className="w-full min-h-24 resize-y"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </Field>
+ </FormDialog>
+ );
+}
+
+/* ---------- 用一个已有的关系连接这个类 ---------- */
+
+export function ConnectDialog({
+ kbId,
+ cls,
+ relations,
+ onClose,
+ onConnected,
+ onError,
+}: {
+ kbId: string;
+ cls: EntityTypeView;
+ /** kind === "relation" 的那些 */
+ relations: RelationTypeView[];
+ onClose: () => void;
+ /** 连完带着那条关系的 id:调用方跳过去,域/值域改没改一眼可见 */
+ onConnected: (relationId: string) => void;
+ onError: (e: unknown) => void;
+}) {
+ const [relationId, setRelationId] = useState("");
+ const [side, setSide] = useState<"domain" | "range">("domain");
+ const connect = useMutation({
+ mutationFn: () => {
+ const rel = relations.find((r) => r.id === relationId);
+ if (!rel) return Promise.reject(new Error("relation not found"));
+ // 只加不减:已经连着的那一侧原样保留,另一侧才可能被追加。
+ // Set 去重——挑到已经连过的关系时这是个无害的空操作
+ const domains =
+ side === "domain" ? [...new Set([...rel.domains, cls.id])] : rel.domains;
+ const ranges =
+ side === "range" ? [...new Set([...rel.ranges, cls.id])] : rel.ranges;
+ return api.updateRelationType(kbId, rel.id, {
+ label: rel.label,
+ temporal: rel.temporal,
+ functional: rel.functional,
+ inverse_functional: rel.inverse_functional,
+ is_transitive: rel.is_transitive,
+ is_symmetric: rel.is_symmetric,
+ is_asymmetric: rel.is_asymmetric,
+ is_irreflexive: rel.is_irreflexive,
+ inverse_of: rel.inverse_of,
+ sub_property_of: rel.sub_property_of,
+ description: rel.description,
+ domains,
+ ranges,
+ });
+ },
+ onSuccess: () => {
+ const rel = relations.find((r) => r.id === relationId);
+ toast.success(S.ontology.schemaConnected(rel?.label ?? ""));
+ onConnected(relationId);
+ },
+ onError,
+ });
+ return (
+ <FormDialog
+ width="sm"
+ title={S.ontology.connectTitle}
+ description={S.ontology.schemaConnectHint}
+ closeLabel={S.ui.close}
+ saveLabel={S.ontology.schemaConnect}
+ cancelLabel={S.ontology.cancel}
+ canSave={!!relationId}
+ busy={connect.isPending}
+ onSave={() => connect.mutate()}
+ onCancel={onClose}
+ >
+ <Field label={S.ontology.tabProperties}>
+ <SearchSelect
+ value={relationId}
+ onChange={setRelationId}
+ options={relations.map((r) => ({ value: r.id, label: r.label, hint: r.key }))}
+ className="w-full"
+ placeholder={S.ontology.schemaConnectPlaceholder}
+ />
+ </Field>
+ <Field label={`${S.ontology.schemaConnectAs} ${cls.label}`} className="mb-0">
+ <Segmented
+ size="sm"
+ value={side}
+ onChange={setSide}
+ options={[
+ { value: "domain", label: S.ontology.domainLabel },
+ { value: "range", label: S.ontology.rangeLabel },
+ ]}
+ />
+ </Field>
+ </FormDialog>
+ );
+}
diff --git a/web/src/ui/dialog.tsx b/web/src/ui/dialog.tsx
index b0a72730..1c1347e2 100644
--- a/web/src/ui/dialog.tsx
+++ b/web/src/ui/dialog.tsx
@@ -136,3 +136,94 @@ export function DangerConfirm({
</Dialog>
);
}
+
+/* ---------- FormDialog(编辑弹窗) ----------
+ 类、属性、关系、实体、事实区间的改动都在这一个壳里:面板只展示,改动开一扇窗。
+ 正文包在 <form> 里——输入框里按 Enter 就是保存;页脚在表单之外,取消与删除
+ 不会被当成提交。与 DangerConfirm 一样**总是挂载着**(open 恒真):调用方条件渲染。
+ 删除放在左下角、次要样式:它和保存不是一对,隔开才不会顺手点到 */
+export function FormDialog({
+ title,
+ description,
+ closeLabel,
+ width = "md",
+ saveLabel,
+ cancelLabel,
+ canSave = true,
+ busy,
+ onSave,
+ onCancel,
+ danger,
+ children,
+}: {
+ title: ReactNode;
+ description?: ReactNode;
+ closeLabel: string;
+ width?: "sm" | "md" | "lg";
+ saveLabel: string;
+ cancelLabel: string;
+ /** 没填够就点不动保存 */
+ canSave?: boolean;
+ busy?: boolean;
+ onSave: () => void;
+ onCancel: () => void;
+ /** 左下角的破坏性动作(删除);缺省没有 */
+ danger?: {
+ label: string;
+ disabled?: boolean;
+ title?: string;
+ onClick: () => void;
+ };
+ children: ReactNode;
+}) {
+ return (
+ <Dialog
+ open
+ onOpenChange={(o) => {
+ if (!o) onCancel();
+ }}
+ title={title}
+ description={description}
+ closeLabel={closeLabel}
+ width={width}
+ footer={
+ <>
+ {danger && (
+ <Button
+ variant="secondary"
+ size="sm"
+ className="mr-auto"
+ disabled={danger.disabled || busy}
+ title={danger.title}
+ onClick={danger.onClick}
+ >
+ {danger.label}
+ </Button>
+ )}
+ <Button variant="secondary" size="sm" onClick={onCancel}>
+ {cancelLabel}
+ </Button>
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={!canSave}
+ busy={busy}
+ onClick={onSave}
+ >
+ {saveLabel}
+ </Button>
+ </>
+ }
+ >
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (canSave && !busy) onSave();
+ }}
+ >
+ {children}
+ </form>
+ </Dialog>
+ );
+}
+
diff --git a/web/src/ui/index.tsx b/web/src/ui/index.tsx
index 1ae8db5e..a9e7ba62 100644
--- a/web/src/ui/index.tsx
+++ b/web/src/ui/index.tsx
@@ -1578,7 +1578,7 @@ export const HOVER_ROW =
export const REVEAL = "u-reveal";
/* 各在自己文件里的组件,从这里一并导出,页面只认 "../ui" 一个入口 */
-export { Dialog, DangerConfirm } from "./dialog";
+export { Dialog, DangerConfirm, FormDialog } from "./dialog";
export { Tooltip } from "./tooltip";
export { Table, THead, TBody, Tr, Th, Td } from "./table";
export { Field } from "./field";