Inserting text following selection in Office-JS - ms-word

I am trying to append a hyperlink immediately following a piece of selected text in Word 2013 using the Shared JS API.
Inserting the hyperlink using OOXML works fine when inserting at current cursor with no selection. My problem is 'finding' the end of the selected text to append the OOXML.
Just using setSelectedDataAsync overwrites the existing text. I have tried reading the selected text as OOXML and concatenating the hyperlink XML to it but without success.
I have not tried reading the current selection and then modifying that OOXML but would prefer to avoid.
In the Word JS API a before and after are provided on the selection so it is straightforward to do. Is it possible to do this in the Shared API? Thanks.

The following code sample illustrates the approach that Marc described in his comment above (with one exception: it gets the selected data as Text, not as HTML).
This snippet uses getSelectedDataAsync to get the selected data (as Text), and then appends a hyperlink to that data and uses setSelectedDataAsync to push that string back into the document (as HTML).
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
{ valueFormat: "unformatted" },
function (asyncResult) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log(error.name + ": " + error.message);
}
else {
// Get selected data.
var dataValue = asyncResult.value;
console.log("Selected data is: " + dataValue);
// Create newText by appending hyperlink to dataValue.
var myHyperlink = "<a href='https://www.bing.com'>https://www.bing.com</a>";
var newText = dataValue + " " + myHyperlink;
console.log("New text is: " + newText);
// Replace selected text with newText value.
Office.context.document.setSelectedDataAsync(newText, { coercionType: "html" },
function (asyncResult) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log(error.name + ": " + error.message);
}
});
}
});
Note: One side-effect of getting the selected data as Text, as this snippet does, is that when you write back that string (with the hyperlink appended) to the document, you'll lose any formatting (for example: font color, style, etc.) that was previously present in the selected text. If it's important that you preserve formatting of the originally selected text, you'll need to get the selected data as HTML and then append your hyperlink to the the portion of HTML which contains the originally selected text, before writing that HTML back to the document.
You can quickly and easily try this code snippet yourself in Word by using Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following GIST URL: https://gist.github.com/kbrandl/8e235fb0ccc190bf42ed9ce1874f5559.

Related

Understanding binding and selection in Word Add-in

