parse_selectors 2.1.2

minify-selectors' API
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
pub mod markup;
pub mod regexes;
pub mod script;
pub mod style;

use markup::*;
use minify_selectors_utils::*;
use onig::*;
use script::*;
use style::*;




pub fn read_from_css(
	file_string: &mut str,
	selectors: &mut Selectors,
	config: &Config,
) {
	analyse_css(file_string, selectors, config);
}

pub fn write_to_css(
	file_string: &mut String,
	selectors: &Selectors,
	config: &Config,
) {
	rewrite_css(file_string, selectors, config);
}

pub fn read_from_html(
	file_string: &mut str,
	selectors: &mut Selectors,
	config: &Config,
) {
	analyse_html(file_string, selectors, config, None);
}

pub fn write_to_html(
	file_string: &mut String,
	selectors: &Selectors,
	config: &Config,
) {
	rewrite_html(file_string, selectors, config);
}

pub fn read_from_js(
	file_string: &mut str,
	selectors: &mut Selectors,
	config: &Config,
) {
	analyse_js(file_string, selectors, config);
}

pub fn write_to_js(
	file_string: &mut String,
	selectors: &Selectors,
	config: &Config,
) {
	rewrite_js(file_string, selectors, config);
}




pub fn add_selector_to_map(
	selector: &str,
	selectors: &mut Selectors,
	usage: Option<SelectorUsage>,
) {
	selectors.add(selector.to_owned(), usage);
}

/// Fetch replacement encoded selector from selectors hashmap.
// In the event selector has been removed from the mapping because
// it is deemed not worth encoding, leave it as is by returning
// the selector right back.
pub fn get_encoded_selector(
	selector: &str,
	selectors: &Selectors,
) -> Option<String> {
	if let Some(encoded_selector) = selectors.map.get(selector) {
		if encoded_selector.replacement.is_some() {
			encoded_selector.replacement.clone()
		} else {
			None
		}
	} else {
		Some(selector.to_owned())
	}
}

/// Returns an iterator of function arguments.
pub fn get_function_arguments(string: &str) -> FindCaptures {
	regexes::STRING_DELIMITED_BY_COMMA.captures_iter(string)
}

/// Checks if a (minify-selector specific) prefixed selector
/// is used in the given string snippet.
pub fn is_prefixed_selector(string: &str) -> bool {
	regexes::PREFIXED_SELECTORS.find(string).is_some()
}




/// Analyse minify-selectors specific prefixed selectors.
pub fn analyse_prefixed_selectors(
	file_string: &mut str,
	selectors: &mut Selectors,
) {
	for capture in regexes::PREFIXED_SELECTORS.captures_iter(file_string) {
		// "#__ignore--foo", ".__ignore--bar" or "__ignore--baz"
		// Note: no need to add a selector that has been marked as ignore
		// to selectors map.
		if capture.at(2) == Some("ignore") {
			continue;
		}

		let mut indentifier = unescape_css_chars(capture.at(3).unwrap().trim());

		match capture.at(2) {
			// "__class--foo"
			Some("class") => indentifier = format!(".{indentifier}"),
			// "__id--foo"
			Some("id") => indentifier = format!("#{indentifier}"),
			// "#__--foo" or ".__--bar"
			Some(&_) | None => {
				indentifier = format!(
					"{prefix}{name}",
					prefix = capture.at(1).unwrap(),
					name = indentifier,
				)
			},
		}

		add_selector_to_map(&indentifier, selectors, Some(SelectorUsage::Prefix));
	}
}

/// Rewrite minify-selectors specific prefixed selectors.
pub fn rewrite_prefixed_selectors(
	file_string: &mut String,
	selectors: &Selectors,
) {
	*file_string = regexes::PREFIXED_SELECTORS.replace_all(file_string, |capture: &Captures| {
		let mut indentifier = unescape_css_chars(capture.at(3).unwrap().trim());

		match capture.at(2) {
			// "__class--foo"
			Some("class") => {
				indentifier = get_encoded_selector(&format!(".{indentifier}"), selectors)
					.unwrap_or(indentifier);
			},
			// "__id--foo"
			Some("id") => {
				indentifier = get_encoded_selector(&format!("#{indentifier}"), selectors)
					.unwrap_or(indentifier);
			},
			// "#__ignore--foo", ".__ignore--bar" or "__ignore--baz"
			Some("ignore") => {
				indentifier = format!(
					"{prefix}{name}",
					prefix = capture.at(1).unwrap_or(""),
					name = indentifier,
				);
			},
			// "#__--foo" or ".__--bar"
			Some(&_) | None => {
				indentifier = format!(
					"{prefix}{name}",
					prefix = capture.at(1).unwrap(),
					name = get_encoded_selector(
						&format!(
							"{prefix}{name}",
							prefix = capture.at(1).unwrap(),
							name = indentifier,
						),
						selectors,
					)
					.unwrap_or(indentifier)
				);
			},
		}

		indentifier
	});
}

