Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: single line collapsed input (#3941)
Peter Chinmanb1c0117b4313
diff --git a/js/app/packages/app/component/mobile/SwipeDownDismissKeyboard.tsx b/js/app/packages/app/component/mobile/SwipeDownDismissKeyboard.tsxindex cdf089caf1..7542b0424c 100644--- a/js/app/packages/app/component/mobile/SwipeDownDismissKeyboard.tsx+++ b/js/app/packages/app/component/mobile/SwipeDownDismissKeyboard.tsx@@ -8,6 +8,19 @@ import { onCleanup, onMount } from 'solid-js';const SWIPE_DOWN_THRESHOLD = 5; // px of downward movement to register as a swipe downconst ZONE_HEIGHT = 20; // px above keyboard that activates blur+// The activation zone overlaps an input's action buttons when the input is+// docked to the keyboard, and taps commonly drift past the swipe threshold —+// treat gestures starting on interactive elements as taps, not dismissal+// swipes.+const INTERACTIVE_SELECTOR =+ 'button, [role="button"], a[href], input, textarea, select, [contenteditable="true"]';++function isInteractiveTarget(target: EventTarget | null): boolean {+ return (+ target instanceof Element && target.closest(INTERACTIVE_SELECTOR) !== null+ );+}+function hasTextSelection(active: Element | null): boolean {if (active instanceof HTMLInputElement ||@@ -30,16 +43,19 @@ export function SwipeDownDismissKeyboard() {if (!isPlatform('ios')) return;let startY = 0;+ let startedOnInteractive = false;function handleTouchStart(e: TouchEvent) {if (!virtualKeyboardVisible()) return;const touch = e.touches[0];if (!touch) return;startY = touch.clientY;+ startedOnInteractive = isInteractiveTarget(e.target);}function handleTouchMove(e: TouchEvent) {if (!virtualKeyboardVisible()) return;+ if (startedOnInteractive) return;const touch = e.touches[0];if (!touch) return;const keyboardTop = window.innerHeight - virtualKeyboardHeight();diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsxindex bf508ff295..c5634561e9 100644--- a/js/app/packages/channel/Channel/Channel.tsx+++ b/js/app/packages/channel/Channel/Channel.tsx@@ -563,6 +563,7 @@ export function Channel(props: ChannelProps) {><ChannelInputautofocus={props.autofocus}+ collapsibleinput={{mode: 'channel',id: `channel-input-${props.channelId}`,diff --git a/js/app/packages/channel/Input/ChannelInput.tsx b/js/app/packages/channel/Input/ChannelInput.tsxindex 43ce287d26..3f3f948fe3 100644--- a/js/app/packages/channel/Input/ChannelInput.tsx+++ b/js/app/packages/channel/Input/ChannelInput.tsx@@ -1,9 +1,11 @@import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { DragInsertIndicator } from '@core/component/LexicalMarkdown/component/misc/DragInsertIndicator';import {createDragInsertStore,INSERT_DOCUMENT_MENTION_COMMAND,} from '@core/component/LexicalMarkdown/plugins';+import { singleLineMarkdownTheme } from '@core/component/LexicalMarkdown/theme';import {clearDragInsertPreview,insertDocumentMentionAtDragCoordinates,@@ -20,7 +22,7 @@ import {} from '@core/util/upload';import type { EntityData } from '@entity';import { isIOS } from '@solid-primitives/platform';-import { Surface } from '@ui';+import { CollapsedInput, cn, Surface } from '@ui';import { $getRoot } from 'lexical';import {type Accessor,@@ -31,8 +33,10 @@ import {Switch,} from 'solid-js';import { MACRO_AI_BOT_ID, macroAiMentionUser } from '../macroAi';+import { CHANNEL_FILE_PICKER_ACCEPT } from './accepted-file-types';import { createInputAttachmentTracker } from './attachment-tracker';import { createConfiguredChannelMarkdownEditor } from './configured-markdown-editor';+import { createCollapsedInputState } from './create-collapsed-input-state';import { createInputState } from './create-input-state';import { createTypingTracker } from './create-typing-tracker';import { FormatButtons } from './FormatButtons';@@ -50,6 +54,7 @@ import { isReplyInput } from './types';import { uploadInputAttachments } from './upload-attachments';import { entityToDocumentMentionInfo } from './utils/entity-mention';import { applyInlineFormat, applyNodeFormat } from './utils/formatting';+import { hasSendableInputContent } from './utils/sendable-content';export type ChannelInputProps = InputCallbacks & {input: InputData;@@ -61,6 +66,11 @@ export type ChannelInputProps = InputCallbacks & {children?: JSX.Element;/** Whether to auto-focus the input on mount. Defaults to `!isMobile()`. */autofocus?: boolean;+ /**+ * Render a one-line `CollapsedInput` stand-in until the user clicks it.+ * Defaults to `false`.+ */+ collapsible?: boolean;};function WebDefaultActions(props: { input: InputData }) {@@ -117,6 +127,9 @@ export function ChannelInput(props: ChannelInputProps) {initialAttachments: props.input.attachments,});let clearComposer = () => {};+ // Suppresses focus-out handling during clearComposer's iOS blur/refocus+ // cycle, which is not a user-intended blur.+ let isInternalRefocus = false;const typingTracker = createTypingTracker({onStartTyping: () => props.onStartTyping?.(),@@ -156,6 +169,12 @@ export function ChannelInput(props: ChannelInputProps) {persistenceKey: props.persistenceKey,});+ const collapsedInput = createCollapsedInputState({+ inputId: () => props.input.id,+ attachFiles: (files) => inputState.commands.attachFiles(files),+ });+ const isCollapsed = () => !!props.collapsible && collapsedInput.isCollapsed();+let isEditorConnected = false;let pendingRestoreSnapshot:| Parameters<InputHandle['restoreSnapshot']>[0]@@ -239,9 +258,13 @@ export function ChannelInput(props: ChannelInputProps) {// avoiding a conflict where clear()'s $setSelection(null) undoes the focus.clearComposer = () => {if (isIOS) {+ isInternalRefocus = true;markdownEditor.controls.blur();markdownEditor.controls.clear();- requestAnimationFrame(() => markdownEditor.controls.focus());+ requestAnimationFrame(() => {+ markdownEditor.controls.focus();+ isInternalRefocus = false;+ });} else {markdownEditor.controls.clear();}@@ -293,6 +316,7 @@ export function ChannelInput(props: ChannelInputProps) {props.onReady?.({clear: () => markdownEditor.controls.clear(),focus: () => markdownEditor.controls.focus(),+ send: () => inputState.commands.send(),attachFiles: (files) => inputState.commands.attachFiles(files),insertEntityMention,previewEntityMentionInsertion,@@ -323,15 +347,47 @@ export function ChannelInput(props: ChannelInputProps) {return (<Input.Root input={inputState.view()} commands={inputState.commands}>+ <Show when={isCollapsed()}>+ {/* File picker opened from the CollapsedInput attach button. */}+ <input+ ref={collapsedInput.setFilePickerRef}+ type="file"+ class="hidden"+ multiple+ accept={CHANNEL_FILE_PICKER_ACCEPT}+ onChange={collapsedInput.onFilePickerChange}+ data-collapsed-input-file-picker+ />+ <CollapsedInput+ draft={inputState.view().value}+ renderDraft={(draft) => (+ <StaticMarkdown+ markdown={draft()}+ theme={singleLineMarkdownTheme}+ singleLine+ />+ )}+ placeholder={inputState.view().placeholder}+ attachmentCount={inputState.view().attachments?.length ?? 0}+ pending={inputState.view().hasPendingAttachments}+ disabled={!hasSendableInputContent(inputState.view())}+ getFocusTarget={() => lexicalEditor().getRootElement()}+ onAttach={collapsedInput.attach}+ onOpen={collapsedInput.expand}+ onSend={() => void inputState.commands.send()}+ />+ </Show><SurfaceonFocusOut={(e) => {const next = e.relatedTarget as Node | null;if (next && e.currentTarget.contains(next)) return;+ if (isInternalRefocus) return;setIsFocused(false);+ collapsedInput.collapse();}}onFocusIn={() => setIsFocused(true)}active={isFocused()}- class="rounded-xl"+ class={cn('rounded-xl', isCollapsed() && 'hidden')}depth={2}solid>diff --git a/js/app/packages/channel/Input/InputActions.tsx b/js/app/packages/channel/Input/InputActions.tsxindex f326126c7e..28e50b0f43 100644--- a/js/app/packages/channel/Input/InputActions.tsx+++ b/js/app/packages/channel/Input/InputActions.tsx@@ -1,7 +1,6 @@import { pickNativePhotoLibraryMedia } from '@core/mobile/nativePhotoLibrary';import FormatIcon from '@phosphor/text-aa.svg';import TrashIcon from '@phosphor/trash.svg';-import ImageIcon from '@phosphor-icons/core/regular/image.svg?component-solid';import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';import type { JSX } from 'solid-js';import { InputActionButton } from './ActionButton';@@ -59,7 +58,7 @@ export function AttachNativeMediaAction() {label="Attach photos or videos"onClick={() => void onAttachMedia()}>- <ImageIcon />+ <PaperclipIcon /></InputActionButton>);}diff --git a/js/app/packages/channel/Input/Root.tsx b/js/app/packages/channel/Input/Root.tsxindex ad70e7de5a..6978048884 100644--- a/js/app/packages/channel/Input/Root.tsx+++ b/js/app/packages/channel/Input/Root.tsx@@ -1,3 +1,4 @@+import { usePreserveFocusOnButtonTaps } from '@core/mobile/usePreserveFocusOnButtonTaps';import { useTouchOutsideToDismissKeyboard } from '@core/mobile/useTouchOutsideToDismissKeyboard';import { cn } from '@ui';import { type JSX, splitProps } from 'solid-js';@@ -27,6 +28,7 @@ export function Root(props: RootProps) {let containerRef: HTMLDivElement | undefined;useTouchOutsideToDismissKeyboard(() => containerRef);+ usePreserveFocusOnButtonTaps(() => containerRef);return (<divdiff --git a/js/app/packages/channel/Input/create-collapsed-input-state.ts b/js/app/packages/channel/Input/create-collapsed-input-state.tsnew file mode 100644index 0000000000..aca3dec918--- /dev/null+++ b/js/app/packages/channel/Input/create-collapsed-input-state.ts@@ -0,0 +1,54 @@+import { pickNativePhotoLibraryMedia } from '@core/mobile/nativePhotoLibrary';+import { isPlatform } from '@core/util/platform';+import { type Accessor, createEffect, createSignal, on } from 'solid-js';++/**+ * State and handlers for the `CollapsedInput` that stands in for a full+ * input until the user expands it.+ */+export function createCollapsedInputState(options: {+ /** Id of the input this state serves; collapses again when it changes. */+ inputId: Accessor<string | undefined>;+ attachFiles: (files: File[]) => Promise<void>;+}) {+ const [isExpanded, setIsExpanded] = createSignal(false);+ let filePickerRef: HTMLInputElement | undefined;++ // Collapse again when the surrounding view switches to another input.+ createEffect(+ on(options.inputId, () => setIsExpanded(false), { defer: true })+ );++ const attachFiles = async (files: File[]) => {+ if (files.length === 0) return;+ await options.attachFiles(files);+ };++ const attach = () => {+ if (isPlatform('ios')) {+ void pickNativePhotoLibraryMedia().then(attachFiles);+ return;+ }+ filePickerRef?.click();+ };++ const onFilePickerChange = (+ event: Event & { currentTarget: HTMLInputElement }+ ) => {+ const files = Array.from(event.currentTarget.files ?? []);+ event.currentTarget.value = '';+ void attachFiles(files);+ };++ return {+ /** Whether the collapsed stand-in renders instead of the real input. */+ isCollapsed: () => !isExpanded(),+ expand: () => setIsExpanded(true),+ collapse: () => setIsExpanded(false),+ attach,+ onFilePickerChange,+ setFilePickerRef: (element: HTMLInputElement) => {+ filePickerRef = element;+ },+ };+}diff --git a/js/app/packages/channel/Input/index.ts b/js/app/packages/channel/Input/index.tsindex c296dbcc34..33d539254a 100644--- a/js/app/packages/channel/Input/index.ts+++ b/js/app/packages/channel/Input/index.ts@@ -5,6 +5,7 @@ export { createInputAttachmentTracker } from './attachment-tracker';export { ChannelInput } from './ChannelInput';export { createConfiguredChannelMarkdownEditor } from './configured-markdown-editor';export { InputProvider, useInput, useInputCommands } from './context';+export { createCollapsedInputState } from './create-collapsed-input-state';export { createInputState } from './create-input-state';export { DropOverlay } from './DropOverlay';export { DropZone } from './DropZone';diff --git a/js/app/packages/channel/Input/tests/input-slots.test.tsx b/js/app/packages/channel/Input/tests/input-slots.test.tsxindex adc407621a..93549e3892 100644--- a/js/app/packages/channel/Input/tests/input-slots.test.tsx+++ b/js/app/packages/channel/Input/tests/input-slots.test.tsx@@ -27,6 +27,34 @@ vi.mock('@core/util/upload', () => ({uploadFile: vi.fn(),}));+// Several service clients in StaticMarkdown's import graph build websocket+// connections at module scope, which jsdom cannot do. Stub the builder so+// every module-scope socket is inert.+vi.mock('@websocket', async (importOriginal) => {+ const actual = await importOriginal<object>();+ const socket = {+ addEventListener: () => {},+ removeEventListener: () => {},+ send: () => {},+ close: () => {},+ };+ const builder: object = new Proxy(+ {},+ {+ get: (_target, prop) => {+ if (typeof prop === 'symbol' || prop === 'then') return undefined;+ return prop === 'build' ? () => socket : () => builder;+ },+ }+ );+ return {+ ...actual,+ WebsocketBuilder: function WebsocketBuilder() {+ return builder;+ },+ };+});+vi.mock('@core/constant/allBlocks', () => ({fileTypeToBlockName: (type?: string | null) => type ?? 'unknown',}));@@ -165,7 +193,7 @@ import { createInputAttachmentTracker } from '../attachment-tracker';import { ChannelInput } from '../ChannelInput';import { DropOverlay } from '../DropOverlay';import { Root } from '../Root';-import type { InputData } from '../types';+import type { InputData, InputHandle } from '../types';const baseInput: InputData = {mode: 'channel',@@ -271,6 +299,26 @@ describe('Input slots', () => {);});+ it('exposes send through the input handle', async () => {+ const onSend = vi.fn();+ let handle: InputHandle | undefined;++ render(() => (+ <ChannelInput+ input={{ ...baseInput, value: 'handle send' }}+ onReady={(nextHandle) => {+ handle = nextHandle;+ }}+ onSend={onSend}+ />+ ));++ await handle?.send();++ expect(onSend).toHaveBeenCalledOnce();+ expect(onSend.mock.calls[0]?.[0]?.value).toBe('handle send');+ });+it('shows invalid state in drop overlay', () => {render(() => (<Rootdiff --git a/js/app/packages/channel/Input/types.ts b/js/app/packages/channel/Input/types.tsindex 14712acc65..e6e6c0cc8c 100644--- a/js/app/packages/channel/Input/types.ts+++ b/js/app/packages/channel/Input/types.ts@@ -78,6 +78,7 @@ export type InputCommands = {export type InputHandle = {clear: () => void;focus: () => void;+ send: () => Promise<boolean>;attachFiles: (files: File[]) => Promise<void>;restoreSnapshot: (snapshot: InputSnapshot) => void;/**diff --git a/js/app/packages/core/comments/discussion/DiscussionInput.tsx b/js/app/packages/core/comments/discussion/DiscussionInput.tsxindex 2a4ed98ee6..6b7a58ca33 100644--- a/js/app/packages/core/comments/discussion/DiscussionInput.tsx+++ b/js/app/packages/core/comments/discussion/DiscussionInput.tsx@@ -190,6 +190,7 @@ export function DiscussionInput(props: DiscussionInputProps) {setMentions([]);},focus: () => markdownEditor.controls.focus(),+ send: () => commands.send(),attachFiles: async (files: File[]) => {// Insert images into the editorfor (const file of files) {diff --git a/js/app/packages/core/mobile/usePreserveFocusOnButtonTaps.ts b/js/app/packages/core/mobile/usePreserveFocusOnButtonTaps.tsnew file mode 100644index 0000000000..2b8032074d--- /dev/null+++ b/js/app/packages/core/mobile/usePreserveFocusOnButtonTaps.ts@@ -0,0 +1,57 @@+import { isMobile } from '@core/mobile/isMobile';+import { onCleanup, onMount } from 'solid-js';++/**+ * Keeps the focused editor inside the given container focused (and the+ * virtual keyboard open) when the user taps buttons within the same+ * container.+ *+ * On iOS, tapping a button blurs a focused contenteditable even when the+ * button cancels `pointerdown` — WebKit ends the editing session while+ * processing the tap itself, after `touchend`. Cancelling `touchend` is what+ * actually prevents the blur, but it also suppresses the synthesized click,+ * so the click is re-dispatched on the button manually.+ *+ * @param getContainer - Accessor that returns the container element whose+ * buttons should not steal focus from its editor. Pass `() => ref` where+ * `ref` is the local element ref.+ */+export function usePreserveFocusOnButtonTaps(+ getContainer: () => HTMLElement | null | undefined+) {+ if (!isMobile()) return;++ onMount(() => {+ function handleTouchEnd(e: TouchEvent) {+ // A gesture that turned into a scroll is no longer cancelable.+ if (!e.cancelable) return;++ const container = getContainer();+ if (!container) return;++ // Only intervene while something inside the container (the editor) is+ // focused — otherwise there is no focus to preserve.+ const active = document.activeElement;+ if (!active || !container.contains(active)) return;++ const target = e.target instanceof Element ? e.target : null;+ const button = target?.closest<HTMLElement>('button, [role="button"]');+ if (!button || !container.contains(button)) return;++ e.preventDefault();++ // Mirror native tap semantics: only activate the button when the+ // finger was released over it.+ const touch = e.changedTouches[0];+ if (!touch) return;+ const released = document.elementFromPoint(touch.clientX, touch.clientY);+ if (released && button.contains(released)) button.click();+ }++ window.addEventListener('touchend', handleTouchEnd, { passive: false });++ onCleanup(() => {+ window.removeEventListener('touchend', handleTouchEnd);+ });+ });+}diff --git a/js/app/packages/ui/components/CollapsedInput.tsx b/js/app/packages/ui/components/CollapsedInput.tsxnew file mode 100644index 0000000000..6d9454ad5e--- /dev/null+++ b/js/app/packages/ui/components/CollapsedInput.tsx@@ -0,0 +1,129 @@+import { focusInput } from '@core/directive/focusInput';+import { isMobile } from '@core/mobile/isMobile';+import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';+import { type Accessor, type JSX, Show } from 'solid-js';+import { cn } from '../utils/classname';+import { Button } from './Button';+import { SendButton } from './SendButton';+import { Surface } from './Surface';++export type CollapsedInputProps = {+ /** Draft of the real input, shown as the one-line preview. */+ draft?: string;+ /**+ * Renders the one-line draft preview. Receives the trimmed draft as an+ * accessor; the draft is rendered as plain text when omitted.+ */+ renderDraft?: (draft: Accessor<string>) => JSX.Element;+ placeholder?: string;+ attachmentCount?: number;+ /** Renders the send button with a spinner and disables it. */+ pending?: boolean;+ /**+ * Disables sending, e.g. when the draft has nothing sendable. The send+ * button is hidden on mobile and rendered disabled on desktop.+ */+ disabled?: boolean;+ class?: string;+ /**+ * Target of the real input this trigger stands in for. Focused via the+ * `focusInput` directive when the trigger is clicked, so the iOS virtual+ * keyboard opens within the user gesture.+ */+ getFocusTarget?: () => HTMLElement | null | undefined;+ onAttach?: () => void;+ onOpen?: () => void;+ onSend?: () => void | Promise<void>;+};++export function CollapsedInput(props: CollapsedInputProps) {+ const attachFocusInput = (el: HTMLElement) => {+ const getTarget = props.getFocusTarget;+ if (getTarget) focusInput(el, () => ({ getTarget }));+ };++ const text = () => props.draft?.trim() ?? '';+ const hasText = () => text().length > 0;+ const attachmentCount = () => props.attachmentCount ?? 0;+ const hasAttachments = () => attachmentCount() > 0;++ return (+ <Surface+ depth={2}+ solid+ // h-12.5 and px-2 keep the attach/send buttons exactly where the+ // expanded input's footer puts them (`p-2 mb-2 h-8` plus the surface's+ // 1px border: button centers 25px above the outer bottom edge, 8px in+ // from the border).+ class={cn('rounded-xl w-full h-12.5', props.class)}+ data-collapsed-input+ >+ <div class="flex h-full min-w-0 items-center gap-1.5 px-2">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Attach files"+ label="Attach files"+ onClick={() => props.onAttach?.()}+ >+ <PaperclipIcon />+ </Button>+ <button+ type="button"+ class={cn(+ 'min-w-0 flex-1 overflow-hidden rounded-sm px-1.5 text-left text-sm outline-none',+ 'flex h-8 items-center text-ink focus-visible:bg-active'+ )}+ ref={attachFocusInput}+ onClick={() => props.onOpen?.()}+ data-collapsed-input-preview+ >+ <Show+ when={hasText()}+ fallback={+ <span class="truncate text-ink-placeholder">+ {props.placeholder ?? 'Message'}+ </span>+ }+ >+ {/* Interactive content in the rendered draft (mentions, links)+ must not swallow the tap that opens the input. */}+ <div class="pointer-events-none min-w-0 flex-1 truncate">+ {props.renderDraft ? props.renderDraft(text) : text()}+ </div>+ </Show>+ </button>+ <Show when={hasAttachments() && !hasText()}>+ <Button+ variant="ghost"+ size="sm"+ class="h-8 px-1.5 gap-1"+ aria-label={`${attachmentCount()} attachment${+ attachmentCount() === 1 ? '' : 's'+ }`}+ label={`${attachmentCount()} attachment${+ attachmentCount() === 1 ? '' : 's'+ }`}+ ref={attachFocusInput}+ onClick={() => props.onOpen?.()}+ data-collapsed-input-attachments+ >+ <PaperclipIcon />+ <span>{attachmentCount()}</span>+ </Button>+ </Show>+ <Show when={!isMobile() || !props.disabled}>+ <SendButton+ pending={props.pending}+ disabled={props.disabled || props.pending}+ onPointerDown={(event) => {+ event.preventDefault();+ void props.onSend?.();+ }}+ data-collapsed-input-send+ />+ </Show>+ </div>+ </Surface>+ );+}diff --git a/js/app/packages/ui/index.ts b/js/app/packages/ui/index.tsindex d980d57748..9136eb1999 100644--- a/js/app/packages/ui/index.ts+++ b/js/app/packages/ui/index.ts@@ -18,6 +18,8 @@ export {InlineCheckbox,SingleSelectCheck,} from './components/Checkbox';+export type { CollapsedInputProps } from './components/CollapsedInput';+export { CollapsedInput } from './components/CollapsedInput';export type { DialogProps } from './components/Dialog';export { Dialog } from './components/Dialog';export { Dropdown } from './components/Dropdown';diff --git a/js/app/tauri/photo_library_plugin/ios/Sources/PhotoLibraryPlugin.swift b/js/app/tauri/photo_library_plugin/ios/Sources/PhotoLibraryPlugin.swiftindex 2bce21c61c..b2a3ed7efb 100644--- a/js/app/tauri/photo_library_plugin/ios/Sources/PhotoLibraryPlugin.swift+++ b/js/app/tauri/photo_library_plugin/ios/Sources/PhotoLibraryPlugin.swift@@ -20,6 +20,7 @@ class UnavailablePhotoLibraryPlugin: Plugin {@available(iOS 14.0, *)class PhotoLibraryPlugin: Plugin {private var pickerDelegate: PhotoLibraryPickerDelegate?+ private weak var presentedPicker: PHPickerViewController?@objc public func pickPhotoLibraryImages(_ invoke: Invoke) throws {let payload = try invoke.parseArgs(PickPhotoLibraryImagesPayload.self)@@ -29,10 +30,17 @@ class PhotoLibraryPlugin: Plugin {)DispatchQueue.main.async {- guard self.pickerDelegate == nil else {+ if let activePicker = self.presentedPicker,+ activePicker.isBeingPresented || activePicker.presentingViewController != nil+ {invoke.reject("Photo library picker is already open")return}+ // A lingering delegate whose picker is no longer on screen means+ // the previous session ended without a delegate callback (the+ // sheet can be dismissed without one); drop it so the picker can+ // open again instead of being stuck "already open".+ self.pickerDelegate = nilguard let rootViewController = self.manager.viewController else {invoke.reject("No view controller available to present photo library")@@ -55,12 +63,17 @@ class PhotoLibraryPlugin: Plugin {invoke: invoke,stagingDirectory: stagingDirectory,tokenPrefix: payload.tokenPrefix,- onComplete: { [weak self] in- self?.pickerDelegate = nil+ onComplete: { [weak self] finishedDelegate in+ // A stale session may complete after a newer picker was+ // opened; only clear the delegate it still owns.+ if self?.pickerDelegate === finishedDelegate {+ self?.pickerDelegate = nil+ }})self.pickerDelegate = delegatepicker.delegate = delegate+ self.presentedPicker = pickerviewController.present(picker, animated: true)}@@ -176,14 +189,14 @@ private class PhotoLibraryPickerDelegate: NSObject, PHPickerViewControllerDelegaprivate let invoke: Invokeprivate let stagingDirectory: URLprivate let tokenPrefix: String- private let onComplete: () -> Void+ private let onComplete: (PhotoLibraryPickerDelegate) -> Voidinit(plugin: PhotoLibraryPlugin,invoke: Invoke,stagingDirectory: URL,tokenPrefix: String,- onComplete: @escaping () -> Void+ onComplete: @escaping (PhotoLibraryPickerDelegate) -> Void) {self.plugin = pluginself.invoke = invoke@@ -197,13 +210,13 @@ private class PhotoLibraryPickerDelegate: NSObject, PHPickerViewControllerDelegaguard !results.isEmpty else {invoke.resolve([StagedPhotoLibraryMedia]())- onComplete()+ onComplete(self)return}guard let plugin = plugin else {invoke.reject("Photo library plugin was released")- onComplete()+ onComplete(self)return}@@ -271,7 +284,7 @@ private class PhotoLibraryPickerDelegate: NSObject, PHPickerViewControllerDelega} else {self.invoke.resolve([StagedPhotoLibraryMedia]())}- self.onComplete()+ self.onComplete(self)}}}