Skip to content

Instantly share code, notes, and snippets.

@GitaiQAQ
Created January 9, 2019 15:13
Show Gist options
  • Save GitaiQAQ/3270e71be64525a5ff03e40a2e7fd331 to your computer and use it in GitHub Desktop.
Save GitaiQAQ/3270e71be64525a5ff03e40a2e7fd331 to your computer and use it in GitHub Desktop.
自动挂载 ACE 替换普通文本域。
(function() {
'use strict';
jQuery(document).ready(function() {
let Language = {
"C": "c_cpp",
"C++": "c_cpp",
"Java": "java",
"JavaScript": "javascript",
"Python": "python"
};
class OJEditor {
lang: string = "C";
textarea: HTMLTextAreaElement;
container: JQuery<HTMLElement>;
editor: AceAjax.Editor;
constructor(ta) {
this.textarea = ta;
this.textarea.style.display = "none";
this.initContainer();
this.update();
}
initContainer() {
this.container = jQuery(`<div class="wpcw_fe_quiz_q_callforcode">
选择编程语言:
<select>
</select>
<div></div>
</div>`);
this.textarea.after(this.container.get(0));
this.initSelect(this.container.children()[0]);
this.initEditor(this.container.children()[1]);
}
initSelect(select) {
for (let name of Object.keys(Language)) {
let opt = document.createElement("option");
opt.innerText = name;
select.add(opt)
}
select.onchange = () => {
this.lang = Object.keys(Language)[select.selectedIndex];
this.editor.getSession().setMode('ace/mode/' + Language[this.lang]);
}
}
initEditor(editor) {
this.editor = ace.edit(editor);
this.editor.getSession().setUseWrapMode(true);
this.editor.getSession().setMode('ace/mode/' + Language[this.lang]);
this.editor.setFontSize("14px");
this.editor.setValue(this.textarea.value, -1);
this.editor.on('change', () => {
this.textarea.value = `language:${this.lang}\n${this.editor.getValue()}`;
this.update();
});
}
update() {
this.editor.container.style.height = ((this.editor.getSession().getScreenLength() + 1) *
this.editor.renderer.lineHeight) + "px";
this.editor.resize();
}
}
class Loader {
constructor(selector) {
let textareas = jQuery(selector);
if (textareas.length <= 0)
return;
if ("ace" in window) {
textareas.map((_, el) => {
new OJEditor(el);
});
} else {
let script = document.createElement("script");
let head = document.getElementsByTagName('head')[0];
script.async = true;
script.src = "https://cdn.bootcss.com/ace/1.4.2/ace.js";
script.onload = function () {
new Loader(selector);
};
head.appendChild(script);
return null;
}
}
}
new Loader("textarea.callforcode");
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment