vize_maestro 0.0.1-alpha.26

Maestro - Language Server Protocol implementation for Vize Vue templates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Workspace symbols provider.
//!
//! Provides workspace-wide symbol search for:
//! - Vue components (from file names)
//! - Script bindings (functions, variables, classes)
//! - CSS classes and IDs

use tower_lsp::lsp_types::{Location, Position, Range, SymbolInformation, SymbolKind, Url};

use crate::server::ServerState;

/// Workspace symbols service.
pub struct WorkspaceSymbolsService;

impl WorkspaceSymbolsService {
    /// Search for symbols matching a query.
    pub fn search(state: &ServerState, query: &str) -> Vec<SymbolInformation> {
        let mut symbols = Vec::new();
        let query_lower = query.to_lowercase();

        // Search in all open documents
        for entry in state.documents.iter() {
            let uri = entry.key();
            let doc = entry.value();
            let content = doc.text();

            // Only process .vue files
            if !uri.path().ends_with(".vue") {
                continue;
            }

            Self::collect_symbols_from_document(uri, &content, &query_lower, &mut symbols);
        }

        // Sort by relevance (exact match first, then prefix match, then contains)
        symbols.sort_by(|a, b| {
            let a_name = a.name.to_lowercase();
            let b_name = b.name.to_lowercase();

            let a_exact = a_name == query_lower;
            let b_exact = b_name == query_lower;

            if a_exact != b_exact {
                return b_exact.cmp(&a_exact);
            }

            let a_prefix = a_name.starts_with(&query_lower);
            let b_prefix = b_name.starts_with(&query_lower);

            if a_prefix != b_prefix {
                return b_prefix.cmp(&a_prefix);
            }

            a_name.cmp(&b_name)
        });

        // Limit results
        symbols.truncate(100);

        symbols
    }

    /// Collect symbols from a single document.
    #[allow(deprecated)] // SymbolInformation.deprecated is deprecated in favor of tags
    fn collect_symbols_from_document(
        uri: &Url,
        content: &str,
        query: &str,
        symbols: &mut Vec<SymbolInformation>,
    ) {
        let options = vize_atelier_sfc::SfcParseOptions {
            filename: uri.path().to_string(),
            ..Default::default()
        };

        let Ok(descriptor) = vize_atelier_sfc::parse_sfc(content, options) else {
            return;
        };

        // Extract component name from file path
        if let Some(component_name) = Self::extract_component_name(uri) {
            if component_name.to_lowercase().contains(query) {
                symbols.push(SymbolInformation {
                    name: component_name,
                    kind: SymbolKind::CLASS,
                    tags: None,
                    deprecated: None,
                    location: Location {
                        uri: uri.clone(),
                        range: Range {
                            start: Position {
                                line: 0,
                                character: 0,
                            },
                            end: Position {
                                line: 0,
                                character: 0,
                            },
                        },
                    },
                    container_name: None,
                });
            }
        }

        // Collect from script setup
        if let Some(ref script_setup) = descriptor.script_setup {
            Self::collect_script_symbols(
                uri,
                &script_setup.content,
                script_setup.loc.start_line as u32,
                query,
                Some("script setup"),
                symbols,
            );
        }

        // Collect from script
        if let Some(ref script) = descriptor.script {
            Self::collect_script_symbols(
                uri,
                &script.content,
                script.loc.start_line as u32,
                query,
                Some("script"),
                symbols,
            );
        }

        // Collect from styles
        for (idx, style) in descriptor.styles.iter().enumerate() {
            Self::collect_style_symbols(
                uri,
                &style.content,
                style.loc.start_line as u32,
                query,
                Some(&format!("style[{}]", idx)),
                symbols,
            );
        }
    }

    /// Extract component name from URI.
    fn extract_component_name(uri: &Url) -> Option<String> {
        let path = uri.path();
        let file_name = path.rsplit('/').next()?;

        // Remove .vue extension
        let name = file_name.strip_suffix(".vue")?;

        // Convert to PascalCase
        Some(Self::to_pascal_case(name))
    }

