@cpsoft13/z-agent-ui 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/bin/lines-baseline.json +1 -15
  2. package/bin/text-baseline.json +1 -2
  3. package/dist/build-info.json +2 -2
  4. package/dist/components/context-menu/ContextMenu.js +7 -7
  5. package/dist/components/context-menu/ContextMenu.js.map +1 -1
  6. package/dist/components/date-range/DateRange.js +4 -4
  7. package/dist/components/date-range/DateRange.js.map +1 -1
  8. package/dist/components/datepicker/Datepicker.js +207 -332
  9. package/dist/components/datepicker/Datepicker.js.map +1 -1
  10. package/dist/components/datepicker/datepicker-keyboard.js +66 -0
  11. package/dist/components/datepicker/datepicker-keyboard.js.map +1 -0
  12. package/dist/components/datepicker/datepicker-panel-render.js +78 -0
  13. package/dist/components/datepicker/datepicker-panel-render.js.map +1 -0
  14. package/dist/components/form/Form.js +69 -47
  15. package/dist/components/form/Form.js.map +1 -1
  16. package/dist/components/form/form-context.js +9 -0
  17. package/dist/components/form/form-context.js.map +1 -0
  18. package/dist/components/form.js +2 -0
  19. package/dist/components/form.js.map +1 -1
  20. package/dist/components/menu/Menu.js +27 -27
  21. package/dist/components/menu/Menu.js.map +1 -1
  22. package/dist/components/popover/Popover.js +1 -1
  23. package/dist/components/popover/Popover.js.map +1 -1
  24. package/dist/components/select/Select.js +235 -351
  25. package/dist/components/select/Select.js.map +1 -1
  26. package/dist/components/select/option-search.js +49 -0
  27. package/dist/components/select/option-search.js.map +1 -0
  28. package/dist/components/select/select-render.js +75 -0
  29. package/dist/components/select/select-render.js.map +1 -0
  30. package/dist/components/select/selection-strategy.js +151 -0
  31. package/dist/components/select/selection-strategy.js.map +1 -0
  32. package/dist/components/time-picker/TimePicker.js +1 -1
  33. package/dist/components/time-picker/TimePicker.js.map +1 -1
  34. package/dist/components/tooltip/Tooltip.js +16 -16
  35. package/dist/components/tooltip/Tooltip.js.map +1 -1
  36. package/dist/core/BaseElement.js +96 -77
  37. package/dist/core/BaseElement.js.map +1 -1
  38. package/dist/core/context.js +68 -0
  39. package/dist/core/context.js.map +1 -0
  40. package/dist/core/controller.js +2 -0
  41. package/dist/core/controller.js.map +1 -0
  42. package/dist/core/public.js +35 -30
  43. package/dist/core/public.js.map +1 -1
  44. package/dist/core.js +95 -90
  45. package/dist/core.js.map +1 -1
  46. package/dist/doc/doc-template-editor-core.js +12 -11
  47. package/dist/doc/doc-template-editor-core.js.map +1 -1
  48. package/dist/doc/doc-template-editor-panel.css.js +202 -0
  49. package/dist/doc/doc-template-editor-panel.css.js.map +1 -0
  50. package/dist/doc/doc-template-editor.css.js +1 -200
  51. package/dist/doc/doc-template-editor.css.js.map +1 -1
  52. package/dist/flow/Flow.js +104 -195
  53. package/dist/flow/Flow.js.map +1 -1
  54. package/dist/flow/flow-keyboard-controller.js +101 -0
  55. package/dist/flow/flow-keyboard-controller.js.map +1 -0
  56. package/dist/primitives/overlay/floatingPanel.js +6 -2
  57. package/dist/primitives/overlay/floatingPanel.js.map +1 -1
  58. package/dist/report/chart/Chart.js +271 -761
  59. package/dist/report/chart/Chart.js.map +1 -1
  60. package/dist/report/chart/chart-brush-controller.js +187 -0
  61. package/dist/report/chart/chart-brush-controller.js.map +1 -0
  62. package/dist/report/chart/chart-layout-pipeline.js +158 -0
  63. package/dist/report/chart/chart-layout-pipeline.js.map +1 -0
  64. package/dist/report/chart/chart-zoom.js +79 -0
  65. package/dist/report/chart/chart-zoom.js.map +1 -0
  66. package/dist/report/chart/geometry/build.js +41 -26
  67. package/dist/report/chart/geometry/build.js.map +1 -1
  68. package/dist/report/chart/geometry/extra-flow-dist.js +283 -0
  69. package/dist/report/chart/geometry/extra-flow-dist.js.map +1 -0
  70. package/dist/report/chart/geometry/extra-radial-grid.js +280 -0
  71. package/dist/report/chart/geometry/extra-radial-grid.js.map +1 -0
  72. package/dist/report/chart/geometry/extra-shared.js +36 -0
  73. package/dist/report/chart/geometry/extra-shared.js.map +1 -0
  74. package/dist/report/chart/geometry/extra.js +20 -583
  75. package/dist/report/chart/geometry/extra.js.map +1 -1
  76. package/dist/report/chart/geometry/registry.js +20 -0
  77. package/dist/report/chart/geometry/registry.js.map +1 -0
  78. package/dist/report/chart.js +12 -6
  79. package/dist/report/chart.js.map +1 -1
  80. package/dist/report/gantt/Gantt.js +199 -308
  81. package/dist/report/gantt/Gantt.js.map +1 -1
  82. package/dist/report/gantt/gantt-bars.css.js +247 -0
  83. package/dist/report/gantt/gantt-bars.css.js.map +1 -0
  84. package/dist/report/gantt/gantt-edit-controller.js +94 -0
  85. package/dist/report/gantt/gantt-edit-controller.js.map +1 -0
  86. package/dist/report/gantt/gantt.css.js +0 -272
  87. package/dist/report/gantt/gantt.css.js.map +1 -1
  88. package/dist/report/table/ReportTable.js +336 -493
  89. package/dist/report/table/ReportTable.js.map +1 -1
  90. package/dist/report/table/report-table-config.css.js +172 -0
  91. package/dist/report/table/report-table-config.css.js.map +1 -0
  92. package/dist/report/table/report-table-types.js.map +1 -1
  93. package/dist/report/table/report-table.css.js +0 -176
  94. package/dist/report/table/report-table.css.js.map +1 -1
  95. package/dist/report/table/table-cell-registry.js +29 -0
  96. package/dist/report/table/table-cell-registry.js.map +1 -0
  97. package/dist/report/table/table-keyboard-controller.js +96 -0
  98. package/dist/report/table/table-keyboard-controller.js.map +1 -0
  99. package/dist/report/table/table-pipeline.js +36 -0
  100. package/dist/report/table/table-pipeline.js.map +1 -0
  101. package/dist/report/table/table-render.js +97 -96
  102. package/dist/report/table/table-render.js.map +1 -1
  103. package/dist/report/table/table-scroll-controller.js +33 -0
  104. package/dist/report/table/table-scroll-controller.js.map +1 -0
  105. package/dist/report/table.js +7 -2
  106. package/dist/report/table.js.map +1 -1
  107. package/dist/report.js +39 -28
  108. package/dist/report.js.map +1 -1
  109. package/dist/types/components/datepicker/Datepicker.d.ts +1 -109
  110. package/dist/types/components/datepicker/datepicker-keyboard.d.ts +21 -0
  111. package/dist/types/components/datepicker/datepicker-panel-render.d.ts +25 -0
  112. package/dist/types/components/form/Form.d.ts +7 -2
  113. package/dist/types/components/form/form-context.d.ts +11 -0
  114. package/dist/types/components/form/index.d.ts +1 -1
  115. package/dist/types/components/select/Select.d.ts +7 -110
  116. package/dist/types/components/select/option-search.d.ts +38 -0
  117. package/dist/types/components/select/select-render.d.ts +39 -0
  118. package/dist/types/components/select/selection-strategy.d.ts +86 -0
  119. package/dist/types/core/BaseElement.d.ts +7 -1
  120. package/dist/types/core/context.d.ts +66 -0
  121. package/dist/types/core/controller.d.ts +22 -0
  122. package/dist/types/core/public.d.ts +2 -0
  123. package/dist/types/flow/Flow.d.ts +3 -76
  124. package/dist/types/flow/flow-keyboard-controller.d.ts +35 -0
  125. package/dist/types/primitives/overlay/floatingPanel.d.ts +2 -0
  126. package/dist/types/report/chart/Chart.d.ts +2 -245
  127. package/dist/types/report/chart/chart-brush-controller.d.ts +59 -0
  128. package/dist/types/report/chart/chart-layout-pipeline.d.ts +42 -0
  129. package/dist/types/report/chart/chart-zoom.d.ts +12 -0
  130. package/dist/types/report/chart/geometry/build.d.ts +2 -0
  131. package/dist/types/report/chart/geometry/extra-flow-dist.d.ts +6 -0
  132. package/dist/types/report/chart/geometry/extra-radial-grid.d.ts +6 -0
  133. package/dist/types/report/chart/geometry/extra-shared.d.ts +24 -0
  134. package/dist/types/report/chart/geometry/extra.d.ts +2 -34
  135. package/dist/types/report/chart/geometry/registry.d.ts +26 -0
  136. package/dist/types/report/chart/index.d.ts +1 -0
  137. package/dist/types/report/gantt/Gantt.d.ts +7 -97
  138. package/dist/types/report/gantt/gantt-edit-controller.d.ts +34 -0
  139. package/dist/types/report/table/ReportTable.d.ts +9 -180
  140. package/dist/types/report/table/index.d.ts +1 -0
  141. package/dist/types/report/table/report-table-types.d.ts +2 -0
  142. package/dist/types/report/table/table-cell-registry.d.ts +17 -0
  143. package/dist/types/report/table/table-keyboard-controller.d.ts +30 -0
  144. package/dist/types/report/table/table-pipeline.d.ts +33 -0
  145. package/dist/types/report/table/table-scroll-controller.d.ts +25 -0
  146. package/dist/z-agent-ui.js +35 -30
  147. package/dist/z-agent-ui.js.map +1 -1
  148. package/package.json +1 -1
  149. package/registry/component-manifest.json +39 -7
  150. package/src/components/context-menu/ContextMenu.ts +1 -1
  151. package/src/components/date-range/DateRange.ts +1 -1
  152. package/src/components/datepicker/Datepicker.ts +99 -417
  153. package/src/components/datepicker/datepicker-keyboard.ts +94 -0
  154. package/src/components/datepicker/datepicker-panel-render.ts +169 -0
  155. package/src/components/form/Form.ts +39 -11
  156. package/src/components/form/form-context.ts +11 -0
  157. package/src/components/form/index.ts +1 -1
  158. package/src/components/menu/Menu.ts +1 -1
  159. package/src/components/popover/Popover.ts +1 -1
  160. package/src/components/select/Select.ts +140 -525
  161. package/src/components/select/option-search.ts +114 -0
  162. package/src/components/select/select-render.ts +161 -0
  163. package/src/components/select/selection-strategy.ts +245 -0
  164. package/src/components/time-picker/TimePicker.ts +1 -1
  165. package/src/components/tooltip/Tooltip.ts +1 -1
