ckeditor5-cta-link
Version:
Link with button class for CTA
135 lines (94 loc) • 2.79 kB
JavaScript
import Plugin from '@ckeditor/ckeditor5-core/src/plugin'
import {
toWidget,
toWidgetEditable
} from '@ckeditor/ckeditor5-widget/src/utils'
import Widget from '@ckeditor/ckeditor5-widget/src/widget'
import InsertButtonCommand from './Buttoncommand'
export default class ButtonEditing extends Plugin {
static get requires() {
return [
Widget
]
}
init() {
/* Define the schema structure */
this._defineSchema()
/* Define the converters for the schema */
this._defineConverters()
/* Register insertion command */
this.editor.commands.add('insertButton', new InsertButtonCommand(this.editor))
}
_defineSchema() {
const schema = this.editor.model.schema
schema.register('Button', {
/* Is a self contained object */
isObject: true,
inline: false,
/* Allow in places where blocks are allowed */
allowWhere: '$block',
allowAttributes: ['alt', 'href', 'target']
})
}
_defineConverters() {
const conversion = this.editor.conversion
let value = []
let href = []
/* Containing wrapper */
conversion.for('upcast').elementToElement({
model: 'Button',
view: (modelElement) => {
const index = modelElement.index
const getHref = modelElement.getAttribute('href')
const getAlt = modelElement.getAttribute('alt')
if(getHref) {
href[index] = getHref
}
if(getAlt) {
value[index] = getAlt
}
return modelElement
}
})
conversion.for('dataDowncast').elementToElement({
model: 'Button',
view: (modelElement, viewWriter) => {
const index = modelElement.index
const link = modelElement.getAttribute('href') || href[index]
const altText = modelElement.getAttribute('alt') || value[index]
const button = viewWriter.createContainerElement('a', {
class: 'button',
target: 'blank',
href: link,
alt: altText
})
if(altText) {
const innerText = viewWriter.createText(altText)
viewWriter.insert(viewWriter.createPositionAt(button, 0), innerText)
}
return button
}
})
/* Conversion while editing */
conversion.for('editingDowncast').elementToElement({
model: 'Button',
view: (modelElement, viewWriter) => {
const index = modelElement.index
const linkTo = modelElement.getAttribute('href') || href[index]
const alt = modelElement.getAttribute('alt') || value[index]
const button = viewWriter.createContainerElement('a', {
class: 'button',
target: 'blank',
href: linkTo,
alt: alt
})
const innerText = viewWriter.createText(alt)
viewWriter.insert(viewWriter.createPositionAt(button, 0), innerText)
/* To widget makes the element not editable */
return toWidget(button, viewWriter, {
label: 'Button widget'
})
}
})
}
}