TinyMCE: How to tell if a custom format is applied to the current selection? - tinymce

I have a custom format frmt defined, but I want to be able to tell if the format is already applied to the selection before executing execCommand('mceToggleFormat', false, 'frmt') since it isn't just a matter of toggling the <frmt> tags because I use AJAX to also fetch a ID in the tag, i.e. <frmt id='nnn'>. queryCommandState('frmt') always returns false. What am I doing wrong?
Here's the code:
ed.addButton('frmt', {
text: 'FRMT',
onclick: function() {
// I've tried using ed.queryCommandState('frmt') here to test if 'frmt' is already applied.
editor_content(ed, 'frmt'); // This uses ed.insertContent to add id='nnn'
ed.execCommand('mceToggleFormat', false, 'frmt');
}
})

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.

Latest version tinyMCE.remove() method appears to save changes to the textarea by default (with no explicit saving)

I am using a single instance on a page with many other fields and when the other fields gain focus, I call tinyMCE.remove() to remove the iframe and show the marked up text in the textarea it was refrencing. However, even without explicitly saving the content, it appreas that the remove() method will actually save whatever changes were made. This is actually acceptable for our use of the control, but I there is no documentation stating this will happen. So I'm concerned that a future version may 'fix' this and then I'll have to be sure to explicitly save the content first. Also the 'cancel' doesn't appear to do anything when including it.
Has anyone else experience this?
I was able to confirm this with the following:
Where txtDetails is the textarea used on the tinyMCE init.
$("textarea").focus(function () {
console.log($("#txtDetails").val());
tinymce.activeEditor.remove();
console.log($("#txtDetails").val());
});
This is the tinyMCE init used:
tinymce.init({
selector: '#' + clientID, //'#tinyEditor',
plugins: 'code link', // save
menubar: false,
toolbar: 'link bold italic underline forecolor', // save cancel
toolbar_mode: 'floating',
paste_block_drop: true,
paste_merge_formats: true,
paste_as_text: false,
paste_webkit_styles: 'color font-size',
smart_paste: false,
statusbar: false,
//save_enablewhendirty: false,
force_br_newlines: true,
newline_behavior: 'linebreak',
link_target_list: [
{ title: 'New page', value: '_blank' }
],
default_link_target: '_blank',
link_assume_external_targets: 'https',
init_instance_callback: function (editor) {
var $html = document.getElementById(clientID).value;
editor.setContent($html);
} //,
// save_onsavecallback: () => {
// tinymce.remove();
// },
// save_oncancelcallback: () => {
// tinymce.remove();
// }
I'm getting the same behavior with or without the save plugin.
It is expected behavior. And it is not specific to the latest version.
TinyMCE sticks to the textarea/div/etc. to change their content. But once TinyMCE is removed - it leaves the content as is.
Imagine that you need to edit the textarea content successively with two different editors. It would be much more complicated if one of the editors cleans the textarea on remove().
If you need to clean the textarea before remove(), you can call something like setContent(''). But don't forget to save the content somewhere with getContent().
I'd also recommend considering calling destroy() instead of remove, as, besides the editor itself, it removes all events, element references, etc., preventing memory leaks. destroy() calls remove() during execution.

Algolia autocomplete js with select2

I am using aloglia autocomplete.js and followed the tutorial.
I want to use autocomplete text box with others select2 selectbox.
var client = algoliasearch('YourApplicationID','YourSearchOnlyAPIKey')
var index = client.initIndex('YourIndex');
autocomplete('#search-input', { hint: false }, [
{
source: autocomplete.sources.hits(index, { hitsPerPage: 5 }),
displayKey: 'my_attribute',
templates: {
suggestion: function(suggestion) {
return suggestion._highlightResult.my_attribute.value;
}
}
}
]).on('autocomplete:selected', function(event, suggestion, dataset) {
console.log(suggestion, dataset);
$("#search-input").val(suggestion.full_name.name)
});
Problem is when I clicked anywhere beside that autocomplete box autocomplete disappear and it showed only what I typed before.
I don't want it to disappear. How can I implement it? Thanks for helping.
Please see the example below for detail problem.
Assume you have a simple form with one auto complete input field,two select2 boxes and one submit button. After you choose auto complete filed, when you click anywhere, it changed to default text. I mean, you put "piz" and it shows "pizza". Therefore you select pizza and it display "pizza".Then, you try to choose one select2 box or click anywhere. The autocomplete input field changed back to "piz".
I tried autocomplete:closed , $("#search-input").focusout to set the input field but it just changed back to my query.
To prevent it from disappearing, you can use autocomplete.js's debug option:
autocomplete('#search-input', { hint: false, debug: true }, [ /* ... */ ]);
The complete options list is available on GitHub.
Now I have it. When you need to only select and not to do any action, you can safety remove autocomplete:selected. And make sure your display key is value not object.
It saves me for trouble.

Code Mirror with Firebase mark text

I am trying to understand Code Mirror which I am using with FirePad - I get it all working, but now I want to do something a bit more 'exciting'.
I am looking to markText to make it readOnly but I cannot find out anywhere how to actually do it. My need is to load the editor, and preset with a template (best way to describe it) so that the template has some preset readOnly text and users then update the textarea after the read only text i.e. it can't be deleted/over written
Example (template being inserted into the FirePad):
<div><strong>Note</strong></div><br/>
<div>Type text in here</div><br/>
<div><strong>What has been achieved since last session</strong></div><br/>
<div>Type text in here</div><br/>
in this example people should be able to type in the area/s marked 'type text here'.
To call the text editor I use this:
var firepadRef = new Firebase('https://XXXXXXXXX.firebaseio.com/test');
var codeMirror = CodeMirror(document.getElementById('someID'), { lineWrapping: true });
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, { richTextToolbar: true, richTextShortcuts: true });
any ideas?

How do I dynamically add a Dijit widget to a Dojo form?

I'm trying to add a new FilteringSelect widget dynamically to a preexisting form I made out of declarative tags (on page load).
prereqs = 0;
function addAnotherPrerequisite(){
var newPreReqCursor = dijit.byId("Prerequisite"+(prereqs-1)).domNode;
dojo.create("input",{
id:"prerequisite"+prereqs,
jsId:"Prerequisite"+prereqs,
dojoType:"dijit.form.FilteringSelect",
store:"PrerequisitesStore",
searchAttr:"name",
style:"width: 350px;",
required:"true",
class: "appendedPreReq"},newPreReqCursor,"after");
dojo.parser.parse( newPreReqCursor.parentNode );
prereqs++;
}
This code properly builds a FilteringSelect widget, but the widget does not seem to be registered with the form. Whenever I submit the form, none of the values in the new widgets appear. The validation attribute works, though, and it properly pulls the values from the store.I can even call the new widget via its jsId(Prerequisite1, Prerequisite2, etc) It just won't POST!
Instead of dojo.create I also tried called the FilteringSelect widget directly. This also made the widget, but did not register the values with the form during POSTing.
var filteringSelect = new dijit.form.FilteringSelect({
id: "prereq"+prereqs,
jsId: "Prerequisite"+prereqs,
store: PrerequisitesStore,
searchAttr: "name",
required: true,
style: 'width: 350px;',
class: 'appendedPreReq'
},
"prerequisite"+prereqs).startup();
I'm going crazy trying to figure this out.
So it looks like there's some sort of bug or something. I had to define the 'name' attribute explicitly to get the widget to show up in my form's .getDependents() method. That's how dijit.forms gets its list of form values. After doing this I also couldn't access this widget by dijit.byId (didn't return anything, silently caught the error I guess), so I returned the object via its jsId with an eval.
prereqs = 0;
function(){
var newPreReqCursor = eval("Prerequisite"+(prereqs-1));
newPreReqCursor = newPreReqCursor.domNode;
dojo.create("input",{
id:"Prerequisite"+prereqs,
name:"Prerequisite"+prereqs,
jsId:"Prerequisite"+prereqs,
dojoType:"dijit.form.FilteringSelect",
store:"PrerequisitesStore",
searchAttr:"name",
style:"width: 350px;",
required:"true",
class: "appendedPreReq"},newPreReqCursor,"after");
var filterSelect = dojo.parser.parse( newPreReqCursor.parentNode );
}
It is very easy. Just create a new object like that:
// first let's create an empty node (you can reuse the existing one)
var node = dojo.create("div", {
// all necessary node attributes
className: "appendedPreReq",
style: {
width: "350px"
}
}, "myAnchorNodeId", "after");
// now let's create a widget
var widget = new dijit.form.FilteringSelect(
{
// all necessary widget properties
id: "prereq" + prereqs,
store: PrerequisitesStore,
searchAttr: "name",
required: true
},
node // optional node to replace with the widget
);
Read all about it:
http://docs.dojocampus.org/dijit/info
http://docs.dojocampus.org/dijit/form/FilteringSelect
yes while creating widgets as said by Eugene Lazutkin the input type hidden related with the filtering select gets the name as of the id, and also the value of the hidden field is updating correctly. But when the filtering select is created thr .create() method we need to give the name , and also the value of the hidden field is not updating after we select some values from the filtering select(even when we blur out). Eugene Lazutkin can you let me know why its happening so... how to update the value of hidden field in the .create() method.