chem.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. var list = ['',
  2. 'H', 'He',
  3. 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne',
  4. 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar',
  5. 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr',
  6. 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe',
  7. 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn',
  8. 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og'
  9. ]
  10. var weighList = {
  11. H: 1, He: 4,
  12. Li: 7, Be: 9, B: 11, C: 12, N: 14, O: 16, F: 19, Ne: 20,
  13. Na: 23, Mg: 24, Al: 27, Si: 28, P: 31, S: 32, Cl: 35.5, Ar: 40,
  14. K: 39, Ca: 40, Sc: 45, Ti: 48, V: 51, Cr: 52, Mn: 55, Fe: 56, Co: 59, Ni: 59, Cu: 64, Zn: 65.5, Ga: 70, Ge: 72.5, As: 75, Se: 79, Br: 80, Kr: 84,
  15. Rb: 85.5, Sr: 87.5, Y: 89, Zr: 91, Nb: 93, Mo: 96, Tc: 99, Ru: 101, Rh: 103, Pd: 106.5, Ag: 108, Cd: 112.5, In: 115, Sn: 118.5, Sb: 122, Te: 127.5, I: 127, Xe: 131,
  16. Cs: 133, Ba: 137, La: 139, Ce: 140, Pr: 141, Nd: 144, Pm: 147, Sm: 150.5, Eu: 152, Gd: 157, Tb: 159, Dy: 162.5, Ho: 165, Er: 167, Tm: 169, Yb: 173, Lu: 175, Hf: 178.5, Ta: 181, W: 184, Re: 186, Os: 190, Ir: 192, Pt: 195, Au: 197, Hg: 200.5, Tl: 204.5, Pb: 207, Bi: 209, Po: 209, At: 210, Rn: 222,
  17. Fr: 223, Ra: 226, Ac: 227, Th: 232, Pa: 231, U: 238, Np: 237, Pu: 244, Am: 243, Cm: 247, Bk: 247, Cf: 251, Es: 252, Fm: 257, Md: 258, No: 259, Lr: 260, Rf: 261, Db: 262, Sg: 263, Bh: 262, Hs: 265, Mt: 266, Ds: 269, Rg: 272, Cn: 285, Nh: 284, Fl: 289, Mc: 288, Lv: 293, Ts: 291, Og: 294
  18. }
  19. var weighList2 = {
  20. H: 1.008, He: 4.003,
  21. Li: 6.941, Be: 9.012, B: 10.81, C: 12.01, N: 14.01, O: 16.00, F: 19.00, Ne: 20.18,
  22. Na: 22.99, Mg: 24.31, Al: 26.98, Si: 28.09, P: 30.97, S: 32.07, Cl: 35.45, Ar: 49.95,
  23. K: 39.10, Ca: 40.08, Sc: 44.96, Ti: 47.87, V: 50.94, Cr: 52.00, Mn: 54.94, Fe: 55.85, Co: 58.93, Ni: 58.69, Cu: 63.55, Zn: 65.39, Ga: 79.72, Ge: 72.61, As: 74.92, Se: 78.96, Br: 79.90, Kr: 83.80,
  24. Rb: 85.47, Sr: 87.62, Y: 88.91, Zr: 91.22, Nb: 92.91, Mo: 95.94, Tc: 99, Ru: 101.1, Rh: 102.9, Pd: 106.4, Ag: 107.9, Cd: 112.4, In: 114.8, Sn: 118.7, Sb: 121.8, Te: 127.6, I: 126.9, Xe: 131.3,
  25. Cs: 132.9, Ba: 137.3, La: 138.9, Ce: 140.1, Pr: 140.9, Nd: 144.2, Pm: 147, Sm: 150.4, Eu: 152.0, Gd: 157.3, Tb: 158.9, Dy: 162.5, Ho: 164.9, Er: 167.3, Tm: 168.9, Yb: 173.0, Lu: 175.0, Hf: 178.5, Ta: 180.9, W: 183.8, Re: 186.2, Os: 190.2, Ir: 192.2, Pt: 195.1, Au: 197.0, Hg: 200.6, Tl: 204.4, Pb: 207.2, Bi: 209.0, Po: 209, At: 210, Rn: 222,
  26. Fr: 223, Ra: 226.0, Ac: 227.0, Th: 232.0, Pa: 231.0, U: 238.0, Np: 237.0, Pu: 244, Am: 243, Cm: 247, Bk: 247, Cf: 251, Es: 252, Fm: 257, Md: 258, No: 259, Lr: 260, Rf: 261, Db: 262, Sg: 263, Bh: 262, Hs: 265, Mt: 266, Ds: 269, Rg: 272, Cn: 285, Nh: 284, Fl: 289, Mc: 288, Lv: 293, Ts: 291, Og: 294
  27. }
  28. var bracket = {}, preview = 1, precise = 0, collapse = 0, useIon = 0, useIonId = 0
  29. function getco(str) {
  30. var n = str.length, ret = 0
  31. for (var i = 0; i < n; i++) {
  32. var ch = str.charAt(i)
  33. if (isNaN(ch)) break;
  34. ret *= 10;
  35. ret += ch - 0;
  36. }
  37. str = str.slice(i, n)
  38. return [ret, str, i]
  39. }
  40. function workMolecule(str, st) {
  41. // console.log(str, st)
  42. var n = str.length, ans = {};
  43. for (let i = 0; i < n; i++) {
  44. var ch = str.charAt(i)
  45. var f = {}
  46. if (ch == '(') {
  47. f = workMolecule(str.slice(i + 1, bracket[i + st] - st), st + i + 1)
  48. i = bracket[i + st] - st;
  49. } else if ('A' <= ch && ch <= 'Z') {
  50. if (i + 1 < n) {
  51. let nch = str.charAt(i + 1)
  52. if ('a' <= nch && nch <= 'z') i++, ch += nch
  53. }
  54. if (f[ch]) f[ch]++;
  55. else f[ch] = 1;
  56. } else return {}
  57. let g = getco(str.slice(i + 1, n))
  58. if (g[0]) {
  59. for (key in f) {
  60. f[key] *= g[0]
  61. }
  62. }
  63. for (key in f) {
  64. if (ans[key]) ans[key] = ans[key] + f[key]
  65. else ans[key] = f[key]
  66. }
  67. i += g[2]
  68. }
  69. // console.log('ans', ans)
  70. return ans;
  71. }
  72. function parseMolecule(str) {
  73. str = str.replace(/[\[{]/g, "(").replace(/[\]}]/g, ")")
  74. str = str.replace(/<\d*e[\+\-]>*/g, "");
  75. // console.log('Parsing molecule', str)
  76. var n = str.length, co = 1, stack = [], top = 0;
  77. for (let i = 0; i < n; i++) {
  78. var ch = str.charAt(i);
  79. if (ch == '(') stack[top] = i, top++;
  80. else if (ch == ')') bracket[stack[top - 1]] = i, bracket[i] = stack[top - 1], top--;
  81. if (top < 0) return {}
  82. }
  83. if (top != 0) return {};
  84. var g = getco(str)
  85. if (g[0]) co = g[0]
  86. var f = workMolecule(g[1], g[2])
  87. for (key in f) {
  88. f[key] *= co;
  89. }
  90. return f;
  91. }
  92. function eps(a, mode = 0) {
  93. if (mode) {
  94. var s = a.toString().split('e')
  95. if (s.length == 1) return parseFloat(parseFloat(a).toFixed(4))
  96. return Math.round(parseFloat(s[0]) * 10000) / 10000 + 'e' + s[1];
  97. } else return a
  98. }
  99. function weigh(hash, mode = 0) {
  100. var ans = 0
  101. if (mode) {
  102. for (key in hash) {
  103. if (weighList2[key]) ans += hash[key] * weighList2[key]
  104. }
  105. } else {
  106. for (key in hash) {
  107. if (weighList[key]) ans += hash[key] * weighList[key]
  108. }
  109. }
  110. return eps(ans, mode);
  111. }
  112. function weighEquation(str, mode = 0) {
  113. str = str.replace(/<\d*e[\+\-]>*/g, "").replace(/[^\dA-Za-z<>\(\)\+\-=\.;]/g, "");
  114. var q = str.split(/[=\+\-\.;]/g)
  115. var p = str.replace(/[^=\+\-\.;]/g, "").replace(/\./g, '*')
  116. var ans = ""
  117. if (str == "") return ""
  118. var n = p.length, sum = 0, gsum = "";
  119. for (let i = 0; i <= n; i++) {
  120. var k = weigh(parseMolecule(q[i]), mode)
  121. sum += k
  122. if (p.charAt(i) == '=') gsum += eps(sum, mode) + '=', sum = 0;
  123. ans = ans + k + p.charAt(i)
  124. }
  125. if (n) ans += '<br>' + gsum + eps(sum, mode)
  126. return ans.replace(/\*/g, "\\cdot");
  127. }
  128. function parseEquation(str) {
  129. str = str.replace(/ /g, '').replace(/<\d*e[\+\-]>*/g, "")
  130. var q = str.split(/[=\+\-\.]/g)
  131. var p = str.replace(/[^=\+\-\.]/g, "")
  132. var ans = {}
  133. var n = p.length;
  134. for (let i = 0; i <= n; i++) {
  135. var f = parseMolecule(q[i])
  136. for (key in f) {
  137. if (ans[key]) ans[key] = ans[key] + f[key]
  138. else ans[key] = f[key]
  139. }
  140. }
  141. return ans
  142. }
  143. function getCondition(e) {
  144. if (e == '加热') return '\\Delta'
  145. return e
  146. }
  147. function renderEquation(str, condition = '') {
  148. // if (!preview) return str;
  149. str = str
  150. .replace(/[\[{]/g, "(")
  151. .replace(/[\]}]/g, ")")
  152. .replace(/([\+\=\.;])\1+/g, '$1')
  153. .replace(/[^\dA-Za-z<>\(\)\+\-=\.;~]/g, "")
  154. .replace(/([A-Za-z]+)/g, "\\text{$1}")
  155. .replace(/<(\d*)\\text\{e\}([\+\-])>/g, "^{$1$2}")
  156. .replace(/([\}\)])(\d+)/g, "$1_{$2}")
  157. .replace(/\./g, "\\cdot")
  158. .replace(/~/g, '\\times')
  159. if (condition) str = str.replace(/=/g, `\\stackrel{${getCondition(condition)}}{=}`)
  160. str = "\\(" + str + "\\)"
  161. return str
  162. }
  163. //PROCESS-------------------------------
  164. var mode = 'bal', balInput, balText = '', inputText, case1 = 'CrI3+Cl2+KOH=K2CrO4+KIO4+KCl+H2O', case2 = 'CH3CHO+2Ag(NH3)2OH=CH3COONH4+2Ag+3NH3+H2O'
  165. $().ready(function () {
  166. balInput = $("#balInput")[0]
  167. setBal();
  168. setQry();
  169. $("#balInput").keydown(function (e) {
  170. if (e.keyCode == 13 && mode == 'bal') {
  171. $("#balBtn")[0].click();
  172. }
  173. });
  174. $("#qryInput").keydown(function (e) {
  175. if (e.keyCode == 13) {
  176. $("#qryBtn")[0].click();
  177. }
  178. });
  179. $("#preview").tooltip()
  180. $(function () { $("[data-toggle='tooltip']").tooltip(); });
  181. $(".has").on('click', e => {
  182. if (!$(e.currentTarget).children().hasClass('active')) {
  183. $(e.currentTarget).children('span').click()
  184. }
  185. })
  186. })
  187. function setBal() {
  188. $('#precise').hide()
  189. $('.frame')[0].innerHTML = renderEquation(balText);
  190. $('#balBtn').html('配平 <span class="glyphicon glyphicon-transfer"></span>')
  191. $('#balInput').attr('placeholder', case1 + '(输入化学式以配平)')
  192. $('#balBtn').attr('href', '/chem?' + case1)
  193. $('#balBtn').removeClass('disabled')
  194. mode = 'bal'
  195. input()
  196. MathJax.typeset()
  197. }
  198. function setWeigh() {
  199. $('#precise').show()
  200. $('#balBtn').text('相对质量')
  201. $('#balInput').attr('placeholder', case2 + '(输入化学式以计算相对质量)')
  202. $('#balBtn').attr('href', '')
  203. $('#balBtn').addClass('disabled')
  204. mode = 'weigh'
  205. input()
  206. }
  207. function input() {
  208. inputText = balInput.value.replace(/[\[\{]/g, '(').replace(/[\]\}]/g, ')')
  209. if (mode == 'bal') {
  210. $('.frame')[0].innerHTML = renderEquation((inputText == '') ? case1 : inputText) + '<br>'
  211. + '<span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span><br>' + ((balText != '') ? (renderEquation(balText)) : ('...'));
  212. } else if (mode == 'weigh') {
  213. $('.frame')[0].innerHTML = renderEquation((inputText == '') ? case2 : inputText) + '<br>'
  214. + weighEquation((inputText == '') ? case2 : inputText, precise);
  215. }
  216. if (preview) MathJax.typeset()
  217. if (inputText.match('!')) {
  218. balUp()
  219. }
  220. }
  221. var running;
  222. function balance() {
  223. input()
  224. if (running || mode != 'bal') return;
  225. $('#balBtn').text('配平...')
  226. $('#balBtn').addClass('disabled')
  227. $('.frame').addClass('text-muted')
  228. running = 1;
  229. fetch('/alog', {
  230. method: 'POST',
  231. headers: {
  232. 'Content-type': 'application/json',
  233. },
  234. body: '{"content":"' + ((inputText == '') ? case1 : inputText) + '"}'
  235. })
  236. return fetch('https://43.143.233.184:7989/chem', {
  237. method: 'POST',
  238. headers: {
  239. 'Content-type': 'application/json',
  240. },
  241. body: '{"q":"' + ((inputText == '') ? case1 : inputText) + '"}'
  242. }).then(
  243. res => res.text()
  244. ).then(e => {
  245. if (e == '{}') e = '"!Description: Invalid Character."'
  246. e = e.split('"')[1].replace(/\\n/g, '\n')
  247. $('.frame')[0].innerHTML = (e.charAt(0) == '!') ? ('<pre class="text-danger bg-danger">' + e.slice(1, e.length) + '</pre>') : (renderEquation((inputText == '') ? case1 : inputText)
  248. + '<br><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span><br>' + renderEquation(e));
  249. if (e.charAt(0) != '!') balText = e
  250. MathJax.typeset()
  251. $('#balBtn').html('配平 <span class="glyphicon glyphicon-transfer"></span>')
  252. $('#balBtn').removeClass('disabled')
  253. $('.frame').removeClass('text-muted')
  254. running = 0;
  255. return new Promise(res => res(e))
  256. })
  257. }
  258. function balUp() {
  259. if (mode != 'bal') return;
  260. $('#balInput').val(balText);
  261. input()
  262. }
  263. //QUERY-------------------------------
  264. var modeq = 'query', nameq = 'eq', strict = false, matchMode = 'mole', namels = ['eq', 'mo', 'io', 'el'], ionRegex = ''
  265. function toggl(str, is = 0) {
  266. $('#qryBtn').html(str)
  267. $('.op').hide()
  268. $('.op-' + modeq + '-' + nameq).show()
  269. if (modeq == 'add' || modeq == 'upd') {
  270. $('.add:not(.add-' + nameq + ',#addId)').hide()
  271. $('.add-' + nameq).show(500)
  272. if (modeq == 'upd') $('#addId').show(300)
  273. else $('#addId').hide(300)
  274. } else $('.add').hide()
  275. if (is) $('.qryInputHidable').show()
  276. else $('.qryInputHidable').hide()
  277. }
  278. function setQry() {
  279. $('.qry-group>label').removeClass('active')
  280. $('.frame').removeClass('active')
  281. $('.frame')[0].classList.add('active')
  282. if (modeq == 'query') toggl('查询 <span class="glyphicon glyphicon-search"></span>', nameq == 'eq' && strict)
  283. else if (modeq == 'add') toggl('上传 <span class="glyphicon glyphicon-plus"></span>')
  284. else toggl('修改 <span class="glyphicon glyphicon-pencil"></span>')
  285. if (nameq == 'eq') {
  286. $('.frame')[1].classList.add('active')
  287. $('.qry-group>label')[0].classList.add('active')
  288. if (modeq == 'query') $('#qryInput').attr('placeholder', 'O2=H2O' + '(查询数据库中的化学式,也可输入 id)')
  289. else if (modeq == 'add') $('#qryInput').attr('placeholder', 'H2+O2=H2O' + '(将化学式上传至数据库)')
  290. else $('#qryInput').attr('placeholder', '(修改已有化学式)')
  291. } else if (nameq == 'mo') {
  292. $('.qry-group>label')[1].classList.add('active')
  293. $('.frame')[2].classList.add('active')
  294. if (modeq == 'query') {
  295. if (useIon) {
  296. if (!useIonId) $('#qryInput').attr('placeholder', 'Fe<3e+>' + '(输入离子查询数据库中的分子)')
  297. else {
  298. $('#qryInput').attr('placeholder', '2,3' + '(输入离子编号查询数据库中的分子)')
  299. $('.qry-group>label')[2].classList.add('active')
  300. $('.frame')[3].classList.add('active')
  301. }
  302. } else $('#qryInput').attr('placeholder', 'Fe' + '(查询数据库中的分子,也可输入 id)')
  303. }
  304. else if (modeq == 'add') {
  305. $('#qryInput').attr('placeholder', 'Fe3O4' + '(将分子上传至数据库)')
  306. $('#addTitle').attr('placeholder', '四氧化三铁')
  307. } else {
  308. $('#qryInput').attr('placeholder', '(修改已有分子)')
  309. $('#addTitle').attr('placeholder', '四氧化三铁')
  310. }
  311. if (useIon) $('.op-ionid').show()
  312. } else if (nameq == 'io') {
  313. $('.qry-group>label')[2].classList.add('active')
  314. $('.frame')[3].classList.add('active')
  315. if (modeq == 'query') {
  316. $('#qryInput').attr('placeholder', 'Fe' + '(查询数据库中的离子,也可输入 id)')
  317. }
  318. else if (modeq == 'add') {
  319. $('#qryInput').attr('placeholder', 'Fe<3e+>' + '(将离子上传至数据库)')
  320. $('#addTitle').attr('placeholder', '三价铁')
  321. } else {
  322. $('#qryInput').attr('placeholder', '(修改已有离子)')
  323. $('#addTitle').attr('placeholder', '三价铁')
  324. }
  325. } else {
  326. $('.qry-group>label')[3].classList.add('active')
  327. $('.frame')[4].classList.add('active')
  328. if (modeq == 'query') {
  329. $('#qryInput').attr('placeholder', 'Fe' + '(输入元素获取汇总信息)')
  330. }
  331. }
  332. input2()
  333. if (modeq == 'upd') inputId()
  334. if (collapse) $('.frame:not(.active)').parent().hide(300), $('.frame.active:not(#balFrame)').parent().show(200);
  335. else $('.frame:not(#balFrame)').parent().show(300)
  336. }
  337. function replaceRegex(s) {
  338. return s.replace(/([\+\=\.;])+/g, '$1').replace(/([\(\)])/g, '\\\\$1').replace(/(<\d*)e\+/g, '$1%')
  339. }
  340. function getRegex() {
  341. var ret = ''
  342. if (nameq == 'eq') {
  343. if (strict) {
  344. var acont = $('#qryInput').val(), bcont = $('#qryInput2').val();
  345. if (!acont && !bcont) acont = $('#qryInput').attr('placeholder').split('(')[0]
  346. acont = replaceRegex(acont)
  347. bcont = replaceRegex(bcont)
  348. ret = '^'
  349. if (acont) {
  350. var as = acont.split('+')
  351. for (let i = 0; i < as.length; i++) {
  352. if (matchMode == 'mole') ret += '(?=([^=]*\\+|)[0-9]?' + as[i] + '([+=]|$))'
  353. else ret += '(?=[^=]*' + as[i] + '([^a-z]|$))'
  354. }
  355. }
  356. if (bcont) {
  357. var bs = bcont.split('+');
  358. for (let i = 0; i < bs.length; i++) {
  359. if (matchMode == 'mole') ret += '(?=.*=(.*\\+|)[0-9]?' + bs[i] + '([+=]|$))'
  360. else ret += '(?=.*=.*' + bs[i] + '([^a-z]|$))'
  361. }
  362. }
  363. ret += '.*'
  364. } else {
  365. ret = $('#qryInput').val()
  366. if (ret && !ret.match(/[^\d]/g)) return ret
  367. if (!ret) ret = $('#qryInput').attr('placeholder').split('(')[0]
  368. ret = replaceRegex(ret)
  369. var scont = ret.split('=')
  370. if (scont.length > 2) return;
  371. var as = scont[0].split('+');
  372. ret = matchMode == 'mole' ? '^' : ''
  373. for (let i = 0; i < as.length; i++) {
  374. if (matchMode == 'mole') ret += "(?=(.*[+=]|)[0-9]?" + as[i] + "([+=]|$))"
  375. else ret += '(?=.*' + as[i] + '([^a-z]|$))'
  376. }
  377. if (scont.length > 1) {
  378. var bs = scont[1].split('+')
  379. for (let i = 0; i < bs.length; i++) {
  380. if (matchMode == 'mole') ret += "(?=(.*[+=]|)[0-9]?" + bs[i] + "([+=]|$))"
  381. else ret += '(?=.*' + bs[i] + '([^a-z]|$))'
  382. }
  383. }
  384. ret += '.*'
  385. }
  386. return ret.replace(/%/g, 'e+')
  387. } else return replaceRegex($('#qryInput').val() ? $('#qryInput').val() : $('#qryInput').attr('placeholder').split('(')[0]).replace(/%/g, 'e+') + '([^a-z]|$)'
  388. }
  389. function procClass(e) {
  390. e[0].class = JSON.parse(e[0].class)
  391. let c = e[0].class
  392. for (let j = 0; j < c.length; j++) {
  393. let t = JSON.stringify(c[j]).split(':')[0].split('"')[1]
  394. let str = ''
  395. c.filter(e => {
  396. if (JSON.stringify(e).split(':')[0].split('"')[1] == t) str += ',' + JSON.stringify(e).split(':')[1].split('}')[0].replace(/"/g, '')
  397. })
  398. curClass[t] = str.slice(1)
  399. }
  400. getClass(1)
  401. }
  402. function renderTable(bd, e) {
  403. bd = JSON.parse(bd).content.split('(')[0]
  404. console.log(bd, e)
  405. var uc = [], ut = []
  406. for (i = 0; i < e.length; i++) {
  407. console.log(JSON.parse(e[i].class).filter(e => e[bd])[0])
  408. let k = JSON.parse(e[i].class).filter(e => e[bd])[0][bd]
  409. if (!uc.includes(k)) uc.push(k)
  410. if (!ut.includes(e[i].type)) ut.push(e[i].type)
  411. }
  412. uc.sort()
  413. ut.sort()
  414. console.log(uc, ut)
  415. str = '<thead><tr><th>' + bd + '</th>'
  416. for (let i = 0; i < ut.length; i++) {
  417. str += `<th>${ut[i]}</th>`
  418. }
  419. str += '</tr></thead><tbody>'
  420. for (let i = 0; i < uc.length; i++) {
  421. str += `<tr><td>${uc[i]}</td>`
  422. for (let j = 0; j < ut.length; j++) {
  423. let f = e.filter(e =>
  424. JSON.parse(e.class).filter(e => e[bd] == uc[i]).length
  425. && e.type == ut[j]
  426. )
  427. str += '<td>'
  428. let g = ''
  429. for (let k = 0; k < f.length; k++) {
  430. g += `${f[k].content}`
  431. if (k < f.length - 1) g += ';'
  432. if (k % 5 == 0) {
  433. str += renderEquation(g)
  434. g = ''
  435. }
  436. }
  437. str += renderEquation(g)
  438. str += '</td>'
  439. }
  440. str += '</tr>'
  441. }
  442. str += '</tbody>'
  443. $('.table-el').html(str)
  444. console.log(str)
  445. }
  446. function renderResult(bd, e, isId, replace, insAfter) {
  447. let qin = $('#qryInput').val()
  448. if (e[0] == '!') {
  449. $('.frame')[getC(nameq)].innerHTML = '<pre class="text-danger bg-danger">' + e + '</pre>';
  450. return
  451. }
  452. e = JSON.parse(e)
  453. if (nameq == 'eq') {
  454. if (insAfter != -1) {
  455. if (isId) {
  456. if (replace) $('#qryInput').val(e[0].content)
  457. $('#addCondition').val(e[0].conditions)
  458. $('#addIdText').val(JSON.parse(bd).content)
  459. $('#addDescription').val(e[0].descriptions)
  460. }
  461. var str = ''
  462. str += '<div class="result" style="margin-left: 50px;margin-top: -20px;">' + renderEquation(e[0].content, e[0].conditions) + '<br>';
  463. if (e[0].conditions) str += '(' + e[0].conditions + ')';
  464. str += e[0].descriptions + '<br>';
  465. str += '</div>'
  466. $('.res-' + insAfter).append(str)
  467. } else {
  468. if (!isId || !replace) {
  469. $('.frame')[1].innerHTML = '<span id="qryInputRender">' + renderEquation(strict ? (qin + '=' + $('#qryInput2').val()) : qin) + ' - 匹配到 ' + e.length + ' 个</span><br><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span><br>';
  470. } else $('.frame')[1].innerHTML = ''
  471. var str = ''
  472. for (let i = 0; i < e.length; i++) {
  473. str += `<div class="result res-${i}">${renderEquation(e[i].content, e[i].conditions)}<br><span class="label label-${e[i].rel ? (e[i].rel > 0 ? 'warning' : 'success') : 'default'}" onclick="doQuery(JSON.stringify({content:'${e[i].id}'}),'id',2,-2)">${e[i].id}</span> `;
  474. if (e[i].conditions) str += '(' + e[i].conditions + ')';
  475. str += e[i].descriptions + '<br>';
  476. if (e[i].rel > 0) {
  477. str += `<span class="glyphicon glyphicon-share-alt"></span> <span class="label label-sub label-success" onclick="$(this).siblings('.result').length||doQuery(JSON.stringify({content:'${e[i].rel}'}),'id',2,${i})">${e[i].rel}</span><br>`;
  478. }
  479. if (e[i].rel < 0) {
  480. str += `<span class="glyphicon glyphicon-share-alt"></span> <span class="label label-sub label-warning" onclick="$(this).siblings('.result').length||doQuery(JSON.stringify({content:'${-e[i].rel}'}),'id',2,${i})">${-e[i].rel}</span><br>`;
  481. }
  482. if (isId) {
  483. if (replace) $('#qryInput').val(e[0].content)
  484. $('#addCondition').val(e[0].conditions)
  485. $('#addIdText').val(JSON.parse(bd).content)
  486. $('#addDescription').val(e[0].descriptions)
  487. }
  488. if (qin.match('!') || replace == 2) $('#qryInput').val(e[0].content)
  489. str += '</div>'
  490. }
  491. $('.frame')[1].innerHTML += str
  492. }
  493. } else if (nameq == 'mo') {
  494. if (insAfter == -1) {
  495. if (!isId) $('.frame')[2].innerHTML = '<span id="qryInputRender-mo">' + renderEquation(qin) + ' - 匹配到 ' + e.length + ' 个</span><br><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span><br>';
  496. else $('.frame')[2].innerHTML = ''
  497. }
  498. var str = ''
  499. for (let i = 0; i < e.length; i++) {
  500. str += `<div class="result">${renderEquation(e[i].content)}<br><span class="label label-default" onclick="doQuery(JSON.stringify({content:'${e[i].id}'}),'id',2,-2)">${e[i].id}</span> `;
  501. str += `${e[i].title}${e[i].descriptions ? ' - ' + e[i].descriptions : ''}<span class="pull-right">${e[i].type}</span><br>`
  502. let ions = JSON.parse(e[i].ions)
  503. str += '<span class="ions">'
  504. for (let j = 0; j < ions.length; j++) {
  505. str += `<span class="ion"><span class="label label-ion label-sub">${ions[j].id}</span> ${renderEquation(ions[j].c + '~' + ions[j].v)}</span>`
  506. if (j < ions.length - 1) str += '/'
  507. }
  508. if (ions.length) str += '<br>'
  509. str += '</span>'
  510. if (isId) {
  511. if (replace) $('#qryInput').val(e[0].content)
  512. $('#addTitle').val(e[0].title)
  513. $('#addIdText').val(JSON.parse(bd).content)
  514. $('#addDescription').val(e[0].descriptions)
  515. procClass(e)
  516. type = e[0].type
  517. $('.type').removeClass('active')
  518. $('.type-' + type).addClass('active')
  519. ionList = JSON.parse(e[0].ions)
  520. updateIon()
  521. }
  522. if (qin.match('!') || replace == 2) $('#qryInput').val(e[0].content)
  523. str += '</div>'
  524. }
  525. if (insAfter == -1) $('.frame')[2].innerHTML += str
  526. } else if (nameq == 'io') {
  527. if (insAfter == -1) {
  528. if (!isId) $('.frame')[3].innerHTML = '<span id="qryInputRender-io">' + renderEquation(qin) + ' - 匹配到 ' + e.length + ' 个</span><br><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span><br>';
  529. else $('.frame')[3].innerHTML = ''
  530. }
  531. var str = '', okstr = ''
  532. ionRegex = ''
  533. for (let i = 0; i < e.length; i++) {
  534. str += `<div class="result"><span class="count-ion-${e[i].id}"></span>${renderEquation(e[i].content)}<br><span class="label label-ion" onclick="addIon(${e[i].id},'${e[i].content}')">${e[i].id}</span> `;
  535. str += e[i].title + '<br>';
  536. ionClass[e[i].id] = e[i].class
  537. if (useIonId) {
  538. okstr += e[i].content + ' / ';
  539. ionRegex += '(?=.*"id":' + e[i].id + ',.*)'
  540. } else if (isId) {
  541. if (replace) $('#qryInput').val(e[0].content)
  542. $('#addTitle').val(e[0].title)
  543. $('#addIdText').val(JSON.parse(bd).content)
  544. $('#addDescription').val(e[0].descriptions)
  545. procClass(e)
  546. type = e[0].type
  547. $('.type').removeClass('active')
  548. $('.type-' + type).addClass('active')
  549. }
  550. if (qin.match('!') || replace == 2) $('#qryInput').val(e[0].content)
  551. str += '</div>'
  552. }
  553. ionRegex += '.*'
  554. if (insAfter == -1) $('.frame')[3].innerHTML += str
  555. $('.ok').text(okstr)
  556. } else renderTable(bd, e)
  557. MathJax.typeset()
  558. return e.length
  559. }
  560. async function doQuery(bd, isId = '', replace = 1, insAfter = -1) {
  561. const res = await fetch('/chem/query/' + nameq + isId, {
  562. method: 'POST',
  563. headers: {
  564. 'Content-type': 'application/json',
  565. },
  566. body: bd
  567. })
  568. const e = await res.text()
  569. return renderResult(bd, e, isId, replace, insAfter)
  570. }
  571. function doUpload(bd) {
  572. fetch('/chem/' + modeq + '/' + nameq, {
  573. method: 'POST',
  574. headers: {
  575. 'Content-type': 'application/json',
  576. },
  577. body: bd
  578. }).then(() => {
  579. if (nameq == 'eq' && modeq == 'upd') inputId()
  580. else if (!$('#qryInput').val()) return
  581. else doQuery(JSON.stringify({
  582. content: getRegex()
  583. }))
  584. })
  585. }
  586. async function upload(res) {
  587. var bd = {}
  588. if (nameq == 'eq') {
  589. $('#balInput').val($('#qryInput').val() ? $('#qryInput').val() : $('#qryInput').attr('placeholder').split('(')[0])
  590. setBal();
  591. e = await balance()
  592. if (e[0] == '!') return;
  593. input();
  594. if (!$('#addDescription').val()) return alert('无描述!')
  595. if (!confirm(e + (res ? '有相似项,' : '') + '确认上传?')) return
  596. $('#qryInput').val(e)
  597. bd = {
  598. content: $('#qryInput').val(),
  599. conditions: $('#addCondition').val(),
  600. descriptions: $('#addDescription').val(),
  601. }
  602. } else if (nameq == 'mo') {
  603. getClass()
  604. if (!$('#addTitle').val()) return alert('无中文名!')
  605. if (!checkIon()) {
  606. await autoClass()
  607. if (!checkIon() && !confirm('电荷总数不为零,确认继续?')) return
  608. }
  609. if (!confirm((res ? '有相似项,' : '') + '确认上传?')) return;
  610. bd = {
  611. content: $('#qryInput').val(),
  612. title: $('#addTitle').val(),
  613. descriptions: $('#addDescription').val(),
  614. class: JSON.stringify(filClass()),
  615. ions: JSON.stringify(ionList),
  616. type: type
  617. }
  618. } else if (nameq == 'io') {
  619. getClass()
  620. if (!$('#addTitle').val()) return alert('无中文名!')
  621. if (!checkIon(1) && !confirm('电荷总数不符,确认继续?')) return
  622. if (!confirm((res ? '有相似项,' : '') + '确认上传?')) return;
  623. bd = {
  624. content: $('#qryInput').val(),
  625. class: JSON.stringify(filClass()),
  626. title: $('#addTitle').val()
  627. }
  628. }
  629. if (modeq == 'upd') bd['id'] = $('#addIdText').val()
  630. if (bd.content) doUpload(JSON.stringify(bd))
  631. }
  632. function query() {
  633. if (modeq == 'query' || modeq == 'add') {
  634. var bd
  635. if (nameq == 'mo' && modeq == 'query' && useIonId) {
  636. if (ionRegex == '') return
  637. bd = JSON.stringify({
  638. content: ionRegex,
  639. type: 'ions'
  640. })
  641. } else {
  642. var cont = getRegex();
  643. $('.ok').text(cont);
  644. if (cont == '') return
  645. bd = JSON.stringify({
  646. content: cont,
  647. type: useIon && modeq == 'query' && nameq == 'mo' ? (useIonId ? 'ionid' : 'ions') : 'content'
  648. })
  649. }
  650. doQuery(bd).then(res => {
  651. if (modeq == 'add') {
  652. upload(res)
  653. }
  654. })
  655. }
  656. if (modeq == 'upd') {
  657. upload(0)
  658. }
  659. }
  660. var curCount = {}, curClass = {}
  661. function getClass(force = 0) {
  662. let e = parseEquation($('#qryInput').val())
  663. if (!force) {
  664. for (let i in curCount) {
  665. curClass[i] = $('#class-' + i).val()
  666. }
  667. }
  668. $('#class').empty()
  669. if (e != curCount) {
  670. if (JSON.stringify(e) == '{}') $('#pclass').show()
  671. else $('#pclass').hide(300)
  672. for (let i in e) {
  673. $("#class").append(`<span class="input-group-addon">${i}</span><input id="class-${i}" type="text" class="form-control" autocomplete="off" placeholder="">`)
  674. $('#class-' + i).val(curClass[i])
  675. if (!curCount[i]) {
  676. $('#class-' + i).hide()
  677. $('#class-' + i).show(300)
  678. }
  679. }
  680. }
  681. curCount = e
  682. }
  683. function filClass() {
  684. let fil = []
  685. for (j in curCount) {
  686. if (curClass[j].match(',')) {
  687. let sp = curClass[j].split(',')
  688. for (k = 0; k < sp.length; k++) {
  689. let g = {}; g[j] = sp[k]
  690. if (sp[k]) fil.push(g)
  691. }
  692. } else {
  693. let g = {}; g[j] = curClass[j]
  694. if (curClass[j]) fil.push(g)
  695. }
  696. }
  697. return fil
  698. }
  699. async function autoClass() {
  700. await getIons()
  701. for (i in curClass) curClass[i] = ''
  702. for (let i = 0; i < ionList.length; i++) {
  703. let e = JSON.parse(ionClass[ionList[i].id])
  704. for (let j = 0; j < e.length; j++) {
  705. for (k in e[j]) {
  706. if (curClass[k]) curClass[k] += ',' + e[j][k]
  707. else curClass[k] = e[j][k]
  708. }
  709. }
  710. }
  711. getClass(1)
  712. }
  713. var ionList = [], ionClass = {}
  714. async function getIons() {
  715. $('.frame')[3].classList.add('active')
  716. $('.qry-group>label')[2].classList.add('active')
  717. getClass()
  718. let str = ''
  719. for (let i in curCount) {
  720. str += '|' + i
  721. }
  722. bd = JSON.stringify({ content: '^((' + str.slice(1) + ')\\d?)+(<|[^a-z])' })
  723. nameq = 'io'
  724. await doQuery(bd, '')
  725. nameq = 'mo'
  726. $('#qryInputRender-io').append(' - 点击标签以添加')
  727. }
  728. async function getOkIons() {
  729. let e = $('#qryInput').val()
  730. if (e && e.replace(/[^\d,]/g, '') == e) {
  731. e = e.replace(/,/g, "' or id='")
  732. bd = JSON.stringify({ content: e })
  733. nameq = 'io'
  734. await doQuery(bd, 'id', 0)
  735. nameq = 'mo'
  736. }
  737. }
  738. function updateIon() {
  739. let str = ''
  740. $('.ionList').empty()
  741. if (!ionList.length) return $('.ionList').append('...')
  742. for (let i = 0; i < ionList.length; i++) {
  743. str += `<span class="ion"><span class="label label-ion" onclick="removeIon(${ionList[i].id})">${ionList[i].id}</span> ${renderEquation(ionList[i].v)} x${ionList[i].c}</span>/`
  744. }
  745. str += ' 点击标签以减少 / <span style="cursor:pointer" class="glyphicon glyphicon-trash" onclick="clearIon()"></span>'
  746. $('.ionList').append(str)
  747. if (preview) MathJax.typeset()
  748. }
  749. function clearIon() {
  750. ionList = []
  751. updateIon()
  752. }
  753. function addIon(id, v) {
  754. console.log(ionList)
  755. if (!ionList.filter(e => {
  756. if (e.id == id) e.c++, $('.count-ion-' + id).text(e.c + ' ')
  757. return e.id == id
  758. }).length) {
  759. $('.count-ion-' + id).text('1 ')
  760. ionList.push({ id: id, v: v, c: 1 })
  761. }
  762. updateIon()
  763. }
  764. function removeIon(id, v) {
  765. ionList = ionList.filter(e => {
  766. if (e.id == id) e.c--, $('.count-ion-' + id).text(e.c + ' ')
  767. return e.c
  768. })
  769. updateIon()
  770. }
  771. function checkIon(f = 0) {
  772. if (f) f = $('#qryInput').val().replace(/<e([+-])>/g, '<1e$1>').replace(/.*<(\d)e([+-])>$/g, '$2$1')
  773. let sum = 0
  774. for (let i in curCount) {
  775. if (curClass[i].match(',')) return true
  776. sum += curCount[i] * curClass[i]
  777. }
  778. return sum == f
  779. }
  780. function input2() {
  781. if ((modeq == 'add' || modeq == 'upd') && (nameq == 'mo' || nameq == 'io')) getClass()
  782. if (nameq == 'mo' && modeq == 'query' && useIonId) {
  783. getOkIons()
  784. } else {
  785. if (modeq == 'query') {
  786. $('.ok').text(getRegex())
  787. }
  788. if ($('#qryInput').val() && $('#qryInput').val().match(/^\d+!?$/g)) {
  789. doQuery(JSON.stringify({ content: $('#qryInput').val().split('!')[0] }), 'id', 0)
  790. } else if ($('#qryInput').val().match('!')) {
  791. $('#qryInput').val($('#qryInput').val().split('!')[0])
  792. doQuery(JSON.stringify({ content: getRegex() }), '', 2)
  793. }
  794. }
  795. if (nameq == 'eq') {
  796. if ($('#qryInputRender')[0]) {
  797. if (preview) {
  798. $('#qryInputRender').html(renderEquation(strict ? ($('#qryInput').val() + '=' + $('#qryInput2').val()) : ($('#qryInput').val())))
  799. } else $('#qryInputRender').text((strict ? ($('#qryInput').val() + '=' + $('#qryInput2').val()) : ($('#qryInput').val())))
  800. }
  801. } else {
  802. if ($('#qryInputRender-' + nameq)[0]) {
  803. if (preview) {
  804. $('#qryInputRender-' + nameq).html(renderEquation($('#qryInput').val()))
  805. } else $('#qryInputRender-' + nameq).text($('#qryInput').val())
  806. }
  807. }
  808. if (preview) MathJax.typeset()
  809. }
  810. function getC(str) {
  811. if (str == 'eq') return 1
  812. if (str == 'mo') return 2
  813. if (str == 'io') return 3
  814. }
  815. function inputId() {
  816. var bd = JSON.stringify({
  817. content: $('#addIdText').val(),
  818. })
  819. if (!$('#addIdText').val()) {
  820. if (nameq != 'el') $('.frame')[getC(nameq)].innerHTML = '';
  821. return;
  822. }
  823. doQuery(bd, 'id')
  824. }
  825. function qryToggleMatch() {
  826. if (matchMode == 'mole') {
  827. matchMode = 'elem'
  828. } else {
  829. matchMode = 'mole'
  830. }
  831. }
  832. var type = '酸';