### Kekule.js Application DOM Ready Initialization Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/molIO.html Initializes the application by setting up an event listener for the file input to trigger local file loading, ensuring the setup occurs after the DOM is fully loaded. ```JavaScript function init() { document.getElementById('inputFile').addEventListener('change', function(){ runOperation('loadLocalFile'); }); } Kekule.X.domReady(init); ``` -------------------------------- ### Initialize Kekule.js Application Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/algorithm/structureSearch.html This function sets up the Kekule.js application by initializing the molecule grid, populating it with predefined structures, and attaching event listeners for user interactions like molecule selection (double-click) and triggering the search functionality. It uses Kekule.X.domReady to ensure all setup occurs after the DOM is fully loaded. ```JavaScript function init() { gridMol = Kekule.Widget.getWidgetById('gridMol'); fillGrid(gridMol); gridMol.addEventListener('dblclick', selectGridMol) var btn = Kekule.Widget.getWidgetById('btnSearch'); btn.addEventListener('execute', search); } Kekule.X.domReady(init); ``` -------------------------------- ### Initialize Tool Buttons and Predefined Settings for Kekule.js Chem Viewer Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/chemViewer.html Initializes the tool button setter and configures predefined settings for the Kekule.js Chem Viewer. It sets up an event listener for a 'Set Tool Buttons' button and defines a list of preset configurations (e.g., 'fullFunc', 'basic'). These presets are loaded into a select widget, allowing users to quickly apply different viewer configurations. The entire setup is executed when the DOM is ready via `Kekule.X.domReady(init)`. ```JavaScript initToolButtonSetter(); Kekule.Widget.getWidgetById('btnSetToolButtons').on('execute', function(){ runOperation('changeToolButtons'); }); var presets = ['', 'fullFunc', 'basic', 'static', 'editOnly']; var presetItems = []; for (var i = 0, l = presets.length; i < l; ++i) { presetItems.push({'value': presets[i]}); } Kekule.Widget.getWidgetById('selectPreset') .setItems(presetItems).setValue('') .on('valueChange', function(){ runOperation('changePredefinedSetting'); }); Kekule.X.domReady(init); ``` -------------------------------- ### Kekule.js Exception Handling and Logging Setup Source: https://github.com/partridgejiang/kekule.js/blob/master/test/lanTest/exceptionHandlerTest.html This snippet provides a complete example of setting up a custom exception handler for Kekule.js. It includes a utility 'log' function to display messages, an 'exceptionListener' that processes Kekule.Error and Kekule.Exception instances, extracting details like file name, line number, and raiser. It also shows three different ways to trigger exceptions using Kekule.raise(). ```javascript function log(msg) { var list = document.getElementById('logList'); var item = document.createElement('li'); item.innerHTML = msg; list.appendChild(item); } function exceptionListener(e) { if (e.exception instanceof Kekule.Error) ; else e.stop = true; var ex = e.exception; var msg = ex.getMessage(); msg += '
' + ex.fileName + ' ' + ex.lineNumber; msg += '
Raiser: ' + ex.raiserName; log(msg); log(ex.stack); } function raise1() { var e = new Kekule.Exception('This is an exception'); Kekule.raise(e); } function raise2() { var e = new Kekule.Error('This is an error'); Kekule.raise(e); } function raise3() { Kekule.raise('implicit exception'); } Kekule.exceptionHandler.addEventListener('exceptionThrown', exceptionListener); ``` -------------------------------- ### Load Specific Kekule.js Modules via HTML Script Tag Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/installation.rst These HTML examples illustrate how to load only specific Kekule.js modules using the `kekule.js` bootstrap file with URL parameters. This method allows for reduced payload size and can also be used to specify localization settings. ```html ``` ```html ``` -------------------------------- ### Install Kekule.js Package via npm Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/installation.rst This command installs the Kekule.js package using npm, saving it as a dependency in your project's `package.json` file. It's the recommended way for modern JavaScript projects. ```shell npm install --save kekule ``` -------------------------------- ### JavaScript Function Definition Example Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/chemNote/chemNote.html Illustrates a simple JavaScript function named `example` that returns a boolean value. This snippet demonstrates basic function syntax. ```JavaScript function example() { return true; } ``` -------------------------------- ### Orchestrate Three.js Scene Initialization and Rendering Source: https://github.com/partridgejiang/kekule.js/blob/master/test/misc/threeRendererTest.html This function orchestrates the entire Three.js setup process. It calls all initialization functions for the renderer, camera, scene, light, and objects, then renders the scene from the camera's perspective. ```javascript function threeStart() { initThree(); initCamera(); initScene(); initLight(); initObject(); //renderer.clear(); renderer.render(scene, camera); } ``` -------------------------------- ### CSS Styling for Kekule.js Viewer and Code Display Layout Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/chemViewer.html CSS rules defining the layout and appearance of the chemical viewer and code display areas, including dimensions, borders, floating behavior, and font styles for a Kekule.js tutorial example. ```CSS p { margin: 0.3em 0.5em; } #chemViewer, #codeViewer { height: 350px; border: 1px solid black; float: left; } #chemViewer { width: 550px; } #codeViewer { width: 450px; font-family: "Courier New", Courier, monospace; white-space: pre; } .FloatClearer { clear: both; } #setter { max-width: 1000px; } #panelToolButtons { overflow: hidden; } .ToolButtonSetter { width: 12em; } ``` -------------------------------- ### Draw Kekule.js Text Block Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/renderMol.html Illustrates the creation and rendering of a simple `Kekule.TextBlock` object containing the text 'Example'. The text block is drawn in 2D using the `drawObj` utility function. ```JavaScript function drawText() { // create text block var textBlock = new Kekule.TextBlock(); textBlock.setText('Example'); // draw on screen drawObj(textBlock, Kekule.Render.RendererType.R2D); } ``` -------------------------------- ### Initialize Kekule.js Application on DOM Ready Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/algorithm/reactionExercise.html The `init` function serves as the main entry point for the Kekule.js application, executed once the DOM is fully loaded. It orchestrates the initial setup by calling `loadKeys` to fetch chemical data, `prepareViewers` to set up the UI, and attaches event listeners to 'btnToggleKeys' and 'btnCheckAnswers' for user interaction. ```javascript function init() { loadKeys(); prepareViewers(); Kekule.Widget.getWidgetById('btnToggleKeys').addEventListener('execute', toggleKeys); Kekule.Widget.getWidgetById('btnCheckAnswers').addEventListener('execute', checkAnswers); } Kekule.X.domReady(init); ``` -------------------------------- ### Run JSTest Example Tests with Rake Source: https://github.com/partridgejiang/kekule.js/blob/master/test/JSTest/README.md To execute the example test cases provided with JSTest, navigate to the project root and use the 'rake test' command. This requires the Rake build automation tool to be installed. ```Ruby rake test ``` -------------------------------- ### Basic DOM Element Retrieval Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/algorithm/structureSearch.html A simple utility function to get a DOM element by its ID, commonly used for quick access to HTML elements. ```JavaScript function $(id) { return document.getElementById(id); } ``` -------------------------------- ### Example Console Output for Kekule.js Ring Analysis Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/getMolInfo.rst This snippet shows the expected console output when analyzing rings in phenanthrene using Kekule.js, demonstrating the total ring count and counts for specific ring sizes. ```text Find 6 rings ring with 6 atoms: 3 ring with 10 atoms: 2 ring with 14 atoms: 1 ``` -------------------------------- ### Initialize Kekule.js Application and Load Molecule Files Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/renderMol.html Initializes the application by setting up event listeners for 'Draw 2D Molecule' and 'Draw 3D Molecule' buttons. It uses `Kekule.ActionFileOpen` to handle file selection and `Kekule.IO.loadFileData` to load molecule data, subsequently drawing the loaded molecule. ```JavaScript function init() { var btn2D = Kekule.Widget.getWidgetById('btnDraw2D'); var btn3D = Kekule.Widget.getWidgetById('btnDraw3D'); var actionOpenFile = new Kekule.ActionFileOpen(); actionOpenFile.on('open', function(event){ var renderType = (event.invoker === btn3D)? Kekule.Render.RendererType.R3D: Kekule.Render.RendererType.R2D; // load molecule from file Kekule.IO.loadFileData(event.file, function(mol, success){ if (mol && success) // now we can draw it { drawObj(mol, renderType); } }); }); btn2D.setAction(actionOpenFile); btn3D.setAction(actionOpenFile); } Kekule.X.domReady(init); ``` -------------------------------- ### Load Full Kekule.js Package via HTML Script Tag Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/installation.rst These HTML snippets demonstrate how to include the full Kekule.js library and its default theme directly in an HTML page using `` and ` ``` ```html ``` -------------------------------- ### Import Full Kekule.js Package in JavaScript Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/installation.rst These examples demonstrate how to import the entire Kekule.js package along with its default theme into your JavaScript project. Both ES module `import` and CommonJS `require` syntaxes are provided, suitable for different module environments. ```javascript import { Kekule } from 'kekule'; import 'kekule/theme/default'; // if Kekule widgets is used in browser, the theme CSS should be imported as well console.log(Kekule.VERSION); ``` ```javascript let Kekule = require('kekule').Kekule; require('kekule/theme/default'); // if Kekule widgets is used in browser, the theme CSS should be imported as well console.log(Kekule.VERSION); ``` -------------------------------- ### Apply Predefined Settings to Kekule.js Composer Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/composer.rst Shows how to apply a predefined configuration preset, such as 'fullFunc', to the Kekule.js composer widget using the `setPredefinedSetting` method for quick setup. ```JavaScript // change to preset fullFunc composer.setPredefinedSetting('fullFunc'); ``` -------------------------------- ### Example Console Output for Kekule.js SSSR Ring Analysis Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/getMolInfo.rst This snippet shows the expected console output when analyzing SSSR rings in phenanthrene using Kekule.js, demonstrating the total SSSR ring count and counts for specific ring sizes. ```text Find 3 SSSR rings ring with 6 atoms: 3 ``` -------------------------------- ### Kekule.js Viewer Initialization and Resizing Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/openbabel/openBabel.html Initializes the Kekule.js chemical viewer by retrieving it by ID and sets up dynamic resizing. The `adjustSize` function calculates viewport dimensions and updates the viewer's width and height accordingly, ensuring it fits the available screen space and responds to window resizing. ```JavaScript var chemViewer; function init() { chemViewer = Kekule.Widget.getWidgetById('chemViewer'); // adjust size adjustSize(); window.onresize = adjustSize; } function adjustSize() { var dim = Kekule.HtmlElementUtils.getViewportDimension(document); chemViewer.setWidth(dim.width - 20 + 'px').setHeight(dim.height - 50 + 'px'); } Kekule.X.domReady(init); ``` -------------------------------- ### Set and Get Chemical Objects in Kekule.js Chem Viewer Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/chemViewer.rst Provides examples of how to programmatically set a new chemical object (e.g., a molecule from CML data) into the viewer and retrieve the currently displayed object, then save it back to CML format. ```JavaScript // set new object in viewer var cmlData = ''; var myMolecule = Kekule.IO.loadFormatData(cmlData, 'cml'); chemViewer.setChemObj(myMolecule); // get object in viewer var molecule = chemViewer.getChemObj(); // and save molecule in CML var cmlData = Kekule.IO.saveFormatData(obj, 'cml'); console.log(cmlData); ``` -------------------------------- ### Kekule.js Viewer Initialization and Dynamic Resizing Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/chemViewer/chemViewer3D.html Initializes the Kekule.js chemical viewer, retrieves its instance by ID, and sets up dynamic resizing based on the window's dimensions. It also includes an event listener for a button ('btnOpenBabel') to enable OpenBabel format support, demonstrating integration with external libraries. ```JavaScript var chemViewer; function init() { chemViewer = Kekule.Widget.getWidgetById('chemViewer'); // adjust size adjustSize(); window.onresize = adjustSize; Kekule.Widget.getWidgetById('btnOpenBabel').addEventListener('execute', function(e){ Kekule.IO.enableOpenBabelFormats(); }); } function adjustSize() { var dim = Kekule.HtmlElementUtils.getViewportDimension(document); var headerDim = Kekule.HtmlElementUtils.getElemClientDimension(document.getElementById('header')); chemViewer.setWidth(dim.width - 10 + 'px').setHeight(dim.height - 10 - headerDim.height + 'px'); } Kekule.X.domReady(init); ``` -------------------------------- ### Kekule.js UI Utility Functions Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/renderMol.html Provides helper functions to retrieve the code viewer widget by ID, display the string representation of a function's code, and get the drawing parent HTML element for Kekule.js rendering. ```JavaScript function getCodeViewer() { return Kekule.Widget.getWidgetById('codeViewer'); } function showCode(func) { getCodeViewer().setValue(func.toString()); } function getDrawParentElem() { return document.getElementById('stage'); } ``` -------------------------------- ### OpenAIModel Class Constructor API Reference Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/chemNote/chemNote.html Detailed API documentation for the `__init__` method of the `OpenAIModel` class. It specifies the `model_name` and optional `provider` parameters, along with their types and descriptions. ```APIDOC OpenAIModel: __init__(model_name: str, provider: str = 'openai') model_name: The name of the OpenAI model to use provider: The provider to use (defaults to 'openai') ``` -------------------------------- ### Initialize Kekule.js Drag Helper Source: https://github.com/partridgejiang/kekule.js/blob/master/test/widgetTest/commonCtrls/moverTest.html Initializes the Kekule.js `MoveHelper` to enable dragging functionality for a specified target element using a gripper handle. It ensures the setup runs after the DOM is fully loaded, attaching the drag behavior to the designated elements. ```JavaScript var moveHelper; function init() { var target = document.getElementById('target'); var gripper = document.getElementById('gripper'); moveHelper = new Kekule.Widget.MoveHelper(target, gripper); //moveHelper.setCssPropX('right'); //moveHelper.setCssPropY('bottom'); } Kekule.X.domReady(init); ``` -------------------------------- ### Initialize Kekule.js Viewers with Empty Molecules Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/algorithm/reactionExercise.html The `prepareViewers` function initializes all designated Kekule.js widget viewers. It iterates through `viewerAnswerIds`, retrieves each viewer by its ID, and sets an empty `Kekule.Molecule` object as its chemical content, preparing them for user input. ```javascript function prepareViewers() { for (var i = 0; i < viewerAnswerIds.length; ++i) { var viewerId = viewerAnswerIds[i]; var viewer = Kekule.Widget.getWidgetById(viewerId); var mol = new Kekule.Molecule(); //mol.createCtab(); viewer.setChemObj(mol); } } ``` -------------------------------- ### Define a JSTest Test Case Source: https://github.com/partridgejiang/kekule.js/blob/master/test/JSTest/README.md This example illustrates the structure of a JSTest.TestCase, including optional lifecycle methods like 'init', 'setup', 'cleanup', and 'teardown', which are called at different stages of the test execution, along with individual test functions. ```JavaScript var MyTestCase = JSTest.TestCase({ name: 'My Custom Test Case Name', init: function () { // this is called only once, before any tests are run }, setup: function () { // this is called before every test }, cleanup: function () { // this is called after every test }, teardown: function () { // this is called only once, after all tests have been run }, testSomething: function () { // this is a test }, testSomethingElse: function () { // this is another test } }); ``` -------------------------------- ### Import Specific Kekule.js Modules in JavaScript Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/installation.rst These snippets show how to import only specific Kekule.js modules, such as IO and ChemWidget, to reduce the overall bundle size and improve tree-shaking efficiency. Examples are provided for both ES module and CommonJS environments, including loading localization data. ```javascript // Import IO and ChemWidget modules (and their prerequisites) only import { Kekule } from './node_modules/kekule/dist/jsmods/io.esm.mjs'; import './node_modules/kekule/dist/jsmods/spectroscopy.esm.mjs'; // Yes, no need to set Kekule here again // Also load the Chinese(zh-CN) language data resource import './node_modules/kekule/dist/jsmods/localizationData.zh.esm.mjs'; import 'Kekule/theme/default'; ``` ```javascript // Import IO and ChemWidget modules (and their prerequisites) only let Kekule = require('./node_modules/kekule/dist/jsmods/io.cm.js').Kekule; require('./node_modules/kekule/dist/jsmods/chemWidget.cm.js'); // No need to set Kekule here again // Also load the Chinese(zh-CN) language data resource require('./node_modules/kekule/dist/jsmods/localizationData.zh.cm.js'); require('Kekule/theme/default'); ``` -------------------------------- ### Initialize Kekule.js Viewer UI Elements and Event Handlers Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/chemViewer.html The `init` function sets up various user interface controls for the Kekule.js chemical viewer and attaches event listeners to them. It handles operations like loading files, changing render types, enabling autofit, adjusting colors, toggling direct interaction, enabling/disabling the toolbar, setting zoom ratios, and configuring 2D/3D molecule display types, as well as binding rotation buttons. ```javascript function init() { document.getElementById('inputFile').addEventListener('change', function() { runOperation('loadFromFile'); }); document.getElementById('selectRenderType').addEventListener('change', function() { runOperation('changeRenderType'); }); document.getElementById('checkBoxAutofit').addEventListener('change', function() { runOperation('changeAutofit'); }); document.getElementById('checkBoxSpecifiedColor').addEventListener('change', function() { runOperation('changeRenderColor'); }); document.getElementById('checkBoxDirectInteraction').addEventListener('change', function() { runOperation('changeDirectInteraction'); }); document.getElementById('checkBoxDirectInteraction').checked = getChemViewer().getEnableDirectInteraction(); document.getElementById('checkBoxEnableToolbar').addEventListener('change', function() { runOperation('changeEnableToolbar'); }); document.getElementById('checkBoxEnableToolbar').checked = getChemViewer().getEnableToolbar(); var zoomRatios = Kekule.ZoomUtils.PREDEFINED_ZOOM_RATIOS; var zoomItems = []; for (var i = 0, l = zoomRatios.length; i < l; ++i) { var zoom = zoomRatios[i]; zoomItems.push({'text': Math.round(zoom * 100) + '%', 'value': zoom}); } Kekule.Widget.getWidgetById('selectZoomRatio') .setItems(zoomItems).setValue(getChemViewer().getZoom() || 1) .on('valueChange', function(){ runOperation('zoomToRatio'); }); var mol2DDisplayTypes = ['skeletal', 'condensed']; var mol3DDisplayTypes = ['wire', 'sticks', 'ball_stick', 'space_fill']; var disTypeItems = []; for (var i = 0, l = mol2DDisplayTypes.length; i < l; ++i) { disTypeItems.push({'value': mol2DDisplayTypes[i]}); } Kekule.Widget.getWidgetById('selectMol2DDisplayType') .setItems(disTypeItems) .on('valueChange', function(){ runOperation('changeMol2DDisplayType'); }); var disTypeItems = []; for (var i = 0, l = mol3DDisplayTypes.length; i < l; ++i) { disTypeItems.push({'value': mol3DDisplayTypes[i]}); } Kekule.Widget.getWidgetById('selectMol3DDisplayType') .setItems(disTypeItems) .on('valueChange', function(){ runOperation('changeMol3DDisplayType'); }); Kekule.Widget.getWidgetById('selectBondColor').on('valueChange', function(){ runOperation('changeRenderColor'); }); Kekule.Widget.getWidgetById('selectAtomColor').on('valueChange', function(){ runOperation('changeRenderColor'); }); Kekule.Widget.getWidgetById('btnRotate2D').on('execute', function(){ runOperation('rotate2D'); }); Kekule.Widget.getWidgetById('btnRotateX').on('execute', function(){ runOperation('rotateX'); }); Kekule.Widget.getWidgetById('btnRotateY').on('exec ``` -------------------------------- ### Create Basic Molecule with Kekule.js Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/creatingMol.html This JavaScript function demonstrates how to construct a simple molecule using Kekule.js. It involves creating Kekule.Molecule, Kekule.Atom, and Kekule.Bond objects, setting their properties like symbol, coordinates, and bond order, and then appending them to the molecule. ```JavaScript function createBasicMolecule() { // create molecule first var mol = new Kekule.Molecule(); // add three atoms to molecule, property setter can be called cascadely var a1 = (new Kekule.Atom()).setSymbol('C').setCoord2D({'x': -0.4, 'y': 0.23}); var a2 = (new Kekule.Atom()).setSymbol('C').setCoord2D({'x': 0.4, 'y': 0.23}); var a3 = (new Kekule.Atom()).setSymbol('O').setCoord2D({'x': 0, 'y': -0.46}); mol.appendNode(a1); mol.appendNode(a2); mol.appendNode(a3); // add three bonds to molecule var b1 = (new Kekule.Bond()).setBondOrder(1).setConnectedObjs([a1, a2]); var b2 = (new Kekule.Bond()).setBondOrder(1).setConnectedObjs([a2, a3]); var b3 = (new Kekule.Bond()).setBondOrder(1).setConnectedObjs([a3, a1]); mol.appendConnector(b1); mol.appendConnector(b2); mol.appendConnector(b3); return mol; } ``` -------------------------------- ### Iterate Through Spectrum Data Section in JavaScript Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/chemViewer/spectrumViewer.html This example illustrates how to obtain the active data section of a spectrum and then loop through its individual data points. It uses `getActiveDataSection()` to get the section, `getDataCount()` to determine the number of points, and `getValueAt(i)` to retrieve each data value by index. ```JavaScript var section = spectrum.getActiveDataSection(); for (var i = 0, l = section.getDataCount(); i < l; ++i){ var value = section.getValueAt(i); } ``` -------------------------------- ### Dynamically Load Kekule.js Modules in JavaScript Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/installation.rst These JavaScript snippets demonstrate how to dynamically load additional Kekule.js modules at runtime using `Kekule.modules()`. This is useful for loading features on demand, including specialized modules like OpenBabel WebAssembly components. ```javascript Kekule.modules(['algorithm', 'calculation'], function(error) { if (!error) { // algorithm and calculation modules loaded successfully, functions can be used now. } }); ``` ```javascript Kekule.OpenBabel.enable(error => { if (!error) { console.log('OpenBabel wasm loaded and can be accessed!'); } }); ``` -------------------------------- ### Removing Atoms and Bonds from a Kekule.js Molecule Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/molCreation.rst This example illustrates how to remove existing atoms and bonds from a Kekule.Molecule instance in Kekule.js. It demonstrates using removeNodeAt() and removeConnectorAt() methods, which take an index, or removeNode() and removeConnector() which take the object itself, to modify the molecule's structure. The atom index starts from 0. ```JavaScript // remove atom O related bonds in molecule mol.removeNodeAt(2); // the atom index starts from 0 // or mol.removeNode(mol.getNodeAt(2)); mol.removeConnectorAt(1); // or mol.removeConnector(mol.getConnectorAt(1)); mol.removeConnectorAt(2); ``` -------------------------------- ### Execute Kekule.js Initialization on DOM Ready Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/chemViewer/mirrorViewer.html This line uses Kekule.js's utility function to ensure that the `init` function, which sets up the chemical viewers and their functionalities, is executed only after the entire HTML document has been fully loaded and parsed. This prevents errors that might occur if the script tries to access DOM elements before they exist. ```JavaScript Kekule.X.domReady(init); ``` -------------------------------- ### Initialize and Update Kekule.js Viewer Toolbar Buttons Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/chemViewer.html This set of functions manages the display and configuration of individual buttons on the Kekule.js chemical viewer's toolbar. `initToolButtonSetter` creates checkboxes for each available button, allowing users to toggle their visibility, and `changeToolButtons` applies the selected button set to the viewer. ```javascript var toolBtns = [ 'loadData', 'saveData', 'clearObjs', 'molDisplayType', 'zoomIn', 'zoomOut', 'rotateLeft', 'rotateRight', 'rotateX', 'rotateY', 'rotateZ', 'reset', 'molHideHydrogens', 'openEditor', 'config', 'custom' ]; var toolBtnSetCheckBoxes = []; function changeToolButtons() { var btns = []; // gather buttons for (var i = 0, l = toolBtnSetCheckBoxes.length; i < l; ++i) { var checkBox = toolBtnSetCheckBoxes[i]; if (checkBox.getChecked()) btns.push(checkBox._value || checkBox.getValue()); } // set tool buttons of chem viewer getChemViewer().setToolButtons(btns); } function initToolButtonSetter() { var chemViewer = getChemViewer(); var btns = toolBtns; var currBtns = chemViewer.getToolButtons() || chemViewer.getDefaultToolBarButtons(); var parentElem = document.getElementById('panelToolButtons'); for (var i = 0, l = btns.length; i < l; ++i) { var btnName = btns[i]; // create check box widget var checkBox = new Kekule.Widget.CheckBox(document); checkBox.addClassName('ToolButtonSetter'); checkBox.setText(btnName); checkBox.setValue(btnName); if (btnName === 'custom') // custom button checkBox._value = {'text': 'Custom', 'htmlClass': 'K-Res-Button-YesOk', 'showText': true, '#execute': function(){ alert('Custom button'); } }; else // default button checkBox._value = btnName; if (currBtns.indexOf(btnName) >= 0) checkBox.setChecked(true); checkBox.appendToElem(parentElem); toolBtnSetCheckBoxes.push(checkBox); } } ``` -------------------------------- ### JavaScript Utility Functions for Kekule.js Viewer Interaction Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/chemViewer.html A set of JavaScript functions to retrieve Kekule.js viewer and code display widgets, get the current chemical object, display code, and execute functions dynamically. These are essential for programmatic control and interaction within a Kekule.js application. ```JavaScript function getCurrMol() { return getChemViewer().getChemObj(); } ``` ```JavaScript function getChemViewer() { return Kekule.Widget.getWidgetById('chemViewer'); } ``` ```JavaScript function getCodeViewer() { return Kekule.Widget.getWidgetById('codeViewer'); } ``` ```JavaScript function showCode(code) { getCodeViewer().setValue(code); } ``` ```JavaScript function getFuncCode(func) { return func.toString(); } ``` ```JavaScript function runOperation(funcName) { var func = this[funcName]; func(); // show function code in text area var code = func.toString(); showCode(code); } ``` ```JavaScript function loadFromFile() { // get local file object var file = document.getElementBy ``` -------------------------------- ### JavaScript DOM Event Listener Setup Source: https://github.com/partridgejiang/kekule.js/blob/master/test/misc/keyEventTest.html Initializes event listeners on the document body and a specific element (`#stage2`) for `keydown`, `focusin`, and `focusout` events. It logs various event properties to the console, including key codes, key names, and event flags. Includes commented-out examples for `keypress` and `keyup` events. ```JavaScript function $(id) { return document.getElementById(id); } function init() { document.body.addEventListener('keydown', function(e){ console.log('key down', e.target.id, e.keyCode, e.charCode, e.key, e.code, e.shiftKey, e.ctrlKey, e.altKey, e.metaKey, e.repeat); console.log('event flags: ', 'cancelBubble: ', e.cancelBubble, 'bubbles: ', e.bubbles, 'cancelble: ', e.cancelable); }); $('stage2').addEventListener('keydown', function(e){ console.log('key down on stage 2', e.target.id, e.keyCode, e.charCode, e.key, e.code, e.shiftKey, e.ctrlKey, e.altKey, e.metaKey, e.repeat); }); /* document.body.addEventListener('keypress', function(e){ console.log('key press', e.keyCode, e.charCode, e.key, e.code, e.shiftKey, e.ctrlKey, e.altKey); }); document.body.addEventListener('keyup', function(e){ console.log('key up', e.keyCode, e.charCode, e.key, e.code, e.shiftKey, e.ctrlKey, e.altKey); }); */ /* document.body.addEventListener('keypress', function(e){ console.log('key press', e.keyCode, e.charCode, e.key, e.code); }); */ document.body.addEventListener('focusin', function(e){ console.log('focus', e.target.id); }); document.body.addEventListener('focusout', function(e){ console.log('blur', e.target.id); }); } ``` -------------------------------- ### Initialize Three.js Scene Source: https://github.com/partridgejiang/kekule.js/blob/master/test/misc/threeRendererTest.html Creates a new Three.js scene object. The scene acts as a container for all objects, cameras, and lights in the 3D environment. ```javascript var scene; function initScene() { scene = new THREE.Scene(); } ``` -------------------------------- ### Load Molecule from Direct External File Path in Kekule.js Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/molIO.html Shows how to load a molecule directly from a file path without an explicit HTML element, and displays the corresponding loader code. ```JavaScript function loadDirectExternalResource() { loadMolFromResource('url(data/mol2D/cyclohextone.mol)'); showResLoaderCode('url(data/mol2D/cyclohextone.mol)', ''); } ``` -------------------------------- ### Create Molecule with Diverse Atom Types in Kekule.js Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/creatingMol.html This JavaScript function shows how to build a Kekule.js molecule incorporating different types of nodes, such as atoms with explicit mass numbers, pseudoatoms (e.g., 'ANY'), and variable atoms (e.g., 'F', 'Cl', 'Br'). It also demonstrates using the `appendBond` shortcut method. ```JavaScript function createMolWithMoreTypesOfNodes() { // create molecule var mol = new Kekule.Molecule(); // add atoms to molecule mol.appendNode(new Kekule.Atom().setSymbol('C').setCoord2D({x: 0, y: 0.80})); // explicit set mass number of an atom mol.appendNode(new Kekule.Atom().setSymbol('C').setMassNumber(13).setCoord2D({x: -0.69, y: 0.40})); mol.appendNode(new Kekule.Atom().setSymbol('C').setCoord2D({x: -0.69, y: -0.40})); // a pseudo atom mol.appendNode(new Kekule.Pseudoatom().setAtomType(Kekule.PseudoatomType.ANY).setCoord2D({x: 0, y: -0.80})); mol.appendNode(new Kekule.Atom().setSymbol('C').setCoord2D({x: 0.69, y: -0.40})); mol.appendNode(new Kekule.Atom().setSymbol('C').setCoord2D({x: 0.69, y: 0.40})); // a variable atom mol.appendNode(new Kekule.VariableAtom().setAllowedIsotopeIds(['F', 'Cl', 'Br']).setCoord2D({x: 1.39, y: 0.80})); // add bonds to molecule // here a shortcut method appendBond(atomIndexes, bondOrder) is used mol.appendBond([0, 1], 1); mol.appendBond([1, 2], 2); mol.appendBond([2, 3], 1); mol.appendBond([3, 4], 2); mol.appendBond([4, 5], 1); mol.appendBond([5, 0], 2); mol.appendBond([5, 6], 1); return mol; } ``` -------------------------------- ### Global Variable Setup for XML/CML Parsing Source: https://github.com/partridgejiang/kekule.js/blob/master/test/lanTest/namespaceTest2.html This snippet defines global variables used throughout the XML/CML parsing and manipulation examples. `preText` holds a sample CML XML string, `xmlDoc` will store the parsed XML document, and `nsCml` and `nsDc` define the CML and Dublin Core XML namespaces, respectively. ```javascript var preText = 'test file for http://www.xml-cml.org/conventions/molecular conventionvalid molecularJ A TownsendCopyright J A Townsend jat45@cantab.net 2009.2009-01-21'; var xmlDoc; var nsCml = 'http://www.xml-cml.org/schema'; var nsDc = 'http://purl.org/dc/elements/1.1/'; ``` -------------------------------- ### Create and Configure Kekule.js Periodic Table Widget in JavaScript Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/widgetIntro.rst This JavaScript snippet demonstrates how to instantiate a Kekule.ChemWidget.PeriodicTable widget, configure its properties like enabling selection and displaying specific components, and append it to an HTML element. ```JavaScript var widget = new Kekule.ChemWidget.PeriodicTable(document); widget.setEnableSelect(true) .setDisplayedComponents(['symbol', 'name', 'atomicNumber']) .appendToElem(document.getElementById('parent')); // append to HTML element ``` -------------------------------- ### Execute Operations and Display Source Code in Kekule.js Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/molIO.html Functions to execute a specified operation, display the resulting molecule in the viewer, and show the source code of the executed function or resource loader in the code viewer. ```JavaScript function showResLoaderCode(resId, resContent, loadFunc) { if (!loadFunc) loadFunc = loadMolFromResource; var funcCodes = loadFunc.toString().split('\n'); funcCodes.splice(0, 2); funcCodes.pop(); var funcCode = funcCodes.join('\n'); var code = '[Resource Definition]\n\n' + resContent + '\n\n'; code += '========================================\n\n'; code += '[JavaScript Code]\n\n'; code += '\tvar resId = \'' + resId + '\';\n'; code += funcCode; showCode(code); } function runOperation(funcName) { var func = this[funcName]; var mol = func(); if (mol) { // show molecule in chem viewer showMolecule(mol); } // show function code in text area var code = func.toString(); showCode(code); } ``` -------------------------------- ### Install Kekule.js using npm Source: https://github.com/partridgejiang/kekule.js/blob/master/README.md Installs the Kekule.js package and saves it as a dependency in your project. ```shell npm install --save kekule ``` -------------------------------- ### Load Chemical Data from File into Kekule.js Viewer Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/chemViewer.html This function loads a chemical file selected by the user, parses its data using Kekule.IO.loadFileData, and then displays the resulting chemical object in the Kekule.js viewer. It handles successful loading and updates the viewer. ```javascript function loadFile() { var file = Id('inputFile').files[0]; if (file) { // load file and parse to chem object Kekule.IO.loadFileData(file, function(chemObj, success) { // load chem object into chem viewer if (success && chemObj) getChemViewer().setChemObj(chemObj); }); } } ``` -------------------------------- ### Load and Display Image from File with Kekule.js Source: https://github.com/partridgejiang/kekule.js/blob/master/test/widgetTest/misc/imageInfo.html This snippet provides two JavaScript functions: `loadImgFromFile` and `init`. The `loadImgFromFile` function reads a selected file as a Data URL, sets it as the source for an image element, and then logs the image's width and height. The `init` function sets up a file open button using `Kekule.js` widgets and actions, triggering `loadImgFromFile` when a file is selected. The entire setup runs once the DOM is ready. ```javascript function loadImgFromFile(file) { var reader = new FileReader(); reader.addEventListener('load', function(){ var imgElem = document.getElementById('image'); imgElem.src = reader.result; (function(){ console.log(imgElem.width, imgElem.height); }).defer(); }); reader.readAsDataURL(file); } function init() { var btnOpen = Kekule.Widget.getWidgetById('btnOpen'); // create open file action var action = new Kekule.ActionFileOpen(); btnOpen.setAction(action); action.on('open', function(e){ var file = e.file; loadImgFromFile(file); }); } Kekule.X.domReady(init); ``` -------------------------------- ### Load Molecule from External HTML Link Resource in Kekule.js Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/molIO.html Illustrates loading a molecule from an external file referenced by an HTML link element's href attribute, along with displaying the resource definition and loader code. ```JavaScript function loadExternalResource() { loadMolFromResource('url(#molResExternalLink)'); var resContent = ''; showResLoaderCode('url(#molResExternalLink)', resContent); } ``` -------------------------------- ### Kekule.js Bond Object JSON Structure Example Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/chemViewer/moleculeViewer.html An example of the JSON serialization for Kekule.Bond objects. Each object represents a chemical bond with properties like `__type__` (identifying it as Kekule.Bond), `parity`, `bondType` (e.g., 'covalent'), `bondOrder`, `electronCount`, `isInAromaticRing`, and `connectedNodes` (an array of node IDs). This snippet is a fragment from a larger molecular data serialization. ```JSON nnectedNodes\":\[96,107\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[97,108\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[100,109\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[103,110\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[103,111\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[103,112\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[104,113\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[106,114\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[110,115\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[110,116\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[110,117\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[111,118\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[113,115\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[113,119\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[113,120\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\"connectedNodes\":\[114,121\]},{ \"\_\_type\_\_\":\"Kekule.Bond\",\"parity\":null,\"bondType\":\"covalent\",\"bondOrder\":1,\"electronCount\":2,\"isInAromaticRing\":false,\ ``` -------------------------------- ### Load Chemical Reaction Key Structures in Kekule.js Source: https://github.com/partridgejiang/kekule.js/blob/master/demos/items/algorithm/reactionExercise.html This code block asynchronously loads chemical reaction key structures from predefined URLs. It iterates through `keyResUrls`, fetches each resource using `Kekule.PredefinedResReferer.loadResource`, and stores the loaded chemical objects in the `productKeys` global object, indexed by their URI. ```javascript for (var i = 0, l = keyResUrls.length; i < l; ++i) { var ks = Kekule.ArrayUtils.toArray(keyResUrls[i]); for (var j = 0, k = ks.length; j < k; ++j) { var id = ks[j]; var resUrl = 'url(' + id + ')'; Kekule.PredefinedResReferer.loadResource(resUrl, function(resInfo, success) { if (success) { var chemObj = Kekule.IO.loadTypedData(resInfo.data, resInfo.resType, resInfo.resUri); productKeys[resInfo.resUri] = chemObj; } }, null, document); } } ``` -------------------------------- ### Get Parent Fragment of Kekule.js Atom or Bond Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/content/getMolInfo.rst This code illustrates how to obtain the parent molecule or structure fragment to which an atom or bond belongs using the `getParentFragment` method. ```JavaScript var mol = atom.getParentFragment(); var mol = bond.getParentFragment(); ``` -------------------------------- ### Apply Predefined Settings to Kekule.js Chemical Viewer Source: https://github.com/partridgejiang/kekule.js/blob/master/tutorial/source/_extra/examples/chemViewer.html This function applies a predefined configuration preset to the Kekule.js chemical viewer. It retrieves the selected preset name from a UI element and uses `chemViewer.setPredefinedSetting()` to update the viewer's behavior and appearance. ```javascript function changePredefinedSetting() { var chemViewer = getChemViewer(); var preset = document.getElementById('selectPreset').value; chemViewer.setPredefinedSetting(preset); } ```