Issue #2052Opened May 31, 2019by tsuwunrut-carecloud0 reactions

Merge Fields

Question

I have a question regarding merge fields, similar to https://github.com/artf/grapesjs/issues/481. I'm trying to have my merge field icon button toggle a modal with an inputdropdown, then after selecting an option from the dropdown, have the merge field insert itself.

    rte.add('newMergeField', {
      icon: `<button  onclick="searchMergField(true)" id="newMergeFieldButton">Merge Field Search</button>`,
      event: 'click',
      result: rte => {
        const { focusOffset, anchorOffset } = rte.doc.getSelection();
        window.rteInsertHTML = res => {
          const currentHtml = cloneDeep(rte.el.innerText);
          const [start, end] = focusOffset < anchorOffset ? [focusOffset, anchorOffset] : [anchorOffset, focusOffset];
          const [first, last] = [currentHtml.slice(0, start), currentHtml.slice(end, currentHtml.length - 1)];
          rte.el.innerText = first + res + last;
        }
      },
    });

^ I have something along these lines. Clicking the icon button simply stores a function in the window object to be called after I select an option from the inputdropdown. Now this actually works perfectly except for one problem. If I decide to hit "enter" multiple times at the very end of the text area and try to add a merge field at the very bottom, it'll instead add it to the beginning of the text field.

I believe this is because the Range object loses all of its offsets when I hit "enter". But if this is the case, how does simply calling rte.insertHTML() work inside of the built in event handler for the icon?

Is there anyway I can replica the behavior of rte.insertHTML() and have it insert at the very bottom of my text area after creating multiple new lines by hitting "enter"?

I've tried this with both the Selection object and the Range object (calling rte.doc.getSelection().getRangeAt(0)

Answers (1)

artfJune 2, 20190 reactions

Generally, to prevent losing selection on element click you use event.preventDefault() so it might your case, but I'm not sure. Try at least to create a reproducible demo, BTW I close the issue as it has nothing to do with the core itself

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.