seam-skeleton 0.5.38

HTML skeleton extraction pipeline for SeamJS CLI
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
/* src/cli/skeleton/src/extract/array.rs */

use std::collections::HashSet;

use super::boolean::insert_boolean_directives;
use super::combo::AxisGroup;
use super::container::{hoist_list_container, is_list_container, unwrap_container_tree};
use super::directives::{comment_each, comment_else, comment_endeach, comment_endif, comment_if};
use super::dom::{DomNode, parse_html, serialize};
use super::tree_diff::{DiffOp, diff_children};
use super::variant::{find_pair_for_axis, find_scoped_variant_indices};
use super::{
	Axis, content_indices, extract_template_inner, navigate_to_children, nth_content_index,
	rename_slot_markers,
};

/// Process a single array axis (without nested children):
/// insert each/endeach directives, rename slot markers, unwrap container.
pub(super) fn process_array(
	result: Vec<DomNode>,
	axes: &[Axis],
	variants: &[String],
	axis_idx: usize,
) -> Vec<DomNode> {
	let axis = &axes[axis_idx];
	let pair = find_pair_for_axis(axes, variants.len(), axis_idx);
	let Some((vi_pop, vi_empty)) = pair else {
		return result;
	};

	let tree_pop = parse_html(&variants[vi_pop]);
	let tree_empty = parse_html(&variants[vi_empty]);

	insert_array_directives(result, &tree_pop, &tree_empty, &axis.path)
}

/// Insert array directives (each/endeach) by comparing populated vs empty trees.
fn insert_array_directives(
	tree: Vec<DomNode>,
	pop_nodes: &[DomNode],
	empty_nodes: &[DomNode],
	path: &str,
) -> Vec<DomNode> {
	let ops = diff_children(pop_nodes, empty_nodes);

	// Collect body nodes (OnlyLeft in populated) and replacement nodes (OnlyRight in empty)
	let mut body_indices: Vec<usize> = Vec::new();
	let mut has_only_right = false;
	let mut has_modified = false;

	for op in &ops {
		match op {
			DiffOp::OnlyLeft(ai) => body_indices.push(*ai),
			DiffOp::OnlyRight(_) => has_only_right = true,
			DiffOp::Modified(_, _) => has_modified = true,
			DiffOp::Identical(_, _) => {}
		}
	}

	// If content only differs inside a shared element, recurse
	if body_indices.is_empty() && has_modified {
		return insert_array_modified(tree, pop_nodes, empty_nodes, path);
	}

	// If there's only a replacement (OnlyLeft + OnlyRight at same position), treat
	// the entire region as a conditional with if/else semantics for the array
	if body_indices.is_empty() && has_only_right {
		// Fall back to treating as boolean-like diff
		return insert_boolean_directives(&tree, pop_nodes, empty_nodes, path);
	}

	if body_indices.is_empty() {
		return tree;
	}

	// Extract body nodes and rename slot markers
	let mut body: Vec<DomNode> = body_indices.iter().map(|&i| pop_nodes[i].clone()).collect();
	rename_slot_markers(&mut body, path);

	// Container unwrap + each/endeach wrapping
	let each_nodes = wrap_array_body(&body, path);

	// If empty variant has replacement content, wrap each in if/else
	let final_nodes = if has_only_right {
		let fallback: Vec<DomNode> = ops
			.iter()
			.filter_map(|op| match op {
				DiffOp::OnlyRight(bi) => Some(empty_nodes[*bi].clone()),
				_ => None,
			})
			.collect();

		let mut nodes = vec![comment_if(path)];
		nodes.extend(each_nodes);
		nodes.push(comment_else());
		nodes.extend(fallback);
		nodes.push(comment_endif(path));
		nodes
	} else {
		each_nodes
	};

	// Build result: copy content map approach
	let content_map = content_indices(&tree);

	let mut result = Vec::new();
	let mut tree_content_idx = 0usize;
	let mut tree_pos = 0usize;

	for op in &ops {
		// Copy leading directives
		let target =
			if tree_content_idx < content_map.len() { content_map[tree_content_idx] } else { tree.len() };
		while tree_pos < target {
			result.push(tree[tree_pos].clone());
			tree_pos += 1;
		}

		match op {
			DiffOp::Identical(_, _) => {
				result.push(tree[tree_pos].clone());
				tree_pos += 1;
				tree_content_idx += 1;
			}
			DiffOp::OnlyLeft(ai) => {
				// First body node gets the final_nodes, rest are consumed
				if *ai == body_indices[0] {
					result.extend(final_nodes.iter().cloned());
				}
				tree_pos += 1;
				tree_content_idx += 1;
			}
			DiffOp::OnlyRight(_) => {
				// Empty variant's extra content — skip (replaced by array when populated)
			}
			DiffOp::Modified(_, _) => {
				result.push(tree[tree_pos].clone());
				tree_pos += 1;
				tree_content_idx += 1;
			}
		}
	}

	while tree_pos < tree.len() {
		result.push(tree[tree_pos].clone());
		tree_pos += 1;
	}

	result
}

