@joinskips/common 0.0.0-stage → 0.1.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.
Files changed (131) hide show
  1. package/README.md +104 -2
  2. package/dist/chat/SkipsChat.d.ts +37 -0
  3. package/dist/chat/SkipsChat.js +103 -0
  4. package/dist/chat/client.d.ts +53 -0
  5. package/dist/chat/client.js +178 -0
  6. package/dist/chat/connection.d.ts +4 -0
  7. package/dist/chat/connection.js +6 -0
  8. package/dist/chat/generated/skips-app/index.d.ts +1 -0
  9. package/dist/chat/generated/skips-app/index.js +2 -0
  10. package/dist/chat/generated/skips-app/types.gen.d.ts +733 -0
  11. package/dist/chat/generated/skips-app/types.gen.js +2 -0
  12. package/dist/chat/index.d.ts +3 -0
  13. package/dist/chat/index.js +2 -0
  14. package/dist/chat/platform.d.ts +4 -0
  15. package/dist/chat/platform.js +46 -0
  16. package/dist/chat/session.d.ts +19 -0
  17. package/dist/chat/session.js +95 -0
  18. package/dist/chat/useSkipsChat.d.ts +79 -0
  19. package/dist/chat/useSkipsChat.js +507 -0
  20. package/dist/chat/verify.d.ts +35 -0
  21. package/dist/chat/verify.js +84 -0
  22. package/dist/elements/skips-elements.js +18521 -0
  23. package/dist/helpers/attachments.d.ts +12 -0
  24. package/dist/helpers/attachments.js +34 -0
  25. package/dist/helpers/cable.d.ts +34 -0
  26. package/dist/helpers/cable.js +88 -0
  27. package/dist/helpers/cableFrames.d.ts +40 -0
  28. package/dist/helpers/cableFrames.js +70 -0
  29. package/dist/helpers/cardNote.d.ts +79 -0
  30. package/dist/helpers/cardNote.js +152 -0
  31. package/dist/helpers/commandNote.d.ts +4 -0
  32. package/dist/helpers/commandNote.js +23 -0
  33. package/dist/helpers/index.d.ts +19 -0
  34. package/dist/helpers/index.js +19 -0
  35. package/dist/helpers/markdown.d.ts +47 -0
  36. package/dist/helpers/markdown.js +129 -0
  37. package/dist/helpers/medicationOrder.d.ts +333 -0
  38. package/dist/helpers/medicationOrder.js +383 -0
  39. package/dist/helpers/message.d.ts +46 -0
  40. package/dist/helpers/message.js +12 -0
  41. package/dist/helpers/noteView.d.ts +35 -0
  42. package/dist/helpers/noteView.js +65 -0
  43. package/dist/helpers/orderForm.d.ts +126 -0
  44. package/dist/helpers/orderForm.js +271 -0
  45. package/dist/helpers/ordersMenu.d.ts +56 -0
  46. package/dist/helpers/ordersMenu.js +129 -0
  47. package/dist/helpers/regimenChoice.d.ts +42 -0
  48. package/dist/helpers/regimenChoice.js +73 -0
  49. package/dist/helpers/scrollBox.d.ts +5 -0
  50. package/dist/helpers/scrollBox.js +15 -0
  51. package/dist/helpers/skipTyping.d.ts +26 -0
  52. package/dist/helpers/skipTyping.js +29 -0
  53. package/dist/helpers/skipsMessage.d.ts +55 -0
  54. package/dist/helpers/skipsMessage.js +130 -0
  55. package/dist/helpers/stageRefill.d.ts +33 -0
  56. package/dist/helpers/stageRefill.js +41 -0
  57. package/dist/helpers/thread.d.ts +54 -0
  58. package/dist/helpers/thread.js +122 -0
  59. package/dist/helpers/typing.d.ts +13 -0
  60. package/dist/helpers/typing.js +68 -0
  61. package/dist/helpers/usrxNote.d.ts +22 -0
  62. package/dist/helpers/usrxNote.js +26 -0
  63. package/dist/helpers/visibleArea.d.ts +15 -0
  64. package/dist/helpers/visibleArea.js +11 -0
  65. package/dist/helpers/welcome.d.ts +25 -0
  66. package/dist/helpers/welcome.js +51 -0
  67. package/dist/hooks/index.d.ts +8 -0
  68. package/dist/hooks/index.js +8 -0
  69. package/dist/hooks/useCardNoteActions.d.ts +82 -0
  70. package/dist/hooks/useCardNoteActions.js +210 -0
  71. package/dist/hooks/useCodeEntry.d.ts +6 -0
  72. package/dist/hooks/useCodeEntry.js +14 -0
  73. package/dist/hooks/useComposer.d.ts +20 -0
  74. package/dist/hooks/useComposer.js +40 -0
  75. package/dist/hooks/useOrderForm.d.ts +80 -0
  76. package/dist/hooks/useOrderForm.js +403 -0
  77. package/dist/hooks/useOrdersMenu.d.ts +114 -0
  78. package/dist/hooks/useOrdersMenu.js +337 -0
  79. package/dist/hooks/useRegimenChoice.d.ts +23 -0
  80. package/dist/hooks/useRegimenChoice.js +50 -0
  81. package/dist/hooks/useResendCountdown.d.ts +2 -0
  82. package/dist/hooks/useResendCountdown.js +19 -0
  83. package/dist/hooks/useStepField.d.ts +8 -0
  84. package/dist/hooks/useStepField.js +17 -0
  85. package/dist/hooks/useTypingCue.d.ts +11 -0
  86. package/dist/hooks/useTypingCue.js +41 -0
  87. package/dist/hooks/useWelcomeTyping.d.ts +2 -0
  88. package/dist/hooks/useWelcomeTyping.js +25 -0
  89. package/dist/index.d.ts +5 -0
  90. package/dist/index.js +5 -0
  91. package/dist/staff/CardNoteActions.d.ts +10 -0
  92. package/dist/staff/CardNoteActions.js +16 -0
  93. package/dist/staff/OrderFormNote.d.ts +8 -0
  94. package/dist/staff/OrderFormNote.js +8 -0
  95. package/dist/staff/OrdersMenuNote.d.ts +8 -0
  96. package/dist/staff/OrdersMenuNote.js +8 -0
  97. package/dist/staff/RegimenChoiceNote.d.ts +7 -0
  98. package/dist/staff/RegimenChoiceNote.js +8 -0
  99. package/dist/staff/features.d.ts +9 -0
  100. package/dist/staff/features.js +8 -0
  101. package/dist/staff/index.d.ts +11 -0
  102. package/dist/staff/index.js +7 -0
  103. package/dist/ui/Bubble.d.ts +5 -0
  104. package/dist/ui/Bubble.js +9 -0
  105. package/dist/ui/CardActions.d.ts +34 -0
  106. package/dist/ui/CardActions.js +28 -0
  107. package/dist/ui/Conversation.d.ts +69 -0
  108. package/dist/ui/Conversation.js +192 -0
  109. package/dist/ui/Markdown.d.ts +11 -0
  110. package/dist/ui/Markdown.js +51 -0
  111. package/dist/ui/NoteFold.d.ts +19 -0
  112. package/dist/ui/NoteFold.js +12 -0
  113. package/dist/ui/NoteViewControl.d.ts +19 -0
  114. package/dist/ui/NoteViewControl.js +20 -0
  115. package/dist/ui/OrderForm.d.ts +71 -0
  116. package/dist/ui/OrderForm.js +118 -0
  117. package/dist/ui/OrdersMenu.d.ts +71 -0
  118. package/dist/ui/OrdersMenu.js +128 -0
  119. package/dist/ui/RegimenChoice.d.ts +23 -0
  120. package/dist/ui/RegimenChoice.js +16 -0
  121. package/dist/ui/SkipAvatar.d.ts +7 -0
  122. package/dist/ui/SkipAvatar.js +8 -0
  123. package/dist/ui/StaffButton.d.ts +18 -0
  124. package/dist/ui/StaffButton.js +17 -0
  125. package/dist/ui/Welcome.d.ts +91 -0
  126. package/dist/ui/Welcome.js +128 -0
  127. package/dist/ui/index.d.ts +8 -0
  128. package/dist/ui/index.js +7 -0
  129. package/dist/ui/parts.d.ts +38 -0
  130. package/dist/ui/parts.js +6 -0
  131. package/package.json +115 -4
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # common
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@joinskips/common`, the code the Skips apps share, built once in React Native: components, hooks and helpers. The member app renders it on web, iOS and Android, and joinskips.com renders it through react-native-web. Its first part is the Skips chat, `SkipsChat`, which both apps mount: joinskips.com in its chat island and the member app on its chat screen. The chat holds its own connection to the Skips App, and each app passes in who is chatting, the opening line, its words, addresses and brand tokens.
4
+
5
+ ## Styling
6
+
7
+ Components are styled with Tailwind 4 classes, which Uniwind compiles in the app that renders them: through Metro in an Expo app, and through Uniwind's Vite plugin with `vite-plugin-rnw` on a Vite site. react-native-web drops a `className` prop, so the classes render only through that step. Tailwind skips `node_modules`, so each app names the package in its CSS entry, with the path relative to that file:
8
+
9
+ ```css
10
+ @import 'tailwindcss';
11
+ @import 'uniwind';
12
+ @source '../node_modules/@joinskips/common';
13
+ ```
14
+
15
+ Each app's theme, generated from the brand tokens, gives every class the package uses: the colour roles (`bg-surface`, `text-ink`, `text-error-ink` and the rest), the font families `font-ui` and `font-mono`, the type sizes, the radii `control` and `pill`, the shadow `card`, the spacing `control`, `control-compact`, `control-tall` and `gutter-phone`, and the container `reading`. `scripts/storybook-theme.ts` builds the same theme for Storybook and the elements' bundle from `@joinskips/brand`.
16
+
17
+ ## Using it
18
+
19
+ `@joinskips/common` exports everything, and has one entry point for each kind of code. Apart from the elements' bundle, the package has no side effects on import, so an app's bundler keeps only what the app uses either way:
20
+
21
+ - `@joinskips/common/ui`: the components. Each draws the values it is given and hands each press and keystroke back to a callback. The only state a component keeps is how it draws: focus, an image that has not loaded yet, and its animation.
22
+ - `@joinskips/common/hooks`: the behavior the components draw. `useComposer` runs the message box. `useStepField`, `useCodeEntry` and `useResendCountdown` run the welcome's steps. `useTypingCue` times Skip's typing dots in a conversation, and `useWelcomeTyping` times them in the welcome.
23
+ - `@joinskips/common/helpers`: the logic with no React. It holds the thread reducers, the typing signal and watch, the welcome's checks and times, the attachment rules, the message types and `fitVisibleArea`. It also holds the Skips App's live feed: `openCable` subscribes the member's pubsub tokens on the Skips App's socket, reports it connecting, live or down, and reconnects with a doubling wait, and `readFrame` reads each frame into the message, typing and conversation events an app acts on. `toChatMessage` turns a Skips App message from its API or its socket into the member's view, so a private note or an internal activity line never reaches the member.
24
+
25
+ The helpers also hold the rules of the Skips App's staff features, which the web dashboard and the mobile app both draw, reading a conversation's messages as `StaffMessage` with camelCase keys: `medicationOrder` for the Order form and the Orders menu (the SIG, the dispense amount, the `usrx_order` note and the past orders' rows), `ordersMenu` for the Orders menu's lists, tags, status filter and the Cancel Rx, Discontinue and Change pharmacy notes, `orderForm` for the Order form's medicines, rounds, pharmacy search and when Create, Update or a queued save may run, `stageRefill` for a refill to the same pharmacy, which posts its order note with no form unless it lacks something or Treat holds several charts, `cardNote` for usrx's card notes and the Send, Cancel and Discontinue commands, `regimenChoice` for the regimen choice note and its pick, `commandNote` for folding a command and its answer to one line, and `noteView` for showing all, the messages only or the notes only. A note's `contentAttributes` is read as unknown and checked, since it is what the Skips App sent.
26
+ - `@joinskips/common/staff`: the Skips App's staff features, each drawn from a conversation's messages and handing what staff do back to the app, and `SKIPS_FEATURES`, the list of them. `RegimenChoiceNote` is usrx's regimen choice note: the app passes the conversation's messages, the note's id and `contentAttributes`, its words, and `sendNote`, which posts a private note and reports its own failure. `CardNoteActions` is usrx's card note with its Send, Edit and Delete: the app also passes the staff member's `role`, `readCards` and `deleteCard`, which call the Skips App's `treat_lookups`, and `editCard`, which opens a card in its order form, or nothing for an app without one, which then shows no Edit. When usrx's note says it left a controlled card unsigned (`usrxSigningCode`), the note shows a provider or an admin a field for the ID.me app's six-digit code, and the app's `sendWithCode` sends the code with those cards to `treat_lookups`' `send_with_code`, never into a note, and rejects when it did not reach usrx. A delete asks in the note itself, since a dialog would draw outside a web element's shadow root. `NoteFold` is a command note's fold, its first line and time while folded and Show less while open, and `NoteViewControl` is the thread's choice of all, the messages only or the notes only. For both, the app keeps the state (whether the note is open, the view chosen), shows or filters its own thread with `isCommandNote` and `notesInView`, and gets each press back. `OrdersMenuNote` is the Orders menu beside the private note box: the staged cards, current orders, refills and past orders, with their actions. The app passes the `conversationId`, its `messages`, the staff member's `role`, its `words` and `openLink`, and calls of its own: `readStaged` and `readPast`, which read the conversation's staged cards and sent orders from `treat_lookups`, `deleteCard` and `deleteQueued`, `sendNote`, `openForm`, which opens its order form, `stageRefill`, which stages a refill to the same pharmacy and rejects when that fails, and `formChanges`, a count it raises each time its order form changed the cards. Without `openForm`, New order, Edit, Send, Refill and Re-order are off. `OrderFormNote` is the Order form the app shows in its own dialog for the menu's `OrderFormRequest`: blank, a staged card to change or send, a queued medicine, or a sent order to order again. The app passes the `conversationId`, the staff member's `role`, the `request`, its `words` and `openLink`, its `treat_lookups` calls (`findDrugs`, `readChoices`, `findPharmacies`, `readCharts`, `updateCard`, `updateQueued`), each rejecting with the lookup's answer when it fails, `postOrder`, which posts the order note with `usrx_order`, `sendNote`, `changed`, which makes the menu read Treat again, and `close`. The mobile app draws these directly.
27
+ - `@joinskips/common/elements`: the same staff features as custom elements, one JavaScript file with React, react-native-web, Uniwind and the brand theme inside, for the Skips App's web dashboard. `defineSkipsElements()` defines an element per feature in `SKIPS_FEATURES` (`<skips-regimen-choice>`, `<skips-card-note-actions>`, `<skips-note-fold>`, `<skips-note-view>`, `<skips-orders-menu>`, `<skips-order-form>`), and the dashboard sets an element's `value` to the feature's props, callbacks among them. Each element draws in its own shadow root, so the dashboard's styles and its own leave each other alone. Uniwind's web runtime keeps its theme as a class on `<html>`, so the bundle copies the dashboard's `dark` class from `<body>` to `<html>` as it loads and follows it after, and puts only the brand's colour variables, the Onest font faces and Tailwind's `@property` rules in the document, since Chrome ignores a font face or an `@property` rule inside a shadow root. The bundle also exports `stageRefill` from `helpers/stageRefill.ts` and its outcomes `POSTED`, `OPEN_FORM`, `PICK_CHART` and `LEFT`. Given a past order, a promise that settles once no Treat read is on the way, and a `StageRefillSource` (the conversation, the Treat reads, the order note's post and whether the conversation is still the one shown), it posts a refill to the same pharmacy with no form, or answers with the outcome that asks for the form, for a chart to pick, or for nothing because the conversation changed.
28
+ - `@joinskips/common/chat`: `SkipsChat`, below, and the session helpers an app reads beside it.
29
+ - `@joinskips/common/connection`: the chat's Skips App client, session and platform pieces without its screen, for code that runs without React Native, such as an app's Node tests.
30
+
31
+ ## SkipsChat
32
+
33
+ `SkipsChat` is the whole chat: the welcome for a new visitor, the conversation, Skip's questions and typing dots, and the message box. It calls the Skips App's public Client API itself (`src/chat/client.ts`) and keeps its conversation live on `openCable`, so a phone and a browser reach the Skips App the same way. The calls' types come from the Skips App's description pinned in `api/upstream.json` (`npm run api:pull`, then `npm run api`).
34
+
35
+ An app passes:
36
+
37
+ - `baseUrl`, `inboxIdentifier` and `careTeamName`: the Skips App, the inbox a new conversation lands in, and the app's words for a care team line whose sender the Skips App leaves unnamed.
38
+ - `pageAddress`: the website page a visitor's conversation was opened from, which the care team sees. Never a query string. A conversation started with one is marked `website_chat` with the page as its referer, which is where Skip asks questions with buttons. One started without it is not, as a member's is not.
39
+ - `opening`: the first line, sent as soon as the chat opens.
40
+ - `draft`: what the box starts with, unsent.
41
+ - `notice`: a line under the conversation's last message, centred in the secondary ink, such as that a conversation the care team closed opens again when the member writes. Nothing shows without it.
42
+ - `member`: for a member signed in on the app, their Skips App contact and the conversation to open, or null to start one with their first line. `onStarted` is told the new conversation's id once that first line is in it, and `onSent` each line of theirs the Skips App has. A member is never welcomed, the chat signs them out only when the Skips App refuses their conversation or key, and nothing goes in the store.
43
+ - `welcome`: without `member`, a visitor with no conversation is welcomed first. They log in through the app's `onLogIn`, which is given their waiting line, or continue here with an email, the code the `verifyUrl` service emails to it, and a name if the Skips App does not know them.
44
+ - `onSignedOut`: a visitor's conversation is kept in the tab's `sessionStorage`, in memory on a phone, and signs itself out after `SESSION_IDLE_MS` unused.
45
+ - `fetchFn`, `createSocket`, `store` and `now` only to stand in for the platform's own, as a story or a local stand-in does.
46
+ - `words` (`SkipsChatWords`), `Icon`, `skipMark`, `skipUserId`, and `pickFile` for photos and PDFs.
47
+
48
+ A line, a photo or a PDF goes as a message, and older messages load as the member scrolls back. The care team sees the visitor typing and when they have read the conversation. While Skip types, a new line, a retry and an answer wait for Skip to finish, and a reply that lands inside Skip's first second of typing waits it out.
49
+
50
+ `Conversation` is one conversation: the thread in runs by sender, notices, unsent lines with retry, typing, photos and files, and the message box with attach and send. The app keeps the thread with the reducers from the helpers and its own connection, and passes:
51
+
52
+ - `words`: every word the chat shows (`ChatWords`).
53
+ - `Icon`: the app's own icon component, given `attach`, `arrow-right`, `file` or `close`.
54
+ - `skipMark`: the image source of Skip's mark.
55
+ - `composer`: from `useComposer`, given the app's `onSend`, `onTyped`, `initialText` and `pickFile`. Without `pickFile` there is no attach button. `pickFile` resolves null when nothing was picked and never rejects, so a picker that fails, as on a refused photo permission, tells the member itself.
56
+ - The callbacks `onRetry`, `onLoadOlder` and `onReload`.
57
+
58
+ An address the device must reach differently, such as `localhost` from an Android emulator, is mapped by the app when it builds each `ChatMessage`.
59
+
60
+ Lines from Skips draw their Markdown with no HTML taken from it, and only `http`, `https`, `mailto` and `tel` addresses become links. The member's own lines show exactly as typed.
61
+
62
+ The website's welcome is a set of parts the website places in its thread, each taking its words from `WelcomeWords`:
63
+
64
+ - `WelcomeChoice`: log in or continue here.
65
+ - `Choices`: the answers to a question from Skips, all held while one is on its way or while Skip types.
66
+ - `EmailStep` and `NameStep`: one field each, whose `field` comes from `useStepField` with `givenEmail` or `givenName`, so what was typed is trimmed and checked before it goes on. The email step shows the `terms` words under its button, as Markdown with their links.
67
+ - `CodeStep`: the emailed code, in one field of large spaced digits. Its `entry` comes from `useCodeEntry`, which sends the code by itself once whole, and its `secondsLeft` from `useResendCountdown(RESEND_AFTER_MS)`. The app calls both in a component it mounts afresh for each code that goes out.
68
+ - `SkipTyping`: Skip's typing dots, drawn while `useTypingCue` or `useWelcomeTyping` says Skip is typing.
69
+ - `Pill`: the chat's button, black, white or a plain link. Black and white are the member sign-in's button, as wide as their column, and a plain link is the only smaller one. `back` leads with an arrow.
70
+
71
+ `fitVisibleArea` sizes the website's full-screen chat to the part of the page the phone's keyboard leaves visible.
72
+
73
+ Uniwind carries its own Tailwind compiler, so `uniwind` is a peer dependency pinned to one version, and every app installs that version. An upgrade of Uniwind or Tailwind changes the peer range here first and ships as a release.
74
+
75
+ ## Commands
76
+
77
+ ```sh
78
+ npm ci
79
+ npm run build # dist/: the JavaScript and its types, and dist/elements/skips-elements.js from vite.elements.config.ts
80
+ npm run check # the type check
81
+ npm run lint # the lint
82
+ npm test # Vitest: the logic in Node, every story in headless Chromium with axe, 100 percent coverage
83
+ npm run storybook # http://localhost:6007, each component in light and dark
84
+ ```
85
+
86
+ `npx playwright install chromium` once per machine, for the stories. A story's play is the test of an interaction the component owns.
87
+
88
+ ## How it ships
89
+
90
+ Work reaches `develop` by pull request, and a release pull request from `develop` to `main` ships it. A pull request into `develop` runs the same checks as one into `main`, and its ruleset takes no merge until they pass. A pull request into `main` runs the type check, the lint, the tests and the build on the `browser-checks` runner, since the stories run in Chromium.
91
+
92
+ The npm job is off, so nothing below publishes ([#11](https://github.com/joinskips/chat/issues/11)).
93
+
94
+ A push to `develop` publishes `<version>-develop.<run>` under the `develop` tag, and a push to `main` publishes `<version>` under `latest`, where `<version>` is `package.json`'s and `<run>` is the workflow run's number. A version npm already has is skipped, so a release raises `version` in its pull request into `main`.
95
+
96
+ ```sh
97
+ npm install @joinskips/common@develop # develop as it is
98
+ npm install @joinskips/common@0.1.0 # a release
99
+ ```
100
+
101
+ `.github/workflows/release.yml` publishes through npm trusted publishing: the package's trusted publisher on npmjs.com is `joinskips/common`, workflow `release.yml`, and npm takes the run's OIDC identity with no token. npm runs trusted publishing on GitHub-hosted runners only, so that job runs on `ubuntu-24.04`.
102
+
103
+ ## Issues
104
+
105
+ A pull request into `develop` names the issues it ships as `Ships #N`, never `Fixes #N` or `Closes #N`, so nothing closes before the release. A release pull request into `main` lists `Closes #N` for each issue it ships, and GitHub closes them when it merges.
@@ -0,0 +1,37 @@
1
+ import type { ImageSourcePropType } from 'react-native';
2
+ import { type PickedFile, type TypingTimes, type WelcomeTypingTimes } from '../helpers/index.ts';
3
+ import type { ChatIcon, ChatWords } from '../ui/parts.ts';
4
+ import { type WelcomeWords } from '../ui/Welcome.tsx';
5
+ import { type SkipsChatOptions } from './useSkipsChat.ts';
6
+ export interface SkipsChatWords extends ChatWords {
7
+ thread: string;
8
+ welcome: WelcomeWords;
9
+ welcomeText: string;
10
+ emailText: string;
11
+ nameText: string;
12
+ codeText: (email: string) => string;
13
+ unreachable: string;
14
+ tryAgain: string;
15
+ }
16
+ export interface SkipsChatWelcome {
17
+ verifyUrl: string;
18
+ onLogIn: (line: string) => void;
19
+ codeNote?: string | undefined;
20
+ resendAfterMs?: number | undefined;
21
+ typing?: WelcomeTypingTimes | undefined;
22
+ }
23
+ export interface SkipsChatProps extends Omit<SkipsChatOptions, 'verifyUrl'> {
24
+ welcome?: SkipsChatWelcome | undefined;
25
+ words: SkipsChatWords;
26
+ Icon: ChatIcon;
27
+ skipMark: ImageSourcePropType;
28
+ skipUserId: number | null;
29
+ typingTimes?: TypingTimes | undefined;
30
+ pickFile?: (() => Promise<PickedFile | null>) | undefined;
31
+ keyboardOffset?: number | undefined;
32
+ bottomInset?: number | undefined;
33
+ draft?: string | undefined;
34
+ notice?: string | undefined;
35
+ }
36
+ /** The one Skips chat: the welcome for a new visitor, the conversation, Skip's questions and dots, and the box. */
37
+ export declare function SkipsChat({ welcome, words, Icon, skipMark, skipUserId, typingTimes, pickFile, keyboardOffset, bottomInset, draft, notice, ...options }: SkipsChatProps): import("react").JSX.Element;
@@ -0,0 +1,103 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Text, View } from 'react-native';
3
+ import { givenEmail, givenName, RESEND_AFTER_MS, } from "../helpers/index.js";
4
+ import { useCodeEntry, useComposer, useResendCountdown, useStepField, useTypingCue, useWelcomeTyping, } from "../hooks/index.js";
5
+ import { Bubble } from "../ui/Bubble.js";
6
+ import { Conversation, Unsent } from "../ui/Conversation.js";
7
+ import { SkipAvatar } from "../ui/SkipAvatar.js";
8
+ import { CodeStep, EmailStep, NameStep, Pill, SkipTyping, WelcomeChoice } from "../ui/Welcome.js";
9
+ import { CODE_LENGTH } from "./verify.js";
10
+ import { useSkipsChat, } from "./useSkipsChat.js";
11
+ /** The one Skips chat: the welcome for a new visitor, the conversation, Skip's questions and dots, and the box. */
12
+ export function SkipsChat({ welcome, words, Icon, skipMark, skipUserId, typingTimes, pickFile, keyboardOffset, bottomInset, draft = '', notice, ...options }) {
13
+ const chat = useSkipsChat({ ...options, verifyUrl: welcome?.verifyUrl });
14
+ const { thread, status, welcome: way } = chat;
15
+ const cue = useTypingCue(thread.messages.filter((message) => !message.mine).map((message) => message.id), chat.skipsTyping, typingTimes);
16
+ const welcomeTyping = useWelcomeTyping(way?.step ?? null, welcome?.typing);
17
+ const composer = useComposer({
18
+ onSend: (text, picked) => {
19
+ chat.stillHere();
20
+ void chat.send(text, picked);
21
+ },
22
+ onTyped: (text) => {
23
+ chat.stillHere();
24
+ chat.typed(text);
25
+ },
26
+ ...(pickFile ? { pickFile } : {}),
27
+ initialText: draft,
28
+ });
29
+ // The visitor's first line stays where they wrote it, above the welcome. Once they are through, it is the
30
+ // conversation's first line.
31
+ const opening = way?.step === 'through'
32
+ ? thread.messages.find((message) => message.id === way.lineId || message.localId === way.lineId)
33
+ : undefined;
34
+ // A sign-in that continued an open conversation brought lines older than the visitor's, so the conversation reads
35
+ // in time order with no welcome above it.
36
+ const { continued } = chat;
37
+ const retry = (id) => {
38
+ for (const failed of thread.messages)
39
+ if (failed.id === id)
40
+ void chat.retry(failed);
41
+ };
42
+ const hidden = new Set(cue.held);
43
+ if (opening && !continued)
44
+ hidden.add(opening.id);
45
+ const load = status === 'starting' && way === null && thread.messages.length === 0 ? 'loading' : 'ready';
46
+ return (_jsx(View, { className: "flex-1",
47
+ // A tap anywhere in the chat is the visitor still being there. Asked on the way down, it takes nothing over.
48
+ onStartShouldSetResponderCapture: () => {
49
+ chat.stillHere();
50
+ return false;
51
+ }, children: _jsx(Conversation, { thread: thread, load: load, feedDown: chat.reconnecting, typists: [], skipUserId: skipUserId, composer: composer, composerClosed: status !== 'ready' || (way !== null && way.step !== 'through'), focusBox: way?.step === 'through', holding: cue.dots, onRetry: retry, onLoadOlder: () => void chat.loadOlder(), onReload: chat.tryAgain, keyboardOffset: keyboardOffset, bottomInset: bottomInset, words: words, Icon: Icon, skipMark: skipMark, label: words.thread, hidden: hidden, choices: {
52
+ sending: chat.choosing,
53
+ failed: chat.choiceFailed,
54
+ holding: cue.dots,
55
+ words: words.welcome,
56
+ onChoose: (question, answer) => void chat.choose(question, answer),
57
+ }, lead: way !== null && welcome !== undefined && !continued ? (_jsx(WelcomeLead, { way: way, opening: opening, welcome: welcome, words: words, Icon: Icon, typing: welcomeTyping, holding: cue.dots, onRetry: retry, chat: chat, skipMark: skipMark })) : null, trail: _jsxs(_Fragment, { children: [notice ? (_jsx(Text, { role: "status", className: "text-center font-ui text-sm text-ink-secondary", children: notice })) : null, cue.dots || welcomeTyping !== null ? _jsx(SkipTyping, { label: words.welcome.typing, skipMark: skipMark }) : null, status === 'unreachable' || way?.unreachable === true ? (_jsxs(View, { role: "alert", className: "w-full max-w-[360px] items-center gap-2 self-center", children: [_jsx(Text, { className: "font-ui text-sm text-error-ink", children: words.unreachable }), status === 'unreachable' ? _jsx(Pill, { label: words.tryAgain, onPress: chat.tryAgain }) : null] })) : null] }) }) }));
58
+ }
59
+ // The welcome, line by line: each step's line, and its field or buttons, show once Skip has typed it.
60
+ function WelcomeLead({ way, opening, welcome, words, Icon, typing, holding, onRetry, chat, skipMark }) {
61
+ const typed = (step) => typing !== step;
62
+ const skip = (text) => _jsx(SkipLine, { text: text, label: words.skip, skipMark: skipMark });
63
+ const asked = way.step === 'code' || way.step === 'name' || (way.step === 'through' && !way.signedIn);
64
+ return (_jsxs(View, { className: "gap-4 pb-4", children: [opening && opening.delivery !== 'sent' ? (_jsx(Unsent, { message: opening, words: words, onRetry: onRetry, Icon: Icon, holding: holding })) : (_jsxs(View, { className: "items-end gap-1 self-end", children: [_jsx(Bubble, { mine: true, text: opening?.text ?? way.line }), _jsx(LineLabel, { text: opening ? `${words.you} · ${words.messageTime(opening.sentAt)}` : words.you })] })), typed('choosing') ? skip(words.welcomeText) : null, way.step === 'choosing' ? (typed('choosing') ? (_jsx(WelcomeChoice, { words: words.welcome, onLogIn: () => {
65
+ welcome.onLogIn(way.line);
66
+ }, onContinueHere: () => {
67
+ chat.continueHere(way.line);
68
+ } })) : null) : !(way.step === 'through' && way.signedIn) && typed('email') ? (skip(words.emailText)) : null, way.step === 'email' && typed('email') ? (_jsx(EmailField, { initial: way.email ?? '', words: words.welcome, onSubmit: (email) => {
69
+ void chat.sendCode(email);
70
+ } })) : null, asked && typed('code') ? (_jsxs(_Fragment, { children: [skip(words.codeText(way.email)), welcome.codeNote === undefined ? null : skip(welcome.codeNote)] })) : null, way.step === 'code' && typed('code') ? (_jsx(CodeField, { step: way, words: words.welcome,
71
+ // No new code has gone out since the one that ran out, so there is no wait to sit through.
72
+ resendAfterMs: way.ranOut ? 0 : (welcome.resendAfterMs ?? RESEND_AFTER_MS), chat: chat }, way.codes)) : null, (way.step === 'name' || (way.step === 'through' && way.named)) && typed('name') ? skip(words.nameText) : null, way.step === 'name' && typed('name') ? _jsx(NameField, { step: way, words: words.welcome, chat: chat }) : null] }));
73
+ }
74
+ // A line of Skip's as the thread draws one: Skip's mark beside it and the label under it.
75
+ function SkipLine({ text, label, skipMark }) {
76
+ return (_jsxs(View, { className: "max-w-[82%] items-start gap-1 self-start", children: [_jsxs(View, { className: "flex-row items-end gap-2", children: [_jsx(SkipAvatar, { skipMark: skipMark }), _jsx(View, { className: "shrink", children: _jsx(Bubble, { text: text }) })] }), _jsx(View, { className: "ml-10", children: _jsx(LineLabel, { text: label }) })] }));
77
+ }
78
+ // Who said a line of the welcome, as the thread names each run of lines.
79
+ function LineLabel({ text }) {
80
+ return _jsx(Text, { className: "px-1 font-ui text-xs text-ink-secondary", children: text });
81
+ }
82
+ function EmailField({ initial, words, onSubmit }) {
83
+ return _jsx(EmailStep, { words: words, field: useStepField(givenEmail, onSubmit, initial) });
84
+ }
85
+ function NameField({ step, words, chat }) {
86
+ const field = useStepField(givenName, (name) => {
87
+ void chat.giveName(step, name);
88
+ });
89
+ return (_jsx(NameStep, { words: words, field: field, onChangeEmail: () => {
90
+ chat.changeEmail(step);
91
+ } }));
92
+ }
93
+ // Mounted afresh for each code that goes out.
94
+ function CodeField({ step, words, resendAfterMs, chat }) {
95
+ const onSubmit = (code) => {
96
+ void chat.checkCode(step, code);
97
+ };
98
+ return (_jsx(CodeStep, { words: words, length: CODE_LENGTH, noMatch: step.noMatch, ranOut: step.ranOut, entry: useCodeEntry(CODE_LENGTH, onSubmit), secondsLeft: useResendCountdown(resendAfterMs), onSubmit: onSubmit, onResend: () => {
99
+ void chat.sendCode(step.email);
100
+ }, onChangeEmail: () => {
101
+ chat.changeEmail(step);
102
+ } }));
103
+ }
@@ -0,0 +1,53 @@
1
+ import { type ChatMessage, type ChoiceItem, type PickedFile, type RawMessage } from '../helpers/index.ts';
2
+ export interface ChatClientOptions {
3
+ baseUrl: string;
4
+ inboxIdentifier: string;
5
+ careTeamName: string;
6
+ fetchFn?: typeof fetch;
7
+ }
8
+ export interface ContactSession {
9
+ sourceId: string;
10
+ pubsubToken: string;
11
+ inboxIdentifier?: string;
12
+ }
13
+ export interface Conversation {
14
+ id: number;
15
+ }
16
+ export declare const WEBSITE_CHAT_ATTRIBUTE = "website_chat";
17
+ export declare class ChatApiError extends Error {
18
+ readonly status: number;
19
+ constructor(status: number, detail: string);
20
+ }
21
+ /** A conversation as the Skips App started it, or continued it with the lines it already has. */
22
+ export interface StartedConversation extends Conversation {
23
+ history: ChatMessage[];
24
+ }
25
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
26
+ export declare function isInbox(value: unknown): value is string;
27
+ export declare function contactSessionFrom(value: unknown): ContactSession | null;
28
+ /**
29
+ * The visitor's view of a Skips App message, or null for one they never see. A care team member's photo shows only
30
+ * from a secure web address, so the page never loads one over plain http, and their name stays without it.
31
+ */
32
+ export declare function visitorView(raw: RawMessage, careTeamName: string): ChatMessage | null;
33
+ export declare class ChatClient {
34
+ private readonly baseUrl;
35
+ private readonly inbox;
36
+ private readonly careTeamName;
37
+ private readonly fetchFn;
38
+ constructor({ baseUrl, inboxIdentifier, careTeamName, fetchFn }: ChatClientOptions);
39
+ private messageFrom;
40
+ private url;
41
+ private inboxOf;
42
+ private request;
43
+ createContact(): Promise<ContactSession>;
44
+ /** `startingPage` is the page the chat was opened on, which the Skips App shows the care team as the conversation's referer. */
45
+ createConversation(contact: ContactSession, startingPage?: string): Promise<StartedConversation>;
46
+ choose(contact: ContactSession, conversation: Conversation, question: number, answer: ChoiceItem): Promise<ChatMessage>;
47
+ private conversationPath;
48
+ sendMessage(contact: ContactSession, conversation: Conversation, text: string, picked?: PickedFile | null): Promise<ChatMessage>;
49
+ listMessages(contact: ContactSession, conversation: Conversation, before?: number): Promise<ChatMessage[]>;
50
+ private visible;
51
+ typing(contact: ContactSession, conversation: Conversation, on: boolean): Promise<void>;
52
+ seen(contact: ContactSession, conversation: Conversation): Promise<void>;
53
+ }
@@ -0,0 +1,178 @@
1
+ // The Skips App's public Client API, the part of it a visitor's browser may call with
2
+ // no secret: make a contact, open a conversation, send and list messages. The inbox
3
+ // identifier is public by design. Plain fetch, no framework, so a native app can use it.
4
+ import { isRawMessage, toChatMessage, } from "../helpers/index.js";
5
+ // The conversation attribute the chat sets on each conversation it opens, so Skips asks a question with buttons only
6
+ // where they can be pressed.
7
+ export const WEBSITE_CHAT_ATTRIBUTE = 'website_chat';
8
+ export class ChatApiError extends Error {
9
+ status;
10
+ constructor(status, detail) {
11
+ super(`Skips App answered ${String(status)}: ${detail}`);
12
+ this.name = 'ChatApiError';
13
+ this.status = status;
14
+ }
15
+ }
16
+ export function isRecord(value) {
17
+ return typeof value === 'object' && value !== null;
18
+ }
19
+ // An inbox's identifier as a contact can carry it.
20
+ export function isInbox(value) {
21
+ return typeof value === 'string' && value.length > 0;
22
+ }
23
+ // An inbox that is named and cannot be used is not left out: the contact is in it, so the built-in one is wrong.
24
+ function isContactResponse(value) {
25
+ return (isRecord(value) &&
26
+ typeof value.source_id === 'string' &&
27
+ typeof value.pubsub_token === 'string' &&
28
+ (value.inbox_identifier === undefined || isInbox(value.inbox_identifier)));
29
+ }
30
+ // The contact as the Skips App answers with it, from its own route or by way of the code service.
31
+ export function contactSessionFrom(value) {
32
+ if (!isContactResponse(value))
33
+ return null;
34
+ const contact = { sourceId: value.source_id, pubsubToken: value.pubsub_token };
35
+ return value.inbox_identifier === undefined
36
+ ? contact
37
+ : { ...contact, inboxIdentifier: value.inbox_identifier };
38
+ }
39
+ function isConversationResponse(value) {
40
+ return isRecord(value) && typeof value.id === 'number';
41
+ }
42
+ function isSecureAddress(address) {
43
+ try {
44
+ return new URL(address).protocol === 'https:';
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ /**
51
+ * The visitor's view of a Skips App message, or null for one they never see. A care team member's photo shows only
52
+ * from a secure web address, so the page never loads one over plain http, and their name stays without it.
53
+ */
54
+ export function visitorView(raw, careTeamName) {
55
+ const message = toChatMessage(raw, careTeamName);
56
+ const photo = message?.author?.avatarUrl;
57
+ if (!message?.author || photo === null || photo === undefined || isSecureAddress(photo)) {
58
+ return message;
59
+ }
60
+ return { ...message, author: { ...message.author, avatarUrl: null } };
61
+ }
62
+ export class ChatClient {
63
+ baseUrl;
64
+ inbox;
65
+ careTeamName;
66
+ fetchFn;
67
+ constructor({ baseUrl, inboxIdentifier, careTeamName, fetchFn = fetch }) {
68
+ this.baseUrl = baseUrl.replace(/\/$/, '');
69
+ this.inbox = inboxIdentifier;
70
+ this.careTeamName = careTeamName;
71
+ this.fetchFn = fetchFn;
72
+ }
73
+ // A message the Skips App answered with, as the visitor sees it. One it stored for the visitor is never hidden.
74
+ messageFrom(body) {
75
+ const message = isRawMessage(body) ? visitorView(body, this.careTeamName) : null;
76
+ if (!message)
77
+ throw new ChatApiError(200, 'unexpected message shape');
78
+ return message;
79
+ }
80
+ url(inbox, path) {
81
+ return `${this.baseUrl}/public/api/v1/inboxes/${inbox}${path}`;
82
+ }
83
+ // A contact's own routes are in the inbox the contact was made in.
84
+ inboxOf(contact) {
85
+ return contact.inboxIdentifier ?? this.inbox;
86
+ }
87
+ async request(inbox, path, init = {}) {
88
+ const headers = new Headers(init.headers);
89
+ // A photo goes as a form, whose boundary fetch writes into the type itself.
90
+ if (!(init.body instanceof FormData))
91
+ headers.set('Content-Type', 'application/json');
92
+ headers.set('Accept', 'application/json');
93
+ // Called detached: window.fetch throws when any other object is its this.
94
+ const { fetchFn } = this;
95
+ const response = await fetchFn(this.url(inbox, path), { ...init, headers });
96
+ const body = await response.json().catch(() => null);
97
+ if (!response.ok) {
98
+ const detail = isRecord(body) && typeof body.error === 'string' ? body.error : response.statusText;
99
+ throw new ChatApiError(response.status, detail);
100
+ }
101
+ return body;
102
+ }
103
+ async createContact() {
104
+ const contact = contactSessionFrom(await this.request(this.inbox, '/contacts', {
105
+ method: 'POST',
106
+ body: JSON.stringify({}),
107
+ }));
108
+ if (!contact)
109
+ throw new ChatApiError(200, 'unexpected contact shape');
110
+ return contact;
111
+ }
112
+ /** `startingPage` is the page the chat was opened on, which the Skips App shows the care team as the conversation's referer. */
113
+ async createConversation(contact, startingPage) {
114
+ // Skips asks a question with buttons only in a conversation the website chat opened.
115
+ const conversation = startingPage
116
+ ? { referer_url: startingPage, custom_attributes: { [WEBSITE_CHAT_ATTRIBUTE]: true } }
117
+ : {};
118
+ const body = await this.request(this.inboxOf(contact), `/contacts/${contact.sourceId}/conversations`, { method: 'POST', body: JSON.stringify(conversation) });
119
+ if (!isConversationResponse(body))
120
+ throw new ChatApiError(200, 'unexpected conversation shape');
121
+ // The Skips App continues a member's open conversation (its patch 120), and answers with its lines.
122
+ return { id: body.id, history: Array.isArray(body.messages) ? this.visible(body.messages) : [] };
123
+ }
124
+ // The visitor's answer to a question from Skips, kept on the question itself, where a reload finds it.
125
+ async choose(contact, conversation, question, answer) {
126
+ const body = await this.request(this.inboxOf(contact), `/contacts/${contact.sourceId}/conversations/${String(conversation.id)}/messages/${String(question)}`, {
127
+ method: 'PATCH',
128
+ body: JSON.stringify({
129
+ submitted_values: [{ title: answer.title, value: answer.value }],
130
+ }),
131
+ });
132
+ return this.messageFrom(body);
133
+ }
134
+ conversationPath(contact, conversation, path) {
135
+ return `/contacts/${contact.sourceId}/conversations/${String(conversation.id)}${path}`;
136
+ }
137
+ // A line, a photo or PDF, or both. The description types the JSON body only: the form's attachments[] is what
138
+ // the Skips App's Chatwoot takes for files (app/controllers/public/api/v1/inboxes/messages_controller.rb).
139
+ async sendMessage(contact, conversation, text, picked = null) {
140
+ let body = JSON.stringify({ content: text });
141
+ if (picked) {
142
+ if (!picked.file)
143
+ throw new ChatApiError(0, 'picked file has no contents');
144
+ const form = new FormData();
145
+ form.append('content', text);
146
+ form.append('attachments[]', picked.file, picked.name);
147
+ body = form;
148
+ }
149
+ const answer = await this.request(this.inboxOf(contact), this.conversationPath(contact, conversation, '/messages'), { method: 'POST', body });
150
+ return this.messageFrom(answer);
151
+ }
152
+ // The newest page, or the page before a stored message.
153
+ async listMessages(contact, conversation, before) {
154
+ const query = before === undefined ? '' : `?before=${String(before)}`;
155
+ const body = await this.request(this.inboxOf(contact), this.conversationPath(contact, conversation, `/messages${query}`));
156
+ if (!Array.isArray(body))
157
+ throw new ChatApiError(200, 'unexpected messages shape');
158
+ return this.visible(body);
159
+ }
160
+ // The lines of a page the visitor sees.
161
+ visible(raws) {
162
+ return raws.filter(isRawMessage).flatMap((raw) => visitorView(raw, this.careTeamName) ?? []);
163
+ }
164
+ // Whether the visitor is typing, for the care team.
165
+ async typing(contact, conversation, on) {
166
+ const status = { typing_status: on ? 'on' : 'off' };
167
+ await this.request(this.inboxOf(contact), this.conversationPath(contact, conversation, '/toggle_typing'), {
168
+ method: 'POST',
169
+ body: JSON.stringify(status),
170
+ });
171
+ }
172
+ // The visitor has read the conversation up to now.
173
+ async seen(contact, conversation) {
174
+ await this.request(this.inboxOf(contact), this.conversationPath(contact, conversation, '/update_last_seen'), {
175
+ method: 'POST',
176
+ });
177
+ }
178
+ }
@@ -0,0 +1,4 @@
1
+ export { ChatApiError, ChatClient, WEBSITE_CHAT_ATTRIBUTE, type ContactSession } from './client.ts';
2
+ export { clearSession, loadReadThrough, loadSession, saveReadThrough, saveSession, SESSION_IDLE_MS, sessionEndsAt, type ChatSession, type SessionStore, } from './session.ts';
3
+ export { platformSocket, platformStore } from './platform.ts';
4
+ export { CODE_LENGTH } from './verify.ts';
@@ -0,0 +1,6 @@
1
+ // The chat's Skips App connection without its screen, for code that runs where React Native does not, as an app's
2
+ // Node tests and a header that only counts replies do.
3
+ export { ChatApiError, ChatClient, WEBSITE_CHAT_ATTRIBUTE } from "./client.js";
4
+ export { clearSession, loadReadThrough, loadSession, saveReadThrough, saveSession, SESSION_IDLE_MS, sessionEndsAt, } from "./session.js";
5
+ export { platformSocket, platformStore } from "./platform.js";
6
+ export { CODE_LENGTH } from "./verify.js";
@@ -0,0 +1 @@
1
+ export type { AccountId, AgentBotId, BadRequestError, ClientOptions, ContactSortParam, ConversationId, ConversationUuid, CreateAContactData, CreateAContactError, CreateAContactErrors, CreateAContactResponse, CreateAContactResponses, CreateAConversationData, CreateAConversationError, CreateAConversationErrors, CreateAConversationResponse, CreateAConversationResponses, CreateAMessageData, CreateAMessageError, CreateAMessageErrors, CreateAMessageResponse, CreateAMessageResponses, CustomFilterId, HookId, InboxId, MessageId, Page, PlatformUserId, PortalSlug, PublicContact, PublicContactCreateUpdatePayload, PublicContactIdentifier, PublicContactRecord, PublicConversation, PublicConversationCreatePayload, PublicInbox, PublicInboxIdentifier, PublicMessage, PublicMessageAttachment, PublicMessageCreatePayload, PublicMessageSender, PublicMessageUpdatePayload, ReportMetric, ReportType, RequestError, SourceId, TeamId, ToggleTypingStatusData, ToggleTypingStatusError, ToggleTypingStatusErrors, ToggleTypingStatusResponses, UpdateAMessageData, UpdateAMessageError, UpdateAMessageErrors, UpdateAMessageResponse, UpdateAMessageResponses, WebhookId } from './types.gen';
@@ -0,0 +1,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};