@proef/common-ui 2.6.43 → 2.6.45
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/dist/esm/index.js +2 -1
- package/dist/esm/v1/capabilities/onepoint-rn/connectInbox.js +6 -0
- package/dist/esm/v1/capabilities/onepoint-rn/connectInbox.js.map +1 -1
- package/dist/esm/v1/capabilities/onepoint-rn/connectOutbox.js.map +1 -1
- package/dist/esm/v1/capabilities/onepoint-rn/useOrientacaoNaApp.js +1 -1
- package/dist/esm/v1/capabilities/onepoint-rn/useOrientacaoNaApp.js.map +1 -1
- package/dist/esm/v1/components/feedback/OfflineBoxes/OfflineBoxes.js +13 -2
- package/dist/esm/v1/components/feedback/OfflineBoxes/OfflineBoxes.js.map +1 -1
- package/dist/esm/v1/components/feedback/OfflineBoxes/OfflineBoxesView.js +212 -30
- package/dist/esm/v1/components/feedback/OfflineBoxes/OfflineBoxesView.js.map +1 -1
- package/dist/style.components.css +1 -1
- package/dist/style.css +1 -1
- package/dist/style.layered.css +1 -1
- package/dist/types/v1/capabilities/onepoint-rn/connectInbox.d.ts +17 -0
- package/dist/types/v1/capabilities/onepoint-rn/connectOutbox.d.ts +4 -0
- package/dist/types/v1/capabilities/onepoint-rn/useOrientacaoNaApp.d.ts +5 -0
- package/dist/types/v1/components/feedback/OfflineBoxes/OfflineBoxes.d.ts +3 -2
- package/dist/types/v1/components/feedback/OfflineBoxes/OfflineBoxesView.d.ts +30 -1
- package/dist/types/v1/index.d.ts +2 -2
- package/package.json +1 -1
package/dist/esm/index.js
CHANGED
|
@@ -113,7 +113,7 @@ import { ESTILO_AVATAR_PILHA, PessoaComFoto, PilhaAvatares } from "./legacy/comp
|
|
|
113
113
|
import { ErroBridge, pedirAoNativo } from "./v1/capabilities/onepoint-rn/bridge.js";
|
|
114
114
|
import { FilterChips } from "./v1/primitives/display/FilterChips/FilterChips.js";
|
|
115
115
|
import { FontWeight } from "./legacy/constants/FontWeight.js";
|
|
116
|
-
import { INBOX_SAVED_AT_HEADER, connectInbox, inboxSavedAt, inboxStatus, syncInbox, watchInbox } from "./v1/capabilities/onepoint-rn/connectInbox.js";
|
|
116
|
+
import { INBOX_SAVED_AT_HEADER, connectInbox, inboxSavedAt, inboxStatus, readInbox, syncInbox, watchInbox } from "./v1/capabilities/onepoint-rn/connectInbox.js";
|
|
117
117
|
import { InputData, InputHora } from "./legacy/components/atoms/InputData/InputData.js";
|
|
118
118
|
import { Kpi } from "./v1/primitives/display/Kpi/Kpi.js";
|
|
119
119
|
import { LazyLoader } from "./legacy/components/organisms/LazyLoader/LazyLoader.js";
|
|
@@ -378,6 +378,7 @@ export {
|
|
|
378
378
|
orderColumns,
|
|
379
379
|
partialMatchWithUsername,
|
|
380
380
|
pedirAoNativo,
|
|
381
|
+
readInbox,
|
|
381
382
|
richTextContentClasses,
|
|
382
383
|
richTextIsEmpty,
|
|
383
384
|
richTextToPlain,
|
|
@@ -54,6 +54,11 @@ function inboxSavedAt(response) {
|
|
|
54
54
|
const savedAt = response.headers[INBOX_SAVED_AT_HEADER];
|
|
55
55
|
return typeof savedAt === "string" ? savedAt : null;
|
|
56
56
|
}
|
|
57
|
+
async function readInbox(options) {
|
|
58
|
+
const storageId = checkedStorageId(options.storageId, "readInbox");
|
|
59
|
+
if (!dentroDaApp()) return null;
|
|
60
|
+
return pedirAoNativo("inbox.read", { storageId, address: options.address, path: options.path }, BRIDGE_WAIT_MS);
|
|
61
|
+
}
|
|
57
62
|
async function inboxStatus(options) {
|
|
58
63
|
const storageId = checkedStorageId(options.storageId, "inboxStatus");
|
|
59
64
|
const inboxId = checkedInboxId(options.inboxId, "inboxStatus");
|
|
@@ -113,6 +118,7 @@ export {
|
|
|
113
118
|
connectInbox,
|
|
114
119
|
inboxSavedAt,
|
|
115
120
|
inboxStatus,
|
|
121
|
+
readInbox,
|
|
116
122
|
syncInbox,
|
|
117
123
|
watchInbox
|
|
118
124
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connectInbox.js","sources":["../../../../../src/v1/capabilities/onepoint-rn/connectInbox.ts"],"sourcesContent":["import axios, { AxiosError } from 'axios'\r\nimport type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'\r\nimport { onNativeEvent, pedirAoNativo } from './bridge'\r\nimport { dentroDaApp } from './dentroDaApp'\r\nimport { addressAndPath } from './requestAddress'\r\nimport { checkedStorageId } from './storageId'\r\n\r\nexport type PedidoInbox = 'inbox.read' | 'inbox.state' | 'inbox.sync'\r\n\r\nexport type InboxTier = 'account' | 'device'\r\n\r\nexport type InboxEach = {\r\n id: string\r\n stamp?: string\r\n list?: string\r\n paths: string[]\r\n}\r\n\r\nexport type InboxBundle = {\r\n ids: string\r\n list: string\r\n id: string\r\n parts: Record<string, string>\r\n since?: { param: string; from: string }\r\n missing?: { param: string }\r\n}\r\n\r\nexport type InboxGet = { path: string; tier?: InboxTier } & ({ each?: InboxEach; bundle?: never } | { bundle: InboxBundle; each?: never })\r\n\r\nexport type InboxOptions = { storageId: string | undefined }\r\n\r\nexport type InboxConnectOptions = InboxOptions & { paused?: () => boolean }\r\n\r\nexport type InboxSyncOptions = InboxOptions & { inboxId: string; tier: InboxTier; gets: InboxGet[] }\r\n\r\nexport type InboxProgress = { total: number; ready: number; failed: number }\r\n\r\nexport type InboxStatus = InboxProgress & { finishedAt: string | null; saved?: string[] }\r\n\r\nexport type InboxEvent = InboxProgress & { inboxId: string; finishedAt: string | null }\r\n\r\ndeclare module 'axios' {\r\n interface AxiosRequestConfig {\r\n inbox?: false\r\n }\r\n}\r\n\r\nexport const INBOX_SAVED_AT_HEADER = 'x-inbox-saved-at'\r\n\r\nconst INBOX_ID_FORMAT = /^[a-z0-9]+(-[a-z0-9]+)*$/\r\nconst BRIDGE_WAIT_MS = 30_000\r\nconst SYNC_WAIT_MS = 30 * 60_000\r\n\r\ntype InboxRead = { found: false } | { found: true; status: number; body: unknown; savedAt: string }\r\n\r\nfunction checkedInboxId(inboxId: string, caller: string): string {\r\n if (INBOX_ID_FORMAT.test(inboxId)) return inboxId\r\n throw new Error(`${caller}: inboxId \"${inboxId}\" is not valid; use lowercase letters, digits and hyphens, such as ajustes`)\r\n}\r\n\r\nconst pausedChecks = new WeakMap<AxiosInstance, () => boolean>()\r\n\r\nfunction isPaused(api: AxiosInstance): boolean {\r\n const paused = pausedChecks.get(api)\r\n return paused ? paused() : false\r\n}\r\n\r\nfunction answersFromInbox(error: unknown): error is AxiosError & { config: InternalAxiosRequestConfig } {\r\n // O cancelamento primeiro, ainda com `error: unknown`. O `isCancel` do axios é um type guard\r\n // (`value is Cancel`) e o `Cancel` é só `{ message }`, forma que o AxiosError também tem: depois\r\n // do `instanceof`, o `!isCancel` tirava o AxiosError ao tipo e sobrava `never` (erro no build).\r\n if (axios.isCancel(error)) return false\r\n if (!(error instanceof AxiosError) || !error.config || error.response) return false\r\n const method = (error.config.method ?? 'get').toLowerCase()\r\n return method === 'get' && error.config.inbox !== false && dentroDaApp()\r\n}\r\n\r\nasync function storedAnswer(api: AxiosInstance, storageId: string, config: InternalAxiosRequestConfig): Promise<AxiosResponse | null> {\r\n const { address, path } = addressAndPath(api, config)\r\n let stored: InboxRead\r\n try {\r\n stored = await pedirAoNativo<InboxRead>('inbox.read', { storageId, address, path }, BRIDGE_WAIT_MS)\r\n } catch {\r\n return null\r\n }\r\n if (!stored.found) return null\r\n return {\r\n data: stored.body,\r\n status: stored.status,\r\n statusText: '',\r\n headers: { [INBOX_SAVED_AT_HEADER]: stored.savedAt },\r\n config,\r\n request: {},\r\n }\r\n}\r\n\r\nexport function connectInbox(api: AxiosInstance, options: InboxConnectOptions): void {\r\n const storageId = checkedStorageId(options.storageId, 'connectInbox')\r\n if (options.paused) pausedChecks.set(api, options.paused)\r\n api.interceptors.response.use(undefined, async (error: unknown) => {\r\n if (!answersFromInbox(error) || isPaused(api)) throw error\r\n const answer = await storedAnswer(api, storageId, error.config)\r\n if (!answer) throw error\r\n return answer\r\n })\r\n}\r\n\r\nexport function inboxSavedAt(response: AxiosResponse): string | null {\r\n const savedAt: unknown = response.headers[INBOX_SAVED_AT_HEADER]\r\n return typeof savedAt === 'string' ? savedAt : null\r\n}\r\n\r\nexport async function inboxStatus(options: InboxOptions & { inboxId: string }): Promise<InboxStatus | null> {\r\n const storageId = checkedStorageId(options.storageId, 'inboxStatus')\r\n const inboxId = checkedInboxId(options.inboxId, 'inboxStatus')\r\n if (!dentroDaApp()) return null\r\n return pedirAoNativo<InboxStatus>('inbox.state', { storageId, inboxId }, BRIDGE_WAIT_MS)\r\n}\r\n\r\nfunction countIn(event: object, field: keyof InboxProgress): number {\r\n const count: unknown = Reflect.get(event, field)\r\n return typeof count === 'number' ? count : 0\r\n}\r\n\r\nfunction eventFor(event: unknown, storageId: string): InboxEvent | null {\r\n if (typeof event !== 'object' || event === null) return null\r\n const inboxId: unknown = Reflect.get(event, 'inboxId')\r\n if (Reflect.get(event, 'storageId') !== storageId || typeof inboxId !== 'string') return null\r\n const finishedAt: unknown = Reflect.get(event, 'finishedAt')\r\n return {\r\n inboxId,\r\n total: countIn(event, 'total'),\r\n ready: countIn(event, 'ready'),\r\n failed: countIn(event, 'failed'),\r\n finishedAt: typeof finishedAt === 'string' ? finishedAt : null,\r\n }\r\n}\r\n\r\nfunction progressFor(event: unknown, storageId: string, inboxId: string): InboxProgress | null {\r\n const inboxEvent = eventFor(event, storageId)\r\n if (!inboxEvent || inboxEvent.inboxId !== inboxId) return null\r\n return { total: inboxEvent.total, ready: inboxEvent.ready, failed: inboxEvent.failed }\r\n}\r\n\r\nexport function watchInbox(options: InboxOptions, onEvent: (event: InboxEvent) => void): () => void {\r\n const storageId = checkedStorageId(options.storageId, 'watchInbox')\r\n if (!dentroDaApp()) return () => undefined\r\n return onNativeEvent('inbox', (carga) => {\r\n const inboxEvent = eventFor(carga, storageId)\r\n if (inboxEvent) onEvent(inboxEvent)\r\n })\r\n}\r\n\r\nexport async function syncInbox(\r\n api: AxiosInstance,\r\n options: InboxSyncOptions,\r\n onProgress?: (progress: InboxProgress) => void,\r\n): Promise<InboxStatus | null> {\r\n const storageId = checkedStorageId(options.storageId, 'syncInbox')\r\n const inboxId = checkedInboxId(options.inboxId, 'syncInbox')\r\n if (!dentroDaApp() || isPaused(api)) return null\r\n\r\n const gets = options.gets.map((get) => {\r\n const { address, path } = addressAndPath(api, { baseURL: api.defaults.baseURL, url: get.path })\r\n return { address, path, tier: get.tier ?? options.tier, each: get.each, bundle: get.bundle }\r\n })\r\n const stop = onNativeEvent('inbox', (carga) => {\r\n const progress = progressFor(carga, storageId, inboxId)\r\n if (progress && onProgress) onProgress(progress)\r\n })\r\n try {\r\n return await pedirAoNativo<InboxStatus>('inbox.sync', { storageId, inboxId, gets }, SYNC_WAIT_MS)\r\n } finally {\r\n stop()\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;;AA+CO,MAAM,wBAAwB;AAErC,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,eAAe,KAAK;AAI1B,SAAS,eAAe,SAAiB,QAAwB;AAC/D,MAAI,gBAAgB,KAAK,OAAO,EAAG,QAAO;AAC1C,QAAM,IAAI,MAAM,GAAG,MAAM,cAAc,OAAO,4EAA4E;AAC5H;AAEA,MAAM,mCAAmB,QAAA;AAEzB,SAAS,SAAS,KAA6B;AAC7C,QAAM,SAAS,aAAa,IAAI,GAAG;AACnC,SAAO,SAAS,WAAW;AAC7B;AAEA,SAAS,iBAAiB,OAA8E;AAItG,MAAI,MAAM,SAAS,KAAK,EAAG,QAAO;AAClC,MAAI,EAAE,iBAAiB,eAAe,CAAC,MAAM,UAAU,MAAM,SAAU,QAAO;AAC9E,QAAM,UAAU,MAAM,OAAO,UAAU,OAAO,YAAA;AAC9C,SAAO,WAAW,SAAS,MAAM,OAAO,UAAU,SAAS,YAAA;AAC7D;AAEA,eAAe,aAAa,KAAoB,WAAmB,QAAmE;AACpI,QAAM,EAAE,SAAS,KAAA,IAAS,eAAe,KAAK,MAAM;AACpD,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AM,QAAQ,IAAI,OAAA;AAAA,EACtF,CAAC;AACD,QAAM,OAAO,cAAc,SAAS,CAAC,UAAU;AAC7C,UAAM,WAAW,YAAY,OAAO,WAAW,OAAO;AACtD,QAAI,YAAY,WAAY,YAAW,QAAQ;AAAA,EACjD,CAAC;AACD,MAAI;AACF,WAAO,MAAM,cAA2B,cAAc,EAAE,WAAW,SAAS,KAAA,GAAQ,YAAY;AAAA,EAClG,UAAA;AACE,SAAA;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"connectInbox.js","sources":["../../../../../src/v1/capabilities/onepoint-rn/connectInbox.ts"],"sourcesContent":["import axios, { AxiosError } from 'axios'\r\nimport type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'\r\nimport { onNativeEvent, pedirAoNativo } from './bridge'\r\nimport { dentroDaApp } from './dentroDaApp'\r\nimport { addressAndPath } from './requestAddress'\r\nimport { checkedStorageId } from './storageId'\r\n\r\nexport type PedidoInbox = 'inbox.read' | 'inbox.state' | 'inbox.sync'\r\n\r\nexport type InboxTier = 'account' | 'device'\r\n\r\nexport type InboxEach = {\r\n id: string\r\n stamp?: string\r\n list?: string\r\n paths: string[]\r\n}\r\n\r\nexport type InboxBundle = {\r\n ids: string\r\n list: string\r\n id: string\r\n parts: Record<string, string>\r\n since?: { param: string; from: string }\r\n missing?: { param: string }\r\n}\r\n\r\nexport type InboxGet = { path: string; tier?: InboxTier } & ({ each?: InboxEach; bundle?: never } | { bundle: InboxBundle; each?: never })\r\n\r\nexport type InboxOptions = { storageId: string | undefined }\r\n\r\nexport type InboxConnectOptions = InboxOptions & { paused?: () => boolean }\r\n\r\nexport type InboxSyncOptions = InboxOptions & { inboxId: string; tier: InboxTier; gets: InboxGet[] }\r\n\r\nexport type InboxProgress = { total: number; ready: number; failed: number }\r\n\r\nexport type InboxStatus = InboxProgress & { finishedAt: string | null; saved?: string[] }\r\n\r\nexport type InboxEvent = InboxProgress & { inboxId: string; finishedAt: string | null }\r\n\r\ndeclare module 'axios' {\r\n interface AxiosRequestConfig {\r\n inbox?: false\r\n }\r\n}\r\n\r\nexport const INBOX_SAVED_AT_HEADER = 'x-inbox-saved-at'\r\n\r\nconst INBOX_ID_FORMAT = /^[a-z0-9]+(-[a-z0-9]+)*$/\r\nconst BRIDGE_WAIT_MS = 30_000\r\nconst SYNC_WAIT_MS = 30 * 60_000\r\n\r\nexport type InboxRead = { found: false } | { found: true; status: number; body: unknown; savedAt: string }\r\n\r\nfunction checkedInboxId(inboxId: string, caller: string): string {\r\n if (INBOX_ID_FORMAT.test(inboxId)) return inboxId\r\n throw new Error(`${caller}: inboxId \"${inboxId}\" is not valid; use lowercase letters, digits and hyphens, such as ajustes`)\r\n}\r\n\r\nconst pausedChecks = new WeakMap<AxiosInstance, () => boolean>()\r\n\r\nfunction isPaused(api: AxiosInstance): boolean {\r\n const paused = pausedChecks.get(api)\r\n return paused ? paused() : false\r\n}\r\n\r\nfunction answersFromInbox(error: unknown): error is AxiosError & { config: InternalAxiosRequestConfig } {\r\n // O cancelamento primeiro, ainda com `error: unknown`. O `isCancel` do axios é um type guard\r\n // (`value is Cancel`) e o `Cancel` é só `{ message }`, forma que o AxiosError também tem: depois\r\n // do `instanceof`, o `!isCancel` tirava o AxiosError ao tipo e sobrava `never` (erro no build).\r\n if (axios.isCancel(error)) return false\r\n if (!(error instanceof AxiosError) || !error.config || error.response) return false\r\n const method = (error.config.method ?? 'get').toLowerCase()\r\n return method === 'get' && error.config.inbox !== false && dentroDaApp()\r\n}\r\n\r\nasync function storedAnswer(api: AxiosInstance, storageId: string, config: InternalAxiosRequestConfig): Promise<AxiosResponse | null> {\r\n const { address, path } = addressAndPath(api, config)\r\n let stored: InboxRead\r\n try {\r\n stored = await pedirAoNativo<InboxRead>('inbox.read', { storageId, address, path }, BRIDGE_WAIT_MS)\r\n } catch {\r\n return null\r\n }\r\n if (!stored.found) return null\r\n return {\r\n data: stored.body,\r\n status: stored.status,\r\n statusText: '',\r\n headers: { [INBOX_SAVED_AT_HEADER]: stored.savedAt },\r\n config,\r\n request: {},\r\n }\r\n}\r\n\r\nexport function connectInbox(api: AxiosInstance, options: InboxConnectOptions): void {\r\n const storageId = checkedStorageId(options.storageId, 'connectInbox')\r\n if (options.paused) pausedChecks.set(api, options.paused)\r\n api.interceptors.response.use(undefined, async (error: unknown) => {\r\n if (!answersFromInbox(error) || isPaused(api)) throw error\r\n const answer = await storedAnswer(api, storageId, error.config)\r\n if (!answer) throw error\r\n return answer\r\n })\r\n}\r\n\r\nexport function inboxSavedAt(response: AxiosResponse): string | null {\r\n const savedAt: unknown = response.headers[INBOX_SAVED_AT_HEADER]\r\n return typeof savedAt === 'string' ? savedAt : null\r\n}\r\n\r\n/**\r\n * O que a app tem guardado para um pedido (ex: para mostrar a quem usa o que\r\n * está no telemóvel). `address` é o endereço da API por inteiro (com\r\n * `https://`); `path` é o resto. Fora da app, `null`.\r\n */\r\nexport async function readInbox(options: InboxOptions & { address: string; path: string }): Promise<InboxRead | null> {\r\n const storageId = checkedStorageId(options.storageId, 'readInbox')\r\n if (!dentroDaApp()) return null\r\n return pedirAoNativo<InboxRead>('inbox.read', { storageId, address: options.address, path: options.path }, BRIDGE_WAIT_MS)\r\n}\r\n\r\nexport async function inboxStatus(options: InboxOptions & { inboxId: string }): Promise<InboxStatus | null> {\r\n const storageId = checkedStorageId(options.storageId, 'inboxStatus')\r\n const inboxId = checkedInboxId(options.inboxId, 'inboxStatus')\r\n if (!dentroDaApp()) return null\r\n return pedirAoNativo<InboxStatus>('inbox.state', { storageId, inboxId }, BRIDGE_WAIT_MS)\r\n}\r\n\r\nfunction countIn(event: object, field: keyof InboxProgress): number {\r\n const count: unknown = Reflect.get(event, field)\r\n return typeof count === 'number' ? count : 0\r\n}\r\n\r\nfunction eventFor(event: unknown, storageId: string): InboxEvent | null {\r\n if (typeof event !== 'object' || event === null) return null\r\n const inboxId: unknown = Reflect.get(event, 'inboxId')\r\n if (Reflect.get(event, 'storageId') !== storageId || typeof inboxId !== 'string') return null\r\n const finishedAt: unknown = Reflect.get(event, 'finishedAt')\r\n return {\r\n inboxId,\r\n total: countIn(event, 'total'),\r\n ready: countIn(event, 'ready'),\r\n failed: countIn(event, 'failed'),\r\n finishedAt: typeof finishedAt === 'string' ? finishedAt : null,\r\n }\r\n}\r\n\r\nfunction progressFor(event: unknown, storageId: string, inboxId: string): InboxProgress | null {\r\n const inboxEvent = eventFor(event, storageId)\r\n if (!inboxEvent || inboxEvent.inboxId !== inboxId) return null\r\n return { total: inboxEvent.total, ready: inboxEvent.ready, failed: inboxEvent.failed }\r\n}\r\n\r\nexport function watchInbox(options: InboxOptions, onEvent: (event: InboxEvent) => void): () => void {\r\n const storageId = checkedStorageId(options.storageId, 'watchInbox')\r\n if (!dentroDaApp()) return () => undefined\r\n return onNativeEvent('inbox', (carga) => {\r\n const inboxEvent = eventFor(carga, storageId)\r\n if (inboxEvent) onEvent(inboxEvent)\r\n })\r\n}\r\n\r\nexport async function syncInbox(\r\n api: AxiosInstance,\r\n options: InboxSyncOptions,\r\n onProgress?: (progress: InboxProgress) => void,\r\n): Promise<InboxStatus | null> {\r\n const storageId = checkedStorageId(options.storageId, 'syncInbox')\r\n const inboxId = checkedInboxId(options.inboxId, 'syncInbox')\r\n if (!dentroDaApp() || isPaused(api)) return null\r\n\r\n const gets = options.gets.map((get) => {\r\n const { address, path } = addressAndPath(api, { baseURL: api.defaults.baseURL, url: get.path })\r\n return { address, path, tier: get.tier ?? options.tier, each: get.each, bundle: get.bundle }\r\n })\r\n const stop = onNativeEvent('inbox', (carga) => {\r\n const progress = progressFor(carga, storageId, inboxId)\r\n if (progress && onProgress) onProgress(progress)\r\n })\r\n try {\r\n return await pedirAoNativo<InboxStatus>('inbox.sync', { storageId, inboxId, gets }, SYNC_WAIT_MS)\r\n } finally {\r\n stop()\r\n }\r\n}\r\n"],"names":[],"mappings":";;;;;AA+CO,MAAM,wBAAwB;AAErC,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACv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int-rn/connectOutbox.ts"],"sourcesContent":["import { AxiosError, AxiosHeaders } from 'axios'\r\nimport type { AxiosAdapter, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'\r\nimport { ErroBridge, onNativeEvent, pedirAoNativo } from './bridge'\r\nimport { dentroDaApp } from './dentroDaApp'\r\nimport { addressAndPath } from './requestAddress'\r\nimport { checkedStorageId } from './storageId'\r\n\r\nexport type PedidoOutbox = 'outbox.send' | 'outbox.watch'\r\n\r\nconst WRITE_METHODS = ['post', 'put', 'patch', 'delete']\r\nconst BRIDGE_WAIT_MS = 30_000\r\n\r\nexport const OUTBOX_SAVED_MESSAGE = 'Guardado no telemóvel. Será enviado quando a ligação voltar.'\r\n\r\nexport type OutboxOptions = { storageId: string | undefined }\r\n\r\nexport type OutboxRequestOptions = { expiresAt?: string | Date }\r\n\r\ndeclare module 'axios' {\r\n interface AxiosRequestConfig {\r\n outbox?: true | OutboxRequestOptions\r\n }\r\n}\r\n\r\ntype OutboxReply =\r\n | { outcome: 'delivered' | 'rejected'; status: number; body: unknown }\r\n | { outcome: 'saved'; id: string }\r\n\r\nexport class OutboxSavedError extends Error {\r\n readonly outboxActionId: string | null\r\n\r\n constructor(outboxActionId: string | null) {\r\n super(OUTBOX_SAVED_MESSAGE)\r\n this.name = 'OutboxSavedError'\r\n this.outboxActionId = outboxActionId\r\n }\r\n}\r\n\r\nexport function isOutboxSaved(error: unknown): error is OutboxSavedError {\r\n return error instanceof OutboxSavedError\r\n}\r\n\r\nfunction stringHeaders(config: InternalAxiosRequestConfig): Record<string, string> {\r\n const headers: Record<string, string> = {}\r\n for (const [name, value] of Object.entries(AxiosHeaders.from(config.headers).toJSON())) {\r\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') headers[name] = String(value)\r\n }\r\n return headers\r\n}\r\n\r\nasync function replyOf(carga: unknown): Promise<OutboxReply> {\r\n try {\r\n return await pedirAoNativo<OutboxReply>('outbox.send', carga, BRIDGE_WAIT_MS)\r\n } catch (error) {\r\n if (error instanceof ErroBridge && error.codigo === 'expirou') throw new OutboxSavedError(null)\r\n throw error\r\n }\r\n}\r\n\r\nfunction expiryOf(config: InternalAxiosRequestConfig): string | undefined {\r\n const expiresAt = config.outbox === true ? undefined : config.outbox?.expiresAt\r\n return expiresAt instanceof Date ? expiresAt.toISOString() : expiresAt\r\n}\r\n\r\nfunction outboxAdapter(api: AxiosInstance, storageId: string): AxiosAdapter {\r\n return async (config) => {\r\n const { address, path } = addressAndPath(api, config)\r\n const reply = await replyOf({\r\n storageId,\r\n address,\r\n method: config.method,\r\n path,\r\n headers: stringHeaders(config),\r\n body: config.data,\r\n expiresAt: expiryOf(config),\r\n })\r\n if (reply.outcome === 'saved') throw new OutboxSavedError(reply.id)\r\n\r\n const response: AxiosResponse = {\r\n data: reply.body,\r\n status: reply.status,\r\n statusText: '',\r\n headers: {},\r\n config,\r\n request: {},\r\n }\r\n const accepted = config.validateStatus ? config.validateStatus(reply.status) : reply.outcome === 'delivered'\r\n if (accepted) return response\r\n throw new AxiosError(\r\n `Request failed with status code ${reply.status}`,\r\n reply.status >= 500 ? AxiosError.ERR_BAD_RESPONSE : AxiosError.ERR_BAD_REQUEST,\r\n config,\r\n response.request,\r\n response,\r\n )\r\n }\r\n}\r\n\r\nfunction goesThroughOutbox(config: InternalAxiosRequestConfig): boolean {\r\n if (!config.outbox) return false\r\n const method = (config.method ?? 'get').toLowerCase()\r\n if (!WRITE_METHODS.includes(method)) {\r\n throw new Error(`connectOutbox: only writes go through the Outbox, and this ${method.toUpperCase()} is marked with outbox`)\r\n }\r\n const data: unknown = config.data\r\n if (data instanceof FormData || data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\r\n throw new Error('connectOutbox: files do not go through the Outbox yet; send this write without outbox')\r\n }\r\n return dentroDaApp()\r\n}\r\n\r\nexport type OutboxState = 'pending' | 'sending' | 'delivered' | 'rejected' | 'expired' | 'deleted'\r\n\r\nexport type OutboxActionStatus = {\r\n id: string\r\n state: OutboxState\r\n createdAt?: string\r\n reason?: string\r\n method?: string\r\n path?: string\r\n}\r\n\r\nexport type OutboxWatch = { actions: OutboxActionStatus[]; stop: () => void }\r\n\r\nconst WATCH_WAIT_MS = 10_000\r\n\r\nfunction statusFor(carga: unknown, storageId: string): OutboxActionStatus | null {\r\n if (typeof carga !== 'object' || carga === null) return null\r\n const { storageId: of, ...status } = carga as OutboxActionStatus & { storageId?: string }\r\n return of === storageId ? status : null\r\n}\r\n\r\nexport async function watchOutbox(options: OutboxOptions, onChange: (status: OutboxActionStatus) => void): Promise<OutboxWatch> {\r\n const storageId = checkedStorageId(options.storageId, 'connectOutbox')\r\n if (!dentroDaApp()) return { actions: [], stop: () => undefined }\r\n const stop = onNativeEvent('outbox', (carga) => {\r\n const status = statusFor(carga, storageId)\r\n if (status) onChange(status)\r\n })\r\n try {\r\n const actions = await pedirAoNativo<OutboxActionStatus[]>('outbox.watch', { storageId }, WATCH_WAIT_MS)\r\n return { actions, stop }\r\n } catch (error) {\r\n stop()\r\n throw error\r\n }\r\n}\r\n\r\nexport function connectOutbox(api: AxiosInstance, options: OutboxOptions): void {\r\n const storageId = checkedStorageId(options.storageId, 'connectOutbox')\r\n const adapter = outboxAdapter(api, storageId)\r\n api.interceptors.request.use((config) => {\r\n if (goesThroughOutbox(config)) config.adapter = adapter\r\n return config\r\n })\r\n}\r\n"],"names":[],"mappings":";;;;;AASA,MAAM,gBAAgB,CAAC,QAAQ,OAAO,SAAS,QAAQ;AACvD,MAAM,iBAAiB;AAEhB,MAAM,uBAAuB;AAgB7B,MAAM,yBAAyB,MAAM;AAAA,EAG1C,YAAY,gBAA+B;AACzC,UAAM,oBAAoB;AAC1B,SAAK,OAAO;AACZ,SAAK,iBAAiB;AAAA,EACxB;AACF;AAEO,SAAS,cAAc,OAA2C;AACvE,SAAO,iBAAiB;AAC1B;AAEA,SAAS,cAAc,QAA4D;AACjF,QAAM,UAAkC,CAAA;AACxC,aAAW,CAAC,MAAM,KAA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,WAAW,mBAAmB,WAAW;AAAA,MAC/D;AAAA,MACA,SAAS;AAAA,MACT;AAAA,IAAA;AAAA,EAEJ;AACF;AAEA,SAAS,kBAAkB,QAA6C;AACtE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,QAAM,UAAU,OAAO,UAAU,OAAO,YAAA;AACxC,MAAI,CAAC,cAAc,SAAS,MAAM,GAAG;AACnC,UAAM,IAAI,MAAM,8DAA8D,OAAO,YAAA,CAAa,wBAAwB;AAAA,EAC5H;AACA,QAAM,OAAgB,OAAO;AAC7B,MAAI,gBAAgB,YAAY,gBAAgB,QAAQ,gBAAgB,eAAe,YAAY,OAAO,IAAI,GAAG;AAC/G,UAAM,IAAI,MAAM,uFAAuF;AAAA,EACzG;AACA,SAAO,YAAA;AACT;
|
|
1
|
+
{"version":3,"file":"connectOutbox.js","sources":["../../../../../src/v1/capabilities/onepoint-rn/connectOutbox.ts"],"sourcesContent":["import { AxiosError, AxiosHeaders } from 'axios'\r\nimport type { AxiosAdapter, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'\r\nimport { ErroBridge, onNativeEvent, pedirAoNativo } from './bridge'\r\nimport { dentroDaApp } from './dentroDaApp'\r\nimport { addressAndPath } from './requestAddress'\r\nimport { checkedStorageId } from './storageId'\r\n\r\nexport type PedidoOutbox = 'outbox.send' | 'outbox.watch'\r\n\r\nconst WRITE_METHODS = ['post', 'put', 'patch', 'delete']\r\nconst BRIDGE_WAIT_MS = 30_000\r\n\r\nexport const OUTBOX_SAVED_MESSAGE = 'Guardado no telemóvel. Será enviado quando a ligação voltar.'\r\n\r\nexport type OutboxOptions = { storageId: string | undefined }\r\n\r\nexport type OutboxRequestOptions = { expiresAt?: string | Date }\r\n\r\ndeclare module 'axios' {\r\n interface AxiosRequestConfig {\r\n outbox?: true | OutboxRequestOptions\r\n }\r\n}\r\n\r\ntype OutboxReply =\r\n | { outcome: 'delivered' | 'rejected'; status: number; body: unknown }\r\n | { outcome: 'saved'; id: string }\r\n\r\nexport class OutboxSavedError extends Error {\r\n readonly outboxActionId: string | null\r\n\r\n constructor(outboxActionId: string | null) {\r\n super(OUTBOX_SAVED_MESSAGE)\r\n this.name = 'OutboxSavedError'\r\n this.outboxActionId = outboxActionId\r\n }\r\n}\r\n\r\nexport function isOutboxSaved(error: unknown): error is OutboxSavedError {\r\n return error instanceof OutboxSavedError\r\n}\r\n\r\nfunction stringHeaders(config: InternalAxiosRequestConfig): Record<string, string> {\r\n const headers: Record<string, string> = {}\r\n for (const [name, value] of Object.entries(AxiosHeaders.from(config.headers).toJSON())) {\r\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') headers[name] = String(value)\r\n }\r\n return headers\r\n}\r\n\r\nasync function replyOf(carga: unknown): Promise<OutboxReply> {\r\n try {\r\n return await pedirAoNativo<OutboxReply>('outbox.send', carga, BRIDGE_WAIT_MS)\r\n } catch (error) {\r\n if (error instanceof ErroBridge && error.codigo === 'expirou') throw new OutboxSavedError(null)\r\n throw error\r\n }\r\n}\r\n\r\nfunction expiryOf(config: InternalAxiosRequestConfig): string | undefined {\r\n const expiresAt = config.outbox === true ? undefined : config.outbox?.expiresAt\r\n return expiresAt instanceof Date ? expiresAt.toISOString() : expiresAt\r\n}\r\n\r\nfunction outboxAdapter(api: AxiosInstance, storageId: string): AxiosAdapter {\r\n return async (config) => {\r\n const { address, path } = addressAndPath(api, config)\r\n const reply = await replyOf({\r\n storageId,\r\n address,\r\n method: config.method,\r\n path,\r\n headers: stringHeaders(config),\r\n body: config.data,\r\n expiresAt: expiryOf(config),\r\n })\r\n if (reply.outcome === 'saved') throw new OutboxSavedError(reply.id)\r\n\r\n const response: AxiosResponse = {\r\n data: reply.body,\r\n status: reply.status,\r\n statusText: '',\r\n headers: {},\r\n config,\r\n request: {},\r\n }\r\n const accepted = config.validateStatus ? config.validateStatus(reply.status) : reply.outcome === 'delivered'\r\n if (accepted) return response\r\n throw new AxiosError(\r\n `Request failed with status code ${reply.status}`,\r\n reply.status >= 500 ? AxiosError.ERR_BAD_RESPONSE : AxiosError.ERR_BAD_REQUEST,\r\n config,\r\n response.request,\r\n response,\r\n )\r\n }\r\n}\r\n\r\nfunction goesThroughOutbox(config: InternalAxiosRequestConfig): boolean {\r\n if (!config.outbox) return false\r\n const method = (config.method ?? 'get').toLowerCase()\r\n if (!WRITE_METHODS.includes(method)) {\r\n throw new Error(`connectOutbox: only writes go through the Outbox, and this ${method.toUpperCase()} is marked with outbox`)\r\n }\r\n const data: unknown = config.data\r\n if (data instanceof FormData || data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\r\n throw new Error('connectOutbox: files do not go through the Outbox yet; send this write without outbox')\r\n }\r\n return dentroDaApp()\r\n}\r\n\r\nexport type OutboxState = 'pending' | 'sending' | 'delivered' | 'rejected' | 'expired' | 'deleted'\r\n\r\nexport type OutboxActionStatus = {\r\n id: string\r\n state: OutboxState\r\n createdAt?: string\r\n reason?: string\r\n method?: string\r\n path?: string\r\n /** Os cabeçalhos guardados com a escrita (nunca o token). */\r\n headers?: Record<string, string>\r\n /** O que vai ser enviado. */\r\n body?: unknown\r\n}\r\n\r\nexport type OutboxWatch = { actions: OutboxActionStatus[]; stop: () => void }\r\n\r\nconst WATCH_WAIT_MS = 10_000\r\n\r\nfunction statusFor(carga: unknown, storageId: string): OutboxActionStatus | null {\r\n if (typeof carga !== 'object' || carga === null) return null\r\n const { storageId: of, ...status } = carga as OutboxActionStatus & { storageId?: string }\r\n return of === storageId ? status : null\r\n}\r\n\r\nexport async function watchOutbox(options: OutboxOptions, onChange: (status: OutboxActionStatus) => void): Promise<OutboxWatch> {\r\n const storageId = checkedStorageId(options.storageId, 'connectOutbox')\r\n if (!dentroDaApp()) return { actions: [], stop: () => undefined }\r\n const stop = onNativeEvent('outbox', (carga) => {\r\n const status = statusFor(carga, storageId)\r\n if (status) onChange(status)\r\n })\r\n try {\r\n const actions = await pedirAoNativo<OutboxActionStatus[]>('outbox.watch', { storageId }, WATCH_WAIT_MS)\r\n return { actions, stop }\r\n } catch (error) {\r\n stop()\r\n throw error\r\n }\r\n}\r\n\r\nexport function connectOutbox(api: AxiosInstance, options: OutboxOptions): void {\r\n const storageId = checkedStorageId(options.storageId, 'connectOutbox')\r\n const adapter = outboxAdapter(api, storageId)\r\n api.interceptors.request.use((config) => {\r\n if (goesThroughOutbox(config)) config.adapter = adapter\r\n return config\r\n })\r\n}\r\n"],"names":[],"mappings":";;;;;AASA,MAAM,gBAAgB,CAAC,QAAQ,OAAO,SAAS,QAAQ;AACvD,MAAM,iBAAiB;AAEhB,MAAM,uBAAuB;AAgB7B,MAAM,yBAAyB,MAAM;AAAA,EAG1C,YAAY,gBAA+B;AACzC,UAAM,oBAAoB;AAC1B,SAAK,OAAO;AACZ,SAAK,iBAAiB;AAAA,EACxB;AACF;AAEO,SAAS,cAAc,OAA2C;AACvE,SAAO,iBAAiB;AAC1B;AAEA,SAAS,cAAc,QAA4D;AACjF,QAAM,UAAkC,CAAA;AACxC,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,aAAa,KAAK,OAAO,OAAO,EAAE,OAAA,CAAQ,GAAG;AACtF,QAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,UAAW,SAAQ,IAAI,IAAI,OAAO,KAAK;AAAA,EACxH;AACA,SAAO;AACT;AAEA,eAAe,QAAQ,OAAsC;AAC3D,MAAI;AACF,WAAO,MAAM,cAA2B,eAAe,OAAO,cAAc;AAAA,EAC9E,SAAS,OAAO;AACd,QAAI,iBAAiB,cAAc,MAAM,WAAW,UAAW,OAAM,IAAI,iBAAiB,IAAI;AAC9F,UAAM;AAAA,EACR;AACF;AAEA,SAAS,SAAS,QAAwD;AACxE,QAAM,YAAY,OAAO,WAAW,OAAO,SAAY,OAAO,QAAQ;AACtE,SAAO,qBAAqB,OAAO,UAAU,YAAA,IAAgB;AAC/D;AAEA,SAAS,cAAc,KAAoB,WAAiC;AAC1E,SAAO,OAAO,WAAW;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AACxD,QAAM,EAAE,WAAW,IAAI,GAAG,WAAW;AACrC,SAAO,OAAO,YAAY,SAAS;AACrC;AAEA,eAAsB,YAAY,SAAwB,UAAsE;AAC9H,QAAM,YAAY,iBAAiB,QAAQ,WAAW,eAAe;AACrE,MAAI,CAAC,YAAA,EAAe,QAAO,EAAE,SAAS,IAAI,MAAM,MAAM,OAAA;AACtD,QAAM,OAAO,cAAc,UAAU,CAAC,UAAU;AAC9C,UAAM,SAAS,UAAU,OAAO,SAAS;AACzC,QAAI,iBAAiB,MAAM;AAAA,EAC7B,CAAC;AACD,MAAI;AACF,UAAM,UAAU,MAAM,cAAoC,gBAAgB,EAAE,UAAA,GAAa,aAAa;AACtG,WAAO,EAAE,SAAS,KAAA;AAAA,EACpB,SAAS,OAAO;AACd,SAAA;AACA,UAAM;AAAA,EACR;AACF;AAEO,SAAS,cAAc,KAAoB,SAA8B;AAC9E,QAAM,YAAY,iBAAiB,QAAQ,WAAW,eAAe;AACrE,QAAM,UAAU,cAAc,KAAK,SAAS;AAC5C,MAAI,aAAa,QAAQ,IAAI,CAAC,WAAW;AACvC,QAAI,kBAAkB,MAAM,EAAG,QAAO,UAAU;AAChD,WAAO;AAAA,EACT,CAAC;AACH;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOrientacaoNaApp.js","sources":["../../../../../src/v1/capabilities/onepoint-rn/useOrientacaoNaApp.ts"],"sourcesContent":["import { useEffect } from 'react'\r\nimport { frame, type OrientacaoEcra } from './frame'\r\n\r\nfunction pedirOrientacao(modo: OrientacaoEcra): void {\r\n frame.orientacao(modo).catch(() => undefined)\r\n}\r\n\r\nexport function useOrientacaoNaApp(modo: OrientacaoEcra): void {\r\n useEffect(() => {\r\n pedirOrientacao(modo)\r\n return () => pedirOrientacao('
|
|
1
|
+
{"version":3,"file":"useOrientacaoNaApp.js","sources":["../../../../../src/v1/capabilities/onepoint-rn/useOrientacaoNaApp.ts"],"sourcesContent":["import { useEffect } from 'react'\r\nimport { frame, type OrientacaoEcra } from './frame'\r\n\r\nfunction pedirOrientacao(modo: OrientacaoEcra): void {\r\n frame.orientacao(modo).catch(() => undefined)\r\n}\r\n\r\n/**\r\n * Pede à app uma orientação enquanto o ecrã está montado (ex: 'paisagem'\r\n * numa tabela larga). Ao sair, volta a retrato: na app os portais ficam em\r\n * retrato, salvo quando um ecrã pede outra coisa.\r\n */\r\nexport function useOrientacaoNaApp(modo: OrientacaoEcra): void {\r\n useEffect(() => {\r\n pedirOrientacao(modo)\r\n return () => pedirOrientacao('retrato')\r\n }, [modo])\r\n}\r\n"],"names":[],"mappings":";;AAGA,SAAS,gBAAgB,MAA4B;AACnD,QAAM,WAAW,IAAI,EAAE,MAAM,MAAM,MAAS;AAC9C;AAOO,SAAS,mBAAmB,MAA4B;AAC7D,YAAU,MAAM;AACd,oBAAgB,IAAI;AACpB,WAAO,MAAM,gBAAgB,SAAS;AAAA,EACxC,GAAG,CAAC,IAAI,CAAC;AACX;"}
|
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
import { jsxs, jsx } from "react/jsx-runtime";
|
|
2
|
-
import { useState, useRef, useEffect } from "react";
|
|
2
|
+
import { useState, useRef, useEffect, useCallback } from "react";
|
|
3
3
|
import { createPortal } from "react-dom";
|
|
4
4
|
import { useOfflineBoxes } from "../../../capabilities/onepoint-rn/useOfflineBoxes.js";
|
|
5
|
+
import { readInbox } from "../../../capabilities/onepoint-rn/connectInbox.js";
|
|
5
6
|
import { useDialogContainer } from "../../overlays/Dialog/Dialog.js";
|
|
6
7
|
import { OfflineBoxesIcon } from "./OfflineBoxesIcon.js";
|
|
7
8
|
import OfflineBoxesView, { DEFAULT_OFFLINE_BOXES_LABELS, percentOf, toSendOf, INBOX_GREEN, OfflineArrow, OUTBOX_ORANGE, filled } from "./OfflineBoxesView.js";
|
|
9
|
+
function addressAndPathOf(path, address) {
|
|
10
|
+
if (/^https?:\/\//.test(path)) {
|
|
11
|
+
const url = new URL(path);
|
|
12
|
+
return { address: url.origin, path: url.pathname + url.search };
|
|
13
|
+
}
|
|
14
|
+
const base = new URL(address ?? "/", window.location.href).href.replace(/\/$/, "");
|
|
15
|
+
return { address: base, path };
|
|
16
|
+
}
|
|
8
17
|
function OfflineBoxes({ storageId, inboxIds, onRefresh, address, subtitle, describeSaved, describeWrite, labels, className = "" }) {
|
|
9
18
|
const L = { ...DEFAULT_OFFLINE_BOXES_LABELS, ...labels };
|
|
10
19
|
const state = useOfflineBoxes({ storageId, inboxIds });
|
|
@@ -25,6 +34,7 @@ function OfflineBoxes({ storageId, inboxIds, onRefresh, address, subtitle, descr
|
|
|
25
34
|
document.addEventListener("keydown", escape);
|
|
26
35
|
return () => document.removeEventListener("keydown", escape);
|
|
27
36
|
}, [open]);
|
|
37
|
+
const readSaved = useCallback((path) => readInbox({ storageId, ...addressAndPathOf(path, address) }), [storageId, address]);
|
|
28
38
|
if (!state) return null;
|
|
29
39
|
const pct = percentOf(state);
|
|
30
40
|
const pctLabel = pct === null ? "–" : `${pct}%`;
|
|
@@ -76,7 +86,8 @@ function OfflineBoxes({ storageId, inboxIds, onRefresh, address, subtitle, descr
|
|
|
76
86
|
onRefresh,
|
|
77
87
|
onBack: close,
|
|
78
88
|
describeSaved,
|
|
79
|
-
describeWrite
|
|
89
|
+
describeWrite,
|
|
90
|
+
readSaved
|
|
80
91
|
}
|
|
81
92
|
),
|
|
82
93
|
dialogContainer ?? document.body
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OfflineBoxes.js","sources":["../../../../../../src/v1/components/feedback/OfflineBoxes/OfflineBoxes.tsx"],"sourcesContent":["import React, { useEffect, useRef, useState } from 'react'\r\nimport { createPortal } from 'react-dom'\r\nimport { useOfflineBoxes } from '../../../capabilities/onepoint-rn/useOfflineBoxes'\r\nimport { useDialogContainer } from '../../overlays/Dialog/Dialog'\r\nimport OfflineBoxesIcon from './OfflineBoxesIcon'\r\nimport OfflineBoxesView, {\r\n DEFAULT_OFFLINE_BOXES_LABELS,\r\n INBOX_GREEN,\r\n OUTBOX_ORANGE,\r\n OfflineArrow,\r\n filled,\r\n percentOf,\r\n toSendOf,\r\n type OfflineBoxesLabels,\r\n type OfflineSavedSummary,\r\n type OfflineWrite,\r\n type OfflineWriteDescription,\r\n} from './OfflineBoxesView'\r\n\r\nexport {\r\n DEFAULT_OFFLINE_BOXES_LABELS,\r\n type OfflineBoxesLabels,\r\n type OfflineSavedItem,\r\n type OfflineSavedSummary,\r\n type OfflineSavedTag,\r\n type OfflineWrite,\r\n type OfflineWriteDescription,\r\n} from './OfflineBoxesView'\r\n\r\nexport interface OfflineBoxesProps {\r\n /** O mesmo `storageId` do `connectOutbox` e do `connectInbox`. */\r\n storageId: string | undefined\r\n /** As inboxes que este sítio mostra (ex: `['ajustes']`). Somam-se. */\r\n inboxIds: string[]\r\n /** O que o botão Atualizar faz (ex: chamar o `syncInbox`). Sem ele, não há botão. */\r\n onRefresh?: () => void\r\n /** Endereço da API (`api.defaults.baseURL`): os endereços chegam ao `describeSaved` e ao `describeWrite` sem ele à frente. */\r\n address?: string\r\n /** Linha ao lado do título na vista (ex: o nome do ecrã). */\r\n subtitle?: string\r\n /** Transforma os endereços guardados nas linhas que se mostram (ex: uma por OT). Sem ele, mostra os endereços. */\r\n describeSaved?: (paths: string[]) => OfflineSavedSummary\r\n /** Diz o que é cada escrita por enviar (ex: \"Ajuste guardado\"). Sem ele, ou se devolver `null`, mostra método e endereço. */\r\n describeWrite?: (write: OfflineWrite) => OfflineWriteDescription | null\r\n labels?: Partial<OfflineBoxesLabels>\r\n className?: string\r\n}\r\n\r\n/**\r\n * O que a app tem guardado para usar sem rede (Inbox, verde) e o que tem por\r\n * enviar (Outbox, laranja), num botão que se põe onde se quiser (ex: à\r\n * direita do título): o ícone e uma pílula com duas metades, a percentagem\r\n * guardada (sobe enquanto a descarga corre) e quantas escritas faltam enviar. Tocar abre a vista inteira\r\n * com o detalhe. Fora da app OnePoint não aparece.\r\n */\r\nexport default function OfflineBoxes({ storageId, inboxIds, onRefresh, address, subtitle, describeSaved, describeWrite, labels, className = '' }: OfflineBoxesProps) {\r\n const L = { ...DEFAULT_OFFLINE_BOXES_LABELS, ...labels }\r\n const state = useOfflineBoxes({ storageId, inboxIds })\r\n const [open, setOpen] = useState(false)\r\n const triggerRef = useRef<HTMLButtonElement>(null)\r\n const dialogContainer = useDialogContainer()\r\n\r\n const close = () => {\r\n setOpen(false)\r\n triggerRef.current?.focus()\r\n }\r\n\r\n useEffect(() => {\r\n if (!open) return\r\n const escape = (e: KeyboardEvent) => {\r\n if (e.key !== 'Escape') return\r\n setOpen(false)\r\n triggerRef.current?.focus()\r\n }\r\n document.addEventListener('keydown', escape)\r\n return () => document.removeEventListener('keydown', escape)\r\n }, [open])\r\n\r\n if (!state) return null\r\n\r\n const pct = percentOf(state)\r\n const pctLabel = pct === null ? '–' : `${pct}%`\r\n const toSend = toSendOf(state)\r\n\r\n return (\r\n <div className={`relative inline-flex shrink-0 ${className}`}>\r\n <button\r\n ref={triggerRef}\r\n type=\"button\"\r\n aria-haspopup=\"dialog\"\r\n aria-expanded={open}\r\n aria-label={`${L.title}: ${L.saved} ${pctLabel} · ${filled(L.toSend, { n: toSend })}`}\r\n onClick={(e) => {\r\n e.stopPropagation()\r\n setOpen(true)\r\n }}\r\n className=\"flex min-h-11 cursor-pointer items-center gap-1.5 rounded-full border-0 bg-transparent px-1 hover:bg-slate-100 dark:hover:bg-slate-800\"\r\n >\r\n <OfflineBoxesIcon size={26} />\r\n <span className=\"flex h-7 items-stretch overflow-hidden rounded-full text-[11px] font-black whitespace-nowrap tabular-nums shadow-[0_1px_3px_rgba(0,27,99,0.18)]\">\r\n <span className=\"flex items-center gap-0.5 pr-1.5 pl-2 text-white\" style={{ background: INBOX_GREEN }}>\r\n <OfflineArrow />\r\n {pctLabel}\r\n </span>\r\n <span\r\n className={`flex items-center gap-0.5 pr-2 pl-1.5 ${toSend > 0 ? 'text-white' : 'bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400'}`}\r\n style={toSend > 0 ? { background: OUTBOX_ORANGE } : undefined}\r\n >\r\n <OfflineArrow up />\r\n {toSend}\r\n </span>\r\n </span>\r\n </button>\r\n {open &&\r\n createPortal(\r\n <OfflineBoxesView\r\n state={state}\r\n labels={L}\r\n subtitle={subtitle}\r\n address={address}\r\n onRefresh={onRefresh}\r\n onBack={close}\r\n describeSaved={describeSaved}\r\n describeWrite={describeWrite}\r\n />,\r\n dialogContainer ?? document.body,\r\n )}\r\n </div>\r\n )\r\n}\r\n\r\nexport { OfflineBoxes }\r\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"OfflineBoxes.js","sources":["../../../../../../src/v1/components/feedback/OfflineBoxes/OfflineBoxes.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useRef, useState } from 'react'\r\nimport { createPortal } from 'react-dom'\r\nimport { useOfflineBoxes } from '../../../capabilities/onepoint-rn/useOfflineBoxes'\r\nimport { readInbox } from '../../../capabilities/onepoint-rn/connectInbox'\r\nimport { useDialogContainer } from '../../overlays/Dialog/Dialog'\r\nimport OfflineBoxesIcon from './OfflineBoxesIcon'\r\nimport OfflineBoxesView, {\r\n DEFAULT_OFFLINE_BOXES_LABELS,\r\n INBOX_GREEN,\r\n OUTBOX_ORANGE,\r\n OfflineArrow,\r\n filled,\r\n percentOf,\r\n toSendOf,\r\n type OfflineBoxesLabels,\r\n type OfflineSavedSummary,\r\n type OfflineWrite,\r\n type OfflineWriteDescription,\r\n} from './OfflineBoxesView'\r\n\r\nexport {\r\n DEFAULT_OFFLINE_BOXES_LABELS,\r\n type OfflineBoxesLabels,\r\n type OfflineSavedItem,\r\n type OfflineSavedPart,\r\n type OfflineSavedSummary,\r\n type OfflineSavedTag,\r\n type OfflineWrite,\r\n type OfflineWriteDescription,\r\n} from './OfflineBoxesView'\r\n\r\nexport interface OfflineBoxesProps {\r\n /** O mesmo `storageId` do `connectOutbox` e do `connectInbox`. */\r\n storageId: string | undefined\r\n /** As inboxes que este sítio mostra (ex: `['ajustes']`). Somam-se. */\r\n inboxIds: string[]\r\n /** O que o botão Atualizar faz (ex: chamar o `syncInbox`). Sem ele, não há botão. */\r\n onRefresh?: () => void\r\n /** Endereço da API (`api.defaults.baseURL`): os endereços chegam ao `describeSaved` e ao `describeWrite` sem ele à frente. */\r\n address?: string\r\n /** Linha ao lado do título na vista (ex: o nome do ecrã). */\r\n subtitle?: string\r\n /** Transforma os endereços guardados nas linhas que se mostram (ex: uma por OT). Sem ele, mostra os endereços. */\r\n describeSaved?: (paths: string[]) => OfflineSavedSummary\r\n /** Diz o que é cada escrita por enviar (ex: \"Ajuste guardado\"). Sem ele, ou se devolver `null`, mostra método e endereço. */\r\n describeWrite?: (write: OfflineWrite) => OfflineWriteDescription | null\r\n labels?: Partial<OfflineBoxesLabels>\r\n className?: string\r\n}\r\n\r\n/** Um endereço guardado partido no que a app pede: o endereço da API por inteiro e o resto. */\r\nfunction addressAndPathOf(path: string, address: string | undefined): { address: string; path: string } {\r\n if (/^https?:\\/\\//.test(path)) {\r\n const url = new URL(path)\r\n return { address: url.origin, path: url.pathname + url.search }\r\n }\r\n const base = new URL(address ?? '/', window.location.href).href.replace(/\\/$/, '')\r\n return { address: base, path }\r\n}\r\n\r\n/**\r\n * O que a app tem guardado para usar sem rede (Inbox, verde) e o que tem por\r\n * enviar (Outbox, laranja), num botão que se põe onde se quiser (ex: à\r\n * direita do título): o ícone e uma pílula com duas metades, a percentagem\r\n * guardada (sobe enquanto a descarga corre) e quantas escritas faltam enviar. Tocar abre a vista inteira\r\n * com o detalhe; nela, tocar numa linha guardada mostra o que está guardado\r\n * por inteiro (JSON). Fora da app OnePoint não aparece.\r\n */\r\nexport default function OfflineBoxes({ storageId, inboxIds, onRefresh, address, subtitle, describeSaved, describeWrite, labels, className = '' }: OfflineBoxesProps) {\r\n const L = { ...DEFAULT_OFFLINE_BOXES_LABELS, ...labels }\r\n const state = useOfflineBoxes({ storageId, inboxIds })\r\n const [open, setOpen] = useState(false)\r\n const triggerRef = useRef<HTMLButtonElement>(null)\r\n const dialogContainer = useDialogContainer()\r\n\r\n const close = () => {\r\n setOpen(false)\r\n triggerRef.current?.focus()\r\n }\r\n\r\n useEffect(() => {\r\n if (!open) return\r\n const escape = (e: KeyboardEvent) => {\r\n if (e.key !== 'Escape') return\r\n setOpen(false)\r\n triggerRef.current?.focus()\r\n }\r\n document.addEventListener('keydown', escape)\r\n return () => document.removeEventListener('keydown', escape)\r\n }, [open])\r\n\r\n const readSaved = useCallback((path: string) => readInbox({ storageId, ...addressAndPathOf(path, address) }), [storageId, address])\r\n\r\n if (!state) return null\r\n\r\n const pct = percentOf(state)\r\n const pctLabel = pct === null ? '–' : `${pct}%`\r\n const toSend = toSendOf(state)\r\n\r\n return (\r\n <div className={`relative inline-flex shrink-0 ${className}`}>\r\n <button\r\n ref={triggerRef}\r\n type=\"button\"\r\n aria-haspopup=\"dialog\"\r\n aria-expanded={open}\r\n aria-label={`${L.title}: ${L.saved} ${pctLabel} · ${filled(L.toSend, { n: toSend })}`}\r\n onClick={(e) => {\r\n e.stopPropagation()\r\n setOpen(true)\r\n }}\r\n className=\"flex min-h-11 cursor-pointer items-center gap-1.5 rounded-full border-0 bg-transparent px-1 hover:bg-slate-100 dark:hover:bg-slate-800\"\r\n >\r\n <OfflineBoxesIcon size={26} />\r\n <span className=\"flex h-7 items-stretch overflow-hidden rounded-full text-[11px] font-black whitespace-nowrap tabular-nums shadow-[0_1px_3px_rgba(0,27,99,0.18)]\">\r\n <span className=\"flex items-center gap-0.5 pr-1.5 pl-2 text-white\" style={{ background: INBOX_GREEN }}>\r\n <OfflineArrow />\r\n {pctLabel}\r\n </span>\r\n <span\r\n className={`flex items-center gap-0.5 pr-2 pl-1.5 ${toSend > 0 ? 'text-white' : 'bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400'}`}\r\n style={toSend > 0 ? { background: OUTBOX_ORANGE } : undefined}\r\n >\r\n <OfflineArrow up />\r\n {toSend}\r\n </span>\r\n </span>\r\n </button>\r\n {open &&\r\n createPortal(\r\n <OfflineBoxesView\r\n state={state}\r\n labels={L}\r\n subtitle={subtitle}\r\n address={address}\r\n onRefresh={onRefresh}\r\n onBack={close}\r\n describeSaved={describeSaved}\r\n describeWrite={describeWrite}\r\n readSaved={readSaved}\r\n />,\r\n dialogContainer ?? document.body,\r\n )}\r\n </div>\r\n )\r\n}\r\n\r\nexport { OfflineBoxes }\r\n"],"names":[],"mappings":";;;;;;;;AAmDA,SAAS,iBAAiB,MAAc,SAAgE;AACtG,MAAI,eAAe,KAAK,IAAI,GAAG;AAC7B,UAAM,MAAM,IAAI,IAAI,IAAI;AACxB,WAAO,EAAE,SAAS,IAAI,QAAQ,MAAM,IAAI,WAAW,IAAI,OAAA;AAAA,EACzD;AACA,QAAM,OAAO,IAAI,IAAI,WAAW,KAAK,OAAO,SAAS,IAAI,EAAE,KAAK,QAAQ,OAAO,EAAE;AACjF,SAAO,EAAE,SAAS,MAAM,KAAA;AAC1B;AAUA,SAAwB,aAAa,EAAE,WAAW,UAAU,WAAW,SAAS,UAAU,eAAe,eAAe,QAAQ,YAAY,GAAA,GAAyB;AACnK,QAAM,IAAI,EAAE,GAAG,8BAA8B,GAAG,OAAA;AAChD,QAAM,QAAQ,gBAAgB,EAAE,WAAW,UAAU;AACrD,QAAM,CAAC,MAAM,OAAO,IAAI,SAAS,KAAK;AACtC,QAAM,aAAa,OAA0B,IAAI;AACjD,QAAM,kBAAkB,mBAAA;AAExB,QAAM,QAAQ,MAAM;AAClB,YAAQ,KAAK;AACb,eAAW,SAAS,MAAA;AAAA,EACtB;AAEA,YAAU,MAAM;AACd,QAAI,CAAC,KAAM;AACX,UAAM,SAAS,CAAC,MAAqB;AACnC,UAAI,EAAE,QAAQ,SAAU;AACxB,cAAQ,KAAK;AACb,iBAAW,SAAS,MAAA;AAAA,IACtB;AACA,aAAS,iBAAiB,WAAW,MAAM;AAC3C,WAAO,MAAM,SAAS,oBAAoB,WAAW,MAAM;AAAA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AAA,MAAA;AAAA,IAAA;AAAA,IAED,QACC;AAAA,MACE;AAAA,QAAC;AAAA,QAAA;AAAA,UACC;AAAA,UACA,QAAQ;AAAA,UACR;AAAA,UACA;AAAA,UACA;AAAA,UACA,QAAQ;AAAA,UACR;AAAA,UACA;AAAA,UACA;AAAA,QAAA;AAAA,MAAA;AAAA,MAEF,mBAAmB,SAAS;AAAA,IAAA;AAAA,EAC9B,GACJ;AAEJ;"}
|
|
@@ -21,7 +21,15 @@ const DEFAULT_OFFLINE_BOXES_LABELS = {
|
|
|
21
21
|
rejected: "Refused",
|
|
22
22
|
available: "Available offline",
|
|
23
23
|
allSent: "All sent",
|
|
24
|
-
rejectedCount: "{n} refused"
|
|
24
|
+
rejectedCount: "{n} refused",
|
|
25
|
+
openSaved: "See what is saved for {title}",
|
|
26
|
+
showJson: "Show JSON",
|
|
27
|
+
hideJson: "Hide JSON",
|
|
28
|
+
copy: "Copy",
|
|
29
|
+
copied: "Copied",
|
|
30
|
+
reading: "Reading…",
|
|
31
|
+
notOnPhone: "Not on the phone",
|
|
32
|
+
savedOn: "Saved {date} {time}"
|
|
25
33
|
};
|
|
26
34
|
const INBOX_GREEN = "#19C99B";
|
|
27
35
|
const OUTBOX_ORANGE = "#EA6A12";
|
|
@@ -62,6 +70,15 @@ function matches(item, search) {
|
|
|
62
70
|
if (!search) return true;
|
|
63
71
|
return plain(`${item.title} ${item.meta ?? ""} ${item.detail ?? ""}`).includes(search);
|
|
64
72
|
}
|
|
73
|
+
function groupsOf(items) {
|
|
74
|
+
const groups = /* @__PURE__ */ new Map();
|
|
75
|
+
for (const item of items) {
|
|
76
|
+
const grouped = groups.get(item.group);
|
|
77
|
+
if (grouped) grouped.push(item);
|
|
78
|
+
else groups.set(item.group, [item]);
|
|
79
|
+
}
|
|
80
|
+
return [...groups].map(([group, grouped]) => ({ group, items: grouped }));
|
|
81
|
+
}
|
|
65
82
|
function legendOf(items) {
|
|
66
83
|
const seen = /* @__PURE__ */ new Map();
|
|
67
84
|
for (const item of items) {
|
|
@@ -110,31 +127,150 @@ function TabCard({ active, color, up, label, value, line, progress, alert, onCli
|
|
|
110
127
|
}
|
|
111
128
|
);
|
|
112
129
|
}
|
|
113
|
-
function
|
|
114
|
-
return /* @__PURE__ */
|
|
130
|
+
function SavedTags({ tags }) {
|
|
131
|
+
return /* @__PURE__ */ jsx("span", { className: "flex shrink-0 gap-1", children: tags.map((tag) => /* @__PURE__ */ jsx(
|
|
132
|
+
"span",
|
|
133
|
+
{
|
|
134
|
+
title: tag.label,
|
|
135
|
+
"aria-label": tag.label,
|
|
136
|
+
className: "flex h-[18px] min-w-[20px] items-center justify-center rounded-md border border-emerald-200 bg-emerald-50 px-1 text-[9px] font-black text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300",
|
|
137
|
+
children: tag.short
|
|
138
|
+
},
|
|
139
|
+
tag.short
|
|
140
|
+
)) });
|
|
141
|
+
}
|
|
142
|
+
function Chevron() {
|
|
143
|
+
return /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 20 20", "aria-hidden": "true", className: "shrink-0 text-slate-400", children: /* @__PURE__ */ jsx("path", { d: "M7.5 4l6 6-6 6", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) });
|
|
144
|
+
}
|
|
145
|
+
function SavedRow({ item, openLabel, onOpen }) {
|
|
146
|
+
const content = /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
115
147
|
/* @__PURE__ */ jsx("span", { className: "w-1 shrink-0", style: { background: INBOX_GREEN } }),
|
|
116
148
|
/* @__PURE__ */ jsxs("span", { className: "flex min-w-0 flex-1 flex-col gap-0.5 px-3 py-2", children: [
|
|
117
149
|
/* @__PURE__ */ jsxs("span", { className: "flex items-center justify-between gap-2", children: [
|
|
118
150
|
/* @__PURE__ */ jsx("span", { className: "text-[13px] font-bold tracking-tight whitespace-nowrap tabular-nums", children: item.title }),
|
|
119
|
-
item.tags && item.tags.length > 0 && /* @__PURE__ */ jsx(
|
|
120
|
-
"span",
|
|
121
|
-
{
|
|
122
|
-
title: tag.label,
|
|
123
|
-
"aria-label": tag.label,
|
|
124
|
-
className: "flex h-[18px] min-w-[20px] items-center justify-center rounded-md border border-emerald-200 bg-emerald-50 px-1 text-[9px] font-black text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300",
|
|
125
|
-
children: tag.short
|
|
126
|
-
},
|
|
127
|
-
tag.short
|
|
128
|
-
)) })
|
|
151
|
+
item.tags && item.tags.length > 0 && /* @__PURE__ */ jsx(SavedTags, { tags: item.tags })
|
|
129
152
|
] }),
|
|
130
153
|
item.detail && /* @__PURE__ */ jsx("span", { className: "truncate text-xs font-semibold text-slate-800 dark:text-slate-100", children: item.detail }),
|
|
131
154
|
item.meta && /* @__PURE__ */ jsx("span", { className: "truncate text-[11px] text-slate-500 dark:text-slate-400", children: item.meta })
|
|
132
|
-
] })
|
|
155
|
+
] }),
|
|
156
|
+
onOpen && /* @__PURE__ */ jsx("span", { className: "flex items-center pr-2.5", children: /* @__PURE__ */ jsx(Chevron, {}) })
|
|
157
|
+
] });
|
|
158
|
+
return /* @__PURE__ */ jsx("li", { className: `overflow-hidden rounded-xl bg-white dark:bg-slate-900 ${CARD_SHADOW}`, children: onOpen ? /* @__PURE__ */ jsx(
|
|
159
|
+
"button",
|
|
160
|
+
{
|
|
161
|
+
type: "button",
|
|
162
|
+
onClick: onOpen,
|
|
163
|
+
"aria-label": filled(openLabel, { title: item.title }),
|
|
164
|
+
style: { WebkitTapHighlightColor: "transparent" },
|
|
165
|
+
className: "flex w-full cursor-pointer touch-manipulation items-stretch border-0 bg-transparent p-0 text-left font-[inherit] text-current active:bg-slate-50 dark:active:bg-slate-800",
|
|
166
|
+
children: content
|
|
167
|
+
}
|
|
168
|
+
) : /* @__PURE__ */ jsx("span", { className: "flex items-stretch", children: content }) });
|
|
169
|
+
}
|
|
170
|
+
function sizeOf(text) {
|
|
171
|
+
const bytes = new Blob([text]).size;
|
|
172
|
+
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
|
|
173
|
+
}
|
|
174
|
+
function requestJson(action, address) {
|
|
175
|
+
return JSON.stringify(
|
|
176
|
+
{ method: action.method, path: action.path ? shownPath(action.path, address) : void 0, headers: action.headers ?? {}, body: action.body ?? null },
|
|
177
|
+
null,
|
|
178
|
+
2
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
function JsonToggle({ json, L, tone }) {
|
|
182
|
+
const [open, setOpen] = useState(false);
|
|
183
|
+
const [copied, setCopied] = useState(false);
|
|
184
|
+
const copy = async () => {
|
|
185
|
+
try {
|
|
186
|
+
await navigator.clipboard.writeText(json);
|
|
187
|
+
setCopied(true);
|
|
188
|
+
setTimeout(() => setCopied(false), 1500);
|
|
189
|
+
} catch {
|
|
190
|
+
setCopied(false);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
const toneClass = tone === "inbox" ? "border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300" : "border-orange-200 bg-orange-50 text-orange-800 dark:border-orange-900 dark:bg-orange-950 dark:text-orange-300";
|
|
194
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
195
|
+
/* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
|
|
196
|
+
/* @__PURE__ */ jsx(
|
|
197
|
+
"button",
|
|
198
|
+
{
|
|
199
|
+
type: "button",
|
|
200
|
+
onClick: () => setOpen((before) => !before),
|
|
201
|
+
"aria-expanded": open,
|
|
202
|
+
className: `flex h-9 cursor-pointer items-center rounded-full border px-3 text-[11px] font-bold ${toneClass}`,
|
|
203
|
+
children: open ? L.hideJson : L.showJson
|
|
204
|
+
}
|
|
205
|
+
),
|
|
206
|
+
open && typeof navigator !== "undefined" && navigator.clipboard && /* @__PURE__ */ jsx(
|
|
207
|
+
"button",
|
|
208
|
+
{
|
|
209
|
+
type: "button",
|
|
210
|
+
onClick: () => void copy(),
|
|
211
|
+
className: "flex h-9 cursor-pointer items-center rounded-full border border-slate-300 bg-white px-3 text-[11px] font-bold text-current dark:border-slate-600 dark:bg-slate-800",
|
|
212
|
+
children: copied ? L.copied : L.copy
|
|
213
|
+
}
|
|
214
|
+
)
|
|
215
|
+
] }),
|
|
216
|
+
open && /* @__PURE__ */ jsx("pre", { className: "m-0 max-h-[60vh] overflow-auto rounded-lg bg-slate-950 p-2.5 font-mono text-[10.5px] leading-snug whitespace-pre text-emerald-100", children: json })
|
|
217
|
+
] });
|
|
218
|
+
}
|
|
219
|
+
function SavedPartCard({ part, L, read }) {
|
|
220
|
+
const [result, setResult] = useState({ state: "reading" });
|
|
221
|
+
useEffect(() => {
|
|
222
|
+
let current = true;
|
|
223
|
+
read(part.path).then((answer) => {
|
|
224
|
+
if (!current) return;
|
|
225
|
+
if (!answer || !answer.found) setResult({ state: "missing" });
|
|
226
|
+
else setResult({ state: "found", json: JSON.stringify(answer.body, null, 2), savedAt: answer.savedAt });
|
|
227
|
+
}).catch(() => {
|
|
228
|
+
if (current) setResult({ state: "missing" });
|
|
229
|
+
});
|
|
230
|
+
return () => {
|
|
231
|
+
current = false;
|
|
232
|
+
};
|
|
233
|
+
}, [part.path, read]);
|
|
234
|
+
return /* @__PURE__ */ jsxs("li", { className: `flex flex-col gap-1.5 rounded-xl bg-white px-3 py-2.5 dark:bg-slate-900 ${CARD_SHADOW}`, children: [
|
|
235
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
|
|
236
|
+
/* @__PURE__ */ jsxs("span", { className: "flex min-w-0 flex-col gap-0.5", children: [
|
|
237
|
+
/* @__PURE__ */ jsx("span", { className: "text-[13px] font-bold", children: part.label }),
|
|
238
|
+
/* @__PURE__ */ jsx("span", { className: "font-mono text-[10px] break-all text-slate-500 dark:text-slate-400", children: part.path })
|
|
239
|
+
] }),
|
|
240
|
+
/* @__PURE__ */ jsxs("span", { className: "shrink-0 text-right text-[10px] text-slate-600 tabular-nums dark:text-slate-300", children: [
|
|
241
|
+
result.state === "reading" && L.reading,
|
|
242
|
+
result.state === "missing" && /* @__PURE__ */ jsx("span", { className: "font-bold text-red-700 dark:text-red-300", children: L.notOnPhone }),
|
|
243
|
+
result.state === "found" && /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
244
|
+
/* @__PURE__ */ jsx("span", { className: "block", children: filled(L.savedOn, { date: day(result.savedAt), time: clock(result.savedAt) }) }),
|
|
245
|
+
/* @__PURE__ */ jsx("span", { className: "block", children: sizeOf(result.json) })
|
|
246
|
+
] })
|
|
247
|
+
] })
|
|
248
|
+
] }),
|
|
249
|
+
result.state === "found" && /* @__PURE__ */ jsx(JsonToggle, { json: result.json, L, tone: "inbox" })
|
|
133
250
|
] });
|
|
134
251
|
}
|
|
135
|
-
function
|
|
252
|
+
function SavedItemDetail({ item, L, read }) {
|
|
253
|
+
return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2.5", children: [
|
|
254
|
+
/* @__PURE__ */ jsxs("div", { className: `flex items-stretch overflow-hidden rounded-xl bg-white dark:bg-slate-900 ${CARD_SHADOW}`, children: [
|
|
255
|
+
/* @__PURE__ */ jsx("span", { className: "w-1 shrink-0", style: { background: INBOX_GREEN } }),
|
|
256
|
+
/* @__PURE__ */ jsxs("span", { className: "flex min-w-0 flex-1 flex-col gap-0.5 px-3 py-2", children: [
|
|
257
|
+
/* @__PURE__ */ jsxs("span", { className: "flex items-center justify-between gap-2", children: [
|
|
258
|
+
/* @__PURE__ */ jsx("span", { className: "text-[15px] font-black tracking-tight whitespace-nowrap tabular-nums", children: item.title }),
|
|
259
|
+
item.tags && item.tags.length > 0 && /* @__PURE__ */ jsx(SavedTags, { tags: item.tags })
|
|
260
|
+
] }),
|
|
261
|
+
item.detail && /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold text-slate-800 dark:text-slate-100", children: item.detail }),
|
|
262
|
+
item.meta && /* @__PURE__ */ jsx("span", { className: "text-[11px] text-slate-500 dark:text-slate-400", children: item.meta })
|
|
263
|
+
] })
|
|
264
|
+
] }),
|
|
265
|
+
/* @__PURE__ */ jsx("ul", { className: "m-0 flex list-none flex-col gap-1.5 p-0", children: (item.parts ?? []).map((part) => /* @__PURE__ */ jsx(SavedPartCard, { part, L, read }, part.path)) })
|
|
266
|
+
] });
|
|
267
|
+
}
|
|
268
|
+
function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBack, describeSaved, describeWrite, readSaved }) {
|
|
136
269
|
const [tab, setTab] = useState(() => toSendOf(state) > 0 ? "waiting" : "saved");
|
|
137
270
|
const [search, setSearch] = useState("");
|
|
271
|
+
const [openItem, setOpenItem] = useState(null);
|
|
272
|
+
const listScroll = useRef(0);
|
|
273
|
+
const panelRef = useRef(null);
|
|
138
274
|
const backRef = useRef(null);
|
|
139
275
|
const { inbox, downloading, waiting } = state;
|
|
140
276
|
const pct = percentOf(state);
|
|
@@ -148,16 +284,35 @@ function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBa
|
|
|
148
284
|
document.body.style.overflow = before;
|
|
149
285
|
};
|
|
150
286
|
}, []);
|
|
287
|
+
useEffect(() => {
|
|
288
|
+
if (!openItem) return;
|
|
289
|
+
const escape = (e) => {
|
|
290
|
+
if (e.key !== "Escape") return;
|
|
291
|
+
e.stopImmediatePropagation();
|
|
292
|
+
setOpenItem(null);
|
|
293
|
+
};
|
|
294
|
+
document.addEventListener("keydown", escape, true);
|
|
295
|
+
return () => document.removeEventListener("keydown", escape, true);
|
|
296
|
+
}, [openItem]);
|
|
297
|
+
const openSaved = (item) => {
|
|
298
|
+
listScroll.current = panelRef.current?.scrollTop ?? 0;
|
|
299
|
+
setOpenItem(item);
|
|
300
|
+
panelRef.current?.scrollTo?.({ top: 0 });
|
|
301
|
+
};
|
|
302
|
+
const closeSaved = () => {
|
|
303
|
+
setOpenItem(null);
|
|
304
|
+
requestAnimationFrame(() => panelRef.current?.scrollTo?.({ top: listScroll.current }));
|
|
305
|
+
};
|
|
151
306
|
const summary = useMemo(() => {
|
|
152
307
|
const paths = inbox.saved.map((saved) => shownPath(saved, address));
|
|
153
308
|
if (describeSaved) return describeSaved(paths);
|
|
154
|
-
return { items: paths.map((path) => ({ key: path, title: path })) };
|
|
309
|
+
return { items: paths.map((path) => ({ key: path, title: path, parts: [{ label: path, path }] })) };
|
|
155
310
|
}, [inbox.saved, address, describeSaved]);
|
|
156
311
|
const wanted = plain(search.trim());
|
|
157
312
|
const shown = summary.items.filter((item) => matches(item, wanted));
|
|
158
313
|
const legend = legendOf(summary.items);
|
|
159
314
|
const downloadingLine = filled(L.downloading, { ready: inbox.ready, total: inbox.total });
|
|
160
|
-
const savedLine = downloading ? downloadingLine : summary.items.length ? filled(L.savedCount, { n: summary.items.length }) : L.nothingSaved;
|
|
315
|
+
const savedLine = downloading ? downloadingLine : summary.items.length ? filled(L.savedCount, { n: summary.count ?? summary.items.length }) : L.nothingSaved;
|
|
161
316
|
const describe = (action) => {
|
|
162
317
|
if (!action.method || !action.path) return { title: action.id };
|
|
163
318
|
const write = { method: action.method, path: shownPath(action.path, address) };
|
|
@@ -190,7 +345,7 @@ function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBa
|
|
|
190
345
|
ref: backRef,
|
|
191
346
|
type: "button",
|
|
192
347
|
"aria-label": L.back,
|
|
193
|
-
onClick: onBack,
|
|
348
|
+
onClick: tab === "saved" && openItem ? closeSaved : onBack,
|
|
194
349
|
className: "-ml-2 flex h-11 w-11 cursor-pointer items-center justify-center rounded-full border-0 bg-transparent text-white outline-none hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-white/70",
|
|
195
350
|
children: /* @__PURE__ */ jsx("svg", { width: "20", height: "20", viewBox: "0 0 20 20", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M12.5 4L6.5 10l6 6", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round" }) })
|
|
196
351
|
}
|
|
@@ -226,7 +381,10 @@ function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBa
|
|
|
226
381
|
value: pct === null ? "–" : `${pct}%`,
|
|
227
382
|
line: downloading ? downloadingLine : L.available,
|
|
228
383
|
progress: pct,
|
|
229
|
-
onClick: () =>
|
|
384
|
+
onClick: () => {
|
|
385
|
+
setTab("saved");
|
|
386
|
+
setOpenItem(null);
|
|
387
|
+
}
|
|
230
388
|
}
|
|
231
389
|
),
|
|
232
390
|
/* @__PURE__ */ jsx(
|
|
@@ -243,7 +401,7 @@ function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBa
|
|
|
243
401
|
}
|
|
244
402
|
)
|
|
245
403
|
] }),
|
|
246
|
-
tab === "saved" ? /* @__PURE__ */
|
|
404
|
+
tab === "saved" ? /* @__PURE__ */ jsx("div", { ref: panelRef, role: "tabpanel", "aria-label": L.saved, className: panel, children: openItem && readSaved ? /* @__PURE__ */ jsx(SavedItemDetail, { item: openItem, L, read: readSaved }) : /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
247
405
|
/* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 text-[11px] font-semibold text-slate-600 tabular-nums dark:text-slate-300", children: [
|
|
248
406
|
/* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5", children: [
|
|
249
407
|
/* @__PURE__ */ jsx("span", { className: `h-2 w-2 rounded-full ${downloading ? "animate-pulse" : ""}`, style: { background: INBOX_GREEN } }),
|
|
@@ -269,7 +427,21 @@ function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBa
|
|
|
269
427
|
}
|
|
270
428
|
)
|
|
271
429
|
] }),
|
|
272
|
-
shown.
|
|
430
|
+
groupsOf(shown).map(({ group, items }) => /* @__PURE__ */ jsxs("section", { "aria-label": group, className: "flex shrink-0 flex-col gap-1.5", children: [
|
|
431
|
+
group && /* @__PURE__ */ jsxs("h3", { className: "m-0 flex items-baseline gap-1.5 px-1 pt-1 text-[10px] font-black tracking-[0.14em] text-slate-500 uppercase dark:text-slate-400", children: [
|
|
432
|
+
group,
|
|
433
|
+
/* @__PURE__ */ jsx("span", { className: "tabular-nums", children: items.length })
|
|
434
|
+
] }),
|
|
435
|
+
/* @__PURE__ */ jsx("ul", { className: "m-0 flex list-none flex-col gap-1.5 p-0", children: items.map((item) => /* @__PURE__ */ jsx(
|
|
436
|
+
SavedRow,
|
|
437
|
+
{
|
|
438
|
+
item,
|
|
439
|
+
openLabel: L.openSaved,
|
|
440
|
+
onOpen: readSaved && item.parts && item.parts.length > 0 ? () => openSaved(item) : void 0
|
|
441
|
+
},
|
|
442
|
+
item.key
|
|
443
|
+
)) })
|
|
444
|
+
] }, group ?? "")),
|
|
273
445
|
summary.items.length > 0 && shown.length === 0 && /* @__PURE__ */ jsx("p", { className: "m-0 px-1 text-xs text-slate-600 dark:text-slate-300", children: L.noMatches }),
|
|
274
446
|
(legend.length > 0 || summary.note) && /* @__PURE__ */ jsxs("div", { className: "mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-[10px] text-slate-500 dark:text-slate-400", children: [
|
|
275
447
|
legend.map((tag) => /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1", children: [
|
|
@@ -278,7 +450,7 @@ function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBa
|
|
|
278
450
|
] }, tag.short)),
|
|
279
451
|
summary.note && /* @__PURE__ */ jsx("span", { className: "basis-full", children: summary.note })
|
|
280
452
|
] })
|
|
281
|
-
] }) : /* @__PURE__ */ jsx("div", { role: "tabpanel", "aria-label": L.waiting, className: panel, children: waiting.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col items-center justify-center gap-3 px-6 pb-16 text-center", children: [
|
|
453
|
+
] }) }) : /* @__PURE__ */ jsx("div", { role: "tabpanel", "aria-label": L.waiting, className: panel, children: waiting.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col items-center justify-center gap-3 px-6 pb-16 text-center", children: [
|
|
282
454
|
/* @__PURE__ */ jsx("span", { className: "flex h-20 w-20 items-center justify-center rounded-full", style: { background: `${OUTBOX_ORANGE}1f` }, children: /* @__PURE__ */ jsx("span", { className: "flex h-12 w-12 items-center justify-center rounded-full text-white", style: { background: OUTBOX_ORANGE }, children: /* @__PURE__ */ jsx("svg", { width: "22", height: "22", viewBox: "0 0 20 20", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M4.5 10.5l3.5 3.5 7.5-8", fill: "none", stroke: "currentColor", strokeWidth: "2.6", strokeLinecap: "round", strokeLinejoin: "round" }) }) }) }),
|
|
283
455
|
/* @__PURE__ */ jsx("span", { className: "text-lg font-black tracking-tight", children: L.allSent }),
|
|
284
456
|
/* @__PURE__ */ jsx("span", { className: "max-w-[260px] text-xs text-slate-600 dark:text-slate-300", children: L.nothingWaiting })
|
|
@@ -298,15 +470,25 @@ function OfflineBoxesView({ state, labels: L, subtitle, address, onRefresh, onBa
|
|
|
298
470
|
style: { background: tone.dot }
|
|
299
471
|
}
|
|
300
472
|
),
|
|
301
|
-
/* @__PURE__ */ jsxs("div", { className: `flex
|
|
302
|
-
/* @__PURE__ */ jsxs("
|
|
303
|
-
/* @__PURE__ */
|
|
304
|
-
|
|
305
|
-
|
|
473
|
+
/* @__PURE__ */ jsxs("div", { className: `flex flex-col gap-1.5 rounded-xl bg-white px-3 py-2.5 dark:bg-slate-900 ${CARD_SHADOW}`, children: [
|
|
474
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2", children: [
|
|
475
|
+
/* @__PURE__ */ jsxs("span", { className: "flex min-w-0 flex-1 flex-col gap-0.5", children: [
|
|
476
|
+
/* @__PURE__ */ jsx("span", { className: "text-[13px] font-bold break-words", children: description.title }),
|
|
477
|
+
description.detail && /* @__PURE__ */ jsx("span", { className: "truncate text-[11px] text-slate-600 dark:text-slate-300", children: description.detail }),
|
|
478
|
+
action.state === "rejected" && action.reason && /* @__PURE__ */ jsx("span", { className: "text-[11px] text-red-700 dark:text-red-300", children: action.reason })
|
|
479
|
+
] }),
|
|
480
|
+
/* @__PURE__ */ jsxs("span", { className: "flex shrink-0 flex-col items-end gap-1", children: [
|
|
481
|
+
/* @__PURE__ */ jsx("span", { className: `rounded-full px-2 py-0.5 text-[10px] font-bold whitespace-nowrap ${tone.pill}`, children: stateLabel(action) }),
|
|
482
|
+
action.createdAt && /* @__PURE__ */ jsx("span", { className: "text-[10px] text-slate-500 tabular-nums dark:text-slate-400", children: clock(action.createdAt) })
|
|
483
|
+
] })
|
|
306
484
|
] }),
|
|
307
|
-
/* @__PURE__ */ jsxs(
|
|
308
|
-
/* @__PURE__ */
|
|
309
|
-
|
|
485
|
+
action.method && action.path && /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
486
|
+
/* @__PURE__ */ jsxs("span", { className: "font-mono text-[10px] break-all text-slate-500 dark:text-slate-400", children: [
|
|
487
|
+
action.method,
|
|
488
|
+
" ",
|
|
489
|
+
shownPath(action.path, address)
|
|
490
|
+
] }),
|
|
491
|
+
/* @__PURE__ */ jsx(JsonToggle, { json: requestJson(action, address), L, tone: "outbox" })
|
|
310
492
|
] })
|
|
311
493
|
] })
|
|
312
494
|
] }, action.id);
|