svgm-core 0.2.0

SVG optimization engine — fast, safe, fixed-point convergence SVG optimizer
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
use super::{Pass, PassResult};
use crate::ast::{Document, NodeId, NodeKind};
use std::collections::{HashMap, HashSet};

pub struct CleanupIds;

impl Pass for CleanupIds {
    fn name(&self) -> &'static str {
        "cleanupIds"
    }

    fn run(&self, doc: &mut Document) -> PassResult {
        let ids = doc.traverse();

        // Phase 1: Collect all ID declarations
        let mut declarations: HashMap<String, NodeId> = HashMap::new();
        for &id in &ids {
            if let NodeKind::Element(ref elem) = doc.node(id).kind
                && let Some(id_val) = elem.attr("id")
            {
                declarations.insert(id_val.to_string(), id);
            }
        }

        if declarations.is_empty() {
            return PassResult::Unchanged;
        }

        let declared_ids: HashSet<String> = declarations.keys().cloned().collect();

        // Phase 2: Collect all references to IDs
        let mut referenced: HashSet<String> = HashSet::new();

        for &id in &ids {
            let node = doc.node(id);
            match &node.kind {
                NodeKind::Element(elem) => {
                    for attr in &elem.attributes {
                        // url(#id) references in any attribute
                        for r in extract_url_refs(&attr.value) {
                            if declared_ids.contains(&r) {
                                referenced.insert(r);
                            }
                        }

                        // href="#id" or xlink:href="#id"
                        if attr.name == "href"
                            && let Some(r) = extract_href_ref(&attr.value)
                            && declared_ids.contains(r)
                        {
                            referenced.insert(r.to_string());
                        }

                        // SMIL timing: begin="id.click", end="id.end+2s"
                        if attr.name == "begin" || attr.name == "end" {
                            for r in extract_smil_refs(&attr.value, &declared_ids) {
                                referenced.insert(r);
                            }
                        }
                    }
                }
                NodeKind::Text(text) | NodeKind::CData(text) => {
                    // Check if inside <style> element
                    if let Some(parent_id) = node.parent
                        && let NodeKind::Element(ref parent_elem) = doc.node(parent_id).kind
                        && parent_elem.name == "style"
                    {
                        for r in extract_css_id_refs(text, &declared_ids) {
                            referenced.insert(r);
                        }
                    }
                }
                _ => {}
            }
        }

        // Phase 3: Build rename map for referenced IDs
        // Sort by traversal order for deterministic naming
        let mut referenced_ids: Vec<(&String, &NodeId)> = declarations
            .iter()
            .filter(|(name, _)| referenced.contains(name.as_str()))
            .collect();
        referenced_ids.sort_by_key(|(_, node_id)| node_id.0);

        let mut generator = IdGenerator::new();
        let mut rename_map: HashMap<String, String> = HashMap::new();

        for (old_name, _) in &referenced_ids {
            let new_name = generator.next_id();
            if new_name != **old_name {
                rename_map.insert((*old_name).clone(), new_name);
            }
        }

        // Phase 4: Check if there's anything to do
        let unreferenced_count = declarations.len() - referenced.len();
        if unreferenced_count == 0 && rename_map.is_empty() {
            return PassResult::Unchanged;
        }

        // Phase 5: Apply changes
        let mut changed = false;

        for &id in &ids {
            let node = doc.node_mut(id);
            match &mut node.kind {
                NodeKind::Element(elem) => {
                    // Remove unreferenced IDs or rename referenced ones
                    if let Some(id_attr_pos) = elem
                        .attributes
                        .iter()
                        .position(|a| a.name == "id" && a.prefix.is_none())
                    {
                        let id_val = elem.attributes[id_attr_pos].value.clone();
                        if !referenced.contains(&id_val) {
                            // Unreferenced — remove
                            elem.attributes.remove(id_attr_pos);
                            changed = true;
                        } else if let Some(new_name) = rename_map.get(&id_val) {
                            // Referenced — shorten
                            elem.attributes[id_attr_pos].value = new_name.clone();
                            changed = true;
                        }
                    }

                    // Update references in attributes
                    for attr in &mut elem.attributes {
                        // url(#id) references
                        if attr.value.contains("url(#") {
                            let new_val = replace_url_refs(&attr.value, &rename_map);
                            if new_val != attr.value {
                                attr.value = new_val;
                                changed = true;
                            }
                        }

                        // href="#id"
                        if attr.name == "href" && attr.value.starts_with('#') {
                            let old_ref = &attr.value[1..];
                            if let Some(new_name) = rename_map.get(old_ref) {
                                attr.value = format!("#{new_name}");
                                changed = true;
                            }
                        }

                        // SMIL timing
                        if attr.name == "begin" || attr.name == "end" {
                            let new_val = replace_smil_refs(&attr.value, &rename_map);
                            if new_val != attr.value {
                                attr.value = new_val;
                                changed = true;
                            }
                        }
                    }
                }
                NodeKind::Text(text) | NodeKind::CData(text) => {
                    // Update CSS #id references in <style> text nodes
                    if let Some(parent_id) = node.parent {
                        // Can't borrow doc again here, so check parent via ids list
                        // We stored style parents during collect. Use a simpler approach:
                        // just try replacement on all text nodes — replace_css_ids is
                        // a no-op if no matches.
                        let _ = parent_id; // used for context only
                        let new_text = replace_css_ids(text, &rename_map, &declared_ids);
                        if new_text != *text {
                            *text = new_text;
                            changed = true;
                        }
                    }
                }
                _ => {}
            }
        }

        if changed {
            PassResult::Changed
        } else {
            PassResult::Unchanged
        }
    }
}

