11use js_sys:: Array ;
2+ use std:: collections:: HashSet ;
23use serde:: { Deserialize , Serialize } ;
34use wasm_bindgen:: prelude:: * ;
45
@@ -37,20 +38,49 @@ impl LinkTargetCandidate {
3738}
3839
3940impl LinkTargetCandidate {
40- pub fn new ( title : String , path : String , aliases : & [ String ] , selected_index : usize ) -> Self {
41+ pub fn new ( title : String , path : String , aliases : & [ String ] , matched_text : & str ) -> Self {
42+ let mut seen_candidates: HashSet < String > = HashSet :: new ( ) ;
4143 let mut _replacement_candidates: Vec < PreferrableItem > = vec ! [ ] ;
42- let replacement_candidate_title = PreferrableItem :: new ( title. clone ( ) , true ) ;
43- _replacement_candidates. push ( replacement_candidate_title) ;
44-
45- aliases. iter ( ) . enumerate ( ) . for_each ( |( index, alias) | {
46- let replacement_candidate_alias = PreferrableItem :: new (
47- alias. clone ( ) ,
48- // add one because the index starts with the title at 0
49- true ,
50- ) ;
44+
45+ let mut case_sensitive_match_index: Option < usize > = None ;
46+ let mut case_insensitive_match_index: Option < usize > = None ;
47+
48+ seen_candidates. insert ( title. clone ( ) ) ;
49+ _replacement_candidates. push ( PreferrableItem :: new ( title. clone ( ) , false ) ) ;
50+ if title == matched_text {
51+ case_sensitive_match_index = Some ( 0 ) ;
52+ } else if title. eq_ignore_ascii_case ( matched_text) {
53+ case_insensitive_match_index = Some ( 0 ) ;
54+ }
55+
56+ aliases. iter ( ) . for_each ( |alias| {
57+ if seen_candidates. contains ( alias) {
58+ return ;
59+ }
60+
61+ let candidate_index = _replacement_candidates. len ( ) ;
62+
63+ if alias == matched_text && case_sensitive_match_index. is_none ( ) {
64+ case_sensitive_match_index = Some ( candidate_index) ;
65+ } else if alias. eq_ignore_ascii_case ( matched_text)
66+ && case_insensitive_match_index. is_none ( )
67+ {
68+ case_insensitive_match_index = Some ( candidate_index) ;
69+ }
70+
71+ seen_candidates. insert ( alias. clone ( ) ) ;
72+ let replacement_candidate_alias = PreferrableItem :: new ( alias. clone ( ) , false ) ;
5173 _replacement_candidates. push ( replacement_candidate_alias) ;
5274 } ) ;
5375
76+ let preferred_index = case_sensitive_match_index
77+ . or ( case_insensitive_match_index)
78+ . unwrap_or ( 0 ) ;
79+
80+ if let Some ( preferred_candidate) = _replacement_candidates. get_mut ( preferred_index) {
81+ preferred_candidate. is_preferred = true ;
82+ }
83+
5484 LinkTargetCandidate {
5585 title,
5686 path,
@@ -65,4 +95,4 @@ pub fn link_target_candidate_vec_into_array(link_target_candidates: Vec<LinkTarg
6595 link_target_candidates_array. push ( & link_target_candidate. into ( ) ) ;
6696 }
6797 link_target_candidates_array
68- }
98+ }
0 commit comments