@windowkit/appkit 0.7.0 → 0.8.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/README.md CHANGED
@@ -501,11 +501,11 @@ native.beginDrag(win, {
501
501
  ## Privacy authorizations (TCC)
502
502
 
503
503
  macOS decides per process whether an app may use the camera, microphone,
504
- screen, accessibility, input monitoring or location, or send Apple Events to
505
- another app. The bridge is mechanism only: read the status, raise the system
506
- prompt where a framework offers one, and deep-link to the Settings pane where
507
- it does not. Policy — when to ask, what to do with a refusal — stays in the
508
- renderer.
504
+ screen, accessibility, input monitoring or location, read the user's
505
+ calendars and reminders, or send Apple Events to another app. The bridge is
506
+ mechanism only: read the status, raise the system prompt where a framework
507
+ offers one, and deep-link to the Settings pane where it does not. Policy —
508
+ when to ask, what to do with a refusal — stays in the renderer.
509
509
 
510
510
  ```js
511
511
  const { permissions, native } = require('@windowkit/appkit');
@@ -513,6 +513,8 @@ const { permissions, native } = require('@windowkit/appkit');
513
513
  permissions.status('camera'); // 'authorized' | 'denied' | 'restricted' | 'notDetermined'
514
514
  await permissions.request('microphone'); // raises the system prompt; resolves to granted (boolean)
515
515
  permissions.status('automation', { target: 'com.apple.finder' }); // Apple Events, per target app
516
+ permissions.status('calendars'); // the four words, or 'writeOnly' — macOS 14's save-only grant
517
+ await permissions.request('calendars', { access: 'write-only' }); // the narrower prompt; granted when write-only or full access is held
516
518
  permissions.openSettings('screen-recording'); // System Settings › Privacy & Security › Screen Recording
517
519
 
518
520
  // the natives underneath, callback-shaped
@@ -529,6 +531,7 @@ native.openPrivacySettings(kind?); // no kind: th
529
531
  | `input-monitoring` | `IOHIDCheckAccess` (listen) | `IOHIDRequestAccess` | granted / denied / unknown → `notDetermined`; the request posts the prompt and resolves at once, `notDetermined` while it is still up |
530
532
  | `automation` | `AEDeterminePermissionToAutomateTarget` | the same, asking | needs `{ target: bundleId }` of a **running** app, otherwise throws — TCC only answers for a running target. Asking blocks until answered, so it runs off the main thread |
531
533
  | `location` | `CLLocationManager.authorizationStatus` | `requestWhenInUseAuthorization` | the answer comes through the delegate on the main run loop, i.e. while `app.run()` is pumping |
534
+ | `calendars`, `reminders` | `EKEventStore authorizationStatusForEntityType:` | `requestFullAccessToEventsWithCompletion:`, `requestWriteOnlyAccessToEventsWithCompletion:`, `requestFullAccessToRemindersWithCompletion:` (14+; `requestAccessToEntityType:completion:` before) | the fifth word: on macOS 14+ the status can be `writeOnly`, the partial grant that lets an app save items it cannot read. It crosses as it is — a writer treats it as granted, a reader as denied, and that is the renderer's call. `{ access: 'write-only' }` asks calendars for just that grant (reminders have no such grant: a TypeError); `granted` in the answer is whether the level asked for is held afterwards, so a write-only request is granted by write-only or full access. One `EKEventStore` serves the process, created by the first request — creating a store never prompts, only the request does — and it is the store the calendar-reading verbs share |
532
535
 
533
536
  - A request answers **once, asynchronously** — never inside the call — and
534
537
  holds the event loop open until then, like pending I/O.
@@ -536,12 +539,188 @@ native.openPrivacySettings(kind?); // no kind: th
536
539
  process* (Terminal, an IDE) or to `node` itself, and prompts with no
537
540
  usage-description strings. A bundled app must carry the keys
538
541
  (`NSCameraUsageDescription`, `NSMicrophoneUsageDescription`,
539
- `NSLocationUsageDescription`, `NSAppleEventsUsageDescription`); without
540
- them the request never prompts, or TCC ends the process.
542
+ `NSLocationUsageDescription`, `NSAppleEventsUsageDescription`; for
543
+ EventKit on macOS 14+ `NSCalendarsFullAccessUsageDescription`,
544
+ `NSCalendarsWriteOnlyAccessUsageDescription` and
545
+ `NSRemindersFullAccessUsageDescription`, and before 14
546
+ `NSCalendarsUsageDescription` / `NSRemindersUsageDescription`); without
547
+ them the request never prompts, or TCC ends the process. A sandboxed build
548
+ also needs the App Sandbox's one EventKit entitlement,
549
+ `com.apple.security.personal-information.calendars`.
550
+ - **A refusal is an answer; a prompt nobody saw is not.** After a calendars
551
+ or reminders request the status is what the request reads back: `denied`
552
+ when the user refused, and still `notDetermined` when nothing was shown
553
+ (a bundle without the usage string, a process TCC cannot attribute) —
554
+ measured on macOS 15.2, a bundle without the keys gets its answer within
555
+ a few milliseconds, `granted` false and the status unchanged. The bridge
556
+ does not tell those apart; the renderer re-reads and decides.
541
557
  - **Folders** (Desktop, Documents, Downloads) need nothing native: reading the
542
558
  directory *is* the prompt and `EPERM` is the denial. `openSettings` also
543
559
  takes `'files-and-folders'` and `'full-disk-access'` for their panes.
544
560
  - `restricted` is MDM or parental controls: the user cannot grant it.
561
+ ## Calendars (EventKit)
562
+
563
+ Every account the user added in System Settings › Internet Accounts — iCloud,
564
+ Google, Exchange, CalDAV, a subscribed feed — is served by one framework,
565
+ `EKEventStore`: the macOS counterpart of Evolution Data Server plus GNOME
566
+ Online Accounts, where the desktop did the OAuth and the app never sees a
567
+ credential. Reading and writing go through the same store and the same
568
+ grant. Mechanism only — which calendars to show, how to draw an all-day
569
+ span, when to re-query and what to put in an event stay in the renderer.
570
+
571
+ ```js
572
+ const { calendars, permissions, native } = require('@windowkit/appkit');
573
+
574
+ await permissions.request('calendars'); // the TCC grant — "Privacy authorizations" above
575
+
576
+ const list = await calendars.list();
577
+ // [{ id, title, color: [r, g, b, a] | null, type: 'local' | 'calDAV' | 'exchange' |
578
+ // 'subscription' | 'birthday', source: { id, title, type }, immutable,
579
+ // allowsModifications, subscribed }]
580
+
581
+ const day = 24 * 60 * 60 * 1000;
582
+ const events = await calendars.eventsBetween({ start: Date.now(), end: Date.now() + 7 * day });
583
+ // the occurrences in the range, recurrences already expanded, sorted by start
584
+ const oneCalendar = await calendars.eventsBetween({
585
+ start: new Date('2026-09-01'), end: new Date('2026-10-01'), calendars: [list[0].id],
586
+ });
587
+
588
+ native.setBackendEventCallback((ev) => {
589
+ // 'calendar-store-changed' {} something in the store changed: query again
590
+ });
591
+
592
+ // writing: the same store, the full grant or macOS 14's write-only one
593
+ const home = await calendars.defaultCalendar(); // where a save with no calendar goes, or null
594
+ const id = await calendars.saveEvent({
595
+ title: 'Dentist', start: new Date('2026-10-05T09:00'), end: new Date('2026-10-05T10:00'),
596
+ location: '12 High St', alarms: [{ offset: -15 * 60 }],
597
+ recurrence: { frequency: 'weekly', daysOfWeek: [{ day: 2 }], count: 6 }, // six Mondays
598
+ });
599
+ const [, second] = await calendars.eventsBetween({ start, end, calendars: [home.id] });
600
+ await calendars.saveEvent({ id, occurrenceDate: second.occurrenceDate, start: later, end: later + hour }, { span: 'this' });
601
+ await calendars.saveEvent({ id, occurrenceDate: second.occurrenceDate, title: 'Orthodontist' }, { span: 'future' });
602
+ await calendars.removeEvent(id, { span: 'future' }); // the whole series, from its first occurrence
603
+ // a batch: nothing reaches the database until commit(); reset() forgets it instead
604
+ await calendars.saveEvent(a, { commit: false });
605
+ await calendars.saveEvent(b, { commit: false });
606
+ await calendars.commit();
607
+
608
+ // the natives underneath, callback-shaped
609
+ native.calendars(cb); // cb(err, [calendar])
610
+ native.eventsBetween({ start, end, calendars? }, cb); // epoch ms; cb(err, [event])
611
+ native.defaultCalendar(cb); // cb(err, calendar | null)
612
+ native.saveEvent(props, opts?, cb); // cb(err, id)
613
+ native.removeEvent(id, opts?, cb); // opts: { span, commit, occurrenceDate }; cb(err)
614
+ native.commitCalendarStore(cb); // cb(err)
615
+ native.resetCalendarStore(cb); // cb(null)
616
+ native.postCalendarStoreChanged(); // test-only: the notification EventKit posts
617
+ ```
618
+
619
+ | event field | what |
620
+ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
621
+ | `id`, `itemId`, `externalId` | `eventIdentifier`, `calendarItemIdentifier`, `calendarItemExternalIdentifier` — `null` where the store has none (a local calendar's items carry no external id). Every occurrence of a series shares the series' `id`; a detached occurrence gets its own, the series' with `/RID=<slot>` appended |
622
+ | `calendar` | the `id` of the calendar it is in |
623
+ | `title`, `location`, `notes`, `url` | strings, or `null` where the item has none — never `''` for absent |
624
+ | `start`, `end` | epoch ms, as the store reports them |
625
+ | `allDay`, `timeZone` | `isAllDay`; the event's time-zone identifier (`'Europe/London'`) or `null` for a floating one |
626
+ | `status` | `'none'`, `'confirmed'`, `'tentative'`, `'cancelled'` |
627
+ | `availability` | `'notSupported'`, `'busy'`, `'free'`, `'tentative'`, `'unavailable'` |
628
+ | `recurring`, `detached` | `hasRecurrenceRules`; whether this occurrence was edited away from its series |
629
+ | `occurrenceDate` | where the occurrence sits in the series (epoch ms). For a detached occurrence that was moved, macOS 15.2 reports the start it was moved *to* (the original slot survives as the `RID=` in its `externalId`), not the documented original date — pass it back as reported |
630
+ | `organizer`, `attendees` | present only when the event has them: `{ name, url, status, role, type, isCurrentUser }` — `url` is the `mailto:` the account gave, `status` `'unknown'` … `'inProcess'`, `role` `'required'`/`'optional'`/`'chair'`/`'nonParticipant'`, `type` `'person'`/`'room'`/`'resource'`/`'group'` |
631
+ | `recurrence` | present only on a recurring event: its rule in the shape `saveEvent` takes (below), so it can be read, changed and written back. The framework allows several rules on an item; the first is carried, which is the only one Calendar or any account writes |
632
+ | `alarms` | present only when the event has alarms: `[{ offset: seconds from the start, negative before it } \| { at: epoch ms }]` |
633
+
634
+ `saveEvent(props, opts?)` — every field but the ones that identify the event
635
+ is optional. On an existing event a field left out stays as it is and `null`
636
+ clears it; on a new one `start` and `end` are required.
637
+
638
+ | prop | what |
639
+ | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
640
+ | `id`, `occurrenceDate` | neither: a new event. `id` names an existing one (`eventWithIdentifier:`); with `occurrenceDate` — as `eventsBetween` reported it for that occurrence — one occurrence of a recurring event, found through the same predicate the reads use; without it the first occurrence, which with `span: 'future'` is the whole series |
641
+ | `calendar` | a calendar id. A new event without one goes to `defaultCalendar()`; on an existing event it is a move, which an invitation refuses (`EKErrorInvitesCannotBeMoved`) |
642
+ | `title`, `location`, `notes`, `url`, `timeZone` | strings, or `null` to clear. `url` must be absolute (`https://…`), `timeZone` an identifier (`'Europe/London'`), `null` for a floating event |
643
+ | `start`, `end` | epoch ms, or a `Date` through the wrapper. Inverted ones are the framework's to refuse (`EKErrorDatesInverted`) |
644
+ | `allDay` | in the store's own convention, the one `eventsBetween` reports: `start` at local midnight, `end` at the last second of the last day. An exclusive end — the next midnight — makes a two-day event (measured: it reads back as 48 hours) |
645
+ | `availability` | `'busy'`, `'free'`, `'tentative'`, `'unavailable'` |
646
+ | `recurrence` | `EKRecurrenceRule`'s own vocabulary, what its initialiser takes: `{ frequency: 'daily' \| 'weekly' \| 'monthly' \| 'yearly', interval?, until? \| count?, daysOfWeek?: [{ day: 1..7 (Sunday = 1), week? }], daysOfMonth?, monthsOfYear?, weeksOfYear?, daysOfYear?, setPositions? }` — `until` epoch ms, `count` occurrences, neither for never; the arrays as iCalendar's BYDAY, BYMONTHDAY, BYMONTH, BYWEEKNO, BYYEARDAY, BYSETPOS, negatives counting from the end; `week` on a day only in a monthly (±1..5) or yearly (±1..53) rule. `null` removes the rule. Not an RRULE string: a consumer holding iCalendar text parses it on its own side |
647
+ | `alarms` | `[{ offset: seconds from the start, negative before it }]` or `[{ at: epoch ms }]`; `null` or `[]` removes them |
648
+ | `opts.span` | `'this'` (the default) or `'future'`: how far a change to — or the removal of — a recurring event reaches, `EKSpanThisEvent` / `EKSpanFutureEvents`. `'this'` on one occurrence detaches it (it then carries its own `id`); `'future'` from a middle occurrence splits the series there, and what follows answers under a new `id` — though the account keeps it with the original object, so removing `'future'` from an earlier occurrence takes the split-off part and any detached occurrence with it |
649
+ | `opts.commit` | `true` by default. `false` leaves the change pending for `commit()` — `commitCalendarStore` — and `reset()` forgets what is pending; the id is answered either way |
650
+
651
+ - **Reading needs the full grant.** Both verbs answer an error naming the
652
+ status — `notDetermined`, `denied`, `restricted`, or macOS 14's `writeOnly`,
653
+ which may save what it cannot read — rather than an empty list, so "no
654
+ events" and "not allowed to look" stay distinguishable. Neither verb
655
+ prompts: ask for `'calendars'` first. They share the one `EKEventStore` the
656
+ grant created, and `refreshSourcesIfNecessary` runs before a listing so a
657
+ calendar just added in Settings is there (the refresh itself is
658
+ asynchronous; what it pulls in arrives as a change event).
659
+ - **Four years.** `predicateForEventsWithStartDate:endDate:calendars:` is
660
+ limited to a four-year span, so a longer range is a `TypeError` at the
661
+ bridge rather than a silently truncated answer — chunk it. An `end` before
662
+ the `start` is one too, and so is a `calendars` filter naming nothing: an
663
+ empty list would reach the predicate as "every calendar", the opposite of
664
+ what it says. An id that names no calendar is an error through the
665
+ callback, not a widened query.
666
+ - **All-day events cross as the store reports them**: `allDay` true, `start`
667
+ at local midnight and `end` at the last second of the last day (23:59:59),
668
+ *not* an exclusive end. Normalising is the renderer's job; the bridge is
669
+ mechanism, and `test/calendars.js` pins the convention so a renderer's
670
+ normalisation has something to be checked against.
671
+ - **Off the JS thread.** `eventsMatchingPredicate:` is synchronous and can
672
+ take a while over many calendars, so both verbs run on a background queue
673
+ and answer through a thread-safe function — never inside the call — holding
674
+ the loop open like pending I/O until they do. What the framework hands back
675
+ is copied into plain objects on that queue, so nothing EventKit-owned
676
+ crosses to JS. Colours are converted to sRGB like every other colour on
677
+ this bridge.
678
+ - **The change event.** EventKit posts one notification for *any* change, and
679
+ its documented contract is "re-fetch": `'calendar-store-changed'` carries
680
+ nothing, and the answer to it is to query again. The observer is installed
681
+ with the process's store — i.e. from the first EventKit call, before a
682
+ listener could exist — and a change that arrives before
683
+ `setBackendEventCallback` is held and replayed at the start of the next
684
+ `pump2()`, coalesced into one. The framework coalesces too, and a duplicate
685
+ is harmless to a renderer whose answer is to re-query.
686
+ - **Writing needs either grant.** A save, a removal, a commit and the
687
+ default calendar answer under the full grant or macOS 14's `writeOnly`
688
+ one, and an error naming the status otherwise. Under write-only the store
689
+ cannot read back what it saved — `eventWithIdentifier:` answers nil — so
690
+ changing or removing an event by id is refused as the EKError it is
691
+ (`EKErrorEventStoreNotAuthorized`) rather than reported as success; what
692
+ a write-only app can do is add. Measured on 15.2: `defaultCalendar()`
693
+ answers a stand-in the framework makes for the grant — id
694
+ `VIRTUAL_APP_CALENDAR_UUID`, title "Calendar", a source called "Account"
695
+ — and a save into it, or with no calendar named, lands in the user's real
696
+ default calendar; `list()` and `eventsBetween()` answer the error naming
697
+ `writeOnly`.
698
+ - **What the framework refuses crosses as its error, never as a bare
699
+ boolean.** The rejection carries `code` (the `EKErrorCode` number),
700
+ `domain` (`'EKErrorDomain'`) and `reason`, the code's name from the
701
+ framework's own header — `EKErrorCalendarReadOnly`, `EKErrorNoCalendar`,
702
+ `EKErrorDatesInverted`, `EKErrorInvitesCannotBeMoved` … — so a consumer
703
+ can switch on the word; the message carries the framework's own text. An
704
+ id that names no event, a calendar id that names none, an `occurrenceDate`
705
+ that is not one of the series: errors through the callback with the
706
+ bridge's own message. What the framework *raises* — a rule it cannot
707
+ build, an object from another store — is caught and crosses the same way
708
+ rather than ending the process. A save that finds nothing changed is not a
709
+ failure.
710
+ - **Writes are serial.** Every write runs on one serial queue at the reads'
711
+ QoS — off the JS thread, answered through a thread-safe function, never
712
+ inside the call — and one after another in the order asked, which is what
713
+ makes a batch (`commit: false` … `commit()`) mean something. A commit,
714
+ the consumer's own included, is followed by `'calendar-store-changed'`,
715
+ so a change made here and one made elsewhere look the same to the reader,
716
+ which is correct.
717
+ - **No system sheet.** There is no `EKEventEditViewController` on macOS, so
718
+ there is nothing to defer to; this is API only, and the renderer draws the
719
+ editor.
720
+ - **Not here:** reminders (`EKReminder` has its own predicate and its own
721
+ grant), calendars themselves (`saveCalendar:`), and attendees, which an
722
+ account manages through its invitations.
723
+
545
724
  ## Status item (the menu-bar extra)
546
725
 
547
726
  `NSStatusItem` is the tray. An item shows an image or a title (or both) in the
package/binding.gyp CHANGED
@@ -6,7 +6,8 @@
6
6
  "src/addon.mm",
7
7
  "src/backend.mm",
8
8
  "src/permissions.mm",
9
- "src/notifications.mm"
9
+ "src/notifications.mm",
10
+ "src/calendars.mm"
10
11
  ],
11
12
  "include_dirs": [
12
13
  "<!@(node -p \"require('node-addon-api').include\")"
@@ -30,7 +31,8 @@
30
31
  "-framework CoreLocation",
31
32
  "-framework IOKit",
32
33
  "-framework ApplicationServices",
33
- "-framework UserNotifications"
34
+ "-framework UserNotifications",
35
+ "-framework EventKit"
34
36
  ]
35
37
  }
