script.js 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  1. /**
  2. * Main Application Script
  3. * Handles editor functionality, grammar checking, and template management
  4. * The 'templates' global variable is used by decoder.js module
  5. */
  6. // Global variables
  7. let currentTemplate = null;
  8. let currentConfigType = null;
  9. let templates = new Map(); // Used by decoder.js for template decoding
  10. // Initialize the application
  11. document.addEventListener('DOMContentLoaded', function() {
  12. const editor = document.getElementById('expressionEditor');
  13. const decodeTemplatesBtn = document.getElementById('decodeTemplates');
  14. const detectTemplatesBtn = document.getElementById('detectTemplates');
  15. const clearEditorBtn = document.getElementById('clearEditor');
  16. // Initialize navigation
  17. initializeNavigation();
  18. // Debounce timer for automatic grammar checking
  19. let grammarCheckTimer;
  20. // Update line numbers when content changes
  21. editor.addEventListener('input', function(e) {
  22. updateLineNumbers();
  23. updateSyntaxHighlight();
  24. // Handle auto-completion
  25. handleAutoComplete(e);
  26. // Clear previous timer
  27. clearTimeout(grammarCheckTimer);
  28. // Set new timer for automatic grammar check (300ms delay)
  29. grammarCheckTimer = setTimeout(function() {
  30. checkGrammar();
  31. detectTemplates();
  32. }, 300);
  33. });
  34. // Handle keydown events for Tab completion and other keys
  35. editor.addEventListener('keydown', function(e) {
  36. if (e.key === 'Tab') {
  37. e.preventDefault();
  38. handleTabCompletion();
  39. } else if (e.key === 'Escape') {
  40. // Allow users to dismiss the shadow suggestion
  41. hideShadowSuggestion();
  42. autoCompleteActive = false;
  43. }
  44. });
  45. editor.addEventListener('scroll', syncScroll);
  46. // Hide shadow suggestion when editor loses focus
  47. editor.addEventListener('blur', function() {
  48. hideShadowSuggestion();
  49. autoCompleteActive = false;
  50. });
  51. // Button event listeners
  52. decodeTemplatesBtn.addEventListener('click', decodeTemplates);
  53. clearEditorBtn.addEventListener('click', clearEditor);
  54. // Random iteration button
  55. const randomIterationBtn = document.getElementById('randomIterationBtn');
  56. if (randomIterationBtn) {
  57. randomIterationBtn.addEventListener('click', randomIteration);
  58. }
  59. // BRAIN connection button
  60. const connectToBrainBtn = document.getElementById('connectToBrain');
  61. connectToBrainBtn.addEventListener('click', openBrainLoginModal);
  62. // Simulator button
  63. const runSimulatorBtn = document.getElementById('runSimulator');
  64. if (runSimulatorBtn) {
  65. runSimulatorBtn.addEventListener('click', runSimulator);
  66. }
  67. // Results button listeners
  68. const copyDisplayedBtn = document.getElementById('copyDisplayedResults');
  69. const copyAllBtn = document.getElementById('copyAllResults');
  70. const downloadBtn = document.getElementById('downloadResults');
  71. const nextMoveBtn = document.getElementById('nextMoveBtn');
  72. if (copyDisplayedBtn) copyDisplayedBtn.addEventListener('click', copyDisplayedResults);
  73. if (copyAllBtn) copyAllBtn.addEventListener('click', copyAllResults);
  74. if (downloadBtn) downloadBtn.addEventListener('click', downloadResults);
  75. if (nextMoveBtn) nextMoveBtn.addEventListener('click', openSettingsModal);
  76. // Initialize line numbers and syntax highlighting
  77. updateLineNumbers();
  78. updateSyntaxHighlight();
  79. // Auto-detect templates and check grammar on load
  80. detectTemplates();
  81. checkGrammar();
  82. // Handle Enter key in variable input
  83. const variableInput = document.getElementById('variableInput');
  84. variableInput.addEventListener('keydown', function(event) {
  85. if (event.key === 'Enter' && !event.shiftKey) {
  86. event.preventDefault();
  87. applyTemplate();
  88. }
  89. });
  90. // Update line numbers on window resize
  91. window.addEventListener('resize', function() {
  92. updateLineNumbers();
  93. });
  94. // Load custom templates on startup
  95. loadCustomTemplates();
  96. });
  97. // Custom Templates Management (Server-side storage)
  98. // Load custom templates from server
  99. async function loadCustomTemplates() {
  100. try {
  101. const response = await fetch('/api/templates');
  102. const customTemplates = await response.json();
  103. const buttonsContainer = document.getElementById('customTemplateButtons');
  104. const noTemplatesInfo = document.getElementById('noCustomTemplates');
  105. if (!buttonsContainer) {
  106. console.error('customTemplateButtons container not found!');
  107. return;
  108. }
  109. buttonsContainer.innerHTML = '';
  110. if (!Array.isArray(customTemplates) || customTemplates.length === 0) {
  111. // Only show "no templates" message if we're viewing custom or all templates
  112. if (noTemplatesInfo && (currentTemplateView === 'all' || currentTemplateView === 'custom')) {
  113. noTemplatesInfo.style.display = 'block';
  114. }
  115. } else {
  116. if (noTemplatesInfo) {
  117. noTemplatesInfo.style.display = 'none';
  118. }
  119. customTemplates.forEach((template, index) => {
  120. const button = document.createElement('button');
  121. button.className = 'btn btn-template btn-template-custom';
  122. button.setAttribute('data-template-type', 'custom');
  123. button.innerHTML = `
  124. ${template.name}
  125. <span class="delete-btn" onclick="deleteCustomTemplate(${index}, event)" title="Delete template">×</span>
  126. `;
  127. button.onclick = () => loadCustomTemplate(index);
  128. button.title = template.description || 'Click to load this template';
  129. buttonsContainer.appendChild(button);
  130. });
  131. }
  132. } catch (error) {
  133. console.error('Error loading templates:', error);
  134. showNotification('Error loading templates', 'error');
  135. }
  136. }
  137. // Save current template
  138. function saveCurrentTemplate() {
  139. const editor = document.getElementById('expressionEditor');
  140. const expression = editor.value.trim();
  141. if (!expression) {
  142. showNotification('Please enter an expression before saving', 'error');
  143. return;
  144. }
  145. // Show save modal
  146. const modal = document.getElementById('saveTemplateModal');
  147. const preview = document.getElementById('templatePreview');
  148. const nameInput = document.getElementById('templateName');
  149. const descInput = document.getElementById('templateDescription');
  150. const configurationsInfo = document.getElementById('templateConfigurationsInfo');
  151. const configurationsList = document.getElementById('configurationsList');
  152. preview.textContent = expression;
  153. nameInput.value = '';
  154. descInput.value = '';
  155. // Check for configured templates and show info
  156. const configuredTemplates = [];
  157. templates.forEach((template, templateName) => {
  158. if (template.variables && template.variables.length > 0 && template.configType) {
  159. configuredTemplates.push({
  160. name: templateName,
  161. type: template.configType,
  162. count: template.variables.length
  163. });
  164. }
  165. });
  166. if (configuredTemplates.length > 0) {
  167. configurationsList.innerHTML = configuredTemplates.map(config =>
  168. `<li>&lt;${config.name}/&gt; - ${config.type} (${config.count} values)</li>`
  169. ).join('');
  170. configurationsInfo.style.display = 'block';
  171. } else {
  172. configurationsInfo.style.display = 'none';
  173. }
  174. modal.style.display = 'block';
  175. nameInput.focus();
  176. // Add Enter key support
  177. const handleEnter = (event) => {
  178. if (event.key === 'Enter' && !event.shiftKey) {
  179. event.preventDefault();
  180. confirmSaveTemplate();
  181. }
  182. };
  183. nameInput.addEventListener('keydown', handleEnter);
  184. descInput.addEventListener('keydown', handleEnter);
  185. // Clean up event listeners when modal closes
  186. modal.addEventListener('close', () => {
  187. nameInput.removeEventListener('keydown', handleEnter);
  188. descInput.removeEventListener('keydown', handleEnter);
  189. });
  190. }
  191. // Close save template modal
  192. function closeSaveTemplateModal() {
  193. const modal = document.getElementById('saveTemplateModal');
  194. modal.style.display = 'none';
  195. }
  196. // Overwrite existing template
  197. async function overwriteExistingTemplate() {
  198. const editor = document.getElementById('expressionEditor');
  199. const expression = editor.value.trim();
  200. if (!expression) {
  201. showNotification('Please enter an expression before overwriting a template', 'error');
  202. return;
  203. }
  204. // Check if there are any custom templates first
  205. try {
  206. const response = await fetch('/api/templates');
  207. const customTemplates = await response.json();
  208. if (!Array.isArray(customTemplates) || customTemplates.length === 0) {
  209. showNotification('No custom templates available to overwrite. Create a template first using "Save Current Template".', 'warning');
  210. return;
  211. }
  212. } catch (error) {
  213. console.error('Error checking templates:', error);
  214. showNotification('Error checking existing templates', 'error');
  215. return;
  216. }
  217. // Show overwrite modal
  218. const modal = document.getElementById('overwriteTemplateModal');
  219. const preview = document.getElementById('overwriteTemplatePreview');
  220. const templateSelect = document.getElementById('existingTemplateSelect');
  221. const confirmBtn = document.getElementById('overwriteConfirmBtn');
  222. const configurationsInfo = document.getElementById('overwriteConfigurationsInfo');
  223. const configurationsList = document.getElementById('overwriteConfigurationsList');
  224. preview.textContent = expression;
  225. // Reset UI
  226. templateSelect.value = '';
  227. confirmBtn.disabled = true;
  228. document.getElementById('selectedTemplateInfo').style.display = 'none';
  229. // Check for configured templates and show info
  230. const configuredTemplates = [];
  231. templates.forEach((template, templateName) => {
  232. if (template.variables && template.variables.length > 0 && template.configType) {
  233. configuredTemplates.push({
  234. name: templateName,
  235. type: template.configType,
  236. count: template.variables.length
  237. });
  238. }
  239. });
  240. if (configuredTemplates.length > 0) {
  241. configurationsList.innerHTML = configuredTemplates.map(config =>
  242. `<li>&lt;${config.name}/&gt; - ${config.type} (${config.count} values)</li>`
  243. ).join('');
  244. configurationsInfo.style.display = 'block';
  245. } else {
  246. configurationsInfo.style.display = 'none';
  247. }
  248. // Load existing templates for dropdown
  249. loadExistingTemplatesForOverwrite();
  250. // Add event listener for template selection
  251. templateSelect.onchange = handleTemplateSelectionForOverwrite;
  252. modal.style.display = 'block';
  253. }
  254. // Load existing templates for the overwrite dropdown
  255. async function loadExistingTemplatesForOverwrite() {
  256. try {
  257. const response = await fetch('/api/templates');
  258. const customTemplates = await response.json();
  259. const templateSelect = document.getElementById('existingTemplateSelect');
  260. // Clear existing options except the first one
  261. templateSelect.innerHTML = '<option value="">Select a template...</option>';
  262. if (Array.isArray(customTemplates) && customTemplates.length > 0) {
  263. customTemplates.forEach((template, index) => {
  264. const option = document.createElement('option');
  265. option.value = index;
  266. option.textContent = template.name;
  267. option.dataset.description = template.description || '';
  268. templateSelect.appendChild(option);
  269. });
  270. } else {
  271. const option = document.createElement('option');
  272. option.textContent = 'No custom templates available';
  273. option.disabled = true;
  274. templateSelect.appendChild(option);
  275. }
  276. } catch (error) {
  277. console.error('Error loading templates for overwrite:', error);
  278. showNotification('Error loading templates', 'error');
  279. }
  280. }
  281. // Handle template selection for overwrite
  282. function handleTemplateSelectionForOverwrite() {
  283. const templateSelect = document.getElementById('existingTemplateSelect');
  284. const selectedTemplateInfo = document.getElementById('selectedTemplateInfo');
  285. const currentTemplateDescription = document.getElementById('currentTemplateDescription');
  286. const confirmBtn = document.getElementById('overwriteConfirmBtn');
  287. if (templateSelect.value === '') {
  288. selectedTemplateInfo.style.display = 'none';
  289. confirmBtn.disabled = true;
  290. return;
  291. }
  292. // Show selected template info
  293. const selectedOption = templateSelect.options[templateSelect.selectedIndex];
  294. const description = selectedOption.dataset.description || 'No description';
  295. currentTemplateDescription.textContent = description;
  296. selectedTemplateInfo.style.display = 'block';
  297. confirmBtn.disabled = false;
  298. }
  299. // Close overwrite template modal
  300. function closeOverwriteTemplateModal() {
  301. const modal = document.getElementById('overwriteTemplateModal');
  302. modal.style.display = 'none';
  303. }
  304. // Confirm and overwrite template
  305. async function confirmOverwriteTemplate() {
  306. const templateSelect = document.getElementById('existingTemplateSelect');
  307. const editor = document.getElementById('expressionEditor');
  308. if (templateSelect.value === '') {
  309. showNotification('Please select a template to overwrite', 'error');
  310. return;
  311. }
  312. const selectedIndex = parseInt(templateSelect.value);
  313. const selectedTemplateName = templateSelect.options[templateSelect.selectedIndex].textContent;
  314. // Confirm the overwrite action
  315. if (!confirm(`Are you sure you want to overwrite the template "${selectedTemplateName}"? This action cannot be undone.`)) {
  316. return;
  317. }
  318. const expression = editor.value.trim();
  319. // Capture current template configurations
  320. const templateConfigurations = {};
  321. templates.forEach((template, templateName) => {
  322. if (template.variables && template.variables.length > 0 && template.configType) {
  323. templateConfigurations[templateName] = {
  324. variables: template.variables,
  325. configType: template.configType
  326. };
  327. }
  328. });
  329. try {
  330. // First get the existing template to preserve its name and original creation date
  331. const response = await fetch('/api/templates');
  332. const customTemplates = await response.json();
  333. if (!Array.isArray(customTemplates) || selectedIndex >= customTemplates.length) {
  334. showNotification('Selected template not found', 'error');
  335. return;
  336. }
  337. const existingTemplate = customTemplates[selectedIndex];
  338. // Update the template with new expression and configurations
  339. const updateResponse = await fetch('/api/templates', {
  340. method: 'POST',
  341. headers: {
  342. 'Content-Type': 'application/json'
  343. },
  344. body: JSON.stringify({
  345. name: existingTemplate.name, // Keep the original name
  346. description: existingTemplate.description, // Keep the original description
  347. expression: expression,
  348. templateConfigurations: templateConfigurations
  349. })
  350. });
  351. const result = await updateResponse.json();
  352. if (result.success) {
  353. // Close modal and reload templates
  354. closeOverwriteTemplateModal();
  355. loadCustomTemplates();
  356. showNotification(`Template "${existingTemplate.name}" overwritten successfully`, 'success');
  357. } else {
  358. showNotification(result.error || 'Error overwriting template', 'error');
  359. }
  360. } catch (error) {
  361. console.error('Error overwriting template:', error);
  362. showNotification('Error overwriting template', 'error');
  363. }
  364. }
  365. // Confirm and save template
  366. async function confirmSaveTemplate() {
  367. const nameInput = document.getElementById('templateName');
  368. const descInput = document.getElementById('templateDescription');
  369. const editor = document.getElementById('expressionEditor');
  370. const name = nameInput.value.trim();
  371. const description = descInput.value.trim();
  372. const expression = editor.value.trim();
  373. if (!name) {
  374. showNotification('Please enter a name for the template', 'error');
  375. nameInput.focus();
  376. return;
  377. }
  378. // Capture current template configurations
  379. const templateConfigurations = {};
  380. templates.forEach((template, templateName) => {
  381. if (template.variables && template.variables.length > 0 && template.configType) {
  382. templateConfigurations[templateName] = {
  383. variables: template.variables,
  384. configType: template.configType
  385. };
  386. }
  387. });
  388. try {
  389. const response = await fetch('/api/templates', {
  390. method: 'POST',
  391. headers: {
  392. 'Content-Type': 'application/json'
  393. },
  394. body: JSON.stringify({
  395. name: name,
  396. description: description,
  397. expression: expression,
  398. templateConfigurations: templateConfigurations
  399. })
  400. });
  401. const result = await response.json();
  402. if (result.success) {
  403. // Close modal and reload templates
  404. closeSaveTemplateModal();
  405. loadCustomTemplates();
  406. showNotification(result.message, 'success');
  407. } else {
  408. showNotification(result.error || 'Error saving template', 'error');
  409. }
  410. } catch (error) {
  411. console.error('Error saving template:', error);
  412. showNotification('Error saving template', 'error');
  413. }
  414. }
  415. // Load a custom template
  416. async function loadCustomTemplate(index) {
  417. try {
  418. const response = await fetch('/api/templates');
  419. const customTemplates = await response.json();
  420. if (Array.isArray(customTemplates) && index >= 0 && index < customTemplates.length) {
  421. const template = customTemplates[index];
  422. const editor = document.getElementById('expressionEditor');
  423. editor.value = template.expression;
  424. updateLineNumbers();
  425. updateSyntaxHighlight();
  426. checkGrammar();
  427. detectTemplates();
  428. // Restore template configurations if they exist
  429. if (template.templateConfigurations) {
  430. setTimeout(() => {
  431. Object.entries(template.templateConfigurations).forEach(([templateName, config]) => {
  432. if (templates.has(templateName) && config.variables && config.configType) {
  433. const templateObj = templates.get(templateName);
  434. templateObj.variables = config.variables;
  435. templateObj.configType = config.configType;
  436. // Update visual state
  437. if (templateObj.element) {
  438. templateObj.element.className = 'template-item configured';
  439. }
  440. updateTemplateCount(templateName);
  441. }
  442. });
  443. // Update the overall template status
  444. updateTemplateStatus();
  445. }, 100); // Small delay to ensure templates are detected first
  446. }
  447. showNotification(`Loaded template: ${template.name}`, 'success');
  448. }
  449. } catch (error) {
  450. console.error('Error loading template:', error);
  451. showNotification('Error loading template', 'error');
  452. }
  453. }
  454. // Delete a custom template
  455. async function deleteCustomTemplate(index, event) {
  456. event.stopPropagation(); // Prevent button click from triggering
  457. try {
  458. const response = await fetch('/api/templates');
  459. const customTemplates = await response.json();
  460. if (Array.isArray(customTemplates) && index >= 0 && index < customTemplates.length) {
  461. const template = customTemplates[index];
  462. if (confirm(`Are you sure you want to delete the template "${template.name}"?`)) {
  463. const deleteResponse = await fetch(`/api/templates/${index}`, {
  464. method: 'DELETE'
  465. });
  466. const result = await deleteResponse.json();
  467. if (result.success) {
  468. loadCustomTemplates();
  469. showNotification(result.message, 'info');
  470. } else {
  471. showNotification(result.error || 'Error deleting template', 'error');
  472. }
  473. }
  474. }
  475. } catch (error) {
  476. console.error('Error deleting template:', error);
  477. showNotification('Error deleting template', 'error');
  478. }
  479. }
  480. // Export custom templates to JSON file
  481. async function exportCustomTemplates() {
  482. try {
  483. const response = await fetch('/api/templates/export');
  484. const customTemplates = await response.json();
  485. if (!Array.isArray(customTemplates) || customTemplates.length === 0) {
  486. showNotification('No custom templates to export', 'warning');
  487. return;
  488. }
  489. const dataStr = JSON.stringify(customTemplates, null, 2);
  490. const dataBlob = new Blob([dataStr], { type: 'application/json' });
  491. const link = document.createElement('a');
  492. link.href = URL.createObjectURL(dataBlob);
  493. link.download = `brain_custom_templates_${new Date().toISOString().slice(0, 10)}.json`;
  494. document.body.appendChild(link);
  495. link.click();
  496. document.body.removeChild(link);
  497. showNotification(`Exported ${customTemplates.length} template${customTemplates.length > 1 ? 's' : ''}`, 'success');
  498. } catch (error) {
  499. console.error('Error exporting templates:', error);
  500. showNotification('Error exporting templates', 'error');
  501. }
  502. }
  503. // Import custom templates from JSON file
  504. function importCustomTemplates(event) {
  505. const file = event.target.files[0];
  506. if (!file) return;
  507. const reader = new FileReader();
  508. reader.onload = async function(e) {
  509. try {
  510. const importedTemplates = JSON.parse(e.target.result);
  511. if (!Array.isArray(importedTemplates)) {
  512. throw new Error('Invalid template file format');
  513. }
  514. // Validate template structure
  515. const validTemplates = importedTemplates.filter(t =>
  516. t.name && typeof t.name === 'string' &&
  517. t.expression && typeof t.expression === 'string'
  518. );
  519. if (validTemplates.length === 0) {
  520. throw new Error('No valid templates found in file');
  521. }
  522. // Get existing templates to check for duplicates
  523. const response = await fetch('/api/templates');
  524. const existingTemplates = await response.json();
  525. // Check for duplicates
  526. const duplicates = validTemplates.filter(imported =>
  527. Array.isArray(existingTemplates) && existingTemplates.some(existing => existing.name === imported.name)
  528. );
  529. let overwrite = false;
  530. if (duplicates.length > 0) {
  531. const duplicateNames = duplicates.map(t => t.name).join(', ');
  532. overwrite = confirm(`The following templates already exist: ${duplicateNames}\n\nDo you want to overwrite them?`);
  533. if (!overwrite) {
  534. // Filter out duplicates if user doesn't want to overwrite
  535. const nonDuplicates = validTemplates.filter(imported =>
  536. !Array.isArray(existingTemplates) || !existingTemplates.some(existing => existing.name === imported.name)
  537. );
  538. if (nonDuplicates.length === 0) {
  539. showNotification('Import cancelled - all templates already exist', 'info');
  540. event.target.value = ''; // Reset file input
  541. return;
  542. }
  543. }
  544. }
  545. // Import templates
  546. const importResponse = await fetch('/api/templates/import', {
  547. method: 'POST',
  548. headers: {
  549. 'Content-Type': 'application/json'
  550. },
  551. body: JSON.stringify({
  552. templates: validTemplates,
  553. overwrite: overwrite
  554. })
  555. });
  556. const result = await importResponse.json();
  557. if (result.success) {
  558. loadCustomTemplates();
  559. let message = `Imported ${result.imported} new template${result.imported !== 1 ? 's' : ''}`;
  560. if (result.overwritten > 0) {
  561. message += `, overwritten ${result.overwritten}`;
  562. }
  563. showNotification(message, 'success');
  564. } else {
  565. showNotification(result.error || 'Import failed', 'error');
  566. }
  567. } catch (error) {
  568. showNotification(`Import failed: ${error.message}`, 'error');
  569. }
  570. event.target.value = ''; // Reset file input
  571. };
  572. reader.readAsText(file);
  573. }
  574. // Run simulator script
  575. function runSimulator() {
  576. // Show modal with two options
  577. showSimulatorOptionsModal();
  578. }
  579. function showSimulatorOptionsModal() {
  580. // Create modal HTML if it doesn't exist
  581. let modal = document.getElementById('simulatorOptionsModal');
  582. if (!modal) {
  583. modal = document.createElement('div');
  584. modal.id = 'simulatorOptionsModal';
  585. modal.className = 'modal';
  586. modal.innerHTML = `
  587. <div class="modal-content" style="max-width: 600px;">
  588. <div class="modal-header">
  589. <h3>🚀 Run Simulator</h3>
  590. <span class="close" onclick="closeSimulatorOptionsModal()">&times;</span>
  591. </div>
  592. <div class="modal-body">
  593. <p style="margin-bottom: 20px;">选择您想要运行 BRAIN Alpha 模拟器的方式:</p>
  594. <div class="simulator-options">
  595. <div class="simulator-option" onclick="runTraditionalSimulator()">
  596. <div class="option-icon">⚙️</div>
  597. <div class="option-content">
  598. <h4>命令行界面</h4>
  599. <p>传统的交互式命令行界面,带有逐步提示。</p>
  600. <ul>
  601. <li>交互式参数输入</li>
  602. <li>逐步配置</li>
  603. <li>适合熟悉命令行的高级用户</li>
  604. </ul>
  605. </div>
  606. </div>
  607. <div class="simulator-option" onclick="runWebSimulator()">
  608. <div class="option-icon">🌐</div>
  609. <div class="option-content">
  610. <h4>Web 界面</h4>
  611. <p>用户友好的 Web 表单,所有参数集中在一个页面。</p>
  612. <ul>
  613. <li>所有参数在一个表单中</li>
  614. <li>实时日志监控</li>
  615. <li>可视化进度跟踪</li>
  616. <li>对初学者友好的界面</li>
  617. </ul>
  618. </div>
  619. </div>
  620. </div>
  621. </div>
  622. </div>
  623. `;
  624. document.body.appendChild(modal);
  625. }
  626. modal.style.display = 'block';
  627. }
  628. function closeSimulatorOptionsModal() {
  629. const modal = document.getElementById('simulatorOptionsModal');
  630. if (modal) {
  631. modal.style.display = 'none';
  632. }
  633. }
  634. async function runTraditionalSimulator() {
  635. closeSimulatorOptionsModal();
  636. try {
  637. const response = await fetch('/api/run-simulator', {
  638. method: 'POST',
  639. headers: {
  640. 'Content-Type': 'application/json'
  641. }
  642. });
  643. const result = await response.json();
  644. if (result.success) {
  645. showNotification(result.message, 'success');
  646. } else {
  647. showNotification(result.error || 'Failed to run simulator', 'error');
  648. }
  649. } catch (error) {
  650. console.error('Error running simulator:', error);
  651. showNotification('Error running simulator', 'error');
  652. }
  653. }
  654. function runWebSimulator() {
  655. closeSimulatorOptionsModal();
  656. // Navigate to the new simulator page
  657. window.location.href = '/simulator';
  658. }
  659. // Make functions globally accessible
  660. window.saveCurrentTemplate = saveCurrentTemplate;
  661. window.closeSaveTemplateModal = closeSaveTemplateModal;
  662. window.confirmSaveTemplate = confirmSaveTemplate;
  663. window.overwriteExistingTemplate = overwriteExistingTemplate;
  664. window.closeOverwriteTemplateModal = closeOverwriteTemplateModal;
  665. window.confirmOverwriteTemplate = confirmOverwriteTemplate;
  666. window.loadCustomTemplate = loadCustomTemplate;
  667. window.deleteCustomTemplate = deleteCustomTemplate;
  668. window.exportCustomTemplates = exportCustomTemplates;
  669. window.importCustomTemplates = importCustomTemplates;
  670. window.runSimulator = runSimulator;
  671. window.showSimulatorOptionsModal = showSimulatorOptionsModal;
  672. window.closeSimulatorOptionsModal = closeSimulatorOptionsModal;
  673. window.runTraditionalSimulator = runTraditionalSimulator;
  674. window.runWebSimulator = runWebSimulator;
  675. // Template View Toggle Functionality
  676. let currentTemplateView = 'all'; // 'all', 'custom', 'example'
  677. function toggleTemplateView() {
  678. const toggleBtn = document.getElementById('toggleTemplateView');
  679. const toggleText = document.getElementById('toggleTemplateViewText');
  680. const exampleTemplates = document.getElementById('exampleTemplateButtons');
  681. const customTemplates = document.getElementById('customTemplateButtons');
  682. const noTemplatesInfo = document.getElementById('noCustomTemplates');
  683. // Cycle through views: all -> custom -> example -> all
  684. if (currentTemplateView === 'all') {
  685. currentTemplateView = 'custom';
  686. toggleText.textContent = 'Show Examples Only';
  687. exampleTemplates.style.display = 'none';
  688. customTemplates.style.display = 'block';
  689. // Check if there are custom templates
  690. if (customTemplates.children.length === 0 && noTemplatesInfo) {
  691. noTemplatesInfo.style.display = 'block';
  692. }
  693. } else if (currentTemplateView === 'custom') {
  694. currentTemplateView = 'example';
  695. toggleText.textContent = 'Show All Templates';
  696. exampleTemplates.style.display = 'block';
  697. customTemplates.style.display = 'none';
  698. if (noTemplatesInfo) {
  699. noTemplatesInfo.style.display = 'none';
  700. }
  701. } else {
  702. currentTemplateView = 'all';
  703. toggleText.textContent = 'Show Custom Only';
  704. exampleTemplates.style.display = 'block';
  705. customTemplates.style.display = 'block';
  706. // Show no templates info only if in all view and no custom templates
  707. if (customTemplates.children.length === 0 && noTemplatesInfo) {
  708. noTemplatesInfo.style.display = 'block';
  709. } else if (noTemplatesInfo) {
  710. noTemplatesInfo.style.display = 'none';
  711. }
  712. }
  713. }
  714. // Make toggleTemplateView globally accessible
  715. window.toggleTemplateView = toggleTemplateView;
  716. // Load template examples
  717. function loadTemplateExample(exampleNumber) {
  718. const editor = document.getElementById('expressionEditor');
  719. const examples = {
  720. 1: `to_nan(
  721. group_normalize(
  722. group_neutralize(
  723. group_rank(
  724. ts_rank(
  725. ts_decay_linear(
  726. ts_returns(
  727. ts_backfill(<data_field/>, <backfill_days/>)/<secondary_data_field/>, <returns_window/>
  728. ), <decay_window/>
  729. ), <rank_window/>
  730. ), <group/>
  731. ), <group/>
  732. ), <market/>
  733. ), value=<nan_value/>, reverse=<reverse_bool/>
  734. )`,
  735. 2: `ts_decay_exp_window(
  736. ts_max(
  737. vec_avg(<model_field/>), <max_window/>
  738. ), <decay_window/>
  739. )`,
  740. 3: `financial_data = ts_backfill(vec_func(<analyst_metric/>), <backfill_days/>);
  741. gp = group_cartesian_product(<group1/>, <group2/>);
  742. data = <ts_operator/>(
  743. <group_operator/>(financial_data, gp), <window/>
  744. )`,
  745. 4: `alpha = <cross_sectional_transform/>(
  746. <time_series_transform/>(<feature/>, <ts_window/>), <group/>
  747. );
  748. alpha_gpm = group_mean(alpha, <weight/>, <group/>);
  749. resid = <neutralization_func/>(alpha, alpha_gpm);
  750. final_signal = <time_series_transform2/>(
  751. group_neutralize(resid, <group2/>), <final_window/>
  752. )`,
  753. 5: `alpha = group_zscore(
  754. ts_zscore(
  755. ts_backfill(vec_avg(<analyst_field/>), <backfill_days/>), <zscore_window/>
  756. ), <exchange/>
  757. );
  758. alpha_gpm = group_mean(alpha, <cap_weight/>, <country/>);
  759. resid = subtract(alpha, alpha_gpm);
  760. ts_mean(group_neutralize(resid, <market/>), <mean_window/>)`,
  761. 6: `data = ts_backfill(
  762. winsorize(vec_avg(<analyst_field/>), std=<std_value/>), <backfill_days/>
  763. );
  764. t_data = normalize(data);
  765. gp = group_cartesian_product(<market/>, <country/>);
  766. signal = group_normalize(ts_zscore(t_data, <zscore_window/>), gp);
  767. gpm = group_mean(signal, 1, gp);
  768. gpm_signal = subtract(signal, gpm);
  769. opt = group_neutralize(
  770. arc_tan(ts_decay_exp_window(gpm_signal, <decay_window/>)), gp
  771. );
  772. ts_target_tvr_delta_limit(opt, ts_std_dev(opt, <std_window/>), target_tvr=<tvr_value/>)`,
  773. 7: `group = <industry/>;
  774. data = ts_min_max_cps(
  775. group_zscore(
  776. ts_backfill(vec_min(<model_field/>), <backfill_days/>), group
  777. ), <minmax_window/>
  778. );
  779. ts_data = ts_median(data, <median_window/>);
  780. ts_target_tvr_hump(
  781. group_neutralize(subtract(data, ts_data), group), target_tvr=<tvr_value/>
  782. )`
  783. };
  784. if (examples[exampleNumber]) {
  785. editor.value = examples[exampleNumber];
  786. updateLineNumbers();
  787. updateSyntaxHighlight();
  788. checkGrammar();
  789. detectTemplates();
  790. // Show a notification
  791. showNotification(`Loaded template example ${exampleNumber}`, 'success');
  792. }
  793. }
  794. // Show notification
  795. function showNotification(message, type = 'info') {
  796. // Create notification element
  797. const notification = document.createElement('div');
  798. notification.className = `notification ${type}`;
  799. notification.textContent = message;
  800. notification.style.cssText = `
  801. position: fixed;
  802. top: 20px;
  803. right: 20px;
  804. padding: 12px 20px;
  805. background: ${type === 'success' ? '#48bb78' : '#667eea'};
  806. color: white;
  807. border-radius: 6px;
  808. box-shadow: 0 2px 10px rgba(0,0,0,0.2);
  809. z-index: 10000;
  810. animation: slideIn 0.3s ease;
  811. `;
  812. document.body.appendChild(notification);
  813. // Remove after 3 seconds
  814. setTimeout(() => {
  815. notification.style.animation = 'fadeOut 0.3s ease';
  816. setTimeout(() => {
  817. document.body.removeChild(notification);
  818. }, 300);
  819. }, 3000);
  820. }
  821. // Make loadTemplateExample globally accessible
  822. window.loadTemplateExample = loadTemplateExample;
  823. // Initialize navigation system
  824. function initializeNavigation() {
  825. const navTabs = document.querySelectorAll('.nav-tab');
  826. navTabs.forEach(tab => {
  827. tab.addEventListener('click', function() {
  828. const targetPage = this.getAttribute('data-page');
  829. navigateToPage(targetPage);
  830. });
  831. });
  832. }
  833. // Navigate to a specific page
  834. function navigateToPage(pageName) {
  835. // Update nav tabs
  836. const navTabs = document.querySelectorAll('.nav-tab');
  837. navTabs.forEach(tab => {
  838. if (tab.getAttribute('data-page') === pageName) {
  839. tab.classList.add('active');
  840. } else {
  841. tab.classList.remove('active');
  842. }
  843. });
  844. // Update page content
  845. const pages = document.querySelectorAll('.page-content');
  846. pages.forEach(page => {
  847. if (page.id === pageName + 'Page') {
  848. page.classList.add('active');
  849. } else {
  850. page.classList.remove('active');
  851. }
  852. });
  853. // Update template status when navigating to decode page
  854. if (pageName === 'decode') {
  855. updateTemplateStatus();
  856. }
  857. }
  858. // Update template status on decode page
  859. function updateTemplateStatus() {
  860. const statusDiv = document.getElementById('templateStatus');
  861. const decodeHeading = document.querySelector('#decodePage h2');
  862. const totalTemplates = templates.size;
  863. const configuredTemplates = Array.from(templates.values()).filter(t => t.variables.length > 0).length;
  864. // Reset heading to default
  865. decodeHeading.textContent = 'Template Decoding Options';
  866. if (totalTemplates === 0) {
  867. statusDiv.innerHTML = `
  868. <div class="info-message">
  869. No templates detected in your expression.
  870. <button class="btn btn-secondary btn-small" onclick="navigateToPage('editor')">Go back to editor</button>
  871. </div>
  872. `;
  873. } else if (configuredTemplates === 0) {
  874. statusDiv.innerHTML = `
  875. <div class="warning-message">
  876. <strong>⚠️ No templates configured yet!</strong><br>
  877. You have ${totalTemplates} variable${totalTemplates > 1 ? 's' : ''} in your expression, but none are configured.<br>
  878. <button class="btn btn-secondary btn-small" onclick="navigateToPage('editor')">Configure templates</button>
  879. </div>
  880. `;
  881. } else if (configuredTemplates < totalTemplates) {
  882. statusDiv.innerHTML = `
  883. <div class="warning-message">
  884. <strong>⚠️ Some templates not configured!</strong><br>
  885. ${configuredTemplates} out of ${totalTemplates} templates are configured.<br>
  886. <button class="btn btn-secondary btn-small" onclick="navigateToPage('editor')">Configure remaining templates</button>
  887. </div>
  888. `;
  889. } else {
  890. // All templates configured - calculate search space
  891. let searchSpace = [];
  892. let totalCombinations = 1;
  893. templates.forEach((template, name) => {
  894. if (template.variables.length > 0) {
  895. searchSpace.push(template.variables.length);
  896. totalCombinations *= template.variables.length;
  897. }
  898. });
  899. // Update heading with search space
  900. const searchSpaceStr = searchSpace.join(' × ');
  901. decodeHeading.innerHTML = `Template Decoding Options <span class="search-space">(SearchSpace: ${searchSpaceStr} = ${totalCombinations.toLocaleString()})</span>`;
  902. let configDetails = '<ul style="margin: 10px 0; padding-left: 20px;">';
  903. templates.forEach((template, name) => {
  904. if (template.variables.length > 0) {
  905. configDetails += `<li><strong>&lt;${name}/&gt;</strong>: ${template.variables.length} ${template.configType || 'values'}</li>`;
  906. }
  907. });
  908. configDetails += '</ul>';
  909. statusDiv.innerHTML = `
  910. <div class="success-message">
  911. <strong>✓ All templates configured!</strong><br>
  912. ${configDetails}
  913. Ready to decode your expressions.
  914. </div>
  915. `;
  916. }
  917. }
  918. // Make navigateToPage globally accessible
  919. window.navigateToPage = navigateToPage;
  920. // Update line numbers in the editor
  921. function updateLineNumbers() {
  922. const editor = document.getElementById('expressionEditor');
  923. const lineNumbers = document.getElementById('lineNumbers');
  924. const lines = editor.value.split('\n');
  925. // Calculate how many lines we need based on editor height
  926. const editorHeight = editor.offsetHeight || 500;
  927. const lineHeight = 25.6; // 16px font-size * 1.6 line-height
  928. const visibleLines = Math.ceil(editorHeight / lineHeight);
  929. const totalLines = Math.max(lines.length, visibleLines);
  930. // Build line numbers text
  931. let lineNumbersText = '';
  932. for (let i = 1; i <= totalLines; i++) {
  933. lineNumbersText += i + '\n';
  934. }
  935. // Remove trailing newline for better alignment
  936. lineNumbers.textContent = lineNumbersText.trimEnd();
  937. }
  938. // Sync scroll between editor and line numbers
  939. function syncScroll() {
  940. const editor = document.getElementById('expressionEditor');
  941. const lineNumbers = document.getElementById('lineNumbers');
  942. const highlightedText = document.getElementById('highlightedText');
  943. lineNumbers.scrollTop = editor.scrollTop;
  944. highlightedText.scrollTop = editor.scrollTop;
  945. highlightedText.scrollLeft = editor.scrollLeft;
  946. // Hide shadow suggestion when scrolling
  947. hideShadowSuggestion();
  948. }
  949. // Update syntax highlighting
  950. function updateSyntaxHighlight() {
  951. const editor = document.getElementById('expressionEditor');
  952. const highlightedText = document.getElementById('highlightedText');
  953. const text = editor.value;
  954. // Escape HTML special characters
  955. let escapedText = text
  956. .replace(/&/g, '&amp;')
  957. .replace(/</g, '&lt;')
  958. .replace(/>/g, '&gt;')
  959. .replace(/"/g, '&quot;')
  960. .replace(/'/g, '&#039;');
  961. // Highlight template tags
  962. escapedText = escapedText.replace(/(&lt;)(\/?)(\w+)(\/&gt;)/g, function(match, open, slash, tagName, close) {
  963. return `<span class="template-brackets">${open}</span>` +
  964. `<span class="template-brackets">${slash}</span>` +
  965. `<span class="template-tag">${tagName}</span>` +
  966. `<span class="template-brackets">${close}</span>`;
  967. });
  968. highlightedText.innerHTML = escapedText;
  969. }
  970. // Grammar checking function
  971. function checkGrammar() {
  972. const editor = document.getElementById('expressionEditor');
  973. const content = editor.value;
  974. const errorsDiv = document.getElementById('grammarErrors');
  975. const errors = [];
  976. // Clear previous errors
  977. errorsDiv.innerHTML = '';
  978. // Check for unclosed block comments
  979. const commentStart = content.match(/\/\*/g) || [];
  980. const commentEnd = content.match(/\*\//g) || [];
  981. if (commentStart.length !== commentEnd.length) {
  982. errors.push({
  983. type: 'error',
  984. message: 'Unclosed block comment detected. Each /* must have a matching */'
  985. });
  986. }
  987. // Remove comments for statement detection
  988. let contentWithoutComments = content.replace(/\/\*[\s\S]*?\*\//g, '').trim();
  989. // Check if content is empty after removing comments
  990. if (!contentWithoutComments) {
  991. errorsDiv.innerHTML = '<div class="info-message">Enter an expression to check grammar</div>';
  992. return;
  993. }
  994. // Detect statements by looking for assignment patterns (variable = expression)
  995. // or by semicolons
  996. const lines = contentWithoutComments.split('\n');
  997. let statements = [];
  998. let currentStatement = '';
  999. let statementStartLine = 0;
  1000. let openParens = 0;
  1001. let openBrackets = 0;
  1002. let inStatement = false;
  1003. for (let i = 0; i < lines.length; i++) {
  1004. const line = lines[i];
  1005. const trimmedLine = line.trim();
  1006. // Skip empty lines
  1007. if (trimmedLine === '') {
  1008. if (currentStatement.trim()) {
  1009. currentStatement += '\n';
  1010. }
  1011. continue;
  1012. }
  1013. // Track parentheses and brackets to handle multi-line expressions
  1014. for (let char of trimmedLine) {
  1015. if (char === '(') openParens++;
  1016. else if (char === ')') openParens--;
  1017. else if (char === '[') openBrackets++;
  1018. else if (char === ']') openBrackets--;
  1019. }
  1020. currentStatement += (currentStatement ? '\n' : '') + line;
  1021. // Check if this line starts a new statement (has assignment operator)
  1022. if (!inStatement && trimmedLine.match(/^\w+\s*=/)) {
  1023. inStatement = true;
  1024. statementStartLine = i;
  1025. }
  1026. // Check if statement is complete
  1027. if (trimmedLine.endsWith(';') ||
  1028. (i === lines.length - 1) || // Last line
  1029. (i < lines.length - 1 && lines[i + 1].trim().match(/^\w+\s*=/))) { // Next line starts new assignment
  1030. // Statement is complete
  1031. if (currentStatement.trim()) {
  1032. statements.push({
  1033. text: currentStatement.trim(),
  1034. startLine: statementStartLine,
  1035. endLine: i,
  1036. hasSemicolon: trimmedLine.endsWith(';'),
  1037. isLastStatement: i === lines.length - 1 || (i < lines.length - 1 && !lines.slice(i + 1).some(l => l.trim()))
  1038. });
  1039. }
  1040. currentStatement = '';
  1041. inStatement = false;
  1042. openParens = 0;
  1043. openBrackets = 0;
  1044. }
  1045. }
  1046. // Validate statements
  1047. if (statements.length === 0) {
  1048. // Single expression without assignment
  1049. const hasSemicolon = contentWithoutComments.trim().endsWith(';');
  1050. if (hasSemicolon) {
  1051. errors.push({
  1052. type: 'warning',
  1053. message: 'Single expression (Alpha expression) should not end with a semicolon'
  1054. });
  1055. }
  1056. // Check if single expression is a variable assignment
  1057. const assignmentPattern = /^\s*\w+\s*=\s*[\s\S]*$/;
  1058. if (assignmentPattern.test(contentWithoutComments)) {
  1059. errors.push({
  1060. type: 'error',
  1061. message: 'The Alpha expression (final result) cannot be assigned to a variable. Remove the variable assignment.'
  1062. });
  1063. }
  1064. } else if (statements.length === 1) {
  1065. // Single statement
  1066. if (statements[0].hasSemicolon && statements[0].isLastStatement) {
  1067. errors.push({
  1068. type: 'warning',
  1069. message: 'The last statement (Alpha expression) should not end with a semicolon'
  1070. });
  1071. }
  1072. // Check if single statement is a variable assignment
  1073. const assignmentPattern = /^\s*\w+\s*=\s*[\s\S]*$/;
  1074. if (assignmentPattern.test(statements[0].text)) {
  1075. errors.push({
  1076. type: 'error',
  1077. message: 'The Alpha expression (final result) cannot be assigned to a variable. Remove the variable assignment.'
  1078. });
  1079. }
  1080. } else {
  1081. // Multiple statements
  1082. for (let i = 0; i < statements.length; i++) {
  1083. const stmt = statements[i];
  1084. if (i < statements.length - 1 && !stmt.hasSemicolon) {
  1085. // Not the last statement and missing semicolon
  1086. errors.push({
  1087. type: 'error',
  1088. line: stmt.endLine + 1,
  1089. message: `Line ${stmt.endLine + 1}: Missing semicolon at the end of the statement`
  1090. });
  1091. } else if (i === statements.length - 1 && stmt.hasSemicolon) {
  1092. // Last statement with semicolon
  1093. errors.push({
  1094. type: 'warning',
  1095. line: stmt.endLine + 1,
  1096. message: `Line ${stmt.endLine + 1}: The last statement (Alpha expression) should not end with a semicolon`
  1097. });
  1098. }
  1099. // Check if last statement is a variable assignment
  1100. if (i === statements.length - 1) {
  1101. const assignmentPattern = /^\s*\w+\s*=\s*[\s\S]*$/;
  1102. if (assignmentPattern.test(stmt.text)) {
  1103. errors.push({
  1104. type: 'error',
  1105. line: stmt.endLine + 1,
  1106. message: `Line ${stmt.endLine + 1}: The Alpha expression (final result) cannot be assigned to a variable. Remove the variable assignment.`
  1107. });
  1108. }
  1109. }
  1110. }
  1111. }
  1112. // Check for forbidden constructs
  1113. const forbiddenPatterns = [
  1114. { pattern: /\bclass\s+\w+/, message: 'Classes are not allowed in this expression language' },
  1115. { pattern: /\bfunction\s+\w+/, message: 'Functions are not allowed in this expression language' },
  1116. { pattern: /\w+\s*\*\s*\w+/, message: 'Pointers are not allowed in this expression language' },
  1117. { pattern: /\bnew\s+\w+/, message: 'Object creation (new) is not allowed in this expression language' }
  1118. ];
  1119. forbiddenPatterns.forEach(({ pattern, message }) => {
  1120. const matches = content.match(pattern);
  1121. if (matches) {
  1122. errors.push({
  1123. type: 'error',
  1124. message: message
  1125. });
  1126. }
  1127. });
  1128. // Display errors or success message
  1129. if (errors.length === 0) {
  1130. errorsDiv.innerHTML = '<div class="success-message">✓ Grammar check passed! No errors found.</div>';
  1131. } else {
  1132. errors.forEach(error => {
  1133. const errorDiv = document.createElement('div');
  1134. errorDiv.className = 'error-item';
  1135. errorDiv.innerHTML = `<strong>${error.type.toUpperCase()}:</strong> ${error.message}`;
  1136. errorsDiv.appendChild(errorDiv);
  1137. });
  1138. }
  1139. }
  1140. // Update template count display
  1141. function updateTemplateCount(templateName) {
  1142. const template = templates.get(templateName);
  1143. if (template && template.element) {
  1144. const countSpan = template.element.querySelector('.template-count');
  1145. if (countSpan) {
  1146. if (template.variables && template.variables.length > 0) {
  1147. countSpan.textContent = ` (${template.variables.length})`;
  1148. countSpan.style.color = '#48bb78';
  1149. countSpan.style.fontWeight = '600';
  1150. } else {
  1151. countSpan.textContent = '';
  1152. }
  1153. }
  1154. }
  1155. }
  1156. // Detect templates in the expression
  1157. function detectTemplates() {
  1158. const editor = document.getElementById('expressionEditor');
  1159. const content = editor.value;
  1160. const templateList = document.getElementById('templateList');
  1161. // Store existing template configurations
  1162. const existingTemplates = new Map(templates);
  1163. // Clear previous templates
  1164. templateList.innerHTML = '';
  1165. templates.clear();
  1166. // Regular expression to match templates like <variable_name/>
  1167. const templateRegex = /<(\w+)\/>/g;
  1168. const matches = [...content.matchAll(templateRegex)];
  1169. // Get unique templates
  1170. const uniqueTemplates = [...new Set(matches.map(match => match[1]))];
  1171. if (uniqueTemplates.length === 0) {
  1172. templateList.innerHTML = '<p style="color: #999; font-style: italic;">No templates detected</p>';
  1173. return;
  1174. }
  1175. // Display each template
  1176. uniqueTemplates.forEach(templateName => {
  1177. const templateDiv = document.createElement('div');
  1178. templateDiv.className = 'template-item not-configured'; // Add default not-configured class
  1179. const nameSpan = document.createElement('span');
  1180. nameSpan.className = 'template-name';
  1181. nameSpan.innerHTML = `<span class="template-brackets">&lt;</span><span class="template-tag">${templateName}</span><span class="template-brackets">/&gt;</span><span class="template-count"></span>`;
  1182. nameSpan.onclick = () => showTemplateConfig(templateName);
  1183. nameSpan.title = 'Click to view current configuration';
  1184. // Create container for the three buttons
  1185. const buttonContainer = document.createElement('div');
  1186. buttonContainer.className = 'template-buttons';
  1187. // Create Op button
  1188. const opBtn = document.createElement('button');
  1189. opBtn.className = 'btn btn-primary btn-small';
  1190. opBtn.textContent = 'Op';
  1191. opBtn.onclick = () => openTemplateModal(templateName, 'operator');
  1192. // Create Data button
  1193. const dataBtn = document.createElement('button');
  1194. dataBtn.className = 'btn btn-secondary btn-small';
  1195. dataBtn.textContent = 'DataField';
  1196. dataBtn.onclick = () => openTemplateModal(templateName, 'data');
  1197. // Create Normal button
  1198. const normalBtn = document.createElement('button');
  1199. normalBtn.className = 'btn btn-outline btn-small';
  1200. normalBtn.textContent = 'Other';
  1201. normalBtn.onclick = () => openTemplateModal(templateName, 'normal');
  1202. buttonContainer.appendChild(opBtn);
  1203. buttonContainer.appendChild(dataBtn);
  1204. buttonContainer.appendChild(normalBtn);
  1205. templateDiv.appendChild(nameSpan);
  1206. templateDiv.appendChild(buttonContainer);
  1207. templateList.appendChild(templateDiv);
  1208. // Store template info - restore existing config if available
  1209. const existingTemplate = existingTemplates.get(templateName);
  1210. if (existingTemplate && existingTemplate.variables.length > 0) {
  1211. templates.set(templateName, {
  1212. name: templateName,
  1213. variables: existingTemplate.variables,
  1214. element: templateDiv,
  1215. configType: existingTemplate.configType
  1216. });
  1217. // Update visual state
  1218. templateDiv.className = 'template-item configured';
  1219. updateTemplateCount(templateName);
  1220. } else {
  1221. templates.set(templateName, {
  1222. name: templateName,
  1223. variables: [],
  1224. element: templateDiv,
  1225. configType: null
  1226. });
  1227. }
  1228. });
  1229. }
  1230. // Open modal for template configuration
  1231. function openTemplateModal(templateName, configType) {
  1232. currentTemplate = templateName;
  1233. currentConfigType = configType; // Store the configuration type
  1234. const modal = document.getElementById('templateModal');
  1235. const modalTitle = document.getElementById('modalTitle');
  1236. const modalDescription = document.getElementById('modalDescription');
  1237. const variableInput = document.getElementById('variableInput');
  1238. const brainChooseSection = document.getElementById('brainChooseSection');
  1239. // Update modal content based on configuration type
  1240. let typeDescription = '';
  1241. switch(configType) {
  1242. case 'operator':
  1243. typeDescription = 'operators';
  1244. break;
  1245. case 'data':
  1246. typeDescription = 'data fields';
  1247. break;
  1248. case 'normal':
  1249. typeDescription = 'normal parameters (like dates, etc.)';
  1250. break;
  1251. }
  1252. modalTitle.textContent = `Configure Template: <${templateName}/> - ${configType.charAt(0).toUpperCase() + configType.slice(1)}`;
  1253. modalDescription.textContent = `Enter a comma-separated list of ${typeDescription} for the ${templateName} template:`;
  1254. // Show "Choose from BRAIN" button for operators and data fields if connected to BRAIN
  1255. if ((configType === 'operator' || configType === 'data') && window.brainAPI && window.brainAPI.isConnectedToBrain()) {
  1256. brainChooseSection.style.display = 'block';
  1257. const chooseBrainBtn = document.getElementById('chooseBrainBtn');
  1258. if (configType === 'operator') {
  1259. chooseBrainBtn.textContent = 'Choose Operators from BRAIN';
  1260. chooseBrainBtn.onclick = openBrainOperatorsModal;
  1261. } else if (configType === 'data') {
  1262. chooseBrainBtn.textContent = 'Choose Data Fields from BRAIN';
  1263. chooseBrainBtn.onclick = openBrainDataFieldsModal;
  1264. }
  1265. } else {
  1266. brainChooseSection.style.display = 'none';
  1267. }
  1268. // Load existing variables if any
  1269. const template = templates.get(templateName);
  1270. if (template && template.variables.length > 0 && template.configType === configType) {
  1271. variableInput.value = template.variables.join(', ');
  1272. } else {
  1273. variableInput.value = '';
  1274. }
  1275. modal.style.display = 'block';
  1276. variableInput.focus();
  1277. }
  1278. // Close modal
  1279. function closeModal() {
  1280. const modal = document.getElementById('templateModal');
  1281. modal.style.display = 'none';
  1282. currentTemplate = null;
  1283. }
  1284. // Show current template configuration
  1285. function showTemplateConfig(templateName) {
  1286. const template = templates.get(templateName);
  1287. const modal = document.getElementById('configInfoModal');
  1288. const title = document.getElementById('configInfoTitle');
  1289. const content = document.getElementById('configInfoContent');
  1290. title.textContent = `Template: <${templateName}/>`;
  1291. if (!template || !template.variables || template.variables.length === 0) {
  1292. content.innerHTML = `
  1293. <div class="config-info-item">
  1294. <strong>Status:</strong> <span class="config-status-unconfigured">Not configured</span><br>
  1295. <strong>Template:</strong> &lt;${templateName}/&gt;<br><br>
  1296. <em>Click one of the configuration buttons (Op, Data, Normal) to set up this template.</em>
  1297. </div>
  1298. `;
  1299. } else {
  1300. const configTypeDisplay = template.configType ?
  1301. template.configType.charAt(0).toUpperCase() + template.configType.slice(1) :
  1302. 'Unknown';
  1303. content.innerHTML = `
  1304. <div class="config-info-item">
  1305. <strong>Status:</strong> <span class="config-status-configured">Configured</span><br>
  1306. <strong>Template:</strong> &lt;${templateName}/&gt;<br>
  1307. <strong>Type:</strong> ${configTypeDisplay}<br>
  1308. <strong>Count:</strong> ${template.variables.length} value${template.variables.length > 1 ? 's' : ''}<br>
  1309. <div class="config-info-values">
  1310. <strong>Values:</strong><br>
  1311. ${template.variables.join(', ')}
  1312. </div>
  1313. </div>
  1314. `;
  1315. }
  1316. modal.style.display = 'block';
  1317. }
  1318. // Close configuration info modal
  1319. function closeConfigInfoModal() {
  1320. const modal = document.getElementById('configInfoModal');
  1321. modal.style.display = 'none';
  1322. }
  1323. // Close modal when clicking outside
  1324. window.onclick = function(event) {
  1325. const templateModal = document.getElementById('templateModal');
  1326. const configInfoModal = document.getElementById('configInfoModal');
  1327. const brainLoginModal = document.getElementById('brainLoginModal');
  1328. const brainOperatorsModal = document.getElementById('brainOperatorsModal');
  1329. const brainDataFieldsModal = document.getElementById('brainDataFieldsModal');
  1330. const settingsModal = document.getElementById('settingsModal');
  1331. const saveTemplateModal = document.getElementById('saveTemplateModal');
  1332. const overwriteTemplateModal = document.getElementById('overwriteTemplateModal');
  1333. if (event.target === templateModal) {
  1334. closeModal();
  1335. } else if (event.target === configInfoModal) {
  1336. closeConfigInfoModal();
  1337. } else if (event.target === brainLoginModal) {
  1338. // Check if login is in progress
  1339. const loginBtn = document.getElementById('loginBtn');
  1340. if (!loginBtn || !loginBtn.disabled) {
  1341. closeBrainLoginModal();
  1342. }
  1343. } else if (event.target === brainOperatorsModal) {
  1344. closeBrainOperatorsModal();
  1345. } else if (event.target === brainDataFieldsModal) {
  1346. closeBrainDataFieldsModal();
  1347. } else if (event.target === settingsModal) {
  1348. closeSettingsModal();
  1349. } else if (event.target === saveTemplateModal) {
  1350. closeSaveTemplateModal();
  1351. } else if (event.target === overwriteTemplateModal) {
  1352. closeOverwriteTemplateModal();
  1353. }
  1354. }
  1355. // Apply template variables
  1356. function applyTemplate() {
  1357. const variableInput = document.getElementById('variableInput');
  1358. const variables = variableInput.value
  1359. .split(',')
  1360. .map(v => v.trim())
  1361. .filter(v => v !== '');
  1362. if (variables.length === 0) {
  1363. alert('Please enter at least one variable');
  1364. return;
  1365. }
  1366. // Store variables for the template
  1367. const template = templates.get(currentTemplate);
  1368. if (template) {
  1369. template.variables = variables;
  1370. template.configType = currentConfigType; // Store the configuration type
  1371. // Update the visual indicator
  1372. if (template.element) {
  1373. template.element.className = 'template-item configured';
  1374. }
  1375. // Update the count display
  1376. updateTemplateCount(currentTemplate);
  1377. }
  1378. // Close the modal
  1379. closeModal();
  1380. // Show success message
  1381. const errorsDiv = document.getElementById('grammarErrors');
  1382. errorsDiv.innerHTML = `<div class="success-message">✓ Template <${currentTemplate}/> configured as ${currentConfigType} with ${variables.length} variable${variables.length > 1 ? 's' : ''}</div>`;
  1383. }
  1384. // Clear editor
  1385. function clearEditor() {
  1386. const editor = document.getElementById('expressionEditor');
  1387. editor.value = '';
  1388. updateLineNumbers();
  1389. updateSyntaxHighlight();
  1390. document.getElementById('grammarErrors').innerHTML = '';
  1391. document.getElementById('decodedResults').style.display = 'none';
  1392. detectTemplates();
  1393. }
  1394. // Auto-completion functionality
  1395. let autoCompleteActive = false;
  1396. let autoCompletePosition = null;
  1397. let shadowSuggestion = null;
  1398. function handleAutoComplete(event) {
  1399. const editor = event.target;
  1400. const cursorPos = editor.selectionStart;
  1401. const text = editor.value;
  1402. const lastChar = text[cursorPos - 1];
  1403. const prevChar = cursorPos > 1 ? text[cursorPos - 2] : '';
  1404. // If user typed '<', show shadow suggestion
  1405. if (lastChar === '<' && event.inputType === 'insertText') {
  1406. // Show shadow suggestion for template
  1407. showShadowSuggestion(editor, cursorPos, 'variable_name/>');
  1408. autoCompleteActive = true;
  1409. autoCompletePosition = cursorPos;
  1410. }
  1411. // If user typed '/', check if it's after '<'
  1412. else if (lastChar === '/' && prevChar === '<') {
  1413. // Auto-complete the closing '>'
  1414. const before = text.substring(0, cursorPos);
  1415. const after = text.substring(cursorPos);
  1416. editor.value = before + '>' + after;
  1417. editor.setSelectionRange(cursorPos, cursorPos);
  1418. // Update shadow to show between < and />
  1419. hideShadowSuggestion();
  1420. autoCompleteActive = false;
  1421. }
  1422. // If user typed something after '<' that's not '/', hide suggestion
  1423. else if (prevChar === '<' && lastChar !== '/' && autoCompleteActive) {
  1424. // User is typing something else after '<', like a comparison
  1425. hideShadowSuggestion();
  1426. autoCompleteActive = false;
  1427. }
  1428. else {
  1429. // Check if we should hide suggestion for other cases
  1430. if (!autoCompleteActive || (autoCompletePosition && cursorPos > autoCompletePosition + 1)) {
  1431. hideShadowSuggestion();
  1432. autoCompleteActive = false;
  1433. }
  1434. }
  1435. }
  1436. function handleTabCompletion() {
  1437. const editor = document.getElementById('expressionEditor');
  1438. const cursorPos = editor.selectionStart;
  1439. const text = editor.value;
  1440. if (autoCompleteActive && shadowSuggestion) {
  1441. // Check if we're right after '<'
  1442. if (cursorPos > 0 && text[cursorPos - 1] === '<') {
  1443. // Complete the template
  1444. const before = text.substring(0, cursorPos);
  1445. const after = text.substring(cursorPos);
  1446. editor.value = before + '/>' + after;
  1447. editor.setSelectionRange(cursorPos, cursorPos);
  1448. hideShadowSuggestion();
  1449. autoCompleteActive = false;
  1450. // Trigger input event to update everything
  1451. const inputEvent = new Event('input', { bubbles: true });
  1452. editor.dispatchEvent(inputEvent);
  1453. // Update syntax highlighting immediately
  1454. updateSyntaxHighlight();
  1455. }
  1456. }
  1457. }
  1458. function showShadowSuggestion(editor, position, suggestion) {
  1459. // Remove any existing shadow
  1460. hideShadowSuggestion();
  1461. // Create shadow element
  1462. shadowSuggestion = document.createElement('div');
  1463. shadowSuggestion.className = 'shadow-suggestion';
  1464. shadowSuggestion.textContent = suggestion;
  1465. // Get editor wrapper for relative positioning
  1466. const editorWrapper = editor.closest('.editor-wrapper');
  1467. const editorRect = editor.getBoundingClientRect();
  1468. // Calculate position based on character position
  1469. const lineHeight = parseInt(window.getComputedStyle(editor).lineHeight);
  1470. const lines = editor.value.substring(0, position).split('\n');
  1471. const currentLine = lines.length;
  1472. const currentCol = lines[lines.length - 1].length;
  1473. // Approximate character width (monospace font)
  1474. const charWidth = 9.6; // Approximate width for 16px monospace font
  1475. // Position shadow relative to editor
  1476. shadowSuggestion.style.position = 'fixed';
  1477. shadowSuggestion.style.left = (editorRect.left + 15 + (currentCol * charWidth)) + 'px';
  1478. shadowSuggestion.style.top = (editorRect.top + 12 + ((currentLine - 1) * lineHeight) - editor.scrollTop) + 'px';
  1479. shadowSuggestion.style.pointerEvents = 'none';
  1480. shadowSuggestion.style.zIndex = '1000';
  1481. // Add hint text below
  1482. const hintText = document.createElement('div');
  1483. hintText.className = 'shadow-hint';
  1484. hintText.textContent = 'Tab to complete template';
  1485. shadowSuggestion.appendChild(hintText);
  1486. document.body.appendChild(shadowSuggestion);
  1487. }
  1488. function hideShadowSuggestion() {
  1489. if (shadowSuggestion) {
  1490. shadowSuggestion.remove();
  1491. shadowSuggestion = null;
  1492. }
  1493. }
  1494. // BRAIN Operators Modal Functions
  1495. let selectedOperators = new Set();
  1496. function openBrainOperatorsModal() {
  1497. const modal = document.getElementById('brainOperatorsModal');
  1498. selectedOperators.clear();
  1499. // Populate categories
  1500. populateOperatorCategories();
  1501. // Populate operators list
  1502. populateOperatorsList();
  1503. // Set up event listeners
  1504. setupOperatorsModalEventListeners();
  1505. modal.style.display = 'block';
  1506. }
  1507. function closeBrainOperatorsModal() {
  1508. const modal = document.getElementById('brainOperatorsModal');
  1509. modal.style.display = 'none';
  1510. selectedOperators.clear();
  1511. updateSelectedOperatorsDisplay();
  1512. }
  1513. function populateOperatorCategories() {
  1514. const categoryFilter = document.getElementById('categoryFilter');
  1515. const operators = window.brainAPI ? window.brainAPI.getLoadedOperators() : [];
  1516. // Clear existing options except "All Categories"
  1517. categoryFilter.innerHTML = '<option value="">All Categories</option>';
  1518. // Get unique categories
  1519. const categories = [...new Set(operators.map(op => op.category))].sort();
  1520. categories.forEach(category => {
  1521. const option = document.createElement('option');
  1522. option.value = category;
  1523. option.textContent = category;
  1524. categoryFilter.appendChild(option);
  1525. });
  1526. }
  1527. function populateOperatorsList(searchTerm = '', categoryFilter = '') {
  1528. const operatorsList = document.getElementById('operatorsList');
  1529. const operators = window.brainAPI ? window.brainAPI.getLoadedOperators() : [];
  1530. // Filter operators
  1531. let filteredOperators = operators;
  1532. if (searchTerm) {
  1533. const term = searchTerm.toLowerCase();
  1534. filteredOperators = filteredOperators.filter(op =>
  1535. op.name.toLowerCase().includes(term) ||
  1536. op.category.toLowerCase().includes(term)
  1537. );
  1538. }
  1539. if (categoryFilter) {
  1540. filteredOperators = filteredOperators.filter(op => op.category === categoryFilter);
  1541. }
  1542. // Clear list
  1543. operatorsList.innerHTML = '';
  1544. if (filteredOperators.length === 0) {
  1545. operatorsList.innerHTML = '<p style="text-align: center; color: #666;">No operators found</p>';
  1546. return;
  1547. }
  1548. // Create operator items
  1549. filteredOperators.forEach(operator => {
  1550. const item = document.createElement('div');
  1551. item.className = 'operator-item';
  1552. item.dataset.operatorName = operator.name;
  1553. // Build tooltip content if description or definition is available
  1554. let tooltipContent = '';
  1555. if (operator.description) {
  1556. tooltipContent += `Description: ${operator.description}`;
  1557. }
  1558. if (operator.definition) {
  1559. tooltipContent += tooltipContent ? `\n\nDefinition: ${operator.definition}` : `Definition: ${operator.definition}`;
  1560. }
  1561. if (operator.example) {
  1562. tooltipContent += tooltipContent ? `\n\nExample: ${operator.example}` : `Example: ${operator.example}`;
  1563. }
  1564. if (operator.usageCount !== undefined) {
  1565. tooltipContent += tooltipContent ? `\n\nUsage Count: ${operator.usageCount}` : `Usage Count: ${operator.usageCount}`;
  1566. }
  1567. // Add custom tooltip if we have content
  1568. if (tooltipContent) {
  1569. item.dataset.tooltip = tooltipContent;
  1570. item.style.cursor = 'help';
  1571. // Add mouse event listeners for custom tooltip
  1572. item.addEventListener('mouseenter', showCustomTooltip);
  1573. item.addEventListener('mouseleave', hideCustomTooltip);
  1574. item.addEventListener('mousemove', moveCustomTooltip);
  1575. }
  1576. // Create description indicator if description or definition is available
  1577. const descriptionIndicator = (operator.description || operator.definition) ?
  1578. '<span class="description-indicator" title="Has description/definition">📖</span>' : '';
  1579. item.innerHTML = `
  1580. <input type="checkbox" class="operator-checkbox" ${selectedOperators.has(operator.name) ? 'checked' : ''}>
  1581. <div class="operator-info">
  1582. <span class="operator-name">${operator.name} ${descriptionIndicator}</span>
  1583. <span class="operator-category">${operator.category}</span>
  1584. </div>
  1585. `;
  1586. item.onclick = () => toggleOperatorSelection(operator.name, item);
  1587. operatorsList.appendChild(item);
  1588. });
  1589. }
  1590. function toggleOperatorSelection(operatorName, item) {
  1591. const checkbox = item.querySelector('.operator-checkbox');
  1592. if (selectedOperators.has(operatorName)) {
  1593. selectedOperators.delete(operatorName);
  1594. checkbox.checked = false;
  1595. item.classList.remove('selected');
  1596. } else {
  1597. selectedOperators.add(operatorName);
  1598. checkbox.checked = true;
  1599. item.classList.add('selected');
  1600. }
  1601. updateSelectedOperatorsDisplay();
  1602. }
  1603. function updateSelectedOperatorsDisplay() {
  1604. const selectedContainer = document.getElementById('selectedOperators');
  1605. selectedContainer.innerHTML = '';
  1606. if (selectedOperators.size === 0) {
  1607. selectedContainer.innerHTML = '<em style="color: #666;">No operators selected</em>';
  1608. return;
  1609. }
  1610. selectedOperators.forEach(operatorName => {
  1611. const item = document.createElement('span');
  1612. item.className = 'selected-item';
  1613. item.innerHTML = `
  1614. ${operatorName}
  1615. <button class="remove-btn" onclick="removeSelectedOperator('${operatorName}')">&times;</button>
  1616. `;
  1617. selectedContainer.appendChild(item);
  1618. });
  1619. }
  1620. function removeSelectedOperator(operatorName) {
  1621. selectedOperators.delete(operatorName);
  1622. updateSelectedOperatorsDisplay();
  1623. // Update the checkbox in the list
  1624. const operatorItem = document.querySelector(`[data-operator-name="${operatorName}"]`);
  1625. if (operatorItem) {
  1626. const checkbox = operatorItem.querySelector('.operator-checkbox');
  1627. checkbox.checked = false;
  1628. operatorItem.classList.remove('selected');
  1629. }
  1630. }
  1631. function setupOperatorsModalEventListeners() {
  1632. const searchInput = document.getElementById('operatorSearch');
  1633. const categoryFilter = document.getElementById('categoryFilter');
  1634. const selectAllBtn = document.getElementById('selectAllFilteredOperators');
  1635. const clearAllBtn = document.getElementById('clearAllOperators');
  1636. searchInput.oninput = () => {
  1637. populateOperatorsList(searchInput.value, categoryFilter.value);
  1638. };
  1639. categoryFilter.onchange = () => {
  1640. populateOperatorsList(searchInput.value, categoryFilter.value);
  1641. };
  1642. selectAllBtn.onclick = selectAllFilteredOperators;
  1643. clearAllBtn.onclick = clearAllOperators;
  1644. }
  1645. function selectAllFilteredOperators() {
  1646. const operatorItems = document.querySelectorAll('.operator-item');
  1647. operatorItems.forEach(item => {
  1648. const operatorName = item.dataset.operatorName;
  1649. if (!selectedOperators.has(operatorName)) {
  1650. selectedOperators.add(operatorName);
  1651. const checkbox = item.querySelector('.operator-checkbox');
  1652. checkbox.checked = true;
  1653. item.classList.add('selected');
  1654. }
  1655. });
  1656. updateSelectedOperatorsDisplay();
  1657. }
  1658. function clearAllOperators() {
  1659. selectedOperators.clear();
  1660. // Update all checkboxes
  1661. document.querySelectorAll('.operator-item').forEach(item => {
  1662. const checkbox = item.querySelector('.operator-checkbox');
  1663. checkbox.checked = false;
  1664. item.classList.remove('selected');
  1665. });
  1666. updateSelectedOperatorsDisplay();
  1667. }
  1668. function applySelectedOperators() {
  1669. if (selectedOperators.size === 0) {
  1670. alert('Please select at least one operator');
  1671. return;
  1672. }
  1673. // Add selected operators to the variable input
  1674. const variableInput = document.getElementById('variableInput');
  1675. const currentValues = variableInput.value.trim();
  1676. const newValues = Array.from(selectedOperators);
  1677. if (currentValues) {
  1678. variableInput.value = currentValues + ', ' + newValues.join(', ');
  1679. } else {
  1680. variableInput.value = newValues.join(', ');
  1681. }
  1682. closeBrainOperatorsModal();
  1683. }
  1684. // BRAIN Data Fields Modal Functions
  1685. let selectedDataFields = new Set();
  1686. let currentDataFields = [];
  1687. let filteredDataFields = [];
  1688. let columnFilters = {
  1689. id: '',
  1690. description: '',
  1691. type: '',
  1692. coverage: { min: null, max: null },
  1693. userCount: null,
  1694. alphaCount: null
  1695. };
  1696. let sortColumn = null;
  1697. let sortOrder = 'asc';
  1698. function openBrainDataFieldsModal() {
  1699. const modal = document.getElementById('brainDataFieldsModal');
  1700. selectedDataFields.clear();
  1701. currentDataFields = [];
  1702. filteredDataFields = [];
  1703. // Reset column filters
  1704. columnFilters = {
  1705. id: '',
  1706. description: '',
  1707. type: '',
  1708. coverage: { min: null, max: null },
  1709. userCount: null,
  1710. alphaCount: null
  1711. };
  1712. sortColumn = null;
  1713. sortOrder = 'asc';
  1714. // Reset UI state
  1715. document.getElementById('dataFieldsContent').style.display = 'none';
  1716. document.getElementById('dataFieldsLoading').style.display = 'none';
  1717. // Clear column filter inputs
  1718. document.querySelectorAll('.column-filter').forEach(filter => {
  1719. filter.value = '';
  1720. });
  1721. document.querySelectorAll('.column-filter-min, .column-filter-max').forEach(filter => {
  1722. filter.value = '';
  1723. });
  1724. // Reset sort buttons
  1725. document.querySelectorAll('.sort-btn').forEach(btn => {
  1726. btn.classList.remove('asc', 'desc');
  1727. btn.dataset.order = 'asc';
  1728. });
  1729. // Set up event listeners
  1730. setupDataFieldsModalEventListeners();
  1731. modal.style.display = 'block';
  1732. }
  1733. function closeBrainDataFieldsModal() {
  1734. const modal = document.getElementById('brainDataFieldsModal');
  1735. modal.style.display = 'none';
  1736. selectedDataFields.clear();
  1737. updateSelectedDataFieldsDisplay();
  1738. }
  1739. async function loadDataFields() {
  1740. const region = document.getElementById('regionInput').value;
  1741. const delay = document.getElementById('delayInput').value;
  1742. const universe = document.getElementById('universeInput').value;
  1743. const datasetId = document.getElementById('datasetInput').value;
  1744. const loadingDiv = document.getElementById('dataFieldsLoading');
  1745. const contentDiv = document.getElementById('dataFieldsContent');
  1746. try {
  1747. loadingDiv.style.display = 'block';
  1748. contentDiv.style.display = 'none';
  1749. // Fetch data fields using the brain API
  1750. if (!window.brainAPI || !window.brainAPI.isConnectedToBrain()) {
  1751. throw new Error('Not connected to BRAIN');
  1752. }
  1753. const dataFields = await window.brainAPI.getDataFields(region, parseInt(delay), universe, datasetId);
  1754. currentDataFields = dataFields;
  1755. filteredDataFields = [...dataFields];
  1756. populateDataFieldsList();
  1757. updateDataFieldsStats();
  1758. populateTypeFilter();
  1759. loadingDiv.style.display = 'none';
  1760. contentDiv.style.display = 'block';
  1761. } catch (error) {
  1762. loadingDiv.style.display = 'none';
  1763. alert(`Failed to load data fields: ${error.message}`);
  1764. }
  1765. }
  1766. function populateDataFieldsList() {
  1767. const tableBody = document.getElementById('dataFieldsTableBody');
  1768. const highCoverageFilter = document.getElementById('filterHighCoverage').checked;
  1769. const popularFilter = document.getElementById('filterPopular').checked;
  1770. const matrixOnlyFilter = document.getElementById('filterMatrixOnly').checked;
  1771. // Apply filters
  1772. filteredDataFields = currentDataFields.filter(field => {
  1773. // Column-specific filters
  1774. // ID filter
  1775. if (columnFilters.id && !field.id.toLowerCase().includes(columnFilters.id.toLowerCase())) {
  1776. return false;
  1777. }
  1778. // Description filter
  1779. if (columnFilters.description && !field.description.toLowerCase().includes(columnFilters.description.toLowerCase())) {
  1780. return false;
  1781. }
  1782. // Type filter
  1783. if (columnFilters.type && field.type !== columnFilters.type) {
  1784. return false;
  1785. }
  1786. // Coverage range filter
  1787. if (columnFilters.coverage.min !== null && field.coverage * 100 < columnFilters.coverage.min) {
  1788. return false;
  1789. }
  1790. if (columnFilters.coverage.max !== null && field.coverage * 100 > columnFilters.coverage.max) {
  1791. return false;
  1792. }
  1793. // User count filter
  1794. if (columnFilters.userCount !== null && field.userCount < columnFilters.userCount) {
  1795. return false;
  1796. }
  1797. // Alpha count filter
  1798. if (columnFilters.alphaCount !== null && field.alphaCount < columnFilters.alphaCount) {
  1799. return false;
  1800. }
  1801. // High coverage filter
  1802. if (highCoverageFilter && field.coverage < 0.9) {
  1803. return false;
  1804. }
  1805. // Popular filter
  1806. if (popularFilter && field.userCount < 1000) {
  1807. return false;
  1808. }
  1809. // Matrix type filter
  1810. if (matrixOnlyFilter && field.type !== 'MATRIX') {
  1811. return false;
  1812. }
  1813. return true;
  1814. });
  1815. // Sort filtered data fields
  1816. if (sortColumn) {
  1817. filteredDataFields.sort((a, b) => {
  1818. let aVal = a[sortColumn];
  1819. let bVal = b[sortColumn];
  1820. // Handle numeric values
  1821. if (sortColumn === 'coverage' || sortColumn === 'userCount' || sortColumn === 'alphaCount') {
  1822. aVal = Number(aVal);
  1823. bVal = Number(bVal);
  1824. } else {
  1825. // String comparison
  1826. aVal = String(aVal).toLowerCase();
  1827. bVal = String(bVal).toLowerCase();
  1828. }
  1829. if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1;
  1830. if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1;
  1831. return 0;
  1832. });
  1833. }
  1834. // Clear table
  1835. tableBody.innerHTML = '';
  1836. if (filteredDataFields.length === 0) {
  1837. tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #666; padding: 40px;">No data fields found matching the filters</td></tr>';
  1838. updateDataFieldsStats();
  1839. return;
  1840. }
  1841. // Create table rows
  1842. filteredDataFields.forEach(field => {
  1843. const row = document.createElement('tr');
  1844. row.dataset.fieldId = field.id;
  1845. if (selectedDataFields.has(field.id)) {
  1846. row.classList.add('selected');
  1847. }
  1848. row.innerHTML = `
  1849. <td>
  1850. <input type="checkbox" class="data-field-checkbox" ${selectedDataFields.has(field.id) ? 'checked' : ''}>
  1851. </td>
  1852. <td><span class="data-field-id">${field.id}</span></td>
  1853. <td><span class="data-field-description">${field.description}</span></td>
  1854. <td><span class="data-field-type">${field.type}</span></td>
  1855. <td><span class="data-field-coverage">${(field.coverage * 100).toFixed(1)}%</span></td>
  1856. <td><span class="data-field-count">${field.userCount.toLocaleString()}</span></td>
  1857. <td><span class="data-field-count">${field.alphaCount.toLocaleString()}</span></td>
  1858. `;
  1859. row.onclick = (e) => {
  1860. if (e.target.type !== 'checkbox') {
  1861. toggleDataFieldSelection(field.id, row);
  1862. }
  1863. };
  1864. const checkbox = row.querySelector('.data-field-checkbox');
  1865. checkbox.onclick = (e) => {
  1866. e.stopPropagation();
  1867. toggleDataFieldSelection(field.id, row);
  1868. };
  1869. tableBody.appendChild(row);
  1870. });
  1871. updateDataFieldsStats();
  1872. }
  1873. function toggleDataFieldSelection(fieldId, row) {
  1874. const checkbox = row.querySelector('.data-field-checkbox');
  1875. if (selectedDataFields.has(fieldId)) {
  1876. selectedDataFields.delete(fieldId);
  1877. checkbox.checked = false;
  1878. row.classList.remove('selected');
  1879. } else {
  1880. selectedDataFields.add(fieldId);
  1881. checkbox.checked = true;
  1882. row.classList.add('selected');
  1883. }
  1884. updateSelectedDataFieldsDisplay();
  1885. updateDataFieldsStats();
  1886. updateSelectAllCheckbox();
  1887. }
  1888. function updateSelectedDataFieldsDisplay() {
  1889. const selectedContainer = document.getElementById('selectedDataFields');
  1890. selectedContainer.innerHTML = '';
  1891. if (selectedDataFields.size === 0) {
  1892. selectedContainer.innerHTML = '<em style="color: #666;">No data fields selected</em>';
  1893. return;
  1894. }
  1895. selectedDataFields.forEach(fieldId => {
  1896. const item = document.createElement('span');
  1897. item.className = 'selected-item';
  1898. item.innerHTML = `
  1899. ${fieldId}
  1900. <button class="remove-btn" onclick="removeSelectedDataField('${fieldId}')">&times;</button>
  1901. `;
  1902. selectedContainer.appendChild(item);
  1903. });
  1904. }
  1905. function removeSelectedDataField(fieldId) {
  1906. selectedDataFields.delete(fieldId);
  1907. updateSelectedDataFieldsDisplay();
  1908. updateDataFieldsStats();
  1909. // Update the checkbox in the table
  1910. const row = document.querySelector(`tr[data-field-id="${fieldId}"]`);
  1911. if (row) {
  1912. const checkbox = row.querySelector('.data-field-checkbox');
  1913. checkbox.checked = false;
  1914. row.classList.remove('selected');
  1915. }
  1916. updateSelectAllCheckbox();
  1917. }
  1918. function updateDataFieldsStats() {
  1919. document.getElementById('dataFieldsCount').textContent = `${currentDataFields.length} fields loaded`;
  1920. document.getElementById('filteredCount').textContent = `${filteredDataFields.length} filtered`;
  1921. document.getElementById('selectedCount').textContent = `${selectedDataFields.size} selected`;
  1922. }
  1923. function populateTypeFilter() {
  1924. const typeFilter = document.getElementById('typeFilter');
  1925. if (!typeFilter) return;
  1926. // Get unique types from current data fields
  1927. const uniqueTypes = [...new Set(currentDataFields.map(field => field.type))].sort();
  1928. // Clear existing options except "All Types"
  1929. typeFilter.innerHTML = '<option value="">All Types</option>';
  1930. // Add unique types as options
  1931. uniqueTypes.forEach(type => {
  1932. const option = document.createElement('option');
  1933. option.value = type;
  1934. option.textContent = type;
  1935. typeFilter.appendChild(option);
  1936. });
  1937. // Restore selected value if it exists
  1938. if (columnFilters.type && uniqueTypes.includes(columnFilters.type)) {
  1939. typeFilter.value = columnFilters.type;
  1940. }
  1941. }
  1942. function selectAllFilteredDataFields() {
  1943. filteredDataFields.forEach(field => {
  1944. selectedDataFields.add(field.id);
  1945. const row = document.querySelector(`tr[data-field-id="${field.id}"]`);
  1946. if (row) {
  1947. const checkbox = row.querySelector('.data-field-checkbox');
  1948. checkbox.checked = true;
  1949. row.classList.add('selected');
  1950. }
  1951. });
  1952. updateSelectedDataFieldsDisplay();
  1953. updateDataFieldsStats();
  1954. updateSelectAllCheckbox();
  1955. }
  1956. function clearAllSelectedDataFields() {
  1957. selectedDataFields.clear();
  1958. // Update all checkboxes
  1959. document.querySelectorAll('.data-field-checkbox').forEach(checkbox => {
  1960. checkbox.checked = false;
  1961. checkbox.closest('tr').classList.remove('selected');
  1962. });
  1963. updateSelectedDataFieldsDisplay();
  1964. updateDataFieldsStats();
  1965. updateSelectAllCheckbox();
  1966. }
  1967. function setupDataFieldsModalEventListeners() {
  1968. const loadBtn = document.getElementById('loadDataFieldsBtn');
  1969. const selectAllBtn = document.getElementById('selectAllFiltered');
  1970. const clearAllBtn = document.getElementById('clearAllSelected');
  1971. const selectAllCheckbox = document.getElementById('selectAllCheckbox');
  1972. // Filter checkboxes
  1973. const highCoverageFilter = document.getElementById('filterHighCoverage');
  1974. const popularFilter = document.getElementById('filterPopular');
  1975. const matrixOnlyFilter = document.getElementById('filterMatrixOnly');
  1976. loadBtn.onclick = loadDataFields;
  1977. // Filter checkbox listeners
  1978. highCoverageFilter.onchange = () => populateDataFieldsList();
  1979. popularFilter.onchange = () => populateDataFieldsList();
  1980. matrixOnlyFilter.onchange = () => populateDataFieldsList();
  1981. selectAllBtn.onclick = selectAllFilteredDataFields;
  1982. clearAllBtn.onclick = clearAllSelectedDataFields;
  1983. selectAllCheckbox.onclick = (e) => {
  1984. e.stopPropagation();
  1985. if (selectAllCheckbox.checked) {
  1986. selectAllFilteredDataFields();
  1987. } else {
  1988. clearAllFilteredDataFields();
  1989. }
  1990. };
  1991. // Column filter listeners
  1992. document.querySelectorAll('.column-filter').forEach(filter => {
  1993. filter.addEventListener('input', (e) => {
  1994. const column = e.target.dataset.column;
  1995. const value = e.target.value;
  1996. if (column === 'userCount' || column === 'alphaCount') {
  1997. columnFilters[column] = value ? parseInt(value) : null;
  1998. } else {
  1999. columnFilters[column] = value;
  2000. }
  2001. // Add/remove active class
  2002. if (value) {
  2003. e.target.classList.add('active');
  2004. } else {
  2005. e.target.classList.remove('active');
  2006. }
  2007. populateDataFieldsList();
  2008. });
  2009. });
  2010. // Coverage range filters
  2011. document.querySelectorAll('.column-filter-min, .column-filter-max').forEach(filter => {
  2012. filter.addEventListener('input', (e) => {
  2013. const isMin = e.target.classList.contains('column-filter-min');
  2014. const value = e.target.value;
  2015. if (isMin) {
  2016. columnFilters.coverage.min = value ? parseFloat(value) : null;
  2017. } else {
  2018. columnFilters.coverage.max = value ? parseFloat(value) : null;
  2019. }
  2020. // Add/remove active class
  2021. const minInput = e.target.parentElement.querySelector('.column-filter-min');
  2022. const maxInput = e.target.parentElement.querySelector('.column-filter-max');
  2023. if (minInput.value || maxInput.value) {
  2024. minInput.classList.add('active');
  2025. maxInput.classList.add('active');
  2026. } else {
  2027. minInput.classList.remove('active');
  2028. maxInput.classList.remove('active');
  2029. }
  2030. populateDataFieldsList();
  2031. });
  2032. });
  2033. // Sort button listeners
  2034. document.querySelectorAll('.sort-btn').forEach(btn => {
  2035. btn.addEventListener('click', (e) => {
  2036. const column = e.target.dataset.column;
  2037. // Reset all other sort buttons
  2038. document.querySelectorAll('.sort-btn').forEach(b => {
  2039. if (b !== e.target) {
  2040. b.classList.remove('asc', 'desc');
  2041. b.dataset.order = 'asc';
  2042. }
  2043. });
  2044. // Toggle sort order
  2045. if (sortColumn === column) {
  2046. sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
  2047. } else {
  2048. sortColumn = column;
  2049. sortOrder = 'asc';
  2050. }
  2051. e.target.dataset.order = sortOrder;
  2052. e.target.classList.remove('asc', 'desc');
  2053. e.target.classList.add(sortOrder);
  2054. populateDataFieldsList();
  2055. });
  2056. });
  2057. }
  2058. function updateSelectAllCheckbox() {
  2059. const selectAllCheckbox = document.getElementById('selectAllCheckbox');
  2060. if (!selectAllCheckbox) return;
  2061. const allFilteredSelected = filteredDataFields.length > 0 &&
  2062. filteredDataFields.every(field => selectedDataFields.has(field.id));
  2063. selectAllCheckbox.checked = allFilteredSelected;
  2064. selectAllCheckbox.indeterminate = !allFilteredSelected &&
  2065. filteredDataFields.some(field => selectedDataFields.has(field.id));
  2066. }
  2067. function clearAllFilteredDataFields() {
  2068. filteredDataFields.forEach(field => {
  2069. selectedDataFields.delete(field.id);
  2070. const row = document.querySelector(`tr[data-field-id="${field.id}"]`);
  2071. if (row) {
  2072. const checkbox = row.querySelector('.data-field-checkbox');
  2073. checkbox.checked = false;
  2074. row.classList.remove('selected');
  2075. }
  2076. });
  2077. updateSelectedDataFieldsDisplay();
  2078. updateDataFieldsStats();
  2079. updateSelectAllCheckbox();
  2080. }
  2081. function applySelectedDataFields() {
  2082. if (selectedDataFields.size === 0) {
  2083. alert('Please select at least one data field');
  2084. return;
  2085. }
  2086. // Add selected data fields to the variable input
  2087. const variableInput = document.getElementById('variableInput');
  2088. const currentValues = variableInput.value.trim();
  2089. const newValues = Array.from(selectedDataFields);
  2090. if (currentValues) {
  2091. variableInput.value = currentValues + ', ' + newValues.join(', ');
  2092. } else {
  2093. variableInput.value = newValues.join(', ');
  2094. }
  2095. closeBrainDataFieldsModal();
  2096. }
  2097. // Custom tooltip functionality
  2098. let tooltipElement = null;
  2099. function createTooltipElement() {
  2100. if (!tooltipElement) {
  2101. tooltipElement = document.createElement('div');
  2102. tooltipElement.className = 'custom-tooltip';
  2103. document.body.appendChild(tooltipElement);
  2104. }
  2105. return tooltipElement;
  2106. }
  2107. function showCustomTooltip(event) {
  2108. const tooltip = createTooltipElement();
  2109. const content = event.target.closest('[data-tooltip]')?.dataset.tooltip;
  2110. if (content) {
  2111. tooltip.textContent = content;
  2112. tooltip.style.opacity = '1';
  2113. moveCustomTooltip(event);
  2114. }
  2115. }
  2116. function hideCustomTooltip() {
  2117. if (tooltipElement) {
  2118. tooltipElement.style.opacity = '0';
  2119. }
  2120. }
  2121. function moveCustomTooltip(event) {
  2122. if (!tooltipElement || tooltipElement.style.opacity === '0') return;
  2123. const tooltip = tooltipElement;
  2124. const mouseX = event.clientX;
  2125. const mouseY = event.clientY;
  2126. const offset = 10;
  2127. // Get tooltip dimensions
  2128. const tooltipRect = tooltip.getBoundingClientRect();
  2129. const windowWidth = window.innerWidth;
  2130. const windowHeight = window.innerHeight;
  2131. // Calculate position
  2132. let left = mouseX + offset;
  2133. let top = mouseY + offset;
  2134. // Adjust if tooltip would go off-screen to the right
  2135. if (left + tooltipRect.width > windowWidth) {
  2136. left = mouseX - tooltipRect.width - offset;
  2137. }
  2138. // Adjust if tooltip would go off-screen at the bottom
  2139. if (top + tooltipRect.height > windowHeight) {
  2140. top = mouseY - tooltipRect.height - offset;
  2141. }
  2142. // Ensure tooltip doesn't go off-screen to the left or top
  2143. if (left < 0) left = offset;
  2144. if (top < 0) top = offset;
  2145. tooltip.style.left = left + 'px';
  2146. tooltip.style.top = top + 'px';
  2147. }