From 937c2c5eaae22d4f753b8d6e6ced17f7e8dd844c Mon Sep 17 00:00:00 2001 From: Roy Attias Date: Sat, 18 Mar 2023 17:12:06 +0200 Subject: [PATCH] examples: json_tree: Use cleaner API and allow custom file --- CHANGELOG.md | 1 + examples/json_tree.py | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dfb8feb7f..407bb0e6a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added - Added `parser_factory` argument to `Markdown` and `MarkdownViewer` constructors https://github.com/Textualize/textual/pull/2075 +- Added the option to supply a custom path in the `json_tree.py` example https://github.com/Textualize/textual/pull/2087 ### Changed diff --git a/examples/json_tree.py b/examples/json_tree.py index 45cede3c54..65ffe736b2 100644 --- a/examples/json_tree.py +++ b/examples/json_tree.py @@ -1,5 +1,7 @@ import json +from sys import argv from pathlib import Path +from typing import Optional from rich.text import Text @@ -16,6 +18,10 @@ class TreeApp(App): ("t", "toggle_root", "Toggle root"), ] + def __init__(self, json_path: Optional[Path] = None, *args, **kwargs): + self.json_path = json_path or Path(__file__).parent / "food.json" + super().__init__(*args, **kwargs) + def compose(self) -> ComposeResult: yield Header() yield Footer() @@ -43,31 +49,30 @@ def add_node(name: str, node: TreeNode, data: object) -> None: data (object): Data associated with the node. """ if isinstance(data, dict): - node._label = Text(f"{{}} {name}") + node.set_label(Text(f"{{}} {name}")) for key, value in data.items(): new_node = node.add("") add_node(key, new_node, value) elif isinstance(data, list): - node._label = Text(f"[] {name}") + node.set_label(Text(f"[] {name}")) for index, value in enumerate(data): new_node = node.add("") add_node(str(index), new_node, value) else: - node._allow_expand = False + node.allow_expand = False if name: label = Text.assemble( Text.from_markup(f"[b]{name}[/b]="), highlighter(repr(data)) ) else: label = Text(repr(data)) - node._label = label + node.set_label(label) add_node("JSON", node, json_data) def on_mount(self) -> None: """Load some JSON when the app starts.""" - file_path = Path(__file__).parent / "food.json" - with open(file_path) as data_file: + with open(self.json_path) as data_file: self.json_data = json.load(data_file) def action_add(self) -> None: @@ -89,5 +94,5 @@ def action_toggle_root(self) -> None: if __name__ == "__main__": - app = TreeApp() + app = TreeApp(json_path=Path(argv[1]) if len(argv) >= 2 else None) app.run()