@octane-xplat/contacts 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/contacts.ts CHANGED
@@ -6,13 +6,13 @@ import { Application } from '@nativescript/core'
6
6
  import { Contact as NativeContact, Contacts as NativeContacts } from '@nativescript/contacts'
7
7
  import { android } from '@octane-xplat/platform/android'
8
8
  import type {
9
- Contact,
10
- ContactAddress,
11
- ContactField,
12
- Contacts,
13
- GetContactsOptions,
14
- NewContact,
15
- PermissionResult,
9
+ Contact,
10
+ ContactAddress,
11
+ ContactField,
12
+ Contacts,
13
+ GetContactsOptions,
14
+ NewContact,
15
+ PermissionResult,
16
16
  } from './types'
17
17
 
18
18
  // iOS CNContactStore — outside the @nativescript/types default subset.
@@ -20,235 +20,266 @@ declare const CNContactStore: any
20
20
  declare const CNEntityTypeContacts: number | undefined
21
21
 
22
22
  const ALL_FIELDS: ContactField[] = [
23
- 'name',
24
- 'emails',
25
- 'phoneNumbers',
26
- 'addresses',
27
- 'urls',
28
- 'company',
29
- 'note',
30
- 'image',
31
- 'nickname',
23
+ 'name',
24
+ 'emails',
25
+ 'phoneNumbers',
26
+ 'addresses',
27
+ 'urls',
28
+ 'company',
29
+ 'note',
30
+ 'image',
31
+ 'nickname',
32
32
  ]
33
33
 
34
34
  // Our field names → the plugin's contactFields vocabulary.
35
35
  const PLUGIN_FIELDS: Record<ContactField, string> = {
36
- name: 'name',
37
- emails: 'emailAddresses',
38
- phoneNumbers: 'phoneNumbers',
39
- addresses: 'postalAddresses',
40
- urls: 'urls',
41
- company: 'organization',
42
- note: 'notes',
43
- image: 'photo',
44
- nickname: 'nickname',
36
+ name: 'name',
37
+ emails: 'emailAddresses',
38
+ phoneNumbers: 'phoneNumbers',
39
+ addresses: 'postalAddresses',
40
+ urls: 'urls',
41
+ company: 'organization',
42
+ note: 'notes',
43
+ image: 'photo',
44
+ nickname: 'nickname',
45
45
  }
46
46
 
47
47
  function pluginFields(fields?: ContactField[]): string[] {
48
- const wanted = fields ?? ALL_FIELDS
49
- const mapped = wanted.map((f) => PLUGIN_FIELDS[f])
50
- // The plugin reads `name` for the display string regardless of selection.
51
- if (!mapped.includes('name')) {
52
- mapped.push('name')
53
- }
54
- return mapped
48
+ const wanted = fields ?? ALL_FIELDS
49
+ const mapped = wanted.map((f) => PLUGIN_FIELDS[f])
50
+
51
+ // The plugin reads `name` for the display string regardless of selection.
52
+ if (!mapped.includes('name')) {
53
+ mapped.push('name')
54
+ }
55
+
56
+ return mapped
55
57
  }
56
58
 
