How to get HTML of each paragraph of a Word document with Office JS - wordpress

I have MS Word documents where the table of contents, built using title 1 to title 4, is a hierarchy of more than 100 items.
I want to use Office JS to develop an add-in to import these documents in WordPress as a set of Pages with the same hierarchy as one of the tables of contents.
Each WP page would contain the HTML of all the paragraphs contained under each title level.
Looking at the Office JS samples, I have been able to log to the console the outline levels of all paragraphs in the document, but I am stuck with getting the HTML.
I think this is probably because I misunderstand context.sync().
Here is my code:
$("#exportToCMS").click(() => tryCatch(exportToCMS));
function exportToCMS() {
return Word.run(function (context) {
// Create a proxy object for the paragraphs collection
var paragraphs = context.document.body.paragraphs;
// Queue a command to load the outline level property for all of the paragraphs
paragraphs.load("outlineLevel");
return context.sync().then(function () {
// Queue a a set of commands to get the HTML of each paragraph.
paragraphs.items.forEach((paragraph) => {
// Queue a command to get the HTML of the paragraph.
var ooxml = paragraph.getOoxml();
return context.sync().then(function () {
console.log(ooxml.value);
console.log(paragraph.outlineLevel);
});
});
});
});
}
/** Default helper for invoking an action and handling errors. */
function tryCatch(callback) {
Promise.resolve()
.then(callback)
.catch(function (error) {
console.error(error);
});
}
If I comment out the line which logs ooxml.value, the script runs fine.
When uncommented, I get an error "Unhandled promise rejection".

Broken promise chains are common when you have a context.sync inside a loop. This is also bad from a performance standpoint. Your first step to fixing your code is to get the context.sync out of the forEach loop by following the guidance in this article: Avoid using the context.sync method in loops.

Related

createPages in Gatsby issues ; duplications and unrendered content

