Skip to content

Commit

Permalink
chore: 优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
luckyadam committed Oct 16, 2023
1 parent 644a0d3 commit 43b415d
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 97 deletions.
15 changes: 8 additions & 7 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@ use std::collections::HashMap;

use selectors::attr::CaseSensitivity;
use swc_common::{
comments::SingleThreadedComments,
errors::{ColorConfig, Handler},
sync::Lrc,
SourceMap, Mark, comments::SingleThreadedComments, Globals, GLOBALS,
Globals, Mark, SourceMap, GLOBALS,
};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsConfig};
use swc_ecma_visit::{VisitWith, FoldWith, VisitAllWith};
use swc_ecma_transforms_base::{fixer::fixer, hygiene::hygiene, resolver};
use swc_ecma_visit::{FoldWith, VisitAllWith, VisitWith};
use swc_ecmascript::transforms::typescript::strip;

use crate::{
scraper::Element,
visitor::{AstVisitor, JSXRecord, CollectVisitor},
visitor::{AstVisitor, CollectVisitor, JSXRecord},
};

pub struct JSXDocument {
Expand Down Expand Up @@ -53,10 +54,10 @@ impl JSXDocument {
e.into_diagnostic(&handler).emit();
}
let program = parser
.parse_program()
.map_err(|e| e.into_diagnostic(&handler).emit())
.expect("解析 JSX 失败");
.parse_program()
.map_err(|e| e.into_diagnostic(&handler).emit())
.expect("解析 JSX 失败");

let globals = Globals::default();
GLOBALS.set(&globals, || {
let unresolved_mark = Mark::new();
Expand Down
9 changes: 7 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::{cell::RefCell, rc::Rc};

use swc_common::{comments::SingleThreadedComments, SourceMap, sync::Lrc};
use swc_common::{comments::SingleThreadedComments, sync::Lrc, SourceMap};
use swc_ecma_codegen::{text_writer::JsWriter, Emitter};

use crate::{document::JSXDocument, style_parser::StyleParser, style_write::StyleWrite};
Expand Down Expand Up @@ -33,7 +33,12 @@ pub fn parse(component: String, styles: Vec<String>) -> String {

let program = Rc::new(RefCell::new(document.program.as_ref().unwrap().clone()));
let jsx_record = Rc::new(RefCell::new(document.jsx_record.as_ref().unwrap().clone()));
let mut style_write = StyleWrite::new(program.clone(), jsx_record.clone(), style_data.style_record.clone(), style_data.all_style.clone());
let mut style_write = StyleWrite::new(
program.clone(),
jsx_record.clone(),
style_data.style_record.clone(),
style_data.all_style.clone(),
);
style_write.write();

// ast 转代码
Expand Down
45 changes: 29 additions & 16 deletions src/scraper.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
// inpired by https://github.com/causal-agent/scraper

use core::fmt;
use std::{cell::OnceCell, collections::HashMap, ops::Deref, slice::Iter as SliceIter, collections::hash_map::Iter as HashMapIter};
use std::{
cell::OnceCell, collections::hash_map::Iter as HashMapIter, collections::HashMap, ops::Deref,
slice::Iter as SliceIter,
};

use html5ever::{QualName, tendril::StrTendril, LocalName, Attribute};
use html5ever::{tendril::StrTendril, Attribute, LocalName, QualName};
use selectors::attr::CaseSensitivity;

use crate::visitor::SpanKey;

pub struct Classes<'a> {
inner: SliceIter<'a, LocalName>
inner: SliceIter<'a, LocalName>,
}

impl<'a> Iterator for Classes<'a> {
Expand All @@ -23,7 +26,7 @@ pub type AttributesIter<'a> = HashMapIter<'a, QualName, StrTendril>;

#[derive(Debug, Clone)]
pub struct Attrs<'a> {
inner: AttributesIter<'a>
inner: AttributesIter<'a>,
}

impl<'a> Iterator for Attrs<'a> {
Expand All @@ -41,7 +44,7 @@ pub struct Element {
pub attrs: Attributes,
pub span: SpanKey,
id: OnceCell<Option<StrTendril>>,
classes: OnceCell<Vec<LocalName>>
classes: OnceCell<Vec<LocalName>>,
}

impl Element {
Expand All @@ -55,7 +58,7 @@ impl Element {
span,
attrs,
id: OnceCell::new(),
classes: OnceCell::new()
classes: OnceCell::new(),
}
}

Expand All @@ -64,22 +67,28 @@ impl Element {
}

pub fn id(&self) -> Option<&str> {
self.id.get_or_init(|| {
self.attrs
.iter()
.find(|(name,_ )| name.local.as_ref() == "id")
.map(|(_, value)| value.clone())
}).as_deref()
self
.id
.get_or_init(|| {
self
.attrs
.iter()
.find(|(name, _)| name.local.as_ref() == "id")
.map(|(_, value)| value.clone())
})
.as_deref()
}

pub fn has_class(&self, class: &str, case_sensitive: CaseSensitivity) -> bool {
self.classes()
self
.classes()
.any(|class_name| case_sensitive.eq(class.as_bytes(), class_name.as_bytes()))
}

pub fn classes(&self) -> Classes {
let classes = self.classes.get_or_init(|| {
let mut classes: Vec<LocalName> = self.attrs
let mut classes: Vec<LocalName> = self
.attrs
.iter()
.filter(|(name, _)| name.local.as_ref() == "className")
.flat_map(|(_, value)| value.split_whitespace().map(LocalName::from))
Expand All @@ -89,11 +98,15 @@ impl Element {
classes
});

Classes { inner: classes.iter() }
Classes {
inner: classes.iter(),
}
}

pub fn attrs(&self) -> Attrs {
Attrs { inner: self.attrs.iter() }
Attrs {
inner: self.attrs.iter(),
}
}
}

Expand Down
13 changes: 10 additions & 3 deletions src/style_parser.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{cell::RefCell, collections::HashMap, convert::Infallible, rc::Rc, hash::Hash};
use std::{cell::RefCell, collections::HashMap, convert::Infallible, hash::Hash, rc::Rc};

use lightningcss::{
declaration::DeclarationBlock,
Expand Down Expand Up @@ -96,11 +96,18 @@ impl<'i> StyleParser<'i> {

pub fn parse(&mut self, css: &'i str) {
let mut stylesheet = StyleSheet::parse(css, ParserOptions::default()).expect("解析样式失败");
let mut style_visitor = StyleVisitor::new(self.document, Rc::clone(&self.style_record), Rc::clone(&self.all_style));
let mut style_visitor = StyleVisitor::new(
self.document,
Rc::clone(&self.style_record),
Rc::clone(&self.all_style),
);
stylesheet.visit(&mut style_visitor).unwrap();
}

fn calc_style_record<T: Hash + Eq + Clone>(&self, style_record: &mut HashMap<T, Vec<StyleDeclaration<'i>>>) -> HashMap<T, StyleDeclaration<'i>> {
fn calc_style_record<T: Hash + Eq + Clone>(
&self,
style_record: &mut HashMap<T, Vec<StyleDeclaration<'i>>>,
) -> HashMap<T, StyleDeclaration<'i>> {
let mut final_style_record = HashMap::new();
for (id, declarations) in style_record.iter_mut() {
declarations.sort_by(|a, b| a.specificity.cmp(&b.specificity));
Expand Down
6 changes: 5 additions & 1 deletion src/style_write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ impl<'i> StyleWrite<'i> {
}

pub fn write(&mut self) {
let mut style_visitor = AstMutVisitor::new(self.jsx_record.clone(), self.style_record.clone(), self.all_style.clone());
let mut style_visitor = AstMutVisitor::new(
self.jsx_record.clone(),
self.style_record.clone(),
self.all_style.clone(),
);
self.module.borrow_mut().visit_mut_with(&mut style_visitor);
}
}
Loading

0 comments on commit 43b415d

Please sign in to comment.