Word addin inserting complex list structure with styling in a contentControl using office.js done or not? - openxml

I'm trying to insert a complex list structure into a contentControl in MS Word using the javascript API. The structure is build according to an object that contains nested arrays: Different items containing sub items that contain different properties. These items arrays can change in size so it needs to be generic. Maybe the Office.js API isn't really build for what I am trying to achieve and I should be using either insertHTML (with the structure build in HTML) or OOXML.
This is the structure I already build
The function that produced this:
import ContentControl = Word.ContentControl;
import {formatDate} from '../formatters';
let firstItem = true;
let listId;
export async function resolveItems(contentControl: ContentControl, data: Array<any>, t) {
Word.run( contentControl, async (context) => {
contentControl.load('paragraphs');
await context.sync();
for (const item of data) {
if (firstItem) {
const firstPara = contentControl.paragraphs.getFirst();
firstPara.insertText('ITEM (' + formatDate(item.date) + ')', 'Replace');
firstItem = false;
const contactList = firstPara.startNewList();
contactList.load('id');
await context.sync().catch((error) => {
console.log('Error: ' + error);
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
listId = contactList.id;
} else {
const otherItem = contentControl.insertParagraph('ITEM (' + formatDate(item.date) + ')', 'End');
otherItem.load(['isListItem']);
await context.sync();
otherItem.attachToList(listId, 0);
}
for (const subItem of item.subItems) {
let descriptionParaList = new Array();
let subItemPara = contentControl.insertParagraph(subItem.title + ' (' + formatDate(subItem.date) + ')', 'End');
subItemPara.load(['isListItem']);
await context.sync();
if (subItemPara.isListItem) {
subItemPara.listItem.level = 1;
} else {
subItemPara.attachToList(listId, 1);
}
let descriptions = subItem.descriptions;
for (const description of descriptions) {
let descriptionPara = contentControl.insertParagraph('', 'End');
descriptionPara.insertText(t(description.descriptionType) + ': ', 'Start').font.set({
italic: true
});
descriptionPara.insertText(description.description, 'End').font.set({
italic: false
});
descriptionPara.load(['isListItem', 'leftIndent']);
descriptionParaList.push(descriptionPara);
}
await context.sync();
for (const subItemPara of descriptionParaList) {
if (subItemPara.isListItem) {
subItemPara.detachFromList();
}
subItemPara.leftIndent = 72;
}
}
}
return context.sync().catch((error) => {
console.log('Error: ' + error);
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
});}
The data structure looks like this:
'LAST_5_Items': [
{
'date': '2019-03-14T14:51:29.506+01:00',
'type': 'ITEM',
'subItems': [
{
'date': '2019-03-14T14:51:29.506+01:00',
'title': 'SUBITEM 1',
'descriptions': [
{
'descriptionType': 'REASON',
'description': 'Reason 1',
'additionalInformation': ''
}
]
},
{
'date': '2019-03-14T14:51:29.506+01:00',
'title': 'SUBITEM 2',
'descriptions': [
{
'descriptionType': 'REASON',
'description': 'Reason 1',
'additionalInformation': ''
}
]
}
]
},
{
'date': '2019-03-14T14:16:26.220+01:00',
'type': 'ITEM',
'subItems': [
{
'date': '2019-03-14T14:16:26.220+01:00',
'title': 'SUBITEM 1',
'descriptions': [
{
'descriptionType': 'REASON',
'description': 'Reason 1',
'additionalInformation': ''
}
]
},
{
'date': '2019-03-14T14:16:26.220+01:00',
'title': 'SUBITEM 2',
'descriptions': [
{
'descriptionType': 'REASON',
'description': 'Reason 1',
'additionalInformation': ''
},
{
'descriptionType': 'SUBJECTIVE',
'description': 'Subjective 1',
'additionalInformation': ''
},
{
'descriptionType': 'SUBJECTIVE',
'description': 'Subjective 2',
'additionalInformation': ''
},
{
'descriptionType': 'OBJECTIVE',
'description': 'Objective 1',
'additionalInformation': ''
},
{
'descriptionType': 'OBJECTIVE',
'description': 'Objective 2',
'additionalInformation': ''
},
{
'descriptionType': 'EVALUATION',
'description': 'Evaluation',
'additionalInformation': ''
},
{
'descriptionType': 'REASON',
'description': 'Reason 1',
'additionalInformation': ''
}
]
}
]
}
]
What I am trying to achieve is a template resolver. The addin will allow the user to put placeholder (ContentControls), tags like First name, Last name,... and the 5 last contacts (the one I am now describing) in the document and when he resolves the file it will fetch all the data needed and start replacing the ContentControls with this structured layout.
Yes the code works, but I highly doubt that the code is well structured with so many context.sync() calls. It is too slow and it is not usable.
I need so many context.sync() because I need the properties of the List ID and if a Paragraph belongs to a list.
Is there a better way to achieve what I am trying to achieve using the office.js API?
Ideally the queue should be synced once so the user would not see the content being added and changed in a very strange way like it is now behaving.
Thanks

There is a technique for avoiding having context.sync inside a loop. The basic idea is that you have two loops, with a single context.sync in between them. In the first loop, you create an array of objects. Each object contains a reference to one of the Office objects that you want to process (e.g., change, delete, etc.) It looks like paragraphs in your case. But the object has other properties. Each of them holds some item of data that you need to process the object. These other items may be properties of other Office objects or they may be other data. Also, either in your loop or just after it, you load all the properties you're going to need of all the Office objects in the objects in your array. (This is usually easier to do inside the loop.)
Then you have context.sync.
After the sync, you loop through the array of objects that you created before the context.sync. The code inside this second loop processes the first item in each object (which is the Office object that you want to process) using the other properties of the object you created.
Here are a couple of examples of this technique:
My answer to this StackOverflow question: Document not in sync after replace text.
This code sample:
https://github.com/OfficeDev/Word-Add-in-Angular2-StyleChecker/blob/master/app/services/word-document/word.document.service.js.

Related

Conditionally populating a path in a Mongo query

I have the following schema:
const connectionSchema = new Schema( {
...
event: {
type: Schema.ObjectId,
ref: 'events'
},
place: {
type: Schema.ObjectId,
ref: 'places'
},
} )
const eventsSchema = new Schema( {
...
place: {
type: Schema.ObjectId,
ref: 'places'
},
} )
When I query for either a single connection or a collection of connections, I want it to check if event is specified and if so return the place from the event, otherwise return the place from the connection.
I'm currently doing something like this when I'm querying a single connection:
let c
const execFunction = ( err, connection ) => {
if ( connection.event ) {
connection.place = connection.event.place
}
c = connection
}
const connectionPromise = Connection.findById( connectionId )
connectionPromise.populate( { path: 'event', populate: { path: 'place' } } )
connectionPromise.populate( 'place' )
connectionPromise.exec( execFunction )
But, I'm trying to avoid having to iterate through the entire collection in the execFunction to do the replace logic on each individual result if I query for a collection instead.
Is there a better (i.e. more performant) way to approach this?
As far as I know, there is no way to do conditional population with mongoose.
In your case, I think you are trying to do "deep population".
Deep population is not supported out of the box, but there is a plugin for that! mongoose-deep-populate
const connectionQuery = Connection.findById( connectionId )
connectionQuery.populate( 'place event event.place' )
connectionQuery.exec( execFunction );
I'm guessing that 'place event.place' will probably do it: 'event' should be implied.
I also expect that, if place or event or event.place are undefined, there won't be an error, they simply won't be populated.
But I don't think there is any way, in one line, to skip populating place when event.place is available.
By the way, if you want to use promises, you could write like this:
return Connection.findById( connectionId )
.populate( 'place event event.place' )
.then( onSuccessFunc );
to propagate errors, or:
Connection.findById( connectionId )
.populate( 'place event event.place' )
.then( onSuccessFunc )
.catch( onErrorFunc );
to handle errors locally. I find that preferable to callbacks, because we don't have to worry about if (err) at every stage.

the best way to exclude some data from a method in sails controller

I want's to exclude some data in some controller method and in other method i want's that data. I do it with forEach function right into method after finding that :
nine: function (req, res) {
Dore.find()
.limit(9)
.sort('createdAt DESC')
.populate('file')
.exec(function (err, sh) {
if (err) {
return res.negotiate(err);
} else {
console.log('before : ', sh);
sh.forEach(function (item, i) {
delete item.zaman;
});
console.log('after : ', sh);
return res.send(sh);
}
});
},
I want to know how possible to do that with finding and do not included ever in finding so we don't need to remove that again with forEach.
tanks
As #zabware say we have select method in Query option I try this format but do not work and return all data :
I try to use that with following format but don't working :
Model.find( {
where: {},
limit: 9,
sort: 'createdAt DESC'
},
{
select: [ 'id', 'createdAt' ]
} )
and
Model.find( {
where: {},
limit: 9,
sort: 'createdAt DESC',
select: [ 'id', 'createdAt' ]
} )
and
Model.find( {}, select: [ 'id', 'createdAt' ] )
Although toJson is really designed to solve the kind of problem you are facing, it will not help you, since in some actions you want to exclude certain fields and in others not.
So we need to select fields per query. Luckily there is a solution for this in waterline:
Dore.find({}, {select: ['foo', 'bar']})
.limit(9)
.sort('createdAt DESC')
.populate('file')
.exec(function (err, sh) {
console.log(err);
console.log(sh);
});
This is supported since sails 0.11 but not really documented. You can find it under query options here https://github.com/balderdashy/waterline-docs/blob/e7b9ecf2510646b7de69663f709175a186da10d5/queries/query-language.md#query-options
I accidentally stumbled upon it while playing with the debugger - Sails version 1.2.3
There is something like omit and You can put it into your find method call:
const user = await User.findOne({
where: {email : inputs.email},
omit: ['password']
}); //There won't be password field in the user object
It is a pity that there is no word about it in the documentation.

CKEditor Link dialog modification

I am trying to add a drop down to CKEditor's link dialog. When selected, the drop down should insert corresponding class name to the link.
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' ) {
var infoTab = dialogDefinition.getContents( 'info' );
infoTab.add({
type: 'select',
label: 'Display link as a button',
id: 'buttonType',
'default': '',
items: [
['- Not button -', ''],
['Button one', 'btn-primary'],
['Button two', 'btn-success'],
['Button three', 'btn-danger']
],
commit: function(data) {
data.className = this.getValue();
}
});
}
});
I have a feeling commit function is not doing the job, but cannot figure out how to make it work. I saw a code that almost does the same thing as I want at http://www.lxg.de/code/simplify-ckeditors-link-dialog. I tried it and it does not work either.
I am using CKEditor 4.3.2.
I appreciate your help in advance.
If you console.log the data object in link dialog's onOk, you'll find quite a different hierarchy. Element classes are in data.advanced.advCSSClasses. But even if you decide to override (or extend) the value of this property in your commit, your string will be nuked by the original commit of advCSSClasses input field ("Advanced" tab) anyway. So the approach got to be a little bit different:
Always store the value of the select in data.
Override commit of advCSSClasses input field to consider stored value.
Remember to execute the original commit of advCSSClasses input.
Here we go:
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' ) {
var infoTab = dialogDefinition.getContents( 'info' ),
advTab = dialogDefinition.getContents( 'advanced' ),
advCSSClasses = advTab.get( 'advCSSClasses' );
infoTab.add( {
type: 'select',
label: 'Display link as a button',
id: 'buttonType',
'default': '',
items: [
['- Not button -', ''],
['Button one', 'btn-primary'],
['Button two', 'btn-success'],
['Button three', 'btn-danger']
],
commit: function( data ) {
data.buttonType = this.getValue();
}
});
var orgAdvCSSClassesCommit = advCSSClasses.commit;
advCSSClasses.commit = function( data ) {
orgAdvCSSClassesCommit.apply( this, arguments );
if ( data.buttonType && data.advanced.advCSSClasses.indexOf( data.buttonType ) == -1 )
data.advanced.advCSSClasses += ' ' + data.buttonType;
};
}
});
Now you got to only write a setup function which will detect whether one of your button classes is present to set a proper value of your select field once the dialog is open.