// --- Reference extraction helpers ---

/// Extract all IDs from `url(#id)` patterns in an attribute value.
fn extract_url_refs(value: &str) -> Vec<String> {
    let mut refs = Vec::new();
    let mut search = value;
    while let Some(start) = search.find("url(#") {
        let rest = &search[start + 5..];
        if let Some(end) = rest.find(')') {
            let id = rest[..end]
                .trim()
                .trim_matches(|c: char| c == '\'' || c == '"');
            if !id.is_empty() {
                refs.push(id.to_string());
            }
        }
        search = &search[start + 5..];
    }
    refs
}

/// Extract an ID from an href="#id" value.
fn extract_href_ref(value: &str) -> Option<&str> {
    let id = value.strip_prefix('#')?;
    if id.is_empty() { None } else { Some(id) }
}

/// Extract IDs from SMIL timing values like "id.click", "id.end+2s".
fn extract_smil_refs(value: &str, known_ids: &HashSet<String>) -> Vec<String> {
    let mut refs = Vec::new();
    for part in value.split(';') {
        let trimmed = part.trim();
        if let Some(dot_pos) = trimmed.find('.') {
            let candidate = &trimmed[..dot_pos];
            if known_ids.contains(candidate) {
                refs.push(candidate.to_string());
            }
        }
    }
    refs
}

/// Extract IDs referenced as CSS selectors (#id) in <style> text.
/// Conservative: checks against known IDs to avoid false positives with hex colors.
fn extract_css_id_refs(text: &str, known_ids: &HashSet<String>) -> Vec<String> {
    let mut refs = Vec::new();
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'#' {
            let start = i + 1;
            let mut end = start;
            while end < bytes.len()
                && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'_' || bytes[end] == b'-')
            {
                end += 1;
            }
            if end > start {
                let candidate = &text[start..end];
                if known_ids.contains(candidate) {
                    refs.push(candidate.to_string());
                }
            }
            i = end;
        } else {
            i += 1;
        }
    }
    refs
}

// --- Reference replacement helpers ---

