|
| 1 | +use std::{collections::HashMap, rc}; |
| 2 | + |
1 | 3 | use ego_tree::Tree;
|
2 |
| -use swc_common::{sync::Lrc, SourceMap, errors::{Handler, ColorConfig}}; |
3 |
| -use swc_ecma_ast::EsVersion; |
| 4 | +use swc_common::{sync::Lrc, SourceMap, errors::{Handler, ColorConfig}, comments::SingleThreadedComments}; |
| 5 | +use swc_ecma_ast::{EsVersion, Module}; |
| 6 | +use swc_ecma_codegen::{text_writer::JsWriter, Emitter}; |
4 | 7 | use swc_ecma_parser::{lexer::Lexer, Syntax, TsConfig, StringInput, Parser};
|
5 |
| -use swc_ecma_visit::VisitWith; |
| 8 | +use swc_ecma_visit::{VisitWith, VisitMutWith}; |
6 | 9 |
|
7 |
| -use crate::{scraper::{Node, Selector, ElementRef}, visitor::AstVisitor}; |
| 10 | +use crate::{scraper::{Node, Selector, ElementRef}, visitor::{AstVisitor, JSXRecord, AstMutVisitor}}; |
8 | 11 |
|
9 | 12 | pub struct JSXDocument {
|
10 |
| - pub tree: Tree<Node> |
| 13 | + pub tree: Tree<Node>, |
| 14 | + pub module: Option<Module>, |
11 | 15 | }
|
12 | 16 |
|
13 | 17 | impl JSXDocument {
|
14 | 18 | pub fn new() -> Self {
|
15 |
| - JSXDocument { tree: Tree::new(Node::Document) } |
| 19 | + JSXDocument { |
| 20 | + tree: Tree::new(Node::Document), |
| 21 | + module: None, |
| 22 | + } |
16 | 23 | }
|
17 | 24 |
|
18 | 25 | pub fn parse(&mut self, jsx: String) {
|
@@ -50,15 +57,36 @@ impl JSXDocument {
|
50 | 57 | e.into_diagnostic(&handler).emit();
|
51 | 58 | }
|
52 | 59 |
|
53 |
| - let module = parser |
| 60 | + let mut module = parser |
54 | 61 | .parse_module()
|
55 | 62 | .map_err(|e| {
|
56 | 63 | e.into_diagnostic(&handler).emit()
|
57 | 64 | })
|
58 | 65 | .expect("failed to parser module");
|
59 |
| - |
60 |
| - let mut vistor = AstVisitor::new(&module, &mut self.tree); |
| 66 | + let mut jsx_record: JSXRecord = HashMap::new(); |
| 67 | + let mut vistor = AstVisitor::new(&module, &mut self.tree, &mut jsx_record); |
61 | 68 | module.visit_with(&mut vistor);
|
| 69 | + let mut mut_visitor = AstMutVisitor::new( &mut jsx_record); |
| 70 | + module.visit_mut_with(&mut mut_visitor); |
| 71 | + // // ast 转代码 |
| 72 | + // let cm = rc::Rc::new(SourceMap::default()); |
| 73 | + // let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(cm.clone())); |
| 74 | + // let comments = SingleThreadedComments::default(); |
| 75 | + |
| 76 | + // let mut buf = Vec::new(); |
| 77 | + // { |
| 78 | + // let writer = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)); |
| 79 | + // let mut emitter = Emitter { |
| 80 | + // cfg: Default::default(), |
| 81 | + // cm: cm.clone(), |
| 82 | + // wr: writer, |
| 83 | + // comments: Some(&comments), |
| 84 | + // }; |
| 85 | + // emitter.emit_module(&module).unwrap(); |
| 86 | + // } |
| 87 | + // let code = String::from_utf8(buf).unwrap(); |
| 88 | + // println!("{}", code); |
| 89 | + self.module = Some(module); |
62 | 90 | }
|
63 | 91 |
|
64 | 92 | pub fn select<'a>(&self, selector: &'a Selector) -> Vec<ElementRef> {
|
|
0 commit comments