GetmeUK / ContentTools

A JS library for building WYSIWYG editors for HTML content.
http://getcontenttools.com
MIT License
3.95k stars 395 forks source link

Customized tool: <HR> #433

Closed Ardius closed 7 years ago

Ardius commented 7 years ago

Starting from (copying) ContentTools.Tools.LineBreak i create a class to add the HR tag. It works, but i can't select the horizontal line to add styles. Is just possible to delete it as it is a character (with del or backspace). I know that there is a list of "editable elements" (p, li, img, ...) but i don't find a way to add hr.

However, this is the tool ss it is now:

class ContentTools.Tools.HorizontalLine extends ContentTools.Tool

    # Insert a HR in to the current element at the specified selection.

    ContentTools.ToolShelf.stow(@, 'horizontal-line')

    @label = 'Horizontal line'
    @icon = 'horizontal-line'

    @canApply: (element, selection) ->
        # Return true if the tool can be applied to the current
        # element/selection.
        return element.content

    @apply: (element, selection, callback) ->
        # Apply the tool to the current element

        # Dispatch `apply` event
        toolDetail = {
            'tool': this,
            'element': element,
            'selection': selection
            }
        if not @dispatchEditorEvent('tool-apply', toolDetail)
            return

        # Insert HR at the current in index
        cursor = selection.get()[0] + 1

        tip = element.content.substring(0, selection.get()[0])
        tail = element.content.substring(selection.get()[1])
        HR_tag = new HTMLString.String('<hr>', element.content.preserveWhitespace())
        element.content = tip.concat(HR_tag, tail)
        element.updateInnerHTML()
        element.taint()

        # Restore the selection
        selection.set(cursor, cursor)
        element.selection(selection)

        callback(true)

        # Dispatch `applied` event
        @dispatchEditorEvent('tool-applied', toolDetail)
anthonyjb commented 7 years ago

Yeah so because you're inserting the <hr> inline (into the HTML) it isn't an editable element (for example like an element), instead its just part of a text elements HTML body. To make it selectable, draggable, etc. you'd need to create a new element type for <hr>s, however a <hr> would currently be treated as a static element outside of text element (e.g <p>test</p><hr>) and so that probably isn't required, you'd just need your tool to insert a hr as a static element.