/// Replace `url(#old_id)` with `url(#new_id)` in an attribute value.
fn replace_url_refs(value: &str, rename_map: &HashMap<String, String>) -> String {
    let mut result = String::with_capacity(value.len());
    let mut search = value;
    while let Some(start) = search.find("url(#") {
        result.push_str(&search[..start + 5]);
        let rest = &search[start + 5..];
        if let Some(end) = rest.find(')') {
            let raw_id = &rest[..end];
            let id = raw_id.trim().trim_matches(|c: char| c == '\'' || c == '"');
            if let Some(new_name) = rename_map.get(id) {
                result.push_str(new_name);
            } else {
                result.push_str(raw_id);
            }
            search = &rest[end..];
        } else {
            result.push_str(rest);
            return result;
        }
    }
    result.push_str(search);
    result
}

/// Replace SMIL timing references: "old_id.click" -> "new_id.click".
fn replace_smil_refs(value: &str, rename_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = value.split(';').collect();
    let mut new_parts = Vec::new();
    let mut any_changed = false;

    for part in parts {
        let trimmed = part.trim();
        if let Some(dot_pos) = trimmed.find('.') {
            let candidate = &trimmed[..dot_pos];
            if let Some(new_name) = rename_map.get(candidate) {
                new_parts.push(format!("{new_name}{}", &trimmed[dot_pos..]));
                any_changed = true;
                continue;
            }
        }
        new_parts.push(trimmed.to_string());
    }

    if any_changed {
        new_parts.join(";")
    } else {
        value.to_string()
    }
}

/// Replace #old_id with #new_id in CSS text, only for known declared IDs.
fn replace_css_ids(
    text: &str,
    rename_map: &HashMap<String, String>,
    declared_ids: &HashSet<String>,
) -> String {
    let bytes = text.as_bytes();
    let mut result = String::with_capacity(text.len());
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'#' {
            let start = i + 1;
            let mut end = start;
            while end < bytes.len()
                && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'_' || bytes[end] == b'-')
            {
                end += 1;
            }
            if end > start {
                let candidate = &text[start..end];
                if let Some(new_name) = rename_map.get(candidate) {
                    result.push('#');
                    result.push_str(new_name);
                    i = end;
                    continue;
                } else if declared_ids.contains(candidate) {
                    // Known ID but not renamed (already short) — keep as-is
                    result.push_str(&text[i..end]);
                    i = end;
                    continue;
                }
            }
            // Not a known ID — keep the # and the text as-is
            result.push('#');
            i = start;
        } else {
            result.push(text[i..].chars().next().unwrap());
            i += text[i..].chars().next().unwrap().len_utf8();
        }
    }

    result
}

// --- ID generator ---

struct IdGenerator {
    counter: usize,
}

impl IdGenerator {
    fn new() -> Self {
        Self { counter: 0 }
    }

    fn next_id(&mut self) -> String {
        let name = encode(self.counter);
        self.counter += 1;
        name
    }
}

