1use crate::{KeyboardInput, SemanticId};
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum ComboboxKind {
6 Select,
8 Editable,
10 Autocomplete,
12 Multiple,
14}
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct OptionSemantics {
18 pub owner: SemanticId,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum ChoiceCommand {
23 OpenFirst,
24 OpenLast,
25 Previous,
26 Next,
27 First,
28 Last,
29 Commit,
30 Close,
31 RemoveLast,
32}
33
34impl KeyboardInput<'_> {
35 pub fn choice_remove_last(self, kind: ComboboxKind, empty: bool) -> Option<ChoiceCommand> {
36 (kind == ComboboxKind::Multiple
37 && empty
38 && self.key == "Backspace"
39 && !self.composing
40 && !self.control
41 && !self.meta
42 && !self.alt
43 && !self.shift)
44 .then_some(ChoiceCommand::RemoveLast)
45 }
46 pub fn choice(self, kind: ComboboxKind, expanded: bool) -> Option<ChoiceCommand> {
47 use ChoiceCommand::*;
48 if self.composing || self.control || self.meta || self.shift {
49 return None;
50 }
51 if self.alt {
52 return (!expanded && self.key == "ArrowDown").then_some(OpenFirst);
53 }
54 match self.key {
55 "ArrowDown" if kind == ComboboxKind::Select => Some(Next),
58 "ArrowUp" if kind == ComboboxKind::Select => Some(Previous),
59 "Enter" | " " if kind == ComboboxKind::Select => Some(Commit),
60 "Escape" if kind == ComboboxKind::Select => Some(Close),
61 "ArrowDown" => Some(if expanded { Next } else { OpenFirst }),
62 "ArrowUp" => Some(if expanded { Previous } else { OpenLast }),
63 "Home" if kind == ComboboxKind::Select => Some(First),
64 "End" if kind == ComboboxKind::Select => Some(Last),
65 "Enter" => {
66 if expanded {
67 Some(Commit)
68 } else {
69 (kind == ComboboxKind::Select).then_some(OpenFirst)
70 }
71 }
72 "Escape" if expanded => Some(Close),
73 _ => None,
74 }
75 }
76}
77
78impl crate::Semantics {
79 pub(crate) fn validate_choice(
80 &self,
81 node: crate::DescriptorView<'_>,
82 ) -> Result<(), crate::Error> {
83 use crate::{Error, FocusMode, Orientation, PopupKind, Props, Role};
84 if let Some(kind) = self.combobox {
85 let valid = matches!((kind, node.props), (ComboboxKind::Select, Props::Button(_)))
86 || matches!(node.props, Props::Input(input) if kind != ComboboxKind::Select && !input.multiline);
87 if !valid
88 || self.id.is_none()
89 || self.controls.is_none()
90 || !(self.popup == Some(PopupKind::Listbox)
91 || kind == ComboboxKind::Select && self.popup == Some(PopupKind::Tree))
92 || self.expanded.is_none()
93 || self.tab
94 || self.menu_item.is_some()
95 || self.option.is_some()
96 || self.form_action.is_some()
97 || self.pressed.is_some()
98 {
99 return Err(Error::InvalidProps(
100 "combobox requires a matching intrinsic trigger, listbox popup and controls/expanded metadata",
101 ));
102 }
103 }
104 if self.active_descendant.is_some()
105 && (self.combobox.is_none()
106 || self.expanded != Some(true)
107 || self.active_descendant == self.id
108 || self.popup != Some(PopupKind::Listbox))
109 {
110 return Err(Error::InvalidProps(
111 "active descendant requires an expanded combobox and distinct option",
112 ));
113 }
114 if let Some(option) = &self.option
115 && (!matches!(node.props, Props::Button(_))
116 || node.focus != FocusMode::Programmatic
117 || self.id.is_none()
118 || self.id.as_ref() == Some(&option.owner)
119 || self.selected.is_none()
120 || self.tab
121 || self.menu_item.is_some()
122 || self.combobox.is_some()
123 || self.popup.is_some()
124 || self.controls.is_some()
125 || self.expanded.is_some()
126 || self.pressed.is_some()
127 || self.form_action.is_some()
128 || self.form_control.is_some())
129 {
130 return Err(Error::InvalidProps(
131 "listbox options require an unfocusable intrinsic button, selected state and distinct owner",
132 ));
133 }
134 if self.listbox_multiple && node.role != Some(Role::Listbox) {
135 return Err(Error::InvalidProps("multiple selection requires a listbox"));
136 }
137 if node.role == Some(Role::Listbox)
138 && (self.id.is_none()
139 || node.focus != FocusMode::Auto
140 || self.navigation != Some(Orientation::Vertical))
141 {
142 return Err(Error::InvalidProps(
143 "listbox requires a vertical unfocused collection boundary",
144 ));
145 }
146 Ok(())
147 }
148}
149
150impl crate::memory::Memory {
151 pub(crate) fn validate_choice_patch(&self, id: crate::NodeId) -> Result<(), crate::Error> {
152 let node = self.node(id)?;
153 if !node.placed && node.parent.is_none() {
154 return Ok(());
155 }
156 if self.nearest_listbox(node.parent)?.is_none() {
157 let mut root = id;
158 while let Some(parent) = self.node(root)?.parent {
159 root = parent;
160 }
161 let root = self.node(root)?;
162 if !root.placed && root.descriptor.pending_external_options() {
163 return Ok(());
164 }
165 }
166 self.validate_choice_child(crate::memory::Subtree::Existing(id), node.parent)
167 }
168 fn nearest_listbox(
169 &self,
170 mut node: Option<crate::NodeId>,
171 ) -> Result<Option<crate::NodeId>, crate::Error> {
172 while let Some(id) = node {
173 let current = self.node(id)?;
174 if current.descriptor.view().role == Some(crate::Role::Listbox) {
175 return Ok(Some(id));
176 }
177 node = current.parent;
178 }
179 Ok(None)
180 }
181
182 pub(crate) fn validate_choice_child(
183 &self,
184 child: crate::memory::Subtree<'_>,
185 parent: Option<crate::NodeId>,
186 ) -> Result<(), crate::Error> {
187 use crate::memory::Subtree;
188 let owner = self.nearest_listbox(parent)?;
189 let name = owner
190 .and_then(|id| self.node(id).ok())
191 .and_then(|node| node.descriptor.view().semantic_id());
192 match child {
193 Subtree::New(descriptor) => check_child(descriptor, name)?,
194 Subtree::Plan(plan) => validate_plan_owners(plan, name, false)?,
195 Subtree::Existing(id) => {
196 let root = self.node(id)?;
197 check_child(root.descriptor.view(), name)?;
198 let old = self.nearest_listbox(root.parent)?;
199 let pending_plan = !root.placed && root.descriptor.pending_external_options();
200 if old != owner || pending_plan {
201 self.validate_choice_subtree(id, parent)?;
202 }
203 }
204 }
205 Ok(())
206 }
207
208 pub(crate) fn validate_choice_subtree(
209 &self,
210 root: crate::NodeId,
211 parent: Option<crate::NodeId>,
212 ) -> Result<(), crate::Error> {
213 let owner = self.nearest_listbox(parent)?;
214 let name = owner
215 .and_then(|id| self.node(id).ok())
216 .and_then(|node| node.descriptor.view().semantic_id());
217 self.validate_choice_range(vec![root], name)
218 }
219
220 pub(crate) fn validate_choice_contents(&self, root: crate::NodeId) -> Result<(), crate::Error> {
221 let owner = self.nearest_listbox(Some(root))?;
222 let name = owner
223 .and_then(|id| self.node(id).ok())
224 .and_then(|node| node.descriptor.view().semantic_id());
225 let children = &self.node(root)?.children;
226 if children.len() > 4096 {
227 return Err(crate::Error::InvalidPlacement(
228 "restricted listbox subtree exceeds 4096 live nodes",
229 ));
230 }
231 self.validate_choice_range(children.iter().copied().collect(), name)
232 }
233
234 fn validate_choice_range(
235 &self,
236 mut pending: Vec<crate::NodeId>,
237 name: Option<&SemanticId>,
238 ) -> Result<(), crate::Error> {
239 let mut inspected = 0usize;
240 while let Some(id) = pending.pop() {
241 inspected += 1;
242 if inspected > 4096 {
243 return Err(crate::Error::InvalidPlacement(
244 "restricted listbox subtree exceeds 4096 live nodes",
245 ));
246 }
247 let node = self.node(id)?;
248 let descriptor = node.descriptor.view();
249 check_child(descriptor, name)?;
250 if descriptor.role == Some(crate::Role::Listbox) {
253 continue;
254 }
255 if pending.len() + inspected + node.children.len() > 4096 {
256 return Err(crate::Error::InvalidPlacement(
257 "restricted listbox subtree exceeds 4096 live nodes",
258 ));
259 }
260 pending.extend(node.children.iter().copied());
261 }
262 Ok(())
263 }
264 pub fn resolve_active_descendant(
268 &self,
269 trigger: crate::NodeId,
270 ) -> Result<Option<crate::NodeId>, crate::Error> {
271 let descriptor = self.node(trigger)?.descriptor.view();
272 let Some(semantics) = descriptor
273 .semantics
274 .as_deref()
275 .filter(|s| s.combobox.is_some() && s.expanded == Some(true))
276 else {
277 return Ok(None);
278 };
279 let Some(owner) = semantics
280 .controls
281 .as_ref()
282 .and_then(|name| self.named(name))
283 else {
284 return Ok(None);
285 };
286 let Some(option) = semantics
287 .active_descendant
288 .as_ref()
289 .and_then(|name| self.named(name))
290 else {
291 return Ok(None);
292 };
293 if !self.active(trigger)
294 || !self.active(owner)
295 || !self.active(option)
296 || !self.enabled(option)
297 {
298 return Ok(None);
299 }
300 let owner_descriptor = self.node(owner)?.descriptor.view();
301 let option_descriptor = self.node(option)?.descriptor.view();
302 if !option_descriptor.activation_enabled() {
303 return Ok(None);
304 }
305 if owner_descriptor.role != Some(crate::Role::Listbox)
306 || owner_descriptor
307 .semantics
308 .as_ref()
309 .is_some_and(|owner| owner.listbox_multiple)
310 != (semantics.combobox == Some(ComboboxKind::Multiple))
311 || !option_descriptor
312 .semantics
313 .as_ref()
314 .and_then(|s| s.option.as_ref())
315 .is_some_and(|s| Some(&s.owner) == semantics.controls.as_ref())
316 {
317 return Ok(None);
318 }
319 let mut cursor = self.node(option)?.parent;
320 while let Some(id) = cursor {
321 if id == owner {
322 return Ok(Some(option));
323 }
324 if self.node(id)?.descriptor.view().role == Some(crate::Role::Listbox) {
325 return Ok(None);
326 }
327 cursor = self.node(id)?.parent;
328 }
329 Ok(None)
330 }
331
332 pub(crate) fn validate_choice_reference(
333 &self,
334 descriptor: crate::DescriptorView<'_>,
335 ) -> Result<(), crate::Error> {
336 let Some(semantics) = descriptor.semantics.as_deref() else {
337 return Ok(());
338 };
339 if semantics.combobox.is_some()
340 && let Some(owner) = semantics
341 .controls
342 .as_ref()
343 .and_then(|name| self.named(name))
344 {
345 let owner = self.node(owner)?.descriptor.view();
346 let tree_popup = semantics.popup == Some(crate::PopupKind::Tree);
347 if (tree_popup
348 && (owner.role != Some(crate::Role::Tree)
349 || owner
350 .semantics
351 .as_ref()
352 .is_none_or(|s| s.tree_navigation.is_none())))
353 || (!tree_popup
354 && (owner.role != Some(crate::Role::Listbox)
355 || owner
356 .semantics
357 .as_ref()
358 .is_some_and(|owner| owner.listbox_multiple)
359 != (semantics.combobox == Some(ComboboxKind::Multiple))))
360 {
361 return Err(crate::Error::InvalidProps(
362 "combobox controls must resolve to the declared tree or matching single/multiple listbox",
363 ));
364 }
365 }
366 let Some(active) = semantics
367 .active_descendant
368 .as_ref()
369 .and_then(|name| self.named(name))
370 else {
371 return Ok(());
372 };
373 let target = self.node(active)?.descriptor.view();
374 if !target
375 .semantics
376 .as_ref()
377 .and_then(|s| s.option.as_ref())
378 .is_some_and(|option| Some(&option.owner) == semantics.controls.as_ref())
379 {
380 return Err(crate::Error::InvalidProps(
381 "active descendant must identify an option belonging to the controlled listbox",
382 ));
383 }
384 Ok(())
385 }
386}
387
388fn check_child(
389 descriptor: crate::DescriptorView<'_>,
390 owner: Option<&SemanticId>,
391) -> Result<(), crate::Error> {
392 let option = descriptor
393 .semantics
394 .as_ref()
395 .and_then(|s| s.option.as_ref());
396 if let Some(option) = option {
397 if owner != Some(&option.owner) {
398 return Err(crate::Error::InvalidPlacement(
399 "option requires its nearest owning listbox",
400 ));
401 }
402 } else if owner.is_some()
403 && (descriptor.props.interactive() || descriptor.role == Some(crate::Role::Listbox))
404 {
405 return Err(crate::Error::InvalidPlacement(
406 "listboxes contain options and passive groups, not unrelated controls",
407 ));
408 }
409 Ok(())
410}
411
412pub(crate) fn validate_plan_owners(
416 plan: &crate::Plan,
417 owner: Option<&SemanticId>,
418 pending: bool,
419) -> Result<(), crate::Error> {
420 if !pending {
421 if owner.is_none() && !plan.external_options() {
424 return Ok(());
425 }
426 for &index in plan.choice_roots() {
427 check_child(plan.nodes()[index].descriptor.view(), owner)?;
428 }
429 return Ok(());
430 }
431 let mut contexts = Vec::with_capacity(plan.nodes().len());
432 for node in plan.nodes() {
433 let context = node.parent.map_or(owner, |parent| contexts[parent]);
434 let descriptor = node.descriptor.view();
435 if !(pending && context.is_none()) {
436 check_child(descriptor, context)?;
437 }
438 contexts.push(if descriptor.role == Some(crate::Role::Listbox) {
439 descriptor.semantic_id()
440 } else {
441 context
442 });
443 }
444 Ok(())
445}
446
447pub(crate) fn plan_external_options(plan: &crate::Plan) -> bool {
448 plan.external_options()
449}