I've had a few errors trying to render single blog posts.
I tried using the page template with /post/{post_name} and I was getting this error:
warn Non-deterministic routing danger: Attempting to create page: "/blog/", but
page "/blog" already exists
This could lead to non-deterministic routing behavior
I tried again with /blog/{post_name}.
I now have both routes, which I'm not sure how to clean up; but more importantly, on those pages, nothing renders, even though there should be an h1 with it's innerhtml set to the node.title and likewise a div for the content.
I've uploaded my config and components to https://github.com/zackrosegithub/gatsby so you can have a look.
Not sure how to fix
I just want to see my content rendered on the screen.
Developer tools don't seem to help when there's no content rendered as I can't find anything to inspect to try to access it another way.
Thank you for your help
Your approach is partially correct. You are using a promise-based approach but when using then() you are already settling and partially resolving it so you don't need to use the callback of resolve(), which may be causing a duplication of the promise function so try removing it.
Additionally, you may want to use a more friendly approach using async/await functions. Something like:
exports.createPages = async ({ graphql, actions, reporter }) => {
const yourQuery= await graphql(
`
{
allWordpressPost {
edges{
node{
id
title
slug
excerpt
content
}
}
}
}
`
if (yourQuery.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`);
return;
}
const postTemplate = path.resolve("./src/templates/post.js")
_.each(yourQuery.data.allWordpressPost.edges, edge => {
createPage({
path: `/post/${edge.node.slug}/`,
component: slash(postTemplate),
context: edge.node,
})
})
})
// and so on for the rest of the queries
};
In addition, place a console.log(pageContext) in your postTemplate to get what's reaching that point and name the template as:
const Post = ({pageContext}) => {
console.log("your pageContext is", pageContext);
return <div>
<h1>
{pageContext.title}
</h1>
</div>
}
export default Post;

Vue JS AJAX computed property

Ok, I believe I am VERY close to having my first working Vue JS application but I keep hitting little snag after little snag. I hope this is the last little snag.
I am using vue-async-computed and axios to fetch a customer object from my API.
I am then passing that property to a child component and rendering to screen like: {{customer.fName}}.
As far as I can see, the ajax call is being made and the response coming back is expected, the problem is there is nothing on the page, the customer object doesnt seem to update after the ajax call maybe.
Here is the profile page .vue file I'm working on
http://pastebin.com/DJH9pAtU
The component has a computed property called "customer" and as I said, I can see in the network tab, that request is being made and there are no errors. The response is being sent to the child component here:
<app-customerInfo :customer="customer"></app-customerInfo>
within that component I am rendering the data to the page:
{{customer.fName}}
But, the page shows no results. Is there a way to verify the value of the property "customer" in inspector? is there something obvious I am missing?
I've been using Vue for about a year and a half, and I realize the struggle that is dealing with async data loading and that good stuff. Here's how I would set up your component:
<script>
export default {
components: {
// your components were fine
},
data: () => ({ customer: {} }),
async mounted() {
const { data } = await this.axios.get(`/api/customer/get/${this.$route.params.id}`);
this.customer = data;
}
}
</script>
so what I did was initialize customer in the data function for your component, then when the component gets mounted, send an axios call to the server. When that call returns, set this.customer to the data. And like I said in my comment above, definitely check out Vue's devtools, they make tracking down variables and events super easy!
I believed your error is with naming. The vue-async-computed plugin needs a new property of the Vue object.
computed: {
customer: async function() {
this.axios.get('/api/customer/get/' + this.$route.params.id).then(function(response){
return(response.data);
});
}
}
should be:
asyncComputed: {
async customer() {
const res = await this.axios.get(`/api/customer/get/${this.$route.params.id}`);
return res.data;
}
}

How to get patterns widgets to work in an iframe overlay

I have some "classic" tiles on a Plone 4.3.6 site, which contain a richtext field and two RelationChoice fields using plone.formwidget.contenttree widgets.
I have installed plone.app.widgets 1.8.0 (along with p.a.contenttypes), and I can't get the new TinyMCE and the new relateditems pattern widget to work properly. If I load the tile view URL directly (at the ##edit-tile/.... URL), the widgets actually show up and work properly. But in the iframe/overlay, they don't.
The prep-overlay looks like this:
jQuery('.tile-editable').each(function () {
jQuery(this).find('a.tile-edit-link, a.tile-delete-link').
prepOverlay({
subtype: 'iframe',
config: {
onLoad: function (e) {
jQuery('body').addClass('noscroll');
return true;
},
onClose: function() {
jQuery('body').removeClass('noscroll');
location.reload();
}
}
});
});
The iframe loads ++resource++plone.app.widgets.js in the header, and the fields are given the pat-relateditems and pat-tinymce classes as expected. But the init method inside the relateditems pattern is never called. I suppose the iframe DOM is not parsed for patterns, but I don't know where to look for the cause of this.
FWIW, there is an error in the console:
Uncaught Error: Mismatched anonymous define() module: function (){return eb}
http://requirejs.org/docs/errors.html#mismatch
in plone.app.widgets.js:166, but I don't know where that's coming from, or if it matters.
Are there any tricks to getting mockup widgets to work in an ifram overlay?
To reinitialise all patterns you can do:
var registry = require("pat-registry");
registry.scan(SELECTOR); // document or iframe or wherever you want to rescan all patterns.
IMHO you could do this on the onLoad method.

Meteor event when Template is freshed

I am working on a Meteor project that has come custom Pagination using Sessions. The template rendering the contents of said items is using ellipsis.js and highlight.js to do some DOM formatting. The code looks something like thus:
if (Meteor.isClient) {
Meteor.startup(function () {
Session.setDefault("homePageSize", 10);
Session.setDefault("homePageStart", 0);
});
}
Template.home.articlesPaginated = function() {
return Articles.find({published: true}, {sort: {post_date: -1}, skip: Session.get("homePageStart"), limit: Session.get("homePageSize")});
}
Template.home.rendered = function() {
// Setup ellipsis
$('.ellipsis').dotdotdot({
ellipsis: '...',
wrap: 'word',
fallbackToLetter: true,
after: $('a.blog_continue')
});
// Setup highlight.js
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}
Template.home.events({
'click .next': function(event) {
var offset = Session.get("homePageStart") + Session.get("homePageSize");
if (offset < 0) {
offset = 0;
}
Session.set("homePageStart", offset);
},
'click .prev': function(event) {
var offset = Session.get("homePageStart") - Session.get("homePageSize");
if (offset < 0) {
offset = 0;
}
Session.set("homePageStart", offset);
}
});
Pagination is working just fine, but as soon as the Template re-renders I loose all the ellipsis.js and highlight.js formatting. I know the obvious reason is that the DOM has changed, and since the Template.render only runs once up-front and doesn't happen when the Template re-renders the DOM updates are not being applied. So, what is the best way to trigger ellipsis.js and highlight.js after the Template is done such that it gets re-called everytime the Template re-renders?
Basically you need to listen for changes in your Articles collection, which is a client-side subset of the server database clipped to contain only the currently visible paginated articles.
When you detect a change in the articles subset, you'll need to retrigger initialization of ellipsis.js and highlight.js.
You could reorganize your code as follow :
First, we define the cursor declaration as a separate function on his own because we need to use it twice :
function articlesPaginated(){
return Articles.find({
published: true
}, {
sort: {
post_date: -1
},
skip: Session.get("homePageStart"),
limit: Session.get("homePageSize")
});
}
Template.home.helpers({
articlesPaginated:articlesPaginated
});
Then in the rendered callback, we need to setup a reactive computation that will depend on this cursor, so whenever the articles subset is updated to a new page, our computation will rerun.
But we need to be aware that the helper we defined on the home template returns the same cursor so it's going to be invalidated and trigger DOM refresh AT THE SAME TIME... JavaScript is single-threaded and the Tracker.Computation manual states that the order of execution of concurrently invalidated computations is unpredictable.
So we cannot just trigger the ellipsis/highlight initialization code in the computation because this setup code assumes that the DOM is ready, however at this precise moment we don't know if DOM manipulation has just happened before or is going to happen immediately after.
Fortunately there is a Tracker.afterFlush method which allows us to execute code after concurrent computations are done so we are sure that by that time DOM state is OK.
Having understand all these implications, we can write the following rendered callback :
Template.home.rendered=function(){
// declare a template managed Deps.Computation
this.autorun(function(){
// have this reactive computation depend on the SAME cursor
// that triggers DOM rerendering
var articles=articlesPaginated();
// forEach is actually the method that triggers a dependency on the cursor in this computation
articles.forEach(function(article){
// you can manipulate the model here if needed
});
// setup a callback to execute your DOM alteration code after
// it is actually rerendered by Blaze
Tracker.afterFlush(function(){
// your ellipsis/highlight initialization code goes here
});
});
};
If you can put your Articles into another template, then you could apply formatting individually as they are inserted.
Template.article.rendered = function () {
// Setup ellipsis
this.$('.ellipsis').dotdotdot({
ellipsis: '...',
wrap: 'word',
fallbackToLetter: true,
after: $('a.blog_continue')
});
// Setup highlight.js
this.$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
};
Assuming your template looks something like this.
<template name="home">
...
{{#each articlesPaginated}}
{{> article}}
{{/each}}
{{> paginationControls}}
...
</template>
This has the added benefit of scoping the formatting to just the articles, rather than the entire DOM.

Subscribing to changes in a Collection but not in a template

I'm very new to meteor, so apologies if I'm missing something very basic here.
I thought it would be fun to create a very simple textpad style app to check out meteor. I took the todo app and changed the data structures to be 'folders' and 'docs' rather than 'lists' and 'todos', so I have a list of folders and when you click on the folder you get a list of the documents in that folder.
I've then added some code to show the 'content' attribute of a single 'doc' when one of the docs in the list is clicked.
I'm using ace to add some pretty print to the content of the doc (https://github.com/ajaxorg/ace). I've set ace up to work with a hidden textarea containing the plaintext version of my document, and the editor object takes this text and pretty prints it.
The problem with ace is that I don't want the template containing the ace editor to be replaced every time the contents of the doc changes (as it takes half a second to reinitialise, which is a crappy experience after every character is typed!). Instead, I want to update the textarea template and then use the ace API to tell the editor to update it's input based on what is in the textarea.
Now, this is probably the wrong way to approach the problem, but I've ended up using two templates. The first contains a textarea containing doc.contents, which is reactive to the underlying model:
<template name="doc_content">
<textarea name="editor">{{content}}</textarea>
</template>
The second one contains the 'editor' div which ace uses to display the pretty printed text.
<template name="doc_init">
<div id="editor"></div>
</template>
The idea is that the first template will update every time the user types (on all clients), and the second template is only ever re-loaded for each new doc we load.
Template.doc_content.content = function() {
var doc_id = Session.get('viewing_itemname');
if (!doc_id) {
return {};
}
var doc = Docs.findOne({_id:doc_id});
if (doc && doc.content) {
// #1 Later
var editor = Session.get('editor');
if (editor) {
editor.getSession().setValue(doc.content);
}
return doc.content;
} else {
return '';
}
};
When you enter text into the editor div I make a call to Docs.update(doc_id, {$set: {content: text}});, which updates the value in the textarea on each client. All good so far.
editor.getSession().on('change', function(){
var text = editor.getSession().getValue();
Docs.update(doc_id, {$set: {content: text}});
});
What I want to do, for all clients other than the client which made the change, is to subscribe to the change for that doc and call editor.getSession().setContent() with the text which has just been changed, taking the text from the textarea and using it to fill the editor.
I've tried to do this by making that call from the template containing the textarea (as this changes whenever the doc is updated - see #1 above). However, this puts the clients into an infinite loop because changing the value in the editor causes another call to Docs.update.
Obviously this doesn't happen when you render a template, so I'm assuming there's some magic in meteor which can prevent this happening, but I'm not sure how.
Any thoughts?
TIA!
There's a lot to absorb in your question, but if I understand correctly, you might simply be after Deps.autorun:
Deps.autorun(function () {
var doc_id = Session.get('viewing_itemname');
if (!doc_id) {
return {};
}
var doc = Docs.findOne({_id:doc_id});
// do stuff with doc
});
Deps.autorun is really useful in that it will get re-run if any of its
dependencies change. These dependencies are limited to those that are "reactive"
such as Collections and Sessions, or anything that implements the reactive API.
In your case, both Session.get and findOne are reactive so if their values
change at all, Deps.autorun will run the function again.

Resources