chem.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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
  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, co = 1, 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, '')
  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
  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'
  265. function toggl(str, is = 0) {
  266. $('#qryBtn').html(str)
  267. $('.add').hide()
  268. $('.op').hide()
  269. $('.op-' + modeq + '-' + nameq).show()
  270. if (modeq == 'add' || modeq == 'upd') {
  271. $('.add-' + nameq).show()
  272. if (modeq == 'upd') $('#addId').show()
  273. else $('#addId').hide()
  274. }
  275. if (is) $('.qryInputHidable').show()
  276. else $('.qryInputHidable').hide()
  277. }
  278. function setQry() {
  279. if (nameq == 'eq') {
  280. $('.frame').removeClass('active')
  281. $('.frame')[0].classList.add('active')
  282. $('.frame')[1].classList.add('active')
  283. $('.qry-group>label').removeClass('active')
  284. $('.qry-group>label')[0].classList.add('active')
  285. if (modeq == 'query') {
  286. toggl('查询 <span class="glyphicon glyphicon-search"></span>', strict)
  287. $('#qryInput').attr('placeholder', 'O2=H2O' + '(输入化学式查询数据库,也可输入 id)')
  288. input2();
  289. }
  290. else if (modeq == 'add') {
  291. toggl('上传 <span class="glyphicon glyphicon-plus"></span>')
  292. $('#qryInput').attr('placeholder', 'H2+O2=H2O' + '(输入化学式上传至数据库)')
  293. } else {
  294. toggl('修改 <span class="glyphicon glyphicon-pencil"></span>')
  295. $('#qryInput').attr('placeholder', '(修改已有化学式)')
  296. }
  297. } else if (nameq == 'mo') {
  298. $('.qry-group>label').removeClass('active')
  299. $('.qry-group>label')[1].classList.add('active')
  300. $('.frame').removeClass('active')
  301. $('.frame')[0].classList.add('active')
  302. $('.frame')[2].classList.add('active')
  303. if (modeq == 'query') {
  304. toggl('查询 <span class="glyphicon glyphicon-search"></span>')
  305. $('#qryMatch').html('<span class="glyphicon glyphicon-cog"></span> 匹配分子')
  306. matchMode = 'mole'
  307. $('#qryInput').attr('placeholder', 'Fe' + '(输入分子查询数据库,也可输入 id)')
  308. input2();
  309. }
  310. else if (modeq == 'add') {
  311. toggl('上传 <span class="glyphicon glyphicon-plus"></span>')
  312. $('#qryInput').attr('placeholder', 'Fe3O4' + '(输入分子上传至数据库)')
  313. $('#addTitle').attr('placeholder', '四氧化三铁')
  314. } else {
  315. toggl('修改 <span class="glyphicon glyphicon-pencil"></span>')
  316. $('#qryInput').attr('placeholder', '(修改已有分子)')
  317. $('#addTitle').attr('placeholder', '四氧化三铁')
  318. }
  319. } else if (nameq == 'io') {
  320. $('.qry-group>label').removeClass('active')
  321. $('.qry-group>label')[2].classList.add('active')
  322. $('.frame').removeClass('active')
  323. $('.frame')[0].classList.add('active')
  324. $('.frame')[3].classList.add('active')
  325. if (modeq == 'query') {
  326. toggl('查询 <span class="glyphicon glyphicon-search"></span>')
  327. $('#qryMatch').html('<span class="glyphicon glyphicon-cog"></span> 匹配离子')
  328. matchMode = 'mole'
  329. $('#qryInput').attr('placeholder', 'Fe' + '(输入离子查询数据库,也可输入 id)')
  330. input2();
  331. }
  332. else if (modeq == 'add') {
  333. toggl('上传 <span class="glyphicon glyphicon-plus"></span>')
  334. $('#qryInput').attr('placeholder', 'Fe<3e+>' + '(输入离子上传至数据库)')
  335. $('#addTitle').attr('placeholder', '三价铁')
  336. } else {
  337. toggl('修改 <span class="glyphicon glyphicon-pencil"></span>')
  338. $('#qryInput').attr('placeholder', '(修改已有离子)')
  339. $('#addTitle').attr('placeholder', '三价铁')
  340. }
  341. } else {
  342. $('.qry-group>label').removeClass('active')
  343. $('.qry-group>label')[3].classList.add('active')
  344. $('.frame').removeClass('active')
  345. $('.frame')[0].classList.add('active')
  346. $('.frame')[4].classList.add('active')
  347. }
  348. input2()
  349. }
  350. function replaceRegex(s) {
  351. return s.replace(/([\+\=\.;])+/g, '$1').replace(/([\(\)])/g, '\\\\$1').replace(/(<\d*)e\+/g, '$1%')
  352. }
  353. function getRegex() {
  354. var ret = ''
  355. if (nameq == 'eq') {
  356. if (strict) {
  357. var acont = $('#qryInput').val(), bcont = $('#qryInput2').val();
  358. if (!acont && !bcont) acont = $('#qryInput').attr('placeholder').split('(')[0]
  359. acont = replaceRegex(acont)
  360. bcont = replaceRegex(bcont)
  361. ret = '^'
  362. if (acont) {
  363. var as = acont.split('+')
  364. for (let i = 0; i < as.length; i++) {
  365. if (matchMode == 'mole') ret += '(?=([^=]*\\+|)[0-9]?' + as[i] + '([+=]|$))'
  366. else ret += '(?=[^=]*' + as[i] + '([^a-z]|$))'
  367. }
  368. }
  369. if (bcont) {
  370. var bs = bcont.split('+');
  371. for (let i = 0; i < bs.length; i++) {
  372. if (matchMode == 'mole') ret += '(?=.*=(.*\\+|)[0-9]?' + bs[i] + '([+=]|$))'
  373. else ret += '(?=.*=.*' + bs[i] + '([^a-z]|$))'
  374. }
  375. }
  376. ret += '.*'
  377. } else {
  378. ret = $('#qryInput').val()
  379. if (ret && !ret.match(/[^\d]/g)) return ret
  380. if (!ret) ret = $('#qryInput').attr('placeholder').split('(')[0]
  381. ret = replaceRegex(ret)
  382. var scont = ret.split('=')
  383. if (scont.length > 2) return;
  384. var as = scont[0].split('+');
  385. ret = matchMode == 'mole' ? '^' : ''
  386. for (let i = 0; i < as.length; i++) {
  387. if (matchMode == 'mole') ret += "(?=(.*[+=]|)[0-9]?" + as[i] + "([+=]|$))"
  388. else ret += '(?=.*' + as[i] + '([^a-z]|$))'
  389. }
  390. if (scont.length > 1) {
  391. var bs = scont[1].split('+')
  392. for (let i = 0; i < bs.length; i++) {
  393. if (matchMode == 'mole') ret += "(?=(.*[+=]|)[0-9]?" + bs[i] + "([+=]|$))"
  394. else ret += '(?=.*' + bs[i] + '([^a-z]|$))'
  395. }
  396. }
  397. ret += '.*'
  398. }
  399. return ret.replace(/%/g, 'e+')
  400. } else return $('#qryInput').val()
  401. }
  402. var ggg
  403. function doQuery(bd, isId = '', replace = 1, insAfter = -1) {
  404. return fetch('/chem/query/' + nameq + isId, {
  405. method: 'POST',
  406. headers: {
  407. 'Content-type': 'application/json',
  408. },
  409. body: bd
  410. }).then(res => {
  411. return res.text()
  412. }).then(e => {
  413. if (nameq == 'eq') {
  414. if (e[0] == '!') {
  415. $('.frame')[1].innerHTML = '<pre class="text-danger bg-danger">' + e + '</pre>';
  416. } else if (insAfter != -1) {
  417. e = JSON.parse(e)
  418. if (isId) {
  419. if (replace) $('#qryInput').val(e[0].content)
  420. $('#addCondition').val(e[0].conditions)
  421. $('#addIdText').val(JSON.parse(bd).content)
  422. $('#addDescription').val(e[0].descriptions)
  423. }
  424. var str = ''
  425. str += '<div class="result" style="margin-left: 50px;margin-top: -20px;">' + renderEquation(e[0].content, e[0].conditions) + '<br>';
  426. if (e[0].conditions) str += '(' + e[0].conditions + ')';
  427. str += e[0].descriptions + '<br>';
  428. str += '</div>'
  429. $('.res-' + insAfter).append(str)
  430. MathJax.typeset()
  431. } else {
  432. let qin = $('#qryInput').val()
  433. e = JSON.parse(e)
  434. if (!isId || !replace) {
  435. $('.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>';
  436. } else $('.frame')[1].innerHTML = ''
  437. var str = ''
  438. for (let i = 0; i < e.length; i++) {
  439. 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> `;
  440. if (e[i].conditions) str += '(' + e[i].conditions + ')';
  441. str += e[i].descriptions + '<br>';
  442. if (e[i].rel > 0) {
  443. 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>`;
  444. }
  445. if (e[i].rel < 0) {
  446. 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>`;
  447. }
  448. if (isId) {
  449. if (replace) $('#qryInput').val(e[0].content)
  450. $('#addTitle').val(e[0].conditions)
  451. $('#addIdText').val(JSON.parse(bd).content)
  452. $('#addDescription').val(e[0].descriptions)
  453. }
  454. if (qin.match('!') || replace == 2) $('#qryInput').val(e[0].content)
  455. str += '</div>'
  456. }
  457. $('.frame')[1].innerHTML += str
  458. MathJax.typeset()
  459. return e.length
  460. }
  461. } else if (nameq == 'mo') {
  462. let qin = $('#qryInput').val()
  463. e = JSON.parse(e)
  464. if (insAfter == -1) {
  465. 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>';
  466. else $('.frame')[2].innerHTML = ''
  467. }
  468. var str = ''
  469. for (let i = 0; i < e.length; i++) {
  470. 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> `;
  471. str += e[i].title + ' ' + e[i].descriptions + '<br>';
  472. let ions = JSON.parse(e[i].ions)
  473. for (let j = 0; j < ions.length; j++) {
  474. str += `<span class="ion">${renderEquation(ions[j].c + '~' + ions[j].v)}</span>`
  475. if (j < ions.length - 1) str += '/'
  476. }
  477. if (ions.length) str += '<br>'
  478. if (isId) {
  479. if (replace) $('#qryInput').val(e[0].content)
  480. $('#addTitle').val(e[0].title)
  481. $('#addIdText').val(JSON.parse(bd).content)
  482. $('#addDescription').val(e[0].descriptions)
  483. e[0].class = JSON.parse(e[0].class)
  484. let c = e[0].class
  485. console.log(ggg = c)
  486. for (let j = 0; j < c.length; j++) {
  487. let t = JSON.stringify(c[j]).split(':')[0].split('"')[1]
  488. let str = ''
  489. c.filter(e => {
  490. if (JSON.stringify(e).split(':')[0].split('"')[1] == t) str += ',' + JSON.stringify(e).split(':')[1].split('}')[0].replace(/"/g, '')
  491. })
  492. curClass[t] = str.slice(1)
  493. }
  494. console.log(curClass, e[0].class, e[0].ions)
  495. ionList = JSON.parse(e[0].ions)
  496. updateIon()
  497. getClass(1)
  498. }
  499. if (qin.match('!') || replace == 2) $('#qryInput').val(e[0].content)
  500. str += '</div>'
  501. }
  502. if (insAfter == -1) $('.frame')[2].innerHTML += str
  503. MathJax.typeset()
  504. return e.length
  505. } else if (nameq == 'io') {
  506. let qin = $('#qryInput').val()
  507. e = JSON.parse(e)
  508. if (insAfter == -1) {
  509. 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>';
  510. else $('.frame')[3].innerHTML = ''
  511. }
  512. var str = ''
  513. for (let i = 0; i < e.length; i++) {
  514. 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> `;
  515. str += e[i].title + '<br>';
  516. if (isId) {
  517. if (replace) $('#qryInput').val(e[0].content)
  518. $('#addTitle').val(e[0].title)
  519. $('#addIdText').val(JSON.parse(bd).content)
  520. $('#addDescription').val(e[0].descriptions)
  521. }
  522. if (qin.match('!') || replace == 2) $('#qryInput').val(e[0].content)
  523. str += '</div>'
  524. }
  525. if (insAfter == -1) $('.frame')[3].innerHTML += str
  526. MathJax.typeset()
  527. return e.length
  528. }
  529. });
  530. }
  531. function queryFetch(bd) {
  532. console.log(bd)
  533. fetch('/chem/' + modeq + '/' + nameq, {
  534. method: 'POST',
  535. headers: {
  536. 'Content-type': 'application/json',
  537. },
  538. body: bd
  539. }).then(() => {
  540. doQuery(JSON.stringify({
  541. content: $('#qryInput').val()
  542. }))
  543. })
  544. }
  545. function query() {
  546. if (modeq == 'query' || modeq == 'add') {
  547. var cont = getRegex();
  548. $('.ok').text(cont);
  549. var bd = JSON.stringify({
  550. content: cont,
  551. })
  552. doQuery(bd).then(res => {
  553. if (modeq == 'add') {
  554. if (nameq == 'eq') {
  555. $('#balInput').val($('#qryInput').val() ? $('#qryInput').val() : $('#qryInput').attr('placeholder').split('(')[0])
  556. setBal();
  557. balance().then(e => {
  558. if (e[0] == '!') return;
  559. input();
  560. if (!$('#addDescription').val()) {
  561. alert('无描述')
  562. return;
  563. }
  564. var resp = confirm(e + (res ? '有相似项,' : '') + '确认上传?')
  565. if (!resp) return
  566. $('#qryInput').val(e)
  567. var bd = JSON.stringify({
  568. content: $('#qryInput').val(),
  569. conditions: $('#addCondition').val(),
  570. descriptions: $('#addDescription').val(),
  571. })
  572. queryFetch(bd)
  573. })
  574. } else if (nameq == 'mo') {
  575. getClass()
  576. let fil = []
  577. for (j in curClass) {
  578. if (curClass[j].match(',')) {
  579. let sp = curClass[j].split(',')
  580. for (k = 0; k < sp.length; k++) {
  581. let g = {};
  582. g[j] = sp[k]
  583. if (sp[k]) fil.push(g)
  584. }
  585. } else {
  586. let g = {};
  587. g[j] = curClass[j]
  588. if (curClass[j]) fil.push(g)
  589. }
  590. }
  591. if (!$('#addTitle').val()) return alert('无中文名!')
  592. if (!checkIon() && !confirm('电荷总数不为零,确认继续?')) return
  593. var resp = confirm('确认上传?')
  594. if (!resp) return;
  595. var bd = JSON.stringify({
  596. content: $('#qryInput').val(),
  597. title: $('#addTitle').val(),
  598. descriptions: $('#addDescription').val(),
  599. class: JSON.stringify(fil),
  600. ions: JSON.stringify(ionList),
  601. })
  602. queryFetch(bd)
  603. } else if (nameq == 'io') {
  604. if (!$('#addTitle').val()) return alert('无中文名!')
  605. var resp = confirm('确认上传?')
  606. if (!resp) return;
  607. var bd = JSON.stringify({
  608. content: $('#qryInput').val(),
  609. title: $('#addTitle').val(),
  610. })
  611. queryFetch(bd)
  612. }
  613. }
  614. })
  615. }
  616. if (modeq == 'upd') {
  617. if (nameq == 'eq') {
  618. $('#balInput').val($('#qryInput').val() ? $('#qryInput').val() : $('#qryInput').attr('placeholder').split('(')[0])
  619. setBal();
  620. balance().then(e => {
  621. if (e[0] == '!') return
  622. input();
  623. if (!$('#addDescription').val()) {
  624. alert('无描述')
  625. return;
  626. }
  627. var resp = confirm(e + '确认上传?')
  628. if (!resp) return;
  629. $('#qryInput').val(e)
  630. var bd = JSON.stringify({
  631. content: $('#qryInput').val(),
  632. id: $('#addIdText').val(),
  633. conditions: $('#addCondition').val(),
  634. descriptions: $('#addDescription').val(),
  635. })
  636. console.log(bd)
  637. return fetch('/chem/upd/' + nameq, {
  638. method: 'POST',
  639. headers: {
  640. 'Content-type': 'application/json',
  641. },
  642. body: bd
  643. })
  644. }).then(inputId)
  645. } else if (nameq == 'mo') {
  646. getClass()
  647. let fil = []
  648. for (j in curClass) {
  649. if (curClass[j].match(',')) {
  650. let sp = curClass[j].split(',')
  651. for (k = 0; k < sp.length; k++) {
  652. let g = {};
  653. g[j] = sp[k]
  654. if (sp[k]) fil.push(g)
  655. }
  656. } else {
  657. let g = {};
  658. g[j] = curClass[j]
  659. if (curClass[j]) fil.push(g)
  660. }
  661. }
  662. if (!$('#addTitle').val()) return alert('无中文名!')
  663. if (!checkIon() && !confirm('电荷总数不为零,确认继续?')) return
  664. var resp = confirm('确认上传?')
  665. if (!resp) return;
  666. var bd = JSON.stringify({
  667. content: $('#qryInput').val(),
  668. title: $('#addTitle').val(),
  669. descriptions: $('#addDescription').val(),
  670. class: JSON.stringify(fil),
  671. ions: JSON.stringify(ionList),
  672. id: $('#addIdText').val()
  673. })
  674. queryFetch(bd)
  675. } else if (nameq == 'io') {
  676. if (!$('#addTitle').val()) return alert('无中文名!')
  677. var resp = confirm('确认上传?')
  678. if (!resp) return;
  679. var bd = JSON.stringify({
  680. content: $('#qryInput').val(),
  681. title: $('#addTitle').val(),
  682. id: $('#addIdText').val()
  683. })
  684. queryFetch(bd)
  685. }
  686. }
  687. }
  688. var curCount = {}, curClass = {}
  689. function getClass(force = 0) {
  690. let e = parseEquation($('#qryInput').val())
  691. if (!force) {
  692. for (let i in curCount) {
  693. curClass[i] = $('#class-' + i).val()
  694. }
  695. }
  696. $('#class').empty()
  697. if (e != curCount) {
  698. if (JSON.stringify(e) == '{}') $('#pclass').show()
  699. else $('#pclass').hide(300)
  700. for (let i in e) {
  701. $("#class").append(`<span class="input-group-addon">${i}</span><input id="class-${i}" type="text" class="form-control" autocomplete="off" placeholder="">`)
  702. $('#class-' + i).val(curClass[i])
  703. if (!curCount[i]) {
  704. $('#class-' + i).hide()
  705. $('#class-' + i).show(300)
  706. }
  707. }
  708. }
  709. curCount = e
  710. }
  711. var ionList = []
  712. function getIons() {
  713. $('.frame')[3].classList.add('active')
  714. $('.qry-group>label')[2].classList.add('active')
  715. getClass()
  716. let str = ''
  717. for (let i in curCount) {
  718. str += '|' + i
  719. }
  720. bd = JSON.stringify({ content: '^(' + str.slice(1) + ')(<|)' })
  721. nameq = 'io'
  722. doQuery(bd, '').then(() => {
  723. nameq = 'mo'
  724. $('#qryInputRender-io').append(' - 点击标签以添加')
  725. })
  726. }
  727. function updateIon() {
  728. let str = ''
  729. $('.ionList').empty()
  730. if (!ionList.length) return $('.ionList').append('...')
  731. for (let i = 0; i < ionList.length; i++) {
  732. 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>/`
  733. }
  734. str += ' 点击标签以减少'
  735. $('.ionList').append(str)
  736. if (preview) MathJax.typeset()
  737. }
  738. function addIon(id, v) {
  739. console.log(ionList)
  740. if (!ionList.filter(e => {
  741. if (e.id == id) e.c++, $('.count-ion-' + id).text(e.c + ' ')
  742. return e.id == id
  743. }).length) {
  744. $('.count-ion-' + id).text('1 ')
  745. ionList.push({ id: id, v: v, c: 1 })
  746. }
  747. updateIon()
  748. }
  749. function removeIon(id, v) {
  750. ionList = ionList.filter(e => {
  751. if (e.id == id) e.c--, $('.count-ion-' + id).text(e.c + ' ')
  752. return e.c
  753. })
  754. updateIon()
  755. }
  756. function checkIon() {
  757. let sum = 0
  758. for (let i in curCount) {
  759. if (curClass[i].match(',')) return true
  760. sum += curCount[i] * curClass[i]
  761. }
  762. console.log(sum)
  763. return sum == 0
  764. }
  765. function input2() {
  766. if ((modeq == 'add' || modeq == 'upd') && nameq == 'mo') getClass()
  767. if (modeq == 'query') {
  768. $('.ok').text(getRegex())
  769. }
  770. if ($('#qryInput').val() && $('#qryInput').val().match(/^\d+!?$/g)) {
  771. doQuery(JSON.stringify({ content: $('#qryInput').val().split('!')[0] }), 'id', 0)
  772. } else if ($('#qryInput').val().match('!')) {
  773. $('#qryInput').val($('#qryInput').val().split('!')[0])
  774. doQuery(JSON.stringify({ content: getRegex() }), '', 2)
  775. }
  776. if (nameq == 'eq') {
  777. if ($('#qryInputRender')[0]) {
  778. if (preview) {
  779. $('#qryInputRender').html(renderEquation(strict ? ($('#qryInput').val() + '=' + $('#qryInput2').val()) : ($('#qryInput').val())))
  780. } else $('#qryInputRender').text((strict ? ($('#qryInput').val() + '=' + $('#qryInput2').val()) : ($('#qryInput').val())))
  781. }
  782. } else {
  783. if ($('#qryInputRender-' + nameq)[0]) {
  784. if (preview) {
  785. $('#qryInputRender-' + nameq).html(renderEquation($('#qryInput').val()))
  786. } else $('#qryInputRender-' + nameq).text($('#qryInput').val())
  787. }
  788. }
  789. if (preview) MathJax.typeset()
  790. }
  791. function getC(str) {
  792. if (str == 'eq') return 1
  793. if (str == 'mo') return 2
  794. if (str == 'io') return 3
  795. if (str == 'el') return 4
  796. }
  797. function inputId() {
  798. var bd = JSON.stringify({
  799. content: $('#addIdText').val(),
  800. })
  801. if (!$('#addIdText').val()) {
  802. $('.frame')[getC(nameq)].innerHTML = '';
  803. return;
  804. }
  805. doQuery(bd, 'id')
  806. }
  807. function qryToggleMatch() {
  808. if (matchMode == 'mole') {
  809. $('#qryMatch').html('<span class="glyphicon glyphicon-cog"></span> 匹配元素')
  810. matchMode = 'elem'
  811. } else {
  812. $('#qryMatch').html('<span class="glyphicon glyphicon-cog"></span> 匹配分子')
  813. matchMode = 'mole'
  814. }
  815. }