57
59
  function iosEnsure(): Promise<PermissionResult> {
58
- const store = typeof CNContactStore === 'undefined' ? null : CNContactStore.new?.()
59
- if (!store || typeof CNEntityTypeContacts === 'undefined') {
60
- return Promise.resolve('unsupported')
61
- }
62
- // CNAuthorizationStatus: 0 notDetermined, 1 restricted, 2 denied, 3 authorized
63
- const status = CNContactStore.authorizationStatusForEntityType(CNEntityTypeContacts)
64
- if (status === 3) {
65
- return Promise.resolve('granted')
66
- }
67
- if (status === 1 || status === 2) {
68
- return Promise.resolve('denied')
69
- }
70
- return new Promise((resolve) => {
71
- store.requestAccessForEntityTypeCompletionHandler(CNEntityTypeContacts, (granted: boolean) =>
72
- resolve(granted ? 'granted' : 'denied'),
73
- )
74
- })
60
+ const store = typeof CNContactStore === 'undefined' ? null : CNContactStore.new?.()
61
+
62
+ if (!store || typeof CNEntityTypeContacts === 'undefined') {
63
+ return Promise.resolve('unsupported')
64
+ }
65
+
66
+ // CNAuthorizationStatus: 0 notDetermined, 1 restricted, 2 denied, 3 authorized
67
+ const status = CNContactStore.authorizationStatusForEntityType(CNEntityTypeContacts)
68
+
69
+ if (status === 3) {
70
+ return Promise.resolve('granted')
71
+ }
72
+
73
+ if (status === 1 || status === 2) {
74
+ return Promise.resolve('denied')
75
+ }
76
+
77
+ return new Promise((resolve) => {
78
+ store.requestAccessForEntityTypeCompletionHandler(CNEntityTypeContacts, (granted: boolean) =>
79
+ resolve(granted ? 'granted' : 'denied'),
80
+ )
81
+ })
75
82
  }
76
83
 
77
84
  let contactRequestCode = 7719
78
85
 
79
86
  function androidEnsure(): Promise<PermissionResult> {
80
- const perm = 'android.permission.READ_CONTACTS'
81
- const activity = Application.android.foregroundActivity ?? Application.android.startActivity
82
- try {
83
- if (
84
- activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
85
- ) {
86
- return Promise.resolve('granted')
87
- }
88
-
89
- if (!activity) {
90
- return Promise.resolve('denied')
91
- }
92
-
93
- return new Promise<PermissionResult>((resolve) => {
94
- const requestCode = contactRequestCode++
95
- const event = Application.android.activityRequestPermissionsEvent
96
- const onResult = (args: any) => {
97
- if (args.requestCode !== requestCode) {
98
- return
99
- }
100
- Application.android.off(event, onResult)
101
- resolve(
102
- args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
103
- ? 'granted'
104
- : 'denied',
105
- )
106
- }
107
- Application.android.on(event, onResult)
108
- try {
109
- activity.requestPermissions([perm], requestCode)
110
- } catch {
111
- Application.android.off(event, onResult)
112
- resolve('denied')
113
- }
114
- })
115
- } catch {
116
- return Promise.resolve('denied')
117
- }
87
+ const perm = 'android.permission.READ_CONTACTS'
88
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
89
+
90
+ try {
91
+ if (
92
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
93
+ ) {
94
+ return Promise.resolve('granted')
95
+ }
96
+
97
+ if (!activity) {
98
+ return Promise.resolve('denied')
99
+ }
100
+
101
+ return new Promise<PermissionResult>((resolve) => {
102
+ const requestCode = contactRequestCode++
103
+ const event = Application.android.activityRequestPermissionsEvent
104
+ const onResult = (args: any) => {
105
+ if (args.requestCode !== requestCode) {
106
+ return
107
+ }
108
+
109
+ Application.android.off(event, onResult)
110
+ resolve(
111
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
112
+ ? 'granted'
113
+ : 'denied',
114
+ )
115
+ }
116
+
117
+ Application.android.on(event, onResult)
118
+ try {
119
+ activity.requestPermissions([perm], requestCode)
120
+ } catch {
121
+ Application.android.off(event, onResult)
122
+ resolve('denied')
123
+ }
124
+ })
125
+ } catch {
126
+ return Promise.resolve('denied')
127
+ }
118
128
  }
119
129
 
120
130
  function asContact(native: any): Contact {
121
- const collection = (list: any, key: string) =>
122
- (list ?? []).map((c: any) => ({ label: c?.label, [key]: c?.value }))
123
- const address = (list: any): ContactAddress[] =>
124
- (list ?? []).map((c: any) => {
125
- const v = c?.value ?? {}
126
- return {
127
- label: c?.label,
128
- street: v.street ?? v.Street,
129
- city: v.city ?? v.City,
130
- region: v.state ?? v.State ?? v.region,
131
- postalCode: v.postalCode ?? v.postcode ?? v.PostalCode,
132
- country: v.country ?? v.Country,
133
- }
134
- })
135
- const given = native?.name?.given
136
- const family = native?.name?.family
137
- return {
138
- id: String(native?.id ?? ''),
139
- name: native?.name?.displayname ?? [given, family].filter(Boolean).join(' ') ?? '',
140
- firstName: given,
141
- middleName: native?.name?.middle,
142
- lastName: family,
143
- nickname: native?.nickname,
144
- emails: collection(native?.emailAddresses, 'email'),
145
- phoneNumbers: collection(native?.phoneNumbers, 'number'),
146
- addresses: address(native?.postalAddresses),
147
- urls: collection(native?.urls, 'url'),
148
- company: native?.organization?.name,
149
- jobTitle: native?.organization?.jobTitle,
150
- note: native?.notes,
151
- image: native?.photo,
152
- }
131
+ const collection = (list: any, key: string) =>
132
+ (list ?? []).map((c: any) => ({ label: c?.label, [key]: c?.value }))
133
+
134
+ const address = (list: any): ContactAddress[] =>
135
+ (list ?? []).map((c: any) => {
136
+ const v = c?.value ?? {}
137
+
138
+ return {
139
+ label: c?.label,
140
+ street: v.street ?? v.Street,
141
+ city: v.city ?? v.City,
142
+ region: v.state ?? v.State ?? v.region,
143
+ postalCode: v.postalCode ?? v.postcode ?? v.PostalCode,
144
+ country: v.country ?? v.Country,
145
+ }
146
+ })
147
+
148
+ const given = native?.name?.given
149
+ const family = native?.name?.family
150
+
151
+ return {
152
+ id: String(native?.id ?? ''),
153
+ name: native?.name?.displayname ?? [given, family].filter(Boolean).join(' ') ?? '',
154
+ firstName: given,
155
+ middleName: native?.name?.middle,
156
+ lastName: family,
157
+ nickname: native?.nickname,
158
+ emails: collection(native?.emailAddresses, 'email'),
159
+ phoneNumbers: collection(native?.phoneNumbers, 'number'),
160
+ addresses: address(native?.postalAddresses),
161
+ urls: collection(native?.urls, 'url'),
162
+ company: native?.organization?.name,
163
+ jobTitle: native?.organization?.jobTitle,
164
+ note: native?.notes,
165
+ image: native?.photo,
166
+ }
153
167
  }
154
168
 
155
169
  function applySort(list: Contact[], sort?: GetContactsOptions['sort']): Contact[] {
156
- if (!sort || sort === 'none') {
157
- return list
158
- }
159
- const key = sort === 'firstName' ? 'firstName' : 'lastName'
160
- return [...list].sort((a, b) => (a[key] ?? a.name).localeCompare(b[key] ?? b.name))
170
+ if (!sort || sort === 'none') {
171
+ return list
172
+ }
173
+
174
+ const key = sort === 'firstName' ? 'firstName' : 'lastName'
175
+
176
+ return [...list].sort((a, b) => (a[key] ?? a.name).localeCompare(b[key] ?? b.name))
161
177
  }
162
178
 
163
179
  function applyPage(list: Contact[], options?: GetContactsOptions): Contact[] {
164
- const start = options?.pageOffset ?? 0
165
- const size = options?.pageSize
166
- return size === undefined ? list.slice(start) : list.slice(start, start + size)
180
+ const start = options?.pageOffset ?? 0
181
+ const size = options?.pageSize
182
+
183
+ return size === undefined ? list.slice(start) : list.slice(start, start + size)
167
184
  }
168
185
 