36
38
  }
package/index.js CHANGED
@@ -189,14 +189,21 @@ const controls = {
189
189
 
190
190
  // Privacy (TCC) authorizations. kind: 'camera' | 'microphone' |
191
191
  // 'screen-recording' | 'accessibility' | 'input-monitoring' | 'location' |
192
- // 'automation' (with { target: bundleId }). Status and request never touch
193
- // policy: the renderer decides when to ask and what to do with a refusal.
192
+ // 'automation' (with { target: bundleId }) | 'calendars' | 'reminders'
193
+ // (EventKit; calendars takes { access: 'full' | 'write-only' }, full by
194
+ // default). Status and request never touch policy: the renderer decides when
195
+ // to ask and what to do with a refusal.
194
196
  const permissions = {
195
- // -> 'authorized' | 'denied' | 'restricted' | 'notDetermined'; never prompts
197
+ // -> 'authorized' | 'denied' | 'restricted' | 'notDetermined', or
198
+ // 'writeOnly' for calendars and reminders on macOS 14+: the app may save
199
+ // items it cannot read, which is granted to a writer and denied to a reader
200
+ // — the word crosses as it is so the caller can decide. Never prompts.
196
201
  status: (kind, opts) => native.authorizationStatus(kind, opts),
197
- // Raises the system prompt where macOS has one; resolves to granted. Screen
198
- // recording and accessibility can only be granted in Settings, so their
199
- // prompt is the system's go-to-Settings dialog and this resolves at once.
202
+ // Raises the system prompt where macOS has one; resolves to granted — the
203
+ // level asked for is held afterwards (for calendars with
204
+ // { access: 'write-only' }, write-only or full). Screen recording and
205
+ // accessibility can only be granted in Settings, so their prompt is the
206
+ // system's go-to-Settings dialog and this resolves at once.
200
207
  request: (kind, opts) =>
201
208
  new Promise((resolve) => native.requestAuthorization(kind, opts, resolve)),
202
209
  // Best-effort deep link to the Privacy pane (or its top level with no kind);
@@ -245,6 +252,85 @@ const notifications = {
245
252
  categories: () => new Promise((resolve) => native.notificationCategories(resolve)),
246
253
  };
247
254
 
255
+ // A Date is a convenience of the wrapper's; the bridge takes epoch ms, and
256
+ // anything else is left alone so it is refused there rather than coerced.
257
+ const toMs = (v) => (v instanceof Date ? v.getTime() : v);
258
+
259
+ // The same for every date in a save: start, end, the occurrence, the
260
+ // recurrence's until, an absolute alarm. A spread leaves absent fields
261
+ // undefined, which the bridge reads as absent.
262
+ const eventMs = (p) => {
263
+ const out = { ...p, start: toMs(p.start), end: toMs(p.end), occurrenceDate: toMs(p.occurrenceDate) };
264
+ if (p.recurrence && typeof p.recurrence === 'object') out.recurrence = { ...p.recurrence, until: toMs(p.recurrence.until) };
265
+ if (Array.isArray(p.alarms)) out.alarms = p.alarms.map((a) => (a && a.at instanceof Date ? { ...a, at: a.at.getTime() } : a));
266
+ return out;
267
+ };
268
+ const optsMs = (o) => (o && o.occurrenceDate instanceof Date ? { ...o, occurrenceDate: o.occurrenceDate.getTime() } : o);
269
+
270
+ // The user's calendars, the occurrences in a date range, and the writes —
271
+ // an event put in, changed or taken out — through EventKit (EKEventStore):
272
+ // every account added in System Settings › Internet Accounts (iCloud,
273
+ // Google, Exchange, CalDAV, a subscribed feed) is served by it, and the
274
+ // desktop did the OAuth, so the app never sees a credential. Mechanism only:
275
+ // which calendars to show, how to render an all-day span, when to re-query
276
+ // and what to put in an event stay in the renderer.
277
+ //
278
+ // Reading needs the 'calendars' authorization (permissions.request); a write
279
+ // is content with macOS 14's write-only grant too. Without one these reject
280
+ // with an error naming the status rather than answering an empty list, so
281
+ // "no events" and "not allowed to look" stay apart. A change to anything in
282
+ // the store — the consumer's own commit included — arrives as a
283
+ // 'calendar-store-changed' backend event (native.setBackendEventCallback)
284
+ // whose only sensible answer is to query again; the observer is in place
285
+ // from the first EventKit call.
286
+ const calendars = {
287
+ // -> [{ id, title, color: [r, g, b, a] | null (sRGB), type: 'local' |
288
+ // 'calDAV' | 'exchange' | 'subscription' | 'birthday', source: { id,
289
+ // title, type }, immutable, allowsModifications, subscribed }]
290
+ list: () =>
291
+ new Promise((resolve, reject) =>
292
+ native.calendars((err, list) => (err ? reject(err) : resolve(list)))),
293
+ // { start, end, calendars?: [id] } — epoch ms or Date, at most a four-year
294
+ // span (EventKit's own limit on the predicate; chunk anything longer).
295
+ // Resolves to the occurrences in the range, recurrences already expanded by
296
+ // the framework, sorted by start. All-day events come back as the store
297
+ // reports them: allDay true, start at local midnight, end at the last
298
+ // second of the last day — normalising that is the renderer's job.
299
+ eventsBetween: ({ start, end, calendars: ids } = {}) =>
300
+ new Promise((resolve, reject) =>
301
+ native.eventsBetween(
302
+ { start: toMs(start), end: toMs(end), calendars: ids },
303
+ (err, events) => (err ? reject(err) : resolve(events)),
304
+ )),
305
+ // -> the calendar a save with no calendar goes to (defaultCalendarForNewEvents),
306
+ // in the shape list() gives, or null when the store has none
307
+ defaultCalendar: () =>
308
+ new Promise((resolve, reject) =>
309
+ native.defaultCalendar((err, cal) => (err ? reject(err) : resolve(cal)))),
310
+ // { id?, occurrenceDate?, calendar?, title?, start, end, allDay?, location?,
311
+ // notes?, url?, timeZone?, availability?, recurrence?, alarms? } — epoch ms
312
+ // or Date. No id creates an event (start and end required; the default
313
+ // calendar when none is named); an id changes that event, and with
314
+ // occurrenceDate the one occurrence of a recurring one, a field absent
315
+ // left as it is and null cleared. opts: { span: 'this' | 'future', commit }.
316
+ // Resolves to the event's id. What the framework refuses rejects with its
317
+ // EKError: { code, domain: 'EKErrorDomain', reason: 'EKErrorCalendarReadOnly' }.
318
+ saveEvent: (props = {}, opts) =>
319
+ new Promise((resolve, reject) =>
320
+ native.saveEvent(eventMs(props), opts, (err, id) => (err ? reject(err) : resolve(id)))),
321
+ // (id, { span, commit, occurrenceDate }) — the same span; the occurrence
322
+ // when one is named.
323
+ removeEvent: (id, opts) =>
324
+ new Promise((resolve, reject) =>
325
+ native.removeEvent(id, optsMs(opts), (err) => (err ? reject(err) : resolve()))),
326
+ // A batch: saves and removes with { commit: false } wait for this, in the
327
+ // order they were asked; reset() forgets them instead.
328
+ commit: () =>
329
+ new Promise((resolve, reject) =>
330
+ native.commitCalendarStore((err) => (err ? reject(err) : resolve()))),
331
+ reset: () => new Promise((resolve) => native.resetCalendarStore(resolve)),
332
+ };
333
+
248
334
  const accessibility = {
249
335
  // System Settings › Accessibility › Display, as NSWorkspace reports it:
250
336
  // { reduceMotion, reduceTransparency, increaseContrast, differentiateWithoutColor, invertColors }.
@@ -255,5 +341,6 @@ const accessibility = {
255
341
 
256
342
  module.exports = {
257
343
  app, Window, Layer, TextLayer, GradientLayer, ShapeLayer,
258
- transaction, withoutAnimations, text, controls, permissions, notifications, accessibility, native,
344
+ transaction, withoutAnimations, text, controls, permissions, notifications, calendars,
345
+ accessibility, native,
259
346
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Retained-mode AppKit backend for Node.js: Core Animation (CALayer) layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu, and native control bezels — the macOS half of react-x11.",
5
5
  "author": "Andrey Sidorov <andrey.sidorov@gmail.com>",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "install": "node scripts/install.js",
44
44
  "build": "node-gyp rebuild",
45
45
  "demo": "node demo/demo.js",
46
- "test": "node test/app-lifecycle.js && node test/animation.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/surface-blit.js"
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/surface-blit.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js"
47
47
  },
48
48
  "dependencies": {
49
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/addon.mm CHANGED
@@ -1283,6 +1283,9 @@ void InitPermissions(Napi::Env env, Napi::Object exports);
1283
1283
  // src/notifications.mm — user notifications through UNUserNotificationCenter:
1284
1284
  // settings, authorization, categories, post/update/remove, action events.
1285
1285
  void InitNotifications(Napi::Env env, Napi::Object exports);
1286
+ // src/calendars.mm — the user's calendars and the occurrences in a range
1287
+ // through EventKit, and the store's change notification as a backend event.
1288
+ void InitCalendars(Napi::Env env, Napi::Object exports);
1286
1289
 
1287
1290
  static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1288
1291
  #define FN(js, fn) exports.Set(js, Napi::Function::New(env, fn))
@@ -1325,6 +1328,7 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1325
1328
  InitBackend(env, exports);
1326
1329
  InitPermissions(env, exports);
1327
1330
  InitNotifications(env, exports);
1331
+ InitCalendars(env, exports);
1328
1332
  return exports;
1329
1333
  }
1330
1334
 
package/src/backend.mm CHANGED
@@ -950,6 +950,8 @@ static Napi::Value SetBackendEventCallback(const Napi::CallbackInfo& info) {
950
950
 
951
951
  // notifications.mm: responses that arrived before a listener was installed
952
952
  void CALNotificationsReplayHeld(Napi::Env env);
953
+ // calendars.mm: an EventKit store change from before there was a listener
954
+ void CALCalendarsReplayHeld(Napi::Env env);
953
955
 
954
956
  static Napi::Value Pump2(const Napi::CallbackInfo& info) {
955
957
  Napi::Env env = info.Env();
@@ -957,9 +959,10 @@ static Napi::Value Pump2(const Napi::CallbackInfo& info) {
957
959
  // what came before the callback did, ahead of this tick's input so the
958
960
  // renderer hears of it first: the launch's URL (or a Dock click), then a
959
961
  // notification acted on before the callback existed (one that launched
960
- // the app, say)
962
+ // the app, say), then a calendar store that changed under it
961
963
  FlushPendingAppEvents(env);
962
964
  CALNotificationsReplayHeld(env);
965
+ CALCalendarsReplayHeld(env);
963
966
  @autoreleasepool {
964
967
  while (true) {
965
968
  NSEvent* e = [NSApp nextEventMatchingMask:NSEventMaskAny