-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwrplusplus.html
300 lines (300 loc) · 14.8 KB
/
wrplusplus.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
<!DOCTYPE html>
<html lang = "en">
<head>
<title>WR++</title>
<meta charset = "utf-8">
<script src = "https://cdn.jsdelivr.net/npm/brython@3.11.0/brython.min.js"></script>
<script src = "https://cdn.jsdelivr.net/npm/brython@3.11.0/brython_stdlib.min.js"></script>
<style>
html, body {
margin: 0px;
}
p {
font-family: Arial, sans-serif;
font-size: 20px;
margin: 20px;
line-height: normal;
}
p.actext {
display: inline;
margin: 5px;
}
h2 {
font-family: Arial, sans-serif;
font-size: 28px;
text-decoration: none;
font-weight: normal;
margin: 20px;
}
#load, #start {
margin: 0px 20px 20px;
}
a, a:visited {
text-decoration: none;
color: blue;
}
a:focus {
background-color: darkblue;
color: white;
}
a:hover {
text-decoration: underline;
}
img {
margin: 0px 20px;
}
h1 {
font-family: Arial, sans-serif;
font-size: 28px;
font-weight: bold;
margin: 0px 20px;
}
iframe {
margin: 20px;
display: block;
}
input, button {
font-family: Arial, sans-serif;
font-size: 20px;
padding: 5px 7px;
margin: 0px 10px 20px;
border-radius: 0px;
text-decoration: none;
font-weight: normal;
background-color: #f8f8f8;
color: black;
-webkit-appearance: none;
border: 1px solid black;
}
input {
flex: 1;
width: 150px;
}
form {
margin: 20px 10px 0px;
display: flex;
}
div {
margin: 0px;
display: flex;
flex-direction: column;
}
span {
margin: 0px 20px 20px;
display: flex;
white-space: nowrap;
overflow-x: scroll;
}
</style>
</head>
<body onload = "brython (0)">
<noscript>
<p>JavaScript is required to use this website.</p>
</noscript>
<script type = "text/python">
from browser import document, ajax, html, window
global ac_cache, dict_lang
dict_lang = document.query.getvalue ("dict")
if not dict_lang:
document ["results"].clear ()
document ["results"].innerHTML = """
<h1>Welcome to WR++!</h1>
<p style = "line-height: 1.25;">
This is a front-end to <a href = "https://www.wordreference.com">WordReference.com</a> online dictionaries with improved search, autocomplete, and navigation features.
<br><br>To get started, please select a dictionary using the 'dict' query parameter (e.g. <a href = "?dict=enfr">dict=enfr</a>).
<br><br>The following parameters are supported:
<br> - A four-letter string consisting of two language codes (<a href = "https://www.wordreference.com/virtual_dictionaries.html">these options</a> are available along with 'en' for English)
<br> - One language code followed by 'conj' (e.g. 'frconj' for French conjugations)
<br><br>The entire site is easily navigable using only the keyboard. The keyboard shortcuts are as follows:
<br> - Enter: Focus on the search bar, search, swap languages (e.g. 'enfr' to 'fren') if search bar is empty
<br> - Shift + Enter: Search for the first autocomplete suggestion, change dictionary if the search bar is empty
<br> - Up & Down Arrows: Navigate between the search bar and autocomplete list
<br> - Left & Right Arrows: Navigate between autocomplete suggestions
<br> - Right Arrow: Focus on the first autocomplete suggestion if at the right edge of the search bar
<br> - '1' to '9': While focused on the autocomplete list, search for the corresponding suggestion
<br><br>If the search word is only found in the other language, the dictionary will automatically switch to that language. Double-clicking on any word in the dictionary page will search for that word.
<br><br>Autocomplete suggestions are cached for faster loading times. The cache is cleared on page reload.
<br><br>The entire site is contained within a single <a href = "https://github.com/CyrilSLi/cyrilsli.github.io/blob/main/wrplusplus.html">HTML file</a> and is fully functional if opened locally.
</p>
"""
raise SystemExit
ac_cache = {}
def rfind (text, values, start = True, end = False):
pointer = 0
for j in values [ : -1]:
pointer += text [pointer : ].find (j)
if pointer == -1:
return "N/A"
return text [pointer + (0 if start else len (values [-2])) : pointer + text [pointer : ].find (values [-1]) + (len (values [-1]) if end else 0)]
def resize_page (_ = None):
document ["page"].attrs ["style"] = f"height: {document ['page'].contentDocument.documentElement.offsetHeight + 1}px;"
def complete (res, dict_type):
document ["results"].clear ()
if dict_type == "dict":
sw_lang (rfind (res.text, ["wrserver", "ddict", '"dict": "', '",'], start = False))
page_doc = "<!DOCTYPE html><html><head>"
page_doc += rfind (res.text, ["<style", "</style>"], end = True)
page_doc += "</head><body>"
page_doc += rfind (res.text, ["<div id='articleWRD'>", "<div id='collinsdiv'>"])
page_doc += "</body></html>"
elif dict_type == "conj":
page_doc = '<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="https://www.wordreference.com/css/main.min.css"><link rel="stylesheet" type="text/css" href="https://www.wordreference.com/css/WRredesign.min.css"></head><body>'
page_doc += rfind (res.text, ["<div class='content'>", "<script>"])
page_doc += "</body></html>"
else:
return
document ["results"] <= html.H1 (rfind (res.text, ["<title>", "</title>"], start = False))
document ["results"] <= html.IFRAME (srcdoc = page_doc, id = "page", frameBorder = "0", onload = "resize_page ()", sandbox = "allow-same-origin", scrolling = "no")
document ["search"].value = ""
document ["page"].contentWindow.addEventListener ("keydown", arrow_nav)
document ["page"].contentWindow.addEventListener ("resize", resize_page)
def word_click (ev):
sel = document ["page"].contentWindow.getSelection ().toString ()
if sel not in ("", " ", "\n", "(", ")"):
sw_lang ()
document ["search"].value = sel
req_search ()
document ["page"].contentWindow.addEventListener ("dblclick", word_click)
autocomplete ()
def sw_lang (lang = None):
global dict_lang
if lang == "N/A":
return
elif lang:
dict_lang = lang
elif len (dict_lang) == 4:
dict_lang = dict_lang [2 : ] + dict_lang [ : 2]
document ["lang"].textContent = dict_lang
document ["search"].focus ()
autocomplete ()
def sw_dict ():
sw_lang (window.prompt ("Enter a dictionary code (e.g. 'enfr'):"))
window.history.replaceState (None, None, f'?dict={dict_lang}')
def req_search ():
global dict_lang
if document ["search"].value:
if dict_lang.endswith ("conj"):
url = f'https://www.wordreference.com/conj/{dict_lang [ : 2]}verbs.aspx?v={document ["search"].value}'
ajax.get (url, oncomplete = lambda res: complete (res, "conj"), cache = True)
else:
if dict_lang == "enes": # Special cases for English - Spanish
url = f'https://www.wordreference.com/es/translation.asp?tranword={document ["search"].value}'
elif dict_lang == "esen":
url = f'https://www.wordreference.com/es/en/translation.asp?spen={document ["search"].value}'
else:
url = f'https://www.wordreference.com/{dict_lang}/{document ["search"].value}'
ajax.get (url, oncomplete = lambda res: complete (res, "dict"), cache = True)
else:
sw_lang ()
def autocomplete (word = None):
global lastac, ac_cache, cache_key, dict_lang
if word:
document ["search"].focus ()
document ["search"].value = word
req_search ()
elif document ["search"].value:
if "aclist" not in document:
document.body.insertBefore (html.SPAN (id = "aclist"), document ["results"])
document ["aclist"].clear ()
cache_key = f'{dict_lang}_{document ["search"].value}'
if cache_key not in ac_cache or not ac_cache [cache_key]:
for i in range (1, len (document ["search"].value)):
if cache_key [ : -i] in ac_cache:
document ["aclist"].innerHTML = "".join ((f'<a id = "ac{i}" href = "javascript:void (0);" onclick = "autocomplete (\'{j}\')"><p class = "actext">{j}</p></a>' for i, j in enumerate ((k for k in ac_cache [cache_key [ : -i]] if k.startswith (document ["search"].value)))))
break
if not document ["aclist"].innerHTML:
document ["aclist"].innerHTML = '<a><p class = "actext">​</p></a>'
ajax.get (f'https://www.wordreference.com/autocomplete?dict={dict_lang}&query={document ["search"].value}' + (f'&conj={dict_lang [ : 2]}' if dict_lang.endswith ("conj") else ""), oncomplete = ac_comp, cache = True)
else:
ac_comp (None, True)
lastac = "ac0"
elif "aclist" in document:
del document ["aclist"]
def ac_comp (res, cache = False):
global ac_cache, cache_key, dict_lang
try:
document ["aclist"].clear ()
except KeyError:
pass
if not cache:
words, count = [], 0
for i in (i.split ("\t") for i in res.text.split ("\n")):
try:
if i [1] == dict_lang [ : 2] and (not dict_lang.endswith ("conj") or i [3] == "1"):
words.append (i [0])
count += 1
else:
raise IndexError
except IndexError:
break
if count:
ac_cache [cache_key] = tuple (words)
else:
ac_cache [cache_key] = (document ["search"].value, )
try:
document ["aclist"].innerHTML = "".join ((f'<a id = "ac{i}" href = "javascript:void (0);" onclick = "autocomplete ("{j.replace ("\'", "'")}");"><p class = "actext">{j}</p></a>' for i, j in enumerate (ac_cache [cache_key])))
if not document ["search"].value:
del document ["aclist"]
except KeyError:
pass
def arrow_nav (ev):
global lastac
if document.activeElement == document ["search"]:
if "ac0" in document and ev.key == "ArrowDown":
window.event.preventDefault ()
document [lastac].focus ()
elif "ac0" in document and ev.key == "ArrowRight" and document ["search"].selectionEnd == len (document ["search"].value):
window.event.preventDefault ()
document ["ac0"].focus ()
elif ev.key == "Enter" and ev.shiftKey:
window.event.preventDefault ()
if "ac0" in document:
autocomplete (document ["ac0"].textContent)
else:
sw_dict ()
elif document.activeElement.id [ : 2] == "ac":
if ev.key in ("ArrowLeft", "ArrowRight"):
window.event.preventDefault ()
next_id = f'ac{int (document.activeElement.id [2 : ]) + (1 if ev.key == "ArrowRight" else -1)}'
if next_id in document:
document [next_id].focus ()
elif next_id == "ac-1":
lastac = document.activeElement.id
document ["search"].focus ()
elif ev.key in ("1", "2", "3", "4", "5", "6", "7", "8", "9"):
window.event.preventDefault ()
autocomplete (document [f'ac{int (ev.key) - 1}'].textContent)
elif ev.key == "ArrowUp":
window.event.preventDefault ()
lastac = document.activeElement.id
document ["search"].focus ()
elif ev.key == "Enter":
window.event.preventDefault ()
document ["search"].focus ()
def lang_lp (ev = None):
global lp_timer
if ev.type == "mousedown":
lp_timer = window.setTimeout (sw_dict, 500)
elif ev.type == "mouseup":
window.clearTimeout (lp_timer)
sw_lang ()
else:
sw_dict ()
document.bind ("keydown", arrow_nav)
window.resize_page = resize_page
window.req_search = req_search
window.sw_lang = sw_lang
window.autocomplete = autocomplete
document ["request"] <= html.BUTTON (dict_lang, id = "lang", type = "reset")
document ["lang"].bind ("mousedown", lang_lp)
document ["lang"].bind ("mouseup", lang_lp)
document ["request"] <= html.INPUT (type = "text", id = "search", oninput = "autocomplete ();", autofocus = "autofocus")
document ["request"] <= html.BUTTON ("Search", id = "enter", type = "submit") # Replace "Search" with language-neutral equivalent (e.g. a magnifying glass)
document ["results"].clear ()
</script>
<form action = "javascript:void (0);" id = "request" onsubmit = "req_search ();" autocomplete = "off"></form>
<script>
document.body.insertAdjacentHTML ("beforeend", '<div id = "results"><p id = "start">Starting Brython...</p></div>')
</script>
</body>
</html>