Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-fabric.py
More file actions
Latest commit
495 lines (393 loc) · 15.9 KB
/
Copy pathbasic-fabric.py
File metadata and controls
495 lines (393 loc) · 15.9 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
fromtimeimportsleep
importjson
# Simplified version of get_node_from_instance
defget_node_from_instance(inst):
# For simplicity, we assume inst is already the node.
returninst
# Guarded Callback Handling
definvoke_guarded_callback_impl(name, func, context, *args):
try:
func(context, *args)
exceptExceptionaserror:
reporter.on_error(error)
classReporter:
def__init__(self):
self.has_error=False
self.caught_error=None
defon_error(self, error):
self.has_error=True
self.caught_error=error
reporter=Reporter()
# Synthetic Event System
classSyntheticEvent:
def__init__(self, dispatch_config, target_inst, native_event, native_event_target):
self.dispatch_config=dispatch_config
self._target_inst=target_inst
self.native_event=native_event
self._dispatch_instances=self._dispatch_listeners=None
dispatch_config=self.__class__.Interface
forprop_nameindispatch_config:
ifprop_nameindispatch_config:
self[prop_name] =dispatch_config[prop_name](native_event) ifdispatch_config[prop_name] elsenative_event.get(prop_name, None)
self.target=native_event_target
defprevent_default(self):
self.is_default_prevented=True
defstop_propagation(self):
self.is_propagation_stopped=True
# Responder Event Handling
classResponderSyntheticEvent(SyntheticEvent):
def__init__(self, dispatch_config, target_inst, native_event, native_event_target):
super().__init__(dispatch_config, target_inst, native_event, native_event_target)
self.touch_history=None
classResponderEventPlugin:
@staticmethod
defextract_events(top_level_type, target_inst, native_event, native_event_target):
# Implement touch event extraction logic here, similar to JavaScript version
pass
# Node Creation and Updates
classNode:
def__init__(self, node_type, props=None, context=None):
self.node_type=node_type
self.props=propsor {}
self.context=context
self.children= []
defadd_child(self, child):
self.children.append(child)
defupdate_props(self, new_props):
self.props.update(new_props)
defto_dict(self):
"""Recursively converts the node and its children to a dictionary."""
return {
"node_type": self.node_type,
"props": self.props,
"children": [child.to_dict() forchildinself.children]
}
defto_json(self):
"""Converts the node tree to a JSON string."""
returnjson.dumps(self.to_dict(), indent=4)
# Creating and cloning nodes
defcreate_node(context, node_type, root_container, props, internal_instance_handle):
returnNode(node_type, props, context)
defclone_node_with_new_props(node, new_props):
node.update_props(new_props)
returnnode
# Guarded callback wrapper to catch and handle errors
definvoke_guarded_callback_and_catch_first_error(listener, event):
try:
listener(event) # Execute the listener with the event
exceptExceptionase:
print(f"Error occurred while executing callback: {e}")
# Additional error handling logic can go here if needed
# Event Dispatching
defexecute_dispatch(event, listener, inst):
event.current_target=get_node_from_instance(inst)
invoke_guarded_callback_and_catch_first_error(listener, event)
event.current_target=None
defexecute_direct_dispatch(event):
dispatch_listener=event._dispatch_listeners
event.current_target=dispatch_listenerandget_node_from_instance(event._dispatch_instances) orNone
ifdispatch_listener:
dispatch_listener(event)
event.current_target=None
event._dispatch_listeners=None
event._dispatch_instances=None
returndispatch_listener
defschedule_callback(callback, priority=1):
sleep(priority) # Simulate delay based on priority
callback()
defcancel_callback(callback):
# Logic to cancel the scheduled callback (if needed)
pass
defshould_yield():
# Placeholder to control when to yield to other tasks
returnFalse
# Basic Reconciliation Logic
defdiff_trees(old_node, new_node):
changes= []
# Type change
ifold_node.node_type!=new_node.node_type:
changes.append(("REPLACE", new_node))
returnchanges
# Prop change
forkeyinnew_node.props:
ifnew_node.props.get(key) !=old_node.props.get(key):
changes.append(("UPDATE_PROP", key, new_node.props[key]))
# Child changes
old_children=old_node.children
new_children=new_node.children
fori, childinenumerate(new_children):
ifi<len(old_children):
changes.extend(diff_trees(old_children[i], child))
else:
changes.append(("ADD_CHILD", child))
returnchanges
# Node Update Handling
defapply_changes(node, changes):
forchangeinchanges:
ifchange[0] =="REPLACE":
node=change[1] # Replace the node with the new one
elifchange[0] =="UPDATE_PROP":
node.props[change[1]] =change[2] # Update the property
elifchange[0] =="ADD_CHILD":
node.add_child(change[1]) # Add a new child
returnnode
# Simplified Scheduler and Task Management
classTask:
def__init__(self, callback, priority=1):
self.callback=callback
self.priority=priority
classScheduler:
def__init__(self):
self.queue= []
defschedule(self, task):
self.queue.append(task)
self.queue.sort(key=lambdax: x.priority, reverse=True) # Sort by priority
defrun(self):
whileself.queue:
task=self.queue.pop(0)
task.callback()
# Example usage of Scheduler
scheduler=Scheduler()
scheduler.schedule(Task(lambda: print("Task 1"), priority=2))
scheduler.schedule(Task(lambda: print("Task 2"), priority=1))
scheduler.run()
# UI Rendering Logic
classRenderer:
def__init__(self):
self.root_node=None
defset_root(self, root_node):
self.root_node=root_node
defrender(self):
ifself.root_node:
self._render_node(self.root_node)
def_render_node(self, node):
print(f"Rendering {node.node_type} with props: {node.props}")
forchildinnode.children:
self._render_node(child)
# Example of setting up and rendering a simple UI
root=Node("View", {"style": "background-color: blue"})
child=Node("Text", {"value": "Hello, World!"})
root.add_child(child)
renderer=Renderer()
renderer.set_root(root)
renderer.render()
# Simplified Event Propagation
classEvent:
def__init__(self, type, target):
self.type=type
self.target=target
self.current_target=target
self.is_propagation_stopped=False
self.is_default_prevented=False
defstop_propagation(self):
self.is_propagation_stopped=True
defprevent_default(self):
self.is_default_prevented=True
classEventDispatcher:
def__init__(self):
self.listeners= {}
defadd_event_listener(self, target, event_type, listener):
iftargetnotinself.listeners:
self.listeners[target] = {}
ifevent_typenotinself.listeners[target]:
self.listeners[target][event_type] = []
self.listeners[target][event_type].append(listener)
defdispatch_event(self, event):
ifevent.targetinself.listenersandevent.typeinself.listeners[event.target]:
forlistenerinself.listeners[event.target][event.type]:
listener(event)
ifevent.is_propagation_stopped:
break
# React-like Component System
classComponent:
def__init__(self, props=None):
self.props=propsor {}
self.state= {}
defset_state(self, new_state):
self.state.update(new_state)
self.render()
defrender(self):
raiseNotImplementedError("Subclasses must implement render()")
classView(Component):
def__init__(self, props=None):
super().__init__(props)
defrender(self):
print(f"Rendering View with props: {self.props} and state: {self.state}")
classText(Component):
def__init__(self, props=None):
super().__init__(props)
defrender(self):
print(f"Rendering Text with props: {self.props} and state: {self.state}")
# Example of usage
view=View({"style": "background-color: red"})
text=Text({"value": "Hello, ReactPy!"})
view.set_state({"background_color": "blue"})
view.render()
text.render()
# Node Reconciliation and Diffing
defreconcile(old_node, new_node):
changes= []
# Check if node types are different
ifold_node.node_type!=new_node.node_type:
changes.append(("REPLACE", new_node))
returnchanges
# Check if node properties have changed
forkey, valueinnew_node.props.items():
ifold_node.props.get(key) !=value:
changes.append(("UPDATE_PROP", key, value))
# Handle child nodes (diffing them)
old_children=old_node.children
new_children=new_node.children
fori, new_childinenumerate(new_children):
ifi<len(old_children):
changes.extend(reconcile(old_children[i], new_child))
else:
changes.append(("ADD_CHILD", new_child))
# Remove any extra children
foriinrange(len(new_children), len(old_children)):
changes.append(("REMOVE_CHILD", old_children[i]))
returnchanges
# Applying Changes to Nodes
defapply_reconciliation_changes(node, changes):
forchangeinchanges:
ifchange[0] =="REPLACE":
node=change[1] # Replace the node with a new one
elifchange[0] =="UPDATE_PROP":
node.props[change[1]] =change[2] # Update the property
elifchange[0] =="ADD_CHILD":
node.add_child(change[1]) # Add a new child
elifchange[0] =="REMOVE_CHILD":
node.children.remove(change[1]) # Remove the child
returnnode
# Component Lifecycle
classComponent:
def__init__(self, props=None):
self.props=propsor {}
self.state= {}
self._is_mounted=False
defset_state(self, new_state):
self.state.update(new_state)
self.render()
defrender(self):
raiseNotImplementedError("Subclasses must implement render()")
defcomponent_did_mount(self):
print(f"{self.__class__.__name__} mounted.")
defcomponent_will_unmount(self):
print(f"{self.__class__.__name__} will unmount.")
defmount(self):
ifnotself._is_mounted:
self._is_mounted=True
self.component_did_mount()
defunmount(self):
ifself._is_mounted:
self._is_mounted=False
self.component_will_unmount()
# Example of a Component with Lifecycle Methods
classMyComponent(Component):
def__init__(self, props=None):
super().__init__(props)
self.state= {"count": 0}
defrender(self):
print(f"Rendering MyComponent with props: {self.props} and state: {self.state}")
defincrement(self):
self.set_state({"count": self.state["count"] +1})
print(f"Count incremented: {self.state['count']}")
# Creating and mounting the component
my_component=MyComponent(props={"name": "Test Component"})
my_component.mount() # Trigger the componentDidMount lifecycle method
my_component.render() # Initial render
# Updating the state and triggering the lifecycle method
my_component.increment()
my_component.render()
# Unmounting the component
my_component.unmount() # Trigger componentWillUnmount lifecycle method
# Handling Node Update in a UI Tree
classUIUpdater:
def__init__(self, root_node):
self.root_node=root_node
defupdate_node(self, old_node, new_node):
changes=reconcile(old_node, new_node) # Get differences between old and new node
returnapply_reconciliation_changes(old_node, changes) # Apply changes to the node
defupdate_ui(self, new_tree):
self.root_node=self.update_node(self.root_node, new_tree)
print("UI updated to reflect changes.")
# Event Listener Management
classEventListenerManager:
def__init__(self):
self.listeners= {}
defadd_listener(self, target, event_type, listener):
iftargetnotinself.listeners:
self.listeners[target] = {}
ifevent_typenotinself.listeners[target]:
self.listeners[target][event_type] = []
self.listeners[target][event_type].append(listener)
defremove_listener(self, target, event_type, listener):
iftargetinself.listenersandevent_typeinself.listeners[target]:
self.listeners[target][event_type].remove(listener)
ifnotself.listeners[target][event_type]:
delself.listeners[target][event_type]
ifnotself.listeners[target]:
delself.listeners[target]
defdispatch_event(self, event):
ifevent.targetinself.listenersandevent.typeinself.listeners[event.target]:
forlistenerinself.listeners[event.target][event.type]:
listener(event)
ifevent.is_propagation_stopped:
break
# Handling Task Scheduling and Execution
classTaskScheduler:
def__init__(self):
self.task_queue= []
defschedule_task(self, task, priority=1):
self.task_queue.append({"task": task, "priority": priority})
self.task_queue.sort(key=lambdax: x["priority"], reverse=True) # Sort by priority
defexecute_tasks(self):
whileself.task_queue:
task=self.task_queue.pop(0)["task"]
task() # Execute the task
# Example usage of TaskScheduler
scheduler=TaskScheduler()
# Schedule tasks with different priorities
scheduler.schedule_task(lambda: print("High priority task"), priority=2)
scheduler.schedule_task(lambda: print("Low priority task"), priority=1)
# Execute the tasks
scheduler.execute_tasks()
# Complete Example and Final Integration with Child Node Update
classMyApp:
def__init__(self):
self.scheduler=TaskScheduler()
self.event_manager=EventListenerManager()
self.ui_updater=UIUpdater(None) # Initial empty root node
self.root=Node("View", {"style": "background-color: white"})
self.ui_updater.root_node=self.root# Set the root node for UI updates
# Create child nodes and add them to the root
self.child1=Node("Text", {"value": "Child 1"})
self.child2=Node("Text", {"value": "Child 2"})
self.root.add_child(self.child1)
self.root.add_child(self.child2)
defupdate_child_node(self, child, new_props):
# Update the child node's props and trigger a re-render
print(f"Updating {child.node_type} with new props: {new_props}")
child.update_props(new_props)
self.ui_updater.update_ui(self.root) # Reconcile the root to apply changes
defstart(self):
# Schedule and run tasks
self.scheduler.schedule_task(lambda: print("App has started"))
self.scheduler.execute_tasks()
# Initial UI render
print("Initial UI Render:")
self.ui_updater.update_ui(self.root)
print(f"Root node style: {self.root.props['style']}")
# Simulate updating the child nodes
print("\nUpdating child nodes:")
self.update_child_node(self.child1, {"value": "Updated Child 1"})
self.update_child_node(self.child2, {"value": "Updated Child 2"})
# Simulate an event dispatch (just an example)
event=Event(type="click", target=self.root)
self.event_manager.add_listener(self.root, "click", lambdae: print(f"Event {e.type} triggered on {e.target.node_type}"))
self.event_manager.dispatch_event(event)
print("Current UI Tree in JSON:")
print(self.root.to_json())
# Running the application
app=MyApp()
app.start()