|
| 1 | +import Gtk from "gi://Gtk"; |
| 2 | +import GObject from "gi://GObject"; |
| 3 | +import Gio from "gi://Gio"; |
| 4 | + |
| 5 | +const list_view = workbench.builder.get_object("list_view"); |
| 6 | +const factory = workbench.builder.get_object("factory"); |
| 7 | + |
| 8 | +const TreeNode = GObject.registerClass( |
| 9 | + class TreeNode extends GObject.Object { |
| 10 | + constructor(title, children) { |
| 11 | + super(); |
| 12 | + this.title = title; |
| 13 | + this.children = children; |
| 14 | + } |
| 15 | + }, |
| 16 | +); |
| 17 | + |
| 18 | +const TreeWidget = GObject.registerClass( |
| 19 | + class TreeWidget extends Gtk.Box { |
| 20 | + constructor(...args) { |
| 21 | + super(...args); |
| 22 | + this.spacing = 6; |
| 23 | + this.margin_start = 6; |
| 24 | + this.margin_end = 12; |
| 25 | + this.margin_top = 6; |
| 26 | + this.margin_bottom = 6; |
| 27 | + |
| 28 | + this.expander = new Gtk.TreeExpander(); |
| 29 | + this.label = new Gtk.Label({ halign: Gtk.Align.START }); |
| 30 | + |
| 31 | + this.append(this.expander); |
| 32 | + this.append(this.label); |
| 33 | + } |
| 34 | + }, |
| 35 | +); |
| 36 | + |
| 37 | +function create_model_func(item) { |
| 38 | + if (item.children.length < 1) return null; |
| 39 | + const child_model = new Gio.ListStore(TreeNode); |
| 40 | + for (const child of item.children) { |
| 41 | + child_model.append(child); |
| 42 | + } |
| 43 | + return child_model; |
| 44 | +} |
| 45 | + |
| 46 | +factory.connect("setup", (_self, list_item) => { |
| 47 | + list_item.set_child(new TreeWidget()); |
| 48 | +}); |
| 49 | + |
| 50 | +factory.connect("bind", (_self, list_item) => { |
| 51 | + const list_row = list_item.get_item(); |
| 52 | + const widget = list_item.get_child(); |
| 53 | + const item = list_row.get_item(); |
| 54 | + |
| 55 | + widget.expander.set_list_row(list_row); |
| 56 | + widget.label.set_label(item.title); |
| 57 | +}); |
| 58 | + |
| 59 | +const root_model = new TreeNode("Root", [ |
| 60 | + new TreeNode("Child 1", [ |
| 61 | + new TreeNode("Child 1.1", []), |
| 62 | + new TreeNode("Child 1.2", []), |
| 63 | + ]), |
| 64 | + new TreeNode("Child 2", [ |
| 65 | + new TreeNode("Child 2.1", []), |
| 66 | + new TreeNode("Child 2.2", []), |
| 67 | + new TreeNode("Child 2.3", [new TreeNode("Child 3.1", [])]), |
| 68 | + ]), |
| 69 | +]); |
| 70 | + |
| 71 | +const tree_model = new Gio.ListStore(TreeNode); |
| 72 | +tree_model.append(root_model); |
| 73 | + |
| 74 | +const tree_list_model = Gtk.TreeListModel.new( |
| 75 | + tree_model, |
| 76 | + false, |
| 77 | + true, |
| 78 | + create_model_func, |
| 79 | +); |
| 80 | +tree_list_model.set_autoexpand(false); |
| 81 | + |
| 82 | +const selection_model = new Gtk.NoSelection({ model: tree_list_model }); |
| 83 | + |
| 84 | +list_view.set_model(selection_model); |
0 commit comments