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/xcodegen.mjs CHANGED
@@ -4,6 +4,17 @@ import { createHash } from 'node:crypto';
4
4
 
5
5
  export const SPEC_FILE = 'live-activity.yml';
6
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 activitykit and the widget. */
10
+ export const APP_GROUP_KEY = 'ActivityKitAppGroup';
11
+ /** The key of 0.2 and 0.3, which a spec they wrote may hold. */
12
+ const OLD_APP_GROUP_KEY = 'TauriLiveActivityAppGroup';
13
+ /**
14
+ * The files of the widget folder that the app target compiles too. The custom views file is Swift, so the app target
15
+ * compiles Swift, which Xcode needs to take the App Intents metadata of the linked ActivityKitIntent product.
16
+ */
17
+ export const APP_SOURCES = ['LiveActivityCustomViews.swift'];
7
18
 
8
19
  const DIGEST_LINE = /^# setup-digest: ([0-9a-f]{16})\n/m;
9
20
 
@@ -37,24 +48,45 @@ function children(body) {
37
48
  return result;
38
49
  }
39
50
 
51
+ /** The `path` under the `entitlements` key of a target's lines. */
52
+ function entitlementsPath(lines) {
53
+ const at = lines.findIndex(line => /^\s+entitlements:\s*$/.test(line));
54
+ if (at === -1) return undefined;
55
+ const indent = /^\s*/.exec(lines[at])[0].length;
56
+ for (const line of lines.slice(at + 1)) {
57
+ if (isContent(line) && /^\s*/.exec(line)[0].length <= indent) break;
58
+ const path = /^\s+path:\s*(.+?)\s*$/.exec(line)?.[1];
59
+ if (path) return unquote(path);
60
+ }
61
+ return undefined;
62
+ }
63
+
40
64
  /**
41
- * The project name, Tauri's app target (`<name>_iOS`) when it exists, the setting groups, the first
42
- * bundle identifier and a target that already is a widget extension.
65
+ * The project name, Tauri's app target (`<name>_iOS`) when it exists, the path of its entitlements, the
66
+ * setting groups, the first bundle identifier and a target that already is a widget extension.
43
67
  */
44
68
  export function readProject(text) {
45
69
  const lines = text.split('\n');
46
70
  const name = unquote(/^name:\s*(.+?)\s*$/m.exec(text)?.[1]);
47
71
  const targets = children(topLevel(lines, 'targets')?.body ?? []);
48
72
  const isWidget = target => target.name === WIDGET || target.lines.some(line => line.includes('com.apple.widgetkit-extension'));
73
+ const app = targets.find(target => name && target.name === `${name}_iOS`);
49
74
  return {
50
75
  name,
51
- appTarget: targets.find(target => name && target.name === `${name}_iOS`)?.name,
76
+ appTarget: app?.name,
77
+ entitlements: app && entitlementsPath(app.lines),
52
78
  settingGroups: children(topLevel(lines, 'settingGroups')?.body ?? []).map(group => group.name),
53
79
  bundleId: unquote(/^\s*PRODUCT_BUNDLE_IDENTIFIER:\s*(\S+)\s*$/m.exec(text)?.[1]),
54
80
  widget: targets.find(isWidget)?.name,
55
81
  };
56
82
  }
57
83
 
