Thursday 31 January 2019

Caching Selected Text Element with Google Doc Apps Script

Update: This is a better way of asking the following question.

Is there an Id like attribute for an Element in a Document which I can use to reach that element at a later time. Let's say I inserted a paragraph to a document as follows:

var myParagraph = 'This should be highlighted when user clicks a button';
body.insertParagraph(0, myParagraph);

Then the user inserts another one at the beginning manually (i.e. by typing or pasting). Now the childIndex of my paragraph changes to 1 from 0. I want to reach that paragraph at a later time and highlight it. But because of the insertion, the childIndex is not valid anymore. There is no Id like attribute for Element interface or any type implementing that. CahceService and PropertiesService only accepts String data, so I can't store myParagraphas an Object.

Do you guys have any idea to achieve what I want?

Thanks,

Old version of the same question (Optional Read):

Imagine that user selects a word and presses the highlight button of my add-on. Then she does the same thing for several more words. Then she edits the document in a way that the start end end indexes of those highlighted words change.

At this point she presses the remove highlighting button. My add-on should disable highlighting on all previously selected words. The problem is that I don't want to scan the entire document and find any highlighted text. I just want direct access to those that previously selected.

Is there a way to do that? I tried caching selected elements. But when I get them back from the cache, I get TypeError: Cannot find function insertText in object Text. error. It seems like the type of the object or something changes in between cache.put() and cache.get().

var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; ++i) {
      if (elements[i].isPartial()) {
        Logger.log('partial');
        var element = elements[i].getElement().asText();

        var cache = CacheService.getDocumentCache();
        cache.put('element', element);  


        var startIndex = elements[i].getStartOffset();
        var endIndex = elements[i].getEndOffsetInclusive();
     }
    // ...
   }

When I get back the element I get TypeError: Cannot find function insertText in object Text. error.

 var cache = CacheService.getDocumentCache();
 cache.get('text').insertText(0, ':)');  

I hope I can clearly explained what I want to achieve.



from Caching Selected Text Element with Google Doc Apps Script

No comments:

Post a Comment