rspack_style 0.1.16

a rust toolkit bundled for front-end style files
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
use crate::extend::string::StringExtend;
use crate::style_core::extension::StyleExtension;
use crate::style_core::filenode::StyleFileNode;
use crate::style_core::option::ParseOption;
use crate::util::file::get_dir;
use crate::util::hash::StyleHash;
use crate::util::str_enum::StringToEnum;
use serde_json::{Map, Value};
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter};
use std::path::Path;
use std::rc::Rc;
use std::sync::{Arc, Mutex, Weak};

pub type ParseCacheMap = Mutex<HashMap<String, String>>;

pub type ParseContext = Arc<Mutex<Context>>;

pub type RenderCacheMap = Mutex<HashMap<String, String>>;

///
/// 全局调用 转化时的 上下文
///
pub struct Context {
  // 内部调用方式时 需要拿到对应的 转化配置
  pub option: ParseOption,
  // 转文件 的缓存
  pub filecache: ParseCacheMap,
  // 渲染结果 的缓存
  pub render_cache: RenderCacheMap,
  // 文件的绝对路径 入口文件
  pub application_fold: String,
  // 已经生成目录的 文件
  pub code_gen_file_path: Vec<String>,
  // 自身的弱引用
  pub weak_ref: Option<Weak<Mutex<Context>>>,
}

impl Debug for Context {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("Context")
      .field("option", &self.option)
      .field("entry", &self.application_fold)
      .field("filepaths", &self.code_gen_file_path)
      .finish()
  }
}

impl Context {
  ///
  /// 创建全局应用 共享上下文
  ///
  pub fn new(
    option: ParseOption,
    application_fold: Option<String>,
  ) -> Result<Arc<Mutex<Self>>, String> {
    let mut fold = application_fold.unwrap_or_else(|| {
      std::env::current_dir()
        .unwrap()
        .into_os_string()
        .into_string()
        .unwrap()
    });
    let filepath = Path::new(&fold);
    if filepath.exists() {
      if filepath.is_absolute() {
        if filepath.is_file() {
          let current_dir = get_dir(&fold)?;
          fold = current_dir
        } else if !filepath.is_dir() {
          return Err(format!("application_fold is not file or dir,{}", fold));
        }
      } else {
        return Err(format!(
          "application_fold is must absolutely path ,{}",
          fold
        ));
      }
    } else {
      return Err(format!("application_fold is not exists,{}", fold));
    }
    let mut obj = Context {
      option,
      filecache: Mutex::new(HashMap::new()),
      render_cache: Mutex::new(HashMap::new()),
      application_fold: fold.clone(),
      code_gen_file_path: vec![],
      weak_ref: None,
    };
    obj.set_include_paths(vec![fold]);
    let heap_obj = Arc::new(Mutex::new(obj));
    {
      let mut self_value = heap_obj.try_lock().unwrap();
      self_value.weak_ref = Some(Arc::downgrade(&heap_obj));
    }
    Ok(heap_obj)
  }

  ///
  /// 查询 缓存上 翻译结果
  ///
  pub fn get_parse_cache(&self, file_path: &str) -> Result<Option<StyleFileNode>, String> {
    self.recovery_parse_object(file_path)
  }

  ///
  /// 添加 缓存上 翻译结果
  ///
  pub fn set_parse_cache(&mut self, file_path: &str, file_info_json: String) {
    let mut filecache = self.filecache.lock().unwrap();
    let res = filecache.get(file_path);
    if res.is_none() {
      filecache.insert(file_path.to_string(), file_info_json);
    }
  }

  ///
  /// 清除 parse cache
  /// 由于现在 缓存的是 指针 只能 单次 transform 同一个文件多次使用
  ///
  pub fn clear_parse_cache(&mut self) {
    self.filecache.lock().unwrap().clear();
  }

  ///
  /// 获取选项
  ///
  pub fn get_options(&self) -> ParseOption {
    self.option.clone()
  }

  ///
  /// 安全设置 include-path
  ///
  pub fn set_include_paths(&mut self, paths: Vec<String>) {
    paths.iter().for_each(|x| {
      if !self.option.include_path.contains(x) {
        self.option.include_path.push(x.clone());
      }
    });
  }

  ///
  /// 增加一个css transform 下 @import 引用生成的记录
  ///
  pub fn add_codegen_record(&mut self, path: &str) {
    self.code_gen_file_path.push(path.to_string());
  }

  ///
  /// 清除本次 codegen 文件的记录
  ///
  pub fn clear_codegen_record(&mut self) {
    self.code_gen_file_path.clear();
  }

  ///
  /// 是否已经生成过 该文件
  ///
  pub fn has_codegen_record(&self, path: &str) -> bool {
    self.code_gen_file_path.contains(&path.to_string())
  }

  ///
  /// 插入 生成 样式文件的缓存
  ///
  pub fn add_render_cache(&mut self, filepath: &str, source: &str) {
    self
      .render_cache
      .lock()
      .unwrap()
      .insert(filepath.to_string(), source.to_string());
  }

  ///
  /// 清除本次 codegen 文件的记录
  ///
  pub fn clear_render_cache(&mut self) {
    self.render_cache.lock().unwrap().clear();
  }

  ///
  /// 获取 codegen 缓存 目标样式代码
  ///
  pub fn get_render_cache(&self, filepath: &str) -> Option<String> {
    self.render_cache.lock().unwrap().get(filepath).cloned()
  }

  ///
  /// 生成默认上下文
  ///
  pub fn default() -> ParseContext {
    Self::new(Default::default(), None).unwrap()
  }

  ///
  /// 递归恢复 json 上下文
  ///
  pub fn recovery_parse_object(&self, key: &str) -> Result<Option<StyleFileNode>, String> {
    let filecache = self.filecache.lock().unwrap();
    let json_res = filecache.get(key);
    if let Some(json) = json_res {
      let root: HashMap<String, Value> = serde_json::from_str(json).unwrap();
      return if let Some(Value::Object(map)) = root.get("info") {
        let node = self.deserializer(map)?;
        Ok(Some(node))
      } else {
        Err("info value is empty!".to_string())
      };
    }
    Ok(None)
  }