/// Handle array where the diff is inside a shared parent element (Modified case).
fn insert_array_modified(
	mut tree: Vec<DomNode>,
	pop_nodes: &[DomNode],
	empty_nodes: &[DomNode],
	path: &str,
) -> Vec<DomNode> {
	let ops = diff_children(pop_nodes, empty_nodes);
	for op in ops {
		if let DiffOp::Modified(ai, bi) = op
			&& let (DomNode::Element { children: pc, .. }, DomNode::Element { children: ec, .. }) =
				(&pop_nodes[ai], &empty_nodes[bi])
		{
			// Find corresponding tree node (skip directive comments)
			if let Some(ti) = nth_content_index(&tree, ai)
				&& let DomNode::Element { children: tc, .. } = &mut tree[ti]
			{
				*tc = insert_array_directives(std::mem::take(tc), pc, ec, path);
			}
		}
	}
	tree
}

/// Wrap array body nodes with each/endeach, unwrapping container if applicable.
fn wrap_array_body(body: &[DomNode], path: &str) -> Vec<DomNode> {
	// Descend through a single wrapper to preserve static table shell around repeated rows.
	if body.len() == 1
		&& let Some(wrapped) = wrap_single_body_node(&body[0], path)
	{
		return vec![wrapped];
	}

	// Simple case: single list container
	if let Some((tag, attrs, inner)) = unwrap_container_tree(body) {
		let mut inner_with_directives = vec![comment_each(path)];
		inner_with_directives.extend(inner.iter().cloned());
		inner_with_directives.push(comment_endeach());
		return vec![DomNode::Element {
			tag: tag.to_string(),
			attrs: attrs.to_string(),
			children: inner_with_directives,
			self_closing: false,
		}];
	}

	// Hoist case: directive comments wrap identical list containers
	if let Some((tag, attrs, inner)) = hoist_list_container(body) {
		let mut inner_with_directives = vec![comment_each(path)];
		inner_with_directives.extend(inner);
		inner_with_directives.push(comment_endeach());
		return vec![DomNode::Element {
			tag: tag.clone(),
			attrs: attrs.clone(),
			children: inner_with_directives,
			self_closing: false,
		}];
	}

	// No container unwrap
	let mut nodes = vec![comment_each(path)];
	nodes.extend(body.iter().cloned());
	nodes.push(comment_endeach());
	nodes
}

