Код:
/* Client scripts module */
declare const document: any
declare const console: any
async function onInit():Promise <void> {
Context.data.editor_id = "pac-markdown-editor-" + getRandomIntString();
}
function getRandomIntString(max: number = Number.MAX_SAFE_INTEGER, min: number = 0): string {
min = Math.ceil(min);
max = Math.floor(max);
const randomValue = Math.floor(Math.random() * (max - min + 1)) + min;
return randomValue.toString();
}
function getChangedMarkdownText(text: string) {
Context.data.property_value = text;
}
async function onRender(): Promise<void> {
toastuiLoadScript(makeReadOnly);
}
function toastuiLoadScript(callback?: () => void): void {
const link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = 'https://uicdn.toast.com/editor/latest/toastui-editor.min.css';
document.head.appendChild(link);
const script = document.createElement('script');
script.src = 'https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js';
script.onload = () => {
const selectorString = `#${Context.data.editor_id}`;
const markdownEditors = document.querySelectorAll(selectorString);
markdownEditors.forEach((divItem: any) => {
//@ts-ignore
const markdownEditor = new toastui.Editor({
el: divItem,
height: Context.data.height,
initialEditType: 'wysiwyg',
initialValue: Context.data.property_value,
events: {
change: (e1: any) => {
getChangedMarkdownText(markdownEditor.getMarkdown());
}
}
});
});
callback?.();
};
document.head.appendChild(script);
}
function makeReadOnly(): void {
//Удаляем элементы из дерева если доступ тольько на чтение
if(Context.data.widget_read_only){
deleteToolbar();
deleteFooter();
setContentEditableFalse();
}
}
function deleteToolbar(): void {
const selector = `#${Context.data.editor_id} > div > div.toastui-editor-toolbar`;
const toolbarElement = document.querySelector(selector);
if (toolbarElement) {
toolbarElement.remove(); // Удаляем элементы из дерева
console.log('Markdown editor: Toolbar has been deleted.');
} else {
console.log('Markdown editor: Toolbar element not found.');
console.log(selector);
}
}
function deleteFooter(): void {
const selector = `#${Context.data.editor_id} > div > div.toastui-editor-mode-switch`;
const footerElement = document.querySelector(selector);
if (footerElement) {
footerElement.remove(); // Удаляем элементы из дерева
console.log('Markdown editor: Footer has been deleted.');
} else {
console.log('Markdown editor: Footer element not found.');
console.log(selector);
}
}
function setContentEditableFalse(): void {
const selector = `#${Context.data.editor_id} > div > div.toastui-editor-main.toastui-editor-ww-mode > div > div.toastui-editor-ww-container > div > div`;
const editableDiv = document.querySelector(selector);
if (editableDiv) {
// делаем поле нередактируемым
editableDiv.setAttribute('contenteditable', 'false');
} else {
console.log('Markdown editor: Textbox not found');
}
}