Contacts

The phone's address book, from the contacts plugin: the system's contact picker, reading the contacts, and adding or editing one through the system's own screens. To let the user choose a person, use Contacts.pick() — it needs no permission; Contacts.list() reads the whole address book and asks the contacts permission.

  • let the user choose a contact and get the phone number or email
  • invite friends: pick several contacts
  • show the user's contacts in a list, search them by name
  • show a contact's photo
  • ask for the contacts permission, handle a refusal
  • work with the contacts the user selected on iOS ("limited access")
  • save a new contact to the address book
  • open a contact's card to edit or delete it
  • refresh the list when the address book changes

Platforms: iOS, Android; on the web only pick(), in a browser that has a contact picker (Chrome on Android); not on desktop or in headless tests — check Contacts.supported.

At a glance

TypeScript
// app.json: "plugins": { "contacts": "*" }
const chosen = signal('Nobody chosen')

const choose = async () => {
  try {
    const [person] = await Contacts.pick({ fields: ['phones'] })    // the system's picker, no permission
    if (!person) return                                              // closed without choosing
    chosen.value = `${person.name}: ${person.phones?.[0]?.number ?? 'no number'}`
  } catch (e) {
    toast(e.message === 'unavailable' ? 'Contacts are not available here' : 'Could not open the contacts')
  }
}

Router.init(UIScreen(
  UIText(() => chosen.value),
  UIButton(UIText('Choose a contact')).onClick(choose),
).style({ p: 20, pt: 'safe-top', gap: 16 }))

Add the contacts plugin to the app: app.json

The address book is the contacts plugin: list it in the project's app.json — "plugins": { "contacts": "*" }. The list is one for every platform: a plugin it does not name is not there, and the compile warns about one the app uses and does not list. The plugin brings what the platforms need declared: the iOS usage text (NSContactsUsageDescription) and Android's READ_CONTACTS. It declares no write permission — a contact is written by the system's own editor (below). The le.codes viewer app has the plugin from the release that carries it; an older viewer answers Contacts.supported === false.

Let the user choose a contact: Contacts.pick

TypeScript
Contacts.pick(options?: {
  fields?: ContactField[]      // what the picked contacts carry beyond their names; default: nothing
  multiple?: boolean           // let the user choose several; default false
}): Promise<Contact[]>         // what was chosen; [] when the picker was closed without a choice

type ContactField = 'phones' | 'emails' | 'addresses' | 'organization' | 'birthday' | 'urls'

pick opens the system's contact picker. The app gets the contacts the user chose and nothing else, so there is no permission and no dialog. It rejects "unavailable" where there is no picker (also every host without the plugin), "busy" while another screen of the plugin is up, and "failed" when the picker could not be shown.

TypeScript
const invited = signal<string[]>([])

const invite = async () => {
  const people = await Contacts.pick({ fields: ['emails'], multiple: true }).catch(() => [])
  invited.value = people.flatMap(p => p.emails?.map(e => e.address) ?? [])
}

UIColumn(
  UIButton(UIText('Invite friends')).onClick(invite),
  UIText(() => invited.value.join(', ')),
).style({ gap: 12 })
Note

Android before 17 has a picker of ONE contact, whatever multiple says, and it hands over one kind of data. Without the contacts permission the picked contact carries the first of phones / emails / addresses asked — the one number or address the user tapped — and the other fields empty; ask for one field per pick there. With the permission granted it carries every field asked. Android 17 and iOS pick several contacts with every field.

Note

on the web a picked contact has no id (""), no name parts and no photo, and urls, organization and birthday are not handed over.

What a contact holds: Contact

TypeScript
interface Contact {
  id: string                    // this device's id of the contact: what get(), photo() and openCard() take
  name: string                  // as the device shows it; '' for a contact without a name
  givenName: string | null
  familyName: string | null
  middleName: string | null
  nickname: string | null
  hasPhoto: boolean             // photo() has a picture to give
  phones?: { label?: string, number: string }[]      // the number as typed, not normalized
  emails?: { label?: string, address: string }[]
  addresses?: { label?: string, street?: string, city?: string, region?: string, postalCode?: string, country?: string }[]
  urls?: { label?: string, url: string }[]
  organization?: { company?: string, title?: string }
  birthday?: { year?: number, month: number, day: number }   // month 1..12; no year when the person gave none
}

