index.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. <!--
  2. Copyright (C) 2024 Richard Hao Cao
  3. Ebrowser is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  4. Ebrowser is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  5. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
  6. -->
  7. <!DOCTYPE html><html><head><meta charset="UTF-8">
  8. <style>
  9. html{
  10. height: 100%;
  11. overflow: hidden;
  12. }
  13. body{
  14. display: flex;
  15. flex-direction: column;
  16. height: 100%;
  17. margin-top: 1px;
  18. }
  19. div.webviews{
  20. display: flex;
  21. flex-direction: column;
  22. flex-grow:1;
  23. }
  24. webview{display: none;width:100%;height:100%}
  25. .curWV{display: inherit !important;}
  26. .autocomplete-active {
  27. background-color: DodgerBlue !important;
  28. color: #ffffff;
  29. }
  30. .invis{display: none}
  31. /*the container must be positioned relative:*/
  32. .autocomplete {
  33. position: relative;
  34. display: inline-block;
  35. width:100%;
  36. }
  37. .autocomplete-items {
  38. position: absolute;
  39. border: 1px solid #d4d4d4;
  40. border-bottom: none;
  41. border-top: none;
  42. z-index: 99;
  43. /*position the autocomplete items to be the same width as the container:*/
  44. top: 100%;
  45. left: 0;
  46. right: 0;
  47. }
  48. .autocomplete-items div {
  49. cursor: pointer;
  50. background-color: #fff;
  51. }
  52. .autocomplete-items div:hover {
  53. background-color: #e9e9e9;
  54. }
  55. </style>
  56. <script>
  57. const { ipcRenderer } = require('electron');
  58. const fs = require('fs');
  59. const path = require('path');
  60. const readline = require('readline');
  61. var iTab = 0;
  62. var tabs;
  63. var engines = {};
  64. var mapKeys = {};
  65. var closedUrls = [];
  66. var autocStrArray = [];
  67. var defaultSE = "https://www.bing.com/search?q=%s";
  68. var historyFile = path.join(__dirname,'history.rec');
  69. var bHistory = false;
  70. var bQueryHistory = false;
  71. let sitecssP = path.join(__dirname,"sitecss");
  72. let sitejsP = path.join(__dirname,"sitejs");
  73. let gjsA = [];
  74. let gcssA = [];
  75. let gcssJSA = [];
  76. var bDomainJS = fs.existsSync(sitejsP);
  77. var bDomainCSS = fs.existsSync(sitecssP);
  78. var autocMode = 0; //0 for substring, 1 for startsWith
  79. const BML_head = "(async ()=>{let d=document;async function _loadJs(u){var a=d.createElement('script');a.type='text/javascript';a.async=false;a.src=u;d.body.appendChild(a);await new Promise(resolve=>a.onload=resolve)}";
  80. const BML_tail = "})()";
  81. const BML_md = BML_head + "await _loadJs('https://cdn.jsdelivr.net/npm/marked@12.0.2/marked.min.js');let b=d.body;b.innerHTML=marked.parse(b.textContent)})()";
  82. let lastKeys;
  83. let lastKeys_millis = 0;
  84. var lastVal;
  85. fs.readFile(path.join(__dirname,'search.json'), 'utf8', (err, jsonString) => {
  86. if (err) {
  87. coloncommand(":js fetch2file(repositoryurl,'search.json')");
  88. return;
  89. }
  90. initSearchEngines(jsonString,false);
  91. });
  92. fs.readFile(path.join(__dirname,'mapkeys.json'), 'utf8', (err, jsonStr) => {
  93. if (err) {
  94. coloncommand(":js fetch2file(repositoryurl,'mapkeys.json')");
  95. return;
  96. }
  97. try {
  98. mapKeys = JSON.parse(jsonStr);
  99. }catch(e){}
  100. });
  101. appendAutoc_rec(path.join(__dirname,'default.autoc'),null);
  102. appendAutoc_rec(path.join(__dirname,'bookmark.rec'),' ');
  103. function initSearchEngines(jsonStr){
  104. try{
  105. engines=JSON.parse(jsonStr);
  106. let match = jsonStr.match(/:"([^"]+)"/);
  107. if(match) defaultSE=match[1];
  108. }catch(e){}
  109. }
  110. function save(filePath, u8array){
  111. //alert(Object.prototype.toString.call(u8array))
  112. fs.writeFile (filePath, u8array, (err) => {
  113. if (err) {
  114. console.error (err);
  115. return;
  116. }
  117. });
  118. }
  119. function print2PDF(filePath, options){
  120. tabs.children[iTab].printToPDF(options)
  121. .then(u8array=>save(filePath,u8array));
  122. }
  123. function bookmark(argrest){//b [filenamestem] :bookmark
  124. let bmFileName = "bookmark.rec";
  125. let tab = tabs.children[iTab];
  126. let url = tab.getURL();
  127. if(argrest)
  128. bmFileName = argrest+".rec";
  129. let title = tab.getTitle();
  130. let line = title + " " + url + "\n";
  131. fs.appendFile(path.join(__dirname,bmFileName), line, (err)=>{});
  132. }
  133. function switchTab(i){
  134. let tab = tabs.children[iTab];
  135. if(document.activeElement == tab) tab.blur();
  136. tab.classList.remove('curWV');
  137. iTab = i;
  138. tabs.children[iTab].classList.add('curWV');
  139. }
  140. async function loadJSFile(tab,jsF){
  141. try {
  142. let js = await fs.promises.readFile(jsF,'utf8');
  143. tab.executeJavaScript(js,false);
  144. }catch(e){}
  145. }
  146. async function loadCSSFile(tab,jsF){
  147. try {
  148. let js = await fs.promises.readFile(jsF,'utf8');
  149. tab.insertCSS(css);
  150. }catch(e){}
  151. }
  152. function cbStartLoading(e){
  153. if(!bDomainCSS) return;
  154. let tab = e.target;
  155. let domain;
  156. try{
  157. domain = new URL(tab.getURL()).hostname;
  158. }catch(e){return;}
  159. let jsF = path.join(sitecssP, domain+".js");
  160. loadJSFile(tab,jsF);
  161. jsF = path.join(sitecssP, domain+".css");
  162. loadCSSFile(tab,jsF);
  163. gcssA.forEach((fname)=>{
  164. jsF = path.join(__dirname, fname);
  165. loadCSSFile(tab,jsF);
  166. });
  167. gcssJSA.forEach((fname)=>{
  168. jsF = path.join(__dirname, fname);
  169. loadJSFile(tab,jsF);
  170. });
  171. }
  172. function cbNavigate(e){
  173. let url = e.url;
  174. if(58===url.charCodeAt(1)){
  175. e.preventDefault();
  176. if(confirm("Proceed to execute risky operations: "+url))
  177. internalLink(url);
  178. else
  179. document.forms[0].q.value = url;
  180. }
  181. }
  182. function cbFinishLoad(e){
  183. let tab = e.target;
  184. let url = tab.getURL();
  185. if(bHistory){
  186. let histItem = tab.getTitle()+" "+url+"\n";
  187. fs.appendFile(historyFile, histItem, (err) => {});
  188. }
  189. let js = tab.dataset.jsonce;
  190. if(js){
  191. tab.dataset.jsonce = null;
  192. tab.executeJavaScript(js,false);
  193. }
  194. if(bDomainJS){
  195. let domain = new URL(url).hostname;
  196. let jsF = path.join(sitejsP, domain+".js");
  197. loadJSFile(tab,jsF);
  198. }
  199. gjsA.forEach((fname)=>{
  200. let jsF = path.join(__dirname, fname);
  201. loadJSFile(tab,jsF);
  202. });
  203. }
  204. function initTab(tab){
  205. tab.allowpopups = true;
  206. tab.addEventListener('did-finish-load',cbFinishLoad);
  207. tab.addEventListener('did-start-loading',cbStartLoading);
  208. tab.addEventListener('will-navigate',cbNavigate);
  209. }
  210. function newTab(){
  211. var tab = document.createElement('webview');
  212. initTab(tab);
  213. tabs.appendChild(tab);
  214. }
  215. function tabInc(num){
  216. let nTabs = tabs.children.length;
  217. if(nTabs<2) return;
  218. let i = iTab +num;
  219. if(i>=nTabs) i=0;
  220. switchTab(i);
  221. }
  222. function tabDec(num){
  223. let nTabs = tabs.children.length;
  224. if(nTabs<2) return;
  225. let i = iTab +num;
  226. if(i<0) i=nTabs-1;
  227. switchTab(i);
  228. }
  229. function tabClose(){
  230. let nTabs = tabs.children.length;
  231. if(nTabs<2) return "";//no remain tab
  232. let tab = tabs.children[iTab];
  233. closedUrls.push(tab.getURL());
  234. if(document.activeElement == tab) tab.blur();
  235. tabs.removeChild(tab);
  236. nTabs--;
  237. if(iTab>=nTabs) iTab=iTab-1;
  238. tabs.children[iTab].classList.add('curWV');
  239. return getWinTitle();
  240. }
  241. function tabJS(js){
  242. tabs.children[iTab].executeJavaScript(js,false);
  243. }
  244. function getWinTitle(){
  245. let t=tabs.children[iTab];
  246. let title = (iTab+1) + '/' + tabs.children.length;
  247. try{title=title+' '+t.getTitle()+' '+t.getURL()}catch(e){}
  248. return title
  249. }
  250. async function appendAutoc_rec(filename, delimit){
  251. try{
  252. const readInterface = readline.createInterface ({
  253. input: fs.createReadStream (filename, 'utf8'),
  254. });
  255. for await (const line of readInterface) {
  256. let iS;
  257. if(delimit && (iS=line.lastIndexOf(delimit))>0){
  258. autocStrArray.push(line.substring(iS+1));
  259. }else
  260. autocStrArray.push(line);
  261. }
  262. lastVal = null; //trigger full search
  263. }catch(e){return;}
  264. }
  265. function keyPress(e){
  266. var inputE = document.forms[0].q;
  267. if (e.altKey||e.metaKey)
  268. return;
  269. var key = e.key;
  270. if(e.ctrlKey){
  271. switch(key){
  272. case "Home":
  273. tabJS("window.scrollTo(0,0)");
  274. return;
  275. case "End":
  276. tabJS("window.scrollTo(0,document.body.scrollHeight)");
  277. return;
  278. }
  279. return;
  280. }
  281. SCROLL: do {
  282. let h = -32;
  283. switch(key){
  284. case " ":
  285. if(inputE === document.activeElement) return;
  286. if(e.shiftKey){
  287. h = -3*document.documentElement.clientHeight/4;
  288. break;
  289. }
  290. case "PageDown":
  291. h = 3*document.documentElement.clientHeight/4;
  292. break;
  293. case "PageUp":
  294. h = -3*document.documentElement.clientHeight/4;
  295. break;
  296. case "ArrowDown":
  297. h = 32;
  298. case "ArrowUp":
  299. if(inputE === document.activeElement &&
  300. 0!==inputE.nextElementSibling.children.length)
  301. return;
  302. break;
  303. default:
  304. break SCROLL;
  305. }
  306. let js = `javascript:window.scrollBy(0,${h})`;
  307. tabJS(js);
  308. return;
  309. }while(false);
  310. if(inputE === document.activeElement){
  311. if (9===e.keyCode){
  312. e.preventDefault();
  313. tabs.children[iTab].focus();
  314. }
  315. return;
  316. }
  317. var curMillis = Date.now();
  318. if(curMillis-lastKeys_millis>1000)
  319. lastKeys = null;
  320. lastKeys_millis = curMillis;
  321. switch (key) {
  322. case "!":
  323. case "/":
  324. case ":":
  325. inputE.value = "";
  326. inputE.focus();
  327. lastKeys = null;
  328. return;
  329. }
  330. lastKeys = !lastKeys ? key : lastKeys + key;
  331. let cmds = mapKeys[lastKeys];
  332. if(cmds){//try to run cmds
  333. let keyLen = lastKeys.length;
  334. setTimeout(()=>{
  335. if(lastKeys.length != keyLen) return;
  336. lastKeys = null;
  337. handleQueries(cmds);
  338. }, 500);
  339. }
  340. }
  341. function getQ(){return document.forms[0].q.value;}
  342. function bang(query, iSpace){
  343. let se=defaultSE;
  344. {
  345. let name = query.slice(0,iSpace);
  346. let engine = engines[name];
  347. if(engine){
  348. se = engine;
  349. query = query.substring(iSpace+1);
  350. }
  351. }
  352. return se.replace('%s',query);
  353. }
  354. function coloncommand(q){
  355. ipcRenderer.send("command",q);
  356. }
  357. function coloncommand_render(cmd){
  358. const delimiter = /\s+/;
  359. let arg0;
  360. let argrest = null;
  361. const match = delimiter.exec(cmd);
  362. if(match){
  363. const sIndex = match.index;
  364. const eIndex = sIndex + match[0].length;
  365. arg0 = cmd.substring(1,sIndex);
  366. argrest = cmd.substring(eIndex);
  367. }else
  368. arg0 = cmd.substring(1);
  369. switch(arg0){
  370. case "ac":
  371. autoc(argrest);
  372. return;
  373. case "b":
  374. bookmark(argrest);
  375. return;
  376. case "bjs":
  377. eval(argrest);
  378. return;
  379. case "bml":
  380. bangcommand(argrest,0);
  381. return;
  382. case "pdf":
  383. savePdf(argrest);
  384. return;
  385. }
  386. }
  387. function autoc(argrest){
  388. if(!argrest) return;
  389. let fpath = path.join(__dirname,argrest);
  390. let fname = fpath;
  391. let delimit = ' ';
  392. if (!fs.existsSync(fname)){
  393. fname = fpath+".autoc";
  394. if (!fs.existsSync(fname))
  395. fname = fpath+".rec";
  396. else
  397. delimit = null;
  398. }
  399. appendAutoc_rec(fname,delimit);
  400. }
  401. function bml(args){
  402. if(2!=args.length) return;
  403. let filename = args[1]+".js";
  404. fs.readFile(path.join(__dirname,filename), 'utf8', (err,str) => {
  405. if (err) return;
  406. tabs.children[iTab].executeJavaScript(str,false);
  407. });
  408. }
  409. function savePdf(argrest){
  410. let filename = "ebrowser.pdf";
  411. let options = {};
  412. if(argrest){
  413. let c0 = argrest.charCodeAt(0);
  414. let iOpts = 0;
  415. if(123!=c0){//not '{' options then it is filename
  416. let iS = argrest.indexOf(' ');
  417. let filestem = argrest;
  418. if(iS>0) {
  419. filestem = argrest.substring(0,iS);
  420. iOpts = iS+1;
  421. }else
  422. iOpts = argrest.length;
  423. filename = filestem + ".pdf";
  424. }
  425. if(argrest.length>iOpts){//:Pdf [filename] {...}
  426. if(iOpts+2==argrest.length){// '{}'
  427. let width = document.body.clientWidth/96;
  428. tabs.children[iTab].executeJavaScript("document.documentElement.scrollHeight",
  429. false).then((h)=>{
  430. let opts = {
  431. printBackground:true,
  432. pageSize:{width:width,height:h/96}};
  433. print2PDF(filename,opts);
  434. });
  435. return;
  436. }else{
  437. try {
  438. options = JSON.parse(argrest.substring(iOpts));
  439. }catch(e){};
  440. }
  441. }
  442. }
  443. print2PDF(filename,options);
  444. }
  445. function bangcommand(q,offset){
  446. let iS = q.indexOf(' ',offset);
  447. if(iS<0) iS=q.length;
  448. let fname = q.substring(offset,iS);
  449. let fpath = path.join(__dirname,fname+'.js');
  450. if (fs.existsSync(fpath)) {
  451. fs.readFile(fpath, 'utf8',(err, js)=>{
  452. if (err) {
  453. console.log(err);
  454. return;
  455. }
  456. const prefix = "(function(){";
  457. const postfix = "})(`";
  458. const end ="`)";
  459. const fjs = `${prefix}${js}${postfix}${q}${end}`;
  460. eval(fjs);
  461. });
  462. }
  463. }
  464. function recQueryHistory(q){
  465. if(bQueryHistory)
  466. fs.appendFile(path.join(__dirname,"history.autoc"), q, (err)=>{});
  467. }
  468. function handleQuery(q){
  469. if(q.length>1){
  470. let c0=q.charCodeAt(0);
  471. let c1=q.charCodeAt(1);
  472. switch(c0){
  473. case 33://"!"
  474. if(33!=c1)
  475. coloncommand(q);
  476. else
  477. bangcommand(q,2);
  478. recQueryHistory(q);
  479. return;
  480. case 47://"/"
  481. tabs.children[iTab].findInPage(q.substring(1));
  482. return;
  483. case 58://':'
  484. if(c1>98 && 112!=c1)
  485. coloncommand(q);
  486. else
  487. coloncommand_render(q);
  488. recQueryHistory(q);
  489. return;
  490. }
  491. if(58===c1){
  492. internalLink(q);
  493. return;
  494. }
  495. }
  496. var url=q;
  497. NOREC: do{
  498. do {
  499. if(q.length>12){
  500. let c6 = q.charCodeAt(6);
  501. if(47===c6){// '/'
  502. let c5 = q.charCodeAt(5);
  503. if(47===c5 && 58===q.charCodeAt(4))//http/file urls
  504. break NOREC;
  505. if(58===c5 && 47===q.charCodeAt(7))//https://
  506. break NOREC;
  507. }else if(q.startsWith("javascript:")){
  508. tabs.children[iTab].executeJavaScript(q.substring(11),false);
  509. recQueryHistory(q);
  510. return;
  511. }else if(q.startsWith("view-source:")) break;
  512. else if(q.startsWith("data:")) break;
  513. }
  514. let iS = q.indexOf(' ');
  515. if(iS<0){
  516. if(q.length>5 && 58===q.charCodeAt(5)){// about:
  517. break;
  518. }
  519. if(q.indexOf('.')>0){
  520. url = 'https://'+q;
  521. break NOREC;
  522. }
  523. url = defaultSE.replace('%s',q);
  524. break;
  525. }
  526. url = bang(q, iS);
  527. if(58===url.charCodeAt(1)){
  528. internalLink(url);
  529. recQueryHistory(q);
  530. return;
  531. }
  532. }while(false);
  533. recQueryHistory(q);
  534. }while(false);
  535. tabs.children[iTab].src=url;
  536. }
  537. function internalLink(url){
  538. let cmd = url.charCodeAt(2);
  539. let subcmd = url.charCodeAt(3);
  540. switch(cmd){
  541. case 48://'0' i:0
  542. {
  543. let iColon = url.indexOf(':',5);
  544. let name = decodeURIComponent(url.slice(4,iColon));
  545. let rurl = url.substring(iColon+1);
  546. switch(subcmd){
  547. case 47://'/' i:0/
  548. if(106===url.charCodeAt(4) && 115===url.charCodeAt(5) && 47===url.charCodeAt(6)){
  549. //i:0/js/xx:[url]
  550. let fname = name;
  551. let pname = path.join(__dirname,fname);
  552. if(fs.existsSync(pname)){
  553. (async ()=>{
  554. try {
  555. let js = await fs.promises.readFile(pname,'utf8');
  556. let t=tabs.children[iTab];
  557. t.dataset.jsonce=js;
  558. t.src = rurl;
  559. }catch(e){}
  560. })();
  561. }
  562. }
  563. return;
  564. case 48: //i:00
  565. {
  566. let endS;
  567. let is = url.indexOf('%s',iColon+1);
  568. if(is<0)
  569. endS = '%s"\n';
  570. else
  571. endS = '"\n';
  572. let pname = path.join(__dirname,"search.json");
  573. let str = '"'+name+'":"'+rurl+
  574. endS;
  575. jsonAppend(pname,125,str);
  576. }
  577. return;
  578. case 49: //i:01
  579. {
  580. let pname = path.join(__dirname,"menu.json");
  581. let str = '"'+name+'",":bjs handleQuery(`'+
  582. rurl+'${tabs.children[iTab].getURL()}`)"\n';
  583. jsonAppend(pname,93,str);
  584. }
  585. return;
  586. case 50: //i:02
  587. {
  588. let pname = path.join(__dirname,"uas.json");
  589. let str = '"'+name+'":"'+rurl+'"\n';
  590. jsonAppend(pname,125,str);
  591. }
  592. return;
  593. default:
  594. }
  595. }
  596. return;
  597. case 56: //i:8
  598. switch(subcmd){
  599. case 100: //i:8d[url] to download
  600. tabs.children[iTab].downloadURL(url.substring(4));
  601. return;
  602. }
  603. return;
  604. case 112: //i:p[url]#[querystring] for http POST
  605. {
  606. let iQ = url.indexOf('#',12);
  607. let data;
  608. let rurl;
  609. let headers;
  610. switch(subcmd){
  611. case 49: //i:p1
  612. {
  613. if(iQ>4) {
  614. rurl = url.substring(4,iQ);
  615. data = [{
  616. type: 'rawData',
  617. bytes: Buffer.from(url.substring(iQ+1))
  618. }];
  619. }else{
  620. rurl = url.substring(4);
  621. data = [];
  622. }
  623. headers = 'Content-Type: application/x-www-form-urlencoded';
  624. break;
  625. }
  626. case 50: //i:p2[url]#[filePath] post request with local file
  627. rurl = url.substring(4,iQ);
  628. data = [{type: 'file', filePath:url.substring(iQ+1)}];
  629. headers = 'Content-Type: multipart/form-data';
  630. break;
  631. default:
  632. return;
  633. }
  634. tabs.children[iTab].loadURL(rurl,{postData:data,extraHeaders:headers});
  635. return;
  636. }
  637. case 113: //i:q for multiple queries
  638. handleQueries(url.substring(3));
  639. return;
  640. }
  641. }
  642. function handleQueries(cmds){
  643. for(var cmd of cmds.split("\n"))
  644. handleQuery(cmd);
  645. }
  646. async function jsonAppend(filePath, charcode, str){
  647. let fd;
  648. try{
  649. fd = await fs.promises.open(filePath, 'r+');
  650. }catch(e){
  651. try {
  652. fd = await fs.promises.open(filePath, 'w+');
  653. }catch(e1){return}
  654. }
  655. try{
  656. const stats = await fd.stat();
  657. const fileSize = stats.size;
  658. const buffer = Buffer.alloc(1);
  659. let position = fileSize-1;
  660. while (position >= 0) {
  661. await fd.read(buffer, 0, 1, position);
  662. if (buffer[0] === charcode) break;
  663. position--;
  664. }
  665. let endS = String.fromCharCode(charcode);
  666. if(position<0){//re-write whole file
  667. str = String.fromCharCode(charcode-2)+str+endS;
  668. position = 0;
  669. }else
  670. str = ","+str+endS;
  671. await fd.truncate(position);
  672. const buf = Buffer.from(str);
  673. await fd.write(buf, 0, buf.length, position);
  674. await fd.close();
  675. }catch(e){console.log(e)}
  676. }
  677. function autocomplete(inp,container,arr) {
  678. var currentFocus;
  679. function clickItem(e){inp.value = arr[e.target.dataset.index];}
  680. function appendElement(el,dataindex){
  681. el.dataset.index = dataindex;
  682. el.addEventListener("click", clickItem);
  683. container.appendChild(el);
  684. }
  685. function itemInnerHTML(b,str,val,iStr){
  686. b.innerHTML = str.substr(0,iStr);
  687. b.innerHTML += "<strong>" + str.substr(iStr, val.length) + "</strong>";
  688. b.innerHTML += str.substr(iStr+val.length);
  689. }
  690. inp.addEventListener("input", function(e) {
  691. const MAXITEMS = 30;
  692. var b, i, val = this.value;
  693. if (!val) { return false;}
  694. currentFocus = -1;
  695. let items = container.children;
  696. let iBase = 0;
  697. let lastV = lastVal;
  698. lastVal = val;
  699. if(val.startsWith(lastV)){
  700. let itemsLen = items.length;
  701. if(itemsLen<=0) return;
  702. i = itemsLen -1;
  703. iBase = items[i].dataset.index +1;
  704. switch(autocMode){
  705. case 0:
  706. for (; i>=0; i--) {
  707. b = items[i];
  708. let str = arr[b.dataset.index];
  709. let iStr = str.indexOf(val);
  710. if(iStr<0) {
  711. b.parentNode.removeChild(b);
  712. continue;
  713. }
  714. itemInnerHTML(b,str,val,iStr);
  715. }
  716. break;
  717. case 1:
  718. for (; i>=0; i--) {
  719. b = items[i];
  720. let str = arr[b.dataset.index];
  721. let oLen = lastval.length;
  722. if(!str.startsWith(val.substring(oLen),oLen)) {
  723. b.parentNode.removeChild(b);
  724. continue;
  725. }
  726. itemInnerHTML(b,str,val,0);
  727. }
  728. break;
  729. }
  730. if(itemsLen<MAXITEMS)
  731. return;
  732. else
  733. if(container.children.length>=MAXITEMS) return;
  734. }else
  735. closeAllLists();
  736. i = iBase;
  737. switch(autocMode){
  738. case 0:
  739. for (; i < arr.length; i++) {
  740. let iStr = arr[i].indexOf(val);
  741. if(iStr<0) continue;
  742. {
  743. b = document.createElement("DIV");
  744. itemInnerHTML(b,arr[i],val,iStr);
  745. appendElement(b,i);
  746. if(container.children.length>=MAXITEMS) break;
  747. }
  748. }
  749. return;
  750. case 1://startsWith
  751. for (; i < arr.length; i++) {
  752. if (arr[i].startsWith(val)) {
  753. b = document.createElement("DIV");
  754. itemInnerHTML(b,arr[i],val,0);
  755. appendElement(b,i);
  756. if(container.children.length>=MAXITEMS) break;
  757. }
  758. }
  759. }
  760. });
  761. inp.addEventListener("keydown", function(e) {
  762. var x = container.getElementsByTagName("div");
  763. if (0===x.length) return false;
  764. if (e.keyCode == 40) {//downarrow
  765. currentFocus++;
  766. addActive(x);
  767. } else if (e.keyCode == 38) { //up
  768. currentFocus--;
  769. addActive(x);
  770. } else if (e.keyCode == 13) {
  771. if (currentFocus > -1) {
  772. e.preventDefault();
  773. if (x) x[currentFocus].click();
  774. currentFocus = -1;
  775. }
  776. closeAllLists();
  777. lastVal = null;
  778. }
  779. });
  780. function addActive(x) {
  781. removeActive(x);
  782. if (currentFocus >= x.length) currentFocus = 0;
  783. if (currentFocus < 0) currentFocus = (x.length - 1);
  784. x[currentFocus].classList.add("autocomplete-active");
  785. }
  786. function removeActive(x) {
  787. for (var i = 0; i < x.length; i++) {
  788. x[i].classList.remove("autocomplete-active");
  789. }
  790. }
  791. function closeAllLists() {
  792. container.innerHTML = '';
  793. }
  794. inp.addEventListener("blur", function () {
  795. setTimeout(()=>container.classList.add("invis"),200);
  796. });
  797. inp.addEventListener("focus", function () {
  798. container.classList.remove("invis");
  799. });
  800. }
  801. </script>
  802. </head>
  803. <body>
  804. <form class="autocomplete" autocomplete="off" action="javascript:handleQuery(getQ())">
  805. <input type="text" name=q style="width:100%" autofocus>
  806. <div class="autocomplete-items"></div>
  807. </form>
  808. <div class="webviews">
  809. <webview class="curWV" allowpopups></webview>
  810. </div>
  811. <script>
  812. tabs = document.body.children[1];
  813. initTab(tabs.children[0]);
  814. {
  815. let inp = document.forms[0].q;
  816. autocomplete(inp,inp.nextElementSibling,autocStrArray);
  817. }
  818. document.addEventListener('keydown', keyPress);
  819. </script>
  820. </body></html>