84
+ /** The App Group of a spec that setup wrote, this version or 0.2 and 0.3, so that a later run keeps it. */
85
+ export function appGroupOf(spec = '') {
86
+ const value = new RegExp(`^\\s+(?:${APP_GROUP_KEY}|${OLD_APP_GROUP_KEY}): ("[^"\\n]*")$`, 'm').exec(spec)?.[1];
87
+ return value && JSON.parse(value);
88
+ }
89
+
58
90
  /**
59
91
  * Adds `file` to the spec's `include` list. Status: `added` (with the new `text`), `present`, or
60
92
  * `unsupported` when the list has a form this does not edit.
@@ -86,41 +118,63 @@ export function writtenBySetup(text) {
86
118
 
87
119
  const quoted = value => JSON.stringify(String(value));
88
120
 
89
- /** The included spec: the widget extension target, and the button intent and the extension in the app target. */
90
- export function widgetSpec({ pluginVersion, packagePath, appTarget, bundleId, appVersion, buildVersion, teamGroup }) {
121
+ /**
122
+ * The included spec: activitykit's Swift package, the widget extension target, and in the app target the extension,
123
+ * the button intent and the custom views. `fonts` go to the extension's UIAppFonts. An `appGroup` goes to the
124
+ * entitlements of both targets, the app's at `appEntitlements`, and to the extension's Info.plist, where activitykit
125
+ * and the widget read it. XcodeGen merges the app target's part into the target of project.yml.
126
+ */
127
+ export function widgetSpec({
128
+ pluginVersion, packagePath, appTarget, bundleId, appVersion, buildVersion, teamGroup, fonts = [], appGroup, appEntitlements,
129
+ }) {
91
130
  const versions = appVersion === undefined ? [] : [
92
131
  ` CFBundleShortVersionString: ${quoted(appVersion)}`,
93
132
  ` CFBundleVersion: ${quoted(buildVersion ?? appVersion)}`,
94
133
  ];
134
+ const fontList = fonts.length === 0 ? [] : [' UIAppFonts:', ...fonts.map(font => ` - ${quoted(font)}`)];
135
+ const group = appGroup === undefined ? [] : [` ${APP_GROUP_KEY}: ${quoted(appGroup)}`];
136
+ const entitlements = path => (appGroup === undefined ? [] : [
137
+ ' entitlements:',
138
+ ` path: ${path}`,
139
+ ' properties:',
140
+ ` com.apple.security.application-groups: [${quoted(appGroup)}]`,
141
+ ]);
142
+ const product = name => [' - package: ActivityKit', ` product: ${name}`];
95
143
  const body = [
96
144
  'packages:',
97
- ' LiveActivity:',
145
+ ' ActivityKit:',
98
146
  ` path: ${quoted(packagePath)}`,
99
147
  'targets:',
100
148
  ` ${quoted(appTarget)}:`,
101
- ` sources: [${WIDGET}/LiveActivityActionIntent.swift]`,
102
- ` dependencies: [{ target: ${WIDGET} }]`,
149
+ ` sources: [${APP_SOURCES.map(file => `${WIDGET}/${file}`).join(', ')}]`,
150
+ ' dependencies:',
151
+ ` - target: ${WIDGET}`,
152
+ // The system runs a button's intent in the app. The bridge itself is in the Rust library already.
153
+ ...product('ActivityKitIntent'),
154
+ ...product('ActivityKitViews'),
155
+ ...entitlements(quoted(appEntitlements)),
103
156
  ' settings:',
104
157
  ' base:',
105
158
  ' SWIFT_VERSION: "5.0"',
106
159
  ` ${WIDGET}:`,
107
160
  ' type: app-extension',
108
161
  ' platform: iOS',
109
- ' deploymentTarget: "16.1"',
162
+ ' deploymentTarget: "16.2"',
110
163
  ` sources: [${WIDGET}]`,
111
164
  ' dependencies:',
112
- ' - package: LiveActivity',
113
- ' product: LiveActivityShared',
114
- ' - package: LiveActivity',
115
- ' product: LiveActivityUI',
165
+ ...product('ActivityKitWidget'),
166
+ ...product('ActivityKitViews'),
116
167
  ' info:',
117
168
  ` path: ${WIDGET}/Info.plist`,
118
169
  ' properties:',
119
170
  ...versions,
120
171
  ' NSExtension:',
121
172
  ' NSExtensionPointIdentifier: com.apple.widgetkit-extension',
122
- ' # startLayout answers CONFIGURATION_REQUIRED without an extension that declares this.',
123
- ' TauriLiveActivityLayout: 2',
173
+ ' # A start answers CONFIGURATION_REQUIRED without an extension that declares this.',
174
+ ' ActivityKitLayout: 2',
175
+ ...fontList,
176
+ ...group,
177
+ ...entitlements(WIDGET_ENTITLEMENTS),
124
178
  ' settings:',
125
179
  ...(teamGroup ? [' groups: [app]'] : []),
126
180
  ' base:',
@@ -133,7 +187,7 @@ export function widgetSpec({ pluginVersion, packagePath, appTarget, bundleId, ap
133
187
  ].join('\n');
134
188
  return [
135
189
  `# Written by \`npx tauri-plugin-live-activity setup\` for tauri-plugin-live-activity ${pluginVersion}.`,
136
- '# project.yml includes it. Setup writes it again for a new plugin version or app version, unless',
190
+ '# project.yml includes it. Setup writes it again for a new plugin or activitykit version or app version, unless',
137
191
  '# the lines below were changed by hand.',
138
192
  `# setup-digest: ${digest(body)}`,
139
193
  body,
@@ -1,5 +1,5 @@
1
1
  import { type UnlistenFn } from '@tauri-apps/api/event';
2
- import type { ActionEvent, ActivityRecord, Capabilities, EndInput, LayoutActivityRecord, LayoutStartInput, LayoutUpdateInput, PermissionKind, Permissions, StartInput, UpdateInput } from './types.js';
2
+ import type { ActionEvent, ActivityRecord, Capabilities, EndInput, LayoutActivityRecord, LayoutEndInput, LayoutStartInput, LayoutUpdateInput, PermissionKind, Permissions, StartInput, UpdateInput } from './types.js';
3
3
  export type * from './types.js';
4
4
  /** Builders for the nodes of a layout tree. */
5
5
  export * as layout from './layout.js';
@@ -21,12 +21,24 @@ export declare function list(): Promise<readonly ActivityRecord[]>;
21
21
  export declare function startLayout(input: LayoutStartInput): Promise<LayoutActivityRecord>;
22
22
  /** Replace every value with a newer revision; the layout stays as started. */
23
23
  export declare function updateLayout(input: LayoutUpdateInput): Promise<LayoutActivityRecord>;
24
- /** End this layout generation. A late update cannot revive it. */
25
- export declare function endLayout(input: EndInput): Promise<LayoutActivityRecord>;
24
+ /** End this layout generation, with final content when `snapshot` is given. A late update cannot revive it. */
25
+ export declare function endLayout(input: LayoutEndInput): 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), where activitykit writes it to
33
+ * `activitykit/images`; on Android the first such image
34
+ * becomes the notification's large icon.
35
+ */
36
+ export declare function writeImage(name: string, png: Uint8Array | ArrayBuffer): Promise<void>;
28
37
  /**
29
38
  * Receive button taps while this webview is alive; resolves to the function that stops listening.
30
- * Listening uses Tauri's event permissions (`core:event:default`).
39
+ * Listening uses Tauri's event permissions (`core:event:default`). The tap reaches the page after the Rust
40
+ * `on_action` handlers have run; the tap's intent does not wait for this handler, which runs in the webview whenever it
41
+ * gets the event, and not at all while the webview is suspended or was never created. Act on taps in Rust when they
42
+ * must not be lost.
31
43
  */
32
44
  export declare function onAction(handler: (event: ActionEvent) => void): Promise<UnlistenFn>;
package/dist-js/index.js CHANGED
@@ -38,7 +38,7 @@ export function startLayout(input) {
38
38
  export function updateLayout(input) {
39
39
  return invoke('plugin:live-activity|update_layout', { input });
40
40
  }
41
- /** End this layout generation. A late update cannot revive it. */
41
+ /** End this layout generation, with final content when `snapshot` is given. A late update cannot revive it. */
42
42
  export function endLayout(input) {
43
43
  return invoke('plugin:live-activity|end_layout', { input });
44
44
  }
@@ -46,9 +46,24 @@ 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), where activitykit writes it to
54
+ * `activitykit/images`; on Android the first such image
55
+ * becomes the notification's large icon.
56
+ */
57
+ export function writeImage(name, png) {
58
+ const bytes = png instanceof Uint8Array ? png : new Uint8Array(png);
59
+ return invoke('plugin:live-activity|write_image', { input: { name, png: Array.from(bytes) } });
60
+ }
49
61
  /**
50
62
  * Receive button taps while this webview is alive; resolves to the function that stops listening.
51
- * Listening uses Tauri's event permissions (`core:event:default`).
63
+ * Listening uses Tauri's event permissions (`core:event:default`). The tap reaches the page after the Rust
64
+ * `on_action` handlers have run; the tap's intent does not wait for this handler, which runs in the webview whenever it
65
+ * gets the event, and not at all while the webview is suspended or was never created. Act on taps in Rust when they
66
+ * must not be lost.
52
67
  */
53
68
  export function onAction(handler) {
54
69
  return listen('live-activity://action', event => handler(event.payload));
@@ -0,0 +1,59 @@
1
+ import type { LayoutButtonNode, LayoutCustomNode, LayoutDividerNode, LayoutGaugeNode, LayoutHStackNode, LayoutImageNode, LayoutNode, LayoutPathNode, LayoutProgressNode, LayoutSpacerNode, LayoutSymbolNode, LayoutTextNode, LayoutTimerTextNode, LayoutVStackNode, LayoutZStackNode } from '../types.js';
2
+ export { bind } from '../layout.js';
3
+ /** What a stack takes as children: nodes, arrays of them, and booleans, `null` or `undefined`, which are left out. */
4
+ export type LayoutChild = LayoutNode | readonly LayoutChild[] | boolean | null | undefined;
5
+ /** What `Text` takes as children: strings and numbers, joined, and booleans, `null` or `undefined`, left out. */
6
+ export type TextChild = string | number | readonly TextChild[] | boolean | null | undefined;
7
+ /** The members of node `N` but its type and the members `Taken` that a component takes another way. */
8
+ type Props<N extends LayoutNode, Taken extends PropertyKey = never> = N extends unknown ? Omit<N, 'type' | Taken> : never;
9
+ type StackProps<N extends LayoutNode> = Props<N, 'children'> & {
10
+ readonly children: LayoutChild;
11
+ };
12
+ export type VStackProps = StackProps<LayoutVStackNode>;
13
+ export type HStackProps = StackProps<LayoutHStackNode>;
14
+ export type ZStackProps = StackProps<LayoutZStackNode>;
15
+ export type TextProps = Props<LayoutDividerNode> & ({
16
+ readonly children: TextChild;
17
+ readonly bind?: never;
18
+ } | {
19
+ readonly bind: string;
20
+ readonly children?: never;
21
+ });
22
+ export type ImageProps = Props<LayoutImageNode, 'source'> & ({
23
+ readonly asset: string;
24
+ readonly file?: never;
25
+ } | {
26
+ readonly file: string;
27
+ readonly asset?: never;
28
+ });
29
+ export type ButtonProps = Props<LayoutButtonNode, 'child'> & {
30
+ readonly children: LayoutNode;
31
+ };
32
+ /** Children from top to bottom. */
33
+ export declare function VStack({ children, ...options }: VStackProps): LayoutVStackNode;
34
+ /** Children side by side. */
35
+ export declare function HStack({ children, ...options }: HStackProps): LayoutHStackNode;
36
+ /** Children on top of each other, the first at the back. */
37
+ export declare function ZStack({ children, ...options }: ZStackProps): LayoutZStackNode;
38
+ /** Flexible space inside a stack. */
39
+ export declare function Spacer(props: Props<LayoutSpacerNode>): LayoutSpacerNode;
40
+ /** A separator line. */
41
+ export declare function Divider(props: Props<LayoutDividerNode>): LayoutDividerNode;
42
+ /** Literal text from its children, or with `bind` the value of that key. */
43
+ export declare function Text({ children, bind, ...options }: TextProps): LayoutTextNode;
44
+ /** An SF Symbol. */
45
+ export declare function SFSymbol({ name, ...options }: Props<LayoutSymbolNode>): LayoutSymbolNode;
46
+ /** An image of the widget extension's asset catalog (`asset`), or a PNG that the app wrote with `writeImage` (`file`). */
47
+ export declare function Image({ asset, file, ...options }: ImageProps): LayoutImageNode;
48
+ /** A shape from SVG path data `d`, drawn in a `box` of `[width, height]`. */
49
+ export declare function Path({ d, box, ...options }: Props<LayoutPathNode>): LayoutPathNode;
50
+ /** A progress bar or ring for the number value of `bind`. */
51
+ export declare function Progress({ bind, ...options }: Props<LayoutProgressNode>): LayoutProgressNode;
52
+ /** A gauge for the number value of `bind`. */
53
+ export declare function Gauge({ bind, ...options }: Props<LayoutGaugeNode>): LayoutGaugeNode;
54
+ /** A timer the system draws between the epoch-millisecond values of the `start` and `end` keys. */
55
+ export declare function TimerText({ start, end, ...options }: Props<LayoutTimerTextNode>): LayoutTimerTextNode;
56
+ /** A button around its one child; a tap reports `actionId` to `onAction`. */
57
+ export declare function Button({ actionId, children, ...options }: ButtonProps): LayoutButtonNode;
58
+ /** A SwiftUI view that the app registers under `name`; `props` are its inputs. */
59
+ export declare function Custom({ name, ...options }: Props<LayoutCustomNode>): LayoutCustomNode;
@@ -0,0 +1,101 @@
1
+ // Layout components for TSX. Each returns the plain node object of its `layout` builder; nothing here
2
+ // imports Tauri or React, so a server can build the same layout.
3
+ import { bound, button, custom, divider, gauge, hstack, image, path, progress, spacer, symbol, text, timerText, vstack, zstack, } from '../layout.js';
4
+ export { bind } from '../layout.js';
5
+ /** Children from top to bottom. */
6
+ export function VStack({ children, ...options }) {
7
+ return vstack(nodes('VStack', children), options);
8
+ }
9
+ /** Children side by side. */
10
+ export function HStack({ children, ...options }) {
11
+ return hstack(nodes('HStack', children), options);
12
+ }
13
+ /** Children on top of each other, the first at the back. */
14
+ export function ZStack({ children, ...options }) {
15
+ return zstack(nodes('ZStack', children), options);
16
+ }
17
+ /** Flexible space inside a stack. */
18
+ export function Spacer(props) {
19
+ return spacer(props);
20
+ }
21
+ /** A separator line. */
22
+ export function Divider(props) {
23
+ return divider(props);
24
+ }
25
+ /** Literal text from its children, or with `bind` the value of that key. */
26
+ export function Text({ children, bind, ...options }) {
27
+ if (bind !== undefined) {
28
+ if (children !== undefined)
29
+ throw new TypeError('Text: takes children or bind, not both');
30
+ return bound(bind, options);
31
+ }
32
+ if (children === undefined)
33
+ throw new TypeError('Text: needs children or bind');
34
+ return text(words(children), options);
35
+ }
36
+ /** An SF Symbol. */
37
+ export function SFSymbol({ name, ...options }) {
38
+ return symbol(name, options);
39
+ }
40
+ /** An image of the widget extension's asset catalog (`asset`), or a PNG that the app wrote with `writeImage` (`file`). */
41
+ export function Image({ asset, file, ...options }) {
42
+ if ((asset === undefined) === (file === undefined))
43
+ throw new TypeError('Image: takes either asset or file');
44
+ return image(asset ?? { file: file }, options);
45
+ }
46
+ /** A shape from SVG path data `d`, drawn in a `box` of `[width, height]`. */
47
+ export function Path({ d, box, ...options }) {
48
+ return path(d, box, options);
49
+ }
50
+ /** A progress bar or ring for the number value of `bind`. */
51
+ export function Progress({ bind, ...options }) {
52
+ return progress(bind, options);
53
+ }
54
+ /** A gauge for the number value of `bind`. */
55
+ export function Gauge({ bind, ...options }) {
56
+ return gauge(bind, options);
57
+ }
58
+ /** A timer the system draws between the epoch-millisecond values of the `start` and `end` keys. */
59
+ export function TimerText({ start, end, ...options }) {
60
+ return timerText(start, end, options);
61
+ }
62
+ /** A button around its one child; a tap reports `actionId` to `onAction`. */
63
+ export function Button({ actionId, children, ...options }) {
64
+ const child = Array.isArray(children) && children.length === 1 ? children[0] : children;
65
+ if (!isNode(child))
66
+ throw new TypeError('Button: needs exactly one node as its child');
67
+ return button(actionId, child, options);
68
+ }
69
+ /** A SwiftUI view that the app registers under `name`; `props` are its inputs. */
70
+ export function Custom({ name, ...options }) {
71
+ return custom(name, options);
72
+ }
73
+ function isNode(value) {
74
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
75
+ && typeof value.type === 'string';
76
+ }
77
+ function nodes(component, children) {
78
+ const found = [];
79
+ const visit = (child) => {
80
+ if (typeof child === 'boolean' || child === null || child === undefined)
81
+ return;
82
+ if (Array.isArray(child))
83
+ return child.forEach(visit);
84
+ if (!isNode(child))
85
+ throw new TypeError(`${component}: a child must be a layout node; put text in <Text>`);
86
+ found.push(child);
87
+ };
88
+ visit(children);
89
+ if (found.length === 0)
90
+ throw new TypeError(`${component}: needs at least one child`);
91
+ return found;
92
+ }
93
+ function words(children) {
94
+ if (typeof children === 'boolean' || children === null || children === undefined)
95
+ return '';
96
+ if (Array.isArray(children))
97
+ return children.map(words).join('');
98
+ if (typeof children === 'string' || typeof children === 'number')
99
+ return String(children);
100
+ throw new TypeError('Text: a child must be a string or a number');
101
+ }
@@ -0,0 +1,4 @@
1
+ import type { LayoutNode } from '../types.js';
2
+ export type { JSX } from './jsx-runtime.js';
3
+ /** Calls the component with its props; the key and the source location are dropped. */
4
+ export declare function jsxDEV(type: unknown, props: unknown, _key?: unknown, _isStatic?: boolean, _source?: unknown, _self?: unknown): LayoutNode;
@@ -0,0 +1,6 @@
1
+ // The development JSX runtime (`"jsx": "react-jsxdev"`): the same elements as the production runtime.
2
+ import { jsx } from './jsx-runtime.js';
3
+ /** Calls the component with its props; the key and the source location are dropped. */
4
+ export function jsxDEV(type, props, _key, _isStatic, _source, _self) {
5
+ return jsx(type, props);
6
+ }
@@ -0,0 +1,16 @@
1
+ import type { LayoutNode } from '../types.js';
2
+ type Component = (props: never) => LayoutNode;
3
+ export declare namespace JSX {
4
+ type Element = LayoutNode;
5
+ type ElementType = Component;
6
+ interface IntrinsicElements {
7
+ }
8
+ interface ElementChildrenAttribute {
9
+ children: unknown;
10
+ }
11
+ }
12
+ /** Calls the component with its props. The key has no place in a layout node. */
13
+ export declare function jsx(type: unknown, props: unknown, _key?: unknown): LayoutNode;
14
+ /** The same for an element with several static children. */
15
+ export declare const jsxs: typeof jsx;
16
+ export {};
@@ -0,0 +1,9 @@
1
+ /** Calls the component with its props. The key has no place in a layout node. */
2
+ export function jsx(type, props, _key) {
3
+ if (typeof type !== 'function') {
4
+ throw new TypeError(`a layout has no element <${String(type)}>: use the components of tauri-plugin-live-activity/jsx`);
5
+ }
6
+ return type(props);
7
+ }
8
+ /** The same for an element with several static children. */
9
+ export const jsxs = jsx;
@@ -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
+ }
@@ -0,0 +1,12 @@
1
+ import type { ActionEvent } from '../types.js';
2
+ import { type LiveActivityState, type SessionOptions } from './session.js';
3
+ export type { LiveActivityState, LiveActivityStatus } from './session.js';
4
+ export interface UseLiveActivityOptions extends SessionOptions {
5
+ /** Taps on the buttons of this activity; taps of other activities are not passed on. */
6
+ readonly onAction?: (event: ActionEvent) => void;
7
+ }
8
+ /**
9
+ * Starts a layout activity on mount, sends `values` as an update whenever they change, and ends the activity on
10
+ * unmount or when `enabled` turns false.
11
+ */
12
+ export declare function useLiveActivity(options: UseLiveActivityOptions): LiveActivityState;
@@ -0,0 +1,42 @@
1
+ // `useLiveActivity`: one layout activity kept in step with a React component. Only this entry imports React.
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import { endLayout, onAction, startLayout, updateLayout } from '../index.js';
4
+ import { IDLE, Session } from './session.js';
5
+ const commands = { startLayout, updateLayout, endLayout };
6
+ /**
7
+ * Starts a layout activity on mount, sends `values` as an update whenever they change, and ends the activity on
8
+ * unmount or when `enabled` turns false.
9
+ */
10
+ export function useLiveActivity(options) {
11
+ const [state, setState] = useState(IDLE);
12
+ const session = useRef(null);
13
+ if (session.current === null)
14
+ session.current = new Session(commands, setState);
15
+ const handler = useRef(options.onAction);
16
+ handler.current = options.onAction;
17
+ const listening = options.onAction !== undefined;
18
+ useEffect(() => {
19
+ session.current?.sync(options);
20
+ });
21
+ useEffect(() => {
22
+ const current = session.current;
23
+ // Strict Mode unmounts and mounts again at once: the end waits for a microtask, which the mount cancels.
24
+ current?.keep();
25
+ return () => current?.release();
26
+ }, []);
27
+ useEffect(() => {
28
+ if (!listening)
29
+ return undefined;
30
+ let open = true;
31
+ const stop = onAction((event) => {
32
+ const running = session.current?.activityId;
33
+ if (open && running !== undefined && event.activityId === running)
34
+ handler.current?.(event);
35
+ });
36
+ return () => {
37
+ open = false;
38
+ stop.then((unlisten) => unlisten(), () => { });
39
+ };
40
+ }, [listening]);
41
+ return state;
42
+ }
@@ -0,0 +1,68 @@
1
+ import type { EndPolicy, Fallback, Layout, LayoutActivityRecord, LayoutAndroidOptions, LayoutEndInput, LayoutStartInput, LayoutStyle, LayoutUpdateInput, LayoutValues, LiveActivityError } from '../types.js';
2
+ export interface SessionOptions {
3
+ /** The app's key of the activity; another key ends the running activity and starts one for it. */
4
+ readonly activityKey: string;
5
+ /** Read at start: a change while the activity runs is not sent, since the layout is fixed for a generation. */
6
+ readonly layout: Layout;
7
+ /** The values to show; a render with other values sends them as an update. */
8
+ readonly values: LayoutValues;
9
+ /** Read at start. */
10
+ readonly styles?: {
11
+ readonly [token: string]: LayoutStyle;
12
+ };
13
+ /** Read at start. Defaults to `notification`. */
14
+ readonly fallback?: Fallback;
15
+ /** Read at start. */
16
+ readonly android?: LayoutAndroidOptions;
17
+ /** False ends the activity, and true starts it again. Defaults to true. */
18
+ readonly enabled?: boolean;
19
+ /** How the activity ends on unmount or when `enabled` turns false. Defaults to `{ kind: 'immediate' }`. */
20
+ readonly endPolicy?: EndPolicy;
21
+ }
22
+ export type LiveActivityStatus = 'idle' | 'starting' | 'active' | 'ending' | 'ended' | 'failed';
23
+ export interface LiveActivityState {
24
+ readonly status: LiveActivityStatus;
25
+ /** The plugin's newest record of the activity. */
26
+ readonly record: LayoutActivityRecord | undefined;
27
+ /** The last refusal; an accepted request clears it. */
28
+ readonly error: LiveActivityError | undefined;
29
+ }
30
+ /** The commands the session sends. */
31
+ export interface SessionCommands {
32
+ readonly startLayout: (input: LayoutStartInput) => Promise<LayoutActivityRecord>;
33
+ readonly updateLayout: (input: LayoutUpdateInput) => Promise<LayoutActivityRecord>;
34
+ readonly endLayout: (input: LayoutEndInput) => Promise<LayoutActivityRecord>;
35
+ }
36
+ export declare const IDLE: LiveActivityState;
37
+ export declare class Session {
38
+ private readonly commands;
39
+ private readonly changed;
40
+ private state;
41
+ private wanted;
42
+ private endPolicy;
43
+ /** The running activity of this generation, and the values and revision it last took. */
44
+ private running;
45
+ /** Values that an update was refused with: not sent again until they change. */
46
+ private refused;
47
+ /** The key whose start was refused: not started again until `enabled` turns off or the key changes. */
48
+ private failedKey;
49
+ private busy;
50
+ private mounts;
51
+ constructor(commands: SessionCommands, changed: (state: LiveActivityState) => void);
52
+ /** The id of the running activity. */
53
+ get activityId(): string | undefined;
54
+ /** The options of a render. */
55
+ sync(options: SessionOptions): void;
56
+ /** The component is gone: the activity ends, now or once the request in flight has answered. */
57
+ dispose(): void;
58
+ /** The component mounted, also again in Strict Mode. */
59
+ keep(): void;
60
+ /** The component unmounted: it is disposed after a microtask, unless it mounts again before (Strict Mode). */
61
+ release(): void;
62
+ private pump;
63
+ private start;
64
+ private update;
65
+ private end;
66
+ private send;
67
+ private set;
68
+ }