No results when setting the firstpage header - ms-word

When you look at the documentation for office-js api's you have three header locations:
primary
firstpage
even
I would expect that setting a firstpage header would only show on the first page. However I doesn't seem to do anything. Am I missing something? The documentation is not very clear on this. In this sample only the primary is showing up.
private setHeader(): void {
Word.run((context) => {
let body = context.document.body;
let sections = context.document.sections;
context.load(sections, 'body/style');
return context.sync()
.then(() => {
let primary = sections.items[0].getHeader(Word.HeaderFooterType.primary);
primary.insertText('primary', Word.InsertLocation.replace)
let firstPage = sections.items[0].getHeader(Word.HeaderFooterType.firstPage);
firstPage.insertText('first page', Word.InsertLocation.replace);
context.sync()
.then(() => { },
((result: OfficeErrorMessage) => {
this.setErrorState(result);
})
);
;
});
});
}
ps. the sample is typescript.

very good question. if you set the headers with the API and then select the 'Different First Page' option on the Design ribbon of the header
you will see that effectively the header is there. The bad part is that we are fixing a bug to make sure its shown, basically we will expose those properties in the section object, we are planning to ship those as part of the next deliverable of the Word js API. Now, those options are actually on the file format (the odd and events on the settings package as <w:evenAndOddHeaders/> , and the 'Different first' a <w:titlePg> element is added on the section definition, so maybe inserting an OOXML can be a workaround for now.
Hope this helps!

Related

Update global state after RTK Query loads data

I've noticed a problem with splitting responsibilities in React components based on the fetched data using RTK Query.
Basically, I have two components like HomePage and NavigationComponent.
On HomePage I'd like to fetch the information about the user so that I can modify NavigationComponent accordingly.
What I do inside HomePage:
import { setNavigationMode } from "features/nav/navSlice";
export default function HomePage() {
const {data: user} = useGetUserDataQuery();
const dispatch = useAppDispatch();
const navMode = user ? "all-options" : "none";
dispatch(setNavigationMode(navMode)); // here I change the default Navigation mode
return <MainLayout>
<Navigation/>
<Content/>
<Footer/>
</MainLayout>;
}
The HomePage is a special Page when the NavigationComponent shouldn't display any options for the not logged in user.
Other pages presents additional Logo and Title on Nav.
React communicates:
Warning: Cannot update a component (NavComponent) while rendering a different component (HomePage). To locate the bad setState() call inside HomePage, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
Not sure what is the right way to follow.
Whether the state should be changed in GetUser query after it is loaded - that doesn't seem to be legit.
problem is dispatch calls every render. Instead you can create a navigationSlice (if you don't have already) and use extraReducers for matching your authorization action like:
extraReducers: (builder) => {
builder.addMatcher(
usersApi.endpoints.login.matchFulfilled,
(state, { payload }) => {
if (payload.user) {
state.navigationMode = "all-options"
}
}
);
}
This way, state.navigationMode will only change when authorization changes
The solution was too obvious. The dispatch should be run in useEffect.
import { setNavigationMode } from "features/nav/navSlice";
export default function HomePage() {
const {data: user} = useGetUserDataQuery();
const dispatch = useAppDispatch();
const navMode = user ? "all-options" : "none";
// changed lines
useEffect( () => {
dispatch(setNavMode(navMode));
}, [navMode, dispatch]);
// /changed lines
return <MainLayout>
<Navigation/>
<Content/>
<Footer/>
</MainLayout>;
}
Thank you #papa-xvii for the hint with changing the navMode after user login. That solves the second problem I had.
However I cannot accept the answer as it does not solve the problem I described above.

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.

How to use the nextHandler functionality as shown in the Infinite Ajax Scroll JSON example

I’m hoping to be able to use Infinite Ajax Scroll for a project I’m working on.
I’ve been looking at the Infinite Scroll JSON example here (https://infiniteajaxscroll.com/examples/json/) and I’m finding it difficult to understand how it works. I was wondering if there is any further documentation or code examples on how to use a JS or jQuery handler as shown in the example.
Ultimately what I want to do is load my container "items" using my own ajax function and then have Infinite Ajax Scroll display them. I want to do this because my container "items" are not located at URLs, but are saved as Wordpress transients.
Any help I could get with this would be very much appreciated.
Thanks,
David.
Thank you for your question. The docs on using the nextHandler could indeed use improvement. Regardless, I'll try to explain how it works.
Normally IAS uses a selector to find the url of the next page. Then it loads the page and extracts the elements and appends them to the DOM. If you use the nextHandler, you will completely bypass this behavior. That means you will have to fetch data (in this case JSON) yourself and also insert new elements in the DOM.
Here is an example with comments to explain what it does.
First, let's assume our movie(1..n).json has the following format:
[
{
Title: 'item1',
Plot: 'description1'
}, {
Title: 'item2',
Plot: 'description2'
}
]
Now the implementation of the nextHandler:
import InfiniteAjaxScroll from "#webcreate/infinite-ajax-scroll";
function nextHandler(pageIndex) {
// we use the fetch api to load the next page. Any http client library will do, like axios.
return fetch("./static/movies"+pageIndex+".json")
// use the response as json
.then((response) => response.json())
// process the actual json data
.then((jsonData) => {
// create an array to store our html elements in memory
let elements = [];
// we loop over the items in our json and create an html element for each item
jsonData.forEach(function (item) {
const template = `<div class="item">
<h1>${item.Title}</h1>
<p>${item.Plot}</p>
</div>`;
const element = document.createElement("div");
element.innerHTML = template.trim();
elements.push(element.firstChild);
});
// now use IAS's append method to insert the elements
// it's import that we return the append result, as it's an promise
return this.append(elements);
})
// page 3 returns a 404, returning false here indicates there are no more pages to load
.catch(() => false);
}
window.ias = new InfiniteAjaxScroll(".container", {
item: ".item",
next: nextHandler,
pagination: false
});
I also prepared an interactive demo on Codesandbox:
https://codesandbox.io/s/serene-einstein-f73em

Is there a onScroll event for ag-grid

I am looking for a scroll event on ag-grid, I want to know when the scroll reaches the end and load the next set of rows, I know if you set the infinite scroll mode then ag-grid calles the getRows method, but in my application I do not get the next set of rows right away, I make a call to the server and server sends a separate message to the client with the new set of rows
After getting in deep, I found the perfect solution to this problem.
Please note here I am used AngularJS, But very easy to understand.
onBodyScroll:function(params) {
var bottom_px = $scope.gridOptions.api.getVerticalPixelRange().bottom;
var grid_height = $scope.gridOptions.api.getDisplayedRowCount() * $scope.gridOptions.api.getSizesForCurrentTheme().rowHeight;
if(bottom_px == grid_height)
{
alert('Bottom')
}
},
There's a grid event called 'onBodyScroll' which you can attach an event handler to it.
This event is somewhat secret as it was not there on their GridOptions type before version 18, even though it does work.
see this comment: https://github.com/ag-grid/ag-grid-enterprise/issues/89#issuecomment-264477535
They do have this event in document tho: https://www.ag-grid.com/javascript-grid-events/#miscellaneous
BodyScrollEvent
bodyScroll - The body was scrolled horizontally or vertically.
onBodyScroll = (event: BodyScrollEvent) => void;
interface BodyScrollEvent {
// Event identifier
type: string;
api: GridApi;
columnApi: ColumnApi;
direction: ScrollDirection;
left: number;
top: number;
}
You should be able to do that thing (loading the data from the server) as per below example.
First of all, define your dataSource.
const dataSource: IServerSideDatasource = {
getRows: (params: IServerSideGetRowsParams) => this._getRows(params, [])
};
this.gridApi.setServerSideDatasource(dataSource);
Declare _getRows method like this.
private _getRows(params: IServerSideGetRowsParams, data: any[]) {
this.gridApi.showLoadingOverlay();
service.getData(params) // the payload your service understands
.subscribe((result: any[]) => {
params.successCallback(result, -1);
params.failCallback = () => console.log('some error occured while loading new chunk of data');
this.gridApi.hideOverlay();
},
error => this._serverErrorHandler(error)
);
}
This is pretty much self-explanatory. Let's me know if anything is unclear to you.
BTW, I've used typescript for the example, javascript example would be kind of the same for ag-grid-react

OfficeJS deleting headers on load

I have a simple piece of code that loads headers and then changes some text in them. Recently an issue was reported where the headers are deleted. I've tracked it down to happening on loading the headers for these documents, and it appears they have 'Link to Previous' selected in the header options. I'm not sure why this would cause it to be deleted as the code up to that point makes no changes. Even this simple snippet causes the same issue.
Word.run(function (context) {
var sections = context.document.sections;
context.load(sections);
return context.sync().then(function() {
if (sections !== null) {
var headers = [];
for (var i = 0; i < sections.items.length; i++) {
var header = sections.items[i].getHeader('primary');
context.load(header);
headers.push(header);
}
context.sync().then(function() {
// when you get here all headers are deleted.
});
}
}).then(context.sync);
});
After some testing, what's really happening is that the LinkToPrevious setting is being removed. When that happens the content of the original header is removed from that header, which leaves nothing.
I could determine this by alternating the setting from section to section (on/off).
LinkToPrevious is not supported in the Office JS API that I can find, which may explain why the setting isn't being respected. I consider this a bug.
The only possibility to work around this that occurs to me would be to work over the Word Open XML for the headers.