-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmynote.html
More file actions
414 lines (346 loc) · 12.8 KB
/
mynote.html
File metadata and controls
414 lines (346 loc) · 12.8 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
<head>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.9.5/brython.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.9.5/brython_stdlib.min.js">
</script>
</head>
<body onload="brython()">
<div id="notes_taking"></div>
<div id='zone_kv'>kv list here</div>
<br>load from or save to localfile<br>
<input type="file" id="load_file">
<a id="save_file" href="#" download >save</a>
<br><textarea id="text_file" rows="5" cols="80"></textarea>
<br>test post to backend<br>
<textarea id='myinput'></textarea>
<div id='myoutput'></div>
<button id="myupdate">submit</button>
<button id="fetch_remote">fetch remote</button>
<br>entiry relation table for future AI training<br>
<div id='db_table'>db table here</div>
<script type="text/python">
from browser import document, html
from browser import ajax
url_notes = "http://bridge.x10host.com/testmysql.php"
ajax_headers = { 'Content-Type': 'application/json; charset=utf-8' }
def complete2(request):
data = request.json
document["myoutput"].text = data['log']
def click(event):
value = document['myinput'].value
title = value.splitlines()[0]
import javascript
data = javascript.JSON.stringify(dict(doc=dict(title=title, body=value)))
ajax.post(url_notes, headers=ajax_headers, data=data, oncomplete=complete2)
document["myoutput"].text = "waiting..."
def fetch_remote_click(event):
ajax.post(url_notes, headers=ajax_headers, oncomplete=save_remote_notes)
document["myupdate"].bind("click", click)
document['fetch_remote'].bind('click', fetch_remote_click)
# ------------------------
from browser import document, window
from browser.html import TABLE, TR, TD, INPUT, BUTTON, PRE, TEXTAREA
zone = document["zone_kv"]
search_kv = "status"
"""Test if the browser supports local storage"""
try:
storage = window.localStorage
storage.setItem("x", "x")
storage.removeItem("x")
except:
storage = None
from browser import bind
from browser.widgets.dialog import Dialog
def noteTakingWindow(ev):
noteText = Dialog("Note", ok_cancel=True, left=0, top=0)
noteText.panel <= html.DIV("" + TEXTAREA(cols=80, rows=10))
# Event handler for "Ok" button
@bind(noteText.ok_button, "click")
def ok(ev):
note = noteText.select_one("TEXTAREA").value
print(note)
noteText.close()
key = note.splitlines()[0]
value = storage.getItem(key)
if value:
note = note + value
storage.setItem(key, note)
show_kv()
btn = BUTTON('click me to start taking notes')
btn.bind('click', noteTakingWindow)
document['notes_taking'] <= btn
def action_kv_delete(ev):
"""User clicked on "remove" button"""
button = ev.target
row = button.closest("TR")
key = row.get(selector="TD")[0].text
if button.text == 'remove':
storage.removeItem(key)
else:
value = storage.getItem(key)
noteText = Dialog("Note update", ok_cancel=True, left=0, top=0)
print([value])
noteText.panel <= html.DIV(TEXTAREA(value, cols=80, rows=10))
# Event handler for "Ok" button
@bind(noteText.ok_button, "click")
def ok(ev):
note = noteText.select_one("TEXTAREA").value
noteText.close()
title = note.splitlines()[0]
if title != key:
storage.removeItem(key)
storage.setItem(title, note)
show_kv()
# refresh table
show_kv()
def action_kv_search(ev):
"""User clicked on "search" button"""
global search_kv
search_kv = document['search_kv'].value
search_kv = search_kv.strip()
# refresh table
show_kv()
def menu_click(ev):
print('menu_click ', ev.target.text)
document['search_kv'].value = ev.target.text
action_kv_search(ev)
def show_kv(*args):
"""Shows the data stored locally, add buttons to add / remove items"""
zone.clear()
if storage is None:
zone <= "No local storage for this browser"
return
table = TABLE()
btn_search = BUTTON("Search")
btn_search.bind('click', action_kv_search)
table <= TR(TD(INPUT(id='search_kv', value=search_kv, size=70) + btn_search))
from browser.widgets.menu import Menu
menu = Menu(zone).add_menu('tag tree')
menu_tree = dict()
for i in range(storage.length):
key = storage.key(i)
value = storage.getItem(key)
node = menu_tree
parent_menu = menu
level = 0
def build_menu_tree(level, node, parent_menu, words):
if level > 5:
return
if len(words) == 0:
word = ''
else:
word = words[0].lower()
if word not in node:
words_rest = ' '.join(words[1:])
node[word] = (words_rest, parent_menu.add_item(' '.join(words[:2]), callback=menu_click))
return
if isinstance(node[word][0], str):
first = node[word][0]
node[word] = (dict(), parent_menu.add_menu(word))
build_menu_tree(level + 1, node[word][0], node[word][1], first.split()[1:])
build_menu_tree(level + 1, node[word][0], node[word][1], words[1:])
build_menu_tree(0, menu_tree, menu, key.split())
if len(search_kv) > 2 and (search_kv.lower() in value.lower()):
value = value[value.find(key)+len(key)+1:]
rows = len(value.splitlines())
value_field = TEXTAREA(value, rows=rows, cols=80)
btn = BUTTON("remove")
btn_update = BUTTON("update")
btn.bind('click', action_kv_delete)
btn_update.bind('click', action_kv_delete)
table <= TR(TD(key) + TD(btn_update + btn))
table <= TR(value_field)
zone <= table
def save_remote_notes(request):
"""Store remote data locally
data is list of body,title dictionary
"""
data = request.json
for note in data:
title = note.get('title')
if not title or len(title) == 0:
continue
storage.setItem(title, note.get('body'))
show_kv()
# ------------------------
# indexd DB for entity relationship graph
from browser import document, window, html
IDB = window.indexedDB
search_terms = {}
def create_db(*args):
# The database did not previously exist, so create object stores and indexes.
print('create db')
db = dbreq.result
store = db.createObjectStore("eb", {"keyPath": "eb"})
entityIndex = store.createIndex("by_entity", "entity")
relationIndex = store.createIndex("by_relation", "relation")
print('db scrture')
# Populate with initial data.
store.put({"entity": "cap-backend", "relation": "down stream", "eb": "PCAP"})
store.put({"entity": "cap-backend", "relation": "up stream", "eb": "hp-ep-mt"})
def btn_click(ev):
"""Generic callback function for buttons
"""
global search_terms
# The text on the button indicates the action: Add, Edit, Update or Delete
action = ev.target.text
# table row of the clicked button
row = ev.target.parent.parent
if action == "Delete":
db = dbreq.result
tx = db.transaction("eb", "readwrite")
store = tx.objectStore("eb")
cursor = store.delete(row.key)
# when record is deleted, update table
cursor.bind("success", show)
elif action == "Add":
values = [entry.value for entry in row.get(selector="INPUT")]
data = dict(zip(['entity', 'relation', 'eb'], values))
db = dbreq.result
tx = db.transaction("eb", "readwrite")
store = tx.objectStore("eb")
if action == "Add":
cursor = store.put(data)
else:
cursor = store.put(data, row.key)
search_terms = data
# when record is added, update table
cursor.bind("success", show_db)
elif action == "Edit":
# Replace cells for "entity" and "author" by INPUT fields
# Since isbn is he keyPath it can't be edited
cells = row.get(selector="TD")
for cell in cells[:-2]:
value = cell.text
cell.clear()
cell <= html.INPUT(value=value)
# Replace buttons "Edit" and "Delete" by button "Update"
cells[-1].clear()
update_btn = html.BUTTON("Update")
cells[-1] <= update_btn
# Bind its "click" event
update_btn.bind("click", btn_click)
elif action == "Update":
values = [entry.value for entry in row.select("INPUT")]
data = dict(zip(["entity", "relation"], values))
data['eb'] = row.key # required for the "store.put" method below
db = dbreq.result
tx = db.transaction("eb", "readwrite")
store = tx.objectStore("eb")
cursor = store.put(data)
# When record is updated, update table
cursor.bind("success", show)
elif action == 'Search':
values = [entry.value for entry in row.get(selector="INPUT")]
search_terms = dict(zip(['entity', 'relation', 'eb'], values))
print('search', values, search_terms)
db = dbreq.result
tx = db.transaction("eb", "readonly")
store = tx.objectStore("eb")
cursor = store.openCursor()
cursor.bind("success", show_db)
def show_db(ev):
"""Show the contents of store "eb" in a table"""
print('show db')
db = dbreq.result
tx = db.transaction("eb", "readonly")
store = tx.objectStore("eb")
cursor = store.openCursor()
# clear table
document["db_table"].clear()
# headers
t = html.TABLE()
document["db_table"] <= t
t <= html.TR(html.TH(x) for x in ["Entity", "relation", "Entity", "Actions"])
def add_row(ev):
"""Add a row to the table for each iteration on cursor
When cursor in empty, add a line for new record insertion
"""
res = ev.target.result
if res:
v = res.value
toShow = False
for key in ["entity", "relation", "eb"]:
if search_terms.get(key) and search_terms[key] == getattr(v, key):
toShow = True
break
if toShow:
row = html.TR()
row <= (html.TD(getattr(v, key))
for key in ["entity", "relation", "eb"])
row <= html.TD(html.BUTTON("Edit")+
html.BUTTON("Delete"))
row.key = res.key
t <= row
getattr(res, "continue")()
else:
# add empty row
row = html.TR()
row <= (html.TD(html.INPUT(name="new_%s" %key))
for key in ["entity", "relation", "eb"])
row <= html.TD(html.BUTTON("Add")+
html.BUTTON("Search"))
t <= row
# bind all buttons
for btn in t.get(selector="BUTTON"):
btn.bind("click", btn_click)
cursor.bind("success", add_row)
dbreq = IDB.open("library")
# If database doesn't exist, create it
dbreq.bind("upgradeneeded", create_db)
# Else print a table with all elements in table "books"
dbreq.bind("success", show_db)
#---------------------------------
def split_and_save(texts):
buffer = []
title = None
rtn = chr(10)
for line in texts.splitlines():
if line.strip() == '':
# reset
if title:
value = rtn.join(buffer)
if not buffer:
value = title
storage.setItem(title, value)
title = None
buffer = []
continue
if not title:
title = line
buffer.append(line)
from browser import bind, window, document
load_btn = document["load_file"]
save_btn = document["save_file"]
@bind(load_btn, "input")
def file_read(ev):
def onload(event):
"""Triggered when file is read. The FileReader instance is
event.target.
The file content, as text, is the FileReader instance's "result"
attribute."""
document['text_file'].value = event.target.result
# display "save" button
save_btn.style.display = "inline"
# set attribute "download" to file name
save_btn.attrs["download"] = file.name
split_and_save(event.target.result)
# Get the selected file as a DOM File object
file = load_btn.files[0]
# Create a new DOM FileReader instance
reader = window.FileReader.new()
# Read the file content as text
reader.readAsText(file)
reader.bind("load", onload)
@bind(save_btn, "mousedown")
def mousedown(evt):
"""Create a "data URI" to set the downloaded file content
Cf. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
"""
content = window.encodeURIComponent(document['text_file'].value)
# set attribute "href" of save link
save_btn.attrs["href"] = "data:text/plain," + content
</script>
</body>