  ///
  /// 递归调用 json 反序列化 自制方法
  ///
  fn deserializer(&self, map: &Map<String, Value>) -> Result<StyleFileNode, String> {
    let json_disk_location = map.get("disk_location");
    let json_origin_txt_content = map.get("origin_txt_content");
    let disk_location = if let Some(Value::String(disk_location)) = json_disk_location {
      disk_location.to_string()
    } else {
      return Err("deserializer FileNode -> disk_location is empty!".to_string());
    };
    let ext_str_value = Path::new(disk_location.as_str())
      .extension()
      .unwrap()
      .to_str()
      .unwrap();
    let ext = ext_str_value
      .to_string()
      .to_enum::<StyleExtension>()
      .unwrap();
    let resolve_extension = ext;

    match resolve_extension {
      StyleExtension::Css => {
        let mut obj = crate::css::fileinfo::FileInfo {
          disk_location,
          block_node: vec![],
          origin_txt_content: "".to_string(),
          origin_charlist: vec![],
          locmap: None,
          context: self.weak_ref.as_ref().unwrap().upgrade().unwrap(),
          self_weak: None,
          import_files: vec![],
          modules: false,
          class_selector_collect: Default::default(),
          hash_perfix: "".to_string(),
          resolve_extension,
        };
        if let Some(value) = map.get("class_selector_collect") {
          let class_selector_collect = value
            .as_array()
            .unwrap()
            .iter()
            .map(|x| x.as_str().unwrap().to_string())
            .collect::<Vec<String>>();
          let mut set = HashSet::new();
          for item in class_selector_collect {
            set.insert(item);
          }
          obj.class_selector_collect = set;
        }
        let need_modules = crate::css::filenode::FileNode::is_need_css_modules(
          obj.disk_location.as_str(),
          self.option.modules,
        );
        obj.modules = need_modules;
        if let Some(Value::String(origin_txt_content)) = json_origin_txt_content {
          obj.origin_txt_content = origin_txt_content.to_string();
          obj.hash_perfix =
            StyleHash::generate_css_module_hash(&obj.disk_location, origin_txt_content);
          obj.origin_charlist = obj.origin_txt_content.to_char_vec();
        } else {
          return Err("deserializer FileNode -> origin_txt_content is empty!".to_string());
        }

        if self.option.sourcemap {
          obj.locmap = Some(crate::css::fileinfo::FileInfo::get_loc_by_content(
            &obj.origin_charlist,
          ));
        }
        let json_import_files = map.get("import_file");
        if let Some(Value::Array(disk_location)) = json_import_files {
          for json_item in disk_location {
            if let Value::Object(json_import_file_node) = json_item {
              let import_info = json_import_file_node
                .get("info")
                .unwrap()
                .as_object()
                .unwrap();
              let import_info_obj = self.deserializer(import_info)?;
              if let StyleFileNode::Css(css_node) = import_info_obj {
                obj.import_files.push(css_node);
              }
            }
          }
        }

        let info = obj.toheap();
        let json_block_node = map.get("block_node");
        let mut block_node_recovery_list = vec![];
        if let Some(Value::Array(block_nodes)) = json_block_node {
          for json_node in block_nodes {
            if let Value::Object(json_stylenode) = json_node {
              block_node_recovery_list.push(crate::css::node::StyleNode::deserializer(
                json_stylenode,
                self.weak_ref.as_ref().unwrap().upgrade().unwrap().clone(),
                None,
                Some(Rc::downgrade(&info)),
              )?);
            }
          }
        }
        info.borrow_mut().block_node = block_node_recovery_list;
        let node = crate::css::filenode::FileNode { info };

        Ok(StyleFileNode::Css(node))
      }
      StyleExtension::Less => {
        let mut obj = crate::less::fileinfo::FileInfo {
          disk_location,
          block_node: vec![],
          origin_txt_content: "".to_string(),
          origin_charlist: vec![],
          locmap: None,
          context: self.weak_ref.as_ref().unwrap().upgrade().unwrap(),
          self_weak: None,
          import_files: vec![],
          modules: false,
          class_selector_collect: Default::default(),
          hash_perfix: "".to_string(),
          resolve_extension,
        };

        if let Some(value) = map.get("class_selector_collect") {
          let class_selector_collect = value
            .as_array()
            .unwrap()
            .iter()
            .map(|x| x.as_str().unwrap().to_string())
            .collect::<Vec<String>>();
          let mut set = HashSet::new();
          for item in class_selector_collect {
            set.insert(item);
          }
          obj.class_selector_collect = set;
        }
        let need_modules = crate::less::filenode::FileNode::is_need_css_modules(
          obj.disk_location.as_str(),
          self.option.modules,
        );
        obj.modules = need_modules;
        if let Some(Value::String(origin_txt_content)) = json_origin_txt_content {
          obj.origin_txt_content = origin_txt_content.to_string();
          obj.hash_perfix =
            StyleHash::generate_css_module_hash(&obj.disk_location, origin_txt_content);
          obj.origin_charlist = obj.origin_txt_content.to_char_vec();
        } else {
          return Err("deserializer FileNode -> origin_txt_content is empty!".to_string());
        }

        if self.option.sourcemap {
          obj.locmap = Some(crate::less::fileinfo::FileInfo::get_loc_by_content(
            &obj.origin_charlist,
          ));
        }
        let json_import_files = map.get("import_file");
        if let Some(Value::Array(disk_location)) = json_import_files {
          for json_item in disk_location {
            if let Value::Object(json_import_file_node) = json_item {
              let import_info = json_import_file_node
                .get("value")
                .unwrap()
                .as_object()
                .unwrap()
                .get("info")
                .unwrap()
                .as_object()
                .unwrap();
              obj.import_files.push(self.deserializer(import_info)?);
            }
          }
        }

        let info = obj.toheap();
        let json_block_node = map.get("block_node");
        let mut block_node_recovery_list = vec![];
        if let Some(Value::Array(block_nodes)) = json_block_node {
          for json_node in block_nodes {
            if let Value::Object(json_stylenode) = json_node {
              block_node_recovery_list.push(crate::less::node::StyleNode::deserializer(
                json_stylenode,
                self.weak_ref.as_ref().unwrap().upgrade().unwrap().clone(),
                None,
                Some(Rc::downgrade(&info)),
              )?);
            }
          }
        }
        info.borrow_mut().block_node = block_node_recovery_list;
        let node = crate::less::filenode::FileNode { info };
        Ok(StyleFileNode::Less(node))
      }
      StyleExtension::Sass => Err("*.sass has not support!".to_string()),
      StyleExtension::Scss => Err("*.scss has not support!".to_string()),
    }
  }
}