fn wrap_single_body_node(node: &DomNode, path: &str) -> Option<DomNode> {
	match node {
		DomNode::Element { tag, attrs, children, self_closing: false } => {
			if tag == "table" {
				return wrap_table_body(tag, attrs, children, path);
			}

			if is_list_container(tag) {
				let mut inner_with_directives = vec![comment_each(path)];
				inner_with_directives.extend(children.iter().cloned());
				inner_with_directives.push(comment_endeach());
				return Some(DomNode::Element {
					tag: tag.clone(),
					attrs: attrs.clone(),
					children: inner_with_directives,
					self_closing: false,
				});
			}

			let mut target_idx: Option<usize> = None;
			let mut wrapped_child: Option<DomNode> = None;
			for (idx, child) in children.iter().enumerate() {
				if let Some(candidate) = wrap_single_body_node(child, path) {
					if target_idx.is_some() {
						return None;
					}
					target_idx = Some(idx);
					wrapped_child = Some(candidate);
				}
			}

			if let (Some(idx), Some(child)) = (target_idx, wrapped_child) {
				let mut new_children = children.clone();
				new_children[idx] = child;
				return Some(DomNode::Element {
					tag: tag.clone(),
					attrs: attrs.clone(),
					children: new_children,
					self_closing: false,
				});
			}

			None
		}
		_ => None,
	}
}

fn wrap_table_body(tag: &str, attrs: &str, children: &[DomNode], path: &str) -> Option<DomNode> {
	let tbody_indices: Vec<usize> = children
		.iter()
		.enumerate()
		.filter_map(|(idx, child)| match child {
			DomNode::Element { tag, self_closing: false, .. } if tag == "tbody" => Some(idx),
			_ => None,
		})
		.collect();

	if tbody_indices.len() != 1 {
		return None;
	}

	let tbody_idx = tbody_indices[0];
	let mut new_children = children.to_vec();
	if let DomNode::Element {
		tag: tbody_tag,
		attrs: tbody_attrs,
		children: tbody_children,
		self_closing: false,
	} = &children[tbody_idx]
	{
		let mut inner_with_directives = vec![comment_each(path)];
		inner_with_directives.extend(tbody_children.iter().cloned());
		inner_with_directives.push(comment_endeach());
		new_children[tbody_idx] = DomNode::Element {
			tag: tbody_tag.clone(),
			attrs: tbody_attrs.clone(),
			children: inner_with_directives,
			self_closing: false,
		};
		return Some(DomNode::Element {
			tag: tag.to_string(),
			attrs: attrs.to_string(),
			children: new_children,
			self_closing: false,
		});
	}

	None
}

/// Recursively find the body location by diffing populated vs empty trees.
/// Traverses through Modified elements until OnlyLeft items (the body) are found.
struct BodyLocation {
	path: Vec<usize>,
	body_indices: Vec<usize>,
	fallback_indices: Vec<usize>,
}

fn find_body_in_trees(pop: &[DomNode], empty: &[DomNode]) -> Option<BodyLocation> {
	let ops = diff_children(pop, empty);

	let body_idx: Vec<usize> = ops
		.iter()
		.filter_map(|op| if let DiffOp::OnlyLeft(ai) = op { Some(*ai) } else { None })
		.collect();

	if !body_idx.is_empty() {
		let fallback_idx: Vec<usize> = ops
			.iter()
			.filter_map(|op| if let DiffOp::OnlyRight(bi) = op { Some(*bi) } else { None })
			.collect();
		return Some(BodyLocation {
			path: vec![],
			body_indices: body_idx,
			fallback_indices: fallback_idx,
		});
	}

	// Recurse into Modified elements to find body deeper
	for op in &ops {
		if let DiffOp::Modified(ai, bi) = op
			&& let (DomNode::Element { children: pc, .. }, DomNode::Element { children: ec, .. }) =
				(&pop[*ai], &empty[*bi])
			&& let Some(mut loc) = find_body_in_trees(pc, ec)
		{
			loc.path.insert(0, *ai);
			return Some(loc);
		}
	}

	None
}

/// Navigate into a tree at a path and replace the body nodes with replacement.
fn replace_body_at_path(
	result: &mut Vec<DomNode>,
	path: &[usize],
	body_indices: &[usize],
	replacement: Vec<DomNode>,
) {
	if path.is_empty() {
		let body_set: HashSet<usize> = body_indices.iter().copied().collect();
		let mut new = Vec::new();
		for (i, node) in result.iter().enumerate() {
			if body_set.contains(&i) {
				if i == body_indices[0] {
					new.extend(replacement.iter().cloned());
				}
			} else {
				new.push(node.clone());
			}
		}
		*result = new;
	} else {
		// Navigate to the content node at index path[0] (skip directive comments)
		if let Some(ci) = nth_content_index(result, path[0])
			&& let DomNode::Element { children, .. } = &mut result[ci]
		{
			replace_body_at_path(children, &path[1..], body_indices, replacement);
		}
	}
}

/// Process an array axis that has nested child axes.
pub(super) fn process_array_with_children(
	mut result: Vec<DomNode>,
	axes: &[Axis],
	variants: &[String],
	group: &AxisGroup,
) -> Vec<DomNode> {
	let array_axis = &axes[group.parent_axis_idx];
	if array_axis.kind != "array" {
		return result;
	}

	// 1. Find populated/empty pair
	let pair = find_pair_for_axis(axes, variants.len(), group.parent_axis_idx);
	let Some((_, vi_empty)) = pair else {
		return result;
	};
	let tree_empty = parse_html(&variants[vi_empty]);

	// 2. Find all scoped variants (array=populated, non-child axes at reference)
	let scoped_indices =
		find_scoped_variant_indices(axes, variants.len(), group.parent_axis_idx, &group.children);
	if scoped_indices.is_empty() {
		return result;
	}

	// 3. Parse all scoped variants
	let scoped_trees: Vec<Vec<DomNode>> =
		scoped_indices.iter().map(|&i| parse_html(&variants[i])).collect();
	let first_pop = &scoped_trees[0];

	// 4. Find body location by recursively traversing Modified elements
	let Some(body_loc) = find_body_in_trees(first_pop, &tree_empty) else {
		return result;
	};

	// 5. Extract body from each scoped variant at the found path
	let body_variants: Vec<String> = scoped_trees
		.iter()
		.map(|tree| {
			let parent = navigate_to_children(tree, &body_loc.path);
			let body_nodes: Vec<DomNode> = body_loc
				.body_indices
				.iter()
				.filter(|&&i| i < parent.len())
				.map(|&i| parent[i].clone())
				.collect();
			serialize(&body_nodes)
		})
		.collect();

	// 6. Build child axes with stripped parent prefix
	let parent_dot = format!("{}.", array_axis.path);
	let child_axes: Vec<Axis> = group
		.children
		.iter()
		.map(|&i| {
			let orig = &axes[i];
			Axis {
				path: orig.path.strip_prefix(&parent_dot).unwrap_or(&orig.path).to_string(),
				kind: orig.kind.clone(),
				values: orig.values.clone(),
			}
		})
		.collect();

	// 6b. Pre-rename slot markers in body variants
	let slot_prefix = format!("<!--seam:{}.", array_axis.path);
	let body_variants: Vec<String> =
		body_variants.into_iter().map(|b| b.replace(&slot_prefix, "<!--seam:")).collect();

	// 7. Recursively extract template from body variants
	let template_body = extract_template_inner(&child_axes, &body_variants);
	let mut body_tree = parse_html(&template_body);
	rename_slot_markers(&mut body_tree, &array_axis.path);

	// 8. Wrap with each markers, adding if/else fallback when present
	let each_nodes = wrap_array_body(&body_tree, &array_axis.path);

	let final_nodes = if !body_loc.fallback_indices.is_empty() {
		let empty_children = navigate_to_children(&tree_empty, &body_loc.path);
		let fallback: Vec<DomNode> = body_loc
			.fallback_indices
			.iter()
			.filter(|&&i| i < empty_children.len())
			.map(|&i| empty_children[i].clone())
			.collect();

		let mut nodes = vec![comment_if(&array_axis.path)];
		nodes.extend(each_nodes);
		nodes.push(comment_else());
		nodes.extend(fallback);
		nodes.push(comment_endif(&array_axis.path));
		nodes
	} else {
		each_nodes
	};

	// 9. Insert into result tree at the body location
	replace_body_at_path(&mut result, &body_loc.path, &body_loc.body_indices, final_nodes);
	result
}