169
186
  function applyNewContact(target: any, source: NewContact): void {
170
- // The plugin's save() reads every name member incl. phonetic — unset
171
- // members are native crashes, not omissions.
172
- target.name = {
173
- given: source.firstName ?? '',
174
- middle: source.middleName ?? '',
175
- family: source.lastName ?? '',
176
- prefix: '',
177
- suffix: '',
178
- phonetic: { given: '', middle: '', family: '' },
179
- }
180
- target.nickname = source.nickname
181
- target.notes = source.note
182
- if (source.company || source.jobTitle) {
183
- target.organization = { name: source.company, jobTitle: source.jobTitle }
184
- }
185
- target.emailAddresses = (source.emails ?? []).map((e) => ({ label: e.label, value: e.email }))
186
- target.phoneNumbers = (source.phoneNumbers ?? []).map((p) => ({
187
- label: p.label,
188
- value: p.number,
189
- }))
190
- // save() also maps postalAddresses/urls unconditionally.
191
- target.postalAddresses = []
192
- target.urls = []
193
- target.photo = null
187
+ // The plugin's save() reads every name member incl. phonetic — unset
188
+ // members are native crashes, not omissions.
189
+ target.name = {
190
+ given: source.firstName ?? '',
191
+ middle: source.middleName ?? '',
192
+ family: source.lastName ?? '',
193
+ prefix: '',
194
+ suffix: '',
195
+ phonetic: { given: '', middle: '', family: '' },
196
+ }
197
+
198
+ target.nickname = source.nickname
199
+ target.notes = source.note
200
+ if (source.company || source.jobTitle) {
201
+ target.organization = { name: source.company, jobTitle: source.jobTitle }
202
+ }
203
+
204
+ target.emailAddresses = (source.emails ?? []).map((e) => ({ label: e.label, value: e.email }))
205
+ target.phoneNumbers = (source.phoneNumbers ?? []).map((p) => ({
206
+ label: p.label,
207
+ value: p.number,
208
+ }))
209
+
210
+ // save() also maps postalAddresses/urls unconditionally.
211
+ target.postalAddresses = []
212
+ target.urls = []
213
+ target.photo = null
194
214
  }
195
215
 
196
216
  /** Contacts service — system address book. */
