v4.1.5: KaTeX 수식·화학식 렌더링 + SMILES 2D 구조식(결합선) 추가 + 코드블록 이스케이핑 버그 수정

- KaTeX self-host (vendor/katex) 추가, $...$/$$...$$ 자동 렌더링 + mhchem 확장으로
  \ce{C4H10} 같은 화학식·반응식 표기 지원 (renderKatexIn, renderChatMessages 후처리)
- SmilesDrawer self-host (vendor/smiles-drawer) 추가, ```smiles``` 코드블록으로 SMILES
  표기를 실제 결합선 있는 2D 구조식으로 렌더링. 라이브러리의 Drawer(canvas) 클래스가
  내부 svgWrapper null 참조로 깨지는 버그가 있어 SvgDrawer로 우회
- 진짜 원인 버그 수정: escHtml()가 백틱(`)/백슬래시/달러도 이스케이프하는데, 코드블록·
  인라인코드 정규식이 이스케이프 *이후*에 원본 백틱을 찾고 있어 애초에 매치가 안 됐음
  — tradingview 차트·네이버 주식차트·MIDI 위젯 등 기존 기능도 전부 이 버그로 작동 안
  하고 있었고, 이번에 같이 고쳐서 정상 작동 확인

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-07-14 12:35:33 +09:00
1 parent 4526de2914
commit c8b4e251bf
68 files changed
+168 -5

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "smallclaw",
"version": "4.1.4",
"version": "4.1.5",
"description": "Local AI agent framework powered by Ollama - OpenClaw alternative",
"main": "dist/index.js",
"bin": {
+87 -4
View File
@@ -1076,6 +1076,26 @@ async function openInFileLocation(targetPath) {
}
}
// KaTeX auto-render must run AFTER the HTML is in the DOM — innerHTML doesn't execute
// embedded <script>, so this has to be called explicitly wherever chat HTML gets inserted
// (mirrors validateDownloadLinks() right above each call site). mhchem.min.js (loaded in
// index.html alongside katex.min.js) extends KaTeX's math mode with \ce{...} for reaction/
// formula notation, e.g. $\ce{C4H10}$ or $\ce{2H2 + O2 -> 2H2O}$.
function renderKatexIn(container) {
if (!window.renderMathInElement || !container) return;
try {
renderMathInElement(container, {
delimiters: [
{ left: '$$', right: '$$', display: true },
{ left: '\\[', right: '\\]', display: true },
{ left: '$', right: '$', display: false },
{ left: '\\(', right: '\\)', display: false },
],
throwOnError: false,
});
} catch (e) {}
}
function renderChatMessages() {
const container = document.getElementById('chat-messages');
@@ -1115,6 +1135,7 @@ function renderChatMessages() {
}).join('');
validateDownloadLinks(container);
renderKatexIn(container);
if (isThinking && streamingSessionId === activeChatSessionId) {
const progressHtml = currentProgressLines.length
@@ -6244,8 +6265,11 @@ function renderMarkdown(text, opts) {
html = html.replace('\x00IMG' + i + '\x00', img);
});
// Code blocks (``` ... ```)
html = html.replace(/```([\w-]*)\n([\s\S]*?)```/g, function(_, lang, code) {
// Code blocks (``` ... ```) — escHtml() above already turned literal backticks into
// &#96; (it escapes backtick/backslash/$ too, not just &<>"'), so matching on literal
// backticks here never matched anything — every special widget block (midi-widget, abc,
// lilypond, tradingview, kstock, smiles) silently fell through as escaped plain text.
html = html.replace(/&#96;&#96;&#96;([\w-]*)\n([\s\S]*?)&#96;&#96;&#96;/g, function(_, lang, code) {
var trimmed = code.trim();
if (lang === 'midi-widget') {
try {
@@ -6332,11 +6356,35 @@ function renderMarkdown(text, opts) {
'</div>' +
'</div>';
}
if (lang === 'smiles') {
// Also undo escHtml()'s backslash/backtick/$ escaping (not just the amp/lt/gt/quote
// set the other widget blocks unescape) — SMILES cis/trans bond notation uses
// backslash (e.g. C/C=C/C), which would otherwise stay mangled as &#92;.
var smRaw = trimmed.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/gi,'"').replace(/&#39;/g,"'").replace(/&#96;/g,'`').replace(/&#36;/g,'$').replace(/&#92;/g,'\\').trim();
if (!smRaw) return '<pre class="md-code-block"><code>' + trimmed + '</code></pre>';
var smId = 'sm-' + Math.random().toString(36).slice(2, 9);
var smEncoded = encodeURIComponent(smRaw);
return '<div class="music-widget" id="' + smId + '">' +
'<div class="music-widget-header">' +
'<span class="music-widget-label">⚗️ ' + escHtml(smRaw) + '</span>' +
'<div style="display:flex;gap:6px;align-items:center">' +
'<button class="music-render-btn" onclick="renderSmilesStructure(this,\'' + smId + '-c\',decodeURIComponent(\'' + smEncoded + '\'))">구조식 그리기</button>' +
'<button onclick="toggleMusicWidget(\'' + smId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="접기/펼치기">▾</button>' +
'<button onclick="closeMusicWidget(\'' + smId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="닫기">✕</button>' +
'</div>' +
'</div>' +
'<div class="music-widget-body" style="padding:8px;text-align:center">' +
'<svg id="' + smId + '-c" width="400" height="300" style="max-width:100%"></svg>' +
'</div>' +
'</div>';
}
return '<pre class="md-code-block"><code>' + trimmed + '</code></pre>';
});
// Inline code
html = html.replace(/`([^`]+)`/g, '<code class="md-inline-code">$1</code>');
// Inline code — same escHtml()-escapes-backticks issue as the fenced code blocks above.
// Content may still contain other entities (&amp;, &lt;, ...), so only exclude another
// &#96; sequence rather than excluding every '&' (which would truncate on those entities).
html = html.replace(/&#96;((?:(?!&#96;)[\s\S])+?)&#96;/g, '<code class="md-inline-code">$1</code>');
// Images: ![alt](url)
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, function(_, alt, url) {
@@ -6492,6 +6540,41 @@ function renderTVChart(btn, containerId, symbol, interval) {
}
}
// SMILES → 2D 화학 구조식 (결합선 포함). SmilesDrawer는 로컬 캔버스 렌더링이라
// 네트워크 지연 없이 즉시 그려지지만, innerHTML로 삽입된 <canvas>는 아직 DOM에
// 붙기 전이라 위젯 코드 블록에서 바로 그릴 수 없음 — 버튼 클릭으로 트리거.
function renderSmilesStructure(btn, svgId, smiles) {
btn.disabled = true;
btn.textContent = '그리는 중...';
var isDark = document.documentElement.getAttribute('data-theme') !== 'light';
if (!window.SmilesDrawer) {
btn.disabled = false;
btn.textContent = '⚠️ 라이브러리 로드 실패';
return;
}
try {
SmilesDrawer.parse(smiles, function(tree) {
try {
// SmilesDrawer.Drawer (canvas) throws internally in this build ("this.svgWrapper
// is null" — a bug in the npm package itself, reproduced directly against the
// unminified call). SvgDrawer works correctly, so render to <svg> instead.
var drawer = new SmilesDrawer.SvgDrawer({ width: 400, height: 300 });
drawer.draw(tree, svgId, isDark ? 'dark' : 'light');
btn.style.display = 'none';
} catch (e) {
btn.disabled = false;
btn.textContent = '⚠️ 렌더링 실패';
}
}, function() {
btn.disabled = false;
btn.textContent = '⚠️ SMILES 파싱 실패';
});
} catch (e) {
btn.disabled = false;
btn.textContent = '⚠️ 렌더링 실패';
}
}
function toggleMusicWidget(widgetId) {
var widget = document.getElementById(widgetId);
if (!widget) return;
+5
View File
@@ -21,6 +21,11 @@
<script src="/vendor/xterm.js"></script>
<script src="/vendor/addon-fit.js"></script>
<script src="/vendor/addon-web-links.js"></script>
<link rel="stylesheet" href="/vendor/katex/katex.min.css">
<script src="/vendor/katex/katex.min.js"></script>
<script src="/vendor/katex/auto-render.min.js"></script>
<script src="/vendor/katex/mhchem.min.js"></script>
<script src="/vendor/smiles-drawer/smiles-drawer.min.js"></script>
<link rel="stylesheet" href="styles.css">
<script src="/vendor/tone-midi.js"></script>
+1
View File
@@ -0,0 +1 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("katex")):"function"==typeof define&&define.amd?define(["katex"],t):"object"==typeof exports?exports.renderMathInElement=t(require("katex")):e.renderMathInElement=t(e.katex)}("undefined"!=typeof self?self:this,(function(e){return function(){"use strict";var t={771:function(t){t.exports=e}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var a=r[e]={exports:{}};return t[e](a,a.exports,n),a.exports}n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};var i={};return function(){n.d(i,{default:function(){return s}});var e=n(771),t=n.n(e),r=function(e,t,r){for(var n=r,i=0,a=e.length;n<t.length;){var o=t[n];if(i<=0&&t.slice(n,n+a)===e)return n;"\\"===o?n++:"{"===o?i++:"}"===o&&i--,n++}return-1},a=/^\\begin{/,o=function(e,t){for(var n,i=[],o=new RegExp("("+t.map((function(e){return e.left.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")})).join("|")+")");-1!==(n=e.search(o));){n>0&&(i.push({type:"text",data:e.slice(0,n)}),e=e.slice(n));var l=t.findIndex((function(t){return e.startsWith(t.left)}));if(-1===(n=r(t[l].right,e,t[l].left.length)))break;var d=e.slice(0,n+t[l].right.length),s=a.test(d)?d:e.slice(t[l].left.length,n);i.push({type:"math",data:s,rawData:d,display:t[l].display}),e=e.slice(n+t[l].right.length)}return""!==e&&i.push({type:"text",data:e}),i},l=function(e,r){var n=o(e,r.delimiters);if(1===n.length&&"text"===n[0].type)return null;for(var i=document.createDocumentFragment(),a=0;a<n.length;a++)if("text"===n[a].type)i.appendChild(document.createTextNode(n[a].data));else{var l=document.createElement("span"),d=n[a].data;r.displayMode=n[a].display;try{r.preProcess&&(d=r.preProcess(d)),t().render(d,l,r)}catch(e){if(!(e instanceof t().ParseError))throw e;r.errorCallback("KaTeX auto-render: Failed to parse `"+n[a].data+"` with ",e),i.appendChild(document.createTextNode(n[a].rawData));continue}i.appendChild(l)}return i},d=function e(t,r){for(var n=0;n<t.childNodes.length;n++){var i=t.childNodes[n];if(3===i.nodeType){for(var a=i.textContent,o=i.nextSibling,d=0;o&&o.nodeType===Node.TEXT_NODE;)a+=o.textContent,o=o.nextSibling,d++;var s=l(a,r);if(s){for(var f=0;f<d;f++)i.nextSibling.remove();n+=s.childNodes.length-1,t.replaceChild(s,i)}else n+=d}else 1===i.nodeType&&function(){var t=" "+i.className+" ";-1===r.ignoredTags.indexOf(i.nodeName.toLowerCase())&&r.ignoredClasses.every((function(e){return-1===t.indexOf(" "+e+" ")}))&&e(i,r)}()}},s=function(e,t){if(!e)throw new Error("No element provided to render");var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);r.delimiters=r.delimiters||[{left:"$$",right:"$$",display:!0},{left:"\\(",right:"\\)",display:!1},{left:"\\begin{equation}",right:"\\end{equation}",display:!0},{left:"\\begin{align}",right:"\\end{align}",display:!0},{left:"\\begin{alignat}",right:"\\end{alignat}",display:!0},{left:"\\begin{gather}",right:"\\end{gather}",display:!0},{left:"\\begin{CD}",right:"\\end{CD}",display:!0},{left:"\\[",right:"\\]",display:!0}],r.ignoredTags=r.ignoredTags||["script","noscript","style","textarea","pre","code","option"],r.ignoredClasses=r.ignoredClasses||[],r.errorCallback=r.errorCallback||console.error,r.macros=r.macros||{},d(e,r)}}(),i=i.default}()}));
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(fonts/KaTeX_AMS-Regular.woff2) format("woff2"),url(fonts/KaTeX_AMS-Regular.woff) format("woff"),url(fonts/KaTeX_AMS-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Caligraphic-Bold.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Bold.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Caligraphic-Regular.woff2) format("woff2"),url(fonts/KaTeX_Caligraphic-Regular.woff) format("woff"),url(fonts/KaTeX_Caligraphic-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Fraktur-Bold.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Bold.woff) format("woff"),url(fonts/KaTeX_Fraktur-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Fraktur-Regular.woff2) format("woff2"),url(fonts/KaTeX_Fraktur-Regular.woff) format("woff"),url(fonts/KaTeX_Fraktur-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Main-Bold.woff2) format("woff2"),url(fonts/KaTeX_Main-Bold.woff) format("woff"),url(fonts/KaTeX_Main-Bold.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Main-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Main-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Main-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Main-Italic.woff2) format("woff2"),url(fonts/KaTeX_Main-Italic.woff) format("woff"),url(fonts/KaTeX_Main-Italic.ttf) format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Main-Regular.woff2) format("woff2"),url(fonts/KaTeX_Main-Regular.woff) format("woff"),url(fonts/KaTeX_Main-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Math-BoldItalic.woff2) format("woff2"),url(fonts/KaTeX_Math-BoldItalic.woff) format("woff"),url(fonts/KaTeX_Math-BoldItalic.ttf) format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Math-Italic.woff2) format("woff2"),url(fonts/KaTeX_Math-Italic.woff) format("woff"),url(fonts/KaTeX_Math-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:700;src:url(fonts/KaTeX_SansSerif-Bold.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Bold.woff) format("woff"),url(fonts/KaTeX_SansSerif-Bold.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:italic;font-weight:400;src:url(fonts/KaTeX_SansSerif-Italic.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Italic.woff) format("woff"),url(fonts/KaTeX_SansSerif-Italic.ttf) format("truetype")}@font-face{font-family:"KaTeX_SansSerif";font-style:normal;font-weight:400;src:url(fonts/KaTeX_SansSerif-Regular.woff2) format("woff2"),url(fonts/KaTeX_SansSerif-Regular.woff) format("woff"),url(fonts/KaTeX_SansSerif-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Script-Regular.woff2) format("woff2"),url(fonts/KaTeX_Script-Regular.woff) format("woff"),url(fonts/KaTeX_Script-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size1-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size1-Regular.woff) format("woff"),url(fonts/KaTeX_Size1-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size2-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size2-Regular.woff) format("woff"),url(fonts/KaTeX_Size2-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size3-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size3-Regular.woff) format("woff"),url(fonts/KaTeX_Size3-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size4-Regular.woff2) format("woff2"),url(fonts/KaTeX_Size4-Regular.woff) format("woff"),url(fonts/KaTeX_Size4-Regular.ttf) format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Typewriter-Regular.woff2) format("woff2"),url(fonts/KaTeX_Typewriter-Regular.woff) format("woff"),url(fonts/KaTeX_Typewriter-Regular.ttf) format("truetype")}.katex{text-rendering:auto;font:normal 1.21em KaTeX_Main,Times New Roman,serif;line-height:1.2;text-indent:0}.katex *{-ms-high-contrast-adjust:none!important;border-color:currentColor}.katex .katex-version:after{content:"0.16.9"}.katex .katex-mathml{clip:rect(1px,1px,1px,1px);border:0;height:1pxLine truncated
+1
View File
@@ -0,0 +1 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.katex=t():e.katex=t()}("undefined"!=typeof self?self:this,(function(){return function(){"use strict";var e={d:function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{default:function(){return na}});var r=function e(t,r){this.name=void 0,this.position=void 0,this.length=void 0,this.rawMessage=void 0;var n,a,i="KaTeX parse error: "+t,o=r&&r.loc;if(o&&o.start<=o.end){var s=o.lexer.input;n=o.start,a=o.end,n===s.length?i+=" at end of input: ":i+=" at position "+(n+1)+": ";var l=s.slice(n,a).replace(/[^]/g,"$&\u0332");i+=(n>15?"\u2026"+s.slice(n-15,n):s.slice(0,n))+l+(a+15<s.length?s.slice(a,a+15)+"\u2026":s.slice(a))}var h=new Error(i);return h.name="ParseError",h.__proto__=e.prototype,h.position=n,null!=n&&null!=a&&(h.length=a-n),h.rawMessage=t,h};r.prototype.__proto__=Error.prototype;var n=r,a=/([A-Z])/g,i={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},o=/[&><"']/g;var s=function e(t){return"ordgroup"===t.type||"color"===t.type?1===t.body.length?e(t.body[0]):t:"font"===t.type?e(t.body):t},l={contains:function(e,t){return-1!==e.indexOf(t)},deflt:function(e,t){return void 0===e?t:e},escape:function(e){return String(e).replace(o,(function(e){return i[e]}))},hyphenate:function(e){return e.replace(a,"-$1").toLowerCase()},getBaseElem:s,isCharacterBox:function(e){var t=s(e);return"mathord"===t.type||"textord"===t.type||"atom"===t.type},protocolFromUrl:function(e){var t=/^\s*([^\\/#]*?)(?::|&#0*58|&#x0*3a)/i.exec(e);return null!=t?t[1]:"_relative"}},h={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format <type>"},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color <color>",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:function(e){return"#"+e}},macros:{type:"object",cli:"-m, --macro <def>",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:function(e,t){return t.push(e),t}},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:function(e){return Math.max(0,e)},cli:"--min-rule-thickness <size>",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:function(e){return Math.max(0,e)},cli:"-s, --max-size <n>",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:function(e){return Math.max(0,e)},cli:"-e, --max-expand <n>",cliProcessor:function(e){return"Infinity"===e?1/0:parseInt(e)}},globalGroup:{type:"boolean",cli:!1}};function c(e){if(e.default)return e.default;var t=e.type,r=Array.isArray(t)?t[0]:t;if("string"!=typeof r)return r.enum[0];switch(r){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{}}}var m=function(){function e(e){for(var t in this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void Line truncated
+1
View File
@@ -0,0 +1 @@
!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("katex"));else if("function"==typeof define&&define.amd)define(["katex"],e);else{var n="object"==typeof exports?e(require("katex")):e(t.katex);for(var o in n)("object"==typeof exports?exports:t)[o]=n[o]}}("undefined"!=typeof self?self:this,(function(t){return function(){"use strict";var e={771:function(e){e.exports=t}},n={};function o(t){var a=n[t];if(void 0!==a)return a.exports;var r=n[t]={exports:{}};return e[t](r,r.exports,o),r.exports}o.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return o.d(e,{a:e}),e},o.d=function(t,e){for(var n in e)o.o(e,n)&&!o.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},o.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};var a={};return function(){var t=o(771),e=o.n(t);e().__defineMacro("\\ce",(function(t){return n(t.consumeArgs(1)[0],"ce")})),e().__defineMacro("\\pu",(function(t){return n(t.consumeArgs(1)[0],"pu")})),e().__defineMacro("\\tripledash","{\\vphantom{-}\\raisebox{2.56mu}{$\\mkern2mu\\tiny\\text{-}\\mkern1mu\\text{-}\\mkern1mu\\text{-}\\mkern2mu$}}");var n=function(t,e){for(var n="",o=t.length&&t[t.length-1].loc.start,i=t.length-1;i>=0;i--)t[i].loc.start>o&&(n+=" ",o=t[i].loc.start),n+=t[i].text,o+=t[i].text.length;return r.go(a.go(n,e))},a={go:function(t,e){if(!t)return[];void 0===e&&(e="ce");var n,o="0",r={};r.parenthesisLevel=0,t=(t=(t=t.replace(/\n/g," ")).replace(/[\u2212\u2013\u2014\u2010]/g,"-")).replace(/[\u2026]/g,"...");for(var i=10,c=[];;){n!==t?(i=10,n=t):i--;var u=a.stateMachines[e],p=u.transitions[o]||u.transitions["*"];t:for(var s=0;s<p.length;s++){var _=a.patterns.match_(p[s].pattern,t);if(_){for(var d=p[s].task,m=0;m<d.action_.length;m++){var l;if(u.actions[d.action_[m].type_])l=u.actions[d.action_[m].type_](r,_.match_,d.action_[m].option);else{if(!a.actions[d.action_[m].type_])throw["MhchemBugA","mhchem bug A. Please report. ("+d.action_[m].type_+")"];l=a.actions[d.action_[m].type_](r,_.match_,d.action_[m].option)}a.concatArray(c,l)}if(o=d.nextState||o,!(t.length>0))return c;if(d.revisit||(t=_.remainder),!d.toContinue)break t}}if(i<=0)throw["MhchemBugU","mhchem bug U. Please report."]}},concatArray:function(t,e){if(e)if(Array.isArray(e))for(var n=0;n<e.length;n++)t.push(e[n]);else t.push(e)},patterns:{patterns:{empty:/^$/,else:/^./,else2:/^./,space:/^\s/,"space A":/^\s(?=[A-Z\\$])/,space$:/^\s$/,"a-z":/^[a-z]/,x:/^x/,x$:/^x$/,i$:/^i$/,letters:/^(?:[a-zA-Z\u03B1-\u03C9\u0391-\u03A9?@]|(?:\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))))+/,"\\greek":/^\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))/,"one lowercase latin letter $":/^(?:([a-z])(?:$|[^a-zA-Z]))$/,"$one lowercase latin letter$ $":/^\$(?:([a-z])(?:$|[^a-zA-Z]))\$$/,"one lowercase greek letter $":/^(?:\$?[\u03B1-\u03C9]\$?|\$?\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega)\s*\$?)(?:\s+|\{\}|(?![a-zA-Z]))$/,digits:/^[0-9]+/,"-9.,9":/^[+\-]?(?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))/,"-9.,9 no missing 0":/^[+\-]?[0-9]+(?:[.,][0-9]+)?/,"(-)(9.,9)(e)(99)":function(t){var e=t.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))?(\((?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))\))?(?:([eE]|\s*(\*|x|\\times|\u00D7)\s*10\^)([+\-]?[0-9]+|\{[+\-]?[0-9]+\}))?/);return e&&e[0]?{match_:e.splice(1),remainder:t.substr(e[0].length)}:null},"(-)(9)^(-9)":function(t){var e=t.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+)?)\^([+\-]?[0-9]+|\{[+\-]?[0-9]+\})/);return e&&e[0]?{match_:e.splice(1),remainder:t.substr(e[0].length)}:null},"state of aggregation $":function(t){var e=a.patterns.findObserveGroups(t,"",/^\([a-z]{1,3}(?=[\),])/,")","");if(e&&e.remainder.match(/^($|[\s,;\)\]\}])/))return e;var n=t.match(/^(?:\((?:\\ca\s?)?\$[amothc]\$\))/);return n?{match_:n[0],remainder:t.substr(n[0].length)}:null},"_{(state of aggregation)}$":/^_\{(\([a-z]{1,3}\))\}/,"{[(":/^(?:\\\{|\[|\()/,")]}":/^(?:\)|\]|\\\})/,", ":/^[,;]\s*/,",":/^[,;]/,".":/^[.]/,". ":/^([.\u22C5\u00B7\u2022])\s*/,"...":/^\.\.\.(?=$|[^.])/,"* ":/^([*])\s*/,"^{(...)}":function(t){return a.patterns.findObserveGroups(t,"^{","","","}")},"^($...$)":function(t){return a.patterns.findObserveGroups(t,"^","$","$","")},"^a":/^\^([0-9]+|[^\\_])/,"^\\x{}{}":function(t){return a.patterns.findObserveGroups(t,"^",/^\\[a-zA-Z]+\{/,"}","","","{","}","",!0)},"^\\x{}":function(t){return a.patterns.findObserveGroups(t,"^",/^\\[a-zA-Z]+\{/,"}","")},"^\\x":/^\^(\\[a-zA-Z]+)\s*/,"^(-1)":/^\^(-?\d+)/,"'":/^'/,"_{(...)}":function(t){return a.patterns.Line truncated
+71
View File
@@ -0,0 +1,71 @@
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module){"use strict";var _Mathmin=Math.min,_Mathmax=Math.max;const Drawer=require("./src/Drawer"),Parser=require("./src/Parser"),ReactionParser=require("./src/ReactionParser"),SvgDrawer=require("./src/SvgDrawer"),ReactionDrawer=require("./src/ReactionDrawer"),SmiDrawer=require("./src/SmilesDrawer"),GaussDrawer=require("./src/GaussDrawer");var canUseDOM=!!("undefined"!=typeof window&&window.document&&window.document.createElement),SmilesDrawer={Version:"1.0.0"};SmilesDrawer.Drawer=Drawer,SmilesDrawer.Parser=Parser,SmilesDrawer.SvgDrawer=SvgDrawer,SmilesDrawer.ReactionDrawer=ReactionDrawer,SmilesDrawer.ReactionParser=ReactionParser,SmilesDrawer.GaussDrawer=GaussDrawer,SmilesDrawer.clean=function(smiles){return smiles.replace(/[^A-Za-z0-9@\.\+\-\?!\(\)\[\]\{\}/\\=#\$:\*]/g,"")},SmilesDrawer.apply=function(options,selector="canvas[data-smiles]",themeName="light",onError=null){let smilesDrawer=new Drawer(options),elements=document.querySelectorAll(selector);for(var i=0;i<elements.length;i++){let element=elements[i];SmilesDrawer.parse(element.getAttribute("data-smiles"),function(tree){smilesDrawer.draw(tree,element,themeName,!1)},function(err){onError&&onError(err)})}},SmilesDrawer.parse=function(smiles,successCallback,errorCallback){try{successCallback&&successCallback(Parser.parse(smiles))}catch(err){errorCallback&&errorCallback(err)}},SmilesDrawer.parseReaction=function(reactionSmiles,successCallback,errorCallback){try{successCallback&&successCallback(ReactionParser.parse(reactionSmiles))}catch(err){errorCallback&&errorCallback(err)}},canUseDOM&&(window.SmilesDrawer=SmilesDrawer,window.SmiDrawer=SmiDrawer),SmilesDrawer.SmiDrawer=SmiDrawer,Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{value:function(value){if(null==this)throw new TypeError("this is null or not defined");for(var O=Object(this),len=O.length>>>0,start=arguments[1],relativeStart=start>>0,k=0>relativeStart?_Mathmax(len+relativeStart,0):_Mathmin(relativeStart,len),end=arguments[2],relativeEnd=void 0===end?len:end>>0,final=0>relativeEnd?_Mathmax(len+relativeEnd,0):_Mathmin(relativeEnd,len);k<final;)O[k]=value,k++;return O}}),module.exports=SmilesDrawer},{"./src/Drawer":6,"./src/GaussDrawer":10,"./src/Parser":15,"./src/ReactionDrawer":18,"./src/ReactionParser":19,"./src/SmilesDrawer":23,"./src/SvgDrawer":24}],2:[function(require,module,exports){var _NumberMAX_VALUE=Number.MAX_VALUE,_Mathsin=Math.sin,_Mathatan=Math.atan2,_Mathpow=Math.pow,_Mathcos=Math.cos,_Mathsqrt=Math.sqrt,_Mathfloor=Math.floor,_Mathround=Math.round,_MathPI=Math.PI,_Mathabs=Math.abs,_Mathmin2=Math.min,_Mathmax2=Math.max;/**
* chroma.js - JavaScript library for color conversions
*
* Copyright (c) 2011-2019, Gregor Aisch
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name Gregor Aisch may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* -------------------------------------------------------
*
* chroma.js includes colors from colorbrewer2.org, which are released under
* the following license:
*
* Copyright (c) 2002 Cynthia Brewer, Mark Harrower,
* and The Pennsylvania State University.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
* ------------------------------------------------------
*
* Named colors are taken from X11 Color Names.
* http://www.w3.org/TR/css3-color/#svg-color
*
* @preserve
*/(function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global="undefined"==typeof globalThis?global||self:globalThis,global.chroma=factory())})(this,function(){'use strict';var _Mathsign=Math.sign,_Mathlog=Math.log,_NumberNaN=Number.NaN;function rgb2lrgb(c){var abs=_Mathabs(c);return .04045>abs?c/12.92:(sign$1(c)||1)*pow$8((abs+.055)/1.055,2.4)}function lrgb2rgb(c){var abs=_Mathabs(c);return .0031308<abs?(sign(c)||1)*(1.055*pow$7(abs,1/2.4)-.055):12.92*c}function __range__(left,right,inclusive){for(var range=[],ascending=left<right,end=inclusive?ascending?right+1:right-1:right,i=left;ascending?i<end:i>end;ascending?i++:i--)range.push(i);return range}for(var limit$2=function(x,min,max){return void 0===min&&(min=0),void 0===max&&(max=1),x<min?min:x>max?max:x},limit$1=limit$2,clip_rgb$3=function(rgb){rgb._clipped=!1,rgb._unclipped=rgb.slice(0);for(var i=0;3>=i;i++)3>i?((0>rgb[i]||255<rgb[i])&&(rgb._clipped=!0),rgb[i]=limit$1(rgb[i],0,255)):3===i&&(rgb[i]=limit$1(rgb[i],0,1));return rgb},classToType={},i$1=0,list$1=["Boolean","Number","String","Function","Array","Date","RegExp","Undefined","Null"],name;i$1<list$1.length;i$1+=1)name=list$1[i$1],classToType["[object "+name+"]"]=name.toLowerCase();var type$p=function(obj){return classToType[Object.prototype.toString.call(obj)]||"object"},PI$2=_MathPI,utils={clip_rgb:clip_rgb$3,limit:limit$2,type:type$p,unpack:function(args,keyOrder){return void 0===keyOrder&&(keyOrder=null),3<=args.length?Array.prototype.slice.call(args):"object"==type$p(args[0])&&keyOrder?keyOrder.split("").filter(function(k){return void 0!==args[0][k]}).map(function(k){return args[0][k]}):args[0]},last:function(args){if(2>args.length)return null;var l=args.length-1;return"string"==type$p(args[l])?args[l].toLowerCase():null},PI:PI$2,TWOPI:2*PI$2,PITHIRD:PI$2/3,DEG2RAD:PI$2/180,RAD2DEG:180/PI$2},input$h={format:{},autodetect:[]},last$3=utils.last,clip_rgb$2=utils.clip_rgb,type$m=utils.type,_input=input$h,Color$D=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var me=this;if("object"===type$m(args[0])&&args[0].constructor&&args[0].constructor===this.constructor)return args[0];var mode=last$3(args),autodetect=!1;if(!mode){autodetect=!0,_input.sorted||(_input.autodetect=_input.autodetect.sort(function(a,b){return b.p-a.p}),_input.sorted=!0);for(var i=0,list=_input.autodetect,chk;i<list.length&&(chk=list[i],mode=chk.test.apply(chk,args),!mode);i+=1);}if(_input.format[mode]){var rgb=_input.format[mode].apply(null,autodetect?args:args.slice(0,-1));me._rgb=clip_rgb$2(rgb)}else throw new Error("unknown format: "+args);3===me._rgb.length&&me._rgb.push(1)};Color$D.prototype.toString=function(){return"function"==type$m(this.hex)?this.hex():"["+this._rgb.join(",")+"]"};var Color_1=Color$D,chroma$k=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(chroma$k.Color,[null].concat(args)))};chroma$k.Color=Color_1,chroma$k.version="2.4.2";var chroma_1=chroma$k,unpack$A=utils.unpack,max$2=_Mathmax2,unpack$z=utils.unpack,Color$C=Color_1,input$g=input$h,unpack$y=utils.unpack,type$l=utils.type,rgb2cmyk=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$A(args,"rgb"),r=ref[0],g=ref[1],b=ref[2];r/=255,g/=255,b/=255;var k=1-max$2(r,max$2(g,b)),f=1>k?1/(1-k):0,c=(1-r-k)*f,m=(1-g-k)*f,y=(1-b-k)*f;return[c,m,y,k]};Color$C.prototype.cmyk=function(){return rgb2cmyk(this._rgb)},chroma_1.cmyk=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$C,[null].concat(args,["cmyk"])))},input$g.format.cmyk=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$z(args,"cmyk");var c=args[0],m=args[1],y=args[2],k=args[3],alpha=4<args.length?args[4]:1;return 1===k?[0,0,0,alpha]:[1<=c?0:255*(1-c)*(1-k),1<=m?0:255*(1-m)*(1-k),1<=y?0:255*(1-y)*(1-k),alpha]},input$g.autodetect.push({p:2,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$y(args,"cmyk"),"array"===type$l(args)&&4===args.length)return"cmyk"}});var unpack$x=utils.unpack,last$2=utils.last,rnd=function(a){return _Mathround(100*a)/100},unpack$w=utils.unpack,rgb2hsl_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$w(args,"rgba");var r=args[0],g=args[1],b=args[2];r/=255,g/=255,b/=255;var min=_Mathmin2(r,g,b),max=_Mathmax2(r,g,b),l=(max+min)/2,s,h;return max===min?(s=0,h=_NumberNaN):s=.5>l?(max-min)/(max+min):(max-min)/(2-max-min),r==max?h=(g-b)/(max-min):g==max?h=2+(b-r)/(max-min):b==max&&(h=4+(r-g)/(max-min)),h*=60,0>h&&(h+=360),3<args.length&&void 0!==args[3]?[h,s,l,args[3]]:[h,s,l]},unpack$v=utils.unpack,last$1=utils.last,hsl2css=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var hsla=unpack$x(args,"hslaLine truncated
.element {
font: ${this.opts.fontSizeLarge}pt ${this.opts.fontFamily};
}
.sub {
font: ${this.opts.fontSizeSmall}pt ${this.opts.fontFamily};
}
`)),this.svg?this.svg.appendChild(this.style):(this.container=document.createElementNS("http://www.w3.org/2000/svg","g"),container.appendChild(this.style))}constructSvg(){let defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),masks=document.createElementNS("http://www.w3.org/2000/svg","mask"),background=document.createElementNS("http://www.w3.org/2000/svg","g"),highlights=document.createElementNS("http://www.w3.org/2000/svg","g"),paths=document.createElementNS("http://www.w3.org/2000/svg","g"),vertices=document.createElementNS("http://www.w3.org/2000/svg","g"),pathChildNodes=this.paths,mask=document.createElementNS("http://www.w3.org/2000/svg","rect");mask.setAttributeNS(null,"x",this.minX),mask.setAttributeNS(null,"y",this.minY),mask.setAttributeNS(null,"width",this.maxX-this.minX),mask.setAttributeNS(null,"height",this.maxY-this.minY),mask.setAttributeNS(null,"fill","white"),masks.appendChild(mask),masks.setAttributeNS(null,"id",this.uid+"-text-mask");for(let path of pathChildNodes)paths.appendChild(path);for(let backgroundItem of this.backgroundItems)background.appendChild(backgroundItem);for(let highlight of this.highlights)highlights.appendChild(highlight);for(let vertex of this.vertices)vertices.appendChild(vertex);for(let mask of this.maskElements)masks.appendChild(mask);for(let gradient of this.gradients)defs.appendChild(gradient);return paths.setAttributeNS(null,"mask","url(#"+this.uid+"-text-mask)"),this.updateViewbox(this.opts.scale),background.setAttributeNS(null,"style",`transform: translateX(${this.minX}px) translateY(${this.minY}px)`),this.svg?void(this.svg.appendChild(defs),this.svg.appendChild(masks),this.svg.appendChild(background),this.svg.appendChild(highlights),this.svg.appendChild(paths),this.svg.appendChild(vertices)):(this.container.appendChild(defs),this.container.appendChild(masks),this.container.appendChild(background),this.container.appendChild(paths),this.container.appendChild(vertices),this.container)}addLayer(svg){this.backgroundItems.push(svg.firstChild)}createGradient(line){let gradient=document.createElementNS("http://www.w3.org/2000/svg","linearGradient"),gradientUrl=this.uid+`-line-${this.gradientId++}`,l=line.getLeftVector(),r=line.getRightVector(),fromX=l.x,fromY=l.y,toX=r.x,toY=r.y;gradient.setAttributeNS(null,"id",gradientUrl),gradient.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),gradient.setAttributeNS(null,"x1",fromX),gradient.setAttributeNS(null,"y1",fromY),gradient.setAttributeNS(null,"x2",toX),gradient.setAttributeNS(null,"y2",toY);let firstStop=document.createElementNS("http://www.w3.org/2000/svg","stop");firstStop.setAttributeNS(null,"stop-color",this.themeManager.getColor(line.getLeftElement())||this.themeManager.getColor("C")),firstStop.setAttributeNS(null,"offset","20%");let secondStop=document.createElementNS("http://www.w3.org/2000/svg","stop");return secondStop.setAttributeNS(null,"stop-color",this.themeManager.getColor(line.getRightElement()||this.themeManager.getColor("C"))),secondStop.setAttributeNS(null,"offset","100%"),gradient.appendChild(firstStop),gradient.appendChild(secondStop),this.gradients.push(gradient),gradientUrl}createSubSuperScripts(text,shift){let elem=document.createElementNS("http://www.w3.org/2000/svg","tspan");return elem.setAttributeNS(null,"baseline-shift",shift),elem.appendChild(document.createTextNode(text)),elem.setAttributeNS(null,"class","sub"),elem}static createUnicodeCharge(n){return 1===n?"\u207A":-1===n?"\u207B":1<n?SvgWrapper.createUnicodeSuperscript(n)+"\u207A":-1>n?SvgWrapper.createUnicodeSuperscript(n)+"\u207B":""}determineDimensions(vertices){for(var i=0;i<vertices.length;i++){if(!vertices[i].value.isDrawn)continue;let p=vertices[i].position;this.maxX<p.x&&(this.maxX=p.x),this.maxY<p.y&&(this.maxY=p.y),this.minX>p.x&&(this.minX=p.x),this.minY>p.y&&(this.minY=p.y)}let padding=this.opts.padding;this.maxX+=padding,this.maxY+=padding,this.minX-=padding,this.minY-=padding,this.drawingWidth=this.maxX-this.minX,this.drawingHeight=this.maxY-this.minY}updateViewbox(scale){let x=this.minX,y=this.minY,width=this.maxX-this.minX,height=this.maxY-this.minY;if(!(0>=scale))this.svg&&(this.svg.style.width=scale*width+"px",this.svg.style.height=scale*height+"px");else if(width>height){let diff=width-height;height=width,y-=diff/2}else{let diff=height-width;width=height,x-=diff/2}this.svg.setAttributeNS(null,"viewBox",`${x} ${y} ${width} ${height}`)}drawBall(x,y,elementName){let r=this.opts.bondLength/4.5;x-r<this.minX&&(this.minX=x-r),x+r>this.maxX&&(this.maxX=x+r),y-r<this.minY&&(this.minY=y-r),y+r>this.maxY&&(this.maxY=y+r);let ball=document.createElementNS("http://www.w3.org/2000/svg","circle");ball.setAttributeNS(null,"cx",x),ball.setAttributeNS(null,"cy",y),ball.setAttributeNS(null,"r",r),ball.setAttributeNS(null,"fill",this.themeManager.getColor(elementName)),this.vertices.push(ball)}drawWedge(line){let l=line.getLeftVector().clone(),r=line.getRightVector().clone(),normals=Vector2.normals(l,r Line truncated
font: 5px Droid Sans, sans-serif;
`),textElem.appendChild(document.createTextNode(text)),this.vertices.push(textElem)}drawRing(x,y,s){let circleElem=document.createElementNS("http://www.w3.org/2000/svg","circle"),radius=MathHelper.apothemFromSideLength(this.opts.bondLength,s);circleElem.setAttributeNS(null,"cx",x),circleElem.setAttributeNS(null,"cy",y),circleElem.setAttributeNS(null,"r",radius-this.opts.bondSpacing),circleElem.setAttributeNS(null,"stroke",this.themeManager.getColor("C")),circleElem.setAttributeNS(null,"stroke-width",this.opts.bondThickness),circleElem.setAttributeNS(null,"fill","none"),this.paths.push(circleElem)}drawLine(line,dashed=!1,gradient=null,linecap="round"){let opts=this.opts,stylesArr=[["stroke-width",this.opts.bondThickness],["stroke-linecap",linecap],["stroke-dasharray",dashed?"5, 5":"none"]],l=line.getLeftVector(),r=line.getRightVector(),fromX=l.x,fromY=l.y,toX=r.x,toY=r.y,styles=stylesArr.map(sub=>sub.join(":")).join(";"),lineElem=document.createElementNS("http://www.w3.org/2000/svg","line");lineElem.setAttributeNS(null,"x1",fromX),lineElem.setAttributeNS(null,"y1",fromY),lineElem.setAttributeNS(null,"x2",toX),lineElem.setAttributeNS(null,"y2",toY),lineElem.setAttributeNS(null,"style",styles),this.paths.push(lineElem),null==gradient&&(gradient=this.createGradient(line,fromX,fromY,toX,toY)),lineElem.setAttributeNS(null,"stroke",`url('#${gradient}')`)}drawPoint(x,y,elementName){let r=.75;x-r<this.minX&&(this.minX=x-r),x+r>this.maxX&&(this.maxX=x+r),y-r<this.minY&&(this.minY=y-r),y+r>this.maxY&&(this.maxY=y+r);let mask=document.createElementNS("http://www.w3.org/2000/svg","circle");mask.setAttributeNS(null,"cx",x),mask.setAttributeNS(null,"cy",y),mask.setAttributeNS(null,"r","1.5"),mask.setAttributeNS(null,"fill","black"),this.maskElements.push(mask);let point=document.createElementNS("http://www.w3.org/2000/svg","circle");point.setAttributeNS(null,"cx",x),point.setAttributeNS(null,"cy",y),point.setAttributeNS(null,"r",r),point.setAttributeNS(null,"fill",this.themeManager.getColor(elementName)),this.vertices.push(point)}drawText(x,y,elementName,hydrogens,direction,isTerminal,charge,isotope,totalVertices,attachedPseudoElement={}){let text=[],display=elementName;for(let key in 0!==charge&&null!==charge&&(display+=SvgWrapper.createUnicodeCharge(charge)),0!==isotope&&null!==isotope&&(display=SvgWrapper.createUnicodeSuperscript(isotope)+display),text.push([display,elementName]),1===hydrogens?text.push(["H","H"]):1<hydrogens&&text.push(["H"+SvgWrapper.createUnicodeSubscript(hydrogens),"H"]),1===charge&&"N"===elementName&&attachedPseudoElement.hasOwnProperty("0O")&&attachedPseudoElement.hasOwnProperty("0O-1")&&(attachedPseudoElement={"0O":{element:"O",count:2,hydrogenCount:0,previousElement:"C",charge:""}},charge=0),attachedPseudoElement){if(!attachedPseudoElement.hasOwnProperty(key))continue;let pe=attachedPseudoElement[key],display=pe.element;1<pe.count&&(display+=SvgWrapper.createUnicodeSubscript(pe.count)),""!==pe.charge&&(display+=SvgWrapper.createUnicodeCharge(charge)),text.push([display,pe.element]),1===pe.hydrogenCount?text.push(["H","H"]):1<pe.hydrogenCount&&text.push(["H"+SvgWrapper.createUnicodeSubscript(pe.hydrogenCount),"H"])}this.write(text,direction,x,y,1===totalVertices)}write(text,direction,x,y,singleVertex){let bbox=SvgWrapper.measureText(text[0][1],this.opts.fontSizeLarge,this.opts.fontFamily);"left"===direction&&text[0][0]!==text[0][1]&&(bbox.width*=2),singleVertex?(x+bbox.width*text.length>this.maxX&&(this.maxX=x+bbox.width*text.length),x-bbox.width/2<this.minX&&(this.minX=x-bbox.width/2),y-bbox.height<this.minY&&(this.minY=y-bbox.height),y+bbox.height>this.maxY&&(this.maxY=y+bbox.height)):("right"===direction?"left"!=direction&&(x+bbox.width*text.length>this.maxX&&(this.maxX=x+bbox.width*text.length),x-bbox.width/2<this.minX&&(this.minX=x-bbox.width/2)):(x+bbox.width*text.length>this.maxX&&(this.maxX=x+bbox.width*text.length),x-bbox.width*text.length<this.minX&&(this.minX=x-bbox.width*text.length)),y-bbox.height<this.minY&&(this.minY=y-bbox.height),y+bbox.height>this.maxY&&(this.maxY=y+bbox.height),"down"===direction&&y+.8*bbox.height*text.length>this.maxY&&(this.maxY=y+.8*bbox.height*text.length),"up"===direction&&y-.8*bbox.height*text.length<this.minY&&(this.minY=y-.8*bbox.height*text.length));let cx=x,textElem=document.createElementNS("http://www.w3.org/2000/svg","text");textElem.setAttributeNS(null,"class","element");let g=document.createElementNS("http://www.w3.org/2000/svg","g");textElem.setAttributeNS(null,"fill","#ffffff"),"left"===direction&&(text=text.reverse()),("right"===direction||"down"===direction||"up"===direction)&&(x-=bbox.width/2),"left"===direction&&(x+=bbox.width/2),text.forEach((part,i)=>{const display=part[0],elementName=part[1];let tspanElem=document.createElementNS("http://www.w3.org/2000/svg","tspan");tspanElem.setAttributeNS(null,"fill",this.themeManager.getColor(elementName)),tspanElem.textContent=display,("up"===direction||"down"===direction)&&(tspanElem.s Line truncated
.text {
font: ${fontSize}pt ${fontFamily};
dominant-baseline: ideographic;
}
`)),svg.appendChild(style);let textElem=document.createElementNS("http://www.w3.org/2000/svg","text");textElem.setAttributeNS(null,"class","text");let maxLineWidth=0,totalHeight=0,lines=[];return text.split("\n").forEach(line=>{let dims=SvgWrapper.measureText(line,fontSize,fontFamily,1);if(dims.width>=maxWidth){let totalWordsWidth=0,maxWordsHeight=0,words=line.split(" "),offset=0;for(let i=0,wordDims;i<words.length;i++)wordDims=SvgWrapper.measureText(words[i],fontSize,fontFamily,1),totalWordsWidth+wordDims.width>maxWidth&&(lines.push({text:words.slice(offset,i).join(" "),width:totalWordsWidth,height:maxWordsHeight}),totalWordsWidth=0,maxWordsHeight=0,offset=i),wordDims.height>maxWordsHeight&&(maxWordsHeight=wordDims.height),totalWordsWidth+=wordDims.width;offset<words.length&&lines.push({text:words.slice(offset,words.length).join(" "),width:totalWordsWidth,height:maxWordsHeight})}else lines.push({text:line,width:dims.width,height:dims.height})}),lines.forEach(line=>{totalHeight+=line.height;let tspanElem=document.createElementNS("http://www.w3.org/2000/svg","tspan");tspanElem.setAttributeNS(null,"fill",themeManager.getColor("C")),tspanElem.textContent=line.text,tspanElem.setAttributeNS(null,"x","0px"),tspanElem.setAttributeNS(null,"y",`${totalHeight}px`),textElem.appendChild(tspanElem),line.width>maxLineWidth&&(maxLineWidth=line.width)}),svg.appendChild(textElem),{svg:svg,width:maxLineWidth,height:totalHeight}}}module.exports=SvgWrapper},{"./Line":12,"./MathHelper":13,"./UtilityFunctions":27,"./Vector2":28}],26:[function(require,module){"use strict";module.exports=class{constructor(colors,theme){this.colors=colors,this.theme=this.colors[theme]}getColor(key){return key&&(key=key.toUpperCase(),key in this.theme)?this.theme[key]:this.theme.C}setTheme(theme){this.colors.hasOwnProperty(theme)&&(this.theme=this.colors[theme])}}},{}],27:[function(require,module){"use strict";module.exports={getChargeText:function(charge){return 1===charge?"+":2===charge?"2+":-1===charge?"-":-2===charge?"2-":""}}},{}],28:[function(require,module){"use strict";var _Mathsin5=Math.sin,_Mathcos5=Math.cos,_Mathacos=Math.acos,_Mathsqrt4=Math.sqrt;class Vector2{constructor(x,y){0==arguments.length?(this.x=0,this.y=0):1==arguments.length?(this.x=x.x,this.y=x.y):(this.x=x,this.y=y)}clone(){return new Vector2(this.x,this.y)}toString(){return"("+this.x+","+this.y+")"}add(vec){return this.x+=vec.x,this.y+=vec.y,this}subtract(vec){return this.x-=vec.x,this.y-=vec.y,this}divide(scalar){return this.x/=scalar,this.y/=scalar,this}multiply(v){return this.x*=v.x,this.y*=v.y,this}multiplyScalar(scalar){return this.x*=scalar,this.y*=scalar,this}invert(){return this.x=-this.x,this.y=-this.y,this}angle(){return Math.atan2(this.y,this.x)}distance(vec){return _Mathsqrt4((vec.x-this.x)*(vec.x-this.x)+(vec.y-this.y)*(vec.y-this.y))}distanceSq(vec){return(vec.x-this.x)*(vec.x-this.x)+(vec.y-this.y)*(vec.y-this.y)}clockwise(vec){let a=this.y*vec.x,b=this.x*vec.y;if(a>b)return-1;return a===b?0:1}relativeClockwise(center,vec){let a=(this.y-center.y)*(vec.x-center.x),b=(this.x-center.x)*(vec.y-center.y);if(a>b)return-1;return a===b?0:1}rotate(angle){let tmp=new Vector2(0,0),cosAngle=_Mathcos5(angle),sinAngle=_Mathsin5(angle);return tmp.x=this.x*cosAngle-this.y*sinAngle,tmp.y=this.x*sinAngle+this.y*cosAngle,this.x=tmp.x,this.y=tmp.y,this}rotateAround(angle,vec){let s=_Mathsin5(angle),c=_Mathcos5(angle);this.x-=vec.x,this.y-=vec.y;let x=this.x*c-this.y*s,y=this.x*s+this.y*c;return this.x=x+vec.x,this.y=y+vec.y,this}rotateTo(vec,center,offsetAngle=0){this.x+=.001,this.y-=.001;let a=Vector2.subtract(this,center),b=Vector2.subtract(vec,center),angle=Vector2.angle(b,a);return this.rotateAround(angle+offsetAngle,center),this}rotateAwayFrom(vec,center,angle){this.rotateAround(angle,center);let distSqA=this.distanceSq(vec);this.rotateAround(-2*angle,center);let distSqB=this.distanceSq(vec);distSqB<distSqA&&this.rotateAround(2*angle,center)}getRotateAwayFromAngle(vec,center,angle){let tmp=this.clone();tmp.rotateAround(angle,center);let distSqA=tmp.distanceSq(vec);tmp.rotateAround(-2*angle,center);let distSqB=tmp.distanceSq(vec);return distSqB<distSqA?angle:-angle}getRotateTowardsAngle(vec,center,angle){let tmp=this.clone();tmp.rotateAround(angle,center);let distSqA=tmp.distanceSq(vec);tmp.rotateAround(-2*angle,center);let distSqB=tmp.distanceSq(vec);return distSqB>distSqA?angle:-angle}getRotateToAngle(vec,center){let a=Vector2.subtract(this,center),b=Vector2.subtract(vec,center),angle=Vector2.angle(b,a);return Number.isNaN(angle)?0:angle}isInPolygon(polygon){let inside=!1;for(let i=0,j=polygon.length-1;i<polygon.length;j=i++)polygon[i].y>this.y!=polygon[j].y>this.y&&this.x<(polygon[j].x-polygon[i].x)*(this.y-polygon[i].y)/(polygon[j].y-polygon[i].y)+polygon[i].x&&(inside=!inside);return inside}length(){return _Mathsqrt4(this.x*this.x+this.y*this.y)}lengthSq(){return this.x*this.x+this.y*this.y}normalize(){return this.divide(this.length()),this}normalized(){return Vect Line truncated
//# sourceMappingURL=smiles-drawer.min.js.map