    /// Convert string to PascalCase.
    fn to_pascal_case(s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        let mut capitalize_next = true;

        for c in s.chars() {
            if c == '-' || c == '_' || c == '.' {
                capitalize_next = true;
            } else if capitalize_next {
                result.push(c.to_ascii_uppercase());
                capitalize_next = false;
            } else {
                result.push(c);
            }
        }

        result
    }

    /// Collect symbols from script content.
    fn collect_script_symbols(
        uri: &Url,
        script: &str,
        base_line: u32,
        query: &str,
        container: Option<&str>,
        symbols: &mut Vec<SymbolInformation>,
    ) {
        let lines: Vec<&str> = script.lines().collect();

        for (line_idx, line) in lines.iter().enumerate() {
            let line_num = base_line + line_idx as u32;
            let trimmed = line.trim_start();

            // const name = ...
            if let Some(rest) = trimmed.strip_prefix("const ") {
                if let Some((name, kind)) = Self::parse_declaration(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            kind,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
            // let name = ...
            else if let Some(rest) = trimmed.strip_prefix("let ") {
                if let Some((name, kind)) = Self::parse_declaration(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            kind,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
            // function name(...) { ... }
            else if let Some(rest) = trimmed.strip_prefix("function ") {
                if let Some(name) = Self::extract_identifier(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            SymbolKind::FUNCTION,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
            // async function name(...) { ... }
            else if let Some(rest) = trimmed.strip_prefix("async function ") {
                if let Some(name) = Self::extract_identifier(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            SymbolKind::FUNCTION,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
            // class Name { ... }
            else if let Some(rest) = trimmed.strip_prefix("class ") {
                if let Some(name) = Self::extract_identifier(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            SymbolKind::CLASS,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
            // interface Name { ... }
            else if let Some(rest) = trimmed.strip_prefix("interface ") {
                if let Some(name) = Self::extract_identifier(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            SymbolKind::INTERFACE,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
            // type Name = ...
            else if let Some(rest) = trimmed.strip_prefix("type ") {
                if let Some(name) = Self::extract_identifier(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            SymbolKind::TYPE_PARAMETER,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
            // enum Name { ... }
            else if let Some(rest) = trimmed.strip_prefix("enum ") {
                if let Some(name) = Self::extract_identifier(rest) {
                    if name.to_lowercase().contains(query) {
                        symbols.push(Self::create_symbol(
                            name,
                            SymbolKind::ENUM,
                            uri.clone(),
                            line_num - 1,
                            container,
                        ));
                    }
                }
            }
        }
    }

    /// Collect symbols from style content.
    fn collect_style_symbols(
        uri: &Url,
        style: &str,
        base_line: u32,
        query: &str,
        container: Option<&str>,
        symbols: &mut Vec<SymbolInformation>,
    ) {
        let lines: Vec<&str> = style.lines().collect();

        for (line_idx, line) in lines.iter().enumerate() {
            let line_num = base_line + line_idx as u32;
            let trimmed = line.trim();

            // CSS class selectors
            for class in Self::extract_css_classes(trimmed) {
                if class.to_lowercase().contains(query) {
                    symbols.push(Self::create_symbol(
                        format!(".{}", class),
                        SymbolKind::STRING,
                        uri.clone(),
                        line_num - 1,
                        container,
                    ));
                }
            }

            // CSS ID selectors
            for id in Self::extract_css_ids(trimmed) {
                if id.to_lowercase().contains(query) {
                    symbols.push(Self::create_symbol(
                        format!("#{}", id),
                        SymbolKind::STRING,
                        uri.clone(),
                        line_num - 1,
                        container,
                    ));
                }
            }
        }
    }

    /// Parse a declaration and return name and kind.
    fn parse_declaration(s: &str) -> Option<(String, SymbolKind)> {
        let name = Self::extract_identifier(s)?;

        // Determine kind based on initialization
        let kind = if s.contains("ref(") || s.contains("computed(") || s.contains("reactive(") {
            SymbolKind::VARIABLE
        } else if s.contains("=>") || s.contains("function") {
            SymbolKind::FUNCTION
        } else {
            SymbolKind::CONSTANT
        };

        Some((name, kind))
    }

    /// Extract identifier from string.
    fn extract_identifier(s: &str) -> Option<String> {
        let s = s.trim_start();
        if s.is_empty() {
            return None;
        }

        let bytes = s.as_bytes();
        let first = bytes[0] as char;

        // Skip destructuring
        if first == '{' || first == '[' {
            return None;
        }

        if !Self::is_ident_start(first) {
            return None;
        }

        let mut end = 1;
        while end < bytes.len() && Self::is_ident_char(bytes[end] as char) {
            end += 1;
        }

        Some(s[..end].to_string())
    }

    /// Extract CSS class names from a selector line.
    fn extract_css_classes(line: &str) -> Vec<String> {
        let mut classes = Vec::new();
        let mut pos = 0;

        while let Some(dot_pos) = line[pos..].find('.') {
            let abs_pos = pos + dot_pos + 1;
            if abs_pos < line.len() {
                let rest = &line[abs_pos..];
                let end = rest
                    .find(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_')
                    .unwrap_or(rest.len());

                if end > 0 {
                    classes.push(rest[..end].to_string());
                }

                pos = abs_pos + end;
            } else {
                break;
            }
        }

        classes
    }

    /// Extract CSS ID names from a selector line.
    fn extract_css_ids(line: &str) -> Vec<String> {
        let mut ids = Vec::new();
        let mut pos = 0;

        while let Some(hash_pos) = line[pos..].find('#') {
            let abs_pos = pos + hash_pos + 1;
            if abs_pos < line.len() {
                let rest = &line[abs_pos..];
                let end = rest
                    .find(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_')
                    .unwrap_or(rest.len());

                if end > 0 {
                    ids.push(rest[..end].to_string());
                }

                pos = abs_pos + end;
            } else {
                break;
            }
        }

        ids
    }

    /// Create a symbol information entry.
    #[allow(deprecated)]
    fn create_symbol(
        name: String,
        kind: SymbolKind,
        uri: Url,
        line: u32,
        container: Option<&str>,
    ) -> SymbolInformation {
        SymbolInformation {
            name,
            kind,
            tags: None,
            deprecated: None,
            location: Location {
                uri,
                range: Range {
                    start: Position { line, character: 0 },
                    end: Position { line, character: 0 },
                },
            },
            container_name: container.map(|s| s.to_string()),
        }
    }

    fn is_ident_start(c: char) -> bool {
        c.is_ascii_alphabetic() || c == '_' || c == '$'
    }

    fn is_ident_char(c: char) -> bool {
        c.is_ascii_alphanumeric() || c == '_' || c == '$'
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_to_pascal_case() {
        assert_eq!(
            WorkspaceSymbolsService::to_pascal_case("hello-world"),
            "HelloWorld"
        );
        assert_eq!(
            WorkspaceSymbolsService::to_pascal_case("my_component"),
            "MyComponent"
        );
        assert_eq!(WorkspaceSymbolsService::to_pascal_case("Button"), "Button");
    }

    #[test]
    fn test_extract_identifier() {
        assert_eq!(
            WorkspaceSymbolsService::extract_identifier("count = 0"),
            Some("count".to_string())
        );
        assert_eq!(
            WorkspaceSymbolsService::extract_identifier("MyClass extends Base"),
            Some("MyClass".to_string())
        );
        assert_eq!(
            WorkspaceSymbolsService::extract_identifier("{ a, b } = obj"),
            None
        );
    }

    #[test]
    fn test_extract_css_classes() {
        let classes = WorkspaceSymbolsService::extract_css_classes(".container .item-active { }");
        assert_eq!(classes, vec!["container", "item-active"]);
    }

    #[test]
    fn test_extract_css_ids() {
        let ids = WorkspaceSymbolsService::extract_css_ids("#app #main-content { }");
        assert_eq!(ids, vec!["app", "main-content"]);
    }

    #[test]
    fn test_parse_declaration() {
        let (name, kind) = WorkspaceSymbolsService::parse_declaration("count = ref(0)").unwrap();
        assert_eq!(name, "count");
        assert_eq!(kind, SymbolKind::VARIABLE);

        let (name, kind) =
            WorkspaceSymbolsService::parse_declaration("handleClick = () => {}").unwrap();
        assert_eq!(name, "handleClick");
        assert_eq!(kind, SymbolKind::FUNCTION);
    }
}