/// Analyse string with tokens delimited by whitespaces.
///
/// Notes:
///  - As regexes::STRING_DELIMITED_BY_SPACE regex is simple - only grouping non
///    whitespace characters together - any quote delimiters will need to be
///    trimmed and added back on afterwards.
///  - context is neseccary in order to determine what the token(s) should be
///    processed as (e.g. class or id).
pub fn analyse_string_of_tokens(
	string: &mut String,
	selectors: &mut Selectors,
	context: &str,
	usage: Option<SelectorUsage>,
) {
	let prefix: &str = match context {
		"class" => ".",
		"id" => "#",
		_ => "",
	};

	// Handle strings that have quote delimiters included.
	let quote_type: &str = match string.chars().next() {
		Some('\'') if string.len() >= 2 => "'",
		Some('"') if string.len() >= 2 => "\"",
		Some('`') if string.len() >= 2 => "`",
		_ => "",
	};

	// Trim quotes (if any) from value capture group.
	if !quote_type.is_empty() {
		string.pop();
		string.remove(0);
	}

	for capture in regexes::STRING_DELIMITED_BY_SPACE.captures_iter(string) {
		// Check if token has a minify-selectors specific prefix,
		// It should be handled with parse_prefixed_selectors().
		if !is_prefixed_selector(capture.at(0).unwrap()) {
			add_selector_to_map(
				&format!(
					"{prefix}{token}",
					prefix = prefix,
					token = unescape_css_chars(capture.at(1).unwrap()),
				),
				selectors,
				usage,
			);
		}
	}
}

/// Rewrite string with tokens delimited by whitespaces.
///
/// Notes:
///  - As regexes::STRING_DELIMITED_BY_SPACE regex is simple - only grouping non
///    whitespace characters together - any quote delimiters will need to be
///    trimmed and added back on afterwards.
///  - context is neseccary in order to determine what the token(s) should be
///    processed as (e.g. class or id).
pub fn rewrite_string_of_tokens(
	string: &mut String,
	selectors: &Selectors,
	context: &str,
) {
	let prefix: &str = match context {
		"class" => ".",
		"id" => "#",
		_ => "",
	};

	// Handle strings that have quote delimiters included.
	let quote_type: &str = match string.chars().next() {
		Some('\'') if string.len() >= 2 => "'",
		Some('"') if string.len() >= 2 => "\"",
		Some('`') if string.len() >= 2 => "`",
		_ => "",
	};

	// Trim quotes (if any) from value capture group.
	if !quote_type.is_empty() {
		string.pop();
		string.remove(0);
	}

	*string = format!(
		"{quote}{tokens}{quote}",
		tokens = regexes::STRING_DELIMITED_BY_SPACE.replace_all(string, |capture: &Captures| {
			// Check if token has a minify-selectors specific prefix,
			// It should be handled with parse_prefixed_selectors().
			if is_prefixed_selector(capture.at(0).unwrap()) {
				return capture.at(0).unwrap().to_string();
			}

			get_encoded_selector(
				&format!(
					"{prefix}{token}",
					prefix = prefix,
					token = unescape_css_chars(capture.at(1).unwrap())
				),
				selectors,
			)
			.unwrap_or_else(|| capture.at(1).unwrap().to_string())
		}),
		quote = quote_type,
	);
}

