import './style.scss' /* EditorJS */ import { API, BlockTool } from '@editorjs/editorjs' /* Utils */ import { make } from './utils/dom.util' import { makeSelect } from './ui' import { Utils } from './utils/util' /* Libs */ import hljs from 'highlight.js/lib/core' import type { LanguageFn } from 'highlight.js' import { HIGHLIGHTJS_LANGUAGES } from './constants/highlightjs-languages' type LanguageModule = LanguageFn | { default: LanguageFn } type LanguageModuleContext = { (request: string): Promise keys(): string[] } declare const require: { context: ( request: string, recursive: boolean, regExp: RegExp, mode: 'lazy', ) => LanguageModuleContext } const languageModuleContext = require.context( '../node_modules/highlight.js/lib/languages', false, /\.js$/, 'lazy', ) const availableLanguageModules = new Set(languageModuleContext.keys()) const languageModuleAliases: Record = { dpr: 'delphi', graph: 'roboconf', hbs: 'handlebars', k: 'q', p21: 'step21', tex: 'latex', yml: 'yaml', } const languageModulePromises = new Map>() async function loadLanguageModule(language: string): Promise { const normalizedLanguage = language.toLowerCase() const moduleName = languageModuleAliases[normalizedLanguage] ?? normalizedLanguage const request = `./${moduleName}.js` if (!availableLanguageModules.has(request)) return false let loadPromise = languageModulePromises.get(moduleName) if (!loadPromise) { loadPromise = languageModuleContext(request).then((loadedModule) => { const languageDefinition = typeof loadedModule === 'function' ? loadedModule : loadedModule.default hljs.registerLanguage(moduleName, languageDefinition) }) languageModulePromises.set(moduleName, loadPromise) } try { await loadPromise } catch (error) { languageModulePromises.delete(moduleName) throw error } return true } export interface ISupportedLanguage { label: string value: string } export interface ICodeBlockData { language: string code: string caption: string } export interface ICodeBlockConfigs { allowValidation?: boolean supportedLanguages?: ISupportedLanguage[] defaultLanguage?: string onContentCopied?: (content: string) => unknown } export interface ICodeBlockConstructorParams { data?: ICodeBlockData config?: ICodeBlockConfigs api?: API readOnly?: boolean } export default class CodeBlock implements BlockTool { /** * Reference for editing area */ private inputRef: HTMLTextAreaElement | null = null /** * Reference for higlighting area */ private codeRef: HTMLElement | null = null /** * Reference for block container */ private containerRef: HTMLDivElement | null = null /** * Reference for caption input */ private captionInputRef: HTMLTextAreaElement | null = null /** * List of supported languages for highlighting syntax * Please check more information at: https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md */ private supportedLanguages: ISupportedLanguage[] = [] /** * Current language used for highlighting */ private currentSelectedLanguage = '' /** * A flag to check whether user just copied code */ private copiedContent = false /** * A flag to check whether the block has caption */ private useCaption = false /** * Saved data */ private data: ICodeBlockData | null = null /** * Configs when EditorJS initializes */ private configs: ICodeBlockConfigs = { allowValidation: true, } /** * EditorJS API */ private api: API | null = null /** * A flag to check whether the content is for readOnly */ private readOnly = false constructor({ data, config, api, readOnly }: ICodeBlockConstructorParams) { /* Build supported languages based on hljs registered languages */ this.buildSupportedLanguages(config ? config.supportedLanguages : []) /* Save Config */ /* When readOnly mode is true, then there's no point to set config here */ if (config && !readOnly) { this.configs = Object.assign(this.configs, config) if (config.defaultLanguage) { const index = this.supportedLanguages.findIndex( (l) => l.value === config.defaultLanguage, ) if (index !== -1) { this.currentSelectedLanguage = config.defaultLanguage } else { throw new Error( 'The default language you provided is not existed in the given supported languages. More detail about supported languages from highlight.js: https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md', ) } } else { this.currentSelectedLanguage = this.supportedLanguages[0].value } } /* Check saved data */ if (data && this.isDataValid(data)) { // Saved data is valid, initialize block from the saved data this.data = data this.currentSelectedLanguage = data.language } /* Save API */ if (api) { this.api = api } /* Save readOnly */ this.readOnly = Boolean(readOnly) } /* Getters */ /** * Notify core that read-only mode is supported * * @returns {boolean} */ static get isReadOnlySupported() { return true } /** * Get Tool toolbox settings * icon - Tool icon's SVG * title - title to show in toolbox * * @returns {{icon: string, title: string}} */ static get toolbox() { return { title: 'Code', icon: '', } } /** * Whether validating on block is allowed * @returns {boolean} */ get allowValidation() { return this.configs.allowValidation } /** * Check whether the saved data is valid to display * @param data * @returns {boolean} */ isDataValid(data: unknown) { if (data === null) return false if (typeof data === 'object') { return ( 'language' in data && 'code' in data && 'caption' in data && typeof data.language === 'string' && typeof data.caption === 'string' && typeof data.code === 'string' ) } return false } buildSupportedLanguages(custom?: ISupportedLanguage[]) { let lang: ISupportedLanguage | undefined const usingCustom = Boolean(custom) for (const l of HIGHLIGHTJS_LANGUAGES) { if (usingCustom) { // Check whether user want different name for this language lang = custom!.find((lg) => lg.value === l.value) lang = lang ?? l } else { lang = l } this.supportedLanguages.push(lang) } } /** * Renders Block content * * @public * * @returns {HTMLDivElement} */ render(): HTMLElement { const codeContainer = make('div', 'editorjs-code-block') /* Build control container */ const controlContainer = make('div', 'control-container') if (this.readOnly) { const language = make('span', 'language') const lang = this.supportedLanguages.find( (l) => l.value === this.currentSelectedLanguage, ) language.innerHTML = lang ? lang.label : '' controlContainer.appendChild(language) } else { const languageSelect = makeSelect(this.supportedLanguages, { defaultOption: this.currentSelectedLanguage, onSelect: this.onSelectLanguage.bind(this), }) if (!languageSelect) { throw new Error('No supported languages are available') } controlContainer.appendChild(languageSelect) } /* Buttons */ const btnDiv = make('div', 'btn-div') /* Copy Button */ const copyButton = make('button', ['control-btn', 'copy-btn']) if (this.readOnly) { copyButton.classList.add('copy-btn-only') } const copyBtnText = this.api ? this.api.i18n.t('Copy') : 'Copy' copyButton.innerHTML = ` ${copyBtnText} ` copyButton.onclick = this.onCopyContent.bind(this) btnDiv.appendChild(copyButton) /* Caption Button */ if (!this.readOnly) { const captionButton = make('button', ['control-btn', 'caption-btn']) captionButton.innerText = this.api ? this.api.i18n.t('Caption') : 'Caption' captionButton.onclick = this.onAddCaption.bind(this) btnDiv.appendChild(captionButton) } controlContainer.appendChild(btnDiv) codeContainer.appendChild(controlContainer) const contentLayer = make('div', 'content-container') /* Build the rendered layer */ const renderedLayer = make('div', 'rendered-layer') const pre = make('pre', undefined, { 'aria-hidden': 'true', }) const code = make('code', `language-${this.currentSelectedLanguage}`) pre.appendChild(code) renderedLayer.appendChild(pre) /* Build the input layer */ const inputLayer = make('textarea', 'input-layer', { placeholder: this.api ? this.api.i18n.t('Enter your code') : 'Enter your code', }) as HTMLTextAreaElement inputLayer.disabled = this.readOnly inputLayer.spellcheck = false contentLayer.appendChild(renderedLayer) contentLayer.appendChild(inputLayer) codeContainer.appendChild(contentLayer) // Save refs this.inputRef = inputLayer as HTMLTextAreaElement this.codeRef = code this.containerRef = codeContainer as HTMLDivElement /* Fetch data if present */ if (this.data) { const savedCode = this.data.code this.inputRef.value = savedCode // wait until the input ref value is all set setTimeout(() => { this.updateContent(savedCode) }, 500) if (this.data.caption && this.data.caption.trim() !== '') { this.addCaption(this.data.caption) } } // Initialize events this.inputRef.oninput = this.onContentUpdated.bind(this) this.inputRef.onkeydown = this.onInputAreaKeyDown.bind(this) return codeContainer } /** * Return Block data * * @public * * @returns {ICodeBlockData} */ save() { if (!this.inputRef) { throw new Error('No ref found! You may forgot to call render()') } // Return back the '<' and '&' characters that were escaped for HTML rendering this.inputRef.value = this.inputRef.value .replace(/</g, '<') .replace(/&/g, '&') return { language: this.currentSelectedLanguage, code: this.inputRef.value, caption: this.captionInputRef ? this.captionInputRef.value : '', } } /** * Validate date: Check if code is not empty * @param blockData * @returns */ validate(blockData: ICodeBlockData): boolean { if (this.allowValidation) { return blockData.code.trim() !== '' } // allowValidation is disabled, // always returns true return true } /* Events */ /* Fired when content in the editing area is updated */ onContentUpdated(ev: Event) { const target = ev.target as HTMLTextAreaElement const value = target.value this.updateContent(value) } /* Fired when keydown event is detected in the editing area */ onInputAreaKeyDown(ev: KeyboardEvent) { if (ev.key === 'Enter') { ev.stopPropagation() } else if (ev.key === 'Tab') { ev.preventDefault() const target = ev.target as HTMLTextAreaElement const value = target.value const beforeTab = value.slice(0, target.selectionStart) const afterTab = value.slice(target.selectionEnd, value.length) const curPos = target.selectionEnd + 1 // Add tab character target.value = beforeTab + '\t' + afterTab // Move cursor target.selectionStart = curPos target.selectionEnd = curPos this.updateContent(target.value) ev.stopPropagation() } } /* Fired when a language is selected from the select box */ onSelectLanguage(language: string) { if (!this.codeRef || !this.inputRef) { throw new Error('No ref found! You may forgot to call render()') } this.codeRef.classList.replace( `language-${this.currentSelectedLanguage}`, `language-${language}`, ) this.currentSelectedLanguage = language // rerender code this.updateContent(this.inputRef.value) } /* Fired when the copy button is clicked */ async onCopyContent(e: MouseEvent) { if (!this.inputRef) { throw new Error('No ref found! You may forgot to call render()') } const target = e.target as HTMLButtonElement const value = this.inputRef.value const success = await Utils.CopyTextToClipBoard(value) if (success) { target.innerHTML = ` ${this.api ? this.api.i18n.t('Copied') : 'Copied'} ` if (!this.copiedContent) { setTimeout(() => { target.innerHTML = ` ${this.api ? this.api.i18n.t('Copy') : 'Copy'} ` this.copiedContent = false }, 1000) this.copiedContent = true // Callback if ( this.configs.onContentCopied && typeof this.configs.onContentCopied === 'function' ) { this.configs.onContentCopied(value) } } } } /* Fired when the caption button is clicked */ onAddCaption() { if (!this.containerRef) { throw new Error('No ref found! You may forgot to call render()') } this.addCaption() } /* Fired when keydown event is detected in the caption input field */ onCaptionKeyDown(e: KeyboardEvent) { const captionInput = this.captionInputRef const container = this.containerRef if (!captionInput || !container) { throw new Error('No ref found!') } if (e.key === 'Backspace') { const value = (e.target as HTMLTextAreaElement).value if (value === '') { container.removeChild(captionInput) this.useCaption = false } } } /* Add caption input field */ addCaption(caption = '') { const container = this.containerRef if (!container) { throw new Error('No ref found! You may forgot to call render()') } if (!this.useCaption) { const input = make('textarea', 'caption-input', { placeholder: this.api ? this.api.i18n.t('Write your caption') : 'Write your caption', }) as HTMLTextAreaElement input.disabled = this.readOnly input.onkeydown = this.onCaptionKeyDown.bind(this) container.appendChild(input) this.captionInputRef = input as HTMLTextAreaElement // auto focus on the element input.focus() // prevent creating another one this.useCaption = true } const captionInput = this.captionInputRef if (!captionInput) { throw new Error('No caption input found!') } captionInput.value = caption } /** * Render highlighted code based on given value * @param value */ async updateContent(value: string) { if (!this.codeRef || !this.inputRef) { throw new Error('No reference found! You may forgot to call render()') } if (value[value.length - 1] == '\n') { value += ' ' } // Update code this.codeRef.innerHTML = value .replace(new RegExp('&', 'g'), '&') .replace(new RegExp('<', 'g'), '<') const languageLoaded = await loadLanguageModule( this.currentSelectedLanguage, ) if (languageLoaded) { // Remove data-highlighted attribute if it exists this.codeRef.removeAttribute('data-highlighted') // Highlight hljs.highlightElement(this.codeRef) } // Update textarea height this.inputRef.style.height = '5px' this.inputRef.style.height = this.inputRef.scrollHeight + 'px' } }