chem.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. for (let i = 0; i < typelist.length; i++) {
  187. $('.type-list').append(`<label class="btn btn-default type type-${typelist[i]} add add-mo${i ? '' : ' active'}" onclick="type=${typelist[i]}"><input type="radio"> ${typelist[i]} </label>`)
  188. }
  189. })
  190. function setBal() {
  191. $('#precise').hide()
  192. $('.frame')[0].innerHTML = renderEquation(balText);
  193. $('#balBtn').html('配平 <span class="glyphicon glyphicon-transfer"></span>')
  194. $('#balInput').attr('placeholder', case1 + '(输入化学式以配平)')
  195. $('#balBtn').attr('href', '/chem?' + case1)
  196. $('#balBtn').removeClass('disabled')
  197. mode = 'bal'
  198. input()
  199. MathJax.typeset()
  200. }
  201. function setWeigh() {
  202. $('#precise').show()
  203. $('#balBtn').text('相对质量')
  204. $('#balInput').attr('placeholder', case2 + '(输入化学式以计算相对质量)')
  205. $('#balBtn').attr('href', '')
  206. $('#balBtn').addClass('disabled')
  207. mode = 'weigh'
  208. input()
  209. }
  210. function input() {
  211. inputText = balInput.value.replace(/[\[\{]/g, '(').replace(/[\]\}]/g, ')')
  212. if (mode == 'bal') {
  213. $('.frame')[0].innerHTML = renderEquation((inputText == '') ? case1 : inputText) + '<br>'
  214. + '<span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span><br>' + ((balText != '') ? (renderEquation(balText)) : ('...'));
  215. } else if (mode == 'weigh') {
  216. $('.frame')[0].innerHTML = renderEquation((inputText == '') ? case2 : inputText) + '<br>'
  217. + weighEquation((inputText == '') ? case2 : inputText, precise);
  218. }
  219. if (preview) MathJax.typeset()
  220. if (inputText.match('!')) {
  221. balUp()
  222. }
  223. }
  224. var running;
  225. function balance() {
  226. input()
  227. if (running || mode != 'bal') return;
  228. $('#balBtn').text('配平...')
  229. $('#balBtn').addClass('disabled')
  230. $('.frame').addClass('text-muted')
  231. running = 1;
  232. fetch('/alog', {
  233. method: 'POST',
  234. headers: {
  235. 'Content-type': 'application/json',
  236. },
  237. body: '{"content":"' + ((inputText == '') ? case1 : inputText) + '"}'
  238. })
  239. return fetch('https://43.143.233.184:7989/chem', {
  240. method: 'POST',
  241. headers: {
  242. 'Content-type': 'application/json',
  243. },
  244. body: '{"q":"' + ((inputText == '') ? case1 : inputText) + '"}'
  245. }).then(
  246. res => res.text()
  247. ).then(e => {
  248. if (e == '{}') e = '"!Description: Invalid Character."'
  249. e = e.split('"')[1].replace(/\\n/g, '\n')
  250. $('.frame')[0].innerHTML = (e.charAt(0) == '!') ? ('<pre class="text-danger bg-danger">' + e.slice(1, e.length) + '</pre>') : (renderEquation((inputText == '') ? case1 : inputText)
  251. + '<br><span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span><br>' + renderEquation(e));
  252. if (e.charAt(0) != '!') balText = e
  253. MathJax.typeset()
  254. $('#balBtn').html('配平 <span class="glyphicon glyphicon-transfer"></span>')
  255. $('#balBtn').removeClass('disabled')
  256. $('.frame').removeClass('text-muted')
  257. running = 0;
  258. return new Promise(res => res(e))
  259. })
  260. }
  261. function balUp() {
  262. if (mode != 'bal') return;
  263. $('#balInput').val(balText);
  264. input()
  265. }
  266. //QUERY-------------------------------
  267. var modeq = 'query', nameq = 'eq', strict = false, matchMode = 'mole', namels = ['eq', 'mo', 'io', 'el'], ionRegex = ''
  268. function toggl(str, is = 0) {
  269. $('#qryBtn').html(str)
  270. $('.op').hide()
  271. $('.op-' + modeq + '-' + nameq).show()
  272. if (modeq == 'add' || modeq == 'upd') {
  273. $('.add:not(.add-' + nameq + ',#addId)').hide()
  274. $('.add-' + nameq).show(500)
  275. if (modeq == 'upd') $('#addId').show(300)
  276. else $('#addId').hide(300)
  277. } else $('.add').hide()
  278. if (is) $('.qryInputHidable').show()
  279. else $('.qryInputHidable').hide()
  280. }
  281. function setQry(f = 0) {
  282. $('.qry-group>label').removeClass('active')
  283. $('.frame').removeClass('active')
  284. $('.frame')[0].classList.add('active')
  285. if (modeq == 'query') toggl('查询 <span class="glyphicon glyphicon-search"></span>', nameq == 'eq' && strict)
  286. else if (modeq == 'add') toggl('上传 <span class="glyphicon glyphicon-plus"></span>')
  287. else toggl('修改 <span class="glyphicon glyphicon-pencil"></span>')
  288. if (nameq == 'eq') {
  289. $('.frame')[1].classList.add('active')
  290. $('.qry-group>label')[0].classList.add('active')
  291. if (modeq == 'query') $('#qryInput').attr('placeholder', 'O2=H2O' + '(查询数据库中的化学式,也可输入 id)')
  292. else if (modeq == 'add') $('#qryInput').attr('placeholder', 'H2+O2=H2O' + '(将化学式上传至数据库)')
  293. else $('#qryInput').attr('placeholder', '(修改已有化学式)')
  294. } else if (nameq == 'mo') {
  295. $('.qry-group>label')[1].classList.add('active')
  296. $('.frame')[2].classList.add('active')
  297. if (modeq == 'query') {
  298. if (useIon) {
  299. if (!useIonId) $('#qryInput').attr('placeholder', 'Fe<3e+>' + '(输入离子查询数据库中的分子)')
  300. else {
  301. $('#qryInput').attr('placeholder', '2,3' + '(输入离子编号查询数据库中的分子)')
  302. $('.qry-group>label')[2].classList.add('active')
  303. $('.frame')[3].classList.add('active')
  304. }
  305. } else $('#qryInput').attr('placeholder', 'Fe' + '(查询数据库中的分子,也可输入 id)')
  306. }
  307. else if (modeq == 'add') {
  308. $('#qryInput').attr('placeholder', 'Fe3O4' + '(将分子上传至数据库)')
  309. $('#addTitle').attr('placeholder', '四氧化三铁')
  310. } else {
  311. $('#qryInput').attr('placeholder', '(修改已有分子)')
  312. $('#addTitle').attr('placeholder', '四氧化三铁')
  313. }
  314. if (useIon) $('.op-ionid').show()
  315. } else if (nameq == 'io') {
  316. $('.qry-group>label')[2].classList.add('active')
  317. $('.frame')[3].classList.add('active')
  318. if (modeq == 'query') {
  319. $('#qryInput').attr('placeholder', 'Fe' + '(查询数据库中的离子,也可输入 id)')
  320. }
  321. else if (modeq == 'add') {
  322. $('#qryInput').attr('placeholder', 'Fe<3e+>' + '(将离子上传至数据库)')
  323. $('#addTitle').attr('placeholder', '三价铁')
  324. } else {
  325. $('#qryInput').attr('placeholder', '(修改已有离子)')
  326. $('#addTitle').attr('placeholder', '三价铁')
  327. }
  328. } else {
  329. $('.qry-group>label')[3].classList.add('active')
  330. $('.frame')[4].classList.add('active')
  331. if (modeq == 'query') {
  332. $('#qryInput').attr('placeholder', 'Fe' + '(输入元素获取汇总信息)')
  333. }
  334. }
  335. input2()
  336. if (modeq == 'upd' && f) $('.add-reload').show(300)
  337. if (collapse) $('.frame:not(.active)').parent().hide(300), $('.frame.active:not(#balFrame)').parent().show(200);
  338. else $('.frame:not(#balFrame)').parent().show(300)
  339. }
  340. function replaceRegex(s) {
  341. return s.replace(/([\+\=\.;])+/g, '$1').replace(/([\(\)])/g, '\\\\$1').replace(/(<\d*)e\+/g, '$1%')
  342. }
  343. function getRegex() {
  344. var ret = ''
  345. if (nameq == 'eq') {
  346. if (strict) {
  347. var acont = $('#qryInput').val(), bcont = $('#qryInput2').val();
  348. if (!acont && !bcont) acont = $('#qryInput').attr('placeholder').split('(')[0]
  349. acont = replaceRegex(acont)
  350. bcont = replaceRegex(bcont)
  351. ret = '^'
  352. if (acont) {
  353. var as = acont.split('+')
  354. for (let i = 0; i < as.length; i++) {
  355. if (matchMode == 'mole') ret += '(?=([^=]*\\+|)[0-9]?' + as[i] + '([+=]|$))'
  356. else ret += '(?=[^=]*' + as[i] + '([^a-z]|$))'
  357. }
  358. }
  359. if (bcont) {
  360. var bs = bcont.split('+');
  361. for (let i = 0; i < bs.length; i++) {
  362. if (matchMode == 'mole') ret += '(?=.*=(.*\\+|)[0-9]?' + bs[i] + '([+=]|$))'
  363. else ret += '(?=.*=.*' + bs[i] + '([^a-z]|$))'
  364. }
  365. }
  366. ret += '.*'
  367. } else {
  368. ret = $('#qryInput').val()
  369. if (ret && !ret.match(/[^\d]/g)) return ret
  370. if (!ret) ret = $('#qryInput').attr('placeholder').split('(')[0]
  371. ret = replaceRegex(ret)
  372. var scont = ret.split('=')
  373. if (scont.length > 2) return;
  374. var as = scont[0].split('+');
  375. ret = matchMode == 'mole' ? '^' : ''
  376. for (let i = 0; i < as.length; i++) {
  377. if (matchMode == 'mole') ret += "(?=(.*[+=]|)[0-9]?" + as[i] + "([+=]|$))"
  378. else ret += '(?=.*' + as[i] + '([^a-z]|$))'
  379. }
  380. if (scont.length > 1) {
  381. var bs = scont[1].split('+')
  382. for (let i = 0; i < bs.length; i++) {
  383. if (matchMode == 'mole') ret += "(?=(.*[+=]|)[0-9]?" + bs[i] + "([+=]|$))"
  384. else ret += '(?=.*' + bs[i] + '([^a-z]|$))'
  385. }
  386. }
  387. ret += '.*'
  388. }
  389. return ret.replace(/%/g, 'e+')
  390. } else return replaceRegex($('#qryInput').val() ? $('#qryInput').val() : $('#qryInput').attr('placeholder').split('(')[0]).replace(/%/g, 'e+') + '([^a-z]|$)'
  391. }
  392. function procClass(e) {
  393. e[0].class = JSON.parse(e[0].class)
  394. let c = e[0].class
  395. for (let j = 0; j < c.length; j++) {
  396. let t = JSON.stringify(c[j]).split(':')[0].split('"')[1]
  397. let str = ''
  398. c.filter(e => {
  399. if (JSON.stringify(e).split(':')[0].split('"')[1] == t) str += ',' + JSON.stringify(e).split(':')[1].split('}')[0].replace(/"/g, '')
  400. })
  401. curClass[t] = str.slice(1)
  402. }
  403. getClass(1)
  404. }
  405. function renderTable(bd, e) {
  406. var uc = [], ut = []
  407. for (i = 0; i < e.length; i++) {
  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 == 4) {
  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 {
  557. str = ''
  558. bd = JSON.parse(bd).content.split('(')[0]
  559. str += `${bd} - ${list.indexOf(bd) > 0 ? `第 ${list.indexOf(bd)} 号` : '未知'}元素`
  560. if (list.indexOf(bd) > 0) {
  561. }
  562. $('.frame')[4].innerHTML = str + '<table class="table table-el"></table>'
  563. renderTable(bd, e)
  564. }
  565. MathJax.typeset()
  566. return e.length
  567. }
  568. async function doQuery(bd, isId = '', replace = 1, insAfter = -1) {
  569. const res = await fetch('/chem/query/' + nameq + isId, {
  570. method: 'POST',
  571. headers: {
  572. 'Content-type': 'application/json',
  573. },
  574. body: bd
  575. })
  576. const e = await res.text()
  577. return renderResult(bd, e, isId, replace, insAfter)
  578. }
  579. function doUpload(bd) {
  580. fetch('/chem/' + modeq + '/' + nameq, {
  581. method: 'POST',
  582. headers: {
  583. 'Content-type': 'application/json',
  584. },
  585. body: bd
  586. }).then(() => {
  587. if (nameq == 'eq' && modeq == 'upd') inputId()
  588. else if (!$('#qryInput').val()) return
  589. else doQuery(JSON.stringify({
  590. content: getRegex()
  591. }))
  592. })
  593. }
  594. async function upload(res) {
  595. var bd = {}
  596. if (nameq == 'eq') {
  597. $('#balInput').val($('#qryInput').val() ? $('#qryInput').val() : $('#qryInput').attr('placeholder').split('(')[0])
  598. setBal();
  599. e = await balance()
  600. if (e[0] == '!') return;
  601. input();
  602. if (!$('#addDescription').val()) return alert('无描述!')
  603. if (!confirm(e + (res ? '有相似项,' : '') + '确认上传?')) return
  604. $('#qryInput').val(e)
  605. bd = {
  606. content: $('#qryInput').val(),
  607. conditions: $('#addCondition').val(),
  608. descriptions: $('#addDescription').val(),
  609. }
  610. } else if (nameq == 'mo') {
  611. getClass()
  612. if (!$('#addTitle').val()) return alert('无中文名!')
  613. if (!checkIon()) {
  614. await autoClass()
  615. if (!checkIon() && !confirm('电荷总数不为零,确认继续?')) return
  616. }
  617. if (!confirm((res ? '有相似项,' : '') + '确认上传?')) return;
  618. bd = {
  619. content: $('#qryInput').val(),
  620. title: $('#addTitle').val(),
  621. descriptions: $('#addDescription').val(),
  622. class: JSON.stringify(filClass()),
  623. ions: JSON.stringify(ionList),
  624. type: type
  625. }
  626. } else if (nameq == 'io') {
  627. getClass()
  628. if (!$('#addTitle').val()) return alert('无中文名!')
  629. if (!checkIon(1) && !confirm('电荷总数不符,确认继续?')) return
  630. if (!confirm((res ? '有相似项,' : '') + '确认上传?')) return;
  631. bd = {
  632. content: $('#qryInput').val(),
  633. class: JSON.stringify(filClass()),
  634. title: $('#addTitle').val()
  635. }
  636. }
  637. if (modeq == 'upd') bd['id'] = $('#addIdText').val()
  638. if (bd.content) doUpload(JSON.stringify(bd))
  639. }
  640. function query() {
  641. if (modeq == 'query' || modeq == 'add') {
  642. var bd
  643. if (nameq == 'mo' && modeq == 'query' && useIonId) {
  644. if (ionRegex == '') return
  645. bd = JSON.stringify({
  646. content: ionRegex,
  647. type: 'ions'
  648. })
  649. } else {
  650. var cont = getRegex();
  651. // $('.ok').text(cont);
  652. if (cont == '') return
  653. bd = JSON.stringify({
  654. content: cont,
  655. type: useIon && modeq == 'query' && nameq == 'mo' ? (useIonId ? 'ionid' : 'ions') : 'content'
  656. })
  657. }
  658. doQuery(bd).then(res => {
  659. if (modeq == 'add') {
  660. upload(res)
  661. }
  662. })
  663. }
  664. if (modeq == 'upd') {
  665. upload(0)
  666. }
  667. }
  668. var curCount = {}, curClass = {}
  669. function getClass(force = 0) {
  670. let e = parseEquation($('#qryInput').val())
  671. if (!force) {
  672. for (let i in curCount) {
  673. curClass[i] = $('#class-' + i).val()
  674. }
  675. }
  676. $('#class').empty()
  677. if (e != curCount) {
  678. if (JSON.stringify(e) == '{}') $('#pclass').show()
  679. else $('#pclass').hide(300)
  680. for (let i in e) {
  681. $("#class").append(`<span class="input-group-addon">${i}</span><input id="class-${i}" type="text" class="form-control" autocomplete="off" placeholder="">`)
  682. $('#class-' + i).val(curClass[i])
  683. if (!curCount[i]) {
  684. $('#class-' + i).hide()
  685. $('#class-' + i).show(300)
  686. }
  687. }
  688. }
  689. curCount = e
  690. }
  691. function filClass() {
  692. let fil = []
  693. for (j in curCount) {
  694. if (curClass[j].match(',')) {
  695. let sp = curClass[j].split(',')
  696. for (k = 0; k < sp.length; k++) {
  697. let g = {}; g[j] = sp[k]
  698. if (sp[k]) fil.push(g)
  699. }
  700. } else {
  701. let g = {}; g[j] = curClass[j]
  702. if (curClass[j]) fil.push(g)
  703. }
  704. }
  705. return fil
  706. }
  707. async function autoClass() {
  708. await getIons()
  709. for (i in curClass) curClass[i] = ''
  710. for (let i = 0; i < ionList.length; i++) {
  711. let e = JSON.parse(ionClass[ionList[i].id])
  712. for (let j = 0; j < e.length; j++) {
  713. for (k in e[j]) {
  714. if (curClass[k]) curClass[k] += ',' + e[j][k]
  715. else curClass[k] = e[j][k]
  716. }
  717. }
  718. }
  719. getClass(1)
  720. }
  721. var ionList = [], ionClass = {}
  722. async function getIons() {
  723. $('.frame')[3].classList.add('active')
  724. $('.qry-group>label')[2].classList.add('active')
  725. getClass()
  726. let str = ''
  727. for (let i in curCount) {
  728. str += '|' + i
  729. }
  730. bd = JSON.stringify({ content: '^((' + str.slice(1) + ')\\d?)+(<|[^a-z])' })
  731. nameq = 'io'
  732. await doQuery(bd, '')
  733. nameq = 'mo'
  734. $('#qryInputRender-io').append(' - 点击标签以添加')
  735. }
  736. async function getOkIons() {
  737. let e = $('#qryInput').val()
  738. if (e && e.replace(/[^\d,]/g, '') == e) {
  739. e = e.replace(/,/g, "' or id='")
  740. bd = JSON.stringify({ content: e })
  741. nameq = 'io'
  742. await doQuery(bd, 'id', 0)
  743. nameq = 'mo'
  744. }
  745. }
  746. function updateIon() {
  747. let str = ''
  748. $('.ionList').empty()
  749. if (!ionList.length) return $('.ionList').append('...')
  750. for (let i = 0; i < ionList.length; i++) {
  751. 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>/`
  752. }
  753. str += ' 点击标签以减少 / <span style="cursor:pointer" class="glyphicon glyphicon-trash" onclick="clearIon()"></span>'
  754. $('.ionList').append(str)
  755. if (preview) MathJax.typeset()
  756. }
  757. function clearIon() {
  758. ionList = []
  759. updateIon()
  760. }
  761. function addIon(id, v) {
  762. console.log(ionList)
  763. if (!ionList.filter(e => {
  764. if (e.id == id) e.c++, $('.count-ion-' + id).text(e.c + ' ')
  765. return e.id == id
  766. }).length) {
  767. $('.count-ion-' + id).text('1 ')
  768. ionList.push({ id: id, v: v, c: 1 })
  769. }
  770. updateIon()
  771. }
  772. function removeIon(id, v) {
  773. ionList = ionList.filter(e => {
  774. if (e.id == id) e.c--, $('.count-ion-' + id).text(e.c + ' ')
  775. return e.c
  776. })
  777. updateIon()
  778. }
  779. function checkIon(f = 0) {
  780. if (f) f = $('#qryInput').val().replace(/<e([+-])>/g, '<1e$1>').replace(/.*<(\d)e([+-])>$/g, '$2$1')
  781. let sum = 0
  782. for (let i in curCount) {
  783. if (curClass[i].match(',')) return true
  784. sum += curCount[i] * curClass[i]
  785. }
  786. return sum == f
  787. }
  788. function input2() {
  789. if ((modeq == 'add' || modeq == 'upd') && (nameq == 'mo' || nameq == 'io')) getClass()
  790. if (nameq == 'mo' && modeq == 'query' && useIonId) {
  791. getOkIons()
  792. } else {
  793. if (modeq == 'query') {
  794. // $('.ok').text(getRegex())
  795. }
  796. if ($('#qryInput').val() && $('#qryInput').val().match(/^\d+!?$/g)) {
  797. doQuery(JSON.stringify({ content: $('#qryInput').val().split('!')[0] }), 'id', 0)
  798. } else if ($('#qryInput').val().match('!')) {
  799. $('#qryInput').val($('#qryInput').val().split('!')[0])
  800. doQuery(JSON.stringify({ content: getRegex() }), '', 2)
  801. }
  802. }
  803. if (nameq == 'eq') {
  804. if ($('#qryInputRender')[0]) {
  805. if (preview) {
  806. $('#qryInputRender').html(renderEquation(strict ? ($('#qryInput').val() + '=' + $('#qryInput2').val()) : ($('#qryInput').val())))
  807. } else $('#qryInputRender').text((strict ? ($('#qryInput').val() + '=' + $('#qryInput2').val()) : ($('#qryInput').val())))
  808. }
  809. } else {
  810. if ($('#qryInputRender-' + nameq)[0]) {
  811. if (preview) {
  812. $('#qryInputRender-' + nameq).html(renderEquation($('#qryInput').val()))
  813. } else $('#qryInputRender-' + nameq).text($('#qryInput').val())
  814. }
  815. }
  816. if (preview) MathJax.typeset()
  817. }
  818. function getC(str) {
  819. if (str == 'eq') return 1
  820. if (str == 'mo') return 2
  821. if (str == 'io') return 3
  822. }
  823. function inputId() {
  824. var bd = JSON.stringify({
  825. content: $('#addIdText').val(),
  826. })
  827. if (!$('#addIdText').val()) {
  828. if (nameq != 'el') $('.frame')[getC(nameq)].innerHTML = '';
  829. return;
  830. }
  831. doQuery(bd, 'id')
  832. }
  833. function qryToggleMatch() {
  834. if (matchMode == 'mole') {
  835. matchMode = 'elem'
  836. } else {
  837. matchMode = 'mole'
  838. }
  839. }
  840. var typelist = ['单质', '酸', '碱', '盐', '氧化物', '氢化物'], type = typelist[0];