I'm trying to build an add-in with similar behaviour like the comment system.
I select a part of text.
Press a button in my add-in. A card is created that links to that text.
I do something else, like write text on a different position.
When I press the card in my add-in, I'd like to jump back to the selected text (in point 1).
I studied the API, documentation. And learned that I could do something like that with Bindings. A contentcontrol might also be an option, although I noticed that you can't connect and eventhandler (it's in beta). I might need an eventhandler to track changes later.
Create binding (step 2)
Office.context.document.bindings.addFromSelectionAsync(Office.BindingType.Text, { id: 'MyBinding' }, (asyncResult) => {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
console.log('Action failed. Error: ' + asyncResult.error.message);
} else {
console.log('Added new binding with id: ' + asyncResult.value.id);
}
});
Works. Then I click somewhere else in my document, to continue with step 4.
View binding (step 4).
So I click the card and what to jump back to that text binding, with the binding selected.
I figured there are multiple ways.
Method #1
Use the Office.select function below logs the text contents of the binding. However, it doesn't select that text in the document.
Office.select("bindings#MyBinding").getDataAsync(function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
}
else {
console.log(asyncResult.value);
}
});
Method #2
Use the GoToById function to jump to the binding.
Office.context.document.goToByIdAsync("MyBinding", Office.GoToType.Binding, function (asyncResult) {
let val = asyncResult.value;
console.log(val);
});
This shows like a blue like frame around the text that was previously selected and puts the cursor at the start.
I'd prefer that I don't see that frame (no idea if that's possible) and I would like to the text selected.
There is the Office.GoToByIdOptions interface that mentions:
In Word: Office.SelectionMode.Selected selects all content in the binding.
I don't understand how pass that option in the function call though and I can't find an example. Can I use this interface to get the selection?
https://learn.microsoft.com/en-us/javascript/api/office/office.document?view=common-js-preview#office-office-document-gotobyidasync-member(1)
goToByIdAsync(id, goToType, options, callback)
If there are other ways to do this, I'd like to know that as well.
With some help I could figure it out. I learned that an Interface is just an object.
So in this case:
const options = {
selectionMode: Office.SelectionMode.Selected
};
Office.context.document.goToByIdAsync("MyBinding", Office.GoToType.Binding, options, function (asyncResult) {
console.log(asyncResult);
});
This gives the selected result.
Sure someone can provide a better answer than this, as it's unfamiliar territory for me, but...
When you create a Binding from the Selection in Word, you're going to get a Content Control anyway. So to avoid having something that looks like a content control with the blue box, you either have to modify the control's display or you have to find some other way to reference a region of your document. In the traditional Word Object model, you could use a bookmark, for example. But the office-js APIs do not seem very interested in them.
However, when you create a Binding, which is an Office object, you don't get immediate access to the Content Control's properties (since that's a Word object). So instead of creating the Binding then trying to modify the Content Control, you may be better off creating the Content Control then Binding to it.
Something like this:
async function markTarget() {
Word.run(async (context) => {
const cc = context.document.getSelection().insertContentControl();
// "Hidden" means you don't get the "Bounding Box"
// (blue box with Title), or the Start/End tag view
cc.appearance = "Hidden";
// Provide a Title so we have a Name to bind to
cc.title = "myCC";
// If you don't want users changing the content, you
// could uncomment the following line
//cc.cannotDelete = true;
return context.sync()
.then(
() => {
console.log("Content control inserted");
// Now create a binding using the named item
Office.context.document.bindings.addFromNamedItemAsync("myCC",
Office.BindingType.Text,
{ id: 'MyBinding' });
},
() => console.log("Content control insertion failed")
).then(
() => console.log("Added new binding"),
() => console.log("Binding creation failed")
)
});
}
So why not just create the ContentControl, name it, and then you should be able to select it later using its Title, right? Well, getting the "data" from a control is one thing. Actually selecting it doesn't seem straightforward in the API, whereas Selecting a Binding seems to be.
So this code is pretty similar to your approach, but adds the parameter to select the whole text. The syntax for that is really the same syntax as { id: 'MyBinding' } in the code you already have.
function selectTarget() {
Office.context.document.goToByIdAsync(
"MyBinding",
Office.GoToType.Binding,
{ selectionMode: Office.SelectionMode.Selected },
function(asyncResult) {
let val = asyncResult.value;
console.log(val);
}
);
}
Both the Binding and the ContentControl (and its Title) are persisted when you save/reopen the document. In this case, the Binding is persisted as a piece of XML that stores the type ("text"), name ("MyBinding") and a reference to the internal ID of the content control, which is a 32-bit number, although that is not immediately obvious when you look at the XML - in an example here, the Id Word stores for the ContentControl is -122165626, but "Office" stores the ID for the Binding as 4172801670, but that's because they are using the two different two's complement representations of the same number.

Check if text selection is in header/footer

The Word Addin we created allows adding custom comments to text selections. Word does not allow adding comments in headers / footers. Because of that, users should get warned when text in a header/footer is selected.
The selection's OOXML structure for text in body and text in header is identical.
The Word UI itself disabled the review comments section when footer/header text is selected.
When dumping the text selection object to te console, none of the object fields point to the selection being in header/footer.
How can be found out programmatically that text is selected in the header/footer?
Issue: https://github.com/OfficeDev/office-js/issues/341
You can achieve this by looking at the parentBody property of the selection range. The type property on the parentBody will reveal whether the selection is in the 'Header' or elsewhere (see documentation).
Example
function determineSelectionInHeader() {
Word.run(function (context) {
const HEADER_TYPE = "Header";
// Retrieve and load 'type' of selection.
var selection = context.document.getSelection();
var parentBody = selection.parentBody;
parentBody.load("type");
context
.sync()
.then(function () {
if (parentBody.type === HEADER_TYPE) {
console.log("This is the header");
}
});
});
}

Insert a line break with inserted text in a Word document

Building a word add-in using javascript (office.js) to insert text. So far unformatted text with .insertText. If I would like to insert the below, which function should be used?
formatted text (for instance size, font, style)
Line break
Bullet point
Code:
results.items[i].insertText("Any text going here.", "replace");
How would I for instance insert a line break in the "Any text going here"?
Using JavaScript, add a "line-break" (I'm assuming you mean the same as pressing ENTER in the UI - this is technically a new paragraph) using the string "\n". So, for example:
results.items[i].insertText("Any text going here.\n", "replace");
Use insertBreak for inserting breaks of different types. It could be line break, paragraph break, section break etc.
insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void;
For adding lists like bullet points. Use startNewList
startNewList(): Word.List;
List example
//This example starts a new list stating with the second paragraph.
await Word.run(async (context) => {
let paragraphs = context.document.body.paragraphs;
paragraphs.load("$none"); //We need no properties.
await context.sync();
var list = paragraphs.items[1].startNewList(); //Indicates new list to be started in the second paragraph.
list.load("$none"); //We need no properties.
await context.sync();
//To add new items to the list use start/end on the insert location parameter.
list.insertParagraph('New list item on top of the list', 'Start');
let paragraph = list.insertParagraph('New list item at the end of the list (4th level)', 'End');
paragraph.listItem.level = 4; //Sets up list level for the lsit item.
//To add paragraphs outside the list use before/after:
list.insertParagraph('New paragraph goes after (not part of the list)', 'After');
await context.sync();
});
For formatting text, you can get hints by looking at examples here which set Font family and color of text.
//adding formatting like html style
var blankParagraph = context.document.body.paragraphs.getLast().insertParagraph("", "After");
blankParagraph.insertHtml('<p style="font-family: verdana;">Inserted HTML.</p><p>Another paragraph</p>', "End");
// another example using modern Change the font color
// Run a batch operation against the Word object model.
Word.run(function (context) {
// Create a range proxy object for the current selection.
var selection = context.document.getSelection();
// Queue a commmand to change the font color of the current selection.
selection.font.color = 'blue';
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('The font color of the selection has been changed.');
});
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
The Word addin tutorial has a lot of nifty tricks for common tasks with code samples.

Mapbox GL Popup .setDOMContent example

I'm trying to create a customized button to appear on a pop up which generates a dynamic link (a URL). I don't seem to be able to do this via the .setHTML because of the timing, can't bind a button to a function at runtime. So I thought I'd try the newish .setDOMContent
There's zero information online as to how this feature works. I'm wondering if anyone has an example of this where a button is added to the popup that can run a function and send data.
Here's my very poor attempt at setting this up.
This function creates the popup
function GameObjectPopup(myObject) {
var features = map.queryRenderedFeatures(myObject.point, {
layers: ['seed']
});
if (!features.length) {
return;
}
var feature = features[0];
// Populate the popup and set its coordinates
// based on the feature found.
var popup = new mapboxgl.Popup()
.setLngLat(feature.geometry.coordinates)
.setHTML(ClickedGameObject(feature))
.setDOMContent(ClickedGameObject2(feature))
.addTo(map);
};
This function adds the html via the .setHTML
function ClickedGameObject(feature){
console.log("clicked on button");
var html = '';
html += "<div id='mapboxgl-popup'>";
html += "<h2>" + feature.properties.title + "</h2>";
html += "<p>" + feature.properties.description + "</p>";
html += "<button class='content' id='btn-collectobj' value='Collect'>";
html += "</div>";
return html;
}
This function wants to add the DOM content via the .setDOMContent
function ClickedGameObject2(feature){
document.getElementById('btn-collectobj').addEventListener('click', function()
{
console.log("clicked a button");
AddGameObjectToInventory(feature.geometry.coordinates);
});
}
I'm trying to pipe the variable from features.geometry.coordinates into the function AddGameObjectToInventory()
the error I'm getting when clicking on an object (so as popup is being generated)
Uncaught TypeError: Cannot read property 'addEventListener' of null
Popup#setHTML takes a string that represents some HTML content:
var str = "<h1>Hello, World!</h1>"
popup.setHTML(str);
while Popup#setDOMContent takes actual HTML nodes. i.e:
var h1 = document.createElement('h1');
h1.innerHTML="Hello, World";
popup.setDOMContent(h1);
both of those code snippets would result in identical Popup HTML contents. You wouldn't want to use both methods on a single popup because they are two different ways to do the same thing.
The problem in the code you shared is that you're trying to use the setDOMContent to add an event listener to your button, but you don't need to access the Popup object to add the event listener once the popup DOM content has been added to the map. Here is a working version of what I think you're trying to do: https://jsfiddle.net/h4j554sk/

Does a PageDown plugin exist for Jeditable?

I am using the jQuery inline editing plugin Jeditable. Thankfully, Jeditable provides a plugin capability for extending the out of the box inline editing it provides.
I am hoping to not reinvent the wheel-- as such does a PageDown plugin already exist for Jeditable? If one does my Google-fu is not turning up any results.
I never found a ready to go Jeditable PageDown plugin so I wrote my own. The below example is too specific to be used without modification, but should provide a decent enough outline for anyone endeavoring to accomplish a similar task.
Code to add a "markdown" input type to Jeditable:
var converter = Markdown.getSanitizingConverter();
$.editable.addInputType('markdown', {
element: function(settings, original) {
var editorId = original.id.substring(original.id.lastIndexOf("-"));
var input = $('<textarea />');
input.attr('id', 'wmd-input' + editorId);
var panel = $('<div class="wmd-panel" />');
panel.append('<div id="wmd-button-bar' + editorId + '" />');
panel.append(input);
panel.append('<div id="wmd-preview' + editorId + '" />');
$(this).append(panel);
return (input);
},
plugin: function(settings, original) {
var editorId = original.id.substring(original.id.lastIndexOf("-"));
var editor = new Markdown.Editor(converter, editorId);
editor.run();
}
});
The above code goes through a bunch of gyrations concerning the elements id, because in my case I can have several editors on a single page. See the PageDown documentation about Markdown.Editor for more details.
Once I've added the "markdown" input type to Jeditable it's just a matter of utilizing it with this code:
$('.editable-element-area').editable('http://jsfiddle.net/echo/jsonp/', {
onblur: 'submit',
type: 'markdown',
indicator: 'Saving...',
loadurl: 'http://jsfiddle.net/echo/jsonp/', // retrieve existing markdown
callback: function(value, settings) {
$(this).html(converter.makeHtml(value)); // render updated markdown
}
});​
I want my users to see the markdown as HTML when they aren't editing it so I have to make use of the callback and loadurl Jeditable parameters. The load url retrieves the text to edit in markdown format, while the callback converts the new text back to html.