197
217
  export const contacts: Contacts = {
198
- supported: true,
199
-
200
- ensure(): Promise<PermissionResult> {
201
- return Application.ios ? iosEnsure() : androidEnsure()
202
- },
203
-
204
- async getAll(options?: GetContactsOptions): Promise<Contact[]> {
205
- const result = await NativeContacts.getAllContacts(pluginFields(options?.fields))
206
- return applyPage(applySort((result?.data ?? []).map(asContact), options?.sort), options)
207
- },
208
-
209
- async getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]> {
210
- const result = await NativeContacts.getContactsByName(predicate, pluginFields(fields))
211
- return (result?.data ?? []).map(asContact)
212
- },
213
-
214
- async getById(id: string, fields?: ContactField[]): Promise<Contact | null> {
215
- if (Application.ios) {
216
- const result = await NativeContacts.getContactById(id, pluginFields(fields))
217
- const native = result?.data ?? result
218
- return native ? asContact(native) : null
219
- }
220
- // Plugin ships getContactById for iOS only — full-store fetch + filter.
221
- const result = await NativeContacts.getAllContactsWithoutWorker(pluginFields(fields))
222
- const native = (result?.data ?? []).find((c: any) => String(c?.id) === id)
223
- return native ? asContact(native) : null
224
- },
225
-
226
- async add(contact: NewContact): Promise<string> {
227
- const native = new (NativeContact as any)()
228
- applyNewContact(native, contact)
229
- native.save()
230
- return String(native.id ?? '')
231
- },
232
-
233
- async update(id: string, contact: NewContact): Promise<string> {
234
- const existing = await contacts.getById(id)
235
- if (!existing) {
236
- throw new Error(`contacts.update: no contact with id ${id}`)
237
- }
238
- const native = new (NativeContact as any)()
239
- native.id = id
240
- applyNewContact(native, contact)
241
- native.save()
242
- return id
243
- },
244
-
245
- async remove(id: string): Promise<void> {
246
- const native = new (NativeContact as any)()
247
- native.id = id
248
- native.delete()
249
- },
218
+ supported: true,
219
+
220
+ ensure(): Promise<PermissionResult> {
221
+ return Application.ios ? iosEnsure() : androidEnsure()
222
+ },
223
+
224
+ async getAll(options?: GetContactsOptions): Promise<Contact[]> {
225
+ const result = await NativeContacts.getAllContacts(pluginFields(options?.fields))
226
+
227
+ return applyPage(applySort((result?.data ?? []).map(asContact), options?.sort), options)
228
+ },
229
+
230
+ async getByName(predicate: string, fields?: ContactField[]): Promise<Contact[]> {
231
+ const result = await NativeContacts.getContactsByName(predicate, pluginFields(fields))
232
+
233
+ return (result?.data ?? []).map(asContact)
234
+ },
235
+
236
+ async getById(id: string, fields?: ContactField[]): Promise<Contact | null> {
237
+ if (Application.ios) {
238
+ const result = await NativeContacts.getContactById(id, pluginFields(fields))
239
+ const native = result?.data ?? result
240
+
241
+ return native ? asContact(native) : null
242
+ }
243
+
244
+ // Plugin ships getContactById for iOS only — full-store fetch + filter.
245
+ const result = await NativeContacts.getAllContactsWithoutWorker(pluginFields(fields))
246
+ const native = (result?.data ?? []).find((c: any) => String(c?.id) === id)
247
+
248
+ return native ? asContact(native) : null
249
+ },
250
+
251
+ async add(contact: NewContact): Promise<string> {
252
+ const native = new (NativeContact as any)()
253
+
254
+ applyNewContact(native, contact)
255
+ native.save()
256
+ return String(native.id ?? '')
257
+ },
258
+
259
+ async update(id: string, contact: NewContact): Promise<string> {
260
+ const existing = await contacts.getById(id)
261
+
262
+ if (!existing) {
263
+ throw new Error(`contacts.update: no contact with id ${id}`)
264
+ }
265
+
266
+ const native = new (NativeContact as any)()
267
+
268
+ native.id = id
269
+ applyNewContact(native, contact)
270
+ native.save()
271
+ return id
272
+ },
273
+
274
+ async remove(id: string): Promise<void> {
275
+ const native = new (NativeContact as any)()
276
+
277
+ native.id = id
278
+ native.delete()
279
+ },
250
280
  }
251
281
 
252
282
  // Register the permission kind this leaf owns for the platform dispatcher.
253
283
  const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
284
+
254
285
  permissionOwners.contacts = () => contacts.ensure()
@@ -5,54 +5,59 @@
5
5
  import type { Contact, Contacts, GetContactsOptions, NewContact, PermissionResult } from './types'
6
6
 
7
7
  interface ContactPicker {
8
- select(properties: string[], options?: { multiple?: boolean }): Promise<any[]>
9
- getProperties(): Promise<string[]>
8
+ select(properties: string[], options?: { multiple?: boolean }): Promise<any[]>
9
+ getProperties(): Promise<string[]>
10
10
  }
11
11
 
12
12
  const picker = (): ContactPicker | null => {
13
- const nav = (globalThis as any).navigator
14
- return typeof nav?.contacts?.select === 'function' ? (nav.contacts as ContactPicker) : null
13
+ const nav = (globalThis as any).navigator
14
+
15
+ return typeof nav?.contacts?.select === 'function' ? (nav.contacts as ContactPicker) : null
15
16
  }
16
17
 
17
18
  function asContact(native: any): Contact {
18
- return {
19
- id: '',
20
- name: Array.isArray(native?.name) ? native.name.join(' ') : (native?.name ?? ''),
21
- emails: (native?.email ?? []).map((e: string) => ({ email: e })),
22
- phoneNumbers: (native?.tel ?? []).map((t: string) => ({ number: t })),
23
- }
19
+ return {
20
+ id: '',
21
+ name: Array.isArray(native?.name) ? native.name.join(' ') : (native?.name ?? ''),
22
+ emails: (native?.email ?? []).map((e: string) => ({ email: e })),
23
+ phoneNumbers: (native?.tel ?? []).map((t: string) => ({ number: t })),
24
+ }
24
25
  }