The name parts always come. Everything else is asked for with fields, so a big address book is cheap to list by name: a list that was asked for is present (empty when the contact has none) and absent when it was not asked; organization and birthday are absent when not asked or when the contact has none. A label is "mobile", "home", "work", "main", "other" (a url's also "homepage"), or the user's own label; absent when there is none. Phone numbers come as the user typed them — "+1 (555) 010-9999", "8 800 555 35 35" — compare them after stripping what is not a digit. An id is this device's: it is not the same contact's id on another phone.

Show the user's contacts, search by name: Contacts.list

TypeScript
Contacts.list(options?: {
  fields?: ContactField[]      // default: nothing beyond the names
  query?: string               // only the contacts whose name matches (the platform's own search)
}): Promise<Contact[]>         // sorted by name

list reads the address book. The first call shows the OS permission dialog; a refusal rejects "denied". It rejects "unavailable" on the web and on every host without the plugin.

TypeScript
const people = signal<Contact[]>([])
const note = signal('')

const load = (query?: string) => Contacts.list({ fields: ['phones'], query })
  .then(list => { people.value = list; note.value = list.length ? '' : 'No contacts' })
  .catch(e => { note.value = e.message === 'denied' ? 'Contacts are off for this app' : 'Contacts are not available' })

Router.init(UIScreen(
  UIInput().style({ placeholder: 'Search' }).onChange(text => load(text)),
  UIText(() => note.value),
  UIScrollable(
    UIColumn(() => people.value.map(p =>
      UIText(`${p.name}  ${p.phones?.[0]?.number ?? ''}`))).style({ gap: 8 }),
  ).style({ flex: 1 }),
).style({ p: 20, pt: 'safe-top', gap: 12 }))
load()

One contact and its photo: Contacts.get, Contacts.photo

TypeScript
Contacts.get(id: string, fields?: ContactField[]): Promise<Contact | null>    // null: no such contact
Contacts.photo(id: string, size?: 'thumbnail' | 'full'): Promise<File | null> // default 'thumbnail'; null: no picture

Both are behind the contacts permission, like list. get answers null for a contact that was deleted — and, with iOS's limited access, for one the app may not read. photo resolves with a File (a JPEG or PNG, as stored): an image's source, an upload, a share. Ask for the thumbnail in a list and the full picture on a contact's own screen.

TypeScript
const avatar = UIBox().style({ width: 64, height: 64, borderRadius: 32, bgColor: '#ddd' })

const showAvatar = async (person: Contact) => {
  if (!person.hasPhoto) return
  const file = await Contacts.photo(person.id).catch(() => null)
  if (file) avatar.setContent([UIImage(file).style({ width: 64, height: 64, borderRadius: 32 })])
}

The contacts permission, a refusal, iOS's limited access: Contacts.limited

TypeScript
permissions.query('contacts'): Promise<'granted' | 'denied' | 'prompt'>   // the state, never a dialog
permissions.request('contacts'): Promise<'granted' | 'denied' | 'prompt'> // ask now
Contacts.limited(): Promise<boolean>                // iOS 18+: the user gave the app SOME contacts
Contacts.manageLimitedAccess(): Promise<void>       // iOS 18+: change which contacts the app may read

The contacts permission is asked and read like every other one, through permissions (permissions.md): the OS asks at the first list / get / photo / openCard, or when the app calls permissions.request('contacts'); pick and openEditor never ask. After a refusal iOS never asks again — permissions.openSettings() opens the app's page of the system settings.

On iOS 18 and later the user may give the app only SOME contacts. The permission still reads "granted" and the reads go through: list answers with the chosen contacts only, and Contacts.limited() says so. manageLimitedAccess() shows the system's sheet where the user changes the selection; it resolves when the sheet closes. On Android, on the web and on a host without the plugin limited() is false and manageLimitedAccess() resolves at once.

TypeScript
const state = signal('')
const partial = signal(false)

const refresh = async () => {
  state.value = await permissions.query('contacts')
  partial.value = await Contacts.limited()
}
refresh()

UIColumn(() => [
  state.value === 'denied'
    ? UIButton(UIText('Turn contacts on in Settings')).onClick(() => permissions.openSettings())
    : partial.value
      ? UIButton(UIText('Choose more contacts')).onClick(() => Contacts.manageLimitedAccess().then(refresh))
      : UIText(state.value === 'granted' ? 'All contacts' : 'Not asked yet'),
])
Note

permissions.query('contacts') says whether a dialog stands between the app and the address book, not whether there is one: where the plugin is absent it answers "granted", and Contacts.supported is the answer to "can I read contacts here".

Save a new contact: the system's editor, Contacts.openEditor

TypeScript
Contacts.openEditor(draft: {
  givenName?: string, familyName?: string, middleName?: string, nickname?: string
  phones?: { label?: string, number: string }[]
  emails?: { label?: string, address: string }[]
  addresses?: { label?: string, street?: string, city?: string, region?: string, postalCode?: string, country?: string }[]
  urls?: { label?: string, url: string }[]
  organization?: { company?: string, title?: string }
  birthday?: { year?: number, month: number, day: number }
}): Promise<boolean>           // true: the user saved the contact; false: they left without saving

openEditor opens the system's "new contact" editor filled from the draft; the user may change anything and saves it themselves. One call is one editor on screen: the app writes nothing on its own, so there is no write permission and no dialog — the editor saves even when the app may not read the contacts. There is no call that creates, changes or deletes a contact without the user, and none that adds several at once. It rejects "unavailable" (no contacts app, a host without the plugin), "busy", "failed".

TypeScript
const saveSupport = async () => {
  const saved = await Contacts.openEditor({
    givenName: 'Acme', familyName: 'Support',
    phones: [{ label: 'work', number: '+1 555 010 9999' }],
    emails: [{ label: 'work', address: 'help@acme.example' }],
  }).catch(() => false)
  toast(saved ? 'Saved to your contacts' : 'Not saved')
}

UIButton(UIText('Add us to your contacts')).onClick(saveSupport)
Note

on Android the editor is the phone's contacts app, and true is what it reports: an app that saves without saying so answers false. Where two apps can add a contact, Android first asks the user which one to use.

Open a contact's card to edit or delete it: Contacts.openCard

TypeScript
Contacts.openCard(id: string): Promise<void>     // resolves when the card closes

openCard opens the system's card of a contact — where the user calls, edits or deletes it. It is behind the contacts permission (it opens a contact the app read). It rejects "notFound" for an id that is no contact (also the "" of a web pick), and "denied", "busy", "unavailable", "failed". Whether anything was changed in the card is what onChange says.

TypeScript
const openCard = (person: Contact) => Contacts.openCard(person.id)
  .catch(e => toast(e.message === 'notFound' ? 'This contact is gone' : 'Could not open the contact'))

Refresh when the address book changes: Contacts.onChange

TypeScript
Contacts.onChange(listener: () => void): () => void   // returns a function that stops listening

The listener runs when a contact is added, edited or deleted — by this app's openEditor / openCard screens, by the user in the contacts app, by a sync — and on iOS when the user changes the selection in manageLimitedAccess(). It carries nothing: read the list again. It is heard from the app's first call to the plugin on (the list it refreshes), while the app may read the address book, and never on a host without the plugin.

TypeScript
const names = signal<string[]>([])
const reload = () => Contacts.list().then(list => { names.value = list.map(c => c.name) }).catch(() => {})

const screen = UIScreen(UIColumn(() => names.value.map(n => UIText(n))))
const stop = Contacts.onChange(reload)
screen.onClose(stop)
reload()

Where it works, and why a call failed: Contacts.supported, the codes

TypeScript
Contacts.supported: boolean     // this host registered the "contacts" service

supported is false on desktop, in headless tests, in a browser without a contact picker and in a shell built without the plugin. Nothing throws there: limited() answers false, manageLimitedAccess() does nothing, and every other call rejects "unavailable". A call rejects with a code as e.message:

code when
"denied" the user refused the contacts permission, now or earlier (list, get, photo, openCard)
"unavailable" no address book here: a host without the plugin; on the web every call but pick; a device with no contacts app
"busy" a screen of the plugin is already up (a picker, an editor, a card)
"notFound" openCard: no contact has that id
"failed" the screen could not be shown (the app is in the background), or a read failed
TypeScript
UIColumn(() => [Contacts.supported
  ? UIButton(UIText('Choose a contact')).onClick(() => Contacts.pick().catch(e => toast(e.message)))
  : UIText('Contacts are not available on this device')])

See also