Skip to content

Commit

Permalink
fix list render diff (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
ogrodnek authored Sep 11, 2024
1 parent c52144b commit 448a39d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ packages = [
{ include = "pyview" },
]

version = "0.0.24"
version = "0.0.25"
description = "LiveView in Python"
authors = ["Larry Ogrodnek <[email protected]>"]
license = "MIT"
Expand Down
11 changes: 8 additions & 3 deletions pyview/template/render_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,24 @@ def calc_diff(old_tree: dict[str, Any], new_tree: dict[str, Any]) -> dict[str, A
and "s" in new_tree[key]
and "d" in new_tree[key]
):
if isinstance(old_tree[key], str):
diff[key] = new_tree[key]
continue

# Handle special case of for loop
old_static = old_tree[key].get("s", [])
new_static = new_tree[key]["s"]

old_dynamic = old_tree[key]["d"]
new_dynamic = new_tree[key]["d"]

old_static = old_tree[key]["s"]
new_static = new_tree[key]["s"]

if old_static != new_static:
diff[key] = {"s": new_static, "d": new_dynamic}
continue

if old_dynamic != new_dynamic:
diff[key] = {"d": new_dynamic}

elif isinstance(new_tree[key], dict):
nested_diff = calc_diff(old_tree[key], new_tree[key])
if nested_diff:
Expand Down
29 changes: 29 additions & 0 deletions tests/template/test_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,35 @@ def test_loop_diff_no_change():
assert calc_diff(old, new) == {}


def test_loop_diff_empty_to_nonempty():
t = Template("<div>{% for item in items %}<span>{{item}}</span>{% endfor %}</div>")

old = t.tree({"items": []})
new = t.tree({"items": ["One", "Two", "Three"]})

assert calc_diff(old, new) == {
"0": {"d": [["One"], ["Two"], ["Three"]], "s": ["<span>", "</span>"]}
}


def test_loop_diff_nonempty_to_empty():
t = Template("<div>{% for item in items %}<span>{{item}}</span>{% endfor %}</div>")

old = t.tree({"items": ["One", "Two", "Three"]})
new = t.tree({"items": []})

assert calc_diff(old, new) == {"0": ""}


def test_loop_diff_size_change():
t = Template("<div>{% for item in items %}<span>{{item}}</span>{% endfor %}</div>")

old = t.tree({"items": ["One", "Two", "Three"]})
new = t.tree({"items": ["One"]})

assert calc_diff(old, new) == {"0": {"d": [["One"]]}}


def test_loop_diff_static_change():
t = Template("<div>{% for item in items %}<span>{{item}}</span>{% endfor %}</div>")
t2 = Template("<div>{% for item in items %}<div>{{item}}</div>{% endfor %}</div>")
Expand Down

0 comments on commit 448a39d

Please sign in to comment.