/// Bijective base-26 encoding: 0=a, 1=b, ..., 25=z, 26=aa, 27=ab, ..., 51=az, 52=ba, ...
fn encode(mut n: usize) -> String {
    let mut result = Vec::new();
    loop {
        result.push(b'a' + (n % 26) as u8);
        n /= 26;
        if n == 0 {
            break;
        }
        n -= 1;
    }
    result.reverse();
    String::from_utf8(result).unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse;
    use crate::serializer::serialize;

    fn run_pass(input: &str) -> (PassResult, String) {
        let mut doc = parse(input).unwrap();
        let result = CleanupIds.run(&mut doc);
        (result, serialize(&doc))
    }

    // --- ID generator ---

    #[test]
    fn encode_sequence() {
        assert_eq!(encode(0), "a");
        assert_eq!(encode(1), "b");
        assert_eq!(encode(25), "z");
        assert_eq!(encode(26), "aa");
        assert_eq!(encode(27), "ab");
        assert_eq!(encode(51), "az");
        assert_eq!(encode(52), "ba");
        assert_eq!(encode(701), "zz");
        assert_eq!(encode(702), "aaa");
    }

    // --- Unreferenced ID removal ---

    #[test]
    fn removes_unreferenced_id() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><rect id=\"unused\" width=\"10\" height=\"10\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(!output.contains("id="));
        assert!(!output.contains("unused"));
    }

    #[test]
    fn no_change_without_ids() {
        let input =
            "<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"10\" height=\"10\"/></svg>";
        let (result, _) = run_pass(input);
        assert_eq!(result, PassResult::Unchanged);
    }

    // --- url(#id) references ---

    #[test]
    fn shortens_url_referenced_id() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><defs><clipPath id=\"clip0_7441_19649\"><rect width=\"10\" height=\"10\"/></clipPath></defs><rect clip-path=\"url(#clip0_7441_19649)\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(output.contains("id=\"a\""));
        assert!(output.contains("url(#a)"));
        assert!(!output.contains("clip0_7441_19649"));
    }

    #[test]
    fn preserves_and_shortens_multiple_ids() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><defs><clipPath id=\"clip1\"><rect width=\"10\" height=\"10\"/></clipPath><clipPath id=\"clip2\"><rect width=\"20\" height=\"20\"/></clipPath><clipPath id=\"unused\"><rect width=\"5\" height=\"5\"/></clipPath></defs><rect clip-path=\"url(#clip1)\"/><rect clip-path=\"url(#clip2)\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(output.contains("id=\"a\""));
        assert!(output.contains("id=\"b\""));
        assert!(output.contains("url(#a)"));
        assert!(output.contains("url(#b)"));
        // "unused" ID should be removed
        assert!(!output.contains("unused"));
    }

    // --- href references ---

    #[test]
    fn shortens_href_reference() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><defs><symbol id=\"icon\" viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></symbol></defs><use xlink:href=\"#icon\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(output.contains("id=\"a\""));
        assert!(output.contains("href=\"#a\""));
        assert!(!output.contains("icon"));
    }

    #[test]
    fn shortens_plain_href() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><defs><symbol id=\"longname\" viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></symbol></defs><use href=\"#longname\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(output.contains("id=\"a\""));
        assert!(output.contains("href=\"#a\""));
    }

    // --- SMIL timing references ---

    #[test]
    fn shortens_smil_timing_reference() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><rect id=\"target\" width=\"10\" height=\"10\"/><animate begin=\"target.click\" attributeName=\"opacity\" to=\"0\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(output.contains("id=\"a\""));
        assert!(output.contains("begin=\"a.click\""));
    }

    // --- CSS style references ---

    #[test]
    fn shortens_css_id_reference() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><style>#myid{opacity:.5}</style><rect id=\"myid\" width=\"10\" height=\"10\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(output.contains("id=\"a\""));
        assert!(output.contains("#a{"));
    }

    // --- Edge cases ---

    #[test]
    fn already_short_id_no_change() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><defs><clipPath id=\"a\"><rect width=\"10\" height=\"10\"/></clipPath></defs><rect clip-path=\"url(#a)\"/></svg>";
        let (result, _) = run_pass(input);
        assert_eq!(result, PassResult::Unchanged);
    }

    #[test]
    fn multiple_url_refs_in_single_attr() {
        // This is rare but possible in CSS shorthand-like values
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><defs><linearGradient id=\"grad1\"><stop offset=\"0\" stop-color=\"red\"/></linearGradient><linearGradient id=\"grad2\"><stop offset=\"0\" stop-color=\"blue\"/></linearGradient></defs><rect fill=\"url(#grad1)\" stroke=\"url(#grad2)\"/></svg>";
        let (result, output) = run_pass(input);
        assert_eq!(result, PassResult::Changed);
        assert!(output.contains("url(#a)"));
        assert!(output.contains("url(#b)"));
    }

    #[test]
    fn full_optimizer_convergence() {
        let input = "<svg xmlns=\"http://www.w3.org/2000/svg\"><defs><clipPath id=\"clip0_long_name\"><rect width=\"10\" height=\"10\"/></clipPath></defs><rect clip-path=\"url(#clip0_long_name)\"/></svg>";
        let result1 = crate::optimize(input).unwrap();
        let result2 = crate::optimize(&result1.data).unwrap();
        assert_eq!(result1.data, result2.data, "should converge");
    }
}