-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuykHtml.py
2468 lines (2162 loc) · 97.7 KB
/
QuykHtml.py
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
import os
import sys
import time
import random
from time import sleep
import copy
import platform
import subprocess
print('############################################')
print('Thank you for using QuykHtml.\nAny donation for my hard work is GREATLY appreciated')
print('You can donate to my cash app:\n\n\t$elmling\n')
print('I hope you continue to enjoy using QuykHtml!')
print('############################################')
class qhtml:
"""
Main qhtml class
"""
def __init__(self):
# Variables
# -------------------------------------
self.all = []
self.scripts = []
self.scripts_on_page_load = []
self.scripts_draggable = False
self.scripts_img_group = False
self.scripts_img_group_time = 5000
self.head = []
self.css = self._css()
self.display = self.new("div").style.append('background-color:transparent;')
self.bootstrap = self.bootstrap()
self.preview = self.new("div")
self.last = None # type: qhtml._q_element
self.seo = self.__seo(self)
self._animation_scripts = False
self.themes = self._themes(self)
self.__body_background = ''
self._htmlData = {}
def express(self, expression_or_file):
"""
allows you to easily create bootstrap rows/columns\n\n
you can also load from a .exp file\n\n
example code usage: express_obj = q.express([ ['p text="text1"','p text="text2"','p text="text3"'] ])\n\n
example file usage: express_obj = q.express("path/to/express/file.exp")\n\n
inside file.exp would look like so:\n\n
'p text="text1"|p text="text2"|p text="text3"\n\n
basically providing a file is using a markup language to instantiate qhtml objects
"""
errorMsg = 'express method error: '
results2 = self.new('div')
# print("Expression: " + str(expression_or_file))
if type(expression_or_file) is list:
expression = expression_or_file
# print("Expression: " + expression.__str__())
results = []
row_index = 0
for row in expression:
if type(row) is not list:
print('express method formatting error, cannot build expression:\n' + expression.__str__())
row_index += 1
col_index = 0
rowd = self.new('div').set_class('row')
for col in row:
element_type = col.split()[0]
element_attrs = col.split()
element_attrs.pop(0)
element_attrs = ' '.join(element_attrs)
col_index += 1
obj = self.new(element_type)
for attr in element_attrs.split('" '):
if len(attr) > 0:
_keyword = attr[:attr.find('="')]
if 'attr-' in _keyword:
call = attr[attr.find('='):attr.find(')')]
# callattr = attr[:attr.find('" ')]
callattr = attr[attr.find('-') + 1:] + '"'
obj.add_attribute(callattr)
print(obj.attributes)
elif 'style' in _keyword:
has_function = hasattr(obj.style, 'set')
if has_function:
method = getattr(obj.style, 'set')
call = attr[attr.find('=') + 1:].replace('"', "").replace("'", "")
method(call)
else:
print(
errorMsg + ' could not apply attribute \'' + _keyword + '\', try attr-' + _keyword + ' to set actual HTML attributes')
elif 'text' in _keyword:
obj.set_text(attr[attr.find('=') + 1:].replace('"', "").replace("'", ""))
else:
has_function = hasattr(obj, 'set_' + _keyword)
if has_function:
method = getattr(obj, 'set_' + _keyword)
call = attr[attr.find('=') + 1:].replace('"', "").replace("'", "")
# print('calling method with ' + call)
method(call)
else:
print(
errorMsg + ' could not apply attribute \'' + _keyword + '\', try attr-' + _keyword + ' to set actual HTML attributes')
container = self.new('div').col().insert(obj)
# obj.set_class('col', append=True)
obj.meta = col + ' at row ' + str(row_index) + ', column ' + str(col_index)
results.append(container)
rowd.insert(container)
results2.insert(rowd)
else:
file = -1
if os.path.exists(expression_or_file):
file = expression_or_file
elif os.path.exists(os.getcwd() + '/Expressions/' + expression_or_file):
file = os.getcwd() + '/Expressions/' + expression_or_file
if file != -1:
r = self.file_read(file)
rs = r.split('\n')
mainlist = []
rowlist = []
for row in rs:
if row == "":
continue
# print(row)
cs = row.split('|')
for col in cs:
col = col.strip()
# print(col)
rowlist.append(col)
mainlist.append(rowlist)
rowlist = []
# print('main list - > ' + str(mainlist))
results2 = self.express(mainlist)
return results2
def new(self, _type):
"""
Returns a new q_element object
div, pre, p, a, img, iframe, etc
"""
_split = _type.split(" ")
_obj = ""
if len(_split) > 1:
_first = _split[0]
_second = _split[1]
if "button" in _first or "input" in _first:
if _second == "br":
_container = self._q_element("div")
_br = self._q_element("br")
_obj = self._q_element(_first)
_container.insert([_obj, _br])
_obj.parent = self
self.last = _obj
self.all.append(_container)
self.all.append(_br)
self.all.append(_obj)
return _container # type: qhtml._q_element
else:
return False
else:
return False
else:
_obj = self._q_element(_type)
_obj.parent = self
self.all.append(_obj)
self.last = _obj
return _obj # type: qhtml._q_element
def webbrowser_open(self, path):
if sys.platform == 'win32':
os.startfile(path)
elif sys.platform == 'darwin':
subprocess.Popen(['open', path])
else:
try:
subprocess.Popen(['xdg-open', path])
except OSError:
print
'Please open a browser on: ' + path
def img_group(self, sources: list, transition_delay=5, force_img_size=(-1,-1)):
"""
Creates an image group to be used for image transitions, ie:\n
img_group = q.img_group(["img1.com","img2.com","img3.com"],5)\n
q.display.insert(img_group).render()\n
Which will render a single image element that cycles through sources
force_img_size takes a tuple of width and height to force all images to adhere to (pixels)
:param sources:
:param transition_delay:
:param force_img_size
:return:
"""
_ran = []
for i in range(5):
_ran.append(str(random.randint(0, 9)))
_ran = ''.join(_ran)
ms = transition_delay * 1000
_img = self.new("img").set_img_src(sources[0]).scripts_add(
"quykHtml_register('img_group_" + str(_ran) + "'," + str(sources) + ");", on_page_load=True
).set_id('img_group_' + str(_ran))
if force_img_size[0] != -1 and force_img_size[1] != -1:
_img.style.append('width:' + str(force_img_size[0]) + ';height:' + str(force_img_size[1]))
ig = self.new("div").insert([
_img
])
self.scripts_img_group = True
self.scripts_img_group_time = ms
return ig
def dupe(self, q_element):
"""
Dupes an element:\n
p = q.new('p').set_text('hi')\n
p_dupe = q.dupe(p).style.set('background-color:gray;')\n
"""
if isinstance(q_element, self._q_element):
new = copy.deepcopy(q_element)
new.parent = self
self.all.append(new)
return new
else:
print('q_element instance is not valid or was not provided.')
return False
def prettify_html(self, html):
return html
def render(self, output_file="render.html", only_html=False, set_clip_board=False, prettify_html=True):
"""
Renders a file, returns the html generated
"""
if "." not in output_file:
output_file = output_file + ".html"
_css = ""
_scripts = ""
_scripts_on_page_load = ""
_head_append = ""
_bootstrap = ""
_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'
if not os.path.exists(_path):
_path = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
if not os.path.exists(_path):
_path = os.getenv('APPDATA') + '/Google/Chrome/Application/chrome.exe'
if not os.path.exists(_path):
print('Could not find google chrome. Trying to Render html file via default browser.')
_path = _path + ' %s'
_preview_scripts_loaded = False
for _obj_element in self.all:
if _obj_element.has_preview() and _preview_scripts_loaded is False:
self.__get_preview_scripts()
_preview_scripts_loaded = True
# noinspection PyProtectedMember
if _obj_element._ajax_code != "":
# noinspection PyProtectedMember
self.scripts.append(_obj_element._ajax_code)
if len(_obj_element.scripts_on_page_load) > 0:
for __scr in _obj_element.scripts_on_page_load:
_scripts_on_page_load += __scr
if len(_obj_element.scripts) > 0:
_build = ""
for _scr in _obj_element.scripts:
_build += _scr
self.scripts.append(_build)
if self.bootstrap.using():
_bootstrap = self.bootstrap.get()
for _s in self.css.styles:
_css = _css + "" + _s
for _sc in self.scripts:
_scripts = _scripts + "" + _sc + "\n"
if self.scripts_img_group is True:
img_data = 'var cycle_data = {' \
'speed:' + str(self.scripts_img_group_time) + ',' \
'};' \
'cycle_data.cycles = [];' \
'setInterval(function() {quykHtml_cycle_images()}, cycle_data.speed);' \
'function quykHtml_register(element_id, images_array) {' \
'cycle_data.cycles.push({id:element_id,images:images_array,index:-1});' \
'}' \
'function quykHtml_cycle_images() {' \
'for(var i = 0; i < cycle_data.cycles.length; i++) {' \
'var d = cycle_data.cycles[i];' \
'var id = d.id;' \
'var images = d.images;' \
'd.index = d.index + 1;' \
'var ind = d.index;' \
'var image = images[ind];' \
'var el = document.getElementById(id);' \
'if(el) {' \
' el.src = image;' \
'} else {' \
'' \
'}' \
'if(ind >= images.length-1) {' \
' d.index = -1;' \
'}' \
'}' \
'}'
_scripts = _scripts + img_data
for h in self.head:
_head_append += h + "\n"
if _preview_scripts_loaded:
self.display.insert(self.preview)
if _scripts_on_page_load != "":
_scripts_on_page_load = ' window.addEventListener("load", on_page_load_init); function on_page_load_init() {' + _scripts_on_page_load + '}'
if _scripts != "" or _scripts_on_page_load != "" or self._animation_scripts:
_anim_scripts = ""
if self._animation_scripts:
_anim_scripts = self.__get_anim_scripts()
_scripts = '<script type="text/javascript">' + _scripts + '' + _scripts_on_page_load + _anim_scripts + '</script>'
if self.__body_background:
print('body background - >\n' + self.__body_background)
# html_string = "<head>" + _head_append + _bootstrap + "<style>" + _css + '</style>' + _scripts + '</head><body' + self.__body_background + '>' + str(self.display.html()) + '</body>'
html_string = "<head>" + _head_append + _bootstrap + "<style>" + _css + '</style>' + _scripts + '</head><body' + self.__body_background + '>' + str(
self.display.innerHtml(full_html=True)) + '</body>'
f = open(os.getcwd() + "/" + output_file, "w")
f.write(html_string)
f.close()
sleep(0.2)
if prettify_html:
html_string = self.prettify_html(html_string)
if not only_html:
if 'chrome' not in _path.lower():
self.webbrowser_open(str(os.getcwd()) + "/" + output_file)
else:
self.webbrowser_open(str(os.getcwd()) + "/" + output_file)
if set_clip_board:
self.clip_put(html_string)
return html_string
def col(self):
"""
Returns a new div with the col class set for bootstrap
:return: _q_element
"""
return self.new('div').col()
def row(self):
"""
Returns a new div with the row class set for bootstrap
:return: _q_element
"""
return self.new('div').row()
def clip_put(self, _str):
"""
Attempts to put a string to your clipboard
"""
copy_keyword = ""
if platform.system() == 'Darwin':
copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
copy_keyword = 'clip'
else:
print('Could not copy to clipboard for some reason.')
return False
subprocess.run(copy_keyword, universal_newlines=True, input=_str)
# Easily read a file. Returns the file's contents as a string
# returns: file-contents/boolean
def file_read(self, file_name, file_path='', to_list=False):
"""
Easily read a file. Returns the file's contents as a string
"""
s = self
if file_name:
if file_path:
dir_path = file_path
else:
dir_path = os.path.dirname(os.path.realpath(__file__)) + '/'
f = ""
read = ""
try:
f = open(dir_path + file_name, 'r')
except:
f = open(file_name, 'r')
read = f.read()
f.close()
if to_list:
read = read.split('\n')
return read
return False
def set_body_background(self, _src, _transparency_strength=0.15, background_attachment='fixed'):
"""Set the body background image for the page.\n
Transparency Range (0,1) | 1 = full transparency
"""
self.__body_background = ' style="background: linear-gradient(rgba(255,255,255,' + str(
_transparency_strength) + '), rgba(255,255,255,' + str(_transparency_strength) + ')),'
self.__body_background += 'url(\'' + _src + '\');background-attachment:' + background_attachment + ';background-repeat:no-repeat;background-position:center;background-size: cover;"'
return self
def __get_preview_scripts(self):
# ** PREVIEW HELPER **
# -------------------------------------------------------------
# Preview helper for on_click_show_preview. Shows the element
# object that was clicked in full screen. Good for images, but
# can be used with any element created by qhtml.new(type)
# -------------------------------------------------------------
self.css.add(".quykHtml_preview",
"display:none;padding-top:60px;text-align:center;z-index:100;position:fixed;top:0;width:100%;height:100%;background-color:rgba(255,255,255,0.9);")
self.preview.set_class("quykHtml_preview").add_attribute('id="quykHtml_preview"')
# preview display code
self.scripts.append(
'function quykHtml_showPreview(el){'
'd = document.getElementById("quykHtml_preview");'
'if(d.style.display == "none" || d.style.display == ""){'
'd.style.display = "inline";'
'var node = el.cloneNode(true);'
'node.className = "strat-img-no-hover";'
'if(node.tagName.toLowerCase() == "img"){'
'node.style.height = "640px";'
'node.style.width = "800px";'
'}'
'd.appendChild(node);'
'd.innerHTML = d.innerHTML + "<p style=\'font-weight:bold;font-size:20px;\'>Press Escape to close or click <span onclick=\'quykHtml_preview_close();\' style=\'cursor:pointer;color:green;font-size:24px;\'>here</span></p>";'
'}'
'}'
)
# preview display escape key press code
self.scripts.append(
'document.onkeydown = function(evt) {'
'evt = evt || window.event;'
'var isEscape = false;'
'if ("key" in evt) {'
'isEscape = (evt.key === "Escape" || evt.key === "Esc");'
'} else {'
'isEscape = (evt.keyCode === 27);'
'}'
'if(isEscape){'
'd = document.getElementById("quykHtml_preview");'
'if(d){'
'if(d.style.display != "none"){'
'd.innerHTML = "";'
'd.style.display = "none";'
'}'
'}}};'
)
# preview display click here escape option for mobile
self.scripts.append(
'function quykHtml_preview_close(){'
'd = document.getElementById("quykHtml_preview");'
'if(d){'
'if(d.style.display != "none"){'
'd.innerHTML = "";'
'd.style.display = "none";'
'}'
'}'
'}'
)
# -------------------------------------------------------------
return True
def __get_anim_scripts(self):
# ' els[i].classList.add("fade-in-now");' \
# ' els[i].classList.remove("fade-in");' \
_anim_scripts = 'window.onscroll = function(e){' \
'var els = document.getElementsByTagName("*");' \
'for(var i=0; i<els.length; i++) {' \
' if(isScrolledIntoView(els[i]) && els[i].id.includes("fade-in")) {' \
' if(els[i].id.includes("-now") == false)' \
' els[i].id = els[i].id + "-now";' \
' }' \
'} \n' \
'var elss = document.getElementsByTagName("*");' \
'for(i=0; i<elss.length; i++) {' \
' if(isScrolledIntoView(elss[i]) && window.jQuery.hasData(elss[i])) {' \
' var _data = e.currentTarget.window.jQuery.data(elss[i]);' \
' var _anim = _data["animation"];' \
' var _anim_length = JSON.stringify(_data["animation_length"]);' \
' $("#" + elss[i].id).animate(_anim,_anim_length,function(){});' \
' elss[i].classList.add("slide-in-horiz-now");' \
' elss[i].classList.remove("slide-in-horiz");' \
' }' \
'} \n' \
'}\n'
# alert("invalid el for scroll");
_anim_scripts += 'function isScrolledIntoView(el) {' \
'if(!el){ return false;}' \
'var rect = el.getBoundingClientRect();' \
'var elemTop = rect.top;' \
'var elemBottom = rect.bottom;' \
'var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);' \
'var _new = parseInt(elemTop) + parseInt(document.body.scrollTop);' \
'return isVisible;' \
'}\n'
return _anim_scripts
class _themes:
"""Themes class which contains theme objects.\n
print(q.themes.basic.about())
"""
def __init__(self, parent=''):
if parent:
self.parent = parent
theme_info = {
'name': 'basic',
'description': 'A basic theme with: Green buttons, Gray Text and white backgrounds.',
'css': [
[
'button',
'color:white;font-size:24px;background-color:#6dad7a;padding:16px;padding-top:5px;'
'padding-bottom:5px;border:solid 1px black;border-radius:6px;margin-top:20px;margin-bottom:20px;'
],
[
'button:hover',
'background-color:#7ecc8e;'
],
[
'p',
'font-size:18px;font-weight:bold;margin-top:12px;margin-bottom:12px;color:#454a46;'
],
[
'input',
'font-size:18px;font-weight:bold;padding:6px;border-radius:2px;border: 1px solid black;'
]
]
}
self.basic = self._theme_object(theme_info['css'], theme_info['name'], theme_info['description'])
theme_info['name'] = 'greens'
theme_info[
'description'] = 'A green theme with: Green buttons, White Text and Green Divs and a White backgrounds.'
theme_info['css'] = [
[
'button',
'color:white;font-size:24px;background-color:#739e7e;padding-top:5px;'
'padding-bottom:5px;border:solid 1px black;border-radius:6px;margin-top:20px;margin-bottom:20px;'
'padding:16px;padding-top:5px;padding-bottom:5px;'
],
[
'button:hover',
'background-color:#84b591;'
],
[
'p',
'font-size:18px;font-weight:bold;margin-top:12px;margin-bottom:12px;color:#454a46;'
'color:white;'
],
[
'div',
'background-color:#597560;'
],
['.dark-green-text', 'color:#27362b;']
]
self.greens = self._theme_object(theme_info['css'], theme_info['name'], theme_info['description'])
theme_info['name'] = 'blues'
theme_info[
'description'] = 'A Blue theme with: Blue buttons, Gray Text and Blue Divs and a Light Gray background.'
theme_info['css'] = [
[
'button',
'color:white;font-size:24px;background-color:#5987a8;padding:16px;padding-top:5px;'
'padding-bottom:5px;border:solid 1px black;border-radius:6px;margin-top:20px;margin-bottom:20px;'
],
[
'button:hover',
'background-color:#699dc2;'
],
[
'div',
'background-color:#426b8a;color:white;'
],
[
'body',
'background-color:#a9bdcc;'
],
[
'p',
'font-size:18px;font-weight:bold;margin-top:12px;margin-bottom:12px;'
'color:#265373;'
],
]
self.blues = self._theme_object(theme_info['css'], theme_info['name'], theme_info['description'])
theme_info['name'] = 'night'
theme_info['description'] = 'A Night-Mode theme where everything is mostly dark.'
theme_info['css'] = [
]
class _theme_object:
def __init__(self, css, name, about):
self.css = css
self.__name = name
self.__about = about
def about(self):
"""Get the description of a theme and available classes you can use\n
print(q.themes.basic.about())
"""
_avail_classes = []
for ee in self.css:
_ind = 0
for e in ee:
if _ind == 1:
_ind = 0
break
_ind += 1
if e[:1] == ".":
_avail_classes.append(e)
_append = ""
if len(_avail_classes) > 0:
_append = ' '.join(_avail_classes)
else:
_append = 'None'
return '***** Theme \'' + self.__name + '\' ***** \n' + self.__about + '\nClasses Available For Use:\n\t\t' + _append + ''
def __repr__(self):
print(self.about())
return 'Usage: q.css.add(q.themes.' + str(self.__name).lower() + ')\n'
# CLASS Style sheet attached to the html object
class _css:
# INITIALIZE CLASS
def __init__(self):
self.styles = []
self.colors = self._colors()
self.helpers = self._helpers()
# Add a style to an object element
# returns: class object/itself
def add(self, name: str or list, style=""):
"""
Add a style to an object element
q.css.add( [\n\t['p','font-size:64px;], ['div','background-color:gray;'] \n] )\n
or\n
q.css.add('p','font-size:64px;')\n
q.css.add('div','background-color:gray;')
"""
# noinspection PyProtectedMember
if type(name) is qhtml._themes._theme_object:
name = name.css
if style == "":
if type(name) is list:
for li in name:
if type(li) is list:
_name = li[0]
_style = li[1]
self.styles.append(_name + "{" + _style + "}")
else:
print("Error using add function in class QuykHtml - > ss:")
print("Usage: add(style,name) or add([[\"style\",\"name\"],[\"style\",\"name\"]]")
return self
else:
self.styles.append(name + "{" + style + "}")
return self
def export(self, _file):
"""
Export every style into an external style sheet in the program's directory
"""
if "." not in _file:
return False
f = open(_file, "w")
_b = ""
for s in self.styles:
_b = _b + "" + s + "\n"
f.write(_b)
f.close()
class _colors:
def __init__(self):
self.LIGHT_GRAY = "#9e9e9e"
self.LIGHT_BLUE = "#699bf5"
self.LIGHT_RED = "#ed7476"
self.LIGHT_GREEN = "#53d490"
self.LIGHT_BROWN = "#82716c"
self.DARK_GRAY = "#4a4a4a"
self.DARK_BLUE = "#304873"
self.DARK_RED = "#633233"
self.DARK_GREEN = "#21573a"
self.DARK_BROWN = "#403735"
self.WHITE = "#FFFFFF"
self.BLACK = "#000000"
class _helpers:
def __init__(self):
pass
def font_size(self, _value=-1):
_s = self
if _value == -1:
print("css.helpers.font_size(val) error -> value should be structured like: 1px or 1em etc")
return False
else:
return "font-size:" + _value + ";"
def font_color(self, _color=-1):
_s = self
if _color == -1:
print(
"css.helpers.font_color(_color) error -> _color should be formatted like: #ffffff or #000000 etc")
return False
else:
return "color:" + _color + ";"
def bgr_color(self, _value=-1):
_s = self
if _value == -1:
return False
else:
return "background-color:" + _value + ";"
def shadow(self, _color, _w="5px", _x="5px", _y="5px", _z="5px"):
_s = self
return "box-shadow:" + _w + " " + _x + " " + _y + " " + _z + " " + _color + ";"
def rgbtohex(self, rgb):
_s = self
'''Takes an RGB tuple or list and returns a hex RGB string.'''
return f'#{int(rgb[0] * 255):02x}{int(rgb[1] * 255):02x}{int(rgb[2] * 255):02x}'
def hextorgb(self, _hex):
_s = self
_hex = _hex.lstrip('#')
return tuple(int(_hex[i:i + 2], 16) for i in (0, 2, 4))
# CLASS _q_element, an element object type
class _q_element:
"""
An 'element' which allows us to simulate a web element
"""
# INITIALIZE CLASS
def __init__(self, _type, _parent=0):
self.type = _type
self.children = [] # type: _q_element
self.animations = self.__animations(self)
if _parent != 0:
self.parent = _parent
else:
self.parent = ""
self.scripts = []
self.scripts_on_page_load = []
self.id = -1
self.attributes = []
self._attr_check = []
self.style = self._style_obj(self)
self._innerHTML = ""
self.innerText = ""
self._ajax_code = ""
self._ajax_pointer = ""
self._ajax_callback = ""
self._onclick_showpreview_html = False
def render(self, output_file="render.html", only_html=False, set_clip_board=False, prettify_html=True):
"""
Attempts to render the full webpage from the object
"""
if self.parent == "":
return False
else:
if set_clip_board:
self.parent.render(output_file, only_html, set_clip_board)
else:
if only_html:
self.parent.render(output_file, only_html=True)
else:
self.parent.render(output_file)
def row(self):
"""
Makes this element a row (bootstrap)\n
Same as calling:\n
element.set_class('row')
:return: self
"""
self.set_class('row', append=True)
return self
def col(self):
"""
Makes this element a column (goes inside a row)\n
Same as calling:\n
element.set_class('row')
:return: self
"""
self.set_class('col', append=True)
return self
def fetch_children(self, s_string):
"""
Fetch a child _q_element by a sub string of the element's open tag\n
Example:\n
mydiv = q.new('div').insert(q.new('div').set_class('testing1212'))\n
search = mydiv.fetch_children('testing12')\n
--- > [QuykHtml.qhtml._q_element object at 0x000001D211E48610]
:param s_string: string to find in the elements opening tag
:return: a list of elements found
"""
detected = []
if len(self.children) > 0:
for c in self.children:
if len(c.children) > 0:
for cc in c.children:
detected = detected + cc.fetch_children(s_string)
# print(s_string + " in " + c.get_tag_open().lower())
if s_string in c.get_tag_open().lower():
detected.append(c)
else:
# print(s_string + " in " + self.get_tag_open().lower())
if s_string in self.get_tag_open().lower():
return [self]
return detected
def scripts_add(self, js_code, on_page_load=False):
"""
Adds javascript code to the main page/display
"""
if on_page_load:
self.scripts_on_page_load.append(js_code)
else:
self.scripts.append(js_code)
return self
def insert_table_raw(self, table_raw_obj: object, append_html=False):
"""
Insert a table into an element as pure html
returns: itself/html object
"""
if append_html:
self._innerHTML += table_raw_obj.__build_html()
else:
self._innerHTML = table_raw_obj.__build_html()
return self
def insert_table_html(self, table_html: str, append_html=False):
if append_html:
self._innerHTML = self.innerHTML + table_html
else:
self._innerHTML = table_html
return self
def insert(self, _obj):
"""
Insert an object into another object
IE: insert a p object inside of a div object
returns: itself/html object
"""
if type(_obj) is list:
for l in _obj:
self.children.append(l)
# self.innerHTML += l.get_tag_open() + l.innerText + l.innerHTML + l.get_tag_close()
# self.innerHTML = self.innerHTML.replace(" ", " ")
self._innerHTML += self.innerHtml(full_html=True)
l.parent = self
l.__link_self()
else:
self.children.append(_obj)
# self.innerHTML += _obj.get_tag_open() + _obj.innerText + _obj.innerHTML + _obj.get_tag_close()
# self.innerHTML = self.innerHTML.replace(" ", " ")
self._innerHTML += self.innerHtml(full_html=True)
_obj.parent = self
_obj.__link_self()
return self
def innerHtml(self, full_html=False):
html = ''
for child in self.children:
html += child.innerHtml(full_html=True)
# if len(child.children) > 0:
# for child2 in child.children:
# html += child2.get_innerHtml()
# if len(self.children) == 0:
if hasattr(self, '_is_table'):
html += self._innerHTML
if full_html:
return self.get_tag_open() + self.innerText + html + self.get_tag_close()
else:
return html
def add_attribute(self, _str, append=False):
"""
Adds an attribute to an element
returns: self/object
"""
if len(_str) < 4:
print('QuykHtml add_attribute error, no value defined!\n- > ' + _str)
return self
_attr_name = _str[:_str.find("=")]
_attr_val = _str[_str.find("=") + 1:]
# TODO - allow for appending of different attribute types.
# TODO For now, it only works with class attribute type
if append is False:
if _attr_name in self._attr_check:
self.clear_attribute(_attr_name)
self._attr_check.append(_attr_name)
self.attributes.append(_attr_name + "=" + _attr_val)
else:
# TODO For now, it only works with class attribute type
_index = -1
_found = False
for attr in self.attributes:
_index += 1
if "class=" in attr:
self.attributes[_index] = attr[:-1] + " " + _attr_val.replace('"', "") + '"'
_found = True
else:
d = self.get_attribute(_attr_name)
d = d[:-1] + _str + '"'
self.clear_attribute(_attr_name)
self.add_attribute(d)
if _found is False:
self._attr_check.append(_attr_name)
self.attributes.append(_attr_name + "=" + _attr_val)
return self
def clear_attribute(self, _attr_name):
"""
Attempts to clear an attribute from an element
returns: self
"""
if _attr_name in self._attr_check:
for _a in self.attributes:
if _attr_name in _a:
self.attributes.remove(_a)
self._attr_check.remove(_attr_name)
break
else:
print("FALSE\n")
return self
def get_attributes(self):
"""
Retrieves all attributes from an object
returns: html attributes (str)
"""
_b = ""
for s in self.attributes:
_b = _b + " " + s
return _b.strip()