-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomBehaviorTests.cs
More file actions
621 lines (518 loc) · 23.6 KB
/
DomBehaviorTests.cs
File metadata and controls
621 lines (518 loc) · 23.6 KB
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
using System.Runtime.Versioning;
using Abies.DOM;
using DOMAttribute = Abies.DOM.Attribute;
namespace Abies.Tests;
[SupportedOSPlatform("browser")]
public class DomBehaviorTests
{
private record DummyMessage() : Message;
[Fact]
public void AddRoot_ShouldRenderCorrectly()
{
var newDom = new Element("1", "div", [],
new Text("2", "Hello"));
var patches = Operations.Diff(null, newDom);
var result = ApplyPatches(null, patches, null);
Assert.Equal(Render.Html(newDom), Render.Html(result!));
}
[Fact]
public void ReplaceChild_ShouldUpdateTree()
{
var oldDom = new Element("1", "div", [],
new Element("2", "span", [], new Text("3", "Old")));
var newDom = new Element("1", "div", [],
new Element("4", "p", [], new Text("5", "New")));
var patches = Operations.Diff(oldDom, newDom);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDom), Render.Html(result));
}
[Fact]
public void AttributeChanges_ShouldReflectInResult()
{
var oldDom = new Element("1", "button",
new DOMAttribute[] { new DOMAttribute("a1", "class", "btn") },
[]);
var newDom = new Element("1", "button",
new DOMAttribute[]
{
new DOMAttribute("a1", "class", "btn-primary"),
new Handler("click", "cmd1", new DummyMessage(), "h1")
},
[]);
var patches = Operations.Diff(oldDom, newDom);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDom), Render.Html(result));
}
[Fact]
public void AttributeIdChange_ShouldNotRemoveAttribute()
{
var oldDom = new Element("1", "div",
new DOMAttribute[] { new DOMAttribute("a1", "class", "foo") },
[]);
var newDom = new Element("1", "div",
new DOMAttribute[] { new DOMAttribute("a2", "class", "foo") },
[]);
var patches = Operations.Diff(oldDom, newDom);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDom), Render.Html(result));
}
[Fact]
public void AttributeIdChange_WithValueChange_ShouldUpdateAttribute()
{
var oldDom = new Element("1", "div",
new DOMAttribute[] { new DOMAttribute("a1", "class", "inactive") },
[]);
var newDom = new Element("1", "div",
new DOMAttribute[] { new DOMAttribute("a2", "class", "active") },
[]);
var alignedNew = PreserveIdsForTest(oldDom, newDom);
var patches = Operations.Diff(oldDom, alignedNew);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(alignedNew), Render.Html(result));
Assert.Contains(patches, p => p is UpdateAttribute);
Assert.DoesNotContain(patches, p => p is RemoveAttribute);
}
[Fact]
public void HandlerIdChange_ShouldUpdateHandler()
{
var oldDom = new Element("1", "button",
new DOMAttribute[] { new Handler("click", "cmd-old", new DummyMessage(), "h1") },
[]);
var newDom = new Element("1", "button",
new DOMAttribute[] { new Handler("click", "cmd-new", new DummyMessage(), "h2") },
[]);
var alignedNew = PreserveIdsForTest(oldDom, newDom);
var patches = Operations.Diff(oldDom, alignedNew);
Assert.Contains(patches, p => p is UpdateHandler);
Assert.DoesNotContain(patches, p => p is RemoveHandler);
Assert.DoesNotContain(patches, p => p is AddHandler);
}
[Fact]
public void Render_ShouldIncludeElementIds()
{
var dom = new Element("el1", "div", [],
new Element("child", "span", [], new Text("t", "hi")));
var html = Render.Html(dom);
Assert.Contains("id=\"el1\"", html);
Assert.Contains("id=\"child\"", html);
}
[Fact]
public void TextUpdate_ShouldUpdateTextContent()
{
var oldDom = new Element("1", "h1", [],
new Text("2", "Sign up"));
var newDom = new Element("1", "h1", [],
new Text("3", "Sign in"));
var patches = Operations.Diff(oldDom, newDom);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDom), Render.Html(result));
// Verify that an UpdateText patch was generated
Assert.Contains(patches, p => p is UpdateText);
var textPatch = patches.OfType<UpdateText>().First();
Assert.Equal("Sign in", textPatch.Text);
}
[Fact]
public void TextUpdate_WithPreservedIds_ShouldUpdateTextContent()
{
// Simulate the ID preservation scenario
var oldDom = new Element("1", "h1", [],
new Text("2", "Sign up"));
var newDomBeforePreservation = new Element("1", "h1", [],
new Text("3", "Sign in"));
// Simulate what PreserveIds does - preserve the old text ID but use new text content
var newDomAfterPreservation = new Element("1", "h1", [],
new Text("2", "Sign in")); // Same ID as old, new content
var patches = Operations.Diff(oldDom, newDomAfterPreservation);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDomAfterPreservation), Render.Html(result));
// Verify that an UpdateText patch was generated
Assert.Contains(patches, p => p is UpdateText);
var textPatch = patches.OfType<UpdateText>().First();
Assert.Equal("Sign in", textPatch.Text);
Assert.Equal("2", textPatch.Node.Id); // Should use the preserved ID
}
[Fact]
public void KeyedChildren_Reorder_ShouldUseMoveChild()
{
// Per ADR-016: Element Id is used for keyed diffing, not data-key attribute.
// When children have different IDs in different order, the algorithm detects reordering.
// With LIS optimization, reordering uses MoveChild instead of Remove+Add.
//
// IMPORTANT: In a pure reorder, the NEW virtual DOM should have the SAME IDs as the old DOM.
// This is because Abies identifies elements by their ID, and a reorder doesn't change IDs.
// The MoveChild operation moves elements by their existing IDs, not creating new ones.
var oldDom = new Element("root", "div", [],
new Element("item-a", "div", new DOMAttribute[]
{
new DOMAttribute("ca", "class", "item")
}, new Text("ta", "A")),
new Element("item-b", "div", new DOMAttribute[]
{
new DOMAttribute("cb", "class", "item")
}, new Text("tb", "B")));
// For a pure reorder test, new DOM has SAME IDs but DIFFERENT ORDER
// This simulates what happens when the same elements are rendered in a different order
var newDom = new Element("root", "div", [],
new Element("item-b", "div", new DOMAttribute[]
{
new DOMAttribute("cb", "class", "item") // Same IDs as old
}, new Text("tb", "B")),
new Element("item-a", "div", new DOMAttribute[]
{
new DOMAttribute("ca", "class", "item") // Same IDs as old
}, new Text("ta", "A")));
var patches = Operations.Diff(oldDom, newDom);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDom), Render.Html(result));
// With LIS optimization, reordering uses MoveChild instead of Remove+Add
Assert.Contains(patches, p => p is MoveChild);
Assert.DoesNotContain(patches, p => p is RemoveChild);
Assert.DoesNotContain(patches, p => p is AddChild);
}
[Fact]
public void KeyedChildren_SameOrder_ShouldDiffInPlace()
{
// Per ADR-016: Element Id is used for keyed diffing.
// When children have the same IDs in the same order, diff in place.
var oldDom = new Element("root", "div", [],
new Element("item-a", "div", new DOMAttribute[]
{
new DOMAttribute("ca", "class", "item")
}, new Text("ta", "Old")),
new Element("item-b", "div", new DOMAttribute[]
{
new DOMAttribute("cb", "class", "item")
}, new Text("tb", "Old")));
var newDom = new Element("root", "div", [],
new Element("item-a", "div", new DOMAttribute[]
{
new DOMAttribute("ca2", "class", "item")
}, new Text("ta2", "New")),
new Element("item-b", "div", new DOMAttribute[]
{
new DOMAttribute("cb2", "class", "item")
}, new Text("tb2", "New")));
var patches = Operations.Diff(oldDom, newDom);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDom), Render.Html(result));
// Same IDs, same order: should update in place, not remove/add
Assert.DoesNotContain(patches, p => p is RemoveChild);
Assert.DoesNotContain(patches, p => p is AddChild);
}
[Fact]
public void KeyedChildren_DifferentIds_ShouldReplaceList()
{
// Per ADR-016: When child IDs change completely, remove old and add new.
// This is the navigation scenario: unauthenticated (login, register) -> authenticated (editor, settings, profile)
var oldDom = new Element("root", "ul", [],
new Element("nav-home", "li", [], new Text("t1", "Home")),
new Element("nav-login", "li", [], new Text("t2", "Sign in")),
new Element("nav-register", "li", [], new Text("t3", "Sign up")));
var newDom = new Element("root", "ul", [],
new Element("nav-home", "li", [], new Text("t1", "Home")),
new Element("nav-editor", "li", [], new Text("t4", "New Article")),
new Element("nav-settings", "li", [], new Text("t5", "Settings")),
new Element("nav-profile-bob", "li", [], new Text("t6", "bob")));
var patches = Operations.Diff(oldDom, newDom);
var result = ApplyPatches(oldDom, patches, oldDom);
Assert.NotNull(result);
Assert.Equal(Render.Html(newDom), Render.Html(result));
// Should remove nav-login and nav-register
var removePatches = patches.OfType<RemoveChild>().ToList();
Assert.Equal(2, removePatches.Count);
Assert.Contains(removePatches, p => p.Child.Id == "nav-login");
Assert.Contains(removePatches, p => p.Child.Id == "nav-register");
// Should add nav-editor, nav-settings, nav-profile-bob
var addPatches = patches.OfType<AddChild>().ToList();
Assert.Equal(3, addPatches.Count);
Assert.Contains(addPatches, p => p.Child.Id == "nav-editor");
Assert.Contains(addPatches, p => p.Child.Id == "nav-settings");
Assert.Contains(addPatches, p => p.Child.Id == "nav-profile-bob");
}
[Fact]
public void KeyedChildren_SharedHomeLink_ShouldBePreserved()
{
// Per ADR-016: Elements with matching IDs should be diffed in place, not replaced.
// The "Home" link has the same ID in both states, so it should be updated, not replaced.
var oldDom = new Element("root", "ul", [],
new Element("nav-home", "li", new DOMAttribute[] { new DOMAttribute("c1", "class", "nav-item") },
new Text("t1", "Home")),
new Element("nav-login", "li", new DOMAttribute[] { new DOMAttribute("c2", "class", "nav-item") },
new Text("t2", "Sign in")));
var newDom = new Element("root", "ul", [],
new Element("nav-home", "li", new DOMAttribute[] { new DOMAttribute("c1", "class", "nav-item active") },
new Text("t1", "Home")),
new Element("nav-editor", "li", new DOMAttribute[] { new DOMAttribute("c3", "class", "nav-item") },
new Text("t3", "New Article")));
var patches = Operations.Diff(oldDom, newDom);
// nav-home should have an attribute update (class changed), not be removed/added
var removePatches = patches.OfType<RemoveChild>().ToList();
var addPatches = patches.OfType<AddChild>().ToList();
// Only nav-login should be removed
Assert.Single(removePatches);
Assert.Equal("nav-login", removePatches[0].Child.Id);
// Only nav-editor should be added
Assert.Single(addPatches);
Assert.Equal("nav-editor", addPatches[0].Child.Id);
// nav-home's class should be updated
var attrPatches = patches.OfType<UpdateAttribute>().ToList();
Assert.Contains(attrPatches, p => p.Element.Id == "nav-home" && p.Attribute.Name == "class");
}
[Fact]
public void LegacyDataKey_ShouldStillWork()
{
// Backward compatibility: data-key attribute should still work for keyed diffing
// even though ADR-016 recommends using element Id instead.
var oldDom = new Element("root", "div", [],
new Element("1", "div", new DOMAttribute[]
{
new DOMAttribute("ka", "data-key", "a"),
new DOMAttribute("ca", "class", "item")
}, new Text("ta", "A")),
new Element("2", "div", new DOMAttribute[]
{
new DOMAttribute("kb", "data-key", "b"),
new DOMAttribute("cb", "class", "item")
}, new Text("tb", "B")));
var newDom = new Element("root", "div", [],
new Element("3", "div", new DOMAttribute[]
{
new DOMAttribute("kb2", "data-key", "b"),
new DOMAttribute("cb2", "class", "item")
}, new Text("tb2", "B")),
new Element("4", "div", new DOMAttribute[]
{
new DOMAttribute("ka2", "data-key", "a"),
new DOMAttribute("ca2", "class", "item")
}, new Text("ta2", "A")));
var patches = Operations.Diff(oldDom, newDom);
// Keys are reordered, so should use MoveChild (optimized reordering)
Assert.Contains(patches, p => p is MoveChild);
}
private static Node? ApplyPatches(Node? root, IEnumerable<Patch> patches, Node? initialRoot)
{
var current = root;
foreach (var patch in patches)
{
current = ApplyPatch(current, patch, initialRoot);
}
return current;
}
private static Node? ApplyPatch(Node? root, Patch patch, Node? initialRoot)
{
return patch switch
{
AddRoot ar => ar.Element,
ReplaceChild rc => ReplaceNode(root!, rc.OldElement, rc.NewElement),
AddChild ac => UpdateElement(root!, ac.Parent.Id, e => e with { Children = e.Children.Append(ac.Child).ToArray() }),
RemoveChild rc => UpdateElement(root!, rc.Parent.Id, e => e with { Children = e.Children.Where(c => c.Id != rc.Child.Id).ToArray() }),
MoveChild mc => UpdateElement(root!, mc.Parent.Id, e =>
{
// Remove child from current position
var children = e.Children.Where(c => c.Id != mc.Child.Id).ToList();
// Find position to insert (before the specified element, or at end)
int insertIndex = mc.BeforeId != null
? children.FindIndex(c => c.Id == mc.BeforeId)
: children.Count;
if (insertIndex < 0)
{
insertIndex = children.Count;
}
children.Insert(insertIndex, mc.Child);
return e with { Children = children.ToArray() };
}),
UpdateAttribute ua => UpdateElement(root!, ua.Element.Id, e =>
{
var updated = false;
var attrs = e.Attributes.Select(a =>
{
if (a.Name == ua.Attribute.Name)
{
updated = true;
return a with { Value = ua.Value };
}
return a;
}).ToArray();
if (!updated)
{
attrs = attrs.Append(ua.Attribute with { Value = ua.Value }).ToArray();
}
return e with { Attributes = attrs };
}),
AddAttribute aa => UpdateElement(root!, aa.Element.Id, e =>
{
var attrs = e.Attributes.Where(a => a.Name != aa.Attribute.Name).Append(aa.Attribute).ToArray();
return e with { Attributes = attrs };
}),
RemoveAttribute ra => UpdateElement(root!, ra.Element.Id, e => e with { Attributes = e.Attributes.Where(a => a.Name != ra.Attribute.Name).ToArray() }),
AddHandler ah => UpdateElement(root!, ah.Element.Id, e => e with { Attributes = e.Attributes.Append(ah.Handler).ToArray() }),
RemoveHandler rh => UpdateElement(root!, rh.Element.Id, e => e with { Attributes = e.Attributes.Where(a => a.Id != rh.Handler.Id).ToArray() }),
UpdateText ut => ReplaceNode(root!, ut.Node, new Text(ut.NewId, ut.Text)),
_ => root
};
}
private static Node ReplaceNode(Node node, Node target, Node newNode)
{
if (ReferenceEquals(node, target) || node.Id == target.Id)
{
return newNode;
}
if (node is Element el)
{
var newChildren = el.Children.Select(c => ReplaceNode(c, target, newNode)).ToArray();
return el with { Children = newChildren };
}
return node;
}
private static Node PreserveIdsForTest(Node? oldNode, Node newNode)
{
if (oldNode is Element oldElement && newNode is Element newElement && oldElement.Tag == newElement.Tag)
{
var attrs = new DOMAttribute[newElement.Attributes.Length];
for (int i = 0; i < newElement.Attributes.Length; i++)
{
var attr = newElement.Attributes[i];
var oldAttr = Array.Find(oldElement.Attributes, a => a.Name == attr.Name);
var attrId = oldAttr?.Id ?? attr.Id;
if (attr.Name == "id")
{
attrs[i] = attr with { Id = attrId, Value = oldElement.Id };
}
else
{
attrs[i] = attr with { Id = attrId };
}
}
var children = new Node[newElement.Children.Length];
for (int i = 0; i < newElement.Children.Length; i++)
{
var oldChild = i < oldElement.Children.Length ? oldElement.Children[i] : null;
children[i] = PreserveIdsForTest(oldChild, newElement.Children[i]);
}
return new Element(oldElement.Id, newElement.Tag, attrs, children);
}
if (oldNode is Text oldText && newNode is Text newText)
{
return new Text(oldText.Id, newText.Value);
}
if (newNode is Element newElem)
{
var children = new Node[newElem.Children.Length];
for (int i = 0; i < newElem.Children.Length; i++)
{
children[i] = PreserveIdsForTest(null, newElem.Children[i]);
}
return new Element(newElem.Id, newElem.Tag, newElem.Attributes, children);
}
return newNode;
}
private static Node UpdateElement(Node node, string targetId, Func<Element, Element> update)
{
if (node is Element el)
{
if (el.Id == targetId)
{
var updated = update(el);
return updated;
}
var newChildren = el.Children.Select(c => UpdateElement(c, targetId, update)).ToArray();
return el with { Children = newChildren };
}
return node;
}
#region Memo Tests
/// <summary>
/// Test data record for memoization tests.
/// </summary>
private record TestRow(int Id, string Label);
[Fact]
public void Memo_WithSameData_SkipsDiffing()
{
// Create two memo nodes with the same data
var row = new TestRow(1, "Test");
var element = new Element("row-1", "tr", [], new Text("t1", "Test"));
var oldNode = new Memo<TestRow>(row, element);
var newNode = new Memo<TestRow>(row, element);
var patches = Operations.Diff(oldNode, newNode);
// Should produce no patches because data is equal
Assert.Empty(patches);
}
[Fact]
public void Memo_WithDifferentData_ProducesDiff()
{
// Create two memo nodes with different data
var oldRow = new TestRow(1, "Old");
var newRow = new TestRow(1, "New");
var oldElement = new Element("row-1", "tr", [], new Text("t1", "Old"));
var newElement = new Element("row-1", "tr", [], new Text("t1", "New"));
var oldNode = new Memo<TestRow>(oldRow, oldElement);
var newNode = new Memo<TestRow>(newRow, newElement);
var patches = Operations.Diff(oldNode, newNode);
// Should produce patches because data changed
Assert.NotEmpty(patches);
Assert.Contains(patches, p => p is UpdateText);
}
[Fact]
public void Memo_RendersCorrectHtml()
{
var row = new TestRow(1, "Test");
var element = new Element("row-1", "tr", [], new Text("t1", "Test"));
var memoNode = new Memo<TestRow>(row, element);
var html = Render.Html(memoNode);
// Memo should render the inner element
Assert.Contains("row-1", html);
Assert.Contains("<tr", html);
Assert.Contains("Test", html);
}
[Fact]
public void Memo_GetKey_ReturnsInnerElementKey()
{
var row = new TestRow(1, "Test");
var element = new Element("row-1", "tr",
[new DOMAttribute("k1", "data-key", "custom-key")],
new Text("t1", "Test"));
var memoNode = new Memo<TestRow>(row, element);
// The key should be extracted from the inner element
// We can't test GetKey directly since it's private, but we can test
// that diffing works correctly with keyed memo nodes
var parent = new Element("p1", "tbody", [], memoNode);
var html = Render.Html(parent);
Assert.Contains("custom-key", html);
}
[Fact]
public void Memo_ListReorder_SkipsDiffingUnchangedItems()
{
// Simulate a list reorder where items don't change, just move
var rows = new[]
{
new TestRow(1, "First"),
new TestRow(2, "Second"),
new TestRow(3, "Third")
};
// Create memo-wrapped elements for old tree
var oldChildren = rows.Select((row, i) =>
(Node)new Memo<TestRow>(row, new Element($"row-{row.Id}", "tr", [], new Text($"t{row.Id}", row.Label)))
).ToArray();
var oldTree = new Element("tbody", "tbody", [], oldChildren);
// Reorder: swap first and last
var reorderedRows = new[] { rows[2], rows[1], rows[0] };
var newChildren = reorderedRows.Select((row, i) =>
(Node)new Memo<TestRow>(row, new Element($"row-{row.Id}", "tr", [], new Text($"t{row.Id}", row.Label)))
).ToArray();
var newTree = new Element("tbody", "tbody", [], newChildren);
var patches = Operations.Diff(oldTree, newTree);
// The memo optimization means we should NOT see UpdateText patches
// because the data is equal and diffing was skipped for the inner content.
// We may see structural patches (AddChild, RemoveChild) for reordering.
Assert.DoesNotContain(patches, p => p is UpdateText);
}
#endregion
}