@@ -1,51 +1,53 @@
1
1
  // <z-select> 下拉选择:searchable 带搜索、multiple 多选、clearable 清空,开、合、变更、搜索各发事件。
2
+ // [组合架构] 元素壳只保留属性契约与交互编排;浮层托管给 FloatingPanelController、
3
+ // 搜索/防抖/子节点观察托管给 OptionSearchController、单/多/暂存选择委托给 SelectionStrategy、
4
+ // HTML 投影委托给 select-render.ts。
2
5
  import { DROPDOWN_CSS } from "./dropdown-css.js";
3
- import { COPY, BaseElement, html, property, t, injectGlobalStyles, escapeHtml, escapeAttr, controlHeight, type ControlSize, defineElement } from "../../core/index.js";
6
+ import {
7
+ BaseElement,
8
+ html,
9
+ property,
10
+ t,
11
+ injectGlobalStyles,
12
+ controlHeight,
13
+ type ControlSize,
14
+ defineElement,
15
+ } from "../../core/index.js";
4
16
  import { FloatingPanelController, FocusTrap, listIntent, resolveIndex } from "../../primitives/index.js";
5
17
  import type { ZOption } from "../option/Option.js";
18
+ import {
19
+ OptionSearchController,
20
+ type RemoteSearchMethod,
21
+ type ZSelectOptionSpec,
22
+ type ZSelectSearchMode,
23
+ } from "./option-search.js";
24
+ import {
25
+ resolveSelectionStrategy,
26
+ type SelectionStrategy,
27
+ } from "./selection-strategy.js";
28
+ import {
29
+ buildSelectDropdownShell,
30
+ buildSelectOptionsHTML,
31
+ renderSelectTrigger,
32
+ } from "./select-render.js";
6
33
  import selectCSS from "./select.css?raw";
7
34
 
8
- export interface ZSelectOptionSpec {
9
- value: string;
10
- label: string;
11
- disabled?: boolean;
12
- }
13
-
14
- export type ZSelectSearchMode = "frontend" | "backend";
35
+ export type { ZSelectOptionSpec, ZSelectSearchMode } from "./option-search.js";
15
36
 
16
- const REMOTE_SEARCH_DELAY = 300;
37
+ const DEFAULT_PLACEHOLDER = "Select...";
38
+ let SELECT_SEQ = 0;
17
39
 
18
40
  function injectDropdownStyles(): void {
19
41
  injectGlobalStyles("z-select", DROPDOWN_CSS);
20
42
  }
21
43
 
