-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.ts
409 lines (352 loc) · 15.2 KB
/
main.ts
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import papi, { logger } from '@papi/backend';
import type {
ExecutionActivationContext,
WebViewContentType,
WebViewDefinition,
SavedWebViewDefinition,
IWebViewProvider,
GetWebViewOptions,
} from '@papi/core';
import { PlatformEventEmitter } from 'platform-bible-utils';
import type { HelloWorldEvent } from 'hello-world';
import helloWorldReactWebView from './web-views/hello-world.web-view?inline';
import helloWorldReactWebViewStyles from './web-views/hello-world.web-view.scss?inline';
import helloWorldReactWebView2 from './web-views/hello-world-2.web-view?inline';
import helloWorldReactWebView2Styles from './web-views/hello-world-2.web-view.scss?inline';
import helloWorldHtmlWebView from './web-views/hello-world.web-view.html?inline';
import HelloWorldProjectDataProviderEngineFactory from './models/hello-world-project-data-provider-engine-factory.model';
import helloWorldProjectWebView from './web-views/hello-world-project/hello-world-project.web-view?inline';
import helloWorldProjectWebViewStyles from './web-views/hello-world-project/hello-world-project.web-view.scss?inline';
import helloWorldProjectViewerWebView from './web-views/hello-world-project/hello-world-project-viewer.web-view?inline';
import { HTML_COLOR_NAMES } from './util';
/** User data storage key for all hello world project data */
const allProjectDataStorageKey = 'allHelloWorldProjectData';
type IWebViewProviderWithType = IWebViewProvider & { webViewType: string };
logger.info('Hello world is importing!');
// #region Hello World General Web Views
/** Simple web view provider that provides sample html web views when papi requests them */
const htmlWebViewProvider: IWebViewProviderWithType = {
webViewType: 'helloWorld.html',
async getWebView(savedWebView: SavedWebViewDefinition): Promise<WebViewDefinition | undefined> {
if (savedWebView.webViewType !== this.webViewType)
throw new Error(
`${this.webViewType} provider received request to provide a ${savedWebView.webViewType} web view`,
);
return {
...savedWebView,
title: 'Hello World HTML',
// Can't use the enum value from a definition file so assert the type from the string literal.
// eslint-disable-next-line no-type-assertion/no-type-assertion
contentType: 'html' as WebViewContentType.HTML,
content: helloWorldHtmlWebView,
};
},
};
/** Simple web view provider that provides React web views when papi requests them */
const reactWebViewProvider: IWebViewProviderWithType = {
webViewType: 'helloWorld.react',
async getWebView(savedWebView: SavedWebViewDefinition): Promise<WebViewDefinition | undefined> {
if (savedWebView.webViewType !== this.webViewType)
throw new Error(
`${this.webViewType} provider received request to provide a ${savedWebView.webViewType} web view`,
);
return {
iconUrl: 'papi-extension://helloWorld/assets/offline.svg',
title: 'Hello World React',
...savedWebView,
content: helloWorldReactWebView,
styles: helloWorldReactWebViewStyles,
state: {
...savedWebView.state,
clicks: Math.floor(Math.random() * 100),
},
};
},
};
/** Simple web view provider that provides other React web views when papi requests them */
const reactWebView2Provider: IWebViewProviderWithType = {
webViewType: 'helloWorld.react2',
async getWebView(savedWebView: SavedWebViewDefinition): Promise<WebViewDefinition | undefined> {
if (savedWebView.webViewType !== this.webViewType)
throw new Error(
`${this.webViewType} provider received request to provide a ${savedWebView.webViewType} web view`,
);
return {
...savedWebView,
title: 'Hello World React 2',
content: helloWorldReactWebView2,
styles: helloWorldReactWebView2Styles,
};
},
};
// #endregion
// #region Hello World Project Web View, Command, etc.
/** Simple web view provider that provides helloWorld project web views when papi requests them */
const helloWorldProjectWebViewProvider: IWebViewProviderWithType = {
webViewType: 'helloWorld.projectWebView',
async getWebView(
savedWebView: SavedWebViewDefinition,
getWebViewOptions: HelloWorldProjectViewerOptions,
): Promise<WebViewDefinition | undefined> {
if (savedWebView.webViewType !== this.webViewType)
throw new Error(
`${this.webViewType} provider received request to provide a ${savedWebView.webViewType} web view`,
);
// We know that the projectId (if present in the state) will be a string.
const projectId = getWebViewOptions.projectId || savedWebView.projectId || undefined;
return {
title: projectId
? `Hello World Project: ${
(await papi.projectLookup.getMetadataForProject(projectId)).name ?? projectId
}`
: 'Hello World Project',
...savedWebView,
content: helloWorldProjectWebView,
styles: helloWorldProjectWebViewStyles,
projectId,
};
},
};
interface HelloWorldProjectViewerOptions extends GetWebViewOptions {
projectId: string | undefined;
}
/**
* Function to prompt for a project and open it in the hello world project web view. Registered as a
* command handler.
*/
async function openHelloWorldProjectWebView(
projectId: string | undefined,
): Promise<string | undefined> {
let projectIdForWebView = projectId;
if (!projectIdForWebView) {
projectIdForWebView = await papi.dialogs.selectProject({
title: 'Open Hello World Project',
prompt: 'Choose the Hello World project to view:',
includeProjectTypes: '^helloWorld$',
});
}
if (!projectIdForWebView) return undefined;
const options: HelloWorldProjectViewerOptions = { projectId: projectIdForWebView };
return papi.webViews.getWebView(helloWorldProjectWebViewProvider.webViewType, undefined, options);
}
// #endregion
function selectProjectToDelete(): Promise<string | undefined> {
return papi.dialogs.selectProject({
includeProjectTypes: 'helloWorld',
title: 'Delete Hello World Project',
prompt: 'Please choose a project to delete:',
});
}
/**
* Simple web view provider that provides helloWorld project viewer web views when papi requests
* them
*/
const helloWorldProjectViewerProvider: IWebViewProviderWithType = {
webViewType: 'helloWorld.projectViewer',
async getWebView(
savedWebView: SavedWebViewDefinition,
getWebViewOptions: HelloWorldProjectViewerOptions,
): Promise<WebViewDefinition | undefined> {
if (savedWebView.webViewType !== this.webViewType)
throw new Error(
`${this.webViewType} provider received request to provide a ${savedWebView.webViewType} web view`,
);
// We know that the projectId (if present in the state) will be a string.
const projectId = getWebViewOptions.projectId || savedWebView.projectId || undefined;
return {
title: projectId
? `Hello World Project Viewer: ${
(await papi.projectLookup.getMetadataForProject(projectId)).name ?? projectId
}`
: 'Hello World Project Viewer',
...savedWebView,
content: helloWorldProjectViewerWebView,
styles: helloWorldProjectWebViewStyles,
projectId,
};
},
};
/** Number of times the `helloWorld` function has been called */
let helloWorldCount = 0;
/** Emitter to inform subscribers when `helloWorld` is called */
let onHelloWorldEmitter: PlatformEventEmitter<HelloWorldEvent>;
const onHelloWorldEventType = 'helloWorld.onHelloWorld';
/**
* Simple function to return hello world. Registered as a command handler.
*
* Also counts up how many times anyone has called this function and sends events notifying
* subscribers when someone has called this function.
*/
function helloWorld() {
helloWorldCount += 1;
onHelloWorldEmitter?.emit({ times: helloWorldCount });
return 'Hello world!';
}
/** Simple function to throw a customized exception. Registered as a command handler */
function helloException(message: string) {
throw new Error(`Hello World Exception! ${message}`);
}
export async function activate(context: ExecutionActivationContext): Promise<void> {
logger.info('Hello world is activating!');
async function readRawDataForAllProjects(): Promise<string> {
try {
return await papi.storage.readUserData(context.executionToken, allProjectDataStorageKey);
} catch {
// No project data found or some other issue. With more important project data, we would be
// more careful not to do something that would overwrite project data if there were an error
return '{}';
}
}
async function writeRawDataForAllProjects(data: string): Promise<void> {
return papi.storage.writeUserData(context.executionToken, allProjectDataStorageKey, data);
}
const helloWorldProjectDataProviderEngineFactory = new HelloWorldProjectDataProviderEngineFactory(
readRawDataForAllProjects,
writeRawDataForAllProjects,
);
const helloWorldPdpefPromise = papi.projectDataProviders.registerProjectDataProviderEngineFactory(
'helloWorld',
helloWorldProjectDataProviderEngineFactory,
);
const openHelloWorldProjectPromise = papi.commands.registerCommand(
'helloWorld.openProject',
openHelloWorldProjectWebView,
);
const createNewHelloWorldProjectPromise = papi.commands.registerCommand(
'helloWorld.createNewProject',
async (openWebView = true) => {
const projectId = await helloWorldProjectDataProviderEngineFactory.createNewProject();
if (openWebView) papi.commands.sendCommand('helloWorld.openProject', projectId);
return projectId;
},
);
const deleteHelloWorldProjectPromise = papi.commands.registerCommand(
'helloWorld.deleteProject',
async (projectId) => {
const projectIdToDelete = projectId ?? (await selectProjectToDelete());
if (!projectIdToDelete) return false;
// TODO: close web views if this is successful (we don't currently have a way to close them or
// to query for open ones)
return helloWorldProjectDataProviderEngineFactory.deleteProject(projectIdToDelete);
},
);
const deleteHelloWorldProjectByWebViewIdPromise = papi.commands.registerCommand(
'helloWorld.deleteProjectByWebViewId',
async (webViewId) => {
let projectId: string | undefined;
if (webViewId) {
const webViewDefinition = await papi.webViews.getSavedWebViewDefinition(webViewId);
projectId = webViewDefinition?.projectId;
}
const projectIdToDelete = projectId ?? (await selectProjectToDelete());
if (!projectIdToDelete) return false;
// TODO: close web views if this is successful (we don't currently have a way to close them or
// to query for open ones)
return helloWorldProjectDataProviderEngineFactory.deleteProject(projectIdToDelete);
},
);
const openHelloWorldProjectViewerByWebViewIdPromise = papi.commands.registerCommand(
'helloWorld.openViewerByWebViewId',
async (webViewId) => {
let projectId: string | undefined;
if (webViewId) {
const webViewDefinition = await papi.webViews.getSavedWebViewDefinition(webViewId);
projectId = webViewDefinition?.projectId;
}
const projectIdForWebView =
projectId ??
(await papi.dialogs.selectProject({
includeProjectTypes: 'helloWorld',
title: 'Open Hello World Project Viewer',
prompt: 'Please choose a project for which to open the viewer:',
}));
if (!projectIdForWebView) return undefined;
const options: HelloWorldProjectViewerOptions = { projectId: projectIdForWebView };
return papi.webViews.getWebView(
helloWorldProjectViewerProvider.webViewType,
{ type: 'float', position: 'center' },
options,
);
},
);
const helloWorldPersonNamePromise = papi.settings.registerValidator(
'helloWorld.personName',
async (newValue) => typeof newValue === 'string',
);
const helloWorldHeaderSizePromise = papi.projectSettings.registerValidator(
'helloWorld.headerSize',
async (newValue) => typeof newValue === 'number' && Number.isInteger(newValue) && newValue > 0,
);
const helloWorldHeaderColorPromise = papi.projectSettings.registerValidator(
'helloWorld.headerColor',
async (newValue) => HTML_COLOR_NAMES.includes(newValue),
);
const helloWorldProjectWebViewProviderPromise = papi.webViewProviders.register(
helloWorldProjectWebViewProvider.webViewType,
helloWorldProjectWebViewProvider,
);
const helloWorldProjectViewerProviderPromise = papi.webViewProviders.register(
helloWorldProjectViewerProvider.webViewType,
helloWorldProjectViewerProvider,
);
const htmlWebViewProviderPromise = papi.webViewProviders.register(
htmlWebViewProvider.webViewType,
htmlWebViewProvider,
);
const reactWebViewProviderPromise = papi.webViewProviders.register(
reactWebViewProvider.webViewType,
reactWebViewProvider,
);
const reactWebView2ProviderPromise = papi.webViewProviders.register(
reactWebView2Provider.webViewType,
reactWebView2Provider,
);
onHelloWorldEmitter =
papi.network.createNetworkEventEmitter<HelloWorldEvent>(onHelloWorldEventType);
const helloWorldPromise = papi.commands.registerCommand('helloWorld.helloWorld', helloWorld);
const helloExceptionPromise = papi.commands.registerCommand(
'helloWorld.helloException',
helloException,
);
papi
.fetch('https://www.example.com')
.catch((e) => logger.error(`Could not get data from example.com! Reason: ${e}`));
// Create webviews or get an existing webview if one already exists for this type
// Note: here, we are using `existingId: '?'` to indicate we do not want to create a new webview
// if one already exists. The webview that already exists could have been created by anyone
// anywhere; it just has to match `webViewType`. See `hello-someone.ts` for an example of keeping
// an existing webview that was specifically created by `hello-someone`.
papi.webViews.getWebView(htmlWebViewProvider.webViewType, undefined, { existingId: '?' });
papi.webViews.getWebView(reactWebViewProvider.webViewType, undefined, { existingId: '?' });
papi.webViews.getWebView(reactWebView2Provider.webViewType, undefined, { existingId: '?' });
const peopleDataProvider = await papi.dataProviders.get('helloSomeone.people');
if (peopleDataProvider) {
// Test subscribing to a data provider
const unsubGreetings = await peopleDataProvider.subscribeGreeting(
'Bill',
(billGreeting: string | undefined) => logger.debug(`Bill's greeting: ${billGreeting}`),
);
context.registrations.add(unsubGreetings);
}
// Await the registration promises at the end so we don't hold everything else up
context.registrations.add(
await helloWorldPdpefPromise,
await helloWorldProjectWebViewProviderPromise,
await helloWorldProjectViewerProviderPromise,
await openHelloWorldProjectPromise,
await createNewHelloWorldProjectPromise,
await deleteHelloWorldProjectPromise,
await deleteHelloWorldProjectByWebViewIdPromise,
await openHelloWorldProjectViewerByWebViewIdPromise,
await helloWorldPersonNamePromise,
await helloWorldHeaderSizePromise,
await helloWorldHeaderColorPromise,
await htmlWebViewProviderPromise,
await reactWebViewProviderPromise,
await reactWebView2ProviderPromise,
onHelloWorldEmitter,
await helloWorldPromise,
await helloExceptionPromise,
);
logger.info('Hello World is finished activating!');
}