tauri-plugin-live-activity 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/ios.mjs CHANGED
@@ -1,16 +1,23 @@
1
- // The iOS part of setup: Info.ios.plist, the widget files in gen/apple, the XcodeGen spec that adds
2
- // the widget extension, the plugin's Swift package and the regenerated Xcode project.
1
+ // The iOS part of setup: Info.ios.plist, the widget files in gen/apple with the fonts and images it bundles, the
2
+ // XcodeGen spec that adds the widget extension on activitykit's Swift package, the App Group, and the regenerated
3
+ // Xcode project. An app that 0.2 or 0.3 set up loses the plugin's old Swift files on the way (migration.mjs).
3
4
  import { spawnSync } from 'node:child_process';
4
- import { cpSync, existsSync, readdirSync } from 'node:fs';
5
- import { join, relative, resolve, sep } from 'node:path';
5
+ import { readdirSync, rmSync } from 'node:fs';
6
+ import { join, resolve } from 'node:path';
7
+ import { OLD_MODULES, RETIRED, released, renameCustomViews } from './migration.mjs';
6
8
  import { newPlist, setTrueKey } from './plist.mjs';
7
9
  import { SetupError, parseJson, readText, step, tail, which, writeFile } from './steps.mjs';
8
- import { SPEC_FILE, WIDGET, addInclude, readProject, widgetSpec, writtenBySetup } from './xcodegen.mjs';
10
+ import { assetSteps, bundledFonts, fontSteps } from './widget-files.mjs';
11
+ import { SPEC_FILE, WIDGET, addInclude, appGroupOf, readProject, widgetSpec, writtenBySetup } from './xcodegen.mjs';
9
12
 
