yew_virtual/core/virtual_key.rs
1/// Stable identity key for a virtual item.
2///
3/// Supports both numeric and string-based keys to allow custom
4/// key extractors that produce stable identities across item
5/// reordering. When items are reordered, their measured sizes
6/// follow the key rather than the index.
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub enum VirtualKey {
9 /// A numeric key, typically derived from the item index.
10 Index(usize),
11
12 /// A string-based key for custom identity strategies.
13 Named(String),
14}
15
16impl Default for VirtualKey {
17 /// Returns a default key of index zero.
18 ///
19 /// # Returns
20 ///
21 /// - `VirtualKey::Index(0)`: The default key.
22 fn default() -> Self {
23 // Default to index zero.
24 Self::Index(0)
25 }
26}
27
28impl From<usize> for VirtualKey {
29 /// Creates a key from a numeric index.
30 ///
31 /// # Parameters
32 ///
33 /// - `index`: The numeric index value.
34 fn from(index: usize) -> Self {
35 // Wrap the index in the Index variant.
36 Self::Index(index)
37 }
38}
39
40impl From<String> for VirtualKey {
41 /// Creates a key from a string.
42 ///
43 /// # Parameters
44 ///
45 /// - `name`: The string key value.
46 fn from(name: String) -> Self {
47 // Wrap the string in the Named variant.
48 Self::Named(name)
49 }
50}
51
52impl From<&str> for VirtualKey {
53 /// Creates a key from a string slice.
54 ///
55 /// # Parameters
56 ///
57 /// - `name`: The string slice key value.
58 fn from(name: &str) -> Self {
59 // Convert to owned string and wrap.
60 Self::Named(name.to_string())
61 }
62}
63
64impl std::fmt::Display for VirtualKey {
65 /// Formats the key for display.
66 ///
67 /// # Parameters
68 ///
69 /// - `f`: The formatter.
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 // Delegate formatting based on variant.
72 match self {
73 Self::Index(i) => write!(f, "{}", i),
74 Self::Named(s) => write!(f, "{}", s),
75 }
76 }
77}