GetmeUK / ContentTools

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

Adding Images by Image-Source #455

Closed cmedias closed 6 years ago

cmedias commented 6 years ago

Hi there, first of all, thanks for the nice tool!

I've written an own image uploader tool with an own ui. So I won't use the upload dialog from ContentTools.

After the upload, the uploaded images are shown on my page. Now I like to include them after the focused element in the editor panel by clicking an image. Can you help me, which handler I have to use and how? My js code is like this at the moment:

$('.add_img').click(function () {
    const $focused = $('.ce-element--focused');
    const src = $(this).data('img-src');
    let $img = $('<img />');
    let $img_container = $('<div />');
    $img.attr('src', src).addClass('img-responsive');
    $img.addClass('img-responsive');
    $img_container.addClass('ce-element ce-element--type-image');
    $img_container.attr('style', 'background-image: url("' + src + '")');
    $img_container.append($img);
    // $focused.after($img_container);
        // I noticed, that adding to the DOM doesn' work.
        // So it mus be sth like this? 
    editor.insert()
});
anthonyjb commented 6 years ago

Hi @cmedias so you need to create a ContentEdit.Image instance and then insert this after the currently focused element, for example:

insertAt  = () ->
    # Find insert node and index for inserting an element after the
    # focused element.

    insertNode = ContentEdit.Root.get().focused()
    unless insertNode
        return

    if insertNode.parent().type() != 'Region'
        insertNode = element.closest (node) ->
            return node.parent().type() is 'Region'

    insertIndex = insertNode.parent().children.indexOf(insertNode) + 1

    return [insertNode, insertIndex]

# Create the new image
image = new ContentEdit.Image({'src': ..., 'width': ..., 'height': ...})

# Find insert position
[node, index] = insertAt()
node.parent().attach(image, index)

# Focus the new image
image.focus()

Forgive me providing the example in CoffeeScript, I hope it's clear from this the approach I'd recommend you take