File size: 9,554 Bytes
0deb5b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
 * @fileoverview JSME (JavaScript Molecule Editor) integration with Gradio interface
 * Handles bidirectional synchronization between JSME applet and Gradio textbox
 * @author Manny Cortes ('manny@derifyai.com')
 * @version 0.2.0
 */

// ============================================================================
// GLOBAL VARIABLES
// ============================================================================

/** @type {Object|null} The JSME applet instance */
let jsmeApplet = null;

/** @type {string} Last known value of the textbox to prevent infinite loops */
let lastTextboxValue = "";

// ============================================================================
// CONSTANTS
// ============================================================================

/** @const {string} Default SMILES for initial molecule (ethanol) */
const DEFAULT_SMILES = "CCO";

/** @const {string} Container height for JSME applet */
const CONTAINER_HEIGHT = "450px";

/** @const {string} CSS selector for the Gradio SMILES input element */
const SMILES_INPUT_SELECTOR = "#smiles_input textarea, #smiles_input input";

/** @const {number} Delay for paste event handling (ms) */
const PASTE_DELAY = 50;

/** @const {number} Delay for initialization retry (ms) */
const INIT_RETRY_DELAY = 2000;

/** @const {string[]} Events to trigger for Gradio change detection */
const GRADIO_CHANGE_EVENTS = ["input", "change", "keyup"];

// ============================================================================
// CORE INITIALIZATION
// ============================================================================

/**
 * Initializes the JSME applet after the library has been loaded
 * Sets up the molecular editor with default options and callbacks
 * @throws {Error} When JSME initialization fails
 */
function initializeJSME() {
  try {
    console.log("Initializing JSME...");
    // https://github.com/jsme-editor/jsme-editor.github.io
    // https://jsme-editor.github.io/dist/api_javadoc/index.html
    // http://wiki.jmol.org/index.php/Jmol_JavaScript_Object/JME/Options
    jsmeApplet = new JSApplet.JSME(
      "jsme_container",
      getJsmeContainerWidthPx(),
      CONTAINER_HEIGHT,
      {
        options:
          "rButton,zoom,zoomgui,newLook,star,multipart,polarnitro,NOexportInChI,NOexportInChIkey,NOsearchInChIkey,NOexportSVG,NOpaste",
      }
    );

    jsmeApplet.setCallBack("AfterStructureModified", handleJSMEStructureChange);
    jsmeApplet.setMenuScale(getJsmeGuiScale());
    jsmeApplet.setUserInterfaceBackgroundColor("#adadad");

    // Set initial molecule and sync state
    jsmeApplet.readGenericMolecularInput(DEFAULT_SMILES);
    lastTextboxValue = DEFAULT_SMILES;

    setupTextboxEventListeners();
    window.addEventListener("resize", handleResize);

    console.log("JSME initialized successfully");
  } catch (error) {
    console.error("Error initializing JSME:", error);
    throw error;
  }
}

/**
 * Handles structure changes in the JSME applet
 * Converts the structure to SMILES and updates the Gradio textbox
 * @param {Event} event - The JSME structure modification event
 */
function handleJSMEStructureChange(event) {
  try {
    const smiles = jsmeApplet.smiles();
    updateGradioTextbox(smiles);
  } catch (error) {
    console.error("Error getting SMILES from JSME:", error);
  }
}

/**
 * Calculates the appropriate GUI scale for the JSME applet based on container width
 * Uses breakpoints to determine optimal scaling for different screen sizes
 * @returns {number} The scale factor for the JSME GUI (0.88 to 2.0)
 */
function getJsmeGuiScale() {
  const width = getJsmeContainerWidthNumber();
  let menuScale;
  if (width > 460) {
    menuScale = 1.3;
  } else if (width > 420) {
    menuScale = 1.1;
  } else if (width > 370) {
    menuScale = 1.05;
  } else if (width > 300) {
    menuScale = 0.88;
  } else {
    menuScale = 2;
  }
  return menuScale;
}

/**
 * Gets the JSME container width as a CSS-compatible string value
 * Returns either a pixel value or percentage based on available width
 * @returns {string} Width as "100%" or "{width}px" format
 */
function getJsmeContainerWidthPx() {
  const parentWidth = getJsmeContainerWidthNumber();
  if (parentWidth == null || parentWidth <= 0) {
    return "100%";
  }
  return `${parentWidth}px`;
}

/**
 * Gets the numeric width of the JSME container's parent element
 * Used for responsive scaling calculations
 * @returns {number|null} Width in pixels, or null if container not found
 */
function getJsmeContainerWidthNumber() {
  const container = document.getElementById("jsme_container");
  if (!container) {
    return null;
  }
  return container.parentNode.offsetWidth;
}

// ============================================================================
// GRADIO INTEGRATION
// ============================================================================

/**
 * Updates the Gradio textbox with a SMILES string
 * Triggers appropriate events to ensure Gradio detects the change
 * @param {string} smiles - The SMILES string to set in the textbox
 */
function updateGradioTextbox(smiles) {
  try {
    const textbox = document.querySelector(SMILES_INPUT_SELECTOR);

    if (!textbox || textbox.value === smiles) {
      return;
    }

    textbox.value = smiles;
    lastTextboxValue = smiles;

    // Trigger events to ensure Gradio detects the change
    GRADIO_CHANGE_EVENTS.forEach((eventType) => {
      const event = new Event(eventType, {
        bubbles: true,
        cancelable: true,
      });
      textbox.dispatchEvent(event);
    });
  } catch (error) {
    console.error("Error updating Gradio textbox:", error);
  }
}

// ============================================================================
// JSME UPDATE FUNCTIONS
// ============================================================================

/**
 * Updates the JSME applet with a SMILES string from the textbox
 * @param {string} smiles - The SMILES string to display in JSME
 */
function updateJSMEFromTextbox(smiles) {
  if (!jsmeApplet) {
    return;
  }

  try {
    if (smiles && smiles.trim() !== "") {
      jsmeApplet.readGenericMolecularInput(smiles.trim());
    } else {
      jsmeApplet.reset();
    }
    lastTextboxValue = smiles;
  } catch (error) {
    console.error("Error updating JSME from textbox:", error);
  }
}

// ============================================================================
// UI MONITORING
// ============================================================================

/**
 * Finds the textbox element and sets up event listeners
 */
function setupTextboxEventListeners() {
  const textbox = document.querySelector(SMILES_INPUT_SELECTOR);
  if (!textbox) {
    return;
  }

  textbox.addEventListener("input", handleTextboxChange);
  textbox.addEventListener("change", handleTextboxChange);
  textbox.addEventListener("paste", handleTextboxPaste);
  textbox.addEventListener("keyup", handleTextboxChange);
}

/**
 * Handles textbox change events
 * @param {Event} event - The change event
 */
function handleTextboxChange(event) {
  if (event.target.value !== lastTextboxValue) {
    updateJSMEFromTextbox(event.target.value);
  }
}

/**
 * Handles textbox paste events with a delay to ensure content is available
 * @param {Event} event - The paste event
 */
function handleTextboxPaste(event) {
  setTimeout(() => {
    updateJSMEFromTextbox(event.target.value);
  }, PASTE_DELAY);
}

/**
 * Handles window resize events and updates JSME applet width
 */
function handleResize() {
  if (!jsmeApplet) {
    return;
  }

  try {
    jsmeApplet.setMenuScale(getJsmeGuiScale());
    jsmeApplet.setWidth(getJsmeContainerWidthPx());
  } catch (error) {
    console.error("Error resizing JSME applet:", error);
  }
}

// ============================================================================
// PUBLIC API
// ============================================================================

/**
 * Sets a SMILES string in both JSME and Gradio textbox
 * @param {string} smiles - The SMILES string to set
 * @returns {string} The SMILES string that was set
 * @public
 */
window.setJSMESmiles = function (smiles) {
  if (jsmeApplet) {
    updateJSMEFromTextbox(smiles);
  }

  updateGradioTextbox(smiles);
  return smiles;
};

/**
 * Clears both JSME and Gradio textbox
 * @returns {Array} Array containing cleared state for Gradio components
 * @public
 */
window.clearJSME = function () {
  if (jsmeApplet) {
    jsmeApplet.reset();
  }

  updateGradioTextbox("");
  return ["", [], [], "Cleared - Draw a new molecule or enter SMILES"];
};

// ============================================================================
// INITIALIZATION LOGIC
// ============================================================================

/**
 * Checks if JSME library is loaded and initializes JSME applet
 * Retries until the library becomes available
 */
function initializeWhenReady() {
  if (typeof JSApplet !== "undefined" && JSApplet.JSME) {
    console.log("JSME library loaded, initializing...");
    initializeJSME();
  } else {
    console.log("JSME library not ready, retrying...");
    setTimeout(initializeWhenReady, INIT_RETRY_DELAY);
  }
}

/**
 * Starts the initialization process based on document ready state
 */
function startInitialization() {
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => {
      setTimeout(initializeWhenReady, INIT_RETRY_DELAY);
    });
  } else {
    setTimeout(initializeWhenReady, INIT_RETRY_DELAY);
  }
}

startInitialization();