Skip to content

World's first open-source enterprise world model.

Relations get imported at all, and their signature can be edited (#68)

WaylandYang1edeacce8c40
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 9485bcc5..f1cdc143 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -191,12 +191,14 @@ pub struct RelationTypeReq {
/// relation | attribute(创建时定死,更新时忽略)
#[serde(default)]
pub kind: Option<String>,
- /// 可以当主语的类。attribute 至少一个;relation 留空 = 不限
+ /// 可以当主语的类。attribute 至少一个;relation 留空 = 不限。
+ /// **更新时缺省 = 不动**,所以是 Option 而不是 Vec——不管 domain 的
+ /// 调用方(属性表单)不该因为一次改名就把 domain 清空
#[serde(default)]
- pub domains: Vec<Uuid>,
+ pub domains: Option<Vec<Uuid>>,
/// 可以当宾语的类。只对 relation 有意义
#[serde(default)]
- pub ranges: Vec<Uuid>,
+ pub ranges: Option<Vec<Uuid>>,
/// attribute 专用:text | number | date | bool
#[serde(default)]
pub datatype: Option<String>,
@@ -232,8 +234,8 @@ pub async fn create_relation_type(
req.inverse_functional,
req.description.as_deref().unwrap_or("").trim(),
kind,
- &req.domains,
- &req.ranges,
+ req.domains.as_deref().unwrap_or(&[]),
+ req.ranges.as_deref().unwrap_or(&[]),
req.datatype.as_deref(),
req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
)
@@ -269,6 +271,9 @@ pub async fn update_relation_type(
req.description.as_deref().unwrap_or("").trim(),
req.datatype.as_deref(),
req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
+ // 请求里没带这两个字段就不动它们——属性表单不管 domain
+ req.domains.as_deref(),
+ req.ranges.as_deref(),
)
.await?;
let _ = utopia_store::audit::record(
diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rs
index 9064fe02..4dae442d 100644
--- a/crates/utopia-server/src/owl_import.rs
+++ b/crates/utopia-server/src/owl_import.rs
@@ -361,14 +361,72 @@ pub async fn apply(
}
}
- // 属性:类建完、id_of 填好之后才轮到它们。计划里已经算出了每个属性的去向,
- // **这里只执行,不重新判断**——两处各判一次就会分叉,而分叉意味着
- // 预览说的和实际做的不是一回事
let by_prop_iri: HashMap<&str, &_> = proj
.properties
.iter()
.map(|p| (p.iri.as_str(), p))
.collect();
+ // 关系。此前 apply 完全跳过它们——预览却在关系那行写着"N new",
+ // 承诺了不会发生的事。这与今天修掉的 key 撞车缺陷是同一种。
+ //
+ // **functional / inverse_functional 照词汇表的声明写下去**:它们是时态引擎
+ // 自动闭合事实的依据,猜错会成批造假冲突(part_of 那次 59 条)。所以不猜——
+ // 词汇表说是就是,预览已经把它们单独列出来让人过目。
+ let mut created_rels = 0usize;
+ let mut updated_rels = 0usize;
+ for item in &plan.relations {
+ if item.disposition == Disposition::KeyTaken {
+ continue;
+ }
+ let Some(p) = by_prop_iri.get(item.iri.as_str()) else {
+ continue;
+ };
+ // domain/range 指向没被建出来的类时只丢那一个,不丢整条关系:
+ // 关系不像属性那样必须挂在类上,没有 domain 就是"不限主语类型"
+ let resolve = |iris: &[String]| -> Vec<Uuid> {
+ iris.iter().filter_map(|i| id_of.get(i).copied()).collect()
+ };
+ let domains = resolve(&p.domains);
+ let ranges = resolve(&p.ranges);
+
+ if item.disposition == Disposition::Update {
+ if utopia_store::ontology::update_relation_from_import(
+ &state.pool,
+ kb_id,
+ &p.iri,
+ &p.label,
+ &p.description,
+ &domains,
+ &ranges,
+ )
+ .await?
+ {
+ updated_rels += 1;
+ }
+ continue;
+ }
+ if utopia_store::ontology::create_relation_with_iri(
+ &state.pool,
+ kb_id,
+ &p.key,
+ &p.label,
+ &p.description,
+ &p.iri,
+ p.functional,
+ p.inverse_functional,
+ &domains,
+ &ranges,
+ )
+ .await?
+ .is_some()
+ {
+ created_rels += 1;
+ }
+ }
+
+ // 属性:类建完、id_of 填好之后才轮到它们。计划里已经算出了每个属性的去向,
+ // **这里只执行,不重新判断**——两处各判一次就会分叉,而分叉意味着
+ // 预览说的和实际做的不是一回事
let mut created_attrs = 0usize;
for item in &plan.attributes {
if item.disposition == Disposition::KeyTaken {
@@ -412,6 +470,8 @@ pub async fn apply(
"classes_updated": updated_classes,
"classes_key_taken": plan.classes.iter().filter(|c| c.disposition == Disposition::KeyTaken).count(),
"relations_seen": plan.relations.len(),
+ "relations_created": created_rels,
+ "relations_updated": updated_rels,
"attributes_seen": plan.attributes.len(),
"attributes_created": created_attrs,
"attributes_skipped": plan.attr_skips(),
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index f4cebd85..27e40760 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -335,6 +335,10 @@ pub async fn update_relation_type(
description: &str,
datatype: Option<&str>,
unit: Option<&str>,
+ // None = 不动。不管 domain 的调用方(属性表单)传 None,
+ // 否则一次不相干的改名就会把属性的 domain 清空
+ domains: Option<&[Uuid]>,
+ ranges: Option<&[Uuid]>,
) -> AppResult<()> {
if !matches!(temporal, "state" | "event" | "eternal") {
return Err(AppError::Validation(
@@ -346,7 +350,8 @@ pub async fn update_relation_type(
"datatype must be text / number / date / bool".into(),
));
}
- // kind 与 domain 不可变(改 kind 会让存量事实语义错乱;挪类=删了重建);
+ // kind 不可变(改它会让存量事实语义错乱)。domain/range 可改——
+ // 它们是签名不是身份,"这个属性也适用于承包商" 是个正当的编辑。
// datatype/unit 只对 attribute 行生效,datatype 缺省保持原值
let res = sqlx::query(
"UPDATE relation_types SET label = $3, temporal = $4, functional = $5, inverse_functional = $6, description = $7,
@@ -368,6 +373,26 @@ pub async fn update_relation_type(
if res.rows_affected() == 0 {
return Err(AppError::NotFound);
}
+ if domains.is_some() || ranges.is_some() {
+ let (kind,): (String,) = sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?;
+ let next_domains = domains.unwrap_or(&[]);
+ if kind == "attribute" && next_domains.is_empty() {
+ return Err(AppError::invalid(
+ "attr_needs_class",
+ "An attribute needs a class (domain)",
+ ));
+ }
+ // 属性没有 range:它的值域是字面量类型,落在 datatype 上
+ let next_ranges: &[Uuid] = if kind == "attribute" {
+ &[]
+ } else {
+ ranges.unwrap_or(&[])
+ };
+ set_domains_ranges(pool, id, next_domains, next_ranges).await?;
+ }
Ok(())
}
@@ -569,6 +594,87 @@ pub async fn create_attribute_with_iri(
Ok(Some(new_id))
}
+/// 从导入建一个关系(`kind='relation'`),带 IRI。
+///
+/// `temporal` 固定 `state`:OWL 没有对应概念,而 state(有区间)是三者里唯一
+/// 不丢信息的——event 会把区间压成时点,eternal 会宣称它永不改变。
+///
+/// **`functional` / `inverse_functional` 照词汇表写**。它们驱动时态引擎自动闭合
+/// 旧事实,猜错就成批造假冲突(`part_of` 那次 59 条)。预览已经把声明为函数性的
+/// 关系单独列出来让人过目,所以这里不再自作主张改成 false。
+#[allow(clippy::too_many_arguments)]
+pub async fn create_relation_with_iri(
+ pool: &PgPool,
+ kb_id: Uuid,
+ key: &str,
+ label: &str,
+ description: &str,
+ iri: &str,
+ functional: bool,
+ inverse_functional: bool,
+ domains: &[Uuid],
+ ranges: &[Uuid],
+) -> AppResult<Option<Uuid>> {
+ validate_key(key)?;
+ let id = Uuid::now_v7();
+ let row: Option<(Uuid,)> = sqlx::query_as(
+ "INSERT INTO relation_types
+ (id, kb_id, key, label, temporal, functional, inverse_functional,
+ description, kind, iri)
+ VALUES ($1, $2, $3, $4, 'state', $5, $6, $7, 'relation', $8)
+ ON CONFLICT (kb_id, key) DO NOTHING
+ RETURNING id",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(key)
+ .bind(label)
+ .bind(functional)
+ .bind(inverse_functional)
+ .bind(description)
+ .bind(iri)
+ .fetch_optional(pool)
+ .await?;
+ let Some((new_id,)) = row else {
+ return Ok(None);
+ };
+ set_domains_ranges(pool, new_id, domains, ranges).await?;
+ Ok(Some(new_id))
+}
+
+/// 重导入时更新一个已按 IRI 认下的关系。
+///
+/// **key 不动**(它可能已被事实引用),**空描述不覆盖**(人写过的比上游的准),
+/// **domain/range 整体重写**——它们是上游声明的结构,不是人调过的措辞。
+pub async fn update_relation_from_import(
+ pool: &PgPool,
+ kb_id: Uuid,
+ iri: &str,
+ label: &str,
+ description: &str,
+ domains: &[Uuid],
+ ranges: &[Uuid],
+) -> AppResult<bool> {
+ let row: Option<(Uuid,)> = sqlx::query_as(
+ "UPDATE relation_types
+ SET label = $3,
+ description = CASE WHEN $4 = '' THEN description ELSE $4 END
+ WHERE kb_id = $1 AND iri = $2
+ RETURNING id",
+ )
+ .bind(kb_id)
+ .bind(iri)
+ .bind(label)
+ .bind(description)
+ .fetch_optional(pool)
+ .await?;
+ let Some((id,)) = row else {
+ return Ok(false);
+ };
+ set_domains_ranges(pool, id, domains, ranges).await?;
+ Ok(true)
+}
+
pub async fn set_parent(pool: &PgPool, kb_id: Uuid, child: Uuid, parent: Uuid) -> AppResult<()> {
if child == parent {
return Ok(());
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 85e50b6e..94857f28 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -687,6 +687,16 @@ export const en = {
shapeColor: "Shape & color",
parent: "Parent class",
noParent: "(top level)",
+ /* 类型签名。措辞要说清它是引导不是闸门——本体写错时模型仍可覆盖 */
+ signature: "Type signature",
+ signatureHint:
+ "Which classes this relation connects. It goes into the extraction prompt as a hint, " +
+ "not a gate: it steers the model as it writes, and the text still wins when the " +
+ "ontology is wrong.",
+ domainLabel: "Subject",
+ rangeLabel: "Object",
+ anyType: "Any type",
+ searchTypes: "Search classes…",
temporal: "Temporal semantics",
temporalState: "State (has interval)",
temporalEvent: "Event (point in time)",
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index ccc89987..82763357 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -640,6 +640,14 @@ export const zh: Strings = {
shapeColor: "形状与颜色",
parent: "父类",
noParent: "(顶层)",
+ signature: "类型签名",
+ signatureHint:
+ "这个关系连接哪些类。它作为提示进抽取提示词,不是闸门——" +
+ "它在模型落笔那一刻引导,而本体写错时原文仍然说了算。",
+ domainLabel: "主语",
+ rangeLabel: "宾语",
+ anyType: "不限类型",
+ searchTypes: "搜索类…",
temporal: "时态语义",
temporalState: "状态(有区间)",
temporalEvent: "事件(时间点)",
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 2f239260..7b7572e0 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -25,6 +25,7 @@ import {
Dropdown,
Input,
Loading,
+ MultiSearchSelect,
Pager,
PageTitle,
RAIL_CLS,
@@ -322,6 +323,7 @@ export function Ontology() {
key={selectedProp?.id ?? "new"}
kbId={kb.id}
existing={selectedProp}
+ allTypes={entity_types}
onDone={(createdId) => {
if (sel?.kind === "new-relation")
setSel(
@@ -1062,11 +1064,13 @@ function ClassForm({
function PropertyForm({
kbId,
existing,
+ allTypes,
onDone,
onError,
}: {
kbId: string;
existing: RelationTypeView | null;
+ allTypes: EntityTypeView[];
onDone: (createdId?: string) => void;
onError: (e: unknown) => void;
}) {
@@ -1078,6 +1082,19 @@ function PropertyForm({
existing?.inverse_functional ?? false,
);
const [description, setDescription] = useState(existing?.description ?? "");
+ const [domains, setDomains] = useState<string[]>(existing?.domains ?? []);
+ const [ranges, setRanges] = useState<string[]>(existing?.ranges ?? []);
+ // 显示标签,不显示 key。**进提示词的 key 由服务端从库里取**,与界面显示什么无关;
+ // 而类树、属性列表也都显示标签,这里没有理由例外——中文库里用户该看到
+ // "发票记录" 而不是 invoice_record
+ const typeOpts = useMemo(
+ () => parentOptions(allTypes, undefined),
+ [allTypes],
+ );
+ 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> =>
@@ -1088,6 +1105,8 @@ function PropertyForm({
functional,
inverse_functional: inverseFunctional,
description,
+ domains,
+ ranges,
})
: api.createRelationType(kbId, {
key,
@@ -1096,6 +1115,8 @@ function PropertyForm({
functional,
inverse_functional: inverseFunctional,
description,
+ domains,
+ ranges,
}),
onSuccess: (res) => {
toast.success(existing ? S.toast.saved : S.toast.created);
@@ -1148,6 +1169,40 @@ function PropertyForm({
className="w-full"
/>
</div>
+ {/* 类型签名。界面显示标签,而进提示词的是 key —— 那一步在服务端,
+ 与这里显示什么无关(docs/decisions/0004 定的是提示词里必须用 key) */}
+ <div>
+ <label className={lbl}>{S.ontology.signature}</label>
+ <p className="text-[11px] leading-relaxed text-neutral-600 mb-1.5">
+ {S.ontology.signatureHint}
+ </p>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <div className="min-w-0">
+ <div className="text-[10px] uppercase tracking-[0.08em] text-neutral-600 mb-1">
+ {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="text-[10px] uppercase tracking-[0.08em] text-neutral-600 mb-1">
+ {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
diff --git a/web/src/ui/index.tsx b/web/src/ui/index.tsx
index bc17e7cf..bf5f06bb 100644
--- a/web/src/ui/index.tsx
+++ b/web/src/ui/index.tsx
@@ -1,6 +1,10 @@
/* Utopia UI 组件库 — 页面只用这里的组件与 styles.css 语义类,不写颜色字面量。 */
import { useEffect, useRef, useState } from "react";
-import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode } from "react";
+import type {
+ ButtonHTMLAttributes,
+ InputHTMLAttributes,
+ ReactNode,
+} from "react";
import {
ArrowUpRight,
Check,
@@ -28,7 +32,11 @@ export function Wordmark({ className }: { className?: string }) {
style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.06em" }}
>
{[...S.app.name].map((ch, i) => (
- <span key={i} className="u-letter" style={{ animationDelay: `${80 + i * 65}ms` }}>
+ <span
+ key={i}
+ className="u-letter"
+ style={{ animationDelay: `${80 + i * 65}ms` }}
+ >
{ch}
</span>
))}
@@ -47,7 +55,12 @@ type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
size?: "sm" | "md";
};
-export function Button({ variant = "primary", size = "md", className, ...props }: ButtonProps) {
+export function Button({
+ variant = "primary",
+ size = "md",
+ className,
+ ...props
+}: ButtonProps) {
return (
<button
className={cn(
@@ -62,8 +75,16 @@ export function Button({ variant = "primary", size = "md", className, ...props }
}
/* ---------- Input / Select ---------- */
-export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
- return <input className={cn("input-dark px-3 py-2 text-sm", className)} {...props} />;
+export function Input({
+ className,
+ ...props
+}: InputHTMLAttributes<HTMLInputElement>) {
+ return (
+ <input
+ className={cn("input-dark px-3 py-2 text-sm", className)}
+ {...props}
+ />
+ );
}
/* ---------- Dropdown(自制下拉,替代原生 select:原生弹层无法主题化) ---------- */
@@ -124,15 +145,23 @@ export function Dropdown({
type="button"
onClick={() => setOpen(!open)}
title={menuLabel}
- className={cn("input-dark w-full flex items-center gap-2 text-left", pad)}
+ className={cn(
+ "input-dark w-full flex items-center gap-2 text-left",
+ pad,
+ )}
>
{icon && <span className="shrink-0 text-neutral-500">{icon}</span>}
<span className="flex-1 min-w-0 truncate">
- {current?.label ?? <span className="text-neutral-600">{placeholder ?? ""}</span>}
+ {current?.label ?? (
+ <span className="text-neutral-600">{placeholder ?? ""}</span>
+ )}
</span>
<ChevronDown
size={12}
- className={cn("shrink-0 text-neutral-500 transition-transform", open && "rotate-180")}
+ className={cn(
+ "shrink-0 text-neutral-500 transition-transform",
+ open && "rotate-180",
+ )}
/>
</button>
{open && (
@@ -161,12 +190,17 @@ export function Dropdown({
)}
>
<span className="flex-1 min-w-0 truncate">{o.label}</span>
- {o.value === value && <Check size={12} className="shrink-0 text-neutral-400" />}
+ {o.value === value && (
+ <Check size={12} className="shrink-0 text-neutral-400" />
+ )}
</button>
))}
</div>
{footer && (
- <div className="border-t border-white/10" onClick={() => setOpen(false)}>
+ <div
+ className="border-t border-white/10"
+ onClick={() => setOpen(false)}
+ >
{footer}
</div>
)}
@@ -214,7 +248,9 @@ export function SearchSelect({
const current = options.find((o) => o.value === value);
const q = query.trim().toLowerCase();
const matches = q
- ? options.filter((o) => `${o.label} ${o.hint ?? ""}`.toLowerCase().includes(q))
+ ? options.filter((o) =>
+ `${o.label} ${o.hint ?? ""}`.toLowerCase().includes(q),
+ )
: options;
const visible = matches.slice(0, maxVisible);
const hidden = matches.length - visible.length;
@@ -226,7 +262,8 @@ export function SearchSelect({
inputRef.current?.blur();
};
- const pad = size === "sm" ? "pl-7 pr-2.5 py-1 text-xs" : "pl-8 pr-3 py-1.5 text-sm";
+ const pad =
+ size === "sm" ? "pl-7 pr-2.5 py-1 text-xs" : "pl-8 pr-3 py-1.5 text-sm";
const rowPad = size === "sm" ? "px-2.5 py-1 text-xs" : "px-3 py-1.5 text-sm";
return (
@@ -280,7 +317,9 @@ export function SearchSelect({
className={cn(
"w-full flex items-center gap-2 text-left",
rowPad,
- i === active ? "bg-white/[0.08] text-white" : "text-neutral-300",
+ i === active
+ ? "bg-white/[0.08] text-white"
+ : "text-neutral-300",
)}
>
{!q && !!o.indent && (
@@ -288,9 +327,13 @@ export function SearchSelect({
)}
<span className="min-w-0 flex-1 truncate">
{o.label}
- {o.hint && <span className="ml-2 text-neutral-500">{o.hint}</span>}
+ {o.hint && (
+ <span className="ml-2 text-neutral-500">{o.hint}</span>
+ )}
</span>
- {o.value === value && <Check size={12} className="shrink-0 text-neutral-400" />}
+ {o.value === value && (
+ <Check size={12} className="shrink-0 text-neutral-400" />
+ )}
</button>
))}
{visible.length === 0 && (
@@ -312,12 +355,186 @@ export function SearchSelect({
);
}
+/* ---------- MultiSearchSelect(多选版 SearchSelect) ---------- */
+
+/**
+ * 多选 + 搜索。与 [`SearchSelect`] 同一套语汇与键盘操作,三处不同:
+ *
+ * - **已选的显示在输入框上方**,各带一个移除按钮。不显示在下拉里的原因是
+ * 下拉一关就看不见了,而"我到底选了哪些"是随时要看的
+ * - **选完不关**:多选多半要连点几个,每次都重新聚焦是折磨
+ * - 已选项在列表里带勾,再点一次是取消
+ *
+ * 选项多到几百个时(大本体就是这个量级)它仍然可用——这正是它取代芯片墙的理由:
+ * 芯片墙的高度随类数线性增长,搜索框不随。
+ */
+export function MultiSearchSelect({
+ values,
+ options,
+ onToggle,
+ placeholder,
+ emptyHint,
+ className,
+ maxVisible = 8,
+}: {
+ values: string[];
+ options: SearchSelectOption[];
+ onToggle: (v: string) => void;
+ placeholder?: string;
+ /** 一个都没选时显示的话。多选留空往往是有意义的("不限"),不是没填 */
+ emptyHint?: string;
+ className?: string;
+ maxVisible?: number;
+}) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [active, setActive] = useState(0);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const q = query.trim().toLowerCase();
+ const matches = q
+ ? options.filter((o) =>
+ `${o.label} ${o.hint ?? ""}`.toLowerCase().includes(q),
+ )
+ : options;
+ const visible = matches.slice(0, maxVisible);
+ const hidden = matches.length - visible.length;
+ const picked = values
+ .map((v) => options.find((o) => o.value === v))
+ .filter((o): o is SearchSelectOption => !!o);
+
+ const toggle = (v: string) => {
+ onToggle(v);
+ setQuery("");
+ setActive(0);
+ inputRef.current?.focus();
+ };
+
+ return (
+ <div className={cn("relative", className)}>
+ {picked.length > 0 && (
+ <div className="mb-1 flex flex-wrap gap-1">
+ {picked.map((o) => (
+ <button
+ key={o.value}
+ type="button"
+ onClick={() => onToggle(o.value)}
+ className="group flex items-center gap-1 rounded-full bg-white/[0.10] px-2 py-0.5 text-[11px] text-neutral-200 hover:bg-white/[0.16] transition-colors"
+ title={o.hint ?? o.label}
+ >
+ {o.label}
+ <span className="text-neutral-500 group-hover:text-neutral-200">
+ ✕
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ {picked.length === 0 && emptyHint && (
+ <p className="mb-1 text-[11px] text-neutral-600">{emptyHint}</p>
+ )}
+ <SearchIcon
+ size={11}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-600 pointer-events-none"
+ style={{ top: undefined }}
+ />
+ <input
+ ref={inputRef}
+ className="input-dark w-full pl-7 pr-2.5 py-1 text-xs"
+ value={query}
+ placeholder={placeholder}
+ onFocus={() => {
+ setOpen(true);
+ setActive(0);
+ }}
+ onBlur={() => setOpen(false)}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setActive(0);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ setOpen(false);
+ inputRef.current?.blur();
+ } else if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setActive((a) => Math.min(a + 1, visible.length - 1));
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setActive((a) => Math.max(a - 1, 0));
+ } else if (e.key === "Enter" && visible[active]) {
+ e.preventDefault();
+ toggle(visible[active].value);
+ } else if (e.key === "Backspace" && !query && picked.length) {
+ // 空输入时退格删掉最后一个 —— 与各家 token 输入框一致
+ onToggle(picked[picked.length - 1].value);
+ }
+ }}
+ />
+ {open && (
+ <div className="u-pop u-pop-in u-pop-in-tl absolute z-50 mt-1 w-full rounded-lg shadow-xl overflow-hidden">
+ {visible.map((o, i) => (
+ <button
+ key={o.value}
+ type="button"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => toggle(o.value)}
+ onMouseEnter={() => setActive(i)}
+ className={cn(
+ "w-full flex items-center gap-2 text-left px-2.5 py-1 text-xs",
+ i === active
+ ? "bg-white/[0.08] text-white"
+ : "text-neutral-300",
+ )}
+ >
+ {!q && !!o.indent && (
+ <span className="shrink-0" style={{ width: o.indent * 14 }} />
+ )}
+ <span className="min-w-0 flex-1 truncate">
+ {o.label}
+ {o.hint && (
+ <span className="ml-2 text-neutral-500">{o.hint}</span>
+ )}
+ </span>
+ {values.includes(o.value) && (
+ <Check size={12} className="shrink-0 text-neutral-400" />
+ )}
+ </button>
+ ))}
+ {visible.length === 0 && (
+ <p className="px-2.5 py-1 text-xs text-neutral-600">
+ {S.ui.noMatches}
+ </p>
+ )}
+ {hidden > 0 && (
+ <div className="px-2.5 py-1 text-[11px] text-neutral-600 border-t border-white/5">
+ {S.ui.keepTyping(hidden)}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
/* ---------- ColorPicker(精选粉彩色板 + hex 兜底;实体色刻意不开放全色域) ---------- */
export const ENTITY_PALETTE = [
- "#7fd0ff", "#5fa8ff", "#5fd4d0", "#63e2b7",
- "#4cc38a", "#a8d878", "#ffd479", "#f2b66d",
- "#ff9d76", "#ff8a9e", "#ff9daf", "#e797d8",
- "#c4a5ff", "#9fa8ff", "#8ea5bd", "#b3b9c4",
+ "#7fd0ff",
+ "#5fa8ff",
+ "#5fd4d0",
+ "#63e2b7",
+ "#4cc38a",
+ "#a8d878",
+ "#ffd479",
+ "#f2b66d",
+ "#ff9d76",
+ "#ff8a9e",
+ "#ff9daf",
+ "#e797d8",
+ "#c4a5ff",
+ "#9fa8ff",
+ "#8ea5bd",
+ "#b3b9c4",
];
export function ColorPicker({
@@ -429,7 +646,11 @@ export function Pager({
return (
<div className="mt-3 flex items-center justify-end gap-2 text-xs text-neutral-500">
<span className="u-num">
- {S.library.pageOf(safe * pageSize + 1, Math.min((safe + 1) * pageSize, total), total)}
+ {S.library.pageOf(
+ safe * pageSize + 1,
+ Math.min((safe + 1) * pageSize, total),
+ total,
+ )}
</span>
<button
onClick={() => onPage(safe - 1)}
@@ -450,7 +671,11 @@ export function Pager({
}
/** 分页切片辅助:返回当前页数据与安全页号。 */
-export function pageSlice<T>(items: T[], page: number, pageSize: number): { rows: T[]; safe: number } {
+export function pageSlice<T>(
+ items: T[],
+ page: number,
+ pageSize: number,
+): { rows: T[]; safe: number } {
const pageCount = Math.max(1, Math.ceil(items.length / pageSize));
const safe = Math.min(page, pageCount - 1);
return { rows: items.slice(safe * pageSize, (safe + 1) * pageSize), safe };
@@ -496,7 +721,9 @@ export function DangerConfirm({
}}
>
<div className="glass-strong w-[24rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl p-5">
- <h2 className="text-[15px] font-semibold text-[var(--u-danger)] mb-2">{title}</h2>
+ <h2 className="text-[15px] font-semibold text-[var(--u-danger)] mb-2">
+ {title}
+ </h2>
<p className="text-xs text-neutral-400 leading-relaxed mb-4">{hint}</p>
{requireText && (
<input
@@ -508,7 +735,10 @@ export function DangerConfirm({
/>
)}
<div className="flex justify-end gap-2">
- <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={onCancel}>
+ <button
+ className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs"
+ onClick={onCancel}
+ >
{cancelLabel}
</button>
<button
@@ -536,12 +766,17 @@ export function Panel({
children: ReactNode;
}) {
return (
- <div className={cn(strong ? "glass-strong" : "glass", "rounded-xl", className)}>{children}</div>
+ <div
+ className={cn(strong ? "glass-strong" : "glass", "rounded-xl", className)}
+ >
+ {children}
+ </div>
);
}
/* ---------- Chip(状态胶囊) ---------- */
-export type ChipTone = "neutral" | "info" | "success" | "warn" | "danger" | "violet";
+export type ChipTone =
+ "neutral" | "info" | "success" | "warn" | "danger" | "violet";
export function Chip({
tone = "neutral",
@@ -562,18 +797,32 @@ export function Chip({
}
/* ---------- PageTitle ---------- */
-export function PageTitle({ className, children }: { className?: string; children: ReactNode }) {
+export function PageTitle({
+ className,
+ children,
+}: {
+ className?: string;
+ children: ReactNode;
+}) {
return <h2 className={cn("u-title text-lg", className)}>{children}</h2>;
}
/* ---------- EmptyState ---------- */
-export function EmptyState({ icon, children }: { icon: ReactNode; children: ReactNode }) {
+export function EmptyState({
+ icon,
+ children,
+}: {
+ icon: ReactNode;
+ children: ReactNode;
+}) {
return (
<div className="text-center">
<div className="glass mx-auto mb-4 h-14 w-14 rounded-2xl grid place-items-center text-xl font-bold text-neutral-300">
{icon}
</div>
- <div className="text-sm text-neutral-500 whitespace-pre-line">{children}</div>
+ <div className="text-sm text-neutral-500 whitespace-pre-line">
+ {children}
+ </div>
</div>
);
}
@@ -590,7 +839,13 @@ export function ErrorText({ children }: { children: ReactNode }) {
/* ---------- GithubMark(lucide 无品牌图标,官方 mark 内联) ---------- */
export function GithubMark({ size = 16 }: { size?: number }) {
return (
- <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ aria-hidden
+ >
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>
);
@@ -607,7 +862,11 @@ export function SectionMark({ text, title }: { text: string; title: string }) {
style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.06em" }}
>
{[...text].map((ch, i) => (
- <span key={i} className="u-letter" style={{ animationDelay: `${80 + i * 45}ms` }}>
+ <span
+ key={i}
+ className="u-letter"
+ style={{ animationDelay: `${80 + i * 45}ms` }}
+ >
{/* inline-flex 会折叠纯空格 span——换不折叠空格 */}
{ch === " " ? " " : ch}
</span>