@issuecat/react-native 0.0.0-stage → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +97 -2
- package/package.json +26 -4
- package/src/auto-replay.ts +36 -0
- package/src/index.ts +8 -0
- package/src/issuecat-inbox.ts +59 -0
- package/src/issuecat-push.ts +53 -0
- package/src/issuecat-replay.ts +263 -0
- package/src/issuecat-report.ts +164 -0
- package/src/issuecat-usage.ts +377 -0
- package/src/issuecat.tsx +753 -0
package/src/issuecat.tsx
ADDED
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
// Issuecat 문의 창 — npm 패키지 @issuecat/react-native로 넣고 한 줄로 엽니다. (React Native 0.7x+ · Expo 둘 다)
|
|
2
|
+
// 필요한 것(같이 설치): react-native-webview, @react-native-async-storage/async-storage, react-native-shake(흔들어 신고)
|
|
3
|
+
//
|
|
4
|
+
// Issuecat.configure({ installKey: "INSTALL_KEY" }) // 앱이 켜질 때 한 번
|
|
5
|
+
// <IssuecatHost /> // 앱 맨 바깥에 한 번 둔다(창이 뜰 자리)
|
|
6
|
+
// Issuecat.open() // 「문의하기」 단추에서
|
|
7
|
+
//
|
|
8
|
+
// 흔들어 신고(기본 켬): 휴대폰을 흔들면 화면 아래에 작은 시트가 먼저 뜹니다(스레드 Threads 앱 방식) — 제목·짧은 설명·「문제 신고하기」 단추·「흔들어서 문제 신고」 스위치.
|
|
9
|
+
// 단추를 눌러야 신고 창(Issuecat.open({ kind: "report" }))이 흔든 순간의 화면 그림을 싣고 열립니다. 스위치를 끄면 이 기기에 저장해 앱을 다시 켜도 흔들어도 안 뜹니다(Issuecat.shakeToReport).
|
|
10
|
+
// 앱 전체에서 끄려면 configure에 shake: false. 흔들림은 react-native-shake(MIT)가 받습니다: iOS는 시스템 흔들기라 시뮬레이터 Device › Shake에서도, Android는 가속도.
|
|
11
|
+
// Expo Go에는 그 네이티브 모듈이 없어 흔들기만 빠집니다(개발 빌드 npx expo run:ios·EAS에서 됩니다). 디버그 빌드에서는 RN 개발 메뉴도 같이 뜰 수 있습니다.
|
|
12
|
+
//
|
|
13
|
+
// 화면(첫 화면·문의하기·문제 신고하기, 서비스 이름·색, 지난 문의, 답장)은 Issuecat이 웹에서 그대로 줍니다 — 운영 화면에서 바꾸면 앱을 다시 내지 않아도 바뀝니다.
|
|
14
|
+
// 이 파일은 그 화면을 화면 전체 웹뷰로 띄우고, 앱 화면 그림·대화 열쇠·안 읽은 답 수·푸시 토큰만 주고받습니다.
|
|
15
|
+
// 앱 화면 그림: RN은 화면을 찍는 기본 길이 없어 configure의 capture로 받습니다(예: react-native-view-shot의 captureScreen).
|
|
16
|
+
// capture를 안 주거나 false면 그림 없이 보내고 화면의 「지금 화면」 줄도 감춥니다.
|
|
17
|
+
// 사진 붙이기(클립, 한 번에 10장): configure의 pickPhotos로 앱의 사진 고르기를 넘기면 그것을 씁니다(예: expo-image-picker — 안내 참고).
|
|
18
|
+
// 안 주면 react-native-webview의 기본 파일 고르기가 엽니다. Android는 react-native-webview 17.0.1 이상이면 카메라 허락을 보고 고르기를 엽니다.
|
|
19
|
+
// iOS 기본 고르기는 카메라가 있는 기기에서 늘 「사진 찍기」 줄을 넣어, Info.plist에 NSCameraUsageDescription이 없는 앱은 그 줄을 누르면 iOS가 앱을 닫습니다 —
|
|
20
|
+
// 그 키를 넣거나 pickPhotos를 주세요.
|
|
21
|
+
// 망이 끊겨 못 보낸 문의·답장은 AsyncStorage에 두었다가 앱이 앞에 올 때 대신 보냅니다.
|
|
22
|
+
// 받는 곳: https://issuecat.com/sdk/issuecat.tsx · 안내: https://issuecat.com/install/mobile/react-native.md
|
|
23
|
+
// 보낼 곳: configure에 baseURL을 빼면 Issuecat 운영 주소(https://issuecat.com)로 보냅니다 — 시험 서버·자기 서버를 쓰면 baseURL을 꼭 적으세요(위 주소들도 운영 주소 기준).
|
|
24
|
+
// 이용 기록(issuecat-usage.ts)도 넣었다면 Issuecat.identify·Issuecat.reset 한 번으로 그쪽도 같이 바뀝니다.
|
|
25
|
+
// react-native-webview 13.x·14.x 타입 둘 다에서 strict 타입 검사가 통과합니다. Issuecat.open()은 Promise라 단추에서는 `void Issuecat.open()`으로 부릅니다.
|
|
26
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
27
|
+
import React, { useEffect, useRef, useState } from "react";
|
|
28
|
+
import { AppState, Keyboard, Linking, Modal, Platform, Pressable, StatusBar, Switch, Text, useColorScheme, View } from "react-native";
|
|
29
|
+
import { WebView, type WebViewMessageEvent } from "react-native-webview";
|
|
30
|
+
|
|
31
|
+
// react-native-webview 13·14의 `class WebView<P = undefined> extends Component<WebViewProps & P>`는 strict에서 속성이 never가 된다 —
|
|
32
|
+
// 빈 덧속성({})으로 고정한 같은 부품을 쓴다(실행은 같은 WebView).
|
|
33
|
+
const IssuecatWebView = WebView<{}>;
|
|
34
|
+
type IssuecatWebViewRef = WebView<{}>;
|
|
35
|
+
|
|
36
|
+
export const ISSUECAT_VERSION = "1.5.0";
|
|
37
|
+
|
|
38
|
+
type Thread = { reportId: string; threadKey: string };
|
|
39
|
+
type Options = {
|
|
40
|
+
installKey: string;
|
|
41
|
+
baseURL?: string;
|
|
42
|
+
/** 운영 화면 「받은 곳」에 보일 앱 이름표(없으면 "react-native") */
|
|
43
|
+
app?: string;
|
|
44
|
+
/** 앱 판 — 신고 맥락에 실린다(예: DeviceInfo.getVersion()) */
|
|
45
|
+
appVersion?: string;
|
|
46
|
+
/** 지금 앱 화면을 JPEG base64(머리 없이)로. 예: () => captureScreen({ format: "jpg", quality: 0.7, result: "base64" }). false나 없음 = 그림 없음 */
|
|
47
|
+
capture?: (() => Promise<string | null>) | false;
|
|
48
|
+
/** 클립 단추의 사진 고르기(선택): max장까지 골라 JPEG base64(머리 없이) 목록으로 돌려줍니다. 고르지 않으면 빈 목록.
|
|
49
|
+
* 주면 웹뷰 기본 파일 고르기 대신 이것을 씁니다 — iOS 기본 고르기의 「사진 찍기」 줄(카메라 허락 글이 없으면 앱이 닫힘)을 피하려면 줍니다. */
|
|
50
|
+
pickPhotos?: (max: number) => Promise<string[]>;
|
|
51
|
+
/** true면 이 앱이 보내는 문의가 신고함에 「시험」으로 들어갑니다 — 운영자 알림·손님 숫자에 안 섞입니다. 설치를 확인하는 동안만 켜고 내놓을 판에서는 뺍니다(예: test: __DEV__).
|
|
52
|
+
* 이용 기록(issuecat-usage.ts)도 넣었다면 그쪽 행동·녹화도 같이 시험 기록으로 갑니다(check의 test) */
|
|
53
|
+
test?: boolean;
|
|
54
|
+
/** 문의 창 강조색(앱 색): 색 하나(예 "#0b6ef6" — 밝은·어두운 화면 같이) 또는 { light, dark }. 안 주면 운영 화면 서비스 설정의 색 */
|
|
55
|
+
accent?: string | { light?: string; dark?: string };
|
|
56
|
+
/** 창의 말("ko"·"en"). 앱이 쓰는 말을 넘깁니다(예: i18n 라이브러리의 지금 언어). 안 주면 휴대폰 언어를 따릅니다 */
|
|
57
|
+
locale?: string;
|
|
58
|
+
/** 흔들어 신고(기본 true): 휴대폰을 흔들면 아래 시트가 뜨고, 그 안의 「문제 신고하기」로 신고 창이 열립니다. false면 흔들어도 아무것도 안 뜹니다 — 단추·메뉴의 Issuecat.open()은 그대로.
|
|
59
|
+
* 시트의 「흔들어서 문제 신고」 스위치는 앱을 쓰는 사람이 이 기기에서만 끄는 것입니다(Issuecat.shakeToReport) — 앱 설정 화면에 같은 스위치를 둘 수 있습니다. */
|
|
60
|
+
shake?: boolean;
|
|
61
|
+
/** 그 스위치를 끌 때 시트에 보일 한 줄 — 앱에서 신고하는 다른 길을 적습니다(예: "설정 › 고객센터 › 문제 신고에서 알릴 수 있어요").
|
|
62
|
+
* 안 주면 「이제 흔들어도 이 창이 뜨지 않아요. 문제는 앱의 문의하기에서도 신고할 수 있어요.」(영어 화면은 영어로) */
|
|
63
|
+
shakeOffHint?: string;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
let opts: Options | null = null;
|
|
67
|
+
let user: { id: string; name?: string; email?: string; hash?: string; avatar?: string; company?: string } | null = null;
|
|
68
|
+
let extraContext: Record<string, string> = {};
|
|
69
|
+
let pushToken: { token: string; platform: "apns" | "fcm" } | null = null;
|
|
70
|
+
let unreadCallback: ((n: number) => void) | null = null;
|
|
71
|
+
let pushReadyCallback: ((ready: boolean) => void) | null = null;
|
|
72
|
+
let warnedNotReady = false;
|
|
73
|
+
let openState: { url: string; shot: string | null } | null = null;
|
|
74
|
+
let setHost: ((s: typeof openState) => void) | null = null;
|
|
75
|
+
let sendToScreen: ((m: object) => void) | null = null;
|
|
76
|
+
let appStateSub: { remove(): void } | null = null;
|
|
77
|
+
/** 앱 쓰는 사람이 시트 스위치로 흔들어 신고를 껐나 — 기기 저장(AsyncStorage)을 configure 때 읽어 둔다 */
|
|
78
|
+
const SHAKE_OFF_KEY = "issuecat.shake.off";
|
|
79
|
+
let shakeOff = false;
|
|
80
|
+
/** 저장값 읽기(configure 때 시작) — 다 읽기 전에 흔들면 기다리고, 그사이 앱이 값을 쓰면 읽은 값은 버린다 */
|
|
81
|
+
let shakeLoad: Promise<void> | null = null;
|
|
82
|
+
let shakeWritten = false;
|
|
83
|
+
/** 흔들면 뜨는 시트: 흔든 순간 찍은 앱 화면(시트가 덮기 전) */
|
|
84
|
+
let setSheet: ((s: { shot: string | null } | null) => void) | null = null;
|
|
85
|
+
let sheetOpen = false;
|
|
86
|
+
|
|
87
|
+
const base = () => (opts?.baseURL ?? "https://issuecat.com").replace(/\/+$/, "");
|
|
88
|
+
// 대화 열쇠 자리: 로그인한 사람마다 따로(<대화 자리>.<설치키>.u.<아이디>), 로그인 없이 쓰는 앱은 설치키 하나 — reset을 못 부른 채(세션 만료 등)
|
|
89
|
+
// 다른 사람이 identify돼도 그 사람 것만 보인다. 자리 이름은 맨 아래 「옛 코드 호환」의 OLD_STORAGE(앞 판 값 그대로)
|
|
90
|
+
const legacyKey = () => `${OLD_STORAGE.threads}.${opts?.installKey ?? ""}`;
|
|
91
|
+
const storeKey = (u: { id: string } | null = user) => (u ? `${legacyKey()}.u.${encodeURIComponent(u.id)}` : legacyKey());
|
|
92
|
+
const outboxKey = () => `${OLD_STORAGE.outbox}.${opts?.installKey ?? ""}`;
|
|
93
|
+
type Pending = { id: string; path: string; body: string; who?: string };
|
|
94
|
+
|
|
95
|
+
/** 로그인하면 이 기기의 익명 대화를 그 사람에게(Intercom 리드 → 사용자·Chatwoot setUser처럼): 로그인 없이 보낸 대화(<대화 자리>.<설치키>)를
|
|
96
|
+
* 그 사람 자리로 옮기고 익명 자리는 비운다 — 한 번 사람에게 간 대화는 익명 자리로 돌아가지 않아 로그아웃 뒤·다음 사람에게는 안 보인다.
|
|
97
|
+
* 앞 판(사람 구분 없이 <대화 자리>.<설치키> 하나)이 남긴 목록도 이 길로 처음 identify하는 사람(앱이 되살린 로그인)에게 간다.
|
|
98
|
+
* 서버에도 「이 대화들은 이 사람」을 알린다(운영 화면 신고자) — 못 알렸으면 <대화 자리>.claim.<자리> 표시를 남겨 다음 identify 때 다시.
|
|
99
|
+
* identify를 안 쓰는 앱은 설치키 하나를 지금처럼 이 기기의 목록으로 쓴다. */
|
|
100
|
+
async function carryAnon() {
|
|
101
|
+
if (!opts || !user) return;
|
|
102
|
+
const u = user;
|
|
103
|
+
const key = storeKey(u);
|
|
104
|
+
const pending = `${OLD_STORAGE.threads}.claim.${key}`;
|
|
105
|
+
const anon = await threads(legacyKey());
|
|
106
|
+
if (anon.length) {
|
|
107
|
+
// 그 사람 자리에 다 써진 뒤에만 익명 자리를 비운다 — 쓰다 실패하면(저장소 가득) 익명 자리를 그대로 두고 다음 identify 때 다시
|
|
108
|
+
try { for (const t of [...anon].reverse()) await saveThread(t, key); } catch { return; }
|
|
109
|
+
await AsyncStorage.removeItem(legacyKey());
|
|
110
|
+
await AsyncStorage.setItem(pending, "1");
|
|
111
|
+
}
|
|
112
|
+
if (!(await AsyncStorage.getItem(pending))) return;
|
|
113
|
+
const r = await post("/v1/ingest/threads/claim", { installKey: opts.installKey, user: u, threads: (await threads(key)).slice(0, 50) });
|
|
114
|
+
if (r && r.ok === true) await AsyncStorage.removeItem(pending);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 기기 사이 잇기: identify에 확인 값(hash)이 있으면 그 사람의 모든 문의(다른 기기에서 보낸 것 포함)를 받아 이 기기 목록에 더한다.
|
|
118
|
+
* 이 기기가 쥔 대화는 그 사람에게 이어 다른 기기에서도 보이게 한다. 확인 값이 틀리면(401) 아무것도 안 바뀐다 — 이 기기 목록만. */
|
|
119
|
+
async function syncPerson() {
|
|
120
|
+
if (!opts || !user?.hash) return;
|
|
121
|
+
const key = storeKey(user);
|
|
122
|
+
const r = await post("/v1/ingest/threads/mine", { installKey: opts.installKey, user: { id: user.id, hash: user.hash }, threads: (await threads(key)).slice(0, 50) });
|
|
123
|
+
if (!r || !Array.isArray(r.threads) || key !== storeKey()) return; // 그사이 사람이 바뀌었으면 버린다
|
|
124
|
+
let added = false;
|
|
125
|
+
for (const x of [...r.threads].reverse()) {
|
|
126
|
+
if (!x || typeof x.reportId !== "string" || typeof x.threadKey !== "string" || !x.reportId || !x.threadKey) continue;
|
|
127
|
+
const t = { reportId: x.reportId, threadKey: x.threadKey };
|
|
128
|
+
if (await rememberPerson(t, key)) {
|
|
129
|
+
attachPush(t);
|
|
130
|
+
added = true;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (added) void refreshUnread();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// 두었다 보내기: 화면이 망 문제로 못 보낸 요청(queued). 같은 신고·답장 번호라 화면이 먼저 보냈어도 서버는 한 번만 받는다.
|
|
137
|
+
async function outbox(): Promise<Pending[]> {
|
|
138
|
+
try {
|
|
139
|
+
const v = JSON.parse((await AsyncStorage.getItem(outboxKey())) ?? "[]");
|
|
140
|
+
return Array.isArray(v) ? v.filter((x) => x && typeof x.id === "string" && typeof x.path === "string" && typeof x.body === "string") : [];
|
|
141
|
+
} catch {
|
|
142
|
+
return [];
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function outboxSave(list: Pending[]) {
|
|
146
|
+
if (list.length) await AsyncStorage.setItem(outboxKey(), JSON.stringify(list));
|
|
147
|
+
else await AsyncStorage.removeItem(outboxKey());
|
|
148
|
+
}
|
|
149
|
+
let flushing = false;
|
|
150
|
+
/** 창이 닫혀 있을 때 오래된 것부터 보낸다. 다시 보내도 안 받는 것(4xx, 408·429 빼고)은 버린다. */
|
|
151
|
+
async function flushOutbox() {
|
|
152
|
+
if (flushing || !opts || openState) return;
|
|
153
|
+
flushing = true;
|
|
154
|
+
try {
|
|
155
|
+
for (;;) {
|
|
156
|
+
const p = (await outbox())[0];
|
|
157
|
+
if (!p) break;
|
|
158
|
+
let code = 0;
|
|
159
|
+
let out: any = null;
|
|
160
|
+
try {
|
|
161
|
+
const r = await fetch(base() + p.path, { method: "POST", headers: { "content-type": "application/json" }, body: p.body });
|
|
162
|
+
code = r.status;
|
|
163
|
+
out = await r.json().catch(() => null);
|
|
164
|
+
} catch {
|
|
165
|
+
code = 0;
|
|
166
|
+
}
|
|
167
|
+
if (code === 0 || code >= 500 || code === 408 || code === 429) break; // 망·서버 사정: 다음에 앞에 올 때
|
|
168
|
+
await outboxSave((await outbox()).filter((x) => x.id !== p.id));
|
|
169
|
+
if (code >= 200 && code < 300 && p.path === "/v1/ingest/reports") {
|
|
170
|
+
try {
|
|
171
|
+
const sent = JSON.parse(p.body);
|
|
172
|
+
const key = (out && typeof out.threadKey === "string" && out.threadKey) || sent.threadKey;
|
|
173
|
+
if (typeof sent.reportId === "string" && typeof key === "string") {
|
|
174
|
+
const t = { reportId: sent.reportId, threadKey: key };
|
|
175
|
+
const owner = typeof p.who === "string" ? p.who : storeKey(); // 쓴 사람 자리에
|
|
176
|
+
await saveThread(t, owner);
|
|
177
|
+
if (owner === storeKey()) attachPush(t);
|
|
178
|
+
}
|
|
179
|
+
} catch {}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
} finally {
|
|
183
|
+
flushing = false;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 다른 기기에서 보낸 대화(확인 값으로 서버가 다시 만들어 준 열쇠)는 메모리에만 — AsyncStorage에 남기지 않고 앱이 켜질 때·앞에 올 때 다시 받는다 */
|
|
188
|
+
let personThreads: Thread[] = [];
|
|
189
|
+
let personKey = "";
|
|
190
|
+
/** 받은 대화를 메모리에 더한다(열쇠가 바뀌었으면 새 값으로) — 새로 더한 것만 true */
|
|
191
|
+
async function rememberPerson(t: Thread, key = storeKey()): Promise<boolean> {
|
|
192
|
+
if (personKey !== key) {
|
|
193
|
+
personThreads = [];
|
|
194
|
+
personKey = key;
|
|
195
|
+
}
|
|
196
|
+
if ((await threads(key)).some((x) => x.reportId === t.reportId)) return false;
|
|
197
|
+
const i = personThreads.findIndex((x) => x.reportId === t.reportId);
|
|
198
|
+
if (i >= 0) {
|
|
199
|
+
if (personThreads[i].threadKey !== t.threadKey) personThreads[i] = t;
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
personThreads.push(t);
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
/** 이 기기에서 보낸 대화(저장) + 받은 대화(메모리) */
|
|
206
|
+
async function allThreads(): Promise<Thread[]> {
|
|
207
|
+
const key = storeKey();
|
|
208
|
+
const own = await threads(key);
|
|
209
|
+
if (personKey !== key || !personThreads.length) return own;
|
|
210
|
+
const ids = new Set(own.map((t) => t.reportId));
|
|
211
|
+
return [...own, ...personThreads.filter((t) => !ids.has(t.reportId))];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 대화 열쇠: AsyncStorage — 앱을 지우면 사라집니다(iOS도 같음). */
|
|
215
|
+
async function threads(key = storeKey()): Promise<Thread[]> {
|
|
216
|
+
try {
|
|
217
|
+
const v = JSON.parse((await AsyncStorage.getItem(key)) ?? "[]");
|
|
218
|
+
return Array.isArray(v) ? v.filter((t) => t && typeof t.reportId === "string" && typeof t.threadKey === "string") : [];
|
|
219
|
+
} catch {
|
|
220
|
+
return [];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async function saveThread(t: Thread, key = storeKey()) {
|
|
224
|
+
const list = [t, ...(await threads(key)).filter((x) => x.reportId !== t.reportId)].slice(0, 200);
|
|
225
|
+
await AsyncStorage.setItem(key, JSON.stringify(list));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function post(path: string, body: object): Promise<any> {
|
|
229
|
+
try {
|
|
230
|
+
const r = await fetch(base() + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
231
|
+
return await r.json();
|
|
232
|
+
} catch {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function attachPush(t: Thread) {
|
|
238
|
+
if (!pushToken || !opts) return;
|
|
239
|
+
const p = pushToken;
|
|
240
|
+
void post(`/v1/ingest/threads/${encodeURIComponent(t.reportId)}/push`, { installKey: opts.installKey, threadKey: t.threadKey, provider: p.platform, token: p.token }).then((r) => {
|
|
241
|
+
if (!r || typeof r.ready !== "boolean") return;
|
|
242
|
+
if (!r.ready && !warnedNotReady) {
|
|
243
|
+
warnedNotReady = true;
|
|
244
|
+
console.warn(`[Issuecat] 푸시 열쇠가 아직 없어요(ready:false) — 토큰은 등록됐지만 답 푸시는 안 가요. 운영자가 「설정」 → 「알림」 탭 → 「앱 고객 푸시」 → 「앱 고객에게 푸시」에 ${p.platform === "apns" ? "APNs 키(.p8)" : "FCM 서비스 계정 JSON"}을 올리면 가요.`);
|
|
245
|
+
}
|
|
246
|
+
pushReadyCallback?.(r.ready);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// 이용 기록(issuecat-usage.ts)과 로그인 잇기: 두 파일이 서로를 가져오지 않는다(하나만 넣어도 된다). 같은 자바스크립트 안의 globalThis로 지금 사람과 듣는 목록을 나눈다.
|
|
251
|
+
type LinkedUser = { id: string; name?: string; email?: string } | null;
|
|
252
|
+
const link = globalThis as { __issuecatUser?: LinkedUser; __issuecatUserListeners?: Array<(u: LinkedUser) => void> };
|
|
253
|
+
function announceUser() {
|
|
254
|
+
// 확인 값(hash)은 이용 기록 쪽에 넘기지 않는다 — 문의 창만 쓴다
|
|
255
|
+
link.__issuecatUser = user ? { id: user.id, ...(user.name ? { name: user.name } : {}), ...(user.email ? { email: user.email } : {}) } : null;
|
|
256
|
+
setOldLinkedUser(link.__issuecatUser);
|
|
257
|
+
for (const f of linkedListeners()) {
|
|
258
|
+
try { f(link.__issuecatUser); } catch { /* 이용 기록 쪽 오류가 문의 창을 막지 않게 */ }
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 닫혀 있을 때의 안 읽은 수: 저장한 열쇠로 묻는다. 앱이 앞에 있는 동안은 푸시가 없어도 새 답을 알아채게
|
|
264
|
+
* 15초에서 시작해 바뀐 게 없으면 두 배씩 2분까지 늘려 다시 묻는다(앞으로 올 때·창을 닫을 때·답이 오면 15초로). 뒤로 가면 멈춘다.
|
|
265
|
+
*/
|
|
266
|
+
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
|
267
|
+
let pollGap = 15_000;
|
|
268
|
+
let lastTotal: number | null = null;
|
|
269
|
+
function stopPolling() {
|
|
270
|
+
if (pollTimer) clearTimeout(pollTimer);
|
|
271
|
+
pollTimer = null;
|
|
272
|
+
}
|
|
273
|
+
async function refreshUnread(fromTimer = false) {
|
|
274
|
+
if (!fromTimer) pollGap = 15_000;
|
|
275
|
+
stopPolling();
|
|
276
|
+
const cb = unreadCallback;
|
|
277
|
+
if (!cb || !opts || openState) return;
|
|
278
|
+
const saved = await allThreads();
|
|
279
|
+
if (!saved.length) return cb(0);
|
|
280
|
+
const r = await post("/v1/ingest/threads/unread", { installKey: opts.installKey, threads: saved.slice(0, 50) });
|
|
281
|
+
const n = r && typeof r.total === "number" ? r.total : null;
|
|
282
|
+
if (n !== null) cb(n);
|
|
283
|
+
if (n !== null && lastTotal !== null && n !== lastTotal) pollGap = 15_000;
|
|
284
|
+
else if (fromTimer) pollGap = Math.min(pollGap * 2, 120_000);
|
|
285
|
+
if (n !== null) lastTotal = n;
|
|
286
|
+
stopPolling();
|
|
287
|
+
if (AppState.currentState === "active" && !openState && unreadCallback) pollTimer = setTimeout(() => void refreshUnread(true), pollGap);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Issuecat.setNavigation이 받은 React Navigation 컨테이너 참조(Expo Router는 useNavigationContainerRef()) */
|
|
291
|
+
let navRef: { getCurrentRoute?: () => { name?: unknown } | undefined } | null = null;
|
|
292
|
+
|
|
293
|
+
/** 지금 앱 화면 이름 — Issuecat.setScreen·onStateChange·이용 기록(issuecat-usage.ts)의 screen()이 globalThis에 남긴 것,
|
|
294
|
+
* 없으면 setNavigation으로 받은 내비게이션의 지금 화면(첫 화면처럼 상태 변화가 아직 없을 때도 — Sentry registerNavigationContainer와 같은 길) */
|
|
295
|
+
function screenNow(): string | undefined {
|
|
296
|
+
const g = globalThis as { __issuecatScreen?: string };
|
|
297
|
+
let s = typeof g.__issuecatScreen === "string" ? g.__issuecatScreen.trim() : "";
|
|
298
|
+
if (!s && navRef?.getCurrentRoute) {
|
|
299
|
+
try { const n = navRef.getCurrentRoute()?.name; if (typeof n === "string") s = n.trim(); } catch { /* 아직 준비 안 된 컨테이너 */ }
|
|
300
|
+
}
|
|
301
|
+
return s ? s.slice(0, 200) : undefined;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** React Navigation 상태에서 지금 보이는 화면(가장 안쪽 경로)의 이름 */
|
|
305
|
+
function routeName(state: unknown): string | undefined {
|
|
306
|
+
let st = state as { index?: number; routes?: Array<{ name?: string; state?: unknown }> } | undefined;
|
|
307
|
+
let name: string | undefined;
|
|
308
|
+
for (let depth = 0; st && Array.isArray(st.routes) && st.routes.length && depth < 20; depth++) {
|
|
309
|
+
const r = st.routes[typeof st.index === "number" ? st.index : st.routes.length - 1];
|
|
310
|
+
if (!r) break;
|
|
311
|
+
if (typeof r.name === "string") name = r.name;
|
|
312
|
+
st = r.state as typeof st;
|
|
313
|
+
}
|
|
314
|
+
return name;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function context(): Record<string, string> {
|
|
318
|
+
const c: Record<string, string> = { os: `${Platform.OS === "ios" ? "iOS" : "Android"} ${Platform.Version}` };
|
|
319
|
+
if (opts?.appVersion) c.appVersion = opts.appVersion;
|
|
320
|
+
// 기기(Android는 제조사·모델, iOS는 RN이 모델을 안 줘서 빈칸) · 앱의 말 — 상담창(WebView) 값이 아니라 이 값을 운영 화면이 먼저 보인다
|
|
321
|
+
const pc = (Platform as { constants?: { Manufacturer?: string; Model?: string } }).constants;
|
|
322
|
+
if (Platform.OS === "android" && pc?.Model) c.device = [pc.Manufacturer, pc.Model].filter(Boolean).join(" ");
|
|
323
|
+
try { const l = Intl.DateTimeFormat().resolvedOptions().locale; if (l) c.locale = l; } catch { /* Intl 없는 엔진 */ }
|
|
324
|
+
// 신고 직전 앱 화면(Sentry app.view_names·Instabug Current View와 같은 자리)
|
|
325
|
+
const s = screenNow();
|
|
326
|
+
if (s) c.screen = s;
|
|
327
|
+
return { ...c, ...extraContext };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function b64url(s: string): string {
|
|
331
|
+
// UTF-8 → base64url (Hermes에는 Buffer가 없다)
|
|
332
|
+
const bytes = unescape(encodeURIComponent(s));
|
|
333
|
+
const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
334
|
+
let out = "";
|
|
335
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
336
|
+
const n = (bytes.charCodeAt(i) << 16) | ((bytes.charCodeAt(i + 1) || 0) << 8) | (bytes.charCodeAt(i + 2) || 0);
|
|
337
|
+
out += abc[(n >> 18) & 63] + abc[(n >> 12) & 63] + (i + 1 < bytes.length ? abc[(n >> 6) & 63] : "") + (i + 2 < bytes.length ? abc[n & 63] : "");
|
|
338
|
+
}
|
|
339
|
+
return out;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export const Issuecat = {
|
|
343
|
+
/** 설치키와 주소. 앱이 켜질 때 한 번. */
|
|
344
|
+
configure(o: Options) {
|
|
345
|
+
opts = o;
|
|
346
|
+
(globalThis as { __issuecatTest?: boolean }).__issuecatTest = o.test === true; // 이용 기록(issuecat-usage.ts)에 시험 표시를 나눈다
|
|
347
|
+
setOldTestFlag(o.test === true);
|
|
348
|
+
appStateSub?.remove();
|
|
349
|
+
appStateSub = AppState.addEventListener("change", (s) => { if (s === "active") { void refreshUnread(); void flushOutbox(); void syncPerson(); } else stopPolling(); });
|
|
350
|
+
shakeWritten = false;
|
|
351
|
+
shakeLoad = AsyncStorage.getItem(SHAKE_OFF_KEY).then((v) => { if (!shakeWritten) shakeOff = v === "1"; }, () => {});
|
|
352
|
+
void carryAnon().then(syncPerson); // configure 전에 identify한 사람
|
|
353
|
+
void flushOutbox();
|
|
354
|
+
},
|
|
355
|
+
/** 손님 정보(선택) — 운영 화면 「신고자」에 보입니다. 로그아웃은 reset(). 로그인 전에 보낸 문의는 이 사람의 것으로 이어집니다(지난 문의·새 답 수·신고자). */
|
|
356
|
+
/** 이용 기록(issuecat-usage.ts)을 같은 앱에 넣었으면 그쪽 identify도 같이 됩니다 — 따로 안 불러도 됩니다(둘 다 불러도 한 번만 셉니다). */
|
|
357
|
+
/** hash(선택): 내 서버가 서비스 비밀 키로 만든 확인 값(HMAC-SHA256(id)의 16진수). 주면 그 사람이 다른 기기에서 보낸 문의도 이 기기에 이어집니다.
|
|
358
|
+
* 비밀 키는 앱에 넣지 않습니다 — 로그인할 때 내 서버에서 받은 값을 그대로 넘깁니다. */
|
|
359
|
+
/** avatar(선택): 회원 사진 주소(https) — 운영 화면 얼굴 자리에 그 사진(없으면 이름 머리글자). company(선택): 회사 이름 — 고객 정보 칸 「회사」. */
|
|
360
|
+
identify(u: { id: string; name?: string; email?: string; hash?: string; avatar?: string; company?: string }) {
|
|
361
|
+
const changed = user?.id !== u.id;
|
|
362
|
+
user = { ...u };
|
|
363
|
+
announceUser();
|
|
364
|
+
void (async () => {
|
|
365
|
+
await carryAnon();
|
|
366
|
+
await syncPerson();
|
|
367
|
+
sendToScreen?.({ type: "config", user, context: context(), threads: await allThreads() });
|
|
368
|
+
if (changed) void refreshUnread();
|
|
369
|
+
})();
|
|
370
|
+
},
|
|
371
|
+
/** 지금 보이는 앱 화면 이름(예 "/settings"·"Checkout") — 신고에 「앱 화면」으로 붙습니다. 이용 기록(issuecat-usage.ts)의 screen()을 부르는 앱은 안 불러도 됩니다. */
|
|
372
|
+
setScreen(name: string | null) {
|
|
373
|
+
(globalThis as { __issuecatScreen?: string }).__issuecatScreen = name ? String(name).slice(0, 200) : undefined;
|
|
374
|
+
},
|
|
375
|
+
/** React Navigation(Expo Router 포함)에 걸면 화면이 바뀔 때마다 「앱 화면」이 저절로 따라갑니다 — Instabug onStateChange와 같은 꼴:
|
|
376
|
+
* <NavigationContainer onStateChange={Issuecat.onStateChange}> */
|
|
377
|
+
onStateChange(state: unknown) {
|
|
378
|
+
const n = routeName(state);
|
|
379
|
+
if (n) Issuecat.setScreen(n);
|
|
380
|
+
},
|
|
381
|
+
/** React Navigation 컨테이너 참조를 한 번 넘기면 신고 창을 열 때 그 순간의 화면을 읽습니다 — 첫 화면도 붙습니다.
|
|
382
|
+
* const ref = createNavigationContainerRef(); <NavigationContainer ref={ref}> 뒤 Issuecat.setNavigation(ref)
|
|
383
|
+
* Expo Router: const ref = useNavigationContainerRef(); useEffect(() => Issuecat.setNavigation(ref), [ref]) */
|
|
384
|
+
setNavigation(ref: unknown) {
|
|
385
|
+
const r = ref as { getCurrentRoute?: unknown; current?: { getCurrentRoute?: unknown } } | null;
|
|
386
|
+
navRef = (r && typeof r.getCurrentRoute === "function" ? r : r?.current && typeof r.current.getCurrentRoute === "function" ? r.current : null) as typeof navRef;
|
|
387
|
+
},
|
|
388
|
+
/** 신고에 같이 실을 앱 정보(선택) — 앱 판·OS·기기·언어·앱 화면은 SDK가 넣습니다 */
|
|
389
|
+
setContext(c: Record<string, string>) {
|
|
390
|
+
extraContext = { ...c };
|
|
391
|
+
sendToScreen?.({ type: "config", context: context() });
|
|
392
|
+
},
|
|
393
|
+
/**
|
|
394
|
+
* 문의 창을 엽니다. thread: 답 알림을 눌렀을 때 그 신고 번호(푸시의 threadId)를 주면 그 대화가 바로 열립니다.
|
|
395
|
+
* kind: "inquiry"(문의하기 — 운영자와 대화) · "report"(문제 신고하기 — 지금 화면부터)를 주면 그 갈래로 바로 엽니다 — Issuecat.open({ kind: "report" }).
|
|
396
|
+
* 운영자가 꺼 둔 갈래를 부르면 켜진 갈래로 열립니다. 안 주면 첫 화면(손님이 고름).
|
|
397
|
+
* view: "threads"면 지난 문의부터(앱 메뉴 「내 문의」 — 지난 문의가 없으면 첫 화면). 창이 이미 열려 있으면 그 자리로 옮깁니다.
|
|
398
|
+
* 여는 중(앱 화면 찍기를 기다리는 동안)에 또 불러도 창은 하나입니다 — 같은 Promise를 돌려줍니다.
|
|
399
|
+
*/
|
|
400
|
+
open(o: { thread?: string; kind?: "inquiry" | "report"; view?: "threads" } = {}): Promise<void> {
|
|
401
|
+
if (!opening) opening = openNow(o).finally(() => { opening = null; });
|
|
402
|
+
return opening;
|
|
403
|
+
},
|
|
404
|
+
/** 흔들어 신고를 이 기기에서 켜 둘지(기본 true) — 앱을 쓰는 사람이 흔들면 뜨는 시트의 스위치로 바꾸는 값이고, 기기에 저장돼 앱을 다시 켜도 그대로입니다.
|
|
405
|
+
* 앱 설정 화면에 「흔들어서 문제 신고」 스위치를 두려면 이 값을 읽고 씁니다(Issuecat.shakeToReport = false). configure의 shake: false면 이 값과 상관없이 흔들어도 안 뜹니다. */
|
|
406
|
+
get shakeToReport(): boolean {
|
|
407
|
+
return !shakeOff;
|
|
408
|
+
},
|
|
409
|
+
set shakeToReport(on: boolean) {
|
|
410
|
+
shakeOff = !on;
|
|
411
|
+
shakeWritten = true;
|
|
412
|
+
void (on ? AsyncStorage.removeItem(SHAKE_OFF_KEY) : AsyncStorage.setItem(SHAKE_OFF_KEY, "1")).catch(() => {});
|
|
413
|
+
},
|
|
414
|
+
/** 안 읽은 답 수. 창이 열려 있으면 바뀔 때마다, 닫혀 있으면 앱이 앞에 있는 동안 서버에 물어 부릅니다(15초에서 2분까지 점점 느리게, 앞으로 올 때 바로 — 지금 값도 한 번). */
|
|
415
|
+
onUnread(cb: (count: number) => void) {
|
|
416
|
+
unreadCallback = cb;
|
|
417
|
+
void refreshUnread();
|
|
418
|
+
},
|
|
419
|
+
/** 답 푸시 토큰. platform: 네이티브 APNs 토큰이면 "apns", Firebase면 "fcm". 쥐고 있다가 보낸 문의마다 겁니다. */
|
|
420
|
+
/** 운영자가 그 열쇠를 아직 안 올렸으면 서버가 ready:false로 답합니다(등록은 됨, 푸시는 안 감) — onPushReady에 false가 오고 한 번 console.warn을 찍습니다. */
|
|
421
|
+
async registerPush(o: { token: string; platform: "apns" | "fcm" }) {
|
|
422
|
+
pushToken = { ...o };
|
|
423
|
+
(await allThreads()).forEach(attachPush);
|
|
424
|
+
},
|
|
425
|
+
/** (선택) 토큰을 대화에 걸 때마다 서버 답: true = 푸시 준비됨, false = 운영자가 그 종류(apns·fcm)의 푸시 열쇠를 아직 안 올림. */
|
|
426
|
+
onPushReady(cb: (ready: boolean) => void) {
|
|
427
|
+
pushReadyCallback = cb;
|
|
428
|
+
},
|
|
429
|
+
/** 로그아웃 때: 손님 정보·이 기기의 대화 열쇠·안 읽은 수를 지우고, 푸시 토큰을 이 서비스의 대화에서 뺍니다. */
|
|
430
|
+
/** 이용 기록(issuecat-usage.ts)을 같은 앱에 넣었으면 그쪽 reset도 같이 됩니다. */
|
|
431
|
+
async reset() {
|
|
432
|
+
// 로그아웃하는 사람의 대화 열쇠와 로그인 없이 보낸 것(앞 판과 같이 이 기기에서 지운다), 다른 기기에서 받은 열쇠(메모리)
|
|
433
|
+
personThreads = [];
|
|
434
|
+
personKey = "";
|
|
435
|
+
await AsyncStorage.removeItem(storeKey());
|
|
436
|
+
await AsyncStorage.removeItem(legacyKey());
|
|
437
|
+
user = null;
|
|
438
|
+
announceUser();
|
|
439
|
+
if (pushToken && opts) void post("/v1/ingest/threads/push/remove", { installKey: opts.installKey, token: pushToken.token });
|
|
440
|
+
clearWebStorage = true; // 화면이 제 저장소(localStorage)에 둔 대화 목록은 다음에 열 때 지운다
|
|
441
|
+
close();
|
|
442
|
+
unreadCallback?.(0);
|
|
443
|
+
},
|
|
444
|
+
/** 예전에 직접 그린 화면(issuecat-report 등)으로 받은 대화 열쇠를 넘깁니다 — 「지난 문의」에 이어 보입니다. */
|
|
445
|
+
async importThreads(list: Thread[]) {
|
|
446
|
+
for (const t of [...list].reverse()) { await saveThread(t); attachPush(t); }
|
|
447
|
+
void refreshUnread();
|
|
448
|
+
},
|
|
449
|
+
/** 받은 푸시(data)가 Issuecat 답이면 그 신고 번호 — Issuecat.open({ thread })에 줍니다. */
|
|
450
|
+
threadId(data: Record<string, unknown> | undefined): string | null {
|
|
451
|
+
return data && (data.issuecat ?? data[OLD_PUSH_MARK]) === "reply" && typeof data.threadId === "string" ? data.threadId : null;
|
|
452
|
+
},
|
|
453
|
+
};
|
|
454
|
+
|
|
455
|
+
let clearWebStorage = false;
|
|
456
|
+
let opening: Promise<void> | null = null;
|
|
457
|
+
const originOf = (u: string) => { const m = /^([a-z][a-z0-9+.-]*:\/\/[^/?#]*)/i.exec(u); return m ? m[1].toLowerCase() : ""; };
|
|
458
|
+
const ours = (u: string) => originOf(u) === originOf(base());
|
|
459
|
+
const openOutside = (u: string) => { if (/^(https?:|mailto:|tel:)/i.test(u)) void Linking.openURL(u); };
|
|
460
|
+
|
|
461
|
+
/** 흔들어 신고 시트의 「문제 신고하기」(신고 갈래)·「문의하기로」(문의 갈래): 흔든 순간 찍은 화면을 싣고 창 */
|
|
462
|
+
function openReport(shot: string | null, kind: "report" | "inquiry" = "report") {
|
|
463
|
+
if (!opening) opening = openNow({ kind }, shot).finally(() => { opening = null; });
|
|
464
|
+
return opening;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** preShot: 흔든 순간 찍어 둔 앱 화면(시트가 덮기 전) — 없으면 지금 화면을 찍는다 */
|
|
468
|
+
async function openNow(o: { thread?: string; kind?: "inquiry" | "report"; view?: "threads" }, preShot?: string | null) {
|
|
469
|
+
if (!opts) throw new Error("Issuecat.configure({ installKey })를 먼저 부르세요");
|
|
470
|
+
if (!setHost) throw new Error("<IssuecatHost />를 앱 맨 바깥에 두세요");
|
|
471
|
+
const saved = await allThreads();
|
|
472
|
+
if (openState) {
|
|
473
|
+
// 이미 열려 있으면 그 자리로 옮긴다
|
|
474
|
+
if (o.thread) sendToScreen?.({ type: "config", threads: saved, thread: o.thread });
|
|
475
|
+
else if (o.kind) sendToScreen?.({ type: "config", kind: o.kind });
|
|
476
|
+
else if (o.view) sendToScreen?.({ type: "config", view: o.view });
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
let shot: string | null = null;
|
|
480
|
+
if (preShot !== undefined) shot = opts.capture ? preShot : null;
|
|
481
|
+
else try { shot = opts.capture ? await opts.capture() : null; } catch { shot = null; } // 문의 창이 덮기 전의 앱 화면
|
|
482
|
+
const cfg: Record<string, unknown> = { v: 1, sdk: `react-native/${ISSUECAT_VERSION}`, app: opts.app ?? "react-native", context: context() };
|
|
483
|
+
if (!opts.capture) cfg.capture = false; // 찍을 길이 없으면 화면 줄을 감춘다
|
|
484
|
+
if (opts.test === true) cfg.test = true; // 시험 문의
|
|
485
|
+
if (opts.pickPhotos) cfg.pick = true; // 사진 고르기는 앱이(pick-photos → photos)
|
|
486
|
+
if (user) cfg.user = user;
|
|
487
|
+
if (saved.length) cfg.threads = saved;
|
|
488
|
+
if (o.thread) cfg.thread = o.thread;
|
|
489
|
+
if (o.kind) cfg.kind = o.kind;
|
|
490
|
+
if (o.view) cfg.view = o.view;
|
|
491
|
+
if (opts.accent) cfg.accent = opts.accent; // 앱 색
|
|
492
|
+
if (opts.locale) cfg.locale = opts.locale; // 창의 말
|
|
493
|
+
openState = { url: `${base()}/inquiry?k=${encodeURIComponent(opts.installKey)}#cfg=${b64url(JSON.stringify(cfg))}`, shot };
|
|
494
|
+
setHost(openState);
|
|
495
|
+
}
|
|
496
|
+
function close() {
|
|
497
|
+
openState = null;
|
|
498
|
+
setHost?.(null);
|
|
499
|
+
void flushOutbox();
|
|
500
|
+
void refreshUnread();
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// 다리 이름 IssuecatBridge는 iOS·Android 네이티브 SDK 몫 — RN은 화면이 ReactNativeWebView.postMessage로 보낸다
|
|
504
|
+
const CLEAR_JS = `try{Object.keys(localStorage).forEach(function(k){if(k.indexOf("mkThreads:")===0)localStorage.removeItem(k)})}catch(e){}true;`;
|
|
505
|
+
|
|
506
|
+
/** 흔들림을 받는다 — react-native-shake(MIT, https://github.com/Doko-Demo-Doa/react-native-shake)의 addListener.
|
|
507
|
+
* 그 모듈은 네이티브 모듈이 없는 곳(Expo Go)에서 가져오는 순간 던질 수 있어(NativeEventEmitter가 빈 모듈을 읽음) 여기서 늦게 가져온다 — 실패하면 흔들기만 빠진다. */
|
|
508
|
+
let warnedShake = false;
|
|
509
|
+
function listenShake(onShake: () => void): (() => void) | null {
|
|
510
|
+
try {
|
|
511
|
+
const mod = require("react-native-shake");
|
|
512
|
+
const sub = (mod?.default ?? mod).addListener(onShake);
|
|
513
|
+
return () => sub?.remove?.();
|
|
514
|
+
} catch (e) {
|
|
515
|
+
if (__DEV__ && !warnedShake) {
|
|
516
|
+
warnedShake = true;
|
|
517
|
+
console.warn(`[Issuecat] 흔들어 신고를 못 켰습니다 — react-native-shake를 설치하고 앱을 다시 빌드하세요(Expo Go에서는 안 됩니다 — 개발 빌드에서 됩니다). ${String(e)}`);
|
|
518
|
+
}
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
let lastShake = 0;
|
|
523
|
+
/** 흔들림: 앱이 켜 두었고(shake) 쓰는 사람이 끄지 않았고(shakeToReport) 창·시트가 없으면 아래 시트를 띄운다 — 바로 신고 창이 아니라 스레드(Threads) 앱처럼 시트부터 */
|
|
524
|
+
async function onShake() {
|
|
525
|
+
if (shakeLoad) await shakeLoad; // 켜자마자 흔들어도 저장된 「끔」을 먼저 본다
|
|
526
|
+
if (!opts || opts.shake === false || shakeOff || openState || opening || sheetOpen || !setSheet) return;
|
|
527
|
+
// iOS는 글을 쓰는 중에 흔들면 「실행 취소」 창을 띄운다 — 키보드가 떠 있으면 시트를 안 띄운다(두 창이 겹치지 않게)
|
|
528
|
+
if (Platform.OS === "ios" && (Keyboard as { isVisible?: () => boolean }).isVisible?.()) return;
|
|
529
|
+
const now = Date.now();
|
|
530
|
+
if (now - lastShake < 1000) return; // 1초에 한 번
|
|
531
|
+
lastShake = now;
|
|
532
|
+
sheetOpen = true;
|
|
533
|
+
let shot: string | null = null;
|
|
534
|
+
try { shot = opts.capture ? await opts.capture() : null; } catch { shot = null; } // 신고에 실을 그림은 흔든 순간의 앱 화면 — 시트가 덮기 전에
|
|
535
|
+
if (setSheet) setSheet({ shot });
|
|
536
|
+
else sheetOpen = false;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** 시트 글: 앱이 준 말(locale), 없으면 휴대폰 언어. 한국어가 기본 */
|
|
540
|
+
function sheetKorean(): boolean {
|
|
541
|
+
let l = opts?.locale ?? "";
|
|
542
|
+
if (!l) try { l = Intl.DateTimeFormat().resolvedOptions().locale ?? ""; } catch { l = ""; }
|
|
543
|
+
return !l || /^ko/i.test(l);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* 흔들면 뜨는 아래 시트: 제목·짧은 설명·「문제 신고하기」(눌러야 신고 창)·「흔들어서 문제 신고」 스위치(끄면 이 기기에 저장)·끌 때 다른 길 한 줄.
|
|
548
|
+
* 꼴은 스레드(Threads) 앱의 흔들기 시트. RN 기본 부품(Modal·Switch)만 — 바깥을 누르거나 뒤로 가기로 닫힌다.
|
|
549
|
+
*/
|
|
550
|
+
function ShakeSheet({ sheet, onClose, onReport, onDismiss }: { sheet: { shot: string | null } | null; onClose: () => void; onReport: (shot: string | null, kind: "report" | "inquiry") => void; onDismiss: () => void }) {
|
|
551
|
+
const dark = useColorScheme() === "dark";
|
|
552
|
+
const [on, setOn] = useState(!shakeOff);
|
|
553
|
+
useEffect(() => { if (sheet) setOn(!shakeOff); }, [sheet]);
|
|
554
|
+
const ko = sheetKorean();
|
|
555
|
+
const a = opts?.accent;
|
|
556
|
+
const accent = (typeof a === "string" ? a : dark ? a?.dark ?? a?.light : a?.light ?? a?.dark) ?? "#0b6ef6";
|
|
557
|
+
const fg = dark ? "#f2f3f5" : "#111318";
|
|
558
|
+
const sub = dark ? "#a1a7b0" : "#5f6670";
|
|
559
|
+
const line = dark ? "#33363d" : "#e6e8ec";
|
|
560
|
+
const label = ko ? "흔들어서 문제 신고" : "Shake phone to report a problem";
|
|
561
|
+
const toggle = (v: boolean) => { setOn(v); Issuecat.shakeToReport = v; };
|
|
562
|
+
return (
|
|
563
|
+
<Modal visible={!!sheet} transparent animationType="slide" onRequestClose={onClose} onDismiss={onDismiss} statusBarTranslucent>
|
|
564
|
+
<View style={{ flex: 1, justifyContent: "flex-end" }}>
|
|
565
|
+
<Pressable accessibilityLabel={ko ? "닫기" : "Close"} onPress={onClose} style={{ position: "absolute", top: 0, right: 0, bottom: 0, left: 0, backgroundColor: "rgba(0,0,0,0.35)" }} />
|
|
566
|
+
<View style={{ backgroundColor: dark ? "#1f2126" : "#ffffff", borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingHorizontal: 24, paddingTop: 10, paddingBottom: 40 }}>
|
|
567
|
+
<View style={{ alignSelf: "center", width: 36, height: 5, borderRadius: 3, backgroundColor: line }} />
|
|
568
|
+
<Text style={{ marginTop: 22, fontSize: 20, fontWeight: "700", color: fg, textAlign: "center" }}>{ko ? "앱에 문제가 있나요?" : "Something not working?"}</Text>
|
|
569
|
+
<Text style={{ marginTop: 6, fontSize: 14, lineHeight: 20, color: sub, textAlign: "center" }}>{ko ? "지금 화면과 함께 알려 주시면 확인해서 고칠게요." : "Tell us with a picture of this screen and we'll look into it."}</Text>
|
|
570
|
+
<Pressable testID="issuecat-shake-report" accessibilityRole="button" onPress={() => onReport(sheet?.shot ?? null, "report")}
|
|
571
|
+
style={({ pressed }) => ({ marginTop: 20, height: 52, borderRadius: 14, backgroundColor: accent, alignItems: "center", justifyContent: "center", opacity: pressed ? 0.85 : 1 })}>
|
|
572
|
+
<Text style={{ color: "#ffffff", fontSize: 16, fontWeight: "700" }}>{ko ? "문제 신고하기" : "Report a problem"}</Text>
|
|
573
|
+
</Pressable>
|
|
574
|
+
{/* 스레드 시트의 「악용·스팸 신고는 여기 아님」 줄 자리: 이 창은 문제 신고, 궁금한 점·요청은 문의하기(Issuecat은 두 갈래를 나눈다) */}
|
|
575
|
+
<Pressable testID="issuecat-shake-inquiry" accessibilityRole="button" onPress={() => onReport(sheet?.shot ?? null, "inquiry")} style={{ marginTop: 4, minHeight: 40, alignItems: "center", justifyContent: "center" }}>
|
|
576
|
+
<Text style={{ fontSize: 13, color: sub }}>{ko ? "궁금한 점이나 요청은 문의하기로 ›" : "Questions or requests? Contact us ›"}</Text>
|
|
577
|
+
</Pressable>
|
|
578
|
+
<View style={{ marginTop: 12, height: 1, backgroundColor: line }} />
|
|
579
|
+
<Pressable onPress={() => toggle(!on)} style={{ marginTop: 6, minHeight: 48, flexDirection: "row", alignItems: "center" }}>
|
|
580
|
+
<Text style={{ flex: 1, fontSize: 16, color: fg }}>{label}</Text>
|
|
581
|
+
<Switch testID="issuecat-shake-toggle" accessibilityLabel={label} value={on} onValueChange={toggle} trackColor={{ true: accent }} />
|
|
582
|
+
</Pressable>
|
|
583
|
+
{on ? null : (
|
|
584
|
+
<Text testID="issuecat-shake-hint" style={{ marginTop: 2, fontSize: 13, lineHeight: 18, color: sub }}>
|
|
585
|
+
{opts?.shakeOffHint ?? (ko ? "이제 흔들어도 이 창이 뜨지 않아요. 문제는 앱의 문의하기에서도 신고할 수 있어요." : "Shaking won't open this anymore. You can still report a problem from the app's contact menu.")}
|
|
586
|
+
</Text>
|
|
587
|
+
)}
|
|
588
|
+
</View>
|
|
589
|
+
</View>
|
|
590
|
+
</Modal>
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** 창이 뜰 자리. 앱 맨 바깥(내비게이션 바깥)에 한 번 둡니다. 흔들어 신고도 이것이 떠 있는 동안 받습니다. */
|
|
595
|
+
export function IssuecatHost() {
|
|
596
|
+
const [state, setState] = useState<typeof openState>(null);
|
|
597
|
+
const web = useRef<IssuecatWebViewRef>(null);
|
|
598
|
+
const [failed, setFailed] = useState(false);
|
|
599
|
+
const dark = useColorScheme() === "dark";
|
|
600
|
+
const clearOnce = useRef(false);
|
|
601
|
+
const [sheet, setSheetState] = useState<{ shot: string | null } | null>(null);
|
|
602
|
+
// 시트의 「문제 신고하기」: iOS는 시트 Modal이 다 내려간 뒤(onDismiss — iOS에서 부름)에 신고 창을 띄운다 — 두 Modal이 겹쳐 뜨면 iOS가 뒤의 것을 안 띄운다
|
|
603
|
+
const reportAfter = useRef<{ shot: string | null; kind: "report" | "inquiry" } | null>(null);
|
|
604
|
+
|
|
605
|
+
useEffect(() => {
|
|
606
|
+
setHost = (s) => { setFailed(false); clearOnce.current = clearWebStorage; clearWebStorage = false; setState(s); };
|
|
607
|
+
setSheet = (s) => { sheetOpen = !!s; setSheetState(s); };
|
|
608
|
+
const stopShake = listenShake(() => void onShake());
|
|
609
|
+
return () => { setHost = null; setSheet = null; sheetOpen = false; stopShake?.(); };
|
|
610
|
+
}, []);
|
|
611
|
+
const closeSheet = () => { sheetOpen = false; setSheetState(null); };
|
|
612
|
+
const sheetGone = () => {
|
|
613
|
+
const r = reportAfter.current;
|
|
614
|
+
reportAfter.current = null;
|
|
615
|
+
if (r) void openReport(r.shot, r.kind);
|
|
616
|
+
};
|
|
617
|
+
const reportFromSheet = (shot: string | null, kind: "report" | "inquiry") => {
|
|
618
|
+
if (Platform.OS === "ios") {
|
|
619
|
+
reportAfter.current = { shot, kind };
|
|
620
|
+
setTimeout(sheetGone, 700); // onDismiss가 안 오는 판(일부 새 구조)에서도 열리게 — 먼저 온 쪽 한 번만
|
|
621
|
+
}
|
|
622
|
+
closeSheet();
|
|
623
|
+
if (Platform.OS !== "ios") void openReport(shot, kind);
|
|
624
|
+
};
|
|
625
|
+
useEffect(() => {
|
|
626
|
+
sendToScreen = state ? (m) => web.current?.injectJavaScript(`${receiveJS(JSON.stringify(m))};true;`) : null;
|
|
627
|
+
}, [state]);
|
|
628
|
+
|
|
629
|
+
const onMessage = async (e: WebViewMessageEvent) => {
|
|
630
|
+
let m: any;
|
|
631
|
+
try { m = JSON.parse(e.nativeEvent.data); } catch { return; }
|
|
632
|
+
if (!m || (m.issuecat !== 1 && m[OLD_MESSAGE_MARK] !== 1)) return;
|
|
633
|
+
if (m.type === "capture-request") {
|
|
634
|
+
sendToScreen?.(state?.shot ? { type: "capture", id: m.id, jpeg: state.shot } : { type: "capture", id: m.id, none: true });
|
|
635
|
+
} else if (m.type === "sent" && m.reportId && m.threadKey) {
|
|
636
|
+
const t = { reportId: String(m.reportId), threadKey: String(m.threadKey) };
|
|
637
|
+
await saveThread(t);
|
|
638
|
+
attachPush(t);
|
|
639
|
+
} else if (m.type === "threads" && Array.isArray(m.threads)) {
|
|
640
|
+
// 창이 받아 온 대화(다른 기기에서 보낸 것·옛 길의 것) — 쥐어 두면 창이 닫혀 있을 때도 새 답 수에 든다.
|
|
641
|
+
// 다른 기기에서 보낸 것(from "person")은 메모리에만, 옛 길의 것은 저장
|
|
642
|
+
const person = m.from === "person";
|
|
643
|
+
const have = new Set((await threads()).map((t) => t.reportId));
|
|
644
|
+
for (const x of [...m.threads].reverse()) {
|
|
645
|
+
if (!x || typeof x.reportId !== "string" || typeof x.threadKey !== "string" || !x.reportId || !x.threadKey) continue;
|
|
646
|
+
const t = { reportId: x.reportId, threadKey: x.threadKey };
|
|
647
|
+
if (person) {
|
|
648
|
+
if (await rememberPerson(t)) attachPush(t);
|
|
649
|
+
} else if (!have.has(x.reportId)) {
|
|
650
|
+
await saveThread(t);
|
|
651
|
+
attachPush(t);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
} else if (m.type === "unread" && typeof m.count === "number") {
|
|
655
|
+
unreadCallback?.(m.count);
|
|
656
|
+
} else if (m.type === "close") {
|
|
657
|
+
close();
|
|
658
|
+
} else if (m.type === "queued" && typeof m.id === "string" && typeof m.path === "string" && m.path.startsWith("/v1/ingest/") && typeof m.body === "string") {
|
|
659
|
+
await outboxSave([...(await outbox()).filter((x) => x.id !== m.id), { id: m.id, path: m.path, body: m.body, who: storeKey() }]);
|
|
660
|
+
} else if (m.type === "dequeued" && typeof m.id === "string") {
|
|
661
|
+
await outboxSave((await outbox()).filter((x) => x.id !== m.id));
|
|
662
|
+
} else if (m.type === "pick-photos" && typeof m.id === "string") {
|
|
663
|
+
// 클립 단추: 앱의 사진 고르기 → 고른 그림(JPEG base64)을 화면에. 실패·취소는 빈 목록
|
|
664
|
+
const max = typeof m.max === "number" && m.max > 0 ? Math.min(m.max, 10) : 10;
|
|
665
|
+
let jpegs: string[] = [];
|
|
666
|
+
try { jpegs = opts?.pickPhotos ? (await opts.pickPhotos(max)).filter((j) => typeof j === "string" && j).slice(0, max) : []; } catch { jpegs = []; }
|
|
667
|
+
sendToScreen?.({ type: "photos", id: m.id, jpegs });
|
|
668
|
+
} else if (m.type === "open-url" && typeof m.url === "string" && /^https?:\/\//.test(m.url)) {
|
|
669
|
+
void Linking.openURL(m.url); // 창 아래 Issuecat 표시 등: 문의 창 안에서 넘어가지 않게 바깥 브라우저로
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
|
|
673
|
+
// 연결 실패 안내 한 줄 — 언어는 웹뷰의 navigator.language로(문의 화면과 같은 길)
|
|
674
|
+
const offline = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="light dark">
|
|
675
|
+
<body style="margin:0;height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;box-sizing:border-box;font:15px -apple-system,sans-serif;text-align:center">
|
|
676
|
+
<p id="m" style="margin:0;line-height:1.6">연결할 수 없어요. 인터넷 연결을 확인하고 다시 열어 주세요.</p><div style="display:flex;gap:10px">
|
|
677
|
+
<button id="r" onclick="ReactNativeWebView.postMessage(JSON.stringify({issuecat:1,type:'retry'}))" style="font:inherit;height:44px;padding:0 20px;border-radius:22px">다시 시도</button>
|
|
678
|
+
<button id="c" onclick="ReactNativeWebView.postMessage(JSON.stringify({issuecat:1,type:'close'}))" style="font:inherit;height:44px;padding:0 20px;border-radius:22px">닫기</button></div>
|
|
679
|
+
<script>if(!/^ko/i.test(navigator.language||"")){document.documentElement.lang="en";m.textContent="Can't connect. Check your connection and try again.";r.textContent="Retry";c.textContent="Close"}</script></body>`;
|
|
680
|
+
|
|
681
|
+
return (
|
|
682
|
+
<>
|
|
683
|
+
<ShakeSheet sheet={sheet} onClose={closeSheet} onReport={reportFromSheet} onDismiss={sheetGone} />
|
|
684
|
+
<Modal visible={!!state} animationType="slide" presentationStyle="fullScreen" onRequestClose={() => (failed ? close() : sendToScreen?.({ type: "back" }))}>
|
|
685
|
+
{/* 안전 영역·키보드는 화면(viewport-fit=cover, env(safe-area-inset-*), visualViewport)이 맡는다 */}
|
|
686
|
+
<View style={{ flex: 1, backgroundColor: dark ? "#0f1115" : "#f6f7f9" }}>
|
|
687
|
+
{Platform.OS === "android" ? <StatusBar barStyle={dark ? "light-content" : "dark-content"} /> : null}
|
|
688
|
+
{state ? (
|
|
689
|
+
<IssuecatWebView
|
|
690
|
+
ref={web}
|
|
691
|
+
source={failed ? { html: offline } : { uri: state.url }}
|
|
692
|
+
originWhitelist={["*"]}
|
|
693
|
+
javaScriptEnabled
|
|
694
|
+
domStorageEnabled
|
|
695
|
+
injectedJavaScriptBeforeContentLoaded={clearOnce.current ? CLEAR_JS : "true;"}
|
|
696
|
+
contentInsetAdjustmentBehavior="never"
|
|
697
|
+
hideKeyboardAccessoryView
|
|
698
|
+
automaticallyAdjustContentInsets={false}
|
|
699
|
+
bounces={false}
|
|
700
|
+
style={{ flex: 1, backgroundColor: "transparent" }}
|
|
701
|
+
onMessage={(e) => {
|
|
702
|
+
try { if (JSON.parse(e.nativeEvent.data).type === "retry") return setFailed(false); } catch {}
|
|
703
|
+
void onMessage(e);
|
|
704
|
+
}}
|
|
705
|
+
onError={() => setFailed(true)}
|
|
706
|
+
onHttpError={(e) => { if (e.nativeEvent.statusCode >= 500) setFailed(true); }}
|
|
707
|
+
onShouldStartLoadWithRequest={(r) => {
|
|
708
|
+
// 우리 주소 밖 고리(답 속 링크 등)는 브라우저로 — 주소 앞부분이 아니라 출처(scheme+host+port)로 견준다(issuecat.com.다른곳.example 같은 주소 막기)
|
|
709
|
+
if (ours(r.url) || r.url.startsWith("about:") || r.url.startsWith("data:")) return true;
|
|
710
|
+
openOutside(r.url);
|
|
711
|
+
return false;
|
|
712
|
+
}}
|
|
713
|
+
// 새 창(target=_blank — 답 속 링크)은 열지 않고 브라우저로. 문의 창은 그대로
|
|
714
|
+
onOpenWindow={(e) => openOutside(e.nativeEvent.targetUrl)}
|
|
715
|
+
/>
|
|
716
|
+
) : null}
|
|
717
|
+
</View>
|
|
718
|
+
</Modal>
|
|
719
|
+
</>
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/** 앱 → 화면: 화면의 window.issuecatReceive로. 없으면(앞 판 화면) 옛 이름 window.Cuelen.receive로 — 있는 것 하나에만 보낸다 */
|
|
724
|
+
function receiveJS(json: string): string {
|
|
725
|
+
return `(window.issuecatReceive||(window.${OLD_SCREEN_OBJECT}&&window.${OLD_SCREEN_OBJECT}.receive)||function(){})(${json})`;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// ---- 옛 코드 호환 — 앞 판(옛 이름 Cuelen·문제콕) 앱 코드·파일과 섞여도 돌게 하는 이름을 여기 모읍니다.
|
|
729
|
+
|
|
730
|
+
/** 저장 자리(AsyncStorage) — 앞 판이 쓰던 값 그대로입니다. 바꾸면 저장한 대화 열쇠·못 보낸 문의를 잃어요. */
|
|
731
|
+
const OLD_STORAGE = { threads: "cuelen.threads", outbox: "cuelen.outbox" } as const;
|
|
732
|
+
/** 앞 판 문의 화면의 메시지 칸·받는 곳 — 메시지는 어느 칸이든 받는다 */
|
|
733
|
+
const OLD_MESSAGE_MARK = "cuelen";
|
|
734
|
+
/** 앞 판 서버가 보낸 답 푸시의 표시 칸 이름 — 그 칸으로 온 푸시도 받는다 */
|
|
735
|
+
const OLD_PUSH_MARK = "munjaekok";
|
|
736
|
+
const OLD_SCREEN_OBJECT = "Cuelen";
|
|
737
|
+
|
|
738
|
+
/** 앞 판 이용 기록 파일(munjaekok.ts·앞 판 issuecat-usage.ts)이 쓰는 globalThis 칸 — 새 칸과 같은 목록·같은 값을 가리키게 한다(어느 파일이 먼저 떠도) */
|
|
739
|
+
type OldLink = { __cuelenUser?: LinkedUser; __cuelenUserListeners?: Array<(u: LinkedUser) => void>; __cuelenTest?: boolean };
|
|
740
|
+
function linkedListeners(): Array<(u: LinkedUser) => void> {
|
|
741
|
+
const g = globalThis as typeof link & OldLink;
|
|
742
|
+
const list = g.__issuecatUserListeners ?? g.__cuelenUserListeners ?? [];
|
|
743
|
+
g.__issuecatUserListeners = g.__cuelenUserListeners = list;
|
|
744
|
+
return list;
|
|
745
|
+
}
|
|
746
|
+
function setOldLinkedUser(u: LinkedUser) { (globalThis as OldLink).__cuelenUser = u; }
|
|
747
|
+
function setOldTestFlag(on: boolean) { (globalThis as OldLink).__cuelenTest = on; }
|
|
748
|
+
|
|
749
|
+
// 옛 이름(Cuelen) — 앞 판 cuelen.tsx를 이 파일로 바꿔 넣어도(이름은 그대로 cuelen.tsx로 둬도) 앱의 Cuelen·<CuelenHost /> 코드가 그대로 돕니다
|
|
750
|
+
export const Cuelen = Issuecat;
|
|
751
|
+
export const CuelenHost = IssuecatHost;
|
|
752
|
+
export const CUELEN_VERSION = ISSUECAT_VERSION;
|
|
753
|
+
export default Issuecat;
|