/// Analyse function arguments, delimited by commas.
///
/// Notes:
///  - context is neseccary in order to determine what the token(s) should be
///    processed as (e.g. class or id).
pub fn analyse_string_of_arguments(
	string: &mut str,
	selectors: &mut Selectors,
	context: &str,
	usage: Option<SelectorUsage>,
) {
	let prefix: &str = match context {
		"class" => ".",
		"id" => "#",
		_ => "",
	};

	for capture in regexes::STRING_DELIMITED_BY_COMMA.captures_iter(string) {
		// Check if argument has a minify-selectors specific prefix,
		// It should be handled with parse_prefixed_selectors().
		if is_prefixed_selector(capture.at(0).unwrap()) {
			continue;
		}

		// String argument
		if capture.at(3).is_some() {
			add_selector_to_map(
				&format!(
					"{prefix}{token}",
					prefix = prefix,
					token = capture.at(3).unwrap(),
				),
				selectors,
				usage,
			);
		}
	}
}

/// Rewrite function arguments, delimited by commas.
///
/// Notes:
///  - context is neseccary in order to determine what the token(s) should be
///    processed as (e.g. class or id).
pub fn rewrite_string_of_arguments(
	string: &mut String,
	selectors: &Selectors,
	context: &str,
) {
	let prefix: &str = match context {
		"class" => ".",
		"id" => "#",
		_ => "",
	};

	*string = regexes::STRING_DELIMITED_BY_COMMA.replace_all(string, |capture: &Captures| {
		// Check if argument has a minify-selectors specific prefix,
		// It should be handled with parse_prefixed_selectors().
		if is_prefixed_selector(capture.at(0).unwrap()) {
			return capture.at(0).unwrap().to_string();
		}

		// Check if argument is a string, variable/expression or object/array.
		//   - 1: simple string argument (token string and delimiters)
		//       - 2: token delimiter
		//       - 3: token string
		//   - 4: variable or expression argument
		//   - 5: object argument
		//   - 6: array argument
		if capture.at(3).is_some() {
			format!(
				"{quote}{argument}{quote}",
				argument = get_encoded_selector(
					&format!(
						"{prefix}{token}",
						prefix = prefix,
						token = capture.at(3).unwrap(),
					),
					selectors,
				)
				.unwrap_or_else(|| capture.at(3).unwrap().to_string()),
				quote = capture.at(2).unwrap(),
			)
		// TODO:
		//} else if capture.at(4).is_some() {
		//	return capture.at(0).unwrap().to_string();
		} else {
			// Capture group 5 (<object>) or 6 (<array>) .is_some() evaluates to true
			// or another case. Either way nothing needs to be done to this argument.
			return capture.at(0).unwrap().to_string();
		}
	});
}

// Analyse target IDs in anchor link URLs.
pub fn analyse_anchor_links(
	string: &mut String,
	selectors: &mut Selectors,
) {
	// Handle strings that have quote delimiters included.
	let quote_type: &str = match string.chars().next() {
		Some('\'') => "'",
		Some('"') => "\"",
		Some('`') => "`",
		_ => "",
	};

	// Trim quotes (if any).
	if !quote_type.is_empty() {
		string.pop();
		string.remove(0);
	}

	for capture in regexes::INTERNAL_ANCHOR_TARGET_ID.captures_iter(string) {
		if capture.at(1).is_none() {
			continue;
		}

		add_selector_to_map(
			&unescape_js_chars(capture.at(2).unwrap()),
			selectors,
			Some(SelectorUsage::Anchor),
		);
	}
}

// Rewrite target IDs in anchor link URLs.
pub fn rewrite_anchor_links(
	string: &mut String,
	selectors: &Selectors,
) {
	// Handle strings that have quote delimiters included.
	let quote_type: &str = match string.chars().next() {
		Some('\'') => "'",
		Some('"') => "\"",
		Some('`') => "`",
		_ => "",
	};

	// Trim quotes (if any).
	if !quote_type.is_empty() {
		string.pop();
		string.remove(0);
	}

	*string = format!(
		"{quote}{url}{quote}",
		url = regexes::INTERNAL_ANCHOR_TARGET_ID.replace(string, |capture: &Captures| {
			if capture.at(1).is_none() {
				return capture.at(0).unwrap().to_string();
			}

			format!(
				"{url}#{target_id}",
				url = capture.at(1).unwrap_or(""),
				target_id =
					get_encoded_selector(&unescape_js_chars(capture.at(2).unwrap()), selectors,)
						.unwrap_or_else(|| capture.at(2).unwrap().to_string()),
			)
		}),
		quote = quote_type,
	);
}