25
26
 
26
27
  const unsupported = (what: string) => () =>
27
- Promise.reject(
28
- new Error(`unsupported: contact ${what} is not available through the web Contact Picker`),
29
- )
28
+ Promise.reject(
29
+ new Error(`unsupported: contact ${what} is not available through the web Contact Picker`),
30
+ )
30
31
 
31
32
  /** Contacts service — system address book. */
32
33
  export const contacts: Contacts = {
33
- supported: picker() !== null,
34
-
35
- // The picker has no permission state to query — choosing contacts IS the
36
- // grant. Report granted when the API exists so apps don't gate on it.
37
- ensure(): Promise<PermissionResult> {
38
- return Promise.resolve(picker() ? 'granted' : 'unsupported')
39
- },
40
-
41
- async getAll(options?: GetContactsOptions): Promise<Contact[]> {
42
- const p = picker()
43
- if (!p) {
44
- throw new Error('unsupported: navigator.contacts.select is not available')
45
- }
46
- const selected = await p.select(['name', 'email', 'tel'], { multiple: true })
47
- return (selected ?? []).map(asContact)
48
- },
49
-
50
- getByName: unsupported('lookup'),
51
- getById: unsupported('lookup'),
52
- add: (_contact: NewContact) => unsupported('writes')(),
53
- update: (_id: string, _contact: NewContact) => unsupported('writes')(),
54
- remove: unsupported('writes'),
34
+ supported: picker() !== null,
35
+
36
+ // The picker has no permission state to query — choosing contacts IS the
37
+ // grant. Report granted when the API exists so apps don't gate on it.
38
+ ensure(): Promise<PermissionResult> {
39
+ return Promise.resolve(picker() ? 'granted' : 'unsupported')
40
+ },
41
+
42
+ async getAll(options?: GetContactsOptions): Promise<Contact[]> {
43
+ const p = picker()
44
+
45
+ if (!p) {
46
+ throw new Error('unsupported: navigator.contacts.select is not available')
47
+ }
48
+
49
+ const selected = await p.select(['name', 'email', 'tel'], { multiple: true })
50
+
51
+ return (selected ?? []).map(asContact)
52
+ },
53
+
54
+ getByName: unsupported('lookup'),
55
+ getById: unsupported('lookup'),
56
+ add: (_contact: NewContact) => unsupported('writes')(),
57
+ update: (_id: string, _contact: NewContact) => unsupported('writes')(),
58
+ remove: unsupported('writes'),
55
59
  }
56
60
 
57
61
  const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
62
+
58
63
  permissionOwners.contacts = () => contacts.ensure()
@@ -3,19 +3,20 @@
3
3
  import type { Contacts, PermissionResult } from './types'
4
4
 
5
5
  const unsupported = () =>
6
- Promise.reject(new Error('unsupported: contacts is not available on windows'))
6
+ Promise.reject(new Error('unsupported: contacts is not available on windows'))
7
7
 
8
8
  /** Contacts service — system address book. */
9
9
  export const contacts: Contacts = {
10
- supported: false,
11
- ensure: async (): Promise<PermissionResult> => 'unsupported',
12
- getAll: unsupported,
13
- getByName: unsupported,
14
- getById: unsupported,
15
- add: unsupported,
16
- update: unsupported,
17
- remove: unsupported,
10
+ supported: false,
11
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
12
+ getAll: unsupported,
13
+ getByName: unsupported,
14
+ getById: unsupported,
15
+ add: unsupported,
16
+ update: unsupported,
17
+ remove: unsupported,
18
18
  }
19
19
 
20
20
  const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
21
+
21
22
  permissionOwners.contacts = () => contacts.ensure()