-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathsectionPicker.tsx
More file actions
359 lines (315 loc) · 14.6 KB
/
sectionPicker.tsx
File metadata and controls
359 lines (315 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/// <reference path="../../../../node_modules/onenotepicker/target/oneNotePicker.d.ts"/>
/// <reference path="../../../../node_modules/onenoteapi/target/oneNoteApi.d.ts" />
import {Constants} from "../../constants";
import {Localization} from "../../localization/localization";
import * as Log from "../../logging/log";
import {Settings} from "../../settings";
import {ClipperStorageKeys} from "../../storage/clipperStorageKeys";
import {ClipperStateProp} from "../clipperState";
import {ClipperStateUtilities} from "../clipperStateUtilities";
import {ComponentBase} from "../componentBase";
import {Clipper} from "../frontEndGlobals";
import {OneNoteApiUtils} from "../oneNoteApiUtils";
import { Status } from "../status";
export interface SectionPickerState {
notebooks?: OneNoteApi.Notebook[];
status?: Status;
apiResponseCode?: string;
curSection?: {
path: string;
section: OneNoteApi.Section;
};
}
interface SectionPickerProp extends ClipperStateProp {
onPopupToggle: (shouldNowBeOpen: boolean) => void;
}
export class SectionPickerClass extends ComponentBase<SectionPickerState, SectionPickerProp> {
static dataSource: OneNotePicker.OneNotePickerDataSource;
getInitialState(): SectionPickerState {
return {
notebooks: undefined,
status: Status.NotStarted,
curSection: undefined
};
}
onSectionClicked(curSection: any) {
this.props.clipperState.setState({
saveLocation: curSection.section.id
});
this.setState({
curSection: curSection
});
Clipper.storeValue(ClipperStorageKeys.currentSelectedSection, JSON.stringify(curSection));
Clipper.logger.logClickEvent(Log.Click.Label.sectionComponent);
}
onPopupToggle(shouldNowBeOpen: boolean) {
if (shouldNowBeOpen) {
// If the user selects a section, onPopupToggle will fire because it closes the popup, even though it wasn't a click
// so logging only when they open it is potentially the next best thing
Clipper.logger.logClickEvent(Log.Click.Label.sectionPickerLocationContainer);
// Set focus on the selected section for keyboard accessibility
// Use a small delay to ensure the popup is fully rendered before trying to focus
// requestAnimationFrame would be ideal but setTimeout with a small delay is more reliable
// across different browsers and system performance scenarios
setTimeout(() => {
this.setFocusOnSelectedSection();
}, 100);
}
this.props.onPopupToggle(shouldNowBeOpen);
}
// Sets focus on the currently selected section when the dropdown opens
// This ensures keyboard users can immediately see and interact with the selected item
setFocusOnSelectedSection() {
// Get the current section ID from state
const curSectionId = this.state.curSection && this.state.curSection.section
? this.state.curSection.section.id
: undefined;
if (curSectionId) {
// Find the section element by its ID and set focus on it
const sectionElement = document.getElementById(curSectionId);
if (sectionElement) {
sectionElement.focus();
}
} else {
// If no section is selected, focus on the first focusable element in the popup
// Note: "notebookList" is an ID from the OneNotePicker library (v1.0.9)
// This is a known dependency on the external library's DOM structure
const notebookList = document.getElementById("notebookList");
if (notebookList) {
// Query for the first keyboard-focusable element
// The OneNotePicker library uses tabindex on section elements, and we exclude tabindex="-1"
// which is only programmatically focusable
const firstFocusableElement = notebookList.querySelector('[tabindex]:not([tabindex="-1"])') as HTMLElement;
if (firstFocusableElement) {
firstFocusableElement.focus();
}
}
}
}
// Returns true if successful; false otherwise
setDataSource(): boolean {
if (!ClipperStateUtilities.isUserLoggedIn(this.props.clipperState)) {
return false;
}
let userToken = this.props.clipperState.userResult.data.user.accessToken;
SectionPickerClass.dataSource = new OneNotePicker.OneNotePickerDataSource(userToken);
return true;
}
// Begins by updating state with information found in local storage, then retrieves and stores fresh notebook information
// from the API. If the user does not have a previous section selection in storage, or has not made a section selection yet,
// additionally set the current section to the default section.
retrieveAndUpdateNotebookAndSectionSelection(): Promise<SectionPickerState> {
return new Promise<SectionPickerState>((resolve, reject) => {
if (this.dataSourceUninitialized()) {
this.setDataSource();
}
this.setState({
status: Status.InProgress
});
// Always set the values with what is in local storage, and when the XHR returns it will overwrite if necessary
this.fetchCachedNotebookAndSectionInfoAsState((cachedInfoAsState: SectionPickerState) => {
if (cachedInfoAsState) {
this.setState(cachedInfoAsState);
this.props.clipperState.setState({
saveLocation: cachedInfoAsState.curSection && cachedInfoAsState.curSection.section ? cachedInfoAsState.curSection.section.id : ""
});
}
let getNotebooksEvent: Log.Event.PromiseEvent = new Log.Event.PromiseEvent(Log.Event.Label.GetNotebooks);
this.fetchFreshNotebooks(Clipper.getUserSessionId()).then((responsePackage) => {
let correlationId = responsePackage.request.getResponseHeader(Constants.HeaderValues.correlationId);
getNotebooksEvent.setCustomProperty(Log.PropertyName.Custom.CorrelationId, correlationId);
let freshNotebooks = responsePackage.parsedResponse;
if (!freshNotebooks) {
getNotebooksEvent.setStatus(Log.Status.Failed);
let error = {error: "GetNotebooks Promise was resolved but returned null or undefined value for notebooks."};
getNotebooksEvent.setFailureInfo(error);
this.setState({
status: Status.Failed
});
reject(error);
return;
}
getNotebooksEvent.setCustomProperty(Log.PropertyName.Custom.MaxDepth, OneNoteApi.NotebookUtils.getDepthOfNotebooks(freshNotebooks));
Clipper.storeValue(ClipperStorageKeys.cachedNotebooks, JSON.stringify(freshNotebooks));
// The curSection property is the default section found in the notebook list
let freshNotebooksAsState = SectionPickerClass.convertNotebookListToState(freshNotebooks);
let shouldOverrideCurSectionWithDefault = true;
if (this.state.curSection && this.state.curSection.section) {
// The user has already selected a section ...
let currentSectionStillExists = OneNoteApi.NotebookUtils.sectionExistsInNotebooks(freshNotebooks, this.state.curSection.section.id);
if (currentSectionStillExists) {
// ... which exists, so we don't override it with the default
freshNotebooksAsState.curSection = this.state.curSection;
shouldOverrideCurSectionWithDefault = false;
}
getNotebooksEvent.setCustomProperty(Log.PropertyName.Custom.CurrentSectionStillExists, currentSectionStillExists);
}
if (shouldOverrideCurSectionWithDefault) {
// A default section was found, so we set it as currently selected since the user has not made a valid selection yet
// curSection can be undefined if there's no default found, which is fine
Clipper.storeValue(ClipperStorageKeys.currentSelectedSection, JSON.stringify(freshNotebooksAsState.curSection));
this.props.clipperState.setState({saveLocation: freshNotebooksAsState.curSection ? freshNotebooksAsState.curSection.section.id : undefined});
}
this.setState(freshNotebooksAsState);
resolve(freshNotebooksAsState);
}).catch((failure: OneNoteApi.RequestError) => {
this.setState({
apiResponseCode: OneNoteApiUtils.getApiResponseCode(failure)
});
if (this.state.notebooks) {
failure.error += ". Falling back to storage.";
} else {
this.setState({
status: Status.Failed
});
}
OneNoteApiUtils.logOneNoteApiRequestError(getNotebooksEvent, failure);
reject(failure);
}).then(() => {
Clipper.logger.logEvent(getNotebooksEvent);
});
});
});
}
dataSourceUninitialized(): boolean {
return !SectionPickerClass.dataSource ||
!SectionPickerClass.dataSource.authToken ||
!ClipperStateUtilities.isUserLoggedIn(this.props.clipperState) ||
(SectionPickerClass.dataSource.authToken !== this.props.clipperState.userResult.data.user.accessToken);
}
// Retrieves the cached notebook list and last selected section from local storage in state form
fetchCachedNotebookAndSectionInfoAsState(callback: (state: SectionPickerState) => void): void {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => {
if (notebooks) {
let parsedNotebooks: any;
try {
parsedNotebooks = JSON.parse(notebooks);
} catch (e) {
Clipper.logger.logJsonParseUnexpected(notebooks);
}
// It is ok for parsed value to be set to undefined, as this corresponds to the default section
let parsedCurSection: any;
if (parsedNotebooks && curSection) {
try {
parsedCurSection = JSON.parse(curSection);
} catch (e) {
Clipper.logger.logJsonParseUnexpected(curSection);
}
}
callback({
notebooks: parsedNotebooks,
status: Status.Succeeded,
curSection: parsedCurSection
});
} else {
// Cached information not found in storage
callback(undefined);
}
});
});
}
// Fetches the user's notebooks from OneNote API, returning both the notebook list and the XHR
fetchFreshNotebooks(sessionId: string): Promise<OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>> {
if (this.dataSourceUninitialized()) {
this.setDataSource();
}
let headers: { [key: string]: string } = {};
headers[Constants.HeaderValues.appIdKey] = Settings.getSetting("App_Id");
headers[Constants.HeaderValues.userSessionIdKey] = sessionId;
return SectionPickerClass.dataSource.getNotebooks(headers);
}
// Given a notebook list, converts it to state form where the curSection is the default section (or undefined if not found)
static convertNotebookListToState(notebooks: OneNoteApi.Notebook[]): SectionPickerState {
let pathToDefaultSection = OneNoteApi.NotebookUtils.getPathFromNotebooksToSection(notebooks, s => s.isDefault);
let defaultSectionInfo = SectionPickerClass.formatSectionInfoForStorage(pathToDefaultSection);
return {
notebooks: notebooks,
status: Status.Succeeded,
curSection: defaultSectionInfo
};
}
static formatSectionInfoForStorage(pathToSection: OneNoteApi.SectionPathElement[]): { path: string, section: OneNoteApi.Section } {
if (!pathToSection || pathToSection.length === 0) {
return undefined;
}
return {
path: pathToSection.map(elem => elem.name).join(" > "),
section: pathToSection[pathToSection.length - 1] as OneNoteApi.Section
};
}
addSrOnlyLocationDiv(element: HTMLElement) {
const pickerLinkElement = document.getElementById(Constants.Ids.sectionLocationContainer);
if (!pickerLinkElement) {
Clipper.logger.logTrace(Log.Trace.Label.General, Log.Trace.Level.Warning, `Unable to add sr-only div: Parent element with id ${Constants.Ids.sectionLocationContainer} not found`);
return;
}
const srDiv = document.createElement("div");
srDiv.textContent = Localization.getLocalizedString("WebClipper.Label.ClipLocation") + ": ";
srDiv.setAttribute("class", Constants.Classes.srOnly);
// Make srDiv the first child of pickerLinkElement
pickerLinkElement.insertBefore(srDiv, pickerLinkElement.firstChild);
}
render() {
if (this.dataSourceUninitialized()) {
// This logic gets executed on app launch (if already signed in) and whenever the user signs in or out ...
let dataSourceSet = this.setDataSource();
if (dataSourceSet) {
// ... so we want to ensure we only fetch fresh notebooks on the sign in
this.retrieveAndUpdateNotebookAndSectionSelection();
}
} else if (!this.state.notebooks && this.state.status === Status.NotStarted) {
// Since we re-render this with initial state when we switch between modes that do or do not render this component, we don't want to lose our
// stored notebooks in state
this.fetchCachedNotebookAndSectionInfoAsState((cachedInfoAsState: SectionPickerState) => {
if (cachedInfoAsState) {
this.setState(cachedInfoAsState);
this.props.clipperState.setState({
saveLocation: cachedInfoAsState.curSection && cachedInfoAsState.curSection.section ? cachedInfoAsState.curSection.section.id : ""
});
}
});
}
let localizedStrings = {
defaultLocation: Localization.getLocalizedString("WebClipper.SectionPicker.DefaultLocation"),
loadingNotebooks: Localization.getLocalizedString("WebClipper.SectionPicker.LoadingNotebooks"),
noNotebooksFound: Localization.getLocalizedString("WebClipper.SectionPicker.NoNotebooksFound"),
notebookLoadFailureMessage: Localization.getLocalizedString("WebClipper.SectionPicker.NotebookLoadFailureMessage")
};
// Compute all the necessary properties for the Picker based on the state we are in
let curSectionId: string, textToDisplay: string = localizedStrings.defaultLocation;
// We could have returned correctly, but there is no default Notebook
if (this.state.status === Status.Succeeded) {
if (this.state.curSection) {
curSectionId = this.state.curSection.section.id;
textToDisplay = this.state.curSection.path;
}
}
// If we can show a better message, especially an actionable one, we do
if (this.state.apiResponseCode && !OneNoteApiUtils.isRetryable(this.state.apiResponseCode)) {
localizedStrings.notebookLoadFailureMessage = OneNoteApiUtils.getLocalizedErrorMessageForGetNotebooks(this.state.apiResponseCode);
}
let locationString = Localization.getLocalizedString("WebClipper.Label.ClipLocation");
return (
<div id={Constants.Ids.locationPickerContainer} {...this.onElementFirstDraw(this.addSrOnlyLocationDiv)}>
<div id={Constants.Ids.optionLabel} className="optionLabel">
<label htmlFor={Constants.Ids.sectionLocationContainer} aria-label={locationString} className="buttonLabelFont" style={Localization.getFontFamilyAsStyle(Localization.FontFamily.Regular)}>
<span aria-hidden="true">{locationString}</span>
</label>
</div>
<OneNotePicker.OneNotePickerComponent
id={Constants.Ids.sectionLocationContainer}
tabIndex={70}
notebooks={this.state.notebooks}
status={Status[this.state.status]}
onPopupToggle={this.onPopupToggle.bind(this)}
onSectionClicked={this.onSectionClicked.bind(this)}
textToDisplay={textToDisplay}
curSectionId={curSectionId}
localizedStrings={localizedStrings}/>
</div>
);
}
}
let component = SectionPickerClass.componentize();
export {component as SectionPicker};