-
Notifications
You must be signed in to change notification settings - Fork 23
/
app.plugin.ts
456 lines (394 loc) · 11.5 KB
/
app.plugin.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import type { ExpoConfig } from 'expo/config';
import {
AndroidConfig,
withAndroidManifest,
withDangerousMod,
withStringsXml,
type ExportedConfigWithProps,
} from 'expo/config-plugins';
import * as fs from 'fs';
import * as path from 'path';
const { getMainApplicationOrThrow } = AndroidConfig.Manifest;
export type ResourcePath = `./${string}` | `../${string}`;
export interface Widget {
/**
* Name of the widget which will be used to reference it in code
*/
name: string;
/**
* Label that will be shown in widget picker
*/
label?: string;
/**
* Description that will be shown in widget picker
*/
description?: string;
minWidth: `${number}dp`;
minHeight: `${number}dp`;
targetCellWidth?: number;
targetCellHeight?: number;
maxResizeWidth?: `${number}dp`;
maxResizeHeight?: `${number}dp`;
previewImage?: ResourcePath;
resizeMode?: 'none' | 'horizontal' | 'vertical' | 'horizontal|vertical';
/**
* Whether the widget can be configured.
* 'configurable' means that the widget is configurable, and a
* configuration activity will be open when the widget is added on home screen.
* 'reconfigurable|configuration_optional' will make the widget configurable,
* but will not open the configuration activity when added on home screen,
* and the configuration can be changed by holding the widget and selecting configure.
* The widget will not be configurable if `widgetFeatures` is not provided
*/
widgetFeatures?: 'reconfigurable' | 'reconfigurable|configuration_optional';
/**
* How often the widget should be updated, in milliseconds.
*
* Default is 0 (no automatic updates)
*
* Minimum is 1.800.000 (30 minutes == 30 * 60 * 1000).
*/
updatePeriodMillis?: number;
}
export interface WithAndroidWidgetsParams {
fonts?: ResourcePath[];
widgets: Widget[];
}
interface ProjectPaths {
platformProjectRoot: string;
projectRoot: string;
}
export default function withAndroidWidgets(
config: ExpoConfig,
params: WithAndroidWidgetsParams
) {
let projectPaths: ProjectPaths = {
platformProjectRoot: '',
projectRoot: '',
};
config = withAndroidManifest(
config,
(
androidManifestConfig: ExportedConfigWithProps<AndroidConfig.Manifest.AndroidManifest>
) => {
const mainApplication = getMainApplicationOrThrow(
androidManifestConfig.modResults
);
withCollectionService(mainApplication);
projectPaths.platformProjectRoot =
androidManifestConfig.modRequest.platformProjectRoot;
projectPaths.projectRoot = androidManifestConfig.modRequest.projectRoot;
withConfigurableActivity(mainApplication, params);
params.widgets.forEach((widget) => {
withWidgetReceiver(androidManifestConfig, mainApplication, widget);
});
return androidManifestConfig;
}
);
config = withWidgetDescriptions(config, params.widgets);
config = withFonts(config, projectPaths, params.fonts ?? []);
config = withWidgets(config, projectPaths, params.widgets);
config = withConfigurableActivityClass(config, projectPaths, params.widgets);
return config;
}
function withCollectionService(
mainApplication: AndroidConfig.Manifest.ManifestApplication
): void {
mainApplication.service = mainApplication.service ?? [];
const alreadyAdded = mainApplication.service.some(
(service) =>
service.$['android:name'] ===
'com.reactnativeandroidwidget.RNWidgetCollectionService'
);
if (alreadyAdded) return;
mainApplication.service?.push({
$: {
'android:name': 'com.reactnativeandroidwidget.RNWidgetCollectionService',
'android:permission': 'android.permission.BIND_REMOTEVIEWS',
},
});
}
function withConfigurableActivity(
mainApplication: AndroidConfig.Manifest.ManifestApplication,
params: WithAndroidWidgetsParams
) {
const hasConfigurableWidget = params.widgets.some(
(widget) => !!widget.widgetFeatures
);
if (hasConfigurableWidget) {
mainApplication.activity = mainApplication.activity ?? [];
const alreadyAdded = mainApplication.activity.some(
(activity) =>
activity.$['android:name'] === '.WidgetConfigurationActivity'
);
if (alreadyAdded) return;
mainApplication.activity?.push({
'$': {
'android:name': '.WidgetConfigurationActivity',
'android:exported': 'true',
},
'intent-filter': [
{
action: [
{
$: {
'android:name': 'android.appwidget.action.APPWIDGET_CONFIGURE',
},
},
],
},
],
});
}
}
function withConfigurableActivityClass(
config: ExpoConfig,
projectPaths: ProjectPaths,
widgets: Widget[]
) {
const hasConfigurableWidget = widgets.some(
(widget) => !!widget.widgetFeatures
);
if (hasConfigurableWidget) {
withDangerousMod(config, [
'android',
(dangerousConfig) => {
const appPackage = path.join(
projectPaths.platformProjectRoot,
'android/app/src/main/java/' +
config.android?.package?.split('.').join('/')
);
const javaFilePath = path.join(
appPackage,
`/WidgetConfigurationActivity.java`
);
const data = `package ${config.android?.package};
import com.reactnativeandroidwidget.RNWidgetConfigurationActivity;
public class WidgetConfigurationActivity extends RNWidgetConfigurationActivity {
}
`;
fs.writeFileSync(javaFilePath, data);
return dangerousConfig;
},
]);
}
return config;
}
function withWidgetReceiver(
config: ExpoConfig,
mainApplication: AndroidConfig.Manifest.ManifestApplication,
widget: Widget
): void {
mainApplication.receiver = mainApplication.receiver ?? [];
const alreadyAdded = mainApplication.receiver.some(
(service) => service.$['android:name'] === `.widget.${widget.name}`
);
if (alreadyAdded) return;
mainApplication.receiver?.push({
'$': {
'android:name': `.widget.${widget.name}`,
'android:exported': 'false',
'android:label': `${widget.label ?? widget.name}`,
} as any,
'intent-filter': [
{
action: [
{
$: {
'android:name': 'android.appwidget.action.APPWIDGET_UPDATE',
},
},
{
$: {
'android:name': `${config.android?.package}.WIDGET_CLICK`,
},
},
],
},
],
'meta-data': {
$: {
'android:name': 'android.appwidget.provider',
'android:resource': `@xml/widgetprovider_${widget.name.toLowerCase()}`,
},
},
} as any);
}
function withWidgetDescriptions(config: ExpoConfig, widgets: Widget[]) {
return withStringsXml(config, (stringsXml) => {
widgets
.filter((widget) => !!widget.description)
.forEach((widget) => {
stringsXml.modResults = AndroidConfig.Strings.setStringItem(
[
{
$: {
name: `widget_${widget.name.toLowerCase()}_description`,
translatable: 'false',
},
_: `${widget.description}`.replace(/'/g, "\\'"),
},
],
stringsXml.modResults
);
});
return stringsXml;
});
}
function withFonts(
config: ExpoConfig,
androidManifestConfig: ProjectPaths,
fonts: ResourcePath[]
) {
return withDangerousMod(config, [
'android',
(dangerousConfig) => {
if (fonts.length === 0) {
return dangerousConfig;
}
const fontsDir = path.join(
androidManifestConfig.platformProjectRoot,
'android/app/src/main/assets/fonts'
);
fs.mkdirSync(fontsDir, { recursive: true });
fonts.forEach((font: ResourcePath) => {
const fontAssetPath = path.resolve(
androidManifestConfig.projectRoot,
font
);
const output = path.join(fontsDir, path.basename(fontAssetPath));
fs.copyFileSync(fontAssetPath, output);
});
return dangerousConfig;
},
]);
}
function withWidgets(
config: ExpoConfig,
projectPaths: ProjectPaths,
widgets: Widget[]
) {
widgets.forEach((widget: Widget) => {
withWidget(config, projectPaths, widget);
});
return config;
}
function withWidget(
config: ExpoConfig,
projectPaths: ProjectPaths,
widget: Widget
) {
withDangerousMod(config, [
'android',
(dangerousConfig) => {
withWidgetProviderClass(dangerousConfig, projectPaths, widget);
withWidgetProviderXml(dangerousConfig, projectPaths, widget);
withWidgetPreview(projectPaths, widget);
return dangerousConfig;
},
]);
}
function withWidgetProviderClass(
config: ExpoConfig,
projectPaths: ProjectPaths,
widget: Widget
) {
const widgetPackagePath = path.join(
projectPaths.platformProjectRoot,
'android/app/src/main/java/' +
config.android?.package?.split('.').join('/') +
'/widget'
);
const javaFilePath = path.join(widgetPackagePath, `/${widget.name}.java`);
const data = `package ${config.android?.package}.widget;
import com.reactnativeandroidwidget.RNWidgetProvider;
public class ${widget.name} extends RNWidgetProvider {
}
`;
fs.mkdirSync(widgetPackagePath, { recursive: true });
fs.writeFileSync(javaFilePath, data);
}
function withWidgetProviderXml(
config: ExpoConfig,
projectPaths: ProjectPaths,
widget: Widget
) {
const xmlFolderPath = path.join(
projectPaths.platformProjectRoot,
'android/app/src/main/res/xml'
);
const xmlPath = path.join(
xmlFolderPath,
`/widgetprovider_${widget.name.toLowerCase()}.xml`
);
const data = `<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="${widget.minWidth}"
android:minHeight="${widget.minHeight}"
${
widget.targetCellWidth
? ` android:targetCellWidth="${widget.targetCellWidth}"`
: ''
}
${
widget.targetCellHeight
? ` android:targetCellHeight="${widget.targetCellHeight}"`
: ''
}
${
widget.maxResizeWidth
? ` android:maxResizeWidth="${widget.maxResizeWidth}"`
: ''
}
${
widget.maxResizeHeight
? ` android:maxResizeHeight="${widget.maxResizeHeight}"`
: ''
}
android:resizeMode="${widget.resizeMode ?? 'none'}"
${
widget.description
? ` android:description="@string/widget_${widget.name.toLowerCase()}_description"`
: ''
}
android:initialLayout="@layout/rn_widget"
${
widget.previewImage
? ` android:previewImage="@drawable/${widget.name.toLowerCase()}_preview"`
: ''
}
${
widget.widgetFeatures
? ` android:configure="${config.android?.package}.WidgetConfigurationActivity"
android:widgetFeatures="${widget.widgetFeatures}"`
: ''
}
android:updatePeriodMillis="${
widget.updatePeriodMillis
? Math.max(30 * 60 * 1000, widget.updatePeriodMillis)
: 0
}"
android:widgetCategory="home_screen">
</appwidget-provider>
`;
fs.mkdirSync(xmlFolderPath, { recursive: true });
fs.writeFileSync(xmlPath, data);
}
function withWidgetPreview(projectPaths: ProjectPaths, widget: Widget) {
if (widget.previewImage) {
const drawableDir = path.join(
projectPaths.platformProjectRoot,
'android/app/src/main/res/drawable'
);
fs.mkdirSync(drawableDir, { recursive: true });
const previewAssetPath = path.resolve(
projectPaths.projectRoot,
widget.previewImage
);
const output = path.join(
drawableDir,
`${widget.name.toLowerCase()}_preview${path.extname(previewAssetPath)}`
);
fs.copyFileSync(previewAssetPath, output);
}
}