10
- const TEMPLATES = ['LiveActivityWidget.swift', 'LiveActivityActionIntent.swift', 'Info.plist'];
13
+ /** The widget bundle: activitykit's template, under the name 0.2 and 0.3 gave the plugin's. */
14
+ const WIDGET_FILE = 'LiveActivityWidget.swift';
15
+ const WIDGET_TEMPLATE = join('templates', 'ios', 'Widget.swift');
16
+ /** The app's own file: created once from the template and never written again, but for the names of activitykit. */
17
+ const CUSTOM_VIEWS = 'LiveActivityCustomViews.swift';
18
+ const CUSTOM_VIEWS_TEMPLATE = new URL('./templates/LiveActivityCustomViews.swift', import.meta.url);
19
+ const GROUP = /^group\.[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/;
11
20
  const PLIST_KEY = 'NSSupportsLiveActivities';
12
- // Left out of the copy of Tauri's Swift API, as the plugin's build script does.
13
- const NOT_COPIED = ['.build', 'Package.resolved', 'Tests'];
14
21
 
15
22
  export function iosSteps(context) {
16
23
  const { srcTauri, platform, show } = context;
@@ -25,15 +32,54 @@ export function iosSteps(context) {
25
32
  const plist = infoPlistStep(context);
26
33
  if (project.widget) {
27
34
  const detail = `already has a widget extension, ${project.widget}; add the plugin's widget to it by hand (docs/ios-integration.md)`;
28
- return [plist, step('skipped', show(specPath), detail)];
35
+ const { files, appGroup } = context;
36
+ const given = [files.fonts.length && '--font', files.assets.length && '--asset', appGroup && '--app-group'].filter(Boolean);
37
+ const left = given.length === 0 ? [] : [step('todo', show(specPath), `${given.join(', ')} not applied: that widget is yours to give fonts, images and an App Group (docs/ios-integration.md)`)];
38
+ return [plist, step('skipped', show(specPath), detail), ...left];
29
39
  }
30
40
  if (!project.appTarget) {
31
41
  const detail = `no target named ${project.name ?? '<name>'}_iOS, so setup did not add the widget; see docs/usage.md`;
32
42
  return [plist, step('todo', show(specPath), detail)];
33
43
  }
34
- // XcodeGen lists the files of a folder when it generates, so a new widget file also needs a run.
35
- const projectSteps = [...templateSteps(context, apple), specStep(context, apple, project), includeStep(context, specPath, yaml)];
36
- return [plist, ...projectSteps, swiftPackageStep(context), xcodegenStep(context, apple, specPath, projectSteps)];
44
+ const widget = join(apple, WIDGET);
45
+ const appGroup = appGroupFor(context, apple, project);
46
+ const include = includeStep(context, specPath, yaml);
47
+ // XcodeGen lists the files of a folder when it generates, so a new or removed widget file also needs a run.
48
+ const projectSteps = [
49
+ widgetStep(context, widget), ...retiredSteps(context, widget, readText(join(apple, SPEC_FILE))), customViewsStep(context, widget),
50
+ ...fontSteps(context, widget), ...assetSteps(context, widget),
51
+ specStep(context, apple, project, { fonts: bundledFonts(context, widget), appGroup }), include,
52
+ ];
53
+ return [plist, ...projectSteps, xcodegenStep(context, apple, specPath, projectSteps, include)];
54
+ }
55
+
56
+ /**
57
+ * The App Group of `--app-group`: the group it names, or `group.<app identifier>`. A spec that setup wrote
58
+ * with a group keeps it on later runs.
59
+ */
60
+ function appGroupFor({ appGroup, config }, apple, project) {
61
+ const kept = appGroupOf(readText(join(apple, SPEC_FILE)));
62
+ const group = typeof appGroup === 'string' ? appGroup : kept ?? (appGroup ? `group.${project.bundleId ?? config.identifier}` : undefined);
63
+ if (group !== undefined && !GROUP.test(group)) {
64
+ throw new SetupError(`The App Group ${JSON.stringify(group)} must be "group." followed by letters, digits, '-' and '.'.`);
65
+ }
66
+ return group;
67
+ }
68
+
69
+ /**
70
+ * LiveActivityCustomViews.swift belongs to the app: created once, then never written again, except that a file of 0.3
71
+ * takes activitykit's names, its views kept.
72
+ */
73
+ function customViewsStep({ show }, widget) {
74
+ const path = join(widget, CUSTOM_VIEWS);
75
+ const current = readText(path);
76
+ if (current !== undefined) {
77
+ const renamed = renameCustomViews(current);
78
+ if (renamed === undefined) return step('unchanged', show(path));
79
+ return step('updated', show(path), "activitykit's names for the registry and its types; your views are kept", writeFile(path, renamed));
80
+ }
81
+ const stub = readText(CUSTOM_VIEWS_TEMPLATE);
82
+ return step('created', show(path), 'yours, for custom views; setup never changes it again', writeFile(path, stub));
37
83
  }
38
84
 
39
85
  /** Tauri merges src-tauri/Info.ios.plist into the app's Info.plist when it builds. */
@@ -50,24 +96,52 @@ function infoPlistStep({ srcTauri, show }) {
50
96
  return step('kept', show(path), `it sets ${PLIST_KEY} to something other than true; Live Activities need true`);
51
97
  }
52
98
 
53
- function templateSteps({ plugin, show }, apple) {
54
- return TEMPLATES.map(name => {
55
- const wanted = readText(join(plugin.dir, 'templates', 'ios', name));
56
- if (wanted === undefined) throw new SetupError(`The plugin crate at ${plugin.dir} has no templates/ios/${name}.`);
57
- const path = join(apple, WIDGET, name);
99
+ /** The widget bundle from activitykit's template; one that 0.2 or 0.3 wrote is replaced, one of the app's kept. */
100
+ function widgetStep({ activitykit, show }, widget) {
101
+ const wanted = readText(join(activitykit.dir, WIDGET_TEMPLATE));
102
+ if (wanted === undefined) throw new SetupError(`The activitykit crate at ${activitykit.dir} has no ${WIDGET_TEMPLATE}.`);
103
+ const path = join(widget, WIDGET_FILE);
104
+ const current = readText(path);
105
+ if (current === undefined) return step('created', show(path), '', writeFile(path, wanted));
106
+ if (current === wanted) return step('unchanged', show(path));
107
+ if (released(WIDGET_FILE, current)) {
108
+ return step('updated', show(path), "activitykit's widget, in place of the one tauri-plugin-live-activity 0.3 wrote", writeFile(path, wanted));
109
+ }
110
+ if (OLD_MODULES.test(current)) {
111
+ return step('todo', show(path), "imports the Swift modules of tauri-plugin-live-activity 0.3, which 0.4 no longer has: draw with ActivityKitWidget's ActivityKitLayoutWidget(), or delete the file and run setup again");
112
+ }
113
+ return step('kept', show(path), "differs from activitykit's template; to take the template, delete it and run setup again");
114
+ }
115
+
116
+ /**
117
+ * The button intent and the custom views registry of 0.2 and 0.3, which activitykit's products replace. A spec changed
118
+ * by hand, which setup keeps, may still name one: XcodeGen would fail without it, so it stays as a step to do.
119
+ */
120
+ function retiredSteps({ show }, widget, spec) {
121
+ const kept = spec !== undefined && !writtenBySetup(spec);
122
+ return RETIRED.flatMap(name => {
123
+ const path = join(widget, name);
58
124
  const current = readText(path);
59
- if (current === undefined) return step('created', show(path), '', writeFile(path, wanted));
60
- // XcodeGen writes the extension's Info.plist from the spec, so it differs from the template.
61
- if (current === wanted || name === 'Info.plist') return step('unchanged', show(path));
62
- return step('kept', show(path), "differs from the plugin's template; to take the template, delete it and run setup again");
125
+ if (current === undefined) return [];
126
+ if (kept && spec.includes(name)) {
127
+ return [step('todo', show(path), `${SPEC_FILE}, which you changed, still names it: take it out of the spec, then delete it; activitykit's Swift package replaces it`)];
128
+ }
129
+ if (released(name, current)) {
130
+ return [step('removed', show(path), "activitykit's Swift package replaces it", () => rmSync(path))];
131
+ }
132
+ return [step('todo', show(path), "changed by hand; activitykit's Swift package replaces it, so move your changes and delete it")];
63
133
  });
64
134
  }
65
135
 
66
- function specStep({ plugin, config, srcTauri, show }, apple, project) {
136
+ function specStep({ plugin, activitykit, config, srcTauri, show }, apple, project, { fonts, appGroup }) {
67
137
  const path = join(apple, SPEC_FILE);
68
138
  const wanted = widgetSpec({
139
+ fonts,
140
+ appGroup,
141
+ // XcodeGen writes the entitlements file from the spec, so the App Group goes into the spec, at the app's path.
142
+ appEntitlements: project.entitlements ?? `${project.appTarget}/${project.appTarget}.entitlements`,
69
143
  pluginVersion: plugin.version,
70
- packagePath: join(plugin.dir, 'ios'),
144
+ packagePath: join(activitykit.dir, 'swift'),
71
145
  appTarget: project.appTarget,
72
146
  bundleId: `${project.bundleId ?? config.identifier}.widget`,
73
147
  ...appVersions(config, srcTauri),
@@ -75,13 +149,13 @@ function specStep({ plugin, config, srcTauri, show }, apple, project) {
75
149
  });
76
150
  const current = readText(path);
77
151
  if (current === undefined) {
78
- return step('created', show(path), 'the widget extension, and the button intent in both targets', writeFile(path, wanted));
152
+ return step('created', show(path), "the widget extension on activitykit's Swift package, and the button intent and custom views in the app", writeFile(path, wanted));
79
153
  }
80
154
  if (current === wanted) return step('unchanged', show(path));
81
155
  if (!writtenBySetup(current)) {
82
156
  return step('kept', show(path), 'it was changed by hand; delete it and run setup again to have it written anew');
83
157
  }
84
- return step('updated', show(path), 'for the current plugin and app version', writeFile(path, wanted));
158
+ return step('updated', show(path), 'for the current plugin, activitykit and app version', writeFile(path, wanted));
85
159
  }
86
160
 
87
161
  /** The `version` of Cargo.toml's [package] section. */
@@ -110,30 +184,15 @@ function includeStep({ show }, specPath, yaml) {
110
184
  return step('todo', show(specPath), `add ${SPEC_FILE} to its include list`);
111
185
  }
112
186
 
113
- /** The plugin's Swift package refers to Tauri's at ../.tauri/tauri-api, which the plugin's iOS build copies there. */
114
- function swiftPackageStep({ plugin, show }) {
115
- const target = join(plugin.dir, '.tauri', 'tauri-api');
116
- if (existsSync(join(target, 'Package.swift'))) return step('unchanged', show(target));
117
- const source = plugin.tauriDir && join(plugin.tauriDir, 'mobile', 'ios-api');
118
- if (!source || !existsSync(join(source, 'Package.swift'))) {
119
- const detail = "the plugin's Swift package needs Tauri's Swift API here. Build the Rust code for iOS once to make it: "
120
- + 'cargo build --target aarch64-apple-ios-sim (x86_64-apple-ios on an Intel Mac) in src-tauri';
121
- return step('todo', show(target), detail);
122
- }
123
- const copied = path => !NOT_COPIED.some(name => relative(source, path) === name || relative(source, path).startsWith(name + sep));
124
- const detail = "Tauri's Swift API for the plugin's Swift package, as the plugin's iOS build copies it";
125
- return step('created', show(target), detail, () => cpSync(source, target, { recursive: true, filter: copied }));
126
- }
127
-
128
187
  function generatedWithWidget(apple) {
129
188
  return readdirSync(apple).filter(name => name.endsWith('.xcodeproj'))
130
189
  .some(name => readText(join(apple, name, 'project.pbxproj'))?.includes(WIDGET));
131
190
  }
132
191
 
133
- function xcodegenStep({ env, show }, apple, specPath, projectSteps) {
192
+ function xcodegenStep({ env, show }, apple, specPath, projectSteps, include) {
134
193
  const command = `xcodegen generate --spec ${show(specPath)}`;
135
- if (projectSteps.some(item => item.status === 'todo')) return step('skipped', 'Xcode project', 'waits for the include in project.yml');
136
- const changed = projectSteps.some(item => item.status === 'created' || item.status === 'updated');
194
+ if (include.status === 'todo') return step('skipped', 'Xcode project', 'waits for the include in project.yml');
195
+ const changed = projectSteps.some(item => ['created', 'updated', 'removed'].includes(item.status));
137
196
  if (!changed && generatedWithWidget(apple)) return step('unchanged', 'Xcode project');
138
197
  const xcodegen = which('xcodegen', env);
139
198
  if (!xcodegen) return step('todo', 'Xcode project', `XcodeGen is not on PATH. Install it (brew install xcodegen), then run: ${command}`);
package/cli/main.mjs CHANGED
@@ -2,20 +2,42 @@
2
2
  import { formatReport } from './report.mjs';
3
3
  import { SetupError, setup } from './setup.mjs';
4
4
 
5
- const USAGE = `Usage: npx tauri-plugin-live-activity setup [--dry-run] [--ios-only]
5
+ const USAGE = `Usage: npx tauri-plugin-live-activity setup [--dry-run] [--ios-only] [--font <file>]... [--asset <file>]... [--app-group[=<id>]]
6
6
 
7
7
  Run it in the folder of a Tauri 2 app after \`cargo add\` and \`npm i\`. It grants the plugin's
8
8
  permissions, sets the Android minimum to API 26 and, on a Mac, adds the Live Activity widget
9
9
  extension to src-tauri/gen/apple. Run it after \`tauri ios init\`, and again if that folder is
10
10
  ever made from scratch.
11
11
 
12
- --dry-run show what would change, and write nothing
13
- --ios-only do only the iOS part: leave the capabilities and tauri.conf.json alone
12
+ --dry-run show what would change, and write nothing
13
+ --ios-only do only the iOS part: leave the capabilities and tauri.conf.json alone
14
+ --font <file> bundle a .ttf, .otf or .ttc font in the widget extension, for a style's fontFamily
15
+ --asset <file> put a .png, .jpg, .pdf or .svg image in the widget's asset catalog, for image('<name>');
16
+ name@2x.png and name@3x.png are scales of the asset name
17
+ --app-group[=<id>] give the app and the widget extension an App Group, group.<app identifier> unless
18
+ named, so writeImage can share images; later runs keep it
14
19
  `;
15
20
 
16
21
  const FLAGS = { '--dry-run': 'dryRun', '--ios-only': 'iosOnly' };
22
+ const FILES = { '--font': 'fonts', '--asset': 'assets' };
17
23
  const HELP = new Set(['help', '--help', '-h']);
18
24
 
25
+ /** The options of `setup`, or the argument it does not take and why. */
26
+ function parseOptions(args) {
27
+ const options = { fonts: [], assets: [] };
28
+ for (let index = 0; index < args.length; index += 1) {
29
+ const [name, inline] = args[index].split(/=(.*)/s);
30
+ if (Object.hasOwn(FLAGS, args[index])) options[FLAGS[args[index]]] = true;
31
+ else if (name === '--app-group') options.appGroup = inline ?? true;
32
+ else if (Object.hasOwn(FILES, name)) {
33
+ const file = inline ?? args[(index += 1)];
34
+ if (!file) return { error: `${name} needs a file.` };
35
+ options[FILES[name]].push(file);
36
+ } else return { error: `Unknown option ${args[index]}.` };
37
+ }
38
+ return { options };
39
+ }
40
+
19
41
  /** Runs the command and returns its exit status: 0 done, 1 something left to do or an error, 2 usage. */
20
42
  export function main(argv, {
21
43
  cwd = process.cwd(), env = process.env, platform = process.platform,
@@ -26,12 +48,15 @@ export function main(argv, {
26
48
  out(USAGE);
27
49
  return 0;
28
50
  }
29
- const unknown = command === 'setup' ? rest.find(arg => !Object.hasOwn(FLAGS, arg)) : command;
30
- if (unknown !== undefined) {
31
- err(`Unknown ${command === 'setup' ? 'option' : 'command'} ${unknown}.\n\n${USAGE}`);
51
+ if (command !== 'setup') {
52
+ err(`Unknown command ${command}.\n\n${USAGE}`);
53
+ return 2;
54
+ }
55
+ const { options, error } = parseOptions(rest);
56
+ if (error) {
57
+ err(`${error}\n\n${USAGE}`);
32
58
  return 2;
33
59
  }
34
- const options = Object.fromEntries(rest.map(arg => [FLAGS[arg], true]));
35
60
  try {
36
61
  const result = setup({ cwd, env, platform, ...options });
37
62
  out(formatReport(result));
@@ -0,0 +1,55 @@
1
+ // What setup changes in an app that tauri-plugin-live-activity 0.2 or 0.3 set up, whose widget extension and app
2
+ // target compiled the plugin's own Swift: 0.4 takes the widget, the button intent and the custom views registry from
3
+ // activitykit's Swift package.
4
+ import { createHash } from 'node:crypto';
5
+
6
+ /** The SHA-256 of each template as a release of the plugin wrote it into the widget folder. */
7
+ export const RELEASED = {
8
+ // 0.2.0, 0.2.1 and 0.3.0: the button intent, which activitykit's ActivityKitIntent product replaces.
9
+ 'LiveActivityActionIntent.swift': ['cd96e40c42aae84b2e76db2f264f8ead892bf77c282e51f7443dc8624bc3ead5'],
10
+ // 0.3.0: the base of the custom views, which activitykit's ActivityKitViews product replaces.
11
+ 'LiveActivityCustomRegistry.swift': ['75c2275fe63da34234fca039ed459151edb851c1acf1faf0e6a400791345983f'],
12
+ // 0.2.x and 0.3.0: the widget bundle on the plugin's own Swift modules.
13
+ 'LiveActivityWidget.swift': [
14
+ '2a76d033acbbd208c7050e10394c31c120ad96d0ff55189daed11ad5255cbd2c',
15
+ 'a8abe58a70300204b1406e5dbcc0d53f6265b525785903d5b2e6e1d2b317476d',
16
+ ],
17
+ };
18
+
19
+ /** Files that only the plugin's own Swift needed. */
20
+ export const RETIRED = ['LiveActivityActionIntent.swift', 'LiveActivityCustomRegistry.swift'];
21
+
22
+ /** The Swift modules of the plugin before 0.4; a widget file that imports one no longer builds. */
23
+ export const OLD_MODULES = /\bimport\s+(LiveActivityShared|LiveActivityUI|LiveActivityCore)\b/;
24
+
25
+ const sha256 = text => createHash('sha256').update(text).digest('hex');
26
+
27
+ /** True when `text` is the file `name` exactly as a release wrote it. */
28
+ export function released(name, text) {
29
+ return RELEASED[name]?.includes(sha256(text)) ?? false;
30
+ }
31
+
32
+ // The names of 0.3's custom views file and activitykit's, longest first: `LiveActivityCustomView` is a prefix of the
33
+ // other two, and the class `LiveActivityCustomViews` keeps its Swift name.
34
+ const RENAMES = [
35
+ ['TauriLiveActivityCustomViews', 'ActivityKitCustomViews'],
36
+ ['LiveActivityCustomViewRegistry', 'ActivityKitCustomViewRegistry'],
37
+ ['LiveActivityCustomProps', 'ActivityKitCustomProps'],
38
+ ['LiveActivityCustomView', 'ActivityKitCustomView'],
39
+ ];
40
+
41
+ /**
42
+ * The app's custom views file with activitykit's names: the Objective-C name, the registry, the view and props types,
43
+ * and `import ActivityKitViews`. The app's views stay as they are. Undefined when the file has none of 0.3's names.
44
+ */
45
+ export function renameCustomViews(text) {
46
+ if (!RENAMES.some(([old]) => new RegExp(`\\b${old}\\b`).test(text))) return undefined;
47
+ let next = RENAMES.reduce((current, [old, name]) => current.replace(new RegExp(`\\b${old}\\b`, 'g'), name), text);
48
+ if (!/^\s*import\s+ActivityKitViews\b/m.test(next)) {
49
+ const swiftUI = /^import SwiftUI[ \t]*$/m.exec(next);
50
+ next = swiftUI
51
+ ? `${next.slice(0, swiftUI.index)}import ActivityKitViews\n${next.slice(swiftUI.index)}`
52
+ : `import ActivityKitViews\n${next}`;
53
+ }
54
+ return next;
55
+ }
package/cli/report.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // The summary that setup prints.
2
2
 
3
- const DONE = { created: 'created', updated: 'updated', ran: 'ran', kept: 'kept', skipped: 'skipped' };
4
- const WOULD = { created: 'would create', updated: 'would update', ran: 'would run', kept: 'would keep', skipped: 'would skip' };
3
+ const DONE = { created: 'created', updated: 'updated', removed: 'removed', ran: 'ran', kept: 'kept', skipped: 'skipped' };
4
+ const WOULD = { created: 'would create', updated: 'would update', removed: 'would remove', ran: 'would run', kept: 'would keep', skipped: 'would skip' };
5
5
 
6
6
  function line(item, dryRun) {
7
7
  const label = (dryRun ? WOULD : DONE)[item.status];
package/cli/setup.mjs CHANGED
@@ -5,14 +5,17 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { iosSteps } from './ios.mjs';
7
7
  import { SetupError, display, jsonLike, parseJson, readText, step, tail, writeFile } from './steps.mjs';
8
+ import { widgetFiles } from './widget-files.mjs';
8
9
 
9
10
  export { SetupError } from './steps.mjs';
10
11
 
11
12
  export const CRATE = 'tauri-plugin-live-activity';
13
+ /** The crate whose Swift package the widget extension and the app target link. */
14
+ export const ACTIVITYKIT = 'activitykit';
12
15
  /** `default` reads; the others allow the commands that change activities. */
13
16
  export const PERMISSIONS = [
14
17
  'live-activity:default',
15
- ...['request-permissions', 'start', 'update', 'end', 'start-layout', 'update-layout', 'end-layout']
18
+ ...['request-permissions', 'start', 'update', 'end', 'start-layout', 'update-layout', 'end-layout', 'write-image']
16
19
  .map(command => `live-activity:allow-${command}`),
17
20
  ];
18
21
  // The plugin's Android library needs API 26: Tauri's Jackson runtime fails below it.
@@ -21,12 +24,17 @@ const NPM_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.me
21
24
 
22
25
  /**
23
26
  * Sets up the app in `cwd` (its folder or its src-tauri folder) and returns the steps with their
24
- * status, and notes for the person who runs it. Throws SetupError when it cannot start.
27
+ * status, and notes for the person who runs it. `fonts` and `assets` are files for the widget
28
+ * extension; `appGroup` is true or the name of an App Group. Throws SetupError when it cannot start.
25
29
  */
26
- export function setup({ cwd = process.cwd(), env = process.env, dryRun = false, iosOnly = false, platform = process.platform } = {}) {
30
+ export function setup({
31
+ cwd = process.cwd(), env = process.env, dryRun = false, iosOnly = false, platform = process.platform,
32
+ fonts = [], assets = [], appGroup = undefined,
33
+ } = {}) {
34
+ const files = widgetFiles(cwd, { fonts, assets });
27
35
  const app = findApp(cwd);
28
- const plugin = findPlugin(app, env);
29
- const context = { ...app, plugin, env, platform, show: path => display(cwd, path) };
36
+ const { plugin, activitykit } = findCrates(app, env);
37
+ const context = { ...app, plugin, activitykit, env, platform, files, appGroup, show: path => display(cwd, path) };
30
38
  const planned = [...(iosOnly ? [] : [capabilitiesStep(context), ...androidSteps(context)]), ...iosSteps(context)];
31
39
  const steps = dryRun ? planned : planned.map(apply);
32
40
  return { dryRun, version: plugin.version, steps: steps.map(({ effect, ...rest }) => rest), notes: notes(context) };
@@ -57,8 +65,11 @@ function findApp(cwd) {
57
65
  return { srcTauri, configPath, configText, config };
58
66
  }
59
67
 
60
- /** The plugin crate's folder from `cargo metadata`, and the folder of the `tauri` crate it uses. */
61
- function findPlugin({ srcTauri }, env) {
68
+ /**
69
+ * The plugin crate's version and the folder of the activitykit crate it depends on, from `cargo metadata`: the widget
70
+ * extension and the app target link activitykit's Swift package, which lies in that folder.
71
+ */
72
+ export function findCrates({ srcTauri }, env) {
62
73
  const args = ['metadata', '--format-version', '1', '--manifest-path', join(srcTauri, 'Cargo.toml')];
63
74
  const result = spawnSync(env.CARGO || 'cargo', args, { env, encoding: 'utf8', maxBuffer: 1024 ** 3 });
64
75
  if (result.error?.code === 'ENOENT') throw new SetupError('cargo was not found. Install Rust from https://rustup.rs, then run this again.');
@@ -70,9 +81,15 @@ function findPlugin({ srcTauri }, env) {
70
81
  if (!crate) {
71
82
  throw new SetupError(`${CRATE} is not a dependency of src-tauri/Cargo.toml yet. Add it first:\n cargo add ${CRATE} --manifest-path src-tauri/Cargo.toml`);
72
83
  }
73
- const tauriId = metadata.resolve?.nodes?.find(node => node.id === crate.id)?.deps?.find(dep => dep.name === 'tauri')?.pkg;
74
- const tauri = metadata.packages.find(item => (tauriId ? item.id === tauriId : item.name === 'tauri'));
75
- return { version: crate.version, dir: dirname(crate.manifest_path), tauriDir: tauri && dirname(tauri.manifest_path) };
84
+ const kitId = metadata.resolve?.nodes?.find(node => node.id === crate.id)?.deps?.find(dep => dep.name === ACTIVITYKIT)?.pkg;
85
+ const kit = metadata.packages.find(item => (kitId ? item.id === kitId : item.name === ACTIVITYKIT));
86
+ if (!kit) {
87
+ throw new SetupError(`${CRATE} ${crate.version} does not depend on ${ACTIVITYKIT}, whose Swift package the widget extension links: use the crate of the npm package's version, ${NPM_VERSION}.`);
88
+ }
89
+ return {
90
+ plugin: { version: crate.version, dir: dirname(crate.manifest_path) },
91
+ activitykit: { version: kit.version, dir: dirname(kit.manifest_path) },
92
+ };
76
93
  }
77
94
 
78
95
  /** Adds the plugin's permissions to the app's capability: default.json, or the only capability file. */
package/cli/steps.mjs CHANGED
@@ -9,7 +9,7 @@ export class SetupError extends Error {
9
9
  name = 'SetupError';
10
10
  }
11
11
 
12
- /** Status: created, updated, ran, kept, skipped, todo or unchanged. */
12
+ /** Status: created, updated, removed, ran, kept, skipped, todo or unchanged. */
13
13
  export function step(status, path, detail = '', effect = undefined) {
14
14
  return effect ? { status, path, detail, effect } : { status, path, detail };
15
15
  }
@@ -0,0 +1,25 @@
1
+ import ActivityKitViews
2
+ import SwiftUI
3
+
4
+ // Your SwiftUI views for `custom` layout nodes. `npx tauri-plugin-live-activity setup` created this file once and never
5
+ // changes it. It is compiled into the widget extension, which draws the views, and into the app, so that activitykit can
6
+ // report a node whose name has no view here (`degradedFeatures`: `layout.custom.<name>`). Both targets link activitykit's
7
+ // `ActivityKitViews` product. Keep the Objective-C name: activitykit finds the views by it.
8
+ //
9
+ // A view gets the node's props: `props.number("level")`, `props.string("label")`, `props.bool("full")`. A prop bound to a
10
+ // value, `props: { level: bind('bowl') }`, has the value of the latest update. The node's style sets the frame, padding,
11
+ // colors and font around the view. A Live Activity has no network and little memory: draw with shapes, text and images
12
+ // of the extension; no timers, no animations of your own.
13
+
14
+ @available(iOS 16.1, *)
15
+ @objc(ActivityKitCustomViews)
16
+ final class LiveActivityCustomViews: ActivityKitCustomViewRegistry {
17
+ override class var views: [String: ActivityKitCustomView] {
18
+ [
19
+ // The layout node `custom('ring', { props: { level: bind('bowl') } })` draws this ring:
20
+ // "ring": ActivityKitCustomView { props in
21
+ // Circle().trim(from: 0, to: props.number("level") ?? 0).stroke(lineWidth: 4).rotationEffect(.degrees(-90))
22
+ // },
23
+ ]
24
+ }
25
+ }
@@ -0,0 +1,148 @@
1
+ // The files that `setup --font` and `setup --asset` copy into the widget extension: fonts into
2
+ // LiveActivityWidget/Fonts, which the extension's Info.plist lists under UIAppFonts, and images into the
3
+ // extension's asset catalog, LiveActivityWidget/Assets.xcassets.
4
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs';
5
+ import { basename, dirname, extname, join, resolve } from 'node:path';
6
+ import { SetupError, parseJson, readText, step, writeFile } from './steps.mjs';
7
+
8
+ export const FONTS = 'Fonts';
9
+ export const CATALOG = 'Assets.xcassets';
10
+ const FONT_TYPES = new Set(['.ttf', '.otf', '.ttc']);
11
+ const IMAGE_TYPES = new Set(['.png', '.jpg', '.jpeg', '.pdf', '.svg']);
12
+ const VECTOR_TYPES = new Set(['.pdf', '.svg']);
13
+ // The rule of an image node's asset name, and a file name the bundle can carry.
14
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
15
+ const FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._@-]{0,127}$/;
16
+ const CATALOG_INFO = { info: { author: 'xcode', version: 1 } };
17
+
18
+ /**
19
+ * The fonts and images named on the command line, checked before anything is written: each exists, is a
20
+ * file of a kind the widget can use and has a name the bundle and a layout can carry.
21
+ */
22
+ export function widgetFiles(cwd, { fonts = [], assets = [] }) {
23
+ const file = (given, kinds, what) => {
24
+ const source = resolve(cwd, given);
25
+ if (!existsSync(source) || !statSync(source).isFile()) throw new SetupError(`${given}: no such file.`);
26
+ const kind = extname(source).toLowerCase();
27
+ if (!kinds.has(kind)) throw new SetupError(`${given}: ${what} must be ${[...kinds].join(', ')}.`);
28
+ if (!FILE_NAME.test(basename(source))) {
29
+ throw new SetupError(`${given}: rename it to ASCII letters, digits, spaces, '.', '_', '@' and '-' first.`);
30
+ }
31
+ return { source, file: basename(source), kind };
32
+ };
33
+ const once = list => {
34
+ const repeated = list.find((item, index) => list.findIndex(other => other.file === item.file) !== index);
35
+ if (repeated) throw new SetupError(`${repeated.file} is named twice; the widget keeps one file of each name.`);
36
+ return list;
37
+ };
38
+ return {
39
+ fonts: once(fonts.map(given => file(given, FONT_TYPES, 'a font'))),
40
+ assets: once(assets.map(given => {
41
+ const image = file(given, IMAGE_TYPES, 'an image');
42
+ const [, name, scale] = /^(.*?)(?:@([23])x)?$/.exec(basename(image.file, extname(image.file)));
43
+ if (!NAME.test(name)) throw new SetupError(`${given}: the asset name ${JSON.stringify(name)} must be 1 to 64 ASCII letters, digits, '.', '_' or '-'.`);
44
+ if (scale && VECTOR_TYPES.has(image.kind)) throw new SetupError(`${given}: a PDF or SVG image has one scale; drop the @${scale}x.`);
45
+ return { ...image, name, scale: scale && `${scale}x` };
46
+ })),
47
+ };
48
+ }
49
+
50
+ /** Copies `source` to `target`: created when absent, updated when its bytes differ, unchanged otherwise. */
51
+ function copyStep(show, source, target, detail) {
52
+ if (!existsSync(target)) return step('created', show(target), detail, copyEffect(source, target));
53
+ if (readFileSync(source).equals(readFileSync(target))) return step('unchanged', show(target));
54
+ return step('updated', show(target), detail, copyEffect(source, target));
55
+ }
56
+
57
+ const copyEffect = (source, target) => () => {
58
+ mkdirSync(dirname(target), { recursive: true });
59
+ copyFileSync(source, target);
60
+ };
61
+
62
+ /** The steps that copy the fonts into the widget's Fonts folder. */
63
+ export function fontSteps({ files, show }, widget) {
64
+ return files.fonts.map(({ source, file }) => {
65
+ const names = fontNames(readFileSync(source));
66
+ const detail = names ? `fontFamily: ${[...new Set([names.postScript, names.family].filter(Boolean))].map(name => JSON.stringify(name)).join(' or ')}` : '';
67
+ return copyStep(show, source, join(widget, FONTS, file), detail);
68
+ });
69
+ }
70
+
71
+ /** The font files the widget bundles after this run: those in its Fonts folder and those being copied there. */
72
+ export function bundledFonts({ files }, widget) {
73
+ const folder = join(widget, FONTS);
74
+ const present = existsSync(folder) ? readdirSync(folder).filter(name => FONT_TYPES.has(extname(name).toLowerCase())) : [];
75
+ return [...new Set([...present, ...files.fonts.map(({ file }) => file)])].sort();
76
+ }
77
+
78
+ /** The steps that put the images into the widget's asset catalog, one image set per asset name. */
79
+ export function assetSteps({ files, show }, widget) {
80
+ if (files.assets.length === 0) return [];
81
+ const catalog = join(widget, CATALOG);
82
+ const root = join(catalog, 'Contents.json');
83
+ const steps = existsSync(root) ? [] : [step('created', show(root), '', writeFile(root, catalogJson(CATALOG_INFO)))];
84
+ const sets = Map.groupBy(files.assets, ({ name }) => name);
85
+ for (const [name, images] of sets) {
86
+ const folder = join(catalog, `${name}.imageset`);
87
+ steps.push(...images.map(({ source, file }) => copyStep(show, source, join(folder, file), `the asset "${name}"`)));
88
+ steps.push(contentsStep(show, join(folder, 'Contents.json'), images));
89
+ }
90
+ return steps;
91
+ }
92
+
93
+ /** An image set's Contents.json with an entry for each image; entries already there stay as they are. */
94
+ function contentsStep(show, path, images) {
95
+ const text = readText(path);
96
+ const current = text === undefined ? { images: [], ...CATALOG_INFO } : parseJson(text);
97
+ if (!Array.isArray(current?.images)) return step('todo', show(path), `not an image set's Contents.json; add ${images.map(({ file }) => file).join(', ')} to it in Xcode`);
98
+ const missing = images.filter(({ file }) => !current.images.some(entry => entry?.filename === file));
99
+ if (missing.length === 0) return step('unchanged', show(path));
100
+ const next = { ...current, images: [...current.images, ...missing.map(entry)] };
101
+ return step(text === undefined ? 'created' : 'updated', show(path), '', writeFile(path, catalogJson(next)));
102
+ }
103
+
104
+ /** The entry of an image: a bitmap at its scale or for any scale, a PDF or SVG kept as vector data. */
105
+ function entry({ file, kind, scale }) {
106
+ const vector = VECTOR_TYPES.has(kind) ? { properties: { 'preserves-vector-representation': true } } : {};
107
+ return { filename: file, idiom: 'universal', ...vector, ...(scale && { scale }) };
108
+ }
109
+
110
+ /** JSON as Xcode writes an asset catalog: two spaces, and a space before each colon. */
111
+ const catalogJson = value => `${JSON.stringify(value, null, 2).replace(/^(\s*"(?:[^"\\]|\\.)*"): /gm, '$1 : ')}\n`;
112
+
113
+ /**
114
+ * The family and PostScript names in the name table of a TrueType or OpenType font, for the report: they are
115
+ * what a style's `fontFamily` takes. Undefined for a collection or a file it cannot read.
116
+ */
117
+ export function fontNames(bytes) {
118
+ try {
119
+ if (!['\0\u0001\0\0', 'OTTO', 'true'].includes(bytes.toString('latin1', 0, 4))) return undefined;
120
+ for (let index = 0; index < bytes.readUInt16BE(4); index += 1) {
121
+ const record = 12 + index * 16;
122
+ if (bytes.toString('latin1', record, record + 4) !== 'name') continue;
123
+ const offset = bytes.readUInt32BE(record + 8);
124
+ return names(bytes.subarray(offset, offset + bytes.readUInt32BE(record + 12)));
125
+ }
126
+ } catch (error) {
127
+ if (!(error instanceof RangeError)) throw error;
128
+ }
129
+ return undefined;
130
+ }
131
+
132
+ /** Name IDs 1 (family), 16 (typographic family) and 6 (PostScript), Windows Unicode before Macintosh Roman. */
133
+ function names(table) {
134
+ const strings = table.readUInt16BE(4);
135
+ const found = {};
136
+ for (let index = 0; index < table.readUInt16BE(2); index += 1) {
137
+ const record = 6 + index * 12;
138
+ const [platform, , , id, length, offset] = [0, 2, 4, 6, 8, 10].map(at => table.readUInt16BE(record + at));
139
+ if (![1, 6, 16].includes(id) || (platform !== 3 && platform !== 1) || found[id]?.platform === 3) continue;
140
+ const raw = table.subarray(strings + offset, strings + offset + length);
141
+ if (raw.length !== length) throw new RangeError('name record outside the table');
142
+ const text = platform === 3 ? Buffer.from(raw).swap16().toString('utf16le') : raw.toString('latin1');
143
+ found[id] = { platform, text };
144
+ }
145
+ const family = (found[16] ?? found[1])?.text;
146
+ const postScript = found[6]?.text;
147
+ return family || postScript ? { family, postScript } : undefined;
148
+ }