tauri-plugin-live-activity 0.2.0 → 0.3.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.
@@ -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
+ }
@@ -0,0 +1,187 @@
1
+ // Reads the few things setup needs from Tauri's XcodeGen spec (gen/apple/project.yml) and writes the
2
+ // spec file it includes. This is not a YAML parser: it reads top-level blocks and their child keys.
3
+ import { createHash } from 'node:crypto';
4
+
5
+ export const SPEC_FILE = 'live-activity.yml';
6
+ export const WIDGET = 'LiveActivityWidget';
7
+ /** The extension's entitlements, next to its folder so that XcodeGen does not take them for a source. */
8
+ export const WIDGET_ENTITLEMENTS = `${WIDGET}.entitlements`;
9
+ /** The Info.plist key of the extension that names the App Group, for the plugin and the widget. */
10
+ export const APP_GROUP_KEY = 'TauriLiveActivityAppGroup';
11
+ /** The files of the widget folder that the app target compiles too. */
12
+ export const APP_SOURCES = ['LiveActivityActionIntent.swift', 'LiveActivityCustomRegistry.swift', 'LiveActivityCustomViews.swift'];
13
+
14
+ const DIGEST_LINE = /^# setup-digest: ([0-9a-f]{16})\n/m;
15
+
16
+ function unquote(value) {
17
+ const text = value?.trim();
18
+ return text && /^(["']).*\1$/.test(text) ? text.slice(1, -1) : text || undefined;
19
+ }
20
+
21
+ const isContent = line => line.trim() !== '' && !line.trim().startsWith('#');
22
+
23
+ /** The line of a top-level key and the lines under it, up to the next top-level key. */
24
+ function topLevel(lines, key) {
25
+ const start = lines.findIndex(line => line === `${key}:` || line.startsWith(`${key}:`) && /\s/.test(line[key.length + 1]));
26
+ if (start === -1) return undefined;
27
+ let end = start + 1;
28
+ while (end < lines.length && (!isContent(lines[end]) || /^\s/.test(lines[end]))) end += 1;
29
+ return { start, end, head: lines[start], body: lines.slice(start + 1, end) };
30
+ }
31
+
32
+ /** The keys one level under a block, each with its own lines. */
33
+ function children(body) {
34
+ const indent = body.find(isContent)?.match(/^\s*/)[0];
35
+ if (!indent) return [];
36
+ const result = [];
37
+ for (const line of body) {
38
+ const key = line.startsWith(indent) && /^[^\s#-]/.test(line.slice(indent.length))
39
+ ? /^\s*("[^"]*"|'[^']*'|[^:#]+?)\s*:(\s|$)/.exec(line)?.[1] : undefined;
40
+ if (key) result.push({ name: unquote(key), lines: [] });
41
+ else result.at(-1)?.lines.push(line);
42
+ }
43
+ return result;
44
+ }
45
+
46
+ /** The `path` under the `entitlements` key of a target's lines. */
47
+ function entitlementsPath(lines) {
48
+ const at = lines.findIndex(line => /^\s+entitlements:\s*$/.test(line));
49
+ if (at === -1) return undefined;
50
+ const indent = /^\s*/.exec(lines[at])[0].length;
51
+ for (const line of lines.slice(at + 1)) {
52
+ if (isContent(line) && /^\s*/.exec(line)[0].length <= indent) break;
53
+ const path = /^\s+path:\s*(.+?)\s*$/.exec(line)?.[1];
54
+ if (path) return unquote(path);
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * The project name, Tauri's app target (`<name>_iOS`) when it exists, the path of its entitlements, the
61
+ * setting groups, the first bundle identifier and a target that already is a widget extension.
62
+ */
63
+ export function readProject(text) {
64
+ const lines = text.split('\n');
65
+ const name = unquote(/^name:\s*(.+?)\s*$/m.exec(text)?.[1]);
66
+ const targets = children(topLevel(lines, 'targets')?.body ?? []);
67
+ const isWidget = target => target.name === WIDGET || target.lines.some(line => line.includes('com.apple.widgetkit-extension'));
68
+ const app = targets.find(target => name && target.name === `${name}_iOS`);
69
+ return {
70
+ name,
71
+ appTarget: app?.name,
72
+ entitlements: app && entitlementsPath(app.lines),
73
+ settingGroups: children(topLevel(lines, 'settingGroups')?.body ?? []).map(group => group.name),
74
+ bundleId: unquote(/^\s*PRODUCT_BUNDLE_IDENTIFIER:\s*(\S+)\s*$/m.exec(text)?.[1]),
75
+ widget: targets.find(isWidget)?.name,
76
+ };
77
+ }
78
+
79
+ /** The App Group of a spec that setup wrote, so that a later run keeps it. */
80
+ export function appGroupOf(spec = '') {
81
+ const value = new RegExp(`^\\s+${APP_GROUP_KEY}: ("[^"\\n]*")$`, 'm').exec(spec)?.[1];
82
+ return value && JSON.parse(value);
83
+ }
84
+
85
+ /**
86
+ * Adds `file` to the spec's `include` list. Status: `added` (with the new `text`), `present`, or
87
+ * `unsupported` when the list has a form this does not edit.
88
+ */
89
+ export function addInclude(text, file) {
90
+ const lines = text.split('\n');
91
+ const block = topLevel(lines, 'include');
92
+ if (!block) return { status: 'added', text: `${text.endsWith('\n') ? text : `${text}\n`}\ninclude:\n - ${file}\n` };
93
+ if ([block.head, ...block.body].some(line => line.includes(file))) return { status: 'present', text };
94
+ const inline = /^include:\s*\[(.*)\]\s*$/.exec(block.head);
95
+ if (inline) {
96
+ const items = inline[1].trim();
97
+ return { status: 'added', text: lines.with(block.start, `include: [${items ? `${items}, ` : ''}${file}]`).join('\n') };
98
+ }
99
+ const item = block.body.find(line => /^\s+-\s/.test(line));
100
+ if (!/^include:\s*$/.test(block.head) || !item) return { status: 'unsupported', text };
101
+ const last = block.start + 1 + block.body.findLastIndex(isContent);
102
+ const entry = `${item.match(/^\s*/)[0]}- ${file}`;
103
+ return { status: 'added', text: [...lines.slice(0, last + 1), entry, ...lines.slice(last + 1)].join('\n') };
104
+ }
105
+
106
+ const digest = text => createHash('sha256').update(text).digest('hex').slice(0, 16);
107
+
108
+ /** True when the spec is as setup wrote it: its digest line matches the rest of the file. */
109
+ export function writtenBySetup(text) {
110
+ const match = DIGEST_LINE.exec(text);
111
+ return Boolean(match) && digest(text.slice(match.index + match[0].length)) === match[1];
112
+ }
113
+
114
+ const quoted = value => JSON.stringify(String(value));
115
+
116
+ /**
117
+ * The included spec: the widget extension target, and the button intent, the custom views and the extension
118
+ * in the app target. `fonts` go to the extension's UIAppFonts. An `appGroup` goes to the entitlements of both
119
+ * targets, the app's at `appEntitlements`, and to the extension's Info.plist, where the plugin and the widget
120
+ * read it. XcodeGen merges the app target's part into the target of project.yml.
121
+ */
122
+ export function widgetSpec({
123
+ pluginVersion, packagePath, appTarget, bundleId, appVersion, buildVersion, teamGroup, fonts = [], appGroup, appEntitlements,
124
+ }) {
125
+ const versions = appVersion === undefined ? [] : [
126
+ ` CFBundleShortVersionString: ${quoted(appVersion)}`,
127
+ ` CFBundleVersion: ${quoted(buildVersion ?? appVersion)}`,
128
+ ];
129
+ const fontList = fonts.length === 0 ? [] : [' UIAppFonts:', ...fonts.map(font => ` - ${quoted(font)}`)];
130
+ const group = appGroup === undefined ? [] : [` ${APP_GROUP_KEY}: ${quoted(appGroup)}`];
131
+ const entitlements = path => (appGroup === undefined ? [] : [
132
+ ' entitlements:',
133
+ ` path: ${path}`,
134
+ ' properties:',
135
+ ` com.apple.security.application-groups: [${quoted(appGroup)}]`,
136
+ ]);
137
+ const body = [
138
+ 'packages:',
139
+ ' LiveActivity:',
140
+ ` path: ${quoted(packagePath)}`,
141
+ 'targets:',
142
+ ` ${quoted(appTarget)}:`,
143
+ ` sources: [${APP_SOURCES.map(file => `${WIDGET}/${file}`).join(', ')}]`,
144
+ ` dependencies: [{ target: ${WIDGET} }]`,
145
+ ...entitlements(quoted(appEntitlements)),
146
+ ' settings:',
147
+ ' base:',
148
+ ' SWIFT_VERSION: "5.0"',
149
+ ` ${WIDGET}:`,
150
+ ' type: app-extension',
151
+ ' platform: iOS',
152
+ ' deploymentTarget: "16.1"',
153
+ ` sources: [${WIDGET}]`,
154
+ ' dependencies:',
155
+ ' - package: LiveActivity',
156
+ ' product: LiveActivityShared',
157
+ ' - package: LiveActivity',
158
+ ' product: LiveActivityUI',
159
+ ' info:',
160
+ ` path: ${WIDGET}/Info.plist`,
161
+ ' properties:',
162
+ ...versions,
163
+ ' NSExtension:',
164
+ ' NSExtensionPointIdentifier: com.apple.widgetkit-extension',
165
+ ' # startLayout answers CONFIGURATION_REQUIRED without an extension that declares this.',
166
+ ' TauriLiveActivityLayout: 2',
167
+ ...fontList,
168
+ ...group,
169
+ ...entitlements(WIDGET_ENTITLEMENTS),
170
+ ' settings:',
171
+ ...(teamGroup ? [' groups: [app]'] : []),
172
+ ' base:',
173
+ ` PRODUCT_NAME: ${WIDGET}`,
174
+ ` PRODUCT_BUNDLE_IDENTIFIER: ${quoted(bundleId)}`,
175
+ ' SWIFT_VERSION: "5.0"',
176
+ ' APPLICATION_EXTENSION_API_ONLY: YES',
177
+ ' SKIP_INSTALL: YES',
178
+ '',
179
+ ].join('\n');
180
+ return [
181
+ `# Written by \`npx tauri-plugin-live-activity setup\` for tauri-plugin-live-activity ${pluginVersion}.`,
182
+ '# project.yml includes it. Setup writes it again for a new plugin version or app version, unless',
183
+ '# the lines below were changed by hand.',
184
+ `# setup-digest: ${digest(body)}`,
185
+ body,
186
+ ].join('\n');
187
+ }
@@ -25,6 +25,14 @@ export declare function updateLayout(input: LayoutUpdateInput): Promise<LayoutAc
25
25
  export declare function endLayout(input: EndInput): Promise<LayoutActivityRecord>;
26
26
  /** Reconcile plugin-owned layout records with the OS; `list` reports contract v1 activities. */
27
27
  export declare function listLayout(): Promise<readonly LayoutActivityRecord[]>;
28
+ /**
29
+ * Write a PNG that `image` nodes with the source `{ file: name }` show, replacing one of that name. The widget
30
+ * reads it each time it draws the activity, on start and on every update, so write the picture first and then
31
+ * update. At most 1 MiB and 1224 x 480 pixels (`PAYLOAD_TOO_LARGE` beyond). On iOS it needs the App Group
32
+ * that `setup --app-group` configures (`CONFIGURATION_REQUIRED` without one); on Android the first such image
33
+ * becomes the notification's large icon.
34
+ */
35
+ export declare function writeImage(name: string, png: Uint8Array | ArrayBuffer): Promise<void>;
28
36
  /**
29
37
  * Receive button taps while this webview is alive; resolves to the function that stops listening.
30
38
  * Listening uses Tauri's event permissions (`core:event:default`).
package/dist-js/index.js CHANGED
@@ -46,6 +46,17 @@ export function endLayout(input) {
46
46
  export function listLayout() {
47
47
  return invoke('plugin:live-activity|list_layout', {});
48
48
  }
49
+ /**
50
+ * Write a PNG that `image` nodes with the source `{ file: name }` show, replacing one of that name. The widget
51
+ * reads it each time it draws the activity, on start and on every update, so write the picture first and then
52
+ * update. At most 1 MiB and 1224 x 480 pixels (`PAYLOAD_TOO_LARGE` beyond). On iOS it needs the App Group
53
+ * that `setup --app-group` configures (`CONFIGURATION_REQUIRED` without one); on Android the first such image
54
+ * becomes the notification's large icon.
55
+ */
56
+ export function writeImage(name, png) {
57
+ const bytes = png instanceof Uint8Array ? png : new Uint8Array(png);
58
+ return invoke('plugin:live-activity|write_image', { input: { name, png: Array.from(bytes) } });
59
+ }
49
60
  /**
50
61
  * Receive button taps while this webview is alive; resolves to the function that stops listening.
51
62
  * Listening uses Tauri's event permissions (`core:event:default`).
@@ -1,4 +1,4 @@
1
- import type { LayoutButtonNode, LayoutDividerNode, LayoutGaugeNode, LayoutHStackNode, LayoutImageNode, LayoutNode, LayoutPathNode, LayoutProgressNode, LayoutSpacerNode, LayoutSymbolNode, LayoutTextNode, LayoutTimerTextNode, LayoutVStackNode, LayoutZStackNode } from './types.js';
1
+ import type { LayoutBound, LayoutButtonNode, LayoutCustomNode, LayoutDividerNode, LayoutGaugeNode, LayoutHStackNode, LayoutImageNode, LayoutImageSource, LayoutNode, LayoutPathNode, LayoutProgressNode, LayoutSpacerNode, LayoutSymbolNode, LayoutTextNode, LayoutTimerTextNode, LayoutVStackNode, LayoutZStackNode } from './types.js';
2
2
  /** The members of a node that its builder does not take as arguments. */
3
3
  type Options<N extends LayoutNode, Argument extends keyof N = never> = N extends unknown ? Omit<N, 'type' | Argument> : never;
4
4
  /** Children from top to bottom. */
@@ -17,8 +17,11 @@ export declare function text(value: string, options?: Options<LayoutTextNode, 'v
17
17
  export declare function bound(key: string, options?: Options<LayoutTextNode, 'value' | 'bind'>): LayoutTextNode;
18
18
  /** An SF Symbol. */
19
19
  export declare function symbol(name: string, options?: Options<LayoutSymbolNode, 'name'>): LayoutSymbolNode;
20
- /** An image of the widget extension's asset catalog. */
21
- export declare function image(asset: string, options?: Options<LayoutImageNode, 'source'>): LayoutImageNode;
20
+ /**
21
+ * An image of the widget extension's asset catalog, by its name, or a PNG that the app wrote with
22
+ * `writeImage`: `image({ file: 'badge.png' })`.
23
+ */
24
+ export declare function image(source: string | LayoutImageSource, options?: Options<LayoutImageNode, 'source'>): LayoutImageNode;
22
25
  /** A shape from SVG path data `d`, drawn in a `box` of `[width, height]`. */
23
26
  export declare function path(d: string, box: readonly [number, number], options?: Options<LayoutPathNode, 'd' | 'box'>): LayoutPathNode;
24
27
  /** A progress bar or ring for the number value of `key`. */
@@ -29,4 +32,12 @@ export declare function gauge(key: string, options?: Options<LayoutGaugeNode, 'b
29
32
  export declare function timerText(start: string, end: string, options?: Options<LayoutTimerTextNode, 'start' | 'end'>): LayoutTimerTextNode;
30
33
  /** A button around `child`; a tap reports `actionId` to `onAction`. */
31
34
  export declare function button(actionId: string, child: LayoutNode, options?: Options<LayoutButtonNode, 'actionId' | 'child'>): LayoutButtonNode;
35
+ /** A SwiftUI view that the app registers under `name` in LiveActivityCustomViews.swift; `props` are its inputs. */
36
+ export declare function custom(name: string, options?: Options<LayoutCustomNode, 'name'>): LayoutCustomNode;
37
+ /**
38
+ * A style member, `layout.background` or `layout.keyline` that reads the value of `key` on every render,
39
+ * so an update can change it: `{ color: bind('tone') }`. Only `color`, `background`, `tint`, `opacity`,
40
+ * `size`, `weight` and `cornerRadius` can be bound, and the props of a `custom` node.
41
+ */
42
+ export declare function bind(key: string): LayoutBound;
32
43
  export {};
package/dist-js/layout.js CHANGED
@@ -35,9 +35,12 @@ export function bound(key, options) {
35
35
  export function symbol(name, options) {
36
36
  return { type: 'symbol', name, ...given(options) };
37
37
  }
38
- /** An image of the widget extension's asset catalog. */
39
- export function image(asset, options) {
40
- return { type: 'image', source: { asset }, ...given(options) };
38
+ /**
39
+ * An image of the widget extension's asset catalog, by its name, or a PNG that the app wrote with
40
+ * `writeImage`: `image({ file: 'badge.png' })`.
41
+ */
42
+ export function image(source, options) {
43
+ return { type: 'image', source: typeof source === 'string' ? { asset: source } : { ...source }, ...given(options) };
41
44
  }
42
45
  /** A shape from SVG path data `d`, drawn in a `box` of `[width, height]`. */
43
46
  export function path(d, box, options) {
@@ -59,3 +62,15 @@ export function timerText(start, end, options) {
59
62
  export function button(actionId, child, options) {
60
63
  return { type: 'button', actionId, child, ...given(options) };
61
64
  }
65
+ /** A SwiftUI view that the app registers under `name` in LiveActivityCustomViews.swift; `props` are its inputs. */
66
+ export function custom(name, options) {
67
+ return { type: 'custom', name, ...given(options) };
68
+ }
69
+ /**
70
+ * A style member, `layout.background` or `layout.keyline` that reads the value of `key` on every render,
71
+ * so an update can change it: `{ color: bind('tone') }`. Only `color`, `background`, `tint`, `opacity`,
72
+ * `size`, `weight` and `cornerRadius` can be bound, and the props of a `custom` node.
73
+ */
74
+ export function bind(key) {
75
+ return { bind: key };
76
+ }
@@ -127,6 +127,17 @@ export type LayoutColor = ColorName | HexColor | {
127
127
  readonly light: HexColor;
128
128
  readonly dark: HexColor;
129
129
  };
130
+ /**
131
+ * A value key in place of a literal, as `layout.bind(key)` writes it. The member reads the value on
132
+ * every render, so an update can change it. The value must be what the member takes as a literal: a
133
+ * color name or a hex color (not a light and dark pair), a weight name, or a number in the member's range.
134
+ */
135
+ export interface LayoutBound {
136
+ readonly bind: string;
137
+ }
138
+ /** A literal, or a value key that an update can change. */
139
+ export type LayoutBindable<T> = T | LayoutBound;
140
+ type FontWeight = 'ultraLight' | 'thin' | 'light' | 'regular' | 'medium' | 'semibold' | 'bold' | 'heavy' | 'black';
130
141
  type Anchor = 'center' | 'leading' | 'trailing' | 'top' | 'bottom' | 'topLeading' | 'topTrailing' | 'bottomLeading' | 'bottomTrailing';
131
142
  /** At least one member. Sizes are points from 0 to 1024. */
132
143
  export interface LayoutFrame {
@@ -138,12 +149,15 @@ export interface LayoutFrame {
138
149
  readonly maxHeight?: number | 'infinity';
139
150
  readonly alignment?: Anchor;
140
151
  }
152
+ /**
153
+ * `weight`, `color`, `background`, `cornerRadius`, `opacity`, `tint` and `size` may be bound to a value
154
+ * with `layout.bind(key)`. The other members are fixed at start.
155
+ */
141
156
  interface StyleFields {
142
- readonly weight?: 'ultraLight' | 'thin' | 'light' | 'regular' | 'medium' | 'semibold' | 'bold' | 'heavy' | 'black';
143
- readonly design?: 'default' | 'rounded' | 'serif' | 'monospaced';
157
+ readonly weight?: LayoutBindable<FontWeight>;
144
158
  readonly monospacedDigit?: boolean;
145
159
  /** Foreground color. */
146
- readonly color?: LayoutColor;
160
+ readonly color?: LayoutBindable<LayoutColor>;
147
161
  /** Integer from 1 to 10. */
148
162
  readonly lineLimit?: number;
149
163
  /** From 0.1 to 1. */
@@ -153,22 +167,34 @@ interface StyleFields {
153
167
  /** Points from 0 to 64: one number for every edge, or `[top, leading, bottom, trailing]`. */
154
168
  readonly padding?: number | readonly [number, number, number, number];
155
169
  readonly frame?: LayoutFrame;
156
- readonly background?: LayoutColor;
170
+ readonly background?: LayoutBindable<LayoutColor>;
157
171
  /** Points from 0 to 64. */
158
- readonly cornerRadius?: number;
172
+ readonly cornerRadius?: LayoutBindable<number>;
159
173
  /** From 0 to 1. */
160
- readonly opacity?: number;
174
+ readonly opacity?: LayoutBindable<number>;
161
175
  /** Tint of buttons, progress views and gauges. */
162
- readonly tint?: LayoutColor;
176
+ readonly tint?: LayoutBindable<LayoutColor>;
163
177
  readonly buttonStyle?: 'automatic' | 'bordered' | 'borderedProminent' | 'plain';
164
178
  }
165
- /** At least one member. `font`, a system text style, and `size`, points from 6 to 96, exclude each other. */
179
+ /**
180
+ * At least one member. `font`, a system text style, and `size`, points from 6 to 96, exclude each other.
181
+ * `fontFamily`, the PostScript or family name of a font that the widget extension bundles (`setup --font`),
182
+ * and `design`, a design of the system font, exclude each other too.
183
+ */
166
184
  export type LayoutStyle = StyleFields & ({
167
185
  readonly font?: 'largeTitle' | 'title' | 'title2' | 'title3' | 'headline' | 'subheadline' | 'body' | 'callout' | 'footnote' | 'caption' | 'caption2';
168
186
  readonly size?: never;
169
187
  } | {
170
- readonly size?: number;
188
+ readonly size?: LayoutBindable<number>;
171
189
  readonly font?: never;
190
+ }) & ({
191
+ readonly design?: 'default' | 'rounded' | 'serif' | 'monospaced';
192
+ readonly fontFamily?: never;
193
+ }
194
+ /** 1 to 64 ASCII letters, digits, spaces, `.`, `_` and `-`, starting with a letter or digit. */
195
+ | {
196
+ readonly fontFamily?: string;
197
+ readonly design?: never;
172
198
  });
173
199
  /** Members every node may carry. A condition names a value key; `if` and `unless` exclude each other. */
174
200
  type NodeFields = {
@@ -229,12 +255,20 @@ export type LayoutSymbolNode = NodeFields & {
229
255
  /** Key of a number value: the symbol's variable value, from 0 to 1. */
230
256
  readonly variableBind?: string;
231
257
  };
258
+ /**
259
+ * `asset`: an image in the widget extension's asset catalog. `file`: a PNG that the app wrote with
260
+ * `writeImage(file, png)`. A name is 1 to 64 ASCII letters, digits, `.`, `_` and `-`, starting with a letter or digit.
261
+ */
262
+ export type LayoutImageSource = {
263
+ readonly asset: string;
264
+ readonly file?: never;
265
+ } | {
266
+ readonly file: string;
267
+ readonly asset?: never;
268
+ };
232
269
  export type LayoutImageNode = NodeFields & {
233
270
  readonly type: 'image';
234
- /** Name of an image in the widget extension's asset catalog. */
235
- readonly source: {
236
- readonly asset: string;
237
- };
271
+ readonly source: LayoutImageSource;
238
272
  readonly resizable?: boolean;
239
273
  readonly contentMode?: 'fit' | 'fill';
240
274
  };
@@ -279,7 +313,24 @@ export type LayoutButtonNode = NodeFields & {
279
313
  readonly actionId: string;
280
314
  readonly child: LayoutNode;
281
315
  };
282
- export type LayoutNode = LayoutVStackNode | LayoutHStackNode | LayoutZStackNode | LayoutSpacerNode | LayoutDividerNode | LayoutTextNode | LayoutSymbolNode | LayoutImageNode | LayoutPathNode | LayoutProgressNode | LayoutGaugeNode | LayoutTimerTextNode | LayoutButtonNode;
316
+ /**
317
+ * A SwiftUI view that the app registers under `name` in LiveActivityCustomViews.swift of its widget extension.
318
+ * A name without a view draws nothing and is reported in `degradedFeatures` as `layout.custom.<name>`; Android
319
+ * shows no custom view (`layout.custom`).
320
+ */
321
+ export type LayoutCustomNode = NodeFields & {
322
+ readonly type: 'custom';
323
+ /** 1 to 64 ASCII letters, digits, `.`, `_` and `-`, starting with a letter or digit. */
324
+ readonly name: string;
325
+ /**
326
+ * 1 to 16 inputs of the view under value-key names: text of at most 200 code points, a number, a boolean, or
327
+ * `layout.bind(key)` for a value that each update can change.
328
+ */
329
+ readonly props?: {
330
+ readonly [name: string]: LayoutBindable<LayoutValue>;
331
+ };
332
+ };
333
+ export type LayoutNode = LayoutVStackNode | LayoutHStackNode | LayoutZStackNode | LayoutSpacerNode | LayoutDividerNode | LayoutTextNode | LayoutSymbolNode | LayoutImageNode | LayoutPathNode | LayoutProgressNode | LayoutGaugeNode | LayoutTimerTextNode | LayoutButtonNode | LayoutCustomNode;
283
334
  /** At least one region, each of at most 12 nodes. */
284
335
  export interface LayoutIslandExpanded {
285
336
  readonly leading?: LayoutNode;
@@ -303,9 +354,9 @@ export interface Layout {
303
354
  readonly lockScreen: LayoutNode;
304
355
  readonly island?: LayoutIsland;
305
356
  /** Tint behind the lock screen presentation. */
306
- readonly background?: LayoutColor;
357
+ readonly background?: LayoutBindable<LayoutColor>;
307
358
  /** Tint of the Dynamic Island keyline. */
308
- readonly keyline?: LayoutColor;
359
+ readonly keyline?: LayoutBindable<LayoutColor>;
309
360
  }
310
361
  export interface LayoutAndroidOptions {
311
362
  /** Lock screen visibility of the notification. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tauri-plugin-live-activity",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Tauri 2 plugin for iOS Live Activities (ActivityKit and Dynamic Island) and Android Live Updates with ongoing notification fallback",
5
5
  "author": "1eedaegon",
6
6
  "type": "module",
@@ -19,7 +19,8 @@
19
19
  ".": { "types": "./dist-js/index.d.ts", "import": "./dist-js/index.js" },
20
20
  "./package.json": "./package.json"
21
21
  },
22
- "files": ["dist-js", "README.md", "README.ko.md", "LICENSE", "LICENSE-APACHE", "LICENSE-MIT"],
22
+ "bin": { "tauri-plugin-live-activity": "cli/bin.mjs" },
23
+ "files": ["dist-js", "cli", "README.md", "README.ko.md", "LICENSE", "LICENSE-APACHE", "LICENSE-MIT"],
23
24
  "publishConfig": { "access": "public", "tag": "next" },
24
25
  "engines": {
25
26
  "node": ">=22.12.0"
@@ -27,10 +28,11 @@
27
28
  "scripts": {
28
29
  "build": "tsc -p tsconfig.json",
29
30
  "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p examples/demo/tsconfig.json",
30
- "test": "npm run build && npm run test:contracts && npm run test:api && npm run test:demo",
31
+ "test": "npm run build && npm run test:contracts && npm run test:api && npm run test:demo && npm run test:setup",
31
32
  "test:contracts": "node --test --experimental-test-coverage \"--test-coverage-include=tools/validate-request.mjs\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/requests.test.mjs tests/layout-requests.test.mjs",
32
33
  "test:api": "node --test --experimental-test-coverage \"--test-coverage-include=dist-js/*.js\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/api.test.mjs",
33
34
  "test:demo": "node --experimental-strip-types --test --experimental-test-coverage \"--test-coverage-include=examples/demo/src/*.ts\" \"--test-coverage-exclude=examples/demo/tests/**\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 examples/demo/tests/self-test.test.mjs examples/demo/tests/ui-state.test.mjs examples/demo/tests/layouts.test.mjs examples/demo/tests/setup.test.mjs",
35
+ "test:setup": "node --test --experimental-test-coverage \"--test-coverage-include=cli/*.mjs\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/setup.test.mjs",
34
36
  "build:demo": "npm run build && node examples/demo/build.mjs",
35
37
  "prepack": "npm run build",
36
38
  "pack:check": "npm pack --dry-run"