Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(mobile): Redesign the note share sheet (#2408)
Chad Piha827e0687a8bb
diff --git a/openwhispr-mobile/src/components/notes/NoteShareAccessList.tsx b/openwhispr-mobile/src/components/notes/NoteShareAccessList.tsxindex adbd763fa..169f5fc90 100644--- a/openwhispr-mobile/src/components/notes/NoteShareAccessList.tsx+++ b/openwhispr-mobile/src/components/notes/NoteShareAccessList.tsx@@ -1,13 +1,11 @@-import { useEffect, useState } from 'react';-import { Alert, View } from 'react-native';-import { SearchField } from '@/components/ui/SearchField';+import { type ReactNode } from 'react';+import { Alert, Pressable, View } from 'react-native';+import { MenuView, type MenuAction } from '@react-native-menu/menu';import { Text } from '@/components/ui/Text';-import { searchNoteAccessPrincipals } from '@/data/remote/noteSharingApi';+import { SystemIcon } from '@/components/ui/SystemIcon';import { confirmDestructive } from '@/lib/alerts';import type {- AccessPrincipalSuggestion,NoteAccessGrant,- NoteAccessPrincipalType,NoteAccessState,NoteShareInvitation,} from '@/data/remote/noteSharingTypes';@@ -18,22 +16,18 @@ import {isScopeGrant,} from '@/lib/notes/noteShareAccess';import { GroupedList } from './GroupedList';-import { ShareTextButton } from './ShareTextButton';+import { PRINCIPAL_LABEL, PrincipalAvatar } from './NoteSharePrincipal';-const PRINCIPAL_LABEL: Record<NoteAccessPrincipalType, string> = {- user: 'Person',- email: 'Email',- team: 'Team',- space: 'Team space',- folder: 'Folder',- workspace: 'Workspace',-};+type Permission = NoteAccessGrant['permission'];-function grantDetail(grant: NoteAccessGrant): string {+const ROLE_LABEL: Record<Permission, string> = { editor: 'Editor', viewer: 'Viewer' };++function grantDetail(grant: NoteAccessGrant): string | null {if (isScopeGrant(grant) && grant.source !== 'direct')return `Inherited from ${PRINCIPAL_LABEL[grant.source].toLowerCase()}`;// Stored group grants are flagged inherited because their members inherit them.- return isGroupPrincipal(grant.principal.type) ? PRINCIPAL_LABEL[grant.principal.type] : 'Direct';+ if (isGroupPrincipal(grant.principal.type)) return PRINCIPAL_LABEL[grant.principal.type];+ return grant.principal.name ? grant.principal.email : null;}function confirmEditor(name: string, onConfirm: () => void): void {@@ -47,8 +41,89 @@ function confirmEditor(name: string, onConfirm: () => void): void {);}+/** The editor/viewer choice, as its own section of the row's menu. */+function roleSection(rowId: string, current: Permission, busy: boolean): MenuAction {+ return {+ id: `${rowId}:roles`,+ title: '',+ displayInline: true,+ subactions: (['editor', 'viewer'] as const).map((permission) => ({+ id: `${rowId}:${permission}`,+ title: ROLE_LABEL[permission],+ state: permission === current ? 'on' : 'off',+ attributes: { disabled: busy },+ })),+ };+}++interface RoleMenuProps {+ role: Permission;+ accessibilityLabel: string;+ actions: MenuAction[];+ busy: boolean;+ onAction: (id: string) => void;+}++/** The trailing role label, which opens the row's actions when there are any. */+function RoleMenu({ role, accessibilityLabel, actions, busy, onAction }: RoleMenuProps) {+ if (actions.length === 0) {+ return <Text className="text-[13px] text-secondaryLabel">{ROLE_LABEL[role]}</Text>;+ }+ return (+ <MenuView+ actions={actions}+ onPressAction={({ nativeEvent }) => onAction(nativeEvent.event)}+ shouldOpenOnLongPress={false}+ >+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={accessibilityLabel}+ accessibilityValue={{ text: ROLE_LABEL[role] }}+ accessibilityState={{ disabled: busy }}+ className="min-h-[44px] flex-row items-center gap-1 pl-2 active:opacity-60"+ >+ <Text className={busy ? 'text-[13px] text-tertiaryLabel' : 'text-[13px] text-link'}>+ {ROLE_LABEL[role]}+ </Text>+ <SystemIcon+ name="chevron.down"+ mdName="ChevronDown"+ size={10}+ color={busy ? 'tertiaryLabel' : 'link'}+ />+ </Pressable>+ </MenuView>+ );+}++interface PersonRowProps {+ avatar: ReactNode;+ name: string;+ detail: string | null;+ trailing: ReactNode;+}++function PersonRow({ avatar, name, detail, trailing }: PersonRowProps) {+ return (+ <GroupedList.Row leadingIconSlot={avatar}>+ <View className="flex-row items-center gap-3">+ <View className="min-w-0 flex-1">+ <Text numberOfLines={1} className="text-[15px] font-medium text-label">+ {name}+ </Text>+ {detail ? (+ <Text numberOfLines={1} className="text-[12px] text-secondaryLabel">+ {detail}+ </Text>+ ) : null}+ </View>+ {trailing}+ </View>+ </GroupedList.Row>+ );+}+interface NoteShareAccessListProps {- remoteId?: string;access: NoteAccessState;invitations: NoteShareInvitation[];/** External sharing is off, which suspends stored grants and invitations on the server. */@@ -56,48 +131,26 @@ interface NoteShareAccessListProps {/** Organization policy allows invitations, new grants, and raising a permission to editor. */canInvite?: boolean;busy: boolean;- onAddPrincipal?: (principal: AccessPrincipalSuggestion) => void;- onUpdateGrant: (grant: NoteAccessGrant, permission: NoteAccessGrant['permission']) => void;+ /** The field that adds people, shown as the card's first row. */+ inviteField?: ReactNode;+ onUpdateGrant: (grant: NoteAccessGrant, permission: Permission) => void;onRemoveGrant: (grant: NoteAccessGrant) => void;onRevokeInvitation: (invitation: NoteShareInvitation) => void;onResendInvitation: (invitation: NoteShareInvitation) => void;}export function NoteShareAccessList({- remoteId,access,invitations,paused = false,canInvite = true,busy,- onAddPrincipal,+ inviteField,onUpdateGrant,onRemoveGrant,onRevokeInvitation,onResendInvitation,}: NoteShareAccessListProps) {- const [query, setQuery] = useState('');- const [suggestions, setSuggestions] = useState<AccessPrincipalSuggestion[]>([]);- const [searchError, setSearchError] = useState(false);- useEffect(() => {- setSuggestions([]);- setSearchError(false);- if (!remoteId || !access.can_manage_access || query.trim().length < 2) return;- const controller = new AbortController();- const timer = setTimeout(() => {- searchNoteAccessPrincipals(remoteId, query.trim(), { signal: controller.signal })- .then((result) => {- if (!controller.signal.aborted) setSuggestions(result.suggestions);- })- .catch(() => {- if (!controller.signal.aborted) setSearchError(true);- });- }, 300);- return (): void => {- clearTimeout(timer);- controller.abort();- };- }, [remoteId, access.can_manage_access, query]);const pending = invitations.filter((invite) => !invite.revoked_at && !invite.accepted_at);const invitationEmails = new Set(pending.map((invite) => invite.email.toLowerCase()));const grants = access.grants.filter(@@ -108,179 +161,149 @@ export function NoteShareAccessList({invitationEmails.has(grant.principal.email.toLowerCase())),);- const existingIds = new Set(access.grants.map((grant) => grant.principal.id).filter(Boolean));- const existingEmails = new Set([- ...access.grants.map((grant) => grant.principal.email?.toLowerCase()).filter(Boolean),- ...invitations- .filter((invite) => !invite.revoked_at)- .map((invite) => invite.email.toLowerCase()),- ]);- const available = suggestions.filter(- (principal) =>- !principal.existing_grant_id &&- !existingIds.has(principal.id) &&- !existingEmails.has(principal.email?.toLowerCase()) &&- (!isGroupPrincipal(principal.type) || access.can_manage_inherited_access),- );++ const changeRole = (+ grant: NoteAccessGrant,+ current: Permission,+ name: string,+ selectedId: string,+ ): void => {+ const permission: Permission = selectedId.endsWith(':editor') ? 'editor' : 'viewer';+ if (permission === current) return;+ if (permission === 'editor') confirmEditor(name, () => onUpdateGrant(grant, 'editor'));+ else onUpdateGrant(grant, 'viewer');+ };++ const grantRow = (grant: NoteAccessGrant): ReactNode => {+ const name = grant.principal.name || grant.principal.email || 'Unnamed group';+ const actions: MenuAction[] = [];+ if (canChangeGrant(access, grant)) {+ if (canInvite || grant.permission === 'editor')+ actions.push(roleSection(grant.id, grant.permission, busy));+ actions.push({+ id: `${grant.id}:remove`,+ title: 'Remove access',+ attributes: { destructive: true, disabled: busy },+ });+ }+ const detail = [+ grantDetail(grant),+ grant.pending ? 'Pending' : null,+ paused && isPausedBySharingOff(grant) ? 'Paused' : null,+ ]+ .filter(Boolean)+ .join(' · ');+ return (+ <PersonRow+ key={grant.id}+ avatar={+ <PrincipalAvatar+ type={grant.principal.type}+ name={grant.principal.name}+ email={grant.principal.email}+ />+ }+ name={name}+ detail={detail}+ trailing={+ <RoleMenu+ role={grant.permission}+ accessibilityLabel={`Change access for ${name}`}+ actions={actions}+ busy={busy}+ onAction={(id) => {+ if (!id.endsWith(':remove')) {+ changeRole(grant, grant.permission, name, id);+ return;+ }+ confirmDestructive(+ 'Remove access?',+ `${name} will lose the access granted on this note.`,+ () => onRemoveGrant(grant),+ { destructiveLabel: 'Remove' },+ );+ }}+ />+ }+ />+ );+ };++ const invitationRow = (invite: NoteShareInvitation): ReactNode => {+ const invitationGrant = access.grants.find((grant) => grant.id === `invite:${invite.id}`);+ const rowId = `invitation:${invite.id}`;+ const actions: MenuAction[] = [];+ if (access.can_manage_access) {+ if (invitationGrant && (canInvite || invite.permission === 'editor'))+ actions.push(roleSection(rowId, invite.permission, busy));+ // A paused share's emailed link can't open the note, so resending would only confuse.+ if (canInvite && !paused)+ actions.push({+ id: `${rowId}:resend`,+ title: 'Resend invitation',+ attributes: { disabled: busy },+ });+ actions.push({+ id: `${rowId}:revoke`,+ title: 'Revoke invitation',+ attributes: { destructive: true, disabled: busy },+ });+ }+ return (+ <PersonRow+ key={invite.id}+ avatar={<PrincipalAvatar type="email" email={invite.email} />}+ name={invite.email}+ detail={`Pending invitation${paused ? ' · Paused' : ''}`}+ trailing={+ <RoleMenu+ role={invite.permission}+ accessibilityLabel={`Change access for ${invite.email}`}+ actions={actions}+ busy={busy}+ onAction={(id) => {+ if (id.endsWith(':resend')) {+ onResendInvitation(invite);+ } else if (id.endsWith(':revoke')) {+ confirmDestructive(+ 'Revoke invitation?',+ `${invite.email} will lose the access this invitation gave them.`,+ () => onRevokeInvitation(invite),+ { destructiveLabel: 'Revoke' },+ );+ } else if (invitationGrant) {+ changeRole(invitationGrant, invite.permission, invite.email, id);+ }+ }}+ />+ }+ />+ );+ };return (<View className="gap-2"><Text className="px-1 text-[13px] uppercase tracking-wider text-secondaryLabel">People with access</Text>+ <GroupedList>+ {inviteField}+ <PersonRow+ avatar={+ <PrincipalAvatar type="user" name={access.owner.name} email={access.owner.email} />+ }+ name={access.owner.name || access.owner.email || 'Owner'}+ detail={access.owner.name ? access.owner.email : null}+ trailing={<Text className="text-[13px] text-secondaryLabel">Owner</Text>}+ />+ {grants.map(grantRow)}+ {pending.map(invitationRow)}+ </GroupedList>{paused && (- <Text className="px-1 text-[12px] text-secondaryLabel">+ <Text className="px-4 text-[12px] text-secondaryLabel">People you added and invitations are paused until you share this note again.</Text>)}- {access.can_manage_access && canInvite && remoteId && onAddPrincipal && (- <View className="gap-2">- <View className="flex-row">- <SearchField- accessibilityLabel="Find people or groups"- placeholder="Find people or groups"- value={query}- onChangeText={setQuery}- />- </View>- {searchError && (- <Text className="text-[12px] text-systemRed">Search unavailable. Try again.</Text>- )}- {available.length > 0 && (- <GroupedList dividerInset={16}>- {available.map((principal) => (- <GroupedList.Row- key={`${principal.type}:${principal.id ?? principal.email}`}- onPress={() => {- onAddPrincipal(principal);- setQuery('');- }}- disabled={busy}- accessibilityRole="button"- accessibilityLabel={`Grant access to ${principal.name || principal.email}`}- >- <Text- className={busy ? 'text-[15px] text-tertiaryLabel' : 'text-[15px] text-label'}- >- {principal.name || principal.email}- </Text>- <Text className="text-[12px] text-secondaryLabel">- {PRINCIPAL_LABEL[principal.type]}- </Text>- </GroupedList.Row>- ))}- </GroupedList>- )}- </View>- )}- <GroupedList dividerInset={16}>- <GroupedList.Row>- <View className="flex-row items-center justify-between">- <Text className="text-[15px] font-medium text-label">- {access.owner.name || access.owner.email || 'Owner'}- </Text>- <Text className="text-[13px] text-secondaryLabel">Owner</Text>- </View>- </GroupedList.Row>- {grants.map((grant) => {- const name = grant.principal.name || grant.principal.email || 'Unnamed group';- const canEdit = canChangeGrant(access, grant);- return (- <GroupedList.Row key={grant.id}>- <Text className="text-[15px] font-medium text-label">{name}</Text>- <Text className="text-[12px] text-secondaryLabel">- {grant.permission === 'editor' ? 'Editor' : 'Viewer'}- {` · ${grantDetail(grant)}`}- {grant.pending ? ' · Pending' : ''}- {paused && isPausedBySharingOff(grant) ? ' · Paused' : ''}- </Text>- {canEdit && (- <View className="flex-row gap-6">- {(canInvite || grant.permission === 'editor') && (- <ShareTextButton- label={grant.permission === 'viewer' ? 'Make editor' : 'Make viewer'}- accessibilityLabel={`${grant.permission === 'viewer' ? 'Make' : 'Change'} ${name} ${grant.permission === 'viewer' ? 'an editor' : 'a viewer'}`}- disabled={busy}- onPress={() =>- grant.permission === 'viewer'- ? confirmEditor(name, () => onUpdateGrant(grant, 'editor'))- : onUpdateGrant(grant, 'viewer')- }- />- )}- <ShareTextButton- label="Remove"- accessibilityLabel={`Remove access for ${name}`}- destructive- disabled={busy}- onPress={() =>- confirmDestructive(- 'Remove access?',- `${name} will lose the access granted on this note.`,- () => onRemoveGrant(grant),- { destructiveLabel: 'Remove' },- )- }- />- </View>- )}- </GroupedList.Row>- );- })}- {pending.map((invite) => {- const invitationGrant = access.grants.find((grant) => grant.id === `invite:${invite.id}`);- return (- <GroupedList.Row key={invite.id}>- <Text className="text-[15px] font-medium text-label">{invite.email}</Text>- <Text className="text-[12px] text-secondaryLabel">- Pending invitation- {paused ? ' · Paused' : ''}- {` · ${invite.permission === 'editor' ? 'Editor' : 'Viewer'}`}- </Text>- {access.can_manage_access && (- <View className="flex-row gap-6">- {invitationGrant && (canInvite || invite.permission === 'editor') && (- <ShareTextButton- label={invite.permission === 'viewer' ? 'Make editor' : 'Make viewer'}- accessibilityLabel={`Make ${invite.email} ${invite.permission === 'viewer' ? 'an editor' : 'a viewer'}`}- disabled={busy}- onPress={() =>- invite.permission === 'viewer'- ? confirmEditor(invite.email, () =>- onUpdateGrant(invitationGrant, 'editor'),- )- : onUpdateGrant(invitationGrant, 'viewer')- }- />- )}- {canInvite && !paused && (- <ShareTextButton- label="Resend"- accessibilityLabel={`Resend invitation to ${invite.email}`}- disabled={busy}- onPress={() => onResendInvitation(invite)}- />- )}- <ShareTextButton- label="Revoke"- accessibilityLabel={`Revoke invitation for ${invite.email}`}- destructive- disabled={busy}- onPress={() =>- confirmDestructive(- 'Revoke invitation?',- `${invite.email} will lose the access this invitation gave them.`,- () => onRevokeInvitation(invite),- { destructiveLabel: 'Revoke' },- )- }- />- </View>- )}- </GroupedList.Row>- );- })}- </GroupedList></View>);}diff --git a/openwhispr-mobile/src/components/notes/NoteShareActions.tsx b/openwhispr-mobile/src/components/notes/NoteShareActions.tsxnew file mode 100644index 000000000..10f8b4f17--- /dev/null+++ b/openwhispr-mobile/src/components/notes/NoteShareActions.tsx@@ -0,0 +1,74 @@+import { Fragment } from 'react';+import { Pressable, View } from 'react-native';+import { Text } from '@/components/ui/Text';+import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';+import { GroupedList } from './GroupedList';++interface ShareActionRowProps {+ label: string;+ onPress: () => void;+ disabled?: boolean;+ destructive?: boolean;+ accessibilityLabel?: string;+}++/** A tappable row that reads as an action rather than a setting. */+export function ShareActionRow({+ label,+ onPress,+ disabled = false,+ destructive = false,+ accessibilityLabel,+}: ShareActionRowProps) {+ const tone = disabled ? 'text-tertiaryLabel' : destructive ? 'text-systemRed' : 'text-link';+ return (+ <GroupedList.Row+ onPress={onPress}+ disabled={disabled}+ accessibilityRole="button"+ accessibilityLabel={accessibilityLabel ?? label}+ >+ <Text className={`text-[15px] ${tone}`}>{label}</Text>+ </GroupedList.Row>+ );+}++export interface ShareStripAction {+ label: string;+ accessibilityLabel?: string;+ icon: string;+ mdIcon: LucideIconName;+ onPress: () => void;+}++interface ShareActionStripProps {+ actions: ShareStripAction[];+ disabled?: boolean;+}++/** Equal-width icon buttons along the bottom of a card. */+export function ShareActionStrip({ actions, disabled = false }: ShareActionStripProps) {+ const color = disabled ? 'tertiaryLabel' : 'link';+ return (+ <View className="flex-row">+ {actions.map((action, index) => (+ <Fragment key={action.label}>+ {index > 0 && <View className="w-px bg-separator" />}+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={action.accessibilityLabel ?? action.label}+ accessibilityState={{ disabled }}+ disabled={disabled}+ onPress={action.onPress}+ className="min-h-[56px] flex-1 items-center justify-center gap-1 py-2 active:bg-tertiarySystemFill"+ >+ <SystemIcon name={action.icon} mdName={action.mdIcon} size={18} color={color} />+ <Text className={disabled ? 'text-[12px] text-tertiaryLabel' : 'text-[12px] text-link'}>+ {action.label}+ </Text>+ </Pressable>+ </Fragment>+ ))}+ </View>+ );+}diff --git a/openwhispr-mobile/src/components/notes/NoteShareInviteField.tsx b/openwhispr-mobile/src/components/notes/NoteShareInviteField.tsxnew file mode 100644index 000000000..72a82827b--- /dev/null+++ b/openwhispr-mobile/src/components/notes/NoteShareInviteField.tsx@@ -0,0 +1,184 @@+import { useEffect, useState, type ReactElement, type ReactNode } from 'react';+import { TextInput, View, type TextStyle } from 'react-native';+import { Text } from '@/components/ui/Text';+import { searchNoteAccessPrincipals } from '@/data/remote/noteSharingApi';+import type {+ AccessPrincipalSuggestion,+ NoteAccessState,+ NoteShareInvitation,+} from '@/data/remote/noteSharingTypes';+import { iosColor } from '@/config/colors';+import { AppFont } from '@/lib/fonts';+import { isValidEmail } from '@/lib/utils';+import { isGroupPrincipal } from '@/lib/notes/noteShareAccess';+import { GroupedList } from './GroupedList';+import { NOTES_ROW_CONTENT_INSET } from './tokens';+import { PRINCIPAL_LABEL, PrincipalAvatar, RowIcon } from './NoteSharePrincipal';++const PLACEHOLDER_COLOR = iosColor('tertiaryLabel');+const INPUT_STYLE: TextStyle = { fontFamily: AppFont.regular };++interface NoteShareInviteFieldProps {+ value: string;+ onChangeText: (value: string) => void;+ /** Invites the typed address; the caller validates it and clears the field. */+ onInvite: () => void;+ /** Adding people and groups needs a cloud copy to search against; email invitations don't. */+ remoteId?: string;+ access?: NoteAccessState;+ invitations?: NoteShareInvitation[];+ busy: boolean;+ onAddPrincipal?: (principal: AccessPrincipalSuggestion) => void;+}++/** One field that searches people and groups and invites any typed email address. */+export function NoteShareInviteField({+ value,+ onChangeText,+ onInvite,+ remoteId,+ access,+ invitations = [],+ busy,+ onAddPrincipal,+}: NoteShareInviteFieldProps) {+ const [suggestions, setSuggestions] = useState<AccessPrincipalSuggestion[]>([]);+ const [searchError, setSearchError] = useState(false);+ const searchable = Boolean(remoteId && access?.can_manage_access && onAddPrincipal);+ const query = value.trim();+ useEffect(() => {+ setSuggestions([]);+ setSearchError(false);+ if (!searchable || !remoteId || query.length < 2) return;+ const controller = new AbortController();+ const timer = setTimeout(() => {+ searchNoteAccessPrincipals(remoteId, query, { signal: controller.signal })+ .then((result) => {+ if (!controller.signal.aborted) setSuggestions(result.suggestions);+ })+ .catch(() => {+ if (!controller.signal.aborted) setSearchError(true);+ });+ }, 300);+ return (): void => {+ clearTimeout(timer);+ controller.abort();+ };+ }, [searchable, remoteId, query]);++ const grants = access?.grants ?? [];+ const existingIds = new Set(grants.map((grant) => grant.principal.id).filter(Boolean));+ // Groups have no email, so a missing one must never count as a match.+ const existingEmails = new Set(+ [+ access?.owner.email,+ ...grants.map((grant) => grant.principal.email),+ ...invitations.filter((invite) => !invite.revoked_at).map((invite) => invite.email),+ ]+ .filter((email): email is string => Boolean(email))+ .map((email) => email.toLowerCase()),+ );+ const available = suggestions.filter(+ (principal) =>+ !principal.existing_grant_id &&+ !existingIds.has(principal.id) &&+ !(principal.email && existingEmails.has(principal.email.toLowerCase())) &&+ (!isGroupPrincipal(principal.type) || access?.can_manage_inherited_access),+ );+ const typedEmail = query.toLowerCase();+ const offerInvite =+ isValidEmail(query) &&+ !existingEmails.has(typedEmail) &&+ !available.some((principal) => principal.email?.toLowerCase() === typedEmail);+ const placeholder = searchable ? 'Add people or emails' : 'Invite by email';++ const rows = [+ <GroupedList.Row+ key="field"+ leadingIconSlot={<RowIcon name="person.badge.plus" mdName="UserPlus" />}+ >+ <TextInput+ accessibilityLabel={placeholder}+ className="py-1 text-[15px] text-label"+ style={INPUT_STYLE}+ placeholder={placeholder}+ placeholderTextColor={PLACEHOLDER_COLOR}+ autoCapitalize="none"+ autoCorrect={false}+ autoComplete="email"+ textContentType="emailAddress"+ keyboardType="email-address"+ returnKeyType="send"+ clearButtonMode="while-editing"+ value={value}+ onChangeText={onChangeText}+ onSubmitEditing={onInvite}+ />+ {searchError && (+ <Text className="pt-1 text-[12px] text-systemRed">Search unavailable. Try again.</Text>+ )}+ </GroupedList.Row>,+ ];+ if (offerInvite) {+ rows.push(+ <GroupedList.Row+ key="invite"+ onPress={onInvite}+ disabled={busy}+ accessibilityRole="button"+ accessibilityLabel={`Invite ${query}`}+ leadingIconSlot={<RowIcon name="envelope" mdName="Mail" />}+ >+ <Text+ numberOfLines={1}+ className={busy ? 'text-[15px] text-tertiaryLabel' : 'text-[15px] text-link'}+ >+ Invite {query}+ </Text>+ <Text className="text-[12px] text-secondaryLabel">Sends an email invitation</Text>+ </GroupedList.Row>,+ );+ }+ for (const principal of available) {+ const name = principal.name || principal.email || PRINCIPAL_LABEL[principal.type];+ rows.push(+ <GroupedList.Row+ key={`${principal.type}:${principal.id ?? principal.email}`}+ onPress={() => onAddPrincipal?.(principal)}+ disabled={busy}+ accessibilityRole="button"+ accessibilityLabel={`Grant access to ${name}`}+ leadingIconSlot={+ <PrincipalAvatar type={principal.type} name={principal.name} email={principal.email} />+ }+ >+ <Text+ numberOfLines={1}+ className={busy ? 'text-[15px] text-tertiaryLabel' : 'text-[15px] text-label'}+ >+ {name}+ </Text>+ <Text numberOfLines={1} className="text-[12px] text-secondaryLabel">+ {principal.name && principal.email ? principal.email : PRINCIPAL_LABEL[principal.type]}+ </Text>+ </GroupedList.Row>,+ );+ }+ return <View>{withDividers(rows)}</View>;+}++/** Rows inside one card slot, separated like the card's own rows. */+function withDividers(rows: ReactElement[]): ReactNode[] {+ return rows.flatMap((row, index) =>+ index === 0+ ? [row]+ : [+ <View+ key={`divider-${row.key}`}+ className="h-px bg-separator"+ style={{ marginLeft: NOTES_ROW_CONTENT_INSET }}+ />,+ row,+ ],+ );+}diff --git a/openwhispr-mobile/src/components/notes/NoteSharePrincipal.tsx b/openwhispr-mobile/src/components/notes/NoteSharePrincipal.tsxnew file mode 100644index 000000000..5525d2057--- /dev/null+++ b/openwhispr-mobile/src/components/notes/NoteSharePrincipal.tsx@@ -0,0 +1,67 @@+import { View } from 'react-native';+import { Text } from '@/components/ui/Text';+import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';+import type { NoteAccessPrincipalType } from '@/data/remote/noteSharingTypes';++export const PRINCIPAL_LABEL: Record<NoteAccessPrincipalType, string> = {+ user: 'Person',+ email: 'Email',+ team: 'Team',+ space: 'Team space',+ folder: 'Folder',+ workspace: 'Workspace',+};++type IconPair = [sfName: string, mdName: LucideIconName];++const GROUP_ICON: Partial<Record<NoteAccessPrincipalType, IconPair>> = {+ team: ['person.2', 'Users'],+ space: ['person.3', 'Users'],+ folder: ['folder', 'Folder'],+ workspace: ['building.2', 'Building2'],+};+const MAIL_ICON: IconPair = ['envelope', 'Mail'];++interface RowIconProps {+ name: string;+ mdName: LucideIconName;+ /** Brand marks the row's current state; neutral is for everything else. */+ tone?: 'neutral' | 'brand';+}++/** The leading icon of a row in the share sheet's cards. */+export function RowIcon({ name, mdName, tone = 'neutral' }: RowIconProps) {+ const brand = tone === 'brand';+ return (+ <View+ className={`h-8 w-8 items-center justify-center rounded-full ${+ brand ? 'bg-brand/10' : 'bg-tertiarySystemFill'+ }`}+ >+ <SystemIcon+ name={name}+ mdName={mdName}+ size={15}+ color={brand ? 'brand' : 'secondaryLabel'}+ />+ </View>+ );+}++interface PrincipalAvatarProps {+ type: NoteAccessPrincipalType;+ name?: string | null;+ email?: string | null;+}++/** A person's initial, or an icon for groups and addresses without an account. */+export function PrincipalAvatar({ type, name, email }: PrincipalAvatarProps) {+ const icon = GROUP_ICON[type] ?? (type === 'email' ? MAIL_ICON : undefined);+ if (icon) return <RowIcon name={icon[0]} mdName={icon[1]} />;+ const initial = (name || email || '?').trim().charAt(0).toUpperCase();+ return (+ <View className="h-8 w-8 items-center justify-center rounded-full bg-brand/10">+ <Text className="text-[14px] font-semibold text-brand">{initial}</Text>+ </View>+ );+}diff --git a/openwhispr-mobile/src/components/notes/NoteShareSheet.tsx b/openwhispr-mobile/src/components/notes/NoteShareSheet.tsxindex 7d73f140a..28e519629 100644--- a/openwhispr-mobile/src/components/notes/NoteShareSheet.tsx+++ b/openwhispr-mobile/src/components/notes/NoteShareSheet.tsx@@ -4,23 +4,22 @@ import {ActivityIndicator,Alert,Modal,+ Pressable,ScrollView,- TextInput,View,- type TextStyle,+ useColorScheme,} from 'react-native';+import { MenuView, type MenuAction } from '@react-native-menu/menu';import { useRouter } from 'expo-router';import { useSafeAreaInsets } from 'react-native-safe-area-context';import { Text } from '@/components/ui/Text';import { GlassIconButton } from '@/components/ui/GlassIconButton';-import { SystemIcon } from '@/components/ui/SystemIcon';+import { SystemIcon, type LucideIconName } from '@/components/ui/SystemIcon';import { INVALID_EMAIL_ERROR, useNoteSharing } from '@/hooks/useNoteSharing';import { useSuperwallGate } from '@/hooks/useSuperwallGate';import { SUPERWALL_PLACEMENTS } from '@/lib/superwall';-import { AppFont } from '@/lib/fonts';import { confirmDestructive } from '@/lib/alerts';import { isValidEmail } from '@/lib/utils';-import { iosColor } from '@/config/colors';import { useConfigStore } from '@/store/useConfigStore';import { useNotesStore } from '@/store/useNotesStore';import { useUsageStore } from '@/store/useUsageStore';@@ -32,6 +31,9 @@ import { isScopeGrant } from '@/lib/notes/noteShareAccess';import type { ShareVisibility } from '@/data/remote/noteSharingTypes';import { GroupedList } from './GroupedList';import { NoteShareAccessList } from './NoteShareAccessList';+import { NoteShareInviteField } from './NoteShareInviteField';+import { ShareActionRow, ShareActionStrip } from './NoteShareActions';+import { RowIcon } from './NoteSharePrincipal';import { ShareTextButton } from './ShareTextButton';export interface NoteShareSheetProps {@@ -41,9 +43,6 @@ export interface NoteShareSheetProps {onExport: (format: 'md' | 'txt') => void;}-const PLACEHOLDER_COLOR = iosColor('tertiaryLabel');-const EMAIL_INPUT_STYLE: TextStyle = { fontFamily: AppFont.regular, borderCurve: 'continuous' };-const VISIBILITY_REACH: Record<ShareVisibility, number> = {private: 0,invited: 1,@@ -58,6 +57,35 @@ const VISIBILITY_LABEL: Record<ShareVisibility, string> = {invited: 'Invited people',};+const VISIBILITY_ICON: Record<ShareVisibility, [sfName: string, mdName: LucideIconName]> = {+ private: ['lock', 'Lock'],+ link: ['globe', 'Globe'],+ domain: ['building.2', 'Building2'],+ invited: ['person.2', 'Users'],+};++const VISIBILITY_CHOICES = ['link', 'domain', 'invited'] as const;+const VISIBILITY_ACTION_PREFIX = 'visibility:';+const REPLACE_LINK_ID = 'replace-link';+const DISABLE_SHARING_ID = 'disable-sharing';++function describeAccess(+ visibility: ShareVisibility | undefined,+ domains: string[],+ isTeamNote: boolean,+): string {+ switch (visibility) {+ case 'link':+ return 'Anyone with the link can view';+ case 'domain':+ return `Anyone at ${domains.join(', ')} with the link can view`;+ case 'invited':+ return 'Only people you add can open it';+ default:+ return isTeamNote ? 'Not shared outside this space' : 'Not shared with anyone';+ }+}+/** Announces each new message to VoiceOver. */function useAnnouncement(text: string | null): void {useEffect(() => {@@ -65,10 +93,57 @@ function useAnnouncement(text: string | null): void {}, [text]);}+/** Explanatory text as the first row of a card. */+function MessageRow({+ children,+ tone = 'secondary',+}: {+ children: ReactNode;+ tone?: 'secondary' | 'error';+}) {+ return (+ <GroupedList.Row>+ <Text+ accessibilityRole={tone === 'error' ? 'alert' : undefined}+ className={+ tone === 'error' ? 'text-[15px] text-systemRed' : 'text-[15px] text-secondaryLabel'+ }+ >+ {children}+ </Text>+ </GroupedList.Row>+ );+}++function LoadingRow({ label }: { label: string }) {+ return (+ <GroupedList.Row>+ <View className="flex-row items-center gap-2">+ <ActivityIndicator size="small" />+ <Text className="text-[15px] text-secondaryLabel">{label}</Text>+ </View>+ </GroupedList.Row>+ );+}++function SectionLabel({ children }: { children: string }) {+ return (+ <Text className="px-1 text-[13px] uppercase tracking-wider text-secondaryLabel">+ {children}+ </Text>+ );+}++/** Supporting text under a card, like a grouped list's section footer. */+function SectionFooter({ children }: { children: ReactNode }) {+ return <Text className="px-4 text-[12px] text-secondaryLabel">{children}</Text>;+}+export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: NoteShareSheetProps) {const sharing = useNoteSharing(noteId, onFlushDraft);const router = useRouter();const insets = useSafeAreaInsets();+ const scheme = useColorScheme();const cloudBackupEnabled = useConfigStore((state) => state.config?.cloudBackupEnabled ?? true);const setNotePrivacy = useNotesStore((state) => state.setNotePrivacy);const spaces = useNotesStore((state) => state.spaces);@@ -114,7 +189,11 @@ export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: Noteconst allowed = (target: ShareVisibility): boolean =>isShareVisibilityAllowed(sharing.sharingMode, target);const offered = (target: ShareVisibility): boolean => visibility === target || allowed(target);+ const linkManaged = Boolean(visibility && shared && canManage && allowed(visibility));+ const canAddPeople = canManage && !backupOff && allowed('invited');const scrollContentStyle = { paddingHorizontal: 24, paddingBottom: insets.bottom + 24, gap: 18 };+ // Hex literal: the native menu can't serialize PlatformColor.+ const menuIconColor = scheme === 'dark' ? 'rgba(255, 255, 255, 0.95)' : 'rgba(0, 0, 0, 0.85)';// Waiting for the upload can be abandoned; a sharing change in flight must finish to keep its link.const closable = !sharing.busy || sharing.cancellable;const close = (): void => {@@ -164,15 +243,6 @@ export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: Note);};- const modeButton = (target: ShareVisibility, label: string): ReactNode => (- <ShareTextButton- label={label}- selected={visibility === target}- disabled={sharing.busy}- onPress={() => changeVisibility(target)}- />- );-const enableCloudSync = (): void => {Alert.alert('Enable cloud sync?',@@ -243,12 +313,165 @@ export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: Note}).catch(() => {});};+ const accessMenu: MenuAction[] = [];+ if (canManage && !backupOff) {+ const choices = VISIBILITY_CHOICES.filter((target) =>+ target === 'domain' ? domainEligible && offered('domain') : offered(target),+ );+ if (choices.length > 0) {+ accessMenu.push({+ id: 'visibility',+ title: '',+ displayInline: true,+ subactions: choices.map((target) => ({+ id: `${VISIBILITY_ACTION_PREFIX}${target}`,+ title: target === 'invited' ? 'Invited people only' : VISIBILITY_LABEL[target],+ subtitle: target === 'domain' ? businessDomain : undefined,+ image: VISIBILITY_ICON[target][0],+ imageColor: menuIconColor,+ state: visibility === target ? 'on' : 'off',+ attributes: { disabled: sharing.busy },+ })),+ });+ }+ }+ const linkActions: MenuAction[] = [];+ if (linkManaged && !backupOff) {+ linkActions.push({+ id: REPLACE_LINK_ID,+ title: 'Replace link',+ image: 'arrow.triangle.2.circlepath',+ imageColor: menuIconColor,+ attributes: { disabled: sharing.busy },+ });+ }+ if (shared && canManage) {+ linkActions.push({+ id: DISABLE_SHARING_ID,+ title: 'Disable external sharing',+ image: 'lock',+ imageColor: '#FF3B30',+ attributes: { destructive: true, disabled: sharing.busy },+ });+ }+ if (linkActions.length > 0) {+ accessMenu.push({ id: 'link', title: '', displayInline: true, subactions: linkActions });+ }++ const pressAccessMenu = (id: string): void => {+ if (id === REPLACE_LINK_ID) replaceLink();+ else if (id === DISABLE_SHARING_ID) changeVisibility('private');+ else if (id.startsWith(VISIBILITY_ACTION_PREFIX))+ changeVisibility(id.slice(VISIBILITY_ACTION_PREFIX.length) as ShareVisibility);+ };++ const accessTitle =+ shared || !isTeamNote+ ? VISIBILITY_LABEL[visibility ?? 'private']+ : 'Everyone in this team space';+ const accessDetail = pausedAccess+ ? 'External sharing is off'+ : describeAccess(visibility, sharing.state?.share.domain_allowlist ?? [], isTeamNote);+ const [accessIcon, accessMdIcon] = VISIBILITY_ICON[shared && visibility ? visibility : 'private'];+ const accessRowContent = (+ <View className="flex-row items-center gap-3 px-4 py-3">+ <RowIcon name={accessIcon} mdName={accessMdIcon} tone="brand" />+ <View className="min-w-0 flex-1">+ <Text className="text-[15px] font-medium text-label">{accessTitle}</Text>+ <Text className="text-[12px] text-secondaryLabel">{accessDetail}</Text>+ </View>+ {accessMenu.length > 0 && (+ <SystemIcon+ name="chevron.up.chevron.down"+ mdName="ChevronsUpDown"+ size={13}+ color={sharing.busy ? 'quaternaryLabel' : 'tertiaryLabel'}+ />+ )}+ </View>+ );+ const accessRow =+ accessMenu.length > 0 ? (+ <MenuView+ actions={accessMenu}+ onPressAction={({ nativeEvent }) => pressAccessMenu(nativeEvent.event)}+ shouldOpenOnLongPress={false}+ >+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="General access"+ accessibilityValue={{ text: `${accessTitle}. ${accessDetail}` }}+ accessibilityHint="Changes who can open this note"+ className="active:bg-tertiarySystemFill"+ >+ {accessRowContent}+ </Pressable>+ </MenuView>+ ) : (+ <View accessible accessibilityLabel={`General access: ${accessTitle}. ${accessDetail}`}>+ {accessRowContent}+ </View>+ );++ let accessStrip: ReactNode = null;+ if (linkManaged && sharing.hasLink) {+ accessStrip = (+ <ShareActionStrip+ disabled={sharing.busy}+ actions={[+ {+ label: 'Copy link',+ icon: 'doc.on.doc',+ mdIcon: 'Copy',+ onPress: () => sharing.copyLink(),+ },+ {+ label: 'Share',+ accessibilityLabel: 'Share link',+ icon: 'square.and.arrow.up',+ mdIcon: 'Share',+ onPress: () => sharing.shareLink(),+ },+ {+ label: 'Open',+ accessibilityLabel: 'Open in browser',+ icon: 'safari',+ mdIcon: 'Compass',+ onPress: () => sharing.openLink(),+ },+ ]}+ />+ );+ } else if (linkManaged) {+ accessStrip = (+ <Text className="px-4 py-3 text-[13px] text-secondaryLabel">+ {backupOff+ ? 'The full link isn’t saved on this device.'+ : 'The full link isn’t saved on this device. Replace it to get a new one.'}+ </Text>+ );+ } else if (!shared && canManage && !backupOff && allowed('link')) {+ accessStrip = (+ <ShareActionStrip+ disabled={sharing.busy}+ actions={[+ {+ label: 'Create link',+ icon: 'link',+ mdIcon: 'Link',+ onPress: () => changeVisibility('link'),+ },+ ]}+ />+ );+ }+// In the sharing view, feedback sits next to the controls that trigger it rather than below the list.const feedback: ReactNode = (<>{sharing.error && !unknown && !(privateNote && note?.remoteId) && (- <View className="gap-1">- <Text accessibilityRole="alert" className="text-systemRed">+ <View className="gap-1 px-1">+ <Text accessibilityRole="alert" className="text-[13px] text-systemRed">{sharing.error}</Text><View className="flex-row flex-wrap gap-x-6">@@ -267,21 +490,36 @@ export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: Note</View>)}{privacyError && (- <Text accessibilityRole="alert" className="text-systemRed">+ <Text accessibilityRole="alert" className="px-1 text-[13px] text-systemRed">{privacyError}</Text>)}{sharing.message && (- <Text accessibilityRole="alert" className="text-secondaryLabel">+ <Text accessibilityRole="alert" className="px-1 text-[13px] text-secondaryLabel">{sharing.message}</Text>)}</>);- const sectionLabel = (label: string): ReactNode => (- <Text className="px-1 text-[13px] uppercase tracking-wider text-secondaryLabel">{label}</Text>- );+ const inviteField = canAddPeople ? (+ <NoteShareInviteField+ value={email}+ onChangeText={(value) => {+ setEmail(value);+ if (sharing.error === INVALID_EMAIL_ERROR) sharing.dismissError();+ }}+ onInvite={invite}+ remoteId={note?.remoteId ?? undefined}+ access={sharing.state?.access}+ invitations={sharing.state?.invitations}+ busy={sharing.busy}+ onAddPrincipal={(principal) => {+ setEmail('');+ resumeSharing(() => sharing.addPrincipal(principal));+ }}+ />+ ) : null;return (<Modal visible animationType="slide" presentationStyle="pageSheet" onRequestClose={close}>@@ -302,15 +540,15 @@ export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: NotecontentContainerStyle={scrollContentStyle}>{sharing.busy && (- <View className="flex-row items-center gap-2" accessibilityRole="alert">+ <View className="flex-row items-center gap-2 px-1" accessibilityRole="alert"><ActivityIndicator size="small" /><Text className="text-[13px] text-secondaryLabel">Updating sharing…</Text></View>)}{signedOut ? (- <View className="gap-3">- <Text className="text-secondaryLabel">Sign in to share this note online.</Text>- <ShareTextButton+ <GroupedList dividerInset={16}>+ <MessageRow>Sign in to share this note online.</MessageRow>+ <ShareActionRowlabel="Sign in"accessibilityLabel="Sign in to share"onPress={() => {@@ -318,39 +556,32 @@ export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: Noterouter.push('/auth');}}/>- </View>+ </GroupedList>) : localOnly ? (- <View className="gap-3">- <Text className="text-secondaryLabel">+ <GroupedList dividerInset={16}>+ <MessageRow>{backupOff? 'Cloud backup is off. Turn it on in Privacy & Data to share personal notes.': 'Enable cloud sync for this note before sharing.'}- </Text>+ </MessageRow>{note?.remoteId && !sharing.loading && (- <Text className="text-[13px] text-secondaryLabel">+ <MessageRow>{shared? 'A previous link may still be active.': 'Removal of a previous cloud copy may still be pending.'}- </Text>+ </MessageRow>)}{sharing.loading && note?.remoteId && (- <View className="flex-row items-center gap-2">- <ActivityIndicator size="small" />- <Text className="text-[13px] text-secondaryLabel">- Checking previous sharing…- </Text>- </View>+ <LoadingRow label="Checking previous sharing…" />+ )}+ {sharing.error && note?.remoteId && (+ <MessageRow tone="error">{sharing.error}</MessageRow>)}{sharing.error && note?.remoteId && (- <View className="gap-2">- <Text accessibilityRole="alert" className="text-systemRed">- {sharing.error}- </Text>- <ShareTextButton label="Retry" onPress={() => sharing.refresh()} />- </View>+ <ShareActionRow label="Retry" onPress={() => sharing.refresh()} />)}{canDisablePrevious && (- <ShareTextButton+ <ShareActionRowlabel="Disable previous link"destructivedisabled={sharing.busy || sharing.loading}@@ -358,217 +589,113 @@ export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: Note/>)}{backupOff ? (- <ShareTextButton+ <ShareActionRowlabel="Open privacy settings"disabled={sharing.busy}onPress={openPrivacySettings}/>) : (- <ShareTextButton+ <ShareActionRowlabel="Enable cloud sync"accessibilityLabel="Enable cloud sync for this note"disabled={sharing.busy}onPress={enableCloudSync}/>)}- </View>+ </GroupedList>) : upgradeRequired ? (- <View className="gap-3">- <Text className="text-secondaryLabel">+ <GroupedList dividerInset={16}>+ <MessageRow>Sharing uploads this note to your cloud account, which requires Pro.- </Text>- <ShareTextButton label="Upgrade to Pro" onPress={upgrade} />- </View>+ </MessageRow>+ <ShareActionRow label="Upgrade to Pro" onPress={upgrade} />+ </GroupedList>) : sharing.loading ? (- <View className="flex-row items-center gap-3 py-3">+ <View className="flex-row items-center gap-3 px-1 py-3"><ActivityIndicator /><Text className="text-secondaryLabel">Loading sharing settings…</Text></View>) : unknown ? (- <View className="gap-3">- <Text className="text-secondaryLabel">- {sharing.error || 'Sharing settings are unavailable.'}- </Text>- <ShareTextButton label="Retry" onPress={() => sharing.refresh()} />- </View>+ <GroupedList dividerInset={16}>+ <MessageRow>{sharing.error || 'Sharing settings are unavailable.'}</MessageRow>+ <ShareActionRow label="Retry" onPress={() => sharing.refresh()} />+ </GroupedList>) : (<>{backupOff && (- <View className="gap-1">- <Text className="text-secondaryLabel">+ <GroupedList dividerInset={16}>+ <MessageRow>Cloud backup is off. Turn it on in Privacy & Data to change who this note isshared with.- </Text>- <ShareTextButton+ </MessageRow>+ <ShareActionRowlabel="Open privacy settings"disabled={sharing.busy}onPress={openPrivacySettings}/>- </View>- )}- {sectionLabel('General access')}- <GroupedList dividerInset={16}>- <GroupedList.Row>- <Text className="text-[15px] font-medium text-label">- {shared || !isTeamNote- ? VISIBILITY_LABEL[visibility ?? 'private']- : 'Everyone in this team space'}- </Text>- {visibility === 'domain' && (- <Text className="text-[12px] text-secondaryLabel">- {sharing.state?.share.domain_allowlist.join(', ')}- </Text>- )}- </GroupedList.Row>- </GroupedList>- {canManage && !backupOff && (- <View className="gap-2">- {sharing.sharingMode === 'domain_only' && (- <Text className="text-[13px] text-secondaryLabel">- Your organization only allows sharing within your company domain.- </Text>- )}- {sharing.sharingMode === 'disabled' && (- <Text className="text-[13px] text-secondaryLabel">- Your organization does not allow sharing notes outside it.- </Text>- )}- {!shared && allowed('link') && (- <View>- <Text className="text-[13px] text-secondaryLabel">- Anyone with the link can view this note.- </Text>- <ShareTextButton- label="Create link"- disabled={sharing.busy}- onPress={() => changeVisibility('link')}- />- </View>- )}- <View className="flex-row flex-wrap gap-x-6">- {shared && offered('link') && modeButton('link', 'Anyone with link')}- {offered('invited') && modeButton('invited', 'Invited only')}- {domainEligible &&- offered('domain') &&- modeButton('domain', `Organization (${businessDomain})`)}- </View>- </View>- )}- {visibility && shared && canManage && allowed(visibility) && (- <View className="gap-2">- {sectionLabel('Link')}- {sharing.hasLink ? (- <View className="flex-row flex-wrap gap-x-6">- <ShareTextButton- label="Share link"- disabled={sharing.busy}- onPress={() => sharing.shareLink()}- />- <ShareTextButton- label="Copy link"- disabled={sharing.busy}- onPress={() => sharing.copyLink()}- />- <ShareTextButton- label="Open in browser"- disabled={sharing.busy}- onPress={() => sharing.openLink()}- />- </View>- ) : (- <Text className="text-[13px] text-secondaryLabel">- The full link is unavailable on this device.- </Text>- )}- {!backupOff && (- <ShareTextButton- label="Replace link"- disabled={sharing.busy}- onPress={replaceLink}- />- )}- </View>- )}- {canManage && !backupOff && allowed('invited') && (- <View className="gap-2">- {sectionLabel('Invite by email')}- <View className="flex-row items-center gap-2">- <TextInput- accessibilityLabel="Email address"- className="h-12 min-w-0 flex-1 rounded-[10px] bg-tertiarySystemFill px-3 text-[15px] text-label"- style={EMAIL_INPUT_STYLE}- placeholder="[email protected]"- placeholderTextColor={PLACEHOLDER_COLOR}- autoCapitalize="none"- autoCorrect={false}- autoComplete="email"- textContentType="emailAddress"- keyboardType="email-address"- returnKeyType="send"- value={email}- onChangeText={(value) => {- setEmail(value);- if (sharing.error === INVALID_EMAIL_ERROR) sharing.dismissError();- }}- onSubmitEditing={invite}- />- <ShareTextButton- label="Invite"- accessibilityLabel="Invite email"- disabled={sharing.busy || !email.trim()}- onPress={invite}- />- </View>- </View>+ </GroupedList>)}+ <View className="gap-2">+ <SectionLabel>General access</SectionLabel>+ <GroupedList dividerInset={0}>+ {accessRow}+ {accessStrip}+ </GroupedList>+ {canManage && !backupOff && sharing.sharingMode === 'domain_only' && (+ <SectionFooter>+ Your organization only allows sharing within your company domain.+ </SectionFooter>+ )}+ {canManage && !backupOff && sharing.sharingMode === 'disabled' && (+ <SectionFooter>+ Your organization does not allow sharing notes outside it.+ </SectionFooter>+ )}+ </View>{feedback}- {sharing.state && (+ {sharing.state ? (<NoteShareAccessListkey={`${sharing.user?.id}:${note?.remoteId}`}- remoteId={note?.remoteId ?? undefined}access={sharing.state.access}invitations={sharing.state.invitations}paused={visibility === 'private'}canInvite={allowed('invited')}busy={sharing.busy}- onAddPrincipal={- backupOff- ? undefined- : (principal) => resumeSharing(() => sharing.addPrincipal(principal))- }+ inviteField={inviteField}onUpdateGrant={(grant, permission) => sharing.updateGrant(grant, permission)}onRemoveGrant={(grant) => sharing.removeGrant(grant)}onRevokeInvitation={(invitation) => sharing.revokeInvitation(invitation)}onResendInvitation={(invitation) => sharing.resendInvitation(invitation)}/>- )}- {shared && canManage && (- <ShareTextButton- label="Disable external sharing"- destructive- disabled={sharing.busy}- onPress={() => changeVisibility('private')}- />+ ) : (+ inviteField && (+ <View className="gap-2">+ <SectionLabel>Invite people</SectionLabel>+ <GroupedList>{inviteField}</GroupedList>+ </View>+ ))}</>)}{!managed && feedback}<View className="gap-2">- {sectionLabel('Export')}- <GroupedList dividerInset={16}>+ <SectionLabel>Export</SectionLabel>+ <GroupedList><GroupedList.RowonPress={() => onExport('md')}accessibilityRole="button"accessibilityLabel="Export Markdown"+ leadingIconSlot={<RowIcon name="doc.richtext" mdName="FileCode" />}>- <Text className="text-[15px] text-label">Export Markdown</Text>+ <Text className="text-[15px] text-label">Markdown</Text></GroupedList.Row><GroupedList.RowonPress={() => onExport('txt')}accessibilityRole="button"accessibilityLabel="Export Plain Text"+ leadingIconSlot={<RowIcon name="doc.plaintext" mdName="FileText" />}>- <Text className="text-[15px] text-label">Export Plain Text</Text>+ <Text className="text-[15px] text-label">Plain text</Text></GroupedList.Row></GroupedList></View>diff --git a/openwhispr-mobile/src/components/notes/__tests__/NoteShareAccessList.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/NoteShareAccessList.test.tsxindex 0801bc1c9..068d622df 100644--- a/openwhispr-mobile/src/components/notes/__tests__/NoteShareAccessList.test.tsx+++ b/openwhispr-mobile/src/components/notes/__tests__/NoteShareAccessList.test.tsx@@ -1,13 +1,9 @@import { Alert, type AlertButton } from 'react-native';-import { act, fireEvent, render, waitFor } from '@testing-library/react-native';+import { fireEvent, render } from '@testing-library/react-native';import type { NoteAccessState, NoteShareInvitation } from '@/data/remote/noteSharingTypes';import { NoteShareAccessList } from '../NoteShareAccessList';-const mockSearch = jest.fn();-jest.mock('@/data/remote/noteSharingApi', () => ({- searchNoteAccessPrincipals: (...args: unknown[]) => mockSearch(...args),-}));-+jest.mock('@react-native-menu/menu', () => require('./menuViewMock'));jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));@@ -78,17 +74,23 @@ it('shows owner, grants, and pending invitations, and forwards permitted changes);expect(screen.getAllByText('Owner')).toHaveLength(2);expect(screen.getByText('Person')).toBeTruthy();- expect(screen.getByText('Viewer · Direct')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ expect(screen.getByLabelText('Change access for Person').props.accessibilityValue).toEqual({+ text: 'Viewer',+ });expect(screen.getByText('[email protected]')).toBeTruthy();- fireEvent.press(screen.getByLabelText('Make Person an editor'));+ fireEvent.press(screen.getByTestId('menu-grant-1:viewer'));+ expect(Alert.alert).not.toHaveBeenCalled();+ expect(updateGrant).not.toHaveBeenCalled();+ fireEvent.press(screen.getByTestId('menu-grant-1:editor'));expect(updateGrant).not.toHaveBeenCalled();confirmAlert('Make editor');expect(updateGrant).toHaveBeenCalledWith(access.grants[0], 'editor');- fireEvent.press(screen.getByLabelText('Revoke invitation for [email protected]'));+ fireEvent.press(screen.getByTestId('menu-invitation:inv-1:revoke'));expect(revokeInvitation).not.toHaveBeenCalled();confirmAlert('Cancel');expect(revokeInvitation).not.toHaveBeenCalled();- fireEvent.press(screen.getByLabelText('Revoke invitation for [email protected]'));+ fireEvent.press(screen.getByTestId('menu-invitation:inv-1:revoke'));confirmAlert('Revoke');expect(revokeInvitation).toHaveBeenCalledWith(invitation);});@@ -127,84 +129,13 @@ it('keeps inherited grants read-only and invitation actions visible beside invitonResendInvitation={jest.fn()}/>,);- expect(screen.queryByLabelText('Make Person an editor')).toBeNull();- expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();- expect(screen.getByLabelText('Make [email protected] an editor')).toBeTruthy();- expect(screen.getByLabelText('Resend invitation to [email protected]')).toBeTruthy();+ expect(screen.queryByLabelText('Change access for Person')).toBeNull();+ expect(screen.getByTestId('menu-invitation:inv-1:revoke')).toBeTruthy();+ expect(screen.getByTestId('menu-invitation:inv-1:editor')).toBeTruthy();+ expect(screen.getByTestId('menu-invitation:inv-1:resend')).toBeTruthy();expect(screen.queryByText('Pending Person')).toBeNull();});-it('searches principals and only offers grants allowed by server permissions', async () => {- jest.useFakeTimers();- mockSearch.mockResolvedValue({- suggestions: [- {- type: 'user',- id: 'user-2',- name: 'Jamie',- email: '[email protected]',- image: null,- member_count: null,- existing_grant_id: null,- },- {- type: 'team',- id: 'team-2',- name: 'Engineering',- email: null,- image: null,- member_count: 3,- existing_grant_id: null,- },- ],- });- const onAddPrincipal = jest.fn();- const screen = render(- <NoteShareAccessList- remoteId="remote-1"- access={access}- invitations={[]}- busy={false}- onAddPrincipal={onAddPrincipal}- onUpdateGrant={jest.fn()}- onRemoveGrant={jest.fn()}- onRevokeInvitation={jest.fn()}- onResendInvitation={jest.fn()}- />,- );- fireEvent.changeText(screen.getByLabelText('Find people or groups'), 'jam');- await act(async () => {- jest.advanceTimersByTime(350);- await Promise.resolve();- });- await waitFor(() => expect(screen.getByText('Jamie')).toBeTruthy());- expect(screen.queryByText('Engineering')).toBeNull();- fireEvent.press(screen.getByText('Jamie'));- expect(onAddPrincipal).toHaveBeenCalledWith(expect.objectContaining({ id: 'user-2' }));- onAddPrincipal.mockClear();- screen.rerender(- <NoteShareAccessList- remoteId="remote-1"- access={access}- invitations={[]}- busy- onAddPrincipal={onAddPrincipal}- onUpdateGrant={jest.fn()}- onRemoveGrant={jest.fn()}- onRevokeInvitation={jest.fn()}- onResendInvitation={jest.fn()}- />,- );- fireEvent.changeText(screen.getByLabelText('Find people or groups'), 'jam');- await act(async () => {- jest.advanceTimersByTime(350);- await Promise.resolve();- });- fireEvent.press(screen.getByText('Jamie'));- expect(onAddPrincipal).not.toHaveBeenCalled();- jest.useRealTimers();-});-const teamGrant = {...access.grants[0],id: 'grant-team',@@ -231,13 +162,13 @@ it.each([/>,);if (editable) {- expect(screen.getByText('Viewer · Team')).toBeTruthy();- fireEvent.press(screen.getByLabelText('Remove access for Design'));+ expect(screen.getByText('Team')).toBeTruthy();+ fireEvent.press(screen.getByTestId('menu-grant-team:remove'));expect(removeGrant).not.toHaveBeenCalled();confirmAlert('Remove');expect(removeGrant).toHaveBeenCalledWith(teamGrant);} else {- expect(screen.queryByLabelText('Remove access for Design')).toBeNull();+ expect(screen.queryByTestId('menu-grant-team:remove')).toBeNull();}},);@@ -256,7 +187,7 @@ it('marks direct access and invitations as paused while external sharing is off'/>,);expect(screen.getByText(/paused until you share this note again/i)).toBeTruthy();- expect(screen.getByText(/Viewer · Direct · Paused/)).toBeTruthy();+ expect(screen.getByText('[email protected] · Paused')).toBeTruthy();expect(screen.getByText(/Pending invitation · Paused/)).toBeTruthy();});@@ -281,8 +212,8 @@ it('stops offering Resend while sharing is paused, since the email could not opeonResendInvitation={jest.fn()}/>,);- expect(screen.queryByLabelText('Resend invitation to [email protected]')).toBeNull();- expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();+ expect(screen.queryByTestId('menu-invitation:inv-1:resend')).toBeNull();+ expect(screen.getByTestId('menu-invitation:inv-1:revoke')).toBeTruthy();});it('never marks team-space membership as paused', () => {@@ -298,29 +229,27 @@ it('never marks team-space membership as paused', () => {onResendInvitation={jest.fn()}/>,);- expect(screen.getByText('Viewer · Inherited from team space')).toBeTruthy();+ expect(screen.getByText('Inherited from team space')).toBeTruthy();+ expect(screen.queryByLabelText('Change access for Design space')).toBeNull();});it('keeps only removals when the organization blocks invitations', () => {const screen = render(<NoteShareAccessList- remoteId="remote"access={access}invitations={[invitation]}canInvite={false}busy={false}- onAddPrincipal={jest.fn()}onUpdateGrant={jest.fn()}onRemoveGrant={jest.fn()}onRevokeInvitation={jest.fn()}onResendInvitation={jest.fn()}/>,);- expect(screen.queryByLabelText('Find people or groups')).toBeNull();- expect(screen.queryByLabelText('Make Person an editor')).toBeNull();- expect(screen.queryByLabelText('Resend invitation to [email protected]')).toBeNull();- expect(screen.getByLabelText('Remove access for Person')).toBeTruthy();- expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();+ expect(screen.queryByTestId('menu-grant-1:editor')).toBeNull();+ expect(screen.queryByTestId('menu-invitation:inv-1:resend')).toBeNull();+ expect(screen.getByTestId('menu-grant-1:remove')).toBeTruthy();+ expect(screen.getByTestId('menu-invitation:inv-1:revoke')).toBeTruthy();});it('shows an invitation permission from the invitation itself', () => {@@ -335,10 +264,12 @@ it('shows an invitation permission from the invitation itself', () => {onResendInvitation={jest.fn()}/>,);- expect(screen.getByText('Pending invitation · Editor')).toBeTruthy();+ expect(+ screen.getByLabelText('Change access for [email protected]').props.accessibilityValue,+ ).toEqual({ text: 'Editor' });});-it('gives every action a 44pt touch target and greys it out while busy', () => {+it('gives every menu a 44pt touch target and greys out its actions while busy', () => {const screen = render(<NoteShareAccessListaccess={access}@@ -350,15 +281,20 @@ it('gives every action a 44pt touch target and greys it out while busy', () => {onResendInvitation={jest.fn()}/>,);- for (const label of [- 'Make Person an editor',- 'Remove access for Person',- 'Resend invitation to [email protected]',- 'Revoke invitation for [email protected]',+ for (const label of ['Change access for Person', 'Change access for [email protected]']) {+ const trigger = screen.getByLabelText(label);+ expect(trigger.props.className).toContain('min-h-[44px]');+ expect(trigger.props.accessibilityState).toMatchObject({ disabled: true });+ }+ for (const id of [+ 'grant-1:editor',+ 'grant-1:remove',+ 'invitation:inv-1:resend',+ 'invitation:inv-1:revoke',]) {- const button = screen.getByLabelText(label);- expect(button.props.className).toContain('min-h-[44px]');- expect(button.props.accessibilityState).toMatchObject({ disabled: true });+ expect(screen.getByTestId(`menu-${id}`).props.accessibilityState).toMatchObject({+ disabled: true,+ });}});@@ -394,9 +330,17 @@ it('still lets a manager reduce access when the organization blocks invitations'onResendInvitation={jest.fn()}/>,);- fireEvent.press(screen.getByLabelText('Change Person a viewer'));+ expect(screen.getByTestId('menu-grant-1:editor').props.accessibilityState).toMatchObject({+ selected: true,+ });+ fireEvent.press(screen.getByTestId('menu-grant-1:viewer'));+ expect(Alert.alert).not.toHaveBeenCalled();expect(updateGrant).toHaveBeenCalledWith(editorGrant, 'viewer');- expect(screen.getByLabelText('Make [email protected] a viewer')).toBeTruthy();+ fireEvent.press(screen.getByTestId('menu-invitation:inv-1:viewer'));+ expect(updateGrant).toHaveBeenLastCalledWith(+ expect.objectContaining({ id: 'invite:inv-1' }),+ 'viewer',+ );});/** VoiceOver can't focus an element inside another accessible element, so nested actions vanish. */@@ -407,7 +351,7 @@ function insideAccessibleElement(element: RenderedElement): boolean {}return false;}-it('leaves per-person actions reachable by VoiceOver', () => {+it('leaves per-person menus reachable by VoiceOver', () => {const screen = render(<NoteShareAccessListaccess={access}@@ -419,12 +363,23 @@ it('leaves per-person actions reachable by VoiceOver', () => {onResendInvitation={jest.fn()}/>,);- for (const label of [- 'Make Person an editor',- 'Remove access for Person',- 'Resend invitation to [email protected]',- 'Revoke invitation for [email protected]',- ]) {+ for (const label of ['Change access for Person', 'Change access for [email protected]']) {expect(insideAccessibleElement(screen.getByLabelText(label))).toBe(false);}});++it('gives a person without a name the initial of their email', () => {+ const screen = render(+ <NoteShareAccessList+ access={{ ...access, grants: [], owner: { ...owner, name: null, email: '[email protected]' } }}+ invitations={[]}+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.getByText('S')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+});diff --git a/openwhispr-mobile/src/components/notes/__tests__/NoteShareInviteField.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/NoteShareInviteField.test.tsxnew file mode 100644index 000000000..630c696e9--- /dev/null+++ b/openwhispr-mobile/src/components/notes/__tests__/NoteShareInviteField.test.tsx@@ -0,0 +1,199 @@+import { useState } from 'react';+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';+import type {+ AccessPrincipalSuggestion,+ NoteAccessState,+ NoteShareInvitation,+} from '@/data/remote/noteSharingTypes';+import { NoteShareInviteField } from '../NoteShareInviteField';++const mockSearch = jest.fn();+jest.mock('@/data/remote/noteSharingApi', () => ({+ searchNoteAccessPrincipals: (...args: unknown[]) => mockSearch(...args),+}));+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));++const owner = {+ type: 'user' as const,+ id: 'owner',+ email: '[email protected]',+ name: 'Owner',+ image: null,+ member_count: null,+};+const access: NoteAccessState = {+ owner,+ grants: [],+ my_permission: 'owner',+ can_manage_access: true,+ can_manage_inherited_access: false,+};+const jamie: AccessPrincipalSuggestion = {+ type: 'user',+ id: 'user-2',+ name: 'Jamie',+ email: '[email protected]',+ image: null,+ member_count: null,+ existing_grant_id: null,+};+const engineering: AccessPrincipalSuggestion = {+ type: 'team',+ id: 'team-2',+ name: 'Engineering',+ email: null,+ image: null,+ member_count: 3,+ existing_grant_id: null,+};++interface HarnessProps {+ remoteId?: string;+ invitations?: NoteShareInvitation[];+ busy?: boolean;+ onInvite?: () => void;+ onAddPrincipal?: (principal: AccessPrincipalSuggestion) => void;+}++function Harness({ remoteId, invitations, busy = false, onInvite, onAddPrincipal }: HarnessProps) {+ const [value, setValue] = useState('');+ return (+ <NoteShareInviteField+ value={value}+ onChangeText={setValue}+ onInvite={onInvite ?? jest.fn()}+ remoteId={remoteId}+ access={access}+ invitations={invitations}+ busy={busy}+ onAddPrincipal={onAddPrincipal}+ />+ );+}++async function settleSearch(): Promise<void> {+ await act(async () => {+ jest.advanceTimersByTime(350);+ await Promise.resolve();+ });+}++beforeEach(() => {+ mockSearch.mockReset();+ jest.useFakeTimers();+});++afterEach(() => {+ jest.useRealTimers();+});++it('searches principals and only offers grants allowed by server permissions', async () => {+ mockSearch.mockResolvedValue({ suggestions: [jamie, engineering] });+ const onAddPrincipal = jest.fn();+ const screen = render(<Harness remoteId="remote-1" onAddPrincipal={onAddPrincipal} />);+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), 'jam');+ await settleSearch();+ await waitFor(() => expect(screen.getByText('Jamie')).toBeTruthy());+ expect(screen.queryByText('Engineering')).toBeNull();+ fireEvent.press(screen.getByLabelText('Grant access to Jamie'));+ expect(onAddPrincipal).toHaveBeenCalledWith(expect.objectContaining({ id: 'user-2' }));+});++it('does not add anyone while an operation runs', async () => {+ mockSearch.mockResolvedValue({ suggestions: [jamie] });+ const onAddPrincipal = jest.fn();+ const screen = render(<Harness remoteId="remote-1" busy onAddPrincipal={onAddPrincipal} />);+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), 'jam');+ await settleSearch();+ await waitFor(() => expect(screen.getByText('Jamie')).toBeTruthy());+ fireEvent.press(screen.getByLabelText('Grant access to Jamie'));+ expect(onAddPrincipal).not.toHaveBeenCalled();+});++it('offers to invite a typed address, from a row or the return key', () => {+ const onInvite = jest.fn();+ const screen = render(+ <Harness remoteId="remote-1" onInvite={onInvite} onAddPrincipal={jest.fn()} />,+ );+ const input = screen.getByLabelText('Add people or emails');+ fireEvent.changeText(input, 'friend@');+ expect(screen.queryByLabelText('Invite friend@')).toBeNull();+ fireEvent.changeText(input, '[email protected]');+ fireEvent.press(screen.getByLabelText('Invite [email protected]'));+ fireEvent(input, 'submitEditing');+ expect(onInvite).toHaveBeenCalledTimes(2);+});++it('does not offer to invite someone who already has access', () => {+ const invitation: NoteShareInvitation = {+ id: 'inv-1',+ email: '[email protected]',+ invited_by_user_id: 'owner',+ permission: 'viewer',+ accepted_at: null,+ revoked_at: null,+ last_emailed_at: null,+ created_at: '',+ };+ const screen = render(+ <Harness remoteId="remote-1" invitations={[invitation]} onAddPrincipal={jest.fn()} />,+ );+ const input = screen.getByLabelText('Add people or emails');+ fireEvent.changeText(input, '[email protected]');+ expect(screen.queryByLabelText('Invite [email protected]')).toBeNull();+ fireEvent.changeText(input, '[email protected]');+ expect(screen.queryByLabelText('Invite [email protected]')).toBeNull();+});++it('prefers a matching account over a bare invitation', async () => {+ mockSearch.mockResolvedValue({ suggestions: [jamie] });+ const screen = render(<Harness remoteId="remote-1" onAddPrincipal={jest.fn()} />);+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), '[email protected]');+ await settleSearch();+ await waitFor(() => expect(screen.getByText('Jamie')).toBeTruthy());+ expect(screen.queryByLabelText('Invite [email protected]')).toBeNull();+});++it('only invites by email before the note has a cloud copy to search', async () => {+ const screen = render(<Harness onAddPrincipal={jest.fn()} />);+ fireEvent.changeText(screen.getByLabelText('Invite by email'), '[email protected]');+ await settleSearch();+ expect(mockSearch).not.toHaveBeenCalled();+ expect(screen.getByLabelText('Invite [email protected]')).toBeTruthy();+});++it('reports a failed search', async () => {+ mockSearch.mockRejectedValue(new Error('offline'));+ const screen = render(<Harness remoteId="remote-1" onAddPrincipal={jest.fn()} />);+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), 'jam');+ await settleSearch();+ await waitFor(() => expect(screen.getByText('Search unavailable. Try again.')).toBeTruthy());+});++it('still offers groups when an existing grant has no email', async () => {+ mockSearch.mockResolvedValue({ suggestions: [engineering] });+ const designGrant = {+ id: 'grant-team',+ principal: { ...owner, type: 'team' as const, id: 'team-1', email: null, name: 'Design' },+ permission: 'viewer' as const,+ source: 'team' as const,+ inherited: true,+ pending: false,+ created_at: '',+ updated_at: '',+ };+ const screen = render(+ <NoteShareInviteField+ value="eng"+ onChangeText={jest.fn()}+ onInvite={jest.fn()}+ remoteId="remote-1"+ access={{ ...access, can_manage_inherited_access: true, grants: [designGrant] }}+ busy={false}+ onAddPrincipal={jest.fn()}+ />,+ );+ await settleSearch();+ await waitFor(() => expect(screen.getByText('Engineering')).toBeTruthy());+});diff --git a/openwhispr-mobile/src/components/notes/__tests__/NoteShareSheet.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/NoteShareSheet.test.tsxindex 16937d2e0..d98a10bf2 100644--- a/openwhispr-mobile/src/components/notes/__tests__/NoteShareSheet.test.tsx+++ b/openwhispr-mobile/src/components/notes/__tests__/NoteShareSheet.test.tsx@@ -39,6 +39,7 @@ jest.mock('@/hooks/useNoteSharing', () => ({useNoteSharing: () => mockController,}));jest.mock('@/data/remote/noteSharingApi', () => ({ searchNoteAccessPrincipals: jest.fn() }));+jest.mock('@react-native-menu/menu', () => require('./menuViewMock'));jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));jest.mock('@/components/ui/GlassIconButton', () => ({@@ -148,17 +149,17 @@ beforeEach(() => {it('offers invited sharing and email invitation before a new note has a remote ID', () => {mockController.note = { ...mockController.note!, remoteId: null };const screen = render(<NoteShareSheet {...props} />);- fireEvent.press(screen.getByText('Invited only'));+ fireEvent.press(screen.getByTestId('menu-visibility:invited'));expect(mockController.setVisibility).toHaveBeenCalledWith('invited');- fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');- fireEvent.press(screen.getByLabelText('Invite email'));+ fireEvent.changeText(screen.getByLabelText('Invite by email'), '[email protected]');+ fireEvent.press(screen.getByLabelText('Invite [email protected]'));expect(mockController.inviteEmail).toHaveBeenCalledWith('[email protected]');});it('offers the owner business domain without making a new note public', () => {mockController.note = { ...mockController.note!, remoteId: null };const screen = render(<NoteShareSheet {...props} />);- fireEvent.press(screen.getByText('Organization (example.com)'));+ fireEvent.press(screen.getByTestId('menu-visibility:domain'));expect(mockController.setVisibility).toHaveBeenCalledWith('domain', ['example.com']);expect(mockController.setVisibility).not.toHaveBeenCalledWith('link');});@@ -248,14 +249,14 @@ it('keeps both exports available when sharing settings cannot load', () => {expect(screen.queryByText('Create link')).toBeNull();fireEvent.press(screen.getByText('Retry'));expect(mockController.refresh).toHaveBeenCalled();- fireEvent.press(screen.getByText('Export Markdown'));+ fireEvent.press(screen.getByLabelText('Export Markdown'));expect(props.onExport).toHaveBeenCalledWith('md');});it('creates public links only after an explicit tap', () => {mockController.state = { share, invitations: [], access };const screen = render(<NoteShareSheet {...props} />);- expect(screen.getByText('Anyone with the link can view this note.')).toBeTruthy();+ expect(screen.getByText('Not shared with anyone')).toBeTruthy();expect(mockController.setVisibility).not.toHaveBeenCalled();fireEvent.press(screen.getByText('Create link'));expect(mockController.setVisibility).toHaveBeenCalledWith('link');@@ -270,7 +271,7 @@ it('shows the actual invited setting and confirms replacement of an unavailableconst screen = render(<NoteShareSheet {...props} />);expect(screen.getByText('Invited people')).toBeTruthy();expect(screen.queryByText('Create link')).toBeNull();- fireEvent.press(screen.getByText('Replace link'));+ fireEvent.press(screen.getByTestId('menu-replace-link'));const buttons = (Alert.alert as jest.Mock).mock.calls[0][2];expect((Alert.alert as jest.Mock).mock.calls[0][1]).toContain('previous link will stop working');buttons[1].onPress();@@ -287,7 +288,7 @@ it('lets a manager replace a known link and shows a busy status', () => {mockController.busy = true;const screen = render(<NoteShareSheet {...props} />);expect(screen.getByText('Updating sharing…')).toBeTruthy();- expect(screen.getByText('Replace link')).toBeTruthy();+ expect(screen.getByTestId('menu-replace-link')).toBeTruthy();expect(screen.queryByLabelText('Close share sheet')).toBeNull();});@@ -312,9 +313,9 @@ it('hides link management actions when access cannot be managed', () => {};mockController.hasLink = true;const screen = render(<NoteShareSheet {...props} />);- expect(screen.queryByText('Share link')).toBeNull();- expect(screen.queryByText('Replace link')).toBeNull();- expect(screen.getByText('Export Markdown')).toBeTruthy();+ expect(screen.queryByLabelText('Share link')).toBeNull();+ expect(screen.queryByTestId('menu-replace-link')).toBeNull();+ expect(screen.getByLabelText('Export Markdown')).toBeTruthy();});it('allows legacy sharing revocation when the share endpoint authorizes access', () => {@@ -331,7 +332,7 @@ it('confirms before widening a restricted share to anyone with the link', () =>access,};const screen = render(<NoteShareSheet {...props} />);- fireEvent.press(screen.getByText('Anyone with link'));+ fireEvent.press(screen.getByTestId('menu-visibility:link'));expect(mockController.setVisibility).not.toHaveBeenCalled();const [title, , buttons] = (Alert.alert as jest.Mock).mock.calls[0];expect(title).toBe('Make this note public?');@@ -346,10 +347,10 @@ it('marks the current access mode as selected for assistive technology', () => {access,};const screen = render(<NoteShareSheet {...props} />);- expect(screen.getByLabelText('Invited only').props.accessibilityState).toMatchObject({+ expect(screen.getByTestId('menu-visibility:invited').props.accessibilityState).toMatchObject({selected: true,});- expect(screen.getByLabelText('Anyone with link').props.accessibilityState).toMatchObject({+ expect(screen.getByTestId('menu-visibility:link').props.accessibilityState).toMatchObject({selected: false,});});@@ -367,7 +368,7 @@ it('confirms before widening invited-only sharing to the organization', () => {access,};const screen = render(<NoteShareSheet {...props} />);- fireEvent.press(screen.getByText('Organization (example.com)'));+ fireEvent.press(screen.getByTestId('menu-visibility:domain'));expect(mockController.setVisibility).not.toHaveBeenCalled();const [title, , buttons] = (Alert.alert as jest.Mock).mock.calls[0];expect(title).toBe('Share with example.com?');@@ -382,7 +383,7 @@ it('narrows sharing without asking', () => {access,};const screen = render(<NoteShareSheet {...props} />);- fireEvent.press(screen.getByText('Invited only'));+ fireEvent.press(screen.getByTestId('menu-visibility:invited'));expect(Alert.alert).not.toHaveBeenCalled();expect(mockController.setVisibility).toHaveBeenCalledWith('invited');});@@ -406,7 +407,7 @@ it('warns that replacing a link breaks links in invitation emails', () => {access,};const screen = render(<NoteShareSheet {...props} />);- fireEvent.press(screen.getByText('Replace link'));+ fireEvent.press(screen.getByTestId('menu-replace-link'));expect((Alert.alert as jest.Mock).mock.calls[0][1]).toMatch(/invitation emails/i);});@@ -414,16 +415,16 @@ it('clears the email field only after a confirmed invitation', async () => {jest.mocked(mockController.inviteEmail).mockResolvedValueOnce(false).mockResolvedValueOnce(true);mockController.state = { share, invitations: [], access };const screen = render(<NoteShareSheet {...props} />);- const input = screen.getByLabelText('Email address');+ const input = screen.getByLabelText('Add people or emails');fireEvent.changeText(input, '[email protected]');await act(async () => {- fireEvent.press(screen.getByLabelText('Invite email'));+ fireEvent.press(screen.getByLabelText('Invite [email protected]'));});- expect(screen.getByLabelText('Email address').props.value).toBe('[email protected]');+ expect(screen.getByLabelText('Add people or emails').props.value).toBe('[email protected]');await act(async () => {- fireEvent.press(screen.getByLabelText('Invite email'));+ fireEvent.press(screen.getByLabelText('Invite [email protected]'));});- expect(screen.getByLabelText('Email address').props.value).toBe('');+ expect(screen.getByLabelText('Add people or emails').props.value).toBe('');});it('can be closed while the note is still uploading, but not while sharing is saved', () => {@@ -452,9 +453,9 @@ it('offers only domain sharing under a domain-only organization policy', () => {const screen = render(<NoteShareSheet {...props} />);expect(screen.getByText(/only allows sharing within your company/i)).toBeTruthy();expect(screen.queryByText('Create link')).toBeNull();- expect(screen.queryByText('Invited only')).toBeNull();- expect(screen.queryByLabelText('Email address')).toBeNull();- fireEvent.press(screen.getByText('Organization (company.com)'));+ expect(screen.queryByTestId('menu-visibility:invited')).toBeNull();+ expect(screen.queryByLabelText('Add people or emails')).toBeNull();+ fireEvent.press(screen.getByTestId('menu-visibility:domain'));expect(mockController.setVisibility).toHaveBeenCalledWith('domain', ['company.com']);});@@ -468,10 +469,10 @@ it('keeps only disabling when the organization does not allow external sharing',};const screen = render(<NoteShareSheet {...props} />);expect(screen.getByText(/does not allow sharing notes outside/i)).toBeTruthy();- expect(screen.queryByText('Invited only')).toBeNull();+ expect(screen.queryByTestId('menu-visibility:invited')).toBeNull();expect(screen.queryByText('Copy link')).toBeNull();- expect(screen.queryByText('Replace link')).toBeNull();- expect(screen.getByText('Disable external sharing')).toBeTruthy();+ expect(screen.queryByTestId('menu-replace-link')).toBeNull();+ expect(screen.getByTestId('menu-disable-sharing')).toBeTruthy();});it('offers an upgrade before uploading a personal note without a subscription', () => {@@ -494,9 +495,12 @@ it('greys out link actions while an operation runs', () => {access,};const screen = render(<NoteShareSheet {...props} />);- for (const label of ['Share link', 'Copy link', 'Open in browser', 'Replace link']) {+ for (const label of ['Share link', 'Copy link', 'Open in browser']) {expect(screen.getByLabelText(label).props.accessibilityState).toMatchObject({ disabled: true });}+ expect(screen.getByTestId('menu-replace-link').props.accessibilityState).toMatchObject({+ disabled: true,+ });});it('keeps the sheet open while a previous link is being disabled', () => {@@ -526,13 +530,13 @@ it('keeps existing sharing manageable but blocks uploads while cloud backup is oexpect(screen.getByText(/Cloud backup is off\. Turn it on in Privacy & Data/)).toBeTruthy();expect(screen.getByText('Open privacy settings')).toBeTruthy();expect(screen.getByText('[email protected]')).toBeTruthy();- expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();+ expect(screen.getByTestId('menu-invitation:inv-1:revoke')).toBeTruthy();expect(screen.getByText('Copy link')).toBeTruthy();- expect(screen.queryByText('Invite by email')).toBeNull();- expect(screen.queryByText('Replace link')).toBeNull();- expect(screen.queryByText('Invited only')).toBeNull();- expect(screen.queryByLabelText('Find people or groups')).toBeNull();- fireEvent.press(screen.getByText('Disable external sharing'));+ expect(screen.queryByLabelText('Invite by email')).toBeNull();+ expect(screen.queryByTestId('menu-replace-link')).toBeNull();+ expect(screen.queryByTestId('menu-visibility:invited')).toBeNull();+ expect(screen.queryByLabelText('Add people or emails')).toBeNull();+ fireEvent.press(screen.getByTestId('menu-disable-sharing'));const buttons = (Alert.alert as jest.Mock).mock.calls[0][2];buttons[1].onPress();expect(mockController.setVisibility).toHaveBeenCalledWith('private');@@ -545,7 +549,7 @@ it('points a never-uploaded personal note at privacy settings while cloud backupexpect(screen.getByText(/Cloud backup is off/)).toBeTruthy();expect(screen.getByText('Open privacy settings')).toBeTruthy();expect(screen.queryByText('Create link')).toBeNull();- expect(screen.queryByText('Invite by email')).toBeNull();+ expect(screen.queryByLabelText('Invite by email')).toBeNull();});it('marks the sheet title as a heading', () => {@@ -571,7 +575,7 @@ it('shows errors beside the controls with a way to refresh', () => {expect(screen.queryByText('Upgrade to Pro')).toBeNull();fireEvent.press(screen.getByLabelText('Refresh sharing settings'));expect(mockController.refresh).toHaveBeenCalled();- fireEvent.changeText(screen.getByLabelText('Email address'), 'friend@');+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), 'friend@');expect(mockController.dismissError).not.toHaveBeenCalled();});@@ -579,7 +583,7 @@ it('clears an invalid email error once the address is edited', () => {mockController.state = { share, invitations: [], access };mockController.error = INVALID_EMAIL_ERROR;const screen = render(<NoteShareSheet {...props} />);- fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), '[email protected]');expect(mockController.dismissError).toHaveBeenCalled();});@@ -607,13 +611,13 @@ it('keeps the controls while an operation loads settings after the first upload'const screen = render(<NoteShareSheet {...props} />);expect(screen.queryByText('Sharing settings are unavailable.')).toBeNull();expect(screen.queryByText('Retry')).toBeNull();- expect(screen.getByLabelText('Email address')).toBeTruthy();+ expect(screen.getByLabelText('Invite by email')).toBeTruthy();});it('asks before an invitation turns paused sharing back on', () => {mockController.state = { share, invitations: [], access: { ...access, grants: [pausedGrant] } };const screen = render(<NoteShareSheet {...props} />);- fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');- fireEvent.press(screen.getByLabelText('Invite email'));+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), '[email protected]');+ fireEvent.press(screen.getByLabelText('Invite [email protected]'));expect(mockController.inviteEmail).not.toHaveBeenCalled();const [title, message, buttons] = (Alert.alert as jest.Mock).mock.calls[0];expect(title).toBe('Turn sharing back on?');@@ -624,8 +628,8 @@ it('asks before an invitation turns paused sharing back on', () => {it('reports an invalid address on a paused share without asking first', () => {mockController.state = { share, invitations: [], access: { ...access, grants: [pausedGrant] } };const screen = render(<NoteShareSheet {...props} />);- fireEvent.changeText(screen.getByLabelText('Email address'), 'not-an-email');- fireEvent.press(screen.getByLabelText('Invite email'));+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), 'not-an-email');+ fireEvent(screen.getByLabelText('Add people or emails'), 'submitEditing');expect(Alert.alert).not.toHaveBeenCalled();expect(mockController.inviteEmail).toHaveBeenCalledWith('not-an-email');});@@ -633,8 +637,8 @@ it('invites without asking when no access is paused', () => {const inherited = { ...pausedGrant, id: 'scope:space-1', inherited: true };mockController.state = { share, invitations: [], access: { ...access, grants: [inherited] } };const screen = render(<NoteShareSheet {...props} />);- fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');- fireEvent.press(screen.getByLabelText('Invite email'));+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), '[email protected]');+ fireEvent.press(screen.getByLabelText('Invite [email protected]'));expect(Alert.alert).not.toHaveBeenCalled();expect(mockController.inviteEmail).toHaveBeenCalledWith('[email protected]');});@@ -654,7 +658,7 @@ it('asks before adding someone turns paused sharing back on', async () => {});mockController.state = { share, invitations: [], access: { ...access, grants: [pausedGrant] } };const screen = render(<NoteShareSheet {...props} />);- fireEvent.changeText(screen.getByLabelText('Find people or groups'), 'ril');+ fireEvent.changeText(screen.getByLabelText('Add people or emails'), 'ril');await waitFor(() => expect(screen.getByText('Riley')).toBeTruthy());fireEvent.press(screen.getByText('Riley'));expect(mockController.addPrincipal).not.toHaveBeenCalled();diff --git a/openwhispr-mobile/src/components/notes/__tests__/menuViewMock.tsx b/openwhispr-mobile/src/components/notes/__tests__/menuViewMock.tsxnew file mode 100644index 000000000..d72d4b4e4--- /dev/null+++ b/openwhispr-mobile/src/components/notes/__tests__/menuViewMock.tsx@@ -0,0 +1,37 @@+import type { ReactNode } from 'react';+import { Pressable, Text, View } from 'react-native';+import type { MenuAction } from '@react-native-menu/menu';++function flatten(actions: MenuAction[]): MenuAction[] {+ return actions.flatMap((action) => (action.subactions ? flatten(action.subactions) : [action]));+}++/** Renders every menu action inline, so tests press them as `menu-<id>`. */+export function MenuView({+ actions,+ onPressAction,+ children,+}: {+ actions: MenuAction[];+ onPressAction: (event: { nativeEvent: { event: string } }) => void;+ children?: ReactNode;+}) {+ return (+ <View>+ {children}+ {flatten(actions).map((action) => (+ <Pressable+ key={action.id}+ testID={`menu-${action.id}`}+ accessibilityState={{+ disabled: Boolean(action.attributes?.disabled),+ selected: action.state === 'on',+ }}+ onPress={() => onPressAction({ nativeEvent: { event: action.id ?? '' } })}+ >+ <Text>{action.title}</Text>+ </Pressable>+ ))}+ </View>+ );+}