22
- /**
23
- * 组件默认占位文案。
24
- *
25
- * [WHY 单独提出来] 多选的空态要在三层里挑文案:作者写的 → 空值选项的文案 → 这个默认值。
26
- * 而 `this.placeholder` **永远有值**(默认就是它),直接判真假区分不出「作者写了」和
27
- * 「用了默认」—— 判不出来就只能让空值选项永远被英文 "Select..." 盖掉。
28
- */
29
- const DEFAULT_PLACEHOLDER = "Select...";
30
-
31
- /** 实例 id 前缀的自增源(同页多个下拉时 activedescendant 不能互相指错)。 */
32
- let SELECT_SEQ = 0;
33
-
34
44
  export class ZSelect extends BaseElement {
35
45
  static styles = selectCSS;
36
46
 
37
- // 控件高度档位(xs 24 / sm 28 / md 32 / lg 36,随密度缩放)。默认 sm = 既有高度。
38
47
  @property({ type: String }) size: ControlSize = "sm";
39
-
40
- protected willUpdate(): void {
41
- // 见 core/controlSize.ts 的边界说明:size 只改高度,密度改的是令牌本身,局部永远赢。
42
- this.style.setProperty("--_h", controlHeight(this.size));
43
- }
44
48
  @property({ type: String }) value = "";
45
49
  @property({ type: String }) placeholder = DEFAULT_PLACEHOLDER;
46
50
  @property({ type: Boolean }) disabled = false;
47
- // [WHY] 合法/非法是语义,由 z-form-item 写入;控件负责落到自己的可聚焦件(trigger)上。
48
- // 挂在 host 上读屏读不到 —— host 没有角色,也没有 tabindex。
49
51
  @property({ type: Boolean }) invalid = false;
50
52
  @property({ type: Boolean }) open = false;
51
53
  @property({ type: String }) name = "";
@@ -53,245 +55,86 @@ export class ZSelect extends BaseElement {
53
55
  @property({ type: String, attribute: "search-mode" }) searchMode: ZSelectSearchMode = "frontend";
54
56
  @property({ type: String, attribute: "search-placeholder" }) searchPlaceholder = "Search...";
55
57
  @property({ type: Boolean }) loading = false;
56
- // 多选:value 仍是逗号串(空串 = 未选);事件 detail 带 { values, value }。
57
- // [WHY 不改 value 类型] 宿主普遍按字符串绑(表单序列化 / URL 参数);改数组会让所有
58
- // 既有调用点类型改一遍。逗号串 + values 附件是纯增量。
59
58
  @property({ type: Boolean }) multiple = false;
60
- /**
61
- * 有值时是否显示整框「清除」钮。
62
- *
63
- * [WHY 缺省 false] 这是纯增量能力:存量调用方(表单里的普通下拉)外观一个字都不变。
64
- * 筛选场景由渲染层显式打开 —— 那里的「能选不能退」是真问题,下拉本体的默认值不该跟着变。
65
- */
66
59
  @property({ type: Boolean }) clearable = false;
67
- /**
68
- * 多选「先勾选、点确定才提交」。
69
- *
70
- * [WHY 需要这个开关 2026-11-02] 筛选栏里的多选是**取数触发器**:每勾一项就发一次
71
- * `z-change`,宿主立刻发一次查询并整页重渲染。勾 5 项 = 5 次查询,中途还会看到半成品
72
- * 结果(只筛了第一项)—— 而且大表查询本身要几百毫秒,用户勾到第三项时第一项的响应才回来,
73
- * 界面在几批数据之间来回跳。筛选场景要的是「选完再查」,这也是主流后台(Ant Design Pro /
74
- * Fusion / SAP Fiori)的形态:下拉里勾,底部「重置 / 确定」。
75
- *
76
- * [WHY 做成 opt-in 而不是改多选的默认行为] 表单里的多选没有「提交」这一步,勾了就该有值。
77
- * 若默认暂存,表单会**静默丢勾选**(用户以为选了,提交却是空)—— 那是比多几次查询严重得多
78
- * 的问题。所以只在筛选渲染层显式打开(`render.ts` 的 multi 控件)。
79
- *
80
- * 关闭面板(点外部 / Esc / Tab)= 丢弃草稿、不发事件,即「没点确定就不生效」。
81
- * 代价是勾完忘了点确定会白选一次,用面板底部的「已选 N 项」提示。
82
- */
83
60
  @property({ type: Boolean, attribute: "commit-on-confirm" }) commitOnConfirm = false;
84
- /**
85
- * 多选标签最多展开几个,其余折叠成 `+N`;`0` = 不折叠。
86
- *
87
- * [WHY 缺省是 2 而不是 3] 筛选栏一格定宽 168px(`--zpg-filter` 的窄档),三个中文标签
88
- * 会被压成单字(实测「原料」只剩「原」)。2 个标签 + `+N` 是这个宽度下的实际上限;
89
- * 宽容器要更多就显式写 `max-tags=`。
90
- */
91
61
  @property({ type: Number, attribute: "max-tags" }) maxTags = 2;
92
- // 后端搜索回调(property 而非 attribute):返回 OptionSpec[] 或 Promise<OptionSpec[]> 时自动重建 z-option
93
- remoteMethod: ((query: string) => void | ZSelectOptionSpec[] | Promise<ZSelectOptionSpec[]>) | null = null;
62
+ remoteMethod: RemoteSearchMethod | null = null;
94
63
 
95
- // [WHY] 浮层面板生命周期(创建/定位/外部关闭/隐藏动画)委托给公共控制器
96
- private _floating = new FloatingPanelController(this);
64
+ private _floating = this.addController(new FloatingPanelController(this));
65
+ private _search = this.addController(new OptionSearchController());
66
+ private _strategy: SelectionStrategy = resolveSelectionStrategy(false, false);
97
67
  private _focusTrap: FocusTrap | null = null;
98
68
  private _activeIndex = -1;
99
- private _query = "";
100
- /**
101
- * 暂存中的多选值(只在 `commit-on-confirm` 下非 null)。
102
- *
103
- * 与 `value` 分开是为了让「面板里勾了什么」与「控件对外是什么」互不干扰:
104
- * 勾选期间 `value` 一个字都不变(所以 trigger 上的标签、宿主的取数都不会动),
105
- * 只有点「确定」才把草稿一次性写成 `value` 并发一次 `z-change`。
106
- */
107
- /**
108
- * 本实例的 id 前缀。
109
- *
110
- * [WHY 需要它] 选项要有 id 才能被 `aria-activedescendant` 指到,而同一个页面里
111
- * 筛选行常常并排三个 `z-select` —— id 不带实例前缀就会互相指错,读屏念的是隔壁下拉的选项。
112
- */
113
69
  private _uid = `z-select-${++SELECT_SEQ}`;
114
- private _draft: string[] | null = null;
115
- private _searchTimer: number | null = null;
116
- private _optionsObserver: MutationObserver | null = null;
70
+
71
+ protected willUpdate(): void {
72
+ this.style.setProperty("--_h", controlHeight(this.size));
73
+ this._syncStrategy();
74
+ }
117
75
 
118
76
  render(): string {
119
- // [WHY] html() 不剥离 ? 前缀,`?disabled` 会渲染成字面量属性(潜伏 bug,2026-08-06 修复)
120
- // See: wiki/planning/TASKS/W4-datepicker/findings.md
121
- const selected = this._getSelectedOption();
122
- const values = this._selectedValues();
123
- // 多选的空态文案:**作者显式写的 placeholder 优先**,没写才退回空值选项的文案。
124
- // [WHY 顺序不能反] 渲染层总会塞一个 `value=""` 的「全部」项当全清入口,它的文案是
125
- // 通用词「全部」。若让它优先,脚本里 `placeholder="全部分类"` 永远不出现 ——
126
- // 同一个筛选行里文本框显示「物料名称」、下拉却显示「全部」,看起来像两个作者写的。
127
- const emptyLabel = this._optionByValue("")?.label ?? "";
128
- const filled = this.multiple ? values.length > 0 : !!selected;
129
-
130
- // 整框清除钮:只在「单选 + 有值 + clearable」时出现。
131
- // [WHY 多选不放这里] 168px 的筛选格里「标签× × 标签× × 整框×」三个叉挨在一起,
132
- // 点错就是把筛选整个清掉;而且它还挤掉了折叠的「+N」。多选的全清入口放在下拉里的
133
- // 「全部」项(点它 = 清空已选),那里空间不受限、也不会误触。
134
- const clear =
135
- this.clearable && filled && !this.disabled && !this.multiple
136
- ? `<span class="z-select__clear" part="clear" role="button" tabindex="-1" aria-label="${COPY.clear}">` +
137
- `<svg width="10" height="10" viewBox="0 0 10 10" fill="none" aria-hidden="true">` +
138
- `<path d="M2 2l6 6M8 2l-6 6" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg></span>`
139
- : "";
140
-
141
- // 多选走标签列表(每个标签自带 ×),单选仍是单行文案
142
- const body = this.multiple
143
- ? values.length
144
- ? `<span class="z-select__tags" part="value">${this._renderTags(values)}</span>`
145
- : `<span class="z-select__value z-select__placeholder" part="value">${escapeHtml(
146
- this._authoredPlaceholder() || emptyLabel || this.placeholder,
147
- )}</span>`
148
- : `<span class="z-select__value${selected ? "" : " z-select__placeholder"}" part="value">${escapeHtml(
149
- String(selected ? selected.label : this.placeholder),
150
- )}</span>`;
151
-
152
- // 单选整框放不下时悬停看全文;多选的完整清单挂在标签的 title 上(见 _renderTags)
153
- // [WHY] 选项文案来自数据源,进属性必须 escapeAttr —— `"` 未转义可闭合 title 注入新属性
154
- const titleAttr = !this.multiple && selected ? ` title="${escapeAttr(String(selected.label))}"` : "";
155
-
156
- return html`
157
- <button
158
- type="button"
159
- class="z-select__trigger ${this.open ? "z-select__trigger--open" : ""}${this.multiple ? " z-select__trigger--multi" : ""}"
160
- ${this.disabled ? "disabled" : ""}
161
- aria-expanded="${this.open ? "true" : "false"}"
162
- aria-haspopup="listbox"
163
- ${this.invalid ? 'aria-invalid="true"' : ""}
164
- ${titleAttr}
165
- part="trigger"
166
- data-focus-key="trigger"
167
- >
168
- ${body}${clear}
169
- <span class="z-select__chevron ${this.open ? "z-select__chevron--open" : ""}" part="chevron" aria-hidden="true">
170
- <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
171
- <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
172
- </svg>
173
- </span>
174
- </button>
175
- `;
77
+ const strategy = this._syncStrategy();
78
+ const selectedOption = this._getSelectedOption();
79
+ return renderSelectTrigger({
80
+ open: this.open,
81
+ disabled: this.disabled,
82
+ invalid: this.invalid,
83
+ multiple: this.multiple,
84
+ clearable: this.clearable,
85
+ maxTags: this.maxTags,
86
+ placeholder: this.placeholder,
87
+ authoredPlaceholder: this._authoredPlaceholder(),
88
+ emptyLabel: this._optionByValue("")?.label ?? "",
89
+ selectedOption,
90
+ selectedValues: strategy.getCommittedValues(this.value),
91
+ labelOf: (v) => this._optionByValue(v)?.label ?? v,
92
+ });
176
93
  }
177
94
 
178
95
  connectedCallback(): void {
179
96
  super.connectedCallback();
180
- this.addEventListener("click", this._onTriggerClick);
181
- this.addEventListener("keydown", this._onTriggerKey);
97
+ this.listen(this, "click", this._onTriggerClick);
98
+ this.listen(this, "keydown", this._onTriggerKey);
182
99
  }
183
100
 
184
101
  disconnectedCallback(): void {
185
102
  this._closeDropdown();
186
- this.removeEventListener("click", this._onTriggerClick);
187
- this.removeEventListener("keydown", this._onTriggerKey);
188
103
  super.disconnectedCallback();
189
104
  }
190
105
 
191
106
  updated(): void {
192
- // [WHY] loading 可能由外部直接赋值(事件流后端搜索),需同步 light-DOM 下拉里的加载行
193
- // See: wiki/planning/TASKS/2026-08-10-select-search/task_plan.md
194
107
  if (this._floating.panel) this._renderOptionList();
195
108
  }
196
109
 
110
+ private _syncStrategy(): SelectionStrategy {
111
+ this._strategy = resolveSelectionStrategy(this.multiple, this.commitOnConfirm, this._strategy);
112
+ return this._strategy;
113
+ }
114
+
197
115
  private _getOptions(): ZOption[] {
198
116
  return Array.from(this.querySelectorAll<ZOption>("z-option"));
199
117
  }
200
118
 
201
119
  private _getSelectedOption(): ZOption | undefined {
202
- // [WHY 空值不算「已选中」] 筛选控件由渲染层额外插一个 `value=""` 的空值项(点它 = 清空)。
203
- // 若把这一项算成已选中,控件就永远显示它的文案(页面文案里是「—」):
204
- // 作者写的 `placeholder="全部分类"` 一辈子不出现,空状态下还挂着一个清除叉
205
- // —— 用户看到「—」既不知道是什么,也读不出「还没筛」。
206
- // 表单里的普通下拉本来就不写 `value=""` 的选项,缺省值是空串时更该显示 placeholder。
207
120
  if (!this.value) return undefined;
208
- return this._getOptions().find(o => o.value === this.value && !o.disabled);
209
- }
210
-
211
- /** 多选当前值。非多选返回 [](多选分支不参与单选逻辑)。 */
212
- private _selectedValues(): string[] {
213
- if (!this.multiple || !this.value) return [];
214
- return this.value
215
- .split(",")
216
- .map((s) => s.trim())
217
- .filter(Boolean);
218
- }
219
-
220
- /** 是否处于「暂存 + 确认」模式(只有多选才有意义)。 */
221
- private _staging(): boolean {
222
- return this.multiple && this.commitOnConfirm;
223
- }
224
-
225
- /**
226
- * 面板里该显示成「已勾选」的一组值。
227
- *
228
- * 暂存模式下取草稿、否则取已提交值 —— 渲染勾选态与计数都走这一个入口,
229
- * 免得某一处忘了切档(症状是「勾了看不到勾」或「没确定却已经显示为选中」)。
230
- */
231
- private _draftValues(): string[] {
232
- return this._draft ?? this._selectedValues();
233
- }
234
-
235
- /**
236
- * 多选标签列表:每个已选值一个标签,标签自带 ×。
237
- *
238
- * [WHY 从「已选 N 项」改成标签] 折叠成计数之后,取消某一项只能重新打开下拉、在长列表里
239
- * 找回那一行再点一次 —— 「当前筛了什么」和「怎么去掉它」被拆到两个坐标上。标签把它们合回一处。
240
- * 超过 `maxTags` 折叠成 `+N`:筛选栏一格约 168px,三个中文标签就撑破。
241
- *
242
- * 选项文案来自数据源,进属性一律 `escapeAttr` / `escapeHtml`(`"` 不转义可闭合 title 注入)。
243
- */
244
- private _renderTags(values: string[]): string {
245
- // maxTags<=0 时 limit = 全量,slice 全取,不需要额外分支
246
- const limit = this.maxTags > 0 ? this.maxTags : values.length;
247
- const shown = values.slice(0, limit);
248
- const rest = values.length - shown.length;
249
- const tags = shown.map((v) => {
250
- const text = this._optionByValue(v)?.label ?? v;
251
- // [WHY × 用 span 不用 button] trigger 本身就是 <button>,内层再放 <button> 是非法嵌套,
252
- // 浏览器解析时会把内层拆到外面 —— 表现为标签与叉错位、甚至只剩一个孤立的叉。
253
- return (
254
- `<span class="z-select__tag" title="${escapeAttr(text)}">` +
255
- `<span class="z-select__tag-label">${escapeHtml(text)}</span>` +
256
- `<span class="z-select__tag-x" role="button" tabindex="-1" data-value="${escapeAttr(v)}"` +
257
- ` aria-label="${escapeAttr(t("removeItem", { label: text }))}">` +
258
- `<svg width="8" height="8" viewBox="0 0 8 8" fill="none" aria-hidden="true">` +
259
- `<path d="M1.6 1.6l4.8 4.8M6.4 1.6L1.6 6.4" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>` +
260
- `</span></span>`
261
- );
262
- });
263
- if (rest > 0) {
264
- // 折叠起来的那几项必须在悬停里看得见:给一个「+2」却不说 + 的是谁,
265
- // 用户只能靠再打开下拉去数
266
- const hidden = values.slice(limit).map((v) => this._optionByValue(v)?.label ?? v);
267
- tags.push(
268
- `<span class="z-select__tag z-select__tag--more" title="${escapeAttr(hidden.join("、"))}">+${rest}</span>`,
269
- );
270
- }
271
- return tags.join("");
121
+ return this._getOptions().find((o) => o.value === this.value && !o.disabled);
272
122
  }
273
123
 
274
124
  private _optionByValue(v: string): ZOption | undefined {
275
125
  return this._getOptions().find((o) => o.value === v);
276
126
  }
277
127
 
278
- /** 作者显式写的占位文案(没写 = 空串,与组件默认值区分开)。 */
279
128
  private _authoredPlaceholder(): string {
280
129
  return this.placeholder === DEFAULT_PLACEHOLDER ? "" : this.placeholder;
281
130
  }
282
131
 
283
132
  private _getFilteredOptions(): ZOption[] {
284
- const options = this._getOptions();
285
- if (!this.searchable || !this._query) return options;
286
- const q = this._query.toLowerCase();
287
- return options.filter(o => o.label.toLowerCase().includes(q) || o.value.toLowerCase().includes(q));
133
+ return this._search.filter(this._getOptions(), this.searchable);
288
134
  }
289
135
 
290
136
  private _onTriggerClick = (e: Event): void => {
291
137
  if (this.disabled) return;
292
- // [WHY 先判标签上的 × / 清除钮] click 监听取在 host 上,点「×」也会冒泡到这里。
293
- // 直接 toggle 的后果是一次点击既删了值、又把下拉弹开(或反过来把已经开着的关掉)。
294
- // composedPath 而不是 target:标签在 shadow 内,而宿主可能在别的 shadow 里包一层。
295
138
  const origin = (e.composedPath?.()[0] ?? e.target) as HTMLElement | null;
296
139
  const tagX = origin?.closest?.(".z-select__tag-x") as HTMLElement | null;
297
140
  if (tagX) {
@@ -305,72 +148,40 @@ export class ZSelect extends BaseElement {
305
148
  this.open ? this._closeDropdown() : this._openDropdown();
306
149
  };
307
150
 
308
- /**
309
- * 多选去掉一项(标签 ×)。
310
- *
311
- * 值与 `_selectOption` 同一条出口(逗号串 + `z-change`),否则「从标签删」和
312
- * 「从下拉取消勾选」会走出两种状态。面板开着时要同步勾选态:标签没了、下拉里还打着勾,
313
- * 用户会以为没删掉。
314
- */
315
151
  private _removeValue(value: string): void {
316
- const next = this._selectedValues().filter((v) => v !== value);
317
- if (next.length === this._selectedValues().length) return;
318
- this.value = next.join(",");
319
- // 标签 × 是**对已提交值的直接操作**(不经过确定),草稿跟着走一遍,
320
- // 否则面板里那一项还打着勾,而 trigger 上已经没有它了。
321
- if (this._staging()) this._draft = next.slice();
152
+ const res = this._syncStrategy().removeValue(value, this.value);
153
+ if (!res) return;
154
+ this.value = res.nextValue;
322
155
  if (this.open) this._renderOptionList();
323
- this.emit("z-change", { values: next.slice(), value: this.value });
156
+ this.emit("z-change", res.changeDetail);
324
157
  }
325
158
 
326
- /**
327
- * 整框清除。空串 = 不限,与点「value='' 的空值选项」同义。
328
- *
329
- * [WHY 也发 `z-change` 而不是单独的 `z-clear`] 消费方(PageView)已经按「值变化」处理
330
- * 取数与重渲染;再造一个事件就多一条必须被同时监听的路径,漏一个就是「清空后不重新取数」。
331
- */
332
159
  private _clearValue(): void {
333
- if (!this.value) return;
334
- this.value = "";
335
- if (this._staging()) this._draft = [];
160
+ const res = this._syncStrategy().clear(this.value);
161
+ if (!res) return;
162
+ this.value = res.nextValue;
336
163
  if (this.open) this._renderOptionList();
337
- this.emit("z-change", this.multiple ? { values: [], value: "" } : { value: "" });
164
+ this.emit("z-change", res.changeDetail);
338
165
  }
339
166
 
340
167
  private _onTriggerKey = (e: Event): void => {
341
168
  const ke = e as KeyboardEvent;
342
169
  if (ke.key === "ArrowDown" || ke.key === "ArrowUp") {
343
170
  e.preventDefault();
344
- if (!this.open) {
345
- this._openDropdown();
346
- } else if (this._floating.panel) {
347
- // [WHY] 打开状态下把方向键委托给下拉,否则焦点停留在 trigger 时键盘导航无响应
348
- this._onDropdownKey(ke as Event);
349
- }
171
+ if (!this.open) this._openDropdown();
172
+ else if (this._floating.panel) this._onDropdownKey(ke as Event);
350
173
  } else if (ke.key === "Enter" && this.open) {
351
174
  e.preventDefault();
352
175
  this._onDropdownKey(ke as Event);
353
176
  } else if (ke.key === "Escape") {
354
- // [WHY 拦住冒泡 2026-11-05] Esc 的语义是「逐层退出」:下拉开着时这一下只该收起下拉。
355
- // 不拦的话事件会继续冒到 window,外层(页面编辑器的 Esc = 回到上一级)也执行一遍 ——
356
- // 表现是「下拉收起了,同时选中的控件被取消选中、整块属性面板换成上一层的」。
357
- // See: wiki/bugs/20261105-bind-field-select-blur.md
358
177
  e.stopPropagation();
359
178
  this._closeDropdown();
360
179
  } else if (ke.key === "Delete" && !this.open) {
361
- // [WHY 需要这条] 整框清除钮是 `tabindex="-1"` 的(trigger 本身已经是停靠点,
362
- // 再塞一个进去,用户想 Tab 过这个筛选格要按两次)。代价是**键盘用户没有清空路径** ——
363
- // 下拉的值不是能选中删掉的文本。`Delete` 在原生多选 select 与各类选择控件里
364
- // 就是「删掉这个值」。
365
180
  if (this.multiple || !this.clearable || !this.value) return;
366
181
  e.preventDefault();
367
182
  this._clearValue();
368
183
  } else if (ke.key === "Backspace" && this.multiple && !this.open) {
369
- // 多选:退掉最后一个标签。标签上的 × 同样是 `tabindex="-1"`(一个标签一个停靠点
370
- // 太贵),而 `Backspace` 删末项是标签输入框的通行约定(邮件收件人、GitHub 标签)。
371
- // [WHY 取值的末项而不是「最后一个可见标签」] 顺序以值为准;`maxTags` 折叠时
372
- // 反馈是 `+N` 少一,虽然弱但方向正确 —— 取可见项的话折叠掉的那几个永远删不掉。
373
- const values = this._selectedValues();
184
+ const values = this._syncStrategy().getCommittedValues(this.value);
374
185
  if (!values.length) return;
375
186
  e.preventDefault();
376
187
  this._removeValue(values[values.length - 1]);
@@ -379,65 +190,35 @@ export class ZSelect extends BaseElement {
379
190
 
380
191
  private _openDropdown(): void {
381
192
  if (this.open) return;
193
+ const strategy = this._syncStrategy();
382
194
 
383
195
  injectDropdownStyles();
384
- this._query = "";
385
- this._clearSearchTimer();
196
+ this._search.reset();
386
197
  this.loading = false;
387
198
 
388
- // Position relative to trigger
389
- // [WHY] anchor 必须用 getter:open=true 触发 BaseElement 重渲染替换 shadow 内的 trigger,
390
- // 持旧引用会让滚动时 _update 读到脱离元素的全 0 矩形,下拉跳到视口左上角(2026-09-10)
391
- // See: wiki/bugs/bug-20260910-select-dropdown-scroll-anchor.md
392
199
  const trigger = this.shadowRoot!.querySelector(".z-select__trigger") as HTMLElement;
393
200
  const dd = this._floating.open(
394
201
  {
395
202
  panelClass: "z-select__dropdown",
396
203
  hidingClass: "z-select__dropdown--hiding",
397
204
  part: "dropdown",
398
- // [WHY 不在这层给 listbox] 面板里本来就有一个 `.z-select__options[role=listbox]`,
399
- // 两层都标 listbox 会得到「listbox 套 listbox」,读屏进去要报两次。
400
205
  role: null,
401
206
  tabIndex: false,
402
207
  anchor: () => this.shadowRoot!.querySelector<HTMLElement>(".z-select__trigger"),
403
208
  onOutsideClose: () => this._closeDropdown(),
404
209
  },
405
210
  (panel) => {
406
- // [WHY input 才是 combobox、trigger 不是] 可搜索模式下焦点在面板里的 input 上,
407
- // 而它才是「用户往里打字、列表跟着过滤」的那个东西。combobox 角色必须落在**持有
408
- // 焦点**的元素上,否则它的 aria-expanded / aria-activedescendant 全是空转。
409
- // 同时 input 在 body 这边、选项也在 body 这边 —— 同一棵树,IDREF 能解析(这是
410
- // 非搜索模式做不到的,见 _updateActive 的说明)。
411
- const searchHTML = this.searchable
412
- ? html`<input type="text" class="z-select__search" part="search" role="combobox" aria-autocomplete="list" aria-expanded="true" aria-controls="${this._uid}-listbox" placeholder="${escapeAttr(this.searchPlaceholder)}" aria-label="${escapeAttr(this.searchPlaceholder)}" autocomplete="off" />`
413
- : "";
414
- // 暂存模式的底部操作条:左侧计数(唯一能看出「已勾几项、还没提交」的地方),
415
- // 右侧「清空 / 确定」。放在 `.z-select__options` **外面**:那个容器每次勾选都整体
416
- // 重写 innerHTML,放在里面会被一起冲掉。
417
- const footerHTML = this._staging()
418
- ? `<div class="z-select__footer" part="footer">` +
419
- `<span class="z-select__count" part="count"></span>` +
420
- `<span class="z-select__footer-actions">` +
421
- `<button type="button" class="z-select__btn" data-act="reset">${escapeHtml(t("clearAll"))}</button>` +
422
- `<button type="button" class="z-select__btn z-select__btn--primary" data-act="confirm">${escapeHtml(t("confirm"))}</button>` +
423
- `</span></div>`
424
- : "";
425
- // listbox 自身 `tabindex="-1"`:非搜索模式下焦点要落在它身上(见 _updateActive)。
426
- // -1 而不是 0 —— 它不该出现在 Tab 序列里,展开才进来、关闭就回触发器。
427
- //
428
- // [WHY aria-label 要条件写] 焦点进列表后读屏先念「列表框,<名字>」。没名字时它只念
429
- // 「列表框」,用户不知道这是哪个字段的列表(筛选行里常并排三个)。名字取占位符
430
- // ——那是作者对「这里选什么」唯一的表述。空值不写:`aria-label=""` 在 ARIA 里是
431
- // 一个空名字,比没有更糟,而且 a11y 守卫会把空 aria 值判红。
432
- const listName = this._authoredPlaceholder() || this.placeholder;
433
- const listLabel = listName ? ` aria-label="${escapeAttr(listName)}"` : "";
434
- panel.innerHTML = `${searchHTML}<div class="z-select__options" role="listbox" id="${this._uid}-listbox" tabindex="-1"${listLabel}></div>${footerHTML}`;
211
+ panel.innerHTML = buildSelectDropdownShell({
212
+ uid: this._uid,
213
+ searchable: this.searchable,
214
+ searchPlaceholder: this.searchPlaceholder,
215
+ staging: strategy.isStaging,
216
+ listName: this._authoredPlaceholder() || this.placeholder,
217
+ });
435
218
  },
436
219
  );
437
220
 
438
- // Click handler on options
439
221
  dd.addEventListener("click", (e) => {
440
- // 底部按钮优先:它是 `.z-select__option` 的兄弟节点,混进下面的分支会被当成选项
441
222
  const act = (e.target as HTMLElement).closest<HTMLElement>("[data-act]");
442
223
  if (act) {
443
224
  if (act.dataset.act === "confirm") this._commitDraft();
@@ -452,54 +233,31 @@ export class ZSelect extends BaseElement {
452
233
  }
453
234
  });
454
235
 
455
- // Hover tracking for keyboard nav
456
236
  dd.addEventListener("mouseover", (e) => {
457
237
  const opt = (e.target as HTMLElement).closest<HTMLElement>(".z-select__option");
458
- if (opt) {
459
- this._setActiveByElement(opt);
460
- }
238
+ if (opt) this._setActiveByElement(opt);
461
239
  });
462
240
 
463
241
  dd.querySelector(".z-select__search")?.addEventListener("input", this._onSearchInput);
464
242
 
465
- // Sync width
466
243
  const triggerRect = trigger.getBoundingClientRect();
467
- // 暂存模式的下拉里多了「已选 N 项 + 清空 + 确定」一行,按 trigger 宽度铺开会把三个
468
- // 元素挤成两行(筛选栏一格只有 168px)—— 给一个下限,宽容器不受影响。
469
- dd.style.minWidth = `${this._staging() ? Math.max(triggerRect.width, 240) : triggerRect.width}px`;
244
+ dd.style.minWidth = `${strategy.isStaging ? Math.max(triggerRect.width, 240) : triggerRect.width}px`;
470
245
 
471
- // Focus trap
472
246
  this._focusTrap = new FocusTrap({ container: dd });
473
247
 
474
248
  this.open = true;
475
- // 草稿从**已提交值**起步:上一次没点确定就关掉的那批勾选必须丢掉,
476
- // 否则「取消」会变成「悄悄保留」,下次打开看到一堆没生效的勾。
477
- if (this._staging()) this._draft = this._selectedValues();
478
- this._activeIndex = this._getOptions().findIndex(o => o.value === this.value && !o.disabled);
249
+ strategy.onOpen(this.value);
250
+ this._activeIndex = this._getOptions().findIndex((o) => o.value === this.value && !o.disabled);
479
251
  this._renderOptionList();
480
- // [WHY 填完选项必须重定位 2026-10-30] 面板是在**空列表**状态下建好并定位的,上面的
481
- // `_renderOptionList()` 之后高度才变成真实值(4 项 = 130px)。不重定位就沿用按 0 高度
482
- // 算出的坐标 —— 锚点在视口下半部时底边直接越出视口(实测 top 890 / 视口 900 / 高 130)。
483
- // `FloatingPosition` 的 ResizeObserver 也会补一次,但那是下一帧:这一行是消除首帧错位。
484
252
  this._floating.reposition();
485
- this._observeOptions();
253
+ this._search.observeHost(this, () => {
254
+ if (this.open) this._renderOptionList();
255
+ });
486
256
 
487
- // Keyboard nav
488
257
  dd.addEventListener("keydown", this._onDropdownKey);
489
258
 
490
- // [WHY 非搜索模式要把焦点搬进列表] 这是 `aria-activedescendant` 能不能生效的**唯一**
491
- // 前提:它是个 IDREF,只在**同一棵树**里解析。触发器在 `z-select` 的 shadow 里,
492
- // 而面板挂在 `document.body` —— 把 activedescendant 写在触发器上,DOM 里查得到、
493
- // AX 树里根本不出现(2026-11-15 用 CDP 无障碍树实测),读屏全程不吭声。
494
- //
495
- // 所以这里改走 ARIA 的另一种标准用法:触发器是「按钮 + aria-haspopup=listbox」,
496
- // 展开后焦点进入 listbox,由 listbox 自己承载 activedescendant(同树 ⇒ 生效)。
497
- // 可搜索模式不用搬 —— 它的焦点本来就在面板里的 input 上(FocusTrap 已送进去),
498
- // 那个 input 才是 combobox,同样同树。
499
259
  if (!this.searchable) {
500
260
  this._floating.panel?.querySelector<HTMLElement>(".z-select__options")?.focus();
501
- // 焦点进去之后补写一次:浏览器的读屏适配层在 focus 那一刻读取该属性,
502
- // 早于这次 focus 写的值在某些实现里不会重新播报。
503
261
  this._updateActive();
504
262
  }
505
263
 
@@ -509,23 +267,17 @@ export class ZSelect extends BaseElement {
509
267
  private _closeDropdown(): void {
510
268
  if (!this.open) return;
511
269
 
512
- this._clearSearchTimer();
513
- this._optionsObserver?.disconnect();
514
- this._optionsObserver = null;
515
-
270
+ this._search.clearTimer();
271
+ this._search.stopObserving();
516
272
  this._focusTrap?.destroy();
517
273
  this._focusTrap = null;
518
274
  this._floating.panel?.removeEventListener("keydown", this._onDropdownKey);
519
- // [WHY] 控制器负责定位销毁/外部监听解绑/hiding 动画与面板移除
520
275
  this._floating.close();
521
276
 
522
277
  this.open = false;
523
278
  this._activeIndex = -1;
524
- // 关闭 = 丢弃草稿(未点「确定」的勾选不生效)。放在这里而不是各调用点:
525
- // 点外部 / Esc / Tab / 提交后关闭都走同一条出口,漏一处就会残留上一轮的勾选。
526
- this._draft = null;
279
+ this._strategy.onClose();
527
280
 
528
- // Focus back to trigger
529
281
  const trigger = this.shadowRoot!.querySelector(".z-select__trigger") as HTMLElement;
530
282
  trigger?.focus();
531
283
 
@@ -533,78 +285,33 @@ export class ZSelect extends BaseElement {
533
285
  }
534
286
 
535
287
  private _selectOption(value: string): void {
536
- // [暂存模式] 勾选只改草稿:`value` 不动、不发事件,宿主因此不会取数。
537
- // 这是「选完再查」的全部实现 —— 每次点击都发 `z-change` 的话,勾 5 项就是 5 次查询,
538
- // 而用户此时连筛选条件都还没输完。
539
- if (this._staging()) {
540
- const draft = this._draft ?? this._selectedValues();
541
- if (value === "") {
542
- draft.length = 0;
543
- } else {
544
- const i = draft.indexOf(value);
545
- if (i >= 0) draft.splice(i, 1);
546
- else draft.push(value);
547
- }
548
- this._draft = draft;
549
- this._renderOptionList();
550
- return;
551
- }
552
- // [多选] 点选项 = 切换勾选,面板不关;点 value="" 的空值选项 = 清空全部。
553
- // [WHY 不关面板] 多选的典型操作是连续勾几项;关一次就要重开一次。
554
- if (this.multiple) {
555
- const values = value === "" ? [] : this._selectedValues();
556
- if (value !== "") {
557
- const i = values.indexOf(value);
558
- if (i >= 0) values.splice(i, 1);
559
- else values.push(value);
560
- }
561
- this.value = values.join(",");
562
- this._renderOptionList();
563
- this.emit("z-change", { values: values.slice(), value: this.value });
564
- return;
565
- }
566
- if (this.value === value) {
567
- this._closeDropdown();
568
- return;
569
- }
570
- this.value = value;
571
- this._closeDropdown();
572
- this.emit("z-change", { value });
288
+ const res = this._syncStrategy().pick(value, this.value);
289
+ if (res.nextValue !== undefined) this.value = res.nextValue;
290
+ if (res.closeDropdown) this._closeDropdown();
291
+ if (res.rerenderList) this._renderOptionList();
292
+ if (res.changeDetail) this.emit("z-change", res.changeDetail);
573
293
  }
574
294
 
575
- /**
576
- * 提交草稿(暂存模式的「确定」)。
577
- *
578
- * 顺序是**先关面板、再改值、最后发事件**:宿主收到 `z-change` 会重渲染整个筛选栏,
579
- * 这个元素(连同浮层)可能在事件处理里被摘掉 —— 那时再去拆面板就是对已脱离文档的节点
580
- * 做操作,轻则报错重则浮层残留。先把自己收拾干净再交出去。
581
- *
582
- * 值没变就不发事件(否则「打开 → 直接点确定」也会触发一次全量查询)。
583
- */
584
295
  private _commitDraft(): void {
585
- const next = (this._draft ?? []).slice();
586
- const changed = next.join(",") !== this.value;
296
+ const res = this._syncStrategy().commit(this.value);
587
297
  this._closeDropdown();
588
- if (!changed) return;
589
- this.value = next.join(",");
590
- this.emit("z-change", { values: next.slice(), value: this.value });
298
+ if (!res) return;
299
+ this.value = res.nextValue;
300
+ this.emit("z-change", res.changeDetail);
591
301
  }
592
302
 
593
- /** 草稿清空(暂存模式的「清空」)。只清草稿,仍需点「确定」才生效。 */
594
303
  private _resetDraft(): void {
595
- if (!this._draft?.length) return;
596
- this._draft = [];
597
- this._renderOptionList();
304
+ if (this._syncStrategy().resetDraft()) {
305
+ this._renderOptionList();
306
+ }
598
307
  }
599
308
 
600
- /** 底部计数的文案与「清空」的可用态(打开面板、每次勾选都会刷新)。 */
601
309
  private _updateFooter(): void {
602
310
  const panel = this._floating.panel;
603
311
  if (!panel) return;
604
312
  const count = panel.querySelector<HTMLElement>(".z-select__count");
605
313
  if (!count) return;
606
- const n = (this._draft ?? []).length;
607
- // 计数而不是「已选 N 项」在 0 时的空串:空串会让底部只剩两个右对齐按钮,看起来像缺了一块
314
+ const n = this._syncStrategy().draftCount();
608
315
  count.textContent = n > 0 ? t("selectedCount", { count: n }) : t("noneSelected");
609
316
  const reset = panel.querySelector<HTMLButtonElement>('[data-act="reset"]');
610
317
  if (reset) reset.disabled = n === 0;
@@ -612,54 +319,23 @@ export class ZSelect extends BaseElement {
612
319
 
613
320
  private _onSearchInput = (e: Event): void => {
614
321
  const input = e.target as HTMLInputElement;
615
- this._query = input.value;
616
- if (this.searchMode === "backend") {
617
- this._scheduleRemoteSearch();
618
- } else {
619
- this._renderOptionList();
620
- }
322
+ this._search.handleInput(input.value, {
323
+ searchMode: this.searchMode,
324
+ remoteMethod: this.remoteMethod,
325
+ isOpen: () => this.open,
326
+ setLoading: (loading) => {
327
+ this.loading = loading;
328
+ },
329
+ applySpecs: (specs) => this._applyRemoteOptions(specs),
330
+ onLocalFilter: () => this._renderOptionList(),
331
+ onSearchEmit: (query) => {
332
+ this.emit("z-search", { query });
333
+ },
334
+ });
621
335
  };
622
336
 
623
- private _clearSearchTimer(): void {
624
- if (this._searchTimer !== null) {
625
- window.clearTimeout(this._searchTimer);
626
- this._searchTimer = null;
627
- }
628
- }
629
-
630
- private _scheduleRemoteSearch(): void {
631
- this._clearSearchTimer();
632
- this._searchTimer = window.setTimeout(() => {
633
- this._searchTimer = null;
634
- this._runRemoteSearch();
635
- }, REMOTE_SEARCH_DELAY);
636
- }
637
-
638
- private _runRemoteSearch(): void {
639
- const query = this._query;
640
- const result = this.remoteMethod ? this.remoteMethod(query) : undefined;
641
-
642
- if (result && typeof (result as Promise<unknown>).then === "function") {
643
- this.loading = true;
644
- (result as Promise<ZSelectOptionSpec[]>)
645
- .then((specs) => {
646
- // [WHY] 防竞态:下拉已关闭或查询词已变时丢弃过期结果
647
- if (!this.open || this._query !== query || !Array.isArray(specs)) return;
648
- this._applyRemoteOptions(specs);
649
- })
650
- .catch(() => {
651
- // remote search 失败时保留现有选项
652
- })
653
- .finally(() => {
654
- if (this.open && this._query === query) this.loading = false;
655
- });
656
- }
657
-
658
- this.emit("z-search", { query });
659
- }
660
-
661
337
  private _applyRemoteOptions(specs: ZSelectOptionSpec[]): void {
662
- this._getOptions().forEach(o => o.remove());
338
+ this._getOptions().forEach((o) => o.remove());
663
339
  for (const spec of specs) {
664
340
  const opt = document.createElement("z-option") as ZOption;
665
341
  opt.value = spec.value;
@@ -670,14 +346,6 @@ export class ZSelect extends BaseElement {
670
346
  this._renderOptionList();
671
347
  }
672
348
 
673
- private _observeOptions(): void {
674
- if (this._optionsObserver) return;
675
- this._optionsObserver = new MutationObserver(() => {
676
- if (this.open) this._renderOptionList();
677
- });
678
- this._optionsObserver.observe(this, { childList: true });
679
- }
680
-
681
349
  private _renderOptionList(): void {
682
350
  if (!this._floating.panel) return;
683
351
  const container = this._floating.panel.querySelector<HTMLElement>(".z-select__options");
@@ -692,53 +360,33 @@ export class ZSelect extends BaseElement {
692
360
 
693
361
  const options = this._getFilteredOptions();
694
362
  container.innerHTML = this._buildOptionsHTML(options);
695
- // 计数与「清空」的可用态跟着勾选变 —— 它和选项列表同一次刷新,不会有中间态
696
363
  this._updateFooter();
697
364
 
698
365
  if (options.length === 0) {
699
366
  this._activeIndex = -1;
700
367
  return;
701
368
  }
702
- if (this._activeIndex < 0 || this._activeIndex >= options.length || options[this._activeIndex].disabled) {
703
- this._activeIndex = options.findIndex(o => !o.disabled);
369
+ if (
370
+ this._activeIndex < 0 ||
371
+ this._activeIndex >= options.length ||
372
+ options[this._activeIndex].disabled
373
+ ) {
374
+ this._activeIndex = options.findIndex((o) => !o.disabled);
704
375
  }
705
376
  this._updateActive();
706
377
  }
707
378
 
708
379
  private _buildOptionsHTML(options: ZOption[]): string {
709
- if (options.length === 0) {
710
- const msg = this.searchable && this._query ? "No results" : "No options";
711
- return html`<div class="z-select__empty" part="empty">${msg}</div>`;
712
- }
713
- // 勾选态读草稿:暂存模式下 `value` 在点「确定」之前不变,直接读它会让面板里的勾
714
- // 永远停在打开那一刻的样子(勾了没反应)。
715
- const values = this._draftValues();
716
- return options.map((opt, i) => {
717
- const on = this.multiple ? values.includes(opt.value) : opt.value === this.value;
718
- const cls = [
719
- "z-select__option",
720
- on ? "z-select__option--selected" : "",
721
- // 多选里选中态降级为中性底:蓝底会被读成"这行是高亮项",与"已勾选"混淆
722
- this.multiple && on ? "z-select__option--multi" : "",
723
- opt.disabled ? "z-select__option--disabled" : "",
724
- i === this._activeIndex ? "z-select__option--active" : "",
725
- ].filter(Boolean).join(" ");
726
-
727
- const box = this.multiple
728
- ? html`<span class="z-select__box ${on ? "z-select__box--on" : ""}" part="box">${on
729
- ? `<svg width="12" height="12" viewBox="0 0 12 12"><path d="M2.5 6L5 8.5L9.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>`
730
- : ""}</span>`
731
- : "";
732
-
733
- // [WHY] opt.value / opt.label 来自数据源(常见于服务端下发的字典),
734
- // 不转义时 `"` 可闭合属性注入事件处理器,`<img onerror>` 可注入标签。
735
- // 同仓库 data-list / menu / detail-form 早已用 escAttr/esc,此处是漏网([[bug-20261025-xss-injection]])
736
- return html`<div class="${cls}" id="${this._uid}-opt-${i}" data-value="${escapeAttr(String(opt.value))}" role="option" tabindex="-1" aria-selected="${on ? "true" : "false"}" aria-disabled="${opt.disabled ? "true" : "false"}">
737
- ${box}
738
- ${escapeHtml(String(opt.label ?? ""))}
739
- ${!this.multiple && on ? html`<span class="z-select__check" part="check"><svg width="12" height="12" viewBox="0 0 12 12"><path d="M2.5 6L5 8.5L9.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg></span>` : ""}
740
- </div>`;
741
- }).join("");
380
+ const strategy = this._syncStrategy();
381
+ return buildSelectOptionsHTML({
382
+ uid: this._uid,
383
+ options,
384
+ multiple: this.multiple,
385
+ searchable: this.searchable,
386
+ query: this._search.query,
387
+ activeIndex: this._activeIndex,
388
+ isSelected: (v) => strategy.isSelected(v, this.value),
389
+ });
742
390
  }
743
391
 
744
392
  private _setActiveByElement(el: HTMLElement): void {
@@ -751,12 +399,6 @@ export class ZSelect extends BaseElement {
751
399
  }
752
400
  }
753
401
 
754
- /**
755
- * 面板里「持有键盘焦点、并且能承载 activedescendant」的那个元素。
756
- *
757
- * 搜索模式是输入框(combobox),非搜索模式是 listbox 自身。两者都在 body 这棵树里,
758
- * 与选项同树 —— 这是 IDREF 能解析的前提,不是风格选择。
759
- */
760
402
  private _focusOwner(): HTMLElement | null {
761
403
  const panel = this._floating.panel;
762
404
  if (!panel) return null;
@@ -771,15 +413,6 @@ export class ZSelect extends BaseElement {
771
413
  items.forEach((item, i) => {
772
414
  item.classList.toggle("z-select__option--active", i === this._activeIndex);
773
415
  });
774
- // ── aria-activedescendant:写在**持有焦点的那个元素**上 ──
775
- //
776
- // [WHY 不是写在触发器上] 它是个 IDREF,只在**同一棵树**里解析。触发器在 `z-select`
777
- // 的 shadow 里、面板挂在 `document.body` —— 写在触发器上时 DOM 查得到但 AX 树里
778
- // 根本不出现(2026-11-15 CDP 无障碍树实测),读屏全程不吭声,而界面上高亮一格格
779
- // 跳得完全正常。所以焦点必须和选项在同一棵树:搜索模式是面板里的 input(它就是
780
- // combobox),非搜索模式是 listbox 自己(打开时被 focus,见 _openDropdown)。
781
- //
782
- // 反面参照:`z-menu` 的面板与选项都在 body,同一棵树 ⇒ 写上去就生效。
783
416
  const owner = this._focusOwner();
784
417
  const active = items[this._activeIndex];
785
418
  if (owner) {
@@ -792,18 +425,6 @@ export class ZSelect extends BaseElement {
792
425
  private _onDropdownKey = (e: Event): void => {
793
426
  const ke = e as KeyboardEvent;
794
427
  const options = this._getFilteredOptions();
795
-
796
- // ── 一维移动:↑↓ / Home / End 交给 L0 ──
797
- //
798
- // [WHY 候选集是**全集**、靠 isDisabled 跳过] 与菜单相反:下拉的 `_activeIndex`
799
- // 必须落在**过滤后全集**的下标空间里,因为它在三处被同时使用 ——
800
- // `_buildOptionsHTML` 的 `id` 后缀(`aria-activedescendant` 指的就是它)、
801
- // 勾选态判断、以及 hover 的 `_setActiveByElement`。先滤掉禁用项再算下标,
802
- // 这三处就会集体错位一格。
803
- //
804
- // [WHY 补上 Home/End] 原来只接 ↑↓。500 项的物料下拉里跳到末尾要按 499 下 ——
805
- // 而同一份键盘帮助文档里写着菜单支持 Home/End。这两键由 `resolveIndex` 直接给出,
806
- // 不需要在这里各写一条分支。
807
428
  const intent = listIntent(ke.key);
808
429
  if (intent) {
809
430
  e.preventDefault();
@@ -821,25 +442,19 @@ export class ZSelect extends BaseElement {
821
442
  case "Enter": {
822
443
  e.preventDefault();
823
444
  const active = options[this._activeIndex];
824
- if (active && !active.disabled) {
825
- this._selectOption(active.value);
826
- }
445
+ if (active && !active.disabled) this._selectOption(active.value);
827
446
  break;
828
447
  }
829
448
  case "Escape":
830
449
  e.preventDefault();
831
- // 同 trigger 上的说明:Esc 到下拉为止,别再让外层把它读成「退出上一层」
832
450
  e.stopPropagation();
833
451
  this._closeDropdown();
834
452
  break;
835
453
  case "Tab":
836
- // [WHY 暂存模式不关] 面板底部有「确定」,键盘用户得靠 Tab 走过去。这里一关,
837
- // 提交入口就只剩鼠标可达 —— 一个控件自己把可访问性做没了。
838
- if (!this._staging()) this._closeDropdown();
454
+ if (!this._syncStrategy().isStaging) this._closeDropdown();
839
455
  break;
840
456
  }
841
457
  };
842
-
843
458
  }
844
459
 
845
460
  defineElement("z-select", ZSelect);