mirror of
https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-11-09 20:07:43 +08:00
Merge pull request #6586 from deepseek-harness/experiment/home-code-ripple
feat(web): play a pixel and code whale on blank home clicks
This commit is contained in:
+4
-4
@@ -18,11 +18,11 @@
|
||||
en: ce28268021a38b89
|
||||
zh: 7802540e4ef04752
|
||||
/agent-note-the-slot-system-standard-single-register-four-props-shares-and-the-framework-store-seat/decision/component-props-four-shares-each-from-its-own-source-of-truth:
|
||||
en: f3fca569fa0c5168
|
||||
zh: 647a82662f6a887d
|
||||
en: c1892cb7309c0824
|
||||
zh: 21983594d0c7f24f
|
||||
/agent-note-the-slot-system-standard-single-register-four-props-shares-and-the-framework-store-seat/decision/the-chain-kind-entries-self-nominate-first-match-renders:
|
||||
en: 56278be7f3688805
|
||||
zh: 16602ffbf4baef85
|
||||
en: dad15e2e1309c9a4
|
||||
zh: ee2d13b27c92a73b
|
||||
/agent-note-the-slot-system-standard-single-register-four-props-shares-and-the-framework-store-seat/decision/the-store-seat-framework-engine-registrant-schema:
|
||||
en: 2645acc9d29c20ec
|
||||
zh: a8a2fd293ef5da04
|
||||
|
||||
@@ -50,12 +50,13 @@ A contributor whose activation order is independent from the declaring entry use
|
||||
| child render | `PropsRenderSlots<S>` | register's `children` keys | `renderSlot(key, owner)`, key statically narrowed to S; chain keys add `renderSlotChain` |
|
||||
| store | `PropsStore<H>` | store factory return type | `useStore` selector hook + `actions.*` (draft-param stripped) |
|
||||
| business | `I` | inject return type | plain data + callbacks; a reserved `hooks` compartment of bare observables arrives bound as `use<Name>` selector hooks (`InjectFace<I>`) |
|
||||
| kind-specific | `MatchedShare` / `HocShare` | SlotMap entry's kind | chain `matched`; hoc `children`, the next inner layer or the owner content |
|
||||
|
||||
`sessionId` is framework-supplied wherever `scope: 'session'` is declared — owner params do not carry it. The register call site is the double-lock choke point: a component whose renderSlot keys exceed the `children` declaration, or that misses a declared face, or whose store/inject shapes drift, is a compile error on that line. Delegation is ordinary props passing (hand the `renderSlot` function down, optionally behind a narrower signature) — there is no whitelist face object and no minting API.
|
||||
|
||||
### The chain kind: entries self-nominate, first match renders
|
||||
|
||||
The fourth `SlotKind`, `'chain'`, inverts routing authority relative to `keyed`: a keyed dispatch site picks its occupant by `entryKey`, while a chain entry nominates itself — the owner dispatches one common currency of owner props and never learns who takes over, so a new takeover package registers with zero owner edits. A chain registration carries a `select` pure selector (`ChainSelect<O, M>`: `(owner) => matched | null`) and an optional `priority` (ascending; ties keep registration = assembly order — the deployment-controllable inject topology — under the same stable sort as list `order`); registering without `select` is one of the loud-at-load cases above. At render, the outlet runs the selectors in chain order: the first non-null return elects its entry and the returned value joins the component's props as `matched` (the component never re-derives its own match), `null` passes the turn to the next entry, and all-null renders the owner's fallback body (`ChainRenderOpts`).
|
||||
A fifth kind, `'hoc'`, nests entries around owner-supplied `children` and adds a kind-specific `children` prop the same way `chain` adds `matched`; its decision lives in the [hoc slot kind note](2026-11-03-hoc-slot-kind.md). The fourth `SlotKind`, `'chain'`, inverts routing authority relative to `keyed`: a keyed dispatch site picks its occupant by `entryKey`, while a chain entry nominates itself — the owner dispatches one common currency of owner props and never learns who takes over, so a new takeover package registers with zero owner edits. A chain registration carries a `select` pure selector (`ChainSelect<O, M>`: `(owner) => matched | null`) and an optional `priority` (ascending; ties keep registration = assembly order — the deployment-controllable inject topology — under the same stable sort as list `order`); registering without `select` is one of the loud-at-load cases above. At render, the outlet runs the selectors in chain order: the first non-null return elects its entry and the returned value joins the component's props as `matched` (the component never re-derives its own match), `null` passes the turn to the next entry, and all-null renders the owner's fallback body (`ChainRenderOpts`).
|
||||
|
||||
The decline decision lives in `select`, never in a mounted component probing its own props: a component that mounts only to render null still runs its hooks and effects for nothing, and the resulting mount/unmount churn breaks memoization and React key semantics, whereas a selector is a pure function — unit-testable, zero mount side effects — the same discipline as "presentation methods are pure functions of `args`". Purity is the selector's contract: it reads no external mutable state and produces no side effects, so the routing decision is entirely a function of the owner props and safe to run on every dispatch. Selectors route; they never mint — per-dispatch object construction would churn identity every render, so wrapping a matched value in a richer face happens inside the elected component (`useMemo` keyed on `matched`).
|
||||
|
||||
|
||||
+2
-1
@@ -50,12 +50,13 @@ ctx.slots.register({
|
||||
| 子 slot 渲染 | `PropsRenderSlots<S>` | register 的 `children` 键集 | `renderSlot(key, owner)`,键参静态收窄到 S;chain 键另有 `renderSlotChain` |
|
||||
| store | `PropsStore<H>` | store 工厂的返回类型 | `useStore` selector 钩子 + `actions.*`(剥去 draft 形参) |
|
||||
| 业务 | `I` | inject 的返回类型 | 普通数据+回调;保留的 `hooks` 区域内,裸 observable 经绑定后以 `use<Name>` 选择器钩子的形式到达(`InjectFace<I>`) |
|
||||
| 按 kind | `MatchedShare` / `HocShare` | SlotMap entry 的 kind | chain 的 `matched`;hoc 的 `children`,即内一层或宿主内容 |
|
||||
|
||||
凡声明 `scope: 'session'` 之处,`sessionId` 一律由框架供给——owner 传参不携带它。register 调用点是双重类型约束的收口:组件的 renderSlot 键集超出 `children` 声明、漏接某个已声明的面、store/inject 形状漂移,任何一条都在那一行上报编译错误。转授就是普通的 props 传递(把 `renderSlot` 函数递下去,可按需包一层更窄的签名)——不存在白名单面对象,也不存在铸面 API。
|
||||
|
||||
### chain kind:entry 自荐,首个匹配项负责渲染
|
||||
|
||||
第四种 `SlotKind`——`'chain'`——把路由权相对 `keyed` 反转:keyed 的分派现场以 `entryKey` 点选占用 slot 的 entry,chain 则由 entry 自荐——owner 只分派一套格式统一的 owner props,永远不知道谁来接管,新的接管包注册进来 owner 零改动。chain 注册携带一个 `select` 纯选择器(`ChainSelect<O, M>`:`(owner) => matched | null`)与可选的 `priority`(升序;同值保持注册序 = 装配序——部署可控的 inject 拓扑——复用 list `order` 的同一稳定排序);注册缺 `select` 即上文装载即炸情形之一。渲染时 outlet 按链序依次执行各 select:首个非 null 返回值当选,该值以 `matched` 并入组件 props(组件绝不自行重新推导匹配);返回 `null` 则轮到下一个 entry;全 null 则渲染 owner 的 fallback 体(`ChainRenderOpts`)。
|
||||
第五种 kind `'hoc'` 把 entry 层层嵌套在 owner 提供的 `children` 外面,并像 `chain` 提供 `matched` 那样提供按 kind 的 `children` prop;其决策见 [hoc 插槽类型 Note](2026-11-03-hoc-slot-kind.zh.md)。第四种 `SlotKind`——`'chain'`——把路由权相对 `keyed` 反转:keyed 的分派现场以 `entryKey` 点选占用 slot 的 entry,chain 则由 entry 自荐——owner 只分派一套格式统一的 owner props,永远不知道谁来接管,新的接管包注册进来 owner 零改动。chain 注册携带一个 `select` 纯选择器(`ChainSelect<O, M>`:`(owner) => matched | null`)与可选的 `priority`(升序;同值保持注册序 = 装配序——部署可控的 inject 拓扑——复用 list `order` 的同一稳定排序);注册缺 `select` 即上文装载即炸情形之一。渲染时 outlet 按链序依次执行各 select:首个非 null 返回值当选,该值以 `matched` 并入组件 props(组件绝不自行重新推导匹配);返回 `null` 则轮到下一个 entry;全 null 则渲染 owner 的 fallback 体(`ChainRenderOpts`)。
|
||||
|
||||
「不接」的判定住在 `select` 里,绝不在挂载后的组件里自探 props:组件为了渲染 null 也得先挂载,其钩子与 effect 全部白跑,随之而来的挂载/卸载抖动还会破坏 memo 化与 React key 语义;而选择器是纯函数——可单测、零挂载副作用——与「presentation methods are pure functions of `args`」是同一条纪律。纯,就是选择器的约定:不读外部可变状态、不产副作用,路由判定因此完全是 owner props 的函数,每次分派都可安全执行。选择器只做路由,绝不创建新对象——按分派逐次构造对象会让引用每次渲染都换新;把匹配值包成更丰富的面这件事,发生在当选组件内部(以 `matched` 为依赖的 `useMemo`)。
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Bilingual-pair consistency record for 2026-11-03-hoc-slot-kind.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-03-hoc-slot-kind.md
|
||||
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers:
|
||||
en: 8292b8f9884b8802
|
||||
zh: 3a4f34ca79313c9d
|
||||
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/problem:
|
||||
en: d16c3bfef49e16be
|
||||
zh: 6714da1c9c984fe9
|
||||
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/decision:
|
||||
en: 3a4380324cfc1679
|
||||
zh: 44db368e091cbd46
|
||||
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/decision/implementation:
|
||||
en: 01189e457c91deeb
|
||||
zh: 94f7e8865b332a07
|
||||
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/decision/first-consumer:
|
||||
en: 1afdf4ceeef7a3b3
|
||||
zh: be01cf39850db0ca
|
||||
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/alternatives-considered:
|
||||
en: b4824619c502b422
|
||||
zh: 610364f2dc8cb2b7
|
||||
/agent-note-add-the-hoc-slot-kind-so-plugins-can-wrap-owner-content-in-layers/consequences:
|
||||
en: 7542ee2bc2c70258
|
||||
zh: bc0dd1dc6e50de66
|
||||
@@ -0,0 +1,72 @@
|
||||
# Agent Note: Add the `hoc` slot kind so plugins can wrap owner content in layers
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-03-hoc-slot-kind.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The home whale plays when blank space is clicked. Its canvas must paint below the content, and `.scrollBody` fills the whole body, so the canvas itself never receives clicks; only an ancestor of the content does.
|
||||
|
||||
No existing slot kind lets a plugin become an ancestor of the content:
|
||||
|
||||
| Kind | Behavior | Why it is not enough |
|
||||
|---|---|---|
|
||||
| `single` / `list` / `keyed` | Render the occupant at an owner-chosen position | The occupant is a sibling of the content |
|
||||
| `chain` | The elected entry replaces the fallback; with `overlay` it renders beside the fallback | It does not wrap |
|
||||
| Factory local slot | The caller replaces a local Component per occurrence | Only the caller chooses; plugins cannot stack |
|
||||
|
||||
The previous approach had the Conversation classify blank clicks on its body and notify the background plugin through `onBlankClick(listener) => dispose`. The Conversation thereby maintained click classification and subscription forwarding that served only a decorative plugin.
|
||||
|
||||
## Decision
|
||||
|
||||
Add a fifth kind: `hoc`.
|
||||
|
||||
| Item | Contract |
|
||||
|---|---|
|
||||
| Declaration | The parent entry's `children` lists `{ kind: 'hoc', scope }`; `SlotMap` declares `kind: 'hoc'` |
|
||||
| Rendering | `renderSlot(key, owner, { children })`; `entryKey` / `only` / `fallback` / `hookContext` are unavailable; omitted `children` renders the layers around nothing |
|
||||
| Registration | Same as `list`: required `id`, optional `order` and `priority`; the same `id` at the same `priority` throws, a different `priority` shadows |
|
||||
| Nesting order | Ascending `order`, then `priority`, then registration order; lowest outermost |
|
||||
| Layer props | Every layer receives the same owner props plus the framework-supplied `children` (the next inner layer; the innermost is the owner content); `children` is not an owner prop, `HocShare` types it, and owner props must not use that name |
|
||||
| Layer obligation | Render `children` exactly once without creating a box of its own; do not change the props passed inward |
|
||||
| No entry | `children` renders unchanged |
|
||||
| Layer crash | Each layer has its own error boundary; a crashed layer renders its `children` and abdicates, so the next render omits it |
|
||||
| Content error | An error thrown by the wrapped content passes every layer as its original error and is reported against no layer |
|
||||
| Remounting | Adding or removing a layer remounts the content inside it; a `session` or `session-maybe` layer also remounts it when its Session binding changes |
|
||||
|
||||
### Implementation
|
||||
|
||||
| Package | Realization |
|
||||
|---|---|
|
||||
| `ui-slots` | `SlotKind` includes `'hoc'`; `HocRenderOpts`, `HocKeysOf`, `HocShare`; `RenderSlotFn` has a hoc-key overload taking optional `{ children }`; `KindOptions` has a hoc branch; `SlotCore.register` / `entriesOfSlot` key hoc cells by `id` |
|
||||
| `ui-renderer` | `HocOutlet` calls `composeHocLayers` when the slot's ledger version or declaration changes (`useMemo` on the outlet instance) and nests the layers into one render function. Each layer is one Component that fixes its scope-specific Entry (`StrictSessionEntry` / `SessionMaybeEntry` / `RootEntry`), entry, slot inject, and crash reporting at composition, and receives only `owner` and the next inner layer when rendering. With no layer the outlet returns the owner content directly. `HocContentBoundary` wraps each layer's inner content and rethrows its errors as `HocContentError`, which layer boundaries pass through and `HocOutletBoundary` unwraps to the original error. The Entry chain passes `children` to the registered Component as JSX children; non-hoc entries receive `undefined`. `SlotErrorBoundary` takes a `crashed` replacement node |
|
||||
| `scripts/gen-client-catalog.ts` | Register options, a `children`-rendering example, and the `wraps-owner-content` replace risk for hoc slots |
|
||||
|
||||
### First consumer
|
||||
|
||||
| Location | Realization |
|
||||
|---|---|
|
||||
| `ui-conversation` | `conversation.hero.frame` (hoc, root) with owner props `{ hero: boolean }` wraps `.scrollBody` in every phase, so the composer does not remount when the home ends. On the home (`.root[data-phase='hero']`), the Conversation root, which paints the background, sets `isolation: isolate` as part of the frame contract, so layer decorations at negative `z-index` paint above that background and below all Conversation content. The Conversation performs no click classification for its layers |
|
||||
| `ui-brand-official` | `PixelWhale` is a frame layer: a React `onClick` on a `display: contents` frame plays the whale for primary clicks on blank space, excluding portaled overlays (`currentTarget.contains(target)`), controls (a selector), and clicks that end a text selection inside the frame. While `hero` is true it paints a canvas at negative `z-index`. The frame atlas loads through the package asset route; the renderer returns `{ play, dispose }` |
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- `onBlankClick` subscription forwarding: the Conversation owns click classification that serves only a decorative plugin.
|
||||
- Canvas below with `pointer-events: none` on `.scrollBody`: blank space cannot scroll when the home overflows.
|
||||
- A canvas with no `z-index`: it needs no stacking context, but it paints over every unpositioned Conversation content outside the `z-index: 1` home composer stack, such as composer takeovers, and depends on that unrelated rule.
|
||||
- A layer box that establishes the stacking context itself: the layer has to mirror the body's flex column layout.
|
||||
- A separate `renderNestedSlot` or a JSX `<HocSlot>` component: one more set of bindings; `hookContext` already shows that `renderSlot` can constrain its third argument per key.
|
||||
- Precompiling every slot kind per ledger version: no measurable end-to-end time difference, see #7838.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Adding or removing a layer remounts everything inside it, including the composer on the home.
|
||||
- Every non-hoc registered Component receives `children: undefined`, which overrides any owner prop of that name.
|
||||
- Each layer adds one Component and two error boundaries to the tree; each hoc slot with layers adds one outlet boundary.
|
||||
- The outlet's `[data-slot]` element sits between the owner and its content, so owner selectors cannot assume the content is a direct child.
|
||||
- React 18 recollects the component stack where an error is rethrown, so a content error reaching boundaries above a hoc slot with layers carries a component stack that starts at `HocOutletBoundary`.
|
||||
- A layer that wraps its `children` in its own error boundary catches the internal `HocContentError` rather than the original content error.
|
||||
- The frame contract holds only on the home: other phases leave the Conversation root out of the stacking order, so unportaled Conversation popovers still rise above AppFrame chrome that floats over the column, while on the home they stack only within the root.
|
||||
- `HocOutlet` keeps its layer Components through `useMemo`, as Factory local Components keep theirs; if React ever discards memoized values, both need an explicit cache, because these Components are the remount boundary of the content inside them.
|
||||
- [The slot system standard](2026-07-22-slot-type-chain-implementation.md) remains authoritative for the other kinds; this note adds the fifth.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Agent Note: 新增 `hoc` 插槽类型,让插件层层包裹宿主内容
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-03-hoc-slot-kind.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
首页鲸鱼需要在空白处被点击时播放。canvas 必须画在内容下面,`.scrollBody` 铺满整个 body,所以 canvas 自己收不到点击;能收到点击的只有内容的祖先节点。
|
||||
|
||||
现有插槽类型都不能让插件成为内容的祖先:
|
||||
|
||||
| 类型 | 行为 | 为什么不够 |
|
||||
|---|---|---|
|
||||
| `single` / `list` / `keyed` | 在宿主指定位置渲染 occupant | occupant 和内容是兄弟节点 |
|
||||
| `chain` | 选中的 entry 替换 fallback;`overlay` 时与 fallback 并排 | 不包裹 |
|
||||
| Factory 局部 slot | 调用方按次替换局部组件 | 只有调用方能选,插件无法叠加 |
|
||||
|
||||
此前的做法是由 Conversation 在 body 上判定空白点击,再通过 `onBlankClick(listener) => dispose` 通知背景插件。这让 Conversation 维护一套只服务于装饰插件的点击分类和订阅转发。
|
||||
|
||||
## Decision
|
||||
|
||||
新增第五种 kind:`hoc`。
|
||||
|
||||
| 项 | 约定 |
|
||||
|---|---|
|
||||
| 声明 | 父 entry 的 `children` 写 `{ kind: 'hoc', scope }`;`SlotMap` 中 `kind: 'hoc'` |
|
||||
| 渲染 | `renderSlot(key, owner, { children })`;`entryKey` / `only` / `fallback` / `hookContext` 不可用;省略 `children` 时各层包裹空内容 |
|
||||
| 注册 | 与 `list` 相同:必填 `id`,可选 `order`、`priority`;同 `id` 同 `priority` 抛错,不同 `priority` 遮蔽 |
|
||||
| 嵌套顺序 | 依次按 `order`、`priority`、注册顺序升序,最小者在最外层 |
|
||||
| 层的 props | 每层收到同一份 owner props,加上框架注入的 `children`(内一层,最内层是宿主内容);`children` 不属于 owner props,类型由 `HocShare` 提供,owner props 不得使用这个名字 |
|
||||
| 层的义务 | 恰好渲染一次 `children`,自身不产生盒子;不能修改传给内层的 props |
|
||||
| 无 entry | 原样渲染 `children` |
|
||||
| 层崩溃 | 每层有独立 error boundary;崩溃时该层渲染自己的 `children` 并 abdicate,下一次渲染不再包含该层 |
|
||||
| 内容出错 | 被包裹内容抛出的错误以原始错误穿过所有层,不记到任何层名下 |
|
||||
| 重新挂载 | 增减一层会让其内部内容重新挂载;`session` 或 `session-maybe` 作用域的层在 Session binding 变化时也会让内部内容重新挂载 |
|
||||
|
||||
### 实现
|
||||
|
||||
| 包 | 实现 |
|
||||
|---|---|
|
||||
| `ui-slots` | `SlotKind` 包含 `'hoc'`;`HocRenderOpts`、`HocKeysOf`、`HocShare`;`RenderSlotFn` 为 hoc key 提供接受可选 `{ children }` 的重载;`KindOptions` 有 hoc 分支;`SlotCore.register` / `entriesOfSlot` 按 `id` 划分 hoc cell |
|
||||
| `ui-renderer` | `HocOutlet` 在插槽 ledger 版本或声明变化时调用 `composeHocLayers`(`useMemo` 缓存在 outlet 实例上),把各层组合成一个嵌套渲染函数。每层是一个组件,在组合时固定按 scope 选定的 Entry(`StrictSessionEntry` / `SessionMaybeEntry` / `RootEntry`)、entry、slot inject 与崩溃上报,渲染时只接收 `owner` 与内一层。没有层时 outlet 直接返回宿主内容。`HocContentBoundary` 包住每层的内层内容,把其中的错误包装为 `HocContentError` 重新抛出;层的边界放行这种错误,`HocOutletBoundary` 再解开为原始错误。Entry 链以 JSX children 把 `children` 交给注册组件;非 hoc entry 收到 `undefined`。`SlotErrorBoundary` 接受 `crashed` 替换节点 |
|
||||
| `scripts/gen-client-catalog.ts` | hoc 插槽的注册选项、渲染 `children` 的示例,以及 `wraps-owner-content` 替换风险 |
|
||||
|
||||
### 首个使用者
|
||||
|
||||
| 位置 | 实现 |
|
||||
|---|---|
|
||||
| `ui-conversation` | `conversation.hero.frame`(hoc,root),owner props 为 `{ hero: boolean }`,在所有阶段包裹 `.scrollBody`,首页结束时输入框不重新挂载。首页阶段(`.root[data-phase='hero']`),绘制背景的 Conversation 根元素设置 `isolation: isolate`,这是 frame 契约的一部分:层中负 `z-index` 的装饰画在该背景之上、所有 Conversation 内容之下。Conversation 不为层做任何点击判定 |
|
||||
| `ui-brand-official` | `PixelWhale` 是 frame 层:`display: contents` 外框上的 React `onClick` 在主按钮点击留白时播放,排除 portal 浮层(`currentTarget.contains(target)`)、控件(选择器)和结束外框内文字选择的点击。`hero` 为 true 时以负 `z-index` 绘制 canvas。帧图经包 asset 路由加载;渲染器返回 `{ play, dispose }` |
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- `onBlankClick` 订阅转发:Conversation 承担只为装饰插件服务的点击分类。
|
||||
- canvas 放底下、`.scrollBody` 设 `pointer-events: none`:首页溢出时空白处无法滚动。
|
||||
- 不设 `z-index` 的 canvas:不需要层叠上下文,但会画在 `z-index: 1` 的首页输入区以外的所有非定位 Conversation 内容之上(例如输入区接管面板),并依赖那条无关的规则。
|
||||
- 由层自己的盒子建立层叠上下文:层必须复刻 body 的 flex 列布局。
|
||||
- 单独的 `renderNestedSlot` / JSX 组件 `<HocSlot>`:多一套绑定;`hookContext` 已证明可以按 key 约束 `renderSlot` 的第三个参数。
|
||||
- 按 ledger 版本预编译所有插槽类型:端到端测不出耗时差异,见 #7838。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 增减一层会让其内部所有内容重新挂载,包括首页的输入框。
|
||||
- 所有非 hoc 的注册组件都会收到 `children: undefined`,会覆盖同名的 owner prop。
|
||||
- 每层在组件树中多一个组件和两个 error boundary;有层的 hoc 插槽另多一个 outlet 边界。
|
||||
- outlet 的 `[data-slot]` 元素位于 owner 与内容之间,owner 侧选择器不能假定内容是直接子元素。
|
||||
- React 18 会在错误被重新抛出的位置重新采集组件栈,因此有层的 hoc 插槽之上的边界收到的内容错误,组件栈从 `HocOutletBoundary` 开始。
|
||||
- 层如果自己在 `children` 外包错误边界,捕获到的是内部的 `HocContentError`,而不是原始的内容错误。
|
||||
- frame 契约只在首页阶段成立:其他阶段根元素不参与层叠隔离,未经 portal 的 Conversation 浮层仍能盖住悬浮在中栏上方的 AppFrame 元素;首页阶段它们只在根元素内部比较层级。
|
||||
- `HocOutlet` 与 Factory 局部组件一样用 `useMemo` 保持层组件身份;如果 React 将来会丢弃 memo 缓存,两处都需要改成显式缓存,因为这些组件是其内部内容的重新挂载边界。
|
||||
- 其他 kind 仍以 [slot 体系标准](2026-07-22-slot-type-chain-implementation.zh.md) 为准;本 Note 新增第五种。
|
||||
@@ -0,0 +1,201 @@
|
||||
/** Keyless real-profile checks for the default official-home decoration and native input isolation. */
|
||||
import { mkdir, mkdtemp } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { chromium, type Browser, type Page } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
|
||||
import { ZH_BROWSER_LOCALE } from './support.ts'
|
||||
|
||||
const artifacts = fileURLToPath(new URL('../../../.artifacts/home-whale/', import.meta.url))
|
||||
|
||||
describe('official home whale in the default web profile', () => {
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
let page: Page
|
||||
let consoleState: ReturnType<typeof watchConsole>
|
||||
let captureDir: string
|
||||
|
||||
beforeAll(async () => {
|
||||
await mkdir(artifacts, { recursive: true })
|
||||
captureDir = await mkdtemp(join(artifacts, 'run-'))
|
||||
scaffold = await launchWebScaffold({ firstUse: true })
|
||||
browser = await chromium.launch()
|
||||
page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: ZH_BROWSER_LOCALE })
|
||||
consoleState = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl)
|
||||
await page.locator('[data-home-whale]').waitFor()
|
||||
await page.locator('[data-composer-input]').waitFor()
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await browser?.close()
|
||||
} finally {
|
||||
await scaffold?.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('alternates grayscale dot and code breaches on click and respects reduced motion', async () => {
|
||||
const canvas = page.locator('[data-home-whale]')
|
||||
const surface = page.locator('[data-conversation-content]')
|
||||
const pixelSummary = () => canvas.evaluate((node: HTMLCanvasElement) => {
|
||||
const values = node.getContext('2d')!.getImageData(0, 0, node.width, node.height).data
|
||||
let saturated = 0
|
||||
let opaque = 0
|
||||
let nontransparent = 0
|
||||
let contrast = 0
|
||||
for (let i = 0; i < values.length; i += 4) {
|
||||
const alpha = values[i + 3]! / 255
|
||||
if (alpha > 0) nontransparent++
|
||||
if (values[i + 3]! > 2) opaque++
|
||||
contrast = Math.max(contrast, (255 - Math.min(values[i]!, values[i + 1]!, values[i + 2]!)) * alpha)
|
||||
if (values[i + 3]! > 10 && values[i + 2]! - values[i]! > 8 && values[i + 2]! - values[i + 1]! > 4) saturated++
|
||||
}
|
||||
return { saturated, opaque, nontransparent, contrast }
|
||||
})
|
||||
expect(await canvas.evaluate(node => getComputedStyle(node).pointerEvents)).toBe('none')
|
||||
expect(await canvas.getAttribute('aria-hidden')).toBe('true')
|
||||
expect(await canvas.evaluate(node => getComputedStyle(node).filter)).toBe('grayscale(1)')
|
||||
await expect.poll(async () => (await pixelSummary()).nontransparent).toBe(0)
|
||||
await page.screenshot({ path: `${captureDir}/idle.png` })
|
||||
const box = await surface.boundingBox()
|
||||
expect(box).not.toBeNull()
|
||||
const card = (await page.locator('[data-composer-card]').boundingBox())!
|
||||
// The home above the input card, read from the composited page: it changes only if the canvas shows through.
|
||||
const homeClip = { x: box!.x, y: box!.y, width: box!.width, height: card.y - box!.y }
|
||||
const idleHome = await page.screenshot({ clip: homeClip })
|
||||
const marginX = box!.x + 12
|
||||
const marginY = card.y + card.height / 2
|
||||
expect(await page.evaluate(({ x, y }) =>
|
||||
document.elementFromPoint(x, y)?.closest('[data-composer-seat]') !== null,
|
||||
{ x: marginX, y: marginY })).toBe(true)
|
||||
await page.clock.install()
|
||||
await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000))
|
||||
try {
|
||||
await page.mouse.click(marginX, marginY)
|
||||
await expect.poll(async () => {
|
||||
await page.clock.runFor(100)
|
||||
return (await pixelSummary()).opaque
|
||||
}).toBeGreaterThan(300)
|
||||
await page.clock.runFor(1500)
|
||||
await page.screenshot({ path: `${captureDir}/ripple.png` })
|
||||
await page.mouse.click(box!.x + box!.width * 0.78, box!.y + box!.height * 0.72)
|
||||
expect((await pixelSummary()).opaque).toBeGreaterThan(0)
|
||||
expect((await pixelSummary()).contrast).toBeLessThanOrEqual(100)
|
||||
// The last visible pixels disappear before the playback deadline; finish the full timeline before the next click.
|
||||
await page.clock.runFor(5700)
|
||||
expect((await pixelSummary()).nontransparent).toBe(0)
|
||||
|
||||
await page.mouse.click(box!.x + box!.width * 0.78, box!.y + box!.height * 0.72)
|
||||
await page.clock.runFor(1500)
|
||||
expect((await pixelSummary()).opaque).toBeGreaterThan(300)
|
||||
expect((await page.screenshot({ clip: homeClip })).equals(idleHome)).toBe(false)
|
||||
await page.screenshot({ path: `${captureDir}/code.png` })
|
||||
await page.clock.runFor(5700)
|
||||
expect((await pixelSummary()).nontransparent).toBe(0)
|
||||
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' })
|
||||
const staticFrame = await canvas.evaluate((node: HTMLCanvasElement) => node.toDataURL())
|
||||
await page.mouse.click(box!.x + 100, box!.y + 150)
|
||||
await page.clock.runFor(300)
|
||||
expect(await canvas.evaluate((node: HTMLCanvasElement) => node.toDataURL())).toBe(staticFrame)
|
||||
} finally {
|
||||
await page.emulateMedia({ reducedMotion: 'no-preference' })
|
||||
await page.clock.resume()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps native draft editing independent of the decoration', async () => {
|
||||
const input = page.locator('[data-composer-input]')
|
||||
await input.fill('保留这个试用草稿')
|
||||
const canvas = page.locator('[data-home-whale]')
|
||||
const idleFrame = await canvas.evaluate((node: HTMLCanvasElement) => node.toDataURL())
|
||||
await input.click()
|
||||
// Observe several normal animation frames while focus stays in the composer.
|
||||
await page.waitForTimeout(300)
|
||||
expect(await canvas.evaluate((node: HTMLCanvasElement) => node.toDataURL())).toBe(idleFrame)
|
||||
expect(await input.innerText()).toBe('保留这个试用草稿')
|
||||
await input.press('ControlOrMeta+A')
|
||||
await input.press('Backspace')
|
||||
})
|
||||
|
||||
it('paints the decoration between the Conversation background and the home content', async () => {
|
||||
const order = await page.locator('[data-home-whale]').evaluate((node) => {
|
||||
// The canvas's negative z-index resolves in the nearest ancestor that establishes a stacking context. Walk up to
|
||||
// the document root and report the first one, which must be the home Conversation root that paints the background.
|
||||
const stacking = (element: Element): boolean => {
|
||||
const style = getComputedStyle(element)
|
||||
return style.isolation === 'isolate' || (style.zIndex !== 'auto' && style.position !== 'static')
|
||||
|| style.transform !== 'none' || style.opacity !== '1' || style.filter !== 'none'
|
||||
}
|
||||
let context: Element | null = node.parentElement
|
||||
while (context !== null && context !== document.documentElement && !stacking(context)) context = context.parentElement
|
||||
if (context === null || context === document.documentElement) return { found: false }
|
||||
return {
|
||||
found: true,
|
||||
canvasZIndex: getComputedStyle(node).zIndex,
|
||||
conversationPhase: context.getAttribute('data-phase'),
|
||||
isolation: getComputedStyle(context).isolation,
|
||||
paintsBackground: getComputedStyle(context).backgroundColor !== 'rgba(0, 0, 0, 0)',
|
||||
}
|
||||
})
|
||||
expect(order).toEqual({
|
||||
found: true, canvasZIndex: '-1', conversationPhase: 'hero', isolation: 'isolate', paintsBackground: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('loads from the default composition without a separately enabled bundle', async () => {
|
||||
await page.reload()
|
||||
await page.locator('[data-home-whale]').waitFor()
|
||||
const facts = await page.locator('[data-home-whale]').evaluate(node => ({
|
||||
count: document.querySelectorAll('[data-home-whale]').length,
|
||||
hiddenFromAssistiveTech: node.getAttribute('aria-hidden'),
|
||||
pointerEvents: getComputedStyle(node).pointerEvents,
|
||||
nativeComposer: document.querySelectorAll('[data-composer-seat]').length,
|
||||
}))
|
||||
expect(facts).toMatchInlineSnapshot(`
|
||||
{
|
||||
"count": 1,
|
||||
"hiddenFromAssistiveTech": "true",
|
||||
"nativeComposer": 1,
|
||||
"pointerEvents": "none",
|
||||
}
|
||||
`)
|
||||
expect(consoleState.pageErrors).toEqual([])
|
||||
expect(consoleState.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps neutral dots visible in both themes and fits a narrow home', async () => {
|
||||
const settings = scaffold.ctx.get('settings')!
|
||||
const canvas = page.locator('[data-home-whale]')
|
||||
const visibleDots = () => canvas.evaluate((node: HTMLCanvasElement) =>
|
||||
node.getContext('2d')!.getImageData(0, 0, node.width, node.height).data.some((value, i) => i % 4 === 3 && value > 10))
|
||||
const clickHome = async () => {
|
||||
const box = (await page.locator('[data-conversation-content]').boundingBox())!
|
||||
await page.mouse.click(box.x + box.width * 0.78, box.y + box.height * 0.18)
|
||||
}
|
||||
await settings.update('ui-theme', { preference: 'light' })
|
||||
await expect.poll(() => page.locator('body').getAttribute('data-ds-dark-theme')).toBeNull()
|
||||
const lightInk = await canvas.evaluate(node => getComputedStyle(node).color)
|
||||
await clickHome()
|
||||
await expect.poll(visibleDots).toBe(true)
|
||||
try {
|
||||
await settings.update('ui-theme', { preference: 'dark' })
|
||||
await expect.poll(() => page.locator('body').getAttribute('data-ds-dark-theme')).toBe('')
|
||||
await expect.poll(() => canvas.evaluate(node => getComputedStyle(node).color)).not.toBe(lightInk)
|
||||
// A click during playback is ignored and a fading breach can already read as blank, so keep clicking until a
|
||||
// breach is visible after the theme switch.
|
||||
await expect.poll(async () => { await clickHome(); return visibleDots() }, { timeout: 15_000 }).toBe(true)
|
||||
await page.screenshot({ path: `${captureDir}/dark.png` })
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
const box = (await canvas.boundingBox())!
|
||||
expect(box.x).toBeGreaterThanOrEqual(0)
|
||||
expect(box.x + box.width).toBeLessThanOrEqual(390)
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390)
|
||||
} finally {
|
||||
await page.setViewportSize({ width: 1440, height: 960 })
|
||||
await settings.update('ui-theme', { preference: 'light' })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -23,6 +23,7 @@
|
||||
// this client-registered project must not also hold them (one program
|
||||
// cannot see both sides of the cordis Context merges).
|
||||
"exclude": [
|
||||
"tests/home-whale.e2e.ts",
|
||||
"tests/sidebar-drawer.e2e.ts",
|
||||
"tests/creation-recommendations.e2e.ts",
|
||||
"tests/plugin-recommendations.e2e.ts",
|
||||
|
||||
@@ -9,11 +9,14 @@
|
||||
en: f2d2c0d3b8f14ec7
|
||||
zh: 441ed13ff3f81d2a
|
||||
/web-client-slots/cardinality-and-scope:
|
||||
en: cd17e3e0ff6e62ff
|
||||
zh: 6e0db2cb16c41b73
|
||||
en: 488f2f309af94398
|
||||
zh: 7941265e4c545c21
|
||||
/web-client-slots/cardinality-and-scope/hoc-layers:
|
||||
en: e6862954bd8874af
|
||||
zh: 0244a2d7bb0befdf
|
||||
/web-client-slots/component-inputs:
|
||||
en: 9cb70abb2e39b958
|
||||
zh: cd4b6f1705d90e17
|
||||
en: 278b2eee160be413
|
||||
zh: d6e0fd1e9f4a4b27
|
||||
/web-client-slots/framework-provided-hooks:
|
||||
en: c9f8d836214623ae
|
||||
zh: 76dec55006396535
|
||||
@@ -24,5 +27,5 @@
|
||||
en: e1d572c42e91d663
|
||||
zh: 5a649dea2682be7f
|
||||
/web-client-slots/extension-rules:
|
||||
en: b2cce357141883ee
|
||||
zh: 278080a5fb941189
|
||||
en: e5fdcd6fafe4d161
|
||||
zh: 7fd0c4374705b372
|
||||
|
||||
@@ -61,11 +61,22 @@ The slot declaration fixes two independent axes.
|
||||
| cardinality | `list` | Cells are addressed by required `id` and ordered by `order`, then registration order. |
|
||||
| cardinality | `keyed` | The owner dispatches an `entryKey`; the matching cell renders with any key-specific props. |
|
||||
| cardinality | `chain` | Each entry supplies a pure `select(owner)` function. The first non-null result in priority order renders and receives that result as `matched`; otherwise the owner fallback renders. |
|
||||
| cardinality | `hoc` | Entries nest around the owner's `renderSlot(key, owner, { children })` content, lowest outermost; see [Hoc layers](#hoc-layers). |
|
||||
| scope | `root` | One root-scoped component and store instance. |
|
||||
| scope | `session-maybe` | Inherits the surrounding Provider binding but stays renderable without one; Session values are optional. |
|
||||
| scope | `session` | Requires a resolved surrounding Provider binding and receives definite Session values. |
|
||||
|
||||
`priority` is a shadowing rank for `single`, `list`, and `keyed` cells and an election order for `chain`. Lower values run or render first. Ordinary additive contributions should choose a fresh list `id` or keyed `key`; intentionally reusing a shipped cell replaces its presentation.
|
||||
`priority` is a shadowing rank for `single`, `list`, `keyed`, and `hoc` cells and an election order for `chain`. Lower values run or render first. Ordinary additive contributions should choose a fresh list or hoc `id`, or keyed `key`; intentionally reusing a shipped cell replaces its presentation.
|
||||
|
||||
<a id="hoc-layers"></a>
|
||||
|
||||
### Hoc layers
|
||||
|
||||
A hoc entry is a layer addressed by its required `id`. Layers nest by ascending `order`, then `priority`, then registration order, lowest outermost. Each layer receives the same owner props plus the next inner layer as `children`, the owner's content at the innermost, and renders it exactly once; owner props must not use the name `children`. Omitted `children` renders the layers around nothing, and with no live layer the content renders unchanged.
|
||||
|
||||
- Remounting: adding or removing a layer remounts the content inside it, including a crashed layer leaving the slot; a `session` or `session-maybe` layer also remounts it when its Session binding changes.
|
||||
- Errors: a crashed layer renders its `children` and leaves the slot. An error thrown by the wrapped content passes every layer and is reported against none; a layer that wraps its `children` in its own error boundary catches it as an internal wrapper error rather than the original.
|
||||
- Layout: the outlet inserts a `display: contents` `[data-slot]` element between the owner and its content, so owner selectors cannot rely on the content being a direct child. A layer must not create a box of its own — for example, use `display: contents` — or the content leaves its parent's layout.
|
||||
|
||||
The [context-menu plugin](../../packages/client/ui-context-menu/README.md) contributes `useContextMenu` through `provideRoot`; every scope receives the same plugin-owned trigger factory. Its prop and retained handlers retire when the provider unloads. Its root-scoped keyed `contextMenu.icon` Slot renders business-owned icons from action metadata.
|
||||
|
||||
@@ -81,6 +92,7 @@ A registered component receives inputs assembled at its binding site. Components
|
||||
| private data, callbacks, and observable hooks | the registration's `inject` factory | `InjectFace<I>` |
|
||||
| localized `t` function | the registration's `locale` namespace | `PropsLocale<N>` |
|
||||
| selected chain value | the registration's `select` result | `matched` through `ComposedProps` |
|
||||
| wrapped owner content | the `SlotMap` row's `hoc` kind | `children` through `ComposedProps` |
|
||||
|
||||
`SessionProvider` is also present in `PropsRenderSlots` when an entry declares a `session` or `session-maybe` child. With no `session` prop it inherits the surrounding binding; an explicit `SessionReference` or `undefined` overrides only that subtree. The Provider does not key its whole body. A strict `session` entry remounts when its binding generation changes. A blank `session-maybe` entry adopts its first binding without remounting, then remounts for a later generation or a return to absence.
|
||||
|
||||
@@ -182,6 +194,8 @@ Factory: conversation.content [ConversationContent]
|
||||
├─ conversation.input.dock
|
||||
│ └─ id=queue [QueueDock]
|
||||
│ └─ calls Factory: conversation.user.text
|
||||
├─ conversation.hero.frame [hoc]
|
||||
│ └─ id=pixel-whale [PixelWhale]
|
||||
├─ conversation.hero.brand.mark
|
||||
├─ conversation.hero.workspace
|
||||
│ └─ conversation.hero.workspace.directoryFlow
|
||||
@@ -210,4 +224,4 @@ The generated [Client inspect catalog](../../packages/extensions/cordis-client-r
|
||||
- Keep business and transport state in their owning Cordis services or Client models. Slot stores hold shared viewing and interaction state only.
|
||||
- Keep observable source and snapshot identities stable between changes. Republish through the same source whenever its value changes.
|
||||
- Pass JSON-compatible data and callbacks between UI domains. The `hooks` compartment is the sole exception for bare observables; React content travels through slots.
|
||||
- Treat `single` and an occupied keyed cell as replacement points. Use list ids or an unoccupied key for additive extensions.
|
||||
- Treat `single` and an occupied keyed cell as replacement points. Use fresh list or hoc ids, or an unoccupied key, for additive extensions.
|
||||
|
||||
@@ -61,11 +61,22 @@ Slot 声明固定两个相互独立的维度。
|
||||
| cardinality | `list` | cell 由必填 `id` 定址,先按 `order`、再按注册顺序排列。 |
|
||||
| cardinality | `keyed` | owner 传入 `entryKey`;匹配 cell 以该 key 对应的 props 渲染。 |
|
||||
| cardinality | `chain` | 每个 entry 提供纯 `select(owner)` 函数;按 priority 顺序遇到的第一个非 null 结果获选,并以 `matched` 传给组件;全部拒绝时渲染 owner fallback。 |
|
||||
| cardinality | `hoc` | entry 层层包裹 owner 经 `renderSlot(key, owner, { children })` 传入的内容,最小者在最外层;见 [Hoc 层](#hoc-layers)。 |
|
||||
| scope | `root` | 一个 root 作用域组件和 store 实例。 |
|
||||
| scope | `session-maybe` | 继承外围 Provider binding,但没有 binding 时仍可渲染;Session 值是可选的。 |
|
||||
| scope | `session` | 要求可解析的外围 Provider binding,并收到确定存在的 Session 值。 |
|
||||
|
||||
对于 `single`、`list` 和 `keyed` cell,`priority` 是遮蔽优先级;对于 `chain`,它是选举顺序。数值越小越先运行或渲染。普通增量贡献应选用新的 list `id` 或 keyed `key`;复用已有 cell 表示有意替换其展示。
|
||||
对于 `single`、`list`、`keyed` 和 `hoc` cell,`priority` 是遮蔽优先级;对于 `chain`,它是选举顺序。数值越小越先运行或渲染。普通增量贡献应选用新的 list 或 hoc `id`,或 keyed `key`;复用已有 cell 表示有意替换其展示。
|
||||
|
||||
<a id="hoc-layers"></a>
|
||||
|
||||
### Hoc 层
|
||||
|
||||
hoc entry 是以必填 `id` 寻址的一层。各层依次按 `order`、`priority`、注册顺序升序嵌套,最小者在最外层。每层收到同一份 owner props,并以 `children` 收到内一层(最内层是 owner 的内容),且只渲染一次;owner props 不得使用 `children` 这个名字。省略 `children` 时各层包裹空内容;没有存活的层时原样渲染内容。
|
||||
|
||||
- 重新挂载:增减一层会让其内部内容重新挂载,崩溃的层退出 slot 也是如此;`session` 或 `session-maybe` 作用域的层在 Session binding 变化时也会让内部内容重新挂载。
|
||||
- 错误:崩溃的层渲染它的 `children` 并退出 slot。被包裹内容抛出的错误穿过所有层,不记到任何层名下;层如果自己在 `children` 外包错误边界,捕获到的是内部包装错误而不是原始错误。
|
||||
- 布局:outlet 会在 owner 与内容之间插入一个 `display: contents` 的 `[data-slot]` 元素,所以 owner 侧的选择器不能假定内容是直接子元素。层自身不得产生盒子——例如应使用 `display: contents`——否则内容会脱离父元素的布局。
|
||||
|
||||
<a id="component-inputs"></a>
|
||||
|
||||
@@ -83,6 +94,7 @@ Slot 声明固定两个相互独立的维度。
|
||||
| 私有数据、callback 与 observable hook | 注册项的 `inject` factory | `InjectFace<I>` |
|
||||
| 本地化 `t` 函数 | 注册项的 `locale` namespace | `PropsLocale<N>` |
|
||||
| chain 选中的值 | 注册项的 `select` 结果 | 通过 `ComposedProps` 提供的 `matched` |
|
||||
| 被包裹的 owner 内容 | `SlotMap` 条目的 `hoc` kind | 通过 `ComposedProps` 提供的 `children` |
|
||||
|
||||
当 entry 声明 `session` 或 `session-maybe` child 时,`PropsRenderSlots` 还会提供 `SessionProvider`。不传 `session` prop 时,它继承外围 binding;显式传入 `SessionReference` 或 `undefined` 时,只覆盖该子树。Provider 不为整个 body 设置 key。严格 `session` entry 在 binding generation 改变时重新挂载。空白 `session-maybe` entry 接受首个 binding 时不重新挂载,后续 generation 变化或回到缺失状态时才重新挂载。
|
||||
|
||||
@@ -184,6 +196,8 @@ Factory: conversation.content [ConversationContent]
|
||||
├─ conversation.input.dock
|
||||
│ └─ id=queue [QueueDock]
|
||||
│ └─ calls Factory: conversation.user.text
|
||||
├─ conversation.hero.frame [hoc]
|
||||
│ └─ id=pixel-whale [PixelWhale]
|
||||
├─ conversation.hero.brand.mark
|
||||
├─ conversation.hero.workspace
|
||||
│ └─ conversation.hero.workspace.directoryFlow
|
||||
@@ -214,4 +228,4 @@ Factory: conversation.chat.reasoning.content [ReasoningContent / MarkdownText]
|
||||
- 业务与传输状态留在所属 Cordis service 或 Client model 中。Slot store 只承载共享的视图与交互状态。
|
||||
- 可观测 source 及其 snapshot identity 在值变化前保持稳定;值变化时通过同一个 source 发布。
|
||||
- UI domain 之间只传 JSON 兼容数据和 callback。`hooks` compartment 是裸 observable 的唯一例外;React 内容通过 slot 传递。
|
||||
- 将 `single` 和已有 occupant 的 keyed cell 视为替换点。增量扩展使用 list id 或尚未占用的 key。
|
||||
- 将 `single` 和已有 occupant 的 keyed cell 视为替换点。增量扩展使用新的 list 或 hoc id,或尚未占用的 key。
|
||||
|
||||
@@ -339,7 +339,7 @@
|
||||
- id: ui-chat
|
||||
name: '@deepseek-ai/dsh-client-ui-chat'
|
||||
|
||||
# Official occupants for the generic sidebar and conversation brand slots.
|
||||
# Official occupants for the sidebar brand slots and the home whale frame layer.
|
||||
- id: ui-brand-official
|
||||
name: '@deepseek-ai/dsh-client-ui-brand-official'
|
||||
|
||||
|
||||
@@ -3,32 +3,35 @@
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-brand-official/README.md
|
||||
/:
|
||||
en: a031cd88e552dc89
|
||||
zh: 76c1af2393cb6983
|
||||
en: a46a90b8cedd5c45
|
||||
zh: 9b4f0d5fd9ffa945
|
||||
/deepseek-ai-dsh-client-ui-brand-official:
|
||||
en: 7cee1be833cea807
|
||||
zh: 9953e1b38cb23d34
|
||||
/deepseek-ai-dsh-client-ui-brand-official/summary:
|
||||
en: cb6bf0a4eabd271b
|
||||
zh: 181cf091ff44c194
|
||||
en: 784b8216e88b0578
|
||||
zh: 70165dea21d9a2ab
|
||||
/deepseek-ai-dsh-client-ui-brand-official/table-of-contents:
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
/deepseek-ai-dsh-client-ui-brand-official/use-this-package:
|
||||
en: 716dc268f98996db
|
||||
zh: 7372a67ef81a0d5e
|
||||
en: 8144a213ca978516
|
||||
zh: 43dfefbd708d87bf
|
||||
/deepseek-ai-dsh-client-ui-brand-official/use-this-package/choosing-the-profile:
|
||||
en: 3f3f96d6adf98193
|
||||
zh: 0b8691656a8532a0
|
||||
en: 876e7a0e21eaa396
|
||||
zh: 596fcdec565e3eae
|
||||
/deepseek-ai-dsh-client-ui-brand-official/use-this-package/home-feedback:
|
||||
en: f79f52c71a3d1491
|
||||
zh: bda67c8b4050316a
|
||||
/deepseek-ai-dsh-client-ui-brand-official/use-this-package/replacing-the-brand:
|
||||
en: 6a923aa630d01d65
|
||||
zh: 5df0c24eebd9d0d0
|
||||
en: 3fd4b315b27cfa23
|
||||
zh: 8f76a10d642a5811
|
||||
/deepseek-ai-dsh-client-ui-brand-official/understand-the-implementation:
|
||||
en: 4e4aa617edd7f4ad
|
||||
zh: ea4e2d6d4a39535e
|
||||
en: 4b59ceb74b5c9d1e
|
||||
zh: c22bcc7d7344fe12
|
||||
/deepseek-ai-dsh-client-ui-brand-official/further-exploration:
|
||||
en: c9ae240d8e831cc0
|
||||
zh: a7c9170bae79824f
|
||||
en: 268cb9edf0c7d2f0
|
||||
zh: 9b75285a61b44008
|
||||
/deepseek-ai-dsh-client-ui-brand-official/model-experience:
|
||||
en: 618008c7641070e7
|
||||
zh: 7233febb4d92ccfb
|
||||
@@ -36,8 +39,8 @@
|
||||
en: ca75c51c89c2c9b0
|
||||
zh: f57cc48a1b5cbfa9
|
||||
/deepseek-ai-dsh-client-ui-brand-official/known-limitations-and-deferred-work:
|
||||
en: 89e2b4bd095a0265
|
||||
zh: a002f0c8a60267ad
|
||||
en: b8f0ff2ff02bc0be
|
||||
zh: 8f52f9dee0225fad
|
||||
/deepseek-ai-dsh-client-ui-brand-official/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
description: "Official DeepSeek Harness brand occupants for the sidebar, active only in official builds; for users and maintainers choosing or replacing brand presentation."
|
||||
description: "Official sidebar branding and the default click-triggered pixel whale on the home page."
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
This package gives an `official` client build the DeepSeek Harness mark and name in the sidebar. Other build profiles keep the shell's fish mark and local-build label, while the conversation hero always uses the animated fish. Choose it for deployments branded as DeepSeek Harness; deployments with another identity should provide a replacement brand package. It has no runtime state and does not affect model requests.
|
||||
This package supplies a click-triggered pixel whale on the blank home and gives an `official` client build the DeepSeek Harness sidebar artwork. The shipped Web and Desktop compositions load it by default. Other build profiles retain their existing branding. The hero mark stays on its animated fish fallback. The background owns only temporary canvas resources and adds no model requests.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -25,15 +25,23 @@ This package gives an `official` client build the DeepSeek Harness mark and name
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Mount this plugin in the browser roster of a deployment whose identity is DeepSeek's own, then build the client with the `official` profile so the occupants register.
|
||||
The shipped Web and Desktop compositions already mount this plugin. Home feedback needs no extra installation or enablement; an `official` client build also registers the DeepSeek sidebar artwork.
|
||||
|
||||
### Choosing the profile
|
||||
|
||||
`DSH_CLIENT_BUILD_PROFILE` selects which brand renders. An `official` build shows the official mark and name in the sidebar; any other value leaves the shell fallbacks — the fish mark and the local-build label — in place. The conversation hero shows the animated hero fish from `dsh-client-ui-conversation` regardless of profile, because that fallback is already the official mark. The plugin still loads and validates in both cases; only the registration is profile-gated.
|
||||
`DSH_CLIENT_BUILD_PROFILE` selects which brand renders. An `official` build shows the official sidebar mark and name; any other value leaves the shell fallbacks — the fish mark and the local-build label — in place. The conversation hero shows the animated hero fish from `dsh-client-ui-conversation` regardless of profile, because that fallback is already the official mark. The plugin still loads and validates in both cases; only the sidebar artwork registration is profile-gated; the home background is shared across build profiles.
|
||||
|
||||
### Home feedback
|
||||
|
||||
The default home stays clear until a primary click on empty space plays one light-gray whale breach. Successive completed clicks alternate between dots and code lettering, starting with dots. Both use the same large animated silhouette. The animation lasts 5.7 seconds, then clears. Repeated clicks leave the current playback uninterrupted. The whale's frame layer classifies clicks: blank space inside its frame triggers playback, including margins beside the input card, while input fields, controls, the input card, portaled overlays, and a click that ends a text selection never do. The canvas takes neither focus nor pointer events; the frame receives the clicks. On narrow homes the whale keeps a larger scale and is cropped at the canvas edges, without adding horizontal scrolling. Reduced-motion preference disables it, and leaving the blank home releases its animation and observers.
|
||||
|
||||
The whale uses very faint neutral theme ink, appearing as a subtle background texture; code lettering has more contrast than the dots. Water splashes retain fine particles with stronger ink, especially on the left during landing. A packaged frame atlas supplies the motion; the browser loads it once through the plugin asset route on the first eligible click. Code fills use dense 7px lettering drawn only from authored code slogans, and the moving silhouette clips text as it enters or leaves the water. Decode or pixel-read failures stop the decoration, leave home usable, and log a reload action.
|
||||
|
||||
The artwork values are fixed and the row takes no configuration. This is built-in presentation, without a separately installed bundle or Plugins-page toggle.
|
||||
|
||||
### Replacing the brand
|
||||
|
||||
A deployment with its own identity leaves this package out and composes another package that occupies the sidebar slots — and the hero slot, which this package leaves on its fallback. Occupying a slot is the only composition route; there is no brand configuration surface here.
|
||||
A deployment with its own identity leaves this package out and composes another package that occupies the sidebar slots and the `conversation.hero.frame` layer — and the hero-mark slot, which this package leaves on its fallback. Occupying a slot is the only composition route; the artwork identity is not configurable.
|
||||
|
||||
-----
|
||||
|
||||
@@ -43,7 +51,7 @@ A deployment with its own identity leaves this package out and composes another
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
The two occupants install as one declaration-aware registration set: nested `ctx.slots.inject()` calls wait on the sidebar declaration, so the set works whether this row activates before or after the declarer, withdraws both occupants when the declaration collapses, and leaves no partial brand mix during HMR. The browser half is [`src/client/index.ts`](src/client/index.ts); the node half is an empty Loader seat. The browser title is a build-environment concern (`DSH_CLIENT_TITLE`), outside the slot system.
|
||||
The two occupants install as one declaration-aware registration set: nested `ctx.slots.inject()` calls wait on the sidebar declaration, so the set works whether this row activates before or after the declarer, withdraws both occupants when the declaration collapses, and leaves no partial brand mix during HMR. The independent `conversation.hero.frame` layer owns the canvas renderer and waits for its declaration through `ctx.slots.inject()`. While `hero` is true it paints the canvas at negative `z-index`, which the frame contract places above the Conversation background and below all Conversation content. It plays on primary clicks that reach its own frame outside controls and the composer card; clicks from portaled overlays and clicks that end a text selection inside the frame are ignored. It never changes the composer or conversation state. The browser half is [`src/client/index.ts`](src/client/index.ts); the node half is an empty Loader seat. The [frame atlas](src/client/assets/breach-atlas.webp) derives from the user-supplied [showcase video](https://yinghuo-hg.deepseek.com/wuyexinrui/dev-cpu/web-showcase/orca.mp4): 1.5–7.2 seconds at 24 frames per second, sampled to 192 × 108 cells and stored as lossless WebP. Its red and green channels encode dot radius and opacity at 32 levels; the renderer reads it once after the first eligible click. The browser title is a build-environment concern (`DSH_CLIENT_TITLE`), outside the slot system.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -55,7 +63,7 @@ The two occupants install as one declaration-aware registration set: nested `ctx
|
||||
Read these pages when the brand surface is not enough. They move from the slots this package occupies to the shell that renders them.
|
||||
|
||||
- [ui-sidebar](../ui-sidebar/README.md) — declares `sidebar.brand.mark` and `sidebar.brand.name` and renders their fallbacks.
|
||||
- [ui-conversation](../ui-conversation/README.md) — declares `conversation.hero.brand.mark` in the hero.
|
||||
- [ui-conversation](../ui-conversation/README.md) — declares `conversation.hero.brand.mark` in the hero and the `conversation.hero.frame` layer this package occupies.
|
||||
- [Web client architecture](../../../docs/subsystems/web-client.md) — how browser plugin rows load and register slots.
|
||||
|
||||
-----
|
||||
@@ -77,6 +85,7 @@ None; this package neither assembles nor sends a provider request.
|
||||
These limits define how brand presentation is supplied. They are current package constraints, not a brand-design comparison or a task backlog.
|
||||
|
||||
- **One occupant set** — alternative presentation belongs in another Cordis package occupying the same slots.
|
||||
- **Decorative rendering requires Canvas 2D** — unavailable contexts or reduced-motion preference leave the home clear.
|
||||
- **The browser title is independent** — `DSH_CLIENT_TITLE` selects title text at build time rather than through a UI slot.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
description: "面向侧栏的官方 DeepSeek Harness 品牌填充,仅在官方构建中生效;供选择或替换品牌呈现的用户与维护者阅读。"
|
||||
description: "官方侧栏品牌与默认首页点击浮出的像素鲸鱼。"
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
本包让以 `official` profile 构建的客户端在侧栏显示 DeepSeek Harness 标志与名称。其他构建 profile 保留外壳的鱼形标志与本地构建标签,会话首屏则始终使用动画鱼。品牌为 DeepSeek Harness 的部署应选择本包;使用其他品牌的部署应提供替代品牌包。本包不保留运行时状态,也不影响模型请求。
|
||||
本包在空白首页提供点击浮出的像素鲸鱼,并让以 `official` profile 构建的客户端显示 DeepSeek Harness 侧栏品牌图形。随产品提供的 Web 与 Desktop 组合默认加载本包。其他构建 profile 保留原有品牌。首屏标志仍使用动画鱼回退。背景只持有临时 Canvas 资源,不增加模型请求。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -25,15 +25,23 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
在采用 DeepSeek 自有品牌的部署中,将本插件挂载到浏览器插件名单,然后以 `official` profile 构建客户端,让填充得以注册。
|
||||
随产品提供的 Web 与 Desktop 组合已挂载本插件。首页反馈不需要额外安装或启用;`official` 客户端构建还会注册 DeepSeek 侧栏图形。
|
||||
|
||||
### 选择 profile
|
||||
|
||||
`DSH_CLIENT_BUILD_PROFILE` 决定渲染哪个品牌。`official` 构建在侧栏显示官方标志与名称;任何其他取值都让外壳回退——鱼形标志与本地构建标签——保持原样。会话首屏无论 profile 如何都显示来自 `dsh-client-ui-conversation` 的动画首屏鱼,因为这个回退本身就是官方标志。两种情况下插件都会照常加载并通过校验;只有注册受 profile 门控。
|
||||
`DSH_CLIENT_BUILD_PROFILE` 决定渲染哪个品牌。`official` 构建显示官方侧栏标志和名称;任何其他取值都让外壳回退——鱼形标志与本地构建标签——保持原样。会话首屏无论 profile 如何都显示来自 `dsh-client-ui-conversation` 的动画首屏鱼,因为这个回退本身就是官方标志。两种情况下插件都会照常加载并通过校验;只有侧栏图形注册受 profile 门控;各构建 profile 共用首页背景。
|
||||
|
||||
### 首页反馈
|
||||
|
||||
默认首页保持留白,主按钮点击空白处才播放一次浅灰色鲸鱼跃起。每次播放结束后的点击在点阵与代码填充之间交替,首次为点阵;两种填充使用相同的大幅动态轮廓。动画持续 5.7 秒,随后清空。连续点击不会打断当前播放。点击由鲸鱼的 frame 层自己判定:外框内部的留白可触发播放,包括输入卡片两侧的空白;输入框、控件、输入卡片、portal 出去的浮层以及结束文字选择的点击都不触发。Canvas 不获取焦点或指针事件,点击由外框接收。窄屏首页中的鲸鱼保留较大比例,在 Canvas 边缘裁切,不增加横向滚动。减少动态效果偏好会禁用它,离开空白首页时释放动画与观察器。
|
||||
|
||||
鲸鱼使用非常浅的主题中性色,呈现轻微的背景隐纹;代码文字的对比度略高于点阵。水花保留细小颗粒并使用较深的颜色,尤其是入水时左侧的水花。随包帧图提供动作,首次符合条件的点击时由浏览器经插件 asset 路由加载一次。代码填充使用密排的 7px 文字,内容只来自预设的代码标语,出水与入水时文本随动态轮廓裁切。解码或像素读取失败时停止装饰,首页仍可正常使用,并在日志中提示重新加载。
|
||||
|
||||
图形参数固定,本行不接受配置。这是内置呈现,没有需要单独安装的 Bundle 或插件页面开关。
|
||||
|
||||
### 替换品牌
|
||||
|
||||
自有身份的部署不组合本包,而是组合另一个占据侧栏 slot——以及本包留给回退的首屏 slot——的包。占据 slot 是唯一的组合路径;这里不存在任何品牌配置面。
|
||||
自有身份的部署不组合本包,而是组合另一个占据侧栏 slot 和 `conversation.hero.frame` 层——以及本包留给回退的首屏标志 slot——的包。占据 slot 是唯一的组合路径;品牌图形身份不可配置。
|
||||
|
||||
-----
|
||||
|
||||
@@ -43,7 +51,7 @@ kind: "package-reference"
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
两个填充作为一组声明感知的注册安装:嵌套的 `ctx.slots.inject()` 调用等待侧栏声明,因此无论本行在声明者之前还是之后激活,这组注册都能工作;声明消失时两个填充一并撤回,HMR 期间也不会留下残缺的品牌混合。浏览器半部是 [`src/client/index.ts`](src/client/index.ts);node 半部是一个空 Loader 座位。浏览器标题是构建环境的事(`DSH_CLIENT_TITLE`),不在 slot 系统之内。
|
||||
两个填充作为一组声明感知的注册安装:嵌套的 `ctx.slots.inject()` 调用等待侧栏声明,因此无论本行在声明者之前还是之后激活,这组注册都能工作;声明消失时两个填充一并撤回,HMR 期间也不会留下残缺的品牌混合。独立的 `conversation.hero.frame` 层持有 Canvas 绘制器,通过 `ctx.slots.inject()` 等待声明;`hero` 为 true 时它以负 `z-index` 绘制 Canvas,按 frame 层约定画在 Conversation 背景之上、所有 Conversation 内容之下。它在点击落到自身外框、且不在控件和输入卡片上时播放;portal 浮层的点击以及结束外框内文字选择的点击会被忽略。它不更改输入框或会话状态。浏览器半部是 [`src/client/index.ts`](src/client/index.ts);node 半部是空的 Loader 席位。[帧图](src/client/assets/breach-atlas.webp) 来自用户提供的[展示视频](https://yinghuo-hg.deepseek.com/wuyexinrui/dev-cpu/web-showcase/orca.mp4):截取 1.5–7.2 秒,以每秒 24 帧采样为 192 × 108 个单元,以无损 WebP 存储。红色与绿色通道以 32 级分别编码圆点半径和不透明度;绘制器在首次符合条件的点击后读取一次。浏览器标题是构建环境的事(`DSH_CLIENT_TITLE`),不在 slot 系统之内。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -55,7 +63,7 @@ kind: "package-reference"
|
||||
当品牌面不够用时阅读以下页面。它们从本包占据的 slot 进入渲染这些 slot 的外壳。
|
||||
|
||||
- [ui-sidebar](../ui-sidebar/README.zh.md)——声明 `sidebar.brand.mark` 与 `sidebar.brand.name` 并渲染其回退。
|
||||
- [ui-conversation](../ui-conversation/README.zh.md)——在首屏声明 `conversation.hero.brand.mark`。
|
||||
- [ui-conversation](../ui-conversation/README.zh.md)——在首屏声明 `conversation.hero.brand.mark`,以及本包占用的 `conversation.hero.frame` 层。
|
||||
- [Web 客户端架构](../../../docs/subsystems/web-client.zh.md)——浏览器插件行如何加载并注册 slot。
|
||||
|
||||
-----
|
||||
@@ -77,6 +85,7 @@ kind: "package-reference"
|
||||
这些限制界定了品牌呈现的供给方式。它们是当前包约束,不是品牌设计对比或任务积压。
|
||||
|
||||
- **只有一组填充**——替代呈现属于占据相同 slot 的另一个 Cordis 包。
|
||||
- **装饰绘制需要 Canvas 2D**——上下文不可用或偏好减少动态效果时,首页保持留白。
|
||||
- **浏览器标题独立**——`DSH_CLIENT_TITLE` 在构建时选择标题文本,而非通过 UI slot。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-ui-brand-official",
|
||||
"description": "Official DeepSeek Harness brand occupants for the Web client's sidebar slots",
|
||||
"description": "Official DeepSeek Harness brand artwork and click-triggered home background",
|
||||
"version": "0.2.2-alpha.3",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
@@ -24,13 +24,15 @@
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json",
|
||||
"./locale/*.json": "./locale/*.json"
|
||||
"./locale/*.json": "./locale/*.json",
|
||||
"./assets/*": "./lib/assets/*"
|
||||
},
|
||||
"dsh": {
|
||||
"client": {
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-ui-renderer",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar"
|
||||
"@deepseek-ai/dsh-client-ui-sidebar",
|
||||
"@deepseek-ai/dsh-client-ui-conversation"
|
||||
],
|
||||
"platform": "web"
|
||||
}
|
||||
@@ -50,12 +52,15 @@
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
"react-dom": "^18.2.0",
|
||||
"@deepseek-ai/dsh-client-ui-conversation": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:*"
|
||||
},
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
"lib/index.js",
|
||||
"lib/client.js",
|
||||
"lib/assets",
|
||||
"lib/types/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 185 KiB |
@@ -0,0 +1,20 @@
|
||||
/* Layout-neutral: the wrapped scroll body stays a direct flex item of the Conversation body. */
|
||||
.layer {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
.canvas {
|
||||
--home-whale-code-ink: var(--dsw-alias-label-primary);
|
||||
/* The host isolates stacking at the Conversation root, so -1 lands above its background and below its content. */
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
pointer-events: none;
|
||||
opacity: 0.18;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
filter: grayscale(1);
|
||||
font-family: var(--ds-font-family-code);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/** Home frame layer: a decorative canvas below the Conversation content, played by clicks on blank home space. */
|
||||
import { useCallback, useRef, type MouseEvent, type ReactNode } from 'react'
|
||||
import type { HeroFrameOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import atlasUrl from '../assets/breach-atlas.webp'
|
||||
import { WHALE_ARTWORK } from './artwork.ts'
|
||||
import { attachPixelWhale, type PixelWhaleHandle } from './renderer.ts'
|
||||
import css from './PixelWhale.module.css'
|
||||
|
||||
/** Interactive descendants whose clicks belong to the control, not to blank home space. */
|
||||
const CONTROLS = 'button, a, input, textarea, select, label, [contenteditable], [role="button"], [role="dialog"], [role="menu"], [role="listbox"], [data-composer-card]'
|
||||
|
||||
/** Frame owner state and the wrapped content. */
|
||||
export type PixelWhaleProps = HeroFrameOwnerProps & { children: ReactNode }
|
||||
|
||||
/**
|
||||
* Classify a click that bubbled to the frame. React bubbles portaled overlays through their React parent, so a
|
||||
* target outside the frame's DOM subtree is excluded. A click that ends a text selection made inside the frame is
|
||||
* not a blank click; a selection elsewhere in the document does not block playback.
|
||||
* @param event - the click observed on the frame.
|
||||
* @returns whether the click is a primary click on blank home space.
|
||||
*/
|
||||
function isBlankClick(event: MouseEvent<HTMLDivElement>): boolean {
|
||||
// React reports element targets; text-node targets resolve to their parent element.
|
||||
const target = event.target as Element
|
||||
const frame = event.currentTarget
|
||||
const selection = window.getSelection()
|
||||
return event.button === 0
|
||||
&& frame.contains(target)
|
||||
&& target.closest(CONTROLS) === null
|
||||
&& !(selection !== null && !selection.isCollapsed && frame.contains(selection.anchorNode))
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the Conversation scroll body; while the home is shown, paint the whale canvas below the Conversation content.
|
||||
* @param props - the home state and the wrapped scroll body.
|
||||
* @returns a layout-neutral frame around the children.
|
||||
*/
|
||||
export function PixelWhale({ hero, children }: PixelWhaleProps) {
|
||||
const whale = useRef<PixelWhaleHandle | undefined>(undefined)
|
||||
const canvasRef = useCallback((canvas: HTMLCanvasElement | null) => {
|
||||
whale.current?.dispose()
|
||||
whale.current = canvas === null ? undefined : attachPixelWhale(canvas, WHALE_ARTWORK, atlasUrl)
|
||||
}, [])
|
||||
const onClick = (event: MouseEvent<HTMLDivElement>): void => {
|
||||
if (whale.current !== undefined && isBlankClick(event)) whale.current.play()
|
||||
}
|
||||
return (
|
||||
<div className={css.layer} onClick={onClick}>
|
||||
{hero && <canvas ref={canvasRef} className={css.canvas} data-home-whale="" aria-hidden="true" />}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/** Fixed artwork choices for the official home whale. */
|
||||
|
||||
/** Visual parameters shared by the dot and code fills. */
|
||||
export interface WhaleArtwork {
|
||||
/** Maximum fill opacity, multiplied by each frame's water and highlight attenuation. */
|
||||
activeOpacity: number
|
||||
/** Word size in CSS pixels. */
|
||||
fontSize: number
|
||||
/** Authored artwork content, drawn verbatim as complete terms or sentences. */
|
||||
phrases: readonly string[]
|
||||
/** Maximum canvas redraw frequency. */
|
||||
frameRate: number
|
||||
/** One click's total lifetime in milliseconds. */
|
||||
rippleDurationMs: number
|
||||
}
|
||||
|
||||
/** The official artwork; these values are part of the design, not deployment settings. */
|
||||
export const WHALE_ARTWORK: WhaleArtwork = {
|
||||
activeOpacity: 0.65,
|
||||
fontSize: 7,
|
||||
phrases: [
|
||||
'// Everything is a plugin', 'ctx.plugin(Agent)', 'await agent.run()',
|
||||
'ctx.on("turn/end", next)', 'const tools = ctx.tools', 'await session.append(event)',
|
||||
'return next()', 'ctx.effect(() => dispose)', 'const { skills } = ctx',
|
||||
'yield tool.result', 'type Context = Harness', 'MCP.connect()',
|
||||
'useSession()', 'const workspace = cwd', 'await runtime.start()', '// Creator Mode',
|
||||
],
|
||||
frameRate: 24,
|
||||
rippleDurationMs: 5700,
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/** Cached code lettering clipped by the same frames that drive the dotted whale. */
|
||||
import type { WhaleArtwork } from './artwork.ts'
|
||||
|
||||
interface CodeFill {
|
||||
resize(canvas: HTMLCanvasElement, width: number): void
|
||||
paint(ctx: CanvasRenderingContext2D, pixels: Uint8ClampedArray, frame: number,
|
||||
left: number, top: number, width: number, level: number): void
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Allocate lettering and alpha canvases for one home attachment.
|
||||
* @param options - authored code phrases and font size.
|
||||
* @param atlas - bundled frame geometry; green stores opacity.
|
||||
* @returns a drawing cache, or undefined when Canvas 2D is unavailable.
|
||||
*/
|
||||
export function createCodeFill(
|
||||
options: WhaleArtwork, atlas: { width: number; height: number; columns: number; frames: number },
|
||||
): CodeFill | undefined {
|
||||
const lettering = document.createElement('canvas')
|
||||
const mask = document.createElement('canvas')
|
||||
const ink = lettering.getContext('2d')
|
||||
const matte = mask.getContext('2d')
|
||||
if (ink === null || matte === null) return undefined
|
||||
mask.width = atlas.width
|
||||
mask.height = atlas.height
|
||||
const alpha = matte.createImageData(atlas.width, atlas.height)
|
||||
const stride = atlas.width * atlas.columns
|
||||
|
||||
function opacity(pixels: Uint8ClampedArray, frame: number, x: number, y: number): number {
|
||||
const offsetX = (frame % atlas.columns) * atlas.width
|
||||
const offsetY = Math.floor(frame / atlas.columns) * atlas.height
|
||||
return pixels[((offsetY + y) * stride + offsetX + x) * 4 + 1] as number
|
||||
}
|
||||
|
||||
return {
|
||||
resize(canvas: HTMLCanvasElement, width: number): void {
|
||||
const height = width * atlas.height / atlas.width
|
||||
const dpr = Math.min(devicePixelRatio, 2)
|
||||
lettering.width = Math.ceil(width * dpr)
|
||||
lettering.height = Math.ceil(height * dpr)
|
||||
ink.setTransform(dpr, 0, 0, dpr, 0, 0)
|
||||
const style = getComputedStyle(canvas)
|
||||
ink.fillStyle = style.getPropertyValue('--home-whale-code-ink')
|
||||
ink.font = `500 ${options.fontSize}px ${style.fontFamily}`
|
||||
ink.textBaseline = 'middle'
|
||||
let seed = 0x9e3779b9
|
||||
const random = () => {
|
||||
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0
|
||||
return seed / 0x1_0000_0000
|
||||
}
|
||||
const words: { text: string; x: number; y: number; room: number; alpha: number }[] = []
|
||||
for (let y = options.fontSize; y < height; y += options.fontSize * 1.2) {
|
||||
for (let x = -random() * options.fontSize * 10; x < width;) {
|
||||
const text = options.phrases[Math.floor(random() * options.phrases.length)] as string
|
||||
const room = ink.measureText(text).width
|
||||
words.push({ text, x, y, room, alpha: 0.65 + random() * 0.35 })
|
||||
x += room + options.fontSize * (0.35 + random() * 0.65)
|
||||
}
|
||||
}
|
||||
for (const word of words) {
|
||||
ink.globalAlpha = word.alpha
|
||||
ink.fillText(word.text, word.x, word.y)
|
||||
}
|
||||
ink.globalAlpha = 1
|
||||
},
|
||||
|
||||
paint(ctx: CanvasRenderingContext2D, pixels: Uint8ClampedArray, frame: number,
|
||||
left: number, top: number, width: number, level: number): void {
|
||||
for (let y = 0; y < atlas.height; y++) {
|
||||
for (let x = 0; x < atlas.width; x++) {
|
||||
alpha.data[(y * atlas.width + x) * 4 + 3] = opacity(pixels, frame, x, y)
|
||||
}
|
||||
}
|
||||
matte.putImageData(alpha, 0, 0)
|
||||
const height = width * atlas.height / atlas.width
|
||||
ctx.globalAlpha = level
|
||||
ctx.drawImage(lettering, left, top, width, height)
|
||||
ctx.globalAlpha = 1
|
||||
ctx.globalCompositeOperation = 'destination-in'
|
||||
ctx.drawImage(mask, left, top, width, height)
|
||||
ctx.globalCompositeOperation = 'source-over'
|
||||
},
|
||||
|
||||
dispose(): void {
|
||||
lettering.width = lettering.height = mask.width = mask.height = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
/** Alternating dot and code breaches sharing one bundled animation atlas. */
|
||||
import type { WhaleArtwork } from './artwork.ts'
|
||||
import { createCodeFill } from './code-fill.ts'
|
||||
|
||||
// Geometry of assets/breach-atlas.webp: 137 frames at 192 × 108 cells, in twelve columns.
|
||||
const ATLAS = { width: 192, height: 108, columns: 12, frames: 137 } as const
|
||||
|
||||
/** Control of one attached whale decoration. */
|
||||
export interface PixelWhaleHandle {
|
||||
/** Request one playback; ignored while playing, failed, hidden, or under reduced motion. */
|
||||
play: () => void
|
||||
/** Release frame work, atlas pixels, and observers; late atlas loads are ignored. */
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
const NO_WHALE: PixelWhaleHandle = { play: () => {}, dispose: () => {} }
|
||||
|
||||
/**
|
||||
* Bind one noninteractive, initially transparent home decoration.
|
||||
* Missing Canvas support returns a no-op handle, so home stays usable without decoration.
|
||||
* An atlas failure stops decoration and logs a reload action.
|
||||
* @param canvas - presentation-owned output, with its neutral color supplied by CSS.
|
||||
* @param options - fixed opacity, lettering, frame rate, and duration artwork.
|
||||
* @param atlasUrl - URL of the packaged frame atlas, loaded once on the first eligible playback.
|
||||
* @returns the playback trigger and its teardown.
|
||||
*/
|
||||
export function attachPixelWhale(canvas: HTMLCanvasElement, options: WhaleArtwork, atlasUrl: string): PixelWhaleHandle {
|
||||
const context = canvas.getContext('2d')
|
||||
if (context === null) return NO_WHALE
|
||||
const ctx = context
|
||||
const image = new Image()
|
||||
const media = matchMedia('(prefers-reduced-motion: reduce)')
|
||||
let pixels: Uint8ClampedArray | undefined
|
||||
let started: number | undefined
|
||||
let loading = false
|
||||
let disposed = false
|
||||
let failed = false
|
||||
let visible = true
|
||||
let frame = 0
|
||||
let layoutFrame = 0
|
||||
let last = -Infinity
|
||||
let width = 0
|
||||
let height = 0
|
||||
let sceneWidth = 0
|
||||
let left = 0
|
||||
let top = 0
|
||||
let fill: 'pixels' | 'code' = 'code'
|
||||
let code: ReturnType<typeof createCodeFill> | undefined
|
||||
|
||||
const moving = () => !media.matches
|
||||
const drawable = () => !disposed && !document.hidden && visible && width > 0 && height > 0
|
||||
|
||||
function clear(): void {
|
||||
ctx.clearRect(0, 0, width, height)
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
cancelAnimationFrame(frame)
|
||||
frame = 0
|
||||
started = undefined
|
||||
clear()
|
||||
}
|
||||
|
||||
function fail(error: unknown): void {
|
||||
if (disposed) return
|
||||
failed = true
|
||||
stop()
|
||||
console.warn('Home whale animation is unavailable; home remains usable. Reload the page to retry.', error)
|
||||
}
|
||||
|
||||
function paint(now: number): void {
|
||||
clear()
|
||||
if (pixels === undefined || started === undefined) return
|
||||
const progress = (now - started) / options.rippleDurationMs
|
||||
if (progress >= 1) {
|
||||
started = undefined
|
||||
return
|
||||
}
|
||||
const index = Math.floor(progress * ATLAS.frames)
|
||||
const offsetX = (index % ATLAS.columns) * ATLAS.width
|
||||
const offsetY = Math.floor(index / ATLAS.columns) * ATLAS.height
|
||||
const stride = ATLAS.width * ATLAS.columns
|
||||
const cell = sceneWidth / ATLAS.width
|
||||
const fade = Math.min(1, progress * 15, (1 - progress) * 10)
|
||||
if (fill === 'code' && code !== undefined) {
|
||||
code.paint(ctx, pixels, index, left, top, sceneWidth, Math.min(1, options.activeOpacity * 1.5) * fade)
|
||||
return
|
||||
}
|
||||
for (let y = 0; y < ATLAS.height; y++) {
|
||||
for (let x = 0; x < ATLAS.width; x++) {
|
||||
const offset = ((offsetY + y) * stride + offsetX + x) * 4
|
||||
const alpha = (pixels[offset + 1] as number) / 255
|
||||
if (alpha < 0.015) continue
|
||||
ctx.globalAlpha = alpha * options.activeOpacity * fade * 0.8
|
||||
ctx.beginPath()
|
||||
ctx.arc(left + (x + 0.5) * cell, top + (y + 0.5) * cell, (pixels[offset] as number) / 255 * cell, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
ctx.globalAlpha = 1
|
||||
}
|
||||
|
||||
function tick(now: number): void {
|
||||
frame = 0
|
||||
if (!drawable()) return
|
||||
if (!moving()) { stop(); return }
|
||||
if (now - last + 0.5 >= 1000 / options.frameRate) {
|
||||
paint(now)
|
||||
last = now
|
||||
}
|
||||
if (started !== undefined) frame = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
function resume(): void {
|
||||
cancelAnimationFrame(frame)
|
||||
frame = 0
|
||||
if (disposed) return
|
||||
if (!moving()) { stop(); return }
|
||||
if (!drawable()) return
|
||||
paint(performance.now())
|
||||
last = performance.now()
|
||||
if (started !== undefined) frame = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
function resize(): void {
|
||||
width = canvas.clientWidth
|
||||
height = canvas.clientHeight
|
||||
const dpr = Math.min(devicePixelRatio, 2)
|
||||
canvas.width = Math.round(width * dpr)
|
||||
canvas.height = Math.round(height * dpr)
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
|
||||
ctx.fillStyle = getComputedStyle(canvas).color
|
||||
sceneWidth = Math.min(Math.max(width * 0.94, 720), height * 1.6, 1120) * 1.12
|
||||
const sceneHeight = sceneWidth * ATLAS.height / ATLAS.width
|
||||
left = (width - sceneWidth) / 2
|
||||
top = height * 0.43 - sceneHeight / 2
|
||||
if (code !== undefined && sceneWidth > 0) code.resize(canvas, sceneWidth)
|
||||
resume()
|
||||
}
|
||||
|
||||
// Layout redraws all code lettering, so bursts of size or theme changes collapse into one frame.
|
||||
function scheduleResize(): void {
|
||||
if (disposed || layoutFrame !== 0) return
|
||||
layoutFrame = requestAnimationFrame(() => {
|
||||
layoutFrame = 0
|
||||
resize()
|
||||
})
|
||||
}
|
||||
|
||||
function begin(): void {
|
||||
if (!moving() || !drawable()) return
|
||||
if (fill === 'pixels') {
|
||||
code ??= createCodeFill(options, ATLAS)
|
||||
if (code === undefined) { fail(new Error('Home whale code Canvas context is unavailable')); return }
|
||||
code.resize(canvas, sceneWidth)
|
||||
}
|
||||
fill = fill === 'pixels' ? 'code' : 'pixels'
|
||||
started = performance.now()
|
||||
resume()
|
||||
}
|
||||
|
||||
image.onload = () => {
|
||||
if (disposed) return
|
||||
const source = document.createElement('canvas')
|
||||
source.width = image.naturalWidth
|
||||
source.height = image.naturalHeight
|
||||
try {
|
||||
if (source.width !== ATLAS.width * ATLAS.columns
|
||||
|| source.height !== ATLAS.height * Math.ceil(ATLAS.frames / ATLAS.columns)) {
|
||||
throw new Error('Home whale atlas dimensions do not match its frame geometry')
|
||||
}
|
||||
const reader = source.getContext('2d')
|
||||
if (reader === null) { fail(new Error('Home whale atlas Canvas context is unavailable')); return }
|
||||
reader.drawImage(image, 0, 0)
|
||||
pixels = reader.getImageData(0, 0, source.width, source.height).data
|
||||
} catch (error) {
|
||||
fail(error)
|
||||
return
|
||||
} finally {
|
||||
source.width = source.height = 0
|
||||
image.removeAttribute('src')
|
||||
}
|
||||
begin()
|
||||
}
|
||||
image.onerror = () => { fail(new Error('Home whale atlas could not be decoded')) }
|
||||
|
||||
function play(): void {
|
||||
if (failed || !moving() || !drawable() || started !== undefined) return
|
||||
if (pixels !== undefined) { begin(); return }
|
||||
if (loading) return
|
||||
loading = true
|
||||
image.src = atlasUrl
|
||||
}
|
||||
|
||||
const sizeObserver = new ResizeObserver(scheduleResize)
|
||||
const visibilityObserver = new IntersectionObserver(([entry]) => {
|
||||
visible = entry?.isIntersecting ?? false
|
||||
resume()
|
||||
})
|
||||
const themeObserver = new MutationObserver(scheduleResize)
|
||||
sizeObserver.observe(canvas)
|
||||
visibilityObserver.observe(canvas)
|
||||
themeObserver.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'style'] })
|
||||
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-ds-theme-source', 'style'] })
|
||||
document.addEventListener('visibilitychange', resume)
|
||||
media.addEventListener('change', resume)
|
||||
resize()
|
||||
const dispose = (): void => {
|
||||
disposed = true
|
||||
stop()
|
||||
cancelAnimationFrame(layoutFrame)
|
||||
layoutFrame = 0
|
||||
image.onload = image.onerror = null
|
||||
image.removeAttribute('src')
|
||||
pixels = undefined
|
||||
code?.dispose()
|
||||
code = undefined
|
||||
sizeObserver.disconnect()
|
||||
visibilityObserver.disconnect()
|
||||
themeObserver.disconnect()
|
||||
document.removeEventListener('visibilitychange', resume)
|
||||
media.removeEventListener('change', resume)
|
||||
}
|
||||
return { play, dispose }
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
/** Official DeepSeek Harness occupants for the generic browser-brand slots. */
|
||||
/** Official DeepSeek Harness occupants: the profile-gated sidebar brand slots and the home whale frame layer. */
|
||||
import type { Context as ClientContext } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { PixelWhale } from './home-whale/PixelWhale.tsx'
|
||||
import { OfficialBrandMark, OfficialBrandName } from './Brand.tsx'
|
||||
|
||||
/** Required service: the UI slot registry. */
|
||||
export const inject = ['slots']
|
||||
|
||||
/**
|
||||
* Fill the sidebar brand slots as one declaration-aware registration set. The
|
||||
* conversation hero stays on its declaring package's animated fish fallback,
|
||||
* so the official build registers nothing there.
|
||||
* Fill official sidebar artwork and frame the blank home with the whale decoration.
|
||||
* @param ctx - Client root context.
|
||||
*/
|
||||
export function apply(ctx: ClientContext): void {
|
||||
ctx.slots.inject('conversation.hero.frame', () => ctx.slots.register({
|
||||
name: 'conversation.hero.frame',
|
||||
id: 'pixel-whale',
|
||||
}, PixelWhale))
|
||||
if (process.env.DSH_CLIENT_BUILD_PROFILE !== 'official') return
|
||||
ctx.slots.inject('sidebar.brand.mark', () =>
|
||||
ctx.slots.inject('sidebar.brand.name', function* () {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
declare module '*.module.css' {
|
||||
const classes: Record<string, string>
|
||||
export default classes
|
||||
}
|
||||
@@ -10,11 +10,14 @@ import { apply as hostApply } from '../src/index.ts'
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const HOLES = [
|
||||
'sidebar.brand.mark',
|
||||
'sidebar.brand.name',
|
||||
'conversation.hero.frame',
|
||||
] as const
|
||||
|
||||
const HERO_HOLE = 'conversation.hero.brand.mark'
|
||||
@@ -25,7 +28,10 @@ async function bench(declare = true) {
|
||||
const slots = ctx.get('slots') as SlotRegistry
|
||||
const declareHoles = () => slots.register({
|
||||
name: 'root',
|
||||
children: Object.fromEntries([...HOLES, HERO_HOLE].map(name => [name, { kind: 'single', scope: 'root' }])),
|
||||
children: Object.fromEntries([...HOLES, HERO_HOLE].map(name => [name, {
|
||||
kind: name === 'conversation.hero.frame' ? 'hoc' : 'single',
|
||||
scope: 'root',
|
||||
}])),
|
||||
} as never, () => null)
|
||||
const disposeHoles = declare ? declareHoles() : undefined
|
||||
return { ctx, slots, declareHoles, disposeHoles }
|
||||
@@ -40,11 +46,13 @@ describe('official browser-brand plugin', () => {
|
||||
expect(inject).toEqual(['slots'])
|
||||
})
|
||||
|
||||
it('leaves every slot empty outside the official build profile', async () => {
|
||||
it('keeps local sidebar branding and provides the same blank-home feedback', async () => {
|
||||
vi.stubEnv('DSH_CLIENT_BUILD_PROFILE', 'local')
|
||||
const subject = await bench()
|
||||
await subject.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
for (const hole of HOLES) expect(subject.slots.entries(hole)).toHaveLength(0)
|
||||
expect(subject.slots.entries('sidebar.brand.mark')).toHaveLength(0)
|
||||
expect(subject.slots.entries('sidebar.brand.name')).toHaveLength(0)
|
||||
expect(subject.slots.entries('conversation.hero.frame')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('fills declarations before or after apply and removes every occupant on teardown', async () => {
|
||||
@@ -78,6 +86,21 @@ describe('official browser-brand plugin', () => {
|
||||
expect(subject.slots.entries(HERO_HOLE)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('registers the whale as a self-contained frame layer without replacing the hero mark', async () => {
|
||||
vi.stubEnv('DSH_CLIENT_BUILD_PROFILE', 'official')
|
||||
const subject = await bench()
|
||||
const fiber = subject.ctx.plugin({ inject: [...inject], apply })
|
||||
try {
|
||||
await fiber.await()
|
||||
const [entry] = subject.slots.entries('conversation.hero.frame')
|
||||
expect(entry?.options.id).toBe('pixel-whale')
|
||||
expect(entry?.inject).toBeUndefined()
|
||||
expect(subject.slots.entries(HERO_HOLE)).toHaveLength(0)
|
||||
} finally {
|
||||
await fiber.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('renders the official name independently from both requested mark sizes', () => {
|
||||
const name = render(<OfficialBrandName />)
|
||||
expect(name.container.querySelector('svg')?.getAttribute('viewBox')).toBe('26 0 156 24')
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { WHALE_ARTWORK, type WhaleArtwork } from '../src/client/home-whale/artwork.ts'
|
||||
import { attachPixelWhale } from '../src/client/home-whale/renderer.ts'
|
||||
|
||||
const releases: (() => void)[] = []
|
||||
afterEach(() => {
|
||||
for (const release of releases.splice(0)) release()
|
||||
cleanup()
|
||||
document.body.replaceChildren()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
function scene(options: WhaleArtwork = WHALE_ARTWORK, missingContext = -1) {
|
||||
let now = 0
|
||||
let nextFrame = 1
|
||||
const frames = new Map<number, FrameRequestCallback>()
|
||||
const pixels = new Uint8ClampedArray(2304 * 1296 * 4)
|
||||
for (let i = 0; i < 137; i++) {
|
||||
const offset = (Math.floor(i / 12) * 108 * 2304 + (i % 12) * 192) * 4
|
||||
pixels[offset] = 90
|
||||
pixels[offset + 1] = 180
|
||||
}
|
||||
const drawing = () => ({
|
||||
clearRect: vi.fn(), drawImage: vi.fn(), beginPath: vi.fn(), arc: vi.fn(), fill: vi.fn(), setTransform: vi.fn(),
|
||||
fillText: vi.fn<(text: string, x: number, y: number) => void>(),
|
||||
measureText: vi.fn((text: string) => ({ width: text.length * 6 }) as TextMetrics),
|
||||
createImageData: vi.fn((size: number | ImageData, rows?: number) => {
|
||||
const width = typeof size === 'number' ? size : size.width
|
||||
const height = typeof size === 'number' ? rows ?? 0 : size.height
|
||||
return { data: new Uint8ClampedArray(width * height * 4), width, height, colorSpace: 'srgb' as const }
|
||||
}),
|
||||
putImageData: vi.fn<(data: ImageData, x: number, y: number) => void>(),
|
||||
getImageData: vi.fn(() => ({ data: pixels, width: 2304, height: 1296, colorSpace: 'srgb' as const })),
|
||||
globalAlpha: 1,
|
||||
})
|
||||
const contexts: ReturnType<typeof drawing>[] = []
|
||||
const canvases: HTMLCanvasElement[] = []
|
||||
const image = document.createElement('img')
|
||||
Object.defineProperties(image, { naturalWidth: { value: 2304, configurable: true }, naturalHeight: { value: 1296 } })
|
||||
vi.stubGlobal('Image', function () { return image })
|
||||
const media = Object.assign(new EventTarget(), { matches: false })
|
||||
const hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
|
||||
const disposers: ReturnType<typeof vi.fn>[] = []
|
||||
let onResize = () => {}
|
||||
let onTheme = () => {}
|
||||
let onVisibility: (entries: { isIntersecting: boolean }[]) => void = () => {}
|
||||
vi.spyOn(performance, 'now').mockImplementation(() => now)
|
||||
const getContext = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {
|
||||
const context = drawing()
|
||||
const partial: Partial<CanvasRenderingContext2D> = context
|
||||
contexts.push(context)
|
||||
canvases.push(this)
|
||||
return contexts.length - 1 === missingContext ? null : partial as CanvasRenderingContext2D
|
||||
})
|
||||
vi.stubGlobal('devicePixelRatio', 3)
|
||||
vi.stubGlobal('matchMedia', () => media)
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
|
||||
const id = nextFrame++
|
||||
frames.set(id, callback)
|
||||
return id
|
||||
})
|
||||
vi.stubGlobal('cancelAnimationFrame', (id: number) => { frames.delete(id) })
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
constructor(callback: () => void) { onResize = callback; disposers.push(this.disconnect) }
|
||||
observe() {}
|
||||
disconnect = vi.fn()
|
||||
})
|
||||
vi.stubGlobal('IntersectionObserver', class {
|
||||
constructor(callback: typeof onVisibility) { onVisibility = callback; disposers.push(this.disconnect) }
|
||||
observe() {}
|
||||
disconnect = vi.fn()
|
||||
})
|
||||
vi.stubGlobal('MutationObserver', class {
|
||||
constructor(callback: () => void) { onTheme = callback; disposers.push(this.disconnect) }
|
||||
observe() {}
|
||||
disconnect = vi.fn()
|
||||
})
|
||||
const surface = document.createElement('div')
|
||||
const canvas = document.createElement('canvas')
|
||||
let width = 1200
|
||||
Object.defineProperties(canvas, {
|
||||
clientWidth: { get: () => width }, clientHeight: { get: () => 900 },
|
||||
})
|
||||
vi.spyOn(canvas, 'getBoundingClientRect').mockImplementation(() => new DOMRect(10, 20, width, 900))
|
||||
surface.append(canvas)
|
||||
document.body.append(surface)
|
||||
const whale = attachPixelWhale(canvas, options, 'data:image/webp;base64,fixture')
|
||||
const dispose = whale.dispose
|
||||
releases.push(dispose)
|
||||
const click = whale.play
|
||||
function step(time: number) {
|
||||
now = time
|
||||
const pending = [...frames.values()]
|
||||
frames.clear()
|
||||
for (const callback of pending) callback(time)
|
||||
}
|
||||
return {
|
||||
canvas, surface, contexts, canvases, image, media, hidden, disposers, frames,
|
||||
dispose, click, step, getContext, pixels,
|
||||
load: () => image.dispatchEvent(new Event('load')),
|
||||
theme: () => { onTheme() },
|
||||
width: (value: number) => { width = value; onResize() },
|
||||
visibility: (entries: { isIntersecting: boolean }[]) => { onVisibility(entries) },
|
||||
}
|
||||
}
|
||||
|
||||
describe('official home pixel whale', () => {
|
||||
it('alternates dots and code on completed clicks, without interrupting or automatically repeating', () => {
|
||||
const s = scene()
|
||||
const output = s.contexts[0]!
|
||||
expect(s.image.hasAttribute('src')).toBe(false)
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.click()
|
||||
expect(s.image.getAttribute('src')).toBe('data:image/webp;base64,fixture')
|
||||
s.click()
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.load()
|
||||
expect(s.canvases[1]!.width).toBe(0)
|
||||
s.step(1500)
|
||||
expect(output.arc).toHaveBeenCalled()
|
||||
expect(output.globalAlpha).toBe(1)
|
||||
s.click()
|
||||
s.step(5750)
|
||||
expect(s.frames.size).toBe(0)
|
||||
const draws = output.arc.mock.calls.length
|
||||
s.step(6000)
|
||||
expect(output.arc).toHaveBeenCalledTimes(draws)
|
||||
s.click()
|
||||
s.step(6100)
|
||||
expect(output.arc).toHaveBeenCalledTimes(draws)
|
||||
expect(output.drawImage).toHaveBeenCalled()
|
||||
expect(s.contexts[2]!.fillText).toHaveBeenCalled()
|
||||
expect(s.contexts).toHaveLength(4)
|
||||
s.step(12000)
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.click(); s.step(13000)
|
||||
expect(output.arc.mock.calls.length).toBeGreaterThan(draws)
|
||||
s.dispose()
|
||||
for (const canvas of s.canvases.slice(2)) expect(canvas.width).toBe(0)
|
||||
})
|
||||
|
||||
it('fills the code whale only with authored snippets', () => {
|
||||
const options = { ...WHALE_ARTWORK, phrases: ['ctx.effect(() => dispose)', 'await agent.run()'] }
|
||||
const s = scene(options)
|
||||
for (let y = 15; y < 80; y++) {
|
||||
for (let x = 20; x < 165; x++) s.pixels[((3 * 108 + y) * 2304 + x) * 4 + 1] = 180
|
||||
}
|
||||
s.click(); s.load(); s.step(5800)
|
||||
s.click(); s.step(7300)
|
||||
const texts = s.contexts[2]!.fillText.mock.calls.map(call => call[0])
|
||||
expect(texts.length).toBeGreaterThan(0)
|
||||
expect(texts.every(text => options.phrases.includes(text))).toBe(true)
|
||||
const mask = s.contexts[3]!.putImageData.mock.calls.at(-1)![0].data
|
||||
expect(mask[3]).toBe(180)
|
||||
expect(mask[7]).toBe(0)
|
||||
const count = s.contexts[2]!.fillText.mock.calls.length
|
||||
s.step(7400)
|
||||
expect(s.contexts[2]!.fillText).toHaveBeenCalledTimes(count)
|
||||
})
|
||||
|
||||
it('plays only when its handle requests it', () => {
|
||||
const s = scene()
|
||||
s.surface.dispatchEvent(new MouseEvent('click', { bubbles: true, clientX: 200, clientY: 200 }))
|
||||
expect(s.image.hasAttribute('src')).toBe(false)
|
||||
s.click()
|
||||
expect(s.image.hasAttribute('src')).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps a large breach in narrow homes and clips both fills within the canvas', () => {
|
||||
const s = scene()
|
||||
s.width(390)
|
||||
s.step(16)
|
||||
s.click(); s.load(); s.step(1500)
|
||||
const dot = s.contexts[0]!.arc.mock.calls.at(-1)!
|
||||
expect(dot[0]).toBeLessThan(0)
|
||||
expect(s.canvas.width).toBe(780)
|
||||
s.step(5800); s.click(); s.step(7300)
|
||||
const image = s.contexts[0]!.drawImage.mock.calls.at(-1)!
|
||||
expect(image[1]).toBeLessThan(0)
|
||||
expect(image[3]).toBeGreaterThan(390)
|
||||
expect(s.canvas.width).toBe(780)
|
||||
})
|
||||
|
||||
it('stops hidden work, expires elapsed animations, and clears when reduced motion is enabled', () => {
|
||||
const s = scene()
|
||||
s.click(); s.load(); s.step(100)
|
||||
s.hidden.mockReturnValue(true)
|
||||
s.step(200)
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.hidden.mockReturnValue(false)
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
expect(s.frames.size).toBe(1)
|
||||
s.visibility([])
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.visibility([{ isIntersecting: true }])
|
||||
expect(s.frames.size).toBe(1)
|
||||
s.media.matches = true
|
||||
s.media.dispatchEvent(new Event('change'))
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.click()
|
||||
s.media.matches = false
|
||||
s.media.dispatchEvent(new Event('change'))
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.click()
|
||||
s.media.matches = true
|
||||
s.step(400)
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.media.matches = false
|
||||
s.click()
|
||||
s.visibility([])
|
||||
s.step(10000)
|
||||
s.visibility([{ isIntersecting: true }])
|
||||
expect(s.frames.size).toBe(0)
|
||||
})
|
||||
|
||||
it('does not start a late load after motion is disabled, but allows a subsequent explicit click', () => {
|
||||
const s = scene()
|
||||
s.click()
|
||||
s.media.matches = true
|
||||
s.load()
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.media.matches = false
|
||||
s.click()
|
||||
expect(s.frames.size).toBe(1)
|
||||
})
|
||||
|
||||
it('redraws for theme and size changes without decoding the atlas again', () => {
|
||||
const s = scene()
|
||||
s.click(); s.load(); s.step(100)
|
||||
const draws = s.contexts[0]!.arc.mock.calls.length
|
||||
s.theme()
|
||||
s.theme()
|
||||
expect(s.contexts[0]!.arc.mock.calls.length).toBe(draws)
|
||||
s.step(150)
|
||||
expect(s.contexts[0]!.arc.mock.calls.length).toBeGreaterThan(draws)
|
||||
s.width(0)
|
||||
s.step(200)
|
||||
expect(s.frames.size).toBe(0)
|
||||
s.width(390)
|
||||
expect(s.canvas.width).not.toBe(780)
|
||||
s.step(250)
|
||||
expect(s.canvas.width).toBe(780)
|
||||
expect(s.contexts).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('throttles to the artwork frame rate and relays out the code fill on resize', () => {
|
||||
const s = scene()
|
||||
s.click(); s.load(); s.step(100)
|
||||
const draws = s.contexts[0]!.arc.mock.calls.length
|
||||
s.step(110)
|
||||
expect(s.contexts[0]!.arc).toHaveBeenCalledTimes(draws)
|
||||
s.step(5800); s.click(); s.step(7300)
|
||||
const lettering = s.contexts[2]!
|
||||
const layouts = lettering.setTransform.mock.calls.length
|
||||
s.width(900)
|
||||
s.step(7320)
|
||||
expect(lettering.setTransform.mock.calls.length).toBeGreaterThan(layouts)
|
||||
})
|
||||
|
||||
it('stops decoration when the code fill cannot allocate its canvases', () => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const s = scene(WHALE_ARTWORK, 2)
|
||||
s.click(); s.load(); s.step(5800)
|
||||
s.click(); s.step(7300)
|
||||
expect(warning).toHaveBeenCalledOnce()
|
||||
expect(s.frames.size).toBe(0)
|
||||
})
|
||||
|
||||
it('cancels frames and rejects callbacks retained before disposal', () => {
|
||||
const s = scene()
|
||||
s.click()
|
||||
const lateLoad = s.image.onload!
|
||||
const lateError = s.image.onerror!
|
||||
s.dispose()
|
||||
lateLoad.call(s.image, new Event('load'))
|
||||
lateError.call(s.image, new Event('error'))
|
||||
s.theme()
|
||||
s.visibility([{ isIntersecting: true }])
|
||||
s.click()
|
||||
expect(s.frames.size).toBe(0)
|
||||
expect(s.contexts).toHaveLength(1)
|
||||
expect(s.image.hasAttribute('src')).toBe(false)
|
||||
for (const disconnect of s.disposers) expect(disconnect).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('leaves home usable without Canvas through an inert handle', () => {
|
||||
const s = scene(WHALE_ARTWORK, 0)
|
||||
s.click()
|
||||
s.dispose()
|
||||
expect(s.frames.size).toBe(0)
|
||||
expect(s.disposers).toHaveLength(0)
|
||||
expect(s.image.hasAttribute('src')).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['decode', 'geometry', 'context', 'pixels'] as const)('contains %s failure and does not retry until remount', (failure) => {
|
||||
const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const s = scene(WHALE_ARTWORK, failure === 'context' ? 1 : -1)
|
||||
s.click()
|
||||
if (failure === 'decode') s.image.dispatchEvent(new Event('error'))
|
||||
else {
|
||||
if (failure === 'geometry') Object.defineProperty(s.image, 'naturalWidth', { value: 1 })
|
||||
if (failure === 'pixels') {
|
||||
const original = s.getContext.getMockImplementation()!
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {
|
||||
const ctx = original.call(this, '2d') as CanvasRenderingContext2D
|
||||
ctx.getImageData = () => { throw new Error('Unreadable atlas') }
|
||||
return ctx
|
||||
})
|
||||
}
|
||||
s.load()
|
||||
}
|
||||
expect(warning).toHaveBeenCalledOnce()
|
||||
s.click(); s.step(100)
|
||||
expect(s.frames.size).toBe(0)
|
||||
expect(s.contexts[0]!.arc).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { WHALE_ARTWORK } from '../src/client/home-whale/artwork.ts'
|
||||
import { PixelWhale } from '../src/client/home-whale/PixelWhale.tsx'
|
||||
import { attachPixelWhale } from '../src/client/home-whale/renderer.ts'
|
||||
|
||||
vi.mock('../src/client/home-whale/renderer.ts', () => ({ attachPixelWhale: vi.fn() }))
|
||||
|
||||
const attach = vi.mocked(attachPixelWhale)
|
||||
|
||||
function handle() {
|
||||
const whale = { play: vi.fn(), dispose: vi.fn() }
|
||||
attach.mockReturnValueOnce(whale)
|
||||
return whale
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
cleanup()
|
||||
document.body.replaceChildren()
|
||||
attach.mockReset()
|
||||
})
|
||||
|
||||
describe('pixel whale frame layer', () => {
|
||||
it('attaches the artwork to a canvas before its content and releases it on unmount', () => {
|
||||
const whale = handle()
|
||||
const view = render(<PixelWhale hero><p>content</p></PixelWhale>)
|
||||
const canvas = view.container.querySelector('canvas')
|
||||
expect(canvas?.getAttribute('aria-hidden')).toBe('true')
|
||||
expect(canvas?.nextElementSibling?.textContent).toBe('content')
|
||||
expect(attach).toHaveBeenCalledExactlyOnceWith(canvas, WHALE_ARTWORK, expect.stringContaining('breach-atlas'))
|
||||
view.rerender(<PixelWhale hero><p>updated</p></PixelWhale>)
|
||||
expect(attach).toHaveBeenCalledOnce()
|
||||
view.unmount()
|
||||
expect(whale.dispose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('wraps its content without decoration outside the blank home', () => {
|
||||
const whale = handle()
|
||||
const view = render(<PixelWhale hero><p>content</p></PixelWhale>)
|
||||
view.rerender(<PixelWhale hero={false}><p>content</p></PixelWhale>)
|
||||
expect(view.container.querySelector('canvas')).toBeNull()
|
||||
expect(view.getByText('content')).toBeTruthy()
|
||||
expect(whale.dispose).toHaveBeenCalledOnce()
|
||||
fireEvent.click(view.getByText('content'))
|
||||
expect(whale.play).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('plays only for primary clicks on blank space inside its own frame', () => {
|
||||
const whale = handle()
|
||||
const overlay = document.createElement('div')
|
||||
document.body.append(overlay)
|
||||
const view = render(
|
||||
<PixelWhale hero>
|
||||
<section data-testid="blank">
|
||||
<button type="button">control</button>
|
||||
<div data-composer-card=""><span>card</span></div>
|
||||
{createPortal(<span>overlay</span>, overlay)}
|
||||
</section>
|
||||
</PixelWhale>,
|
||||
)
|
||||
fireEvent.click(view.getByText('control'))
|
||||
fireEvent.click(view.getByText('card'))
|
||||
fireEvent.click(view.getByText('overlay'))
|
||||
fireEvent.click(view.getByTestId('blank'), { button: 2 })
|
||||
expect(whale.play).not.toHaveBeenCalled()
|
||||
fireEvent.click(view.getByTestId('blank'))
|
||||
expect(whale.play).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('does not play when the click ends a text selection made inside its frame', () => {
|
||||
const whale = handle()
|
||||
const outside = document.createElement('p')
|
||||
outside.textContent = 'elsewhere'
|
||||
document.body.append(outside)
|
||||
const view = render(<PixelWhale hero><p data-testid="text">selectable headline</p></PixelWhale>)
|
||||
const text = view.getByTestId('text')
|
||||
const selection = window.getSelection()!
|
||||
selection.selectAllChildren(text)
|
||||
fireEvent.click(text)
|
||||
expect(whale.play).not.toHaveBeenCalled()
|
||||
// A selection left elsewhere in the document does not block playback.
|
||||
selection.selectAllChildren(outside)
|
||||
fireEvent.click(text)
|
||||
expect(whale.play).toHaveBeenCalledOnce()
|
||||
selection.removeAllRanges()
|
||||
fireEvent.click(text)
|
||||
expect(whale.play).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('plays when the document exposes no selection', () => {
|
||||
const whale = handle()
|
||||
vi.spyOn(window, 'getSelection').mockReturnValue(null)
|
||||
const view = render(<PixelWhale hero><p data-testid="text">headline</p></PixelWhale>)
|
||||
fireEvent.click(view.getByTestId('text'))
|
||||
expect(whale.play).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -22,6 +22,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../ui-slots"
|
||||
},
|
||||
{
|
||||
"path": "../ui-conversation/tsconfig.client.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: cc4dafd1aae02468
|
||||
zh: be6b67724b7ac4a3
|
||||
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props:
|
||||
en: 04b3ff9e2bdd5eb2
|
||||
zh: 38daec55d2e75ac3
|
||||
en: c11cc27a337174f3
|
||||
zh: a971ef53fa6046a2
|
||||
/deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries:
|
||||
en: 59cd63057dfb6eeb
|
||||
zh: b2e2c86e810b7bb8
|
||||
|
||||
@@ -68,6 +68,8 @@ The existing semantic `DraftSnapshot` retains quote text and clipboard-coordinat
|
||||
<a id="shell-and-standard-props"></a>
|
||||
## Shell and standard props
|
||||
|
||||
The root-scoped `conversation.hero.frame` hoc Slot wraps the scroll body in every phase, so its layers never remount the composer when the home ends. Its owner props carry `hero`, true only for the blank home of a standalone Conversation. Layers keep the scroll body a direct flex item of the body, for example with `display: contents`. On the home, the Conversation root, which paints the background, isolates stacking: a layer decoration at negative `z-index` paints above that background and below all Conversation content, including composer takeovers. Other phases leave the root out of the stacking order, so unportaled Conversation popovers can still rise above AppFrame chrome that floats over the column. Layers own their own input handling. With no occupant, the body is unchanged.
|
||||
|
||||
Below 768px, Web view tabs align with the header's 20px left inset. Desktop and wider Web windows retain the additional 8px tab inset.
|
||||
|
||||
The shared image slot props keep display choices separate from durable references: `thumbnail` requests a contained attachment-list thumbnail, while `compact` requests a cropped gallery tile. An optional per-image `label` supplies the accessible display name; loading and cache identity still use the original attachment reference. `MessageImagesContentInput` adds optional complete `MessageImageLabels` for the root-scoped `conversation.images.content` Factory. Message, tool, and Factory inputs carry the view's authorized `loadImage` callback explicitly; loading and URL caching remain with the resource owner. [ui-attachment](../ui-attachment/README.md) provides this Factory and owns rendering and the lightbox.
|
||||
@@ -106,7 +108,7 @@ View selection is deterministic: a registered persisted selection wins, otherwis
|
||||
|
||||
The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated.
|
||||
|
||||
Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The sticky composer owns its full footer band, which is not a resize target; a captured drag continues under the band and under gutter tables, which cover its indicator. In an active transcript the composer rests at the scrollport floor even when no View fills the column, keeps one stacking rank in every state, above transcript sticky headers and the back-to-bottom control, so menus it opens upward cover that control, and never serves as a scroll-anchoring target. It keeps its own compositor layer whatever lies beneath it, which makes it the containing block for fixed-position descendants: contributions to `conversation.composer`, `conversation.composer.bar`, `conversation.composer.dock`, `conversation.input.dock`, and the other `conversation.input.*` slots must portal fixed overlays to the document body, for example with `Tooltip` or `Menu` `portal` or `createPortal` ([handle and composer styles](src/client/skeleton/ConversationRoot.module.css)).
|
||||
Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The handle scrolls the first `[data-conversation-scroll]` element inside the body, which is the body's own scroll element even when frame layers wrap it. The sticky composer owns its full footer band, which is not a resize target; a captured drag continues under the band and under gutter tables, which cover its indicator. In an active transcript the composer rests at the scrollport floor even when no View fills the column, keeps one stacking rank in every state, above transcript sticky headers and the back-to-bottom control, so menus it opens upward cover that control, and never serves as a scroll-anchoring target. It keeps its own compositor layer whatever lies beneath it, which makes it the containing block for fixed-position descendants: contributions to `conversation.composer`, `conversation.composer.bar`, `conversation.composer.dock`, `conversation.input.dock`, and the other `conversation.input.*` slots must portal fixed overlays to the document body, for example with `Tooltip` or `Menu` `portal` or `createPortal` ([handle and composer styles](src/client/skeleton/ConversationRoot.module.css)).
|
||||
|
||||
The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged.
|
||||
|
||||
|
||||
@@ -68,6 +68,8 @@ Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CS
|
||||
<a id="shell-and-standard-props"></a>
|
||||
## Shell 与标准 props
|
||||
|
||||
root 作用域的 hoc Slot `conversation.hero.frame` 在所有阶段都包裹滚动区,因此首页结束时各层不会让输入框重新挂载。它的所有者 props 提供 `hero`,仅在独立 Conversation 的空白首页时为 true。各层需让滚动区仍是 body 的直接 flex 子项,例如使用 `display: contents`。首页阶段,绘制背景的 Conversation 根元素隔离层叠上下文:层中负 `z-index` 的装饰画在该背景之上、所有 Conversation 内容之下,包括输入区的接管面板。其他阶段根元素不参与层叠隔离,未经 portal 的 Conversation 浮层仍能盖住悬浮在中栏上方的 AppFrame 元素。各层自行处理输入。没有占用者时,body 保持原样。
|
||||
|
||||
宽度小于 768px 时,Web 的 View 标签与页头的 20px 左内边距对齐。桌面客户端和较宽的 Web 窗口保留标签额外的 8px 左内边距。
|
||||
|
||||
共享图片插槽属性将展示选择与持久化引用分开:`thumbnail` 请求完整缩放的附件列表缩略图,`compact` 请求裁剪的图片方块。每张图片可通过可选的 `label` 提供无障碍展示名称;加载和缓存标识仍使用原始附件引用。`MessageImagesContentInput` 为 root 作用域的 `conversation.images.content` Factory 增加可选的完整 `MessageImageLabels`。消息、工具及 Factory 输入显式携带视图提供的授权 `loadImage` 回调;读取和 URL 缓存仍由资源所有者负责。[ui-attachment](../ui-attachment/README.zh.md) 提供该 Factory,负责渲染与灯箱。
|
||||
@@ -106,7 +108,7 @@ View 选择规则固定:有效且已注册的持久化选择优先,其次是
|
||||
|
||||
Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。
|
||||
|
||||
主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。粘滞 composer 拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会在该区带和沟槽中的表格下方继续,此时指示线被它们遮住。在活跃 transcript 中,即使没有 View 撑满整列,composer 也停在滚动区底部;它在所有状态下保持同一层级,高于 transcript 的吸顶标题与“回到底部”按钮,因此它向上打开的菜单会盖住该按钮;它也从不作为滚动锚定目标。无论下方是什么内容,它都保持自己的合成层,因此成为 fixed 定位后代的包含块:向 `conversation.composer`、`conversation.composer.bar`、`conversation.composer.dock`、`conversation.input.dock` 以及其他 `conversation.input.*` slot 贡献的内容,必须把 fixed 浮层 portal 到 document body,例如使用 `Tooltip` 或 `Menu` 的 `portal`,或 `createPortal`([拖动手柄与 composer 样式](src/client/skeleton/ConversationRoot.module.css))。
|
||||
主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。拖拽条滚动的是 body 内第一个 `[data-conversation-scroll]` 元素;即使有 frame 层包在外面,它也是 body 自己的滚动区。粘滞 composer 拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会在该区带和沟槽中的表格下方继续,此时指示线被它们遮住。在活跃 transcript 中,即使没有 View 撑满整列,composer 也停在滚动区底部;它在所有状态下保持同一层级,高于 transcript 的吸顶标题与“回到底部”按钮,因此它向上打开的菜单会盖住该按钮;它也从不作为滚动锚定目标。无论下方是什么内容,它都保持自己的合成层,因此成为 fixed 定位后代的包含块:向 `conversation.composer`、`conversation.composer.bar`、`conversation.composer.dock`、`conversation.input.dock` 以及其他 `conversation.input.*` slot 贡献的内容,必须把 fixed 浮层 portal 到 document body,例如使用 `Tooltip` 或 `Menu` 的 `portal`,或 `createPortal`([拖动手柄与 composer 样式](src/client/skeleton/ConversationRoot.module.css))。
|
||||
|
||||
宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。
|
||||
|
||||
|
||||
@@ -349,6 +349,7 @@ export function apply(ctx: Context, config: Config = Config({})): void {
|
||||
'conversation.composer': { kind: 'chain', scope: 'session' },
|
||||
'conversation.composer.bar': { kind: 'single', scope: 'session-maybe' },
|
||||
'conversation.input.dock': { kind: 'list', scope: 'session' },
|
||||
'conversation.hero.frame': { kind: 'hoc', scope: 'root' },
|
||||
'conversation.hero.brand.mark': { kind: 'single', scope: 'root' },
|
||||
'conversation.hero.workspace': { kind: 'single', scope: 'root' },
|
||||
'conversation.hero.agentPreset': { kind: 'single', scope: 'session-maybe' },
|
||||
|
||||
@@ -283,6 +283,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
'conversation.composer': { kind: 'chain'; scope: 'session'; owner: ComposerChainProps }
|
||||
/** Workspace picker shown by the blank-session Hero. */
|
||||
'conversation.hero.workspace': { kind: 'single'; scope: 'root'; owner: EmptyWorkspaceOwnerProps }
|
||||
/** Layers wrapping the Conversation scroll body; `hero` reports a blank, standalone home. */
|
||||
'conversation.hero.frame': { kind: 'hoc'; scope: 'root'; owner: HeroFrameOwnerProps }
|
||||
/** Brand mark shown before the blank-session headline. */
|
||||
'conversation.hero.brand.mark': { kind: 'single'; scope: 'root'; owner: HeroBrandMarkOwnerProps }
|
||||
/** Agent-preset control staged for a New Session. */
|
||||
@@ -363,6 +365,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
'conversation.composer': { kind: 'chain'; scope: 'session' }
|
||||
'conversation.composer.bar': { kind: 'single'; scope: 'session-maybe' }
|
||||
'conversation.input.dock': { kind: 'list'; scope: 'session' }
|
||||
'conversation.hero.frame': { kind: 'hoc'; scope: 'root' }
|
||||
'conversation.hero.brand.mark': { kind: 'single'; scope: 'root' }
|
||||
'conversation.hero.workspace': { kind: 'single'; scope: 'root' }
|
||||
'conversation.hero.agentPreset': { kind: 'single'; scope: 'session-maybe' }
|
||||
@@ -616,7 +619,13 @@ export interface ComposerChainProps {
|
||||
pendingInteraction: SessionPendingInteraction | undefined
|
||||
}
|
||||
|
||||
/** Presentation props supplied to the blank-session brand mark. */
|
||||
/** Conversation state exposed to scroll-body frame layers. */
|
||||
export interface HeroFrameOwnerProps {
|
||||
/** Whether the body shows the blank home of a standalone, non-embedded Conversation. */
|
||||
hero: boolean
|
||||
}
|
||||
|
||||
/** Brand-mark presentation selected by the blank home. */
|
||||
export interface HeroBrandMarkOwnerProps {
|
||||
/** Requested square edge in pixels. */
|
||||
size: number
|
||||
|
||||
@@ -92,7 +92,7 @@ export type {
|
||||
ConversationViewActionEntry, ConversationViewActionsOwnerProps, ConversationViewsProps,
|
||||
ConversationWidthControlsInputProps, ConversationWidthControlsProps,
|
||||
ConversationStore, ConvViewOwnerProps, ConvViewProps, EmptyWorkspaceOwnerProps,
|
||||
HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, InputControlOwnerProps, InputZone,
|
||||
HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, HeroFrameOwnerProps, InputControlOwnerProps, InputZone,
|
||||
MessageImageLabels, MessageImageLoader, MessageImageSource, MessageImagesContentInput, MessageImagesOwnerProps, UseConversation,
|
||||
UserTextInput, UserTextInjected, UserTextNodeOwnerProps, UserTextNodeProps,
|
||||
UseConversationViews,
|
||||
|
||||
@@ -195,10 +195,15 @@ export function ConversationContent(props: ConversationContentProps) {
|
||||
data-conversation-region="chat"
|
||||
data-content-phase={phase}
|
||||
>
|
||||
<div className={css.scrollBody} data-conversation-scroll="">
|
||||
{sessionId === undefined ? null : <Views />}
|
||||
{composerSeat}
|
||||
</div>
|
||||
{/* The frame wraps the scroll body in every phase, so leaving the home keeps the composer mounted. */}
|
||||
{renderSlot('conversation.hero.frame', { hero: hero && props.variant !== 'embedded' }, {
|
||||
children: (
|
||||
<div className={css.scrollBody} data-conversation-scroll="">
|
||||
{sessionId === undefined ? null : <Views />}
|
||||
{composerSeat}
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
<WidthControls container={body} phase={phase} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -7,6 +7,13 @@
|
||||
background: var(--dsw-alias-bg-base);
|
||||
}
|
||||
|
||||
/* `conversation.hero.frame` contract on the home: layer decorations at negative z-index paint above this
|
||||
background and below all Conversation content. Other phases keep the root out of the stacking order, so
|
||||
unportaled Conversation popovers still rise above AppFrame chrome that floats over the column. */
|
||||
.root[data-phase='hero'] {
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
/* 76px with its rule: the height of the Sidebar's tab strip and header row
|
||||
(ui-dockkit `.tabStrip` 38px + the pane header's 38px), so the two rules
|
||||
meet at the column edge. The rows add up to it — 10px top inset, the 30px
|
||||
|
||||
@@ -106,8 +106,8 @@ function WidthHandle(props: {
|
||||
const body = event.currentTarget.parentElement
|
||||
/* v8 ignore next -- a width handle renders only inside the Conversation body. */
|
||||
if (body === null) return
|
||||
const scrollport = body.querySelector<HTMLElement>(':scope > [data-conversation-scroll]')
|
||||
/* v8 ignore next -- the Conversation body always contains its direct scroll element. */
|
||||
const scrollport = body.querySelector<HTMLElement>('[data-conversation-scroll]')
|
||||
/* v8 ignore next -- the Conversation body always contains its scroll element. */
|
||||
if (scrollport === null) return
|
||||
if (event.ctrlKey || event.deltaY === 0) return
|
||||
scrollport.scrollBy({ top: wheelDeltaY(event, scrollport) })
|
||||
|
||||
@@ -27,14 +27,13 @@ import { ConversationMainPanel } from '../src/client/skeleton/ConversationMainPa
|
||||
import { ConversationSession, ConversationSessionHeader } from '../src/client/skeleton/ConversationSession.tsx'
|
||||
import { conversationPhase } from '../src/client/contract/snapshot.ts'
|
||||
import { HeroShell } from '../src/client/skeleton/EmptyHero.tsx'
|
||||
import type { HeroShellProps } from '../src/client/skeleton/EmptyHero.tsx'
|
||||
import './control-row-dom.ts'
|
||||
import { InputBar } from '../src/client/skeleton/InputBar.tsx'
|
||||
import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx'
|
||||
import type {
|
||||
ComposerBarOwnerProps, ConversationContentInputProps, ConversationContentProps,
|
||||
ConversationHeaderLineageOwnerProps, ConversationSessionHeaderSlotProps, ConversationSessionSlotProps, ConversationSlotProps,
|
||||
ConversationViewActionsOwnerProps, ConversationViewsProps,
|
||||
ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps,
|
||||
} from '../src/client/contract/slots.ts'
|
||||
import type { ViewTab } from '../src/client/contract/views.ts'
|
||||
|
||||
@@ -201,14 +200,20 @@ function mount(
|
||||
/** Owner share handed to the two composer tool-row seats, per render. */
|
||||
const seatOwners: { key: string; owner: unknown }[] = []
|
||||
let pickerOwner: unknown
|
||||
const frameOwners: HeroFrameOwnerProps[] = []
|
||||
let actionsOwner: ConversationViewActionsOwnerProps | undefined
|
||||
const setPinned = vi.fn<(id: string, pinned: boolean) => void>()
|
||||
const renderSlot = ((key: string, owner: object, opts?: { only?: string; fallback?: ReactNode }) => {
|
||||
const renderSlot = ((key: string, owner: object, opts?: { only?: string; fallback?: ReactNode; children?: ReactNode }) => {
|
||||
slotCalls.push(key)
|
||||
if (key === 'conversation.input.model' || key === 'conversation.input.plan') {
|
||||
seatOwners.push({ key, owner })
|
||||
}
|
||||
if (key === 'conversation.hero.workspace') { pickerOwner = owner; return null }
|
||||
if (key === 'conversation.hero.frame') {
|
||||
// A hoc slot with no layers renders its content unchanged.
|
||||
frameOwners.push(owner as HeroFrameOwnerProps)
|
||||
return <div data-testid="hero-frame">{opts?.children}</div>
|
||||
}
|
||||
if (key === 'conversation.session.header.views.actions') {
|
||||
actionsOwner = owner as ConversationViewActionsOwnerProps
|
||||
return <button type="button" role="menuitem" onClick={actionsOwner.onDismiss}>Header view action</button>
|
||||
@@ -401,6 +406,7 @@ function mount(
|
||||
return {
|
||||
view, store, wiring, sink, retargetWorkspace, session, conversation, slotCalls, lineageOwners, seatOwners, open,
|
||||
pickerOwner: () => pickerOwner,
|
||||
frameOwner: () => frameOwners.at(-1),
|
||||
setPinned,
|
||||
actionsOwner: () => {
|
||||
if (actionsOwner === undefined) throw new Error('View actions not rendered')
|
||||
@@ -412,8 +418,8 @@ function mount(
|
||||
|
||||
describe('Hero chrome', () => {
|
||||
it('renders the English preview badge through the hero locale seat', () => {
|
||||
const renderSlot = vi.fn<HeroShellProps['renderSlot']>(() => null)
|
||||
const view = render(<HeroShell t={makeTranslate(en, commonEn)} renderSlot={renderSlot} />)
|
||||
const renderSlot = vi.fn<(key: string, owner: object, opts?: { fallback?: ReactNode }) => ReactNode>(() => null)
|
||||
const view = render(<HeroShell t={makeTranslate(en, commonEn)} renderSlot={renderSlot as never} />)
|
||||
expect(view.getByText('Into the Unknown')).toBeTruthy()
|
||||
expect(view.getByText('Preview')).toBeTruthy()
|
||||
expect(renderSlot).toHaveBeenCalledOnce()
|
||||
@@ -652,6 +658,8 @@ describe('ConversationRoot resident composer', () => {
|
||||
|
||||
it('same textarea DOM node survives the hero → active flip into the sticky scrollport', () => {
|
||||
const b = mount(sessionSnapshotOf({ blank: true }))
|
||||
const frame = b.view.getByTestId('hero-frame')
|
||||
expect(b.frameOwner()).toEqual({ hero: true })
|
||||
const before = b.view.getByRole('textbox')
|
||||
act(() => { b.wiring.setDraft('kept across flip') })
|
||||
// First message landed: content exists, phase leaves blank. Composer
|
||||
@@ -665,9 +673,19 @@ describe('ConversationRoot resident composer', () => {
|
||||
expect(b.store.store.getSnapshot().draft).toEqual({ text: 'kept across flip', references: [] })
|
||||
expect(b.view.container.querySelector('[data-conversation-scroll]')?.contains(after)).toBe(true)
|
||||
expect(b.view.queryByTestId('hero-headline')).toBeNull()
|
||||
// The frame wraps the scroll body in every phase, so leaving the home does not remount it.
|
||||
expect(b.view.getByTestId('hero-frame')).toBe(frame)
|
||||
expect(frame.contains(after)).toBe(true)
|
||||
expect(b.frameOwner()).toEqual({ hero: false })
|
||||
expect(b.view.getByTestId('view-chat')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('wraps the scroll body in the hero frame', () => {
|
||||
const b = mount(sessionSnapshotOf({ blank: true }))
|
||||
const scroll = b.view.container.querySelector('[data-conversation-scroll]')
|
||||
expect(scroll?.parentElement).toBe(b.view.getByTestId('hero-frame'))
|
||||
})
|
||||
|
||||
it('keeps the Chat fallback selected by id when a view is inserted before it', () => {
|
||||
const viewTabs: ViewTab[] = [
|
||||
{ id: 'chat', label: 'Chat' },
|
||||
@@ -1002,16 +1020,6 @@ describe('ConversationRoot resident composer', () => {
|
||||
fireEvent.wheel(handle, { deltaY: 0, deltaMode: 0 })
|
||||
fireEvent.wheel(handle, { ctrlKey: true, deltaY: 120, deltaMode: 0 })
|
||||
expect(scrollBy).toHaveBeenCalledTimes(calls)
|
||||
|
||||
scrollport.removeAttribute('data-conversation-scroll')
|
||||
const nestedScrollport = document.createElement('div')
|
||||
nestedScrollport.setAttribute('data-conversation-scroll', '')
|
||||
const nestedScrollBy = vi.fn()
|
||||
Object.defineProperty(nestedScrollport, 'scrollBy', { value: nestedScrollBy, configurable: true })
|
||||
scrollport.append(nestedScrollport)
|
||||
fireEvent.wheel(handle, { deltaY: 120, deltaMode: 0 })
|
||||
expect(scrollBy).toHaveBeenCalledTimes(calls)
|
||||
expect(nestedScrollBy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not check capture, measure, style, or schedule width-handle moves before dragging', () => {
|
||||
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
} from 'react'
|
||||
import {
|
||||
SlotOwnershipError, StaleAuthorizationError, standardHookPropName,
|
||||
type ChainRenderOpts, type HostObservable, type KeyedStandardSource, type LocaleFace, type RenderFactorySlot, type RenderOpts,
|
||||
type ChainRenderOpts, type HocRenderOpts, type HostObservable, type KeyedStandardSource, type LocaleFace,
|
||||
type RenderFactorySlot, type RenderOpts,
|
||||
type ScopedStandardSourceBinding, type SessionAreaProps, type SessionProviderComponent, type SlotRenderer,
|
||||
type SlotEntryDef, type SlotRendererHost, type SlotScope, type SlotScopeAdapter, type SlotSpec, type StandardSourceBinding,
|
||||
type StoredEntry, type StoredFactory, type Translate,
|
||||
@@ -31,7 +32,10 @@ interface BoundSlotInject {
|
||||
readonly slotHookFactories?: SlotHookFactories | undefined
|
||||
}
|
||||
|
||||
type RenderSlotBinding = (key: string, owner: object, opts?: RenderOpts) => ReactNode
|
||||
/** Type-erased outlet options: every kind's dispatch fields, validated by the typed render shares. */
|
||||
type OutletOpts = RenderOpts & ChainRenderOpts & Partial<HocRenderOpts>
|
||||
|
||||
type RenderSlotBinding = (key: string, owner: object, opts?: OutletOpts) => ReactNode
|
||||
|
||||
type RenderSlotChainBinding = (key: string, owner: object, opts?: ChainRenderOpts) => ReactNode
|
||||
|
||||
@@ -360,7 +364,7 @@ function useLocaleRevision(face: LocaleFace | undefined): number {
|
||||
|
||||
/**
|
||||
* Entry-identity React keys for entry boundaries. An outlet renders one
|
||||
* winner per position (single/keyed/list cell head, chain election) through
|
||||
* winner per position (single/keyed/list/hoc cell head, chain election) through
|
||||
* an error boundary; without a key, a boundary that failed on entry A would
|
||||
* survive a winner change (re-election, shadowing fallback after an
|
||||
* abdication, HMR re-registration) and keep a healthy entry B blacked out.
|
||||
@@ -392,6 +396,39 @@ function sessionGenerationKeyOf(binding: ScopedStandardSourceBinding): number {
|
||||
return key
|
||||
}
|
||||
|
||||
/**
|
||||
* An error thrown by the content a hoc layer wraps. Layer boundaries pass it
|
||||
* through untouched, so content failures never retire or blame a layer; the
|
||||
* hoc outlet rethrows the original error to the boundaries above it.
|
||||
*/
|
||||
class HocContentError extends Error {
|
||||
readonly original: unknown
|
||||
constructor(original: unknown) {
|
||||
super('hoc slot content failed', { cause: original })
|
||||
this.original = original
|
||||
}
|
||||
}
|
||||
|
||||
/** Wrap the content inside one hoc layer: its errors leave as {@link HocContentError}. */
|
||||
class HocContentBoundary extends Component<{ children: ReactNode }> {
|
||||
static getDerivedStateFromError(error: unknown): never {
|
||||
throw error instanceof HocContentError ? error : new HocContentError(error)
|
||||
}
|
||||
override render(): ReactNode {
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
|
||||
/** Surround a hoc slot's composed layers: content errors continue upward as their original error. */
|
||||
class HocOutletBoundary extends Component<{ children: ReactNode }> {
|
||||
static getDerivedStateFromError(error: unknown): never {
|
||||
throw error instanceof HocContentError ? error.original : error
|
||||
}
|
||||
override render(): ReactNode {
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-entry isolation: one registrant crashing (component render or inject
|
||||
* factory) must not take down siblings. Assembly errors (missing providers)
|
||||
@@ -400,14 +437,21 @@ function sessionGenerationKeyOf(binding: ScopedStandardSourceBinding): number {
|
||||
* seam); for shadowing kinds the report abdicates the entry, the outlet
|
||||
* re-renders onto the cell's next survivor, and this boundary's crash face
|
||||
* only shows until that re-render lands (permanently once the cell is dry —
|
||||
* the outlet then owns the crash face).
|
||||
* the outlet then owns the crash face). A hoc layer supplies `crashed`, its
|
||||
* inner content, which replaces the crash face so the failed layer is skipped.
|
||||
*/
|
||||
class SlotErrorBoundary extends Component<
|
||||
{ slotKey: string; anchor?: SlotAnchorTag; onEntryError: (error: unknown) => void; children: ReactNode }, { failed: boolean }
|
||||
{
|
||||
slotKey: string
|
||||
anchor?: SlotAnchorTag
|
||||
crashed?: ReactNode
|
||||
onEntryError: (error: unknown) => void
|
||||
children: ReactNode
|
||||
}, { failed: boolean }
|
||||
> {
|
||||
override state = { failed: false }
|
||||
static getDerivedStateFromError(error: unknown): { failed: boolean } {
|
||||
if (error instanceof SlotAssemblyError) throw error
|
||||
if (error instanceof SlotAssemblyError || error instanceof HocContentError) throw error
|
||||
return { failed: true }
|
||||
}
|
||||
override componentDidCatch(error: unknown): void {
|
||||
@@ -416,7 +460,9 @@ class SlotErrorBoundary extends Component<
|
||||
}
|
||||
override render(): ReactNode {
|
||||
const Anchor = this.props.anchor ?? 'div'
|
||||
if (this.state.failed) return <Anchor data-slot-error={this.props.slotKey} />
|
||||
if (this.state.failed) {
|
||||
return this.props.crashed === undefined ? <Anchor data-slot-error={this.props.slotKey} /> : this.props.crashed
|
||||
}
|
||||
return this.props.children
|
||||
}
|
||||
}
|
||||
@@ -600,7 +646,7 @@ function standardKit(
|
||||
* the registration and renderSlot seams already proved their contracts.
|
||||
*/
|
||||
function ContextualEntry({
|
||||
slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext,
|
||||
slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext, children,
|
||||
}: {
|
||||
slotKey: string
|
||||
Comp: FC<InjectedProps>
|
||||
@@ -611,6 +657,7 @@ function ContextualEntry({
|
||||
ownerProps: object
|
||||
hookContext: unknown
|
||||
hasHookContext: boolean
|
||||
children?: ReactNode
|
||||
}) {
|
||||
const contextual = useMemo(
|
||||
() => {
|
||||
@@ -621,7 +668,7 @@ function ContextualEntry({
|
||||
},
|
||||
[hasHookContext, hookContext, slotInjected.slotHookFactories, slotKey, standard],
|
||||
)
|
||||
return <Comp {...kit} {...injected} {...slotInjected.props} {...contextual} {...ownerProps} />
|
||||
return <Comp {...kit} {...injected} {...slotInjected.props} {...contextual} {...ownerProps}>{children}</Comp>
|
||||
}
|
||||
|
||||
function renderEntry(
|
||||
@@ -634,9 +681,11 @@ function renderEntry(
|
||||
ownerProps: object,
|
||||
hookContext: unknown,
|
||||
hasHookContext: boolean,
|
||||
children: ReactNode | undefined,
|
||||
): ReactNode {
|
||||
// `children` is a hoc layer's inner content; other kinds pass undefined.
|
||||
if (slotInjected.slotHookFactories === undefined) {
|
||||
return <Comp {...kit} {...injected} {...slotInjected.props} {...ownerProps} />
|
||||
return <Comp {...kit} {...injected} {...slotInjected.props} {...ownerProps}>{children}</Comp>
|
||||
}
|
||||
return (
|
||||
<ContextualEntry
|
||||
@@ -649,42 +698,43 @@ function renderEntry(
|
||||
ownerProps={ownerProps}
|
||||
hookContext={hookContext}
|
||||
hasHookContext={hasHookContext}
|
||||
/>
|
||||
>
|
||||
{children}
|
||||
</ContextualEntry>
|
||||
)
|
||||
}
|
||||
|
||||
function SessionEntry({ entry, ownerProps, binding, slotKey, slotInjected, hookContext, hasHookContext }: {
|
||||
/** Props shared by the scope-specific Entry Components; `children` is a hoc layer's inner content. */
|
||||
interface EntryProps {
|
||||
entry: StoredEntry
|
||||
ownerProps: object
|
||||
binding: StandardSourceBinding & { readonly key: string }
|
||||
slotKey: string
|
||||
slotInjected: BoundSlotInject
|
||||
hookContext: unknown
|
||||
hasHookContext: boolean
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
function SessionEntry({ entry, ownerProps, binding, slotKey, slotInjected, hookContext, hasHookContext, children }: EntryProps & {
|
||||
binding: StandardSourceBinding & { readonly key: string }
|
||||
}) {
|
||||
const host = useHost()
|
||||
const rootBinding = useRootBinding()
|
||||
const Comp = entry.component as FC<InjectedProps>
|
||||
const { kit, standard, actions } = standardKit(host, entry, 'session', rootBinding, binding)
|
||||
const injected = cachedSessionInject(entry, binding, actions)
|
||||
return renderEntry(slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext)
|
||||
return renderEntry(slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext, children)
|
||||
}
|
||||
|
||||
function SessionMaybeEntryBody({ entry, ownerProps, binding, slotKey, slotInjected, hookContext, hasHookContext }: {
|
||||
entry: StoredEntry
|
||||
ownerProps: object
|
||||
binding: StandardSourceBinding
|
||||
slotKey: string
|
||||
slotInjected: BoundSlotInject
|
||||
hookContext: unknown
|
||||
hasHookContext: boolean
|
||||
}) {
|
||||
function SessionMaybeEntryBody({
|
||||
entry, ownerProps, binding, slotKey, slotInjected, hookContext, hasHookContext, children,
|
||||
}: EntryProps & { binding: StandardSourceBinding }) {
|
||||
const host = useHost()
|
||||
const rootBinding = useRootBinding()
|
||||
const Comp = entry.component as FC<InjectedProps>
|
||||
const { kit, standard, actions } = standardKit(host, entry, 'session-maybe', rootBinding, binding)
|
||||
const injected = cachedSessionMaybeInject(entry, binding, actions)
|
||||
return renderEntry(slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext)
|
||||
return renderEntry(slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext, children)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -700,14 +750,7 @@ function SessionMaybeEntryBody({ entry, ownerProps, binding, slotKey, slotInject
|
||||
* that must SURVIVE a switch belongs in session-bound sources (machine,
|
||||
* store, hooks) — the existing layering rule, now load-bearing.
|
||||
*/
|
||||
function SessionMaybeEntry({ entry, ownerProps, slotKey, slotInjected, hookContext, hasHookContext }: {
|
||||
entry: StoredEntry
|
||||
ownerProps: object
|
||||
slotKey: string
|
||||
slotInjected: BoundSlotInject
|
||||
hookContext: unknown
|
||||
hasHookContext: boolean
|
||||
}) {
|
||||
function SessionMaybeEntry({ entry, ownerProps, slotKey, slotInjected, hookContext, hasHookContext, children }: EntryProps) {
|
||||
const binding = useScopeBinding()
|
||||
const epoch = useMaybeIncarnation(binding)
|
||||
return (
|
||||
@@ -720,7 +763,9 @@ function SessionMaybeEntry({ entry, ownerProps, slotKey, slotInjected, hookConte
|
||||
slotInjected={slotInjected}
|
||||
hookContext={hookContext}
|
||||
hasHookContext={hasHookContext}
|
||||
/>
|
||||
>
|
||||
{children}
|
||||
</SessionMaybeEntryBody>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -764,20 +809,13 @@ function useMaybeIncarnation(binding: StandardSourceBinding): number {
|
||||
return epoch
|
||||
}
|
||||
|
||||
function RootEntry({ entry, ownerProps, slotKey, slotInjected, hookContext, hasHookContext }: {
|
||||
entry: StoredEntry
|
||||
ownerProps: object
|
||||
slotKey: string
|
||||
slotInjected: BoundSlotInject
|
||||
hookContext: unknown
|
||||
hasHookContext: boolean
|
||||
}) {
|
||||
function RootEntry({ entry, ownerProps, slotKey, slotInjected, hookContext, hasHookContext, children }: EntryProps) {
|
||||
const host = useHost()
|
||||
const rootBinding = useRootBinding()
|
||||
const Comp = entry.component as FC<InjectedProps>
|
||||
const { kit, standard, actions } = standardKit(host, entry, 'root', rootBinding, undefined)
|
||||
const injected = cachedRootInject(entry, actions)
|
||||
return renderEntry(slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext)
|
||||
return renderEntry(slotKey, Comp, kit, standard, injected, slotInjected, ownerProps, hookContext, hasHookContext, children)
|
||||
}
|
||||
|
||||
interface FactoryOccurrenceValue {
|
||||
@@ -1026,14 +1064,11 @@ function FactoryOutlet({ name, inputProps, slots: selected = EMPTY_FACTORY_SELEC
|
||||
)
|
||||
}
|
||||
|
||||
function StrictSessionEntry({ slotKey, anchor, entry, ownerProps, slotInjected, hookContext, hasHookContext, onEntryError }: {
|
||||
slotKey: string
|
||||
function StrictSessionEntry({
|
||||
slotKey, anchor, crashed, entry, ownerProps, slotInjected, hookContext, hasHookContext, onEntryError, children,
|
||||
}: EntryProps & {
|
||||
anchor: SlotAnchorTag
|
||||
entry: StoredEntry
|
||||
ownerProps: object
|
||||
slotInjected: BoundSlotInject
|
||||
hookContext: unknown
|
||||
hasHookContext: boolean
|
||||
crashed?: ReactNode
|
||||
onEntryError: (error: unknown) => void
|
||||
}) {
|
||||
const binding = useScopeBinding()
|
||||
@@ -1044,7 +1079,13 @@ function StrictSessionEntry({ slotKey, anchor, entry, ownerProps, slotInjected,
|
||||
// Per-session remount rides this key; per-entry remount rides the outer
|
||||
// element's entry-identity key (the outlet's guarded() call).
|
||||
return (
|
||||
<SlotErrorBoundary slotKey={slotKey} anchor={anchor} key={sessionGenerationKeyOf(scopedBinding)} onEntryError={onEntryError}>
|
||||
<SlotErrorBoundary
|
||||
slotKey={slotKey}
|
||||
anchor={anchor}
|
||||
crashed={crashed}
|
||||
key={sessionGenerationKeyOf(scopedBinding)}
|
||||
onEntryError={onEntryError}
|
||||
>
|
||||
<SessionEntry
|
||||
entry={entry}
|
||||
ownerProps={ownerProps}
|
||||
@@ -1053,11 +1094,129 @@ function StrictSessionEntry({ slotKey, anchor, entry, ownerProps, slotInjected,
|
||||
slotInjected={slotInjected}
|
||||
hookContext={hookContext}
|
||||
hasHookContext={hasHookContext}
|
||||
/>
|
||||
>
|
||||
{children}
|
||||
</SessionEntry>
|
||||
</SlotErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
/** Props of one hoc layer Component: the owner share and the content it wraps. */
|
||||
interface HocLayerProps {
|
||||
owner: object
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Render the content inside one hoc layer: the next inner layer, or the owner's content itself at the innermost layer. */
|
||||
type RenderHocInner = (owner: object, children: ReactNode) => ReactNode
|
||||
|
||||
/** The innermost step: the owner's content unchanged, with no Component of its own. */
|
||||
const renderHocContent: RenderHocInner = (_owner, children) => children
|
||||
|
||||
/**
|
||||
* Build one hoc layer Component. Scope, entry, and crash reporting are fixed
|
||||
* here; a render passes only the owner share and the next inner layer. A
|
||||
* crashed layer renders that inner content and abdicates.
|
||||
* @param host - registry host owning the ledger.
|
||||
* @param slotKey - the hoc slot.
|
||||
* @param spec - its live declaration.
|
||||
* @param entry - the layer's registration.
|
||||
* @param renderInner - renders the content inside this layer.
|
||||
* @returns the layer Component.
|
||||
*/
|
||||
function hocLayer(
|
||||
host: SlotRendererHost,
|
||||
slotKey: string,
|
||||
spec: SlotSpec<SlotEntryDef>,
|
||||
entry: StoredEntry,
|
||||
renderInner: RenderHocInner,
|
||||
): FC<HocLayerProps> {
|
||||
const anchor: SlotAnchorTag = spec.inline === true ? 'span' : 'div'
|
||||
const slotInjected = cachedSlotInject(spec.inject)
|
||||
const onEntryError = (error: unknown): void => {
|
||||
host.reportEntryError(slotKey, entry, error, { abdicate: true })
|
||||
}
|
||||
let Layer: FC<HocLayerProps>
|
||||
switch (spec.scope) {
|
||||
case 'session':
|
||||
Layer = ({ owner, children }) => {
|
||||
const inner = <HocContentBoundary>{renderInner(owner, children)}</HocContentBoundary>
|
||||
return (
|
||||
<StrictSessionEntry
|
||||
slotKey={slotKey} anchor={anchor} crashed={inner} onEntryError={onEntryError}
|
||||
entry={entry} ownerProps={owner} slotInjected={slotInjected} hookContext={undefined} hasHookContext={false}
|
||||
>
|
||||
{inner}
|
||||
</StrictSessionEntry>
|
||||
)
|
||||
}
|
||||
break
|
||||
case 'session-maybe':
|
||||
Layer = ({ owner, children }) => {
|
||||
const inner = <HocContentBoundary>{renderInner(owner, children)}</HocContentBoundary>
|
||||
return (
|
||||
<SlotErrorBoundary slotKey={slotKey} anchor={anchor} crashed={inner} onEntryError={onEntryError}>
|
||||
<SessionMaybeEntry
|
||||
entry={entry} ownerProps={owner} slotKey={slotKey} slotInjected={slotInjected} hookContext={undefined} hasHookContext={false}
|
||||
>
|
||||
{inner}
|
||||
</SessionMaybeEntry>
|
||||
</SlotErrorBoundary>
|
||||
)
|
||||
}
|
||||
break
|
||||
case 'root':
|
||||
Layer = ({ owner, children }) => {
|
||||
const inner = <HocContentBoundary>{renderInner(owner, children)}</HocContentBoundary>
|
||||
return (
|
||||
<SlotErrorBoundary slotKey={slotKey} anchor={anchor} crashed={inner} onEntryError={onEntryError}>
|
||||
<RootEntry
|
||||
entry={entry} ownerProps={owner} slotKey={slotKey} slotInjected={slotInjected} hookContext={undefined} hasHookContext={false}
|
||||
>
|
||||
{inner}
|
||||
</RootEntry>
|
||||
</SlotErrorBoundary>
|
||||
)
|
||||
}
|
||||
break
|
||||
}
|
||||
return Layer
|
||||
}
|
||||
|
||||
/**
|
||||
* Compose a hoc slot's live layers, lowest `order` outermost. Winners arrive
|
||||
* in ledger order (priority first), so nesting re-sorts by `order`. Each layer
|
||||
* adds exactly one Component; with no layer the result renders the owner's
|
||||
* content directly.
|
||||
* @param host - registry host owning the ledger.
|
||||
* @param slotKey - the hoc slot.
|
||||
* @param spec - its live declaration.
|
||||
* @returns the composed render function; its layer Components are the layer set's identity.
|
||||
*/
|
||||
function composeHocLayers(host: SlotRendererHost, slotKey: string, spec: SlotSpec<SlotEntryDef>): RenderHocInner {
|
||||
const layers = [...host.entriesOfSlot(slotKey)].sort((a, b) => (a.options.order ?? 0) - (b.options.order ?? 0))
|
||||
return layers.reduceRight<RenderHocInner>((renderInner, entry) => {
|
||||
const Layer = hocLayer(host, slotKey, spec, entry, renderInner)
|
||||
return (owner, children) => <Layer owner={owner}>{children}</Layer>
|
||||
}, renderHocContent)
|
||||
}
|
||||
|
||||
/** Hoc dispatch: recomposes only when the slot's ledger version or declaration changes. */
|
||||
function HocOutlet({ slotKey, spec, ownerProps, children }: {
|
||||
slotKey: string
|
||||
spec: SlotSpec<SlotEntryDef>
|
||||
ownerProps: object
|
||||
children: ReactNode
|
||||
}) {
|
||||
const host = useHost()
|
||||
const version = host.getVersion(slotKey)
|
||||
// `version` keys the ledger read inside composeHocLayers; a new layer set yields new layer Components and remounts
|
||||
// the content.
|
||||
const renderLayers = useMemo(() => composeHocLayers(host, slotKey, spec), [host, slotKey, spec, version])
|
||||
if (renderLayers === renderHocContent) return children
|
||||
return <HocOutletBoundary>{renderLayers(ownerProps, children)}</HocOutletBoundary>
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchor style shared by every outlet wrapper: `display:contents` keeps the
|
||||
* wrapper out of layout (grid/flex parents see the slot's own children), so
|
||||
@@ -1069,7 +1228,7 @@ const ANCHOR_STYLE = { display: 'contents' } as const
|
||||
function SlotOutlet({ slotKey, ownerProps, opts, declaredInline }: {
|
||||
slotKey: string
|
||||
ownerProps: object
|
||||
opts?: (RenderOpts & ChainRenderOpts) | undefined
|
||||
opts?: OutletOpts | undefined
|
||||
declaredInline: boolean
|
||||
}) {
|
||||
const host = useHost()
|
||||
@@ -1099,12 +1258,12 @@ function SlotOutlet({ slotKey, ownerProps, opts, declaredInline }: {
|
||||
)
|
||||
}
|
||||
|
||||
/** Kind dispatch behind the outlet anchor (single/keyed/list/chain, fallbacks, crash faces). */
|
||||
/** Kind dispatch behind the outlet anchor (single/keyed/list/chain/hoc, fallbacks, crash faces). */
|
||||
function renderOutletContent(
|
||||
host: SlotRendererHost,
|
||||
slotKey: string,
|
||||
ownerProps: object,
|
||||
opts: (RenderOpts & ChainRenderOpts) | undefined,
|
||||
opts: OutletOpts | undefined,
|
||||
scopeBinding: StandardSourceBinding,
|
||||
spec: SlotSpec<SlotEntryDef>,
|
||||
): ReactNode {
|
||||
@@ -1115,6 +1274,9 @@ function renderOutletContent(
|
||||
if (spec.scope === 'session' && scopeBinding.key === undefined) {
|
||||
throw new SlotAssemblyError(`strict session slot '${slotKey}' rendered without a scope binding`)
|
||||
}
|
||||
if (spec.kind === 'hoc') {
|
||||
return <HocOutlet slotKey={slotKey} spec={spec} ownerProps={ownerProps}>{opts?.children ?? null}</HocOutlet>
|
||||
}
|
||||
const entries = host.entriesOf(slotKey)
|
||||
const slotInjected = cachedSlotInject(spec.inject)
|
||||
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Hoc slots over the real ui-slots SlotCore: nesting order, owner and
|
||||
* children delivery, remount semantics, crash skipping, and every scope.
|
||||
*/
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render } from '@testing-library/react'
|
||||
import { Component, useEffect, useState, type ReactNode } from 'react'
|
||||
import {
|
||||
SlotCore, type PropsRenderSlots, type ScopedStandardSourceBinding, type SlotRendererHost,
|
||||
type SlotScopeAdapter, type StandardSourceBinding,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { createSlotRenderer } from '../src/client/scoped-slots.tsx'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface SlotMap {
|
||||
'spec.hoc': { kind: 'hoc'; scope: 'root'; owner: { tone: string } }
|
||||
'spec.hoc.maybe': { kind: 'hoc'; scope: 'session-maybe' }
|
||||
'spec.hoc.session': { kind: 'hoc'; scope: 'session' }
|
||||
}
|
||||
}
|
||||
|
||||
type Frame = PropsRenderSlots<'spec.hoc' | 'spec.hoc.maybe' | 'spec.hoc.session'>
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
/** Passthrough host over the real core whose current scope is one live Session. */
|
||||
function hostOver(core: SlotCore): SlotRendererHost {
|
||||
const rootBinding: StandardSourceBinding = { key: undefined, hooks: {}, keyedHooks: {}, props: {} }
|
||||
const session = { key: 'S1', ctx: new Context(), hooks: {}, keyedHooks: {}, props: {} } as ScopedStandardSourceBinding
|
||||
const source = <T,>(value: T) => ({ getSnapshot: () => value, subscribe: () => () => {} })
|
||||
const sessionSource = source<StandardSourceBinding>(session)
|
||||
const adapter: SlotScopeAdapter = {
|
||||
current: sessionSource,
|
||||
bindingSource: () => sessionSource,
|
||||
renderArea: (_binding, { children }) => <>{children}</>,
|
||||
}
|
||||
return {
|
||||
subscribe: (key, fn) => core.subscribe(key, fn),
|
||||
getVersion: key => core.getVersion(key),
|
||||
entriesOf: key => core.entries(key),
|
||||
entriesOfSlot: key => core.entriesOfSlot(key),
|
||||
reportEntryError: (key, entry, error, info) => { core.reportEntryError(key, entry, error, info) },
|
||||
reportFactoryError: () => {},
|
||||
specOf: key => core.specDynamic(key),
|
||||
isLive: entry => core.isLive(entry),
|
||||
storeOf: () => undefined,
|
||||
factoryStoreOf: () => undefined,
|
||||
retainFactoryOccurrence: () => () => {},
|
||||
subscribeFactory: () => () => {},
|
||||
getFactoryVersion: () => 0,
|
||||
factoryOf: () => undefined,
|
||||
isFactoryLive: () => false,
|
||||
root: source(rootBinding),
|
||||
scopeRevision: source(0),
|
||||
scope: () => adapter,
|
||||
}
|
||||
}
|
||||
|
||||
const flush = () => act(async () => { await Promise.resolve() })
|
||||
|
||||
const mounts = vi.fn()
|
||||
|
||||
function Content({ label = 'content' }: { label?: string }) {
|
||||
useEffect(() => { mounts(label) }, [label])
|
||||
return <p data-testid={label}>{label}</p>
|
||||
}
|
||||
|
||||
/** A layer that wraps its children in a section carrying its id and the owner's tone. */
|
||||
function layer(id: string) {
|
||||
return ({ tone, children }: { tone?: string; children: ReactNode }) => (
|
||||
<section data-layer={id} data-tone={tone}>{children}</section>
|
||||
)
|
||||
}
|
||||
|
||||
let setTone: (tone: string) => void = () => {}
|
||||
|
||||
/** Register the root declaring the hoc slots, render the root-scope hoc around Content, and mount. */
|
||||
function mount(core: SlotCore, body?: (renderSlot: Frame['renderSlot']) => ReactNode) {
|
||||
core.register({
|
||||
name: 'root',
|
||||
children: {
|
||||
'spec.hoc': { kind: 'hoc', scope: 'root' },
|
||||
'spec.hoc.maybe': { kind: 'hoc', scope: 'session-maybe' },
|
||||
'spec.hoc.session': { kind: 'hoc', scope: 'session' },
|
||||
},
|
||||
}, function Root(props: Frame) {
|
||||
const [tone, set] = useState('calm')
|
||||
setTone = set
|
||||
return <>{body?.(props.renderSlot) ?? props.renderSlot('spec.hoc', { tone }, { children: <Content /> })}</>
|
||||
} as never)
|
||||
return render(<>{createSlotRenderer().renderRoot(hostOver(core), {})}</>)
|
||||
}
|
||||
|
||||
describe('hoc slots', () => {
|
||||
it('renders the content unchanged without layers, then nests layers lowest order outermost', async () => {
|
||||
const core = new SlotCore()
|
||||
const view = mount(core)
|
||||
expect(view.getByTestId('content')).toBeTruthy()
|
||||
expect(view.container.querySelector('section')).toBeNull()
|
||||
|
||||
core.register({ name: 'spec.hoc', id: 'inner', order: 10 }, layer('inner') as never)
|
||||
core.register({ name: 'spec.hoc', id: 'outer' }, layer('outer') as never)
|
||||
await flush()
|
||||
const outer = view.container.querySelector('section[data-layer="outer"]')
|
||||
const inner = outer?.querySelector(':scope > section[data-layer="inner"]')
|
||||
expect(inner?.querySelector(':scope > p')?.textContent).toBe('content')
|
||||
expect(outer?.getAttribute('data-tone')).toBe('calm')
|
||||
expect(inner?.getAttribute('data-tone')).toBe('calm')
|
||||
})
|
||||
|
||||
it('updates owner props without remounting the content, and remounts it when the layer set changes', async () => {
|
||||
const core = new SlotCore()
|
||||
mounts.mockClear()
|
||||
const view = mount(core)
|
||||
core.register({ name: 'spec.hoc', id: 'outer' }, layer('outer') as never)
|
||||
await flush()
|
||||
mounts.mockClear()
|
||||
act(() => { setTone('calm') })
|
||||
expect(mounts).not.toHaveBeenCalled()
|
||||
|
||||
act(() => { setTone('loud') })
|
||||
expect(view.container.querySelector('section')?.getAttribute('data-tone')).toBe('loud')
|
||||
expect(mounts).not.toHaveBeenCalled()
|
||||
|
||||
const dispose = core.register({ name: 'spec.hoc', id: 'inner', order: 10 }, layer('inner') as never)
|
||||
await flush()
|
||||
expect(mounts).toHaveBeenCalledOnce()
|
||||
dispose()
|
||||
await flush()
|
||||
expect(view.container.querySelector('section[data-layer="inner"]')).toBeNull()
|
||||
expect(view.getByTestId('content')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('skips a crashed layer: its content still renders and the layer leaves the slot', async () => {
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const core = new SlotCore()
|
||||
const view = mount(core)
|
||||
core.register({ name: 'spec.hoc', id: 'outer' }, layer('outer') as never)
|
||||
core.register({ name: 'spec.hoc', id: 'broken', order: 10 }, (() => { throw new Error('layer failed') }) as never)
|
||||
await flush()
|
||||
await flush()
|
||||
expect(view.container.querySelector('section[data-layer="outer"] p')?.textContent).toBe('content')
|
||||
expect(view.container.querySelector('[data-slot-error]')).toBeNull()
|
||||
expect(core.entriesOfSlot('spec.hoc').map(entry => entry.options.id)).toEqual(['outer'])
|
||||
expect(error).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes content errors upward without blaming or removing any layer', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const core = new SlotCore()
|
||||
const reported = vi.fn()
|
||||
core.onEntryError(reported)
|
||||
let failing = false
|
||||
function Fragile() {
|
||||
if (failing) throw new Error('content failed')
|
||||
return <p data-testid="fragile">fragile</p>
|
||||
}
|
||||
const caught = vi.fn()
|
||||
class Catch extends Component<{ children: ReactNode }, { error: unknown }> {
|
||||
override state: { error: unknown } = { error: undefined }
|
||||
static getDerivedStateFromError(error: unknown) { return { error } }
|
||||
override componentDidCatch(error: unknown) { caught(error) }
|
||||
override render() { return this.state.error === undefined ? this.props.children : <p data-testid="host-fallback" /> }
|
||||
}
|
||||
const view = mount(core, renderSlot => <Catch>{renderSlot('spec.hoc', { tone: 'calm' }, { children: <Fragile /> })}</Catch>)
|
||||
core.register({ name: 'spec.hoc', id: 'outer' }, layer('outer') as never)
|
||||
core.register({ name: 'spec.hoc', id: 'inner', order: 10 }, layer('inner') as never)
|
||||
await flush()
|
||||
failing = true
|
||||
act(() => { setTone('loud') })
|
||||
await flush()
|
||||
expect(view.getByTestId('host-fallback')).toBeTruthy()
|
||||
expect(caught).toHaveBeenCalledWith(expect.objectContaining({ message: 'content failed' }))
|
||||
expect(reported).not.toHaveBeenCalled()
|
||||
expect(core.entriesOfSlot('spec.hoc').map(entry => entry.options.id)).toEqual(['outer', 'inner'])
|
||||
})
|
||||
|
||||
it('renders its layers around nothing when the owner omits children', async () => {
|
||||
const core = new SlotCore()
|
||||
const view = mount(core, renderSlot => renderSlot('spec.hoc', { tone: 'calm' }))
|
||||
core.register({ name: 'spec.hoc', id: 'outer' }, layer('outer') as never)
|
||||
await flush()
|
||||
expect(view.container.querySelector('section[data-layer="outer"]')?.childNodes).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('wraps content in session-maybe and strict session layers', async () => {
|
||||
const core = new SlotCore()
|
||||
const view = mount(core, renderSlot => (
|
||||
<>
|
||||
{renderSlot('spec.hoc.maybe', {}, { children: <Content label="maybe-content" /> })}
|
||||
{renderSlot('spec.hoc.session', {}, { children: <Content label="session-content" /> })}
|
||||
</>
|
||||
))
|
||||
core.register({ name: 'spec.hoc.maybe', id: 'maybe' }, layer('maybe') as never)
|
||||
core.register({ name: 'spec.hoc.session', id: 'session' }, layer('session') as never)
|
||||
await flush()
|
||||
expect(view.container.querySelector('section[data-layer="maybe"] p')?.textContent).toBe('maybe-content')
|
||||
expect(view.container.querySelector('section[data-layer="session"] p')?.textContent).toBe('session-content')
|
||||
})
|
||||
})
|
||||
@@ -15,8 +15,8 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
/deepseek-ai-dsh-client-ui-slots/use-this-package:
|
||||
en: 05691d44a0c6c48f
|
||||
zh: 434033d5761297f3
|
||||
en: eb72211e6b97afbc
|
||||
zh: d959b329c2eee0c6
|
||||
/deepseek-ai-dsh-client-ui-slots/use-this-package/reusable-component-factories:
|
||||
en: 71cbe7aa26f3ff80
|
||||
zh: 0e35265d4d95cc36
|
||||
|
||||
@@ -25,7 +25,7 @@ English | [中文](README.zh.md)
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Compose UI through this package whenever you write a client plugin: register a component into a slot your parent declared, or declare child slots your component renders. The four kinds cover the composition shapes — `single` (one occupant), `list` (ordered entries), `keyed` (dispatch by a key), and `chain` (entries elect themselves).
|
||||
Compose UI through this package whenever you write a client plugin: register a component into a slot your parent declared, or declare child slots your component renders. The five kinds cover the composition shapes — `single` (one occupant), `list` (ordered entries), `keyed` (dispatch by a key), `chain` (entries elect themselves), and `hoc` (entries nest around the owner's `children`).
|
||||
|
||||
### Reusable Component Factories
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ kind: "package-library"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
编写客户端插件时都通过本包组合 UI:把组件注册进父级已声明的 slot,或声明组件将要渲染的子 slot。四种 kind 覆盖组合形态——`single`(单个占位者)、`list`(有序条目)、`keyed`(按键分派)与 `chain`(条目自行提名)。
|
||||
编写客户端插件时都通过本包组合 UI:把组件注册进父级已声明的 slot,或声明组件将要渲染的子 slot。五种 kind 覆盖组合形态——`single`(单个占位者)、`list`(有序条目)、`keyed`(按键分派)、`chain`(条目自行提名)与 `hoc`(条目层层包裹 owner 的 `children`)。
|
||||
|
||||
### 可复用 Component Factory
|
||||
|
||||
|
||||
@@ -97,8 +97,8 @@ export type PropsLocale<N> = N extends keyof LocaleNamespaceMap & string
|
||||
}
|
||||
: object
|
||||
|
||||
/** Slot cardinality: single occupant, ordered list, key-dispatched, or selector-routed chain. */
|
||||
export type SlotKind = 'single' | 'list' | 'keyed' | 'chain'
|
||||
/** Slot cardinality: single occupant, ordered list, key-dispatched, selector-routed chain, or nested wrapper layers. */
|
||||
export type SlotKind = 'single' | 'list' | 'keyed' | 'chain' | 'hoc'
|
||||
|
||||
/** Slot data context: global, current-session-optional, or strict session-bound. */
|
||||
export type SlotScope = 'root' | 'session-maybe' | 'session'
|
||||
@@ -286,6 +286,16 @@ export interface ChainRenderOpts {
|
||||
overlay?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* renderSlot options for a hoc slot. `children` is the owner's content; every
|
||||
* live entry wraps it, and the slot renders it unchanged when no entry is live.
|
||||
* Omitted content renders the layers around nothing.
|
||||
*/
|
||||
export interface HocRenderOpts {
|
||||
/** Innermost content wrapped by the slot's entries. */
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Chain-entry selector: the routing decision of one chain contribution.
|
||||
* Runs at render time in chain order (ascending `priority`, default 0, lower
|
||||
@@ -303,12 +313,16 @@ export type ChainSelect<O extends object, M> = (owner: O) => M | null
|
||||
export type ChainKeysOf<S extends keyof SlotMap & string> =
|
||||
S extends unknown ? (SlotMap[S]['kind'] extends 'chain' ? S : never) : never
|
||||
|
||||
/** Keys of a slot-key union whose SlotMap entry is hoc-kind (renderSlot requires `children`). */
|
||||
export type HocKeysOf<S extends keyof SlotMap & string> =
|
||||
S extends unknown ? (SlotMap[S]['kind'] extends 'hoc' ? S : never) : never
|
||||
|
||||
/** Keys in a render share whose dispatch occurrence requires hookContext. */
|
||||
type ContextualKeysOf<S extends keyof SlotMap & string> =
|
||||
S extends unknown ? (SlotMap[S] extends { hookContext: unknown } ? S : never) : never
|
||||
|
||||
/** Keys in a render share with the ordinary optional options bag. */
|
||||
type OrdinaryKeysOf<S extends keyof SlotMap & string> = Exclude<S, ContextualKeysOf<S>>
|
||||
type OrdinaryKeysOf<S extends keyof SlotMap & string> = Exclude<S, ContextualKeysOf<S> | HocKeysOf<S>>
|
||||
|
||||
/**
|
||||
* Plain and contextual child dispatch signatures. Keeping them as separate
|
||||
@@ -316,9 +330,12 @@ type OrdinaryKeysOf<S extends keyof SlotMap & string> = Exclude<S, ContextualKey
|
||||
* declared hookContext mandatory only for the Slot keys that need it.
|
||||
*/
|
||||
type RenderSlotFn<S extends keyof SlotMap & string> =
|
||||
([ContextualKeysOf<S>] extends [never] ? object : {
|
||||
([HocKeysOf<S>] extends [never] ? object : {
|
||||
<K extends HocKeysOf<S>>(key: K, owner: OwnerOf<K>, opts?: HocRenderOpts): ReactNode
|
||||
}) &
|
||||
([Exclude<ContextualKeysOf<S>, HocKeysOf<S>>] extends [never] ? object : {
|
||||
<
|
||||
K extends ContextualKeysOf<S>,
|
||||
K extends Exclude<ContextualKeysOf<S>, HocKeysOf<S>>,
|
||||
EntryKey extends EntryKeyOf<K> = EntryKeyOf<K>,
|
||||
>(
|
||||
key: K,
|
||||
@@ -345,6 +362,14 @@ type RenderSlotFn<S extends keyof SlotMap & string> =
|
||||
export type MatchedShare<E extends SlotEntryDef, M> =
|
||||
E['kind'] extends 'chain' ? { matched: M } : object
|
||||
|
||||
/**
|
||||
* Hoc children share: a hoc-slot component receives the next inner layer, or
|
||||
* the owner's content at the innermost layer, as the framework-injected
|
||||
* `children` prop and renders it exactly once.
|
||||
*/
|
||||
export type HocShare<E extends SlotEntryDef> =
|
||||
E['kind'] extends 'hoc' ? { children: ReactNode } : object
|
||||
|
||||
/** Props of the standard-kit SessionProvider seat. */
|
||||
export interface SessionAreaProps {
|
||||
/**
|
||||
@@ -377,10 +402,11 @@ export type SessionProviderComponent = (props: SessionAreaProps) => ReactNode
|
||||
export type PropsRenderSlots<S extends keyof SlotMap & string> = {
|
||||
/**
|
||||
* Render a declared non-chain child slot (chain keys dispatch through
|
||||
* `renderSlotChain` — their routing lives in entry selectors).
|
||||
* `renderSlotChain` — their routing lives in entry selectors). A hoc key
|
||||
* takes the content its entries wrap as `opts.children`.
|
||||
* @param key - declared child key.
|
||||
* @param owner - owner props share for that key (decided at the render site).
|
||||
* @param opts - kind dispatch options.
|
||||
* @param opts - kind dispatch options; `{ children }` for hoc keys.
|
||||
* @returns rendered node(s).
|
||||
*/
|
||||
renderSlot: RenderSlotFn<Exclude<S, ChainKeysOf<S>>>
|
||||
@@ -611,7 +637,7 @@ export type ComposedProps<
|
||||
M = never,
|
||||
N = undefined,
|
||||
> = PropsRuntime<K, EntryKey> & PropsRenderSlots<S> & PropsRenderFactories
|
||||
& PropsStore<H> & InjectFace<I> & MatchedShare<SlotMap[K], M> & PropsLocale<N>
|
||||
& PropsStore<H> & InjectFace<I> & MatchedShare<SlotMap[K], M> & HocShare<SlotMap[K]> & PropsLocale<N>
|
||||
|
||||
/**
|
||||
* Inject factory parameter list, derived from the registration's declaration:
|
||||
@@ -763,7 +789,8 @@ export type SlotLabel = string | (() => string)
|
||||
|
||||
/**
|
||||
* Kind shape fields carried in register options (keyed dispatch key; list
|
||||
* id/order/label; chain select/priority; non-chain priority = cell shadowing rank).
|
||||
* id/order/label; hoc id/order; chain select/priority; for every other kind
|
||||
* priority is the cell shadowing rank, and hoc nesting follows order).
|
||||
*/
|
||||
export type KindOptions<
|
||||
K extends keyof SlotMap & string,
|
||||
@@ -788,13 +815,20 @@ export type KindOptions<
|
||||
/** Explicit chain position (ascending, default 0, lower tries first); ties keep registration = assembly order. */
|
||||
priority?: number
|
||||
}
|
||||
: {
|
||||
/**
|
||||
* Cell shadowing rank (ascending, default 0, lowest renders; a
|
||||
* same-priority second registration throws — see {@link SlotCore.register}).
|
||||
*/
|
||||
: SlotMap[K]['kind'] extends 'hoc' ? {
|
||||
id: string
|
||||
/** Nesting position: ascending, default 0; the lowest order is the outermost layer. */
|
||||
order?: number
|
||||
/** Cell shadowing rank (ascending, default 0, lowest renders; same id + same priority throws — see {@link SlotCore.register}). */
|
||||
priority?: number
|
||||
}
|
||||
: {
|
||||
/**
|
||||
* Cell shadowing rank (ascending, default 0, lowest renders; a
|
||||
* same-priority second registration throws — see {@link SlotCore.register}).
|
||||
*/
|
||||
priority?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile-time presence check: an entry declaring children MUST consume
|
||||
@@ -1132,11 +1166,11 @@ export class SlotCore {
|
||||
* an already-declared child key throws (one declarer per slot — the message
|
||||
* names the first declarer); mounting one shared store handle under slots
|
||||
* of different scopes throws. Kind constraints: keyed — missing `key`
|
||||
* throws; list — missing `id` throws; chain — missing `select` throws (the
|
||||
* selector is the entry's routing seat, see {@link ChainSelect}).
|
||||
* throws; list and hoc — missing `id` throws; chain — missing `select`
|
||||
* throws (the selector is the entry's routing seat, see {@link ChainSelect}).
|
||||
*
|
||||
* Shadowing (single/keyed/list): entries sharing one cell (single — the
|
||||
* slot itself; keyed — same `key`; list — same `id`) coexist at distinct
|
||||
* Shadowing (single/keyed/list/hoc): entries sharing one cell (single — the
|
||||
* slot itself; keyed — same `key`; list and hoc — same `id`) coexist at distinct
|
||||
* priorities, sorted ascending with ties keeping registration order; the
|
||||
* cell's lowest live entry renders ({@link SlotCore.entriesOfSlot}). A
|
||||
* second registration at an occupied cell's exact priority (default 0)
|
||||
@@ -1230,11 +1264,12 @@ export class SlotCore {
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'list': {
|
||||
if (options.id === undefined) throw new Error(`list slot "${options.name}" requires options.id`)
|
||||
case 'list':
|
||||
case 'hoc': {
|
||||
if (options.id === undefined) throw new Error(`${spec.kind} slot "${options.name}" requires options.id`)
|
||||
const occupant = rec.entries.find(e => e.options.id === options.id && (e.options.priority ?? 0) === priority)
|
||||
if (occupant) {
|
||||
throw new Error(`list slot "${options.name}" already has an entry with id "${options.id}" ${occupantHint(occupant)}`)
|
||||
throw new Error(`${spec.kind} slot "${options.name}" already has an entry with id "${options.id}" ${occupantHint(occupant)}`)
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -1281,9 +1316,10 @@ export class SlotCore {
|
||||
const next = [...rec.entries, entry]
|
||||
// Stable sorts: priority ascending for every kind, ties keep registration
|
||||
// sequence — a cell's winner is its first occurrence, chain tries lower
|
||||
// priority first. List refines equal priorities by explicit `order` so the
|
||||
// raw ledger keeps its display sequence for priority-less compositions.
|
||||
next.sort(spec.kind === 'list'
|
||||
// priority first. List and hoc refine equal priorities by explicit `order`
|
||||
// so the raw ledger keeps its display or nesting sequence for priority-less
|
||||
// compositions.
|
||||
next.sort(spec.kind === 'list' || spec.kind === 'hoc'
|
||||
? (a, b) => ((a.options.priority ?? 0) - (b.options.priority ?? 0)) || ((a.options.order ?? 0) - (b.options.order ?? 0))
|
||||
: (a, b) => (a.options.priority ?? 0) - (b.options.priority ?? 0))
|
||||
rec.entries = next
|
||||
@@ -1344,8 +1380,9 @@ export class SlotCore {
|
||||
/**
|
||||
* Project a key's entries to its shadowing winners: the first live
|
||||
* (non-abdicated) entry of each cell in priority order — single: the slot
|
||||
* is one cell; keyed: one cell per `key`; list: one cell per `id` (winners
|
||||
* keep ledger sequence; list renderers still refine display by `order`).
|
||||
* is one cell; keyed: one cell per `key`; list and hoc: one cell per `id`
|
||||
* (winners keep ledger sequence; renderers still refine list display and hoc
|
||||
* nesting by `order`).
|
||||
* Chain keys return the raw entries unchanged: election consumes every
|
||||
* entry, shadowing does not apply. The raw {@link SlotCore.entries} view
|
||||
* stays the inspection surface. Builds a fresh array per call — a render
|
||||
@@ -1363,7 +1400,7 @@ export class SlotCore {
|
||||
for (const entry of rec.entries) {
|
||||
if (this.abdicated.has(entry)) continue
|
||||
// Single-kind entries all share the one undefined cell.
|
||||
const cell = kind === 'keyed' ? entry.options.key : kind === 'list' ? entry.options.id : undefined
|
||||
const cell = kind === 'keyed' ? entry.options.key : kind === 'list' || kind === 'hoc' ? entry.options.id : undefined
|
||||
if (seenCells.has(cell)) continue
|
||||
seenCells.add(cell)
|
||||
heads.push(entry)
|
||||
@@ -1529,7 +1566,7 @@ export class SlotCore {
|
||||
/**
|
||||
* Renderer crash report from an entry boundary. Always notifies
|
||||
* {@link SlotCore.onEntryError} listeners; with `info.abdicate` set (the
|
||||
* shadowing kinds — single/keyed/list) it first retires the entry from its
|
||||
* shadowing kinds — single/keyed/list/hoc) it first retires the entry from its
|
||||
* cell, one-shot: the record's version bumps through the ordinary mutation
|
||||
* channel so outlets re-project onto the cell's next survivor, and a
|
||||
* repeat abdicating report no-ops entirely. Chain crashes report with
|
||||
|
||||
@@ -11,6 +11,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
'test.list': { kind: 'list'; scope: 'root' }
|
||||
'test.keyed': { kind: 'keyed'; scope: 'session' }
|
||||
'test.chain': { kind: 'chain'; scope: 'session'; owner: { tags: string[] } }
|
||||
'test.hoc': { kind: 'hoc'; scope: 'root' }
|
||||
'test.grandchild': { kind: 'single'; scope: 'root' }
|
||||
}
|
||||
}
|
||||
@@ -36,6 +37,7 @@ function mountFrame(core: SlotCore) {
|
||||
'test.list': { kind: 'list', scope: 'root' },
|
||||
'test.keyed': { kind: 'keyed', scope: 'session' },
|
||||
'test.chain': { kind: 'chain', scope: 'session' },
|
||||
'test.hoc': { kind: 'hoc', scope: 'root' },
|
||||
},
|
||||
// Type-level renderSlot presence is proven by the type-chain spec; erasing
|
||||
// here keeps runtime fixtures terse.
|
||||
@@ -168,6 +170,19 @@ describe('kind semantics', () => {
|
||||
expect(core.entries('test.list').map(e => e.options.id)).toEqual(['a', 'b', 'c'])
|
||||
})
|
||||
|
||||
it('hoc: missing or duplicate id throws, layers sort by priority then order, one winner per id', () => {
|
||||
const core = new SlotCore()
|
||||
mountFrame(core)
|
||||
core.register({ name: 'test.hoc', id: 'inner', order: 10 }, Comp as never)
|
||||
core.register({ name: 'test.hoc', id: 'outer' }, Comp as never)
|
||||
expect(() => core.register({ name: 'test.hoc', id: 'outer' }, Comp as never)).toThrow('hoc slot "test.hoc" already has an entry with id "outer"')
|
||||
// @ts-expect-error hoc registration requires options.id
|
||||
expect(() => core.register({ name: 'test.hoc' }, Comp)).toThrow('hoc slot "test.hoc" requires options.id')
|
||||
core.register({ name: 'test.hoc', id: 'inner', priority: -1, registrant: 'shadow' }, Comp as never)
|
||||
expect(core.entries('test.hoc').map(e => e.options.id)).toEqual(['inner', 'outer', 'inner'])
|
||||
expect(core.entriesOfSlot('test.hoc').map(e => e.registrant ?? e.options.id)).toEqual(['shadow', 'outer'])
|
||||
})
|
||||
|
||||
it('chain: missing select throws; select and priority land on the stored entry', () => {
|
||||
const core = new SlotCore()
|
||||
mountFrame(core)
|
||||
@@ -393,7 +408,7 @@ describe('subscription API', () => {
|
||||
const off = core.onMutate(key => keys.push(key))
|
||||
mountFrame(core)
|
||||
// Contribution first, then each declared child key.
|
||||
expect(keys).toEqual(['root', 'test.single', 'test.session', 'test.list', 'test.keyed', 'test.chain'])
|
||||
expect(keys).toEqual(['root', 'test.single', 'test.session', 'test.list', 'test.keyed', 'test.chain', 'test.hoc'])
|
||||
keys.length = 0
|
||||
core.register({ name: 'test.list', id: 'a' }, Comp)
|
||||
expect(keys).toEqual(['test.list'])
|
||||
|
||||
@@ -28,6 +28,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
}
|
||||
'chain.tools': { kind: 'keyed'; scope: 'session' }
|
||||
'chain.takeover': { kind: 'chain'; scope: 'session'; owner: { items: readonly Item[] } }
|
||||
'chain.layer': { kind: 'hoc'; scope: 'root'; owner: { tone: string } }
|
||||
}
|
||||
|
||||
interface LocaleNamespaceMap {
|
||||
@@ -213,6 +214,14 @@ describe('terminal-design type chain', () => {
|
||||
chainSlots.renderSlotChain('chain.takeover', { items: [] }, { fallback: null })
|
||||
chainSlots.renderSlot('chain.conv', {})
|
||||
|
||||
// hoc share: a layer component receives the owner props plus children; renderSlot takes optional
|
||||
// { children } for hoc keys.
|
||||
const Layer: SlotComponent<PropsRuntime<'chain.layer'> & { children: ReactNode }> = ({ children }) => children
|
||||
core.register({ name: 'chain.layer', id: 'frame', order: 1 }, Layer)
|
||||
const layerSlots: PropsRenderSlots<'chain.layer' | 'chain.conv'> = null as never
|
||||
layerSlots.renderSlot('chain.layer', { tone: 'calm' }, { children: null })
|
||||
layerSlots.renderSlot('chain.layer', { tone: 'calm' })
|
||||
|
||||
// A parent registration declares the Slot inject once; every child
|
||||
// entry receives the same custom Hook, bound to official standard props
|
||||
// and each render occurrence's opaque context.
|
||||
@@ -305,6 +314,16 @@ describe('terminal-design type chain', () => {
|
||||
// @ts-expect-error a children set without chain keys provides no renderSlotChain
|
||||
type _NoChainSeat = typeof fp.renderSlotChain
|
||||
|
||||
// hoc keys take only { children }; other keys take no children; hoc registration requires an id.
|
||||
// @ts-expect-error hoc keys accept no fallback
|
||||
layerSlots.renderSlot('chain.layer', { tone: 'calm' }, { fallback: null })
|
||||
// @ts-expect-error non-hoc keys accept no children
|
||||
layerSlots.renderSlot('chain.conv', {}, { children: null })
|
||||
// @ts-expect-error hoc registration requires options.id
|
||||
core.register({ name: 'chain.layer' }, Layer)
|
||||
// @ts-expect-error a hoc layer must accept children
|
||||
core.register({ name: 'chain.layer', id: 'no-children' }, (_p => null) as SlotComponent<PropsRuntime<'chain.layer'> & { children: number }>)
|
||||
|
||||
// renderSlot owner share typed at the call site.
|
||||
// @ts-expect-error owner shape mismatch (width missing)
|
||||
fp.renderSlot('chain.side', { collapsed: false })
|
||||
|
||||
@@ -529,7 +529,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'ComposedProps',
|
||||
declaration: 'export type ComposedProps<K extends keyof SlotMap & string, EntryKey extends EntryKeyOf<K>, S extends keyof SlotMap & string, H, I extends object, M = never, N = undefined> = PropsRuntime<K, EntryKey> & PropsRenderSlots<S> & PropsRenderFactories & PropsStore<H> & InjectFace<I> & MatchedShare<SlotMap[K], M> & PropsLocale<N>;',
|
||||
declaration: 'export type ComposedProps<K extends keyof SlotMap & string, EntryKey extends EntryKeyOf<K>, S extends keyof SlotMap & string, H, I extends object, M = never, N = undefined> = PropsRuntime<K, EntryKey> & PropsRenderSlots<S> & PropsRenderFactories & PropsStore<H> & InjectFace<I> & MatchedShare<SlotMap[K], M> & HocShare<SlotMap[K]> & PropsLocale<N>;',
|
||||
},
|
||||
{
|
||||
name: 'ConnectionGeneration',
|
||||
@@ -639,6 +639,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'HandleOf',
|
||||
declaration: 'export type HandleOf<H> = H extends () => infer R ? R : H;',
|
||||
},
|
||||
{
|
||||
name: 'HocShare',
|
||||
declaration: 'export type HocShare<E extends SlotEntryDef> = E[\'kind\'] extends \'hoc\' ? {\n children: ReactNode;\n} : object;',
|
||||
},
|
||||
{
|
||||
name: 'HooksSources',
|
||||
declaration: 'export type HooksSources = Record<string, HostObservable<unknown>>;',
|
||||
@@ -1001,7 +1005,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'SlotKind',
|
||||
declaration: 'export type SlotKind = \'single\' | \'list\' | \'keyed\' | \'chain\';',
|
||||
declaration: 'export type SlotKind = \'single\' | \'list\' | \'keyed\' | \'chain\' | \'hoc\';',
|
||||
},
|
||||
{
|
||||
name: 'SlotLabel',
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface ClientSlotOption {
|
||||
export interface ClientSlotEntry {
|
||||
/** SlotMap key passed as the register call's `name`. */
|
||||
key: string
|
||||
/** Cardinality: `single`, `list`, `keyed`, or `chain`. */
|
||||
/** Cardinality: `single`, `list`, `keyed`, `chain`, or `hoc`. */
|
||||
kind: string
|
||||
/** Data scope: `root`, `session`, or `session-maybe`. */
|
||||
scope: string
|
||||
@@ -56,7 +56,10 @@ export interface ClientSlotEntry {
|
||||
declaredBy: string
|
||||
/** Entries the shipped composition already registered here. */
|
||||
occupants: readonly string[]
|
||||
/** `shadows-shipped-ui` when registering here replaces shipped UI; `none` when additive. */
|
||||
/**
|
||||
* `shadows-shipped-ui` when registering here replaces shipped UI; `wraps-owner-content` when your
|
||||
* component wraps the owner content and must render `children`; `none` when additive.
|
||||
*/
|
||||
replaceRisk: string
|
||||
/** A minimal browser half that registers into this slot. */
|
||||
example: string
|
||||
@@ -853,7 +856,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.bar\', () => ctx.slots.register(\n { name: \'conversation.composer.bar\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:327',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:329',
|
||||
},
|
||||
{
|
||||
key: 'conversation.composer.dock',
|
||||
@@ -914,7 +917,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.dock\', () => ctx.slots.register(\n { name: \'conversation.composer.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:306',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:308',
|
||||
},
|
||||
{
|
||||
key: 'conversation.header',
|
||||
@@ -1026,7 +1029,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.agentPreset\', () => ctx.slots.register(\n { name: \'conversation.hero.agentPreset\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:289',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:291',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.brand.mark',
|
||||
@@ -1036,7 +1039,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
doc: 'Brand mark shown before the blank-session headline.',
|
||||
registerOptions: [],
|
||||
ownerProps: [
|
||||
'/** Presentation props supplied to the blank-session brand mark. */\nexport interface HeroBrandMarkOwnerProps {\n /** Requested square edge in pixels. */\n size: number\n /** Host class preserving the surrounding mark geometry. */\n className?: string | undefined\n}',
|
||||
'/** Brand-mark presentation selected by the blank home. */\nexport interface HeroBrandMarkOwnerProps {\n /** Requested square edge in pixels. */\n size: number\n /** Host class preserving the surrounding mark geometry. */\n className?: string | undefined\n}',
|
||||
],
|
||||
ownerPropsReferences: [],
|
||||
standardProps: [
|
||||
@@ -1058,6 +1061,53 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.brand.mark\', () => ctx.slots.register(\n { name: \'conversation.hero.brand.mark\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:289',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.frame',
|
||||
kind: 'hoc',
|
||||
scope: 'root',
|
||||
summary: 'Layers wrapping the Conversation scroll body; `hero` reports a blank, standalone home.',
|
||||
doc: 'Layers wrapping the Conversation scroll body; `hero` reports a blank, standalone home.',
|
||||
registerOptions: [
|
||||
{
|
||||
name: 'id',
|
||||
requirement: 'required',
|
||||
type: 'string',
|
||||
doc: 'Your layer key. A fresh id adds a layer; reusing a shipped id replaces that layer. Your component must render its `children` prop: a layer that omits it hides the owner content, such as the whole conversation and its composer.',
|
||||
},
|
||||
{
|
||||
name: 'order',
|
||||
requirement: 'optional',
|
||||
type: 'number',
|
||||
doc: 'Nesting position, ascending (default 0); the lowest order is the outermost layer. Render the `children` prop exactly once.',
|
||||
},
|
||||
],
|
||||
ownerProps: [
|
||||
'/** Conversation state exposed to scroll-body frame layers. */\nexport interface HeroFrameOwnerProps {\n /** Whether the body shows the blank home of a standalone, non-embedded Conversation. */\n hero: boolean\n}',
|
||||
],
|
||||
ownerPropsReferences: [],
|
||||
standardProps: [
|
||||
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
|
||||
'useResource: UseResource',
|
||||
'useContextMenu: UseContextMenu',
|
||||
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
|
||||
'usePanelInfo: UsePanelInfo',
|
||||
'useSessions: UseSessions',
|
||||
'useSessionStatus: UseSessionStatus',
|
||||
'useSessionRetainInfo: UseSessionRetainInfo',
|
||||
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
|
||||
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
|
||||
],
|
||||
keyDomain: '',
|
||||
hookContext: '',
|
||||
slotInject: '',
|
||||
declaredBy: 'factory \'conversation.content\' (client-ui-conversation), so it exists while that definition is registered',
|
||||
occupants: [
|
||||
'client-ui-brand-official PixelWhale id \'pixel-whale\'',
|
||||
],
|
||||
replaceRisk: 'wraps-owner-content',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.frame\', () => ctx.slots.register(\n { name: \'conversation.hero.frame\', id: \'my-layer\', order: 100 },\n ({ children }) => React.createElement(\'div\', null, children),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:287',
|
||||
},
|
||||
{
|
||||
@@ -1118,7 +1168,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.options\', () => ctx.slots.register(\n { name: \'conversation.hero.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:291',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:293',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.workspace',
|
||||
@@ -1234,7 +1284,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.activity\', () => ctx.slots.register(\n { name: \'conversation.input.activity\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:322',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:324',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.attachments',
|
||||
@@ -1279,7 +1329,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.attachments\', () => ctx.slots.register(\n { name: \'conversation.input.attachments\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:332',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:334',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.dock',
|
||||
@@ -1348,7 +1398,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.dock\', () => ctx.slots.register(\n { name: \'conversation.input.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:296',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:298',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.left',
|
||||
@@ -1406,7 +1456,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.left\', () => ctx.slots.register(\n { name: \'conversation.input.left\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:311',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:313',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.model',
|
||||
@@ -1450,7 +1500,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model\', () => ctx.slots.register(\n { name: \'conversation.input.model\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:353',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:355',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.model.label',
|
||||
@@ -1616,7 +1666,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:301',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:303',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.permission',
|
||||
@@ -1660,7 +1710,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.permission\', () => ctx.slots.register(\n { name: \'conversation.input.permission\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:346',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:348',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.plan',
|
||||
@@ -1703,7 +1753,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.plan\', () => ctx.slots.register(\n { name: \'conversation.input.plan\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:341',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:343',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.right',
|
||||
@@ -1761,7 +1811,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.right\', () => ctx.slots.register(\n { name: \'conversation.input.right\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:316',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:318',
|
||||
},
|
||||
{
|
||||
key: 'conversation.plan-review.actions',
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
|
||||
| `@deepseek-ai/dsh-client-ui-agent-team` | no | Web shared task board for a subagent tree |
|
||||
| `@deepseek-ai/dsh-client-ui-approval` | no | Approval composer takeover over the scoped Remote Event waterfall |
|
||||
| `@deepseek-ai/dsh-client-ui-attachment` | no | Dynamic attachment presentation plugin for conversation input, message-image, and trajectory image slots |
|
||||
| `@deepseek-ai/dsh-client-ui-brand-official` | no | Official DeepSeek Harness brand occupants for the Web client's sidebar slots |
|
||||
| `@deepseek-ai/dsh-client-ui-brand-official` | no | Official DeepSeek Harness brand artwork and click-triggered home background |
|
||||
| `@deepseek-ai/dsh-client-ui-chat` | no | Chat Conversation target, node definitions, renderers, and details surface |
|
||||
| `@deepseek-ai/dsh-client-ui-commands` | no | Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry |
|
||||
| `@deepseek-ai/dsh-client-ui-context-menu` | no | Typed, plugin-extensible context menus with captured targets and shared Web presentation |
|
||||
|
||||
Generated
+6
@@ -3918,6 +3918,9 @@ importers:
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: workspace:~
|
||||
version: link:../../../vendor/cordis
|
||||
'@deepseek-ai/dsh-client-ui-conversation':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-conversation
|
||||
'@deepseek-ai/dsh-client-ui-primitives':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-primitives
|
||||
@@ -3927,6 +3930,9 @@ importers:
|
||||
'@deepseek-ai/dsh-client-ui-sidebar':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-sidebar
|
||||
'@deepseek-ai/dsh-client-ui-slots':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-slots
|
||||
'@testing-library/react':
|
||||
specifier: ^16.3.3
|
||||
version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
|
||||
@@ -241,13 +241,17 @@ describe('the real workspace surface', () => {
|
||||
expect(entries.length).toBeGreaterThan(30)
|
||||
for (const entry of entries) {
|
||||
expect(entry.summary, `${entry.key} has no summary`).not.toBe('')
|
||||
expect(['single', 'list', 'keyed', 'chain']).toContain(entry.kind)
|
||||
expect(['single', 'list', 'keyed', 'chain', 'hoc']).toContain(entry.kind)
|
||||
expect(['root', 'session', 'session-maybe']).toContain(entry.scope)
|
||||
}
|
||||
// The frame root is the canonical trap: occupied by the shipped app frame,
|
||||
// so a dynamic package registering there replaces the whole UI.
|
||||
const root = entries.find(entry => entry.key === 'root')
|
||||
expect(root?.replaceRisk).toBe('shadows-shipped-ui')
|
||||
// A hoc layer wraps the owner content; its example must keep rendering it.
|
||||
const frame = entries.find(entry => entry.key === 'conversation.hero.frame')
|
||||
expect(frame?.replaceRisk).toBe('wraps-owner-content')
|
||||
expect(frame?.example).toContain('({ children }) => React.createElement(\'div\', null, children)')
|
||||
expect(root?.occupants.join(' ')).toContain('AppFrame')
|
||||
expect(entries.find(entry => entry.key === 'conversation.session')?.declaredBy)
|
||||
.toContain("factory 'conversation.content' (client-ui-conversation)")
|
||||
|
||||
@@ -33,7 +33,7 @@ const OUT = 'packages/extensions/cordis-client-runner/src/client/slot-catalog.ts
|
||||
const SOURCE_GLOBS = ['packages/*/*/src/**/*.ts', 'packages/*/*/src/**/*.tsx']
|
||||
|
||||
/** Slot cardinalities the contract allows. */
|
||||
const KINDS = ['single', 'list', 'keyed', 'chain'] as const
|
||||
const KINDS = ['single', 'list', 'keyed', 'chain', 'hoc'] as const
|
||||
/** Slot data scopes the contract allows. */
|
||||
const SCOPES = ['root', 'session', 'session-maybe'] as const
|
||||
|
||||
@@ -82,6 +82,10 @@ const REGISTER_OPTIONS: Readonly<Record<(typeof KINDS)[number], readonly OptionD
|
||||
chain: [
|
||||
{ name: 'select', requirement: 'required', type: '(owner) => unknown | null', doc: 'Pure routing selector. Entries are tried in ascending order; the first non-null result wins and arrives as the component\'s `matched` prop. All-null falls through to the owner\'s fallback.' },
|
||||
],
|
||||
hoc: [
|
||||
{ name: 'id', requirement: 'required', type: 'string', doc: 'Your layer key. A fresh id adds a layer; reusing a shipped id replaces that layer. Your component must render its `children` prop: a layer that omits it hides the owner content, such as the whole conversation and its composer.' },
|
||||
{ name: 'order', requirement: 'optional', type: 'number', doc: 'Nesting position, ascending (default 0); the lowest order is the outermost layer. Render the `children` prop exactly once.' },
|
||||
],
|
||||
}
|
||||
|
||||
/** The one register option a dynamic package must NOT pass, and why. */
|
||||
@@ -301,9 +305,11 @@ function entryOf(
|
||||
...occupant.id === undefined ? [] : [`id '${occupant.id}'`],
|
||||
...occupant.entryKey === undefined ? [] : [`key '${occupant.entryKey}'`],
|
||||
].join(' ')),
|
||||
replaceRisk: cellOccupied && (declaration.kind === 'single' || declaration.kind === 'keyed')
|
||||
? 'shadows-shipped-ui'
|
||||
: 'none',
|
||||
replaceRisk: declaration.kind === 'hoc'
|
||||
? 'wraps-owner-content'
|
||||
: cellOccupied && (declaration.kind === 'single' || declaration.kind === 'keyed')
|
||||
? 'shadows-shipped-ui'
|
||||
: 'none',
|
||||
example: exampleOf(declaration),
|
||||
source: declaration.source,
|
||||
}
|
||||
@@ -365,7 +371,9 @@ function exampleOf(declaration: SlotDeclaration): string {
|
||||
' apply(ctx) {',
|
||||
` ctx.slots.inject('${declaration.key}', () => ctx.slots.register(`,
|
||||
` { ${options} },`,
|
||||
" () => React.createElement('div', null, 'hello'),",
|
||||
declaration.kind === 'hoc'
|
||||
? " ({ children }) => React.createElement('div', null, children),"
|
||||
: " () => React.createElement('div', null, 'hello'),",
|
||||
' ))',
|
||||
' },',
|
||||
'}',
|
||||
@@ -393,6 +401,7 @@ const KIND_EXAMPLE: Readonly<Record<string, readonly string[]>> = {
|
||||
list: ["id: 'my-entry'", 'order: 100', "label: 'My entry'"],
|
||||
keyed: ["key: '<one key the owner dispatches>'"],
|
||||
chain: ['select: owner => null'],
|
||||
hoc: ["id: 'my-layer'", 'order: 100'],
|
||||
}
|
||||
|
||||
/** Drop the `@deepseek-ai/dsh-` prefix so rows stay readable. */
|
||||
@@ -476,7 +485,7 @@ export function renderClientCatalog(entries: readonly SlotEntry[]): string {
|
||||
'export interface ClientSlotEntry {',
|
||||
' /** SlotMap key passed as the register call\'s `name`. */',
|
||||
' key: string',
|
||||
' /** Cardinality: `single`, `list`, `keyed`, or `chain`. */',
|
||||
' /** Cardinality: `single`, `list`, `keyed`, `chain`, or `hoc`. */',
|
||||
' kind: string',
|
||||
' /** Data scope: `root`, `session`, or `session-maybe`. */',
|
||||
' scope: string',
|
||||
@@ -502,7 +511,10 @@ export function renderClientCatalog(entries: readonly SlotEntry[]): string {
|
||||
' declaredBy: string',
|
||||
' /** Entries the shipped composition already registered here. */',
|
||||
' occupants: readonly string[]',
|
||||
' /** `shadows-shipped-ui` when registering here replaces shipped UI; `none` when additive. */',
|
||||
' /**',
|
||||
' * `shadows-shipped-ui` when registering here replaces shipped UI; `wraps-owner-content` when your',
|
||||
' * component wraps the owner content and must render `children`; `none` when additive.',
|
||||
' */',
|
||||
' replaceRisk: string',
|
||||
' /** A minimal browser half that registers into this slot. */',
|
||||
' example: string',
|
||||
|
||||
@@ -24,7 +24,7 @@ const REGISTER_HEAD = /\.(?:register|registerFactory)\(/
|
||||
export interface SlotDeclaration {
|
||||
/** SlotMap key, e.g. `settings.section`. */
|
||||
key: string
|
||||
/** Cardinality literal (`single` / `list` / `keyed` / `chain`), or '' when not a literal. */
|
||||
/** Cardinality literal (`single` / `list` / `keyed` / `chain` / `hoc`), or '' when not a literal. */
|
||||
kind: string
|
||||
/** Data-scope literal (`root` / `session` / `session-maybe`), or '' when not a literal. */
|
||||
scope: string
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"rewriteRelativeImportExtensions": false
|
||||
},
|
||||
"include": [
|
||||
"apps/web/tests/home-whale.e2e.ts",
|
||||
"apps/web/tests/sidebar-drawer.e2e.ts",
|
||||
"apps/web/tests/creation-recommendations.e2e.ts",
|
||||
"apps/web/tests/plugin-recommendations.e2e.ts",
|
||||
|
||||
Reference in New Issue
Block a user