Extjs - autocomplete filter 2 properties

By following this example http://dev.sencha.com/deploy/ext-4.1.0-gpl/examples/form/forum-search.html
I could apply the auto-complete feature on my combo box, using php/postgresql query retrieves the names then:
{
xtype: 'combo',
store: ds,
hideTrigger:true,
typeAhead: false,
id: 'search_input_text',
width: 187,
queryMode: 'remote',
hideLabel: true,
queryParam: 'query',
displayField: 'first_name',
valueField: 'first_name',
listConfig: {
loadingText: 'Loading...',
getInnerTpl: function() {
return '{first_name}';
}}
listeners: {
buffer: 50,
change: function() {
var store = this.store;
store.clearFilter();
store.filter({
property: 'first_name',
anyMatch: true,
value : this.getValue()
});
}
}
}
Now, I need to edit this to let user enter either the first or last name of the student, and then each name entered (first or last) will be shown in the combo box.
So, I edited the query to make it retrieve the names :
SELECT first_name, last_name FROM students WHERE first_name ILIKE '%$query%' OR last_name ILIKE '%$query%' ";
and:
displayField: 'first_name'+'last_name',
valueField: 'first_name'+'last_name',
return '{first_name}'+'{last_name}';
store.filter({
property: 'first_name',
anyMatch: true,
value : this.getValue()
},
{
property: 'last_name',
anyMatch: true,
value : this.getValue()
}
but still, it retrieves only first names according to what user types,
Note that if I use this alone:
store.filter({
property: 'last_name',
anyMatch: true,
value : this.getValue()
});
it works fine with last names only.
You can apply multiple filters to data store like this:
var filters = [
new Ext.util.Filter({
filterFn: function(item){return item.get('first_name') == this.getValue() || item.get('last_name') == this.getValue();
}
})
];
store.filter(filters);
The above code block is just an idea on how to apply multiple filters in the same field. Notice the double-pipe "||". You can use "&&" as per your needs. It is like SQL query.

cakePHP + extjs row editor and REST

I've implemented REST routing in cakePHP to properly route REST style requests to the proper methods in my controller.
This is what I've added to my routes.php
Router::mapResources(array('object_fields'));
This properly routes the REST requests to my index/add/edit/delete methods inside my controller.
In my EXTJS grid I am using the row editor with a restful store to achieve CRUD behavior.
Here is the code for my grid
myapp.object_field_grid = Ext.extend(Ext.grid.GridPanel, {
closable: true,
stripeRows: true,
frame: true,
viewConfig: {
forceFit: true
},
editor: new Ext.ux.grid.RowEditor({
saveText: 'Update',
}),
onAdd : function(btn, ev){
var u = new this.store.recordType({
name : '',
type: '',
});
this.editor.stopEditing();
this.store.insert(0, u);
this.editor.startEditing(0);
},
onDelete : function(){
},
initComponent: function() {
var proxy = new Ext.data.HttpProxy({
url: 'object_fields/',
});
var reader = new Ext.data.JsonReader({
totalProperty: 'totalCount',
successProperty: 'success',
idProperty: 'id',
root: 'data',
messageProperty: 'message'
}, [
{name: 'id'},
{name: 'name', allowBlank: false},
{name: 'type', allowBlank: false},
]);
var writer = new Ext.data.JsonWriter({
encode: false,
});
var store = new Ext.data.Store({
baseParams: {id: this.object_id},
id: 'object_fields',
restful: true,
proxy: proxy,
reader: reader,
writer: writer,
});
store.load();
var object_field_columns = [
// {header: "id", width: 250, sortable: true, dataIndex: 'id', editor: new Ext.form.TextField({})},
{header: "name", width: 250, sortable: true, dataIndex: 'name', editor: new Ext.form.TextField({})},
{header: "type", width: 250, sortable: true, dataIndex: 'type', editor: new Ext.form.ComboBox({editable: false, store:['STRING', 'NUMBER']})},
];
var config = {
columns: object_field_columns,
store: store,
plugins: [this.editor],
//autoHeight: true,
height: 200,
tbar: [{
text: 'Add',
iconCls: 'silk-add',
handler: this.onAdd,
scope: this,
}, '-', {
text: 'Delete',
iconCls: 'silk-delete',
handler: this.onDelete,
scope: this,
}, '-'],
}
Ext.apply(this, Ext.apply(this.initialConfig, config));
myapp.object_field_grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
this.store.load();
myapp.object_field_grid.superclass.onRender.apply(this, arguments);
}
});
Ext.reg('object_field_grid', myapp.object_field_grid); // register xtype
My GET/POST requests are being properly routed to my index/add methods inside my controller and I am able to easily retrieve the paramaters that I pass it in the request.
My problem is with the update functionality PUT request. The PUT request does get successfully routed to my edit method inside the controller.
This is what the request looks like in firebug
http://server.local/object_fields/20
JSON
data
Object { name="test7777777777", more...}
id
"18"
Source
{"id":"18","data":{"name":"test7777777777","id":"20"}}
Inside my edit method I'm not receiving my array that I passed through the PUT request.
When I dump $this->params inside my edit method this is what is in the array.
([id] => 20
[named] => Array
(
)
[pass] => Array
(
[0] => 20
)
[controller] => object_fields
[action] => edit
[[method]] => PUT
[plugin] =>
[url] => Array
(
[ext] => html
[url] => object_fields/20
)
[form] => Array
(
)
[isAjax] => 1
)
How can I properly receive my array through the PUT request inside my edit method?
UPDATE:
I am able to retrieve my array using the following code inside the edit method
function edit($id){
$this->autoRender = false;
echo 'edit';
$raw = '';
$httpContent = fopen('php://input', 'r');
while ($kb = fread($httpContent, 1024)) {
$raw .= $kb;
}
fclose($httpContent);
$params = array();
parse_str($raw, $params);
print_r($params);
}
The question is now why does cakePHP not do this automaticly?
put this in your app_controller.php:
public function beforeFilter() {
if (
isset($this->RequestHandler) &&
$this->RequestHandler->requestedWith('json') &&
(
$this->RequestHandler->isPost() ||
$this->RequestHandler->isPut()
)
) {
$jsonData = json_decode(utf8_encode(trim(file_get_contents('php://input'))), true);
if (is_array($jsonData)) {
$this->data = $jsonData;
unset($jsonData);
}
}
}