|
| 1 | +use regex::Regex; |
| 2 | +use serde::Deserialize; |
| 3 | +use swc_ecmascript::ast::*; |
| 4 | +use swc_ecmascript::visit::{noop_fold_type, Fold, FoldWith}; |
| 5 | + |
| 6 | +#[derive(Clone, Debug, Deserialize)] |
| 7 | +#[serde(untagged)] |
| 8 | +pub enum Config { |
| 9 | + All(bool), |
| 10 | + WithOptions(Options), |
| 11 | +} |
| 12 | + |
| 13 | +impl Config { |
| 14 | + pub fn truthy(&self) -> bool { |
| 15 | + match self { |
| 16 | + Config::All(b) => *b, |
| 17 | + Config::WithOptions(_) => true, |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +#[derive(Clone, Debug, Deserialize)] |
| 23 | +pub struct Options { |
| 24 | + #[serde(default)] |
| 25 | + pub properties: Vec<String>, |
| 26 | +} |
| 27 | + |
| 28 | +struct RemoveProperties { |
| 29 | + properties: Vec<Regex>, |
| 30 | +} |
| 31 | + |
| 32 | +impl RemoveProperties { |
| 33 | + fn should_remove_property(&self, name: &str) -> bool { |
| 34 | + self.properties.iter().any(|p| p.is_match(name)) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl Fold for RemoveProperties { |
| 39 | + noop_fold_type!(); |
| 40 | + |
| 41 | + fn fold_jsx_opening_element(&mut self, mut el: JSXOpeningElement) -> JSXOpeningElement { |
| 42 | + el.attrs.retain(|attr| match attr { |
| 43 | + JSXAttrOrSpread::JSXAttr(JSXAttr { |
| 44 | + name: JSXAttrName::Ident(ident), |
| 45 | + .. |
| 46 | + }) if self.should_remove_property(ident.sym.as_ref()) => false, |
| 47 | + _ => true, |
| 48 | + }); |
| 49 | + el.fold_children_with(self) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +pub fn remove_properties(config: Config) -> impl Fold { |
| 54 | + let mut properties: Vec<Regex> = match config { |
| 55 | + Config::WithOptions(x) => x |
| 56 | + .properties |
| 57 | + .iter() |
| 58 | + .map(|pattern| { |
| 59 | + Regex::new(pattern).unwrap_or_else(|e| { |
| 60 | + panic!("error compiling property regex `{}`: {}", pattern, e); |
| 61 | + }) |
| 62 | + }) |
| 63 | + .collect(), |
| 64 | + _ => vec![], |
| 65 | + }; |
| 66 | + if properties.is_empty() { |
| 67 | + // Keep the default regex identical to `babel-plugin-react-remove-properties`. |
| 68 | + properties.push(Regex::new(r"^data-test").unwrap()); |
| 69 | + } |
| 70 | + let remover = RemoveProperties { properties }; |
| 71 | + remover |
| 72 | +} |
0 commit comments