-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.html
1018 lines (821 loc) · 29.4 KB
/
base.html
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<title>Testing</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="rabbit.png">
<style>
@font-face {
font-family: Roboto;
src: url("lib/Roboto-Regular.ttf") format("truetype");
}
* {
font-family: Roboto;
color:white;
}
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url("lib/MaterialIcons-Regular.ttf") format('truetype')
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px; /* Preferred icon size */
display: inline-block;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
/* Support for all WebKit browsers. */
-webkit-font-smoothing: antialiased;
/* Support for Safari and Chrome. */
text-rendering: optimizeLegibility;
/* Support for Firefox. */
-moz-osx-font-smoothing: grayscale;
/* Support for IE. */
font-feature-settings: 'liga';
}
body{
background:#121212;
padding:0px;
margin:0px;
}
input::-webkit-calendar-picker-indicator {
display: none;
}
::-webkit-scrollbar {
width: 0px; /* Remove scrollbar space */
background: transparent; /* Optional: just make scrollbar invisible */
}
</style>
<body onload="brython({indexedDB: false})"></body>
<script src="lib/brython_aio.js"></script>
<script type="text/python">
from browser import document as doc
from browser import window
from browser import aio
from browser.html import *
# storage is like dictionary
#from browser.local_storage import storage
g = None
layout = 'portrait'
def g_resize(self, *l, **kw):
gmap(self, doc['action_bar'], 0, 0, -1)
gmap(self, doc['icon'], 0, 0)
doc['icon'].top += 8
doc['icon'].left += 8
gmap(self, doc['title'], 1, 0, 3)
gmap(self, doc['about_me'], -2, 0)
gmap(self, doc['more'], -1, 0)
if layout == 'landscape':
gmap(self, doc['post_space'], 2, -1)
else:
gmap(self, doc['post_space'], 0, -1, -1)
async def ui():
global g
g = Gridman(rows=[64, ...], cols=[64, 236, ..., 172, 64, 64])
doc <= Space(Edge(Id='posts', flow='column nowrap'), Id='post_space')
doc <= Space(Edge(elevation=4), Id='action_bar')
doc <= Space(IMG(src='rabbit.png', width=48, height=48), Id='icon')
doc <= Space(Label('Bit Garden', style={'font-size': '24px'}, padding='0px'), Id='title')
doc <= Space(Button(Icon('person')), Id='about_me')
doc <= Space(Button(Icon('more_vert')), Id='more')
g.bind(update=g_resize)
on_resize(g)
doc['posts'] <= Card(Label('Post header', grow=0, padding='0px', style={'font-size': '24px'})
+ Edge('Post smosw sksksksks skssksmsk', flat=True)
+ Edge('date', flat=True, grow=0, justify='flex-end')
, elevation=2, flow='column nowrap', style={'min-height': '300px'})
with UIEvent(doc['about_me'], 'click') as am,\
UIEvent(doc['more'], 'click') as mb:
while True:
while not any([mb, am]):
await aio.sleep(0)
if am:
await popup(Card('Hello world', elevation=24))
am.clear()
mb.clear()
def on_resize(*l, **kw):
global g, layout
g.width = getdim(doc.querySelector('body')).width
g.height = getdim(doc.querySelector('body')).height
layout = 'landscape' if g.width > 900 else 'portrait'
g.update()
# do layout changes with this
window.addEventListener('resize', on_resize);
def on_scroll(self, *l, **kw):
if window.pageYOffset == 0:
pass
else:
pass
# do layout changes with this
window.addEventListener('scroll', on_scroll);
def tint(r, g, b, a, val):
'''Tints rgb values to apply 'white' layer to materials'''
rt = r + (val * (255 - r))
gt = g + (val * (255 - g))
bt = b + (val * (255 - b))
return (rt, gt, bt, a)
class Space(DIV):
def __init__(self, *l, **kw):
super().__init__(*l, style={'position': 'absolute', 'margin': '0px', 'padding': '0px',
'display': 'flex',
'transition-timing-function': 'cubic-bezier(0.4, 0.0, 0.2, 1)',
'transition': 'all 0.3s',
'box-sizing': 'border-box',}, **kw)
class Flex(DIV):
opacities = {0: 0, 1: .05, 2: .07, 3: .08, 4: .09, 6: .11, 8: .12, 12: .14, 16: .15, 24: .16}
shadows = {0: 'none',
1: '0 1px 1px 0 rgba(0,0,0,0.14), 0 2px 1px -1px rgba(0,0,0,0.12), 0 1px 3px 0 rgba(0,0,0,0.20)',
2: '0 2px 2px 0 rgba(0,0,0,0.14), 0 3px 1px -2px rgba(0,0,0,0.12), 0 1px 5px 0 rgba(0,0,0,0.20)',
3: '0 3px 4px 0 rgba(0,0,0,0.14), 0 3px 3px -2px rgba(0,0,0,0.12), 0 1px 8px 0 rgba(0,0,0,0.20)',
4: '0 4px 5px 0 rgba(0,0,0,0.14), 0 1px 10px 0 rgba(0,0,0,0.12), 0 2px 4px -1px rgba(0,0,0,0.20)',
6: '0 6px 10px 0 rgba(0,0,0,0.14), 0 1px 18px 0 rgba(0,0,0,0.12), 0 3px 5px -1px rgba(0,0,0,0.20)',
8: '0 8px 10px 1px rgba(0,0,0,0.14), 0 3px 14px 2px rgba(0,0,0,0.12), 0 5px 5px -3px rgba(0,0,0,0.20)',
12: '0 12px 17px 2px rgba(0,0,0,0.14), 0 5px 22px 4px rgba(0,0,0,0.12), 0 7px 8px -4px rgba(0,0,0,0.20)',
16: '0 16px 24px 2px rgba(0,0,0,0.14), 0 6px 30px 5px rgba(0,0,0,0.12), 0 8px 10px -5px rgba(0,0,0,0.20)',
24: '0 24px 38px 3px rgba(0,0,0,0.14), 0 9px 46px 8px rgba(0,0,0,0.12), 0 11px 15px -7px rgba(0,0,0,0.20)',}
def __init__(self, *l, color=(18, 18, 18, 1), padding='12px 18px', elevation=0, flow='row wrap', justify='flex-start', align_items='stretch', align_content='stretch', grow=1, flat=False, style={}, **kw):
base_style = {
#'position': 'absolute',
'border': 'none',
'margin': '8px',
'border-radius': '5px',
'font-size': '16px',
'cursor': 'default',
'color': 'white',
'outline': 'none',
#'background': f'rgba{color}',
'display': 'flex',
'transition-timing-function': 'cubic-bezier(0.4, 0.0, 0.2, 1)',
'transition': 'all 0.3s',
'box-sizing': 'border-box',
'overflow': 'auto',
}
base_style.update(style)
super().__init__(*l, style=base_style, **kw)
self.__color = color
self.__elevation = elevation
self.flat = flat
self.color = color
self.padding = padding
self.elevation = elevation
self.flow = flow
self.justify = justify
self.align_items = align_items
self.align_content = align_content
self.grow = grow
@property
def color(self):
return self.__color
@color.setter
def color(self, value):
self.__color = value
if not self.flat:
self.style['background'] = f'rgba{tint(*value, self.opacities[self.elevation])}'
else:
self.style['background'] = f'rgba(255, 255, 255, {self.opacities[self.elevation]})'
@property
def padding(self):
return self.__padding
@padding.setter
def padding(self, value):
self.__padding = value
self.style['padding'] = value
@property
def elevation(self):
return self.__elevation
@elevation.setter
def elevation(self, value):
self.__elevation = value
if not self.flat:
self.style['background'] = f'rgba{tint(*self.color, self.opacities[value])}'
self.style['box-shadow'] = self.shadows[value]
else:
self.style['background'] = f'rgba(255, 255, 255, {self.opacities[value]})'
@property
def flow(self):
'''
row (default): left to right in ltr; right to left in rtl
row-reverse: right to left in ltr; left to right in rtl
column: same as row but top to bottom
column-reverse: same as row-reverse but bottom to top
nowrap (default): all flex items will be on one line
wrap: flex items will wrap onto multiple lines, from top to bottom.
wrap-reverse: flex items will wrap onto multiple lines from bottom to top.
'''
return self.__flow
@flow.setter
def flow(self, value):
self.__flow = value
self.style['flex-flow'] = value
@property
def justify(self):
'''
flex-start (default): items are packed toward the start of the flex-direction.
flex-end: items are packed toward the end of the flex-direction.
start: items are packed toward the start of the writing-mode direction.
end: items are packed toward the end of the writing-mode direction.
left: items are packed toward left edge of the container, unless that doesn't make sense with the flex-direction, then it behaves like start.
right: items are packed toward right edge of the container, unless that doesn't make sense with the flex-direction, then it behaves like start.
center: items are centered along the line
space-between: items are evenly distributed in the line; first item is on the start line, last item on the end line
space-around: items are evenly distributed in the line with equal space around them. Note that visually the spaces aren't equal, since all the items have equal space on both sides. The first item will have one unit of space against the container edge, but two units of space between the next item because that next item has its own spacing that applies.
space-evenly: items are distributed so that the spacing between any two items (and the space to the edges) is equal.
'''
return self.__justify
@justify.setter
def justify(self, value):
self.__justify = value
self.style['justify-content'] = value
@property
def align_items(self):
'''
stretch (default): stretch to fill the container (still respect min-width/max-width)
flex-start / start / self-start: items are placed at the start of the cross axis. The difference between these is subtle, and is about respecting the flex-direction rules or the writing-mode rules.
flex-end / end / self-end: items are placed at the end of the cross axis. The difference again is subtle and is about respecting flex-direction rules vs. writing-mode rules.
center: items are centered in the cross-axis
baseline: items are aligned such as their baselines align
'''
return self.__align_items
@align_items.setter
def align_items(self, value):
self.__align_items = value
self.style['align-items'] = value
@property
def align_content(self):
'''
flex-start / start: items packed to the start of the container. The (more supported) flex-start honors the flex-direction while start honors the writing-mode direction.
flex-end / end: items packed to the end of the container. The (more support) flex-end honors the flex-direction while end honors the writing-mode direction.
center: items centered in the container
space-between: items evenly distributed; the first line is at the start of the container while the last one is at the end
space-around: items evenly distributed with equal space around each line
space-evenly: items are evenly distributed with equal space around them
stretch (default): lines stretch to take up the remaining space
'''
return self.__align_content
@align_content.setter
def align_content(self, value):
self.__align_content = value
self.style['align-content'] = value
@property
def grow(self):
return self.__grow
@grow.setter
def grow(self, value):
self.__grow = value
self.style['flex-grow'] = value
def __repr__(self):
return "{" + f"'flat': {repr(self.flat)}, 'color': {repr(self.color)}, 'padding': {repr(self.padding)}, 'elevation': {repr(self.elevation)}, 'flow': {repr(self.flow)}, 'justify': {repr(self.justify)}, 'align_items': {repr(self.align_items)}, 'align_content': {repr(self.align_content)}" + "}"
class Textbox(TEXTAREA, Flex):
def __init__(self, *l, placeholder='', name='', **kw):
Flex.__init__(self, *l, **kw)
self.setAttribute('placeholder', placeholder)
self.setAttribute('name', name)
self.style['border-bottom'] = f'solid 2px rgba{tint(*(0, 0, 128, 1), self.opacities[6])}'
self.base_elevation = kw.get('elevation', 0)
self.bind('mouseenter', lambda ev: setattr(self, 'elevation', self.base_elevation + 2))
self.bind('mouseleave', lambda ev: setattr(self, 'elevation', self.base_elevation))
self.bind('focus', lambda ev: setattr(self, 'elevation', self.base_elevation + 2))
self.bind('blur', lambda ev: setattr(self, 'elevation', self.base_elevation))
class Input(INPUT, Flex):
def __init__(self, text='', placeholder='', _list='', name='', _type='', force_list=False, *l, **kw):
Flex.__init__(self, *l, **kw)
self.setAttribute('value', text)
self.setAttribute('placeholder', placeholder)
self.setAttribute('name', name)
self.setAttribute('type', _type)
self.setAttribute('list', _list)
self._list = _list
self.placeholder = placeholder
if not kw.get('flat', False):
self.style['border-bottom'] = f'solid 2px rgba{tint(*(32, 32, 128, 1), self.opacities[6])}'
self.base_elevation = kw.get('elevation', 0)
self.bind('mouseenter', lambda ev: setattr(self, 'elevation', self.base_elevation + 2))
self.bind('mouseleave', lambda ev: setattr(self, 'elevation', self.base_elevation))
self.bind('focus', lambda ev: setattr(self, 'elevation', self.base_elevation + 2))
self.bind('blur', lambda ev: setattr(self, 'elevation', self.base_elevation))
if force_list:
def erase(ev):
if self.value:
self.placeholder = self.value
self.value = ''
def force(ev):
dataset = doc.querySelector(f'#{self._list}').possibilities
if not self.value:
if self.placeholder in dataset:
self.value = self.placeholder
else:
self.value = dataset[0]
else:
for opt in dataset:
if self.value.lower() in opt.lower():
self.value = opt
break
else:
self.value = dataset[0]
self.bind('focus', erase)
self.bind('click', erase)
self.bind('blur', force)
force(None)
@property
def placeholder(self):
return self.__placeholder
@placeholder.setter
def placeholder(self, value):
self.__placeholder = value
self.setAttribute('placeholder', value)
class InputOptions(DATALIST):
def __init__(self, possibilities, *l, **kw):
self.possibilities = possibilities
super().__init__(*l, **kw)
self.update()
def update(self):
self.clear()
for opt in self.possibilities:
self <= OPTION(value=opt)
def __repr__(self):
return "{" + f"'possibilities': {repr(self.possibilities)}" + "}"
class Edge(Flex):
def __init__(self, *l, **kw):
super().__init__(*l, **kw, padding='0px')
self.style['border-radius'] = '0px'
self.style['margin'] = '0px'
class Menu(Flex):
def __init__(self, *l, **kw):
super().__init__(*l, **kw, elevation=8, flow='column wrap')
self.style['width'] = '300px'
class Card(Flex):
pass
class Label(Card):
def __init__(self, *l, flow='column', justify='center', flat=True, **kw):
super().__init__(*l, flow=flow, justify=justify, flat=flat, **kw)
class Button(Flex):
def __init__(self, *l, elevation=0, flat=False, raised=False, flow='column', justify='center', align_items='center', **kw):
if raised:
elevation = 2
else:
flat = True
super().__init__(*l,
elevation=elevation,
flat=flat,
tabindex=0,
justify=justify,
flow=flow,
align_items=align_items,
**kw)
self.base_elevation = elevation
self.bind('mouseenter', lambda ev: setattr(self, 'elevation', self.base_elevation + 6))
self.bind('mouseleave', lambda ev: setattr(self, 'elevation', self.base_elevation))
self.bind('focus', lambda ev: setattr(self, 'elevation', self.base_elevation + 6))
self.bind('blur', lambda ev: setattr(self, 'elevation', self.base_elevation))
self.bind('keyup', self.on_enter)
def on_enter(self, ev):
if ev.keyCode in (13, 32):
ev.preventDefault()
self.click()
class Fab(Button):
def __init__(self, icon, *l, **kw):
super().__init__(Icon(icon), elevation=6, raised=True, *l, **kw)
self.style['padding'] = '18px'
self.style['border-radius'] = '50%'
self.icon = icon
@property
def icon(self):
return self.__icon
@icon.setter
def icon(self, value):
self.__icon = value
self.children[0].icon = value
def __repr__(self):
return "{" + f"'icon': {repr(self.icon)}" + "}"
class Icon(I):
def __init__(self, icon, *l, **kw):
super().__init__(Class='material-icons', *l, **kw)
self.icon = icon
@property
def icon(self):
return self.__icon
@icon.setter
def icon(self, value):
self.__icon = value
self.innerHTML = value
def __repr__(self):
return "{" + f"'icon': {repr(self.icon)}" + "}"
anim = {'transition-timing-function': 'cubic-bezier(0.4, 0.0, 0.2, 1)',
'transition': 'all 0.3s'}
def center(el):
'bottom height left right top width'
root = getdim(doc.querySelector('body'))
eldim = getdim(el)
el.left = int(root.center[0] - eldim.width//2)
el.top = int(root.center[1] - eldim.height//2)
# ready the aio tasks
async def main():
res = await aio.gather(ui())
for k, v in res.items():
print(f'{k}: {v}')
# --- would be imports
# small hacks to be more asyncio like
from browser import aio
def Task(coro, Id, block):
async def _task():
block[Id] = None
try:
block[Id] = await coro
except Exception as e:
block[Id] = e
if not block[Id]:
del block[Id]
return _task()
async def gather(*coros, rate=0):
dones = {}
counts = 0 # only task0, task1, task2 because brython coro is missing __name__
for c in coros:
aio.run(aio.Task(c, f'task{counts}', dones))
counts += 1
while not all(dones.values()):
await aio.sleep(rate)
return dones
aio.gather = gather
aio.Task = Task
class Event:
'''
Asyncio primitive, Event.
https://docs.python.org/3/library/asyncio-sync.html
'''
def __init__(self, *):
self._set = False
async def wait(self):
while not self._set:
await aio.sleep(0)
def is_set(self):
return self._set
def set(self):
self._set = True
def clear(self):
self._set = False
aio.Event = Event
class Lock:
def __init__(self, *):
self._locked = False
async def acquire(self):
while self._locked:
await aio.sleep(0)
self._locked = True
def release(self):
if not self._locked:
raise RuntimeError('Lock is already released')
self._locked = False
def locked(self):
return self._locked
async def __aenter__(self):
await self.acquire()
return self
async def __aexit__(self, *l):
self.release()
aio.Lock = Lock
class Semaphore:
def __init__(self, value=1, *):
self._locked = False
self.count = value
self.limit = value
async def acquire(self):
while self.count < 1:
await aio.sleep(0)
self.count -= 1
def release(self):
self.count = min(self.count + 1, self.limit)
def locked(self):
return self.count == 0
async def __aenter__(self):
await self.acquire()
return self
async def __aexit__(self, *l):
self.release()
aio.Semaphore = Semaphore
class Snack(Label):
lock = aio.Lock()
def __init__(self, *l, delay=5, **kw):
self.delay = delay
super().__init__(*l, **kw, elevation=6, flat=False)
self.style['width'] = '100%'
self.style['border-radius'] = '0px'
self.style['position'] = 'fixed'
self.style['margin'] = '0px'
self.style['bottom'] = '-48px'
self.style['height'] = '48px'
doc <= self
aio.run(self.show())
async def show(self):
await self.lock.acquire()
await aio.sleep(.05)
self.style['bottom'] = 0
await aio.sleep(.3 + self.delay)
await self.hide()
async def hide(self):
self.style['bottom'] = '-48px'
await aio.sleep(.3)
self.remove()
self.lock.release()
def __repr__(self):
return "{" + f"'delay': {repr(self.delay)}" + "}"
class Dimension:
def __init__(self, bottom, height, left, right, top, width):
self.bottom = bottom
self.height = height
self.left = left
self.right = right
self.top = top
self.width = width
self.center = (left + (width/2), top + (height/2))
def __repr__(self):
return "{" + f"'top': {repr(self.top)}, 'bottom': {repr(self.bottom)}, 'left': {repr(self.left)}, 'right': {repr(self.right)}, 'height': {repr(self.height)}, 'width': {repr(self.width)}, 'center': {repr(self.center)}" + "}"
def getdim(el):
br = el.getBoundingClientRect()
out = {
'bottom': br.bottom,
'height': br.height,
'left': br.left,
'right': br.right,
'top': br.top,
'width': br.width
}
return Dimension(**out)
#async def keybind():
# muted_events = ['Meta', 'Shift', 'Control', 'Alt']
#
# aio.cancel_event(doc)
# ev = await aio.select_event(doc, 'keyup keydown')
# while ev.type != 'cancel':
# ctrl = ev.getModifierState('Control')
# alt = ev.getModifierState('Alt')
# shift = ev.getModifierState('Shift')
#
# if ev.key not in muted_events and type(ev.target) not in (TEXTAREA, INPUT):
# if ev.type == 'keyup':
# #print(f'key up {ev.key}')
# pass
# elif ev.type == 'keydown':
# #print(f'key down {ev.key}')
# pass
#
# ev = await aio.select_event(doc, 'keyup keydown')
class Stagger:
def __init__(self, base_delay, rate):
self.delay = base_delay
self.rate = rate
async def delay_fun(self, fun, delay):
await aio.sleep(delay)
fun()
def stagger(self, fun):
aio.run(self.delay_fun(fun, self.delay))
self.delay += self.rate
def __enter__(self):
return self.stagger
def __exit__(self, *_):
pass
class Popup:
lock = aio.Lock()
def __init__(self, _root):
self._root = _root
self.frame = DIV(Class='darken', Id='popupbg', style={
'background': 'rgba(0, 0, 0, 0)',
'transition': 'background .3s',
'transition-timing-function': 'cubic-bezier(0.4, 0.0, 0.2, 1)',
'width': '100%',
'height': '100%',
'position': 'fixed',
'top': '0px',
'left': '0px',
'z-index': '1',
})
self.box = DIV(Id='popup', style={
'position': 'fixed',
'opacity': 0,
'transition': 'opacity .3s, top .3s',
'transition-timing-function': 'cubic-bezier(0.4, 0.0, 0.2, 1)',
'border': 'none',
'color': 'white',
'outline': 'none',
'z-index': '1',
'max-height': '100%',
'max-width': '100%',
})
async def __aenter__(self):
await self.lock.acquire()
self._root <= self.frame
self._root <= self.box
await aio.sleep(.05)
self.frame.style['background'] = 'rgba(0, 0, 0, .5)'
self.box.style['opacity'] = 1
return self.box
async def __aexit__(self, type, value, traceback):
self.frame.style['background'] = 'rgba(0, 0, 0, 0)'
self.box.style['opacity'] = 0
await aio.sleep(.4)
self.frame.remove()
self.box.remove()
self.lock.release()
async def popup(content):
async with Popup(doc) as p:
p <= content
center(p)
with UIEvent(doc['popupbg'], 'click') as pbg:
while not pbg:
await aio.sleep(0)
def gmap(grid, obj, x, y, endx=None, endy=None):
if endx is None:
endx = x
if endy is None:
endy = y
obj.left, obj.top = *grid.cells[x][y].topleft
obj.width, obj.height = *grid.cells[endx][endy].bottomright
obj.width -= obj.left
obj.height -= obj.top
class Point:
__slots__ = 'x', 'y'
def __init__(self, x=0, y=0):
self.x = round(x)
self.y = round(y)
def __iter__(self):
yield from (self.x, self.y)
def __repr__(self):
return "{" + f"'x': {repr(self.x)}, 'y': {repr(self.y)}" + "}"
class Cell:
__slots__ = '_Cell__topleft', '_Cell__bottomright', 'width', 'height', 'center', 'bottomleft', 'topright'
def __init__(self, topleft={'x': 0, 'y': 0}, bottomright={'x': 0, 'y': 0}):
self.__topleft = Point()
self.__bottomright = Point()
self.topleft = topleft
self.bottomright = bottomright
@property
def topleft(self):
return self.__topleft
@topleft.setter
def topleft(self, value):
self.__topleft = value if type(value) is Point else Point(**value)
self.width = self.bottomright.x - self.topleft.x
self.height = self.bottomright.y - self.topleft.y
self.center = Point(self.topleft.x + round(self.width/2.0), self.topleft.y + round(self.height/2.0))
self.bottomleft = Point(self.topleft.x, self.bottomright.y)
self.topright = Point(self.bottomright.x, self.topleft.y)
@property
def bottomright(self):
return self.__bottomright
@bottomright.setter
def bottomright(self, value):
self.__bottomright = value if type(value) is Point else Point(**value)
self.width = self.bottomright.x - self.topleft.x
self.height = self.bottomright.y - self.topleft.y
self.center = Point(self.topleft.x + round(self.width/2.0), self.topleft.y + round(self.height/2.0))
self.bottomleft = Point(self.topleft.x, self.bottomright.y)
self.topright = Point(self.bottomright.x, self.topleft.y)
def __repr__(self):
return "{" + f"'bottomright': {repr(self.bottomright)}, 'bottomleft': {repr(self.bottomleft)}, 'topright': {repr(self.topright)}, 'topleft': {repr(self.topleft)}, 'width': {repr(self.width)}, 'height': {repr(self.height)}, 'center': {repr(self.center)}" + "}"
#def gmap(grid, col, row, obj, width=0, height=0):
# if col < 0:
# col += len(grid.cols)
# if row < 0:
# row += len(grid.rows)
# obj.top = grid.cells[row][col].topleft.y
# obj.left = grid.cells[row][col].topleft.x
#
# obj.width = grid.cells[row+height][col+width].bottomright.x - obj.left
# obj.height = grid.cells[row+height][col+width].bottomright.y - obj.top
class Gridman:
__slots__ = 'cols', 'rows', 'width', 'height', 'left', 'top', '_cbs', 'cells'
def __init__(self, cols=[], rows=[], width=0, height=0, left=0, top=0):
self.cols = cols
self.rows = rows
self.width = width
self.height = height
self.left = left
self.top = top
self._cbs = {}
self.cells = []
self.update()
def update(self):
self.cells.clear()
self.cells.extend(list() for i in range(len(self.cols)))
for col in self.cells:
col.extend(Cell() for i in range(len(self.rows)))
widths = []
for col in self.cols:
if col != ...:
if col < 1:
widths.append(col*self.width)
else:
widths.append(col)
else:
widths.append(...)
remainder = max(0, self.width - sum(i for i in widths if i!=...))
buffs = 0
if ... in widths:
widths[widths.index(...)] = remainder
else:
buffs = remainder/2
last = buffs + self.left
lefts = [buffs + self.left]
for width in widths:
lefts.append(width + last)
last += width
heights = []
for row in self.rows:
if row != ...:
if row < 1:
heights.append(row*self.height)
else:
heights.append(row)
else:
heights.append(...)
remainder = max(0, self.height - sum(i for i in heights if i!=...))
buffs = 0
if ... in heights:
heights[heights.index(...)] = remainder
else:
buffs = remainder/2
last = buffs + self.top
tops = [buffs + self.top]
for height in heights:
tops.append(height + last)
last += height
for ci, col in enumerate(lefts[:-1]):
for ri, row in enumerate(tops[:-1]):
self.cells[ci][ri].topleft = Point(col, row)
self.cells[ci][ri].bottomright = Point(lefts[ci+1], tops[ri+1])
self.dispatch('update')
def bind(self, **kwargs):
for k, v in kwargs.items():
if k not in self._cbs:
self._cbs[k] = []
self._cbs[k].append(v)
def unbind(self, **kwargs):
for k, v in kwargs.items():
self._cbs[k].remove(v)
if not self._cbs[k]:
del self._cbs[k]
def dispatch(self, prop, *l, **kw):
if getattr(self, f'on_{prop}', None):
getattr(self, f'on_{prop}')(prop, *l, **kw)
if prop in self._cbs:
for cb in self._cbs[prop]:
cb(self, prop, *l, **kw)
def __repr__(self):
return "{" + f"'cols': {repr(self.cols)}, 'rows': {repr(self.rows)}, 'width': {repr(self.width)}, 'height': {repr(self.height)}, 'left': {repr(self.left)}, 'top': {repr(self.top)}" + "}"
class Event:
__slots__ = 'tar', 'events', 'out'
def __init__(self, tar, *events):
self.tar = tar
self.events = {e: lambda _self, *l, **kw: self.out.append((_self, l, kw)) for e in events}
self.out = []
def __enter__(self):
for k, v in self.events.items():
self.tar.bind(**{k: v})
return self.out
def __exit__(self, *l):
for k, v in self.events.items():
self.tar.unbind(**{k: v})
class UIEvent:
__slots__ = 'tar', 'events', 'out'
def __init__(self, tar, *events):
self.tar = tar
self.events = {e: lambda ev: self.out.append(ev) for e in events}
self.out = []
def __enter__(self):
for k, v in self.events.items():
self.tar.bind(k, v)
return self.out
def __exit__(self, *l):
for k, v in self.events.items():
self.tar.unbind(k, v)
async def _any(_iterable):
'Await for any(_iterable) to be true'
while not any(_iterable):
await aio.sleep(0)
class Any:
'With version of _any. Auto flushes the lists on exit'
__slots__ = '_iterable'
def __init__(self, _iterable):
self._iterable = _iterable
async def __aenter__(self):
await _any(self._iterable)
async def __aexit__(self, *l):
for i in self._iterable: