在blog中渲染chem对象
在blog中渲染chem对象
截图截累了,研究研究怎么基于chemdoodle.js在blog中渲染chem对象。
配置
基础建设
首先是chemdoodle,把js和css放到对应位置,创建_include/chemdoodle.html:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<link rel="stylesheet" href="/assets/css/ChemDoodleWeb.css" type="text/css">
<link rel="stylesheet" href="/assets/css/jquery-ui-1.11.4.css" type="text/css">
<script src="/assets/js/data/ChemDoodleWeb.js"></script>
<script src="/assets/js/data/ChemDoodleWeb-uis.js"></script>
<script src="/assets/js/data/openchemlib-minimal.js"></script>
<script defer src="/assets/js/data/chem-codeblock.js"></script>
<style>
.molecule-container {
text-align: center;
margin: 20px 0;
}
.canvas-container {
display: inline-block;
border: 1px solid #ddd;
border-radius: 4px;
}
</style>
然后是方便引用的liquid模板_include/xyz.html:
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
<div class="molecule-container">
<div class="canvas-container">
{% assign unique_id = include.id | default: 'mol' %}
{% unless include.id %}
{% assign content_hash = include.xyz | append: include.mol | append: include.smiles | append: include.representation | append: include.bgcolor | size %}
{% assign unique_id = unique_id | append: '_' | append: content_hash | append: '_' | append: include.mode %}
{% endunless %}
{% if include.mode == '2d' %}
<canvas id="viewACS_{{ unique_id }}" width="{{ include.width | default: 400 }}" height="{{ include.height | default: 300 }}"></canvas>
{% elsif include.mode == '3d' %}
<canvas id="transform3d_{{ unique_id }}" width="{{ include.width | default: 400 }}" height="{{ include.height | default: 400 }}"></canvas>
{% endif %}
</div>
</div>
{% if include.mol %}
<pre class="chem-mol-data" hidden aria-hidden="true">{{ include.mol | escape }}</pre>
{% endif %}
<script>
function readMolDataNearCurrentScript() {
var script = document.currentScript;
var node = script ? script.previousElementSibling : null;
if (node && node.classList && node.classList.contains('chem-mol-data')) {
return node.textContent || '';
}
return '';
}
function normalizeMolBlock(rawMol) {
if (!rawMol) return '';
return String(rawMol)
.replace(/^\uFEFF/, '')
.replace(/\r\n?/g, '\n')
.replace(/[ \t]+$/gm, '')
.replace(/\n+$/, '');
}
function tryChemDoodleReadMOL(molData) {
try {
var molecule = ChemDoodle.readMOL(molData);
if (molecule && molecule.atoms && molecule.atoms.length > 0) {
return molecule;
}
} catch (err) {
console.warn('ChemDoodle.readMOL failed, using fallback parser:', err);
}
return null;
}
function parseCountsLine(line) {
if (!line) return null;
/* Standard MDL V2000 counts line: atom and bond counts are fixed-width 3-column fields.
This is important for cases such as " 98122...", which means 98 atoms and 122 bonds. */
var atomFixed = parseInt(line.slice(0, 3), 10);
var bondFixed = parseInt(line.slice(3, 6), 10);
if (Number.isInteger(atomFixed) && Number.isInteger(bondFixed) && atomFixed > 0 && bondFixed >= 0) {
return { atomCount: atomFixed, bondCount: bondFixed };
}
/* Tolerate non-standard counts lines exported without strict fixed-width padding. */
var spaced = line.match(/^\s*(\d{1,3})\s+(\d{1,3})(?:\s|$)/);
if (spaced) {
return { atomCount: parseInt(spaced[1], 10), bondCount: parseInt(spaced[2], 10) };
}
var compact = line.match(/^\s*(\d{1,3})(\d{3})(?:\s|$)/);
if (compact) {
return { atomCount: parseInt(compact[1], 10), bondCount: parseInt(compact[2], 10) };
}
return null;
}
function normalizeElementSymbol(rawSymbol) {
if (!rawSymbol) return null;
var lettersOnly = String(rawSymbol).replace(/[^A-Za-z]/g, '');
if (!lettersOnly) return null;
var normalized = lettersOnly.charAt(0).toUpperCase() + lettersOnly.slice(1).toLowerCase();
if (ChemDoodle.ELEMENT && ChemDoodle.ELEMENT[normalized]) {
return normalized;
}
return null;
}
function parseMolAtomLine(line) {
if (!line) return null;
var x = parseFloat(line.slice(0, 10));
var y = parseFloat(line.slice(10, 20));
var z = parseFloat(line.slice(20, 30));
var element = normalizeElementSymbol(line.slice(31, 34).trim());
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z) || !element) {
var parts = line.trim().split(/\s+/);
if (parts.length < 4) return null;
x = parseFloat(parts[0]);
y = parseFloat(parts[1]);
z = parseFloat(parts[2]);
element = normalizeElementSymbol(parts[3]);
}
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z) || !element) {
return null;
}
return { x: x, y: y, z: z, element: element };
}
function parseMolBondLine(line) {
if (!line) return null;
var beginIndex = parseInt(line.slice(0, 3), 10) - 1;
var endIndex = parseInt(line.slice(3, 6), 10) - 1;
var order = parseInt(line.slice(6, 9), 10);
if (!Number.isInteger(beginIndex) || !Number.isInteger(endIndex)) {
var parts = line.trim().split(/\s+/);
if (parts.length < 3) return null;
beginIndex = parseInt(parts[0], 10) - 1;
endIndex = parseInt(parts[1], 10) - 1;
order = parseInt(parts[2], 10);
}
if (!Number.isInteger(beginIndex) || !Number.isInteger(endIndex)) {
return null;
}
return { beginIndex: beginIndex, endIndex: endIndex, order: Number.isInteger(order) ? order : 1 };
}
function molBlockLooksParseable(lines, countsIndex, counts) {
if (!counts || counts.atomCount <= 0 || counts.bondCount < 0) return false;
if (countsIndex + 1 + counts.atomCount + counts.bondCount > lines.length) return false;
for (var a = 0; a < counts.atomCount; a++) {
if (!parseMolAtomLine(lines[countsIndex + 1 + a])) return false;
}
for (var b = 0; b < counts.bondCount; b++) {
if (!parseMolBondLine(lines[countsIndex + 1 + counts.atomCount + b])) return false;
}
return true;
}
function findCountsLine(lines) {
/* Prefer the normal MOL position first, but do not require a fixed header length.
ChemDraw, GaussView, and Liquid capture can add/remove blank title/comment lines. */
var preferred = [3, 4, 2];
for (var p = 0; p < preferred.length; p++) {
var idx = preferred[p];
if (idx < lines.length) {
var counts = parseCountsLine(lines[idx]);
if (molBlockLooksParseable(lines, idx, counts)) {
return { index: idx, counts: counts };
}
}
}
for (var i = 0; i < lines.length; i++) {
var detected = parseCountsLine(lines[i]);
if (molBlockLooksParseable(lines, i, detected)) {
return { index: i, counts: detected };
}
}
return null;
}
function parseMolWithFallback(rawMol, options) {
var molData = normalizeMolBlock(rawMol);
if (!molData) return null;
/* Keep the original header while trying ChemDoodle first.
Do not trim leading blank title lines: they are meaningful in MDL MOL files. */
var molecule = tryChemDoodleReadMOL(molData);
if (molecule) return molecule;
var lines = molData.split('\n');
var located = findCountsLine(lines);
if (!located) return null;
options = options || {};
var coordinateScale = Number.isFinite(options.coordinateScale) ? options.coordinateScale : 1;
var flipY = !!options.flipY;
var countsIndex = located.index;
var atomCount = located.counts.atomCount;
var bondCount = located.counts.bondCount;
var parsed = new ChemDoodle.structures.Molecule();
for (var a = 0; a < atomCount; a++) {
var atom = parseMolAtomLine(lines[countsIndex + 1 + a]);
if (!atom) return null;
parsed.atoms.push(new ChemDoodle.structures.Atom(
atom.element,
atom.x * coordinateScale,
(flipY ? -atom.y : atom.y) * coordinateScale,
atom.z * coordinateScale
));
}
for (var b = 0; b < bondCount; b++) {
var bond = parseMolBondLine(lines[countsIndex + 1 + atomCount + b]);
if (!bond || !parsed.atoms[bond.beginIndex] || !parsed.atoms[bond.endIndex]) return null;
parsed.bonds.push(new ChemDoodle.structures.Bond(parsed.atoms[bond.beginIndex], parsed.atoms[bond.endIndex], bond.order));
}
return parsed.atoms.length > 0 ? parsed : null;
}
{% if include.mode == '2d' %}
/* 2D Canvas */
(function() {
/* Generate truly unique ID at runtime */
var timestamp = Date.now();
var random = Math.floor(Math.random() * 10000);
var uniqueCanvasId = 'view2d_' + timestamp + '_' + random;
/* Update the canvas element ID */
var originalCanvas = document.getElementById('viewACS_{{ unique_id }}');
if (originalCanvas) {
originalCanvas.id = uniqueCanvasId;
console.log('Canvas ID updated from viewACS_{{ unique_id }} to:', uniqueCanvasId);
} else {
console.error('Original canvas not found: viewACS_{{ unique_id }}');
return;
}
var canvas = new ChemDoodle.ViewerCanvas(uniqueCanvasId, {{ include.width | default: 400 }}, {{ include.height | default: 300 }});
canvas.styles.bonds_width_2D = 0.6;
canvas.styles.bonds_saturationWidthAbs_2D = 2.6;
canvas.styles.atoms_font_size_2D = 10;
{% if include.smiles %}
var smiles = '{{ include.smiles }}';
var molfile = OCL.Molecule.fromSmiles(smiles).toMolfile();
var molecule = ChemDoodle.readMOL(molfile);
molecule.scaleToAverageBondLength({{ include.scale | default: 20 }});
canvas.loadMolecule(molecule);
{% elsif include.mol %}
var molData = readMolDataNearCurrentScript();
var molecule = parseMolWithFallback(molData);
if (molecule && molecule.atoms && molecule.atoms.length > 0) {
molecule.scaleToAverageBondLength({{ include.scale | default: 20 }});
canvas.loadMolecule(molecule);
} else {
console.error('Failed to parse MOL data for:', uniqueCanvasId, molData);
}
{% endif %}
})();
{% elsif include.mode == '3d' %}
/* 3D Canvas */
(function() {
/* Generate truly unique ID at runtime */
var timestamp = Date.now();
var random = Math.floor(Math.random() * 10000);
var uniqueCanvasId = 'transform3d_' + timestamp + '_' + random;
/* Update the canvas element ID */
var originalCanvas = document.getElementById('transform3d_{{ unique_id }}');
if (originalCanvas) {
originalCanvas.id = uniqueCanvasId;
console.log('Canvas ID updated from transform3d_{{ unique_id }} to:', uniqueCanvasId);
} else {
console.error('Original canvas not found: transform3d_{{ unique_id }}');
return;
}
console.log('Starting 3D canvas initialization for:', uniqueCanvasId);
var canvas = new ChemDoodle.TransformCanvas3D(uniqueCanvasId, {{ include.width | default: 400 }}, {{ include.height | default: 400 }});
console.log('3D canvas created:', uniqueCanvasId);
canvas.styles.set3DRepresentation('{{ include.representation | default: "Ball and Stick" }}');
canvas.styles.backgroundColor = '{{ include.bgcolor | default: "black" }}';
canvas.styles.atoms_useVDWDiameters_3D = {{ include.use_vdw_3d | default: false }};
canvas.styles.atoms_vdwMultiplier_3D = {{ include.vdw_multiplier_3d | default: 1.0 }};
canvas.styles.atoms_sphereDiameter_3D = {{ include.atom_diameter_3d | default: 8.0 }};
canvas.styles.bonds_cylinderDiameter_3D = {{ include.bond_diameter_3d | default: 1.0 }};
function applyInitial3DScale() {
/* In ChemDoodle 3D/WebGL canvases, wheel zoom is controlled by camera.zoom,
not styles.scale. Treat initial_scale_3d as apparent display scale:
1 = original size, 0.5 = half size, 0.1 = one tenth size. */
var initialScale3D = {{ include.initial_scale_3d | default: 0.5 }};
if (Number.isFinite(initialScale3D) && initialScale3D > 0) {
canvas.camera.zoom = 1 / initialScale3D;
if (typeof canvas.updateScene === 'function') {
canvas.updateScene();
} else {
canvas.repaint();
}
}
}
console.log('Styles set for:', uniqueCanvasId);
{% if include.xyz %}
/* Parse XYZ coordinate data */
var xyzData = {{ include.xyz | jsonify }};
var lines = xyzData.trim().split('\n');
var numAtoms = parseInt(lines[0]);
var comment = lines[1]; /* Skip comment line */
var molecule = new ChemDoodle.structures.Molecule();
/* Parse atoms from XYZ data */
for (var i = 2; i < 2 + numAtoms && i < lines.length; i++) {
var parts = lines[i].trim().split(/\s+/);
if (parts.length < 4) {
console.warn('Skipping malformed XYZ line at index', i, ':', lines[i]);
continue;
}
var element = normalizeElementSymbol(parts[0]);
var x = parseFloat(parts[1]);
var y = parseFloat(parts[2]);
var z = parseFloat(parts[3]);
if (!element || !Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {
console.warn('Skipping invalid atom entry at line', i, ':', lines[i]);
continue;
}
molecule.atoms.push(new ChemDoodle.structures.Atom(element, x, y, z));
}
/* Auto-generate bonds based on distance (simple approach) */
/* You may want to customize this based on your needs */
for (var j = 0; j < molecule.atoms.length; j++) {
for (var k = j + 1; k < molecule.atoms.length; k++) {
var atom1 = molecule.atoms[j];
var atom2 = molecule.atoms[k];
var dx = atom1.x - atom2.x;
var dy = atom1.y - atom2.y;
var dz = atom1.z - atom2.z;
var distance = Math.sqrt(dx*dx + dy*dy + dz*dz);
/* Simple bonding criteria based on atomic radii */
var maxBondDistance = 2.0; /* Adjust as needed */
if (distance < maxBondDistance) {
molecule.bonds.push(new ChemDoodle.structures.Bond(atom1, atom2));
}
}
}
console.log('XYZ molecule created for', uniqueCanvasId, 'with', molecule.atoms.length, 'atoms and', molecule.bonds.length, 'bonds');
canvas.loadMolecule(molecule);
applyInitial3DScale();
console.log('XYZ molecule loaded for:', uniqueCanvasId);
{% elsif include.mol %}
var molData = readMolDataNearCurrentScript();
var molecule = parseMolWithFallback(molData, {
/* ChemDoodle.readMOL normally multiplies MOL coordinates by bondLength_2D.
Do the same only when readMOL fails and our fallback parser is used;
otherwise shifted-header MOL files look tiny in coordinate space, making fixed-size atoms appear huge. */
coordinateScale: {{ include.mol_coordinate_scale_3d | default: 20 }},
flipY: true
});
if (molecule && molecule.atoms && molecule.atoms.length > 0) {
console.log('MOL molecule created for', uniqueCanvasId, 'with', molecule.atoms.length, 'atoms');
canvas.loadMolecule(molecule);
applyInitial3DScale();
console.log('MOL molecule loaded for:', uniqueCanvasId);
} else {
console.error('Failed to parse MOL data for:', uniqueCanvasId, molData);
}
{% elsif include.smiles %}
var smiles = '{{ include.smiles }}';
var molfile = OCL.Molecule.fromSmiles(smiles).toMolfile();
var molecule = ChemDoodle.readMOL(molfile);
console.log('SMILES molecule created for', uniqueCanvasId, 'with', molecule.atoms.length, 'atoms');
canvas.loadMolecule(molecule);
applyInitial3DScale();
console.log('SMILES molecule loaded for:', uniqueCanvasId);
{% endif %}
})();
{% endif %}
</script>
<style>
.molecule-container {
text-align: center;
margin: 20px 0;
}
.canvas-container {
display: inline-block;
border: 1px solid #ddd;
border-radius: 4px;
}
</style>
为了方便管理,可以在js-selector.html里补上:
1
2
3
{% if page.chem %}
{% include chemdoodle.html %}
{% endif %}
这样可以在文章 front matter 中如此打开 chem:
1
chem: true
随后就能在blog中用liquid语言加载chemdoodle了。
代码块
但是直接写liquid不太友好,可以再加点东西:
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
(function () {
'use strict';
var counter = 0;
function hasChemDoodle() {
/* ChemDoodleWeb.js defines `let ChemDoodle` in the global lexical scope.
That is available as the bare identifier `ChemDoodle`, but not as
`window.ChemDoodle` in modern browsers. */
return typeof ChemDoodle !== 'undefined' && !!ChemDoodle && !!ChemDoodle.structures;
}
function hasOpenChemLib() {
return typeof OCL !== 'undefined' && !!OCL && !!OCL.Molecule;
}
function normalizeText(raw) {
return String(raw || '')
.replace(/^\uFEFF/, '')
.replace(/\r\n?/g, '\n')
.replace(/[ \t]+$/gm, '')
.replace(/\n+$/, '');
}
function normalizeElementSymbol(rawSymbol) {
if (!rawSymbol) return null;
var lettersOnly = String(rawSymbol).replace(/[^A-Za-z]/g, '');
if (!lettersOnly) return null;
var normalized = lettersOnly.charAt(0).toUpperCase() + lettersOnly.slice(1).toLowerCase();
if (hasChemDoodle() && ChemDoodle.ELEMENT && ChemDoodle.ELEMENT[normalized]) {
return normalized;
}
return null;
}
function parseCountsLine(line) {
if (!line) return null;
var atomFixed = parseInt(line.slice(0, 3), 10);
var bondFixed = parseInt(line.slice(3, 6), 10);
if (Number.isInteger(atomFixed) && Number.isInteger(bondFixed) && atomFixed > 0 && bondFixed >= 0) {
return { atomCount: atomFixed, bondCount: bondFixed };
}
var spaced = line.match(/^\s*(\d{1,3})\s+(\d{1,3})(?:\s|$)/);
if (spaced) {
return { atomCount: parseInt(spaced[1], 10), bondCount: parseInt(spaced[2], 10) };
}
var compact = line.match(/^\s*(\d{1,3})(\d{3})(?:\s|$)/);
if (compact) {
return { atomCount: parseInt(compact[1], 10), bondCount: parseInt(compact[2], 10) };
}
return null;
}
function parseMolAtomLine(line) {
if (!line) return null;
var x = parseFloat(line.slice(0, 10));
var y = parseFloat(line.slice(10, 20));
var z = parseFloat(line.slice(20, 30));
var element = normalizeElementSymbol(line.slice(31, 34).trim());
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z) || !element) {
var parts = line.trim().split(/\s+/);
if (parts.length < 4) return null;
x = parseFloat(parts[0]);
y = parseFloat(parts[1]);
z = parseFloat(parts[2]);
element = normalizeElementSymbol(parts[3]);
}
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z) || !element) return null;
return { x: x, y: y, z: z, element: element };
}
function parseMolBondLine(line) {
if (!line) return null;
var beginIndex = parseInt(line.slice(0, 3), 10) - 1;
var endIndex = parseInt(line.slice(3, 6), 10) - 1;
var order = parseInt(line.slice(6, 9), 10);
if (!Number.isInteger(beginIndex) || !Number.isInteger(endIndex)) {
var parts = line.trim().split(/\s+/);
if (parts.length < 3) return null;
beginIndex = parseInt(parts[0], 10) - 1;
endIndex = parseInt(parts[1], 10) - 1;
order = parseInt(parts[2], 10);
}
if (!Number.isInteger(beginIndex) || !Number.isInteger(endIndex)) return null;
return { beginIndex: beginIndex, endIndex: endIndex, order: Number.isInteger(order) ? order : 1 };
}
function molBlockLooksParseable(lines, countsIndex, counts) {
if (!counts || counts.atomCount <= 0 || counts.bondCount < 0) return false;
if (countsIndex + 1 + counts.atomCount + counts.bondCount > lines.length) return false;
for (var a = 0; a < counts.atomCount; a++) {
if (!parseMolAtomLine(lines[countsIndex + 1 + a])) return false;
}
for (var b = 0; b < counts.bondCount; b++) {
if (!parseMolBondLine(lines[countsIndex + 1 + counts.atomCount + b])) return false;
}
return true;
}
function findCountsLine(lines) {
var preferred = [3, 4, 2];
for (var p = 0; p < preferred.length; p++) {
var idx = preferred[p];
if (idx < lines.length) {
var counts = parseCountsLine(lines[idx]);
if (molBlockLooksParseable(lines, idx, counts)) return { index: idx, counts: counts };
}
}
for (var i = 0; i < lines.length; i++) {
var detected = parseCountsLine(lines[i]);
if (molBlockLooksParseable(lines, i, detected)) return { index: i, counts: detected };
}
return null;
}
function tryChemDoodleReadMOL(molData) {
try {
var molecule = ChemDoodle.readMOL(molData);
if (molecule && molecule.atoms && molecule.atoms.length > 0) return molecule;
} catch (err) {
console.warn('ChemDoodle.readMOL failed, using fallback parser:', err);
}
return null;
}
function parseMolWithFallback(rawMol, options) {
var molData = normalizeText(rawMol);
if (!molData) return null;
var molecule = tryChemDoodleReadMOL(molData);
if (molecule) return molecule;
var lines = molData.split('\n');
var located = findCountsLine(lines);
if (!located) return null;
options = options || {};
var coordinateScale = Number.isFinite(options.coordinateScale) ? options.coordinateScale : 1;
var flipY = !!options.flipY;
var countsIndex = located.index;
var atomCount = located.counts.atomCount;
var bondCount = located.counts.bondCount;
var parsed = new ChemDoodle.structures.Molecule();
for (var a = 0; a < atomCount; a++) {
var atom = parseMolAtomLine(lines[countsIndex + 1 + a]);
if (!atom) return null;
parsed.atoms.push(new ChemDoodle.structures.Atom(
atom.element,
atom.x * coordinateScale,
(flipY ? -atom.y : atom.y) * coordinateScale,
atom.z * coordinateScale
));
}
for (var b = 0; b < bondCount; b++) {
var bond = parseMolBondLine(lines[countsIndex + 1 + atomCount + b]);
if (!bond || !parsed.atoms[bond.beginIndex] || !parsed.atoms[bond.endIndex]) return null;
parsed.bonds.push(new ChemDoodle.structures.Bond(parsed.atoms[bond.beginIndex], parsed.atoms[bond.endIndex], bond.order));
}
return parsed.atoms.length > 0 ? parsed : null;
}
function extractXYZAtomLines(rawXYZ) {
var xyzData = normalizeText(rawXYZ).trim();
if (!xyzData) return null;
var allLines = xyzData.split('\n');
var lines = [];
for (var i = 0; i < allLines.length; i++) {
var line = allLines[i].trim();
if (!line || line.charAt(0) === '#') continue;
lines.push(line);
}
if (!lines.length) return null;
var hasCountHeader = /^\d+\s*$/.test(lines[0]);
var expectedCount = hasCountHeader ? parseInt(lines[0], 10) : lines.length;
var start = hasCountHeader ? 2 : 0;
var end = hasCountHeader ? Math.min(start + expectedCount, lines.length) : lines.length;
var atoms = [];
for (var j = start; j < end; j++) {
var parts = lines[j].trim().split(/\s+/);
if (parts.length < 4) continue;
var element = normalizeElementSymbol(parts[0]);
var x = parseFloat(parts[1]);
var y = parseFloat(parts[2]);
var z = parseFloat(parts[3]);
if (!element || !Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {
console.warn('Skipping invalid XYZ atom line:', lines[j]);
continue;
}
atoms.push(element + ' ' + x + ' ' + y + ' ' + z);
}
return atoms.length ? atoms : null;
}
function makeStandardXYZ(rawXYZ) {
var atoms = extractXYZAtomLines(rawXYZ);
if (!atoms || !atoms.length) return null;
return String(atoms.length) + '\nGenerated by chem-codeblock.js\n' + atoms.join('\n');
}
function scaleMoleculeCoordinates(molecule, scale) {
if (!molecule || !molecule.atoms || !Number.isFinite(scale) || scale === 1) return molecule;
for (var i = 0; i < molecule.atoms.length; i++) {
molecule.atoms[i].x *= scale;
molecule.atoms[i].y *= scale;
molecule.atoms[i].z *= scale;
}
return molecule;
}
function deduceCovalentBonds(molecule) {
if (!molecule || !molecule.atoms || molecule.bonds.length) return molecule;
if (ChemDoodle.informatics && ChemDoodle.informatics.BondDeducer) {
try {
new ChemDoodle.informatics.BondDeducer().deduceCovalentBonds(molecule, 1);
return molecule;
} catch (err) {
console.warn('ChemDoodle BondDeducer failed, using simple distance fallback:', err);
}
}
return molecule;
}
function parseXYZ(rawXYZ, options) {
options = options || {};
var standardXYZ = makeStandardXYZ(rawXYZ);
if (!standardXYZ) return null;
var molecule = null;
if (typeof ChemDoodle.readXYZ === 'function') {
try {
molecule = ChemDoodle.readXYZ(standardXYZ);
} catch (err) {
console.warn('ChemDoodle.readXYZ failed, using manual XYZ parser:', err);
}
}
if (!molecule || !molecule.atoms || !molecule.atoms.length) {
var lines = standardXYZ.split('\n');
var count = parseInt(lines[0], 10);
molecule = new ChemDoodle.structures.Molecule();
for (var i = 2; i < 2 + count && i < lines.length; i++) {
var parts = lines[i].trim().split(/\s+/);
if (parts.length < 4) continue;
var element = normalizeElementSymbol(parts[0]);
var x = parseFloat(parts[1]);
var y = parseFloat(parts[2]);
var z = parseFloat(parts[3]);
if (!element || !Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue;
molecule.atoms.push(new ChemDoodle.structures.Atom(element, x, y, z));
}
deduceCovalentBonds(molecule);
}
if (!molecule || !molecule.atoms || !molecule.atoms.length) return null;
/* XYZ coordinates are normally in Angstrom. MOL files read through this
ChemDoodle build are effectively much larger on the canvas, so scale XYZ
after bond deduction to make atom_diameter_3d=8 and bond_diameter_3d=1
behave consistently with your MOL examples. */
scaleMoleculeCoordinates(molecule, Number.isFinite(options.coordinateScale) ? options.coordinateScale : 1);
return molecule;
}
function getLanguage(node) {
var candidates = [];
if (node) candidates.push(node);
if (node && node.parentElement) candidates.push(node.parentElement);
var root = getCodeRoot(node);
if (root) candidates.push(root);
for (var i = 0; i < candidates.length; i++) {
var cls = candidates[i].className || '';
var match = String(cls).match(/(?:^|\s)language-(xyz|mol|sdf|smiles|smi)(?:\s|$)/i);
if (match) return match[1].toLowerCase();
}
return null;
}
function getCodeRoot(code) {
if (!code) return null;
return code.closest('.highlighter-rouge, figure.highlight, div.highlight, pre') || code.parentElement;
}
function readAttr(nodes, names, defaultValue) {
if (!Array.isArray(names)) names = [names];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (!node || !node.getAttribute) continue;
for (var j = 0; j < names.length; j++) {
var value = node.getAttribute(names[j]);
if (value !== null && value !== '') return value;
}
}
return defaultValue;
}
function getParams(code, root) {
var highlight = root && root.querySelector ? root.querySelector('.highlight, pre, code') : null;
var nodes = [code, root, highlight, code && code.parentElement].filter(Boolean);
function numberAttr(names, defaultValue) {
var raw = readAttr(nodes, names, defaultValue);
var num = parseFloat(raw);
return Number.isFinite(num) ? num : defaultValue;
}
function stringAttr(names, defaultValue) {
return readAttr(nodes, names, defaultValue);
}
function boolAttr(names, defaultValue) {
var raw = readAttr(nodes, names, defaultValue ? 'true' : 'false');
if (typeof raw === 'boolean') return raw;
return /^(true|1|yes|y)$/i.test(String(raw));
}
return {
mode: String(stringAttr('mode', '3d')).toLowerCase(),
width: numberAttr('width', 400),
height: numberAttr('height', 400),
representation: stringAttr('representation', 'Ball and Stick'),
bgcolor: stringAttr(['bgcolor', 'background', 'background_color', 'background-color'], 'black'),
useVDW3D: boolAttr(['use_vdw_3d', 'use-vdw-3d'], false),
vdwMultiplier3D: numberAttr(['vdw_multiplier_3d', 'vdw-multiplier-3d'], 1.0),
atomDiameter3D: numberAttr(['atom_diameter_3d', 'atom-diameter-3d'], 8.0),
bondDiameter3D: numberAttr(['bond_diameter_3d', 'bond-diameter-3d'], 1.0),
initialScale3D: numberAttr(['initial_scale_3d', 'initial-scale-3d'], 0.5),
molCoordinateScale3D: numberAttr(['mol_coordinate_scale_3d', 'mol-coordinate-scale-3d'], 20),
xyzCoordinateScale3D: numberAttr(['xyz_coordinate_scale_3d', 'xyz-coordinate-scale-3d'], 20),
bondMaxDistance: numberAttr(['bond_max', 'bond-max', 'bond_max_distance', 'bond-max-distance'], 2.0),
scale2D: numberAttr(['scale', 'scale_2d', 'scale-2d'], 20),
replace: boolAttr('replace', true)
};
}
function createCanvasElement(root, params) {
counter += 1;
var id = 'chem_codeblock_' + Date.now() + '_' + counter + '_' + Math.floor(Math.random() * 10000);
var outer = document.createElement('div');
outer.className = 'molecule-container chem-codeblock-rendered';
outer.setAttribute('data-chem-codeblock', 'true');
var inner = document.createElement('div');
inner.className = 'canvas-container';
var canvasEl = document.createElement('canvas');
canvasEl.id = id;
canvasEl.width = params.width;
canvasEl.height = params.height;
inner.appendChild(canvasEl);
outer.appendChild(inner);
root.parentNode.insertBefore(outer, root);
if (params.replace) {
root.remove();
} else {
root.setAttribute('data-chem-source-kept', 'true');
}
return id;
}
function buildMolecule(language, source, mode, params) {
if (language === 'xyz') {
return parseXYZ(source, { coordinateScale: mode === '3d' ? params.xyzCoordinateScale3D : 1 });
}
if (language === 'mol' || language === 'sdf') {
return parseMolWithFallback(source, {
coordinateScale: mode === '3d' ? params.molCoordinateScale3D : 1,
flipY: mode === '3d'
});
}
if (language === 'smiles' || language === 'smi') {
var smiles = normalizeText(source).trim().split(/\s+/)[0];
if (!smiles || !hasOpenChemLib()) return null;
var molfile = OCL.Molecule.fromSmiles(smiles).toMolfile();
return ChemDoodle.readMOL(molfile);
}
return null;
}
function applyInitial3DScale(canvas, initialScale3D) {
if (Number.isFinite(initialScale3D) && initialScale3D > 0 && canvas.camera) {
canvas.camera.zoom = 1 / initialScale3D;
if (typeof canvas.updateScene === 'function') {
canvas.updateScene();
} else {
canvas.repaint();
}
}
}
function render2D(id, language, source, params) {
var canvas = new ChemDoodle.ViewerCanvas(id, params.width, params.height);
canvas.styles.bonds_width_2D = 0.6;
canvas.styles.bonds_saturationWidthAbs_2D = 2.6;
canvas.styles.atoms_font_size_2D = 10;
var molecule = buildMolecule(language, source, '2d', params);
if (!molecule || !molecule.atoms || !molecule.atoms.length) return false;
if (typeof molecule.scaleToAverageBondLength === 'function') {
molecule.scaleToAverageBondLength(params.scale2D);
}
canvas.loadMolecule(molecule);
return true;
}
function render3D(id, language, source, params) {
var canvas = new ChemDoodle.TransformCanvas3D(id, params.width, params.height);
canvas.styles.set3DRepresentation(params.representation);
canvas.styles.backgroundColor = params.bgcolor;
canvas.styles.atoms_useVDWDiameters_3D = params.useVDW3D;
canvas.styles.atoms_vdwMultiplier_3D = params.vdwMultiplier3D;
canvas.styles.atoms_sphereDiameter_3D = params.atomDiameter3D;
canvas.styles.bonds_cylinderDiameter_3D = params.bondDiameter3D;
var molecule = buildMolecule(language, source, '3d', params);
if (!molecule || !molecule.atoms || !molecule.atoms.length) return false;
canvas.loadMolecule(molecule);
applyInitial3DScale(canvas, params.initialScale3D);
return true;
}
function renderChemCodeBlock(code) {
var language = getLanguage(code);
if (!language) return;
var root = getCodeRoot(code);
if (!root || root.getAttribute('data-chem-rendered') === 'true') return;
root.setAttribute('data-chem-rendered', 'true');
var params = getParams(code, root);
var source = code.textContent || '';
var id = createCanvasElement(root, params);
var ok = params.mode === '2d'
? render2D(id, language, source, params)
: render3D(id, language, source, params);
if (!ok) {
console.error('Failed to render molecule code block:', { language: language, source: source });
var canvas = document.getElementById(id);
var container = canvas && canvas.closest('.molecule-container');
if (container) container.remove();
if (params.replace) root.style.display = '';
}
}
function findChemCodeBlocks() {
var selectors = [
'code.language-xyz',
'code.language-mol',
'code.language-sdf',
'code.language-smiles',
'code.language-smi',
'.language-xyz code',
'.language-mol code',
'.language-sdf code',
'.language-smiles code',
'.language-smi code'
];
var nodes = Array.prototype.slice.call(document.querySelectorAll(selectors.join(',')));
var unique = [];
var seen = new Set();
nodes.forEach(function (node) {
var code = node.tagName && node.tagName.toLowerCase() === 'code' ? node : node.querySelector('code');
if (!code || seen.has(code)) return;
seen.add(code);
unique.push(code);
});
return unique;
}
function renderAllChemCodeBlocks(attempt) {
attempt = attempt || 0;
if (!hasChemDoodle()) {
/* Usually this is only because ChemDoodleWeb.js created a global lexical
binding instead of window.ChemDoodle. If the script is still loading,
wait briefly instead of permanently skipping code blocks. */
if (attempt < 50) {
window.setTimeout(function () {
renderAllChemCodeBlocks(attempt + 1);
}, 100);
return;
}
console.error('ChemDoodle is not loaded; cannot render molecule code blocks.');
return;
}
findChemCodeBlocks().forEach(renderChemCodeBlock);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () {
renderAllChemCodeBlocks(0);
});
} else {
renderAllChemCodeBlocks(0);
}
})();
这样代码块就可以代替手写liquid了
测试
smiles转2d
1
2
3
4
5
6
{% include xyz.html
mode="2d"
scale=60
smiles="CCO"
width=300
height=250 %}
mol转2d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{% include xyz.html
mode="2d"
scale=35
mol="
ChemDraw08232514192D
6 6 0 0 0 0 0 0 0 0999 V2000
-0.7145 0.4125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.7145 -0.4125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
0.0000 -0.8250 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
0.7145 -0.4125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
0.7145 0.4125 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
0.0000 0.8250 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1 2 2 0
2 3 1 0
3 4 2 0
4 5 1 0
5 6 2 0
6 1 1 0
M END"
id="ethanol" %}
xyz转3d
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
{% include xyz.html
mode="3d"
xyz="
19
Converted from Gaussian clipboard
C 0.284528 0.302620 -0.003725
C 1.826238 0.302620 -0.003725
C 1.285123 2.511620 -0.003725
C -0.082043 1.799109 -0.003537
H -0.123876 -0.221202 -0.899237
H -0.107098 -0.205269 0.909453
H -0.686566 2.075056 -0.898829
H -0.663726 2.068225 0.909974
C 2.128864 1.547523 0.869788
H 3.208070 1.811917 0.890025
H 1.744237 1.453324 1.908137
C 2.281902 0.791849 -1.392786
H 3.381794 0.649669 -1.516665
H 1.762184 0.240506 -2.210759
C 1.915178 2.288343 -1.392917
H 2.824668 2.922940 -1.516988
H 1.199360 2.536658 -2.210907
H 2.286514 -0.647873 0.323362
H 1.253999 3.567204 0.323489"
atom_diameter_3d=0.8 bond_diameter_3d=0.22
representation="Ball and Stick"
bgcolor="white" %}
mol转3d
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
{% include xyz.html
mode="3d"
mol="
Created by GaussView 6.0.16
12 12 0 0 0 0 0 0 0 0 0 0
-1.8683 -1.4587 -0.1826 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.4731 -1.4587 -0.1826 C 0 0 0 0 0 0 0 0 0 0 0 0
0.2244 -0.2510 -0.1826 C 0 0 0 0 0 0 0 0 0 0 0 0
-0.4733 0.9575 -0.1838 C 0 0 0 0 0 0 0 0 0 0 0 0
-1.8681 0.9574 -0.1842 C 0 0 0 0 0 0 0 0 0 0 0 0
-2.5657 -0.2508 -0.1832 C 0 0 0 0 0 0 0 0 0 0 0 0
-2.4181 -2.4111 -0.1821 H 0 0 0 0 0 0 0 0 0 0 0 0
0.0764 -2.4113 -0.1812 H 0 0 0 0 0 0 0 0 0 0 0 0
1.3241 -0.2509 -0.1819 H 0 0 0 0 0 0 0 0 0 0 0 0
0.0769 1.9097 -0.1838 H 0 0 0 0 0 0 0 0 0 0 0 0
-2.4182 1.9097 -0.1852 H 0 0 0 0 0 0 0 0 0 0 0 0
-3.6653 -0.2506 -0.1834 H 0 0 0 0 0 0 0 0 0 0 0 0
1 2 4 0 0 0 0
1 6 4 0 0 0 0
1 7 1 0 0 0 0
2 3 4 0 0 0 0
2 8 1 0 0 0 0
3 4 4 0 0 0 0
3 9 1 0 0 0 0
4 5 4 0 0 0 0
4 10 1 0 0 0 0
5 6 4 0 0 0 0
5 11 1 0 0 0 0
6 12 1 0 0 0 0
M END"
atom_diameter_3d=8.0 bond_diameter_3d=1.0
width=500
height=500 %}
mol文件引用
1
2
3
4
5
6
{% include xyz.html
mode="3d"
src="assets/posts/48/1.mol"
format="mol"
width=800
height=450 %}
代码块
xyz
9
Converted from Gaussian clipboard
C -2.795841 0.555562 0.000006
H -2.439141 -0.453232 0.000040
H -2.439172 1.059953 -0.873651
H -3.865841 0.555527 -0.000016
C -2.282557 1.281575 1.257402
H -2.639226 0.777184 2.131060
H -1.212557 1.281610 1.257424
O -2.759268 2.629777 1.257356
H -2.439298 3.082356 2.041188
smiles
c1ccccc1
共 1 个文件,位于 /assets/posts/48/。
This post is licensed under
CC BY 4.0
by the author.